From c21c98b102902278ec003a2e95acb606212b238a Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc Date: Sun, 25 Oct 2026 15:35:52 +0100 Subject: [PATCH] Cache validated gzip fallback representations [#281] --- docs/GZIP_CACHE_MEASUREMENTS.md | 82 +++++++++ docs/HTTP_ASSETS.md | 66 ++++++-- docs/PROJECT_STATUS.md | 10 +- ...DR-009-modules-et-assets-reproductibles.md | 23 ++- docs/adr/README.md | 5 +- include/webfront/http/BuffersPolicy.hpp | 19 ++- include/webfront/http/GzipCache.hpp | 118 +++++++++++++ include/webfront/http/HTTPServer.hpp | 15 +- test/unit/CMakeLists.txt | 4 + test/unit/GzipCacheBenchmark.cpp | 99 +++++++++++ test/unit/GzipTests.cpp | 155 ++++++++++++++++++ test/unit/HTTPEncodingTests.cpp | 140 ++++++++++++++++ 12 files changed, 705 insertions(+), 31 deletions(-) create mode 100644 docs/GZIP_CACHE_MEASUREMENTS.md create mode 100644 include/webfront/http/GzipCache.hpp create mode 100644 test/unit/GzipCacheBenchmark.cpp diff --git a/docs/GZIP_CACHE_MEASUREMENTS.md b/docs/GZIP_CACHE_MEASUREMENTS.md new file mode 100644 index 00000000..7d107030 --- /dev/null +++ b/docs/GZIP_CACHE_MEASUREMENTS.md @@ -0,0 +1,82 @@ +# Gzip fallback cache measurements (#281) + +Measured on Linux x86-64, GCC 15.2.0, Release (`-O3 -DNDEBUG`), 2026-10-25. +Both executables enable `_GLIBCXX_ASSERTIONS` and `-ftrivial-auto-var-init=pattern`. +These are local timing observations, not performance assertions or cross-platform guarantees. +The benchmark calls the real `RequestHandler` with an in-memory compressed provider: URI +parsing, provider reads, negotiation, decoding/cache lookup and response construction are +included; network I/O, browser decompression and filesystem latency are excluded. + +The before executable uses `HTTPServer.hpp` from commit `642a435`, with a counter added at +its `decodeGzip` call. The after executable uses the new cache and its decode-attempt and +retained-byte counters. Each row performs **200 requests**. Repeated rows use one handler +and include its first cold request; cold rows create a fresh handler for every request. +The optional target also runs the new handler with retention disabled as an uncached control. +No decoder algorithm or gzip validation change is included in #281. + +The neutral fixed/dynamic/optional fixtures are from `test/unit/GzipFixtures.hpp`. The +application input is the generated developer compiler bundle `build-distribution/compiler.mjs`, +compressed with Python's `gzip.compress(bytes, mtime=0)`. It is an application bundle, +not a restored core provider. Its SHA-256 is listed below so regenerated bundle changes +cannot silently be mistaken for the same workload. + +## Sizes and retained memory + +| Asset | Compressed bytes | Decoded bytes | Before retained bytes | After retained bytes | +| --- | ---: | ---: | ---: | ---: | +| fixed | 499 | 23768 | 0 | 24357 | +| dynamic | 453 | 23768 | 0 | 24311 | +| optional | 476 | 23768 | 0 | 24334 | +| application | 22902 | 78508 | 0 | 101500 | + +Retained bytes include both string capacities and terminators, entry metadata and list links +(90 bytes of accounted overhead per entry on this libstdc++ build). GET and HEAD retain the +same entry. This measures cache retention, **not peak process memory**: provider/input bytes, +response buffers, decoder temporaries and allocator bookkeeping are outside these figures. +Every cold request still allocates a bounded decoded representation; admission temporarily +constructs a retained copy. An evicted/disabled/oversized entry retains zero bytes. + +## Timing and decode counts + +Before: **200 decodes** in every row. After: **1 decode** for repeated requests and +**200 decodes** for cold requests. With cache retention disabled: **200 decodes**, zero +retained bytes. Tests separately verify mixed GET/HEAD reuse and a smaller active output +budget, content replacement, invalid streams, admission limits, eviction and shutdown. + +| Asset | Method | Repeated before (µs/request) | Repeated after | Cold before | Cold after | +| --- | --- | ---: | ---: | ---: | ---: | +| fixed | GET | 74.60 | 2.30 | 76.30 | 76.14 | +| fixed | HEAD | 75.14 | 1.83 | 77.19 | 76.45 | +| dynamic | GET | 75.11 | 2.27 | 76.58 | 75.71 | +| dynamic | HEAD | 75.22 | 1.81 | 76.17 | 75.75 | +| optional | GET | 75.80 | 2.28 | 76.52 | 76.40 | +| optional | HEAD | 75.21 | 1.82 | 75.57 | 76.17 | +| application | GET | 921.80 | 32.54 | 934.22 | 916.78 | +| application | HEAD | 907.11 | 31.15 | 894.37 | 913.72 | + +The improvement comes from eliminating repeat validation, including CRC32 and DEFLATE. +Cold application decoding remains about 0.9 ms here, on the I/O thread; #283 must address +that occupancy. The warm application cost still includes reading and comparing 22.9 KiB of +compressed bytes; #282 can use the cold rows as a decoder baseline. Small timing differences +between cold before/after runs include allocation and host scheduling noise. + +## Reproduction + +With the normal CEF-off test build configured: + +```bash +cmake --build build --target gzip_cache_benchmark --parallel 2 +# Without an argument, runs all three neutral fixtures. +build/test/unit/gzip_cache_benchmark +# Optionally use a generated application bundle, or any complete gzip asset under 4 MiB decoded. +python3 -c 'import gzip,pathlib; pathlib.Path("/tmp/wf-compiler.mjs.gz").write_bytes(gzip.compress(pathlib.Path("build-distribution/compiler.mjs").read_bytes(), mtime=0))' +build/test/unit/gzip_cache_benchmark /tmp/wf-compiler.mjs.gz +``` + +The CSV reports sizes, iterations, actual decode attempts, retained bytes and mean time per +request for both enabled and disabled retention. It is excluded from the normal build and +CTest; no timing threshold is imposed. Re-run on the target compiler/platform before using +the timings to justify decoder changes. For a historical before comparison, compile the same +harness against the pre-cache `RequestHandler` and count its `decodeGzip` calls. + +Application bundle SHA-256: `5f36728943433f1b88eadcdc0db910133257b4502c8faec3357168b6739f70bc`. diff --git a/docs/HTTP_ASSETS.md b/docs/HTTP_ASSETS.md index 6dc822aa..41171867 100644 --- a/docs/HTTP_ASSETS.md +++ b/docs/HTTP_ASSETS.md @@ -2,9 +2,10 @@ HTTP asset negotiation and fallback apply to every frontend and to custom filesystem providers. -The embedded Jasmine, React, Babel and xterm JavaScript/CSS payloads use gzip. -The Jasmine favicon is served as its original PNG. If a client does not -accept gzip, the HTTP server decodes the asset and serves identity with the decoded `Content-Length` and no +Application providers generated by `wf embed` and custom filesystem providers can serve +gzip resources. The core assets are identity representations; see the current inventory in +[Embedded assets](EMBEDDED_ASSETS.md). If a client does not accept gzip, the HTTP server +decodes the asset and serves identity with the decoded `Content-Length` and no `Content-Encoding`. Encoded responses carry `Vary: Accept-Encoding`; explicit `q=0` exclusions are respected. Duplicate mentions accept a coding if any valid mention accepts it, regardless of their order or which field contains them: `gzip;q=0, gzip` and `gzip, gzip;q=0` @@ -24,26 +25,56 @@ coding nor identity is acceptable, or a custom provider uses an unsupported codi (such as Brotli) the client does not accept, the server returns HTTP 406. Custom codings can still be served directly to accepting clients. -Fallback decoding runs synchronously on the server I/O thread and is repeated for each -request, including HEAD to validate the stream and compute its decoded length. Decoded -assets are not cached. Stored DEFLATE blocks are copied in bulk and match copies grow the -output once per match; Huffman decoding still reads individual bits. Follow-ups track -[validated asset caching and HEAD metadata](https://github.com/ambroise-leclerc/WebFront/issues/281), -[buffered bit reads and benchmarks](https://github.com/ambroise-leclerc/WebFront/issues/282), and -[cold decoding off the I/O thread](https://github.com/ambroise-leclerc/WebFront/issues/283). +## Validated representation cache -Gzip remains the embedded format so fallback needs no compiled dependency or Brotli dictionary. -Pinned versions, reproducible generation and current stored/decoded resource checks are -documented in [Embedded browser dependencies](EMBEDDED_ASSETS.md). Returning them to Brotli -would require a separate decoder dependency and is deferred. +Each server owns a bounded LRU cache through its `RequestHandler`. It is destroyed after +server tasks have drained, with no global state, background work or extra shutdown join. +A copied handler starts with an empty cache; applications never implicitly share entries. +The server context serializes requests: a cold synchronous decode completes before another +request can miss on the same revision. There is no concurrent decode worker or in-flight table. +Moving cold decoding off the I/O thread remains [#283](https://github.com/ambroise-leclerc/WebFront/issues/283). + +Keys contain the **complete compressed bytes**, rather than a pathname, borrowed pointer, +modification time, checksum alone or unvalidated ISIZE trailer. Every request still opens +and reads the provider. Changed bytes at the same path cause a new validation; identical +bytes at different paths or with the `x-gzip` alias share an entry. A custom provider needs +no revision API, but must keep its backing storage valid and stable throughout each read. +Older revisions remain eligible for LRU eviction; returning to exactly those bytes is safe. + +Only successful full gzip validation creates an entry. It stores decoded content and thus +its validated length. GET reuses the content; HEAD reuses its length without copying decoded +content into the response. Each hit checks the **current** decoded output budget. Corrupt +streams and over-budget failures are never cached as successful representations. Pass-through +and 406 negotiation do not access the cache. + +The default retention budget is **8 MiB per server**, allocated lazily. LRU eviction accounts +for both compressed and decoded string capacities plus their terminators, entry metadata and +two list links. Allocator bookkeeping is implementation-dependent and excluded. The fixed +cache object and counters, provider storage, request/response buffers and temporary cold +decoding allocations are outside this retention budget. Admission may temporarily construct +one additional entry before eviction, bounded by the same budget; the output limit separately +bounds cold decoded bytes. A representation too large to retain is still validated and served +under the output budget, without evicting useful entries; repeated requests decode it again. +There is no separate length-only cache for oversized HEAD responses. + +Set `maxDecodedAssetCacheSize` on the buffer policy (or the sixth `CustomBuffersPolicy` +argument) to change retention. The retention budget is captured at handler construction; +the decoded output budget is read for every fallback request. Zero retention disables +caching, including HEAD metadata. Policies without this member inherit 8 MiB. +`RequestHandler::fallbackCacheStatistics()` exposes decode attempts, hits (including budget-rejected hits), entries and accounted retained bytes; read it +on the server context. The LRU lookup compares compressed bytes linearly across retained +entries; gzip pass-through remains independent of this cost. Decoder throughput and buffered +bit reads remain [#282](https://github.com/ambroise-leclerc/WebFront/issues/282). + +See [gzip cache measurements](GZIP_CACHE_MEASUREMENTS.md) for cold/repeated GET and HEAD data +and the optional benchmark target. ## Fallback budget The limit applies to the sum of decoded bytes across all gzip members, for GET and HEAD. Gzip pass-through to an accepting client does not use this budget. A smaller budget reduces the work and memory a fallback request can consume, but it is not an I/O-thread time limit. -All bundled assets fit under the 4 MiB default; custom applications can override it through -their existing buffer policy: +Applications can override decoding and retention through their buffer policy: ```cpp #include @@ -51,6 +82,7 @@ their existing buffer policy: struct AppBuffers : webfront::http::DefaultBuffersPolicy { static constexpr std::size_t maxDecodedAssetSize = 1024 * 1024; + static constexpr std::size_t maxDecodedAssetCacheSize = 2 * 1024 * 1024; }; using App = webfront::BasicWF; ``` @@ -58,4 +90,4 @@ using App = webfront::BasicWF + size_t MaxDecodedAssetSize = defaultMaxDecodedAssetSize, + size_t MaxDecodedAssetCacheSize = defaultMaxDecodedAssetCacheSize> struct CustomBuffersPolicy { static constexpr size_t receptionBufferSize = ReceptionSize; static constexpr size_t emissionBufferSize = EmissionSize; static constexpr size_t functionCallBufferSize = FunctionCallSize; static constexpr size_t maxMessageSize = MaxMessageSize; static constexpr size_t maxDecodedAssetSize = MaxDecodedAssetSize; + static constexpr size_t maxDecodedAssetCacheSize = MaxDecodedAssetCacheSize; }; /// The policy's optional maxMessageSize: a WebSocket closes the connection with @@ -75,6 +81,17 @@ constexpr size_t maxDecodedAssetSize() { return defaultMaxDecodedAssetSize; } +/** @brief Optional retained gzip cache budget. Zero disables retention; legacy policies use 8 MiB. */ +template +constexpr size_t maxDecodedAssetCacheSize() { + if constexpr (requires { + { Policy::maxDecodedAssetCacheSize } -> std::convertible_to; + }) + return Policy::maxDecodedAssetCacheSize; + else + return defaultMaxDecodedAssetCacheSize; +} + static_assert(BuffersPolicyType); } // namespace webfront::http diff --git a/include/webfront/http/GzipCache.hpp b/include/webfront/http/GzipCache.hpp new file mode 100644 index 00000000..9fb1f37a --- /dev/null +++ b/include/webfront/http/GzipCache.hpp @@ -0,0 +1,118 @@ +/** @brief Application-owned, bounded LRU of fully validated gzip identity representations. */ +#pragma once + +#include "Gzip.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace webfront::http::gzip { + +/** + * @brief Serial-context cache keyed by complete compressed bytes, independent of filesystem paths. + * @note Like RequestHandler, calls require serialization on the server context. A cold decode + * finishes before another request runs, so queued misses for the same bytes reuse its result. + * Copies start empty; no cache storage is implicitly shared between applications. + */ +class ValidatedCache { +public: + struct Statistics { + std::size_t decodes{}; + std::size_t hits{}; + std::size_t entries{}; + std::size_t retainedBytes{}; + }; + + explicit ValidatedCache(std::size_t cacheBudget) : budget(cacheBudget) {} + ValidatedCache(const ValidatedCache& other) : budget(other.budget) {} + ValidatedCache& operator=(const ValidatedCache& other) { + if (this != &other) { + entries.clear(); + stats = {}; + budget = other.budget; + } + return *this; + } + ValidatedCache(ValidatedCache&& other) noexcept : budget(other.budget), entries(std::move(other.entries)), stats(std::exchange(other.stats, {})) {} + ValidatedCache& operator=(ValidatedCache&& other) noexcept { + if (this != &other) { + entries = std::move(other.entries); + budget = other.budget; + stats = std::exchange(other.stats, {}); + } + return *this; + } + + /** @brief Replaces compressed content with identity (or clears it for HEAD), returning validated length. */ + std::optional resolve(std::string& content, std::size_t outputLimit, bool head = false) { + auto found = std::find_if(entries.begin(), entries.end(), [&](const Entry& entry) { + return entry.encoded == content; + }); + if (found != entries.end()) { + ++stats.hits; + // Re-check the current policy even when a larger budget validated this revision earlier. + if (found->decoded.size() > outputLimit) + return {}; + entries.splice(entries.begin(), entries, found); + const auto length = found->decoded.size(); + if (head) + content.clear(); + else + content = found->decoded; + return length; + } + ++stats.decodes; + auto decoded = decodeGzip(content, outputLimit); + if (!decoded) + return {}; + const auto length = decoded->size(); + retain(content, *decoded); + if (head) + content.clear(); + else + content = std::move(*decoded); + return length; + } + + [[nodiscard]] Statistics statistics() const { + auto result = stats; + result.entries = entries.size(); + return result; + } + +private: + struct Entry { + std::string encoded; + std::string decoded; + std::size_t charge; + }; + // Includes string capacities/terminators, entry metadata and the two list links. + // Allocator bookkeeping is implementation-defined and excluded. + static constexpr std::size_t overhead = sizeof(Entry) + 2 * sizeof(void*) + 2; + std::size_t budget; + std::list entries; + Statistics stats; + + void retain(std::string_view encoded, std::string_view decoded) { + // Oversized results do not evict useful entries or allocate a retained copy. + if (budget < overhead || encoded.size() > budget - overhead || decoded.size() > budget - overhead - encoded.size()) + return; + Entry entry{std::string(encoded), std::string(decoded), 0}; + if (entry.encoded.capacity() > budget - overhead || entry.decoded.capacity() > budget - overhead - entry.encoded.capacity()) + return; + entry.charge = overhead + entry.encoded.capacity() + entry.decoded.capacity(); + while (stats.retainedBytes > budget - entry.charge) { + stats.retainedBytes -= entries.back().charge; + entries.pop_back(); + } + entries.push_front(std::move(entry)); + stats.retainedBytes += entries.front().charge; + } +}; + +} // namespace webfront::http::gzip diff --git a/include/webfront/http/HTTPServer.hpp b/include/webfront/http/HTTPServer.hpp index 7ba6762c..59137898 100644 --- a/include/webfront/http/HTTPServer.hpp +++ b/include/webfront/http/HTTPServer.hpp @@ -12,7 +12,7 @@ #include "AcceptEncoding.hpp" #include "BuffersPolicy.hpp" #include "Encodings.hpp" -#include "Gzip.hpp" +#include "GzipCache.hpp" #include "MimeType.hpp" #include "WebSocket.hpp" @@ -290,6 +290,9 @@ class RequestHandler { RequestHandler& operator=(const RequestHandler&) = default; RequestHandler& operator=(RequestHandler&&) = default; + /** @brief Per-handler gzip cache counters and retained storage; read on the server context. */ + [[nodiscard]] gzip::ValidatedCache::Statistics fallbackCacheStatistics() const { return fallbackCache.statistics(); } + Response handleRequest(Request request) { auto requestPath = filePath(request.uri); if (!requestPath) return Response::getStatusResponse(Response::badRequest); @@ -312,7 +315,8 @@ class RequestHandler { if (auto error = readFile(request, path, response)) return *error; response.statusCode = Response::ok; - response.headers.emplace_back("Content-Length", std::to_string(response.content.size())); + if (!response.getHeaderValue("Content-Length")) + response.headers.emplace_back("Content-Length", std::to_string(response.content.size())); response.headers.emplace_back("Content-Type", MimeType(path.extension().string()).toString()); if (request.method == Request::Method::Head) response.content.clear(); @@ -383,7 +387,7 @@ class RequestHandler { return error; } - static std::optional negotiateEncoding(const Request& request, std::string_view coding, Response& response) { + std::optional negotiateEncoding(const Request& request, std::string_view coding, Response& response) { response.headers.emplace_back("Vary", "Accept-Encoding"); if (request.acceptsEncoding(coding)) { response.headers.emplace_back("Content-Encoding", coding); @@ -391,15 +395,16 @@ class RequestHandler { } if (!request.acceptsEncoding("identity") || !encoding::isGzip(coding)) return encodingError(Response::notAcceptable); - auto decoded = gzip::decodeGzip(response.content, maxDecodedAssetSize()); + auto decoded = fallbackCache.resolve(response.content, maxDecodedAssetSize(), request.method == Request::Method::Head); if (!decoded) return encodingError(Response::internalServerError); - response.content = std::move(*decoded); + response.headers.emplace_back("Content-Length", std::to_string(*decoded)); return {}; } FS fs; detail::BoundContentPolicy contentPolicy; + gzip::ValidatedCache fallbackCache{maxDecodedAssetCacheSize()}; }; template diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index a8088823..6b26efac 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -171,3 +171,7 @@ add_test(NAME AddSubdirectoryConsumer -DENABLE_CACHE=OFF "-DCMAKE_CXX_COMPILER_LAUNCHER:STRING=$" -DCMAKE_BUILD_TYPE=$ -DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}) set_tests_properties(AddSubdirectoryConsumer PROPERTIES TIMEOUT 600) + +# Manual timing evidence for gzip cache/cold-decode work; never a timing-based test. +add_executable(gzip_cache_benchmark EXCLUDE_FROM_ALL GzipCacheBenchmark.cpp) +target_link_libraries(gzip_cache_benchmark PRIVATE WebFront_test_hardening WebFront_warnings WebFront_options WebFront) diff --git a/test/unit/GzipCacheBenchmark.cpp b/test/unit/GzipCacheBenchmark.cpp new file mode 100644 index 00000000..bd5a9a33 --- /dev/null +++ b/test/unit/GzipCacheBenchmark.cpp @@ -0,0 +1,99 @@ +// Optional manual benchmark: cmake --build --target gzip_cache_benchmark +#include "GzipFixtures.hpp" +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +struct BundleFS { + explicit BundleFS(std::filesystem::path) {} + static inline std::vector words; + static inline std::size_t size{}; + static void load(std::string_view bytes) { + size = bytes.size(); + words.assign((size + 7) / 8, 0); + for (std::size_t index = 0; index < size; ++index) + words[index / 8] |= static_cast(static_cast(bytes[index])) << ((7 - index % 8) * 8); + } + std::optional open(std::filesystem::path) { + return webfront::fs::File(words, size, "gzip"); + } +}; + +template +void measure(std::string_view label, bool head, bool cold) { + using namespace webfront::http; + using Policy = CustomBuffersPolicy<8192, 8192, 32768, defaultMaxMessageSize, defaultMaxDecodedAssetSize, CacheBudget>; + using Handler = RequestHandler; + constexpr unsigned iterations = 200; + Handler handler("."); + Request request; + request.method = head ? Request::Method::Head : Request::Method::Get; + request.uri = "/bundle.js"; + std::size_t decodes = 0, retained = 0, length = 0; + const auto start = std::chrono::steady_clock::now(); + for (unsigned iteration = 0; iteration < iterations; ++iteration) { + auto run = [&](Handler& active) { + const auto response = active.handleRequest(request); + if (response.statusCode != Response::ok) + throw std::runtime_error("fallback failed"); + length = std::stoull(*response.getHeaderValue("Content-Length")); + const auto stats = active.fallbackCacheStatistics(); + retained = stats.retainedBytes; + if (cold) + decodes += stats.decodes; + else + decodes = stats.decodes; + }; + if (cold) { + Handler fresh("."); + run(fresh); + } else { + run(handler); + } + } + const auto elapsed = std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + std::cout << label << ',' << (head ? "HEAD" : "GET") << ',' << (cold ? "cold" : "repeated") << ',' << BundleFS::size << ',' << length << ',' << iterations + << ',' << decodes << ',' << retained << ',' << elapsed / iterations << '\n'; +} +} // namespace + +int main(int argc, char** argv) { + try { + std::string bytes; + if (argc > 1) { + std::ifstream file(argv[1], std::ios::binary); + if (!file) + throw std::runtime_error("cannot open gzip bundle"); + bytes.assign(std::istreambuf_iterator(file), {}); + } + std::cout << "asset,method,requests,compressed_bytes,decoded_bytes,iterations,decodes,retained_bytes,us_per_request\n"; + for (const auto& [label, fixture] : { + std::pair{ "fixed", gzipfixtures::fixed}, + { "dynamic", gzipfixtures::dynamic}, + { "optional", gzipfixtures::optional}, + {"application", std::string_view(bytes)} + }) { + if (fixture.empty()) + continue; + BundleFS::load(fixture); + for (const bool head : {false, true}) { + for (const bool cold : {false, true}) { + measure<0>(std::string(label) + "-disabled", head, cold); + measure(std::string(label) + "-cached", head, cold); + } + } + } + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/test/unit/GzipTests.cpp b/test/unit/GzipTests.cpp index 59a97b87..ff070006 100644 --- a/test/unit/GzipTests.cpp +++ b/test/unit/GzipTests.cpp @@ -1,6 +1,7 @@ #include "GzipFixtures.hpp" #include #include +#include #include @@ -194,3 +195,157 @@ SCENARIO("Gzip CRC32 matches standard and binary reference vectors") { } } } + +SCENARIO("Validated gzip cache shares GET content and HEAD metadata within the current output budget") { + using webfront::http::gzip::ValidatedCache; + ValidatedCache cache(100000); + auto bytes = std::string(gzipfixtures::fixed); + GIVEN("HEAD validates a revision before GET") { + REQUIRE(cache.resolve(bytes, 23768, true) == 23768); + REQUIRE(bytes.empty()); + bytes = gzipfixtures::fixed; + REQUIRE(cache.resolve(bytes, 23768) == 23768); + REQUIRE(bytes == payload()); + THEN("GET reuses the validated bytes and length") { + REQUIRE(cache.statistics().decodes == 1); + REQUIRE(cache.statistics().hits == 1); + } + THEN("a smaller active output budget cannot reuse the larger result") { + for (const bool head : {false, true}) { + bytes = gzipfixtures::fixed; + REQUIRE_FALSE(cache.resolve(bytes, 23767, head)); + } + REQUIRE(cache.statistics().decodes == 1); + bytes = gzipfixtures::fixed; + REQUIRE(cache.resolve(bytes, 23768, true) == 23768); + } + } +} + +SCENARIO("Validated gzip cache bounds keys and data and evicts the least recently used revision") { + using webfront::http::gzip::ValidatedCache; + auto first = std::string(gzipfixtures::fixed); + auto second = first; + auto third = first; + // MTIME changes the compressed revision without changing the validated payload. + second[4] = 1; + third[4] = 2; + ValidatedCache probe(100000); + auto bytes = first; + REQUIRE(probe.resolve(bytes, 23768)); + const auto charge = probe.statistics().retainedBytes; + REQUIRE(charge >= first.size() + 23768); + GIVEN("room for exactly two revisions") { + ValidatedCache cache(2 * charge); + for (const auto& revision : {first, second, first, third, first}) { + bytes = revision; + REQUIRE(cache.resolve(bytes, 23768)); + REQUIRE(cache.statistics().retainedBytes <= 2 * charge); + } + THEN("the touched first revision survives while the second is evicted") { + REQUIRE(cache.statistics().decodes == 3); + REQUIRE(cache.statistics().hits == 2); + REQUIRE(cache.statistics().entries == 2); + bytes = second; + REQUIRE(cache.resolve(bytes, 23768)); + REQUIRE(cache.statistics().decodes == 4); + } + } + GIVEN("a budget one byte below a complete entry, or disabled caching") { + for (const auto budget : {std::size_t{0}, charge - 1}) { + ValidatedCache cache(budget); + for (const bool head : {false, true}) { + bytes = first; + REQUIRE(cache.resolve(bytes, 23768, head)); + } + THEN("both requests succeed without retaining partial keys or metadata") { + REQUIRE(cache.statistics().retainedBytes == 0); + REQUIRE(cache.statistics().entries == 0); + REQUIRE(cache.statistics().decodes == 2); + } + } + } + GIVEN("an oversized revision alongside a retained asset") { + ValidatedCache cache(charge); + bytes = first; + REQUIRE(cache.resolve(bytes, 23768)); + bytes = first + first; + REQUIRE(cache.resolve(bytes, 47536)); + bytes = first; + REQUIRE(cache.resolve(bytes, 23768)); + REQUIRE(cache.statistics().decodes == 2); + REQUIRE(cache.statistics().hits == 1); + } +} + +SCENARIO("Validated gzip cache never promotes invalid streams or trusts ISIZE alone") { + webfront::http::gzip::ValidatedCache cache(100000); + GIVEN("corrupt CRC, invalid trailer, truncated and concatenated invalid members") { + auto corrupt = std::string(gzipfixtures::fixed); + corrupt[corrupt.size() - 8] ^= 1; + auto wrongSize = std::string(gzipfixtures::fixed); + wrongSize.back() = 1; + for (const auto& invalid : {corrupt, wrongSize, std::string(gzipfixtures::fixed.substr(0, 498)), std::string(gzipfixtures::fixed) + corrupt}) { + for (const bool head : {false, true}) { + auto bytes = invalid; + REQUIRE_FALSE(cache.resolve(bytes, 100000, head)); + } + } + THEN("every attempt validates again and nothing is retained") { + REQUIRE(cache.statistics().decodes == 8); + REQUIRE(cache.statistics().entries == 0); + REQUIRE(cache.statistics().retainedBytes == 0); + } + } + GIVEN("an initial decode failing its output budget") { + auto bytes = std::string(gzipfixtures::fixed); + REQUIRE_FALSE(cache.resolve(bytes, 1)); + bytes = gzipfixtures::fixed; + REQUIRE(cache.resolve(bytes, 23768)); + REQUIRE(cache.statistics().decodes == 2); + REQUIRE(cache.statistics().entries == 1); + } +} + +SCENARIO("Validated gzip cache lifetime is owned and copies do not share application state") { + using webfront::http::gzip::ValidatedCache; + std::string response(gzipfixtures::fixed); + GIVEN("a populated cache") { + { + ValidatedCache cache(100000); + REQUIRE(cache.resolve(response, 23768)); + auto copy = cache; + REQUIRE(copy.statistics().entries == 0); + auto bytes = std::string(gzipfixtures::fixed); + REQUIRE(copy.resolve(bytes, 23768)); + REQUIRE(copy.statistics().decodes == 1); + } + THEN("the response survives destruction and a new application starts cold") { + REQUIRE(response == payload()); + ValidatedCache next(100000); + response = gzipfixtures::fixed; + REQUIRE(next.resolve(response, 23768, true)); + REQUIRE(next.statistics().decodes == 1); + REQUIRE(next.statistics().hits == 0); + } + } +} + +SCENARIO("Validated gzip cache permits empty streams under a zero output budget") { + // Empty stored block, with a validated CRC32 and ISIZE of zero. + const std::string empty("\x1f\x8b\x08\x00\x00\x00\x00\x00\x00\x03" + "\x01\x00\x00\xff\xff" + "\x00\x00\x00\x00\x00\x00\x00\x00", + 23); + webfront::http::gzip::ValidatedCache cache(1000); + GIVEN("GET then HEAD of a valid empty asset") { + for (const bool head : {false, true}) { + auto bytes = empty; + REQUIRE(cache.resolve(bytes, 0, head) == 0); + REQUIRE(bytes.empty()); + } + REQUIRE(cache.statistics().decodes == 1); + REQUIRE(cache.statistics().hits == 1); + REQUIRE(cache.statistics().retainedBytes <= 1000); + } +} diff --git a/test/unit/HTTPEncodingTests.cpp b/test/unit/HTTPEncodingTests.cpp index 668dc7dc..f5e6e18f 100644 --- a/test/unit/HTTPEncodingTests.cpp +++ b/test/unit/HTTPEncodingTests.cpp @@ -9,6 +9,7 @@ #include #include #include +#include #include using namespace webfront; @@ -271,3 +272,142 @@ SCENARIO("HTTP treats stored x-gzip assets as gzip for fallback and pass-through } } } + +SCENARIO("HTTP GET and HEAD reuse validated gzip revisions across paths and aliases") { + RequestHandler handler{"."}; + auto request = assetRequest(); + GIVEN("a cold HEAD followed by GET, another path and the x-gzip alias") { + request.method = Request::Method::Head; + REQUIRE(handler.handleRequest(request).content.empty()); + request.method = Request::Method::Get; + REQUIRE(handler.handleRequest(request).content.size() == 23768); + request.uri = "/other.js"; + REQUIRE(handler.handleRequest(request).content.size() == 23768); + request.uri = "/legacy.js"; + REQUIRE(handler.handleRequest(request).content.size() == 23768); + THEN("identical compressed bytes require a single decode") { + REQUIRE(handler.fallbackCacheStatistics().decodes == 1); + REQUIRE(handler.fallbackCacheStatistics().hits == 3); + } + THEN("gzip pass-through leaves the fallback cache untouched") { + request.headers.emplace_back("Accept-Encoding", "gzip"); + REQUIRE(handler.handleRequest(request).content == gzipfixtures::fixed); + REQUIRE(handler.fallbackCacheStatistics().hits == 3); + } + } +} + +namespace { +struct MutableAssetFS : EncodedAssetFS { + using EncodedAssetFS::EncodedAssetFS; + static inline std::string revision; + std::optional open(std::filesystem::path) { + words.assign((revision.size() + 7) / 8, 0); + for (std::size_t index = 0; index < revision.size(); ++index) + words[index / 8] |= static_cast(static_cast(revision[index])) << ((7 - index % 8) * 8); + return fs::File(words, revision.size(), "gzip"); + } +}; +} // namespace + +SCENARIO("HTTP mutable providers cannot reuse stale identity content or HEAD lengths") { + RequestHandler handler{"."}; + auto request = assetRequest(); + MutableAssetFS::revision = gzipfixtures::fixed; + REQUIRE(handler.handleRequest(request).content.size() == 23768); + GIVEN("the provider replaces the same path with two concatenated members") { + MutableAssetFS::revision += gzipfixtures::fixed; + request.method = Request::Method::Head; + const auto head = handler.handleRequest(request); + REQUIRE(head.getHeaderValue("Content-Length") == "47536"); + REQUIRE(head.content.empty()); + request.method = Request::Method::Get; + REQUIRE(handler.handleRequest(request).content.size() == 47536); + REQUIRE(handler.fallbackCacheStatistics().decodes == 2); + REQUIRE(handler.fallbackCacheStatistics().hits == 1); + } + GIVEN("the provider replaces it with corrupt content having the same ISIZE") { + MutableAssetFS::revision[MutableAssetFS::revision.size() - 8] ^= 1; + for (const auto method : {Request::Method::Get, Request::Method::Head}) { + request.method = method; + REQUIRE(handler.handleRequest(request).statusCode == Response::internalServerError); + } + REQUIRE(handler.fallbackCacheStatistics().decodes == 3); + REQUIRE(handler.fallbackCacheStatistics().entries == 1); + } +} + +SCENARIO("HTTP cache ownership and policy remain local to the application") { + using Disabled = CustomBuffersPolicy<8192, 8192, 32768, defaultMaxMessageSize, defaultMaxDecodedAssetSize, 0>; + RequestHandler handler{"."}; + const auto request = assetRequest(); + GIVEN("a policy disabling cache retention") { + REQUIRE(handler.handleRequest(request).statusCode == Response::ok); + REQUIRE(handler.handleRequest(request).statusCode == Response::ok); + REQUIRE(handler.fallbackCacheStatistics().decodes == 2); + REQUIRE(handler.fallbackCacheStatistics().retainedBytes == 0); + } + THEN("legacy policies retain the default cache budget") { + REQUIRE(maxDecodedAssetCacheSize() == defaultMaxDecodedAssetCacheSize); + } + GIVEN("two independent handlers") { + RequestHandler first{"."}, second{"."}; + REQUIRE(first.handleRequest(request).statusCode == Response::ok); + REQUIRE(second.fallbackCacheStatistics().entries == 0); + REQUIRE(second.handleRequest(request).statusCode == Response::ok); + REQUIRE(second.fallbackCacheStatistics().decodes == 1); + } +} + +SCENARIO("HTTP server drains and destroys a populated fallback cache") { + GIVEN("successive applications serving an identity fallback") { + for (unsigned instance = 0; instance < 2; ++instance) { + AssetServerNet::accepts = 0; + AssetServerNet::statusLine.clear(); + { + Server server("127.0.0.1", "0"); + REQUIRE(AssetServerNet::statusLine == "HTTP/1.1 200 OK\r\n"); + server.stop(); + server.drain(); + } + THEN("shutdown completes with no cache work outstanding") { + REQUIRE(AssetServerNet::accepts >= 1); + } + } + } +} + +namespace { +struct ActiveAssetBudget : DefaultBuffersPolicy { + static inline thread_local std::size_t maxDecodedAssetSize = defaultMaxDecodedAssetSize; + + explicit ActiveAssetBudget(std::size_t limit) : previous(std::exchange(maxDecodedAssetSize, limit)) {} + ~ActiveAssetBudget() { + maxDecodedAssetSize = previous; + } + +private: + std::size_t previous; +}; +} // namespace + +SCENARIO("HTTP cached GET and HEAD recheck the active application output budget") { + const ActiveAssetBudget initialBudget{23768}; + RequestHandler handler{"."}; + auto request = assetRequest(); + REQUIRE(handler.handleRequest(request).statusCode == Response::ok); + GIVEN("the application lowers its budget after validating this revision") { + { + const ActiveAssetBudget smallerBudget{23767}; + for (const auto method : {Request::Method::Get, Request::Method::Head}) { + request.method = method; + const auto response = handler.handleRequest(request); + REQUIRE(response.statusCode == Response::internalServerError); + REQUIRE(response.getHeaderValue("Vary") == "Accept-Encoding"); + } + REQUIRE(handler.fallbackCacheStatistics().decodes == 1); + REQUIRE(handler.fallbackCacheStatistics().hits == 2); + } + REQUIRE(handler.handleRequest(request).getHeaderValue("Content-Length") == "23768"); + } +}