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.ThreadSafe;
024import java.util.ArrayList;
025import java.time.Instant;
026import java.util.Collections;
027import java.util.List;
028import java.util.Map;
029import java.util.Optional;
030import java.util.Set;
031
032import static java.lang.String.format;
033import static java.util.Objects.requireNonNull;
034
035/**
036 * Utility methods for evaluating HTTP conditional requests against a selected dynamic representation.
037 * <p>
038 * This helper supports cache validation and optimistic concurrency for application responses without forcing resource
039 * methods into {@link MarshaledResponse}. Applications still own representation validators: choose the current
040 * {@link EntityTag}, {@code Last-Modified} instant, cache headers, and normal success response.
041 * <p>
042 * When a request precondition requires an immediate response, {@link #responseFor(Request, EntityTag, Instant)}
043 * returns a bodyless {@link Response} with status {@code 304 Not Modified} or {@code 412 Precondition Failed}.
044 * Otherwise it returns {@link Optional#empty()} and the application should build its normal response.
045 * {@link #evaluate(Request, EntityTag, Instant)} exposes the same decision as immutable data for application-owned
046 * responses; {@link #evaluateWithoutRepresentation(Request)} supports conditional creation against an absent resource.
047 * <p>
048 * Perform normal authorization, routing, and resource checks first. These helpers do not override an otherwise
049 * applicable failure such as {@code 401}, {@code 403}, {@code 404} on a non-creating endpoint, or {@code 405}.
050 * A typed {@link com.soklet.annotation.RequestBody} is unmarshaled before its resource method is invoked, so in-method
051 * evaluation does not promise header-before-body-validation ordering.
052 * <p>
053 * Evaluation describes a snapshot, not an atomic write. After a known no-effect storage race, reload fresh state and
054 * re-evaluate the client's conditions, or enforce an explicitly equivalent predicate atomically. A failed internal
055 * version compare-and-set alone does not justify {@code 412}. Under snapshot isolation an application may need a new
056 * transaction; uncertain commit outcomes require application recovery rather than blind retries.
057 * <p>
058 * {@code OPTIONS} ignores conditional values. Malformed entity-tag preconditions fail closed when they protect writes:
059 * malformed {@code If-Match} returns
060 * {@code 412 Precondition Failed}, and malformed {@code If-None-Match} does the same for non-{@code GET}/{@code HEAD}
061 * requests to applicable methods. Malformed {@code If-None-Match} on {@code GET} and {@code HEAD} is treated as a
062 * cache miss and still suppresses {@code If-Modified-Since}. The same policy applies to parser-budget exhaustion.
063 * Applications choose required-precondition policies such as {@code 428}; this API neither imposes them nor treats a
064 * nonempty satisfied set as adequate lost-update protection. Strong {@code If-Match} comparison is never weakened for
065 * transport compression: a compressed response's weak ETag cannot satisfy it.
066 * <p>
067 * Applications constructing {@code 304} responses own the selected representation's required cache and validator
068 * metadata. RFC 9110 permits an application-established already-applied successful response for false
069 * {@code If-Match}/{@code If-Unmodified-Since}, not a failed {@code If-None-Match}; the evaluator does not infer it.
070 *
071 * @author <a href="https://www.revetkn.com">Mark Allen</a>
072 */
073@ThreadSafe
074public final class ConditionalRequests {
075        @NonNull
076        private static final Set<@NonNull String> CONTROLLED_EXTRA_HEADER_NAMES;
077
078        static {
079                CONTROLLED_EXTRA_HEADER_NAMES = Set.of(
080                                "content-length",
081                                "content-type",
082                                "etag",
083                                "last-modified",
084                                "transfer-encoding"
085                );
086        }
087
088        private ConditionalRequests() {
089                // Non-instantiable
090        }
091
092        /**
093         * Evaluates conditional fields against an existing selected representation, without constructing a response.
094         * <p>
095         * Either validator may be unavailable. In particular, {@code null}/{@code null} means an existing representation
096         * without validators, never a missing representation. Use {@link #evaluateWithoutRepresentation(Request)} for absence.
097         * A wildcard {@code If-Match} succeeds for an existing representation even with no current ETag; a wildcard
098         * {@code If-None-Match} does not. With no ETag, valid tag lists cannot match. With a weak current tag, no valid
099         * {@code If-Match} list can strongly match; weak comparison still applies to {@code If-None-Match}.
100         * <p>
101         * Repeated entity-tag fields are combined in occurrence order. Valid empty lists match nothing. Tag fields suppress
102         * their corresponding date fields even when empty or malformed. Invalid/unavailable dates are ignored, and valid
103         * dates are compared at whole-second precision. The first decisive precondition is returned; ignored or later fields
104         * are not inspected for diagnostics. {@code OPTIONS} returns an empty {@link ConditionalRequestResult.Proceed}
105         * without parsing conditional values.
106         * <p>
107         * Entity-tag parsing first performs quote-aware bounded splitting, counting empty elements but not quoted commas.
108         * The budget is currently 256 elements. A reached limit immediately reports
109         * {@link ConditionalRequestResult.PreconditionFailed.Reason#ENTITY_TAG_LIST_LIMIT_EXCEEDED}; otherwise an unclosed
110         * quote reports {@link ConditionalRequestResult.PreconditionFailed.Reason#MALFORMED}, then invalid individual tags do
111         * the same. No blanket malformed-versus-limit priority applies when input has both problems.
112         *
113         * @param request the request whose conditional fields should be evaluated
114         * @param entityTag the existing representation's entity tag, or {@code null} if unavailable
115         * @param lastModified its last-modified instant, or {@code null} if unavailable
116         * @return immutable conditional decision for the supplied snapshot
117         */
118        @NonNull
119        public static ConditionalRequestResult evaluate(@NonNull Request request,
120                        @Nullable EntityTag entityTag, @Nullable Instant lastModified) {
121                requireNonNull(request);
122                return ConditionalRequestEvaluator.evaluate(ConditionalRequestEvaluator.RequestContext.fromRequest(request),
123                                entityTag, lastModified, true);
124        }
125
126        /**
127         * Evaluates conditional fields when no current representation exists and the request can otherwise proceed,
128         * such as a creating PUT. Do not use null validators with {@link #evaluate(Request, EntityTag, Instant)} to mean absence.
129         * <p>
130         * On applicable methods, any valid {@code If-Match}, including a wildcard or empty list, fails. Any valid
131         * {@code If-None-Match} evaluates true, including a wildcard or empty list. Date fields are ignored because no
132         * modification time exists. This entry point cannot return {@link ConditionalRequestResult.NotModified}; its
133         * {@link ConditionalRequestResult.Proceed} has either an empty satisfied set or just {@code IF_NONE_MATCH}.
134         * Existing malformed/over-limit policies still apply, and {@code OPTIONS} always proceeds with an empty set.
135         * <p>
136         * Non-creating endpoints should ordinarily return their normal missing-resource response before evaluation.
137         * Conditional creation still requires an atomic insert-if-absent and fresh evaluation after a known target-identity
138         * conflict; arbitrary database errors or uncertain commits are not blind-retry signals.
139         *
140         * @param request the request to evaluate against no current representation
141         * @return immutable decision; never {@link ConditionalRequestResult.NotModified}
142         */
143        @NonNull
144        public static ConditionalRequestResult evaluateWithoutRepresentation(@NonNull Request request) {
145                requireNonNull(request);
146                return ConditionalRequestEvaluator.evaluate(ConditionalRequestEvaluator.RequestContext.fromRequest(request),
147                                null, null, false);
148        }
149
150        /**
151         * Evaluates conditional request headers against an existing representation and builds the default response.
152         * <p>
153         * Null validators mean unavailable validators, never a missing representation. {@code OPTIONS} proceeds without
154         * parsing conditional values. See {@link #evaluate(Request, EntityTag, Instant)} to construct application-owned
155         * responses, and {@link #evaluateWithoutRepresentation(Request)} for a missing representation.
156         *
157         * @param request      the request whose conditional headers should be evaluated
158         * @param entityTag    the current representation's entity tag, or {@code null} if unavailable
159         * @param lastModified the current representation's last-modified instant, or {@code null} if unavailable
160         * @return a short-circuit response, or {@link Optional#empty()} when the application should continue normally
161         */
162        @NonNull
163        public static Optional<@NonNull Response> responseFor(@NonNull Request request,
164                                                                                                                                                                                 @Nullable EntityTag entityTag,
165                                                                                                                                                                                 @Nullable Instant lastModified) {
166                return responseFor(request, entityTag, lastModified, null);
167        }
168
169        /**
170         * Evaluates conditional request headers against an existing representation and builds the default response.
171         * <p>
172         * Null validators mean unavailable validators, never a missing representation. {@code OPTIONS} proceeds without
173         * parsing conditional values. All failure reasons map to a bodyless {@code 412}; see
174         * {@link #evaluate(Request, EntityTag, Instant)} for a fine-grained decision.
175         * <p>
176         * {@code extraHeaders} are included on short-circuit {@code 304} and {@code 412} responses. They are intended for
177         * response metadata such as {@code Cache-Control} or {@code Vary}; validator and body-framing headers are rejected
178         * because they are controlled by this helper.
179         *
180         * @param request      the request whose conditional headers should be evaluated
181         * @param entityTag    the current representation's entity tag, or {@code null} if unavailable
182         * @param lastModified the current representation's last-modified instant, or {@code null} if unavailable
183         * @param extraHeaders endpoint-specific metadata headers to include on short-circuit responses
184         * @return a short-circuit response, or {@link Optional#empty()} when the application should continue normally
185         */
186        @NonNull
187        public static Optional<@NonNull Response> responseFor(@NonNull Request request,
188                                                                                                                                                                                 @Nullable EntityTag entityTag,
189                                                                                                                                                                                 @Nullable Instant lastModified,
190                                                                                                                                                                                 @Nullable Map<@NonNull String, @NonNull List<@NonNull String>> extraHeaders) {
191                requireNonNull(request);
192                Map<String, List<String>> copiedExtraHeaders = copyExtraHeaders(extraHeaders);
193                Instant truncatedLastModified = lastModified == null ? null : ConditionalRequestEvaluator.truncateToSeconds(lastModified);
194                ConditionalRequestResult result = evaluate(request, entityTag, truncatedLastModified);
195
196                return switch (result) {
197                        case ConditionalRequestResult.Proceed ignored -> Optional.empty();
198                        case ConditionalRequestResult.NotModified ignored -> Optional.of(bodylessResponse(304, entityTag, truncatedLastModified, copiedExtraHeaders));
199                        case ConditionalRequestResult.PreconditionFailed ignored -> Optional.of(bodylessResponse(412, entityTag, truncatedLastModified, copiedExtraHeaders));
200                };
201        }
202
203        /**
204         * Builds validator headers for the supplied representation validators.
205         *
206         * @param entityTag    the current representation's entity tag, or {@code null} if unavailable
207         * @param lastModified the current representation's last-modified instant, or {@code null} if unavailable
208         * @return immutable {@code ETag} and {@code Last-Modified} headers for the supplied validators
209         */
210        @NonNull
211        public static Map<@NonNull String, @NonNull List<@NonNull String>> validatorHeaders(@Nullable EntityTag entityTag,
212                                                                                                                                                                                                                                                                                                                                                 @Nullable Instant lastModified) {
213                return validatorHeadersFor(entityTag, lastModified == null ? null : ConditionalRequestEvaluator.truncateToSeconds(lastModified));
214        }
215
216        /**
217         * Builds validator headers plus endpoint-specific metadata headers.
218         * <p>
219         * {@code extraHeaders} are intended for response metadata such as {@code Cache-Control} or {@code Vary}; validator
220         * and body-framing headers are rejected because they are controlled by this helper.
221         *
222         * @param entityTag    the current representation's entity tag, or {@code null} if unavailable
223         * @param lastModified the current representation's last-modified instant, or {@code null} if unavailable
224         * @param extraHeaders endpoint-specific metadata headers to include with the validators
225         * @return immutable combined headers
226         */
227        @NonNull
228        public static Map<@NonNull String, @NonNull List<@NonNull String>> validatorHeaders(@Nullable EntityTag entityTag,
229                                                                                                                                                                                                                                                                                                                                                 @Nullable Instant lastModified,
230                                                                                                                                                                                                                                                                                                                                                 @Nullable Map<@NonNull String, @NonNull List<@NonNull String>> extraHeaders) {
231                return responseHeaders(
232                                entityTag,
233                                lastModified == null ? null : ConditionalRequestEvaluator.truncateToSeconds(lastModified),
234                                copyExtraHeaders(extraHeaders)
235                );
236        }
237
238        @NonNull
239        private static Response bodylessResponse(@NonNull Integer statusCode,
240                                                                                                                                                                         @Nullable EntityTag entityTag,
241                                                                                                                                                                         @Nullable Instant lastModified,
242                                                                                                                                                                         @NonNull Map<@NonNull String, @NonNull List<@NonNull String>> extraHeaders) {
243                requireNonNull(statusCode);
244                requireNonNull(extraHeaders);
245
246                return Response.withStatusCode(statusCode)
247                                .headers(responseHeaders(entityTag, lastModified, extraHeaders))
248                                .build();
249        }
250
251        @NonNull
252        private static Map<@NonNull String, @NonNull List<@NonNull String>> responseHeaders(@Nullable EntityTag entityTag,
253                                                                                                                                                                                                                                                                                                                                                 @Nullable Instant lastModified,
254                                                                                                                                                                                                                                                                                                                                                 @NonNull Map<@NonNull String, @NonNull List<@NonNull String>> extraHeaders) {
255                requireNonNull(extraHeaders);
256                Map<String, List<String>> headers = new LinkedCaseInsensitiveMap<>();
257                headers.putAll(validatorHeadersFor(entityTag, lastModified));
258                headers.putAll(extraHeaders);
259                return Collections.unmodifiableMap(headers);
260        }
261
262        @NonNull
263        private static Map<@NonNull String, @NonNull List<@NonNull String>> validatorHeadersFor(@Nullable EntityTag entityTag,
264                                                                                                                                                                                                                                                                                                                                                                @Nullable Instant truncatedLastModified) {
265                Map<String, List<String>> headers = new LinkedCaseInsensitiveMap<>();
266
267                if (entityTag != null)
268                        headers.put("ETag", List.of(entityTag.toHeaderValue()));
269
270                if (truncatedLastModified != null)
271                        headers.put("Last-Modified", List.of(HttpDate.toHeaderValue(truncatedLastModified)));
272
273                return Collections.unmodifiableMap(headers);
274        }
275
276        @NonNull
277        private static Map<@NonNull String, @NonNull List<@NonNull String>> copyExtraHeaders(
278                        @Nullable Map<@NonNull String, @NonNull List<@NonNull String>> extraHeaders) {
279                if (extraHeaders == null || extraHeaders.isEmpty())
280                        return Map.of();
281
282                Map<String, List<String>> copiedHeaders = new LinkedCaseInsensitiveMap<>();
283
284                for (Map.Entry<String, List<String>> entry : Utilities.immutableValueLists(extraHeaders, true).entrySet()) {
285                        String headerName = requireNonNull(entry.getKey());
286                        rejectControlledExtraHeader(headerName);
287
288                        List<String> copiedHeaderValues = new ArrayList<>(requireNonNull(entry.getValue()));
289                        copiedHeaderValues.forEach(value -> {
290                                requireNonNull(value, format("Header '%s' includes a null value.", headerName));
291                                Utilities.validateHeaderNameAndValue(headerName, value);
292                        });
293                        copiedHeaders.put(headerName, List.copyOf(copiedHeaderValues));
294                }
295
296                return Collections.unmodifiableMap(copiedHeaders);
297        }
298
299        private static void rejectControlledExtraHeader(@NonNull String headerName) {
300                requireNonNull(headerName);
301                String normalizedHeaderName = headerName.toLowerCase(java.util.Locale.US);
302
303                if (CONTROLLED_EXTRA_HEADER_NAMES.contains(normalizedHeaderName))
304                        throw new IllegalArgumentException(format("Header '%s' is controlled by conditional request responses; supply validators through the dedicated arguments.", headerName));
305        }
306}