diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6a98c77..3c1c5fd 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -164,8 +164,8 @@ jobs: - name: Test run: ctest --test-dir build --output-on-failure - # The same remote cache test, against a real server instead of the test one: over http, then - # over https with Basic authentication (the certificate of tests/integration/tls and an + # The same remote cache test, against a real server instead of the test one: over http, + # without and with compressed uploads, then over https with Basic authentication (the certificate of tests/integration/tls and an # htpasswd file). The image is pinned by digest. - name: Test the remote cache against bazel-remote if: matrix.llvm == '21' @@ -185,6 +185,10 @@ jobs: docker run -d --rm --name bazel-remote -p 127.0.0.1:19090:8080 "$BAZEL_REMOTE_IMAGE" --max_size=1 --dir=/data wait_for http://127.0.0.1:19090/status CPPMCACHE_TEST_REMOTE=http://127.0.0.1:19090 ctest --test-dir build -R 'integration\.remote\.plain' --output-on-failure + # Again with zstd-compressed uploads, which bazel-remote decodes (and downloads are asked for + # compressed in both runs). + CPPMCACHE_REMOTE_COMPRESSION=zstd CPPMCACHE_TEST_REMOTE=http://127.0.0.1:19090 \ + ctest --test-dir build -R 'integration\.remote\.plain' --output-on-failure docker logs bazel-remote 2>&1 | grep -cE ' (GET|PUT|HEAD) ' | xargs echo "requests served by bazel-remote:" docker rm -f bazel-remote diff --git a/CMakeLists.txt b/CMakeLists.txt index 0349b5f..0336794 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -138,7 +138,28 @@ if(CPPMCACHE_REMOTE) endif() set(cppmcache_tls_engine ${cppmcache_existing_engine}) endif() - set(cppmcache_transport src/cppmcache/RemoteTransport.cpp) + # zstd compresses the blobs exchanged with the remote cache. Only its sources are fetched: they + # are compiled here into a static library of cppmcache's own, so that zstd's install rules and + # package files never reach the tree, or the installation, of a project that imports cppmcache. + # Confined like stdnet to a classic translation unit (Compression.cpp). + CPMAddPackage( + NAME zstd + GITHUB_REPOSITORY facebook/zstd + # v1.5.7 + GIT_TAG f8745da6ff1ad1e7bab384bd1f9d742439278e99 + DOWNLOAD_ONLY YES + ) + enable_language(C) + file(GLOB cppmcache_zstd_sources CONFIGURE_DEPENDS + "${zstd_SOURCE_DIR}/lib/common/*.c" + "${zstd_SOURCE_DIR}/lib/compress/*.c" + "${zstd_SOURCE_DIR}/lib/decompress/*.c") + add_library(cppmcache_zstd STATIC ${cppmcache_zstd_sources}) + # The decoder's assembly needs no assembler set up when it is left out; one thread is enough. + target_compile_definitions(cppmcache_zstd PRIVATE ZSTD_DISABLE_ASM ZSTD_MULTITHREAD=0) + target_include_directories(cppmcache_zstd SYSTEM PUBLIC "${zstd_SOURCE_DIR}/lib") + set_target_properties(cppmcache_zstd PROPERTIES POSITION_INDEPENDENT_CODE ON) + set(cppmcache_transport src/cppmcache/RemoteTransport.cpp src/cppmcache/Compression.cpp) else() set(cppmcache_transport src/cppmcache/RemoteTransportDisabled.cpp) endif() @@ -147,7 +168,9 @@ endif() target_sources(cppmcache_core PRIVATE ${cppmcache_transport} src/cppmcache/Sha256Blocks.cpp) set_source_files_properties(${cppmcache_transport} src/cppmcache/Sha256Blocks.cpp PROPERTIES CXX_SCAN_FOR_MODULES OFF) if(CPPMCACHE_REMOTE) - target_link_libraries(cppmcache_core PRIVATE stdnet::stdnet) + # zstd first: a static OpenSSL brings `-lzstd` among its own dependencies, which would otherwise + # resolve cppmcache's zstd calls to the system's shared library. + target_link_libraries(cppmcache_core PRIVATE cppmcache_zstd stdnet::stdnet) if(NOT cppmcache_tls_engine STREQUAL "OFF") set_property(SOURCE ${cppmcache_transport} APPEND PROPERTY COMPILE_DEFINITIONS CPPMCACHE_TLS=1) endif() diff --git a/README.md b/README.md index a0aa227..0fe73db 100644 --- a/README.md +++ b/README.md @@ -131,6 +131,7 @@ come from the environment or from files, never from the URL. Details are in | `CPPMCACHE_REMOTE_TOKEN` | bearer token sent to the remote cache (or `CPPMCACHE_REMOTE_TOKEN_FILE`, a file that holds it) | | `CPPMCACHE_REMOTE_USER`, `CPPMCACHE_REMOTE_PASSWORD` | Basic authentication with the remote cache (or `CPPMCACHE_REMOTE_PASSWORD_FILE`) | | `CPPMCACHE_REMOTE_CA_CERT` | PEM file of the only roots trusted over `https://` (default: the system's) | +| `CPPMCACHE_REMOTE_COMPRESSION` | `zstd`: upload blobs compressed, for bazel-remote (downloads are always asked for compressed) | | `CPPMCACHE_REMOTE_READ_ONLY` | fetch from the remote cache but never publish to it | | `CPPMCACHE_REMOTE_TIMEOUT_MS` | time allowed for one remote operation (default: 10000) | | `CPPMCACHE_LOG` | file to which each call appends its outcome, the reason and the time of each phase ([format](docs/usage.md#reading-the-log)) | diff --git a/docs/measurements.md b/docs/measurements.md index 11dbda4..a07696c 100644 --- a/docs/measurements.md +++ b/docs/measurements.md @@ -185,6 +185,60 @@ them. Each cell is a single run. All 950 MduX tests pass on the build served entirely from the cache. +## Remote cache across a network + +MduX at commit `57a7d1d`, GCC 16.1, Release, 336 units, built on one Linux machine with 24 cores +against a bazel-remote on the same machine (the image CI uses), measured on 2026-12-01 with + +```sh +tools/compare_caches.py --source --work --cppmcache \ + --edit include/mdux/core/Units.cppm --cmake-arg=-DCMAKE_CXX_COMPILER=g++ --cmake-arg=-DENABLE_CACHE=OFF \ + --skip none --skip ccache --skip-scenario edit --skip-scenario revert --skip-scenario relocated \ + --remote-server bazel-remote --remote-tls [--remote-delay-ms D --remote-bandwidth-mbit B] [--remote-compression] \ + --runs 3 --profile +``` + +The network is a model: `tools/latency_proxy.py` delays every byte by D milliseconds each way, +the TCP handshake included, and shares B Mbit/s each way between all connections. It has no +packet loss and no congestion control, so a real link of the same latency and bandwidth may do +worse. Each cell is the median of 3 rounds, with the lowest and highest in brackets. "Before" is +the client of 0.4 with TLS; "after" adds pipelined requests, zstd and `TCP_NODELAY`, with +`CPPMCACHE_REMOTE_COMPRESSION=zstd`. + +| Link (round trip, bandwidth) | Clean build, empty local and remote caches | Clean build, empty local cache, populated remote cache | +|---|---:|---:| +| same machine, before | 55.2 s (54.2–55.4) | 6.6 s (6.6–6.7) | +| same machine, after | 54.0 s (54.0–54.9) | 6.5 s (6.4–6.5) | +| 20 ms, 100 Mbit/s, before | 56.1 s (55.2–57.2) | 11.7 s (11.6–12.0) | +| 20 ms, 100 Mbit/s, after | 55.0 s (55.0–55.5) | 8.2 s (8.0–8.4) | +| 60 ms, 50 Mbit/s, before | 61.6 s (61.5–63.4) | 19.9 s (19.8–20.1) | +| 60 ms, 50 Mbit/s, after | 56.2 s (55.4–57.6) | 12.3 s (12.0–12.6) | + +For reference, the same build takes 53–54 s with an empty local cache and no remote one, and +6.0–6.2 s from a populated local cache. What the measurements showed, and what was done: + +- **Uploads cost little wall-clock time.** A miss of the first build waits for its uploads, but + 24 compilations run at once and the compiler dominates: the remote cache adds 1 to 2 s to a + build of about 54 s even at 60 ms. Uploading in the background, after the compilation has + returned, would save at most that, at the price of uploads that a CI job could end before they + are done; it was not done. +- **Bandwidth limits a build served by the remote cache.** The results of MduX weigh 71 MB, 13.5 + MB once compressed with zstd: at 50 Mbit/s the transfer alone takes 11 s uncompressed. Content + blobs are now asked for compressed, which bazel-remote serves from what it stores compressed + anyway, and can be uploaded compressed. +- **Round trips.** Before, a miss made nine requests one after the other, a hit five. Requests now + go in pipelined batches: a miss publishes in four round trips. The time of cppmcache spent + uploading fell by 30 to 40 %, which a parallel build mostly hid already. +- **TLS cost 40 ms per request.** TLS wrote a request in two records, and Nagle's algorithm held + the second back until the server's delayed acknowledgement: 53 ms per call on the same machine, + 15 ms with `TCP_NODELAY`. +- **A connection per compilation.** At 60 ms a hit still spends about 290 ms talking to the server: + the TCP and TLS handshakes, then the manifest, then the result, each one round trip, then the + outputs. A local daemon that kept connections open would save the two handshakes, about 120 ms + per call at 60 ms, which spread over 24 parallel compilations is about 2 s of the 12.3 s above. + That is worth less than its cost (a process to start, find and stop, on three platforms) for + now; HTTP/2 or gRPC (#19) does not change it, since each compilation is still its own process. + ## Reading the tables - **ccache and modules.** With GCC, ccache passes every unit that imports or provides a module diff --git a/docs/usage.md b/docs/usage.md index b8c4ec6..e09aba0 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -138,6 +138,19 @@ export CPPMCACHE_REMOTE=http://localhost:8080 - The server never fails a build. If it cannot be reached, or refuses the credentials, cppmcache counts a remote error, leaves it alone for the rest of that compilation, and carries on with the local cache. +- Requests are pipelined: a compilation sends its requests in a few batches without waiting for + each answer, and a miss publishes its result in four round trips. A server, or a proxy in front + of it, must therefore accept pipelined HTTP/1.1 requests, as bazel-remote and nginx do. It + should also disable Nagle's algorithm on its connections (`TCP_NODELAY`, the default of both): + otherwise each answer of a batch after the first waits for the client's delayed acknowledgement, + 40 ms. A server that refuses pipelining altogether is detected, and then sent one request at a + time. +- Content blobs are asked for compressed (`Accept-Encoding: zstd`): bazel-remote stores them + compressed and sends them so, about five times smaller for object files and BMIs. With + `CPPMCACHE_REMOTE_COMPRESSION=zstd` they are uploaded compressed too (`Content-Encoding: zstd` + and `X-Digest-SizeBytes`, as bazel-remote takes them). Leave it unset with a server that does not + understand that encoding: it would store the compressed bytes, which every client would then + refuse as not matching their digest. ### TLS and credentials @@ -575,8 +588,8 @@ only, and the configure step says so. `openssl` or `schannel` require one, and ` prints for `--version`, which is part of the key. A program of that name that only wraps a compiler and adds options of its own, chosen by its environment, would not be seen: the key would not follow those options. A script is always passed through. -- The remote cache has no compression, and it speaks HTTP, not the gRPC interface of the Remote - Execution API. Uploads are synchronous: a miss waits for them. Each compilation opens its own - connection, so over `https://` each one also makes a TLS handshake; revocation of the server's - certificate is not checked. +- The remote cache speaks HTTP, not the gRPC interface of the Remote Execution API. A miss waits + for its uploads, which a parallel build hides ([measurements](measurements.md#remote-cache-across-a-network)). + Each compilation opens its own connection, so over `https://` each one also makes a TLS + handshake; revocation of the server's certificate is not checked. - A restored dependency file is rewritten, not copied: the same dependencies, laid out differently. diff --git a/src/cppmcache/Cache.cppm b/src/cppmcache/Cache.cppm index 766c2b1..da8b001 100644 --- a/src/cppmcache/Cache.cppm +++ b/src/cppmcache/Cache.cppm @@ -530,7 +530,7 @@ std::optional fetchBlob(Context& context, const Digest& digest) { if (context.remote == nullptr) { return std::nullopt; } - auto content = context.remote->get("cas", digest.hash); + auto content = context.remote->get("cas", digest.hash, digest.size); if (!content) { return std::nullopt; } @@ -543,6 +543,31 @@ std::optional fetchBlob(Context& context, const Digest& digest) { return content; } +// Fetches blobs that the local CAS lacks from the remote cache, in one batch, checks them against +// their digests and keeps them locally. False unless all of them arrived intact. +bool fetchBlobs(Context& context, std::span digests) { + if (context.remote == nullptr) { + return false; + } + std::vector operations; + for (const auto& digest : digests) { + operations.push_back(RemoteCache::getting("cas", digest.hash, digest.size)); + } + context.remote->run(operations); + for (std::size_t i = 0; i < digests.size(); ++i) { + if (!operations[i].found) { + return false; + } + if (digestOf(operations[i].content) != digests[i]) { + context.log("remote error", std::format("remote blob {} does not match its digest", digests[i].hash)); + context.store.count("remote_error"); + return false; + } + context.store.casPut(operations[i].content); + } + return true; +} + // The manifest the remote cache holds for the current manifest key. A manifest is not a REAPI // notion: it is stored as the single output of an ActionResult filed under the manifest key, which // any server of the protocol accepts. @@ -978,16 +1003,21 @@ std::optional serve(Context& context, const ManifestEntry& entry) { if (!result || result->exitCode != 0) { return std::nullopt; } + // The outputs this machine lacks are asked for in one batch. + std::vector missing; for (const auto& file : result->outputFiles) { if (!context.outputPath(file.path).has_value()) { return std::nullopt; } if (!store.casHas(file.digest)) { - if (!fetchBlob(context, file.digest)) { - return std::nullopt; - } - fromRemote = true; + missing.push_back(file.digest); + } + } + if (!missing.empty()) { + if (!fetchBlobs(context, missing)) { + return std::nullopt; } + fromRemote = true; } if (fromRemote) { store.actionPut(actionDigest, *resultBytes); @@ -1067,38 +1097,106 @@ std::optional lookup(Context& context) { } // Publishes a freshly stored result to the remote cache: the output blobs, the ActionResult, then -// the manifest, merged with the one the server already holds. +// the manifest, merged with the one the server already holds. The requests go in four batches, +// each one round trip: what the server lacks and its manifest; the missing blobs and the content of +// that manifest; the ActionResult and the merged manifest; the entry that points to that manifest. +// Nothing is published before what it refers to has been stored. void upload(Context& context, const std::vector& localEntries, const Digest& actionDigest, const ActionResult& result) { + using Operation = RemoteCache::Operation; RemoteCache& remote = *context.remote; - bool stored = true; + const auto count = result.outputFiles.size(); + + std::vector probe; for (const auto& file : result.outputFiles) { - if (remote.has("cas", file.digest.hash)) { + probe.push_back(RemoteCache::checking("cas", file.digest.hash)); + } + probe.push_back(RemoteCache::getting("ac", context.manifestKey)); + remote.run(probe); + + // The server's manifest, from the local CAS when this machine has it. + std::optional known; + std::optional knownDigest; + if (const auto holder = probe.back().found ? ActionResult::decode(probe.back().content) : std::nullopt) { + for (const auto& file : holder->outputFiles) { + if (file.path == manifestOutput) { + knownDigest = file.digest; + } + } + } + if (knownDigest && context.store.casHas(*knownDigest)) { + known = readFile(context.store.casPath(*knownDigest)); + // A damaged local copy must not replace the server's manifest with what it holds. + if (known && digestOf(*known) != *knownDigest) { + known.reset(); + } + } + + // The contents are kept here while the batch refers to them: reserved, so never moved. + std::vector contents; + contents.reserve(count); + std::vector blobs; + bool stored = true; + for (std::size_t i = 0; i < count; ++i) { + if (probe[i].found) { continue; } - const auto content = readFile(context.store.casPath(file.digest)); - stored = stored && content && remote.put("cas", file.digest.hash, *content); - } - stored = stored && remote.put("ac", actionDigest.hash, result.encode()); - if (stored) { - // Entries the server knows and this machine does not are kept, as the oldest ones. - std::vector merged; - if (const auto known = remoteManifest(context)) { - for (auto& entry : decodeManifest(*known)) { - if (!std::ranges::contains(localEntries, entry)) { - merged.push_back(std::move(entry)); - } - } + auto content = readFile(context.store.casPath(result.outputFiles[i].digest)); + if (!content) { + stored = false; + break; } - merged.insert(merged.end(), localEntries.begin(), localEntries.end()); - if (merged.size() > maxManifestEntries) { - merged.erase(merged.begin(), merged.end() - static_cast(maxManifestEntries)); + contents.push_back(std::move(*content)); + blobs.push_back(RemoteCache::putting("cas", result.outputFiles[i].digest.hash, contents.back())); + } + // Last in the batch: the only request whose answer may be large. + const bool fetchKnown = stored && knownDigest && !known; + if (fetchKnown) { + blobs.push_back(RemoteCache::getting("cas", knownDigest->hash, knownDigest->size)); + } + if (!blobs.empty() && stored) { + remote.run(blobs); + } + for (std::size_t i = 0; stored && i < contents.size(); ++i) { + stored = blobs[i].found; + } + if (fetchKnown && blobs.back().found) { + if (digestOf(blobs.back().content) == *knownDigest) { + known = std::move(blobs.back().content); + } else { + context.log("remote error", std::format("remote blob {} does not match its digest", knownDigest->hash)); + context.store.count("remote_error"); } - const std::string manifest = encodeManifest(merged); - ActionResult holder; - holder.outputFiles.push_back({std::string{manifestOutput}, digestOf(manifest)}); - stored = remote.put("cas", holder.outputFiles.front().digest.hash, manifest) && remote.put("ac", context.manifestKey, holder.encode()); } - if (stored) { + if (!stored) { + return; + } + + // Entries the server knows and this machine does not are kept, as the oldest ones. + std::vector merged; + if (known) { + for (auto& entry : decodeManifest(*known)) { + if (!std::ranges::contains(localEntries, entry)) { + merged.push_back(std::move(entry)); + } + } + } + merged.insert(merged.end(), localEntries.begin(), localEntries.end()); + if (merged.size() > maxManifestEntries) { + merged.erase(merged.begin(), merged.end() - static_cast(maxManifestEntries)); + } + const std::string manifest = encodeManifest(merged); + ActionResult holder; + holder.outputFiles.push_back({std::string{manifestOutput}, digestOf(manifest)}); + const std::string encodedResult = result.encode(); + const std::string encodedHolder = holder.encode(); + std::array records{RemoteCache::putting("ac", actionDigest.hash, encodedResult), + RemoteCache::putting("cas", holder.outputFiles.front().digest.hash, manifest)}; + remote.run(records); + if (!std::ranges::all_of(records, &Operation::found)) { + return; + } + // Only now: an entry pointing to a manifest the server lacks would hide the entries it had. + if (remote.put("ac", context.manifestKey, encodedHolder)) { context.store.count("remote_store"); } } @@ -2008,7 +2106,7 @@ int runCompiler(const Config& config, const std::vector& commandLin problem = authorization.error(); } if (problem.empty()) { - remote.emplace(*url, config.remoteTimeoutMillis, *authorization, config.remoteAuthorities); + remote.emplace(*url, config.remoteTimeoutMillis, *authorization, config.remoteAuthorities, config.remoteCompression); context.remote = &*remote; } else { store.count("remote_error"); diff --git a/src/cppmcache/Compression.cpp b/src/cppmcache/Compression.cpp new file mode 100644 index 0000000..954b18d --- /dev/null +++ b/src/cppmcache/Compression.cpp @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Ambroise Leclerc +/** + * @file Compression.cpp + * @brief zstd (https://github.com/facebook/zstd) for the remote cache. + */ +#include "Compression.hpp" + +#include + +namespace cppmcache::compression { + +bool available() noexcept { + return true; +} + +unsigned long long bound(unsigned long long size) noexcept { + return ZSTD_compressBound(static_cast(size)); +} + +long long compress(const char* input, unsigned long long size, char* output, unsigned long long capacity, int level) noexcept { + const size_t written = ZSTD_compress(output, static_cast(capacity), input, static_cast(size), level); + return ZSTD_isError(written) != 0U ? -1 : static_cast(written); +} + +long long decompress(const char* input, unsigned long long size, unsigned long long limit, Grow grow, void* owner) noexcept { + ZSTD_DCtx* context = ZSTD_createDCtx(); + if (context == nullptr) { + return -1; + } + // One byte beyond the limit tells an output that exceeds it. + const unsigned long long ceiling = limit + 1; + unsigned long long capacity = ceiling < 65536 ? ceiling : 65536; + char* output = grow(owner, capacity); + ZSTD_inBuffer in{input, static_cast(size), 0}; + ZSTD_outBuffer out{output, static_cast(capacity), 0}; + long long result = -1; + while (output != nullptr) { + const size_t left = ZSTD_decompressStream(context, &out, &in); + if (ZSTD_isError(left) != 0U) { + break; + } + if (left == 0 && in.pos == in.size) { + // Every frame is complete and the input is consumed. + result = out.pos <= limit ? static_cast(out.pos) : -1; + break; + } + if (out.pos < out.size) { + if (in.pos == in.size) { + break; // a frame is truncated + } + continue; + } + if (capacity == ceiling) { + break; // more than the limit + } + capacity = capacity > ceiling / 2 ? ceiling : capacity * 2; + output = grow(owner, capacity); + out.dst = output; + out.size = static_cast(capacity); + } + ZSTD_freeDCtx(context); + return result; +} + +} // namespace cppmcache::compression diff --git a/src/cppmcache/Compression.hpp b/src/cppmcache/Compression.hpp new file mode 100644 index 0000000..2bbb650 --- /dev/null +++ b/src/cppmcache/Compression.hpp @@ -0,0 +1,34 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Ambroise Leclerc +/** + * @file Compression.hpp + * @brief zstd compression of the remote cache's blobs, behind a boundary free of library headers. + * + * Like RemoteTransport.hpp: zstd's header lives in one classic translation unit (Compression.cpp), + * reached through declarations that use built-in types only. + */ +#pragma once + +namespace cppmcache::compression { + +// Whether this build can compress at all. +bool available() noexcept; + +// The largest size that compressing `size` bytes can produce. +unsigned long long bound(unsigned long long size) noexcept; + +// Compresses into `output`, which holds `capacity` bytes, as one zstd frame. Returns the size +// written, or -1 on failure. +long long compress(const char* input, unsigned long long size, char* output, unsigned long long capacity, int level) noexcept; + +// Asks the caller for a buffer of `size` bytes that keeps what the previous one held; null if +// there is none. +using Grow = char* (*)(void* owner, unsigned long long size) noexcept; + +// Decompresses zstd frames into a buffer that `grow` enlarges as the output grows, never beyond +// `limit` bytes, so that the memory follows what the input really holds. Returns the size written, +// or -1 if the input is not valid zstd, decompresses to more than `limit` bytes, or no buffer was +// given. +long long decompress(const char* input, unsigned long long size, unsigned long long limit, Grow grow, void* owner) noexcept; + +} // namespace cppmcache::compression diff --git a/src/cppmcache/Http.cppm b/src/cppmcache/Http.cppm index 475cf51..e26306d 100644 --- a/src/cppmcache/Http.cppm +++ b/src/cppmcache/Http.cppm @@ -127,13 +127,18 @@ std::string base64(std::string_view bytes) { // Formats a request. `target` is appended to the URL's prefix and starts with a slash. A body is // sent with PUT only, with its exact length. `authorization`, when not empty, is the value of the -// Authorization header. -std::string -formatHttpRequest(std::string_view method, const HttpUrl& url, std::string_view target, std::string_view body = {}, std::string_view authorization = {}) { +// Authorization header; `headers` are more header lines, each ended by CRLF. +std::string formatHttpRequest(std::string_view method, + const HttpUrl& url, + std::string_view target, + std::string_view body = {}, + std::string_view authorization = {}, + std::string_view headers = {}) { std::string request = std::format("{} {}{} HTTP/1.1\r\nHost: {}\r\nUser-Agent: cppmcache\r\nAccept: */*\r\n", method, url.prefix, target, url.authority()); if (!authorization.empty()) { request += std::format("Authorization: {}\r\n", authorization); } + request += headers; if (method == "PUT") { request += std::format("Content-Type: application/octet-stream\r\nContent-Length: {}\r\n", body.size()); } @@ -148,6 +153,7 @@ struct HttpResponse { int status = 0; std::string body; bool keepAlive = true; // the connection can carry another request + std::string contentEncoding; // as the server wrote it, lowercase; empty for none }; // Incremental parser of one response. Bytes are fed as they arrive; `endOfStream()` tells it the @@ -184,6 +190,12 @@ public: return response_; } + // Bytes received after the end of a complete response: the start of the next one, when + // requests were pipelined. + std::string_view remainder() const { + return complete() ? std::string_view{raw_}.substr(cursor_) : std::string_view{}; + } + private: enum class State { headers, fixedLength, chunkSize, chunkData, chunkEnd, trailers, untilClose, complete, failed }; @@ -255,6 +267,11 @@ private: length = parsed; } else if (equalsIgnoreCase(name, "transfer-encoding")) { chunked = value.size() >= 7 && equalsIgnoreCase(value.substr(value.size() - 7), "chunked"); + } else if (equalsIgnoreCase(name, "content-encoding")) { + response_.contentEncoding = value; + for (char& c : response_.contentEncoding) { + c = c >= 'A' && c <= 'Z' ? static_cast(c - 'A' + 'a') : c; + } } else if (equalsIgnoreCase(name, "connection")) { response_.keepAlive = !equalsIgnoreCase(value, "close"); } diff --git a/src/cppmcache/Remote.cppm b/src/cppmcache/Remote.cppm index 9c0d4b3..eeead4c 100644 --- a/src/cppmcache/Remote.cppm +++ b/src/cppmcache/Remote.cppm @@ -11,9 +11,16 @@ * * Over `https://` the server is authenticated with the Web PKI. Credentials come from the * environment or from files, never from the URL, and no message repeats them. + * + * Content blobs are asked for zstd-compressed (`Accept-Encoding: zstd`), which bazel-remote + * answers from what it stores compressed anyway; a server that ignores the header sends them as + * they are. Uploads are compressed only when asked to (`Content-Encoding: zstd` with the + * `X-Digest-SizeBytes` header, as bazel-remote takes them), since a server that does not + * understand the encoding would store the compressed bytes under the digest of the content. */ module; +#include "Compression.hpp" #include "RemoteTransport.hpp" export module cppmcache.remote; @@ -113,8 +120,13 @@ class RemoteCache { public: // `authorization`: the value of the Authorization header, empty for none. `authorities`: a PEM // file of the only roots to trust over https, empty for the system's. - RemoteCache(HttpUrl url, int timeoutMilliseconds, std::string authorization = {}, std::string authorities = {}) - : url_(std::move(url)), timeout_(timeoutMilliseconds), authorization_(std::move(authorization)), authorities_(std::move(authorities)) {} + // `compressUploads`: send content blobs zstd-compressed. + RemoteCache(HttpUrl url, int timeoutMilliseconds, std::string authorization = {}, std::string authorities = {}, bool compressUploads = false) + : url_(std::move(url)), + timeout_(timeoutMilliseconds), + authorization_(std::move(authorization)), + authorities_(std::move(authorities)), + compressUploads_(compressUploads && compression::available()) {} RemoteCache(const RemoteCache&) = delete; RemoteCache& operator=(const RemoteCache&) = delete; ~RemoteCache() { @@ -131,34 +143,66 @@ public: return transport::secureAvailable(); } - // Content stored under kind/hash, or nothing if it is absent or the server cannot be reached. - std::optional get(std::string_view kind, std::string_view hash) { - const auto response = request("GET", target(kind, hash)); - if (!response || response->status == 404) { - return std::nullopt; + // One request of a batch, and what it found. + struct Operation { + enum class Kind { get, has, put }; + Kind what; + std::string kind; // "ac" or "cas" + std::string hash; + std::string_view body{}; // the content of a put; it must outlive the batch + std::int64_t size = -1; // the size of a content blob, which lets it travel compressed + + bool found = false; // get, has: the server holds it; put: it was stored + std::string content{}; // get: what the server holds + }; + + static Operation getting(std::string_view kind, std::string_view hash, std::int64_t size = -1) { + return {Operation::Kind::get, std::string{kind}, std::string{hash}, {}, size}; + } + static Operation checking(std::string_view kind, std::string_view hash) { + return {Operation::Kind::has, std::string{kind}, std::string{hash}}; + } + static Operation putting(std::string_view kind, std::string_view hash, std::string_view content) { + return {Operation::Kind::put, std::string{kind}, std::string{hash}, content, static_cast(content.size())}; + } + + // Runs the operations in order. They are written one after the other on the connection without + // waiting for the answers (HTTP/1.1 pipelining), so a batch costs one round trip instead of one + // per request; the server still handles them in order. Only the last operation of a batch + // should expect a large answer: the others are answered while the client is still sending. + void run(std::span operations) { + std::vector messages; + messages.reserve(operations.size()); + for (const auto& operation : operations) { + messages.push_back(request(operation)); } - if (response->status != 200) { - fail(std::format("GET {}: HTTP status {}", target(kind, hash), response->status)); - return std::nullopt; + std::vector> responses(operations.size()); + transmit(operations, messages, responses); + for (std::size_t i = 0; i < operations.size(); ++i) { + if (responses[i]) { + interpret(operations[i], *responses[i]); + } } - return response->body; + } + + // Content stored under kind/hash, or nothing if it is absent or the server cannot be reached. + // `size`: that of a content blob, when it is known. + std::optional get(std::string_view kind, std::string_view hash, std::int64_t size = -1) { + std::array operation{getting(kind, hash, size)}; + run(operation); + return operation[0].found ? std::optional{std::move(operation[0].content)} : std::nullopt; } bool has(std::string_view kind, std::string_view hash) { - const auto response = request("HEAD", target(kind, hash)); - return response && response->status == 200; + std::array operation{checking(kind, hash)}; + run(operation); + return operation[0].found; } bool put(std::string_view kind, std::string_view hash, std::string_view content) { - const auto response = request("PUT", target(kind, hash), content); - if (!response) { - return false; - } - if (response->status < 200 || response->status >= 300) { - fail(std::format("PUT {}: HTTP status {}", target(kind, hash), response->status)); - return false; - } - return true; + std::array operation{putting(kind, hash, content)}; + run(operation); + return operation[0].found; } // The message of every request that failed, in order. @@ -204,77 +248,209 @@ private: return true; } - // One exchange on the current connection. Nothing is returned on a transport failure. - std::optional exchange(std::string_view method, const std::string& message, std::string& error) { - std::array detail{}; - if (!transport::sendAll(connection_, message.data(), message.size(), timeout_, detail.data(), detail.size())) { - error = std::format("send: {}", detail.data()); - return std::nullopt; + // The request of one operation. Content blobs of known size travel compressed when they can. + std::string request(const Operation& operation) const { + const auto path = target(operation.kind, operation.hash); + const bool blob = operation.kind == "cas" && operation.size >= 0; + if (blob && operation.what == Operation::Kind::get) { + return formatHttpRequest("GET", url_, path, {}, authorization_, "Accept-Encoding: zstd\r\n"); } - HttpResponseReader reader{method == "HEAD"}; - std::vector buffer(std::size_t{64} * 1024); - while (!reader.complete() && !reader.failed()) { - const long long received = transport::receiveSome(connection_, buffer.data(), buffer.size(), timeout_, detail.data(), detail.size()); - if (received < 0) { - error = std::format("receive: {}", detail.data()); - return std::nullopt; + if (blob && operation.what == Operation::Kind::put && compressUploads_) { + if (const auto packed = zstd(operation.body)) { + return formatHttpRequest("PUT", + url_, + path, + *packed, + authorization_, + std::format("Content-Encoding: zstd\r\nX-Digest-SizeBytes: {}\r\n", operation.size)); } - if (received == 0) { - reader.endOfStream(); + } + return formatHttpRequest(method(operation), url_, path, operation.body, authorization_); + } + + static std::string_view method(const Operation& operation) { + switch (operation.what) { + case Operation::Kind::get: + return "GET"; + case Operation::Kind::has: + return "HEAD"; + case Operation::Kind::put: + break; + } + return "PUT"; + } + + // Sends the messages from `first` on in one go (only the first one once pipelining has been + // given up), then reads their responses in order. Returns the index of the first message left + // without a response: all of them, unless the transport failed (`error` says how) or the server + // announced the end of the connection, in which case the rest has to be sent again on a new one. + // A server may answer and close before the whole batch is sent: the answers that arrived count. + std::size_t exchange(std::span operations, + std::span messages, + std::span> responses, + std::size_t first, + std::string& error) { + std::array detail{}; + const std::size_t last = pipelined_ ? messages.size() : first + 1; + // One message after the other, without waiting for the answers: no copy of the batch. + for (std::size_t i = first; i < last; ++i) { + if (!transport::sendAll(connection_, messages[i].data(), messages[i].size(), timeout_, detail.data(), detail.size())) { + error = std::format("send: {}", detail.data()); break; } - reader.feed(std::string_view{buffer.data(), static_cast(received)}); } - if (!reader.complete()) { - error = "malformed or truncated response"; - return std::nullopt; + std::string pending; // bytes of the next response, received with the previous one + std::vector buffer(std::size_t{64} * 1024); + for (std::size_t i = first; i < last; ++i) { + HttpResponseReader reader{operations[i].what == Operation::Kind::has}; + reader.feed(pending); + while (!reader.complete() && !reader.failed()) { + const long long received = transport::receiveSome(connection_, buffer.data(), buffer.size(), timeout_, detail.data(), detail.size()); + if (received < 0) { + if (error.empty()) { + error = std::format("receive: {}", detail.data()); + } + return i; + } + if (received == 0) { + reader.endOfStream(); + break; + } + reader.feed(std::string_view{buffer.data(), static_cast(received)}); + } + if (!reader.complete()) { + if (error.empty()) { + error = "malformed or truncated response"; + } + return i; + } + responses[i] = reader.response(); + pending = reader.remainder(); + if (!responses[i]->keepAlive) { + disconnect(); + return i + 1; + } } - return reader.response(); + return last; } - std::optional request(std::string_view method, const std::string& path, std::string_view body = {}) { - // After a failed connection the server is left alone for the rest of this process. - if (unreachable_) { - return std::nullopt; - } - const std::string message = formatHttpRequest(method, url_, path, body, authorization_); - std::string error; - // A kept-alive connection may have been closed by the server in the meantime: one retry - // on a fresh connection tells that apart from a server that is really failing. - for (int attempt = 0; attempt < 2; ++attempt) { + // Obtains a response to every message, on as many connections as needed. + void transmit(std::span operations, std::span messages, std::span> responses) { + std::size_t next = 0; + while (next < messages.size() && !unreachable_) { + // A kept-alive connection may have been closed by the server in the meantime: a retry + // on a fresh connection tells that apart from a server that is really failing. const bool reused = connection_ != nullptr; if (!connect()) { - return std::nullopt; + return; } - auto response = exchange(method, message, error); - if (response) { - if (!response->keepAlive) { - disconnect(); - } - // Refused credentials would be refused again: the server is left alone. - if (response->status == 401 || response->status == 403) { - fail(std::format("{} {}: HTTP status {}, the credentials were refused", method, path, response->status)); - unreachable_ = true; - return std::nullopt; - } - return response; + std::string error; + const std::size_t reached = exchange(operations, messages, responses, next, error); + const bool progress = reached > next; + next = reached; + if (next == messages.size() || error.empty()) { + continue; } disconnect(); - if (!reused) { + if (!progress && !reused && pipelined_ && messages.size() - next > 1) { + // A batch that fails on a fresh connection before any answer may be a server or a + // proxy that does not take pipelined requests: one at a time from now on. + pipelined_ = false; + continue; + } + if (!progress && !reused) { + // After a failed exchange the server is left alone for the rest of this process. + fail(std::format("{} {}: {}", method(operations[next]), target(operations[next].kind, operations[next].hash), error)); + unreachable_ = true; + } + } + } + + void interpret(Operation& operation, HttpResponse& response) { + const auto path = target(operation.kind, operation.hash); + // Refused credentials would be refused again: the server is left alone. + if (response.status == 401 || response.status == 403) { + if (!unreachable_) { + fail(std::format("{} {}: HTTP status {}, the credentials were refused", method(operation), path, response.status)); + unreachable_ = true; + } + return; + } + if (unreachable_) { + return; + } + switch (operation.what) { + case Operation::Kind::get: + if (response.status == 200) { + if (response.contentEncoding.empty() || response.contentEncoding == "identity") { + operation.found = true; + operation.content = std::move(response.body); + } else if (auto content = response.contentEncoding == "zstd" ? unzstd(response.body, operation.size) : std::nullopt) { + operation.found = true; + operation.content = std::move(*content); + } else { + fail(std::format("GET {}: content encoding {} not understood", path, response.contentEncoding)); + } + } else if (response.status != 404) { + fail(std::format("GET {}: HTTP status {}", path, response.status)); + } + break; + case Operation::Kind::has: + operation.found = response.status == 200; break; + case Operation::Kind::put: + operation.found = response.status >= 200 && response.status < 300; + if (!operation.found) { + fail(std::format("PUT {}: HTTP status {}", path, response.status)); + } + break; + } + } + + // The content compressed, or nothing if compressing does not make it smaller. + static std::optional zstd(std::string_view content) { + std::string packed(static_cast(compression::bound(content.size())), '\0'); + const auto size = compression::compress(content.data(), content.size(), packed.data(), packed.size(), 3); + if (size < 0 || static_cast(size) >= content.size()) { + return std::nullopt; + } + packed.resize(static_cast(size)); + return packed; + } + + // Content of `expected` bytes from zstd frames, or nothing. + static std::optional unzstd(std::string_view packed, std::int64_t expected) { + if (expected < 0) { + return std::nullopt; + } + // The expected size comes from the server: the buffer grows with what really decompresses, + // and an allocation that fails is a failed download, not a failed compilation. + std::string content; + const auto grow = [](void* owner, unsigned long long size) noexcept -> char* { + try { + auto& buffer = *static_cast(owner); + buffer.resize(static_cast(size)); + return buffer.data(); + } catch (...) { + return nullptr; } + }; + const auto size = compression::decompress(packed.data(), packed.size(), static_cast(expected), grow, &content); + if (size != expected) { + return std::nullopt; } - fail(std::format("{} {}: {}", method, path, error)); - unreachable_ = true; - return std::nullopt; + content.resize(static_cast(size)); + return content; } HttpUrl url_; int timeout_; std::string authorization_; std::string authorities_; + bool compressUploads_; transport::Connection* connection_ = nullptr; bool unreachable_ = false; + bool pipelined_ = true; std::vector errors_; }; diff --git a/src/cppmcache/RemoteTransport.cpp b/src/cppmcache/RemoteTransport.cpp index 9fbef9e..7852e7d 100644 --- a/src/cppmcache/RemoteTransport.cpp +++ b/src/cppmcache/RemoteTransport.cpp @@ -22,6 +22,13 @@ #include #include +// setsockopt and TCP_NODELAY; on Windows, stdnet has included Winsock already. +#if !defined(_WIN32) + #include + #include + #include +#endif + namespace { namespace net = stdnet; @@ -100,6 +107,18 @@ Outcome> runFor(net::io_context& context, Sender sender, int ti return outcome; } +// Turns Nagle's algorithm off; a failure only costs time. +template +void noDelay(Handle handle) noexcept { +#if defined(_WIN32) + const BOOL on = TRUE; + ::setsockopt(handle, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&on), sizeof on); +#else + const int on = 1; + ::setsockopt(handle, IPPROTO_TCP, TCP_NODELAY, &on, sizeof on); +#endif +} + void describe(char* error, unsigned long long capacity, std::string_view message) noexcept { if (error == nullptr || capacity == 0) { return; @@ -191,6 +210,10 @@ Connection* open(const char* host, return nullptr; } connection->stream.emplace(std::move(std::get<0>(*outcome.value))); + // A request is written in one go, but TLS may split it into records: without this, Nagle's + // algorithm holds the last one back until the server acknowledges the first, and a server + // that delays its acknowledgements makes every request wait 40 ms. + noDelay(connection->stream->native_handle()); return connection; } catch (const std::exception& exception) { describe(error, errorCapacity, exception.what()); diff --git a/src/cppmcache/RemoteTransportDisabled.cpp b/src/cppmcache/RemoteTransportDisabled.cpp index 7da8f56..ebb811a 100644 --- a/src/cppmcache/RemoteTransportDisabled.cpp +++ b/src/cppmcache/RemoteTransportDisabled.cpp @@ -2,8 +2,10 @@ // Copyright (C) 2026 Ambroise Leclerc /** * @file RemoteTransportDisabled.cpp - * @brief Stand-in for the transport of the remote cache in a build configured without it. + * @brief Stand-ins for the transport and the compression of the remote cache in a build + * configured without it. */ +#include "Compression.hpp" #include "RemoteTransport.hpp" namespace cppmcache::transport { @@ -51,3 +53,25 @@ long long receiveSome(Connection*, char*, unsigned long long, int, char* error, void close(Connection*) noexcept {} } // namespace cppmcache::transport + +// Without the remote cache, nothing is compressed either. + +namespace cppmcache::compression { + +bool available() noexcept { + return false; +} + +unsigned long long bound(unsigned long long) noexcept { + return 0; +} + +long long compress(const char*, unsigned long long, char*, unsigned long long, int) noexcept { + return -1; +} + +long long decompress(const char*, unsigned long long, unsigned long long, Grow, void*) noexcept { + return -1; +} + +} // namespace cppmcache::compression diff --git a/src/cppmcache/Store.cppm b/src/cppmcache/Store.cppm index 577761a..f20878a 100644 --- a/src/cppmcache/Store.cppm +++ b/src/cppmcache/Store.cppm @@ -43,8 +43,10 @@ struct Config { std::string remoteUrl; // A PEM file of the only roots trusted over https, empty for the system's. std::string remoteAuthorities; - bool remoteReadOnly = false; - int remoteTimeoutMillis = 10'000; + // Content blobs are uploaded zstd-compressed (CPPMCACHE_REMOTE_COMPRESSION=zstd). + bool remoteCompression = false; + bool remoteReadOnly = false; + int remoteTimeoutMillis = 10'000; // Size beyond which the least recently used entries are evicted, in bytes. Zero: no limit. std::uintmax_t maxSize = std::uintmax_t{5} << 30; }; @@ -129,6 +131,7 @@ Config loadConfig() { config.remoteUrl = *remote; } config.remoteAuthorities = environment("CPPMCACHE_REMOTE_CA_CERT").value_or(""); + config.remoteCompression = environment("CPPMCACHE_REMOTE_COMPRESSION").value_or("") == "zstd"; config.remoteReadOnly = environment("CPPMCACHE_REMOTE_READ_ONLY").has_value(); if (const auto timeout = environment("CPPMCACHE_REMOTE_TIMEOUT_MS")) { int value = 0; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 5d1fe6e..b7b30c0 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -155,7 +155,9 @@ if(CPPMCACHE_REMOTE AND Python3_Interpreter_FOUND) endif() # https-token and https-basic: TLS with the test root of integration/tls, and a server that # requires credentials. They need a cppmcache built with TLS. - set(remote_variants plain chunked) + # close: a server that closes the connection after every response, which interrupts every + # pipelined batch. + set(remote_variants plain chunked close) if(NOT cppmcache_tls_engine STREQUAL "OFF") list(APPEND remote_variants https-token https-basic) endif() @@ -163,6 +165,8 @@ if(CPPMCACHE_REMOTE AND Python3_Interpreter_FOUND) set(server_options "") if(encoding STREQUAL "chunked") set(server_options --chunked) + elseif(encoding STREQUAL "close") + set(server_options --close) elseif(encoding STREQUAL "https-token") set(server_options --tls --token test-token-a1b2c3) elseif(encoding STREQUAL "https-basic") diff --git a/tests/integration/CacheServer.py b/tests/integration/CacheServer.py index 2cd04f4..3dcad25 100755 --- a/tests/integration/CacheServer.py +++ b/tests/integration/CacheServer.py @@ -30,6 +30,7 @@ import hashlib import os import re +import socket import ssl import subprocess import sys @@ -44,6 +45,7 @@ class CacheHandler(BaseHTTPRequestHandler): blobs: dict[str, bytes] = {} lock = threading.Lock() chunked = False + close = False # close the connection after every response, as an HTTP/1.0 server would authorization: str | None = None # the Authorization header every request must carry def log_message(self, format: str, *args: object) -> None: # noqa: A002 - name imposed by the base class @@ -52,6 +54,10 @@ def log_message(self, format: str, *args: object) -> None: # noqa: A002 - name def reply(self, status: int, body: bytes = b"", *, head: bool = False) -> None: self.send_response(status) + if self.close: + # The rest of a pipelined batch is left unread: the client must send it again. + self.send_header("Connection", "close") + self.close_connection = True if self.chunked and body and not head: # Exercises the client's chunked decoding: the body is sent in two chunks. self.send_header("Transfer-Encoding", "chunked") @@ -67,6 +73,12 @@ def reply(self, status: int, body: bytes = b"", *, head: bool = False) -> None: if not head: self.wfile.write(body) + def setup(self) -> None: + super().setup() + # Responses to pipelined requests are small writes in a row: without this, Nagle's algorithm + # holds each one until the client acknowledges the previous one, 40 ms later. + self.connection.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + def authorised(self) -> bool: if self.authorization is None or self.headers.get("Authorization") == self.authorization: return True @@ -116,6 +128,7 @@ def main() -> int: parser.add_argument("--serve", action="store_true", help="only serve, until interrupted") parser.add_argument("--port", type=int, default=0, help="port to listen on (default: a free one)") parser.add_argument("--chunked", action="store_true", help="answer GET requests with chunked bodies") + parser.add_argument("--close", action="store_true", help="close the connection after every response") parser.add_argument("--tls", action="store_true", help="speak HTTPS with the certificate of tests/integration/tls") credentials = parser.add_mutually_exclusive_group() credentials.add_argument("--token", help="require this bearer token") @@ -128,6 +141,7 @@ def main() -> int: return subprocess.run(command, check=False).returncode CacheHandler.chunked = args.chunked + CacheHandler.close = args.close passed: dict[str, str] = {} if args.token: CacheHandler.authorization = f"Bearer {args.token}" @@ -136,6 +150,9 @@ def main() -> int: user, _, password = args.basic.partition(":") CacheHandler.authorization = "Basic " + base64.b64encode(args.basic.encode()).decode() passed.update(CPPMCACHE_TEST_USER=user, CPPMCACHE_TEST_PASSWORD=password) + # A parallel build opens dozens of connections at once: socketserver's backlog of 5 makes + # Windows refuse the others and retry them hundreds of milliseconds later. + ThreadingHTTPServer.request_queue_size = 128 server = ThreadingHTTPServer(("127.0.0.1", args.port), CacheHandler) scheme = "http" if args.tls: diff --git a/tests/spec/HttpSpec.cpp b/tests/spec/HttpSpec.cpp index 3a7d242..3edc15c 100644 --- a/tests/spec/HttpSpec.cpp +++ b/tests/spec/HttpSpec.cpp @@ -334,4 +334,33 @@ const speclab::Register connectionEnd{"HTTP: connection handling and malformed r .Execute(); }}; +const speclab::Register pipelined{ + "HTTP: pipelined responses", + "unit,http", + [] { + return speclab::Test("HTTP-011") + .Then("a reader stops at the end of its response and hands over the bytes of the next ones", + [] { + const std::string_view stream = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nab" + "HTTP/1.1 200 OK\r\nContent-Length: 9\r\n\r\n" + "HTTP/1.1 404 Not Found\r\nTransfer-Encoding: chunked\r\n\r\n3\r\nxyz\r\n0\r\n\r\n"; + HttpResponseReader first; + first.feed(stream); + HttpResponseReader head{true}; + head.feed(first.remainder()); + HttpResponseReader last; + last.feed(head.remainder()); + Checks checks; + checks.expect(first.complete() && first.response().body == "ab", "the first body ends at its length"); + checks.expect(head.complete() && head.response().body.empty(), "the answer to a HEAD has no body, whatever its length says"); + checks.expect(last.complete() && last.response().status == 404 && last.response().body == "xyz", "a chunked response follows"); + checks.expect(last.remainder().empty(), "nothing is left"); + HttpResponseReader partial; + partial.feed(stream.substr(0, 20)); + checks.expect(!partial.complete() && partial.remainder().empty(), "an incomplete response hands over nothing"); + checks.raise(); + }) + .Execute(); + }}; + } // namespace diff --git a/tools/compare_caches.py b/tools/compare_caches.py index b6940cb..329d850 100755 --- a/tools/compare_caches.py +++ b/tools/compare_caches.py @@ -17,8 +17,13 @@ The checkouts are /trees/a and /trees/b. CCACHE_BASEDIR and CPPMCACHE_BASEDIR are set to /trees, so that the two checkouts can share entries; the dependencies fetched by CPM -are kept outside it, in /cpm, as they would be in a user's home directory. The remote scenarios use the test server of Bazel's HTTP caching protocol in -tests/integration/CacheServer.py. +are kept outside it, in /cpm, as they would be in a user's home directory. + +The remote scenarios use the test server of Bazel's HTTP caching protocol in +tests/integration/CacheServer.py, or a bazel-remote started with Docker (--remote-server), fresh +in every round so that remote-cold starts empty. --remote-tls makes the server speak https with +the test certificate of tests/integration/tls. --remote-delay-ms and --remote-bandwidth-mbit put +tools/latency_proxy.py between cppmcache and the server, to model a distant one. Each cell of the report is the median of the rounds, with the lowest and highest times. The report is written in English, because it is published in the CI job summary. @@ -34,10 +39,13 @@ import json import os import shutil +import ssl import statistics import subprocess import sys import time +import urllib.error +import urllib.request from pathlib import Path # ccache counters that denote a compilation passed to the compiler without going through the cache. @@ -73,7 +81,12 @@ # Extensions of the binary module interfaces written by GCC, Clang and MSVC. BMI_EXTENSIONS = (".gcm", ".pcm", ".ifc") -CACHE_SERVER = Path(__file__).resolve().parent.parent / "tests" / "integration" / "CacheServer.py" +ROOT = Path(__file__).resolve().parent.parent +CACHE_SERVER = ROOT / "tests" / "integration" / "CacheServer.py" +LATENCY_PROXY = ROOT / "tools" / "latency_proxy.py" +TEST_CERTIFICATES = ROOT / "tests" / "integration" / "tls" +# The image CI tests against, pinned by digest. +BAZEL_REMOTE_IMAGE = "buchgr/bazel-remote-cache@sha256:c6e9c3ef67c20bfa558559f314cf4213ec8f890488e5722d42ee26cc743f576f" class BuildFailed(Exception): @@ -124,6 +137,9 @@ def read_profile(log: Path) -> dict | None: calls = 0 for line in log.read_text(encoding="utf-8", errors="replace").splitlines(): fields = line.split("\t") + # Since 0.4 a line starts with the time of the call, in UTC: "2026-11-30T23:10:35.827Z". + if fields and fields[0].endswith("Z") and "T" in fields[0]: + fields = fields[1:] # "error" and "remote error" lines are diagnostics written before the outcome of the same # call, whose line carries the times of the whole call. if len(fields) < 4 or not fields[3].startswith("total=") or fields[0] in ("error", "remote error"): @@ -148,22 +164,73 @@ def count_bmis(build: Path) -> int: class CacheServer: - """The test server of Bazel's HTTP caching protocol, started for the remote scenarios.""" + """The server of the remote scenarios, and the proxy in front of it when one is asked for.""" - def __init__(self) -> None: - self.process = subprocess.Popen([sys.executable, str(CACHE_SERVER), "--serve"], stdout=subprocess.PIPE, text=True) - assert self.process.stdout is not None - self.url = self.process.stdout.readline().strip() - if not self.url.startswith("http://"): + def __init__(self, args: argparse.Namespace) -> None: + self.processes: list[subprocess.Popen] = [] + self.container: str | None = None + self.env: dict[str, str] = {} + scheme = "https" if args.remote_tls else "http" + try: + if args.remote_server == "bazel-remote": + address = self.start_bazel_remote(args.remote_tls) + else: + command = [sys.executable, str(CACHE_SERVER), "--serve"] + (["--tls"] if args.remote_tls else []) + url = self.start(command) + if not url.startswith(f"{scheme}://"): + raise RuntimeError("the test cache server did not start") + address = url.split("://", 1)[1] + if args.remote_delay_ms or args.remote_bandwidth_mbit: + address = self.start([sys.executable, str(LATENCY_PROXY), "--target", address, + "--delay-ms", str(args.remote_delay_ms), "--bandwidth-mbit", str(args.remote_bandwidth_mbit)]) + if args.remote_tls: + self.env["CPPMCACHE_REMOTE_CA_CERT"] = str(TEST_CERTIFICATES / "ca.pem") + if args.remote_compression: + self.env["CPPMCACHE_REMOTE_COMPRESSION"] = "zstd" + self.env["CPPMCACHE_REMOTE"] = f"{scheme}://{address}" + self.wait_ready(self.env["CPPMCACHE_REMOTE"]) + except BaseException: self.stop() - raise RuntimeError("the test cache server did not start") + raise + + def start(self, command: list[str]) -> str: + """Starts a process that prints its address first, and returns that line.""" + process = subprocess.Popen(command, stdout=subprocess.PIPE, text=True) + self.processes.append(process) + assert process.stdout is not None + return process.stdout.readline().strip() + + def start_bazel_remote(self, tls: bool) -> str: + command = ["docker", "run", "-d", "--rm", "-p", "127.0.0.1::8080"] + options = ["--max_size=20", "--dir=/data"] + if tls: + command += ["-v", f"{TEST_CERTIFICATES}:/tls:ro"] + options += ["--tls_cert_file=/tls/server.pem", "--tls_key_file=/tls/server.key"] + self.container = subprocess.run(command + [BAZEL_REMOTE_IMAGE] + options, capture_output=True, text=True, check=True).stdout.strip() + port = subprocess.run(["docker", "port", self.container, "8080/tcp"], capture_output=True, text=True, check=True).stdout + return "127.0.0.1:" + port.split()[0].rpartition(":")[2] + + def wait_ready(self, url: str) -> None: + context = ssl.create_default_context(cafile=str(TEST_CERTIFICATES / "ca.pem")) if url.startswith("https") else None + for _ in range(60): + try: + urllib.request.urlopen(f"{url}/ac/{'0' * 64}", timeout=2, context=context) + return + except urllib.error.HTTPError: + return # 404: the server answers + except OSError: + time.sleep(0.5) + raise RuntimeError(f"the cache server at {url} did not answer") def stop(self) -> None: - self.process.terminate() - try: - self.process.wait(timeout=10) - except subprocess.TimeoutExpired: - self.process.kill() + for process in reversed(self.processes): + process.terminate() + try: + process.wait(timeout=10) + except subprocess.TimeoutExpired: + process.kill() + if self.container: + subprocess.run(["docker", "rm", "-f", self.container], capture_output=True, check=False) class Launcher: @@ -297,8 +364,8 @@ def relocated(record) -> None: record("relocated", timed_build(configure(checkouts[1]))) def remote(record) -> None: - server = CacheServer() - launcher.env["CPPMCACHE_REMOTE"] = server.url + server = CacheServer(args) + launcher.env.update(server.env) try: # The first build populates the remote cache, whether or not it is reported. launcher.reset_cache() @@ -306,7 +373,8 @@ def remote(record) -> None: launcher.reset_cache() record("remote-warm", timed_build(configure(checkouts[0]))) finally: - del launcher.env["CPPMCACHE_REMOTE"] + for variable in server.env: + del launcher.env[variable] server.stop() launcher.reset_cache() @@ -427,6 +495,14 @@ def markdown(report: dict) -> str: "“–” that the scenario does not apply.", "", ] + remote = report.get("remote") + if remote and any(report["results"].get("cppmcache", {}).get(key) for key in ("remote-cold", "remote-warm")): + link = ("no proxy" if not (remote["delay_ms"] or remote["bandwidth_mbit"]) + else f"through tools/latency_proxy.py, {remote['delay_ms']:g} ms each way" + + (f", {remote['bandwidth_mbit']:g} Mbit/s each way" if remote["bandwidth_mbit"] else ", unlimited bandwidth")) + server = "bazel-remote" if remote["server"] == "bazel-remote" else "the test server" + uploads = "compressed uploads" if remote.get("compression") else "uncompressed uploads" + lines += [f"Remote scenarios: {server} on this machine over {'https' if remote['tls'] else 'http'}, {link}, {uploads}.", ""] for note in bmi_notes(report): lines += [note, ""] lines += profile_lines(report) @@ -479,6 +555,15 @@ def main() -> int: help="run cppmcache with CPPMCACHE_LOG and report where its own time went") parser.add_argument("--check-cold", action="store_true", help="fail if cppmcache's clean build with an empty cache is slower than ccache's beyond the spread") + parser.add_argument("--remote-server", choices=["test", "bazel-remote"], default="test", + help="server of the remote scenarios: the test server, or a bazel-remote started with Docker") + parser.add_argument("--remote-tls", action="store_true", help="the remote scenarios over https, with the test certificate") + parser.add_argument("--remote-compression", action="store_true", + help="upload zstd-compressed blobs in the remote scenarios (CPPMCACHE_REMOTE_COMPRESSION=zstd)") + parser.add_argument("--remote-delay-ms", type=float, default=0.0, + help="one-way delay between cppmcache and the server, through tools/latency_proxy.py") + parser.add_argument("--remote-bandwidth-mbit", type=float, default=0.0, + help="bandwidth of each direction between cppmcache and the server, in Mbit/s (0: unlimited)") parser.add_argument("--output-json", type=Path) parser.add_argument("--output-markdown", type=Path) args = parser.parse_args() @@ -526,6 +611,13 @@ def main() -> int: "cppmcache_version": tool_version(cppmcache), "edit": args.edit, "rounds": args.runs, + "remote": { + "server": args.remote_server, + "tls": args.remote_tls, + "compression": args.remote_compression, + "delay_ms": args.remote_delay_ms, + "bandwidth_mbit": args.remote_bandwidth_mbit, + }, "results": {name: {key: summarise(runs) for key, runs in cells.items()} for name, cells in rounds.items()}, } text = markdown(report) diff --git a/tools/latency_proxy.py b/tools/latency_proxy.py new file mode 100644 index 0000000..bfa725d --- /dev/null +++ b/tools/latency_proxy.py @@ -0,0 +1,125 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-or-later +# Copyright (C) 2026 Ambroise Leclerc +"""A TCP proxy that adds the latency and the bandwidth limit of a network link. + +Every byte that crosses the proxy, in either direction, arrives `--delay-ms` later than it was sent, +and each direction is one link of `--bandwidth-mbit`, shared by all connections: a chunk waits for +the link to be free, takes its transmission time on it, then travels for the delay. A round trip +through the proxy therefore costs twice the delay, as a real round trip would. + +The TCP handshake is modelled too: the first bytes of a connection cannot arrive before the round +trip of the handshake plus their own delay. Otherwise it is a model, not a network: the TCP +connections on either side are local, so there is no packet loss, no congestion control and no slow +start. What it reproduces is what dominates a cache client on a distant server: round trips and +transfer times. + + tools/latency_proxy.py --target 127.0.0.1:9090 --delay-ms 10 --bandwidth-mbit 100 + +prints the address it listens on (127.0.0.1 and a free port unless --listen says otherwise), then +serves until interrupted. +""" + +from __future__ import annotations + +import argparse +import asyncio +import sys +import time + + +class Link: + """One direction of the network: a delay and a bandwidth shared by every connection.""" + + def __init__(self, delay: float, bytes_per_second: float | None) -> None: + self.delay = delay + self.bytes_per_second = bytes_per_second + self.free_at = 0.0 + + def arrival(self, size: int) -> float: + """When a chunk of `size` bytes sent now arrives at the other end.""" + now = time.monotonic() + start = max(now, self.free_at) + finish = start + (size / self.bytes_per_second if self.bytes_per_second else 0.0) + self.free_at = finish + return finish + self.delay + + +async def pump(reader: asyncio.StreamReader, writer: asyncio.StreamWriter, link: Link, not_before: float = 0.0) -> None: + """Copies one direction, each chunk released at its arrival time, in order, none before `not_before`.""" + queue: asyncio.Queue[tuple[float, bytes]] = asyncio.Queue() + + async def deliver() -> None: + while True: + arrival, data = await queue.get() + if not data: + break + wait = arrival - time.monotonic() + if wait > 0: + await asyncio.sleep(wait) + writer.write(data) + await writer.drain() + if writer.can_write_eof(): + try: + writer.write_eof() + except OSError: + pass # the other end has gone already + + delivery = asyncio.create_task(deliver()) + try: + while data := await reader.read(65536): + queue.put_nowait((max(link.arrival(len(data)), not_before), data)) + except ConnectionError: + pass + queue.put_nowait((0.0, b"")) + try: + await delivery + except ConnectionError: + pass + + +async def serve(arguments: argparse.Namespace) -> None: + rate = arguments.bandwidth_mbit * 1e6 / 8 if arguments.bandwidth_mbit else None + upstream = Link(arguments.delay_ms / 1000, rate) + downstream = Link(arguments.delay_ms / 1000, rate) + target_host, _, target_port = arguments.target.rpartition(":") + + async def handle(client_reader: asyncio.StreamReader, client_writer: asyncio.StreamWriter) -> None: + # The client may send at once, but on a real link its first bytes would leave after the + # handshake's round trip. + handshaken = time.monotonic() + 3 * upstream.delay + try: + server_reader, server_writer = await asyncio.open_connection(target_host, int(target_port)) + except OSError: + client_writer.close() + return + await asyncio.gather(pump(client_reader, server_writer, upstream, handshaken), pump(server_reader, client_writer, downstream)) + for writer in (client_writer, server_writer): + writer.close() + + host, _, port = arguments.listen.rpartition(":") + server = await asyncio.start_server(handle, host, int(port)) + address = server.sockets[0].getsockname() + print(f"{address[0]}:{address[1]}", flush=True) + async with server: + await server.serve_forever() + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + parser.add_argument("--target", required=True, help="host:port to forward to") + parser.add_argument("--listen", default="127.0.0.1:0", help="host:port to listen on (default: a free local port)") + parser.add_argument("--delay-ms", type=float, default=0.0, help="one-way delay of each direction, in milliseconds") + parser.add_argument("--bandwidth-mbit", type=float, default=0.0, help="bandwidth of each direction, in Mbit/s (0: unlimited)") + arguments = parser.parse_args() + if arguments.delay_ms < 0 or arguments.bandwidth_mbit < 0: + parser.error("--delay-ms and --bandwidth-mbit cannot be negative") + try: + asyncio.run(serve(arguments)) + except KeyboardInterrupt: + pass + return 0 + + +if __name__ == "__main__": + sys.exit(main())