From 56e4699d4b9a7999e31f2fd6eec3db9fb0043982 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:59:38 +0100 Subject: [PATCH 1/4] Speak the gRPC interface of the Remote Execution API (#19) - grpc:// and grpcs:// URLs, the path being the instance name. grpcs is TLS with ALPN h2 and the same authentication and credentials as https. - An HTTP/2 client written here (Grpc.cppm): prior knowledge or ALPN, the largest windows advertised, the server's windows and frame size honoured, no push, GOAWAY and RST_STREAM ending the call. HPACK (Hpack.cppm): literal fields when encoding, the whole format with Huffman coding when decoding. - The operations of the remote cache become ActionCache.GetActionResult and UpdateActionResult, FindMissingBlobs, BatchReadBlobs and BatchUpdateBlobs below 3 MiB, ByteStream.Read and Write above. A manifest key gets a nominal digest size of 1: servers refuse 0 for a hash other than the empty blob's. - Tests: the examples of RFC 7541, Appendix C; gRPC framing and URLs; a 5 MB output in the remote integration test; CI runs that test against bazel-remote's gRPC port, plain and with TLS and Basic authentication. --- .github/workflows/ci.yml | 12 +- CMakeLists.txt | 2 + README.md | 4 +- docs/usage.md | 26 +- src/cppmcache/Cache.cppm | 16 +- src/cppmcache/Grpc.cppm | 526 ++++++++++++++++++++++ src/cppmcache/Hpack.cppm | 379 ++++++++++++++++ src/cppmcache/Http.cppm | 39 +- src/cppmcache/Remote.cppm | 343 +++++++++++++- src/cppmcache/RemoteTransport.cpp | 4 +- src/cppmcache/RemoteTransport.hpp | 8 +- src/cppmcache/RemoteTransportDisabled.cpp | 2 +- tests/CMakeLists.txt | 2 + tests/integration/Remote.cmake | 23 +- tests/spec/GrpcSpec.cpp | 60 +++ tests/spec/HpackSpec.cpp | 157 +++++++ tests/spec/HttpSpec.cpp | 34 +- 17 files changed, 1571 insertions(+), 66 deletions(-) create mode 100644 src/cppmcache/Grpc.cppm create mode 100644 src/cppmcache/Hpack.cppm create mode 100644 tests/spec/GrpcSpec.cpp create mode 100644 tests/spec/HpackSpec.cpp diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 3c1c5fd..b432b9d 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -165,7 +165,8 @@ jobs: run: ctest --test-dir build --output-on-failure # 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 + # without and with compressed uploads, and over its gRPC interface; then over https and + # grpcs 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' @@ -182,26 +183,31 @@ jobs: done curl -sf "$@" > /dev/null } - docker run -d --rm --name bazel-remote -p 127.0.0.1:19090:8080 "$BAZEL_REMOTE_IMAGE" --max_size=1 --dir=/data + docker run -d --rm --name bazel-remote -p 127.0.0.1:19090:8080 -p 127.0.0.1:19092:9092 "$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 + CPPMCACHE_TEST_REMOTE=grpc://127.0.0.1:19092 ctest --test-dir build -R 'integration\.remote\.plain' --output-on-failure + docker logs bazel-remote 2>&1 | grep -c ' GRPC ' | xargs echo "gRPC calls served by bazel-remote:" docker logs bazel-remote 2>&1 | grep -cE ' (GET|PUT|HEAD) ' | xargs echo "requests served by bazel-remote:" docker rm -f bazel-remote secrets="${RUNNER_TEMP}/bazel-remote-secrets" mkdir -p "$secrets" printf '%s:%s\n' "$TEST_USER" "$(openssl passwd -apr1 -salt cppmcache "$TEST_PASSWORD")" > "${secrets}/htpasswd" - docker run -d --rm --name bazel-remote-tls -p 127.0.0.1:19091:8080 \ + docker run -d --rm --name bazel-remote-tls -p 127.0.0.1:19091:8080 -p 127.0.0.1:19093:9092 \ -v "${PWD}/tests/integration/tls:/tls:ro" -v "${secrets}:/secrets:ro" "$BAZEL_REMOTE_IMAGE" --max_size=1 --dir=/data \ --tls_cert_file=/tls/server.pem --tls_key_file=/tls/server.key --htpasswd_file=/secrets/htpasswd wait_for --cacert tests/integration/tls/ca.pem -u "${TEST_USER}:${TEST_PASSWORD}" https://127.0.0.1:19091/status CPPMCACHE_TEST_REMOTE=https://127.0.0.1:19091 CPPMCACHE_TEST_CA="${PWD}/tests/integration/tls/ca.pem" \ CPPMCACHE_TEST_USER="$TEST_USER" CPPMCACHE_TEST_PASSWORD="$TEST_PASSWORD" \ ctest --test-dir build -R 'integration\.remote\.https-basic' --output-on-failure + CPPMCACHE_TEST_REMOTE=grpcs://127.0.0.1:19093 CPPMCACHE_TEST_CA="${PWD}/tests/integration/tls/ca.pem" \ + CPPMCACHE_TEST_USER="$TEST_USER" CPPMCACHE_TEST_PASSWORD="$TEST_PASSWORD" \ + ctest --test-dir build -R 'integration\.remote\.https-basic' --output-on-failure docker logs bazel-remote-tls 2>&1 | grep -cE ' (GET|PUT|HEAD) ' | xargs echo "requests served by bazel-remote over https:" docker rm -f bazel-remote-tls diff --git a/CMakeLists.txt b/CMakeLists.txt index 0336794..75ed114 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -76,6 +76,8 @@ target_sources(cppmcache_core PUBLIC FILE_SET CXX_MODULES BASE_DIRS src FILES src/cppmcache/Driver.cppm src/cppmcache/Process.cppm src/cppmcache/Http.cppm + src/cppmcache/Hpack.cppm + src/cppmcache/Grpc.cppm src/cppmcache/Remote.cppm src/cppmcache/Cache.cppm) cppmcache_configure_target(cppmcache_core) diff --git a/README.md b/README.md index 0fe73db..8791f53 100644 --- a/README.md +++ b/README.md @@ -112,7 +112,7 @@ PDB shared by the compilations of a target. Configure with | To share between… | Set | |-----------------------------|------------------------------------------------------------------| | checkouts, or CI runners | `CPPMCACHE_BASEDIR` to the root of the project: paths under it become relative | -| machines | `CPPMCACHE_REMOTE=https://host[:port]` (or `http://`), a [bazel-remote](https://github.com/buchgr/bazel-remote) or any server of Bazel's HTTP caching protocol | +| machines | `CPPMCACHE_REMOTE=https://host[:port]` (or `http://`), a [bazel-remote](https://github.com/buchgr/bazel-remote) or any server of Bazel's HTTP caching protocol; `grpcs://host[:port][/instance]` (or `grpc://`) for a server of the Remote Execution API's gRPC interface | | machines with different compiler dates | `CPPMCACHE_COMPILERCHECK=content` | Over `https://` the server's certificate is checked against the system's roots, and credentials @@ -127,7 +127,7 @@ come from the environment or from files, never from the URL. Details are in | `CPPMCACHE_MAXSIZE` | size of the local cache beyond which the entries used least recently are evicted: `500M`, `5G`, `0` for no limit (default: `5G`, powers of 1024) | | `CPPMCACHE_BASEDIR` | absolute directory under which paths are made relative | | `CPPMCACHE_COMPILERCHECK` | `content`: identify the compiler by the digest of its executable | -| `CPPMCACHE_REMOTE` | URL of a remote cache, `http://` or `https://` | +| `CPPMCACHE_REMOTE` | URL of a remote cache: `http://`, `https://`, `grpc://` or `grpcs://` | | `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) | diff --git a/docs/usage.md b/docs/usage.md index e09aba0..264a45f 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -152,6 +152,28 @@ export CPPMCACHE_REMOTE=http://localhost:8080 understand that encoding: it would store the compressed bytes, which every client would then refuse as not matching their digest. +### The gRPC interface + +A `grpc://` or `grpcs://` URL makes cppmcache speak the gRPC interface of the +[Remote Execution API](https://github.com/bazelbuild/remote-apis) instead, as servers such as +BuildBuddy, Buildbarn or bazel-remote (on its gRPC port, 9092 by default) offer it: + +```sh +export CPPMCACHE_REMOTE=grpcs://cache.example.com/my-instance +``` + +- `grpcs://` is gRPC over TLS (ALPN `h2`), with the same server authentication and credentials as + `https://` below; `grpc://` is HTTP/2 without TLS. The default port is 443 for `grpcs://`, 80 for + `grpc://`: a server on 9092 needs it written. +- The path, if any, is the instance name (`my-instance` above). +- Results and blobs go through ActionCache.GetActionResult and UpdateActionResult, + ContentAddressableStorage.FindMissingBlobs, BatchReadBlobs and BatchUpdateBlobs, and + ByteStream.Read and Write for blobs above 3 MiB. A manifest is stored as an ActionResult, as over + HTTP, under a digest whose size is a nominal 1. +- Blobs travel uncompressed, and the client is written in this project (HTTP/2 and HPACK + included) rather than taken from the gRPC libraries, which would weigh on every project that + imports cppmcache. + ### TLS and credentials An `https://` URL makes every connection TLS 1.3, and the server is authenticated with the Web PKI: @@ -588,8 +610,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 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)). +- Over gRPC, blobs are not compressed, and calls go one after the other on the connection. 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 da8b001..3cd0ac0 100644 --- a/src/cppmcache/Cache.cppm +++ b/src/cppmcache/Cache.cppm @@ -521,6 +521,10 @@ struct Context { // Name, in an ActionResult stored under a manifest key, of the output that holds the manifest. constexpr std::string_view manifestOutput = "manifest"; +// A manifest key names no action, so its digest has no size of its own. The gRPC interface wants +// one, and servers refuse zero for a hash that is not that of the empty blob: it gets a nominal 1. +constexpr std::int64_t manifestKeySize = 1; + // Content of a blob, from the local CAS or else from the remote cache. A blob that came from the // remote cache is checked against its digest and kept locally. std::optional fetchBlob(Context& context, const Digest& digest) { @@ -575,7 +579,7 @@ std::optional remoteManifest(Context& context) { if (context.remote == nullptr) { return std::nullopt; } - const auto encoded = context.remote->get("ac", context.manifestKey); + const auto encoded = context.remote->get("ac", context.manifestKey, manifestKeySize); const auto result = encoded ? ActionResult::decode(*encoded) : std::nullopt; if (!result) { return std::nullopt; @@ -996,7 +1000,7 @@ std::optional serve(Context& context, const ManifestEntry& entry) { auto resultBytes = store.actionGet(actionDigest); bool fromRemote = false; if (!resultBytes && context.remote != nullptr) { - resultBytes = context.remote->get("ac", actionDigest.hash); + resultBytes = context.remote->get("ac", actionDigest.hash, actionDigest.size); fromRemote = resultBytes.has_value(); } const auto result = resultBytes ? ActionResult::decode(*resultBytes) : std::nullopt; @@ -1108,9 +1112,9 @@ void upload(Context& context, const std::vector& localEntries, co std::vector probe; for (const auto& file : result.outputFiles) { - probe.push_back(RemoteCache::checking("cas", file.digest.hash)); + probe.push_back(RemoteCache::checking("cas", file.digest.hash, file.digest.size)); } - probe.push_back(RemoteCache::getting("ac", context.manifestKey)); + probe.push_back(RemoteCache::getting("ac", context.manifestKey, manifestKeySize)); remote.run(probe); // The server's manifest, from the local CAS when this machine has it. @@ -1189,14 +1193,14 @@ void upload(Context& context, const std::vector& localEntries, co 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), + std::array records{RemoteCache::putting("ac", actionDigest.hash, encodedResult, actionDigest.size), 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)) { + if (remote.put("ac", context.manifestKey, encodedHolder, manifestKeySize)) { context.store.count("remote_store"); } } diff --git a/src/cppmcache/Grpc.cppm b/src/cppmcache/Grpc.cppm new file mode 100644 index 0000000..7c74dc9 --- /dev/null +++ b/src/cppmcache/Grpc.cppm @@ -0,0 +1,526 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Ambroise Leclerc +/** + * @file Grpc.cppm + * @brief A gRPC client over HTTP/2 (RFC 9113), with only what calls to a cache server need. + * + * One connection, one call at a time, on the calling thread. The client opens the connection with + * prior knowledge of HTTP/2 (`grpc://`) or negotiates `h2` with ALPN over TLS (`grpcs://`). It + * advertises the largest flow-control windows, so that it never has to grant more while + * receiving, and honours the server's windows and frame size while sending. Server push is + * refused, priorities are ignored, and a server that ends the connection (GOAWAY) ends the calls. + */ +module; + +#include "RemoteTransport.hpp" + +export module cppmcache.grpc; + +import std; +import cppmcache.hpack; + +namespace cppmcache { + +enum class FrameType : std::uint8_t { + data = 0x0, + headers = 0x1, + priority = 0x2, + rstStream = 0x3, + settings = 0x4, + pushPromise = 0x5, + ping = 0x6, + goaway = 0x7, + windowUpdate = 0x8, + continuation = 0x9, +}; + +constexpr std::uint8_t endStream = 0x1; +constexpr std::uint8_t ack = 0x1; +constexpr std::uint8_t endHeaders = 0x4; +constexpr std::uint8_t padded = 0x8; +constexpr std::uint8_t priority = 0x20; + +constexpr std::uint32_t largestWindow = 0x7FFF'FFFF; +constexpr std::uint32_t defaultWindow = 65'535; +constexpr std::size_t ourFrameSize = 16'384; // SETTINGS_MAX_FRAME_SIZE left at its default + +struct Frame { + FrameType type{}; + std::uint8_t flags = 0; + std::uint32_t stream = 0; + std::string payload; +}; + +std::uint32_t bigEndian32(std::string_view bytes) { + return (static_cast(static_cast(bytes[0])) << 24) | (static_cast(static_cast(bytes[1])) << 16) + | (static_cast(static_cast(bytes[2])) << 8) | static_cast(static_cast(bytes[3])); +} + +void appendBigEndian(std::string& output, std::uint64_t value, int bytes) { + for (int shift = 8 * (bytes - 1); shift >= 0; shift -= 8) { + output.push_back(static_cast((value >> shift) & 0xFF)); + } +} + +} // namespace cppmcache + +export namespace cppmcache { + +// Frames gRPC messages: a flag byte (0: not compressed), a 32-bit length, the message. +std::string grpcFrame(std::span messages) { + std::string body; + for (const auto& message : messages) { + body.push_back('\0'); + appendBigEndian(body, message.size(), 4); + body += message; + } + return body; +} + +// The messages of a gRPC body, or nothing if it is malformed or compressed. +std::optional> grpcUnframe(std::string_view body) { + std::vector messages; + while (!body.empty()) { + if (body.size() < 5 || body[0] != '\0') { + return std::nullopt; + } + const auto length = bigEndian32(body.substr(1, 4)); + if (length > body.size() - 5) { + return std::nullopt; + } + messages.emplace_back(body.substr(5, length)); + body.remove_prefix(5 + static_cast(length)); + } + return messages; +} + +// gRPC status codes that the cache client tells apart. +struct GrpcStatus { + static constexpr int ok = 0; + static constexpr int notFound = 5; +}; + +struct GrpcReply { + // The gRPC status, or -1 when the call did not complete (transport, HTTP/2 or HTTP failure). + int status = -1; + std::string message; // grpc-message, or what went wrong + std::vector responses; +}; + +class GrpcChannel { +public: + // `secure`: TLS with ALPN h2; `authorities`: a PEM file of the only roots to trust, empty for the + // system's. `authorization`: the value of the authorization metadata, empty for none. + GrpcChannel(std::string host, + std::uint16_t port, + bool secure, + std::string authority, + int timeoutMilliseconds, + std::string authorization, + std::string authorities) + : host_(std::move(host)), + port_(port), + secure_(secure), + authority_(std::move(authority)), + timeout_(timeoutMilliseconds), + authorization_(std::move(authorization)), + authorities_(std::move(authorities)) {} + GrpcChannel(const GrpcChannel&) = delete; + GrpcChannel& operator=(const GrpcChannel&) = delete; + ~GrpcChannel() { + disconnect(); + } + + // Calls `path` (`/package.Service/Method`) with the request messages, which a unary call has + // exactly one of, and returns the response messages and the status. + GrpcReply call(std::string_view path, std::span requests) { + GrpcReply reply; + std::string error; + if (connection_ == nullptr && !connect(error)) { + reply.message = std::move(error); + return reply; + } + Stream stream; + stream.id = nextStream_; + stream.window = peerInitialWindow_; + nextStream_ += 2; + if (!sendHeaders(stream.id, path, error) || !sendBody(stream, grpcFrame(requests), error) || !receive(stream, error)) { + disconnect(); + reply.message = std::move(error); + return reply; + } + if (stream.httpStatus != 200) { + reply.message = std::format("HTTP status {}", stream.httpStatus); + return reply; + } + if (!stream.grpcStatus) { + reply.message = "the response has no grpc-status"; + return reply; + } + auto messages = grpcUnframe(stream.body); + if (!messages) { + reply.message = "malformed or compressed gRPC message"; + return reply; + } + reply.status = *stream.grpcStatus; + reply.message = std::move(stream.grpcMessage); + reply.responses = std::move(*messages); + return reply; + } + +private: + struct Stream { + std::uint32_t id = 0; + std::int64_t window = 0; // what the server still accepts on this stream + bool ended = false; + int httpStatus = 0; + std::optional grpcStatus; + std::string grpcMessage; + std::string body; + }; + + bool connect(std::string& error) { + std::array detail{}; + connection_ = transport::open(host_.c_str(), + port_, + secure_, + "h2", + authorities_.empty() ? nullptr : authorities_.c_str(), + std::min(timeout_, secure_ ? 5000 : 2000), + detail.data(), + detail.size()); + if (connection_ == nullptr) { + error = std::format("cannot connect to {}: {}", authority_, detail.data()); + return false; + } + inbox_.clear(); + decoder_ = HpackDecoder{}; + sendWindow_ = defaultWindow; + peerInitialWindow_ = defaultWindow; + peerFrameSize_ = ourFrameSize; + nextStream_ = 1; + // The preface, our settings (no push, the largest stream window), and the largest + // connection window. + std::string opening = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"; + std::string settings; + appendBigEndian(settings, 0x2, 2); // SETTINGS_ENABLE_PUSH + appendBigEndian(settings, 0, 4); + appendBigEndian(settings, 0x4, 2); // SETTINGS_INITIAL_WINDOW_SIZE + appendBigEndian(settings, largestWindow, 4); + frame(opening, FrameType::settings, 0, 0, settings); + std::string increment; + appendBigEndian(increment, largestWindow - defaultWindow, 4); + frame(opening, FrameType::windowUpdate, 0, 0, increment); + if (!send(opening, error)) { + disconnect(); + return false; + } + return true; + } + + void disconnect() { + if (connection_ != nullptr) { + transport::close(connection_); + connection_ = nullptr; + } + } + + static void frame(std::string& output, FrameType type, std::uint8_t flags, std::uint32_t stream, std::string_view payload) { + appendBigEndian(output, payload.size(), 3); + output.push_back(static_cast(type)); + output.push_back(static_cast(flags)); + appendBigEndian(output, stream & 0x7FFF'FFFF, 4); + output += payload; + } + + bool send(std::string_view bytes, std::string& error) { + std::array detail{}; + if (!transport::sendAll(connection_, bytes.data(), bytes.size(), timeout_, detail.data(), detail.size())) { + error = std::format("send: {}", detail.data()); + return false; + } + return true; + } + + bool sendHeaders(std::uint32_t stream, std::string_view path, std::string& error) { + std::vector fields{ + { ":method", "POST"}, + { ":scheme", secure_ ? "https" : "http"}, + { ":path", std::string{path}}, + { ":authority", authority_}, + {"content-type", "application/grpc"}, + { "te", "trailers"}, + { "user-agent", "cppmcache"}, + }; + if (!authorization_.empty()) { + fields.push_back({"authorization", authorization_}); + } + const std::string block = hpackEncode(fields); + std::string output; + std::size_t offset = 0; + do { + const auto piece = std::string_view{block}.substr(offset, peerFrameSize_); + offset += piece.size(); + const bool last = offset >= block.size(); + frame(output, piece.data() == block.data() ? FrameType::headers : FrameType::continuation, last ? endHeaders : 0, stream, piece); + } while (offset < block.size()); + return send(output, error); + } + + // Sends the body in DATA frames within the server's windows, the last one ending the stream. + // While a window is closed, frames from the server are handled until it opens again. + bool sendBody(Stream& stream, std::string_view body, std::string& error) { + std::size_t offset = 0; + for (;;) { + if (stream.ended) { + // The server answered before the end of the request, which it then ignores. + return true; + } + const auto allowed = std::min( + {static_cast(body.size() - offset), static_cast(peerFrameSize_), sendWindow_, stream.window}); + const bool last = offset + static_cast(std::max(allowed, 0)) == body.size(); + if (allowed > 0 || last) { + const auto piece = body.substr(offset, static_cast(std::max(allowed, 0))); + std::string output; + frame(output, FrameType::data, last ? endStream : 0, stream.id, piece); + if (!send(output, error)) { + return false; + } + offset += piece.size(); + sendWindow_ -= static_cast(piece.size()); + stream.window -= static_cast(piece.size()); + if (last) { + return true; + } + continue; + } + Frame incoming; + if (!readFrame(incoming, error) || !handle(incoming, stream, error)) { + return false; + } + } + } + + bool receive(Stream& stream, std::string& error) { + while (!stream.ended) { + Frame incoming; + if (!readFrame(incoming, error) || !handle(incoming, stream, error)) { + return false; + } + } + return true; + } + + bool readFrame(Frame& result, std::string& error) { + std::array detail{}; + std::vector buffer(std::size_t{64} * 1024); + const auto need = [&](std::size_t size) { + while (inbox_.size() < size) { + const long long received = transport::receiveSome(connection_, buffer.data(), buffer.size(), timeout_, detail.data(), detail.size()); + if (received <= 0) { + error = received < 0 ? std::format("receive: {}", detail.data()) : "the server closed the connection"; + return false; + } + inbox_.append(buffer.data(), static_cast(received)); + } + return true; + }; + if (!need(9)) { + return false; + } + const std::size_t length = (static_cast(static_cast(inbox_[0])) << 16) + | (static_cast(static_cast(inbox_[1])) << 8) | static_cast(inbox_[2]); + if (length > ourFrameSize) { + error = "HTTP/2 frame larger than allowed"; + return false; + } + if (!need(9 + length)) { + return false; + } + result.type = static_cast(inbox_[3]); + result.flags = static_cast(inbox_[4]); + result.stream = bigEndian32(std::string_view{inbox_}.substr(5, 4)) & 0x7FFF'FFFF; + result.payload = inbox_.substr(9, length); + inbox_.erase(0, 9 + length); + return true; + } + + // The payload of a DATA or HEADERS frame without its padding (and priority), or nothing. + static std::optional content(const Frame& incoming) { + std::string_view payload = incoming.payload; + std::size_t padding = 0; + if ((incoming.flags & padded) != 0) { + if (payload.empty()) { + return std::nullopt; + } + padding = static_cast(payload[0]); + payload.remove_prefix(1); + } + if (incoming.type == FrameType::headers && (incoming.flags & priority) != 0) { + if (payload.size() < 5) { + return std::nullopt; + } + payload.remove_prefix(5); + } + if (padding > payload.size()) { + return std::nullopt; + } + payload.remove_suffix(padding); + return payload; + } + + bool handle(const Frame& incoming, Stream& stream, std::string& error) { + switch (incoming.type) { + case FrameType::settings: + return settings(incoming, stream, error); + case FrameType::ping: + if ((incoming.flags & ack) == 0 && incoming.payload.size() == 8) { + std::string output; + frame(output, FrameType::ping, ack, 0, incoming.payload); + return send(output, error); + } + return true; + case FrameType::windowUpdate: { + if (incoming.payload.size() != 4) { + error = "malformed WINDOW_UPDATE"; + return false; + } + const auto increment = bigEndian32(incoming.payload) & 0x7FFF'FFFF; + if (incoming.stream == 0) { + sendWindow_ += increment; + } else if (incoming.stream == stream.id) { + stream.window += increment; + } + return true; + } + case FrameType::goaway: + error = "the server ended the connection (GOAWAY)"; + return false; + case FrameType::pushPromise: + error = "the server pushed a stream, which was refused"; + return false; + case FrameType::rstStream: + if (incoming.stream == stream.id) { + error = std::format("the server reset the stream (error {})", incoming.payload.size() == 4 ? bigEndian32(incoming.payload) : 0); + return false; + } + return true; + case FrameType::data: + if (incoming.stream == stream.id) { + const auto payload = content(incoming); + if (!payload) { + error = "malformed DATA frame"; + return false; + } + stream.body += *payload; + stream.ended = (incoming.flags & endStream) != 0; + } + return true; + case FrameType::headers: + case FrameType::continuation: + return headers(incoming, stream, error); + case FrameType::priority: + return true; + } + // Frames of unknown types are ignored (RFC 9113 §5.5). + return true; + } + + bool settings(const Frame& incoming, Stream& stream, std::string& error) { + if ((incoming.flags & ack) != 0) { + return true; + } + if (incoming.payload.size() % 6 != 0) { + error = "malformed SETTINGS"; + return false; + } + for (std::size_t offset = 0; offset < incoming.payload.size(); offset += 6) { + const auto identifier = (static_cast(static_cast(incoming.payload[offset])) << 8) + | static_cast(incoming.payload[offset + 1]); + const auto value = bigEndian32(std::string_view{incoming.payload}.substr(offset + 2, 4)); + if (identifier == 0x4) { + if (value > largestWindow) { + error = "invalid SETTINGS_INITIAL_WINDOW_SIZE"; + return false; + } + // The change applies to the open stream too (RFC 9113 §6.9.2). + stream.window += static_cast(value) - peerInitialWindow_; + peerInitialWindow_ = value; + } else if (identifier == 0x5) { + if (value < 16'384 || value > 0xFF'FFFF) { + error = "invalid SETTINGS_MAX_FRAME_SIZE"; + return false; + } + peerFrameSize_ = value; + } + } + std::string output; + frame(output, FrameType::settings, ack, 0, {}); + return send(output, error); + } + + bool headers(const Frame& incoming, Stream& stream, std::string& error) { + // Header blocks of other streams still go through the decoder, whose table they change. + if (incoming.type == FrameType::headers) { + const auto payload = content(incoming); + if (!payload) { + error = "malformed HEADERS frame"; + return false; + } + pending_ = *payload; + pendingFlags_ = incoming.flags; + pendingStream_ = incoming.stream; + } else { + if (incoming.stream != pendingStream_) { + error = "unexpected CONTINUATION frame"; + return false; + } + pending_ += incoming.payload; + } + if ((incoming.flags & endHeaders) == 0) { + return true; + } + const auto fields = decoder_.decode(pending_); + if (!fields) { + error = "HPACK decoding error"; + return false; + } + if (pendingStream_ != stream.id) { + return true; + } + for (const auto& field : *fields) { + if (field.name == ":status") { + std::from_chars(field.value.data(), field.value.data() + field.value.size(), stream.httpStatus); + } else if (field.name == "grpc-status") { + int status = 0; + if (std::from_chars(field.value.data(), field.value.data() + field.value.size(), status).ec == std::errc{}) { + stream.grpcStatus = status; + } + } else if (field.name == "grpc-message") { + stream.grpcMessage = field.value; + } + } + stream.ended = (pendingFlags_ & endStream) != 0; + return true; + } + + std::string host_; + std::uint16_t port_; + bool secure_; + std::string authority_; + int timeout_; + std::string authorization_; + std::string authorities_; + transport::Connection* connection_ = nullptr; + std::string inbox_; + HpackDecoder decoder_; + std::int64_t sendWindow_ = defaultWindow; + std::int64_t peerInitialWindow_ = defaultWindow; + std::size_t peerFrameSize_ = ourFrameSize; + std::uint32_t nextStream_ = 1; + std::string pending_; + std::uint8_t pendingFlags_ = 0; + std::uint32_t pendingStream_ = 0; +}; + +} // namespace cppmcache diff --git a/src/cppmcache/Hpack.cppm b/src/cppmcache/Hpack.cppm new file mode 100644 index 0000000..186830f --- /dev/null +++ b/src/cppmcache/Hpack.cppm @@ -0,0 +1,379 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Ambroise Leclerc +/** + * @file Hpack.cppm + * @brief HPACK (RFC 7541), the header compression of HTTP/2: what a gRPC client needs. + * + * The encoder writes every field as a literal that is not indexed, without Huffman coding: the + * peer's decoder keeps no state for it, and the few headers of a gRPC call cost little. The decoder + * implements the whole format, since a server may use its dynamic table and Huffman coding. + */ +export module cppmcache.hpack; + +import std; + +namespace cppmcache { + +struct HuffmanCode { + std::uint32_t code; + int length; +}; + +// RFC 7541, Appendix B: code and length in bits of each symbol, 256 being EOS. +constexpr std::array huffmanCodes{ + { + {0x1ff8, 13}, {0x7fffd8, 23}, {0xfffffe2, 28}, {0xfffffe3, 28}, {0xfffffe4, 28}, {0xfffffe5, 28}, {0xfffffe6, 28}, {0xfffffe7, 28}, + {0xfffffe8, 28}, {0xffffea, 24}, {0x3ffffffc, 30}, {0xfffffe9, 28}, {0xfffffea, 28}, {0x3ffffffd, 30}, {0xfffffeb, 28}, {0xfffffec, 28}, + {0xfffffed, 28}, {0xfffffee, 28}, {0xfffffef, 28}, {0xffffff0, 28}, {0xffffff1, 28}, {0xffffff2, 28}, {0x3ffffffe, 30}, {0xffffff3, 28}, + {0xffffff4, 28}, {0xffffff5, 28}, {0xffffff6, 28}, {0xffffff7, 28}, {0xffffff8, 28}, {0xffffff9, 28}, {0xffffffa, 28}, {0xffffffb, 28}, + {0x14, 6}, {0x3f8, 10}, {0x3f9, 10}, {0xffa, 12}, {0x1ff9, 13}, {0x15, 6}, {0xf8, 8}, {0x7fa, 11}, + {0x3fa, 10}, {0x3fb, 10}, {0xf9, 8}, {0x7fb, 11}, {0xfa, 8}, {0x16, 6}, {0x17, 6}, {0x18, 6}, + {0x0, 5}, {0x1, 5}, {0x2, 5}, {0x19, 6}, {0x1a, 6}, {0x1b, 6}, {0x1c, 6}, {0x1d, 6}, + {0x1e, 6}, {0x1f, 6}, {0x5c, 7}, {0xfb, 8}, {0x7ffc, 15}, {0x20, 6}, {0xffb, 12}, {0x3fc, 10}, + {0x1ffa, 13}, {0x21, 6}, {0x5d, 7}, {0x5e, 7}, {0x5f, 7}, {0x60, 7}, {0x61, 7}, {0x62, 7}, + {0x63, 7}, {0x64, 7}, {0x65, 7}, {0x66, 7}, {0x67, 7}, {0x68, 7}, {0x69, 7}, {0x6a, 7}, + {0x6b, 7}, {0x6c, 7}, {0x6d, 7}, {0x6e, 7}, {0x6f, 7}, {0x70, 7}, {0x71, 7}, {0x72, 7}, + {0xfc, 8}, {0x73, 7}, {0xfd, 8}, {0x1ffb, 13}, {0x7fff0, 19}, {0x1ffc, 13}, {0x3ffc, 14}, {0x22, 6}, + {0x7ffd, 15}, {0x3, 5}, {0x23, 6}, {0x4, 5}, {0x24, 6}, {0x5, 5}, {0x25, 6}, {0x26, 6}, + {0x27, 6}, {0x6, 5}, {0x74, 7}, {0x75, 7}, {0x28, 6}, {0x29, 6}, {0x2a, 6}, {0x7, 5}, + {0x2b, 6}, {0x76, 7}, {0x2c, 6}, {0x8, 5}, {0x9, 5}, {0x2d, 6}, {0x77, 7}, {0x78, 7}, + {0x79, 7}, {0x7a, 7}, {0x7b, 7}, {0x7ffe, 15}, {0x7fc, 11}, {0x3ffd, 14}, {0x1ffd, 13}, {0xffffffc, 28}, + {0xfffe6, 20}, {0x3fffd2, 22}, {0xfffe7, 20}, {0xfffe8, 20}, {0x3fffd3, 22}, {0x3fffd4, 22}, {0x3fffd5, 22}, {0x7fffd9, 23}, + {0x3fffd6, 22}, {0x7fffda, 23}, {0x7fffdb, 23}, {0x7fffdc, 23}, {0x7fffdd, 23}, {0x7fffde, 23}, {0xffffeb, 24}, {0x7fffdf, 23}, + {0xffffec, 24}, {0xffffed, 24}, {0x3fffd7, 22}, {0x7fffe0, 23}, {0xffffee, 24}, {0x7fffe1, 23}, {0x7fffe2, 23}, {0x7fffe3, 23}, + {0x7fffe4, 23}, {0x1fffdc, 21}, {0x3fffd8, 22}, {0x7fffe5, 23}, {0x3fffd9, 22}, {0x7fffe6, 23}, {0x7fffe7, 23}, {0xffffef, 24}, + {0x3fffda, 22}, {0x1fffdd, 21}, {0xfffe9, 20}, {0x3fffdb, 22}, {0x3fffdc, 22}, {0x7fffe8, 23}, {0x7fffe9, 23}, {0x1fffde, 21}, + {0x7fffea, 23}, {0x3fffdd, 22}, {0x3fffde, 22}, {0xfffff0, 24}, {0x1fffdf, 21}, {0x3fffdf, 22}, {0x7fffeb, 23}, {0x7fffec, 23}, + {0x1fffe0, 21}, {0x1fffe1, 21}, {0x3fffe0, 22}, {0x1fffe2, 21}, {0x7fffed, 23}, {0x3fffe1, 22}, {0x7fffee, 23}, {0x7fffef, 23}, + {0xfffea, 20}, {0x3fffe2, 22}, {0x3fffe3, 22}, {0x3fffe4, 22}, {0x7ffff0, 23}, {0x3fffe5, 22}, {0x3fffe6, 22}, {0x7ffff1, 23}, + {0x3ffffe0, 26}, {0x3ffffe1, 26}, {0xfffeb, 20}, {0x7fff1, 19}, {0x3fffe7, 22}, {0x7ffff2, 23}, {0x3fffe8, 22}, {0x1ffffec, 25}, + {0x3ffffe2, 26}, {0x3ffffe3, 26}, {0x3ffffe4, 26}, {0x7ffffde, 27}, {0x7ffffdf, 27}, {0x3ffffe5, 26}, {0xfffff1, 24}, {0x1ffffed, 25}, + {0x7fff2, 19}, {0x1fffe3, 21}, {0x3ffffe6, 26}, {0x7ffffe0, 27}, {0x7ffffe1, 27}, {0x3ffffe7, 26}, {0x7ffffe2, 27}, {0xfffff2, 24}, + {0x1fffe4, 21}, {0x1fffe5, 21}, {0x3ffffe8, 26}, {0x3ffffe9, 26}, {0xffffffd, 28}, {0x7ffffe3, 27}, {0x7ffffe4, 27}, {0x7ffffe5, 27}, + {0xfffec, 20}, {0xfffff3, 24}, {0xfffed, 20}, {0x1fffe6, 21}, {0x3fffe9, 22}, {0x1fffe7, 21}, {0x1fffe8, 21}, {0x7ffff3, 23}, + {0x3fffea, 22}, {0x3fffeb, 22}, {0x1ffffee, 25}, {0x1ffffef, 25}, {0xfffff4, 24}, {0xfffff5, 24}, {0x3ffffea, 26}, {0x7ffff4, 23}, + {0x3ffffeb, 26}, {0x7ffffe6, 27}, {0x3ffffec, 26}, {0x3ffffed, 26}, {0x7ffffe7, 27}, {0x7ffffe8, 27}, {0x7ffffe9, 27}, {0x7ffffea, 27}, + {0x7ffffeb, 27}, {0xffffffe, 28}, {0x7ffffec, 27}, {0x7ffffed, 27}, {0x7ffffee, 27}, {0x7ffffef, 27}, {0x7fffff0, 27}, {0x3ffffee, 26}, + {0x3fffffff, 30}, + } +}; + +// RFC 7541, Appendix A: the static table, from index 1. +constexpr std::array, 61> staticTable{ + { + {":authority", ""}, + {":method", "GET"}, + {":method", "POST"}, + {":path", "/"}, + {":path", "/index.html"}, + {":scheme", "http"}, + {":scheme", "https"}, + {":status", "200"}, + {":status", "204"}, + {":status", "206"}, + {":status", "304"}, + {":status", "400"}, + {":status", "404"}, + {":status", "500"}, + {"accept-charset", ""}, + {"accept-encoding", "gzip, deflate"}, + {"accept-language", ""}, + {"accept-ranges", ""}, + {"accept", ""}, + {"access-control-allow-origin", ""}, + {"age", ""}, + {"allow", ""}, + {"authorization", ""}, + {"cache-control", ""}, + {"content-disposition", ""}, + {"content-encoding", ""}, + {"content-language", ""}, + {"content-length", ""}, + {"content-location", ""}, + {"content-range", ""}, + {"content-type", ""}, + {"cookie", ""}, + {"date", ""}, + {"etag", ""}, + {"expect", ""}, + {"expires", ""}, + {"from", ""}, + {"host", ""}, + {"if-match", ""}, + {"if-modified-since", ""}, + {"if-none-match", ""}, + {"if-range", ""}, + {"if-unmodified-since", ""}, + {"last-modified", ""}, + {"link", ""}, + {"location", ""}, + {"max-forwards", ""}, + {"proxy-authenticate", ""}, + {"proxy-authorization", ""}, + {"range", ""}, + {"referer", ""}, + {"refresh", ""}, + {"retry-after", ""}, + {"server", ""}, + {"set-cookie", ""}, + {"strict-transport-security", ""}, + {"transfer-encoding", ""}, + {"user-agent", ""}, + {"vary", ""}, + {"via", ""}, + {"www-authenticate", ""}, + } +}; + +// The symbols ordered by code length then by code: each length's codes then form one range. +struct HuffmanSymbol { + std::uint32_t code; + int length; + int symbol; +}; + +const std::vector& huffmanByLength() { + static const std::vector symbols = [] { + std::vector sorted; + for (int symbol = 0; symbol < 257; ++symbol) { + const auto [code, length] = huffmanCodes[static_cast(symbol)]; + sorted.push_back({code, length, symbol}); + } + std::ranges::sort(sorted, [](const HuffmanSymbol& a, const HuffmanSymbol& b) { + return a.length != b.length ? a.length < b.length : a.code < b.code; + }); + return sorted; + }(); + return symbols; +} + +} // namespace cppmcache + +export namespace cppmcache { + +struct HeaderField { + std::string name; + std::string value; +}; + +// Decodes a Huffman-coded string (RFC 7541 §5.2). Nothing if it is malformed: a code that is not +// in the table, the EOS symbol, or padding longer than 7 bits or not made of ones. +std::optional huffmanDecode(std::string_view input) { + const auto& symbols = huffmanByLength(); + std::string output; + std::uint32_t code = 0; + int length = 0; + for (const char byte : input) { + for (int bit = 7; bit >= 0; --bit) { + code = (code << 1) | ((static_cast(byte) >> bit) & 1U); + ++length; + if (length > 30) { + return std::nullopt; + } + const auto first = std::ranges::lower_bound(symbols, std::pair{length, code}, {}, [](const HuffmanSymbol& s) { + return std::pair{s.length, s.code}; + }); + if (first != symbols.end() && first->length == length && first->code == code) { + if (first->symbol == 256) { + return std::nullopt; + } + output.push_back(static_cast(first->symbol)); + code = 0; + length = 0; + } + } + } + // The padding is the most significant bits of EOS: up to seven ones. + if (length > 7 || code != (std::uint32_t{1} << length) - 1) { + return std::nullopt; + } + return output; +} + +// Encodes `value` as an HPACK integer whose first byte keeps the bits of `flags` above a +// `prefix`-bit prefix (RFC 7541 §5.1). +void hpackInteger(std::string& output, std::uint64_t value, int prefix, std::uint8_t flags) { + const std::uint64_t limit = (std::uint64_t{1} << prefix) - 1; + if (value < limit) { + output.push_back(static_cast(flags | static_cast(value))); + return; + } + output.push_back(static_cast(flags | static_cast(limit))); + value -= limit; + while (value >= 0x80) { + output.push_back(static_cast((value & 0x7F) | 0x80)); + value >>= 7; + } + output.push_back(static_cast(value)); +} + +// Encodes a header block: each field a literal never added to the peer's table, names and values +// as plain strings. A field whose name is `authorization` is marked never-indexed, so that no +// intermediary stores it in a table either (RFC 7541 §7.1.3). +std::string hpackEncode(std::span fields) { + std::string output; + for (const auto& field : fields) { + hpackInteger(output, 0, 4, field.name == "authorization" ? 0x10 : 0x00); + hpackInteger(output, field.name.size(), 7, 0x00); + output += field.name; + hpackInteger(output, field.value.size(), 7, 0x00); + output += field.value; + } + return output; +} + +// Decoder of the header blocks of one connection: it keeps the dynamic table between blocks. +class HpackDecoder { +public: + // `maxTableSize`: SETTINGS_HEADER_TABLE_SIZE as this side advertised it (4096 by default). + explicit HpackDecoder(std::size_t maxTableSize = 4096) : limit_(maxTableSize), capacity_(maxTableSize) {} + + // The fields of a complete header block, or nothing on a compression error, which ends the + // connection (RFC 7540 §4.3). + std::optional> decode(std::string_view block) { + std::vector fields; + std::size_t position = 0; + bool fieldSeen = false; + while (position < block.size()) { + const auto first = static_cast(block[position]); + if ((first & 0x80) != 0) { + // Indexed header field. + const auto index = integer(block, position, 7); + const auto entry = index ? lookup(*index) : nullptr; + if (entry == nullptr) { + return std::nullopt; + } + fields.push_back(*entry); + fieldSeen = true; + } else if ((first & 0xE0) == 0x20) { + // Dynamic table size update, allowed only at the start of a block. + const auto size = integer(block, position, 5); + if (!size || *size > limit_ || fieldSeen) { + return std::nullopt; + } + capacity_ = static_cast(*size); + evict(0); + } else { + // Literal: with incremental indexing (01), without indexing (0000) or never indexed (0001). + const bool indexed = (first & 0xC0) == 0x40; + const auto index = integer(block, position, indexed ? 6 : 4); + if (!index) { + return std::nullopt; + } + HeaderField field; + if (*index != 0) { + const auto entry = lookup(*index); + if (entry == nullptr) { + return std::nullopt; + } + field.name = entry->name; + } else { + auto name = literal(block, position); + if (!name) { + return std::nullopt; + } + field.name = std::move(*name); + } + auto value = literal(block, position); + if (!value) { + return std::nullopt; + } + field.value = std::move(*value); + if (indexed) { + insert(field); + } + fields.push_back(std::move(field)); + fieldSeen = true; + } + } + return fields; + } + +private: + static std::size_t entrySize(const HeaderField& field) { + return field.name.size() + field.value.size() + 32; + } + + // An integer with an N-bit prefix, or nothing if it is truncated or does not fit. + static std::optional integer(std::string_view block, std::size_t& position, int prefix) { + if (position >= block.size()) { + return std::nullopt; + } + const std::uint64_t limit = (std::uint64_t{1} << prefix) - 1; + std::uint64_t value = static_cast(block[position++]) & limit; + if (value < limit) { + return value; + } + for (int shift = 0; shift <= 56; shift += 7) { + if (position >= block.size()) { + return std::nullopt; + } + const auto byte = static_cast(block[position++]); + value += static_cast(byte & 0x7F) << shift; + if ((byte & 0x80) == 0) { + return value; + } + } + return std::nullopt; + } + + static std::optional literal(std::string_view block, std::size_t& position) { + if (position >= block.size()) { + return std::nullopt; + } + const bool huffman = (static_cast(block[position]) & 0x80) != 0; + const auto length = integer(block, position, 7); + if (!length || *length > block.size() - position) { + return std::nullopt; + } + const auto bytes = block.substr(position, static_cast(*length)); + position += static_cast(*length); + if (huffman) { + return huffmanDecode(bytes); + } + return std::string{bytes}; + } + + // Index 1 to 61: the static table; above: the dynamic table, newest first. + const HeaderField* lookup(std::uint64_t index) { + if (index == 0) { + return nullptr; + } + if (index <= staticTable.size()) { + const auto& [name, value] = staticTable[static_cast(index - 1)]; + scratch_ = {std::string{name}, std::string{value}}; + return &scratch_; + } + const auto dynamic = index - staticTable.size() - 1; + return dynamic < table_.size() ? &table_[static_cast(dynamic)] : nullptr; + } + + void insert(const HeaderField& field) { + const auto size = entrySize(field); + if (size > capacity_) { + // An entry larger than the table empties it and is not added (RFC 7541 §4.4). + table_.clear(); + size_ = 0; + return; + } + evict(size); + table_.push_front(field); + size_ += size; + } + + // Evicts the oldest entries until `room` more bytes fit. + void evict(std::size_t room) { + while (!table_.empty() && size_ + room > capacity_) { + size_ -= entrySize(table_.back()); + table_.pop_back(); + } + } + + std::size_t limit_; // the largest size the peer may ask for + std::size_t capacity_; // the size the peer chose + std::size_t size_ = 0; + std::deque table_; + HeaderField scratch_; +}; + +} // namespace cppmcache diff --git a/src/cppmcache/Http.cppm b/src/cppmcache/Http.cppm index e26306d..631a72f 100644 --- a/src/cppmcache/Http.cppm +++ b/src/cppmcache/Http.cppm @@ -12,12 +12,19 @@ import std; export namespace cppmcache { -// An `http[s]://host[:port][/prefix]` URL. The prefix has no trailing slash. +// An `http[s]://host[:port][/prefix]` URL, or a `grpc[s]://host[:port][/instance]` one for the gRPC +// interface of the Remote Execution API. The prefix has no trailing slash. struct HttpUrl { std::string host; std::uint16_t port = 80; std::string prefix; - bool secure = false; // https: TLS + bool secure = false; // https, grpcs: TLS + bool grpc = false; // grpc, grpcs + + // The instance name of a gRPC server: the prefix without its leading slash. + std::string instance() const { + return prefix.empty() ? std::string{} : prefix.substr(1); + } std::uint16_t defaultPort() const { return secure ? 443 : 80; @@ -31,20 +38,28 @@ struct HttpUrl { // The URL as it may be shown: it never holds credentials, which the parser refuses. std::string text() const { - return std::format("{}://{}{}", secure ? "https" : "http", authority(), prefix); + return std::format("{}{}://{}{}", grpc ? "grpc" : "http", secure ? "s" : "", authority(), prefix); } }; -// Parses an `http://` or `https://` URL. Credentials (`user:password@`), a query and a fragment are -// refused. +// Parses an `http://`, `https://`, `grpc://` or `grpcs://` URL. Credentials (`user:password@`), a +// query and a fragment are refused. std::optional parseHttpUrl(std::string_view text) { HttpUrl url; - if (text.starts_with("https://")) { + if (text.starts_with("grpc")) { + url.grpc = true; + text.remove_prefix(4); + } else if (text.starts_with("http")) { + text.remove_prefix(4); + } else { + return std::nullopt; + } + if (text.starts_with("s://")) { url.secure = true; url.port = 443; - text.remove_prefix(8); - } else if (text.starts_with("http://")) { - text.remove_prefix(7); + text.remove_prefix(4); + } else if (text.starts_with("://")) { + text.remove_prefix(3); } else { return std::nullopt; } @@ -97,8 +112,10 @@ std::optional parseHttpUrl(std::string_view text) { // Why a value of CPPMCACHE_REMOTE was refused, without repeating the value: it may hold a password. std::string describeRejectedUrl(std::string_view text) { - if (!text.starts_with("http://") && !text.starts_with("https://")) { - return "CPPMCACHE_REMOTE is not an http:// or https:// URL"; + if (!std::ranges::any_of(std::array{"http://", "https://", "grpc://", "grpcs://"}, [&](std::string_view scheme) { + return text.starts_with(scheme); + })) { + return "CPPMCACHE_REMOTE is not an http://, https://, grpc:// or grpcs:// URL"; } const auto authorityEnd = text.find('/', text.find("//") + 2); if (text.substr(0, authorityEnd).contains('@')) { diff --git a/src/cppmcache/Remote.cppm b/src/cppmcache/Remote.cppm index eeead4c..c9160bf 100644 --- a/src/cppmcache/Remote.cppm +++ b/src/cppmcache/Remote.cppm @@ -2,7 +2,8 @@ // Copyright (C) 2026 Ambroise Leclerc /** * @file Remote.cppm - * @brief Client of a remote cache that speaks Bazel's HTTP caching protocol. + * @brief Client of a remote cache: Bazel's HTTP caching protocol, or the gRPC interface of the + * Remote Execution API. * * The server stores blobs under two paths: `/ac/` for action results and `/cas/` * for content. That is the layout bazel-remote, Bazel's `--remote_cache=http://…` and ccache's @@ -17,6 +18,11 @@ * 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. + * + * With a `grpc://` or `grpcs://` URL the same operations become calls of the Remote Execution API: + * ActionCache.GetActionResult and UpdateActionResult, ContentAddressableStorage.FindMissingBlobs, + * BatchReadBlobs and BatchUpdateBlobs for small blobs, ByteStream.Read and Write for large ones. + * Consecutive operations of one kind go in one call. Blobs travel uncompressed there. */ module; @@ -26,7 +32,9 @@ module; export module cppmcache.remote; import std; +import cppmcache.grpc; import cppmcache.http; +import cppmcache.proto; export namespace cppmcache { @@ -126,7 +134,11 @@ public: timeout_(timeoutMilliseconds), authorization_(std::move(authorization)), authorities_(std::move(authorities)), - compressUploads_(compressUploads && compression::available()) {} + compressUploads_(compressUploads && compression::available()) { + if (url_.grpc) { + grpc_ = std::make_unique(url_.host, url_.port, url_.secure, url_.authority(), timeout_, authorization_, authorities_); + } + } RemoteCache(const RemoteCache&) = delete; RemoteCache& operator=(const RemoteCache&) = delete; ~RemoteCache() { @@ -150,7 +162,7 @@ public: 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 + std::int64_t size = -1; // the size in the digest: of a content blob, of an action bool found = false; // get, has: the server holds it; put: it was stored std::string content{}; // get: what the server holds @@ -159,11 +171,12 @@ public: 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 checking(std::string_view kind, std::string_view hash, std::int64_t size = -1) { + return {Operation::Kind::has, std::string{kind}, std::string{hash}, {}, size}; } - 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())}; + // `size`: that of the digest; a content blob's is the size of its content. + static Operation putting(std::string_view kind, std::string_view hash, std::string_view content, std::int64_t size = -1) { + return {Operation::Kind::put, std::string{kind}, std::string{hash}, content, kind == "cas" ? static_cast(content.size()) : size}; } // Runs the operations in order. They are written one after the other on the connection without @@ -171,6 +184,10 @@ public: // 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) { + if (grpc_) { + runGrpc(operations); + return; + } std::vector messages; messages.reserve(operations.size()); for (const auto& operation : operations) { @@ -199,8 +216,8 @@ public: return operation[0].found; } - bool put(std::string_view kind, std::string_view hash, std::string_view content) { - std::array operation{putting(kind, hash, content)}; + bool put(std::string_view kind, std::string_view hash, std::string_view content, std::int64_t size = -1) { + std::array operation{putting(kind, hash, content, size)}; run(operation); return operation[0].found; } @@ -236,6 +253,7 @@ private: connection_ = transport::open(url_.host.c_str(), url_.port, url_.secure, + "http/1.1", authorities_.empty() ? nullptr : authorities_.c_str(), std::min(timeout_, url_.secure ? 5000 : 2000), error.data(), @@ -407,6 +425,294 @@ private: } } + // Blobs above this size go through ByteStream, and a batch of blobs stays below it: servers + // refuse messages above 4 MiB by default. + static constexpr std::int64_t grpcBatchLimit = std::int64_t{3} << 20; + static constexpr std::size_t grpcChunk = std::size_t{1} << 20; + + static std::string digestMessage(const Operation& operation) { + ProtoWriter writer; + writer.bytes(1, operation.hash); + writer.varint(2, static_cast(std::max(operation.size, 0))); + return writer.take(); + } + + // The hash of an encoded Digest. + static std::string digestHash(std::string_view encoded) { + ProtoReader reader{encoded}; + while (const auto field = reader.next()) { + if (field->number == 1 && field->wire == 2) { + return std::string{field->data}; + } + } + return {}; + } + + // The fields `number` of a message. + static std::vector fields(std::string_view message, int number) { + std::vector found; + ProtoReader reader{message}; + while (const auto field = reader.next()) { + if (field->number == number && field->wire == 2) { + found.push_back(field->data); + } + } + return found; + } + + // The code of an encoded google.rpc.Status: 0 for OK. + static std::uint64_t statusCode(std::string_view encoded) { + ProtoReader reader{encoded}; + while (const auto field = reader.next()) { + if (field->number == 1 && field->wire == 0) { + return field->value; + } + } + return 0; + } + + // One call. Nothing if it failed, the failure recorded; NOT_FOUND is an answer. + std::optional invoke(std::string_view method, std::span requests) { + if (unreachable_) { + return std::nullopt; + } + auto reply = grpc_->call(method, requests); + if (reply.status == -1) { + fail(std::format("{}: {}", method, reply.message)); + unreachable_ = true; + return std::nullopt; + } + // UNAUTHENTICATED or PERMISSION_DENIED would be answered again: the server is left alone. + if (reply.status == 16 || reply.status == 7) { + fail(std::format("{}: gRPC status {}, the credentials were refused", method, reply.status)); + unreachable_ = true; + return std::nullopt; + } + if (reply.status != GrpcStatus::ok && reply.status != GrpcStatus::notFound) { + fail(std::format("{}: gRPC status {} {}", method, reply.status, reply.message)); + return std::nullopt; + } + return reply; + } + + std::optional invoke(std::string_view method, std::string request) { + const std::array requests{std::move(request)}; + return invoke(method, requests); + } + + void runGrpc(std::span operations) { + std::size_t begin = 0; + while (begin < operations.size() && !unreachable_) { + std::size_t end = begin + 1; + while (end < operations.size() && operations[end].what == operations[begin].what && operations[end].kind == operations[begin].kind) { + ++end; + } + const auto group = operations.subspan(begin, end - begin); + if (group.front().kind == "ac") { + for (auto& operation : group) { + actionCache(operation); + } + } else if (group.front().what == Operation::Kind::has) { + findMissing(group); + } else if (group.front().what == Operation::Kind::get) { + readBlobs(group); + } else { + writeBlobs(group); + } + begin = end; + } + } + + void actionCache(Operation& operation) { + ProtoWriter request; + request.bytes(1, url_.instance()); + request.message(2, digestMessage(operation)); + if (operation.what == Operation::Kind::get) { + const auto reply = invoke("/build.bazel.remote.execution.v2.ActionCache/GetActionResult", request.take()); + if (reply && reply->status == GrpcStatus::ok && reply->responses.size() == 1) { + operation.found = true; + operation.content = reply->responses.front(); + } + } else if (operation.what == Operation::Kind::put) { + request.message(3, operation.body); + const auto reply = invoke("/build.bazel.remote.execution.v2.ActionCache/UpdateActionResult", request.take()); + operation.found = reply && reply->status == GrpcStatus::ok; + } + } + + void findMissing(std::span group) { + ProtoWriter request; + request.bytes(1, url_.instance()); + for (const auto& operation : group) { + request.message(2, digestMessage(operation)); + } + const auto reply = invoke("/build.bazel.remote.execution.v2.ContentAddressableStorage/FindMissingBlobs", request.take()); + if (!reply || reply->status != GrpcStatus::ok || reply->responses.size() != 1) { + return; + } + std::set missing; + // FindMissingBlobsResponse.missing_blob_digests + for (const auto digest : fields(reply->responses.front(), 2)) { + missing.insert(digestHash(digest)); + } + for (auto& operation : group) { + operation.found = !missing.contains(operation.hash); + } + } + + // `instance/blobs/hash/size`, the resource ByteStream reads. + std::string resource(const Operation& operation) const { + const auto instance = url_.instance(); + return std::format("{}blobs/{}/{}", instance.empty() ? "" : instance + "/", operation.hash, std::max(operation.size, 0)); + } + + void readBlobs(std::span group) { + std::vector batch; + std::int64_t batchSize = 0; + const auto flush = [&] { + if (batch.empty()) { + return; + } + ProtoWriter request; + request.bytes(1, url_.instance()); + for (const auto* operation : batch) { + request.message(2, digestMessage(*operation)); + } + const auto reply = invoke("/build.bazel.remote.execution.v2.ContentAddressableStorage/BatchReadBlobs", request.take()); + if (reply && reply->status == GrpcStatus::ok && reply->responses.size() == 1) { + for (const auto response : fields(reply->responses.front(), 1)) { + std::string hash; + std::string data; + bool ok = true; + ProtoReader reader{response}; + while (const auto field = reader.next()) { + if (field->number == 1 && field->wire == 2) { + hash = digestHash(field->data); + } else if (field->number == 2 && field->wire == 2) { + data = field->data; + } else if (field->number == 3 && field->wire == 2) { + ok = statusCode(field->data) == 0; + } + } + for (auto* operation : batch) { + if (ok && operation->hash == hash && !operation->found) { + operation->found = true; + operation->content = data; + } + } + } + } + batch.clear(); + batchSize = 0; + }; + for (auto& operation : group) { + if (operation.size > grpcBatchLimit) { + ProtoWriter request; + request.bytes(1, resource(operation)); + const auto reply = invoke("/google.bytestream.ByteStream/Read", request.take()); + if (reply && reply->status == GrpcStatus::ok) { + operation.found = true; + for (const auto& response : reply->responses) { + for (const auto data : fields(response, 10)) { + operation.content += data; + } + } + } + continue; + } + if (batchSize + operation.size > grpcBatchLimit) { + flush(); + } + batch.push_back(&operation); + batchSize += std::max(operation.size, 0); + } + flush(); + } + + void writeBlobs(std::span group) { + std::vector batch; + std::int64_t batchSize = 0; + const auto flush = [&] { + if (batch.empty()) { + return; + } + ProtoWriter request; + request.bytes(1, url_.instance()); + for (const auto* operation : batch) { + ProtoWriter blob; + blob.message(1, digestMessage(*operation)); + blob.bytes(2, operation->body); + request.message(2, blob.take()); + } + const auto reply = invoke("/build.bazel.remote.execution.v2.ContentAddressableStorage/BatchUpdateBlobs", request.take()); + if (reply && reply->status == GrpcStatus::ok && reply->responses.size() == 1) { + for (const auto response : fields(reply->responses.front(), 1)) { + std::string hash; + bool ok = true; + ProtoReader reader{response}; + while (const auto field = reader.next()) { + if (field->number == 1 && field->wire == 2) { + hash = digestHash(field->data); + } else if (field->number == 2 && field->wire == 2) { + ok = statusCode(field->data) == 0; + } + } + for (auto* operation : batch) { + if (operation->hash == hash) { + operation->found = ok; + } + } + } + } + batch.clear(); + batchSize = 0; + }; + for (auto& operation : group) { + if (operation.size > grpcBatchLimit) { + writeStream(operation); + continue; + } + if (batchSize + operation.size > grpcBatchLimit) { + flush(); + } + batch.push_back(&operation); + batchSize += operation.size; + } + flush(); + } + + // ByteStream.Write of one blob, in chunks of 1 MiB. + void writeStream(Operation& operation) { + std::random_device random; + const auto instance = url_.instance(); + const auto name = std::format("{}uploads/{:08x}-{:04x}-4{:03x}-a{:03x}-{:08x}{:04x}/blobs/{}/{}", + instance.empty() ? "" : instance + "/", + random(), + random() & 0xFFFF, + random() & 0xFFF, + random() & 0xFFF, + random(), + random() & 0xFFFF, + operation.hash, + operation.size); + std::vector requests; + std::size_t offset = 0; + do { + const auto piece = operation.body.substr(offset, grpcChunk); + ProtoWriter request; + if (offset == 0) { + request.bytes(1, name); + } + request.varint(2, offset); + offset += piece.size(); + request.varint(3, offset >= operation.body.size() ? 1 : 0); + request.bytes(10, piece); + requests.push_back(request.take()); + } while (offset < operation.body.size()); + const auto reply = invoke("/google.bytestream.ByteStream/Write", requests); + operation.found = reply && reply->status == GrpcStatus::ok; + } + // 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'); @@ -443,15 +749,16 @@ private: 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_; + HttpUrl url_; + int timeout_; + std::string authorization_; + std::string authorities_; + bool compressUploads_; + std::unique_ptr grpc_; + transport::Connection* connection_ = nullptr; + bool unreachable_ = false; + bool pipelined_ = true; + std::vector errors_; }; } // namespace cppmcache diff --git a/src/cppmcache/RemoteTransport.cpp b/src/cppmcache/RemoteTransport.cpp index 7852e7d..0b9eab8 100644 --- a/src/cppmcache/RemoteTransport.cpp +++ b/src/cppmcache/RemoteTransport.cpp @@ -173,6 +173,7 @@ bool secureAvailable() noexcept { Connection* open(const char* host, unsigned short port, bool secure, + const char* alpn, const char* authorities, int timeoutMilliseconds, char* error, @@ -183,7 +184,7 @@ Connection* open(const char* host, #if defined(CPPMCACHE_TLS) // No pin and no trust-verification sender: the engine authenticates the server with the // Web PKI, name and dates included. - security = net::security_parameters{}.alpn({"http/1.1"}); + security = net::security_parameters{}.alpn({alpn}); if (authorities != nullptr) { std::error_code loading; auto roots = net::tls::certificate::all_from_pem_file(authorities, loading); @@ -194,6 +195,7 @@ Connection* open(const char* host, security.trust_anchors(std::move(roots)); } #else + (void)alpn; (void)authorities; describe(error, errorCapacity, "this cppmcache was built without TLS"); return nullptr; diff --git a/src/cppmcache/RemoteTransport.hpp b/src/cppmcache/RemoteTransport.hpp index 60c1dab..f9cbb34 100644 --- a/src/cppmcache/RemoteTransport.hpp +++ b/src/cppmcache/RemoteTransport.hpp @@ -21,12 +21,14 @@ bool available() noexcept; // Whether this build can open TLS connections. bool secureAvailable() noexcept; -// Connects to host:port. With `secure`, the connection is TLS and the server is authenticated by -// the Web PKI: against the system's roots, or only against the certificates of the PEM file -// `authorities` when it is not null. Returns nothing on failure, with a message in `error`. +// Connects to host:port. With `secure`, the connection is TLS, offers the application protocol +// `alpn` ("http/1.1", "h2"), and the server is authenticated by the Web PKI: against the system's +// roots, or only against the certificates of the PEM file `authorities` when it is not null. +// Returns nothing on failure, with a message in `error`. Connection* open(const char* host, unsigned short port, bool secure, + const char* alpn, const char* authorities, int timeoutMilliseconds, char* error, diff --git a/src/cppmcache/RemoteTransportDisabled.cpp b/src/cppmcache/RemoteTransportDisabled.cpp index ebb811a..0620821 100644 --- a/src/cppmcache/RemoteTransportDisabled.cpp +++ b/src/cppmcache/RemoteTransportDisabled.cpp @@ -35,7 +35,7 @@ bool secureAvailable() noexcept { return false; } -Connection* open(const char*, unsigned short, bool, const char*, int, char* error, unsigned long long errorCapacity) noexcept { +Connection* open(const char*, unsigned short, bool, const char*, const char*, int, char* error, unsigned long long errorCapacity) noexcept { describe(error, errorCapacity); return nullptr; } diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index b7b30c0..f489276 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -22,6 +22,8 @@ add_executable(cppmcache_spec spec/DriverSpec.cpp spec/MsvcSpec.cpp spec/HttpSpec.cpp + spec/HpackSpec.cpp + spec/GrpcSpec.cpp spec/RelocationSpec.cpp spec/ShadowSpec.cpp spec/StoreSpec.cpp) diff --git a/tests/integration/Remote.cmake b/tests/integration/Remote.cmake index ca70866..e1ba662 100644 --- a/tests/integration/Remote.cmake +++ b/tests/integration/Remote.cmake @@ -171,10 +171,10 @@ if(TOKEN OR USER) else() use_machine(H NO_CREDENTIALS "CPPMCACHE_REMOTE_USER=${USER}" "CPPMCACHE_REMOTE_PASSWORD=${wrong_secret}") endif() - expect_remote_failure(api.cppm out/api.${OBJ} "HTTP status 401") + expect_remote_failure(api.cppm out/api.${OBJ} "credentials were refused") use_machine(H NO_CREDENTIALS) write_implementation(14) - expect_remote_failure(api_impl.cpp out/api_impl.${OBJ} "HTTP status 401") + expect_remote_failure(api_impl.cpp out/api_impl.${OBJ} "credentials were refused") set(secret_file "${WORK_DIR}/secret") if(TOKEN) @@ -196,6 +196,25 @@ if(TOKEN OR USER) endforeach() endif() +message(STATUS "6d. an output of 5 MB travels whole (ByteStream over gRPC)") +# The array is in read-only data, zeros included: the object file holds all of it. +file(WRITE "${WORK_DIR}/big.cpp" "extern const char big[5000000];\nconst char big[5000000] = \"cppmcache ${run_id}\";\n") +use_machine(J) +compile(big.cpp out/big.${OBJ} miss) +file(SIZE "${WORK_DIR}/out/big.${OBJ}" big_size) +if(big_size LESS 4000000) + message(FATAL_ERROR "big.${OBJ} has ${big_size} bytes: too small to test a large blob") +endif() +file(SHA256 "${WORK_DIR}/out/big.${OBJ}" big_reference) +file(REMOVE "${WORK_DIR}/out/big.${OBJ}") +use_machine(K) +compile(big.cpp out/big.${OBJ} hit) +expect_counter(remote_hit 1) +file(SHA256 "${WORK_DIR}/out/big.${OBJ}" big_restored) +if(NOT big_restored STREQUAL big_reference) + message(FATAL_ERROR "the large output fetched from the remote cache differs from the original") +endif() + message(STATUS "7. an unreachable server never fails a compilation") write_implementation(7) set(REMOTE "http://127.0.0.1:9") diff --git a/tests/spec/GrpcSpec.cpp b/tests/spec/GrpcSpec.cpp new file mode 100644 index 0000000..ece5394 --- /dev/null +++ b/tests/spec/GrpcSpec.cpp @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Ambroise Leclerc +/** + * @file GrpcSpec.cpp + * @brief Scenarios for the gRPC client: message framing and the URLs of a gRPC server. + */ +import std; +import speclab; +import cppmcache.grpc; +import cppmcache.http; + +namespace { + +using namespace cppmcache; +using speclab::core::Assertions; +using speclab::core::Checks; + +const speclab::Register framing{"gRPC: message framing", "unit,grpc", [] { + return speclab::Test("GRPC-001") + .Then("each message is prefixed with an uncompressed flag and its length; malformed bodies are refused", + [] { + const std::vector messages{"ab", "", std::string(300, 'x')}; + const auto body = grpcFrame(messages); + const auto back = grpcUnframe(body); + Checks checks; + checks.expect(body.substr(0, 7) == std::string{"\0\0\0\0\2ab", 7}, + "flag 0, length 2 in big-endian order, the message"); + checks.expect(body.size() == 3 * 5 + 302, "a prefix of five bytes per message"); + checks.expect(back && *back == messages, "round trip, an empty message included"); + checks.expect(grpcUnframe("").has_value() && grpcUnframe("")->empty(), "no message"); + checks.expect(!grpcUnframe(std::string{"\0\0\0\0\5ab", 7}), "a message shorter than its length"); + checks.expect(!grpcUnframe(std::string{"\1\0\0\0\0", 5}), "a compressed message, which was not asked for"); + checks.expect(!grpcUnframe(std::string{"\0\0", 2}), "a truncated prefix"); + checks.raise(); + }) + .Execute(); + }}; + +const speclab::Register urls{ + "gRPC: the URL of a gRPC server", + "unit,grpc", + [] { + return speclab::Test("GRPC-002") + .Then("grpc and grpcs are parsed like http and https; the path is the instance name", + [] { + const auto plain = parseHttpUrl("grpc://cache.example:9092"); + const auto secure = parseHttpUrl("grpcs://cache.example/team/main/"); + Assertions::require(plain && secure, "a valid gRPC URL was refused"); + Checks checks; + checks.expect(plain->grpc && !plain->secure && plain->port == 9092 && plain->instance().empty(), "plain, no instance"); + checks.expect(secure->grpc && secure->secure && secure->port == 443 && secure->instance() == "team/main", "TLS, an instance name"); + checks.expect(secure->text() == "grpcs://cache.example/team/main" && plain->text() == "grpc://cache.example:9092", "shown as given"); + checks.expect(!parseHttpUrl("grpc://user:pw@cache.example") && !parseHttpUrl("grpcx://cache.example"), "credentials, another scheme"); + checks.expect(!parseHttpUrl("https://cache.example")->grpc, "https is not gRPC"); + checks.raise(); + }) + .Execute(); + }}; + +} // namespace diff --git a/tests/spec/HpackSpec.cpp b/tests/spec/HpackSpec.cpp new file mode 100644 index 0000000..3d4b832 --- /dev/null +++ b/tests/spec/HpackSpec.cpp @@ -0,0 +1,157 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +// Copyright (C) 2026 Ambroise Leclerc +/** + * @file HpackSpec.cpp + * @brief Scenarios for HPACK: the examples of RFC 7541, Appendix C, and malformed blocks. + */ +import std; +import speclab; +import cppmcache.hpack; + +namespace { + +using namespace cppmcache; +using speclab::core::Checks; + +std::string fromHex(std::string_view hex) { + std::string bytes; + for (std::size_t i = 0; i + 1 < hex.size(); i += 2) { + unsigned value = 0; + std::from_chars(hex.data() + i, hex.data() + i + 2, value, 16); + bytes.push_back(static_cast(value)); + } + return bytes; +} + +struct Example { + std::string_view hex; + std::vector> fields; +}; + +// Decodes the blocks of one section in order, with one decoder: the later ones refer to entries +// that the earlier ones added to the dynamic table. +bool decodesInOrder(std::size_t tableSize, const std::vector& examples) { + HpackDecoder decoder{tableSize}; + for (const auto& example : examples) { + const auto fields = decoder.decode(fromHex(example.hex)); + if (!fields || fields->size() != example.fields.size()) { + return false; + } + for (std::size_t i = 0; i < fields->size(); ++i) { + if ((*fields)[i].name != example.fields[i].first || (*fields)[i].value != example.fields[i].second) { + return false; + } + } + } + return true; +} + +// RFC 7541, C.3: requests without Huffman coding. +const std::vector section3{ + { "828684410f7777772e6578616d706c652e636f6d",{{":method", "GET"}, {":scheme", "http"}, {":path", "/"}, {":authority", "www.example.com"}} }, + { "828684be58086e6f2d6361636865", + {{":method", "GET"}, {":scheme", "http"}, {":path", "/"}, {":authority", "www.example.com"}, {"cache-control", "no-cache"}} }, + {"828785bf400a637573746f6d2d6b65790c637573746f6d2d76616c7565", + {{":method", "GET"}, {":scheme", "https"}, {":path", "/index.html"}, {":authority", "www.example.com"}, {"custom-key", "custom-value"}}}, +}; + +// RFC 7541, C.4: requests with Huffman coding. +const std::vector section4{ + { "828684418cf1e3c2e5f23a6ba0ab90f4ff",{{":method", "GET"}, {":scheme", "http"}, {":path", "/"}, {":authority", "www.example.com"}} }, + { "828684be5886a8eb10649cbf", {{":method", "GET"}, {":scheme", "http"}, {":path", "/"}, {":authority", "www.example.com"}, {"cache-control", "no-cache"}}}, + {"828785bf408825a849e95ba97d7f8925a849e95bb8e8b4bf", + {{":method", "GET"}, {":scheme", "https"}, {":path", "/index.html"}, {":authority", "www.example.com"}, {"custom-key", "custom-value"}} }, +}; + +// RFC 7541, C.5: responses without Huffman coding, a 256-byte table that evicts. +const std::vector section5{ + {"4803333032580770726976617465611d4d6f6e2c203231204f637420323031332032303a31333a323120474d546e1768747470733a2f2f7777772e6578616d706c652e636f6d", + {{":status", "302"}, {"cache-control", "private"}, {"date", "Mon, 21 Oct 2013 20:13:21 GMT"}, {"location", "https://www.example.com"}} }, + { "4803333037c1c0bf", + {{":status", "307"}, {"cache-control", "private"}, {"date", "Mon, 21 Oct 2013 20:13:21 GMT"}, {"location", "https://www.example.com"}} }, + { "88c1611d4d6f6e2c203231204f637420323031332032303a31333a323220474d54c05a04677a69707738666f6f3d4153444a4b48514b425a584f5157454f50495541585157454f49553b206d6" + "1782d6167653d333630303b2076657273696f6e3d31", {{":status", "200"}, + {"cache-control", "private"}, + {"date", "Mon, 21 Oct 2013 20:13:22 GMT"}, + {"location", "https://www.example.com"}, + {"content-encoding", "gzip"}, + {"set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"}}}, +}; + +// RFC 7541, C.6: responses with Huffman coding, a 256-byte table that evicts. +const std::vector section6{ + {"488264025885aec3771a4b6196d07abe941054d444a8200595040b8166e082a62d1bff6e919d29ad171863c78f0b97c8e9ae82ae43d3", + {{":status", "302"}, {"cache-control", "private"}, {"date", "Mon, 21 Oct 2013 20:13:21 GMT"}, {"location", "https://www.example.com"}} }, + { "4883640effc1c0bf", + {{":status", "307"}, {"cache-control", "private"}, {"date", "Mon, 21 Oct 2013 20:13:21 GMT"}, {"location", "https://www.example.com"}} }, + { "88c16196d07abe941054d444a8200595040b8166e084a62d1bffc05a839bd9ab77ad94e7821dd7f2e6c7b335dfdfcd5b3960d5af27087f3672c1ab270fb5291f9587316065c003ed4ee5b1063" + "d5007", {{":status", "200"}, + {"cache-control", "private"}, + {"date", "Mon, 21 Oct 2013 20:13:22 GMT"}, + {"location", "https://www.example.com"}, + {"content-encoding", "gzip"}, + {"set-cookie", "foo=ASDJKHQKBZXOQWEOPIUAXQWEOIU; max-age=3600; version=1"}}}, +}; + +const speclab::Register rfcExamples{"HPACK: the examples of RFC 7541", "unit,grpc", [] { + return speclab::Test("HPACK-001") + .Then( + "the header blocks of Appendix C decode to their header lists, the dynamic table carried from one to the next", + [] { + Checks checks; + checks.expect(decodesInOrder(4096, section3), "C.3, requests without Huffman coding"); + checks.expect(decodesInOrder(4096, section4), "C.4, requests with Huffman coding"); + checks.expect(decodesInOrder(256, section5), "C.5, responses, entries evicted"); + checks.expect(decodesInOrder(256, section6), "C.6, responses with Huffman coding, entries evicted"); + checks.raise(); + }) + .Execute(); + }}; + +const speclab::Register encoding{"HPACK: encoding", "unit,grpc", [] { + return speclab::Test("HPACK-002") + .Then("what the encoder writes, a decoder reads back; integers use their prefix and continuation bytes", + [] { + const std::vector fields{ + {":path", "/build.bazel.remote.execution.v2.ActionCache/GetActionResult"}, + {"authorization", "Bearer secret"}, + {"x-long", std::string(300, 'v')} + }; + HpackDecoder decoder; + const auto decoded = decoder.decode(hpackEncode(fields)); + std::string ten; + hpackInteger(ten, 10, 5, 0); + std::string large; + hpackInteger(large, 1337, 5, 0); + Checks checks; + checks.expect(decoded && decoded->size() == 3 && (*decoded)[0].value == fields[0].value + && (*decoded)[2].value == fields[2].value, + "round trip, a value longer than the 7-bit prefix"); + checks.expect(hpackEncode(std::span{fields}.subspan(1, 1)).front() == '\x10', + "authorization is never indexed"); + checks.expect(ten == "\x0a", "RFC 7541 C.1.1: 10 on a 5-bit prefix"); + checks.expect(large == "\x1f\x9a\x0a", "RFC 7541 C.1.2: 1337 on a 5-bit prefix"); + checks.raise(); + }) + .Execute(); + }}; + +const speclab::Register malformed{"HPACK: malformed blocks", "unit,grpc", [] { + return speclab::Test("HPACK-003") + .Then("an index out of the tables, a truncated literal, bad Huffman padding or a late size update are errors", + [] { + Checks checks; + checks.expect(!HpackDecoder{}.decode(fromHex("be")), "index 62 with an empty dynamic table"); + checks.expect(!HpackDecoder{}.decode(fromHex("80")), "index 0"); + checks.expect(!HpackDecoder{}.decode(fromHex("400a637573746f6d")), "a name shorter than its length"); + checks.expect(!huffmanDecode(fromHex("00")), "padding of zeros"); + checks.expect(!huffmanDecode(fromHex("ffffffff")), "the EOS symbol, or padding longer than 7 bits"); + checks.expect(huffmanDecode(fromHex("f1e3c2e5f23a6ba0ab90f4ff")) == "www.example.com", "RFC 7541 C.4.1"); + checks.expect(!HpackDecoder{}.decode(fromHex("8220")), "a table size update after a field"); + checks.expect(!HpackDecoder{256}.decode(fromHex("3fe201")), "a table size update above the limit"); + checks.raise(); + }) + .Execute(); + }}; + +} // namespace diff --git a/tests/spec/HttpSpec.cpp b/tests/spec/HttpSpec.cpp index 3edc15c..b145456 100644 --- a/tests/spec/HttpSpec.cpp +++ b/tests/spec/HttpSpec.cpp @@ -77,23 +77,23 @@ const speclab::Register secureUrls{"HTTP: parsing an https URL", "unit,http", [] .Execute(); }}; -const speclab::Register rejectedUrls{"HTTP: describing a refused URL", "unit,http", [] { - return speclab::Test("HTTP-008") - .Then("the message says why without repeating the URL, which may hold a password", - [] { - const auto withCredentials = describeRejectedUrl("https://user:s3cret@cache.example/x"); - Checks checks; - checks.expect(!withCredentials.contains("s3cret") && !withCredentials.contains("user:"), - "the password is not repeated"); - checks.expect(withCredentials.contains("CPPMCACHE_REMOTE_TOKEN"), "the remedy is named"); - checks.expect(describeRejectedUrl("cache.example").contains("not an http:// or https:// URL"), - "missing scheme"); - checks.expect(!describeRejectedUrl("http://host/a@b?q").contains("credentials"), - "an @ in the path is not taken for credentials"); - checks.raise(); - }) - .Execute(); - }}; +const speclab::Register rejectedUrls{ + "HTTP: describing a refused URL", + "unit,http", + [] { + return speclab::Test("HTTP-008") + .Then("the message says why without repeating the URL, which may hold a password", + [] { + const auto withCredentials = describeRejectedUrl("https://user:s3cret@cache.example/x"); + Checks checks; + checks.expect(!withCredentials.contains("s3cret") && !withCredentials.contains("user:"), "the password is not repeated"); + checks.expect(withCredentials.contains("CPPMCACHE_REMOTE_TOKEN"), "the remedy is named"); + checks.expect(describeRejectedUrl("cache.example").contains("not an http://, https://, grpc:// or grpcs:// URL"), "missing scheme"); + checks.expect(!describeRejectedUrl("http://host/a@b?q").contains("credentials"), "an @ in the path is not taken for credentials"); + checks.raise(); + }) + .Execute(); + }}; const speclab::Register base64Encoding{ "HTTP: Base64 for Basic authentication", From 4d21bcb61c642077a528218051677818339eb309 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Tue, 1 Dec 2026 02:05:05 +0100 Subject: [PATCH 2/4] gRPC: retry on a fresh connection, widen the receive windows (#19) - A call on a connection kept from an earlier one is made again once on a new connection when it fails: the server may have closed an idle connection. - The receive windows start at their largest and are widened again once half of either is used, so that a long connection or a large download does not stall. --- src/cppmcache/Grpc.cppm | 63 ++++++++++++++++++++++++++++++++--------- 1 file changed, 49 insertions(+), 14 deletions(-) diff --git a/src/cppmcache/Grpc.cppm b/src/cppmcache/Grpc.cppm index 7c74dc9..5e797f2 100644 --- a/src/cppmcache/Grpc.cppm +++ b/src/cppmcache/Grpc.cppm @@ -136,18 +136,28 @@ public: GrpcReply call(std::string_view path, std::span requests) { GrpcReply reply; std::string error; - if (connection_ == nullptr && !connect(error)) { - reply.message = std::move(error); - return reply; - } - Stream stream; - stream.id = nextStream_; - stream.window = peerInitialWindow_; - nextStream_ += 2; - if (!sendHeaders(stream.id, path, error) || !sendBody(stream, grpcFrame(requests), error) || !receive(stream, error)) { + Stream stream; + // A connection kept from an earlier call may have been closed by the server since: the + // call is made again once on a fresh one. Every call of the cache client may be repeated. + for (int attempt = 0;; ++attempt) { + const bool reused = connection_ != nullptr; + if (!reused && !connect(error)) { + reply.message = std::move(error); + return reply; + } + stream = {}; + stream.id = nextStream_; + stream.window = peerInitialWindow_; + nextStream_ += 2; + if (sendHeaders(stream.id, path, error) && sendBody(stream, grpcFrame(requests), error) && receive(stream, error)) { + break; + } disconnect(); - reply.message = std::move(error); - return reply; + if (!reused || attempt > 0) { + reply.message = std::move(error); + return reply; + } + error.clear(); } if (stream.httpStatus != 200) { reply.message = std::format("HTTP status {}", stream.httpStatus); @@ -171,6 +181,7 @@ public: private: struct Stream { std::uint32_t id = 0; + std::uint64_t received = 0; // DATA received since the stream's window was last widened std::int64_t window = 0; // what the server still accepts on this stream bool ended = false; int httpStatus = 0; @@ -199,6 +210,7 @@ private: peerInitialWindow_ = defaultWindow; peerFrameSize_ = ourFrameSize; nextStream_ = 1; + received_ = 0; // The preface, our settings (no push, the largest stream window), and the largest // connection window. std::string opening = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"; @@ -412,10 +424,13 @@ private: error = "malformed DATA frame"; return false; } - stream.body += *payload; - stream.ended = (incoming.flags & endStream) != 0; + stream.body += *payload; + stream.ended = (incoming.flags & endStream) != 0; + stream.received += incoming.payload.size(); } - return true; + // The whole frame counts against the windows, padding included. + received_ += incoming.payload.size(); + return replenish(stream, error); case FrameType::headers: case FrameType::continuation: return headers(incoming, stream, error); @@ -426,6 +441,25 @@ private: return true; } + // Widens the receive windows, which start at their largest, once half of either is used: a + // long connection, or a large download, would otherwise exhaust them and stall. + bool replenish(Stream& stream, std::string& error) { + std::string output; + if (received_ >= largestWindow / 2) { + std::string increment; + appendBigEndian(increment, received_, 4); + frame(output, FrameType::windowUpdate, 0, 0, increment); + received_ = 0; + } + if (stream.received >= largestWindow / 2 && !stream.ended) { + std::string increment; + appendBigEndian(increment, stream.received, 4); + frame(output, FrameType::windowUpdate, 0, stream.id, increment); + stream.received = 0; + } + return output.empty() || send(output, error); + } + bool settings(const Frame& incoming, Stream& stream, std::string& error) { if ((incoming.flags & ack) != 0) { return true; @@ -518,6 +552,7 @@ private: std::int64_t peerInitialWindow_ = defaultWindow; std::size_t peerFrameSize_ = ourFrameSize; std::uint32_t nextStream_ = 1; + std::uint64_t received_ = 0; // DATA received since the connection's window was last widened std::string pending_; std::uint8_t pendingFlags_ = 0; std::uint32_t pendingStream_ = 0; From f0f578bc8669bba5ce2238cf063dac2ff41aa29d Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Tue, 1 Dec 2026 02:19:06 +0100 Subject: [PATCH 3/4] gRPC: move the blobs of a refused batch to ByteStream (#19) A server whose limit on the size of a batch is below 3 MiB answers INVALID_ARGUMENT or RESOURCE_EXHAUSTED: the blobs of that batch then go one by one through ByteStream, which has no such limit, instead of failing. --- src/cppmcache/Remote.cppm | 60 ++++++++++++++++++++++++++------------- 1 file changed, 41 insertions(+), 19 deletions(-) diff --git a/src/cppmcache/Remote.cppm b/src/cppmcache/Remote.cppm index c9160bf..6871e22 100644 --- a/src/cppmcache/Remote.cppm +++ b/src/cppmcache/Remote.cppm @@ -471,8 +471,10 @@ private: return 0; } - // One call. Nothing if it failed, the failure recorded; NOT_FOUND is an answer. - std::optional invoke(std::string_view method, std::span requests) { + // One call. Nothing if it failed, the failure recorded; NOT_FOUND is an answer. For a batch, + // INVALID_ARGUMENT and RESOURCE_EXHAUSTED are answers too: the server's limit on the size of a + // batch may be below the client's, and the caller then moves the blobs to ByteStream. + std::optional invoke(std::string_view method, std::span requests, bool batch = false) { if (unreachable_) { return std::nullopt; } @@ -488,6 +490,9 @@ private: unreachable_ = true; return std::nullopt; } + if (batch && refusedBatch(reply)) { + return reply; + } if (reply.status != GrpcStatus::ok && reply.status != GrpcStatus::notFound) { fail(std::format("{}: gRPC status {} {}", method, reply.status, reply.message)); return std::nullopt; @@ -495,9 +500,13 @@ private: return reply; } - std::optional invoke(std::string_view method, std::string request) { + std::optional invoke(std::string_view method, std::string request, bool batch = false) { const std::array requests{std::move(request)}; - return invoke(method, requests); + return invoke(method, requests, batch); + } + + static bool refusedBatch(const GrpcReply& reply) { + return reply.status == 3 || reply.status == 8; } void runGrpc(std::span operations) { @@ -578,8 +587,12 @@ private: for (const auto* operation : batch) { request.message(2, digestMessage(*operation)); } - const auto reply = invoke("/build.bazel.remote.execution.v2.ContentAddressableStorage/BatchReadBlobs", request.take()); - if (reply && reply->status == GrpcStatus::ok && reply->responses.size() == 1) { + const auto reply = invoke("/build.bazel.remote.execution.v2.ContentAddressableStorage/BatchReadBlobs", request.take(), true); + if (reply && refusedBatch(*reply)) { + for (auto* operation : batch) { + readStream(*operation); + } + } else if (reply && reply->status == GrpcStatus::ok && reply->responses.size() == 1) { for (const auto response : fields(reply->responses.front(), 1)) { std::string hash; std::string data; @@ -607,17 +620,7 @@ private: }; for (auto& operation : group) { if (operation.size > grpcBatchLimit) { - ProtoWriter request; - request.bytes(1, resource(operation)); - const auto reply = invoke("/google.bytestream.ByteStream/Read", request.take()); - if (reply && reply->status == GrpcStatus::ok) { - operation.found = true; - for (const auto& response : reply->responses) { - for (const auto data : fields(response, 10)) { - operation.content += data; - } - } - } + readStream(operation); continue; } if (batchSize + operation.size > grpcBatchLimit) { @@ -644,8 +647,12 @@ private: blob.bytes(2, operation->body); request.message(2, blob.take()); } - const auto reply = invoke("/build.bazel.remote.execution.v2.ContentAddressableStorage/BatchUpdateBlobs", request.take()); - if (reply && reply->status == GrpcStatus::ok && reply->responses.size() == 1) { + const auto reply = invoke("/build.bazel.remote.execution.v2.ContentAddressableStorage/BatchUpdateBlobs", request.take(), true); + if (reply && refusedBatch(*reply)) { + for (auto* operation : batch) { + writeStream(*operation); + } + } else if (reply && reply->status == GrpcStatus::ok && reply->responses.size() == 1) { for (const auto response : fields(reply->responses.front(), 1)) { std::string hash; bool ok = true; @@ -681,6 +688,21 @@ private: flush(); } + // ByteStream.Read of one blob. + void readStream(Operation& operation) { + ProtoWriter request; + request.bytes(1, resource(operation)); + const auto reply = invoke("/google.bytestream.ByteStream/Read", request.take()); + if (reply && reply->status == GrpcStatus::ok) { + operation.found = true; + for (const auto& response : reply->responses) { + for (const auto data : fields(response, 10)) { + operation.content += data; + } + } + } + } + // ByteStream.Write of one blob, in chunks of 1 MiB. void writeStream(Operation& operation) { std::random_device random; From 153b97af44ef7e42ff37de7624b432f4cb6f33b8 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Tue, 1 Dec 2026 02:28:43 +0100 Subject: [PATCH 4/4] gRPC: reuse the read buffer, refuse invalid WINDOW_UPDATE, has() with a size (#19) - The 64 KiB buffer of readFrame() is allocated once per channel. - A WINDOW_UPDATE of zero, or one that takes a window beyond 2^31 - 1, ends the connection as a protocol error (RFC 9113, section 6.9). - RemoteCache::has() takes the size of the digest, which gRPC needs. --- src/cppmcache/Grpc.cppm | 18 +++++++++++------- src/cppmcache/Remote.cppm | 5 +++-- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/src/cppmcache/Grpc.cppm b/src/cppmcache/Grpc.cppm index 5e797f2..12c7d30 100644 --- a/src/cppmcache/Grpc.cppm +++ b/src/cppmcache/Grpc.cppm @@ -325,15 +325,14 @@ private: bool readFrame(Frame& result, std::string& error) { std::array detail{}; - std::vector buffer(std::size_t{64} * 1024); const auto need = [&](std::size_t size) { while (inbox_.size() < size) { - const long long received = transport::receiveSome(connection_, buffer.data(), buffer.size(), timeout_, detail.data(), detail.size()); + const long long received = transport::receiveSome(connection_, buffer_.data(), buffer_.size(), timeout_, detail.data(), detail.size()); if (received <= 0) { error = received < 0 ? std::format("receive: {}", detail.data()) : "the server closed the connection"; return false; } - inbox_.append(buffer.data(), static_cast(received)); + inbox_.append(buffer_.data(), static_cast(received)); } return true; }; @@ -398,10 +397,14 @@ private: return false; } const auto increment = bigEndian32(incoming.payload) & 0x7FFF'FFFF; - if (incoming.stream == 0) { - sendWindow_ += increment; - } else if (incoming.stream == stream.id) { - stream.window += increment; + // An increment of zero, or a window beyond 2^31 - 1, is a protocol error (RFC 9113 §6.9). + std::int64_t* window = incoming.stream == 0 ? &sendWindow_ : incoming.stream == stream.id ? &stream.window : nullptr; + if (increment == 0 || (window != nullptr && *window + increment > largestWindow)) { + error = "invalid WINDOW_UPDATE"; + return false; + } + if (window != nullptr) { + *window += increment; } return true; } @@ -547,6 +550,7 @@ private: std::string authorities_; transport::Connection* connection_ = nullptr; std::string inbox_; + std::vector buffer_ = std::vector(std::size_t{64} * 1024); // reused by every read HpackDecoder decoder_; std::int64_t sendWindow_ = defaultWindow; std::int64_t peerInitialWindow_ = defaultWindow; diff --git a/src/cppmcache/Remote.cppm b/src/cppmcache/Remote.cppm index 6871e22..37fb801 100644 --- a/src/cppmcache/Remote.cppm +++ b/src/cppmcache/Remote.cppm @@ -210,8 +210,9 @@ public: return operation[0].found ? std::optional{std::move(operation[0].content)} : std::nullopt; } - bool has(std::string_view kind, std::string_view hash) { - std::array operation{checking(kind, hash)}; + // `size`: that of the content blob, which the gRPC interface needs. + bool has(std::string_view kind, std::string_view hash, std::int64_t size = -1) { + std::array operation{checking(kind, hash, size)}; run(operation); return operation[0].found; }