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.ThreadSafe; 023import java.util.Optional; 024import java.util.function.Function; 025import java.util.function.Supplier; 026 027import static java.util.Locale.ENGLISH; 028import static java.util.Objects.requireNonNull; 029 030/** 031 * An immutable selection of no compression or one response-compression codec with an optional 032 * application-supplied compressed-body provider. 033 * <p> 034 * Creating a plan does not compress or cache a body. Soklet first checks whether the selected coding 035 * can be used for this response and client, then computes bytes only if a body will be written. 036 * In particular, {@code HEAD} planning can select compressed representation headers without invoking 037 * the codec or provider. A plan cannot bypass transport eligibility or content-coding negotiation. 038 * <p> 039 * A provider can wrap Soklet's lazy compression operation with an application-owned cache. Cache keys 040 * must identify the exact uncompressed representation and the codec/configuration producing its bytes; 041 * a URL or weak ETag alone is not sufficient. Cache only reusable body bytes, not another request's 042 * response headers or cookies. Applications own cache capacity, expiration, invalidation, and the 043 * handling of private content. Soklet provides no implicit cache. 044 * <p> 045 * Plans retain codec and provider references. Codecs must be thread-safe. A provider is invoked 046 * synchronously on its request-handling thread; if a plan or provider is reused across requests, its 047 * captured state and cache must also support concurrent use. Returned byte arrays are not copied and 048 * must remain unmodified while retained for reuse or written by any response. 049 * 050 * @author <a href="https://www.revetkn.com">Mark Allen</a> 051 */ 052@ThreadSafe 053public final class ResponseCompressionPlan { 054 @NonNull 055 private static final ResponseCompressionPlan NONE_INSTANCE; 056 057 static { 058 NONE_INSTANCE = new ResponseCompressionPlan(null, null); 059 } 060 061 @Nullable 062 private final ResponseCompressionCodec codec; 063 @Nullable 064 private final String contentEncoding; 065 @Nullable 066 private final Function<@NonNull Supplier<byte @NonNull []>, byte @NonNull []> compressedBodyProvider; 067 068 private ResponseCompressionPlan(@Nullable ResponseCompressionCodec codec, 069 @Nullable Function<@NonNull Supplier<byte @NonNull []>, byte @NonNull []> compressedBodyProvider) { 070 this.codec = codec; 071 this.contentEncoding = codec == null ? null : validatedContentEncoding(codec.getContentEncoding()); 072 this.compressedBodyProvider = compressedBodyProvider; 073 } 074 075 /** 076 * Acquires the shared plan that declines response compression. 077 * 078 * @return the no-compression plan 079 */ 080 @NonNull 081 public static ResponseCompressionPlan none() { 082 return NONE_INSTANCE; 083 } 084 085 /** 086 * Selects a codec, letting Soklet invoke it lazily when the response needs compressed body bytes. 087 * <p> 088 * The codec's content coding is validated and snapshotted during this call; compression is not run. 089 * 090 * @param codec the codec to use 091 * @return a compression plan without a custom body provider 092 * @throws IllegalArgumentException if the codec's content coding is not a valid compression token 093 */ 094 @NonNull 095 public static ResponseCompressionPlan compress(@NonNull ResponseCompressionCodec codec) { 096 return new ResponseCompressionPlan(requireNonNull(codec), null); 097 } 098 099 /** 100 * Selects a codec and wraps its lazy body computation with application behavior, such as caching. 101 * <p> 102 * Soklet invokes the provider at most once per written response, after transport and content-coding 103 * checks pass, and never for {@code HEAD}. Its supplier is bound to this response's exact uncompressed 104 * body and the selected codec. The supplier is lazy and memoized per response: repeated successful 105 * calls return the same byte array without repeating compression. A cache hit need not call it. 106 * <p> 107 * The supplier is confined to this provider invocation and its invoking thread. Do not retain it, 108 * submit it to another thread, or call it after the provider returns. Complete all work synchronously. 109 * Cache the resulting bytes, not the supplier or request. The provider must return non-null bytes 110 * that decode to the exact response body using the selected codec's content coding; it must not 111 * mutate the supplied or returned arrays. A null result or an exception is a response-processing 112 * failure, not a request for an uncompressed fallback. 113 * 114 * @param codec the codec to use 115 * @param compressedBodyProvider the function that returns cached bytes or obtains them from Soklet's supplier 116 * @return a compression plan with a custom body provider 117 * @throws IllegalArgumentException if the codec's content coding is not a valid compression token 118 */ 119 @NonNull 120 public static ResponseCompressionPlan compress(@NonNull ResponseCompressionCodec codec, 121 @NonNull Function<@NonNull Supplier<byte @NonNull []>, byte @NonNull []> compressedBodyProvider) { 122 return new ResponseCompressionPlan(requireNonNull(codec), requireNonNull(compressedBodyProvider)); 123 } 124 125 /** 126 * The selected codec, if this plan requests compression. 127 * 128 * @return the codec, or {@link Optional#empty()} for {@link #none()} 129 */ 130 @NonNull 131 public Optional<@NonNull ResponseCompressionCodec> getCodec() { 132 return Optional.ofNullable(this.codec); 133 } 134 135 /** 136 * The validated lowercase content coding captured from the codec when this plan was created. 137 * <p> 138 * Soklet uses this snapshot for content-coding negotiation and the {@code Content-Encoding} header; 139 * later changes to a codec's reported coding cannot change a plan's meaning. 140 * 141 * @return the content coding, or {@link Optional#empty()} for {@link #none()} 142 */ 143 @NonNull 144 public Optional<@NonNull String> getContentEncoding() { 145 return Optional.ofNullable(this.contentEncoding); 146 } 147 148 /** 149 * The custom compressed-body provider, if supplied. 150 * <p> 151 * An empty value means either no compression was requested, or Soklet should obtain bytes directly 152 * from the selected codec. Provider execution belongs to the transport and obeys the lifetime 153 * contract of {@link #compress(ResponseCompressionCodec, Function)}. 154 * 155 * @return the custom provider, or {@link Optional#empty()} when absent 156 */ 157 @NonNull 158 public Optional<@NonNull Function<@NonNull Supplier<byte @NonNull []>, byte @NonNull []>> getCompressedBodyProvider() { 159 return Optional.ofNullable(this.compressedBodyProvider); 160 } 161 162 @NonNull 163 private static String validatedContentEncoding(@NonNull String contentEncoding) { 164 requireNonNull(contentEncoding, "Compression codec content encoding must not be null."); 165 166 if (contentEncoding.isEmpty()) 167 throw new IllegalArgumentException("Compression codec content encoding must be a nonempty HTTP token."); 168 169 for (int i = 0; i < contentEncoding.length(); ++i) { 170 char character = contentEncoding.charAt(i); 171 boolean tokenCharacter = (character >= 'a' && character <= 'z') 172 || (character >= 'A' && character <= 'Z') 173 || (character >= '0' && character <= '9') 174 || "!#$%&'*+-.^_`|~".indexOf(character) >= 0; 175 176 if (!tokenCharacter) 177 throw new IllegalArgumentException("Compression codec content encoding must be a single ASCII HTTP token."); 178 } 179 180 String normalizedContentEncoding = contentEncoding.toLowerCase(ENGLISH); 181 182 if (normalizedContentEncoding.equals("identity") || normalizedContentEncoding.equals("*")) 183 throw new IllegalArgumentException("Compression codec content encoding must not be identity or '*'; use ResponseCompressionPlan.none() to decline compression."); 184 185 return normalizedContentEncoding; 186 } 187}