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;
020import org.jspecify.annotations.Nullable;
021
022import javax.annotation.concurrent.NotThreadSafe;
023import javax.annotation.concurrent.ThreadSafe;
024import java.util.List;
025import java.nio.charset.Charset;
026import java.nio.charset.StandardCharsets;
027import java.util.Set;
028
029import static java.util.Objects.requireNonNull;
030
031/**
032 * Prepares responses for each request scenario Soklet supports (<em>Resource Method</em>, exception, CORS preflight, etc.)
033 * <p>
034 * These methods prepare a {@link MarshaledResponse} for Soklet's remaining response processing. Interceptor selection,
035 * CORS, {@link #postProcess(MarshaledResponse)}, HEAD/bodyless projection, and transport framing or compression may still
036 * affect the response sent to the client; see {@link #postProcess(MarshaledResponse)} for phase ownership and exceptions.
037 * <p>
038 * A standard threadsafe implementation builder can be acquired via {@link #builder()} or {@link #withCharset(Charset)}.
039 * This builder allows you to specify, for example, how to turn a <em>Resource Method</em> response object into a wire format (e.g. JSON) and is generally what you want.
040 * <p>
041 * A standard threadsafe implementation can be acquired via the {@link #defaultInstance()} factory method.
042 * This is generally not needed unless your implementation requires dynamic "fall back to default" behavior that is not otherwise accessible.
043 * <p>
044 * Example implementation using {@link #builder()}:
045 * <pre>{@code // Let's use Gson to write response body data
046 * // See https://github.com/google/gson
047 * final Gson GSON = new Gson();
048 *
049 * // The request was matched to a Resource Method and executed non-exceptionally
050 * ResourceMethodHandler resourceMethodHandler = (
051 *   @NonNull Request request,
052 *   @NonNull Response response,
053 *   @NonNull ResourceMethod resourceMethod
054 * ) -> {
055 *   // Turn response body into JSON bytes with Gson
056 *   Object bodyObject = response.getBody().orElse(null);
057 *   byte[] body = bodyObject == null
058 *     ? null
059 *     : GSON.toJson(bodyObject).getBytes(StandardCharsets.UTF_8);
060 *
061 *   // To be a good citizen, set the Content-Type header
062 *   Map<String, List<String>> headers = new HashMap<>(response.getHeaders());
063 *   headers.put("Content-Type", List.of("application/json;charset=UTF-8"));
064 *
065 *   // Supply the prepared body for Soklet's remaining response processing
066 *   return MarshaledResponse.withResponse(response)
067 *     .headers(headers)
068 *     .body(body)
069 *     .build();
070 * };
071 *
072 * // Function to create responses for exceptions that bubble out
073 * ThrowableHandler throwableHandler = (
074 *   @NonNull Request request,
075 *   @NonNull Throwable throwable,
076 *   @Nullable ResourceMethod resourceMethod
077 * ) -> {
078 *   // Keep track of what to write to the response
079 *   String message;
080 *   int statusCode;
081 *
082 *   // Examine the exception that bubbled out and determine what
083 *   // the HTTP status and a user-facing message should be.
084 *   // Note: real systems should localize these messages
085 *   switch (throwable) {
086 *     // Soklet throws this exception, a specific subclass of BadRequestException
087 *     case IllegalQueryParameterException e -> {
088 *       message = String.format("Illegal value '%s' for parameter '%s'",
089 *         e.getQueryParameterValue().orElse("[not provided]"),
090 *         e.getQueryParameterName());
091 *       statusCode = 400;
092 *     }
093 *
094 *     // Generically handle other BadRequestExceptions
095 *     case BadRequestException ignored -> {
096 *       message = "Your request was improperly formatted.";
097 *       statusCode = 400;
098 *     }
099 *
100 *     // Something else?  Fall back to a 500
101 *     default -> {
102 *       message = "An unexpected error occurred.";
103 *       statusCode = 500;
104 *     }
105 *   }
106 *
107 *   // Turn response body into JSON bytes with Gson.
108 *   // Note: real systems should expose richer error constructs
109 *   // than an object with a single message field
110 *   byte[] body = GSON.toJson(Map.of("message", message))
111 *     .getBytes(StandardCharsets.UTF_8);
112 *
113 *   // Specify our headers
114 *   Map<String, List<String>> headers = new HashMap<>();
115 *   headers.put("Content-Type", List.of("application/json;charset=UTF-8"));
116 *
117 *   return MarshaledResponse.withStatusCode(statusCode)
118 *     .headers(headers)
119 *     .body(body)
120 *     .build();
121 * };
122 *
123 * // Supply our custom handlers to the standard response marshaler
124 * SokletConfig config = SokletConfig.withHttpServer(
125 *   HttpServer.fromPort(8080)
126 * ).responseMarshaler(ResponseMarshaler.builder()
127 *   .resourceMethodHandler(resourceMethodHandler)
128 *   .throwableHandler(throwableHandler)
129 *   .build()
130 * ).build();}</pre>
131 * <p>
132 * Full documentation is available at <a href="https://www.soklet.com/docs/response-writing">https://www.soklet.com/docs/response-writing</a>.
133 *
134 * @author <a href="https://www.revetkn.com">Mark Allen</a>
135 */
136@ThreadSafe
137public interface ResponseMarshaler {
138        /**
139         * Finalizes the response selected by the interceptor after CORS customization and before HEAD/bodyless
140         * projection and transport framing. Soklet invokes this phase once per ordinary dispatch, after
141         * {@link RequestInterceptor#interceptRequest} returns. A response generator supplied to that interceptor
142         * returns an unfinalized response; rebuilding or copying it does not invoke this phase early.
143         * <p>
144         * Implementations without postprocessing return the supplied response. A forwarding decorator must
145         * explicitly delegate this method as well as the {@code forX} methods. An existing helper with the same
146         * signature now implements this phase and must obey its contract. The builder's configured
147         * {@link Builder.PostProcessor} is invoked by the standard implementation here. Custom code composing
148         * the ordinary {@code forX} methods directly should invoke this method once after composing the response.
149         * {@link #forUnparsedRequest(UnparsedRequest)} owns its own finalization because parser-owned failures
150         * bypass ordinary dispatch.
151         *
152         * @param response the composed response
153         * @return the finalized response
154         */
155        @NonNull
156        MarshaledResponse postProcess(@NonNull MarshaledResponse response);
157
158        /**
159         * Prepares a response for incoming bytes that a transport has rejected before
160         * it can construct a valid {@link Request}.
161         * <p>
162         * This method is invoked at most once for each rejected request. It runs only
163         * if the rejection-detail task is accepted and timeout budget remains after
164         * {@link LifecycleObserver#didRejectUnparsedRequest(UnparsedRequest)}.
165         * Captured bytes are untrusted and may contain
166         * credentials or other sensitive values;
167         * applications should apply their own redaction and retention policies before
168         * logging or storing them.
169         * <p>
170         * The built-in HTTP and SSE transports dispatch this method to the
171         * configured request-handler executor and never invoke it inline on the
172         * selector thread. The framework-managed default executor has bounded
173         * concurrency and queue capacity; a custom executor controls its own capacity.
174         * The method should perform bounded work and must not block. The request-handler
175         * timeout bounds how long the transport waits for the combined observation and
176         * marshaling pipeline; cancellation interrupts the worker but remains
177         * cooperative if application code ignores interruption. If application capacity
178         * is unavailable, both callbacks may be skipped and the transport writes its
179         * built-in bodyless response instead. Later HTTP validation failures and SSE
180         * rejections use the remaining handler budget, including any earlier queue wait.
181         * Idle read timeouts and EOF before complete headers close quietly. Admission,
182         * shutdown and broken-socket failsafes do not call this method.
183         * <p>
184         * Transport-owned HTTP framing, including connection closure and message-body
185         * length, is applied after marshaling. A transport may reject a response-body
186         * representation that cannot be safely written on this pre-dispatch path.
187         * <p>
188         * The default implementation returns the conventional bodyless response for
189         * the rejection reason ({@code 400}, {@code 408}, {@code 413}, {@code 414}, {@code 415},
190         * {@code 417}, or {@code 431}), finalized through this implementation's
191         * {@link #postProcess(MarshaledResponse)} method.
192         * Custom implementations may return any final response status from {@code 200}
193         * through {@code 599}, consistent with this interface's other methods. This
194         * default method preserves
195         * compatibility for direct implementations of this interface; applications that use
196         * {@link #builder()} may customize the behavior with
197         * {@link Builder#unparsedRequestHandler(Builder.UnparsedRequestHandler)}.
198         * A forwarding decorator must delegate this method explicitly to preserve its
199         * delegate's unparsed-request handler and finalization. That delegated response
200         * is already finalized and must not be postprocessed a second time.
201         * <p>
202         * Detailed documentation is available at
203         * <a href="https://www.soklet.com/docs/response-writing#advanced-response-marshaling">https://www.soklet.com/docs/response-writing#advanced-response-marshaling</a>.
204         *
205         * @param request the rejected unparsed request
206         * @return the response to be sent over the wire
207         */
208        @NonNull
209        default MarshaledResponse forUnparsedRequest(
210                        @NonNull UnparsedRequest request) {
211                requireNonNull(request);
212                return ResponseBodyCleanup.transform(DefaultResponseMarshaler.defaultInstance()
213                                .forUnparsedRequest(request), this::postProcess);
214        }
215
216        /**
217         * Prepares a response for a request that was matched to a <em>Resource Method</em> and returned normally (i.e., without throwing an exception).
218         * <p>
219         * <strong>Note that the returned {@link Response} may represent any HTTP status (e.g., 200, 403, 404), and is not restricted to "successful" outcomes.</strong>
220         * <p>
221         * Detailed documentation is available at <a href="https://www.soklet.com/docs/response-writing#resource-method">https://www.soklet.com/docs/response-writing#resource-method</a>.
222         *
223         * @param request        the HTTP request
224         * @param response       the response provided by the <em>Resource Method</em> that handled the request
225         * @param resourceMethod the <em>Resource Method</em> that handled the request
226         * @return the response to be sent over the wire
227         */
228        @NonNull
229        MarshaledResponse forResourceMethod(@NonNull Request request,
230                                                                                                                                                        @NonNull Response response,
231                                                                                                                                                        @NonNull ResourceMethod resourceMethod);
232
233        /**
234         * Prepares a response for a request that does not have a matching <em>Resource Method</em>, which triggers an <a href="https://httpwg.org/specs/rfc9110.html#status.404">HTTP 404 Not Found</a>.
235         * <p>
236         * Detailed documentation is available at <a href="https://www.soklet.com/docs/response-writing#404-not-found">https://www.soklet.com/docs/response-writing#404-not-found</a>.
237         *
238         * @param request the HTTP request
239         * @return the response to be sent over the wire
240         */
241        @NonNull
242        MarshaledResponse forNotFound(@NonNull Request request);
243
244        /**
245         * Prepares a response for a request that triggers an
246         * <a href="https://httpwg.org/specs/rfc9110.html#status.405">HTTP 405 Method Not Allowed</a>.
247         * <p>
248         * Detailed documentation is available at <a href="https://www.soklet.com/docs/response-writing#405-method-not-allowed">https://www.soklet.com/docs/response-writing#405-method-not-allowed</a>.
249         *
250         * @param request            the HTTP request
251         * @param allowedHttpMethods appropriate HTTP methods to write to the {@code Allow} response header
252         * @return the response to be sent over the wire
253         */
254        @NonNull
255        MarshaledResponse forMethodNotAllowed(@NonNull Request request,
256                                                                                                                                                                @NonNull Set<@NonNull HttpMethod> allowedHttpMethods);
257
258        /**
259         * Prepares a response for a request that triggers an <a href="https://httpwg.org/specs/rfc9110.html#status.413">HTTP 413 Content Too Large</a>.
260         * <p>
261         * This method is only invoked when the transport can parse enough request data to construct a {@link Request}.
262         * If the size limit is exceeded before a request target can be identified, the transport may close the connection instead.
263         * <p>
264         * Detailed documentation is available at <a href="https://www.soklet.com/docs/response-writing#413-content-too-large">https://www.soklet.com/docs/response-writing#413-content-too-large</a>.
265         *
266         * @param request        the HTTP request
267         * @param resourceMethod the <em>Resource Method</em> that would have handled the request, if available
268         * @return the response to be sent over the wire
269         */
270        @NonNull
271        MarshaledResponse forContentTooLarge(@NonNull Request request,
272                                                                                                                                                         @Nullable ResourceMethod resourceMethod);
273
274        /**
275         * Prepares an application-dispatched overload response (for example, an SSE connection-limit rejection), triggering an <a href="https://httpwg.org/specs/rfc9110.html#status.503">HTTP 503 Service Unavailable</a>.
276         * <p>
277         * The built-in standard HTTP connection cap closes excess sockets without an HTTP response.
278         * Built-in HTTP executor/queue rejection, handler timeouts and shutdown-admission failsafes bypass
279         * this method, CORS and {@link #postProcess(MarshaledResponse)}. They must remain bounded when no
280         * application worker is available, and never invoke application callbacks on the selector or timer.
281         * <p>
282         * Detailed documentation is available at <a href="https://www.soklet.com/docs/response-writing#503-service-unavailable">https://www.soklet.com/docs/response-writing#503-service-unavailable</a>.
283         *
284         * @param request        the HTTP request
285         * @param resourceMethod the <em>Resource Method</em> that would have handled the request, if available
286         * @return the response to be sent over the wire
287         */
288        @NonNull
289        MarshaledResponse forServiceUnavailable(@NonNull Request request,
290                                                                                                                                                                        @Nullable ResourceMethod resourceMethod);
291
292        /**
293         * Prepares a response for an HTTP {@code OPTIONS} request on a path with a
294         * matching route on that listener. Unknown paths use {@link #forNotFound(Request)}.
295         * <p>
296         * Note that CORS preflight responses are handled specially by {@link #forCorsPreflightAllowed(Request, CorsPreflight, CorsPreflightResponse)}
297         * and {@link #forCorsPreflightRejected(Request, CorsPreflight)} - not this method.
298         * <p>
299         * Detailed documentation is available at <a href="https://www.soklet.com/docs/response-writing#http-options">https://www.soklet.com/docs/response-writing#http-options</a>.
300         *
301         * @param request            the HTTP request
302         * @param allowedHttpMethods appropriate HTTP methods to write to the {@code Allow} response header
303         * @return the response to be sent over the wire
304         */
305        @NonNull
306        MarshaledResponse forOptions(@NonNull Request request,
307                                                                                                                         @NonNull Set<@NonNull HttpMethod> allowedHttpMethods);
308
309        /**
310         * Prepares a response for an HTTP {@code OPTIONS *} (colloquially, "{@code OPTIONS} Splat") request.
311         * <p>
312         * This is a special HTTP/1.1 request defined in RFC 7231 §4.3.7 which permits querying of server-wide capabilities, not the capabilities of a particular resource - e.g. a load balancer asking "is the system up?" without an explicit health-check URL.
313         * <p>
314         * Detailed documentation is available at <a href="https://www.soklet.com/docs/response-writing#http-options">https://www.soklet.com/docs/response-writing#http-options</a>.
315         *
316         * @param request the HTTP request
317         * @return the response to be sent over the wire
318         */
319        @NonNull
320        MarshaledResponse forOptionsSplat(@NonNull Request request);
321
322        /**
323         * Prepares a response for scenarios in which an uncaught exception is encountered.
324         * <p>
325         * Detailed documentation is available at <a href="https://www.soklet.com/docs/response-writing#uncaught-exceptions">https://www.soklet.com/docs/response-writing#uncaught-exceptions</a>.
326         *
327         * @param request        the HTTP request
328         * @param throwable      the exception that was thrown
329         * @param resourceMethod the <em>Resource Method</em> that would have handled the request, if available
330         * @return the response to be sent over the wire
331         */
332        @NonNull
333        MarshaledResponse forThrowable(@NonNull Request request,
334                                                                                                                                 @NonNull Throwable throwable,
335                                                                                                                                 @Nullable ResourceMethod resourceMethod);
336
337        /**
338         * Prepares a response for an HTTP {@code HEAD} request.
339         * <p>
340         * For an implicit {@code HEAD} match, the input is the equivalent {@code GET} method's marshaled response.
341         * For an explicit {@link com.soklet.annotation.HEAD} method, the input is that method's own marshaled response.
342         * This projection runs after CORS and {@link #postProcess(MarshaledResponse)}. Custom implementations
343         * should preserve finalized headers and cookies, normally by copying the supplied response.
344         * They are not postprocessed again. The default implementation removes the body and derives {@code Content-Length} from an actual finite
345         * representation body. For an already bodyless response it preserves a valid application-supplied length,
346         * or omits the header when unknown. It omits length for streaming bodies, never generates it for {@code 304},
347         * and enforces the bodyless status restrictions for {@code 1xx}, {@code 204} and {@code 205}.
348         * <p>
349         * Detailed documentation is available at <a href="https://www.soklet.com/docs/response-writing#http-head">https://www.soklet.com/docs/response-writing#http-head</a>.
350         *
351         * @param request                    the HTTP request
352         * @param getMethodMarshaledResponse the equivalent {@code GET} response, or the explicit {@code HEAD} method's own marshaled response
353         * @return the response to be sent over the wire
354         */
355        @NonNull
356        MarshaledResponse forHead(@NonNull Request request,
357                                                                                                                @NonNull MarshaledResponse getMethodMarshaledResponse);
358
359        /**
360         * Prepares a response for "CORS preflight allowed" scenario when your {@link CorsAuthorizer} approves a preflight request.
361         * <p>
362         * Detailed documentation is available at <a href="https://www.soklet.com/docs/cors#writing-cors-responses">https://www.soklet.com/docs/cors#writing-cors-responses</a>.
363         *
364         * @param request               the HTTP request
365         * @param corsPreflight         the CORS preflight request data
366         * @param corsPreflightResponse the data that should be included in this CORS preflight response
367         * @return the response to be sent over the wire
368         */
369        @NonNull
370        MarshaledResponse forCorsPreflightAllowed(@NonNull Request request,
371                                                                                                                                                                                @NonNull CorsPreflight corsPreflight,
372                                                                                                                                                                                @NonNull CorsPreflightResponse corsPreflightResponse);
373
374        /**
375         * Prepares a response for "CORS preflight rejected" scenario when your {@link CorsAuthorizer} denies a preflight request.
376         * <p>
377         * Detailed documentation is available at <a href="https://www.soklet.com/docs/cors#writing-cors-responses">https://www.soklet.com/docs/cors#writing-cors-responses</a>.
378         *
379         * @param request       the HTTP request
380         * @param corsPreflight the CORS preflight request data
381         * @return the response to be sent over the wire
382         */
383        @NonNull
384        MarshaledResponse forCorsPreflightRejected(@NonNull Request request,
385                                                                                                                                                                                 @NonNull CorsPreflight corsPreflight);
386
387        /**
388         * Applies "CORS is permitted for this request" data to a response.
389         * <p>
390         * Invoked for any non-preflight CORS request that your {@link CorsAuthorizer} approves.
391         * <p>
392         * This method will normally return a copy of the {@code marshaledResponse} with these headers applied
393         * based on the values of {@code corsResponse}:
394         * <ul>
395         *   <li>{@code Access-Control-Allow-Origin} (required)</li>
396         *   <li>{@code Access-Control-Allow-Credentials} (optional)</li>
397         *   <li>{@code Access-Control-Expose-Headers} (optional)</li>
398         * </ul>
399         *
400         * @param request           the HTTP request
401         * @param cors              the CORS request data
402         * @param corsResponse      CORS response data to write as specified by {@link CorsAuthorizer}
403         * @param marshaledResponse the existing response to which we should apply relevant CORS headers
404         * @return the response to be sent over the wire
405         */
406        @NonNull
407        MarshaledResponse forCorsAllowed(@NonNull Request request,
408                                                                                                                                         @NonNull Cors cors,
409                                                                                                                                         @NonNull CorsResponse corsResponse,
410                                                                                                                                         @NonNull MarshaledResponse marshaledResponse);
411
412        /**
413         * Acquires a threadsafe {@link ResponseMarshaler} with a reasonable "out of the box" configuration that uses UTF-8 to write character data.
414         * <p>
415         * The returned instance is guaranteed to be a JVM-wide singleton.
416         *
417         * @return a UTF-8 {@code ResponseMarshaler} with default settings
418         */
419        @NonNull
420        static ResponseMarshaler defaultInstance() {
421                return DefaultResponseMarshaler.defaultInstance();
422        }
423
424        /**
425         * Acquires a builder for a default {@link ResponseMarshaler} implementation that uses {@link java.nio.charset.StandardCharsets#UTF_8} encoding.
426         *
427         * @return a {@code ResponseMarshaler} builder
428         */
429        @NonNull
430        static Builder builder() {
431                return new Builder(StandardCharsets.UTF_8);
432        }
433
434        /**
435         * Acquires a builder for a default {@link ResponseMarshaler} implementation.
436         *
437         * @param charset the default charset to use when writing response data
438         * @return a {@code ResponseMarshaler} builder
439         */
440        @NonNull
441        static Builder withCharset(@NonNull Charset charset) {
442                requireNonNull(charset);
443                return new Builder(charset);
444        }
445
446        /**
447         * Builder used to construct a standard implementation of {@link ResponseMarshaler}.
448         * <p>
449         * This class is intended for use by a single thread.
450         *
451         * @author <a href="https://www.revetkn.com">Mark Allen</a>
452         */
453        @NotThreadSafe
454        final class Builder {
455                /**
456                 * Function used to support pluggable implementations of
457                 * {@link ResponseMarshaler#forUnparsedRequest(UnparsedRequest)}.
458                 */
459                @FunctionalInterface
460                @ThreadSafe
461                public interface UnparsedRequestHandler {
462                        /**
463                         * Prepares a response for incoming bytes rejected before a valid
464                         * {@link Request} can be constructed.
465                         * <p>
466                         * This method is invoked at most once for each rejected request, only if
467                         * the rejection-detail task is accepted and timeout budget remains after
468                         * lifecycle observation. Captured bytes are untrusted and may contain
469                         * sensitive values. The built-in HTTP and SSE transports dispatch it to
470                         * the configured request-handler executor and never invoke it inline on
471                         * the selector thread. The framework-managed default executor has bounded
472                         * concurrency and queue capacity; a custom executor controls its own
473                         * capacity. The handler should perform bounded work and must not block. The
474                         * request-handler timeout bounds how long the transport waits; cancellation
475                         * interrupts the worker but is cooperative if application code ignores
476                         * interruption. When application capacity or timeout budget is unavailable,
477                         * the handler may be skipped in favor of a built-in response.
478                         * <p>
479                         * Detailed documentation is available at
480                         * <a href="https://www.soklet.com/docs/response-writing#advanced-response-marshaling">https://www.soklet.com/docs/response-writing#advanced-response-marshaling</a>.
481                         *
482                         * @param request the rejected unparsed request
483                         * @return the response to be sent over the wire
484                         */
485                        @NonNull
486                        MarshaledResponse handle(@NonNull UnparsedRequest request);
487                }
488
489                /**
490                 * Function used to support pluggable implementations of {@link ResponseMarshaler#forResourceMethod(Request, Response, ResourceMethod)}.
491                 */
492                @FunctionalInterface
493                @ThreadSafe
494                public interface ResourceMethodHandler {
495                        /**
496                         * Prepares a response for the scenario in which the request was matched to a <em>Resource Method</em> and executed non-exceptionally.
497                         * <p>
498                         * Detailed documentation is available at <a href="https://www.soklet.com/docs/response-writing#resource-method">https://www.soklet.com/docs/response-writing#resource-method</a>.
499                         *
500                         * @param request        the HTTP request
501                         * @param response       the response provided by the <em>Resource Method</em> that handled the request
502                         * @param resourceMethod the <em>Resource Method</em> that handled the request
503                         * @return the response to be sent over the wire
504                         */
505                        @NonNull
506                        MarshaledResponse handle(@NonNull Request request,
507                                                                                                                         @NonNull Response response,
508                                                                                                                         @NonNull ResourceMethod resourceMethod);
509                }
510
511                /**
512                 * Function used to support pluggable implementations of {@link ResponseMarshaler#forNotFound(Request)}.
513                 */
514                @FunctionalInterface
515                @ThreadSafe
516                public interface NotFoundHandler {
517                        /**
518                         * Prepares a response for a request that triggers an
519                         * <a href="https://httpwg.org/specs/rfc9110.html#status.404">HTTP 404 Not Found</a>.
520                         * <p>
521                         * Detailed documentation is available at <a href="https://www.soklet.com/docs/response-writing#404-not-found">https://www.soklet.com/docs/response-writing#404-not-found</a>.
522                         *
523                         * @param request the HTTP request
524                         * @return the response to be sent over the wire
525                         */
526                        @NonNull
527                        MarshaledResponse handle(@NonNull Request request);
528                }
529
530                /**
531                 * Function used to support pluggable implementations of {@link ResponseMarshaler#forMethodNotAllowed(Request, Set)}.
532                 */
533                @FunctionalInterface
534                @ThreadSafe
535                public interface MethodNotAllowedHandler {
536                        /**
537                         * Prepares a response for a request that triggers an
538                         * <a href="https://httpwg.org/specs/rfc9110.html#status.405">HTTP 405 Method Not Allowed</a>.
539                         * <p>
540                         * Detailed documentation is available at <a href="https://www.soklet.com/docs/response-writing#405-method-not-allowed">https://www.soklet.com/docs/response-writing#405-method-not-allowed</a>.
541                         *
542                         * @param request            the HTTP request
543                         * @param allowedHttpMethods appropriate HTTP methods to write to the {@code Allow} response header
544                         * @return the response to be sent over the wire
545                         */
546                        @NonNull
547                        MarshaledResponse handle(@NonNull Request request,
548                                                                                                                         @NonNull Set<@NonNull HttpMethod> allowedHttpMethods);
549                }
550
551                /**
552                 * Function used to support pluggable implementations of {@link ResponseMarshaler#forContentTooLarge(Request, ResourceMethod)}.
553                 */
554                @FunctionalInterface
555                @ThreadSafe
556                public interface ContentTooLargeHandler {
557                        /**
558                         * Prepares a response for a request that triggers an <a href="https://httpwg.org/specs/rfc9110.html#status.413">HTTP 413 Content Too Large</a>.
559                         * <p>
560                         * Detailed documentation is available at <a href="https://www.soklet.com/docs/response-writing#413-content-too-large">https://www.soklet.com/docs/response-writing#413-content-too-large</a>.
561                         *
562                         * @param request        the HTTP request
563                         * @param resourceMethod the <em>Resource Method</em> that would have handled the request, if available
564                         * @return the response to be sent over the wire
565                         */
566                        @NonNull
567                        MarshaledResponse handle(@NonNull Request request,
568                                                                                                                         @Nullable ResourceMethod resourceMethod);
569                }
570
571                /**
572                 * Function used to support pluggable implementations of {@link ResponseMarshaler#forServiceUnavailable(Request, ResourceMethod)}.
573                 */
574                @FunctionalInterface
575                @ThreadSafe
576                public interface ServiceUnavailableHandler {
577                        /**
578                         * Prepares a response for a request that triggers an <a href="https://httpwg.org/specs/rfc9110.html#status.503">HTTP 503 Service Unavailable</a>.
579                         * <p>
580                         * Detailed documentation is available at <a href="https://www.soklet.com/docs/response-writing#503-service-unavailable">https://www.soklet.com/docs/response-writing#503-service-unavailable</a>.
581                         *
582                         * @param request        the HTTP request
583                         * @param resourceMethod the <em>Resource Method</em> that would have handled the request, if available
584                         * @return the response to be sent over the wire
585                         */
586                        @NonNull
587                        MarshaledResponse handle(@NonNull Request request,
588                                                                                                                         @Nullable ResourceMethod resourceMethod);
589                }
590
591                /**
592                 * Function used to support pluggable implementations of {@link ResponseMarshaler#forOptions(Request, Set)}.
593                 */
594                @FunctionalInterface
595                @ThreadSafe
596                public interface OptionsHandler {
597                        /**
598                         * Prepares a response for an HTTP {@code OPTIONS} request on a path with a
599                         * matching route on that listener. Unknown paths use {@link #forNotFound(Request)}.
600                         * <p>
601                         * Note that CORS preflight responses are handled specially by {@link #forCorsPreflightAllowed(Request, CorsPreflight, CorsPreflightResponse)}
602                         * and {@link #forCorsPreflightRejected(Request, CorsPreflight)} - not this method.
603                         * <p>
604                         * Detailed documentation is available at <a href="https://www.soklet.com/docs/response-writing#http-options">https://www.soklet.com/docs/response-writing#http-options</a>.
605                         *
606                         * @param request            the HTTP request
607                         * @param allowedHttpMethods appropriate HTTP methods to write to the {@code Allow} response header
608                         * @return the response to be sent over the wire
609                         */
610                        @NonNull
611                        MarshaledResponse handle(@NonNull Request request,
612                                                                                                                         @NonNull Set<@NonNull HttpMethod> allowedHttpMethods);
613                }
614
615                /**
616                 * Function used to support pluggable implementations of {@link ResponseMarshaler#forOptionsSplat(Request)}.
617                 */
618                @FunctionalInterface
619                @ThreadSafe
620                public interface OptionsSplatHandler {
621                        /**
622                         * Prepares a response for an HTTP {@code OPTIONS *} (colloquially, "{@code OPTIONS} Splat") request.
623                         * <p>
624                         * This is a special HTTP/1.1 request defined in RFC 7231 §4.3.7 which permits querying of server-wide capabilities, not the capabilities of a particular resource - e.g. a load balancer asking "is the system up?" without an explicit health-check URL.
625                         * <p>
626                         * Detailed documentation is available at <a href="https://www.soklet.com/docs/response-writing#http-options">https://www.soklet.com/docs/response-writing#http-options</a>.
627                         *
628                         * @param request the HTTP request
629                         * @return the response to be sent over the wire
630                         */
631                        @NonNull
632                        MarshaledResponse handle(@NonNull Request request);
633                }
634
635                /**
636                 * Function used to support pluggable implementations of {@link ResponseMarshaler#forThrowable(Request, Throwable, ResourceMethod)}.
637                 */
638                @FunctionalInterface
639                @ThreadSafe
640                public interface ThrowableHandler {
641                        /**
642                         * Prepares a response for scenarios in which an uncaught exception is encountered.
643                         * <p>
644                         * Detailed documentation is available at <a href="https://www.soklet.com/docs/response-writing#uncaught-exceptions">https://www.soklet.com/docs/response-writing#uncaught-exceptions</a>.
645                         *
646                         * @param request        the HTTP request
647                         * @param throwable      the exception that was thrown
648                         * @param resourceMethod the <em>Resource Method</em> that would have handled the request, if available
649                         * @return the response to be sent over the wire
650                         */
651                        @NonNull
652                        MarshaledResponse handle(@NonNull Request request,
653                                                                                                                         @NonNull Throwable throwable,
654                                                                                                                         @Nullable ResourceMethod resourceMethod);
655                }
656
657                /**
658                 * Function used to support pluggable implementations of {@link ResponseMarshaler#forHead(Request, MarshaledResponse)}.
659                 */
660                @FunctionalInterface
661                @ThreadSafe
662                public interface HeadHandler {
663                        /**
664                         * Prepares a response for an HTTP {@code HEAD} request.
665                         * <p>
666                         * The input includes CORS and postprocessing. Preserve its finalized headers and cookies when
667                         * projecting it, normally with {@link MarshaledResponse#copy()}; this hook is not postprocessed again.
668                         * The input is the equivalent {@code GET} response for an implicit {@code HEAD} match,
669                         * or the explicit {@link com.soklet.annotation.HEAD} method's own marshaled response.
670                         * Return a response without either a finite or streaming body. To advertise an application-supplied
671                         * representation length for an empty finite body, preserve its valid {@code Content-Length}
672                         * instead of replacing it with zero. Omit that header when the representation length is unknown.
673                         * <p>
674                         * Detailed documentation is available at <a href="https://www.soklet.com/docs/response-writing#http-head">https://www.soklet.com/docs/response-writing#http-head</a>.
675                         *
676                         * @param request                    the HTTP request
677                         * @param getMethodMarshaledResponse the equivalent {@code GET} response, or the explicit {@code HEAD} method's own marshaled response
678                         * @return the response to be sent over the wire
679                         */
680                        @NonNull
681                        MarshaledResponse handle(@NonNull Request request,
682                                                                                                                         @NonNull MarshaledResponse getMethodMarshaledResponse);
683                }
684
685                /**
686                 * Function used to support pluggable implementations of {@link ResponseMarshaler#forCorsPreflightAllowed(Request, CorsPreflight, CorsPreflightResponse)}.
687                 */
688                @FunctionalInterface
689                @ThreadSafe
690                public interface CorsPreflightAllowedHandler {
691                        /**
692                         * Prepares a response for "CORS preflight allowed" scenario when your {@link CorsAuthorizer} approves a preflight request.
693                         * <p>
694                         * Detailed documentation is available at <a href="https://www.soklet.com/docs/cors#writing-cors-responses">https://www.soklet.com/docs/cors#writing-cors-responses</a>.
695                         *
696                         * @param request               the HTTP request
697                         * @param corsPreflight         the CORS preflight request data
698                         * @param corsPreflightResponse the data that should be included in this CORS preflight response
699                         * @return the response to be sent over the wire
700                         */
701                        @NonNull
702                        MarshaledResponse handle(@NonNull Request request,
703                                                                                                                         @NonNull CorsPreflight corsPreflight,
704                                                                                                                         @NonNull CorsPreflightResponse corsPreflightResponse);
705                }
706
707                /**
708                 * Function used to support pluggable implementations of {@link ResponseMarshaler#forCorsPreflightRejected(Request, CorsPreflight)}.
709                 */
710                @FunctionalInterface
711                @ThreadSafe
712                public interface CorsPreflightRejectedHandler {
713                        /**
714                         * Prepares a response for "CORS preflight rejected" scenario when your {@link CorsAuthorizer} denies a preflight request.
715                         * <p>
716                         * Detailed documentation is available at <a href="https://www.soklet.com/docs/cors#writing-cors-responses">https://www.soklet.com/docs/cors#writing-cors-responses</a>.
717                         *
718                         * @param request       the HTTP request
719                         * @param corsPreflight the CORS preflight request data
720                         * @return the response to be sent over the wire
721                         */
722                        @NonNull
723                        MarshaledResponse handle(@NonNull Request request,
724                                                                                                                         @NonNull CorsPreflight corsPreflight);
725                }
726
727                /**
728                 * Function used to support pluggable implementations of {@link ResponseMarshaler#forCorsAllowed(Request, Cors, CorsResponse, MarshaledResponse)}.
729                 */
730                @FunctionalInterface
731                @ThreadSafe
732                public interface CorsAllowedHandler {
733                        /**
734                         * Applies "CORS is permitted for this request" data to a response.
735                         * <p>
736                         * Invoked for any non-preflight CORS request that your {@link CorsAuthorizer} approves.
737                         * <p>
738                         * This method will normally return a copy of the {@code marshaledResponse} with these headers applied
739                         * based on the values of {@code corsResponse}:
740                         * <ul>
741                         *   <li>{@code Access-Control-Allow-Origin} (required)</li>
742                         *   <li>{@code Access-Control-Allow-Credentials} (optional)</li>
743                         *   <li>{@code Access-Control-Expose-Headers} (optional)</li>
744                         * </ul>
745                         *
746                         * @param request           the HTTP request
747                         * @param cors              the CORS request data
748                         * @param corsResponse      CORS response data to write as specified by {@link CorsAuthorizer}
749                         * @param marshaledResponse the existing response to which we should apply relevant CORS headers
750                         * @return the response to be sent over the wire
751                         */
752                        @NonNull
753                        MarshaledResponse handle(@NonNull Request request,
754                                                                                                                         @NonNull Cors cors,
755                                                                                                                         @NonNull CorsResponse corsResponse,
756                                                                                                                         @NonNull MarshaledResponse marshaledResponse);
757                }
758
759                /**
760                 * Function invoked once by {@link ResponseMarshaler#postProcess(MarshaledResponse)} for each
761                 * selected response, after the interceptor returns and CORS customization, before all HEAD/bodyless
762                 * projection and framing. Body changes contribute to the GET representation used for HEAD.
763                 * Generating or rebuilding responses inside an interceptor does not invoke this hook early.
764                 * The hook need not be idempotent.
765                 * Owned predecessor channels remain available to replacement channels or streaming callbacks
766                 * until the resulting response is completed or abandoned; see {@link MarshaledResponse#close()}.
767                 */
768                @FunctionalInterface
769                @ThreadSafe
770                public interface PostProcessor {
771                        /**
772                         * Applies an optional "post-process" hook for any final customization or processing before data goes over the wire.
773                         *
774                         * @param marshaledResponse the response data generated by the appropriate handler function, but not yet sent over the wire
775                         * @return the response data (possibly customized) to be sent over the wire
776                         */
777                        @NonNull
778                        MarshaledResponse postProcess(@NonNull MarshaledResponse marshaledResponse);
779                }
780
781                @NonNull
782                Charset charset;
783                @Nullable
784                UnparsedRequestHandler unparsedRequestHandler;
785                @Nullable
786                ResourceMethodHandler resourceMethodHandler;
787                @Nullable
788                NotFoundHandler notFoundHandler;
789                @Nullable
790                MethodNotAllowedHandler methodNotAllowedHandler;
791                @Nullable
792                ContentTooLargeHandler contentTooLargeHandler;
793                @Nullable
794                ServiceUnavailableHandler serviceUnavailableHandler;
795                @Nullable
796                OptionsHandler optionsHandler;
797                @Nullable
798                OptionsSplatHandler optionsSplatHandler;
799                @Nullable
800                ThrowableHandler throwableHandler;
801                @Nullable
802                HeadHandler headHandler;
803                @Nullable
804                CorsPreflightAllowedHandler corsPreflightAllowedHandler;
805                @Nullable
806                CorsPreflightRejectedHandler corsPreflightRejectedHandler;
807                @Nullable
808                CorsAllowedHandler corsAllowedHandler;
809                @Nullable
810                PostProcessor postProcessor;
811
812                private Builder(@NonNull Charset charset) {
813                        requireNonNull(charset);
814                        this.charset = charset;
815                }
816
817                /**
818                 * Sets the handler used when incoming bytes are rejected before a valid
819                 * {@link Request} can be constructed. Passing {@code null} restores the
820                 * built-in default response before any configured post-processing.
821                 *
822                 * @param unparsedRequestHandler the handler, or {@code null} for the
823                 * built-in default response before post-processing
824                 * @return this builder
825                 */
826                @NonNull
827                public Builder unparsedRequestHandler(
828                                @Nullable UnparsedRequestHandler unparsedRequestHandler) {
829                        this.unparsedRequestHandler = unparsedRequestHandler;
830                        return this;
831                }
832
833                @NonNull
834                public Builder charset(@NonNull Charset charset) {
835                        requireNonNull(charset);
836                        this.charset = charset;
837                        return this;
838                }
839
840                /**
841                 * Sets the handler used to marshal successful <em>Resource Method</em>
842                 * responses. Passing {@code null} restores the built-in marshaling behavior.
843                 *
844                 * @param resourceMethodHandler the handler, or {@code null} for the built-in behavior
845                 * @return this builder
846                 */
847                @NonNull
848                public Builder resourceMethodHandler(@Nullable ResourceMethodHandler resourceMethodHandler) {
849                        this.resourceMethodHandler = resourceMethodHandler;
850                        return this;
851                }
852
853                /**
854                 * Sets the handler used for HTTP 404 Not Found responses. Passing
855                 * {@code null} restores the built-in response.
856                 *
857                 * @param notFoundHandler the handler, or {@code null} for the built-in response
858                 * @return this builder
859                 */
860                @NonNull
861                public Builder notFoundHandler(@Nullable NotFoundHandler notFoundHandler) {
862                        this.notFoundHandler = notFoundHandler;
863                        return this;
864                }
865
866                /**
867                 * Sets the handler used for HTTP 405 Method Not Allowed responses. Passing
868                 * {@code null} restores the built-in response.
869                 *
870                 * @param methodNotAllowedHandler the handler, or {@code null} for the built-in response
871                 * @return this builder
872                 */
873                @NonNull
874                public Builder methodNotAllowedHandler(@Nullable MethodNotAllowedHandler methodNotAllowedHandler) {
875                        this.methodNotAllowedHandler = methodNotAllowedHandler;
876                        return this;
877                }
878
879                /**
880                 * Sets the handler used for HTTP 413 Content Too Large responses. Passing
881                 * {@code null} restores the built-in response.
882                 *
883                 * @param contentTooLargeHandler the handler, or {@code null} for the built-in response
884                 * @return this builder
885                 */
886                @NonNull
887                public Builder contentTooLargeHandler(@Nullable ContentTooLargeHandler contentTooLargeHandler) {
888                        this.contentTooLargeHandler = contentTooLargeHandler;
889                        return this;
890                }
891
892                /**
893                 * Sets the handler used for HTTP 503 Service Unavailable responses. Passing
894                 * {@code null} restores the built-in response.
895                 *
896                 * @param serviceUnavailableHandler the handler, or {@code null} for the built-in response
897                 * @return this builder
898                 */
899                @NonNull
900                public Builder serviceUnavailableHandler(@Nullable ServiceUnavailableHandler serviceUnavailableHandler) {
901                        this.serviceUnavailableHandler = serviceUnavailableHandler;
902                        return this;
903                }
904
905                /**
906                 * Sets the handler used for path-specific HTTP {@code OPTIONS} responses.
907                 * Passing {@code null} restores the built-in response.
908                 *
909                 * @param optionsHandler the handler, or {@code null} for the built-in response
910                 * @return this builder
911                 */
912                @NonNull
913                public Builder optionsHandler(@Nullable OptionsHandler optionsHandler) {
914                        this.optionsHandler = optionsHandler;
915                        return this;
916                }
917
918                /**
919                 * Sets the handler used for HTTP {@code OPTIONS *} responses. Passing
920                 * {@code null} restores the built-in response.
921                 *
922                 * @param optionsSplatHandler the handler, or {@code null} for the built-in response
923                 * @return this builder
924                 */
925                @NonNull
926                public Builder optionsSplatHandler(@Nullable OptionsSplatHandler optionsSplatHandler) {
927                        this.optionsSplatHandler = optionsSplatHandler;
928                        return this;
929                }
930
931                /**
932                 * Sets the handler used for uncaught exceptions. Passing {@code null}
933                 * restores the built-in response behavior.
934                 *
935                 * @param throwableHandler the handler, or {@code null} for the built-in behavior
936                 * @return this builder
937                 */
938                @NonNull
939                public Builder throwableHandler(@Nullable ThrowableHandler throwableHandler) {
940                        this.throwableHandler = throwableHandler;
941                        return this;
942                }
943
944                /**
945                 * Sets the handler used to derive HTTP {@code HEAD} responses. Passing
946                 * {@code null} restores the built-in response behavior.
947                 *
948                 * @param headHandler the handler, or {@code null} for the built-in behavior
949                 * @return this builder
950                 */
951                @NonNull
952                public Builder headHandler(@Nullable HeadHandler headHandler) {
953                        this.headHandler = headHandler;
954                        return this;
955                }
956
957                /**
958                 * Sets the handler used for allowed CORS preflight requests. Passing
959                 * {@code null} restores the built-in response behavior.
960                 *
961                 * @param corsPreflightAllowedHandler the handler, or {@code null} for the built-in behavior
962                 * @return this builder
963                 */
964                @NonNull
965                public Builder corsPreflightAllowedHandler(@Nullable CorsPreflightAllowedHandler corsPreflightAllowedHandler) {
966                        this.corsPreflightAllowedHandler = corsPreflightAllowedHandler;
967                        return this;
968                }
969
970                /**
971                 * Sets the handler used for rejected CORS preflight requests. Passing
972                 * {@code null} restores the built-in response behavior.
973                 *
974                 * @param corsPreflightRejectedHandler the handler, or {@code null} for the built-in behavior
975                 * @return this builder
976                 */
977                @NonNull
978                public Builder corsPreflightRejectedHandler(@Nullable CorsPreflightRejectedHandler corsPreflightRejectedHandler) {
979                        this.corsPreflightRejectedHandler = corsPreflightRejectedHandler;
980                        return this;
981                }
982
983                /**
984                 * Sets the handler used to apply allowed CORS response data. Passing
985                 * {@code null} restores the built-in response behavior.
986                 *
987                 * @param corsAllowedHandler the handler, or {@code null} for the built-in behavior
988                 * @return this builder
989                 */
990                @NonNull
991                public Builder corsAllowedHandler(@Nullable CorsAllowedHandler corsAllowedHandler) {
992                        this.corsAllowedHandler = corsAllowedHandler;
993                        return this;
994                }
995
996                /**
997                 * Sets the optional final response post-processor. Passing {@code null}
998                 * clears any previously configured post-processor.
999                 *
1000                 * @param postProcessor the post-processor, or {@code null} to clear it
1001                 * @return this builder
1002                 */
1003                @NonNull
1004                public Builder postProcessor(@Nullable PostProcessor postProcessor) {
1005                        this.postProcessor = postProcessor;
1006                        return this;
1007                }
1008
1009                @NonNull
1010                public ResponseMarshaler build() {
1011                        return new DefaultResponseMarshaler(this);
1012                }
1013        }
1014}