diff --git a/.cursor/skills/subspace-builds/SKILL.md b/.cursor/skills/subspace-builds/SKILL.md index bfecfe92..ffa60ece 100644 --- a/.cursor/skills/subspace-builds/SKILL.md +++ b/.cursor/skills/subspace-builds/SKILL.md @@ -52,19 +52,20 @@ bazel build --config=linux_arm32 //server:subspace_server //client:subspace_clie bazel test --config=linux_arm32 //common:common_test //client:client_test ``` -CMake needs a host `protoc` first. The toolchain file is -`cmake/toolchains/linux-armhf.cmake`. CI runs that cross-compile as the +CMake needs a host `protoc` and `protoc-gen-phaser` first. The toolchain file +is `cmake/toolchains/linux-armhf.cmake`. CI runs that cross-compile as the `cmake (armhf)` job; `scripts/build-arm32-colima.sh` is the local Colima equivalent. ```bash cmake -S . -B build/host-protoc -DCMAKE_BUILD_TYPE=Release -cmake --build build/host-protoc --target protoc --parallel +cmake --build build/host-protoc --target protoc protoc-gen-phaser --parallel cmake -S . -B build/armhf \ -DCMAKE_TOOLCHAIN_FILE=cmake/toolchains/linux-armhf.cmake \ -DCMAKE_BUILD_TYPE=Release \ - -DPROTOC_EXECUTABLE="$PWD/build/host-protoc/_deps/protobuf-build/protoc" + -DPROTOC_EXECUTABLE="$PWD/build/host-protoc/_deps/protobuf-build/protoc" \ + -DPHASER_PLUGIN_EXECUTABLE="$PWD/build/host-protoc/_deps/phaser-build/protoc-gen-phaser" cmake --build build/armhf --parallel ``` @@ -98,7 +99,7 @@ Android cross-compile so protobuf versions match: ```bash cmake -S . -B build/host-protoc -DCMAKE_BUILD_TYPE=Release -cmake --build build/host-protoc --target protoc --parallel +cmake --build build/host-protoc --target protoc protoc-gen-phaser --parallel cmake -S . -B build/android \ -DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK_HOME/build/cmake/android.toolchain.cmake \ @@ -106,7 +107,8 @@ cmake -S . -B build/android \ -DANDROID_PLATFORM=android-28 \ -DANDROID_STL=c++_shared \ -DCMAKE_BUILD_TYPE=Release \ - -DPROTOC_EXECUTABLE="$PWD/build/host-protoc/_deps/protobuf-build/protoc" + -DPROTOC_EXECUTABLE="$PWD/build/host-protoc/_deps/protobuf-build/protoc" \ + -DPHASER_PLUGIN_EXECUTABLE="$PWD/build/host-protoc/_deps/phaser-build/protoc-gen-phaser" cmake --build build/android --parallel ``` diff --git a/.cursor/skills/subspace-clients/SKILL.md b/.cursor/skills/subspace-clients/SKILL.md index ab8ddb55..0c554a3b 100644 --- a/.cursor/skills/subspace-clients/SKILL.md +++ b/.cursor/skills/subspace-clients/SKILL.md @@ -273,11 +273,15 @@ bazel build //rust_client:subspace_client_rust bazel test //rust_client:client_test cmake -S . -B build/cmake-Debug -DCMAKE_BUILD_TYPE=Debug -cmake --build build/cmake-Debug --target subspace_client_rust - -cd rust_client && cargo build && cargo test -- --test-threads=1 +cmake --build build/cmake-Debug --target subspace_client_rust subspace_server +ctest --test-dir build/cmake-Debug -R rust_client_test --output-on-failure ``` +Cargo needs the Phaser bindings from a CMake build. To run it directly, set +`SUBSPACE_PHASER_C_RS` to the generated +`build/cmake-Debug/rust_client/subspace_phaser_c_phaser/subspace_phaser_c.rs` and +`SUBSPACE_PHASER_C_LIB_DIR` to `build/cmake-Debug/rust_client`. + Java/JNI for Android: ```bash diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2f671f08..96de1085 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -482,13 +482,13 @@ jobs: g++-arm-linux-gnueabihf \ qemu-user - - name: Build a host protoc + - name: Build a host protoc and phaser plugin run: | cmake -S . -B build/host-protoc \ -DCMAKE_BUILD_TYPE=Release \ -DSUBSPACE_ASIO_RPC=OFF \ -DSUBSPACE_CO20_RPC=OFF - cmake --build build/host-protoc --target protoc --parallel "$(nproc)" + cmake --build build/host-protoc --target protoc protoc-gen-phaser --parallel "$(nproc)" - name: Configure the armhf build run: | @@ -496,6 +496,7 @@ jobs: -DCMAKE_TOOLCHAIN_FILE="$PWD/cmake/toolchains/linux-armhf.cmake" \ -DCMAKE_BUILD_TYPE=Release \ -DPROTOC_EXECUTABLE="$PWD/build/host-protoc/_deps/protobuf-build/protoc" \ + -DPHASER_PLUGIN_EXECUTABLE="$PWD/build/host-protoc/_deps/phaser-build/protoc-gen-phaser" \ -DSUBSPACE_ASIO_RPC=OFF - name: Build armhf targets @@ -530,10 +531,10 @@ jobs: - name: Set up Android NDK run: echo "ANDROID_NDK_HOME=$ANDROID_NDK_LATEST_HOME" >> $GITHUB_ENV - - name: Build host protoc for cross-compilation + - name: Build host protoc and phaser plugin for cross-compilation run: | cmake -S . -B build/host-protoc -DCMAKE_BUILD_TYPE=Release - cmake --build build/host-protoc --target protoc --parallel $(nproc) + cmake --build build/host-protoc --target protoc protoc-gen-phaser --parallel $(nproc) - name: Configure CMake for Android x86_64 run: | @@ -543,7 +544,8 @@ jobs: -DANDROID_PLATFORM=android-28 \ -DANDROID_STL=c++_shared \ -DCMAKE_BUILD_TYPE=Release \ - -DPROTOC_EXECUTABLE="$PWD/build/host-protoc/_deps/protobuf-build/protoc" + -DPROTOC_EXECUTABLE="$PWD/build/host-protoc/_deps/protobuf-build/protoc" \ + -DPHASER_PLUGIN_EXECUTABLE="$PWD/build/host-protoc/_deps/phaser-build/protoc-gen-phaser" - name: Build run: cmake --build build/android --parallel $(nproc) diff --git a/Android.bp b/Android.bp index aa66eee0..a34c91c6 100644 --- a/Android.bp +++ b/Android.bp @@ -59,3 +59,61 @@ cc_library_static { export_shared_lib_headers: ["libprotobuf-cpp-full"], rtti: false, } + +// Phaser messages generated from subspace.proto for the ASIL client's server +// connection. They are sent and received in protobuf wire format. As in the +// Bazel phaser_library rule, the plugin writes +// proto/subspace_phaser/.phaser.{cc,h}, generating any.proto too, +// and a short proto/subspace.phaser.h header includes the generated one. The +// .cc and .h outputs come from separate genrules so the headers never end up +// in `generated_sources`. +subspace_phaser_cmd = "$(location aprotoc) " + + "--plugin=protoc-gen-phaser=$(location protoc-gen-phaser) " + + "--phaser_out=add_namespace=phaser,package_name=proto," + + "target_name=subspace_phaser,frontend=protobuf:$(genDir) " + + "-Iexternal/subspace -Iexternal/protobuf/src " + + "$(in) external/protobuf/src/google/protobuf/any.proto" + +genrule { + name: "libsubspace_phaser_cc", + tools: [ + "aprotoc", + "protoc-gen-phaser", + ], + cmd: subspace_phaser_cmd, + srcs: ["proto/subspace.proto"], + out: [ + "proto/subspace_phaser/proto/subspace.phaser.cc", + "proto/subspace_phaser/google/protobuf/any.phaser.cc", + ], +} + +genrule { + name: "libsubspace_phaser_h", + tools: [ + "aprotoc", + "protoc-gen-phaser", + ], + cmd: subspace_phaser_cmd + " && " + + "echo '#pragma once' > $(genDir)/proto/subspace.phaser.h && " + + "echo '#include \"proto/subspace_phaser/proto/subspace.phaser.h\"' " + + ">> $(genDir)/proto/subspace.phaser.h", + srcs: ["proto/subspace.proto"], + out: [ + "proto/subspace.phaser.h", + "proto/subspace_phaser/proto/subspace.phaser.h", + "proto/subspace_phaser/google/protobuf/any.phaser.h", + ], +} + +cc_library_static { + name: "libsubspace_phaser", + defaults: ["subspace_defaults"], + generated_sources: ["libsubspace_phaser_cc"], + generated_headers: ["libsubspace_phaser_h"], + export_generated_headers: ["libsubspace_phaser_h"], + cppflags: ["-fno-exceptions"], + rtti: false, + static_libs: ["libphaser_runtime"], + export_static_lib_headers: ["libphaser_runtime"], +} diff --git a/CHANGELOG.md b/CHANGELOG.md index 57f8512f..82224a3c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,14 +2,117 @@ ## Unreleased +- x86 builds with SSE4.2 no longer use the SSE4.2 CRC32 instruction for + message checksums. That instruction computes CRC-32C, not the IEEE 802.3 + CRC32 used everywhere else (including the Rust client), so checksums from + such a build did not verify against other builds. x86 now always uses the + IEEE table. ARM hardware CRC32 already used the IEEE polynomial and is + unchanged. + +### Static Channel Config +- `subspace_server --channel_config=FILE` reads a `StaticChannelConfig` and + creates its channels and multiplexers before the server accepts clients. + A file ending in `.pb` or `.binpb` is protobuf wire format; any other name + is protobuf text format. `--tunnel_config` uses the same rule. The + configured channels stay when they have no users, and the server defines + their layout. A standard publisher can still create a channel that isn't + configured by specifying its layout, and any subscriber + can subscribe to one. An ASIL publisher cannot: the ASIL client marks its + connection, and the server rejects its publishers on any other channel. +- Publishers on a static channel must set the new `server_defined` option + (`PublisherOptions::SetServerDefined`, `server_defined` in the C, Python, + Rust and ASIL clients) and can't set the slot size, number of slots, fixed + size, checksum size, metadata size, subscriber queue arena size or split + buffer setting. The server rejects `server_defined` on any other channel. + `CreatePublisherResponse` now reports the channel's slot size, checksum + size, metadata size, split buffer setting and fixed size, and a + `server_defined` publisher uses them. +- `subspace_publisher_options_server_defined()` in the C client gives + options for a static channel. +- The default `checksum_size` in the C++ and Rust `PublisherOptions` is now 0, + which means 4 bytes as before, so a `server_defined` publisher can use the + default options. +- A multiplexer with no publishers now reports its slot size. +- Publishers on different virtual channels of a multiplexer are checked + against each other for fixed size and locality, as they share the + multiplexer's buffers. Before, a second fixed-size publisher on another + virtual channel was rejected, so a static multiplexer could only have + publishers on one virtual channel. +- The server creates the message buffers of every static channel and + multiplexer when it starts, so subscribers can map them before any + publisher exists. +- `use_split_buffers` in a static channel or multiplexer config gives it + split buffers, which the server creates. +- `type` in a static channel or multiplexer config is bytes, the same as the + channel type on the wire. A quoted string is that text's bytes, and + protobuf text escapes carry an opaque blob such as ROS metadata or a + protobuf descriptor. A virtual channel still takes its type from its + multiplexer. +- `GetClientBuffersRequest` can ask for one prefix or slot of a split buffer + set with `filter_slot`, `is_prefix` and `slot_id`. + +### ASIL Client +- `asil_client/` is a new C++17 client for safety-related software. It + shares channels with the standard clients through the same shared memory + protocol, using only the standard library and + POSIX. It is built without exceptions or RTTI, returns an error code from + every operation, and allocates no memory while publishing or reading. + Checksums, metadata, `ReadNewest`, dropped message counts and activation + messages work with the standard clients. The server handshake is behind a + replaceable `ServerConnection` interface. `PhaserServerConnection` + implements the standard protocol with phaser messages in fixed buffers, + sent and received as the native Phaser payload, so the handshake makes no + heap allocations either. See `docs/asil-client.md`. +- The ASIL client also supports reliable publishers and subscribers, virtual + channels and multiplexer subscribers, subscribers holding up to 64 + messages, subscriber queues, split buffers (with C callbacks for slots from + a custom allocator), and the memfd backend. Reading the newest message on + a reliable subscriber marks the skipped messages as read. +- ASIL publishers and subscribers map all of a channel's shared memory when + they open, and publishing and reading make no shared memory calls. A + subscriber needs the channel to have buffers when it opens: always true of + static channels, otherwise a publisher must have opened. Messages in a + buffer that a standard publisher created by resizing after the subscriber + opened return `kBufferNotMapped`. +- The standard C++ client builds its server requests and responses as + phaser messages too, in growable buffers. `ServerWire` in + `common/server_wire.h` encodes them for both C++ clients, with fixed or + growable buffers. The socket carries the native Phaser payload. The Rust + client sends and parses that same payload. Bridge, tunnel, discovery, the + channel directory and statistics stay on protobuf. +- The ASIL client and the standard C++ client share the shared memory + protocol code in `common/`: finding a slot, publishing, the checksum, and + taking, releasing and skipping messages. Sharing it fixed these bugs in the + standard client: + - A reliable subscriber reading the newest message didn't mark the + messages it skipped as seen, so a reliable publisher could no longer get + a slot once the free slots ran out. + - A subscriber ignoring an activation message kept its owner bit on the + slot. If the process then died, the server dropped a reference from + whatever message was in that slot later. + - With retirement notification on, releasing a bridged message crashed if + its slot on the other side of the bridge had a higher id than any slot + in this channel. +- Bazel, CMake and Soong build phaser and generate `subspace_phaser` from + `subspace.proto`. Android CMake cross-compiles need a host + `protoc-gen-phaser` in `PHASER_PLUGIN_EXECUTABLE`. +- CMake also generates the Rust client's Phaser bindings and links their C++ + code into the shared library `subspace_phaser_c_rust`, which the Cargo + build links. A Cargo build run outside CMake sets `SUBSPACE_PHASER_C_RS` + and `SUBSPACE_PHASER_C_LIB_DIR` to the files from a CMake build. +- Abseil 20250814.1, protobuf 33.4, cpp_toolbelt 2.1.6 and phaser 3.1.1 in + the Bazel build. CMake uses cpp_toolbelt 2.1.6 and the same phaser. Both + pin phaser 3.1.1 with the CMake build fixes in dallison/phaser#22. + ### Subscriber Queues Keep Per-Publisher Order - A subscriber with an explicit queue size could read a message that had overflowed its queue after newer messages from the same publisher. The overflowed message stayed visible in the subscriber's slot bitset, where bitset recovery and the first read found it. A publisher now clears that bit when it drops a message from a subscriber's queue, and leaves the entry in - place while the dropped message is still being published. The C++ and Rust - clients both do this, so mixed-language channels keep the same order. + place while the dropped message is still being published. The standard + C++, ASIL and Rust publishers all do this, so mixed-language channels keep + the same order. - A reliable subscriber's queue no longer drops entries when it is full. Reliable subscribers read from their bitset, and must never lose a message. The server sets this when it creates the queue, so upgrade it with the @@ -37,9 +140,10 @@ ### Tunnel-Compatible Discovery and Bridging - The server can exchange channels over TCP with peers that use the Cruise IPC tunnel and discovery protocols. `--tunnel` turns it on, and - `--tunnel_config` names a configuration file in protobuf text format - (`proto/tunnel_config.proto`) that lists the device name, listen port, - peers, discovery denylist and refresh interval. Programs that embed the + `--tunnel_config` names a configuration file, in protobuf text format + unless it ends in `.pb` or `.binpb` (`proto/tunnel_config.proto`) that + lists the device name, listen port, peers, discovery denylist and refresh + interval. Programs that embed the server call `Server::SetTunnelConfig`. See `docs/tunnel.md`. - Tunnel discovery uses the Cruise protobuf format on `/ipc/discovery/proto/receive` (`proto/tunnel_discovery.proto`). ROS-encoded diff --git a/CMakeLists.txt b/CMakeLists.txt index bcb99ffe..9eee8851 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -233,6 +233,25 @@ FetchContent_MakeAvailable(protobuf) # Protobuf provides targets like protobuf::libprotobuf and protobuf::protoc # These targets can be used directly without find_package +# --- External Dependency: phaser (using FetchContent for native CMake) --- +# The C++ clients build their server requests and responses as phaser +# messages: in growable buffers for the standard client and fixed buffers for +# the ASIL client. Phaser uses the Abseil, cpp_toolbelt and protobuf fetched +# above. +# Cross-compiles take a host protoc-gen-phaser in PHASER_PLUGIN_EXECUTABLE. +FetchContent_Declare( + phaser + GIT_REPOSITORY https://github.com/dallison/phaser.git + # phaser 3.1.1 with the CMake build fixes in dallison/phaser#22, plus the + # 32-bit ARM PayloadBuffer header alignment fix from dallison/phaser#23, + # as in the git_override in MODULE.bazel. + GIT_TAG a0c1b24794eff9f872c727664841c4c900da074f + PATCH_COMMAND "${CMAKE_COMMAND}" + "-DPATCH_FILE=${CMAKE_CURRENT_SOURCE_DIR}/patches/phaser_armhf_payload_buffer.patch" + -P "${CMAKE_CURRENT_SOURCE_DIR}/cmake/apply_patch.cmake" +) +FetchContent_MakeAvailable(phaser) + # --- Option: coroutine/networking backend for the server --- # Mirrors the Bazel //:coro_backend flag. "co" (default) builds against the co # coroutine library; "asio" builds the server against Boost.Asio. The value is @@ -328,6 +347,7 @@ add_subdirectory(server) add_subdirectory(plugins) add_subdirectory(shadow) add_subdirectory(c_client) +add_subdirectory(asil_client) add_subdirectory(android) add_subdirectory(rust_client) add_subdirectory(rpc) diff --git a/MODULE.bazel b/MODULE.bazel index 9ac50f54..589bb24d 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -12,13 +12,22 @@ subspace = use_extension("//:extensions.bzl", "subspace") use_repo(subspace, "subspace_max_channels") bazel_dep(name = "bazel_skylib", version = "1.9.0") -bazel_dep(name = "platforms", version = "1.0.0") -bazel_dep(name = "abseil-cpp", version = "20250512.1") +bazel_dep(name = "platforms", version = "1.1.0") +bazel_dep(name = "abseil-cpp", version = "20250814.1") # Only linked when the server is built with --//:mtls. See docs/mtls.md. bazel_dep(name = "boringssl", version = "0.20261020.0") -bazel_dep(name = "googletest", version = "1.17.0") -bazel_dep(name = "protobuf", version = "33.2") +bazel_dep(name = "googletest", version = "1.17.0.bcr.2") +bazel_dep(name = "protobuf", version = "33.4") + +# Phaser 3.1.1 asks for protobuf 34.1 and overrides rules_android to 0.7.2 +# so that toolchain resolves on Bazel 9. The clients still build against +# protobuf 33.4, which this module forces. +single_version_override( + module_name = "protobuf", + version = "33.4", +) + bazel_dep(name = "rules_cc", version = "0.2.17") bazel_dep(name = "rules_java", version = "9.1.0") bazel_dep(name = "rules_pkg", version = "1.0.1") @@ -38,6 +47,7 @@ git_override( ) bazel_dep(name = "cpp_toolbelt", version = "2.1.6") +bazel_dep(name = "phaser", version = "3.1.1") # TriggerFd is a socketpair on QNX and a pipe on other non-Linux POSIX. # cpp_toolbelt qnx_pipes branch, not released to the BCR yet. Override the @@ -48,9 +58,19 @@ git_override( remote = "https://github.com/dallison/cpp_toolbelt.git", ) -# retro 1.1.0 is not in the BCR yet; pin it with git_override below. +# retro 1.1.0 and phaser 3.1.1 are not in the BCR yet; pin them below. bazel_dep(name = "retro", version = "1.1.0") -bazel_dep(name = "rules_python", version = "1.7.0") +bazel_dep(name = "rules_python", version = "1.9.0") + +git_override( + module_name = "phaser", + # Tag 3.1.1 with the CMake build fixes in dallison/phaser#22, plus the + # 32-bit ARM PayloadBuffer header alignment fix from dallison/phaser#23. + commit = "a0c1b24794eff9f872c727664841c4c900da074f", + patch_strip = 1, + patches = ["//patches:phaser_armhf_payload_buffer.patch"], + remote = "https://github.com/dallison/phaser.git", +) git_override( module_name = "retro", @@ -62,7 +82,7 @@ git_override( bazel_dep(name = "boost.asio", version = "1.87.0.bcr.1") bazel_dep(name = "boost.context", version = "1.87.0") bazel_dep(name = "boost.coroutine", version = "1.87.0") -bazel_dep(name = "rules_shell", version = "0.6.1") +bazel_dep(name = "rules_shell", version = "0.8.0") bazel_dep(name = "rules_proto", version = "6.0.2") single_version_override( @@ -78,10 +98,10 @@ python.toolchain( python_version = "3.11.1", ) -bazel_dep(name = "pybind11_bazel", version = "3.0.0") +bazel_dep(name = "pybind11_bazel", version = "3.0.1") # Rust support -bazel_dep(name = "rules_rust", version = "0.68.1") +bazel_dep(name = "rules_rust", version = "0.74.0") rust = use_extension("@rules_rust//rust:extensions.bzl", "rust") rust.toolchain( diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index b9e69dc8..a1b2ef93 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -2,13 +2,9 @@ "lockFileVersion": 28, "registryFileHashes": { "https://bcr.bazel.build/bazel_registry.json": "8a28e4aff06ee60aed2a8c281907fb8bcbf3b753c91fb5a5c57da3215d5b3497", - "https://bcr.bazel.build/modules/abseil-cpp/20210324.2/MODULE.bazel": "7cd0312e064fde87c8d1cd79ba06c876bd23630c83466e9500321be55c96ace2", - "https://bcr.bazel.build/modules/abseil-cpp/20211102.0/MODULE.bazel": "70390338f7a5106231d20620712f7cccb659cd0e9d073d1991c038eb9fc57589", "https://bcr.bazel.build/modules/abseil-cpp/20230125.1/MODULE.bazel": "89047429cb0207707b2dface14ba7f8df85273d484c2572755be4bab7ce9c3a0", - "https://bcr.bazel.build/modules/abseil-cpp/20230802.0.bcr.1/MODULE.bazel": "1c8cec495288dccd14fdae6e3f95f772c1c91857047a098fad772034264cc8cb", "https://bcr.bazel.build/modules/abseil-cpp/20230802.0/MODULE.bazel": "d253ae36a8bd9ee3c5955384096ccb6baf16a1b1e93e858370da0a3b94f77c16", "https://bcr.bazel.build/modules/abseil-cpp/20230802.1/MODULE.bazel": "fa92e2eb41a04df73cdabeec37107316f7e5272650f81d6cc096418fe647b915", - "https://bcr.bazel.build/modules/abseil-cpp/20240116.1/MODULE.bazel": "37bcdb4440fbb61df6a1c296ae01b327f19e9bb521f9b8e26ec854b6f97309ed", "https://bcr.bazel.build/modules/abseil-cpp/20240116.2/MODULE.bazel": "73939767a4686cd9a520d16af5ab440071ed75cec1a876bf2fcfaf1f71987a16", "https://bcr.bazel.build/modules/abseil-cpp/20250127.1/MODULE.bazel": "c4a89e7ceb9bf1e25cf84a9f830ff6b817b72874088bf5141b314726e46a57c1", "https://bcr.bazel.build/modules/abseil-cpp/20250512.1/MODULE.bazel": "d209fdb6f36ffaf61c509fcc81b19e81b411a999a934a032e10cd009a0226215", @@ -30,18 +26,17 @@ "https://bcr.bazel.build/modules/bazel_features/1.18.0/MODULE.bazel": "1be0ae2557ab3a72a57aeb31b29be347bcdc5d2b1eb1e70f39e3851a7e97041a", "https://bcr.bazel.build/modules/bazel_features/1.19.0/MODULE.bazel": "59adcdf28230d220f0067b1f435b8537dd033bfff8db21335ef9217919c7fb58", "https://bcr.bazel.build/modules/bazel_features/1.21.0/MODULE.bazel": "675642261665d8eea09989aa3b8afb5c37627f1be178382c320d1b46afba5e3b", - "https://bcr.bazel.build/modules/bazel_features/1.23.0/MODULE.bazel": "fd1ac84bc4e97a5a0816b7fd7d4d4f6d837b0047cf4cbd81652d616af3a6591a", "https://bcr.bazel.build/modules/bazel_features/1.27.0/MODULE.bazel": "621eeee06c4458a9121d1f104efb80f39d34deff4984e778359c60eaf1a8cb65", "https://bcr.bazel.build/modules/bazel_features/1.28.0/MODULE.bazel": "4b4200e6cbf8fa335b2c3f43e1d6ef3e240319c33d43d60cc0fbd4b87ece299d", "https://bcr.bazel.build/modules/bazel_features/1.3.0/MODULE.bazel": "cdcafe83ec318cda34e02948e81d790aab8df7a929cec6f6969f13a489ccecd9", "https://bcr.bazel.build/modules/bazel_features/1.30.0/MODULE.bazel": "a14b62d05969a293b80257e72e597c2da7f717e1e69fa8b339703ed6731bec87", - "https://bcr.bazel.build/modules/bazel_features/1.32.0/MODULE.bazel": "095d67022a58cb20f7e20e1aefecfa65257a222c18a938e2914fd257b5f1ccdc", "https://bcr.bazel.build/modules/bazel_features/1.33.0/MODULE.bazel": "8b8dc9d2a4c88609409c3191165bccec0e4cb044cd7a72ccbe826583303459f6", - "https://bcr.bazel.build/modules/bazel_features/1.36.0/MODULE.bazel": "596cb62090b039caf1cad1d52a8bc35cf188ca9a4e279a828005e7ee49a1bec3", "https://bcr.bazel.build/modules/bazel_features/1.4.1/MODULE.bazel": "e45b6bb2350aff3e442ae1111c555e27eac1d915e77775f6fdc4b351b758b5d7", "https://bcr.bazel.build/modules/bazel_features/1.42.1/MODULE.bazel": "275a59b5406ff18c01739860aa70ad7ccb3cfb474579411decca11c93b951080", + "https://bcr.bazel.build/modules/bazel_features/1.43.0/MODULE.bazel": "defa2226f06ba20550d6548c3a2ea2a7929634437a52973869c20c225450eb91", "https://bcr.bazel.build/modules/bazel_features/1.47.0/MODULE.bazel": "e34df3cb35b1684cfa69923a61ae3803595babd3942cd306a488d51400886b30", - "https://bcr.bazel.build/modules/bazel_features/1.47.0/source.json": "4ba0b5138327f2d73352a51547a4e49a0a828ef400e046b15334d8905bf6b7ff", + "https://bcr.bazel.build/modules/bazel_features/1.50.0/MODULE.bazel": "2083ef9c7a469f520890483ccf8e0189d6e71e2117e7752e15e6554433d5ae3e", + "https://bcr.bazel.build/modules/bazel_features/1.50.0/source.json": "e0ee3debde2789ff56e4452e612d126925ba9ab64d4bde79c67f099d2902df9b", "https://bcr.bazel.build/modules/bazel_features/1.9.1/MODULE.bazel": "8f679097876a9b609ad1f60249c49d68bfab783dd9be012faf9d82547b14815a", "https://bcr.bazel.build/modules/bazel_skylib/1.0.3/MODULE.bazel": "bcb0fd896384802d1ad283b4e4eb4d718eebd8cb820b0a2c3a347fb971afd9d8", "https://bcr.bazel.build/modules/bazel_skylib/1.1.1/MODULE.bazel": "1add3e7d93ff2e6998f9e118022c84d163917d912f5afafb3058e3d2f1545b5e", @@ -52,7 +47,6 @@ "https://bcr.bazel.build/modules/bazel_skylib/1.4.2/MODULE.bazel": "3bd40978e7a1fac911d5989e6b09d8f64921865a45822d8b09e815eaa726a651", "https://bcr.bazel.build/modules/bazel_skylib/1.5.0/MODULE.bazel": "32880f5e2945ce6a03d1fbd588e9198c0a959bb42297b2cfaf1685b7bc32e138", "https://bcr.bazel.build/modules/bazel_skylib/1.6.1/MODULE.bazel": "8fdee2dbaace6c252131c00e1de4b165dc65af02ea278476187765e1a617b917", - "https://bcr.bazel.build/modules/bazel_skylib/1.7.0/MODULE.bazel": "0db596f4563de7938de764cc8deeabec291f55e8ec15299718b93c4423e9796d", "https://bcr.bazel.build/modules/bazel_skylib/1.7.1/MODULE.bazel": "3120d80c5861aa616222ec015332e5f8d3171e062e3e804a2a0253e1be26e59b", "https://bcr.bazel.build/modules/bazel_skylib/1.8.0/MODULE.bazel": "2fb3fb53675f6adfc1ca5bfbd5cfb655ae350fba4706d924a8ec7e3ba945671c", "https://bcr.bazel.build/modules/bazel_skylib/1.8.1/MODULE.bazel": "88ade7293becda963e0e3ea33e7d54d3425127e0a326e0d17da085a5f1f03ff6", @@ -171,14 +165,12 @@ "https://bcr.bazel.build/modules/google_benchmark/1.8.2/MODULE.bazel": "a70cf1bba851000ba93b58ae2f6d76490a9feb74192e57ab8e8ff13c34ec50cb", "https://bcr.bazel.build/modules/google_benchmark/1.9.5/MODULE.bazel": "8a85cfd90b1e45e6e68f1aa2aa9efce3c04add57df732571d7fd54c07e7c5143", "https://bcr.bazel.build/modules/google_benchmark/1.9.5/source.json": "0bd357fd9db30ee31d5eb4c78b1086ce3d79b4423ce76de19e8a2fa7b2fa2e10", - "https://bcr.bazel.build/modules/googletest/1.11.0/MODULE.bazel": "3a83f095183f66345ca86aa13c58b59f9f94a2f81999c093d4eeaa2d262d12f4", "https://bcr.bazel.build/modules/googletest/1.14.0.bcr.1/MODULE.bazel": "22c31a561553727960057361aa33bf20fb2e98584bc4fec007906e27053f80c6", "https://bcr.bazel.build/modules/googletest/1.14.0/MODULE.bazel": "cfbcbf3e6eac06ef9d85900f64424708cc08687d1b527f0ef65aa7517af8118f", "https://bcr.bazel.build/modules/googletest/1.15.2/MODULE.bazel": "6de1edc1d26cafb0ea1a6ab3f4d4192d91a312fd2d360b63adaa213cd00b2108", "https://bcr.bazel.build/modules/googletest/1.17.0.bcr.2/MODULE.bazel": "827f54f492a3ce549c940106d73de332c2b30cebd0c20c0bc5d786aba7f116cb", "https://bcr.bazel.build/modules/googletest/1.17.0.bcr.2/source.json": "3664514073a819992320ffbce5825e4238459df344d8b01748af2208f8d2e1eb", "https://bcr.bazel.build/modules/googletest/1.17.0/MODULE.bazel": "dbec758171594a705933a29fcf69293d2468c49ec1f2ebca65c36f504d72df46", - "https://bcr.bazel.build/modules/jsoncpp/1.9.5/MODULE.bazel": "31271aedc59e815656f5736f282bb7509a97c7ecb43e927ac1a37966e0578075", "https://bcr.bazel.build/modules/jsoncpp/1.9.6/MODULE.bazel": "2f8d20d3b7d54143213c4dfc3d98225c42de7d666011528dc8fe91591e2e17b0", "https://bcr.bazel.build/modules/jsoncpp/1.9.6/source.json": "a04756d367a2126c3541682864ecec52f92cdee80a35735a3cb249ce015ca000", "https://bcr.bazel.build/modules/libpfm/4.11.0.bcr.1/MODULE.bazel": "e5362dadc90aab6724c83a2cc1e67cbed9c89a05d97fb1f90053c8deb1e445c8", @@ -191,7 +183,6 @@ "https://bcr.bazel.build/modules/platforms/0.0.10/MODULE.bazel": "8cb8efaf200bdeb2150d93e162c40f388529a25852b332cec879373771e48ed5", "https://bcr.bazel.build/modules/platforms/0.0.11/MODULE.bazel": "0daefc49732e227caa8bfa834d65dc52e8cc18a2faf80df25e8caea151a9413f", "https://bcr.bazel.build/modules/platforms/0.0.4/MODULE.bazel": "9b328e31ee156f53f3c416a64f8491f7eb731742655a47c9eec4703a71644aee", - "https://bcr.bazel.build/modules/platforms/0.0.5/MODULE.bazel": "5733b54ea419d5eaf7997054bb55f6a1d0b5ff8aedf0176fef9eea44f3acda37", "https://bcr.bazel.build/modules/platforms/0.0.6/MODULE.bazel": "ad6eeef431dc52aefd2d77ed20a4b353f8ebf0f4ecdd26a807d2da5aa8cd0615", "https://bcr.bazel.build/modules/platforms/0.0.7/MODULE.bazel": "72fd4a0ede9ee5c021f6a8dd92b503e089f46c227ba2813ff183b71616034814", "https://bcr.bazel.build/modules/platforms/0.0.8/MODULE.bazel": "9f142c03e348f6d263719f5074b21ef3adf0b139ee4c5133e2aa35664da9eb2d", @@ -199,23 +190,13 @@ "https://bcr.bazel.build/modules/platforms/1.0.0/MODULE.bazel": "f05feb42b48f1b3c225e4ccf351f367be0371411a803198ec34a389fb22aa580", "https://bcr.bazel.build/modules/platforms/1.1.0/MODULE.bazel": "1c0c09f5bdcf4b3f924720d2478a3711cb39f4977019ca5988685e5b7e18b3d2", "https://bcr.bazel.build/modules/platforms/1.1.0/source.json": "fcf351c47596c939140ab0d333dfdd08ed1ea6ce33c2fe70c12493a301cf1344", - "https://bcr.bazel.build/modules/protobuf/21.7/MODULE.bazel": "a5a29bb89544f9b97edce05642fac225a808b5b7be74038ea3640fae2f8e66a7", - "https://bcr.bazel.build/modules/protobuf/23.1/MODULE.bazel": "88b393b3eb4101d18129e5db51847cd40a5517a53e81216144a8c32dfeeca52a", - "https://bcr.bazel.build/modules/protobuf/24.4/MODULE.bazel": "7bc7ce5f2abf36b3b7b7c8218d3acdebb9426aeb35c2257c96445756f970eb12", - "https://bcr.bazel.build/modules/protobuf/27.0/MODULE.bazel": "7873b60be88844a0a1d8f80b9d5d20cfbd8495a689b8763e76c6372998d3f64c", - "https://bcr.bazel.build/modules/protobuf/29.0-rc2/MODULE.bazel": "6241d35983510143049943fc0d57937937122baf1b287862f9dc8590fc4c37df", - "https://bcr.bazel.build/modules/protobuf/29.0-rc3/MODULE.bazel": "33c2dfa286578573afc55a7acaea3cada4122b9631007c594bf0729f41c8de92", - "https://bcr.bazel.build/modules/protobuf/29.1/MODULE.bazel": "557c3457560ff49e122ed76c0bc3397a64af9574691cb8201b4e46d4ab2ecb95", - "https://bcr.bazel.build/modules/protobuf/3.19.0/MODULE.bazel": "6b5fbb433f760a99a22b18b6850ed5784ef0e9928a72668b66e4d7ccd47db9b0", - "https://bcr.bazel.build/modules/protobuf/32.1/MODULE.bazel": "89cd2866a9cb07fee9ff74c41ceace11554f32e0d849de4e23ac55515cfada4d", - "https://bcr.bazel.build/modules/protobuf/33.2/MODULE.bazel": "e8d408653b855e467ac7f99f2dfae8f073ae421fd4eb9a05b5ade5118d66cc3d", "https://bcr.bazel.build/modules/protobuf/33.4/MODULE.bazel": "114775b816b38b6d0ca620450d6b02550c60ceedfdc8d9a229833b34a223dc42", "https://bcr.bazel.build/modules/protobuf/33.4/source.json": "555f8686b4c7d6b5ba731fbea13bf656b4bfd9a7ff629c1d9d3f6e1d6155de79", "https://bcr.bazel.build/modules/pybind11_bazel/2.11.1/MODULE.bazel": "88af1c246226d87e65be78ed49ecd1e6f5e98648558c14ce99176da041dc378e", "https://bcr.bazel.build/modules/pybind11_bazel/2.12.0/MODULE.bazel": "e6f4c20442eaa7c90d7190d8dc539d0ab422f95c65a57cc59562170c58ae3d34", "https://bcr.bazel.build/modules/pybind11_bazel/2.13.6/MODULE.bazel": "2d746fda559464b253b2b2e6073cb51643a2ac79009ca02100ebbc44b4548656", - "https://bcr.bazel.build/modules/pybind11_bazel/3.0.0/MODULE.bazel": "a2bfa6020ed603a00d944161c63173c7f109774e99bee0c2cd8dbf24159f8134", - "https://bcr.bazel.build/modules/pybind11_bazel/3.0.0/source.json": "d8f5104d4c21d272bf327ebe44366fb0b4c036cdaa1f5cceb21a408ca4ef2ef8", + "https://bcr.bazel.build/modules/pybind11_bazel/3.0.1/MODULE.bazel": "67899804c3dbdf169d107ce7c00e60a38a46d097c7ff3460bdebe192cbc77f56", + "https://bcr.bazel.build/modules/pybind11_bazel/3.0.1/source.json": "5bcb3ae55c0d5a159bd910154d7ee8873bdf61dd7b13cd0a2bb456011ec706ae", "https://bcr.bazel.build/modules/re2/2023-09-01/MODULE.bazel": "cb3d511531b16cfc78a225a9e2136007a48cf8a677e4264baeab57fe78a80206", "https://bcr.bazel.build/modules/re2/2024-07-02.bcr.1/MODULE.bazel": "b4963dda9b31080be1905ef085ecd7dd6cd47c05c79b9cdf83ade83ab2ab271a", "https://bcr.bazel.build/modules/re2/2024-07-02/MODULE.bazel": "0eadc4395959969297cbcf31a249ff457f2f1d456228c67719480205aa306daa", @@ -230,7 +211,6 @@ "https://bcr.bazel.build/modules/rules_apple/4.1.0/source.json": "8ee81e1708756f81b343a5eb2b2f0b953f1d25c4ab3d4a68dc02754872e80715", "https://bcr.bazel.build/modules/rules_cc/0.0.1/MODULE.bazel": "cb2aa0747f84c6c3a78dad4e2049c154f08ab9d166b1273835a8174940365647", "https://bcr.bazel.build/modules/rules_cc/0.0.10/MODULE.bazel": "ec1705118f7eaedd6e118508d3d26deba2a4e76476ada7e0e3965211be012002", - "https://bcr.bazel.build/modules/rules_cc/0.0.13/MODULE.bazel": "0e8529ed7b323dad0775ff924d2ae5af7640b23553dfcd4d34344c7e7a867191", "https://bcr.bazel.build/modules/rules_cc/0.0.15/MODULE.bazel": "6704c35f7b4a72502ee81f61bf88706b54f06b3cbe5558ac17e2e14666cd5dcc", "https://bcr.bazel.build/modules/rules_cc/0.0.16/MODULE.bazel": "7661303b8fc1b4d7f532e54e9d6565771fea666fbdf839e0a86affcd02defe87", "https://bcr.bazel.build/modules/rules_cc/0.0.17/MODULE.bazel": "2ae1d8f4238ec67d7185d8861cb0a2cdf4bc608697c331b95bf990e69b62e64a", @@ -251,24 +231,16 @@ "https://bcr.bazel.build/modules/rules_cc/0.2.19/source.json": "1ef48cdbd7aa6238015189b582d3d74ef0cbea3cb3e2cb259d782463f570c14a", "https://bcr.bazel.build/modules/rules_cc/0.2.4/MODULE.bazel": "1ff1223dfd24f3ecf8f028446d4a27608aa43c3f41e346d22838a4223980b8cc", "https://bcr.bazel.build/modules/rules_cc/0.2.8/MODULE.bazel": "f1df20f0bf22c28192a794f29b501ee2018fa37a3862a1a2132ae2940a23a642", - "https://bcr.bazel.build/modules/rules_cc/0.2.9/MODULE.bazel": "34263f1dca62ea664265438cef714d7db124c03e1ed55ebb4f1dc860164308d1", "https://bcr.bazel.build/modules/rules_foreign_cc/0.9.0/MODULE.bazel": "c9e8c682bf75b0e7c704166d79b599f93b72cfca5ad7477df596947891feeef6", - "https://bcr.bazel.build/modules/rules_fuzzing/0.5.2/MODULE.bazel": "40c97d1144356f52905566c55811f13b299453a14ac7769dfba2ac38192337a8", "https://bcr.bazel.build/modules/rules_java/4.0.0/MODULE.bazel": "5a78a7ae82cd1a33cef56dc578c7d2a46ed0dca12643ee45edbb8417899e6f74", - "https://bcr.bazel.build/modules/rules_java/5.3.5/MODULE.bazel": "a4ec4f2db570171e3e5eb753276ee4b389bae16b96207e9d3230895c99644b86", - "https://bcr.bazel.build/modules/rules_java/6.5.2/MODULE.bazel": "1d440d262d0e08453fa0c4d8f699ba81609ed0e9a9a0f02cd10b3e7942e61e31", - "https://bcr.bazel.build/modules/rules_java/7.1.0/MODULE.bazel": "30d9135a2b6561c761bd67bd4990da591e6bdc128790ce3e7afd6a3558b2fb64", "https://bcr.bazel.build/modules/rules_java/7.10.0/MODULE.bazel": "530c3beb3067e870561739f1144329a21c851ff771cd752a49e06e3dc9c2e71a", "https://bcr.bazel.build/modules/rules_java/7.12.2/MODULE.bazel": "579c505165ee757a4280ef83cda0150eea193eed3bef50b1004ba88b99da6de6", "https://bcr.bazel.build/modules/rules_java/7.2.0/MODULE.bazel": "06c0334c9be61e6cef2c8c84a7800cef502063269a5af25ceb100b192453d4ab", "https://bcr.bazel.build/modules/rules_java/7.6.1/MODULE.bazel": "2f14b7e8a1aa2f67ae92bc69d1ec0fa8d9f827c4e17ff5e5f02e91caa3b2d0fe", - "https://bcr.bazel.build/modules/rules_java/8.3.2/MODULE.bazel": "7336d5511ad5af0b8615fdc7477535a2e4e723a357b6713af439fe8cf0195017", "https://bcr.bazel.build/modules/rules_java/8.5.1/MODULE.bazel": "d8a9e38cc5228881f7055a6079f6f7821a073df3744d441978e7a43e20226939", "https://bcr.bazel.build/modules/rules_java/8.6.1/MODULE.bazel": "f4808e2ab5b0197f094cabce9f4b006a27766beb6a9975931da07099560ca9c2", "https://bcr.bazel.build/modules/rules_java/9.1.0/MODULE.bazel": "ee63f27e36a3fada80342869361182f120a9819c74320e8e65b1e04ba0cd7a9d", "https://bcr.bazel.build/modules/rules_java/9.1.0/source.json": "da589573c1dee2c9ac4a568b301269a2e8191110ff0345c1a959fa7ea6c4dfd6", - "https://bcr.bazel.build/modules/rules_jvm_external/4.4.2/MODULE.bazel": "a56b85e418c83eb1839819f0b515c431010160383306d13ec21959ac412d2fe7", - "https://bcr.bazel.build/modules/rules_jvm_external/5.1/MODULE.bazel": "33f6f999e03183f7d088c9be518a63467dfd0be94a11d0055fe2d210f89aa909", "https://bcr.bazel.build/modules/rules_jvm_external/5.2/MODULE.bazel": "d9351ba35217ad0de03816ef3ed63f89d411349353077348a45348b096615036", "https://bcr.bazel.build/modules/rules_jvm_external/6.3/MODULE.bazel": "c998e060b85f71e00de5ec552019347c8bca255062c990ac02d051bb80a38df0", "https://bcr.bazel.build/modules/rules_jvm_external/6.7/MODULE.bazel": "e717beabc4d091ecb2c803c2d341b88590e9116b8bf7947915eeb33aab4f96dd", @@ -279,7 +251,6 @@ "https://bcr.bazel.build/modules/rules_license/0.0.7/MODULE.bazel": "088fbeb0b6a419005b89cf93fe62d9517c0a2b8bb56af3244af65ecfe37e7d5d", "https://bcr.bazel.build/modules/rules_license/1.0.0/MODULE.bazel": "a7fda60eefdf3d8c827262ba499957e4df06f659330bbe6cdbdb975b768bb65c", "https://bcr.bazel.build/modules/rules_license/1.0.0/source.json": "a52c89e54cc311196e478f8382df91c15f7a2bfdf4c6cd0e2675cc2ff0b56efb", - "https://bcr.bazel.build/modules/rules_pkg/0.7.0/MODULE.bazel": "df99f03fc7934a4737122518bb87e667e62d780b610910f0447665a7e2be62dc", "https://bcr.bazel.build/modules/rules_pkg/1.0.1/MODULE.bazel": "5b1df97dbc29623bccdf2b0dcd0f5cb08e2f2c9050aab1092fd39a41e82686ff", "https://bcr.bazel.build/modules/rules_pkg/1.0.1/source.json": "bd82e5d7b9ce2d31e380dd9f50c111d678c3bdaca190cb76b0e1c71b05e1ba8a", "https://bcr.bazel.build/modules/rules_proto/4.0.0/MODULE.bazel": "a7a7b6ce9bee418c1a760b3d84f83a299ad6952f9903c67f19e4edd964894e06", @@ -288,33 +259,29 @@ "https://bcr.bazel.build/modules/rules_proto/6.0.2/MODULE.bazel": "ce916b775a62b90b61888052a416ccdda405212b6aaeb39522f7dc53431a5e73", "https://bcr.bazel.build/modules/rules_proto/7.1.0/MODULE.bazel": "002d62d9108f75bb807cd56245d45648f38275cb3a99dcd45dfb864c5d74cb96", "https://bcr.bazel.build/modules/rules_proto/7.1.0/source.json": "39f89066c12c24097854e8f57ab8558929f9c8d474d34b2c00ac04630ad8940e", - "https://bcr.bazel.build/modules/rules_python/0.10.2/MODULE.bazel": "cc82bc96f2997baa545ab3ce73f196d040ffb8756fd2d66125a530031cd90e5f", "https://bcr.bazel.build/modules/rules_python/0.23.1/MODULE.bazel": "49ffccf0511cb8414de28321f5fcf2a31312b47c40cc21577144b7447f2bf300", "https://bcr.bazel.build/modules/rules_python/0.25.0/MODULE.bazel": "72f1506841c920a1afec76975b35312410eea3aa7b63267436bfb1dd91d2d382", - "https://bcr.bazel.build/modules/rules_python/0.28.0/MODULE.bazel": "cba2573d870babc976664a912539b320cbaa7114cd3e8f053c720171cde331ed", "https://bcr.bazel.build/modules/rules_python/0.31.0/MODULE.bazel": "93a43dc47ee570e6ec9f5779b2e64c1476a6ce921c48cc9a1678a91dd5f8fd58", "https://bcr.bazel.build/modules/rules_python/0.33.2/MODULE.bazel": "3e036c4ad8d804a4dad897d333d8dce200d943df4827cb849840055be8d2e937", "https://bcr.bazel.build/modules/rules_python/0.34.0/MODULE.bazel": "1d623d026e075b78c9fde483a889cda7996f5da4f36dffb24c246ab30f06513a", - "https://bcr.bazel.build/modules/rules_python/0.4.0/MODULE.bazel": "9208ee05fd48bf09ac60ed269791cf17fb343db56c8226a720fbb1cdf467166c", "https://bcr.bazel.build/modules/rules_python/1.3.0/MODULE.bazel": "8361d57eafb67c09b75bf4bbe6be360e1b8f4f18118ab48037f2bd50aa2ccb13", - "https://bcr.bazel.build/modules/rules_python/1.4.1/MODULE.bazel": "8991ad45bdc25018301d6b7e1d3626afc3c8af8aaf4bc04f23d0b99c938b73a6", "https://bcr.bazel.build/modules/rules_python/1.5.1/MODULE.bazel": "acfe65880942d44a69129d4c5c3122d57baaf3edf58ae5a6bd4edea114906bf5", "https://bcr.bazel.build/modules/rules_python/1.6.0/MODULE.bazel": "7e04ad8f8d5bea40451cf80b1bd8262552aa73f841415d20db96b7241bd027d8", - "https://bcr.bazel.build/modules/rules_python/1.6.3/MODULE.bazel": "a7b80c42cb3de5ee2a5fa1abc119684593704fcd2fec83165ebe615dec76574f", "https://bcr.bazel.build/modules/rules_python/1.7.0/MODULE.bazel": "d01f995ecd137abf30238ad9ce97f8fc3ac57289c8b24bd0bf53324d937a14f8", - "https://bcr.bazel.build/modules/rules_python/1.7.0/source.json": "028a084b65dcf8f4dc4f82f8778dbe65df133f234b316828a82e060d81bdce32", - "https://bcr.bazel.build/modules/rules_rust/0.68.1/MODULE.bazel": "8d3332ef4079673385eb81f8bd68b012decc04ac00c9d5a01a40eff90301732c", - "https://bcr.bazel.build/modules/rules_rust/0.68.1/source.json": "3378e746f81b62457fdfd37391244fa8ff075ba85c05931ee4f3a20ac1efe963", + "https://bcr.bazel.build/modules/rules_python/1.9.0/MODULE.bazel": "afc3a05f29f09f2d3ee95ad99a145250dab41a2b2d8d6f82cc91936b3213282c", + "https://bcr.bazel.build/modules/rules_python/1.9.0/source.json": "3921ea0b65298d51aead5b9e4a82203d7be9b5918619b58b53f1c259f4e63169", + "https://bcr.bazel.build/modules/rules_rust/0.74.0/MODULE.bazel": "6e6fa04d7c8202f9cd63205ec9f96da39382a4ac971ee1d7a900fe8e1f68be17", + "https://bcr.bazel.build/modules/rules_rust/0.74.0/source.json": "04eac31b4536eb23dd8e8e8ca7e079d3c1c4ac99934d38aa54bbae36917c7507", "https://bcr.bazel.build/modules/rules_shell/0.2.0/MODULE.bazel": "fda8a652ab3c7d8fee214de05e7a9916d8b28082234e8d2c0094505c5268ed3c", "https://bcr.bazel.build/modules/rules_shell/0.3.0/MODULE.bazel": "de4402cd12f4cc8fda2354fce179fdb068c0b9ca1ec2d2b17b3e21b24c1a937b", "https://bcr.bazel.build/modules/rules_shell/0.6.1/MODULE.bazel": "72e76b0eea4e81611ef5452aa82b3da34caca0c8b7b5c0c9584338aa93bae26b", - "https://bcr.bazel.build/modules/rules_shell/0.6.1/source.json": "20ec05cd5e592055e214b2da8ccb283c7f2a421ea0dc2acbf1aa792e11c03d0c", + "https://bcr.bazel.build/modules/rules_shell/0.8.0/MODULE.bazel": "f6a89f1d6a669a26f28fe814503857055d76306b79cfc11d12399af08d0b80ae", + "https://bcr.bazel.build/modules/rules_shell/0.8.0/source.json": "eb53cc815bc503c6683c5fe12d943f98883f81fc22f51403ec8a95610cba4195", "https://bcr.bazel.build/modules/rules_swift/1.16.0/MODULE.bazel": "4a09f199545a60d09895e8281362b1ff3bb08bbde69c6fc87aff5b92fcc916ca", "https://bcr.bazel.build/modules/rules_swift/2.1.1/MODULE.bazel": "494900a80f944fc7aa61500c2073d9729dff0b764f0e89b824eb746959bc1046", "https://bcr.bazel.build/modules/rules_swift/2.4.0/MODULE.bazel": "1639617eb1ede28d774d967a738b4a68b0accb40650beadb57c21846beab5efd", "https://bcr.bazel.build/modules/rules_swift/3.1.2/MODULE.bazel": "72c8f5cf9d26427cee6c76c8e3853eb46ce6b0412a081b2b6db6e8ad56267400", "https://bcr.bazel.build/modules/rules_swift/3.1.2/source.json": "e85761f3098a6faf40b8187695e3de6d97944e98abd0d8ce579cb2daf6319a66", - "https://bcr.bazel.build/modules/stardoc/0.5.1/MODULE.bazel": "1a05d92974d0c122f5ccf09291442580317cdd859f07a8655f1db9a60374f9f8", "https://bcr.bazel.build/modules/stardoc/0.5.3/MODULE.bazel": "c7f6948dae6999bf0db32c1858ae345f112cacf98f174c7a8bb707e41b974f1c", "https://bcr.bazel.build/modules/stardoc/0.7.0/MODULE.bazel": "05e3d6d30c099b6770e97da986c53bd31844d7f13d41412480ea265ac9e8079c", "https://bcr.bazel.build/modules/stardoc/0.7.2/MODULE.bazel": "fc152419aa2ea0f51c29583fab1e8c99ddefd5b3778421845606ee628629e0e5", @@ -322,12 +289,8 @@ "https://bcr.bazel.build/modules/swift_argument_parser/1.3.1.1/MODULE.bazel": "5e463fbfba7b1701d957555ed45097d7f984211330106ccd1352c6e0af0dcf91", "https://bcr.bazel.build/modules/swift_argument_parser/1.3.1.2/MODULE.bazel": "75aab2373a4bbe2a1260b9bf2a1ebbdbf872d3bd36f80bff058dccd82e89422f", "https://bcr.bazel.build/modules/swift_argument_parser/1.3.1.2/source.json": "5fba48bbe0ba48761f9e9f75f92876cafb5d07c0ce059cc7a8027416de94a05b", - "https://bcr.bazel.build/modules/upb/0.0.0-20220923-a547704/MODULE.bazel": "7298990c00040a0e2f121f6c32544bab27d4452f80d9ce51349b1a28f3005c43", - "https://bcr.bazel.build/modules/upb/0.0.0-20230516-61a97ef/MODULE.bazel": "c0df5e35ad55e264160417fd0875932ee3c9dda63d9fccace35ac62f45e1b6f9", - "https://bcr.bazel.build/modules/zlib/1.2.11/MODULE.bazel": "07b389abc85fdbca459b69e2ec656ae5622873af3f845e1c9d80fe179f3effa0", "https://bcr.bazel.build/modules/zlib/1.3.1.bcr.5/MODULE.bazel": "eec517b5bbe5492629466e11dae908d043364302283de25581e3eb944326c4ca", - "https://bcr.bazel.build/modules/zlib/1.3.1.bcr.5/source.json": "22bc55c47af97246cfc093d0acf683a7869377de362b5d1c552c2c2e16b7a806", - "https://bcr.bazel.build/modules/zlib/1.3.1/MODULE.bazel": "751c9940dcfe869f5f7274e1295422a34623555916eb98c174c1e945594bf198" + "https://bcr.bazel.build/modules/zlib/1.3.1.bcr.5/source.json": "22bc55c47af97246cfc093d0acf683a7869377de362b5d1c552c2c2e16b7a806" }, "selectedYankedVersions": {}, "moduleExtensions": { @@ -401,178 +364,10 @@ } } }, - "@@rules_python+//python/extensions:config.bzl%config": { - "general": { - "bzlTransitiveDigest": "L+2ZCpb7GIJqvWaXpzkfk/80d916sIFVmSPzrSm6of8=", - "usagesDigest": "ZVSXMAGpD+xzVNPuvF1IoLBkty7TROO0+akMapt1pAg=", - "recordedInputs": [ - "REPO_MAPPING:rules_python+,bazel_tools bazel_tools", - "REPO_MAPPING:rules_python+,pypi__build rules_python++config+pypi__build", - "REPO_MAPPING:rules_python+,pypi__click rules_python++config+pypi__click", - "REPO_MAPPING:rules_python+,pypi__colorama rules_python++config+pypi__colorama", - "REPO_MAPPING:rules_python+,pypi__importlib_metadata rules_python++config+pypi__importlib_metadata", - "REPO_MAPPING:rules_python+,pypi__installer rules_python++config+pypi__installer", - "REPO_MAPPING:rules_python+,pypi__more_itertools rules_python++config+pypi__more_itertools", - "REPO_MAPPING:rules_python+,pypi__packaging rules_python++config+pypi__packaging", - "REPO_MAPPING:rules_python+,pypi__pep517 rules_python++config+pypi__pep517", - "REPO_MAPPING:rules_python+,pypi__pip rules_python++config+pypi__pip", - "REPO_MAPPING:rules_python+,pypi__pip_tools rules_python++config+pypi__pip_tools", - "REPO_MAPPING:rules_python+,pypi__pyproject_hooks rules_python++config+pypi__pyproject_hooks", - "REPO_MAPPING:rules_python+,pypi__setuptools rules_python++config+pypi__setuptools", - "REPO_MAPPING:rules_python+,pypi__tomli rules_python++config+pypi__tomli", - "REPO_MAPPING:rules_python+,pypi__wheel rules_python++config+pypi__wheel", - "REPO_MAPPING:rules_python+,pypi__zipp rules_python++config+pypi__zipp" - ], - "generatedRepoSpecs": { - "rules_python_internal": { - "repoRuleId": "@@rules_python+//python/private:internal_config_repo.bzl%internal_config_repo", - "attributes": { - "transition_setting_generators": {}, - "transition_settings": [] - } - }, - "pypi__build": { - "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", - "attributes": { - "url": "https://files.pythonhosted.org/packages/e2/03/f3c8ba0a6b6e30d7d18c40faab90807c9bb5e9a1e3b2fe2008af624a9c97/build-1.2.1-py3-none-any.whl", - "sha256": "75e10f767a433d9a86e50d83f418e83efc18ede923ee5ff7df93b6cb0306c5d4", - "type": "zip", - "build_file_content": "package(default_visibility = [\"//visibility:public\"])\n\nload(\"@rules_python//python:py_library.bzl\", \"py_library\")\n\npy_library(\n name = \"lib\",\n srcs = glob([\"**/*.py\"]),\n data = glob([\"**/*\"], exclude=[\n # These entries include those put into user-installed dependencies by\n # data_exclude to avoid non-determinism.\n \"**/*.py\",\n \"**/*.pyc\",\n \"**/*.pyc.*\", # During pyc creation, temp files named *.pyc.NNN are created\n \"**/*.dist-info/RECORD\",\n \"BUILD\",\n \"WORKSPACE\",\n ]),\n # This makes this directory a top-level in the python import\n # search path for anything that depends on this.\n imports = [\".\"],\n)\n" - } - }, - "pypi__click": { - "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", - "attributes": { - "url": "https://files.pythonhosted.org/packages/00/2e/d53fa4befbf2cfa713304affc7ca780ce4fc1fd8710527771b58311a3229/click-8.1.7-py3-none-any.whl", - "sha256": "ae74fb96c20a0277a1d615f1e4d73c8414f5a98db8b799a7931d1582f3390c28", - "type": "zip", - "build_file_content": "package(default_visibility = [\"//visibility:public\"])\n\nload(\"@rules_python//python:py_library.bzl\", \"py_library\")\n\npy_library(\n name = \"lib\",\n srcs = glob([\"**/*.py\"]),\n data = glob([\"**/*\"], exclude=[\n # These entries include those put into user-installed dependencies by\n # data_exclude to avoid non-determinism.\n \"**/*.py\",\n \"**/*.pyc\",\n \"**/*.pyc.*\", # During pyc creation, temp files named *.pyc.NNN are created\n \"**/*.dist-info/RECORD\",\n \"BUILD\",\n \"WORKSPACE\",\n ]),\n # This makes this directory a top-level in the python import\n # search path for anything that depends on this.\n imports = [\".\"],\n)\n" - } - }, - "pypi__colorama": { - "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", - "attributes": { - "url": "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", - "sha256": "4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", - "type": "zip", - "build_file_content": "package(default_visibility = [\"//visibility:public\"])\n\nload(\"@rules_python//python:py_library.bzl\", \"py_library\")\n\npy_library(\n name = \"lib\",\n srcs = glob([\"**/*.py\"]),\n data = glob([\"**/*\"], exclude=[\n # These entries include those put into user-installed dependencies by\n # data_exclude to avoid non-determinism.\n \"**/*.py\",\n \"**/*.pyc\",\n \"**/*.pyc.*\", # During pyc creation, temp files named *.pyc.NNN are created\n \"**/*.dist-info/RECORD\",\n \"BUILD\",\n \"WORKSPACE\",\n ]),\n # This makes this directory a top-level in the python import\n # search path for anything that depends on this.\n imports = [\".\"],\n)\n" - } - }, - "pypi__importlib_metadata": { - "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", - "attributes": { - "url": "https://files.pythonhosted.org/packages/2d/0a/679461c511447ffaf176567d5c496d1de27cbe34a87df6677d7171b2fbd4/importlib_metadata-7.1.0-py3-none-any.whl", - "sha256": "30962b96c0c223483ed6cc7280e7f0199feb01a0e40cfae4d4450fc6fab1f570", - "type": "zip", - "build_file_content": "package(default_visibility = [\"//visibility:public\"])\n\nload(\"@rules_python//python:py_library.bzl\", \"py_library\")\n\npy_library(\n name = \"lib\",\n srcs = glob([\"**/*.py\"]),\n data = glob([\"**/*\"], exclude=[\n # These entries include those put into user-installed dependencies by\n # data_exclude to avoid non-determinism.\n \"**/*.py\",\n \"**/*.pyc\",\n \"**/*.pyc.*\", # During pyc creation, temp files named *.pyc.NNN are created\n \"**/*.dist-info/RECORD\",\n \"BUILD\",\n \"WORKSPACE\",\n ]),\n # This makes this directory a top-level in the python import\n # search path for anything that depends on this.\n imports = [\".\"],\n)\n" - } - }, - "pypi__installer": { - "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", - "attributes": { - "url": "https://files.pythonhosted.org/packages/e5/ca/1172b6638d52f2d6caa2dd262ec4c811ba59eee96d54a7701930726bce18/installer-0.7.0-py3-none-any.whl", - "sha256": "05d1933f0a5ba7d8d6296bb6d5018e7c94fa473ceb10cf198a92ccea19c27b53", - "type": "zip", - "build_file_content": "package(default_visibility = [\"//visibility:public\"])\n\nload(\"@rules_python//python:py_library.bzl\", \"py_library\")\n\npy_library(\n name = \"lib\",\n srcs = glob([\"**/*.py\"]),\n data = glob([\"**/*\"], exclude=[\n # These entries include those put into user-installed dependencies by\n # data_exclude to avoid non-determinism.\n \"**/*.py\",\n \"**/*.pyc\",\n \"**/*.pyc.*\", # During pyc creation, temp files named *.pyc.NNN are created\n \"**/*.dist-info/RECORD\",\n \"BUILD\",\n \"WORKSPACE\",\n ]),\n # This makes this directory a top-level in the python import\n # search path for anything that depends on this.\n imports = [\".\"],\n)\n" - } - }, - "pypi__more_itertools": { - "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", - "attributes": { - "url": "https://files.pythonhosted.org/packages/50/e2/8e10e465ee3987bb7c9ab69efb91d867d93959095f4807db102d07995d94/more_itertools-10.2.0-py3-none-any.whl", - "sha256": "686b06abe565edfab151cb8fd385a05651e1fdf8f0a14191e4439283421f8684", - "type": "zip", - "build_file_content": "package(default_visibility = [\"//visibility:public\"])\n\nload(\"@rules_python//python:py_library.bzl\", \"py_library\")\n\npy_library(\n name = \"lib\",\n srcs = glob([\"**/*.py\"]),\n data = glob([\"**/*\"], exclude=[\n # These entries include those put into user-installed dependencies by\n # data_exclude to avoid non-determinism.\n \"**/*.py\",\n \"**/*.pyc\",\n \"**/*.pyc.*\", # During pyc creation, temp files named *.pyc.NNN are created\n \"**/*.dist-info/RECORD\",\n \"BUILD\",\n \"WORKSPACE\",\n ]),\n # This makes this directory a top-level in the python import\n # search path for anything that depends on this.\n imports = [\".\"],\n)\n" - } - }, - "pypi__packaging": { - "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", - "attributes": { - "url": "https://files.pythonhosted.org/packages/49/df/1fceb2f8900f8639e278b056416d49134fb8d84c5942ffaa01ad34782422/packaging-24.0-py3-none-any.whl", - "sha256": "2ddfb553fdf02fb784c234c7ba6ccc288296ceabec964ad2eae3777778130bc5", - "type": "zip", - "build_file_content": "package(default_visibility = [\"//visibility:public\"])\n\nload(\"@rules_python//python:py_library.bzl\", \"py_library\")\n\npy_library(\n name = \"lib\",\n srcs = glob([\"**/*.py\"]),\n data = glob([\"**/*\"], exclude=[\n # These entries include those put into user-installed dependencies by\n # data_exclude to avoid non-determinism.\n \"**/*.py\",\n \"**/*.pyc\",\n \"**/*.pyc.*\", # During pyc creation, temp files named *.pyc.NNN are created\n \"**/*.dist-info/RECORD\",\n \"BUILD\",\n \"WORKSPACE\",\n ]),\n # This makes this directory a top-level in the python import\n # search path for anything that depends on this.\n imports = [\".\"],\n)\n" - } - }, - "pypi__pep517": { - "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", - "attributes": { - "url": "https://files.pythonhosted.org/packages/25/6e/ca4a5434eb0e502210f591b97537d322546e4833dcb4d470a48c375c5540/pep517-0.13.1-py3-none-any.whl", - "sha256": "31b206f67165b3536dd577c5c3f1518e8fbaf38cbc57efff8369a392feff1721", - "type": "zip", - "build_file_content": "package(default_visibility = [\"//visibility:public\"])\n\nload(\"@rules_python//python:py_library.bzl\", \"py_library\")\n\npy_library(\n name = \"lib\",\n srcs = glob([\"**/*.py\"]),\n data = glob([\"**/*\"], exclude=[\n # These entries include those put into user-installed dependencies by\n # data_exclude to avoid non-determinism.\n \"**/*.py\",\n \"**/*.pyc\",\n \"**/*.pyc.*\", # During pyc creation, temp files named *.pyc.NNN are created\n \"**/*.dist-info/RECORD\",\n \"BUILD\",\n \"WORKSPACE\",\n ]),\n # This makes this directory a top-level in the python import\n # search path for anything that depends on this.\n imports = [\".\"],\n)\n" - } - }, - "pypi__pip": { - "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", - "attributes": { - "url": "https://files.pythonhosted.org/packages/8a/6a/19e9fe04fca059ccf770861c7d5721ab4c2aebc539889e97c7977528a53b/pip-24.0-py3-none-any.whl", - "sha256": "ba0d021a166865d2265246961bec0152ff124de910c5cc39f1156ce3fa7c69dc", - "type": "zip", - "build_file_content": "package(default_visibility = [\"//visibility:public\"])\n\nload(\"@rules_python//python:py_library.bzl\", \"py_library\")\n\npy_library(\n name = \"lib\",\n srcs = glob([\"**/*.py\"]),\n data = glob([\"**/*\"], exclude=[\n # These entries include those put into user-installed dependencies by\n # data_exclude to avoid non-determinism.\n \"**/*.py\",\n \"**/*.pyc\",\n \"**/*.pyc.*\", # During pyc creation, temp files named *.pyc.NNN are created\n \"**/*.dist-info/RECORD\",\n \"BUILD\",\n \"WORKSPACE\",\n ]),\n # This makes this directory a top-level in the python import\n # search path for anything that depends on this.\n imports = [\".\"],\n)\n" - } - }, - "pypi__pip_tools": { - "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", - "attributes": { - "url": "https://files.pythonhosted.org/packages/0d/dc/38f4ce065e92c66f058ea7a368a9c5de4e702272b479c0992059f7693941/pip_tools-7.4.1-py3-none-any.whl", - "sha256": "4c690e5fbae2f21e87843e89c26191f0d9454f362d8acdbd695716493ec8b3a9", - "type": "zip", - "build_file_content": "package(default_visibility = [\"//visibility:public\"])\n\nload(\"@rules_python//python:py_library.bzl\", \"py_library\")\n\npy_library(\n name = \"lib\",\n srcs = glob([\"**/*.py\"]),\n data = glob([\"**/*\"], exclude=[\n # These entries include those put into user-installed dependencies by\n # data_exclude to avoid non-determinism.\n \"**/*.py\",\n \"**/*.pyc\",\n \"**/*.pyc.*\", # During pyc creation, temp files named *.pyc.NNN are created\n \"**/*.dist-info/RECORD\",\n \"BUILD\",\n \"WORKSPACE\",\n ]),\n # This makes this directory a top-level in the python import\n # search path for anything that depends on this.\n imports = [\".\"],\n)\n" - } - }, - "pypi__pyproject_hooks": { - "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", - "attributes": { - "url": "https://files.pythonhosted.org/packages/ae/f3/431b9d5fe7d14af7a32340792ef43b8a714e7726f1d7b69cc4e8e7a3f1d7/pyproject_hooks-1.1.0-py3-none-any.whl", - "sha256": "7ceeefe9aec63a1064c18d939bdc3adf2d8aa1988a510afec15151578b232aa2", - "type": "zip", - "build_file_content": "package(default_visibility = [\"//visibility:public\"])\n\nload(\"@rules_python//python:py_library.bzl\", \"py_library\")\n\npy_library(\n name = \"lib\",\n srcs = glob([\"**/*.py\"]),\n data = glob([\"**/*\"], exclude=[\n # These entries include those put into user-installed dependencies by\n # data_exclude to avoid non-determinism.\n \"**/*.py\",\n \"**/*.pyc\",\n \"**/*.pyc.*\", # During pyc creation, temp files named *.pyc.NNN are created\n \"**/*.dist-info/RECORD\",\n \"BUILD\",\n \"WORKSPACE\",\n ]),\n # This makes this directory a top-level in the python import\n # search path for anything that depends on this.\n imports = [\".\"],\n)\n" - } - }, - "pypi__setuptools": { - "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", - "attributes": { - "url": "https://files.pythonhosted.org/packages/90/99/158ad0609729111163fc1f674a5a42f2605371a4cf036d0441070e2f7455/setuptools-78.1.1-py3-none-any.whl", - "sha256": "c3a9c4211ff4c309edb8b8c4f1cbfa7ae324c4ba9f91ff254e3d305b9fd54561", - "type": "zip", - "build_file_content": "package(default_visibility = [\"//visibility:public\"])\n\nload(\"@rules_python//python:py_library.bzl\", \"py_library\")\n\npy_library(\n name = \"lib\",\n srcs = glob([\"**/*.py\"]),\n data = glob([\"**/*\"], exclude=[\n # These entries include those put into user-installed dependencies by\n # data_exclude to avoid non-determinism.\n \"**/*.py\",\n \"**/*.pyc\",\n \"**/*.pyc.*\", # During pyc creation, temp files named *.pyc.NNN are created\n \"**/*.dist-info/RECORD\",\n \"BUILD\",\n \"WORKSPACE\",\n ]),\n # This makes this directory a top-level in the python import\n # search path for anything that depends on this.\n imports = [\".\"],\n)\n" - } - }, - "pypi__tomli": { - "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", - "attributes": { - "url": "https://files.pythonhosted.org/packages/97/75/10a9ebee3fd790d20926a90a2547f0bf78f371b2f13aa822c759680ca7b9/tomli-2.0.1-py3-none-any.whl", - "sha256": "939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc", - "type": "zip", - "build_file_content": "package(default_visibility = [\"//visibility:public\"])\n\nload(\"@rules_python//python:py_library.bzl\", \"py_library\")\n\npy_library(\n name = \"lib\",\n srcs = glob([\"**/*.py\"]),\n data = glob([\"**/*\"], exclude=[\n # These entries include those put into user-installed dependencies by\n # data_exclude to avoid non-determinism.\n \"**/*.py\",\n \"**/*.pyc\",\n \"**/*.pyc.*\", # During pyc creation, temp files named *.pyc.NNN are created\n \"**/*.dist-info/RECORD\",\n \"BUILD\",\n \"WORKSPACE\",\n ]),\n # This makes this directory a top-level in the python import\n # search path for anything that depends on this.\n imports = [\".\"],\n)\n" - } - }, - "pypi__wheel": { - "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", - "attributes": { - "url": "https://files.pythonhosted.org/packages/7d/cd/d7460c9a869b16c3dd4e1e403cce337df165368c71d6af229a74699622ce/wheel-0.43.0-py3-none-any.whl", - "sha256": "55c570405f142630c6b9f72fe09d9b67cf1477fcf543ae5b8dcb1f5b7377da81", - "type": "zip", - "build_file_content": "package(default_visibility = [\"//visibility:public\"])\n\nload(\"@rules_python//python:py_library.bzl\", \"py_library\")\n\npy_library(\n name = \"lib\",\n srcs = glob([\"**/*.py\"]),\n data = glob([\"**/*\"], exclude=[\n # These entries include those put into user-installed dependencies by\n # data_exclude to avoid non-determinism.\n \"**/*.py\",\n \"**/*.pyc\",\n \"**/*.pyc.*\", # During pyc creation, temp files named *.pyc.NNN are created\n \"**/*.dist-info/RECORD\",\n \"BUILD\",\n \"WORKSPACE\",\n ]),\n # This makes this directory a top-level in the python import\n # search path for anything that depends on this.\n imports = [\".\"],\n)\n" - } - }, - "pypi__zipp": { - "repoRuleId": "@@bazel_tools//tools/build_defs/repo:http.bzl%http_archive", - "attributes": { - "url": "https://files.pythonhosted.org/packages/da/55/a03fd7240714916507e1fcf7ae355bd9d9ed2e6db492595f1a67f61681be/zipp-3.18.2-py3-none-any.whl", - "sha256": "dce197b859eb796242b0622af1b8beb0a722d52aa2f57133ead08edd5bf5374e", - "type": "zip", - "build_file_content": "package(default_visibility = [\"//visibility:public\"])\n\nload(\"@rules_python//python:py_library.bzl\", \"py_library\")\n\npy_library(\n name = \"lib\",\n srcs = glob([\"**/*.py\"]),\n data = glob([\"**/*\"], exclude=[\n # These entries include those put into user-installed dependencies by\n # data_exclude to avoid non-determinism.\n \"**/*.py\",\n \"**/*.pyc\",\n \"**/*.pyc.*\", # During pyc creation, temp files named *.pyc.NNN are created\n \"**/*.dist-info/RECORD\",\n \"BUILD\",\n \"WORKSPACE\",\n ]),\n # This makes this directory a top-level in the python import\n # search path for anything that depends on this.\n imports = [\".\"],\n)\n" - } - } - } - } - }, "@@rules_python+//python/uv:uv.bzl%uv": { "general": { - "bzlTransitiveDigest": "IgkgxNrtlAec7OnaFrWoCC5NQhHcY/aIz4jsqcNMm8Y=", - "usagesDigest": "H8dQoNZcoqP+Mu0tHZTi4KHATzvNkM5ePuEqoQdklIU=", + "bzlTransitiveDigest": "/TRCIwkFYo7fpSOLJ54wXFHVpcYJ5edXrsPRRAmCrAg=", + "usagesDigest": "6MjoD3H+netDdhklgMWks3NARpHVXxy8kfsMe9XXPa8=", "recordedInputs": [ "REPO_MAPPING:rules_python+,bazel_tools bazel_tools", "REPO_MAPPING:rules_python+,platforms platforms" @@ -601,8 +396,8 @@ }, "@@rules_rust+//crate_universe:extensions.bzl%crate": { "general": { - "bzlTransitiveDigest": "ebJjXa+P6PCjLNy5r9Y6usOlasRE1po9acRzqmcTvxw=", - "usagesDigest": "elCpzqBbH4Uze4bFcJkhufozV4OiThsWRv8J+c9fLvo=", + "bzlTransitiveDigest": "ene+g3dYrnOOjWEZC1Xtdl3t9sbiC26hVGvSyn5XV3Y=", + "usagesDigest": "AkSzlYDag/ptRiPH/inccjoRKY8ur3ttcbzIxnSHNwo=", "recordedInputs": [ "ENV:CARGO_BAZEL_DEBUG \\0", "ENV:CARGO_BAZEL_GENERATOR_SHA256 \\0", @@ -624,18 +419,32 @@ "REPO_MAPPING:rules_rust+,bazel_skylib bazel_skylib+", "REPO_MAPPING:rules_rust+,bazel_tools bazel_tools", "REPO_MAPPING:rules_rust+,rules_cc rules_cc+", - "REPO_MAPPING:rules_rust+,rules_rust rules_rust+", - "FILE:@@//rust_client/Cargo.lock 45e22042b7cad45750e0f726584f76846d5b87e949aadfed8868a9f27241b44a", - "FILE:@@//rust_client/Cargo.toml 5414980602e0cf05daadeb63b34f308784b7be770934acd322306d5d0872794f" + "FILE:@@//rust_client/Cargo.lock 8f83a3561523d0117dfeeda15bb5d7b4aa55e2cf52ac7cf1094799b3566cc415", + "FILE:@@//rust_client/Cargo.toml 804677aaab469d36bff6e78fb0b54ea94c1da257d12ed8af53d84587349d353e" ], "generatedRepoSpecs": { "crates": { - "repoRuleId": "@@rules_rust+//crate_universe:extensions.bzl%_generate_repo", + "repoRuleId": "@@rules_rust+//crate_universe/private:crates_vendor.bzl%crates_vendor_remote_repository", "attributes": { "contents": { - "BUILD.bazel": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files(\n [\n \"cargo-bazel.json\",\n \"crates.bzl\",\n \"defs.bzl\",\n ] + glob(\n allow_empty = True,\n include = [\"*.bazel\"],\n ),\n)\n\nfilegroup(\n name = \"srcs\",\n srcs = glob(\n allow_empty = True,\n include = [\n \"*.bazel\",\n \"*.bzl\",\n ],\n ),\n)\n\n# Workspace Member Dependencies\nalias(\n name = \"libc-0.2.182\",\n actual = \"@crates__libc-0.2.182//:libc\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"libc\",\n actual = \"@crates__libc-0.2.182//:libc\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"log-0.4.29\",\n actual = \"@crates__log-0.4.29//:log\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"log\",\n actual = \"@crates__log-0.4.29//:log\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"nix-0.29.0\",\n actual = \"@crates__nix-0.29.0//:nix\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"nix\",\n actual = \"@crates__nix-0.29.0//:nix\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"prost-0.13.5\",\n actual = \"@crates__prost-0.13.5//:prost\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"prost\",\n actual = \"@crates__prost-0.13.5//:prost\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"prost-build-0.13.5\",\n actual = \"@crates__prost-build-0.13.5//:prost_build\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"prost-build\",\n actual = \"@crates__prost-build-0.13.5//:prost_build\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"prost-types-0.13.5\",\n actual = \"@crates__prost-types-0.13.5//:prost_types\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"prost-types\",\n actual = \"@crates__prost-types-0.13.5//:prost_types\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"subspace-client-2.2.0\",\n actual = \"@crates__subspace-client-2.2.0//:subspace_client\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"subspace-client\",\n actual = \"@crates__subspace-client-2.2.0//:subspace_client\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"thiserror-2.0.18\",\n actual = \"@crates__thiserror-2.0.18//:thiserror\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"thiserror\",\n actual = \"@crates__thiserror-2.0.18//:thiserror\",\n tags = [\"manual\"],\n)\n", + "BUILD.bazel": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\npackage(default_visibility = [\"//visibility:public\"])\n\nexports_files(\n [\n \"cargo-bazel.json\",\n \"crates.bzl\",\n \"defs.bzl\",\n ] + glob(\n allow_empty = True,\n include = [\"*.bazel\"],\n ),\n)\n\nfilegroup(\n name = \"srcs\",\n srcs = glob(\n allow_empty = True,\n include = [\n \"*.bazel\",\n \"*.bzl\",\n ],\n ),\n)\n\n# Workspace Member Dependencies\nalias(\n name = \"libc-0.2.182\",\n actual = \"@crates__libc-0.2.182//:libc\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"libc\",\n actual = \"@crates__libc-0.2.182//:libc\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"log-0.4.29\",\n actual = \"@crates__log-0.4.29//:log\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"log\",\n actual = \"@crates__log-0.4.29//:log\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"nix-0.29.0\",\n actual = \"@crates__nix-0.29.0//:nix\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"nix\",\n actual = \"@crates__nix-0.29.0//:nix\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"prost-0.13.5\",\n actual = \"@crates__prost-0.13.5//:prost\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"prost\",\n actual = \"@crates__prost-0.13.5//:prost\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"prost-build-0.13.5\",\n actual = \"@crates__prost-build-0.13.5//:prost_build\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"prost-build\",\n actual = \"@crates__prost-build-0.13.5//:prost_build\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"prost-types-0.13.5\",\n actual = \"@crates__prost-types-0.13.5//:prost_types\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"prost-types\",\n actual = \"@crates__prost-types-0.13.5//:prost_types\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"thiserror-2.0.18\",\n actual = \"@crates__thiserror-2.0.18//:thiserror\",\n tags = [\"manual\"],\n)\n\nalias(\n name = \"thiserror\",\n actual = \"@crates__thiserror-2.0.18//:thiserror\",\n tags = [\"manual\"],\n)\n", "alias_rules.bzl": "\"\"\"Alias that transitions its target to `compilation_mode=opt`. Use `transition_alias=\"opt\"` to enable.\"\"\"\n\nload(\"@rules_cc//cc:defs.bzl\", \"CcInfo\")\nload(\"@rules_rust//rust:rust_common.bzl\", \"COMMON_PROVIDERS\")\n\ndef _transition_alias_impl(ctx):\n # `ctx.attr.actual` is a list of 1 item due to the transition\n providers = [ctx.attr.actual[0][provider] for provider in COMMON_PROVIDERS]\n if CcInfo in ctx.attr.actual[0]:\n providers.append(ctx.attr.actual[0][CcInfo])\n return providers\n\ndef _change_compilation_mode(compilation_mode):\n def _change_compilation_mode_impl(_settings, _attr):\n return {\n \"//command_line_option:compilation_mode\": compilation_mode,\n }\n\n return transition(\n implementation = _change_compilation_mode_impl,\n inputs = [],\n outputs = [\n \"//command_line_option:compilation_mode\",\n ],\n )\n\ndef _transition_alias_rule(compilation_mode):\n return rule(\n implementation = _transition_alias_impl,\n provides = COMMON_PROVIDERS,\n attrs = {\n \"actual\": attr.label(\n mandatory = True,\n doc = \"`rust_library()` target to transition to `compilation_mode=opt`.\",\n providers = COMMON_PROVIDERS,\n cfg = _change_compilation_mode(compilation_mode),\n ),\n \"_allowlist_function_transition\": attr.label(\n default = \"@bazel_tools//tools/allowlists/function_transition_allowlist\",\n ),\n },\n doc = \"Transitions a Rust library crate to the `compilation_mode=opt`.\",\n )\n\ntransition_alias_dbg = _transition_alias_rule(\"dbg\")\ntransition_alias_fastbuild = _transition_alias_rule(\"fastbuild\")\ntransition_alias_opt = _transition_alias_rule(\"opt\")\n", - "defs.bzl": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\"\"\"\n# `crates_repository` API\n\n- [aliases](#aliases)\n- [crate_deps](#crate_deps)\n- [all_crate_deps](#all_crate_deps)\n- [crate_repositories](#crate_repositories)\n\n\"\"\"\n\nload(\"@bazel_tools//tools/build_defs/repo:git.bzl\", \"new_git_repository\")\nload(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\nload(\"@bazel_tools//tools/build_defs/repo:utils.bzl\", \"maybe\")\nload(\"@bazel_skylib//lib:selects.bzl\", \"selects\")\nload(\"@rules_rust//crate_universe/private:local_crate_mirror.bzl\", \"local_crate_mirror\")\n\n###############################################################################\n# MACROS API\n###############################################################################\n\n# An identifier that represent common dependencies (unconditional).\n_COMMON_CONDITION = \"\"\n\ndef _flatten_dependency_maps(all_dependency_maps):\n \"\"\"Flatten a list of dependency maps into one dictionary.\n\n Dependency maps have the following structure:\n\n ```python\n DEPENDENCIES_MAP = {\n # The first key in the map is a Bazel package\n # name of the workspace this file is defined in.\n \"workspace_member_package\": {\n\n # Not all dependencies are supported for all platforms.\n # the condition key is the condition required to be true\n # on the host platform.\n \"condition\": {\n\n # An alias to a crate target. # The label of the crate target the\n # Aliases are only crate names. # package name refers to.\n \"package_name\": \"@full//:label\",\n }\n }\n }\n ```\n\n Args:\n all_dependency_maps (list): A list of dicts as described above\n\n Returns:\n dict: A dictionary as described above\n \"\"\"\n dependencies = {}\n\n for workspace_deps_map in all_dependency_maps:\n for pkg_name, conditional_deps_map in workspace_deps_map.items():\n if pkg_name not in dependencies:\n non_frozen_map = dict()\n for key, values in conditional_deps_map.items():\n non_frozen_map.update({key: dict(values.items())})\n dependencies.setdefault(pkg_name, non_frozen_map)\n continue\n\n for condition, deps_map in conditional_deps_map.items():\n # If the condition has not been recorded, do so and continue\n if condition not in dependencies[pkg_name]:\n dependencies[pkg_name].setdefault(condition, dict(deps_map.items()))\n continue\n\n # Alert on any miss-matched dependencies\n inconsistent_entries = []\n for crate_name, crate_label in deps_map.items():\n existing = dependencies[pkg_name][condition].get(crate_name)\n if existing and existing != crate_label:\n inconsistent_entries.append((crate_name, existing, crate_label))\n dependencies[pkg_name][condition].update({crate_name: crate_label})\n\n return dependencies\n\ndef crate_deps(deps, package_name = None):\n \"\"\"Finds the fully qualified label of the requested crates for the package where this macro is called.\n\n Args:\n deps (list): The desired list of crate targets.\n package_name (str, optional): The package name of the set of dependencies to look up.\n Defaults to `native.package_name()`.\n\n Returns:\n list: A list of labels to generated rust targets (str)\n \"\"\"\n\n if not deps:\n return []\n\n if package_name == None:\n package_name = native.package_name()\n\n # Join both sets of dependencies\n dependencies = _flatten_dependency_maps([\n _NORMAL_DEPENDENCIES,\n _NORMAL_DEV_DEPENDENCIES,\n _PROC_MACRO_DEPENDENCIES,\n _PROC_MACRO_DEV_DEPENDENCIES,\n _BUILD_DEPENDENCIES,\n _BUILD_PROC_MACRO_DEPENDENCIES,\n ]).pop(package_name, {})\n\n # Combine all conditional packages so we can easily index over a flat list\n # TODO: Perhaps this should actually return select statements and maintain\n # the conditionals of the dependencies\n flat_deps = {}\n for deps_set in dependencies.values():\n for crate_name, crate_label in deps_set.items():\n flat_deps.update({crate_name: crate_label})\n\n missing_crates = []\n crate_targets = []\n for crate_target in deps:\n if crate_target not in flat_deps:\n missing_crates.append(crate_target)\n else:\n crate_targets.append(flat_deps[crate_target])\n\n if missing_crates:\n fail(\"Could not find crates `{}` among dependencies of `{}`. Available dependencies were `{}`\".format(\n missing_crates,\n package_name,\n dependencies,\n ))\n\n return crate_targets\n\ndef all_crate_deps(\n normal = False, \n normal_dev = False, \n proc_macro = False, \n proc_macro_dev = False,\n build = False,\n build_proc_macro = False,\n package_name = None):\n \"\"\"Finds the fully qualified label of all requested direct crate dependencies \\\n for the package where this macro is called.\n\n If no parameters are set, all normal dependencies are returned. Setting any one flag will\n otherwise impact the contents of the returned list.\n\n Args:\n normal (bool, optional): If True, normal dependencies are included in the\n output list.\n normal_dev (bool, optional): If True, normal dev dependencies will be\n included in the output list..\n proc_macro (bool, optional): If True, proc_macro dependencies are included\n in the output list.\n proc_macro_dev (bool, optional): If True, dev proc_macro dependencies are\n included in the output list.\n build (bool, optional): If True, build dependencies are included\n in the output list.\n build_proc_macro (bool, optional): If True, build proc_macro dependencies are\n included in the output list.\n package_name (str, optional): The package name of the set of dependencies to look up.\n Defaults to `native.package_name()` when unset.\n\n Returns:\n list: A list of labels to generated rust targets (str)\n \"\"\"\n\n if package_name == None:\n package_name = native.package_name()\n\n # Determine the relevant maps to use\n all_dependency_maps = []\n if normal:\n all_dependency_maps.append(_NORMAL_DEPENDENCIES)\n if normal_dev:\n all_dependency_maps.append(_NORMAL_DEV_DEPENDENCIES)\n if proc_macro:\n all_dependency_maps.append(_PROC_MACRO_DEPENDENCIES)\n if proc_macro_dev:\n all_dependency_maps.append(_PROC_MACRO_DEV_DEPENDENCIES)\n if build:\n all_dependency_maps.append(_BUILD_DEPENDENCIES)\n if build_proc_macro:\n all_dependency_maps.append(_BUILD_PROC_MACRO_DEPENDENCIES)\n\n # Default to always using normal dependencies\n if not all_dependency_maps:\n all_dependency_maps.append(_NORMAL_DEPENDENCIES)\n\n dependencies = _flatten_dependency_maps(all_dependency_maps).pop(package_name, None)\n\n if not dependencies:\n if dependencies == None:\n fail(\"Tried to get all_crate_deps for package \" + package_name + \" but that package had no Cargo.toml file\")\n else:\n return []\n\n crate_deps = list(dependencies.pop(_COMMON_CONDITION, {}).values())\n for condition, deps in dependencies.items():\n crate_deps += selects.with_or({\n tuple(_CONDITIONS[condition]): deps.values(),\n \"//conditions:default\": [],\n })\n\n return crate_deps\n\ndef aliases(\n normal = False,\n normal_dev = False,\n proc_macro = False,\n proc_macro_dev = False,\n build = False,\n build_proc_macro = False,\n package_name = None):\n \"\"\"Produces a map of Crate alias names to their original label\n\n If no dependency kinds are specified, `normal` and `proc_macro` are used by default.\n Setting any one flag will otherwise determine the contents of the returned dict.\n\n Args:\n normal (bool, optional): If True, normal dependencies are included in the\n output list.\n normal_dev (bool, optional): If True, normal dev dependencies will be\n included in the output list..\n proc_macro (bool, optional): If True, proc_macro dependencies are included\n in the output list.\n proc_macro_dev (bool, optional): If True, dev proc_macro dependencies are\n included in the output list.\n build (bool, optional): If True, build dependencies are included\n in the output list.\n build_proc_macro (bool, optional): If True, build proc_macro dependencies are\n included in the output list.\n package_name (str, optional): The package name of the set of dependencies to look up.\n Defaults to `native.package_name()` when unset.\n\n Returns:\n dict: The aliases of all associated packages\n \"\"\"\n if package_name == None:\n package_name = native.package_name()\n\n # Determine the relevant maps to use\n all_aliases_maps = []\n if normal:\n all_aliases_maps.append(_NORMAL_ALIASES)\n if normal_dev:\n all_aliases_maps.append(_NORMAL_DEV_ALIASES)\n if proc_macro:\n all_aliases_maps.append(_PROC_MACRO_ALIASES)\n if proc_macro_dev:\n all_aliases_maps.append(_PROC_MACRO_DEV_ALIASES)\n if build:\n all_aliases_maps.append(_BUILD_ALIASES)\n if build_proc_macro:\n all_aliases_maps.append(_BUILD_PROC_MACRO_ALIASES)\n\n # Default to always using normal aliases\n if not all_aliases_maps:\n all_aliases_maps.append(_NORMAL_ALIASES)\n all_aliases_maps.append(_PROC_MACRO_ALIASES)\n\n aliases = _flatten_dependency_maps(all_aliases_maps).pop(package_name, None)\n\n if not aliases:\n return dict()\n\n common_items = aliases.pop(_COMMON_CONDITION, {}).items()\n\n # If there are only common items in the dictionary, immediately return them\n if not len(aliases.keys()) == 1:\n return dict(common_items)\n\n # Build a single select statement where each conditional has accounted for the\n # common set of aliases.\n crate_aliases = {\"//conditions:default\": dict(common_items)}\n for condition, deps in aliases.items():\n condition_triples = _CONDITIONS[condition]\n for triple in condition_triples:\n if triple in crate_aliases:\n crate_aliases[triple].update(deps)\n else:\n crate_aliases.update({triple: dict(deps.items() + common_items)})\n\n return select(crate_aliases)\n\n###############################################################################\n# WORKSPACE MEMBER DEPS AND ALIASES\n###############################################################################\n\n_NORMAL_DEPENDENCIES = {\n \"rust_client\": {\n _COMMON_CONDITION: {\n \"libc\": Label(\"@crates//:libc-0.2.182\"),\n \"log\": Label(\"@crates//:log-0.4.29\"),\n \"nix\": Label(\"@crates//:nix-0.29.0\"),\n \"prost\": Label(\"@crates//:prost-0.13.5\"),\n \"prost-types\": Label(\"@crates//:prost-types-0.13.5\"),\n \"thiserror\": Label(\"@crates//:thiserror-2.0.18\"),\n },\n },\n}\n\n\n_NORMAL_ALIASES = {\n \"rust_client\": {\n _COMMON_CONDITION: {\n },\n },\n}\n\n\n_NORMAL_DEV_DEPENDENCIES = {\n \"rust_client\": {\n },\n}\n\n\n_NORMAL_DEV_ALIASES = {\n \"rust_client\": {\n },\n}\n\n\n_PROC_MACRO_DEPENDENCIES = {\n \"rust_client\": {\n },\n}\n\n\n_PROC_MACRO_ALIASES = {\n \"rust_client\": {\n },\n}\n\n\n_PROC_MACRO_DEV_DEPENDENCIES = {\n \"rust_client\": {\n },\n}\n\n\n_PROC_MACRO_DEV_ALIASES = {\n \"rust_client\": {\n },\n}\n\n\n_BUILD_DEPENDENCIES = {\n \"rust_client\": {\n _COMMON_CONDITION: {\n \"prost-build\": Label(\"@crates//:prost-build-0.13.5\"),\n },\n },\n}\n\n\n_BUILD_ALIASES = {\n \"rust_client\": {\n _COMMON_CONDITION: {\n },\n },\n}\n\n\n_BUILD_PROC_MACRO_DEPENDENCIES = {\n \"rust_client\": {\n },\n}\n\n\n_BUILD_PROC_MACRO_ALIASES = {\n \"rust_client\": {\n },\n}\n\n\n_CONDITIONS = {\n \"aarch64-apple-darwin\": [\"@rules_rust//rust/platform:aarch64-apple-darwin\"],\n \"aarch64-unknown-linux-gnu\": [\"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\"],\n \"cfg(all(any(target_os = \\\"linux\\\", target_os = \\\"android\\\"), any(rustix_use_libc, miri, not(all(target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", any(target_arch = \\\"s390x\\\", target_arch = \\\"powerpc\\\")), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc\\\"), all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\")))))))\": [],\n \"cfg(all(any(target_os = \\\"linux\\\", target_os = \\\"android\\\"), not(any(all(target_os = \\\"linux\\\", target_env = \\\"\\\"), getrandom_backend = \\\"custom\\\", getrandom_backend = \\\"linux_raw\\\", getrandom_backend = \\\"rdrand\\\", getrandom_backend = \\\"rndr\\\"))))\": [\"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\",\"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\",\"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\"],\n \"cfg(all(not(rustix_use_libc), not(miri), target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", any(target_arch = \\\"s390x\\\", target_arch = \\\"powerpc\\\")), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc\\\"), all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\"))))\": [\"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\",\"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\",\"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\"],\n \"cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", any(target_arch = \\\"s390x\\\", target_arch = \\\"powerpc\\\")), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc\\\"), all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\")))))))\": [\"@rules_rust//rust/platform:aarch64-apple-darwin\",\"@rules_rust//rust/platform:wasm32-unknown-unknown\",\"@rules_rust//rust/platform:wasm32-wasip1\"],\n \"cfg(all(target_arch = \\\"wasm32\\\", target_os = \\\"wasi\\\", target_env = \\\"p2\\\"))\": [],\n \"cfg(all(target_arch = \\\"wasm32\\\", target_os = \\\"wasi\\\", target_env = \\\"p3\\\"))\": [],\n \"cfg(all(target_os = \\\"uefi\\\", getrandom_backend = \\\"efi_rng\\\"))\": [],\n \"cfg(any())\": [],\n \"cfg(any(target_os = \\\"dragonfly\\\", target_os = \\\"freebsd\\\", target_os = \\\"hurd\\\", target_os = \\\"illumos\\\", target_os = \\\"cygwin\\\", all(target_os = \\\"horizon\\\", target_arch = \\\"arm\\\")))\": [],\n \"cfg(any(target_os = \\\"haiku\\\", target_os = \\\"redox\\\", target_os = \\\"nto\\\", target_os = \\\"aix\\\"))\": [],\n \"cfg(any(target_os = \\\"ios\\\", target_os = \\\"visionos\\\", target_os = \\\"watchos\\\", target_os = \\\"tvos\\\"))\": [],\n \"cfg(any(target_os = \\\"macos\\\", target_os = \\\"openbsd\\\", target_os = \\\"vita\\\", target_os = \\\"emscripten\\\"))\": [\"@rules_rust//rust/platform:aarch64-apple-darwin\"],\n \"cfg(any(unix, target_os = \\\"wasi\\\"))\": [\"@rules_rust//rust/platform:aarch64-apple-darwin\",\"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\",\"@rules_rust//rust/platform:wasm32-wasip1\",\"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\",\"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\"],\n \"cfg(target_os = \\\"hermit\\\")\": [],\n \"cfg(target_os = \\\"netbsd\\\")\": [],\n \"cfg(target_os = \\\"solaris\\\")\": [],\n \"cfg(target_os = \\\"vxworks\\\")\": [],\n \"cfg(target_os = \\\"wasi\\\")\": [\"@rules_rust//rust/platform:wasm32-wasip1\"],\n \"cfg(unix)\": [\"@rules_rust//rust/platform:aarch64-apple-darwin\",\"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\",\"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\",\"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\"],\n \"cfg(windows)\": [\"@rules_rust//rust/platform:x86_64-pc-windows-msvc\"],\n \"wasm32-unknown-unknown\": [\"@rules_rust//rust/platform:wasm32-unknown-unknown\"],\n \"wasm32-wasip1\": [\"@rules_rust//rust/platform:wasm32-wasip1\"],\n \"x86_64-pc-windows-msvc\": [\"@rules_rust//rust/platform:x86_64-pc-windows-msvc\"],\n \"x86_64-unknown-linux-gnu\": [\"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\"],\n \"x86_64-unknown-nixos-gnu\": [\"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\"],\n}\n\n###############################################################################\n\ndef crate_repositories():\n \"\"\"A macro for defining repositories for all generated crates.\n\n Returns:\n A list of repos visible to the module through the module extension.\n \"\"\"\n maybe(\n http_archive,\n name = \"crates__aho-corasick-1.1.4\",\n sha256 = \"ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/aho-corasick/1.1.4/download\"],\n strip_prefix = \"aho-corasick-1.1.4\",\n build_file = Label(\"@crates//crates:BUILD.aho-corasick-1.1.4.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__anyhow-1.0.101\",\n sha256 = \"5f0e0fee31ef5ed1ba1316088939cea399010ed7731dba877ed44aeb407a75ea\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/anyhow/1.0.101/download\"],\n strip_prefix = \"anyhow-1.0.101\",\n build_file = Label(\"@crates//crates:BUILD.anyhow-1.0.101.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__autocfg-1.5.0\",\n sha256 = \"c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/autocfg/1.5.0/download\"],\n strip_prefix = \"autocfg-1.5.0\",\n build_file = Label(\"@crates//crates:BUILD.autocfg-1.5.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__bitflags-2.11.0\",\n sha256 = \"843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/bitflags/2.11.0/download\"],\n strip_prefix = \"bitflags-2.11.0\",\n build_file = Label(\"@crates//crates:BUILD.bitflags-2.11.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__bytes-1.11.1\",\n sha256 = \"1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/bytes/1.11.1/download\"],\n strip_prefix = \"bytes-1.11.1\",\n build_file = Label(\"@crates//crates:BUILD.bytes-1.11.1.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__cfg-if-1.0.4\",\n sha256 = \"9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/cfg-if/1.0.4/download\"],\n strip_prefix = \"cfg-if-1.0.4\",\n build_file = Label(\"@crates//crates:BUILD.cfg-if-1.0.4.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__cfg_aliases-0.2.1\",\n sha256 = \"613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/cfg_aliases/0.2.1/download\"],\n strip_prefix = \"cfg_aliases-0.2.1\",\n build_file = Label(\"@crates//crates:BUILD.cfg_aliases-0.2.1.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__either-1.15.0\",\n sha256 = \"48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/either/1.15.0/download\"],\n strip_prefix = \"either-1.15.0\",\n build_file = Label(\"@crates//crates:BUILD.either-1.15.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__equivalent-1.0.2\",\n sha256 = \"877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/equivalent/1.0.2/download\"],\n strip_prefix = \"equivalent-1.0.2\",\n build_file = Label(\"@crates//crates:BUILD.equivalent-1.0.2.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__errno-0.3.14\",\n sha256 = \"39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/errno/0.3.14/download\"],\n strip_prefix = \"errno-0.3.14\",\n build_file = Label(\"@crates//crates:BUILD.errno-0.3.14.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__fastrand-2.3.0\",\n sha256 = \"37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/fastrand/2.3.0/download\"],\n strip_prefix = \"fastrand-2.3.0\",\n build_file = Label(\"@crates//crates:BUILD.fastrand-2.3.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__fixedbitset-0.5.7\",\n sha256 = \"1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/fixedbitset/0.5.7/download\"],\n strip_prefix = \"fixedbitset-0.5.7\",\n build_file = Label(\"@crates//crates:BUILD.fixedbitset-0.5.7.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__foldhash-0.1.5\",\n sha256 = \"d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/foldhash/0.1.5/download\"],\n strip_prefix = \"foldhash-0.1.5\",\n build_file = Label(\"@crates//crates:BUILD.foldhash-0.1.5.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__getrandom-0.4.1\",\n sha256 = \"139ef39800118c7683f2fd3c98c1b23c09ae076556b435f8e9064ae108aaeeec\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/getrandom/0.4.1/download\"],\n strip_prefix = \"getrandom-0.4.1\",\n build_file = Label(\"@crates//crates:BUILD.getrandom-0.4.1.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__hashbrown-0.15.5\",\n sha256 = \"9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/hashbrown/0.15.5/download\"],\n strip_prefix = \"hashbrown-0.15.5\",\n build_file = Label(\"@crates//crates:BUILD.hashbrown-0.15.5.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__hashbrown-0.16.1\",\n sha256 = \"841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/hashbrown/0.16.1/download\"],\n strip_prefix = \"hashbrown-0.16.1\",\n build_file = Label(\"@crates//crates:BUILD.hashbrown-0.16.1.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__heck-0.5.0\",\n sha256 = \"2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/heck/0.5.0/download\"],\n strip_prefix = \"heck-0.5.0\",\n build_file = Label(\"@crates//crates:BUILD.heck-0.5.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__id-arena-2.3.0\",\n sha256 = \"3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/id-arena/2.3.0/download\"],\n strip_prefix = \"id-arena-2.3.0\",\n build_file = Label(\"@crates//crates:BUILD.id-arena-2.3.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__indexmap-2.13.0\",\n sha256 = \"7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/indexmap/2.13.0/download\"],\n strip_prefix = \"indexmap-2.13.0\",\n build_file = Label(\"@crates//crates:BUILD.indexmap-2.13.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__itertools-0.14.0\",\n sha256 = \"2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/itertools/0.14.0/download\"],\n strip_prefix = \"itertools-0.14.0\",\n build_file = Label(\"@crates//crates:BUILD.itertools-0.14.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__itoa-1.0.17\",\n sha256 = \"92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/itoa/1.0.17/download\"],\n strip_prefix = \"itoa-1.0.17\",\n build_file = Label(\"@crates//crates:BUILD.itoa-1.0.17.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__leb128fmt-0.1.0\",\n sha256 = \"09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/leb128fmt/0.1.0/download\"],\n strip_prefix = \"leb128fmt-0.1.0\",\n build_file = Label(\"@crates//crates:BUILD.leb128fmt-0.1.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__libc-0.2.182\",\n sha256 = \"6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/libc/0.2.182/download\"],\n strip_prefix = \"libc-0.2.182\",\n build_file = Label(\"@crates//crates:BUILD.libc-0.2.182.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__linux-raw-sys-0.11.0\",\n sha256 = \"df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/linux-raw-sys/0.11.0/download\"],\n strip_prefix = \"linux-raw-sys-0.11.0\",\n build_file = Label(\"@crates//crates:BUILD.linux-raw-sys-0.11.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__log-0.4.29\",\n sha256 = \"5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/log/0.4.29/download\"],\n strip_prefix = \"log-0.4.29\",\n build_file = Label(\"@crates//crates:BUILD.log-0.4.29.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__memchr-2.8.0\",\n sha256 = \"f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/memchr/2.8.0/download\"],\n strip_prefix = \"memchr-2.8.0\",\n build_file = Label(\"@crates//crates:BUILD.memchr-2.8.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__memoffset-0.9.1\",\n sha256 = \"488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/memoffset/0.9.1/download\"],\n strip_prefix = \"memoffset-0.9.1\",\n build_file = Label(\"@crates//crates:BUILD.memoffset-0.9.1.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__multimap-0.10.1\",\n sha256 = \"1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/multimap/0.10.1/download\"],\n strip_prefix = \"multimap-0.10.1\",\n build_file = Label(\"@crates//crates:BUILD.multimap-0.10.1.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__nix-0.29.0\",\n sha256 = \"71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/nix/0.29.0/download\"],\n strip_prefix = \"nix-0.29.0\",\n build_file = Label(\"@crates//crates:BUILD.nix-0.29.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__once_cell-1.21.3\",\n sha256 = \"42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/once_cell/1.21.3/download\"],\n strip_prefix = \"once_cell-1.21.3\",\n build_file = Label(\"@crates//crates:BUILD.once_cell-1.21.3.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__petgraph-0.7.1\",\n sha256 = \"3672b37090dbd86368a4145bc067582552b29c27377cad4e0a306c97f9bd7772\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/petgraph/0.7.1/download\"],\n strip_prefix = \"petgraph-0.7.1\",\n build_file = Label(\"@crates//crates:BUILD.petgraph-0.7.1.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__prettyplease-0.2.37\",\n sha256 = \"479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/prettyplease/0.2.37/download\"],\n strip_prefix = \"prettyplease-0.2.37\",\n build_file = Label(\"@crates//crates:BUILD.prettyplease-0.2.37.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__proc-macro2-1.0.106\",\n sha256 = \"8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/proc-macro2/1.0.106/download\"],\n strip_prefix = \"proc-macro2-1.0.106\",\n build_file = Label(\"@crates//crates:BUILD.proc-macro2-1.0.106.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__prost-0.13.5\",\n sha256 = \"2796faa41db3ec313a31f7624d9286acf277b52de526150b7e69f3debf891ee5\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/prost/0.13.5/download\"],\n strip_prefix = \"prost-0.13.5\",\n build_file = Label(\"@crates//crates:BUILD.prost-0.13.5.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__prost-build-0.13.5\",\n sha256 = \"be769465445e8c1474e9c5dac2018218498557af32d9ed057325ec9a41ae81bf\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/prost-build/0.13.5/download\"],\n strip_prefix = \"prost-build-0.13.5\",\n build_file = Label(\"@crates//crates:BUILD.prost-build-0.13.5.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__prost-derive-0.13.5\",\n sha256 = \"8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/prost-derive/0.13.5/download\"],\n strip_prefix = \"prost-derive-0.13.5\",\n build_file = Label(\"@crates//crates:BUILD.prost-derive-0.13.5.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__prost-types-0.13.5\",\n sha256 = \"52c2c1bf36ddb1a1c396b3601a3cec27c2462e45f07c386894ec3ccf5332bd16\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/prost-types/0.13.5/download\"],\n strip_prefix = \"prost-types-0.13.5\",\n build_file = Label(\"@crates//crates:BUILD.prost-types-0.13.5.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__quote-1.0.44\",\n sha256 = \"21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/quote/1.0.44/download\"],\n strip_prefix = \"quote-1.0.44\",\n build_file = Label(\"@crates//crates:BUILD.quote-1.0.44.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__r-efi-5.3.0\",\n sha256 = \"69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/r-efi/5.3.0/download\"],\n strip_prefix = \"r-efi-5.3.0\",\n build_file = Label(\"@crates//crates:BUILD.r-efi-5.3.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__regex-1.12.3\",\n sha256 = \"e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/regex/1.12.3/download\"],\n strip_prefix = \"regex-1.12.3\",\n build_file = Label(\"@crates//crates:BUILD.regex-1.12.3.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__regex-automata-0.4.14\",\n sha256 = \"6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/regex-automata/0.4.14/download\"],\n strip_prefix = \"regex-automata-0.4.14\",\n build_file = Label(\"@crates//crates:BUILD.regex-automata-0.4.14.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__regex-syntax-0.8.9\",\n sha256 = \"a96887878f22d7bad8a3b6dc5b7440e0ada9a245242924394987b21cf2210a4c\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/regex-syntax/0.8.9/download\"],\n strip_prefix = \"regex-syntax-0.8.9\",\n build_file = Label(\"@crates//crates:BUILD.regex-syntax-0.8.9.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__rustix-1.1.3\",\n sha256 = \"146c9e247ccc180c1f61615433868c99f3de3ae256a30a43b49f67c2d9171f34\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/rustix/1.1.3/download\"],\n strip_prefix = \"rustix-1.1.3\",\n build_file = Label(\"@crates//crates:BUILD.rustix-1.1.3.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__semver-1.0.27\",\n sha256 = \"d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/semver/1.0.27/download\"],\n strip_prefix = \"semver-1.0.27\",\n build_file = Label(\"@crates//crates:BUILD.semver-1.0.27.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__serde-1.0.228\",\n sha256 = \"9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/serde/1.0.228/download\"],\n strip_prefix = \"serde-1.0.228\",\n build_file = Label(\"@crates//crates:BUILD.serde-1.0.228.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__serde_core-1.0.228\",\n sha256 = \"41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/serde_core/1.0.228/download\"],\n strip_prefix = \"serde_core-1.0.228\",\n build_file = Label(\"@crates//crates:BUILD.serde_core-1.0.228.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__serde_derive-1.0.228\",\n sha256 = \"d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/serde_derive/1.0.228/download\"],\n strip_prefix = \"serde_derive-1.0.228\",\n build_file = Label(\"@crates//crates:BUILD.serde_derive-1.0.228.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__serde_json-1.0.149\",\n sha256 = \"83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/serde_json/1.0.149/download\"],\n strip_prefix = \"serde_json-1.0.149\",\n build_file = Label(\"@crates//crates:BUILD.serde_json-1.0.149.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__syn-2.0.116\",\n sha256 = \"3df424c70518695237746f84cede799c9c58fcb37450d7b23716568cc8bc69cb\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/syn/2.0.116/download\"],\n strip_prefix = \"syn-2.0.116\",\n build_file = Label(\"@crates//crates:BUILD.syn-2.0.116.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__tempfile-3.25.0\",\n sha256 = \"0136791f7c95b1f6dd99f9cc786b91bb81c3800b639b3478e561ddb7be95e5f1\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/tempfile/3.25.0/download\"],\n strip_prefix = \"tempfile-3.25.0\",\n build_file = Label(\"@crates//crates:BUILD.tempfile-3.25.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__thiserror-2.0.18\",\n sha256 = \"4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/thiserror/2.0.18/download\"],\n strip_prefix = \"thiserror-2.0.18\",\n build_file = Label(\"@crates//crates:BUILD.thiserror-2.0.18.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__thiserror-impl-2.0.18\",\n sha256 = \"ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/thiserror-impl/2.0.18/download\"],\n strip_prefix = \"thiserror-impl-2.0.18\",\n build_file = Label(\"@crates//crates:BUILD.thiserror-impl-2.0.18.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__unicode-ident-1.0.24\",\n sha256 = \"e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/unicode-ident/1.0.24/download\"],\n strip_prefix = \"unicode-ident-1.0.24\",\n build_file = Label(\"@crates//crates:BUILD.unicode-ident-1.0.24.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__unicode-xid-0.2.6\",\n sha256 = \"ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/unicode-xid/0.2.6/download\"],\n strip_prefix = \"unicode-xid-0.2.6\",\n build_file = Label(\"@crates//crates:BUILD.unicode-xid-0.2.6.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__wasip2-1.0.2-wasi-0.2.9\",\n sha256 = \"9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/wasip2/1.0.2+wasi-0.2.9/download\"],\n strip_prefix = \"wasip2-1.0.2+wasi-0.2.9\",\n build_file = Label(\"@crates//crates:BUILD.wasip2-1.0.2+wasi-0.2.9.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__wasip3-0.4.0-wasi-0.3.0-rc-2026-01-06\",\n sha256 = \"5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/wasip3/0.4.0+wasi-0.3.0-rc-2026-01-06/download\"],\n strip_prefix = \"wasip3-0.4.0+wasi-0.3.0-rc-2026-01-06\",\n build_file = Label(\"@crates//crates:BUILD.wasip3-0.4.0+wasi-0.3.0-rc-2026-01-06.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__wasm-encoder-0.244.0\",\n sha256 = \"990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/wasm-encoder/0.244.0/download\"],\n strip_prefix = \"wasm-encoder-0.244.0\",\n build_file = Label(\"@crates//crates:BUILD.wasm-encoder-0.244.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__wasm-metadata-0.244.0\",\n sha256 = \"bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/wasm-metadata/0.244.0/download\"],\n strip_prefix = \"wasm-metadata-0.244.0\",\n build_file = Label(\"@crates//crates:BUILD.wasm-metadata-0.244.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__wasmparser-0.244.0\",\n sha256 = \"47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/wasmparser/0.244.0/download\"],\n strip_prefix = \"wasmparser-0.244.0\",\n build_file = Label(\"@crates//crates:BUILD.wasmparser-0.244.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__windows-link-0.2.1\",\n sha256 = \"f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/windows-link/0.2.1/download\"],\n strip_prefix = \"windows-link-0.2.1\",\n build_file = Label(\"@crates//crates:BUILD.windows-link-0.2.1.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__windows-sys-0.61.2\",\n sha256 = \"ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/windows-sys/0.61.2/download\"],\n strip_prefix = \"windows-sys-0.61.2\",\n build_file = Label(\"@crates//crates:BUILD.windows-sys-0.61.2.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__wit-bindgen-0.51.0\",\n sha256 = \"d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/wit-bindgen/0.51.0/download\"],\n strip_prefix = \"wit-bindgen-0.51.0\",\n build_file = Label(\"@crates//crates:BUILD.wit-bindgen-0.51.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__wit-bindgen-core-0.51.0\",\n sha256 = \"ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/wit-bindgen-core/0.51.0/download\"],\n strip_prefix = \"wit-bindgen-core-0.51.0\",\n build_file = Label(\"@crates//crates:BUILD.wit-bindgen-core-0.51.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__wit-bindgen-rust-0.51.0\",\n sha256 = \"b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/wit-bindgen-rust/0.51.0/download\"],\n strip_prefix = \"wit-bindgen-rust-0.51.0\",\n build_file = Label(\"@crates//crates:BUILD.wit-bindgen-rust-0.51.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__wit-bindgen-rust-macro-0.51.0\",\n sha256 = \"0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/wit-bindgen-rust-macro/0.51.0/download\"],\n strip_prefix = \"wit-bindgen-rust-macro-0.51.0\",\n build_file = Label(\"@crates//crates:BUILD.wit-bindgen-rust-macro-0.51.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__wit-component-0.244.0\",\n sha256 = \"9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/wit-component/0.244.0/download\"],\n strip_prefix = \"wit-component-0.244.0\",\n build_file = Label(\"@crates//crates:BUILD.wit-component-0.244.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__wit-parser-0.244.0\",\n sha256 = \"ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/wit-parser/0.244.0/download\"],\n strip_prefix = \"wit-parser-0.244.0\",\n build_file = Label(\"@crates//crates:BUILD.wit-parser-0.244.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__zmij-1.0.21\",\n sha256 = \"b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/zmij/1.0.21/download\"],\n strip_prefix = \"zmij-1.0.21\",\n build_file = Label(\"@crates//crates:BUILD.zmij-1.0.21.bazel\"),\n )\n\n return [\n struct(repo=\"crates__libc-0.2.182\", is_dev_dep = False),\n struct(repo=\"crates__log-0.4.29\", is_dev_dep = False),\n struct(repo=\"crates__nix-0.29.0\", is_dev_dep = False),\n struct(repo=\"crates__prost-0.13.5\", is_dev_dep = False),\n struct(repo=\"crates__prost-build-0.13.5\", is_dev_dep = False),\n struct(repo=\"crates__prost-types-0.13.5\", is_dev_dep = False),\n struct(repo=\"crates__thiserror-2.0.18\", is_dev_dep = False),\n ]\n" + "crates.bzl": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\"\"\"\n# `crates_repository` API\n\n- [aliases](#aliases)\n- [crate_edition](#crate_edition)\n- [crate_deps](#crate_deps)\n- [all_crate_deps](#all_crate_deps)\n- [crate_repositories](#crate_repositories)\n\n\"\"\"\n\nload(\"@bazel_tools//tools/build_defs/repo:git.bzl\", \"git_repository\")\nload(\"@bazel_tools//tools/build_defs/repo:http.bzl\", \"http_archive\")\nload(\"@bazel_tools//tools/build_defs/repo:utils.bzl\", \"maybe\")\nload(\"@bazel_skylib//lib:selects.bzl\", \"selects\")\nload(\"@rules_rust//crate_universe:defs.bzl\", \"crates_vendor_remote_repository\", \"local_crate_mirror\")\n\n###############################################################################\n# MACROS API\n###############################################################################\n\n# An identifier that represent common dependencies (unconditional).\n_COMMON_CONDITION = \"\"\n\ndef _flatten_dependency_maps(all_dependency_maps):\n \"\"\"Flatten a list of dependency maps into one dictionary.\n\n Dependency maps have the following structure:\n\n ```python\n DEPENDENCIES_MAP = {\n # The first key in the map is a Bazel package\n # name of the workspace this file is defined in.\n \"workspace_member_package\": {\n\n # Not all dependencies are supported for all platforms.\n # the condition key is the condition required to be true\n # on the host platform.\n \"condition\": {\n\n # An alias to a crate target. # The label of the crate target the\n # Aliases are only crate names. # package name refers to.\n \"package_name\": \"@full//:label\",\n }\n }\n }\n ```\n\n Args:\n all_dependency_maps (list): A list of dicts as described above\n\n Returns:\n dict: A dictionary as described above\n \"\"\"\n dependencies = {}\n\n for workspace_deps_map in all_dependency_maps:\n for pkg_name, conditional_deps_map in workspace_deps_map.items():\n if pkg_name not in dependencies:\n non_frozen_map = dict()\n for key, values in conditional_deps_map.items():\n non_frozen_map.update({key: dict(values.items())})\n dependencies.setdefault(pkg_name, non_frozen_map)\n continue\n\n for condition, deps_map in conditional_deps_map.items():\n # If the condition has not been recorded, do so and continue\n if condition not in dependencies[pkg_name]:\n dependencies[pkg_name].setdefault(condition, dict(deps_map.items()))\n continue\n\n # Alert on any miss-matched dependencies\n inconsistent_entries = []\n for crate_name, crate_label in deps_map.items():\n existing = dependencies[pkg_name][condition].get(crate_name)\n if existing and existing != crate_label:\n inconsistent_entries.append((crate_name, existing, crate_label))\n dependencies[pkg_name][condition].update({crate_name: crate_label})\n\n return dependencies\n\ndef crate_deps(deps, package_name = None):\n \"\"\"Finds the fully qualified label of the requested crates for the package where this macro is called.\n\n Args:\n deps (list): The desired list of crate targets.\n package_name (str, optional): The package name of the set of dependencies to look up.\n Defaults to `native.package_name()`.\n\n Returns:\n list: A list of labels to generated rust targets (str)\n \"\"\"\n\n if not deps:\n return []\n\n if package_name == None:\n package_name = native.package_name()\n\n # Join both sets of dependencies\n dependencies = _flatten_dependency_maps([\n _NORMAL_DEPENDENCIES,\n _NORMAL_DEV_DEPENDENCIES,\n _PROC_MACRO_DEPENDENCIES,\n _PROC_MACRO_DEV_DEPENDENCIES,\n _BUILD_DEPENDENCIES,\n _BUILD_PROC_MACRO_DEPENDENCIES,\n ]).pop(package_name, {})\n\n # Combine all conditional packages so we can easily index over a flat list\n # TODO: Perhaps this should actually return select statements and maintain\n # the conditionals of the dependencies\n flat_deps = {}\n for deps_set in dependencies.values():\n for crate_name, crate_label in deps_set.items():\n flat_deps.update({crate_name: crate_label})\n\n missing_crates = []\n crate_targets = []\n for crate_target in deps:\n if crate_target not in flat_deps:\n missing_crates.append(crate_target)\n else:\n crate_targets.append(flat_deps[crate_target])\n\n if missing_crates:\n fail(\"Could not find crates `{}` among dependencies of `{}`. Available dependencies were `{}`\".format(\n missing_crates,\n package_name,\n dependencies,\n ))\n\n return crate_targets\n\ndef crate_edition(package_name = None):\n \"\"\"Finds the Rust edition for the package where this macro is called.\n\n Args:\n package_name (str, optional): The package name whose edition should be\n looked up. Defaults to `native.package_name()` when unset.\n\n Returns:\n str: The Rust edition declared by the package's Cargo.toml file.\n \"\"\"\n if package_name == None:\n package_name = native.package_name()\n\n if package_name not in _CRATE_EDITIONS:\n fail(\"Tried to get crate_edition for package \" + package_name + \" but that package had no Cargo.toml file\")\n\n return _CRATE_EDITIONS[package_name]\n\ndef all_crate_deps(\n normal = False, \n normal_dev = False, \n proc_macro = False, \n proc_macro_dev = False,\n build = False,\n build_proc_macro = False,\n package_name = None):\n \"\"\"Finds the fully qualified label of all requested direct crate dependencies \\\n for the package where this macro is called.\n\n If no parameters are set, all normal dependencies are returned. Setting any one flag will\n otherwise impact the contents of the returned list.\n\n Args:\n normal (bool, optional): If True, normal dependencies are included in the\n output list.\n normal_dev (bool, optional): If True, normal dev dependencies will be\n included in the output list.\n proc_macro (bool, optional): If True, proc_macro dependencies are included\n in the output list.\n proc_macro_dev (bool, optional): If True, dev proc_macro dependencies are\n included in the output list.\n build (bool, optional): If True, build dependencies are included\n in the output list.\n build_proc_macro (bool, optional): If True, build proc_macro dependencies are\n included in the output list.\n package_name (str, optional): The package name of the set of dependencies to look up.\n Defaults to `native.package_name()` when unset.\n\n Returns:\n list: A list of labels to generated rust targets (str)\n \"\"\"\n\n if package_name == None:\n package_name = native.package_name()\n\n # Determine the relevant maps to use\n all_dependency_maps = []\n if normal:\n all_dependency_maps.append(_NORMAL_DEPENDENCIES)\n if normal_dev:\n all_dependency_maps.append(_NORMAL_DEV_DEPENDENCIES)\n if proc_macro:\n all_dependency_maps.append(_PROC_MACRO_DEPENDENCIES)\n if proc_macro_dev:\n all_dependency_maps.append(_PROC_MACRO_DEV_DEPENDENCIES)\n if build:\n all_dependency_maps.append(_BUILD_DEPENDENCIES)\n if build_proc_macro:\n all_dependency_maps.append(_BUILD_PROC_MACRO_DEPENDENCIES)\n\n # Default to always using normal dependencies\n if not all_dependency_maps:\n all_dependency_maps.append(_NORMAL_DEPENDENCIES)\n\n dependencies = _flatten_dependency_maps(all_dependency_maps).pop(package_name, None)\n\n if not dependencies:\n if dependencies == None:\n fail(\"Tried to get all_crate_deps for package \" + package_name + \" but that package had no Cargo.toml file\")\n else:\n return []\n\n crate_deps = list(dependencies.pop(_COMMON_CONDITION, {}).values())\n for condition, deps in dependencies.items():\n crate_deps += selects.with_or({\n tuple(_CONDITIONS[condition]): deps.values(),\n \"//conditions:default\": [],\n })\n\n return crate_deps\n\ndef aliases(\n normal = False,\n normal_dev = False,\n proc_macro = False,\n proc_macro_dev = False,\n build = False,\n build_proc_macro = False,\n package_name = None):\n \"\"\"Produces a map of Crate alias names to their original label\n\n If no dependency kinds are specified, `normal` and `proc_macro` are used by default.\n Setting any one flag will otherwise determine the contents of the returned dict.\n\n Args:\n normal (bool, optional): If True, normal dependencies are included in the\n output list.\n normal_dev (bool, optional): If True, normal dev dependencies will be\n included in the output list..\n proc_macro (bool, optional): If True, proc_macro dependencies are included\n in the output list.\n proc_macro_dev (bool, optional): If True, dev proc_macro dependencies are\n included in the output list.\n build (bool, optional): If True, build dependencies are included\n in the output list.\n build_proc_macro (bool, optional): If True, build proc_macro dependencies are\n included in the output list.\n package_name (str, optional): The package name of the set of dependencies to look up.\n Defaults to `native.package_name()` when unset.\n\n Returns:\n dict: The aliases of all associated packages\n \"\"\"\n if package_name == None:\n package_name = native.package_name()\n\n # Determine the relevant maps to use\n all_aliases_maps = []\n if normal:\n all_aliases_maps.append(_NORMAL_ALIASES)\n if normal_dev:\n all_aliases_maps.append(_NORMAL_DEV_ALIASES)\n if proc_macro:\n all_aliases_maps.append(_PROC_MACRO_ALIASES)\n if proc_macro_dev:\n all_aliases_maps.append(_PROC_MACRO_DEV_ALIASES)\n if build:\n all_aliases_maps.append(_BUILD_ALIASES)\n if build_proc_macro:\n all_aliases_maps.append(_BUILD_PROC_MACRO_ALIASES)\n\n # Default to always using normal aliases\n if not all_aliases_maps:\n all_aliases_maps.append(_NORMAL_ALIASES)\n all_aliases_maps.append(_PROC_MACRO_ALIASES)\n\n aliases = _flatten_dependency_maps(all_aliases_maps).pop(package_name, None)\n\n if not aliases:\n return dict()\n\n common_items = aliases.pop(_COMMON_CONDITION, {}).items()\n\n # If there are only common items in the dictionary, immediately return them\n if not len(aliases.keys()) == 1:\n return dict(common_items)\n\n # Build a single select statement where each conditional has accounted for the\n # common set of aliases.\n crate_aliases = {\"//conditions:default\": dict(common_items)}\n for condition, deps in aliases.items():\n condition_triples = _CONDITIONS[condition]\n for triple in condition_triples:\n if triple in crate_aliases:\n crate_aliases[triple].update(deps)\n else:\n crate_aliases.update({triple: dict(deps.items() + common_items)})\n\n return select(crate_aliases)\n\n###############################################################################\n# WORKSPACE MEMBER DEPS, ALIASES, AND EDITIONS\n###############################################################################\n\n_CRATE_EDITIONS = {\n \"rust_client\": \"2021\",\n \"rust_client/phaser_c\": \"2021\",\n}\n\n_NORMAL_DEPENDENCIES = {\n \"rust_client\": {\n _COMMON_CONDITION: {\n \"libc\": Label(\"@crates//libc-0.2.182\"),\n \"log\": Label(\"@crates//log-0.4.29\"),\n \"nix\": Label(\"@crates//nix-0.29.0\"),\n \"prost\": Label(\"@crates//prost-0.13.5\"),\n \"prost-types\": Label(\"@crates//prost-types-0.13.5\"),\n \"thiserror\": Label(\"@crates//thiserror-2.0.18\"),\n },\n },\n \"rust_client/phaser_c\": {\n },\n}\n\n\n_NORMAL_ALIASES = {\n \"rust_client\": {\n _COMMON_CONDITION: {\n },\n },\n \"rust_client/phaser_c\": {\n },\n}\n\n\n_NORMAL_DEV_DEPENDENCIES = {\n \"rust_client\": {\n },\n \"rust_client/phaser_c\": {\n },\n}\n\n\n_NORMAL_DEV_ALIASES = {\n \"rust_client\": {\n },\n \"rust_client/phaser_c\": {\n },\n}\n\n\n_PROC_MACRO_DEPENDENCIES = {\n \"rust_client\": {\n },\n \"rust_client/phaser_c\": {\n },\n}\n\n\n_PROC_MACRO_ALIASES = {\n \"rust_client\": {\n },\n \"rust_client/phaser_c\": {\n },\n}\n\n\n_PROC_MACRO_DEV_DEPENDENCIES = {\n \"rust_client\": {\n },\n \"rust_client/phaser_c\": {\n },\n}\n\n\n_PROC_MACRO_DEV_ALIASES = {\n \"rust_client\": {\n },\n \"rust_client/phaser_c\": {\n },\n}\n\n\n_BUILD_DEPENDENCIES = {\n \"rust_client\": {\n _COMMON_CONDITION: {\n \"prost-build\": Label(\"@crates//prost-build-0.13.5\"),\n },\n },\n \"rust_client/phaser_c\": {\n },\n}\n\n\n_BUILD_ALIASES = {\n \"rust_client\": {\n _COMMON_CONDITION: {\n },\n },\n \"rust_client/phaser_c\": {\n },\n}\n\n\n_BUILD_PROC_MACRO_DEPENDENCIES = {\n \"rust_client\": {\n },\n \"rust_client/phaser_c\": {\n },\n}\n\n\n_BUILD_PROC_MACRO_ALIASES = {\n \"rust_client\": {\n },\n \"rust_client/phaser_c\": {\n },\n}\n\n\n_CONDITIONS = {\n \"aarch64-apple-darwin\": [\"@rules_rust//rust/platform:aarch64-apple-darwin\"],\n \"aarch64-unknown-linux-gnu\": [\"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\"],\n \"cfg(all(any(target_os = \\\"linux\\\", target_os = \\\"android\\\"), any(rustix_use_libc, miri, not(all(target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", any(target_arch = \\\"s390x\\\", target_arch = \\\"powerpc\\\")), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc\\\"), all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\")))))))\": [],\n \"cfg(all(any(target_os = \\\"linux\\\", target_os = \\\"android\\\"), not(any(all(target_os = \\\"linux\\\", target_env = \\\"\\\"), getrandom_backend = \\\"custom\\\", getrandom_backend = \\\"linux_raw\\\", getrandom_backend = \\\"rdrand\\\", getrandom_backend = \\\"rndr\\\"))))\": [\"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\",\"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\",\"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\"],\n \"cfg(all(not(rustix_use_libc), not(miri), target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", any(target_arch = \\\"s390x\\\", target_arch = \\\"powerpc\\\")), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc\\\"), all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\"))))\": [\"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\",\"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\",\"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\"],\n \"cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \\\"linux\\\", any(target_endian = \\\"little\\\", any(target_arch = \\\"s390x\\\", target_arch = \\\"powerpc\\\")), any(target_arch = \\\"arm\\\", all(target_arch = \\\"aarch64\\\", target_pointer_width = \\\"64\\\"), target_arch = \\\"riscv64\\\", all(rustix_use_experimental_asm, target_arch = \\\"powerpc\\\"), all(rustix_use_experimental_asm, target_arch = \\\"powerpc64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"s390x\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips32r6\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64\\\"), all(rustix_use_experimental_asm, target_arch = \\\"mips64r6\\\"), target_arch = \\\"x86\\\", all(target_arch = \\\"x86_64\\\", target_pointer_width = \\\"64\\\")))))))\": [\"@rules_rust//rust/platform:aarch64-apple-darwin\",\"@rules_rust//rust/platform:wasm32-unknown-unknown\",\"@rules_rust//rust/platform:wasm32-wasip1\"],\n \"cfg(all(target_arch = \\\"wasm32\\\", target_os = \\\"wasi\\\", target_env = \\\"p2\\\"))\": [],\n \"cfg(all(target_arch = \\\"wasm32\\\", target_os = \\\"wasi\\\", target_env = \\\"p3\\\"))\": [],\n \"cfg(all(target_os = \\\"uefi\\\", getrandom_backend = \\\"efi_rng\\\"))\": [],\n \"cfg(any())\": [],\n \"cfg(any(target_os = \\\"dragonfly\\\", target_os = \\\"freebsd\\\", target_os = \\\"hurd\\\", target_os = \\\"illumos\\\", target_os = \\\"cygwin\\\", all(target_os = \\\"horizon\\\", target_arch = \\\"arm\\\")))\": [],\n \"cfg(any(target_os = \\\"haiku\\\", target_os = \\\"redox\\\", target_os = \\\"nto\\\", target_os = \\\"aix\\\"))\": [],\n \"cfg(any(target_os = \\\"ios\\\", target_os = \\\"visionos\\\", target_os = \\\"watchos\\\", target_os = \\\"tvos\\\"))\": [],\n \"cfg(any(target_os = \\\"macos\\\", target_os = \\\"openbsd\\\", target_os = \\\"vita\\\", target_os = \\\"emscripten\\\"))\": [\"@rules_rust//rust/platform:aarch64-apple-darwin\"],\n \"cfg(any(unix, target_os = \\\"wasi\\\"))\": [\"@rules_rust//rust/platform:aarch64-apple-darwin\",\"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\",\"@rules_rust//rust/platform:wasm32-wasip1\",\"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\",\"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\"],\n \"cfg(target_os = \\\"hermit\\\")\": [],\n \"cfg(target_os = \\\"netbsd\\\")\": [],\n \"cfg(target_os = \\\"solaris\\\")\": [],\n \"cfg(target_os = \\\"vxworks\\\")\": [],\n \"cfg(target_os = \\\"wasi\\\")\": [\"@rules_rust//rust/platform:wasm32-wasip1\"],\n \"cfg(unix)\": [\"@rules_rust//rust/platform:aarch64-apple-darwin\",\"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\",\"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\",\"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\"],\n \"cfg(windows)\": [\"@rules_rust//rust/platform:x86_64-pc-windows-msvc\"],\n \"wasm32-unknown-unknown\": [\"@rules_rust//rust/platform:wasm32-unknown-unknown\"],\n \"wasm32-wasip1\": [\"@rules_rust//rust/platform:wasm32-wasip1\"],\n \"x86_64-pc-windows-msvc\": [\"@rules_rust//rust/platform:x86_64-pc-windows-msvc\"],\n \"x86_64-unknown-linux-gnu\": [\"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\"],\n \"x86_64-unknown-nixos-gnu\": [\"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\"],\n}\n\n###############################################################################\n\ndef crate_repositories():\n \"\"\"A macro for defining repositories for all generated crates.\n\n Returns:\n A list of repos visible to the module through the module extension.\n \"\"\"\n maybe(\n crates_vendor_remote_repository,\n name = \"crates\",\n # Lean interface: just point at `crates.bzl`; the repo rule\n # derives the sibling `BUILD.bazel` and `defs.bzl`.\n crates_module = Label(\"@crates//crates:crates.bzl\"),\n )\n maybe(\n http_archive,\n name = \"crates__aho-corasick-1.1.4\",\n sha256 = \"ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/aho-corasick/1.1.4/download\"],\n strip_prefix = \"aho-corasick-1.1.4\",\n build_file = Label(\"@crates//crates:BUILD.aho-corasick-1.1.4.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__anyhow-1.0.101\",\n sha256 = \"5f0e0fee31ef5ed1ba1316088939cea399010ed7731dba877ed44aeb407a75ea\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/anyhow/1.0.101/download\"],\n strip_prefix = \"anyhow-1.0.101\",\n build_file = Label(\"@crates//crates:BUILD.anyhow-1.0.101.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__autocfg-1.5.0\",\n sha256 = \"c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/autocfg/1.5.0/download\"],\n strip_prefix = \"autocfg-1.5.0\",\n build_file = Label(\"@crates//crates:BUILD.autocfg-1.5.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__bitflags-2.11.0\",\n sha256 = \"843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/bitflags/2.11.0/download\"],\n strip_prefix = \"bitflags-2.11.0\",\n build_file = Label(\"@crates//crates:BUILD.bitflags-2.11.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__bytes-1.11.1\",\n sha256 = \"1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/bytes/1.11.1/download\"],\n strip_prefix = \"bytes-1.11.1\",\n build_file = Label(\"@crates//crates:BUILD.bytes-1.11.1.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__cfg-if-1.0.4\",\n sha256 = \"9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/cfg-if/1.0.4/download\"],\n strip_prefix = \"cfg-if-1.0.4\",\n build_file = Label(\"@crates//crates:BUILD.cfg-if-1.0.4.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__cfg_aliases-0.2.1\",\n sha256 = \"613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/cfg_aliases/0.2.1/download\"],\n strip_prefix = \"cfg_aliases-0.2.1\",\n build_file = Label(\"@crates//crates:BUILD.cfg_aliases-0.2.1.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__either-1.15.0\",\n sha256 = \"48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/either/1.15.0/download\"],\n strip_prefix = \"either-1.15.0\",\n build_file = Label(\"@crates//crates:BUILD.either-1.15.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__equivalent-1.0.2\",\n sha256 = \"877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/equivalent/1.0.2/download\"],\n strip_prefix = \"equivalent-1.0.2\",\n build_file = Label(\"@crates//crates:BUILD.equivalent-1.0.2.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__errno-0.3.14\",\n sha256 = \"39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/errno/0.3.14/download\"],\n strip_prefix = \"errno-0.3.14\",\n build_file = Label(\"@crates//crates:BUILD.errno-0.3.14.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__fastrand-2.3.0\",\n sha256 = \"37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/fastrand/2.3.0/download\"],\n strip_prefix = \"fastrand-2.3.0\",\n build_file = Label(\"@crates//crates:BUILD.fastrand-2.3.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__fixedbitset-0.5.7\",\n sha256 = \"1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/fixedbitset/0.5.7/download\"],\n strip_prefix = \"fixedbitset-0.5.7\",\n build_file = Label(\"@crates//crates:BUILD.fixedbitset-0.5.7.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__foldhash-0.1.5\",\n sha256 = \"d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/foldhash/0.1.5/download\"],\n strip_prefix = \"foldhash-0.1.5\",\n build_file = Label(\"@crates//crates:BUILD.foldhash-0.1.5.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__getrandom-0.4.1\",\n sha256 = \"139ef39800118c7683f2fd3c98c1b23c09ae076556b435f8e9064ae108aaeeec\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/getrandom/0.4.1/download\"],\n strip_prefix = \"getrandom-0.4.1\",\n build_file = Label(\"@crates//crates:BUILD.getrandom-0.4.1.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__hashbrown-0.15.5\",\n sha256 = \"9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/hashbrown/0.15.5/download\"],\n strip_prefix = \"hashbrown-0.15.5\",\n build_file = Label(\"@crates//crates:BUILD.hashbrown-0.15.5.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__hashbrown-0.16.1\",\n sha256 = \"841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/hashbrown/0.16.1/download\"],\n strip_prefix = \"hashbrown-0.16.1\",\n build_file = Label(\"@crates//crates:BUILD.hashbrown-0.16.1.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__heck-0.5.0\",\n sha256 = \"2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/heck/0.5.0/download\"],\n strip_prefix = \"heck-0.5.0\",\n build_file = Label(\"@crates//crates:BUILD.heck-0.5.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__id-arena-2.3.0\",\n sha256 = \"3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/id-arena/2.3.0/download\"],\n strip_prefix = \"id-arena-2.3.0\",\n build_file = Label(\"@crates//crates:BUILD.id-arena-2.3.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__indexmap-2.13.0\",\n sha256 = \"7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/indexmap/2.13.0/download\"],\n strip_prefix = \"indexmap-2.13.0\",\n build_file = Label(\"@crates//crates:BUILD.indexmap-2.13.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__itertools-0.14.0\",\n sha256 = \"2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/itertools/0.14.0/download\"],\n strip_prefix = \"itertools-0.14.0\",\n build_file = Label(\"@crates//crates:BUILD.itertools-0.14.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__itoa-1.0.17\",\n sha256 = \"92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/itoa/1.0.17/download\"],\n strip_prefix = \"itoa-1.0.17\",\n build_file = Label(\"@crates//crates:BUILD.itoa-1.0.17.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__leb128fmt-0.1.0\",\n sha256 = \"09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/leb128fmt/0.1.0/download\"],\n strip_prefix = \"leb128fmt-0.1.0\",\n build_file = Label(\"@crates//crates:BUILD.leb128fmt-0.1.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__libc-0.2.182\",\n sha256 = \"6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/libc/0.2.182/download\"],\n strip_prefix = \"libc-0.2.182\",\n build_file = Label(\"@crates//crates:BUILD.libc-0.2.182.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__linux-raw-sys-0.11.0\",\n sha256 = \"df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/linux-raw-sys/0.11.0/download\"],\n strip_prefix = \"linux-raw-sys-0.11.0\",\n build_file = Label(\"@crates//crates:BUILD.linux-raw-sys-0.11.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__log-0.4.29\",\n sha256 = \"5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/log/0.4.29/download\"],\n strip_prefix = \"log-0.4.29\",\n build_file = Label(\"@crates//crates:BUILD.log-0.4.29.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__memchr-2.8.0\",\n sha256 = \"f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/memchr/2.8.0/download\"],\n strip_prefix = \"memchr-2.8.0\",\n build_file = Label(\"@crates//crates:BUILD.memchr-2.8.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__memoffset-0.9.1\",\n sha256 = \"488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/memoffset/0.9.1/download\"],\n strip_prefix = \"memoffset-0.9.1\",\n build_file = Label(\"@crates//crates:BUILD.memoffset-0.9.1.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__multimap-0.10.1\",\n sha256 = \"1d87ecb2933e8aeadb3e3a02b828fed80a7528047e68b4f424523a0981a3a084\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/multimap/0.10.1/download\"],\n strip_prefix = \"multimap-0.10.1\",\n build_file = Label(\"@crates//crates:BUILD.multimap-0.10.1.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__nix-0.29.0\",\n sha256 = \"71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/nix/0.29.0/download\"],\n strip_prefix = \"nix-0.29.0\",\n build_file = Label(\"@crates//crates:BUILD.nix-0.29.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__once_cell-1.21.3\",\n sha256 = \"42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/once_cell/1.21.3/download\"],\n strip_prefix = \"once_cell-1.21.3\",\n build_file = Label(\"@crates//crates:BUILD.once_cell-1.21.3.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__petgraph-0.7.1\",\n sha256 = \"3672b37090dbd86368a4145bc067582552b29c27377cad4e0a306c97f9bd7772\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/petgraph/0.7.1/download\"],\n strip_prefix = \"petgraph-0.7.1\",\n build_file = Label(\"@crates//crates:BUILD.petgraph-0.7.1.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__prettyplease-0.2.37\",\n sha256 = \"479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/prettyplease/0.2.37/download\"],\n strip_prefix = \"prettyplease-0.2.37\",\n build_file = Label(\"@crates//crates:BUILD.prettyplease-0.2.37.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__proc-macro2-1.0.106\",\n sha256 = \"8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/proc-macro2/1.0.106/download\"],\n strip_prefix = \"proc-macro2-1.0.106\",\n build_file = Label(\"@crates//crates:BUILD.proc-macro2-1.0.106.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__prost-0.13.5\",\n sha256 = \"2796faa41db3ec313a31f7624d9286acf277b52de526150b7e69f3debf891ee5\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/prost/0.13.5/download\"],\n strip_prefix = \"prost-0.13.5\",\n build_file = Label(\"@crates//crates:BUILD.prost-0.13.5.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__prost-build-0.13.5\",\n sha256 = \"be769465445e8c1474e9c5dac2018218498557af32d9ed057325ec9a41ae81bf\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/prost-build/0.13.5/download\"],\n strip_prefix = \"prost-build-0.13.5\",\n build_file = Label(\"@crates//crates:BUILD.prost-build-0.13.5.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__prost-derive-0.13.5\",\n sha256 = \"8a56d757972c98b346a9b766e3f02746cde6dd1cd1d1d563472929fdd74bec4d\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/prost-derive/0.13.5/download\"],\n strip_prefix = \"prost-derive-0.13.5\",\n build_file = Label(\"@crates//crates:BUILD.prost-derive-0.13.5.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__prost-types-0.13.5\",\n sha256 = \"52c2c1bf36ddb1a1c396b3601a3cec27c2462e45f07c386894ec3ccf5332bd16\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/prost-types/0.13.5/download\"],\n strip_prefix = \"prost-types-0.13.5\",\n build_file = Label(\"@crates//crates:BUILD.prost-types-0.13.5.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__quote-1.0.44\",\n sha256 = \"21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/quote/1.0.44/download\"],\n strip_prefix = \"quote-1.0.44\",\n build_file = Label(\"@crates//crates:BUILD.quote-1.0.44.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__r-efi-5.3.0\",\n sha256 = \"69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/r-efi/5.3.0/download\"],\n strip_prefix = \"r-efi-5.3.0\",\n build_file = Label(\"@crates//crates:BUILD.r-efi-5.3.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__regex-1.12.3\",\n sha256 = \"e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/regex/1.12.3/download\"],\n strip_prefix = \"regex-1.12.3\",\n build_file = Label(\"@crates//crates:BUILD.regex-1.12.3.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__regex-automata-0.4.14\",\n sha256 = \"6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/regex-automata/0.4.14/download\"],\n strip_prefix = \"regex-automata-0.4.14\",\n build_file = Label(\"@crates//crates:BUILD.regex-automata-0.4.14.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__regex-syntax-0.8.9\",\n sha256 = \"a96887878f22d7bad8a3b6dc5b7440e0ada9a245242924394987b21cf2210a4c\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/regex-syntax/0.8.9/download\"],\n strip_prefix = \"regex-syntax-0.8.9\",\n build_file = Label(\"@crates//crates:BUILD.regex-syntax-0.8.9.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__rustix-1.1.3\",\n sha256 = \"146c9e247ccc180c1f61615433868c99f3de3ae256a30a43b49f67c2d9171f34\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/rustix/1.1.3/download\"],\n strip_prefix = \"rustix-1.1.3\",\n build_file = Label(\"@crates//crates:BUILD.rustix-1.1.3.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__semver-1.0.27\",\n sha256 = \"d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/semver/1.0.27/download\"],\n strip_prefix = \"semver-1.0.27\",\n build_file = Label(\"@crates//crates:BUILD.semver-1.0.27.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__serde-1.0.228\",\n sha256 = \"9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/serde/1.0.228/download\"],\n strip_prefix = \"serde-1.0.228\",\n build_file = Label(\"@crates//crates:BUILD.serde-1.0.228.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__serde_core-1.0.228\",\n sha256 = \"41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/serde_core/1.0.228/download\"],\n strip_prefix = \"serde_core-1.0.228\",\n build_file = Label(\"@crates//crates:BUILD.serde_core-1.0.228.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__serde_derive-1.0.228\",\n sha256 = \"d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/serde_derive/1.0.228/download\"],\n strip_prefix = \"serde_derive-1.0.228\",\n build_file = Label(\"@crates//crates:BUILD.serde_derive-1.0.228.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__serde_json-1.0.149\",\n sha256 = \"83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/serde_json/1.0.149/download\"],\n strip_prefix = \"serde_json-1.0.149\",\n build_file = Label(\"@crates//crates:BUILD.serde_json-1.0.149.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__syn-2.0.116\",\n sha256 = \"3df424c70518695237746f84cede799c9c58fcb37450d7b23716568cc8bc69cb\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/syn/2.0.116/download\"],\n strip_prefix = \"syn-2.0.116\",\n build_file = Label(\"@crates//crates:BUILD.syn-2.0.116.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__tempfile-3.25.0\",\n sha256 = \"0136791f7c95b1f6dd99f9cc786b91bb81c3800b639b3478e561ddb7be95e5f1\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/tempfile/3.25.0/download\"],\n strip_prefix = \"tempfile-3.25.0\",\n build_file = Label(\"@crates//crates:BUILD.tempfile-3.25.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__thiserror-2.0.18\",\n sha256 = \"4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/thiserror/2.0.18/download\"],\n strip_prefix = \"thiserror-2.0.18\",\n build_file = Label(\"@crates//crates:BUILD.thiserror-2.0.18.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__thiserror-impl-2.0.18\",\n sha256 = \"ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/thiserror-impl/2.0.18/download\"],\n strip_prefix = \"thiserror-impl-2.0.18\",\n build_file = Label(\"@crates//crates:BUILD.thiserror-impl-2.0.18.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__unicode-ident-1.0.24\",\n sha256 = \"e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/unicode-ident/1.0.24/download\"],\n strip_prefix = \"unicode-ident-1.0.24\",\n build_file = Label(\"@crates//crates:BUILD.unicode-ident-1.0.24.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__unicode-xid-0.2.6\",\n sha256 = \"ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/unicode-xid/0.2.6/download\"],\n strip_prefix = \"unicode-xid-0.2.6\",\n build_file = Label(\"@crates//crates:BUILD.unicode-xid-0.2.6.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__wasip2-1.0.2-wasi-0.2.9\",\n sha256 = \"9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/wasip2/1.0.2+wasi-0.2.9/download\"],\n strip_prefix = \"wasip2-1.0.2+wasi-0.2.9\",\n build_file = Label(\"@crates//crates:BUILD.wasip2-1.0.2+wasi-0.2.9.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__wasip3-0.4.0-wasi-0.3.0-rc-2026-01-06\",\n sha256 = \"5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/wasip3/0.4.0+wasi-0.3.0-rc-2026-01-06/download\"],\n strip_prefix = \"wasip3-0.4.0+wasi-0.3.0-rc-2026-01-06\",\n build_file = Label(\"@crates//crates:BUILD.wasip3-0.4.0+wasi-0.3.0-rc-2026-01-06.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__wasm-encoder-0.244.0\",\n sha256 = \"990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/wasm-encoder/0.244.0/download\"],\n strip_prefix = \"wasm-encoder-0.244.0\",\n build_file = Label(\"@crates//crates:BUILD.wasm-encoder-0.244.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__wasm-metadata-0.244.0\",\n sha256 = \"bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/wasm-metadata/0.244.0/download\"],\n strip_prefix = \"wasm-metadata-0.244.0\",\n build_file = Label(\"@crates//crates:BUILD.wasm-metadata-0.244.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__wasmparser-0.244.0\",\n sha256 = \"47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/wasmparser/0.244.0/download\"],\n strip_prefix = \"wasmparser-0.244.0\",\n build_file = Label(\"@crates//crates:BUILD.wasmparser-0.244.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__windows-link-0.2.1\",\n sha256 = \"f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/windows-link/0.2.1/download\"],\n strip_prefix = \"windows-link-0.2.1\",\n build_file = Label(\"@crates//crates:BUILD.windows-link-0.2.1.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__windows-sys-0.61.2\",\n sha256 = \"ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/windows-sys/0.61.2/download\"],\n strip_prefix = \"windows-sys-0.61.2\",\n build_file = Label(\"@crates//crates:BUILD.windows-sys-0.61.2.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__wit-bindgen-0.51.0\",\n sha256 = \"d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/wit-bindgen/0.51.0/download\"],\n strip_prefix = \"wit-bindgen-0.51.0\",\n build_file = Label(\"@crates//crates:BUILD.wit-bindgen-0.51.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__wit-bindgen-core-0.51.0\",\n sha256 = \"ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/wit-bindgen-core/0.51.0/download\"],\n strip_prefix = \"wit-bindgen-core-0.51.0\",\n build_file = Label(\"@crates//crates:BUILD.wit-bindgen-core-0.51.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__wit-bindgen-rust-0.51.0\",\n sha256 = \"b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/wit-bindgen-rust/0.51.0/download\"],\n strip_prefix = \"wit-bindgen-rust-0.51.0\",\n build_file = Label(\"@crates//crates:BUILD.wit-bindgen-rust-0.51.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__wit-bindgen-rust-macro-0.51.0\",\n sha256 = \"0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/wit-bindgen-rust-macro/0.51.0/download\"],\n strip_prefix = \"wit-bindgen-rust-macro-0.51.0\",\n build_file = Label(\"@crates//crates:BUILD.wit-bindgen-rust-macro-0.51.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__wit-component-0.244.0\",\n sha256 = \"9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/wit-component/0.244.0/download\"],\n strip_prefix = \"wit-component-0.244.0\",\n build_file = Label(\"@crates//crates:BUILD.wit-component-0.244.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__wit-parser-0.244.0\",\n sha256 = \"ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/wit-parser/0.244.0/download\"],\n strip_prefix = \"wit-parser-0.244.0\",\n build_file = Label(\"@crates//crates:BUILD.wit-parser-0.244.0.bazel\"),\n )\n\n maybe(\n http_archive,\n name = \"crates__zmij-1.0.21\",\n sha256 = \"b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa\",\n type = \"tar.gz\",\n urls = [\"https://static.crates.io/crates/zmij/1.0.21/download\"],\n strip_prefix = \"zmij-1.0.21\",\n build_file = Label(\"@crates//crates:BUILD.zmij-1.0.21.bazel\"),\n )\n\n return [\n struct(repo = \"crates\", is_dev_dep = False),\n struct(repo=\"crates__libc-0.2.182\", is_dev_dep = False),\n struct(repo=\"crates__log-0.4.29\", is_dev_dep = False),\n struct(repo=\"crates__nix-0.29.0\", is_dev_dep = False),\n struct(repo=\"crates__prost-0.13.5\", is_dev_dep = False),\n struct(repo=\"crates__prost-build-0.13.5\", is_dev_dep = False),\n struct(repo=\"crates__prost-types-0.13.5\", is_dev_dep = False),\n struct(repo=\"crates__thiserror-2.0.18\", is_dev_dep = False),\n ]\n", + "defs.bzl": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\"\"\"Deprecated: re-exports the crate_universe macros from `:crates.bzl`.\"\"\"\n\nload(\n \":crates.bzl\",\n _aliases = \"aliases\",\n _all_crate_deps = \"all_crate_deps\",\n _crate_deps = \"crate_deps\",\n _crate_edition = \"crate_edition\",\n _crate_repositories = \"crate_repositories\",\n)\n\naliases = _aliases\nall_crate_deps = _all_crate_deps\ncrate_deps = _crate_deps\ncrate_edition = _crate_edition\ncrate_repositories = _crate_repositories\n", + "libc-0.2.182/BUILD.bazel": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\npackage(default_visibility = [\"//visibility:public\"])\n\nalias(\n name = \"libc-0.2.182\",\n actual = \"@crates__libc-0.2.182//:libc\",\n tags = [\"manual\"],\n)\n", + "libc/BUILD.bazel": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\npackage(default_visibility = [\"//visibility:public\"])\n\nalias(\n name = \"libc\",\n actual = \"@crates__libc-0.2.182//:libc\",\n tags = [\"manual\"],\n)\n", + "log-0.4.29/BUILD.bazel": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\npackage(default_visibility = [\"//visibility:public\"])\n\nalias(\n name = \"log-0.4.29\",\n actual = \"@crates__log-0.4.29//:log\",\n tags = [\"manual\"],\n)\n", + "log/BUILD.bazel": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\npackage(default_visibility = [\"//visibility:public\"])\n\nalias(\n name = \"log\",\n actual = \"@crates__log-0.4.29//:log\",\n tags = [\"manual\"],\n)\n", + "nix-0.29.0/BUILD.bazel": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\npackage(default_visibility = [\"//visibility:public\"])\n\nalias(\n name = \"nix-0.29.0\",\n actual = \"@crates__nix-0.29.0//:nix\",\n tags = [\"manual\"],\n)\n", + "nix/BUILD.bazel": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\npackage(default_visibility = [\"//visibility:public\"])\n\nalias(\n name = \"nix\",\n actual = \"@crates__nix-0.29.0//:nix\",\n tags = [\"manual\"],\n)\n", + "prost-0.13.5/BUILD.bazel": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\npackage(default_visibility = [\"//visibility:public\"])\n\nalias(\n name = \"prost-0.13.5\",\n actual = \"@crates__prost-0.13.5//:prost\",\n tags = [\"manual\"],\n)\n", + "prost/BUILD.bazel": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\npackage(default_visibility = [\"//visibility:public\"])\n\nalias(\n name = \"prost\",\n actual = \"@crates__prost-0.13.5//:prost\",\n tags = [\"manual\"],\n)\n", + "prost-build-0.13.5/BUILD.bazel": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\npackage(default_visibility = [\"//visibility:public\"])\n\nalias(\n name = \"prost-build-0.13.5\",\n actual = \"@crates__prost-build-0.13.5//:prost_build\",\n tags = [\"manual\"],\n)\n", + "prost-build/BUILD.bazel": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\npackage(default_visibility = [\"//visibility:public\"])\n\nalias(\n name = \"prost-build\",\n actual = \"@crates__prost-build-0.13.5//:prost_build\",\n tags = [\"manual\"],\n)\n", + "prost-types-0.13.5/BUILD.bazel": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\npackage(default_visibility = [\"//visibility:public\"])\n\nalias(\n name = \"prost-types-0.13.5\",\n actual = \"@crates__prost-types-0.13.5//:prost_types\",\n tags = [\"manual\"],\n)\n", + "prost-types/BUILD.bazel": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\npackage(default_visibility = [\"//visibility:public\"])\n\nalias(\n name = \"prost-types\",\n actual = \"@crates__prost-types-0.13.5//:prost_types\",\n tags = [\"manual\"],\n)\n", + "thiserror-2.0.18/BUILD.bazel": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\npackage(default_visibility = [\"//visibility:public\"])\n\nalias(\n name = \"thiserror-2.0.18\",\n actual = \"@crates__thiserror-2.0.18//:thiserror\",\n tags = [\"manual\"],\n)\n", + "thiserror/BUILD.bazel": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\npackage(default_visibility = [\"//visibility:public\"])\n\nalias(\n name = \"thiserror\",\n actual = \"@crates__thiserror-2.0.18//:thiserror\",\n tags = [\"manual\"],\n)\n" } } }, @@ -662,7 +471,7 @@ "https://static.crates.io/crates/anyhow/1.0.101/download" ], "strip_prefix": "anyhow-1.0.101", - "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"anyhow\",\n deps = [\n \"@crates__anyhow-1.0.101//:build_script_build\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"std\",\n ],\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=anyhow\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"1.0.101\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"std\",\n ],\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n edition = \"2021\",\n pkg_name = \"anyhow\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=anyhow\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"1.0.101\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" + "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"anyhow\",\n deps = [\n \":build_script_build\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"std\",\n ],\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=anyhow\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"1.0.101\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n build_script_env_files = [\n \":cargo_toml_env_vars\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"std\",\n ],\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n emit_warnings = False,\n edition = \"2021\",\n pkg_name = \"anyhow\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=anyhow\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"1.0.101\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" } }, "crates__autocfg-1.5.0": { @@ -818,7 +627,7 @@ "https://static.crates.io/crates/getrandom/0.4.1/download" ], "strip_prefix": "getrandom-0.4.1", - "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"getrandom\",\n deps = [\n \"@crates__cfg-if-1.0.4//:cfg_if\",\n \"@crates__getrandom-0.4.1//:build_script_build\",\n ] + selects.with_unmapped({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [\n \"@crates__libc-0.2.182//:libc\", # cfg(any(target_os = \"macos\", target_os = \"openbsd\", target_os = \"vita\", target_os = \"emscripten\"))\n ],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [\n \"@crates__libc-0.2.182//:libc\", # cfg(all(any(target_os = \"linux\", target_os = \"android\"), not(any(all(target_os = \"linux\", target_env = \"\"), getrandom_backend = \"custom\", getrandom_backend = \"linux_raw\", getrandom_backend = \"rdrand\", getrandom_backend = \"rndr\"))))\n ],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [\n \"@crates__libc-0.2.182//:libc\", # cfg(all(any(target_os = \"linux\", target_os = \"android\"), not(any(all(target_os = \"linux\", target_env = \"\"), getrandom_backend = \"custom\", getrandom_backend = \"linux_raw\", getrandom_backend = \"rdrand\", getrandom_backend = \"rndr\"))))\n ],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [\n \"@crates__libc-0.2.182//:libc\", # cfg(all(any(target_os = \"linux\", target_os = \"android\"), not(any(all(target_os = \"linux\", target_env = \"\"), getrandom_backend = \"custom\", getrandom_backend = \"linux_raw\", getrandom_backend = \"rdrand\", getrandom_backend = \"rndr\"))))\n ],\n \"//conditions:default\": [],\n selects.NO_MATCHING_PLATFORM_TRIPLES: {\n \"i686-apple-darwin\": [\n \"@crates__libc-0.2.182//:libc\",\n ],\n \"x86_64-apple-darwin\": [\n \"@crates__libc-0.2.182//:libc\",\n ],\n },\n }),\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_root = \"src/lib.rs\",\n edition = \"2024\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=getrandom\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"0.4.1\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n edition = \"2024\",\n pkg_name = \"getrandom\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=getrandom\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"0.4.1\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" + "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"getrandom\",\n deps = [\n \":build_script_build\",\n \"@crates__cfg-if-1.0.4//:cfg_if\",\n ] + selects.with_unmapped({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [\n \"@crates__libc-0.2.182//:libc\", # cfg(any(target_os = \"macos\", target_os = \"openbsd\", target_os = \"vita\", target_os = \"emscripten\"))\n ],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [\n \"@crates__libc-0.2.182//:libc\", # cfg(all(any(target_os = \"linux\", target_os = \"android\"), not(any(all(target_os = \"linux\", target_env = \"\"), getrandom_backend = \"custom\", getrandom_backend = \"linux_raw\", getrandom_backend = \"rdrand\", getrandom_backend = \"rndr\"))))\n ],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [\n \"@crates__libc-0.2.182//:libc\", # cfg(all(any(target_os = \"linux\", target_os = \"android\"), not(any(all(target_os = \"linux\", target_env = \"\"), getrandom_backend = \"custom\", getrandom_backend = \"linux_raw\", getrandom_backend = \"rdrand\", getrandom_backend = \"rndr\"))))\n ],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [\n \"@crates__libc-0.2.182//:libc\", # cfg(all(any(target_os = \"linux\", target_os = \"android\"), not(any(all(target_os = \"linux\", target_env = \"\"), getrandom_backend = \"custom\", getrandom_backend = \"linux_raw\", getrandom_backend = \"rdrand\", getrandom_backend = \"rndr\"))))\n ],\n \"//conditions:default\": [],\n selects.NO_MATCHING_PLATFORM_TRIPLES: {\n \"i686-apple-darwin\": [\n \"@crates__libc-0.2.182//:libc\",\n ],\n \"x86_64-apple-darwin\": [\n \"@crates__libc-0.2.182//:libc\",\n ],\n },\n }),\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_root = \"src/lib.rs\",\n edition = \"2024\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=getrandom\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"0.4.1\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n build_script_env_files = [\n \":cargo_toml_env_vars\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n emit_warnings = False,\n edition = \"2024\",\n pkg_name = \"getrandom\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=getrandom\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"0.4.1\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" } }, "crates__hashbrown-0.15.5": { @@ -935,7 +744,7 @@ "https://static.crates.io/crates/libc/0.2.182/download" ], "strip_prefix": "libc-0.2.182", - "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"libc\",\n deps = [\n \"@crates__libc-0.2.182//:build_script_build\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"extra_traits\",\n \"std\",\n ],\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=libc\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"0.2.182\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"extra_traits\",\n \"std\",\n ],\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n edition = \"2021\",\n pkg_name = \"libc\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=libc\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"0.2.182\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" + "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"libc\",\n deps = [\n \":build_script_build\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"extra_traits\",\n \"std\",\n ],\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=libc\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"0.2.182\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n build_script_env_files = [\n \":cargo_toml_env_vars\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"extra_traits\",\n \"std\",\n ],\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n emit_warnings = False,\n edition = \"2021\",\n pkg_name = \"libc\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=libc\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"0.2.182\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" } }, "crates__linux-raw-sys-0.11.0": { @@ -987,7 +796,7 @@ "https://static.crates.io/crates/memoffset/0.9.1/download" ], "strip_prefix": "memoffset-0.9.1", - "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"memoffset\",\n deps = [\n \"@crates__memoffset-0.9.1//:build_script_build\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n ],\n crate_root = \"src/lib.rs\",\n edition = \"2015\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=memoffset\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"0.9.1\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n ],\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n deps = [\n \"@crates__autocfg-1.5.0//:autocfg\",\n ],\n edition = \"2015\",\n pkg_name = \"memoffset\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=memoffset\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"0.9.1\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" + "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"memoffset\",\n deps = [\n \":build_script_build\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n ],\n crate_root = \"src/lib.rs\",\n edition = \"2015\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=memoffset\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"0.9.1\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n build_script_env_files = [\n \":cargo_toml_env_vars\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n ],\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n deps = [\n \"@crates__autocfg-1.5.0//:autocfg\",\n ],\n emit_warnings = False,\n edition = \"2015\",\n pkg_name = \"memoffset\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=memoffset\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"0.9.1\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" } }, "crates__multimap-0.10.1": { @@ -1013,7 +822,7 @@ "https://static.crates.io/crates/nix/0.29.0/download" ], "strip_prefix": "nix-0.29.0", - "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"nix\",\n deps = [\n \"@crates__bitflags-2.11.0//:bitflags\",\n \"@crates__cfg-if-1.0.4//:cfg_if\",\n \"@crates__libc-0.2.182//:libc\",\n \"@crates__memoffset-0.9.1//:memoffset\",\n \"@crates__nix-0.29.0//:build_script_build\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"event\",\n \"fs\",\n \"memoffset\",\n \"mman\",\n \"poll\",\n \"socket\",\n \"uio\",\n ],\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=nix\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"0.29.0\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"event\",\n \"fs\",\n \"memoffset\",\n \"mman\",\n \"poll\",\n \"socket\",\n \"uio\",\n ],\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n deps = [\n \"@crates__cfg_aliases-0.2.1//:cfg_aliases\",\n ],\n edition = \"2021\",\n pkg_name = \"nix\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=nix\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"0.29.0\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" + "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"nix\",\n deps = [\n \":build_script_build\",\n \"@crates__bitflags-2.11.0//:bitflags\",\n \"@crates__cfg-if-1.0.4//:cfg_if\",\n \"@crates__libc-0.2.182//:libc\",\n \"@crates__memoffset-0.9.1//:memoffset\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"event\",\n \"fs\",\n \"memoffset\",\n \"mman\",\n \"poll\",\n \"socket\",\n \"uio\",\n ],\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=nix\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"0.29.0\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n build_script_env_files = [\n \":cargo_toml_env_vars\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"event\",\n \"fs\",\n \"memoffset\",\n \"mman\",\n \"poll\",\n \"socket\",\n \"uio\",\n ],\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n deps = [\n \"@crates__cfg_aliases-0.2.1//:cfg_aliases\",\n ],\n emit_warnings = False,\n edition = \"2021\",\n pkg_name = \"nix\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=nix\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"0.29.0\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" } }, "crates__once_cell-1.21.3": { @@ -1052,7 +861,7 @@ "https://static.crates.io/crates/prettyplease/0.2.37/download" ], "strip_prefix": "prettyplease-0.2.37", - "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"prettyplease\",\n deps = [\n \"@crates__prettyplease-0.2.37//:build_script_build\",\n \"@crates__proc-macro2-1.0.106//:proc_macro2\",\n \"@crates__syn-2.0.116//:syn\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=prettyplease\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"0.2.37\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n edition = \"2021\",\n links = \"prettyplease02\",\n pkg_name = \"prettyplease\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=prettyplease\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"0.2.37\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" + "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"prettyplease\",\n deps = [\n \":build_script_build\",\n \"@crates__proc-macro2-1.0.106//:proc_macro2\",\n \"@crates__syn-2.0.116//:syn\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=prettyplease\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"0.2.37\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n build_script_env_files = [\n \":cargo_toml_env_vars\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n emit_warnings = False,\n edition = \"2021\",\n links = \"prettyplease02\",\n pkg_name = \"prettyplease\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=prettyplease\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"0.2.37\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" } }, "crates__proc-macro2-1.0.106": { @@ -1065,7 +874,7 @@ "https://static.crates.io/crates/proc-macro2/1.0.106/download" ], "strip_prefix": "proc-macro2-1.0.106", - "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"proc_macro2\",\n deps = [\n \"@crates__proc-macro2-1.0.106//:build_script_build\",\n \"@crates__unicode-ident-1.0.24//:unicode_ident\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"proc-macro\",\n ],\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=proc-macro2\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"1.0.106\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"proc-macro\",\n ],\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n edition = \"2021\",\n pkg_name = \"proc-macro2\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=proc-macro2\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"1.0.106\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" + "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"proc_macro2\",\n deps = [\n \":build_script_build\",\n \"@crates__unicode-ident-1.0.24//:unicode_ident\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"proc-macro\",\n ],\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=proc-macro2\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"1.0.106\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n build_script_env_files = [\n \":cargo_toml_env_vars\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"proc-macro\",\n ],\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n emit_warnings = False,\n edition = \"2021\",\n pkg_name = \"proc-macro2\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=proc-macro2\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"1.0.106\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" } }, "crates__prost-0.13.5": { @@ -1130,7 +939,7 @@ "https://static.crates.io/crates/quote/1.0.44/download" ], "strip_prefix": "quote-1.0.44", - "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"quote\",\n deps = [\n \"@crates__proc-macro2-1.0.106//:proc_macro2\",\n \"@crates__quote-1.0.44//:build_script_build\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"proc-macro\",\n ],\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=quote\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"1.0.44\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"proc-macro\",\n ],\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n edition = \"2021\",\n pkg_name = \"quote\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=quote\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"1.0.44\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" + "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"quote\",\n deps = [\n \":build_script_build\",\n \"@crates__proc-macro2-1.0.106//:proc_macro2\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"proc-macro\",\n ],\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=quote\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"1.0.44\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n build_script_env_files = [\n \":cargo_toml_env_vars\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"proc-macro\",\n ],\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n emit_warnings = False,\n edition = \"2021\",\n pkg_name = \"quote\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=quote\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"1.0.44\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" } }, "crates__r-efi-5.3.0": { @@ -1195,7 +1004,7 @@ "https://static.crates.io/crates/rustix/1.1.3/download" ], "strip_prefix": "rustix-1.1.3", - "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"rustix\",\n deps = [\n \"@crates__bitflags-2.11.0//:bitflags\",\n \"@crates__rustix-1.1.3//:build_script_build\",\n ] + select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [\n \"@crates__errno-0.3.14//:errno\", # aarch64-apple-darwin, cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\")))))))\n \"@crates__libc-0.2.182//:libc\", # aarch64-apple-darwin, cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\")))))))\n ],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [\n \"@crates__linux-raw-sys-0.11.0//:linux_raw_sys\", # cfg(all(not(rustix_use_libc), not(miri), target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\"))))\n ],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [\n \"@crates__errno-0.3.14//:errno\", # cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\")))))))\n \"@crates__libc-0.2.182//:libc\", # cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\")))))))\n ],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [\n \"@crates__errno-0.3.14//:errno\", # cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\")))))))\n \"@crates__libc-0.2.182//:libc\", # cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\")))))))\n ],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [\n \"@crates__errno-0.3.14//:errno\", # cfg(windows)\n \"@crates__windows-sys-0.61.2//:windows_sys\", # cfg(windows)\n ],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [\n \"@crates__linux-raw-sys-0.11.0//:linux_raw_sys\", # cfg(all(not(rustix_use_libc), not(miri), target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\"))))\n ],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [\n \"@crates__linux-raw-sys-0.11.0//:linux_raw_sys\", # cfg(all(not(rustix_use_libc), not(miri), target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\"))))\n ],\n \"//conditions:default\": [],\n }),\n aliases = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": {\n \"@crates__errno-0.3.14//:errno\": \"libc_errno\", # aarch64-apple-darwin, cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\")))))))\n },\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": {\n \"@crates__errno-0.3.14//:errno\": \"libc_errno\", # cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\")))))))\n },\n \"@rules_rust//rust/platform:wasm32-wasip1\": {\n \"@crates__errno-0.3.14//:errno\": \"libc_errno\", # cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\")))))))\n },\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": {\n \"@crates__errno-0.3.14//:errno\": \"libc_errno\", # cfg(windows)\n },\n \"//conditions:default\": {},\n }),\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"alloc\",\n \"default\",\n \"fs\",\n \"std\",\n ],\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=rustix\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"1.1.3\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"alloc\",\n \"default\",\n \"fs\",\n \"std\",\n ],\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n edition = \"2021\",\n pkg_name = \"rustix\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=rustix\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"1.1.3\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" + "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"rustix\",\n deps = [\n \":build_script_build\",\n \"@crates__bitflags-2.11.0//:bitflags\",\n ] + select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [\n \"@crates__errno-0.3.14//:errno\", # aarch64-apple-darwin, cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\")))))))\n \"@crates__libc-0.2.182//:libc\", # aarch64-apple-darwin, cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\")))))))\n ],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [\n \"@crates__linux-raw-sys-0.11.0//:linux_raw_sys\", # cfg(all(not(rustix_use_libc), not(miri), target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\"))))\n ],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [\n \"@crates__errno-0.3.14//:errno\", # cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\")))))))\n \"@crates__libc-0.2.182//:libc\", # cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\")))))))\n ],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [\n \"@crates__errno-0.3.14//:errno\", # cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\")))))))\n \"@crates__libc-0.2.182//:libc\", # cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\")))))))\n ],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [\n \"@crates__errno-0.3.14//:errno\", # cfg(windows)\n \"@crates__windows-sys-0.61.2//:windows_sys\", # cfg(windows)\n ],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [\n \"@crates__linux-raw-sys-0.11.0//:linux_raw_sys\", # cfg(all(not(rustix_use_libc), not(miri), target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\"))))\n ],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [\n \"@crates__linux-raw-sys-0.11.0//:linux_raw_sys\", # cfg(all(not(rustix_use_libc), not(miri), target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\"))))\n ],\n \"//conditions:default\": [],\n }),\n aliases = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": {\n \"@crates__errno-0.3.14//:errno\": \"libc_errno\", # aarch64-apple-darwin, cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\")))))))\n },\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": {\n \"@crates__errno-0.3.14//:errno\": \"libc_errno\", # cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\")))))))\n },\n \"@rules_rust//rust/platform:wasm32-wasip1\": {\n \"@crates__errno-0.3.14//:errno\": \"libc_errno\", # cfg(all(not(windows), any(rustix_use_libc, miri, not(all(target_os = \"linux\", any(target_endian = \"little\", any(target_arch = \"s390x\", target_arch = \"powerpc\")), any(target_arch = \"arm\", all(target_arch = \"aarch64\", target_pointer_width = \"64\"), target_arch = \"riscv64\", all(rustix_use_experimental_asm, target_arch = \"powerpc\"), all(rustix_use_experimental_asm, target_arch = \"powerpc64\"), all(rustix_use_experimental_asm, target_arch = \"s390x\"), all(rustix_use_experimental_asm, target_arch = \"mips\"), all(rustix_use_experimental_asm, target_arch = \"mips32r6\"), all(rustix_use_experimental_asm, target_arch = \"mips64\"), all(rustix_use_experimental_asm, target_arch = \"mips64r6\"), target_arch = \"x86\", all(target_arch = \"x86_64\", target_pointer_width = \"64\")))))))\n },\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": {\n \"@crates__errno-0.3.14//:errno\": \"libc_errno\", # cfg(windows)\n },\n \"//conditions:default\": {},\n }),\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"alloc\",\n \"default\",\n \"fs\",\n \"std\",\n ],\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=rustix\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"1.1.3\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n build_script_env_files = [\n \":cargo_toml_env_vars\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"alloc\",\n \"default\",\n \"fs\",\n \"std\",\n ],\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n emit_warnings = False,\n edition = \"2021\",\n pkg_name = \"rustix\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=rustix\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"1.1.3\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" } }, "crates__semver-1.0.27": { @@ -1221,7 +1030,7 @@ "https://static.crates.io/crates/serde/1.0.228/download" ], "strip_prefix": "serde-1.0.228", - "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"serde\",\n deps = [\n \"@crates__serde-1.0.228//:build_script_build\",\n \"@crates__serde_core-1.0.228//:serde_core\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"alloc\",\n ],\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=serde\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"1.0.228\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"alloc\",\n ],\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n edition = \"2021\",\n pkg_name = \"serde\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=serde\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"1.0.228\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" + "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"serde\",\n deps = [\n \":build_script_build\",\n \"@crates__serde_core-1.0.228//:serde_core\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"alloc\",\n ],\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=serde\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"1.0.228\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n build_script_env_files = [\n \":cargo_toml_env_vars\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"alloc\",\n ],\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n emit_warnings = False,\n edition = \"2021\",\n pkg_name = \"serde\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=serde\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"1.0.228\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" } }, "crates__serde_core-1.0.228": { @@ -1234,7 +1043,7 @@ "https://static.crates.io/crates/serde_core/1.0.228/download" ], "strip_prefix": "serde_core-1.0.228", - "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"serde_core\",\n deps = [\n \"@crates__serde_core-1.0.228//:build_script_build\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"alloc\",\n \"result\",\n \"std\",\n ],\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=serde_core\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"1.0.228\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"alloc\",\n \"result\",\n \"std\",\n ],\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n edition = \"2021\",\n pkg_name = \"serde_core\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=serde_core\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"1.0.228\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" + "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"serde_core\",\n deps = [\n \":build_script_build\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"alloc\",\n \"result\",\n \"std\",\n ],\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=serde_core\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"1.0.228\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n build_script_env_files = [\n \":cargo_toml_env_vars\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"alloc\",\n \"result\",\n \"std\",\n ],\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n emit_warnings = False,\n edition = \"2021\",\n pkg_name = \"serde_core\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=serde_core\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"1.0.228\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" } }, "crates__serde_derive-1.0.228": { @@ -1260,7 +1069,7 @@ "https://static.crates.io/crates/serde_json/1.0.149/download" ], "strip_prefix": "serde_json-1.0.149", - "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"serde_json\",\n deps = [\n \"@crates__itoa-1.0.17//:itoa\",\n \"@crates__memchr-2.8.0//:memchr\",\n \"@crates__serde_core-1.0.228//:serde_core\",\n \"@crates__serde_json-1.0.149//:build_script_build\",\n \"@crates__zmij-1.0.21//:zmij\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"std\",\n ],\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=serde_json\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"1.0.149\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"std\",\n ],\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n edition = \"2021\",\n pkg_name = \"serde_json\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=serde_json\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"1.0.149\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" + "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"serde_json\",\n deps = [\n \":build_script_build\",\n \"@crates__itoa-1.0.17//:itoa\",\n \"@crates__memchr-2.8.0//:memchr\",\n \"@crates__serde_core-1.0.228//:serde_core\",\n \"@crates__zmij-1.0.21//:zmij\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"std\",\n ],\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=serde_json\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"1.0.149\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n build_script_env_files = [\n \":cargo_toml_env_vars\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"std\",\n ],\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n emit_warnings = False,\n edition = \"2021\",\n pkg_name = \"serde_json\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=serde_json\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"1.0.149\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" } }, "crates__syn-2.0.116": { @@ -1299,7 +1108,7 @@ "https://static.crates.io/crates/thiserror/2.0.18/download" ], "strip_prefix": "thiserror-2.0.18", - "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"thiserror\",\n deps = [\n \"@crates__thiserror-2.0.18//:build_script_build\",\n ],\n proc_macro_deps = [\n \"@crates__thiserror-impl-2.0.18//:thiserror_impl\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"std\",\n ],\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=thiserror\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"2.0.18\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"std\",\n ],\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n edition = \"2021\",\n pkg_name = \"thiserror\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=thiserror\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"2.0.18\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" + "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"thiserror\",\n deps = [\n \":build_script_build\",\n ],\n proc_macro_deps = [\n \"@crates__thiserror-impl-2.0.18//:thiserror_impl\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"std\",\n ],\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=thiserror\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"2.0.18\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n build_script_env_files = [\n \":cargo_toml_env_vars\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_features = [\n \"default\",\n \"std\",\n ],\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n emit_warnings = False,\n edition = \"2021\",\n pkg_name = \"thiserror\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=thiserror\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"2.0.18\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" } }, "crates__thiserror-impl-2.0.18": { @@ -1442,7 +1251,7 @@ "https://static.crates.io/crates/wit-bindgen/0.51.0/download" ], "strip_prefix": "wit-bindgen-0.51.0", - "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"wit_bindgen\",\n deps = [\n \"@crates__wit-bindgen-0.51.0//:build_script_build\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_root = \"src/lib.rs\",\n edition = \"2024\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=wit-bindgen\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"0.51.0\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n edition = \"2024\",\n pkg_name = \"wit-bindgen\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=wit-bindgen\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"0.51.0\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" + "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"wit_bindgen\",\n deps = [\n \":build_script_build\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_root = \"src/lib.rs\",\n edition = \"2024\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=wit-bindgen\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"0.51.0\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n build_script_env_files = [\n \":cargo_toml_env_vars\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n emit_warnings = False,\n edition = \"2024\",\n pkg_name = \"wit-bindgen\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=wit-bindgen\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"0.51.0\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" } }, "crates__wit-bindgen-core-0.51.0": { @@ -1468,7 +1277,7 @@ "https://static.crates.io/crates/wit-bindgen-rust/0.51.0/download" ], "strip_prefix": "wit-bindgen-rust-0.51.0", - "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"wit_bindgen_rust\",\n deps = [\n \"@crates__anyhow-1.0.101//:anyhow\",\n \"@crates__heck-0.5.0//:heck\",\n \"@crates__indexmap-2.13.0//:indexmap\",\n \"@crates__prettyplease-0.2.37//:prettyplease\",\n \"@crates__syn-2.0.116//:syn\",\n \"@crates__wasm-metadata-0.244.0//:wasm_metadata\",\n \"@crates__wit-bindgen-core-0.51.0//:wit_bindgen_core\",\n \"@crates__wit-bindgen-rust-0.51.0//:build_script_build\",\n \"@crates__wit-component-0.244.0//:wit_component\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_root = \"src/lib.rs\",\n edition = \"2024\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=wit-bindgen-rust\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"0.51.0\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n link_deps = [\n \"@crates__prettyplease-0.2.37//:prettyplease\",\n ],\n edition = \"2024\",\n pkg_name = \"wit-bindgen-rust\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=wit-bindgen-rust\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"0.51.0\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" + "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"wit_bindgen_rust\",\n deps = [\n \":build_script_build\",\n \"@crates__anyhow-1.0.101//:anyhow\",\n \"@crates__heck-0.5.0//:heck\",\n \"@crates__indexmap-2.13.0//:indexmap\",\n \"@crates__prettyplease-0.2.37//:prettyplease\",\n \"@crates__syn-2.0.116//:syn\",\n \"@crates__wasm-metadata-0.244.0//:wasm_metadata\",\n \"@crates__wit-bindgen-core-0.51.0//:wit_bindgen_core\",\n \"@crates__wit-component-0.244.0//:wit_component\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_root = \"src/lib.rs\",\n edition = \"2024\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=wit-bindgen-rust\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"0.51.0\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n build_script_env_files = [\n \":cargo_toml_env_vars\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n emit_warnings = False,\n link_deps = [\n \"@crates__prettyplease-0.2.37//:prettyplease\",\n ],\n edition = \"2024\",\n pkg_name = \"wit-bindgen-rust\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=wit-bindgen-rust\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"0.51.0\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" } }, "crates__wit-bindgen-rust-macro-0.51.0": { @@ -1481,7 +1290,7 @@ "https://static.crates.io/crates/wit-bindgen-rust-macro/0.51.0/download" ], "strip_prefix": "wit-bindgen-rust-macro-0.51.0", - "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_proc_macro\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_proc_macro(\n name = \"wit_bindgen_rust_macro\",\n deps = [\n \"@crates__anyhow-1.0.101//:anyhow\",\n \"@crates__prettyplease-0.2.37//:prettyplease\",\n \"@crates__proc-macro2-1.0.106//:proc_macro2\",\n \"@crates__quote-1.0.44//:quote\",\n \"@crates__syn-2.0.116//:syn\",\n \"@crates__wit-bindgen-core-0.51.0//:wit_bindgen_core\",\n \"@crates__wit-bindgen-rust-0.51.0//:wit_bindgen_rust\",\n \"@crates__wit-bindgen-rust-macro-0.51.0//:build_script_build\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_root = \"src/lib.rs\",\n edition = \"2024\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=wit-bindgen-rust-macro\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"0.51.0\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n link_deps = [\n \"@crates__prettyplease-0.2.37//:prettyplease\",\n ],\n edition = \"2024\",\n pkg_name = \"wit-bindgen-rust-macro\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=wit-bindgen-rust-macro\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"0.51.0\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" + "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_proc_macro\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_proc_macro(\n name = \"wit_bindgen_rust_macro\",\n deps = [\n \":build_script_build\",\n \"@crates__anyhow-1.0.101//:anyhow\",\n \"@crates__prettyplease-0.2.37//:prettyplease\",\n \"@crates__proc-macro2-1.0.106//:proc_macro2\",\n \"@crates__quote-1.0.44//:quote\",\n \"@crates__syn-2.0.116//:syn\",\n \"@crates__wit-bindgen-core-0.51.0//:wit_bindgen_core\",\n \"@crates__wit-bindgen-rust-0.51.0//:wit_bindgen_rust\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_root = \"src/lib.rs\",\n edition = \"2024\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=wit-bindgen-rust-macro\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"0.51.0\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n build_script_env_files = [\n \":cargo_toml_env_vars\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n emit_warnings = False,\n link_deps = [\n \"@crates__prettyplease-0.2.37//:prettyplease\",\n ],\n edition = \"2024\",\n pkg_name = \"wit-bindgen-rust-macro\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=wit-bindgen-rust-macro\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"0.51.0\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" } }, "crates__wit-component-0.244.0": { @@ -1520,7 +1329,7 @@ "https://static.crates.io/crates/zmij/1.0.21/download" ], "strip_prefix": "zmij-1.0.21", - "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"zmij\",\n deps = [\n \"@crates__zmij-1.0.21//:build_script_build\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=zmij\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"1.0.21\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n edition = \"2021\",\n pkg_name = \"zmij\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=zmij\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"1.0.21\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" + "build_file_content": "###############################################################################\n# @generated\n# DO NOT MODIFY: This file is auto-generated by a crate_universe tool. To \n# regenerate this file, run the following:\n#\n# bazel mod show_repo 'subspace'\n###############################################################################\n\nload(\n \"@rules_rust//cargo:defs.bzl\",\n \"cargo_build_script\",\n \"cargo_toml_env_vars\",\n)\n\nload(\"@rules_rust//rust:defs.bzl\", \"rust_library\")\n\n# buildifier: disable=bzl-visibility\nload(\"@rules_rust//crate_universe/private:selects.bzl\", \"selects\")\n\npackage(default_visibility = [\"//visibility:public\"])\n\ncargo_toml_env_vars(\n name = \"cargo_toml_env_vars\",\n src = \"Cargo.toml\",\n)\n\nrust_library(\n name = \"zmij\",\n deps = [\n \":build_script_build\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_root = \"src/lib.rs\",\n edition = \"2021\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=zmij\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n target_compatible_with = select({\n \"@rules_rust//rust/platform:aarch64-apple-darwin\": [],\n \"@rules_rust//rust/platform:aarch64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:wasm32-unknown-unknown\": [],\n \"@rules_rust//rust/platform:wasm32-wasip1\": [],\n \"@rules_rust//rust/platform:x86_64-pc-windows-msvc\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-linux-gnu\": [],\n \"@rules_rust//rust/platform:x86_64-unknown-nixos-gnu\": [],\n \"//conditions:default\": [\"@platforms//:incompatible\"],\n }),\n version = \"1.0.21\",\n)\n\ncargo_build_script(\n name = \"_bs\",\n build_script_env_files = [\n \":cargo_toml_env_vars\",\n ],\n compile_data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \"**/*.rs\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n crate_name = \"build_script_build\",\n crate_root = \"build.rs\",\n data = glob(\n allow_empty = True,\n include = [\"**\"],\n exclude = [\n \"**/* *\",\n \".tmp_git_root/**/*\",\n \"BUILD\",\n \"BUILD.bazel\",\n \"WORKSPACE\",\n \"WORKSPACE.bazel\",\n ],\n ),\n emit_warnings = False,\n edition = \"2021\",\n pkg_name = \"zmij\",\n rustc_env_files = [\n \":cargo_toml_env_vars\",\n ],\n rustc_flags = [\n \"--cap-lints=allow\",\n ],\n srcs = glob(\n allow_empty = True,\n include = [\"**/*.rs\"],\n ),\n tags = [\n \"cargo-bazel\",\n \"crate-name=zmij\",\n \"manual\",\n \"noclippy\",\n \"norustfmt\",\n ],\n version = \"1.0.21\",\n visibility = [\"//visibility:private\"],\n)\n\nalias(\n name = \"build_script_build\",\n actual = \":_bs\",\n tags = [\"manual\"],\n)\n" } } } @@ -1528,9 +1337,10 @@ }, "@@rules_rust+//crate_universe/private:internal_extensions.bzl%cu_nr": { "general": { - "bzlTransitiveDigest": "haQl4Qby7NmfQzWjTCcRCzDXlW/X396hi5Py519Vtr8=", - "usagesDigest": "v4We18mWSPeKV4GPp9Gne78W+jZOgP2pC1i4UN9br1g=", + "bzlTransitiveDigest": "FiYnsApmaUqhAe+QnvpBPZKhStJTwVHdWt+mf3/ghpI=", + "usagesDigest": "McimNXAztVHDzspa1Kng94T+YeyY/44zx9FkNqIMn2s=", "recordedInputs": [ + "REPO_MAPPING:apple_support+,bazel_skylib bazel_skylib+", "REPO_MAPPING:bazel_features+,bazel_features_globals bazel_features++version_extension+bazel_features_globals", "REPO_MAPPING:bazel_features+,bazel_features_version bazel_features++version_extension+bazel_features_version", "REPO_MAPPING:rules_cc+,bazel_skylib bazel_skylib+", @@ -1539,6 +1349,7 @@ "REPO_MAPPING:rules_cc+,platforms platforms", "REPO_MAPPING:rules_cc+,rules_cc rules_cc+", "REPO_MAPPING:rules_cc++compatibility_proxy+cc_compatibility_proxy,rules_cc rules_cc+", + "REPO_MAPPING:rules_rust+,apple_support apple_support+", "REPO_MAPPING:rules_rust+,bazel_features bazel_features+", "REPO_MAPPING:rules_rust+,bazel_skylib bazel_skylib+", "REPO_MAPPING:rules_rust+,bazel_tools bazel_tools", @@ -1561,6 +1372,7 @@ "@@rules_rust+//crate_universe:src/cli/splice.rs", "@@rules_rust+//crate_universe:src/cli/vendor.rs", "@@rules_rust+//crate_universe:src/config.rs", + "@@rules_rust+//crate_universe:src/config/label_injection.rs", "@@rules_rust+//crate_universe:src/context.rs", "@@rules_rust+//crate_universe:src/context/crate_context.rs", "@@rules_rust+//crate_universe:src/context/platforms.rs", @@ -1576,13 +1388,13 @@ "@@rules_rust+//crate_universe:src/metadata/metadata_annotation.rs", "@@rules_rust+//crate_universe:src/rendering.rs", "@@rules_rust+//crate_universe:src/rendering/template_engine.rs", + "@@rules_rust+//crate_universe:src/rendering/templates/defs_bzl_shim.j2", "@@rules_rust+//crate_universe:src/rendering/templates/module_bzl.j2", "@@rules_rust+//crate_universe:src/rendering/templates/partials/header.j2", "@@rules_rust+//crate_universe:src/rendering/templates/partials/module/aliases_map.j2", "@@rules_rust+//crate_universe:src/rendering/templates/partials/module/deps_map.j2", "@@rules_rust+//crate_universe:src/rendering/templates/partials/module/repo_git.j2", "@@rules_rust+//crate_universe:src/rendering/templates/partials/module/repo_http.j2", - "@@rules_rust+//crate_universe:src/rendering/templates/vendor_module.j2", "@@rules_rust+//crate_universe:src/rendering/verbatim/alias_rules.bzl", "@@rules_rust+//crate_universe:src/select.rs", "@@rules_rust+//crate_universe:src/splicing.rs", @@ -1607,11 +1419,11 @@ "binary": "cargo-bazel", "cargo_lockfile": "@@rules_rust+//crate_universe:Cargo.lock", "cargo_toml": "@@rules_rust+//crate_universe:Cargo.toml", - "version": "1.86.0", - "timeout": 900, + "version": "1.98.0", "rust_toolchain_cargo_template": "@rust_host_tools//:bin/{tool}", "rust_toolchain_rustc_template": "@rust_host_tools//:bin/{tool}", - "compressed_windows_toolchain_names": false + "compressed_windows_toolchain_names": false, + "timeout": 900 } } }, diff --git a/README.md b/README.md index cc0aa9c9..9809f89a 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,7 @@ See the file docs/subspace.pdf for full documentation. Additional documentation - [Channel Limit](docs/max-channels.md) - [Trigger Mechanism](docs/trigger-mechanism.md) - [C Client API](docs/c-client.md) +- [ASIL Client](docs/asil-client.md) - [Client Architecture](docs/client-architecture.md) - [Server Architecture](docs/server-architecture.md) - [Asio Backend and vsock Bridging](docs/asio-backend.md) @@ -96,7 +97,7 @@ bazel build --config=linux_arm32 //server:subspace_server //client:subspace_clie bazel test --config=linux_arm32 //common:common_test //client:client_test ``` -CMake uses `cmake/toolchains/linux-armhf.cmake` and a host `protoc`, the same way the Android cross compile does. The shared-memory layout matches a 64-bit build: `size_t` fields are padded so 64-bit atomics stay 8-byte aligned. +CMake uses `cmake/toolchains/linux-armhf.cmake` and a host `protoc` plus `protoc-gen-phaser`, the same way the Android cross compile does. The shared-memory layout matches a 64-bit build: `size_t` fields are padded so 64-bit atomics stay 8-byte aligned. ### 32-bit ARM (armhf) with Colima @@ -107,7 +108,7 @@ scripts/build-arm32-colima.sh scripts/build-arm32-colima.sh --test ``` -The script starts the aarch64 Colima profile if it is not already running, builds a host `protoc`, then cross-compiles into `build/armhf`. Binaries are ELF32 ARM, hard-float. The Rust client and the Asio RPC backends are skipped: the Rust build has no armhf Cargo target wired up here, and Boost.Context does not cross-compile cleanly. Tests run under `qemu-arm-static`. `client_test` raises its own file-descriptor soft limit at startup: the container's default is 1024, and past that the kernel drops `SCM_RIGHTS` payloads and the test reports truncated control data. +The script starts the aarch64 Colima profile if it is not already running, builds a host `protoc` and `protoc-gen-phaser`, then cross-compiles into `build/armhf`. Binaries are ELF32 ARM, hard-float. The Rust client and the Asio RPC backends are skipped: the Rust build has no armhf Cargo target wired up here, and Boost.Context does not cross-compile cleanly. Tests run under `qemu-arm-static`. `client_test` raises its own file-descriptor soft limit at startup: the container's default is 1024, and past that the kernel drops `SCM_RIGHTS` payloads and the test reports truncated control data. GitHub Actions job `cmake (armhf)` runs this cross-compile and the CMake tests on `ubuntu-latest`. @@ -2053,6 +2054,86 @@ The `manual_tests/pub` tool takes `--local=false` and `--channel=NAME`, and `manual_tests/sub` takes `--channel=NAME`, so you can also drive bridging by hand against servers on two different computers. +## Static Channel Config + +By default the server creates channels on demand as publishers and subscribers +arrive. For systems that need a fixed, known set of channels, start the server +with `--channel_config=FILE`. The file is a `StaticChannelConfig` +(`proto/subspace.proto`). A name ending in `.pb` or `.binpb` is protobuf +wire format, for a configuration a tool generated. Any other name is +protobuf text format: + +``` +multiplexers { name: "/sensors" slot_size: 1024 num_slots: 16 type: "Sensor" } +channels { name: "/vehicle/state" slot_size: 256 num_slots: 8 type: "State" } +channels { name: "/sensors/lidar" mux: "/sensors" vchan_id: 0 } +channels { name: "/sensors/radar" mux: "/sensors" vchan_id: 1 } +``` + +To give the server a wire-format file instead, encode the text with `protoc`, +which needs the protobuf well-known types on its include path: + +```bash +protoc -I proto --encode=subspace.StaticChannelConfig proto/subspace.proto \ + < channels.textproto > channels.pb +``` + +Either format is validated the same way. A wire-format file that has a field +this build doesn't know is rejected, as a text file with an unknown field is. + +`type` is bytes, the same as the channel type on the wire. A quoted string +such as `type: "State"` is that text's bytes. An opaque blob, such as ROS +metadata or a protobuf descriptor, uses the same field; protobuf text escapes +carry bytes that are not text (`type: "\000\377..."`). A channel on a +multiplexer leaves `type` unset and uses the multiplexer's type. + +The server creates every configured channel and its message buffers before it +accepts clients, so a subscriber that starts first gets the full channel +layout and maps the buffers instead of waiting for a publisher. With a config +loaded: + +- A configured channel is shared by the standard clients and the ASIL client. + Its publishers, of either kind, must set `server_defined`. +- A channel that isn't configured can be created by a standard publisher that + specifies the layout itself (`slot_size`, `num_slots` and the other layout + options) and does not set `server_defined`. An ASIL publisher cannot create + or join that channel. Any subscriber can, including an ASIL subscriber. + The channel is created when the first publisher or subscriber asks for it + and removed when it has no users. An ASIL subscriber that opens before the + channel has buffers gets `Error::kNoBuffers`. +- Configured channels stay for the life of the server, including when they + have no publishers or subscribers. +- The server defines the layout. Publishers on a configured channel must set + `SetServerDefined(true)` and leave every option that shapes the shared + memory unset: `SetSlotSize`, `SetNumSlots`, `SetFixedSize`, + `SetChecksumSize`, `SetMetadataSize`, `SetSubscriberQueueArenaSize` and + `SetUseSplitBuffers`. The server rejects a publisher that sets any of them + or leaves out `server_defined`, and also a `server_defined` publisher on a + channel that isn't configured. The publisher takes its slot size, number of + slots, checksum size, metadata size and split buffer setting from the + server, and is always fixed size: + + ```c++ + absl::StatusOr pub = client.CreatePublisher( + "/vehicle/state", subspace::PublisherOptions().SetServerDefined(true)); + ``` + + The C client has `subspace_publisher_options_server_defined()`, Python has + `set_server_defined(True)`, Rust has `set_server_defined(true)` and the ASIL + client has `PublisherOptions::server_defined`. Options that don't change + the layout, such as reliable, checksum, type and mux, work as usual. +- `use_split_buffers: true` gives a channel or multiplexer + [split buffers](docs/split-buffers.md), which the server creates. +- A channel on a multiplexer takes its slot size, number of slots, type, + prefix layout and split buffer setting from the multiplexer and needs an + explicit `vchan_id`. +- Names starting with `/subspace/` are reserved for the server. +- After a restart from a shadow, the recovered channels must match the config + or the server doesn't start. + +The [ASIL client](docs/asil-client.md) is a C++17 client for safety-related +software that shares these channels with the standard clients. + ## Shadow Server (Crash Recovery) Subspace supports a **shadow process** that mirrors the server's channel, @@ -2128,6 +2209,7 @@ its full state from whichever shadow is available. |------|---------|-------------| | `--shadow_socket` | `""` (disabled) | Unix socket path for the primary shadow process | | `--secondary_shadow_socket` | `""` (disabled) | Unix socket path for the secondary shadow process | +| `--channel_config` | `""` (disabled) | `StaticChannelConfig` file. `.pb` and `.binpb` are protobuf wire format; any other name is text format. See [Static Channel Config](#static-channel-config). | ### Shadow Flags diff --git a/android/CMakeLists.txt b/android/CMakeLists.txt index aa1189b1..27fae7d4 100644 --- a/android/CMakeLists.txt +++ b/android/CMakeLists.txt @@ -1,4 +1,4 @@ -# Copyright 2026 General Motors Inc. +# Copyright 2026 General Motors # All Rights Reserved # See LICENSE file for licensing information. diff --git a/android/java/BUILD.bazel b/android/java/BUILD.bazel index d8c02634..0e41635c 100644 --- a/android/java/BUILD.bazel +++ b/android/java/BUILD.bazel @@ -1,4 +1,4 @@ -# Copyright 2026 General Motors Inc. +# Copyright 2026 General Motors # All Rights Reserved # See LICENSE file for licensing information. diff --git a/android/java/com/subspace/test/SubspaceJavaClientTest.java b/android/java/com/subspace/test/SubspaceJavaClientTest.java index a828b197..a6003b42 100644 --- a/android/java/com/subspace/test/SubspaceJavaClientTest.java +++ b/android/java/com/subspace/test/SubspaceJavaClientTest.java @@ -1,4 +1,4 @@ -// Copyright 2026 General Motors Inc. +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/android/java/subspace_java_client_test.sh b/android/java/subspace_java_client_test.sh index 778d19c8..6cb3f290 100644 --- a/android/java/subspace_java_client_test.sh +++ b/android/java/subspace_java_client_test.sh @@ -1,6 +1,6 @@ #!/system/bin/sh -# Copyright 2026 General Motors Inc. +# Copyright 2026 General Motors # All Rights Reserved # See LICENSE file for licensing information. diff --git a/asil_client/Android.bp b/asil_client/Android.bp new file mode 100644 index 00000000..f186b638 --- /dev/null +++ b/asil_client/Android.bp @@ -0,0 +1,37 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +// The ASIL client core: C++17, the standard library and POSIX only. It is +// built without exceptions or RTTI. +cc_library_static { + name: "libsubspace_asil_client", + defaults: ["subspace_defaults"], + srcs: [ + "channel_memory.cc", + "client.cc", + "error.cc", + "publisher.cc", + "subscriber.cc", + ], + include_dirs: ["external/subspace"], + cppflags: ["-fno-exceptions"], + rtti: false, + static_libs: ["libsubspace_crc32"], +} + +// The handshake with the server, using phaser messages in fixed buffers. +cc_library_static { + name: "libsubspace_asil_phaser_connection", + defaults: ["subspace_defaults"], + srcs: ["phaser_connection.cc"], + include_dirs: ["external/subspace"], + cppflags: ["-fno-exceptions"], + rtti: false, + static_libs: [ + "libsubspace_asil_client", + "libsubspace_phaser", + ], + export_static_lib_headers: ["libsubspace_phaser"], +} diff --git a/asil_client/BUILD.bazel b/asil_client/BUILD.bazel new file mode 100644 index 00000000..c97b9153 --- /dev/null +++ b/asil_client/BUILD.bazel @@ -0,0 +1,115 @@ +package(default_visibility = ["//visibility:public"]) + +load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") + +# The ASIL client core: C++17, the standard library and POSIX only. It is +# built without exceptions or RTTI. +cc_library( + name = "asil_client", + srcs = [ + "channel_memory.cc", + "client.cc", + "error.cc", + "publisher.cc", + "subscriber.cc", + ], + hdrs = [ + "channel_memory.h", + "client.h", + "error.h", + "publisher.h", + "server_connection.h", + "shm_layout.h", + "split_buffer.h", + "subscriber.h", + "unique_fd.h", + ], + copts = [ + "-fno-exceptions", + "-fno-rtti", + ], + linkopts = select({ + "//:macos_x86_64": [], + "//:macos_arm64": [], + "//:macos_default": [], + "//:android": [], + "//:qnx": ["-lsocket"], + "//conditions:default": ["-lrt"], + }), + deps = [ + "//common:crc32", + "//common:max_buffers_setting", + "//common:max_channels_setting", + "//common:max_slot_owners_setting", + "//common:shm_layout", + "//common:shm_protocol", + ], +) + +# The standard server handshake, using Phaser messages in fixed buffers and the +# native Phaser payload as the wire format. +cc_library( + name = "phaser_connection", + srcs = ["phaser_connection.cc"], + hdrs = ["phaser_connection.h"], + copts = [ + "-fno-exceptions", + "-fno-rtti", + ], + deps = [ + ":asil_client", + "//common:server_wire", + ], +) + +cc_test( + name = "layout_test", + size = "small", + srcs = ["layout_test.cc"], + deps = [ + ":asil_client", + "//client:subspace_client", + "//common:shm_protocol", + "//common:subspace_common", + "@googletest//:gtest_main", + ], +) + +cc_test( + name = "asil_client_test", + size = "small", + srcs = ["asil_client_test.cc"], + deps = [ + ":asil_client", + ":phaser_connection", + "//client:subspace_client", + "//client:test_fixture", + "//server", + "@abseil-cpp//absl/status", + "@abseil-cpp//absl/status:status_matchers", + "@abseil-cpp//absl/status:statusor", + "@coroutines//:co", + "@googletest//:gtest", + ], +) + +# Not part of `bazel test //...`. Run it with `bazelisk test //asil_client:stress_test`. +cc_test( + name = "stress_test", + size = "large", + srcs = ["stress_test.cc"], + tags = ["manual"], + deps = [ + ":asil_client", + ":phaser_connection", + "//client:subspace_client", + "//client:test_fixture", + "//server", + "@abseil-cpp//absl/status", + "@abseil-cpp//absl/status:status_matchers", + "@abseil-cpp//absl/status:statusor", + "@abseil-cpp//absl/strings:str_format", + "@coroutines//:co", + "@googletest//:gtest", + ], +) diff --git a/asil_client/CMakeLists.txt b/asil_client/CMakeLists.txt new file mode 100644 index 00000000..582112fd --- /dev/null +++ b/asil_client/CMakeLists.txt @@ -0,0 +1,56 @@ +# CMakeLists.txt for the asil_client subdirectory + +# The ASIL client core: C++17, the standard library and POSIX only. It is +# built without exceptions or RTTI. +add_library(subspace_asil_client STATIC + channel_memory.cc + client.cc + error.cc + publisher.cc + subscriber.cc +) +target_compile_options(subspace_asil_client PRIVATE -fno-exceptions -fno-rtti) +target_link_libraries(subspace_asil_client PUBLIC subspace_crc32) +if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND NOT ANDROID) + target_link_libraries(subspace_asil_client PUBLIC rt) +endif() + +add_executable(asil_layout_test layout_test.cc) +add_test(NAME asil_layout_test COMMAND asil_layout_test) +target_link_libraries(asil_layout_test PUBLIC + subspace_asil_client + subspace_client + subspace_common + gtest + gtest_main +) + +# The handshake with the server, using phaser messages in fixed buffers. +add_library(subspace_asil_phaser_connection STATIC + phaser_connection.cc +) +target_compile_options(subspace_asil_phaser_connection PRIVATE -fno-exceptions -fno-rtti) +target_link_libraries(subspace_asil_phaser_connection PUBLIC + subspace_asil_client + subspace_phaser +) + +add_executable(asil_client_test asil_client_test.cc) +add_test(NAME asil_client_test COMMAND asil_client_test) +target_link_libraries(asil_client_test PUBLIC + subspace_asil_client + subspace_asil_phaser_connection + subspace_client + libserver + gmock +) + +# Manual, like client/stress_test. Build it, but don't register it with ctest. +add_executable(asil_stress_test stress_test.cc) +target_link_libraries(asil_stress_test PUBLIC + subspace_asil_client + subspace_asil_phaser_connection + subspace_client + libserver + gmock +) diff --git a/asil_client/asil_client_test.cc b/asil_client/asil_client_test.cc new file mode 100644 index 00000000..6a9cf25d --- /dev/null +++ b/asil_client/asil_client_test.cc @@ -0,0 +1,1923 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +// Interoperability tests: the ASIL client and the standard client share +// channels on a server running a static channel config. Static channels keep +// their messages for the life of the server, so each test uses its own +// channel. + +#include "client/test_fixture.h" + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "asil_client/client.h" +#include "asil_client/phaser_connection.h" +#include "asil_client/publisher.h" +#include "asil_client/shm_layout.h" +#include "asil_client/split_buffer.h" +#include "asil_client/subscriber.h" +#include "server/static_config.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +// Counts heap allocations made by the thread that called StartCounting. The +// server runs in this process, so other threads must not be counted. +#if defined(__APPLE__) +// The malloc logger sees every allocation in the process, including malloc, +// calloc and realloc calls that don't go through operator new. It can run +// while a thread's local storage is being set up, so it can't use any. +extern "C" { +extern void (*malloc_logger)(uint32_t type, uintptr_t arg1, uintptr_t arg2, + uintptr_t arg3, uintptr_t result, + uint32_t num_hot_frames_to_skip); +} + +constexpr uint32_t kMallocLoggerAlloc = 2; +std::atomic counted_thread{0}; +std::atomic allocations{0}; + +uintptr_t CurrentThread() { return reinterpret_cast(pthread_self()); } + +void CountMalloc(uint32_t type, uintptr_t, uintptr_t, uintptr_t, uintptr_t, + uint32_t) { + if ((type & kMallocLoggerAlloc) != 0 && + counted_thread.load(std::memory_order_relaxed) == CurrentThread()) { + allocations++; + } +} + +struct MallocLoggerInstaller { + MallocLoggerInstaller() { malloc_logger = CountMalloc; } +} malloc_logger_installer; + +void StartCounting() { + allocations = 0; + counted_thread = CurrentThread(); +} + +int StopCounting() { + counted_thread = 0; + return allocations; +} +#else +thread_local bool counting_allocations = false; +thread_local int allocations = 0; + +void StartCounting() { + allocations = 0; + counting_allocations = true; +} + +int StopCounting() { + counting_allocations = false; + return allocations; +} +#endif +} // namespace + +#if !defined(__APPLE__) +void *operator new(std::size_t size) { + if (counting_allocations) { + allocations++; + } + void *p = std::malloc(size == 0 ? 1 : size); + if (p == nullptr) { + throw std::bad_alloc(); + } + return p; +} + +void operator delete(void *p) noexcept { std::free(p); } +void operator delete(void *p, std::size_t) noexcept { std::free(p); } +#endif + +namespace { + +namespace asil = ::subspace::asil; +using ::testing::AnyOf; +using ::testing::HasSubstr; + +constexpr char kConfig[] = R"pb( + multiplexers { name: "/asil/mux" slot_size: 128 num_slots: 8 } + channels { name: "/asil/to_std" slot_size: 256 num_slots: 8 type: "T" } + channels { name: "/asil/from_std" slot_size: 256 num_slots: 8 type: "T" } + channels { name: "/asil/wait" slot_size: 64 num_slots: 4 } + channels { name: "/asil/late_sub" slot_size: 64 num_slots: 4 } + channels { name: "/asil/sum_to_std" slot_size: 128 num_slots: 4 } + channels { name: "/asil/sum_from_std" slot_size: 128 num_slots: 4 } + channels { name: "/asil/meta" slot_size: 64 num_slots: 8 metadata_size: 16 } + channels { name: "/asil/newest" slot_size: 64 num_slots: 8 } + channels { name: "/asil/drops_in" slot_size: 64 num_slots: 4 } + channels { name: "/asil/drops_out" slot_size: 64 num_slots: 4 } + channels { name: "/asil/activate" slot_size: 64 num_slots: 4 } + channels { name: "/asil/cycle" slot_size: 64 num_slots: 4 } + channels { name: "/asil/hold" slot_size: 64 num_slots: 4 } + channels { name: "/asil/reject" slot_size: 64 num_slots: 4 } + channels { name: "/asil/close" slot_size: 64 num_slots: 4 } + channels { name: "/asil/v1" mux: "/asil/mux" vchan_id: 1 } + channels { name: "/asil/v2" mux: "/asil/mux" vchan_id: 2 } + channels { name: "/asil/rel_to_std" slot_size: 64 num_slots: 4 } + channels { name: "/asil/rel_from_std" slot_size: 64 num_slots: 4 } + channels { name: "/asil/rel_newest" slot_size: 64 num_slots: 4 } + channels { name: "/asil/rel_late" slot_size: 64 num_slots: 4 } + channels { name: "/asil/multi" slot_size: 64 num_slots: 8 } + channels { name: "/asil/no_alloc" slot_size: 64 num_slots: 4 } + channels { name: "/asil/steady" slot_size: 64 num_slots: 16 } + channels { name: "/asil/steady_rel" slot_size: 64 num_slots: 8 } + channels { name: "/asil/steady_meta" slot_size: 64 num_slots: 8 metadata_size: 16 } + channels { name: "/asil/oversize" slot_size: 64 num_slots: 4 } + channels { name: "/asil/early_sub" slot_size: 64 num_slots: 4 } + channels { + name: "/asil/split_to_std" + slot_size: 256 + num_slots: 4 + use_split_buffers: true + } + channels { + name: "/asil/split_from_std" + slot_size: 256 + num_slots: 4 + use_split_buffers: true + } + channels { + name: "/asil/split_reject" + slot_size: 64 + num_slots: 4 + use_split_buffers: true + } + multiplexers { + name: "/asil/split_mux" + slot_size: 128 + num_slots: 8 + use_split_buffers: true + } + channels { name: "/asil/split_v" mux: "/asil/split_mux" vchan_id: 4 } +)pb"; + +subspace::PublisherOptions FixedSize() { + return subspace::PublisherOptions().SetFixedSize(true); +} + +// A standard publisher on a static channel. +subspace::PublisherOptions ServerDefined() { + return subspace::PublisherOptions().SetServerDefined(true); +} + +void StdPublish(subspace::Publisher &pub, const std::string &text) { + absl::StatusOr buffer = pub.GetMessageBuffer(); + ASSERT_OK(buffer); + memcpy(*buffer, text.data(), text.size()); + ASSERT_OK(pub.PublishMessage(static_cast(text.size()))); +} + +void AsilPublish(asil::Publisher &pub, const std::string &text) { + void *buffer = pub.Buffer(); + ASSERT_NE(nullptr, buffer); + memcpy(buffer, text.data(), text.size()); + ASSERT_EQ(asil::Error::kOk, pub.Publish(text.size())); +} + +std::string Text(const asil::Message &msg) { + return std::string(static_cast(msg.data), msg.length); +} + +std::string Text(const subspace::Message &msg) { + return std::string(static_cast(msg.buffer), msg.length); +} + +// A copy of a message read by a standard subscriber. The message itself is +// released before returning because standard subscribers default to one +// active message. +struct StdMessage { + std::string text; + uint64_t ordinal = 0; + uint64_t timestamp = 0; + bool is_activation = false; + bool checksum_error = false; + std::string metadata; +}; + +StdMessage StdRead(subspace::Subscriber &sub) { + absl::StatusOr msg = sub.ReadMessage(); + EXPECT_TRUE(msg.ok()) << msg.status(); + StdMessage copy; + if (!msg.ok()) { + return copy; + } + copy.text = Text(*msg); + copy.ordinal = msg->ordinal; + copy.timestamp = msg->timestamp; + copy.is_activation = msg->is_activation; + copy.checksum_error = msg->checksum_error; + absl::Span metadata = sub.GetMetadata(); + copy.metadata.assign(reinterpret_cast(metadata.data()), + metadata.size()); + return copy; +} + +bool Readable(int fd) { + struct pollfd p = {fd, POLLIN, 0}; + return ::poll(&p, 1, 0) == 1; +} + +asil::PublisherOptions AsilPubOptions(int64_t slot_size, int32_t num_slots) { + asil::PublisherOptions options; + options.slot_size = slot_size; + options.num_slots = num_slots; + return options; +} + +// An ASIL publisher on a static channel. +asil::PublisherOptions StaticPubOptions() { + asil::PublisherOptions options; + options.server_defined = true; + return options; +} + +// A server on its own thread. config is a static channel config, or null +// for a server that creates channels on demand. +class TestServer { +public: + void Start(const char *config) { + struct rlimit nofile; + if (getrlimit(RLIMIT_NOFILE, &nofile) == 0) { + rlim_t target = 65536; + if (nofile.rlim_max != RLIM_INFINITY && nofile.rlim_max < target) { + target = nofile.rlim_max; + } + if (nofile.rlim_cur < target) { + nofile.rlim_cur = target; + (void)setrlimit(RLIMIT_NOFILE, &nofile); + } + } + +#if defined(__ANDROID__) + char socket_name_template[] = "/data/local/tmp/subspaceXXXXXX"; // NOLINT +#else + char socket_name_template[] = "/tmp/subspaceXXXXXX"; // NOLINT +#endif + ::close(mkstemp(&socket_name_template[0])); + socket_ = &socket_name_template[0]; + + (void)pipe(server_pipe_); + + server_ = std::make_unique( + engine_, socket_, "", 0, 0, + /*local=*/true, server_pipe_[1], /*initial_ordinal=*/1, + /*wait_for_clients=*/true); + if (config != nullptr) { + absl::StatusOr parsed = + subspace::ParseStaticChannelConfig(config); + ASSERT_OK(parsed); + ASSERT_OK(server_->SetStaticChannelConfig(*std::move(parsed))); + } + + server_thread_ = std::thread([this]() { + absl::Status s = server_->Run(); + if (!s.ok()) { + fprintf(stderr, "Error running Subspace server: %s\n", + s.ToString().c_str()); + exit(1); + } + }); + + char buf[8]; + (void)::read(server_pipe_[0], buf, 8); + } + + void Stop() { + server_->Stop(); + + char buf[8]; + (void)::read(server_pipe_[0], buf, 8); + server_thread_.join(); + server_->CleanupAfterSession(); + server_.reset(); + ::close(server_pipe_[0]); + ::close(server_pipe_[1]); + (void)remove(socket_.c_str()); + } + + const std::string &Socket() const { return socket_; } + +private: + subspace::async::RuntimeEngine engine_; + std::string socket_; + int server_pipe_[2]; + std::unique_ptr server_; + std::thread server_thread_; +}; + +// Connects a standard client and an ASIL client to a test server. +class AsilTestBase : public ::testing::Test { +public: + subspace::Client &Std() { return std_client_; } + asil::Client &Asil() { return asil_client_; } + asil::PhaserServerConnection &Connection() { return connection_; } + +protected: + void Connect(const std::string &socket) { + signal(SIGPIPE, SIG_IGN); + ASSERT_OK(std_client_.Init(socket)); + ASSERT_EQ(asil::Error::kOk, connection_.Connect(socket.c_str())); + ASSERT_EQ(asil::Error::kOk, asil_client_.Init(connection_, "asil_test")); + } + +private: + subspace::Client std_client_; + asil::PhaserServerConnection connection_; + asil::Client asil_client_; +}; + +// A server with a static channel config. +class AsilClientTest : public AsilTestBase { +public: + static void SetUpTestSuite() { server_.Start(kConfig); } + static void TearDownTestSuite() { server_.Stop(); } + void SetUp() override { Connect(server_.Socket()); } + + static const std::string &Socket() { return server_.Socket(); } + +private: + inline static TestServer server_; +}; + +// A server that creates channels on demand, so channels can resize and use +// subscriber queues. +class AsilDynamicTest : public AsilTestBase { +public: + static void SetUpTestSuite() { server_.Start(nullptr); } + static void TearDownTestSuite() { server_.Stop(); } + void SetUp() override { Connect(server_.Socket()); } + +private: + inline static TestServer server_; +}; + +TEST_F(AsilClientTest, AsilPublisherStandardSubscriber) { + absl::StatusOr sub = + Std().CreateSubscriber("/asil/to_std"); + ASSERT_OK(sub); + + asil::Publisher pub; + asil::PublisherOptions options = StaticPubOptions(); + options.type = "T"; + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/asil/to_std", options, pub)); + EXPECT_EQ(256, pub.SlotSize()); + EXPECT_EQ(8, pub.NumSlots()); + + asil::PublishedMessage published; + void *buffer = pub.Buffer(); + ASSERT_NE(nullptr, buffer); + memcpy(buffer, "one", 3); + ASSERT_EQ(asil::Error::kOk, pub.Publish(3, &published)); + EXPECT_NE(0u, published.ordinal); + AsilPublish(pub, "two"); + AsilPublish(pub, "three"); + + StdMessage msg = StdRead(*sub); + EXPECT_EQ("one", msg.text); + EXPECT_EQ(published.ordinal, msg.ordinal); + EXPECT_EQ(published.timestamp, msg.timestamp); + EXPECT_EQ("two", StdRead(*sub).text); + EXPECT_EQ("three", StdRead(*sub).text); + EXPECT_EQ("", StdRead(*sub).text); +} + +TEST_F(AsilClientTest, StandardPublisherAsilSubscriber) { + asil::Subscriber sub; + asil::SubscriberOptions options; + options.type = "T"; + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/asil/from_std", options, sub)); + + // Nothing has been published, so there is no buffer to read yet. + asil::Message msg; + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ(0u, msg.length); + + absl::StatusOr pub = + Std().CreatePublisher("/asil/from_std", ServerDefined()); + ASSERT_OK(pub); + StdPublish(*pub, "alpha"); + StdPublish(*pub, "beta"); + + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ("alpha", Text(msg)); + EXPECT_EQ(0u, msg.dropped); + const uint64_t first = msg.ordinal; + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ("beta", Text(msg)); + EXPECT_EQ(first + 1, msg.ordinal); + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ(0u, msg.length); +} + +TEST_F(AsilClientTest, AsilToAsilWithWait) { + asil::Subscriber sub; + ASSERT_EQ(asil::Error::kOk, Asil().CreateSubscriber("/asil/wait", {}, sub)); + asil::Publisher pub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/asil/wait", StaticPubOptions(), pub)); + + // Drain the trigger set when the subscriber opened. + asil::Message msg; + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ(0u, msg.length); + EXPECT_EQ(asil::Error::kTimeout, sub.Wait(10)); + + AsilPublish(pub, "wake"); + EXPECT_EQ(asil::Error::kOk, sub.Wait(1000)); + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ("wake", Text(msg)); +} + +TEST_F(AsilClientTest, SubscriberJoinsAfterPublisher) { + asil::Publisher pub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/asil/late_sub", StaticPubOptions(), pub)); + + absl::StatusOr sub = + Std().CreateSubscriber("/asil/late_sub"); + ASSERT_OK(sub); + EXPECT_EQ("", StdRead(*sub).text); + ASSERT_FALSE(Readable(sub->GetPollFd().fd)); + + // The publisher learns of the new subscriber's trigger when it publishes. + AsilPublish(pub, "late"); + EXPECT_TRUE(Readable(sub->GetPollFd().fd)); + EXPECT_EQ("late", StdRead(*sub).text); +} + +TEST_F(AsilClientTest, ChecksumToStandard) { + absl::StatusOr sub = Std().CreateSubscriber( + "/asil/sum_to_std", subspace::SubscriberOptions().SetChecksum(true)); + ASSERT_OK(sub); + asil::Publisher pub; + asil::PublisherOptions options = StaticPubOptions(); + options.checksum = true; + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/asil/sum_to_std", options, pub)); + AsilPublish(pub, "checked"); + + StdMessage msg = StdRead(*sub); + EXPECT_EQ("checked", msg.text); + EXPECT_FALSE(msg.checksum_error); +} + +TEST_F(AsilClientTest, ChecksumFromStandard) { + asil::SubscriberOptions strict; + strict.checksum = true; + asil::Subscriber strict_sub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/asil/sum_from_std", strict, strict_sub)); + asil::SubscriberOptions lenient = strict; + lenient.pass_checksum_errors = true; + asil::Subscriber lenient_sub; + ASSERT_EQ(asil::Error::kOk, Asil().CreateSubscriber("/asil/sum_from_std", + lenient, lenient_sub)); + + absl::StatusOr pub = Std().CreatePublisher( + "/asil/sum_from_std", ServerDefined().SetChecksum(true)); + ASSERT_OK(pub); + StdPublish(*pub, "good"); + + // Corrupt the second message after it has been published. + absl::StatusOr buffer = pub->GetMessageBuffer(); + ASSERT_OK(buffer); + memcpy(*buffer, "bad", 3); + ASSERT_OK(pub->PublishMessage(3)); + static_cast(*buffer)[0] = 'B'; + + asil::Message msg; + ASSERT_EQ(asil::Error::kOk, strict_sub.ReadMessage(msg)); + EXPECT_EQ("good", Text(msg)); + EXPECT_FALSE(msg.checksum_error); + EXPECT_EQ(asil::Error::kChecksumMismatch, strict_sub.ReadMessage(msg)); + EXPECT_EQ(0u, msg.length); + + ASSERT_EQ(asil::Error::kOk, lenient_sub.ReadMessage(msg)); + EXPECT_EQ("good", Text(msg)); + ASSERT_EQ(asil::Error::kOk, lenient_sub.ReadMessage(msg)); + EXPECT_EQ("Bad", Text(msg)); + EXPECT_TRUE(msg.checksum_error); +} + +TEST_F(AsilClientTest, Metadata) { + asil::Subscriber asil_sub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/asil/meta", {}, asil_sub)); + absl::StatusOr std_sub = + Std().CreateSubscriber("/asil/meta"); + ASSERT_OK(std_sub); + + asil::Publisher asil_pub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/asil/meta", StaticPubOptions(), asil_pub)); + ASSERT_EQ(16u, asil_pub.MetadataSize()); + memcpy(asil_pub.Metadata(), "asil-metadata!!", 16); + AsilPublish(asil_pub, "from asil"); + + StdMessage std_msg = StdRead(*std_sub); + EXPECT_EQ("from asil", std_msg.text); + EXPECT_EQ(std::string("asil-metadata!!", 16), std_msg.metadata); + + absl::StatusOr std_pub = + Std().CreatePublisher("/asil/meta", ServerDefined()); + ASSERT_OK(std_pub); + absl::StatusOr buffer = std_pub->GetMessageBuffer(); + ASSERT_OK(buffer); + absl::Span meta = std_pub->GetMetadata(); + ASSERT_EQ(16u, meta.size()); + memcpy(meta.data(), "std-metadata!!!", 16); + memcpy(*buffer, "from std", 8); + ASSERT_OK(std_pub->PublishMessage(8)); + + asil::Message msg; + ASSERT_EQ(asil::Error::kOk, asil_sub.ReadMessage(msg)); + EXPECT_EQ("from asil", Text(msg)); + ASSERT_EQ(16u, msg.metadata_length); + EXPECT_EQ(0, memcmp(msg.metadata, "asil-metadata!!", 16)); + ASSERT_EQ(asil::Error::kOk, asil_sub.ReadMessage(msg)); + EXPECT_EQ("from std", Text(msg)); + ASSERT_EQ(16u, msg.metadata_length); + EXPECT_EQ(0, memcmp(msg.metadata, "std-metadata!!!", 16)); +} + +TEST_F(AsilClientTest, ReadNewest) { + asil::Subscriber sub; + ASSERT_EQ(asil::Error::kOk, Asil().CreateSubscriber("/asil/newest", {}, sub)); + absl::StatusOr pub = + Std().CreatePublisher("/asil/newest", ServerDefined()); + ASSERT_OK(pub); + StdPublish(*pub, "old"); + StdPublish(*pub, "older"); + StdPublish(*pub, "newest"); + + asil::Message msg; + ASSERT_EQ(asil::Error::kOk, + sub.ReadMessage(msg, asil::ReadMode::kReadNewest)); + EXPECT_EQ("newest", Text(msg)); + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ(0u, msg.length); + + StdPublish(*pub, "next"); + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ("next", Text(msg)); +} + +TEST_F(AsilClientTest, AsilSubscriberCountsDrops) { + asil::Subscriber sub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/asil/drops_in", {}, sub)); + absl::StatusOr pub = + Std().CreatePublisher("/asil/drops_in", ServerDefined()); + ASSERT_OK(pub); + StdPublish(*pub, "first"); + asil::Message msg; + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ("first", Text(msg)); + const uint64_t first = msg.ordinal; + sub.ReleaseMessage(); + + for (int i = 0; i < 10; i++) { + StdPublish(*pub, "m" + std::to_string(i)); + } + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_GT(msg.dropped, 0u); + EXPECT_EQ(first + 1 + msg.dropped, msg.ordinal); + uint64_t last = msg.ordinal; + std::string last_text = Text(msg); + int received = 1; + for (;;) { + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + if (msg.length == 0) { + break; + } + EXPECT_EQ(last + 1, msg.ordinal); + EXPECT_EQ(0u, msg.dropped); + last = msg.ordinal; + last_text = Text(msg); + received++; + } + EXPECT_EQ("m9", last_text); + EXPECT_EQ(first + 10, last); + EXPECT_LT(received, 10); +} + +TEST_F(AsilClientTest, StandardSubscriberSeesAsilDrops) { + absl::StatusOr sub = + Std().CreateSubscriber("/asil/drops_out"); + ASSERT_OK(sub); + int64_t dropped = 0; + ASSERT_OK(sub->RegisterDroppedMessageCallback( + [&dropped](subspace::Subscriber *, int64_t n) { dropped += n; })); + + asil::Publisher pub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/asil/drops_out", StaticPubOptions(), pub)); + AsilPublish(pub, "first"); + EXPECT_EQ("first", StdRead(*sub).text); + + for (int i = 0; i < 10; i++) { + AsilPublish(pub, "m" + std::to_string(i)); + } + int received = 0; + std::string last; + for (;;) { + const StdMessage msg = StdRead(*sub); + if (msg.text.empty()) { + break; + } + last = msg.text; + received++; + } + EXPECT_EQ("m9", last); + EXPECT_GT(dropped, 0); + EXPECT_EQ(10, received + dropped); +} + +TEST_F(AsilClientTest, Activation) { + absl::StatusOr std_sub = Std().CreateSubscriber( + "/asil/activate", subspace::SubscriberOptions().SetPassActivation(true)); + ASSERT_OK(std_sub); + asil::Subscriber asil_sub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/asil/activate", {}, asil_sub)); + + asil::Publisher pub; + asil::PublisherOptions options = StaticPubOptions(); + options.activate = true; + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/asil/activate", options, pub)); + AsilPublish(pub, "payload"); + + EXPECT_TRUE(StdRead(*std_sub).is_activation); + StdMessage msg = StdRead(*std_sub); + EXPECT_FALSE(msg.is_activation); + EXPECT_EQ("payload", msg.text); + + asil::Message asil_msg; + ASSERT_EQ(asil::Error::kOk, asil_sub.ReadMessage(asil_msg)); + EXPECT_FALSE(asil_msg.is_activation); + EXPECT_EQ("payload", Text(asil_msg)); + EXPECT_EQ(0u, asil_msg.dropped); +} + +TEST_F(AsilClientTest, ManyMessagesThroughFewSlots) { + asil::Subscriber asil_sub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/asil/cycle", {}, asil_sub)); + absl::StatusOr std_sub = + Std().CreateSubscriber("/asil/cycle"); + ASSERT_OK(std_sub); + asil::Publisher pub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/asil/cycle", StaticPubOptions(), pub)); + + for (int i = 0; i < 200; i++) { + const std::string text = "message " + std::to_string(i); + AsilPublish(pub, text); + asil::Message msg; + ASSERT_EQ(asil::Error::kOk, asil_sub.ReadMessage(msg)); + ASSERT_EQ(text, Text(msg)); + ASSERT_EQ(0u, msg.dropped); + ASSERT_EQ(text, StdRead(*std_sub).text); + } +} + +TEST_F(AsilClientTest, HeldMessageIsNotOverwritten) { + asil::Subscriber sub; + ASSERT_EQ(asil::Error::kOk, Asil().CreateSubscriber("/asil/hold", {}, sub)); + absl::StatusOr pub = + Std().CreatePublisher("/asil/hold", ServerDefined()); + ASSERT_OK(pub); + StdPublish(*pub, "held"); + asil::Message held; + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(held)); + ASSERT_EQ("held", Text(held)); + + for (int i = 0; i < 20; i++) { + StdPublish(*pub, "overwrite " + std::to_string(i)); + } + EXPECT_EQ("held", Text(held)); + sub.ReleaseMessage(); + + asil::Message msg; + ASSERT_EQ(asil::Error::kOk, + sub.ReadMessage(msg, asil::ReadMode::kReadNewest)); + EXPECT_EQ("overwrite 19", Text(msg)); +} + +TEST_F(AsilClientTest, Rejections) { + // A static channel's publishers let the server define its layout. + asil::Publisher pub; + EXPECT_EQ(asil::Error::kServerRejected, + Asil().CreatePublisher("/asil/reject", AsilPubOptions(64, 4), pub)); + EXPECT_THAT(Asil().LastServerError(), HasSubstr("must set server_defined")); + EXPECT_FALSE(pub.IsOpen()); + + EXPECT_EQ(asil::Error::kServerRejected, + Asil().CreatePublisher("/asil/unknown", StaticPubOptions(), pub)); + EXPECT_THAT(Asil().LastServerError(), + HasSubstr("isn't in the static channel config")); + + // An ASIL publisher can't create a channel the config doesn't list, even + // by giving the layout itself. + EXPECT_EQ(asil::Error::kServerRejected, + Asil().CreatePublisher("/asil/unknown", AsilPubOptions(64, 4), pub)); + EXPECT_THAT(Asil().LastServerError(), + HasSubstr("ASIL publishers can only use channels")); + EXPECT_FALSE(pub.IsOpen()); + + // A subscriber can ask for that channel. Until a publisher creates its + // buffers there is nothing to map. + asil::Subscriber sub; + EXPECT_EQ(asil::Error::kNoBuffers, + Asil().CreateSubscriber("/asil/unknown", {}, sub)); + EXPECT_FALSE(sub.IsOpen()); + + // Layout options alongside server_defined. + for (int field = 0; field < 6; field++) { + asil::PublisherOptions options = StaticPubOptions(); + switch (field) { + case 0: + options.slot_size = 64; + break; + case 1: + options.num_slots = 4; + break; + case 2: + options.checksum_size = 4; + break; + case 3: + options.metadata_size = 16; + break; + case 4: + options.subscriber_queue_arena_size = 4096; + break; + default: + options.use_split_buffers = true; + break; + } + EXPECT_EQ(asil::Error::kInvalidArgument, + Asil().CreatePublisher("/asil/reject", options, pub)) + << field; + } + EXPECT_EQ(asil::Error::kCapacityExceeded, + Asil().CreatePublisher(std::string(300, 'x').c_str(), + StaticPubOptions(), pub)); + + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/asil/reject", StaticPubOptions(), pub)); + EXPECT_EQ(64, pub.SlotSize()); + EXPECT_EQ(4, pub.NumSlots()); + EXPECT_EQ(asil::Error::kAlreadyInitialized, + Asil().CreatePublisher("/asil/reject", StaticPubOptions(), pub)); + EXPECT_EQ(asil::Error::kMessageTooLarge, pub.Publish(65)); + + asil::Client uninitialized; + asil::Publisher other; + EXPECT_EQ( + asil::Error::kNotInitialized, + uninitialized.CreatePublisher("/asil/reject", StaticPubOptions(), other)); +} + +TEST_F(AsilClientTest, CloseRemovesFromServer) { + asil::Publisher pub; + asil::Subscriber sub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/asil/close", StaticPubOptions(), pub)); + ASSERT_EQ(asil::Error::kOk, Asil().CreateSubscriber("/asil/close", {}, sub)); + absl::StatusOr info = + Std().GetChannelInfo("/asil/close"); + ASSERT_OK(info); + EXPECT_EQ(1, info->num_publishers); + EXPECT_EQ(1, info->num_subscribers); + + EXPECT_EQ(asil::Error::kOk, pub.Close()); + EXPECT_EQ(asil::Error::kOk, sub.Close()); + EXPECT_FALSE(pub.IsOpen()); + EXPECT_EQ(asil::Error::kOk, pub.Close()); + absl::StatusOr closed_info = + Std().GetChannelInfo("/asil/close"); + ASSERT_OK(closed_info); + EXPECT_EQ(0, closed_info->num_publishers); + EXPECT_EQ(0, closed_info->num_subscribers); + + // The channel can be used again. + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/asil/close", StaticPubOptions(), pub)); + ASSERT_EQ(asil::Error::kOk, Asil().CreateSubscriber("/asil/close", {}, sub)); + AsilPublish(pub, "again"); + asil::Message msg; + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ("again", Text(msg)); +} + +TEST_F(AsilClientTest, HandshakeMakesNoHeapAllocations) { + asil::Publisher pub; + asil::Subscriber sub; + // An indirect call keeps an optimized build from lowering this to malloc. + // operator new is assumed free of side effects, so a direct new expression + // never reaches the counter above. + using OpNew = void *(*)(std::size_t); + volatile OpNew allocate = &::operator new; + StartCounting(); + void *counted = allocate(sizeof(int)); + const int sanity_allocations = StopCounting(); + ::operator delete(counted); + ASSERT_EQ(1, sanity_allocations); + + StartCounting(); + const asil::Error pub_error = + Asil().CreatePublisher("/asil/no_alloc", StaticPubOptions(), pub); + const asil::Error sub_error = + Asil().CreateSubscriber("/asil/no_alloc", {}, sub); + const asil::Error pub_close = pub.Close(); + const asil::Error sub_close = sub.Close(); + const int handshake_allocations = StopCounting(); + + EXPECT_EQ(asil::Error::kOk, pub_error); + EXPECT_EQ(asil::Error::kOk, sub_error); + EXPECT_EQ(asil::Error::kOk, pub_close); + EXPECT_EQ(asil::Error::kOk, sub_close); + EXPECT_EQ(0, handshake_allocations); +} + +// Not even initialization allocates, so a client can be set up with the heap +// already closed. The fixture's own clients have initialized, so this uses +// new ones, whose first messages are the first of their kind on the thread. +TEST_F(AsilClientTest, InitializationMakesNoHeapAllocations) { + auto connection = std::make_unique(); + auto client = std::make_unique(); + StartCounting(); + const asil::Error connected = connection->Connect(Socket().c_str()); + const asil::Error initialized = client->Init(*connection, "no_alloc_init"); + const int init_allocations = StopCounting(); + EXPECT_EQ(asil::Error::kOk, connected); + EXPECT_EQ(asil::Error::kOk, initialized); + EXPECT_EQ(0, init_allocations); +} + +// Everything after the handshakes: publishing, reading, waiting, and fetching +// new trigger fds when the other side of a channel changes. +TEST_F(AsilClientTest, SteadyStateMakesNoHeapAllocations) { + asil::Publisher pub; + asil::Subscriber sub; + asil::PublisherOptions pub_options = StaticPubOptions(); + pub_options.checksum = true; + asil::SubscriberOptions sub_options; + sub_options.checksum = true; + sub_options.max_active_messages = 4; + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/asil/steady", pub_options, pub)); + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/asil/steady", sub_options, sub)); + + asil::Publisher rel_pub; + asil::Subscriber rel_sub; + asil::PublisherOptions rel_pub_options = StaticPubOptions(); + rel_pub_options.reliable = true; + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/asil/steady_rel", rel_pub_options, + rel_pub)); + asil::SubscriberOptions rel_options; + rel_options.reliable = true; + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/asil/steady_rel", rel_options, rel_sub)); + + // These grow the channels, and so need the server, but not the ASIL client. + absl::StatusOr std_sub = + Std().CreateSubscriber("/asil/steady"); + ASSERT_OK(std_sub); + + StartCounting(); + asil::Message msg; + asil::Error last = asil::Error::kOk; + for (int i = 0; i < 20; i++) { + void *buffer = pub.Buffer(); + if (buffer == nullptr) { + last = asil::Error::kNoSlot; + break; + } + memcpy(buffer, "steady", 6); + last = pub.Publish(6); + if (last != asil::Error::kOk) { + break; + } + last = sub.Wait(0); + if (last != asil::Error::kOk) { + break; + } + last = sub.ReadMessage(msg); + if (last != asil::Error::kOk) { + break; + } + sub.ReleaseMessage(msg); + last = sub.ReadMessage(msg, asil::ReadMode::kReadNewest); + if (last != asil::Error::kOk) { + break; + } + sub.ReleaseMessage(); + + void *rel_buffer = rel_pub.Buffer(); + if (rel_buffer != nullptr) { + memcpy(rel_buffer, "rel", 3); + last = rel_pub.Publish(3); + if (last != asil::Error::kOk) { + break; + } + } + last = rel_sub.ReadMessage(msg); + if (last != asil::Error::kOk) { + break; + } + rel_sub.ReleaseMessage(); + } + (void)rel_pub.Wait(0); + const int steady_allocations = StopCounting(); + EXPECT_EQ(asil::Error::kOk, last); + EXPECT_EQ(0, steady_allocations) << "publish and read"; + + // A subscriber joining makes the publisher fetch the subscriber triggers. + absl::StatusOr joined = + Std().CreateSubscriber("/asil/steady"); + ASSERT_OK(joined); + StartCounting(); + void *buffer = pub.Buffer(); + ASSERT_NE(nullptr, buffer); + memcpy(buffer, "joined", 6); + last = pub.Publish(6); + const int publisher_refresh_allocations = StopCounting(); + EXPECT_EQ(asil::Error::kOk, last); + EXPECT_EQ(0, publisher_refresh_allocations) << "publisher refresh"; + + // A publisher joining makes the subscriber fetch the publisher triggers. + absl::StatusOr std_pub = + Std().CreatePublisher("/asil/steady", ServerDefined()); + ASSERT_OK(std_pub); + StartCounting(); + last = sub.ReadMessage(msg); + const int subscriber_refresh_allocations = StopCounting(); + EXPECT_EQ(asil::Error::kOk, last); + EXPECT_EQ(0, subscriber_refresh_allocations) << "subscriber refresh"; + + StartCounting(); + sub.ReleaseMessage(); + const asil::Error pub_close = pub.Close(); + const asil::Error sub_close = sub.Close(); + const asil::Error rel_pub_close = rel_pub.Close(); + const asil::Error rel_sub_close = rel_sub.Close(); + const int close_allocations = StopCounting(); + EXPECT_EQ(asil::Error::kOk, pub_close); + EXPECT_EQ(asil::Error::kOk, sub_close); + EXPECT_EQ(asil::Error::kOk, rel_pub_close); + EXPECT_EQ(asil::Error::kOk, rel_sub_close); + EXPECT_EQ(0, close_allocations) << "close"; +} + +// Failures must not allocate either. +TEST_F(AsilClientTest, ErrorsMakeNoHeapAllocations) { + asil::Publisher pub; + asil::Subscriber sub; + const std::string huge(asil::PhaserServerConnection::kWireBufferSize, 'x'); + const std::string long_name(300, 'x'); + asil::TriggersReply reply; + asil::TriggerFdList triggers; + reply.subscriber_triggers = &triggers; + + // Each failure is counted on its own so that a failure names its cause. + StartCounting(); + const asil::Error rejected_pub = + Asil().CreatePublisher("/asil/reject", AsilPubOptions(64, 4), pub); + EXPECT_EQ(0, StopCounting()) << "layout rejected by server"; + StartCounting(); + const asil::Error unknown_pub = + Asil().CreatePublisher("/asil/unknown", StaticPubOptions(), pub); + EXPECT_EQ(0, StopCounting()) << "unknown publisher channel"; + StartCounting(); + const asil::Error unknown_sub = + Asil().CreateSubscriber("/asil/unknown", {}, sub); + EXPECT_EQ(0, StopCounting()) << "unknown subscriber channel"; + StartCounting(); + const asil::Error long_pub = + Asil().CreatePublisher(long_name.c_str(), StaticPubOptions(), pub); + EXPECT_EQ(0, StopCounting()) << "channel name too long"; + StartCounting(); + const asil::Error oversized = Connection().GetTriggers(huge.c_str(), reply); + EXPECT_EQ(0, StopCounting()) << "request too large for the wire buffer"; + + EXPECT_EQ(asil::Error::kServerRejected, rejected_pub); + EXPECT_EQ(asil::Error::kServerRejected, unknown_pub); + EXPECT_EQ(asil::Error::kNoBuffers, unknown_sub); + EXPECT_EQ(asil::Error::kCapacityExceeded, long_pub); + EXPECT_EQ(asil::Error::kCapacityExceeded, oversized); + + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/asil/steady_meta", StaticPubOptions(), pub)); + StartCounting(); + const asil::Error too_large = pub.Publish(1000); + const asil::Error empty = pub.Publish(0); + const int publish_allocations = StopCounting(); + EXPECT_EQ(asil::Error::kMessageTooLarge, too_large); + EXPECT_EQ(asil::Error::kInvalidArgument, empty); + EXPECT_EQ(0, publish_allocations); +} + +TEST_F(AsilClientTest, LargerWireBufferSendsAnOversizedRequest) { + EXPECT_EQ(16 * 1024, asil::PhaserServerConnection().WireBufferSize()); + + asil::PhaserServerConnection connection(64 * 1024); + EXPECT_EQ(64 * 1024, connection.WireBufferSize()); + ASSERT_EQ(asil::Error::kOk, connection.Connect(Socket().c_str())); + + // This name fills the default wire buffer, so the default connection + // rejects it locally. A 64 KB buffer has room for the request and for the + // server's error, which repeats the name. + const std::string huge(asil::PhaserServerConnection::kWireBufferSize, 'x'); + asil::TriggersReply reply; + EXPECT_EQ(asil::Error::kServerRejected, + connection.GetTriggers(huge.c_str(), reply)); + EXPECT_THAT(connection.LastServerError(), HasSubstr("No such channel")); + EXPECT_TRUE(connection.Connected()); + + StartCounting(); + const asil::Error ok = connection.GetTriggers("/asil/oversize", reply); + const int allocations = StopCounting(); + EXPECT_EQ(asil::Error::kOk, ok); + EXPECT_EQ(0, allocations); + EXPECT_TRUE(connection.Connected()); +} + +TEST_F(AsilClientTest, OversizedRequestKeepsTheConnection) { + const std::string huge(asil::PhaserServerConnection::kWireBufferSize, 'x'); + asil::TriggersReply reply; + EXPECT_EQ(asil::Error::kCapacityExceeded, + Connection().GetTriggers(huge.c_str(), reply)); + EXPECT_THAT(Connection().LastServerError(), HasSubstr("too large")); + EXPECT_TRUE(Connection().Connected()); + + asil::TriggerFdList subscribers; + reply.subscriber_triggers = &subscribers; + EXPECT_EQ(asil::Error::kOk, + Connection().GetTriggers("/asil/oversize", reply)); +} + +// Reads exactly length bytes, or returns false. +bool ReadFull(int fd, char *data, size_t length) { + while (length > 0) { + const ssize_t n = ::recv(fd, data, length, 0); + if (n < 0 && errno == EINTR) { + continue; + } + if (n <= 0) { + return false; + } + data += n; + length -= static_cast(n); + } + return true; +} + +bool WriteFull(int fd, const char *data, size_t length) { + while (length > 0) { + const ssize_t n = ::send(fd, data, length, 0); + if (n < 0 && errno == EINTR) { + continue; + } + if (n <= 0) { + return false; + } + data += n; + length -= static_cast(n); + } + return true; +} + +// A response that fits the wire buffer but not the message it is cloned +// into, and a response the wire buffer itself cannot hold. Both name the +// cause, and neither allocates. +TEST_F(AsilClientTest, OversizedResponseMakesNoHeapAllocations) { + StartCounting(); + const absl::Status full = ::phaser::internal::AllocationFailedError(); + const absl::Status too_small = ::phaser::internal::BufferTooSmallError(); + const int status_allocations = StopCounting(); + EXPECT_EQ(0, status_allocations); + EXPECT_EQ("phaser: payload buffer is full", std::string(full.message())); + EXPECT_EQ("phaser: buffer is too small", std::string(too_small.message())); + + ::subspace::phaser::Response source = + ::subspace::phaser::Response::CreateDynamicMutable( + 8192, ::phaser::Tuning::kSize); + source.mutable_get_triggers()->set_error(std::string(4000, 'e')); + ASSERT_FALSE(source.AllocationFailed()); + + ::subspace::ServerWire<::subspace::FixedServerWireBuffers<1024, 64 * 1024>> + small; + absl::StatusOr<::subspace::phaser::Response> decoded = small.NewResponse(); + ASSERT_TRUE(decoded.ok()) << decoded.status(); + StartCounting(); + const absl::Status decoded_status = decltype(small)::Decode( + static_cast(source.Data()), source.ByteSizeLong(), + *decoded); + const int decode_allocations = StopCounting(); + EXPECT_FALSE(decoded_status.ok()); + EXPECT_EQ(absl::StatusCode::kResourceExhausted, decoded_status.code()); + EXPECT_THAT(std::string(decoded_status.message()), + AnyOf(HasSubstr("too large"), HasSubstr("buffer is full"))); + EXPECT_EQ(0, decode_allocations) << decoded_status; + + ::subspace::phaser::Response ok_response = + ::subspace::phaser::Response::CreateDynamicMutable( + 1024, ::phaser::Tuning::kSize); + ok_response.mutable_get_triggers()->set_error(""); + ASSERT_FALSE(ok_response.AllocationFailed()); + const std::string ok_bytes(static_cast(ok_response.Data()), + ok_response.ByteSizeLong()); + +#if defined(__ANDROID__) + char socket_name[] = "/data/local/tmp/asilrespXXXXXX"; +#else + char socket_name[] = "/tmp/asilrespXXXXXX"; +#endif + ::close(::mkstemp(socket_name)); + (void)::unlink(socket_name); + + const int listen_fd = ::socket(AF_UNIX, SOCK_STREAM, 0); + ASSERT_GE(listen_fd, 0); + struct sockaddr_un addr; + std::memset(&addr, 0, sizeof(addr)); + addr.sun_family = AF_UNIX; +#if defined(__linux__) + // Connect() uses the abstract namespace on Linux, as the server does. + std::memcpy(addr.sun_path + 1, socket_name, std::strlen(socket_name)); +#else + std::memcpy(addr.sun_path, socket_name, sizeof(socket_name)); +#endif + ASSERT_EQ(0, ::bind(listen_fd, reinterpret_cast(&addr), + sizeof(addr))); + ASSERT_EQ(0, ::listen(listen_fd, 1)); + + std::thread server([listen_fd, ok_bytes] { + const int client = ::accept(listen_fd, nullptr, nullptr); + if (client < 0) { + return; + } +#if defined(SO_NOSIGPIPE) + const int on = 1; + (void)::setsockopt(client, SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof(on)); +#endif + for (int n = 0; n < 2; n++) { + uint32_t network_length = 0; + if (!ReadFull(client, reinterpret_cast(&network_length), + sizeof(network_length))) { + break; + } + std::string request(ntohl(network_length), '\0'); + if (!request.empty() && + !ReadFull(client, request.data(), request.size())) { + break; + } + if (n == 0) { + const uint32_t length = + asil::PhaserServerConnection::kWireBufferSize + 8; + const uint32_t network = htonl(length); + char zeros[4096] = {}; + if (!WriteFull(client, reinterpret_cast(&network), + sizeof(network))) { + break; + } + for (uint32_t left = length; left > 0;) { + const uint32_t chunk = left < sizeof(zeros) ? left : sizeof(zeros); + if (!WriteFull(client, zeros, chunk)) { + ::close(client); + return; + } + left -= chunk; + } + } else { + const uint32_t network = htonl(static_cast(ok_bytes.size())); + if (!WriteFull(client, reinterpret_cast(&network), + sizeof(network)) || + !WriteFull(client, ok_bytes.data(), ok_bytes.size())) { + ::close(client); + return; + } + } + const int32_t no_fds = 0; + if (!WriteFull(client, reinterpret_cast(&no_fds), + sizeof(no_fds))) { + break; + } + } + ::close(client); + }); + + asil::PhaserServerConnection connection; + const asil::Error connected = connection.Connect(socket_name); + if (connected != asil::Error::kOk) { + // Closing alone does not wake the accept() on Linux. + ::shutdown(listen_fd, SHUT_RDWR); + ::close(listen_fd); + server.join(); + (void)::unlink(socket_name); + FAIL() << "connect"; + return; + } + + asil::TriggersReply reply; + StartCounting(); + const asil::Error oversized = connection.GetTriggers("/asil/resp", reply); + const int response_allocations = StopCounting(); + EXPECT_EQ(asil::Error::kCapacityExceeded, oversized); + EXPECT_THAT(connection.LastServerError(), + HasSubstr("response does not fit the wire buffer")); + EXPECT_EQ(0, response_allocations); + EXPECT_TRUE(connection.Connected()); + + EXPECT_EQ(asil::Error::kOk, connection.GetTriggers("/asil/resp", reply)); + EXPECT_TRUE(connection.Connected()); + EXPECT_THAT(connection.LastServerError(), + HasSubstr("response does not fit the wire buffer")); + + server.join(); + ::close(listen_fd); + (void)::unlink(socket_name); +} + +// Publishes "" for n from first until the reliable publisher has +// no free slot, and returns the number published. +int FillReliable(asil::Publisher &pub, const std::string &prefix, int first) { + int n = first; + for (; n < first + 100; n++) { + void *buffer = pub.Buffer(); + if (buffer == nullptr) { + break; + } + const std::string text = prefix + std::to_string(n); + memcpy(buffer, text.data(), text.size()); + EXPECT_EQ(asil::Error::kOk, pub.Publish(text.size())); + } + return n - first; +} + +asil::PublisherOptions ReliablePubOptions() { + asil::PublisherOptions options = StaticPubOptions(); + options.reliable = true; + return options; +} + +TEST_F(AsilClientTest, ReliableAsilPublisherStandardSubscriber) { + absl::StatusOr sub = Std().CreateSubscriber( + "/asil/rel_to_std", subspace::SubscriberOptions().SetReliable(true)); + ASSERT_OK(sub); + asil::Publisher pub; + ASSERT_EQ( + asil::Error::kOk, + Asil().CreatePublisher("/asil/rel_to_std", ReliablePubOptions(), pub)); + EXPECT_TRUE(pub.IsReliable()); + + // The activation message and the unread messages fill the channel. + const int published = FillReliable(pub, "r", 0); + EXPECT_EQ(3, published); + EXPECT_EQ(asil::Error::kTimeout, pub.Wait(10)); + + // Reading frees slots and wakes the publisher. + EXPECT_EQ("r0", StdRead(*sub).text); + EXPECT_EQ(asil::Error::kOk, pub.Wait(1000)); + const int more = FillReliable(pub, "r", published); + EXPECT_GT(more, 0); + for (int i = 1; i < published + more; i++) { + EXPECT_EQ("r" + std::to_string(i), StdRead(*sub).text); + } + EXPECT_EQ("", StdRead(*sub).text); +} + +TEST_F(AsilClientTest, StandardReliablePublisherAsilSubscriber) { + asil::Subscriber sub; + asil::SubscriberOptions options; + options.reliable = true; + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/asil/rel_from_std", options, sub)); + EXPECT_TRUE(sub.IsReliable()); + absl::StatusOr pub = Std().CreatePublisher( + "/asil/rel_from_std", ServerDefined().SetReliable(true)); + ASSERT_OK(pub); + + int published = 0; + for (; published < 100; published++) { + absl::StatusOr buffer = pub->GetMessageBuffer(); + ASSERT_OK(buffer); + if (*buffer == nullptr) { + break; + } + const std::string text = "s" + std::to_string(published); + memcpy(*buffer, text.data(), text.size()); + ASSERT_OK(pub->PublishMessage(static_cast(text.size()))); + } + EXPECT_EQ(3, published); + EXPECT_FALSE(Readable(pub->GetPollFd().fd)); + + asil::Message msg; + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ("s0", Text(msg)); + EXPECT_FALSE(msg.is_activation); + EXPECT_TRUE(Readable(pub->GetPollFd().fd)); + StdPublish(*pub, "s3"); + + uint64_t last = msg.ordinal; + for (int i = 1; i <= published; i++) { + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ("s" + std::to_string(i), Text(msg)); + EXPECT_EQ(last + 1, msg.ordinal); + EXPECT_EQ(0u, msg.dropped); + last = msg.ordinal; + } + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ(0u, msg.length); +} + +TEST_F(AsilClientTest, ReliableReadNewestFreesSkippedSlots) { + asil::SubscriberOptions options; + options.reliable = true; + asil::Subscriber sub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/asil/rel_newest", options, sub)); + asil::Publisher pub; + ASSERT_EQ( + asil::Error::kOk, + Asil().CreatePublisher("/asil/rel_newest", ReliablePubOptions(), pub)); + ASSERT_EQ(3, FillReliable(pub, "n", 0)); + + asil::Message msg; + ASSERT_EQ(asil::Error::kOk, + sub.ReadMessage(msg, asil::ReadMode::kReadNewest)); + EXPECT_EQ("n2", Text(msg)); + EXPECT_EQ(asil::Error::kOk, pub.Wait(1000)); + + // The skipped messages no longer hold back the publisher. The held message + // keeps its slot. + EXPECT_EQ(3, FillReliable(pub, "m", 0)); + for (int i = 0; i < 3; i++) { + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ("m" + std::to_string(i), Text(msg)); + } +} + +TEST_F(AsilClientTest, ReliablePublisherWaitsForSubscriber) { + asil::Publisher pub; + ASSERT_EQ(asil::Error::kOk, Asil().CreatePublisher( + "/asil/rel_late", ReliablePubOptions(), pub)); + EXPECT_EQ(nullptr, pub.Buffer()); + + absl::StatusOr sub = Std().CreateSubscriber( + "/asil/rel_late", subspace::SubscriberOptions().SetReliable(true)); + ASSERT_OK(sub); + AsilPublish(pub, "hello"); + EXPECT_EQ("hello", StdRead(*sub).text); +} + +TEST_F(AsilClientTest, VirtualChannels) { + asil::Publisher rejected; + EXPECT_EQ(asil::Error::kServerRejected, + Asil().CreatePublisher("/asil/v1", StaticPubOptions(), rejected)); + + asil::Subscriber mux_sub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/asil/mux", {}, mux_sub)); + asil::SubscriberOptions v2_options; + v2_options.mux = "/asil/mux"; + asil::Subscriber v2_sub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/asil/v2", v2_options, v2_sub)); + EXPECT_EQ(2, v2_sub.VirtualChannelId()); + absl::StatusOr v1_sub = Std().CreateSubscriber( + "/asil/v1", subspace::SubscriberOptions().SetMux("/asil/mux")); + ASSERT_OK(v1_sub); + + asil::PublisherOptions v1_options = StaticPubOptions(); + v1_options.mux = "/asil/mux"; + asil::Publisher v1_pub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/asil/v1", v1_options, v1_pub)); + EXPECT_EQ(1, v1_pub.VirtualChannelId()); + absl::StatusOr v2_pub = + Std().CreatePublisher("/asil/v2", ServerDefined().SetMux("/asil/mux")); + ASSERT_OK(v2_pub); + + AsilPublish(v1_pub, "a1"); + StdPublish(*v2_pub, "b1"); + AsilPublish(v1_pub, "a2"); + + EXPECT_EQ("a1", StdRead(*v1_sub).text); + EXPECT_EQ("a2", StdRead(*v1_sub).text); + EXPECT_EQ("", StdRead(*v1_sub).text); + + asil::Message msg; + ASSERT_EQ(asil::Error::kOk, v2_sub.ReadMessage(msg)); + EXPECT_EQ("b1", Text(msg)); + EXPECT_EQ(2, msg.vchan_id); + ASSERT_EQ(asil::Error::kOk, v2_sub.ReadMessage(msg)); + EXPECT_EQ(0u, msg.length); + + // Each virtual channel has its own ordinals, so interleaving is no drop. + const struct { + const char *text; + int vchan_id; + } expected[] = {{"a1", 1}, {"b1", 2}, {"a2", 1}}; + for (const auto &e : expected) { + ASSERT_EQ(asil::Error::kOk, mux_sub.ReadMessage(msg)); + EXPECT_EQ(e.text, Text(msg)); + EXPECT_EQ(e.vchan_id, msg.vchan_id); + EXPECT_EQ(0u, msg.dropped); + } + ASSERT_EQ(asil::Error::kOk, mux_sub.ReadMessage(msg)); + EXPECT_EQ(0u, msg.length); +} + +TEST_F(AsilClientTest, MultipleActiveMessages) { + asil::SubscriberOptions options; + options.max_active_messages = 3; + asil::Subscriber sub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/asil/multi", options, sub)); + absl::StatusOr pub = + Std().CreatePublisher("/asil/multi", ServerDefined()); + ASSERT_OK(pub); + for (const char *text : {"a", "b", "c", "d"}) { + StdPublish(*pub, text); + } + + asil::Message a, b, c, d; + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(a)); + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(b)); + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(c)); + EXPECT_EQ(3, sub.NumActiveMessages()); + EXPECT_EQ(asil::Error::kActiveMessageLimit, sub.ReadMessage(d)); + EXPECT_EQ(0u, d.length); + + // Held messages survive the publisher cycling through the other slots. + for (int i = 0; i < 20; i++) { + StdPublish(*pub, "x" + std::to_string(i)); + } + EXPECT_EQ("a", Text(a)); + EXPECT_EQ("b", Text(b)); + EXPECT_EQ("c", Text(c)); + + EXPECT_EQ(asil::Error::kOk, sub.ReleaseMessage(b)); + EXPECT_EQ(2, sub.NumActiveMessages()); + EXPECT_NE(asil::Error::kOk, sub.ReleaseMessage(b)); + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(d)); + EXPECT_FALSE(Text(d).empty()); + EXPECT_EQ(3, sub.NumActiveMessages()); + EXPECT_EQ("a", Text(a)); + sub.ReleaseMessage(); + EXPECT_EQ(0, sub.NumActiveMessages()); +} + +TEST_F(AsilClientTest, SubscriberOpensBeforeAnyPublisher) { + // The server created the channel's buffer, so the subscriber maps it now. + asil::Subscriber sub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/asil/early_sub", {}, sub)); + asil::Message msg; + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ(0u, msg.length); + + absl::StatusOr pub = + Std().CreatePublisher("/asil/early_sub", ServerDefined()); + ASSERT_OK(pub); + StdPublish(*pub, "early"); + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ("early", Text(msg)); +} + +// An ASIL publisher on a static channel with split buffers. +asil::PublisherOptions SplitPubOptions(asil::SplitSlot *slots, + int32_t capacity) { + asil::PublisherOptions options = StaticPubOptions(); + options.split_slots = slots; + options.split_slot_capacity = capacity; + return options; +} + +asil::SubscriberOptions SplitSubOptions(asil::SplitSlot *slots, + int32_t capacity) { + asil::SubscriberOptions options; + options.split_slots = slots; + options.split_slot_capacity = capacity; + return options; +} + +TEST_F(AsilClientTest, SplitAsilPublisherStandardSubscriber) { + absl::StatusOr std_sub = + Std().CreateSubscriber("/asil/split_to_std"); + ASSERT_OK(std_sub); + EXPECT_TRUE(std_sub->UsesSplitBuffers()); + asil::SplitSlot sub_slots[4]; + asil::Subscriber asil_sub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/asil/split_to_std", + SplitSubOptions(sub_slots, 4), asil_sub)); + + asil::SplitSlot pub_slots[4]; + asil::Publisher pub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/asil/split_to_std", + SplitPubOptions(pub_slots, 4), pub)) + << Asil().LastServerError(); + EXPECT_GE(pub.SlotSize(), 256); + for (const asil::SplitSlot &slot : pub_slots) { + EXPECT_NE(nullptr, slot.mapping.address); + EXPECT_FALSE(slot.allocator_mapped); + } + + asil::Message msg; + for (int i = 0; i < 10; i++) { + const std::string text = "split " + std::to_string(i); + AsilPublish(pub, text); + EXPECT_EQ(text, StdRead(*std_sub).text); + ASSERT_EQ(asil::Error::kOk, asil_sub.ReadMessage(msg)); + EXPECT_EQ(text, Text(msg)); + EXPECT_EQ(sub_slots[msg.slot_id].mapping.address, msg.data); + } + pub.Close(); + asil_sub.Close(); + for (const asil::SplitSlot &slot : sub_slots) { + EXPECT_EQ(nullptr, slot.mapping.address); + } +} + +TEST_F(AsilClientTest, SplitStandardPublisherAsilSubscriber) { + asil::SplitSlot slots[4]; + asil::SubscriberOptions options = SplitSubOptions(slots, 4); + options.checksum = true; + asil::Subscriber sub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/asil/split_from_std", options, sub)); + absl::StatusOr pub = Std().CreatePublisher( + "/asil/split_from_std", ServerDefined().SetChecksum(true)); + ASSERT_OK(pub); + + asil::Message msg; + for (int i = 0; i < 10; i++) { + const std::string text = "from std " + std::to_string(i); + StdPublish(*pub, text); + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ(text, Text(msg)); + EXPECT_FALSE(msg.checksum_error); + } +} + +TEST_F(AsilClientTest, SplitVirtualChannel) { + asil::SplitSlot sub_slots[8]; + asil::SubscriberOptions sub_options = SplitSubOptions(sub_slots, 8); + sub_options.mux = "/asil/split_mux"; + asil::Subscriber sub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/asil/split_v", sub_options, sub)); + EXPECT_EQ(4, sub.VirtualChannelId()); + + asil::SplitSlot pub_slots[8]; + asil::PublisherOptions pub_options = SplitPubOptions(pub_slots, 8); + pub_options.mux = "/asil/split_mux"; + asil::Publisher pub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/asil/split_v", pub_options, pub)) + << Asil().LastServerError(); + AsilPublish(pub, "vchan"); + asil::Message msg; + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ("vchan", Text(msg)); + EXPECT_EQ(4, msg.vchan_id); +} + +TEST_F(AsilClientTest, SplitRejections) { + asil::Subscriber sub; + EXPECT_EQ(asil::Error::kInvalidArgument, + Asil().CreateSubscriber("/asil/split_reject", {}, sub)); + asil::SplitSlot slots[4]; + EXPECT_EQ(asil::Error::kCapacityExceeded, + Asil().CreateSubscriber("/asil/split_reject", + SplitSubOptions(slots, 3), sub)); + EXPECT_FALSE(sub.IsOpen()); + + // The server says the channel has split buffers, and a publisher needs + // somewhere to map them too. + asil::Publisher pub; + EXPECT_EQ( + asil::Error::kInvalidArgument, + Asil().CreatePublisher("/asil/split_reject", StaticPubOptions(), pub)); + EXPECT_EQ(asil::Error::kCapacityExceeded, + Asil().CreatePublisher("/asil/split_reject", + SplitPubOptions(slots, 3), pub)); + EXPECT_FALSE(pub.IsOpen()); +} + +TEST_F(AsilClientTest, StandardPublisherCreatesChannelBesideStaticConfig) { + asil::Publisher rejected; + EXPECT_EQ(asil::Error::kServerRejected, + Asil().CreatePublisher("/dyn/beside", AsilPubOptions(64, 4), + rejected)); + EXPECT_THAT(Asil().LastServerError(), + HasSubstr("ASIL publishers can only use channels")); + + absl::StatusOr pub = + Std().CreatePublisher("/dyn/beside", 64, 4, FixedSize()); + ASSERT_OK(pub); + + // The channel exists now, but it isn't static, so an ASIL publisher still + // can't join it. + EXPECT_EQ(asil::Error::kServerRejected, + Asil().CreatePublisher("/dyn/beside", AsilPubOptions(64, 4), + rejected)); + EXPECT_FALSE(rejected.IsOpen()); + + asil::Subscriber asil_sub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/dyn/beside", {}, asil_sub)); + absl::StatusOr std_sub = + Std().CreateSubscriber("/dyn/beside"); + ASSERT_OK(std_sub); + StdPublish(*pub, "beside"); + asil::Message msg; + ASSERT_EQ(asil::Error::kOk, asil_sub.ReadMessage(msg)); + EXPECT_EQ("beside", Text(msg)); + EXPECT_EQ("beside", StdRead(*std_sub).text); +} + +TEST_F(AsilDynamicTest, AsilPublisherCreatesChannel) { + asil::Publisher pub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/dyn/create", AsilPubOptions(64, 8), pub)); + asil::Subscriber asil_sub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/dyn/create", {}, asil_sub)); + absl::StatusOr std_sub = + Std().CreateSubscriber("/dyn/create"); + ASSERT_OK(std_sub); + asil::Publisher second; + ASSERT_EQ(asil::Error::kOk, Asil().CreatePublisher( + "/dyn/create", AsilPubOptions(64, 8), second)) + << Asil().LastServerError(); + absl::StatusOr std_pub = + Std().CreatePublisher("/dyn/create", 64, 8, FixedSize()); + ASSERT_OK(std_pub); + + AsilPublish(pub, "one"); + AsilPublish(second, "two"); + StdPublish(*std_pub, "three"); + asil::Message msg; + for (const char *text : {"one", "two", "three"}) { + EXPECT_EQ(text, StdRead(*std_sub).text); + ASSERT_EQ(asil::Error::kOk, asil_sub.ReadMessage(msg)); + EXPECT_EQ(text, Text(msg)); + } +} + +TEST_F(AsilDynamicTest, SubscriberNeedsBuffers) { + asil::Subscriber sub; + EXPECT_EQ(asil::Error::kNoBuffers, + Asil().CreateSubscriber("/dyn/placeholder", {}, sub)); + EXPECT_FALSE(sub.IsOpen()); + + absl::StatusOr pub = + Std().CreatePublisher("/dyn/placeholder", 64, 4); + ASSERT_OK(pub); + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/dyn/placeholder", {}, sub)); + StdPublish(*pub, "first"); + EXPECT_EQ(asil::Error::kOk, sub.Wait(1000)); + asil::Message msg; + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ("first", Text(msg)); +} + +TEST_F(AsilDynamicTest, SubscriberSkipsMessagesAfterResize) { + asil::Subscriber sub; + absl::StatusOr pub = + Std().CreatePublisher("/dyn/resize", 64, 4); + ASSERT_OK(pub); + ASSERT_EQ(asil::Error::kOk, Asil().CreateSubscriber("/dyn/resize", {}, sub)); + StdPublish(*pub, "small"); + + const std::string big(1000, 'B'); + absl::StatusOr buffer = pub->GetMessageBuffer(1000); + ASSERT_OK(buffer); + memcpy(*buffer, big.data(), big.size()); + ASSERT_OK(pub->PublishMessage(static_cast(big.size()))); + StdPublish(*pub, "after"); + + // The subscriber maps only the buffer that existed when it opened. + asil::Message msg; + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ("small", Text(msg)); + EXPECT_EQ(asil::Error::kBufferNotMapped, sub.ReadMessage(msg)); + EXPECT_EQ(0u, msg.length); + EXPECT_EQ(asil::Error::kBufferNotMapped, sub.ReadMessage(msg)); + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ(0u, msg.length); + + // A subscriber that opens after the resize maps the new buffer. + asil::Subscriber later; + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/dyn/resize", {}, later)); + EXPECT_EQ(asil::Error::kBufferNotMapped, later.ReadMessage(msg)); + ASSERT_EQ(asil::Error::kOk, later.ReadMessage(msg)); + EXPECT_EQ(big, Text(msg)); + ASSERT_EQ(asil::Error::kOk, later.ReadMessage(msg)); + EXPECT_EQ("after", Text(msg)); + for (int i = 0; i < 10; i++) { + StdPublish(*pub, "later " + std::to_string(i)); + ASSERT_EQ(asil::Error::kOk, later.ReadMessage(msg)); + ASSERT_EQ("later " + std::to_string(i), Text(msg)); + } +} + +TEST_F(AsilDynamicTest, AsilPublisherJoinsResizedChannel) { + asil::Subscriber sub; + { + absl::StatusOr std_pub = + Std().CreatePublisher("/dyn/rejoin", 64, 4); + ASSERT_OK(std_pub); + StdPublish(*std_pub, "small"); + absl::StatusOr buffer = std_pub->GetMessageBuffer(1000); + ASSERT_OK(buffer); + ASSERT_OK(std_pub->PublishMessage(1000)); + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/dyn/rejoin", {}, sub)); + } + + // The publisher maps the newest buffer, which the subscriber also mapped. + asil::Publisher pub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/dyn/rejoin", AsilPubOptions(64, 4), pub)); + EXPECT_GE(pub.SlotSize(), 1000); + AsilPublish(pub, "asil"); + + asil::Message msg; + EXPECT_EQ(asil::Error::kBufferNotMapped, sub.ReadMessage(msg)); + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ(1000u, msg.length); + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ("asil", Text(msg)); +} + +TEST_F(AsilDynamicTest, AsilPublisherFillsSubscriberQueues) { + asil::PublisherOptions options = AsilPubOptions(64, 8); + options.subscriber_queue_arena_size = 4096; + asil::Publisher pub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/dyn/queue", options, pub)); + absl::StatusOr sub = Std().CreateSubscriber( + "/dyn/queue", subspace::SubscriberOptions().SetSubscriberQueueSize(2)); + ASSERT_OK(sub); + asil::Subscriber asil_sub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/dyn/queue", {}, asil_sub)); + + for (int i = 0; i < 5; i++) { + AsilPublish(pub, "q" + std::to_string(i)); + } + // A two entry queue keeps the newest two messages, so they are read first. + EXPECT_EQ("q3", StdRead(*sub).text); + EXPECT_EQ("q4", StdRead(*sub).text); + + asil::Message msg; + for (int i = 0; i < 5; i++) { + ASSERT_EQ(asil::Error::kOk, asil_sub.ReadMessage(msg)); + EXPECT_EQ("q" + std::to_string(i), Text(msg)); + } + + asil::Publisher wrong_arena; + EXPECT_EQ( + asil::Error::kServerRejected, + Asil().CreatePublisher("/dyn/queue", AsilPubOptions(64, 8), wrong_arena)); +} + +// Payloads that a standard publisher's custom allocator put on the heap. +// Clients in one process can share them by address. +struct HeapAllocations { + std::map> memory; + uintptr_t next_handle = 0; + int maps = 0; + int unmaps = 0; +}; + +subspace::SplitBufferCallbacks HeapCallbacks(HeapAllocations &heap) { + subspace::SplitBufferCallbacks callbacks; + callbacks.allocate = [&heap](const subspace::SplitBufferMetadata &metadata) + -> absl::StatusOr { + const uintptr_t handle = ++heap.next_handle; + auto &memory = heap.memory[handle]; + memory = std::make_unique(metadata.allocation_size); + subspace::SplitBufferMapping mapping; + mapping.handle = handle; + mapping.address = memory.get(); + mapping.size = static_cast(metadata.allocation_size); + return mapping; + }; + callbacks.unmap = [](const subspace::SplitBufferMetadata &, + const subspace::SplitBufferMapping &) { + return absl::OkStatus(); + }; + callbacks.free = [](const subspace::SplitBufferMetadata &, + const subspace::SplitBufferMapping &) { + return absl::OkStatus(); + }; + return callbacks; +} + +asil::Error HeapMap(void *context, const asil::SplitBufferInfo &info, + asil::SplitBufferMapping &mapping) { + auto *heap = static_cast(context); + auto it = heap->memory.find(static_cast(info.handle)); + if (it == heap->memory.end()) { + return asil::Error::kInvalidArgument; + } + heap->maps++; + mapping.address = it->second.get(); + mapping.size = info.allocation_size; + return asil::Error::kOk; +} + +void HeapUnmap(void *context, const asil::SplitBufferInfo &, + const asil::SplitBufferMapping &) { + static_cast(context)->unmaps++; +} + +TEST_F(AsilDynamicTest, SplitCustomAllocator) { + HeapAllocations heap; + asil::SplitSlot slots[4]; + asil::SubscriberOptions options; + options.split_slots = slots; + options.split_slot_capacity = 4; + options.split_allocator.map = HeapMap; + options.split_allocator.unmap = HeapUnmap; + options.split_allocator.context = &heap; + + // There is nothing to map until the publisher creates the buffers. + asil::Subscriber sub; + EXPECT_EQ(asil::Error::kNoBuffers, + Asil().CreateSubscriber("/dyn/custom", options, sub)); + + absl::StatusOr pub = Std().CreatePublisher( + "/dyn/custom", subspace::PublisherOptions() + .SetSlotSize(64) + .SetNumSlots(4) + .SetFixedSize(true) + .SetUseSplitBuffers(true) + .SetSplitBufferCallbacks(HeapCallbacks(heap))); + ASSERT_OK(pub); + + asil::Subscriber no_allocator; + asil::SubscriberOptions without = options; + without.split_allocator = asil::SplitBufferAllocator(); + EXPECT_EQ(asil::Error::kUnsupported, + Asil().CreateSubscriber("/dyn/custom", without, no_allocator)); + + ASSERT_EQ(asil::Error::kOk, + Asil().CreateSubscriber("/dyn/custom", options, sub)); + EXPECT_EQ(4, heap.maps); + for (const asil::SplitSlot &slot : slots) { + EXPECT_TRUE(slot.allocator_mapped); + EXPECT_EQ(asil::BufferAllocator::kSplitCallback, slot.info.allocator); + } + + asil::Message msg; + for (int i = 0; i < 8; i++) { + const std::string text = "heap " + std::to_string(i); + StdPublish(*pub, text); + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ(text, Text(msg)); + } + sub.Close(); + EXPECT_EQ(4, heap.unmaps); +} + +} // namespace + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/asil_client/channel_memory.cc b/asil_client/channel_memory.cc new file mode 100644 index 00000000..84646666 --- /dev/null +++ b/asil_client/channel_memory.cc @@ -0,0 +1,750 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +#include "asil_client/channel_memory.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_MEMFD +#include +#endif + +namespace subspace { +namespace asil { +namespace internal { + +namespace { + +constexpr size_t kMaxCcbSize = size_t{1} << 30; +// How long to wait for another client to finish creating a buffer. +constexpr int kBufferWaitMilliseconds = 100; + +void SleepMillisecond() { + struct timespec ts = {0, 1000000}; + (void)::nanosleep(&ts, nullptr); +} + +void *MapFd(int fd, size_t size, int prot) { + return ::mmap(nullptr, size, prot, MAP_SHARED, fd, 0); +} + +uint64_t PageAligned(uint64_t size) { + const uint64_t page = static_cast(::sysconf(_SC_PAGESIZE)); + return (size + page - 1) & ~(page - 1); +} + +#if SUBSPACE_SHMEM_MODE != SUBSPACE_SHMEM_MODE_MEMFD +// Android's libc has no shm_open, and memfd mode never opens a buffer by name. +constexpr mode_t kShmMode = S_IRUSR | S_IWUSR | S_IROTH | S_IWOTH; + +int OpenShm(const char *name, int flags) { + const mode_t old_umask = ::umask(0); + const int fd = ::shm_open(name, flags, kShmMode); + const int saved_errno = errno; + (void)::umask(old_umask); + errno = saved_errno; + return fd; +} +#endif + +#if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_POSIX +// The shm object for a buffer is named after the inode of its shadow file. +Error PosixShmName(const char *shadow_file, char (&out)[64]) { + struct stat st; + if (::stat(shadow_file, &st) != 0) { + return Error::kSharedMemoryError; + } + (void)std::snprintf(out, sizeof(out), "/subspace_%llu", + static_cast(st.st_ino)); + return Error::kOk; +} + +// The shadow file records the buffer size. Its length is not the buffer +// size: fstat of the shm object is page-aligned, and ftruncating the shadow +// file would commit that much memory where /tmp is RAM-backed. A leading +// NUL keeps the server from reading the record as split-buffer metadata. +constexpr char kPosixShadowMagic[8] = {'\0', 'S', 'S', 'B', 'S', 'I', 'Z', 'E'}; + +struct PosixShadowRecord { + char magic[sizeof(kPosixShadowMagic)]; + uint64_t size; +}; + +Error CreateShadowFile(const char *shadow_file) { + const int fd = ::open(shadow_file, O_RDWR | O_CREAT | O_CLOEXEC, 0666); + if (fd < 0) { + return Error::kSharedMemoryError; + } + (void)::close(fd); + return Error::kOk; +} + +Error WriteShadowSize(const char *shadow_file, uint64_t size) { + const int fd = ::open(shadow_file, O_WRONLY | O_TRUNC | O_CLOEXEC); + if (fd < 0) { + return Error::kSharedMemoryError; + } + PosixShadowRecord record = {}; + std::memcpy(record.magic, kPosixShadowMagic, sizeof(kPosixShadowMagic)); + record.size = size; + const ssize_t n = ::write(fd, &record, sizeof(record)); + (void)::close(fd); + return n == static_cast(sizeof(record)) ? Error::kOk + : Error::kSharedMemoryError; +} + +// Sets size to 0 when the creator has not recorded it yet. A shadow file +// longer than the record was sized with ftruncate by an older client. +Error ReadShadowSize(const char *shadow_file, uint64_t &size) { + const int fd = ::open(shadow_file, O_RDONLY | O_CLOEXEC); + if (fd < 0) { + return Error::kSharedMemoryError; + } + struct stat st; + if (::fstat(fd, &st) != 0) { + (void)::close(fd); + return Error::kSharedMemoryError; + } + PosixShadowRecord record; + const ssize_t n = ::read(fd, &record, sizeof(record)); + (void)::close(fd); + if (n == static_cast(sizeof(record)) && + std::memcmp(record.magic, kPosixShadowMagic, sizeof(kPosixShadowMagic)) == + 0) { + size = record.size; + return Error::kOk; + } + if (static_cast(st.st_size) > sizeof(record)) { + size = static_cast(st.st_size); + return Error::kOk; + } + size = 0; + return Error::kOk; +} +#endif + +#if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_MEMFD +int CreateMemfd(const char *name, uint64_t size) { + constexpr unsigned int kMemfdCloexec = 1; + const int fd = + static_cast(::syscall(__NR_memfd_create, name, kMemfdCloexec)); + if (fd < 0) { + return -1; + } + if (::ftruncate(fd, static_cast(size)) != 0) { + const int saved_errno = errno; + (void)::close(fd); + errno = saved_errno; + return -1; + } + return fd; +} +#endif + +} // namespace + +uint64_t Now() { + struct timespec ts; +#if defined(__APPLE__) + // toolbelt::Now() uses mach_absolute_time(), which is this clock. + (void)::clock_gettime(CLOCK_UPTIME_RAW, &ts); +#else + (void)::clock_gettime(CLOCK_MONOTONIC, &ts); +#endif + return static_cast(ts.tv_sec) * 1000000000ULL + + static_cast(ts.tv_nsec); +} + +void Trigger(int fd) { +#if defined(__linux__) + const int64_t value = 1; + (void)::write(fd, &value, sizeof(value)); +#else + const char value = 'x'; + (void)::write(fd, &value, sizeof(value)); +#endif +} + +void ClearTrigger(int fd) { +#if defined(__linux__) + int64_t value; + (void)::read(fd, &value, sizeof(value)); +#else + char buffer[256]; + while (::read(fd, buffer, sizeof(buffer)) > 0) { + } +#endif +} + +Error WaitReadable(int fd, int timeout_ms) { + struct pollfd p = {fd, POLLIN, 0}; + for (;;) { + const int n = ::poll(&p, 1, timeout_ms < 0 ? -1 : timeout_ms); + if (n > 0) { + return Error::kOk; + } + if (n == 0) { + return Error::kTimeout; + } + if (errno != EINTR) { + return Error::kInvalidArgument; + } + } +} + +Error CopyName(const char *name, char (&out)[kMaxChannelNameLength + 1]) { + if (name == nullptr || name[0] == '\0') { + return Error::kInvalidArgument; + } + const size_t length = std::strlen(name); + if (length > kMaxChannelNameLength) { + return Error::kCapacityExceeded; + } + std::memcpy(out, name, length + 1); + return Error::kOk; +} + +Error ChannelMemory::Map(shm::SystemControlBlock *scb, int ccb_fd, int bcb_fd, + int num_slots, int32_t checksum_size, + int32_t metadata_size, + uint64_t subscriber_queue_arena_size, + const BufferContext *context) { + if (ccb_ != nullptr) { + return Error::kAlreadyInitialized; + } + if (num_slots <= 0 || context == nullptr) { + return Error::kInvalidArgument; + } + if (subscriber_queue_arena_size > kMaxCcbSize) { + return Error::kLayoutMismatch; + } + const size_t ccb_size = shm::CcbSize(num_slots, subscriber_queue_arena_size); + if (ccb_size > kMaxCcbSize) { + return Error::kLayoutMismatch; + } + void *ccb = MapFd(ccb_fd, ccb_size, PROT_READ | PROT_WRITE); + if (ccb == MAP_FAILED) { + return Error::kSharedMemoryError; + } + auto *typed_ccb = static_cast(ccb); + if (typed_ccb->version != shm::kChannelControlBlockVersion || + typed_ccb->num_slots != num_slots) { + (void)::munmap(ccb, ccb_size); + return Error::kLayoutMismatch; + } + void *bcb = + MapFd(bcb_fd, sizeof(shm::BufferControlBlock), PROT_READ | PROT_WRITE); + if (bcb == MAP_FAILED) { + (void)::munmap(ccb, ccb_size); + return Error::kSharedMemoryError; + } + scb_ = scb; + ccb_ = typed_ccb; + bcb_ = static_cast(bcb); + context_ = context; + ccb_size_ = ccb_size; + queue_arena_size_ = subscriber_queue_arena_size; + num_slots_ = num_slots; + checksum_size_ = checksum_size > 0 ? checksum_size : 4; + metadata_size_ = metadata_size > 0 ? metadata_size : 0; + prefix_size_ = shm::PrefixSize(checksum_size_, metadata_size_); + return Error::kOk; +} + +void ChannelMemory::Unmap() { + UnmapBuffers(); + if (bcb_ != nullptr) { + (void)::munmap(bcb_, sizeof(shm::BufferControlBlock)); + bcb_ = nullptr; + } + if (ccb_ != nullptr) { + (void)::munmap(ccb_, ccb_size_); + ccb_ = nullptr; + ccb_size_ = 0; + } + scb_ = nullptr; + context_ = nullptr; + queue_arena_size_ = 0; + num_slots_ = 0; +} + +void ChannelMemory::UnmapBuffers() { + if (split_slots_ != nullptr) { + for (int i = 0; i < num_slots_; i++) { + SplitSlot &slot = split_slots_[i]; + if (slot.mapping.address != nullptr) { + if (!slot.allocator_mapped) { + (void)::munmap(slot.mapping.address, + static_cast(slot.mapping.size)); + } else if (allocator_.unmap != nullptr) { + allocator_.unmap(allocator_.context, slot.info, slot.mapping); + } + } + slot = SplitSlot(); + } + split_slots_ = nullptr; + } + allocator_ = SplitBufferAllocator(); + if (base_ != nullptr) { + (void)::munmap(base_, static_cast(size_)); + } + base_ = nullptr; + size_ = 0; + slot_size_ = 0; + index_ = -1; +} + +Error ChannelMemory::BufferName(int index, + char (&out)[kMaxChannelNameLength + 64]) const { + char sanitized[kMaxChannelNameLength + 1]; + if (Error e = CopyName(context_->channel_name, sanitized); e != Error::kOk) { + return e; + } + for (char *p = sanitized; *p != '\0'; p++) { + if (*p == '/') { + *p = '.'; + } + } +#if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_POSIX + const char *format = "/tmp/subspace_%llu_%s_%d"; +#else + const char *format = "subspace_%llu_%s_%d"; +#endif + const int n = std::snprintf( + out, sizeof(out), format, + static_cast(context_->session_id), sanitized, index); + if (n < 0 || static_cast(n) >= sizeof(out)) { + return Error::kCapacityExceeded; + } + return Error::kOk; +} + +Error ChannelMemory::NewestIndex(int &index) const { + const int num_buffers = ccb_->num_buffers.load(std::memory_order_acquire); + if (num_buffers <= 0) { + return Error::kNoBuffers; + } + if (num_buffers > static_cast(shm::kMaxBuffers)) { + return Error::kLayoutMismatch; + } + index = num_buffers - 1; + return Error::kOk; +} + +// Fetches a buffer from the server. Its creator registers it just after +// creating it, so it may not be there yet. +Error ChannelMemory::GetRegisteredBuffer(int index, bool is_prefix, + uint32_t slot_id, + BufferReply &reply) const { + BufferRequest request; + request.channel_name = context_->channel_name; + request.session_id = context_->session_id; + request.buffer_index = static_cast(index); + request.is_prefix = is_prefix; + request.slot_id = slot_id; + for (int attempt = 0; attempt < kBufferWaitMilliseconds; attempt++) { + if (Error e = context_->connection->GetBuffer(request, reply); + e != Error::kOk) { + return e; + } + if (reply.found) { + return Error::kOk; + } + SleepMillisecond(); + } + return Error::kSharedMemoryError; +} + +Error ChannelMemory::MapBuffer(int index, int fd, uint64_t size, int prot) { + const uint64_t prefixes = + static_cast(num_slots_) * static_cast(prefix_size_); + if (size <= prefixes) { + return Error::kLayoutMismatch; + } + void *p = MAP_FAILED; + for (int attempt = 0; attempt < kBufferWaitMilliseconds; attempt++) { + p = MapFd(fd, static_cast(size), prot); + if (p != MAP_FAILED || errno != EINVAL) { + break; + } + // The creator may not have sized the object yet. + SleepMillisecond(); + } + if (p == MAP_FAILED) { + return Error::kSharedMemoryError; + } + index_ = index; + base_ = static_cast(p); + size_ = size; + slot_size_ = static_cast((size - prefixes) / + static_cast(num_slots_)); + return Error::kOk; +} + +// Opens buffer index, which has already been created. +Error ChannelMemory::OpenBuffer(int index, bool writable, UniqueFd &fd, + uint64_t &size) const { +#if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_MEMFD + (void)writable; + BufferReply reply; + if (Error e = GetRegisteredBuffer(index, /*is_prefix=*/false, 0, reply); + e != Error::kOk) { + return e; + } + if (!reply.fd.Valid()) { + return Error::kSharedMemoryError; + } + fd = static_cast(reply.fd); + size = reply.full_size; + if (size == 0) { + struct stat st; + if (::fstat(fd.Get(), &st) != 0) { + return Error::kSharedMemoryError; + } + size = static_cast(st.st_size); + } + return Error::kOk; +#else + char name[kMaxChannelNameLength + 64]; + if (Error e = BufferName(index, name); e != Error::kOk) { + return e; + } + const int flags = writable ? O_RDWR : O_RDONLY; +#if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_POSIX + char shm_name[64]; + if (Error e = PosixShmName(name, shm_name); e != Error::kOk) { + return e; + } + fd.Reset(OpenShm(shm_name, flags)); + if (!fd.Valid()) { + return Error::kSharedMemoryError; + } + // The creator writes the shadow record before sizing the shm object, so a + // nonzero shm size means the record is the buffer's real size. + size = 0; + for (int attempt = 0; attempt < kBufferWaitMilliseconds && size == 0; + attempt++) { + struct stat shm_st; + if (::fstat(fd.Get(), &shm_st) != 0) { + return Error::kSharedMemoryError; + } + if (shm_st.st_size > 0) { + if (Error e = ReadShadowSize(name, size); e != Error::kOk) { + return e; + } + } + if (size == 0) { + SleepMillisecond(); + } + } + if (size == 0) { + return Error::kSharedMemoryError; + } +#else + fd.Reset(OpenShm(name, flags)); + if (!fd.Valid()) { + return Error::kSharedMemoryError; + } + size = 0; + for (int attempt = 0; attempt < kBufferWaitMilliseconds && size == 0; + attempt++) { + struct stat st; + if (::fstat(fd.Get(), &st) != 0) { + return Error::kSharedMemoryError; + } + size = static_cast(st.st_size); + if (size == 0) { + // The creator hasn't sized the object yet. + SleepMillisecond(); + } + } +#endif + return Error::kOk; +#endif +} + +Error ChannelMemory::AttachBuffer(bool writable) { + if (ccb_ == nullptr) { + return Error::kNotInitialized; + } + if (index_ != -1) { + return Error::kAlreadyInitialized; + } + int index = -1; + if (Error e = NewestIndex(index); e != Error::kOk) { + return e; + } + UniqueFd fd; + uint64_t size = 0; + if (Error e = OpenBuffer(index, writable, fd, size); e != Error::kOk) { + return e; + } + return MapBuffer(index, fd.Get(), size, + writable ? PROT_READ | PROT_WRITE : PROT_READ); +} + +// Creates buffer 0 and publishes it in the CCB. If another publisher got +// there first this maps nothing, and the caller attaches to the channel's +// buffer. +Error ChannelMemory::CreateBuffer(uint64_t full_size) { + char name[kMaxChannelNameLength + 64]; + if (Error e = BufferName(0, name); e != Error::kOk) { + return e; + } +#if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_MEMFD + UniqueFd fd(CreateMemfd(name, full_size)); + if (!fd.Valid()) { + return Error::kSharedMemoryError; + } +#else + const bool root = ::getuid() == 0; +#if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_POSIX + if (Error e = CreateShadowFile(name); e != Error::kOk) { + return e; + } + char shm_name[64]; + if (Error e = PosixShmName(name, shm_name); e != Error::kOk) { + return e; + } + const char *path = name; + UniqueFd fd(OpenShm(shm_name, O_RDWR | O_CREAT | O_EXCL)); +#else + char path[kMaxChannelNameLength + 80]; + (void)std::snprintf(path, sizeof(path), "/dev/shm/%s", name); + UniqueFd fd(OpenShm(name, O_RDWR | O_CREAT | O_EXCL)); +#endif + if (!fd.Valid()) { + // EEXIST: another publisher created the buffer. + return errno == EEXIST ? Error::kOk : Error::kSharedMemoryError; + } +#if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_POSIX + // Record the size before sizing the shm object, matching the standard + // client: an attacher that sees a nonzero shm size can trust the record. + if (Error e = WriteShadowSize(name, full_size); e != Error::kOk) { + (void)::shm_unlink(shm_name); + return e; + } +#endif + if (::ftruncate(fd.Get(), static_cast(full_size)) != 0 || + ::chmod(path, 0777) != 0 || + (root && ::chown(path, static_cast(context_->user_id), + static_cast(context_->group_id)) != 0)) { +#if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_POSIX + (void)::shm_unlink(shm_name); +#endif + return Error::kSharedMemoryError; + } +#endif + bcb_->sizes[0].store(full_size, std::memory_order_relaxed); + int expected = 0; + if (!ccb_->num_buffers.compare_exchange_strong( + expected, 1, std::memory_order_release, std::memory_order_relaxed)) { + return Error::kOk; + } +#if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_MEMFD + ClientBuffer registration; + registration.channel_name = context_->channel_name; + registration.session_id = context_->session_id; + registration.buffer_index = 0; + registration.full_size = full_size; + if (Error e = context_->connection->RegisterBuffer(registration, fd.Get()); + e != Error::kOk) { + expected = 1; + if (ccb_->num_buffers.compare_exchange_strong(expected, 0, + std::memory_order_acq_rel, + std::memory_order_relaxed)) { + bcb_->sizes[0].store(0, std::memory_order_relaxed); + } + return e; + } +#endif + return MapBuffer(0, fd.Get(), full_size, PROT_READ | PROT_WRITE); +} + +Error ChannelMemory::CreateOrAttachBuffer(int64_t slot_size) { + if (ccb_ == nullptr) { + return Error::kNotInitialized; + } + if (index_ != -1) { + return Error::kAlreadyInitialized; + } + const uint64_t full_size = + static_cast(num_slots_) * + (static_cast(slot_size) + static_cast(prefix_size_)); + for (int attempt = 0; attempt < kBufferWaitMilliseconds; attempt++) { + if (ccb_->num_buffers.load(std::memory_order_acquire) == 0) { + if (Error e = CreateBuffer(full_size); e != Error::kOk) { + return e; + } + if (index_ == -1) { + // Another publisher created the buffer. It may not have published + // it yet. + SleepMillisecond(); + continue; + } + } else if (Error e = AttachBuffer(/*writable=*/true); e != Error::kOk) { + return e; + } + if (slot_size_ < slot_size) { + UnmapBuffers(); + return Error::kLayoutMismatch; + } + return Error::kOk; + } + return Error::kSharedMemoryError; +} + +Error ChannelMemory::AttachSplitBuffers(bool writable, SplitSlot *slots, + int32_t capacity, + const SplitBufferAllocator &allocator) { + if (ccb_ == nullptr) { + return Error::kNotInitialized; + } + if (index_ != -1) { + return Error::kAlreadyInitialized; + } + if (slots == nullptr) { + return Error::kInvalidArgument; + } + if (capacity < num_slots_) { + return Error::kCapacityExceeded; + } + int index = -1; + if (Error e = NewestIndex(index); e != Error::kOk) { + return e; + } + const uint64_t full_size = bcb_->sizes[index].load(std::memory_order_acquire); + const uint64_t prefixes = + static_cast(num_slots_) * static_cast(prefix_size_); + if (full_size <= prefixes) { + return Error::kLayoutMismatch; + } + BufferReply prefix; + if (Error e = GetRegisteredBuffer(index, /*is_prefix=*/true, 0, prefix); + e != Error::kOk) { + return e; + } + if (!prefix.fd.Valid() || prefix.allocation_size < prefixes) { + return Error::kLayoutMismatch; + } + const int prot = writable ? PROT_READ | PROT_WRITE : PROT_READ; + void *p = + MapFd(prefix.fd.Get(), static_cast(prefix.allocation_size), prot); + if (p == MAP_FAILED) { + return Error::kSharedMemoryError; + } + index_ = index; + base_ = static_cast(p); + size_ = prefix.allocation_size; + slot_size_ = static_cast((full_size - prefixes) / + static_cast(num_slots_)); + split_slots_ = slots; + allocator_ = allocator; + for (int i = 0; i < num_slots_; i++) { + slots[i] = SplitSlot(); + } + const uint64_t payload_size = PageAligned(static_cast(slot_size_)); + for (int i = 0; i < num_slots_; i++) { + if (Error e = MapSplitSlot(i, payload_size, prot); e != Error::kOk) { + UnmapBuffers(); + return e; + } + } + return Error::kOk; +} + +Error ChannelMemory::MapSplitSlot(int slot_id, uint64_t payload_size, + int prot) { + BufferReply reply; + if (Error e = GetRegisteredBuffer(index_, /*is_prefix=*/false, + static_cast(slot_id), reply); + e != Error::kOk) { + return e; + } + SplitSlot &slot = split_slots_[slot_id]; + slot.info.channel_name = context_->channel_name; + slot.info.session_id = context_->session_id; + slot.info.buffer_index = static_cast(index_); + slot.info.slot_id = static_cast(slot_id); + slot.info.full_size = reply.full_size; + slot.info.allocation_size = reply.allocation_size; + slot.info.handle = reply.handle; + slot.info.map_offset = reply.map_offset; + slot.info.allocator = reply.allocator; + if (reply.allocator == BufferAllocator::kSplitCallback) { + if (allocator_.map == nullptr) { + return Error::kUnsupported; + } + slot.info.fd = reply.fd.Get(); + SplitBufferMapping mapping; + const Error e = allocator_.map(allocator_.context, slot.info, mapping); + slot.info.fd = -1; + if (e != Error::kOk) { + return e; + } + if (mapping.address == nullptr) { + return Error::kSharedMemoryError; + } + if (mapping.size == 0) { + mapping.size = payload_size; + } + slot.mapping = mapping; + slot.allocator_mapped = true; + return mapping.size < static_cast(slot_size_) + ? Error::kLayoutMismatch + : Error::kOk; + } + if (!reply.fd.Valid()) { + return Error::kSharedMemoryError; + } + void *p = MapFd(reply.fd.Get(), static_cast(payload_size), prot); + if (p == MAP_FAILED) { + return Error::kSharedMemoryError; + } + slot.mapping.address = p; + slot.mapping.size = payload_size; + return Error::kOk; +} + +shm::MessagePrefix *ChannelMemory::Prefix(const shm::MessageSlot *slot) const { + if (!InMappedBuffer(slot)) { + return nullptr; + } + const int64_t stride = split_slots_ != nullptr + ? prefix_size_ + : prefix_size_ + shm::Aligned64(slot_size_); + return reinterpret_cast(base_ + stride * slot->id); +} + +char *ChannelMemory::Payload(const shm::MessageSlot *slot) const { + if (!InMappedBuffer(slot)) { + return nullptr; + } + if (split_slots_ != nullptr) { + return static_cast(split_slots_[slot->id].mapping.address); + } + return reinterpret_cast(Prefix(slot)) + prefix_size_; +} + +void ChannelMemory::TriggerRetirement(const TriggerFdList &triggers, + int32_t slot_id) const { + if (triggers.Size() == 0 || !ReportsRetirement(slot_id)) { + return; + } + for (int i = 0; i < triggers.Size(); i++) { + (void)::write(triggers.Get(i), &slot_id, sizeof(slot_id)); + } +} + +} // namespace internal +} // namespace asil +} // namespace subspace diff --git a/asil_client/channel_memory.h b/asil_client/channel_memory.h new file mode 100644 index 00000000..e49a3067 --- /dev/null +++ b/asil_client/channel_memory.h @@ -0,0 +1,144 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +// Internal to the ASIL client: the mapped shared memory of one channel and the +// slot operations that publishers and subscribers share. + +#pragma once + +#include "asil_client/error.h" +#include "asil_client/server_connection.h" +#include "asil_client/shm_layout.h" +#include "asil_client/split_buffer.h" +#include "common/bitset_view.h" +#include "common/channel_view.h" + +#include +#include + +namespace subspace { +namespace asil { + +constexpr size_t kMaxChannelNameLength = 255; + +namespace internal { + +// The clock used for message timestamps, which must match toolbelt::Now(). +uint64_t Now(); + +// Wakes the owner of a trigger fd: an eventfd on Linux, a pipe elsewhere. +void Trigger(int fd); +// Drains a poll fd. +void ClearTrigger(int fd); + +// Waits until fd is readable. A negative timeout waits forever. +Error WaitReadable(int fd, int timeout_ms); + +// Copies name into a fixed buffer. +Error CopyName(const char *name, char (&out)[kMaxChannelNameLength + 1]); + +// Where a channel's message buffers live. +struct BufferContext { + // The channel that owns the buffers: the multiplexer of a virtual channel. + const char *channel_name = nullptr; + uint64_t session_id = 0; + int32_t user_id = -1; + int32_t group_id = -1; + // Passes memfd buffers between clients. + ServerConnection *connection = nullptr; +}; + +// The slot, bitset and queue operations come from ChannelView, shared with the +// standard client. +class ChannelMemory : public ChannelView { +public: + ChannelMemory() = default; + ~ChannelMemory() { Unmap(); } + ChannelMemory(const ChannelMemory &) = delete; + ChannelMemory &operator=(const ChannelMemory &) = delete; + + // Maps the CCB and BCB. The SCB is mapped by the client. The context must + // outlive the mapping. + Error Map(shm::SystemControlBlock *scb, int ccb_fd, int bcb_fd, int num_slots, + int32_t checksum_size, int32_t metadata_size, + uint64_t subscriber_queue_arena_size, const BufferContext *context); + void Unmap(); + bool Mapped() const { return ccb_ != nullptr; } + + // A publisher or subscriber maps one buffer, the channel's newest, when it + // opens. Nothing is mapped after that. + + // Maps the newest buffer, creating the channel's first buffer if there is + // none. The buffer's slots must hold at least slot_size bytes. + Error CreateOrAttachBuffer(int64_t slot_size); + // Maps the newest buffer. Returns kNoBuffers if there is none. + Error AttachBuffer(bool writable); + // Maps the newest split buffer set: the prefixes, and each slot's payload + // into slots, which needs room for NumSlots() entries. The allocator maps + // slots that a custom allocator created. Returns kNoBuffers if there are + // none. + Error AttachSplitBuffers(bool writable, SplitSlot *slots, int32_t capacity, + const SplitBufferAllocator &allocator); + // The mapped buffer, or -1. + int BufferIndex() const { return index_; } + // Whether slot's message is in the mapped buffer. + bool InMappedBuffer(const shm::MessageSlot *slot) const { + return index_ != -1 && + slot->buffer_index.load(std::memory_order_relaxed) == index_; + } + + // The slot size of the mapped buffer. + int64_t SlotSize() const { return slot_size_; } + int32_t ChecksumSize() const { return checksum_size_; } + int32_t MetadataSize() const { return metadata_size_; } + + shm::BufferControlBlock *Bcb() const { return bcb_; } + const shm::ChannelCounters &Counters(int channel_id) const { + return scb_->counters[channel_id]; + } + + // The prefix and payload of slot, or null when it isn't in the mapped + // buffer. + shm::MessagePrefix *Prefix(const shm::MessageSlot *slot) const; + char *Payload(const shm::MessageSlot *slot) const; + + // Tells publishers that asked for retirement notification that slot_id is + // free. + void TriggerRetirement(const TriggerFdList &triggers, int32_t slot_id) const; + +private: + Error BufferName(int index, char (&out)[kMaxChannelNameLength + 64]) const; + Error NewestIndex(int &index) const; + Error OpenBuffer(int index, bool writable, UniqueFd &fd, + uint64_t &size) const; + Error MapBuffer(int index, int fd, uint64_t size, int prot); + Error CreateBuffer(uint64_t size); + Error GetRegisteredBuffer(int index, bool is_prefix, uint32_t slot_id, + BufferReply &reply) const; + Error MapSplitSlot(int slot_id, uint64_t payload_size, int prot); + void UnmapBuffers(); + + shm::SystemControlBlock *scb_ = nullptr; + shm::BufferControlBlock *bcb_ = nullptr; + const BufferContext *context_ = nullptr; + size_t ccb_size_ = 0; + int32_t checksum_size_ = 4; + int32_t metadata_size_ = 0; + int32_t prefix_size_ = 64; + + // The mapped buffer: the whole buffer, or the prefixes of a split buffer + // set. + int index_ = -1; + char *base_ = nullptr; + uint64_t size_ = 0; + int64_t slot_size_ = 0; + // The caller's slot storage for a split buffer set, or null. + SplitSlot *split_slots_ = nullptr; + SplitBufferAllocator allocator_; +}; + +} // namespace internal +} // namespace asil +} // namespace subspace diff --git a/asil_client/client.cc b/asil_client/client.cc new file mode 100644 index 00000000..c4f50290 --- /dev/null +++ b/asil_client/client.cc @@ -0,0 +1,45 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +#include "asil_client/client.h" + +#include + +namespace subspace { +namespace asil { + +Client::~Client() { + if (scb_ != nullptr) { + (void)::munmap(scb_, sizeof(shm::SystemControlBlock)); + } +} + +Error Client::Init(ServerConnection &connection, const char *client_name) { + if (scb_ != nullptr) { + return Error::kAlreadyInitialized; + } + InitReply reply; + if (Error e = connection.Init(client_name, reply); e != Error::kOk) { + return e; + } + void *scb = ::mmap(nullptr, sizeof(shm::SystemControlBlock), PROT_READ, + MAP_SHARED, reply.scb.Get(), 0); + if (scb == MAP_FAILED) { + return Error::kSharedMemoryError; + } + connection_ = &connection; + scb_ = static_cast(scb); + session_id_ = reply.session_id; + user_id_ = reply.user_id; + group_id_ = reply.group_id; + return Error::kOk; +} + +const char *Client::LastServerError() const { + return connection_ == nullptr ? "" : connection_->LastServerError(); +} + +} // namespace asil +} // namespace subspace diff --git a/asil_client/client.h b/asil_client/client.h new file mode 100644 index 00000000..44f9be30 --- /dev/null +++ b/asil_client/client.h @@ -0,0 +1,82 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +// A Subspace client for safety-related software. +// +// The client publishes and reads messages on fixed-size channels, reliable or +// unreliable, plain or virtual, sharing them with the standard clients. It +// is written in C++17 using only the standard library and POSIX. It throws no +// exceptions and returns an Error from every operation that can fail. It +// makes no heap allocations: buffers and tables have fixed capacities, and +// publishing and reading messages talks to the server only when publishers, +// subscribers or memfd buffers change. +// +// // The wire buffer is 16 KB. Pass a larger size when a channel handshake +// // needs more room: PhaserServerConnection connection(64 * 1024); +// subspace::asil::PhaserServerConnection connection; +// connection.Connect("/tmp/subspace"); +// subspace::asil::Client client; +// client.Init(connection, "my_client"); +// subspace::asil::PublisherOptions options; +// options.slot_size = 256; +// options.num_slots = 8; +// subspace::asil::Publisher publisher; +// client.CreatePublisher("/chan", options, publisher); + +#pragma once + +#include "asil_client/error.h" +#include "asil_client/publisher.h" +#include "asil_client/server_connection.h" +#include "asil_client/shm_layout.h" +#include "asil_client/subscriber.h" + +#include + +namespace subspace { +namespace asil { + +// A connection to one Subspace server. It must outlive its publishers and +// subscribers, and the ServerConnection must outlive it. It is not thread +// safe. +class Client { +public: + Client() = default; + ~Client(); + Client(const Client &) = delete; + Client &operator=(const Client &) = delete; + + Error Init(ServerConnection &connection, const char *client_name); + bool Initialized() const { return scb_ != nullptr; } + + Error CreatePublisher(const char *channel_name, + const PublisherOptions &options, Publisher &publisher) { + return publisher.Open(*this, channel_name, options); + } + Error CreateSubscriber(const char *channel_name, + const SubscriberOptions &options, + Subscriber &subscriber) { + return subscriber.Open(*this, channel_name, options); + } + + // The detail for the last handshake that failed with one. For + // kServerRejected this is the server's reason. For kCapacityExceeded it + // says which buffer the request or response did not fit. Empty when the + // last such failure had no detail. + const char *LastServerError() const; + +private: + friend class Publisher; + friend class Subscriber; + + ServerConnection *connection_ = nullptr; + shm::SystemControlBlock *scb_ = nullptr; + uint64_t session_id_ = 0; + int32_t user_id_ = -1; + int32_t group_id_ = -1; +}; + +} // namespace asil +} // namespace subspace diff --git a/asil_client/error.cc b/asil_client/error.cc new file mode 100644 index 00000000..b8b11661 --- /dev/null +++ b/asil_client/error.cc @@ -0,0 +1,54 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +#include "asil_client/error.h" + +namespace subspace { +namespace asil { + +const char *ErrorString(Error error) { + switch (error) { + case Error::kOk: + return "ok"; + case Error::kInvalidArgument: + return "invalid argument"; + case Error::kNotInitialized: + return "not initialized"; + case Error::kAlreadyInitialized: + return "already initialized"; + case Error::kConnectionFailed: + return "connection to server failed"; + case Error::kProtocolError: + return "protocol error"; + case Error::kServerRejected: + return "server rejected request"; + case Error::kSharedMemoryError: + return "shared memory error"; + case Error::kLayoutMismatch: + return "shared memory layout mismatch"; + case Error::kUnsupported: + return "unsupported channel feature"; + case Error::kNoSlot: + return "no slot available"; + case Error::kMessageTooLarge: + return "message too large"; + case Error::kChecksumMismatch: + return "checksum mismatch"; + case Error::kTimeout: + return "timeout"; + case Error::kCapacityExceeded: + return "capacity exceeded"; + case Error::kActiveMessageLimit: + return "too many active messages"; + case Error::kNoBuffers: + return "channel has no buffers"; + case Error::kBufferNotMapped: + return "message buffer not mapped"; + } + return "unknown error"; +} + +} // namespace asil +} // namespace subspace diff --git a/asil_client/error.h b/asil_client/error.h new file mode 100644 index 00000000..e4bf179a --- /dev/null +++ b/asil_client/error.h @@ -0,0 +1,59 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +#pragma once + +#include + +namespace subspace { +namespace asil { + +// Every ASIL client operation returns one of these. The client throws no +// exceptions. +enum class Error : int32_t { + kOk = 0, + // An argument is out of range or a required pointer is null. + kInvalidArgument, + // The object hasn't been set up, or has been closed. + kNotInitialized, + // The object is already set up. + kAlreadyInitialized, + // Talking to the server failed. The connection is unusable. + kConnectionFailed, + // The server sent something the client can't use. + kProtocolError, + // The server refused the request. Client::LastServerError() says why. + kServerRejected, + // A shared memory system call failed. errno is preserved. + kSharedMemoryError, + // The channel's shared memory doesn't have the expected layout. + kLayoutMismatch, + // The channel uses a feature that the ASIL client doesn't provide. + kUnsupported, + // No slot could be claimed. + kNoSlot, + // The message is bigger than the slot. + kMessageTooLarge, + // The message checksum is wrong. + kChecksumMismatch, + // The wait timed out. + kTimeout, + // A fixed capacity, such as the channel name length, was exceeded. + kCapacityExceeded, + // The subscriber already holds max_active_messages messages. + kActiveMessageLimit, + // The channel has no message buffers to map. The server creates them for + // a static channel; otherwise a publisher must open first. + kNoBuffers, + // The message is in a buffer that a standard publisher created after this + // subscriber opened, by resizing the channel. The message is skipped. + kBufferNotMapped, +}; + +// Returns a static description of the error. +const char *ErrorString(Error error); + +} // namespace asil +} // namespace subspace diff --git a/asil_client/layout_test.cc b/asil_client/layout_test.cc new file mode 100644 index 00000000..a89bd94b --- /dev/null +++ b/asil_client/layout_test.cc @@ -0,0 +1,750 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +// Checks the shared-memory protocol code in common/ that the ASIL client and +// the standard client share: the channel control block regions, finding and +// publishing a slot, reading a message, and the message checksum. + +#include "asil_client/shm_layout.h" +#include "client/checksum.h" +#include "common/channel.h" +#include "common/channel_view.h" +#include "common/message_checksum.h" +#include "common/publish.h" +#include "common/slot_search.h" +#include "common/subscribe.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace shm = ::subspace::asil::shm; +using ::subspace::ChannelControlBlock; +using ::subspace::ChannelView; +using ::subspace::InPlaceSlotQueue; +using ::subspace::MessagePrefix; +using ::subspace::MessageSlot; +using ::subspace::PublishedSlot; +using ::subspace::SlotSearch; + +TEST(LayoutTest, CcbRegions) { + for (int num_slots : {1, 2, 7, 8, 63, 64, 65, 100, 1000, 4096}) { + SCOPED_TRACE(num_slots); + const size_t bitset = ::subspace::SizeofAtomicBitSet(num_slots); + EXPECT_EQ(shm::SizeofBitset(num_slots), bitset); + const size_t retired = static_cast( + ::subspace::Aligned(sizeof(::subspace::ChannelControlBlock) + + num_slots * sizeof(::subspace::MessageSlot))); + EXPECT_EQ(shm::RetiredSlotsOffset(num_slots), retired); + const size_t free_slots = + retired + static_cast(::subspace::Aligned(bitset)); + EXPECT_EQ(shm::FreeSlotsOffset(num_slots), free_slots); + const size_t available = + free_slots + static_cast(::subspace::Aligned(bitset)); + EXPECT_EQ(shm::AvailableSlotsOffset(num_slots, 0), available); + EXPECT_EQ(shm::AvailableSlotsOffset(num_slots, 5), available + 5 * bitset); + EXPECT_EQ(shm::SlotQueueIndexOffset(num_slots), + available + ::subspace::AvailableSlotsSize(num_slots)); + EXPECT_EQ(shm::SlotQueueArenaOffset(num_slots), + shm::SlotQueueIndexOffset(num_slots) + + ::subspace::AvailableSlotQueueIndexSize()); + EXPECT_EQ(shm::CcbSize(num_slots, 64000), + shm::SlotQueueArenaOffset(num_slots) + 64000); + } +} + +// A channel control block in process memory, set up as the server does. +class TestChannel { +public: + static constexpr int kPublisherId = 2; + + TestChannel(int num_slots, uint64_t queue_arena_size) + : memory_(::subspace::CcbSize(num_slots, queue_arena_size) / + sizeof(Block) + + 1), + view_(reinterpret_cast(memory_.data()), + num_slots, queue_arena_size) { + ChannelControlBlock *ccb = view_.Ccb(); + new (&ccb->num_subs)::subspace::SubscriberCounter(); + new (&ccb->subscriber_cleanup_generation)::subspace:: + SubscriberCleanupGeneration(); + ccb->num_slots = num_slots; + ccb->ordinals.Init(1); + new (&ccb->subscribers) + ::subspace::AtomicBitSet<::subspace::kMaxSlotOwners>(); + auto *index = new (view_.QueueIndex())::subspace::AvailableSlotQueueIndex; + index->next_offset.store(0); + for (auto &offset : index->offsets) { + offset.store(::subspace::kInvalidSlotQueueOffset); + } + for (auto &active : index->active_publishers) { + active.store(0); + } + for (int i = 0; i < num_slots; i++) { + MessageSlot *slot = view_.Slot(i); + slot->id = i; + slot->vchan_id.store(-1); + slot->bridged_slot_id.store(-1); + new (&slot->sub_owners) + ::subspace::AtomicBitSet<::subspace::kMaxSlotOwners>(); + new (&slot->pending_subs) + ::subspace::AtomicBitSet<::subspace::kMaxSlotOwners>(); + } + } + + ChannelView &View() { return view_; } + ChannelControlBlock *Ccb() { return view_.Ccb(); } + + void AddSubscriber(int sub_id, int vchan_id) { + Ccb()->sub_vchan_ids[sub_id] = vchan_id; + Ccb()->num_subs.AddSubscriber(vchan_id); + Ccb()->subscribers.Set(sub_id); + } + + // Places a queue at offset in the queue arena. The capacity recorded in + // the queue can be more than the arena holds. + InPlaceSlotQueue *AddQueue(int sub_id, uint64_t offset, size_t capacity, + bool drop_oldest) { + char *arena = reinterpret_cast(Ccb()) + + ::subspace::SlotQueueArenaOffset(view_.NumSlots()); + auto *queue = new (arena + offset) InPlaceSlotQueue(capacity, drop_oldest); + view_.QueueIndex()->offsets[sub_id].store(offset); + return queue; + } + + // Publishes the slot as a publisher does once it has written the message. + // The message's timestamp defaults to 1000 + slot_id. + PublishedSlot Publish(int slot_id, int vchan_id, uint64_t size, + bool is_activation = false, uint64_t timestamp = 0) { + MessageSlot *slot = view_.Slot(slot_id); + slot->refs.store(::subspace::kPubOwned); + slot->vchan_id.store(static_cast(vchan_id)); + slot->message_size.store(size); + slot->bridged_slot_id.store(slot_id); + ::subspace::StampSlot(Ccb(), slot, + timestamp != 0 ? timestamp : 1000 + slot_id); + ::subspace::SubscriberQueuePublishScope publishing(view_.QueueIndex(), + kPublisherId); + EXPECT_EQ(1u, view_.QueueIndex()->active_publishers[kPublisherId].load()); + return ::subspace::CommitPublishedSlot( + view_, slot, vchan_id, is_activation, publishing, + [this](int32_t retirement_slot_id) { + evicted_retirements_.push_back(retirement_slot_id); + }); + } + + // The slots that retired as publishing dropped them from full queues. + const std::vector &EvictedRetirements() const { + return evicted_retirements_; + } + +private: + struct alignas(64) Block { + char bytes[64]; + }; + std::vector memory_; + ChannelView view_; + std::vector evicted_retirements_; +}; + +TEST(PublishTest, DeliversToSubscribersOnTheVirtualChannel) { + TestChannel channel(/*num_slots=*/8, /*queue_arena_size=*/4096); + channel.AddSubscriber(0, /*vchan_id=*/-1); + channel.AddSubscriber(1, /*vchan_id=*/3); + channel.AddSubscriber(2, /*vchan_id=*/4); + InPlaceSlotQueue *queue = channel.AddQueue(1, /*offset=*/0, /*capacity=*/4, + /*drop_oldest=*/true); + + const PublishedSlot published = channel.Publish(5, /*vchan_id=*/3, 100); + EXPECT_EQ(1u, published.ordinal); + EXPECT_EQ(1005u, published.timestamp); + EXPECT_EQ(5, published.retirement_slot_id); + EXPECT_FALSE(published.retired); + + ChannelView &view = channel.View(); + EXPECT_TRUE(view.AvailableSlots(0).IsSet(5)); + EXPECT_TRUE(view.AvailableSlots(1).IsSet(5)); + EXPECT_FALSE(view.AvailableSlots(2).IsSet(5)); + + ::subspace::QueuedSlot queued; + ASSERT_TRUE(queue->TryPop(queued)); + EXPECT_EQ(5, queued.slot_id); + EXPECT_EQ(1u, queued.ordinal); + EXPECT_FALSE(queue->InsertionFailed()); + + // Subscribers 0 (every virtual channel) and 1 (vchan 3) were delivered it. + EXPECT_EQ(::subspace::BuildRefsBitField(1, 3, 2), + view.Slot(5)->refs.load()); + EXPECT_EQ(1u, channel.Ccb()->total_messages.load()); + EXPECT_EQ(100u, channel.Ccb()->total_bytes); + EXPECT_EQ(100u, channel.Ccb()->max_message_size); + EXPECT_EQ(0u, view.QueueIndex() + ->active_publishers[TestChannel::kPublisherId] + .load()); +} + +TEST(PublishTest, ActivationIsNotCountedAsData) { + TestChannel channel(/*num_slots=*/4, /*queue_arena_size=*/0); + channel.AddSubscriber(0, /*vchan_id=*/-1); + channel.Publish(0, /*vchan_id=*/-1, 1, /*is_activation=*/true); + EXPECT_TRUE(channel.View().AvailableSlots(0).IsSet(0)); + EXPECT_EQ(1u, channel.Ccb()->total_messages.load()); + EXPECT_EQ(0u, channel.Ccb()->total_bytes); +} + +TEST(PublishTest, FullQueueRecordsInsertionFailure) { + TestChannel channel(/*num_slots=*/4, /*queue_arena_size=*/4096); + channel.AddSubscriber(0, /*vchan_id=*/-1); + InPlaceSlotQueue *queue = channel.AddQueue(0, /*offset=*/0, /*capacity=*/1, + /*drop_oldest=*/false); + channel.Publish(0, /*vchan_id=*/-1, 10); + EXPECT_FALSE(queue->InsertionFailed()); + channel.Publish(1, /*vchan_id=*/-1, 10); + EXPECT_TRUE(queue->InsertionFailed()); + + // The bitset still records both messages. + EXPECT_TRUE(channel.View().AvailableSlots(0).IsSet(0)); + EXPECT_TRUE(channel.View().AvailableSlots(0).IsSet(1)); +} + +TEST(PublishTest, EvictionForgetsTheDroppedMessage) { + TestChannel channel(/*num_slots=*/4, /*queue_arena_size=*/4096); + channel.AddSubscriber(0, /*vchan_id=*/-1); + channel.AddSubscriber(1, /*vchan_id=*/-1); + InPlaceSlotQueue *queue = channel.AddQueue(0, /*offset=*/0, /*capacity=*/1, + /*drop_oldest=*/true); + channel.Publish(0, /*vchan_id=*/-1, 10); + channel.Publish(1, /*vchan_id=*/-1, 10); + + ChannelView &view = channel.View(); + EXPECT_FALSE(view.AvailableSlots(0).IsSet(0)); + EXPECT_TRUE(view.AvailableSlots(0).IsSet(1)); + // Subscriber 1 has no queue, so it still has both messages. + EXPECT_TRUE(view.AvailableSlots(1).IsSet(0)); + EXPECT_EQ(1u, queue->OverflowCount()); + EXPECT_FALSE(queue->InsertionFailed()); + // The pin taken to clear the bit is released. + // Both subscribers were delivered the message, and eviction does not + // change the countdown. + EXPECT_EQ(::subspace::BuildRefsBitField(1, -1, 2), view.Slot(0)->refs.load()); + EXPECT_TRUE(channel.EvictedRetirements().empty()); + + ::subspace::QueuedSlot queued; + ASSERT_TRUE(queue->TryPop(queued)); + EXPECT_EQ(1, queued.slot_id); +} + +TEST(PublishTest, EvictionKeepsAMessageStillBeingPublished) { + TestChannel channel(/*num_slots=*/4, /*queue_arena_size=*/4096); + channel.AddSubscriber(0, /*vchan_id=*/-1); + InPlaceSlotQueue *queue = channel.AddQueue(0, /*offset=*/0, /*capacity=*/1, + /*drop_oldest=*/true); + // Another publisher has queued slot 0 but not yet committed it. + MessageSlot *in_flight = channel.View().Slot(0); + in_flight->refs.store(::subspace::kPubOwned); + in_flight->ordinal.store(7); + ASSERT_TRUE(queue->Push(0, 7)); + + channel.Publish(1, /*vchan_id=*/-1, 10); + EXPECT_TRUE(queue->InsertionFailed()); + EXPECT_EQ(0u, queue->OverflowCount()); + EXPECT_TRUE(channel.View().AvailableSlots(0).IsSet(1)); + ::subspace::QueuedSlot queued; + ASSERT_TRUE(queue->TryPop(queued)); + EXPECT_EQ(0, queued.slot_id); +} + +TEST(PublishTest, EvictionRetiresASlotReleasedDuringThePin) { + TestChannel channel(/*num_slots=*/4, /*queue_arena_size=*/4096); + channel.AddSubscriber(0, /*vchan_id=*/-1); + InPlaceSlotQueue *queue = channel.AddQueue(0, /*offset=*/0, /*capacity=*/1, + /*drop_oldest=*/true); + channel.Publish(0, /*vchan_id=*/-1, 10); + ChannelView &view = channel.View(); + MessageSlot *slot = view.Slot(0); + slot->bridged_slot_id.store(6); + // The subscriber has finished with the message (pending is zero), but its + // release found the slot pinned by an earlier eviction and so did not retire + // it. Dropping that pin retires the slot. + slot->refs.store(::subspace::BuildRefsBitField(1, -1, 0)); + + channel.Publish(1, /*vchan_id=*/-1, 10); + EXPECT_EQ(1u, queue->OverflowCount()); + EXPECT_TRUE(view.RetiredSlots().IsSet(0)); + EXPECT_EQ(std::vector{6}, channel.EvictedRetirements()); +} + +TEST(PublishTest, QueueOutsideTheArenaIsIgnored) { + const uint64_t arena = ::subspace::SizeofSlotQueue(4); + TestChannel channel(/*num_slots=*/4, arena); + channel.AddSubscriber(0, /*vchan_id=*/-1); + channel.AddSubscriber(1, /*vchan_id=*/-1); + // Queue 0 claims more entries than the arena holds. + channel.AddQueue(0, /*offset=*/0, /*capacity=*/5, /*drop_oldest=*/true); + // Queue 1 starts past the end of the arena. + channel.View().QueueIndex()->offsets[1].store(arena + 8); + + EXPECT_EQ(nullptr, channel.View().Queue(0)); + EXPECT_EQ(nullptr, channel.View().Queue(1)); + EXPECT_EQ(nullptr, channel.View().Queue(2)); + + channel.Publish(2, /*vchan_id=*/-1, 10); + EXPECT_TRUE(channel.View().AvailableSlots(0).IsSet(2)); + EXPECT_TRUE(channel.View().AvailableSlots(1).IsSet(2)); +} + +// What a slot search asks of its client, recorded. +class TestHooks : public ::subspace::SlotSearchHooks { +public: + explicit TestHooks(int num_slots) : prefixes_(num_slots) {} + + bool UsableSlot(MessageSlot *slot) { return unusable.count(slot->id) == 0; } + void Embargo(int slot_id) { embargoed.insert(slot_id); } + bool Embargoed(int slot_id) const { return embargoed.count(slot_id) != 0; } + void AssignBuffer(MessageSlot *slot) { slot->buffer_index.store(0); } + MessagePrefix *Prefix(MessageSlot *slot) { return &prefixes_[slot->id]; } + void ForcedReuse(MessageSlot *slot) { forced_reuse.push_back(slot->id); } + + std::set unusable; + std::set embargoed; + std::vector forced_reuse; + +private: + std::vector prefixes_; +}; + +SlotSearch Search() { + SlotSearch search; + search.owner = TestChannel::kPublisherId; + return search; +} + +constexpr uint64_t kOwnedByPublisher = + ::subspace::kPubOwned | TestChannel::kPublisherId; + +// A subscriber reads the message in slot_id and releases it. +void ReadAndRelease(ChannelView &view, int sub_id, int slot_id, + bool reliable) { + MessageSlot *slot = view.Slot(slot_id); + ASSERT_TRUE(::subspace::ClaimMessageReference( + view, slot, sub_id, reliable, slot->ordinal.load(), + slot->vchan_id.load())); + view.AvailableSlots(sub_id).Clear(slot_id); + ::subspace::MarkMessageSeen(slot, reliable); + EXPECT_TRUE(::subspace::ReleaseMessageReference(view, slot, sub_id, reliable) + .released); +} + +// A subscriber clears its slot's retired bit only after it has released the +// slot, so a publisher can claim and publish in between, leaving the bit on +// an unread message. +TEST(SlotSearchTest, StaleRetiredBitOnAnUnreadMessageIsNotTaken) { + for (bool reliable : {false, true}) { + SCOPED_TRACE(reliable); + TestChannel channel(/*num_slots=*/4, /*queue_arena_size=*/0); + ChannelView &view = channel.View(); + channel.AddSubscriber(0, /*vchan_id=*/-1); + for (int i = 0; i < 4; i++) { + channel.Publish(i, /*vchan_id=*/-1, 10); + } + view.RetiredSlots().Set(3); + const uint64_t unread_refs = view.Slot(3)->refs.load(); + + TestHooks hooks(4); + const ::subspace::ChannelCounters counters{}; + MessageSlot *slot = + reliable + ? ::subspace::ClaimSlotReliable(view, Search(), counters, hooks) + : ::subspace::ClaimSlotUnreliable(view, Search(), hooks); + + // The oldest message goes instead. + ASSERT_NE(nullptr, slot); + EXPECT_EQ(0, slot->id); + EXPECT_EQ(std::vector{0}, hooks.forced_reuse); + EXPECT_EQ(unread_refs, view.Slot(3)->refs.load()); + EXPECT_TRUE(view.AvailableSlots(0).IsSet(3)); + EXPECT_FALSE(view.RetiredSlots().IsSet(3)); + } +} + +TEST(SlotSearchTest, ClaimedSlotIsReset) { + TestChannel channel(/*num_slots=*/2, /*queue_arena_size=*/0); + ChannelView &view = channel.View(); + channel.AddSubscriber(0, /*vchan_id=*/-1); + channel.AddSubscriber(1, /*vchan_id=*/-1); + channel.Publish(0, /*vchan_id=*/-1, 10); + channel.Publish(1, /*vchan_id=*/-1, 10); + ReadAndRelease(view, 0, 0, /*reliable=*/false); + ReadAndRelease(view, 1, 0, /*reliable=*/false); + ASSERT_TRUE(view.RetiredSlots().IsSet(0)); + + TestHooks hooks(2); + hooks.Prefix(view.Slot(0))->flags = ::subspace::kMessageActivate; + SlotSearch search = Search(); + search.vchan_id = 5; + MessageSlot *slot = ::subspace::ClaimSlotUnreliable(view, search, hooks); + ASSERT_EQ(view.Slot(0), slot); + EXPECT_EQ(kOwnedByPublisher, slot->refs.load()); + EXPECT_EQ(0u, slot->ordinal.load()); + EXPECT_EQ(0u, slot->timestamp.load()); + EXPECT_EQ(5, slot->vchan_id.load()); + EXPECT_EQ(0, slot->buffer_index.load()); + EXPECT_EQ(0, hooks.Prefix(slot)->flags); + EXPECT_EQ(5, hooks.Prefix(slot)->vchan_id); + EXPECT_TRUE(hooks.forced_reuse.empty()); + EXPECT_FALSE(view.RetiredSlots().IsSet(0)); +} + +TEST(SlotSearchTest, ForcedReuseForgetsTheUnreadMessage) { + TestChannel channel(/*num_slots=*/2, /*queue_arena_size=*/0); + ChannelView &view = channel.View(); + channel.AddSubscriber(0, /*vchan_id=*/-1); + channel.AddSubscriber(1, /*vchan_id=*/-1); + channel.Publish(0, /*vchan_id=*/-1, 10); + channel.Publish(1, /*vchan_id=*/-1, 10); + + TestHooks hooks(2); + MessageSlot *slot = ::subspace::ClaimSlotUnreliable(view, Search(), hooks); + ASSERT_EQ(view.Slot(0), slot); + EXPECT_EQ(std::vector{0}, hooks.forced_reuse); + EXPECT_FALSE(view.AvailableSlots(0).IsSet(0)); + EXPECT_FALSE(view.AvailableSlots(1).IsSet(0)); + EXPECT_TRUE(view.AvailableSlots(0).IsSet(1)); +} + +TEST(SlotSearchTest, UnreliablePrefersRetiredSlotsOnlyWhileSubscribed) { + for (bool subscribed : {false, true}) { + for (bool prefer_retired : {false, true}) { + SCOPED_TRACE(testing::Message() << subscribed << " " << prefer_retired); + TestChannel channel(/*num_slots=*/4, /*queue_arena_size=*/0); + ChannelView &view = channel.View(); + view.FreeSlots().Set(2); + view.FreeSlots().Set(3); + if (subscribed) { + channel.AddSubscriber(0, /*vchan_id=*/-1); + } + channel.Publish(0, /*vchan_id=*/-1, 10); + channel.Publish(1, /*vchan_id=*/-1, 10); + if (subscribed) { + ReadAndRelease(view, 0, 1, /*reliable=*/false); + } else { + view.RetiredSlots().Set(1); + } + ASSERT_TRUE(view.RetiredSlots().IsSet(1)); + + TestHooks hooks(4); + SlotSearch search = Search(); + search.prefer_retired = prefer_retired; + MessageSlot *slot = ::subspace::ClaimSlotUnreliable(view, search, hooks); + ASSERT_NE(nullptr, slot); + EXPECT_EQ(subscribed && prefer_retired ? 1 : 2, slot->id); + } + } +} + +// With nothing subscribed every message retires when it's published. +TEST(SlotSearchTest, IdlePublisherRecyclesTheOldestRetiredSlot) { + TestChannel channel(/*num_slots=*/4, /*queue_arena_size=*/0); + ChannelView &view = channel.View(); + const uint64_t timestamps[] = {400, 300, 100, 200}; + for (int i = 0; i < 4; i++) { + channel.Publish(i, /*vchan_id=*/-1, 10, /*is_activation=*/false, + timestamps[i]); + view.RetiredSlots().Set(i); + } + TestHooks hooks(4); + MessageSlot *slot = ::subspace::ClaimSlotUnreliable(view, Search(), hooks); + ASSERT_NE(nullptr, slot); + EXPECT_EQ(2, slot->id); +} + +TEST(SlotSearchTest, UnusableSlotIsGivenBackAndEmbargoed) { + TestChannel channel(/*num_slots=*/3, /*queue_arena_size=*/0); + ChannelView &view = channel.View(); + channel.AddSubscriber(0, /*vchan_id=*/-1); + for (int i = 0; i < 3; i++) { + channel.Publish(i, /*vchan_id=*/-1, 10); + } + ReadAndRelease(view, 0, 0, /*reliable=*/false); + const uint64_t retired_refs = view.Slot(0)->refs.load(); + + TestHooks hooks(3); + hooks.unusable.insert(0); + MessageSlot *slot = ::subspace::ClaimSlotUnreliable(view, Search(), hooks); + ASSERT_NE(nullptr, slot); + EXPECT_EQ(1, slot->id); + EXPECT_EQ(std::set{0}, hooks.embargoed); + EXPECT_EQ(retired_refs, view.Slot(0)->refs.load()); +} + +// A reliable publisher never overtakes a message that a reliable subscriber +// hasn't seen. +TEST(SlotSearchTest, ReliablePublisherStopsAtAnUnseenMessage) { + TestChannel channel(/*num_slots=*/4, /*queue_arena_size=*/0); + ChannelView &view = channel.View(); + channel.AddSubscriber(0, /*vchan_id=*/-1); + ::subspace::ChannelCounters counters{}; + counters.num_reliable_subs = 1; + for (int i = 0; i < 4; i++) { + channel.Publish(i, /*vchan_id=*/-1, 10); + } + for (int i : {0, 2}) { + MessageSlot *s = view.Slot(i); + ASSERT_TRUE(::subspace::SkipUnreadMessage(view, s, 0, /*reliable=*/true, + s->ordinal.load(), + s->vchan_id.load())); + } + + TestHooks hooks(4); + MessageSlot *slot = + ::subspace::ClaimSlotReliable(view, Search(), counters, hooks); + ASSERT_NE(nullptr, slot); + EXPECT_EQ(0, slot->id); + // Slot 2 was seen, but it's newer than the unseen message in slot 1. + EXPECT_EQ(nullptr, + ::subspace::ClaimSlotReliable(view, Search(), counters, hooks)); +} + +TEST(SlotSearchTest, ReliablePublisherDoesNotTakeAHeldSlot) { + TestChannel channel(/*num_slots=*/2, /*queue_arena_size=*/0); + ChannelView &view = channel.View(); + channel.AddSubscriber(0, /*vchan_id=*/-1); + ::subspace::ChannelCounters counters{}; + counters.num_reliable_subs = 1; + channel.Publish(0, /*vchan_id=*/-1, 10); + channel.Publish(1, /*vchan_id=*/-1, 10); + MessageSlot *held = view.Slot(0); + ASSERT_TRUE(::subspace::ClaimMessageReference( + view, held, 0, /*reliable=*/true, held->ordinal.load(), -1)); + ::subspace::MarkMessageSeen(held, /*reliable=*/true); + ReadAndRelease(view, 0, 1, /*reliable=*/true); + + TestHooks hooks(2); + MessageSlot *slot = + ::subspace::ClaimSlotReliable(view, Search(), counters, hooks); + ASSERT_NE(nullptr, slot); + EXPECT_EQ(1, slot->id); + EXPECT_EQ(nullptr, + ::subspace::ClaimSlotReliable(view, Search(), counters, hooks)); +} + +TEST(SubscribeTest, CommittedOrdinal) { + TestChannel channel(/*num_slots=*/1, /*queue_arena_size=*/0); + MessageSlot *slot = channel.View().Slot(0); + EXPECT_EQ(0u, ::subspace::CommittedOrdinal(slot)); + channel.Publish(0, /*vchan_id=*/-1, 10); + EXPECT_EQ(1u, ::subspace::CommittedOrdinal(slot)); + // A publisher reusing the slot zeroes the ordinal first. + slot->ordinal.store(0); + EXPECT_EQ(0u, ::subspace::CommittedOrdinal(slot)); + slot->ordinal.store(2); + EXPECT_EQ(0u, ::subspace::CommittedOrdinal(slot)); + slot->ordinal.store(1); + slot->refs.store(kOwnedByPublisher); + EXPECT_EQ(0u, ::subspace::CommittedOrdinal(slot)); +} + +TEST(SubscribeTest, LastReleaseRetiresTheSlot) { + TestChannel channel(/*num_slots=*/2, /*queue_arena_size=*/0); + ChannelView &view = channel.View(); + channel.AddSubscriber(0, /*vchan_id=*/-1); + channel.AddSubscriber(1, /*vchan_id=*/-1); + channel.Publish(1, /*vchan_id=*/-1, 10); + MessageSlot *slot = view.Slot(1); + slot->bridged_slot_id.store(7); + + // Nothing to release without a reference. + EXPECT_FALSE( + ::subspace::ReleaseMessageReference(view, slot, 0, false).released); + + for (int sub_id : {0, 1}) { + ASSERT_TRUE(::subspace::ClaimMessageReference(view, slot, sub_id, false, + 1, -1)); + EXPECT_TRUE(slot->sub_owners.IsSet(sub_id)); + } + const ::subspace::ReleasedMessage first = + ::subspace::ReleaseMessageReference(view, slot, 0, false); + EXPECT_TRUE(first.released); + EXPECT_FALSE(first.retired); + EXPECT_FALSE(slot->sub_owners.IsSet(0)); + + const ::subspace::ReleasedMessage last = + ::subspace::ReleaseMessageReference(view, slot, 1, false); + EXPECT_TRUE(last.released); + EXPECT_TRUE(last.retired); + EXPECT_EQ(7, last.retirement_slot_id); + EXPECT_TRUE(view.RetiredSlots().IsSet(1)); +} + +TEST(SubscribeTest, UnclaimLeavesTheMessageUnread) { + TestChannel channel(/*num_slots=*/1, /*queue_arena_size=*/0); + ChannelView &view = channel.View(); + channel.AddSubscriber(0, /*vchan_id=*/-1); + channel.Publish(0, /*vchan_id=*/-1, 10); + MessageSlot *slot = view.Slot(0); + const uint64_t refs = slot->refs.load(); + ASSERT_TRUE(::subspace::ClaimMessageReference(view, slot, 0, false, 1, -1)); + ::subspace::UnclaimMessageReference(view, slot, 0, false); + EXPECT_EQ(refs, slot->refs.load()); + EXPECT_FALSE(slot->sub_owners.IsSet(0)); + EXPECT_TRUE(view.AvailableSlots(0).IsSet(0)); + EXPECT_FALSE(view.RetiredSlots().IsSet(0)); +} + +TEST(SubscribeTest, SkippingARecycledSlotKeepsItsBit) { + TestChannel channel(/*num_slots=*/1, /*queue_arena_size=*/0); + ChannelView &view = channel.View(); + channel.AddSubscriber(0, /*vchan_id=*/-1); + channel.Publish(0, /*vchan_id=*/-1, 10); + channel.Publish(0, /*vchan_id=*/-1, 10); + MessageSlot *slot = view.Slot(0); + + // The subscriber's snapshot saw ordinal 1, which has been overwritten. + EXPECT_FALSE(::subspace::SkipUnreadMessage(view, slot, 0, true, 1, -1)); + EXPECT_TRUE(view.AvailableSlots(0).IsSet(0)); + EXPECT_EQ(0, slot->flags.load() & ::subspace::kMessageSeenByReliable); + + EXPECT_TRUE(::subspace::SkipUnreadMessage(view, slot, 0, true, 2, -1)); + EXPECT_FALSE(view.AvailableSlots(0).IsSet(0)); + EXPECT_NE(0, slot->flags.load() & ::subspace::kMessageSeenByReliable); + EXPECT_EQ(::subspace::BuildRefsBitField(2, -1, 1), slot->refs.load()); +} + +TEST(SubscribeTest, ActivationRetirementIsNotReported) { + TestChannel channel(/*num_slots=*/2, /*queue_arena_size=*/0); + ChannelView &view = channel.View(); + view.Slot(0)->flags.store(::subspace::kMessageIsActivation); + EXPECT_FALSE(view.ReportsRetirement(0)); + EXPECT_TRUE(view.ReportsRetirement(1)); + // A bridged message names a slot in another channel. + EXPECT_TRUE(view.ReportsRetirement(5)); + EXPECT_TRUE(view.ReportsRetirement(-1)); +} + +TEST(SubscribeTest, VirtualChannelsMatch) { + EXPECT_TRUE(::subspace::VirtualChannelsMatch(-1, -1)); + EXPECT_TRUE(::subspace::VirtualChannelsMatch(-1, 3)); + EXPECT_TRUE(::subspace::VirtualChannelsMatch(3, -1)); + EXPECT_TRUE(::subspace::VirtualChannelsMatch(3, 3)); + EXPECT_FALSE(::subspace::VirtualChannelsMatch(3, 4)); +} + +TEST(PublishTest, EndNeverTakesActivePublishersBelowZero) { + TestChannel channel(/*num_slots=*/1, /*queue_arena_size=*/0); + ::subspace::AvailableSlotQueueIndex *index = channel.View().QueueIndex(); + std::atomic &active = index->active_publishers[3]; + + ::subspace::BeginSubscriberQueuePublish(index, 3); + ::subspace::BeginSubscriberQueuePublish(index, 3); + ::subspace::EndSubscriberQueuePublish(index, 3); + EXPECT_EQ(1u, active.load()); + + // The server zeroes the count when it removes the publisher. + active.store(0); + ::subspace::EndSubscriberQueuePublish(index, 3); + EXPECT_EQ(0u, active.load()); +} + +// A prefix followed by its checksum storage and metadata. +struct PrefixBuffer { + PrefixBuffer(int32_t checksum_size, int32_t metadata_size) + : memory(::subspace::PrefixSize(checksum_size, metadata_size) / + sizeof(uint64_t) + + 1), + prefix(new (memory.data()) MessagePrefix()) {} + + std::vector memory; + MessagePrefix *prefix; +}; + +uint32_t StandardChecksum(const MessagePrefix *prefix, + const std::vector &payload, + int32_t checksum_size, int32_t metadata_size) { + const ::subspace::MessageChecksumData data = + ::subspace::GetMessageChecksumData(prefix, payload.data(), payload.size(), + checksum_size, metadata_size); + uint32_t checksum = 0; + ::subspace::CalculateCRC32Checksum( + data.Spans(), absl::Span( + reinterpret_cast(&checksum), + sizeof(checksum))); + return checksum; +} + +TEST(ChecksumTest, MatchesStandardClient) { + std::mt19937 random(42); + for (int32_t checksum_size : {4, 16}) { + for (int32_t metadata_size : {0, 1, 16, 100}) { + for (size_t length : {0, 1, 7, 64, 1000}) { + SCOPED_TRACE(testing::Message() << checksum_size << " " + << metadata_size << " " << length); + PrefixBuffer buffer(checksum_size, metadata_size); + MessagePrefix *prefix = buffer.prefix; + prefix->slot_id = static_cast(random() % 100); + prefix->message_size = length; + prefix->ordinal = random(); + prefix->timestamp = random(); + prefix->vchan_id = static_cast(random() % 10) - 1; + prefix->checksum_size = static_cast(checksum_size); + prefix->metadata_size = static_cast(metadata_size); + prefix->SetHasChecksum(); + uint8_t *metadata = const_cast( + ::subspace::ChecksummedMetadata(prefix, checksum_size)); + for (int32_t i = 0; i < metadata_size; i++) { + metadata[i] = static_cast(random()); + } + std::vector payload(length); + for (uint8_t &byte : payload) { + byte = static_cast(random()); + } + + EXPECT_EQ(StandardChecksum(prefix, payload, checksum_size, + metadata_size), + ::subspace::MessageChecksum(prefix, payload.data(), length, + checksum_size, metadata_size)); + } + } + } +} + +// The bridge and the tunnel set flags after the publisher has computed the +// checksum. +TEST(ChecksumTest, TransportFlagsDoNotInvalidateTheChecksum) { + PrefixBuffer buffer(/*checksum_size=*/4, /*metadata_size=*/8); + MessagePrefix *prefix = buffer.prefix; + prefix->slot_id = 2; + prefix->message_size = 5; + prefix->ordinal = 17; + prefix->timestamp = 99; + prefix->checksum_size = 4; + prefix->metadata_size = 8; + prefix->SetHasChecksum(); + const std::vector payload = {1, 2, 3, 4, 5}; + ::subspace::SetMessageChecksum(prefix, payload.data(), payload.size(), 4, 8); + + prefix->SetIsBridged(); + prefix->SetIsCrossMachine(); + prefix->flags |= int64_t{1} << 40; + EXPECT_TRUE(::subspace::MessageChecksumMatches(prefix, payload.data(), + payload.size(), 4, 8)); + const ::subspace::MessageChecksumData data = + ::subspace::GetMessageChecksumData(prefix, payload.data(), payload.size(), + 4, 8); + EXPECT_TRUE(::subspace::VerifyCRC32Checksum( + data.Spans(), ::subspace::GetChecksumSpan( + static_cast(prefix), 4))); + + prefix->SetIsActivation(); + EXPECT_FALSE(::subspace::MessageChecksumMatches(prefix, payload.data(), + payload.size(), 4, 8)); +} + +} // namespace diff --git a/asil_client/phaser_connection.cc b/asil_client/phaser_connection.cc new file mode 100644 index 00000000..c3687787 --- /dev/null +++ b/asil_client/phaser_connection.cc @@ -0,0 +1,783 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +#include "asil_client/phaser_connection.h" + +#include "asil_client/shm_layout.h" +#include "proto/subspace.phaser.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace subspace { +namespace asil { + +namespace wire = ::subspace::phaser; + +namespace { +// Builds the permanent failure statuses before main. Connect names this so +// the initializer cannot be dropped. Copying one later does not allocate. +const bool kPermanentErrorsReady = [] { + (void)::phaser::internal::AllocationFailedError(); + (void)::phaser::internal::BufferTooSmallError(); + (void)::subspace::server_wire_internal::PermanentError( + absl::StatusCode::kResourceExhausted, "Message is too large to build"); + return true; +}(); +} // namespace + +namespace { + +#if defined(MSG_NOSIGNAL) +constexpr int kSendFlags = MSG_NOSIGNAL; +#else +constexpr int kSendFlags = 0; +#endif + +// The server's limit on descriptors in one SCM_RIGHTS message. +constexpr size_t kMaxFdsPerMessage = 252; + +std::string_view View(const char *s) { + return s == nullptr ? std::string_view() : std::string_view(s); +} + +bool SendFully(int fd, const char *data, size_t length) { + while (length > 0) { + const ssize_t n = ::send(fd, data, length, kSendFlags); + if (n < 0) { + if (errno == EINTR) { + continue; + } + return false; + } + data += n; + length -= static_cast(n); + } + return true; +} + +bool ReceiveFully(int fd, char *data, size_t length) { + while (length > 0) { + const ssize_t n = ::recv(fd, data, length, 0); + if (n < 0 && errno == EINTR) { + continue; + } + if (n <= 0) { + return false; + } + data += n; + length -= static_cast(n); + } + return true; +} + +// Duplicates the descriptor at index in fds. Indexes can repeat, so each +// use gets its own descriptor. +Error DupFd(const PhaserServerConnection::ReceivedFds &fds, int32_t index, + UniqueFd &out) { + if (index < 0 || index >= fds.Size()) { + return Error::kProtocolError; + } + const int fd = ::fcntl(fds.Get(index), F_DUPFD_CLOEXEC, 0); + if (fd < 0) { + return Error::kProtocolError; + } + out.Reset(fd); + return Error::kOk; +} + +// index(i) returns the descriptor index of the i'th of count descriptors. +template +Error FillFdList(const PhaserServerConnection::ReceivedFds &fds, size_t count, + Index index, TriggerFdList *list) { + if (list == nullptr) { + return Error::kOk; + } + list->Clear(); + for (size_t i = 0; i < count; i++) { + UniqueFd fd; + if (Error e = DupFd(fds, index(i), fd); e != Error::kOk) { + return e; + } + if (!list->Add(static_cast(fd))) { + return Error::kCapacityExceeded; + } + } + return Error::kOk; +} + +constexpr size_t Align8(size_t n) { return (n + 7) & ~size_t{7}; } + +// The message buffer and the wire buffer are the same size. A request that +// fits in the embedded arrays keeps the full embedded message buffer. +size_t MessageCapacity(size_t wire_bytes) { + if (wire_bytes <= PhaserServerConnection::kWireBufferSize) { + return PhaserServerConnection::kWireBufferSize; + } + if (wire_bytes > std::numeric_limits::max() - 7) { + return 0; + } + return Align8(wire_bytes); +} + +} // namespace + +PhaserServerConnection::PhaserServerConnection(size_t wire_buffer_size) + : wire_buffer_size_(wire_buffer_size == 0 ? kWireBufferSize + : wire_buffer_size), + message_buffer_size_(MessageCapacity(wire_buffer_size_)) { + char *message = embedded_message_; + char *wire = embedded_wire_ + kServerWireHeaderPad; + size_t message_capacity = kWireBufferSize; + size_t wire_capacity = wire_buffer_size_; + if (message_buffer_size_ == 0) { + storage_ok_ = false; + wire_capacity = 0; + } else if (message_buffer_size_ > + std::numeric_limits::max() - kServerWireHeaderPad - + kServerWireHeaderSize - wire_buffer_size_) { + storage_ok_ = false; + wire_capacity = 0; + } else if (wire_buffer_size_ > kWireBufferSize || + message_buffer_size_ > kWireBufferSize) { + const size_t bytes = message_buffer_size_ + kServerWireHeaderPad + + kServerWireHeaderSize + wire_buffer_size_; + allocated_.reset(new (std::nothrow) char[bytes]); + if (allocated_ == nullptr) { + storage_ok_ = false; + wire_capacity = 0; + } else { + message = allocated_.get(); + wire = allocated_.get() + message_buffer_size_ + kServerWireHeaderPad; + message_capacity = message_buffer_size_; + } + } else if (wire_buffer_size_ < kWireBufferSize) { + wire_capacity = wire_buffer_size_; + } + wire_ = ServerWire(ProvidedServerWireBuffers( + message, message_capacity, wire, wire_capacity)); +} + +Error PhaserServerConnection::Connect(const char *socket_name) { + (void)kPermanentErrorsReady; + if (socket_name == nullptr) { + return Error::kInvalidArgument; + } + if (socket_.Valid()) { + return Error::kAlreadyInitialized; + } + struct sockaddr_un addr; + std::memset(&addr, 0, sizeof(addr)); + addr.sun_family = AF_UNIX; + const size_t length = std::strlen(socket_name); +#if defined(__linux__) + // The server binds in the abstract namespace on Linux. + if (length > sizeof(addr.sun_path) - 2) { + return Error::kCapacityExceeded; + } + std::memcpy(addr.sun_path + 1, socket_name, length); +#else + if (length > sizeof(addr.sun_path) - 1) { + return Error::kCapacityExceeded; + } + std::memcpy(addr.sun_path, socket_name, length); +#endif + UniqueFd fd(::socket(AF_UNIX, SOCK_STREAM, 0)); + if (!fd.Valid()) { + return Error::kConnectionFailed; + } +#if defined(SO_NOSIGPIPE) + const int on = 1; + (void)::setsockopt(fd.Get(), SOL_SOCKET, SO_NOSIGPIPE, &on, sizeof(on)); +#endif + if (::connect(fd.Get(), reinterpret_cast(&addr), + sizeof(addr)) != 0) { + return Error::kConnectionFailed; + } + socket_ = static_cast(fd); + return Error::kOk; +} + +void PhaserServerConnection::SetLastError(const char *message, size_t length) { + if (message == nullptr) { + length = 0; + } else if (length > sizeof(last_error_) - 1) { + length = sizeof(last_error_) - 1; + } + if (length != 0) { + std::memcpy(last_error_, message, length); + } + last_error_[length] = '\0'; +} + +Error PhaserServerConnection::Rejected(const char *message, size_t length) { + SetLastError(message, length); + return Error::kServerRejected; +} + +// Sends the serialized request in wire_ after its length. +Error PhaserServerConnection::Send(size_t length) { + char *const header = wire_.Payload() - kServerWireHeaderSize; + const uint32_t network_length = htonl(static_cast(length)); + std::memcpy(header, &network_length, sizeof(network_length)); + if (!SendFully(socket_.Get(), header, kServerWireHeaderSize + length)) { + return Error::kConnectionFailed; + } + return Error::kOk; +} + +// Sends one descriptor the way the server reads them: the descriptor count as +// an int32 with the descriptor as SCM_RIGHTS. +Error PhaserServerConnection::SendFd(int fd) { + alignas(struct cmsghdr) char control[CMSG_SPACE(sizeof(int))]; + std::memset(control, 0, sizeof(control)); + int32_t count = 1; + struct iovec iov; + iov.iov_base = &count; + iov.iov_len = sizeof(count); + struct msghdr msg; + std::memset(&msg, 0, sizeof(msg)); + msg.msg_iov = &iov; + msg.msg_iovlen = 1; + msg.msg_control = control; + msg.msg_controllen = static_cast(sizeof(control)); + struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); + cmsg->cmsg_level = SOL_SOCKET; + cmsg->cmsg_type = SCM_RIGHTS; + cmsg->cmsg_len = CMSG_LEN(sizeof(int)); + std::memcpy(CMSG_DATA(cmsg), &fd, sizeof(int)); + for (;;) { + const ssize_t n = ::sendmsg(socket_.Get(), &msg, kSendFlags); + if (n == static_cast(sizeof(count))) { + return Error::kOk; + } + if (n < 0 && errno == EINTR) { + continue; + } + return Error::kConnectionFailed; + } +} + +// Receives a length-prefixed response into wire_. A response that does not +// fit is read and discarded so that the stream stays in step. +Error PhaserServerConnection::Receive(const char *&data, size_t &length) { + uint32_t network_length = 0; + if (!ReceiveFully(socket_.Get(), reinterpret_cast(&network_length), + sizeof(network_length))) { + return Error::kConnectionFailed; + } + length = ntohl(network_length); + if (char *buffer = wire_.ResponseBuffer(length); buffer != nullptr) { + data = buffer; + return ReceiveFully(socket_.Get(), buffer, length) + ? Error::kOk + : Error::kConnectionFailed; + } + // A response that does not fit is still consumed, so the descriptor + // message that follows stays aligned with this response. + char stack_scratch[256]; + char *scratch = wire_.ResponseBuffer(wire_buffer_size_); + size_t scratch_size = wire_buffer_size_; + if (scratch == nullptr || scratch_size == 0) { + scratch = stack_scratch; + scratch_size = sizeof(stack_scratch); + } + for (size_t remaining = length; remaining > 0;) { + const size_t chunk = remaining < scratch_size ? remaining : scratch_size; + if (!ReceiveFully(socket_.Get(), scratch, chunk)) { + return Error::kConnectionFailed; + } + remaining -= chunk; + } + SetLastError("response does not fit the wire buffer", + sizeof("response does not fit the wire buffer") - 1); + return Error::kCapacityExceeded; +} + +// The server sends one or more messages, each holding the total descriptor +// count as an int32 and some of the descriptors as SCM_RIGHTS. Descriptors +// beyond kMaxReceivedFds are closed and reported as kCapacityExceeded once +// all of them have been read. +Error PhaserServerConnection::ReceiveFds() { + alignas( + struct cmsghdr) char control[CMSG_SPACE(kMaxFdsPerMessage * sizeof(int))]; + int32_t received = 0; + bool overflow = false; + for (;;) { + int32_t total = 0; + size_t total_bytes = 0; + bool saw_rights = false; + int32_t in_message = 0; + while (total_bytes < sizeof(total)) { + std::memset(control, 0, sizeof(control)); + struct iovec iov; + iov.iov_base = reinterpret_cast(&total) + total_bytes; + iov.iov_len = sizeof(total) - total_bytes; + struct msghdr msg; + std::memset(&msg, 0, sizeof(msg)); + msg.msg_iov = &iov; + msg.msg_iovlen = 1; + msg.msg_control = control; + msg.msg_controllen = static_cast(sizeof(control)); +#if defined(MSG_CMSG_CLOEXEC) + const ssize_t n = ::recvmsg(socket_.Get(), &msg, MSG_CMSG_CLOEXEC); +#else + const ssize_t n = ::recvmsg(socket_.Get(), &msg, 0); +#endif + if (n < 0 && errno == EINTR) { + continue; + } + if (n <= 0) { + return Error::kConnectionFailed; + } + total_bytes += static_cast(n); + if ((msg.msg_flags & MSG_CTRUNC) != 0) { + return Error::kProtocolError; + } + for (struct cmsghdr *cmsg = CMSG_FIRSTHDR(&msg); cmsg != nullptr; + cmsg = CMSG_NXTHDR(&msg, cmsg)) { + if (cmsg->cmsg_level != SOL_SOCKET || cmsg->cmsg_type != SCM_RIGHTS) { + continue; + } + saw_rights = true; + const size_t data_length = cmsg->cmsg_len - CMSG_LEN(0); + const int count = static_cast(data_length / sizeof(int)); + const unsigned char *data = CMSG_DATA(cmsg); + for (int i = 0; i < count; i++) { + int fd = -1; + std::memcpy(&fd, data + static_cast(i) * sizeof(int), + sizeof(int)); + if (!fds_.Add(UniqueFd(fd))) { + overflow = true; + } + } + in_message += count; + } + } + if (total == 0) { + return Error::kOk; + } + if (!saw_rights) { + return Error::kProtocolError; + } + received += in_message; + if (received >= total) { + return overflow ? Error::kCapacityExceeded : Error::kOk; + } + } +} + +// build(request) fills in the request and read(response) handles the reply. +// A send_fd of 0 or more goes to the server after the request. +template +Error PhaserServerConnection::Transact(Build build, Read read, int send_fd) { + if (!storage_ok_) { + SetLastError("wire buffer allocation failed", + sizeof("wire buffer allocation failed") - 1); + return Error::kCapacityExceeded; + } + if (!socket_.Valid()) { + return Error::kNotInitialized; + } + fds_.Clear(); + size_t length = 0; + { + // The response is built in the request's storage, so the request goes + // out of scope first. + absl::StatusOr request = wire_.NewRequest(); + if (!request.ok()) { + Remember(request.status().message().data(), + request.status().message().size()); + return Error::kCapacityExceeded; + } + build(*request); + absl::StatusOr serialized = wire_.Serialize(*request); + if (!serialized.ok()) { + Remember(serialized.status().message().data(), + serialized.status().message().size()); + return Error::kCapacityExceeded; + } + length = *serialized; + } + + Error e = Send(length); + if (e == Error::kOk && send_fd >= 0) { + e = SendFd(send_fd); + } + const char *data = nullptr; + if (e == Error::kOk) { + e = Receive(data, length); + } + if (e == Error::kOk || e == Error::kCapacityExceeded) { + // The descriptors follow even a response that did not fit. + const Error fds_error = ReceiveFds(); + if (fds_error != Error::kOk && + (e == Error::kOk || fds_error != Error::kCapacityExceeded)) { + e = fds_error; + } + } + if (e == Error::kConnectionFailed || e == Error::kProtocolError) { + // The stream position is unknown after a failure. + socket_.Reset(); + } + if (e != Error::kOk) { + fds_.Clear(); + return e; + } + + absl::StatusOr response = wire_.NewResponse(); + if (!response.ok()) { + fds_.Clear(); + Remember(response.status().message().data(), + response.status().message().size()); + return Error::kCapacityExceeded; + } + if (absl::Status status = wire_.Decode(data, length, *response); + !status.ok()) { + fds_.Clear(); + Remember(status.message().data(), status.message().size()); + return status.code() == absl::StatusCode::kResourceExhausted + ? Error::kCapacityExceeded + : Error::kProtocolError; + } + e = read(static_cast(*response)); + fds_.Clear(); + return e; +} + +Error PhaserServerConnection::Init(const char *client_name, InitReply &reply) { + return Transact( + [&](wire::Request &request) { + wire::InitRequest *init = request.mutable_init(); + init->set_client_name(View(client_name)); + init->set_asil(true); + init->set_max_channels(shm::kMaxChannels); + init->set_max_slot_owners(shm::kMaxSlotOwners); + init->set_max_buffers(static_cast(shm::kMaxBuffers)); + }, + [&](const wire::Response &response) { + if (!response.has_init()) { + return Error::kProtocolError; + } + const wire::InitResponse &init = response.init(); + if (!init.error().empty()) { + return Rejected(init.error().data(), init.error().size()); + } + if (Error e = DupFd(fds_, init.scb_fd_index(), reply.scb); + e != Error::kOk) { + return e; + } + reply.session_id = static_cast(init.session_id()); + reply.user_id = init.user_id(); + reply.group_id = init.group_id(); + return Error::kOk; + }); +} + +Error PhaserServerConnection::CreatePublisher(const PublisherRequest &request, + PublisherReply &reply) { + return Transact( + [&](wire::Request &req) { + wire::CreatePublisherRequest *cmd = req.mutable_create_publisher(); + cmd->set_channel_name(View(request.channel_name)); + cmd->set_slot_size(request.slot_size); + cmd->set_num_slots(request.num_slots); + cmd->set_is_fixed_size(!request.server_defined); + cmd->set_server_defined(request.server_defined); + cmd->set_is_reliable(request.reliable); + if (request.type != nullptr) { + cmd->set_type(View(request.type)); + } + if (request.mux != nullptr) { + cmd->set_mux(View(request.mux)); + } + cmd->set_vchan_id(request.vchan_id); + cmd->set_subscriber_queue_arena_size( + request.subscriber_queue_arena_size); + cmd->set_checksum_size(request.checksum_size); + cmd->set_metadata_size(request.metadata_size); + cmd->set_use_split_buffers(request.use_split_buffers); + cmd->set_publisher_id(-1); + cmd->set_process_id(static_cast(::getpid())); + cmd->set_max_outstanding_slot_leases(1); + }, + [&](const wire::Response &response) { + if (!response.has_create_publisher()) { + return Error::kProtocolError; + } + const wire::CreatePublisherResponse &pub = response.create_publisher(); + if (!pub.error().empty()) { + return Rejected(pub.error().data(), pub.error().size()); + } + reply.channel_id = pub.channel_id(); + reply.publisher_id = pub.publisher_id(); + reply.num_slots = pub.num_slots(); + reply.vchan_id = pub.vchan_id(); + reply.num_sub_updates = pub.num_sub_updates(); + reply.subscriber_queue_arena_size = pub.subscriber_queue_arena_size(); + reply.slot_size = pub.slot_size(); + reply.checksum_size = pub.checksum_size(); + reply.metadata_size = pub.metadata_size(); + reply.use_split_buffers = pub.use_split_buffers(); + if (Error e = DupFd(fds_, pub.ccb_fd_index(), reply.ccb); + e != Error::kOk) { + return e; + } + if (Error e = DupFd(fds_, pub.bcb_fd_index(), reply.bcb); + e != Error::kOk) { + return e; + } + if (Error e = DupFd(fds_, pub.pub_poll_fd_index(), reply.poll); + e != Error::kOk) { + return e; + } + if (Error e = FillFdList( + fds_, pub.sub_trigger_fd_indexes_size(), + [&](size_t i) { return pub.sub_trigger_fd_indexes(i); }, + reply.subscriber_triggers); + e != Error::kOk) { + return e; + } + return FillFdList( + fds_, pub.retirement_fd_indexes_size(), + [&](size_t i) { return pub.retirement_fd_indexes(i); }, + reply.retirement_triggers); + }); +} + +Error PhaserServerConnection::CreateSubscriber(const SubscriberRequest &request, + SubscriberReply &reply) { + return Transact( + [&](wire::Request &req) { + wire::CreateSubscriberRequest *cmd = req.mutable_create_subscriber(); + cmd->set_channel_name(View(request.channel_name)); + cmd->set_subscriber_id(-1); + cmd->set_is_reliable(request.reliable); + if (request.type != nullptr) { + cmd->set_type(View(request.type)); + } + cmd->set_max_active_messages(request.max_active_messages); + if (request.mux != nullptr) { + cmd->set_mux(View(request.mux)); + } + cmd->set_vchan_id(request.vchan_id); + cmd->set_process_id(static_cast(::getpid())); + }, + [&](const wire::Response &response) { + if (!response.has_create_subscriber()) { + return Error::kProtocolError; + } + const wire::CreateSubscriberResponse &sub = + response.create_subscriber(); + if (!sub.error().empty()) { + return Rejected(sub.error().data(), sub.error().size()); + } + reply.channel_id = sub.channel_id(); + reply.subscriber_id = sub.subscriber_id(); + reply.num_slots = sub.num_slots(); + reply.vchan_id = sub.vchan_id(); + reply.num_pub_updates = sub.num_pub_updates(); + reply.checksum_size = sub.checksum_size(); + reply.metadata_size = sub.metadata_size(); + reply.subscriber_queue_size = sub.subscriber_queue_size(); + reply.subscriber_queue_arena_size = sub.subscriber_queue_arena_size(); + reply.use_split_buffers = sub.use_split_buffers(); + if (Error e = DupFd(fds_, sub.ccb_fd_index(), reply.ccb); + e != Error::kOk) { + return e; + } + if (Error e = DupFd(fds_, sub.bcb_fd_index(), reply.bcb); + e != Error::kOk) { + return e; + } + if (Error e = DupFd(fds_, sub.trigger_fd_index(), reply.trigger); + e != Error::kOk) { + return e; + } + if (Error e = DupFd(fds_, sub.poll_fd_index(), reply.poll); + e != Error::kOk) { + return e; + } + if (Error e = FillFdList( + fds_, sub.reliable_pub_trigger_fd_indexes_size(), + [&](size_t i) { + return sub.reliable_pub_trigger_fd_indexes(i); + }, + reply.reliable_publisher_triggers); + e != Error::kOk) { + return e; + } + return FillFdList( + fds_, sub.retirement_fd_indexes_size(), + [&](size_t i) { return sub.retirement_fd_indexes(i); }, + reply.retirement_triggers); + }); +} + +Error PhaserServerConnection::GetTriggers(const char *channel_name, + TriggersReply &reply) { + return Transact( + [&](wire::Request &req) { + req.mutable_get_triggers()->set_channel_name(View(channel_name)); + }, + [&](const wire::Response &response) { + if (!response.has_get_triggers()) { + return Error::kProtocolError; + } + const wire::GetTriggersResponse &triggers = response.get_triggers(); + if (!triggers.error().empty()) { + return Rejected(triggers.error().data(), triggers.error().size()); + } + if (Error e = FillFdList( + fds_, triggers.reliable_pub_trigger_fd_indexes_size(), + [&](size_t i) { + return triggers.reliable_pub_trigger_fd_indexes(i); + }, + reply.reliable_publisher_triggers); + e != Error::kOk) { + return e; + } + if (Error e = FillFdList( + fds_, triggers.sub_trigger_fd_indexes_size(), + [&](size_t i) { return triggers.sub_trigger_fd_indexes(i); }, + reply.subscriber_triggers); + e != Error::kOk) { + return e; + } + return FillFdList( + fds_, triggers.retirement_fd_indexes_size(), + [&](size_t i) { return triggers.retirement_fd_indexes(i); }, + reply.retirement_triggers); + }); +} + +Error PhaserServerConnection::RemovePublisher(const char *channel_name, + int32_t publisher_id) { + return Transact( + [&](wire::Request &req) { + wire::RemovePublisherRequest *cmd = req.mutable_remove_publisher(); + cmd->set_channel_name(View(channel_name)); + cmd->set_publisher_id(publisher_id); + }, + [&](const wire::Response &response) { + const std::string_view error = response.remove_publisher().error(); + if (!error.empty()) { + return Rejected(error.data(), error.size()); + } + return Error::kOk; + }); +} + +Error PhaserServerConnection::RemoveSubscriber(const char *channel_name, + int32_t subscriber_id) { + return Transact( + [&](wire::Request &req) { + wire::RemoveSubscriberRequest *cmd = req.mutable_remove_subscriber(); + cmd->set_channel_name(View(channel_name)); + cmd->set_subscriber_id(subscriber_id); + }, + [&](const wire::Response &response) { + const std::string_view error = response.remove_subscriber().error(); + if (!error.empty()) { + return Rejected(error.data(), error.size()); + } + return Error::kOk; + }); +} + +Error PhaserServerConnection::RegisterBuffer(const ClientBuffer &buffer, + int fd) { + if (fd < 0) { + return Error::kInvalidArgument; + } + return Transact( + [&](wire::Request &req) { + wire::RegisterClientBufferRequest *cmd = + req.mutable_register_client_buffer(); + wire::ClientBufferHandleMetadataProto *metadata = + cmd->mutable_metadata(); + metadata->set_channel_name(View(buffer.channel_name)); + metadata->set_session_id(buffer.session_id); + metadata->set_buffer_index(buffer.buffer_index); + metadata->set_slot_id(0); + metadata->set_is_prefix(false); + metadata->set_full_size(buffer.full_size); + metadata->set_allocation_size(buffer.full_size); + metadata->set_handle(static_cast(fd)); + metadata->set_allocator(wire::CLIENT_BUFFER_ALLOCATOR_ANDROID_MEMFD); + cmd->set_has_fd(true); + cmd->set_fd_index(0); + }, + [&](const wire::Response &response) { + const std::string_view error = + response.register_client_buffer().error(); + if (!error.empty()) { + return Rejected(error.data(), error.size()); + } + return Error::kOk; + }, + fd); +} + +Error PhaserServerConnection::GetBuffer(const BufferRequest &request, + BufferReply &reply) { + reply = BufferReply(); + return Transact( + [&](wire::Request &req) { + wire::GetClientBuffersRequest *cmd = req.mutable_get_client_buffers(); + cmd->set_channel_name(View(request.channel_name)); + cmd->set_session_id(request.session_id); + cmd->set_buffer_index(request.buffer_index); + cmd->set_filter_slot(true); + cmd->set_is_prefix(request.is_prefix); + cmd->set_slot_id(request.slot_id); + }, + [&](const wire::Response &response) { + if (!response.has_get_client_buffers()) { + return Error::kProtocolError; + } + const wire::GetClientBuffersResponse &buffers = + response.get_client_buffers(); + if (!buffers.error().empty()) { + return Rejected(buffers.error().data(), buffers.error().size()); + } + if (buffers.metadata_size() != buffers.fd_indexes_size()) { + return Error::kProtocolError; + } + for (size_t i = 0; i < buffers.metadata_size(); i++) { + const wire::ClientBufferHandleMetadataProto metadata = + buffers.metadata(i); + if (metadata.is_prefix() != request.is_prefix || + metadata.slot_id() != request.slot_id) { + continue; + } + if (buffers.fd_indexes(i) >= 0) { + if (Error e = DupFd(fds_, buffers.fd_indexes(i), reply.fd); + e != Error::kOk) { + return e; + } + } + reply.found = true; + reply.full_size = metadata.full_size(); + reply.allocation_size = metadata.allocation_size(); + reply.handle = metadata.handle(); + reply.map_offset = metadata.map_offset(); + reply.allocator = static_cast(metadata.allocator()); + return Error::kOk; + } + return Error::kOk; + }); +} + +} // namespace asil +} // namespace subspace diff --git a/asil_client/phaser_connection.h b/asil_client/phaser_connection.h new file mode 100644 index 00000000..6b784ddd --- /dev/null +++ b/asil_client/phaser_connection.h @@ -0,0 +1,104 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +#pragma once + +#include "asil_client/server_connection.h" +#include "common/server_wire.h" + +#include +#include +#include + +namespace subspace { +namespace asil { + +// The standard Subspace protocol: native Phaser requests and responses over +// the server's Unix socket, with file descriptors passed as SCM_RIGHTS. +// Requests and responses are Phaser messages held in a ServerWire. The +// default buffers are inside this object, so a handshake makes no heap +// allocations, even when it fails. A larger wire buffer is allocated once, +// in the constructor, and handshakes still do not allocate. A request or +// response that does not fit fails with kCapacityExceeded, and +// LastServerError() says which buffer it did not fit. +// +// The default object holds about 32 KB of buffers, so keep it in static +// storage or inside a long-lived object rather than on a small stack. +class PhaserServerConnection : public ServerConnection { +public: + // Capacity of the request or response, both as a Phaser message and as the + // payload copied onto the socket. A larger constructor argument uses this + // same size for both buffers. + static constexpr size_t kWireBufferSize = 16 * 1024; + + // wire_buffer_size is the payload capacity of one request or response. + // Zero selects kWireBufferSize. A size up to kWireBufferSize uses the + // buffer inside this object. A larger size allocates its storage here. + explicit PhaserServerConnection(size_t wire_buffer_size = kWireBufferSize); + + size_t WireBufferSize() const { return wire_buffer_size_; } + // Descriptors in one response: the channel's control blocks, the + // publisher or subscriber's own triggers, and a trigger and a retirement + // descriptor for every other publisher or subscriber. + static constexpr int kMaxReceivedFds = 2 * kMaxTriggerFds + 8; + + ~PhaserServerConnection() override = default; + + PhaserServerConnection(const PhaserServerConnection &) = delete; + PhaserServerConnection &operator=(const PhaserServerConnection &) = delete; + + Error Connect(const char *socket_name); + void Close() { socket_.Reset(); } + bool Connected() const { return socket_.Valid(); } + + Error Init(const char *client_name, InitReply &reply) override; + Error CreatePublisher(const PublisherRequest &request, + PublisherReply &reply) override; + Error CreateSubscriber(const SubscriberRequest &request, + SubscriberReply &reply) override; + Error GetTriggers(const char *channel_name, TriggersReply &reply) override; + Error RemovePublisher(const char *channel_name, + int32_t publisher_id) override; + Error RemoveSubscriber(const char *channel_name, + int32_t subscriber_id) override; + Error RegisterBuffer(const ClientBuffer &buffer, int fd) override; + Error GetBuffer(const BufferRequest &request, BufferReply &reply) override; + + const char *LastServerError() const override { return last_error_; } + + using ReceivedFds = FdList; + +private: + template + Error Transact(Build build, Read read, int send_fd = -1); + Error Send(size_t length); + Error SendFd(int fd); + Error Receive(const char *&data, size_t &length); + Error ReceiveFds(); + void SetLastError(const char *message, size_t length); + void Remember(const char *message, size_t length) { + if (message != nullptr && length != 0) { + SetLastError(message, length); + } + } + Error Rejected(const char *message, size_t length); + + UniqueFd socket_; + ReceivedFds fds_; + char last_error_[256] = {}; + size_t wire_buffer_size_ = kWireBufferSize; + size_t message_buffer_size_ = kWireBufferSize; + bool storage_ok_ = true; + // Holds the message buffer and the wire buffer when they do not fit in + // the embedded arrays. Empty for the default size. + std::unique_ptr allocated_; + alignas(8) char embedded_message_[kWireBufferSize]; + alignas(8) char + embedded_wire_[kServerWireHeaderPad + kServerWireHeaderSize + kWireBufferSize]; + ServerWire wire_; +}; + +} // namespace asil +} // namespace subspace diff --git a/asil_client/publisher.cc b/asil_client/publisher.cc new file mode 100644 index 00000000..dd381a4b --- /dev/null +++ b/asil_client/publisher.cc @@ -0,0 +1,337 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +// The publishing side of the shared memory protocol. Finding a slot uses +// common/slot_search.h and publishing one uses common/publish.h, as the +// standard client does. + +#include "asil_client/publisher.h" + +#include "asil_client/client.h" +#include "common/message_checksum.h" +#include "common/publish.h" +#include "common/slot_search.h" + +namespace subspace { +namespace asil { + +namespace { + +bool ValidLayoutSize(int32_t size) { return size >= 0 && size <= 0xFFFF; } + +} // namespace + +Error Publisher::Open(Client &client, const char *channel_name, + const PublisherOptions &options) { + if (client_ != nullptr) { + return Error::kAlreadyInitialized; + } + if (!client.Initialized()) { + return Error::kNotInitialized; + } + if (options.server_defined) { + if (options.slot_size != 0 || options.num_slots != 0 || + options.checksum_size != 0 || options.metadata_size != 0 || + options.subscriber_queue_arena_size != 0 || options.use_split_buffers) { + return Error::kInvalidArgument; + } + } else if (options.slot_size <= 0 || options.num_slots <= 0 || + !ValidLayoutSize(options.checksum_size) || + !ValidLayoutSize(options.metadata_size)) { + return Error::kInvalidArgument; + } + if (options.vchan_id < -1 || options.vchan_id >= shm::kMaxVchanId) { + return Error::kInvalidArgument; + } + if (Error e = internal::CopyName(channel_name, name_); e != Error::kOk) { + return e; + } + if (Error e = internal::CopyName( + options.mux != nullptr ? options.mux : channel_name, resolved_name_); + e != Error::kOk) { + return e; + } + PublisherRequest request; + request.channel_name = name_; + request.server_defined = options.server_defined; + request.slot_size = + options.server_defined ? 0 : shm::Aligned64(options.slot_size); + request.num_slots = options.num_slots; + request.type = options.type; + request.checksum_size = options.checksum_size; + request.metadata_size = options.metadata_size; + request.reliable = options.reliable; + request.mux = options.mux; + request.vchan_id = options.vchan_id; + request.subscriber_queue_arena_size = options.subscriber_queue_arena_size; + request.use_split_buffers = options.use_split_buffers; + PublisherReply reply; + reply.subscriber_triggers = &subscriber_triggers_; + reply.retirement_triggers = &retirement_triggers_; + if (Error e = client.connection_->CreatePublisher(request, reply); + e != Error::kOk) { + Reset(); + return e; + } + client_ = &client; + channel_id_ = reply.channel_id; + publisher_id_ = reply.publisher_id; + vchan_id_ = reply.vchan_id; + num_sub_updates_ = static_cast(reply.num_sub_updates); + checksum_ = options.checksum; + reliable_ = options.reliable; + poll_ = static_cast(reply.poll); + buffer_context_.channel_name = resolved_name_; + buffer_context_.session_id = client.session_id_; + buffer_context_.user_id = client.user_id_; + buffer_context_.group_id = client.group_id_; + buffer_context_.connection = client.connection_; + + int64_t slot_size = request.slot_size; + int32_t checksum_size = options.checksum_size; + int32_t metadata_size = options.metadata_size; + bool use_split_buffers = options.use_split_buffers; + if (options.server_defined) { + slot_size = reply.slot_size; + checksum_size = reply.checksum_size; + metadata_size = reply.metadata_size; + use_split_buffers = reply.use_split_buffers; + } + + Error e = Error::kOk; + if (channel_id_ < 0 || channel_id_ >= shm::kMaxChannels || + publisher_id_ < 0 || publisher_id_ >= shm::kMaxSlotOwners || + vchan_id_ < -1 || vchan_id_ >= shm::kMaxVchanId || + (vchan_id_ != -1) != (options.mux != nullptr) || slot_size <= 0 || + (options.server_defined && reply.num_slots <= 0) || + !ValidLayoutSize(checksum_size) || !ValidLayoutSize(metadata_size)) { + e = Error::kProtocolError; + } + if (e == Error::kOk) { + const int num_slots = + reply.num_slots > 0 ? reply.num_slots : options.num_slots; + e = memory_.Map(client.scb_, reply.ccb.Get(), reply.bcb.Get(), num_slots, + checksum_size, metadata_size, + reply.subscriber_queue_arena_size, &buffer_context_); + } + if (e == Error::kOk) { + e = use_split_buffers + ? memory_.AttachSplitBuffers( + /*writable=*/true, options.split_slots, + options.split_slot_capacity, options.split_allocator) + : memory_.CreateOrAttachBuffer(slot_size); + } + if (e == Error::kOk && memory_.SlotSize() < slot_size) { + e = Error::kLayoutMismatch; + } + if (e == Error::kOk) { + slot_ = FindFreeSlot(); + if (slot_ == nullptr) { + e = Error::kNoSlot; + } + } + if (e != Error::kOk) { + (void)Close(); + return e; + } + const bool activated = + memory_.Ccb()->activation_tracker.IsActivated(vchan_id_); + if (reliable_ || (options.activate && !activated)) { + // Reliable subscribers hold the activation message, which stops a + // reliable publisher overtaking them. + slot_->message_size.store(1, std::memory_order_relaxed); + PublishSlot(slot_, /*is_activation=*/true, nullptr); + slot_ = reliable_ ? nullptr : FindFreeSlot(); + } + TriggerSubscribers(); + return Error::kOk; +} + +void Publisher::Reset() { + memory_.Unmap(); + subscriber_triggers_.Clear(); + retirement_triggers_.Clear(); + poll_.Reset(); + client_ = nullptr; + slot_ = nullptr; + channel_id_ = -1; + publisher_id_ = -1; + vchan_id_ = -1; + reliable_ = false; +} + +Error Publisher::Close() { + if (client_ == nullptr) { + return Error::kOk; + } + // The server releases the slot this publisher holds. + const Error e = client_->connection_->RemovePublisher(name_, publisher_id_); + Reset(); + return e; +} + +Error Publisher::Wait(int timeout_ms) { + if (client_ == nullptr) { + return Error::kNotInitialized; + } + return internal::WaitReadable(poll_.Get(), timeout_ms); +} + +bool Publisher::HoldSlot() { + if (slot_ != nullptr) { + return true; + } + if (client_ == nullptr) { + return false; + } + if (reliable_) { + // A subscriber releasing a message after this makes PollFd() readable. + internal::ClearTrigger(poll_.Get()); + // With no subscribers nothing would stop the publisher taking every + // slot, and a subscriber that joined later would miss those messages. + if (memory_.NumSubscribers(vchan_id_) == 0) { + return false; + } + } + slot_ = FindFreeSlot(); + return slot_ != nullptr; +} + +void *Publisher::Buffer() { + return HoldSlot() ? memory_.Payload(slot_) : nullptr; +} + +void *Publisher::Metadata() { + if (memory_.MetadataSize() == 0 || !HoldSlot()) { + return nullptr; + } + return reinterpret_cast(&memory_.Prefix(slot_)->checksum) + + memory_.ChecksumSize(); +} + +Error Publisher::Publish(size_t message_size, PublishedMessage *published) { + if (client_ == nullptr) { + return Error::kNotInitialized; + } + if (message_size == 0) { + return Error::kInvalidArgument; + } + if (message_size > static_cast(memory_.SlotSize())) { + return Error::kMessageTooLarge; + } + if (slot_ == nullptr) { + // Buffer() found no slot, so there is nothing to publish. + return Error::kNoSlot; + } + if (Error e = RefreshTriggers(); e != Error::kOk) { + return e; + } + slot_->message_size.store(message_size, std::memory_order_relaxed); + PublishSlot(slot_, /*is_activation=*/false, published); + // A reliable publisher takes its next slot when Buffer() asks for one. + slot_ = reliable_ ? nullptr : FindFreeSlot(); + TriggerSubscribers(); + return Error::kOk; +} + +Error Publisher::RefreshTriggers() { + const uint16_t updates = memory_.Counters(channel_id_).num_sub_updates; + if (updates == num_sub_updates_) { + return Error::kOk; + } + TriggersReply reply; + reply.subscriber_triggers = &subscriber_triggers_; + reply.retirement_triggers = &retirement_triggers_; + const Error e = client_->connection_->GetTriggers(name_, reply); + if (e == Error::kOk) { + num_sub_updates_ = updates; + } + return e; +} + +void Publisher::TriggerSubscribers() const { + for (int i = 0; i < subscriber_triggers_.Size(); i++) { + internal::Trigger(subscriber_triggers_.Get(i)); + } +} + +// The publisher maps the channel's buffer when it opens the channel, so every +// claimed slot is usable. +class Publisher::SearchHooks : public SlotSearchHooks { +public: + explicit SearchHooks(Publisher &publisher) : publisher_(publisher) {} + + void AssignBuffer(shm::MessageSlot *slot) { publisher_.SetSlotBuffer(slot); } + shm::MessagePrefix *Prefix(shm::MessageSlot *slot) { + return publisher_.memory_.Prefix(slot); + } + void ForcedReuse(shm::MessageSlot *slot) { + publisher_.memory_.TriggerRetirement(publisher_.retirement_triggers_, + slot->id); + } + +private: + Publisher &publisher_; +}; + +shm::MessageSlot *Publisher::FindFreeSlot() { + SlotSearch search; + search.owner = publisher_id_; + search.vchan_id = vchan_id_; + SearchHooks hooks(*this); + if (reliable_) { + return ClaimSlotReliable(memory_, search, memory_.Counters(channel_id_), + hooks); + } + return ClaimSlotUnreliable(memory_, search, hooks); +} + +void Publisher::SetSlotBuffer(shm::MessageSlot *slot) { + shm::BufferControlBlock *bcb = memory_.Bcb(); + const int old_index = slot->buffer_index.load(std::memory_order_relaxed); + if (old_index >= 0 && old_index < static_cast(shm::kMaxBuffers) && + bcb->refs[old_index].load(std::memory_order_relaxed) > 0) { + bcb->refs[old_index]--; + } + const int index = memory_.BufferIndex(); + slot->buffer_index.store(static_cast(index), + std::memory_order_relaxed); + bcb->refs[index]++; +} + +void Publisher::PublishSlot(shm::MessageSlot *slot, bool is_activation, + PublishedMessage *published) { + shm::MessagePrefix *prefix = memory_.Prefix(slot); + StampSlot(memory_.Ccb(), slot, internal::Now()); + FillPrefix(memory_.Ccb(), slot, prefix, memory_.ChecksumSize(), + memory_.MetadataSize(), is_activation); + if (checksum_) { + prefix->SetHasChecksum(); + SetMessageChecksum(prefix, memory_.Payload(slot), + slot->message_size.load(std::memory_order_relaxed), + memory_.ChecksumSize(), memory_.MetadataSize()); + } + + PublishedSlot result; + { + SubscriberQueuePublishScope publishing(memory_.QueueIndex(), + publisher_id_); + result = CommitPublishedSlot( + memory_, slot, vchan_id_, is_activation, publishing, + [this](int32_t retirement_slot_id) { + memory_.TriggerRetirement(retirement_triggers_, retirement_slot_id); + }); + } + if (result.retired) { + memory_.TriggerRetirement(retirement_triggers_, result.retirement_slot_id); + } + if (published != nullptr) { + published->ordinal = result.ordinal; + published->timestamp = result.timestamp; + } +} + +} // namespace asil +} // namespace subspace diff --git a/asil_client/publisher.h b/asil_client/publisher.h new file mode 100644 index 00000000..daa8bc36 --- /dev/null +++ b/asil_client/publisher.h @@ -0,0 +1,148 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +#pragma once + +#include "asil_client/channel_memory.h" +#include "asil_client/error.h" +#include "asil_client/server_connection.h" +#include "asil_client/unique_fd.h" + +#include +#include + +namespace subspace { +namespace asil { + +class Client; + +struct PublisherOptions { + // The channel is in the server's static channel config, which defines its + // layout. Publishers on static channels must set this and leave + // slot_size, num_slots, checksum_size, metadata_size, + // subscriber_queue_arena_size and use_split_buffers zero; the publisher + // takes them from the server. split_slots and split_allocator still apply + // to a static channel with split buffers. + bool server_defined = false; + // The channel layout, for a channel that isn't static. + int64_t slot_size = 0; + int32_t num_slots = 0; + int32_t checksum_size = 0; // 0 means 4 bytes. + int32_t metadata_size = 0; + const char *type = nullptr; + // Put a checksum in every message. + bool checksum = false; + // Publish an activation message if the channel hasn't been activated. A + // reliable publisher always publishes one. + bool activate = false; + // Never overwrite a message that a reliable subscriber hasn't read. Buffer() + // returns null until there is room; wait for PollFd() and try again. + bool reliable = false; + // Publish on a virtual channel of this multiplexer. vchan_id -1 lets the + // server choose the channel's id. + const char *mux = nullptr; + int32_t vchan_id = -1; + // Bytes in the channel's control block for subscriber queues. This must + // match the channel; 0 for a channel without queues. + uint64_t subscriber_queue_arena_size = 0; + // The channel has split buffers, which a standard publisher must have + // created. On a static channel the server says whether there are split + // buffers, and creates them. split_slots has room for the channel's + // num_slots slot mappings, and the allocator maps slots that a custom + // allocator created. + bool use_split_buffers = false; + SplitSlot *split_slots = nullptr; + int32_t split_slot_capacity = 0; + SplitBufferAllocator split_allocator; +}; + +struct PublishedMessage { + uint64_t ordinal = 0; + uint64_t timestamp = 0; +}; + +// A publisher for a fixed-size channel. An unreliable publisher always holds +// a slot to write the next message into, recycling the oldest message that no +// subscriber holds. A reliable publisher takes a slot only when one is free +// of messages that reliable subscribers haven't read. +// +// A publisher is not thread safe and must not outlive its Client. +class Publisher { +public: + Publisher() = default; + ~Publisher() { (void)Close(); } + Publisher(const Publisher &) = delete; + Publisher &operator=(const Publisher &) = delete; + + Error Open(Client &client, const char *channel_name, + const PublisherOptions &options); + // Removes the publisher from the server. Safe to call more than once. + Error Close(); + bool IsOpen() const { return client_ != nullptr; } + + // Where to write the next message, or null if no slot is available. A + // reliable publisher also returns null while the channel has no + // subscribers. + void *Buffer(); + int64_t SlotSize() const { return memory_.SlotSize(); } + int NumSlots() const { return memory_.NumSlots(); } + + // The user metadata area for the next message, or null if the channel has + // none or no slot is available. + void *Metadata(); + size_t MetadataSize() const { + return static_cast(memory_.MetadataSize()); + } + + // Publishes the message_size bytes written to Buffer(). If a subscriber + // has joined since the last publish this asks the server for its trigger + // fd first. + Error Publish(size_t message_size, PublishedMessage *published = nullptr); + + // Readable when a reliable subscriber may have made room for a message. + int PollFd() const { return poll_.Get(); } + // Waits until PollFd() is readable. A negative timeout waits forever. + Error Wait(int timeout_ms); + + bool IsReliable() const { return reliable_; } + // The publisher's virtual channel id, or -1. + int VirtualChannelId() const { return vchan_id_; } + const char *Name() const { return name_; } + +private: + bool HoldSlot(); + Error RefreshTriggers(); + class SearchHooks; + + // Claims and resets a slot using common/slot_search.h, which the standard + // client shares. + shm::MessageSlot *FindFreeSlot(); + void SetSlotBuffer(shm::MessageSlot *slot); + void PublishSlot(shm::MessageSlot *slot, bool is_activation, + PublishedMessage *published); + void TriggerSubscribers() const; + void Reset(); + + Client *client_ = nullptr; + internal::ChannelMemory memory_; + internal::BufferContext buffer_context_; + char name_[kMaxChannelNameLength + 1] = {}; + // The channel that owns the shared memory: the multiplexer of a virtual + // channel. + char resolved_name_[kMaxChannelNameLength + 1] = {}; + int32_t channel_id_ = -1; + int32_t publisher_id_ = -1; + int32_t vchan_id_ = -1; + uint16_t num_sub_updates_ = 0; + bool checksum_ = false; + bool reliable_ = false; + shm::MessageSlot *slot_ = nullptr; + UniqueFd poll_; + TriggerFdList subscriber_triggers_; + TriggerFdList retirement_triggers_; +}; + +} // namespace asil +} // namespace subspace diff --git a/asil_client/server_connection.h b/asil_client/server_connection.h new file mode 100644 index 00000000..3fe8a4c7 --- /dev/null +++ b/asil_client/server_connection.h @@ -0,0 +1,175 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +// The handshake between the ASIL client and the Subspace server. +// +// The client talks to the server only to connect, to create and remove +// publishers and subscribers, to fetch trigger file descriptors when the +// set of publishers or subscribers on a channel changes, and, while opening a +// publisher or subscriber, to exchange buffer descriptors. Messages move +// through shared memory without the server. ServerConnection hides the wire +// format of these requests so that it can be replaced; PhaserServerConnection +// implements the standard protocol. + +#pragma once + +#include "asil_client/error.h" +#include "asil_client/shm_layout.h" +#include "asil_client/split_buffer.h" +#include "asil_client/unique_fd.h" + +#include + +namespace subspace { +namespace asil { + +constexpr int kMaxTriggerFds = shm::kMaxSlotOwners; +using TriggerFdList = FdList; + +struct InitReply { + UniqueFd scb; + uint64_t session_id = 0; + int32_t user_id = -1; + int32_t group_id = -1; +}; + +struct PublisherRequest { + const char *channel_name = nullptr; + int64_t slot_size = 0; + int32_t num_slots = 0; + const char *type = nullptr; + int32_t checksum_size = 0; + int32_t metadata_size = 0; + bool reliable = false; + // The multiplexer of a virtual channel, or null. + const char *mux = nullptr; + int32_t vchan_id = -1; + uint64_t subscriber_queue_arena_size = 0; + bool use_split_buffers = false; + // The server defines the layout of this static channel, and the layout + // fields above are zero. + bool server_defined = false; +}; + +struct PublisherReply { + int32_t channel_id = -1; + int32_t publisher_id = -1; + int32_t num_slots = 0; + int32_t vchan_id = -1; + int32_t num_sub_updates = 0; + uint64_t subscriber_queue_arena_size = 0; + // The rest of the channel's layout. + int64_t slot_size = 0; + int32_t checksum_size = 0; + int32_t metadata_size = 0; + bool use_split_buffers = false; + UniqueFd ccb; + UniqueFd bcb; + // Readable when a reliable subscriber has released a message. + UniqueFd poll; + // Filled when not null. + TriggerFdList *subscriber_triggers = nullptr; + TriggerFdList *retirement_triggers = nullptr; +}; + +struct SubscriberRequest { + const char *channel_name = nullptr; + const char *type = nullptr; + int32_t max_active_messages = 1; + bool reliable = false; + // The multiplexer of a virtual channel, or null. + const char *mux = nullptr; + int32_t vchan_id = -1; +}; + +struct SubscriberReply { + int32_t channel_id = -1; + int32_t subscriber_id = -1; + int32_t num_slots = 0; + int32_t vchan_id = -1; + int32_t num_pub_updates = 0; + int32_t checksum_size = 0; + int32_t metadata_size = 0; + int32_t subscriber_queue_size = 0; + uint64_t subscriber_queue_arena_size = 0; + bool use_split_buffers = false; + UniqueFd ccb; + UniqueFd bcb; + UniqueFd trigger; + UniqueFd poll; + // Filled when not null. + TriggerFdList *reliable_publisher_triggers = nullptr; + TriggerFdList *retirement_triggers = nullptr; +}; + +struct TriggersReply { + // Filled when not null. + TriggerFdList *reliable_publisher_triggers = nullptr; + TriggerFdList *subscriber_triggers = nullptr; + TriggerFdList *retirement_triggers = nullptr; +}; + +// A memfd message buffer. The server keeps the descriptor so that other +// clients can map the buffer. +struct ClientBuffer { + // The channel that owns the buffer: the multiplexer of a virtual channel. + const char *channel_name = nullptr; + uint64_t session_id = 0; + uint32_t buffer_index = 0; + uint64_t full_size = 0; +}; + +// A buffer registered with the server: buffer_index's single buffer, or the +// prefix or one slot of a split buffer set. +struct BufferRequest { + // The channel that owns the buffer: the multiplexer of a virtual channel. + const char *channel_name = nullptr; + uint64_t session_id = 0; + uint32_t buffer_index = 0; + bool is_prefix = false; + uint32_t slot_id = 0; +}; + +struct BufferReply { + // Whether the server has the buffer. + bool found = false; + // Invalid when the creator registered no descriptor. + UniqueFd fd; + uint64_t full_size = 0; + uint64_t allocation_size = 0; + uint64_t handle = 0; + int64_t map_offset = 0; + BufferAllocator allocator = BufferAllocator::kUnspecified; +}; + +class ServerConnection { +public: + virtual ~ServerConnection() = default; + + virtual Error Init(const char *client_name, InitReply &reply) = 0; + virtual Error CreatePublisher(const PublisherRequest &request, + PublisherReply &reply) = 0; + virtual Error CreateSubscriber(const SubscriberRequest &request, + SubscriberReply &reply) = 0; + virtual Error GetTriggers(const char *channel_name, TriggersReply &reply) = 0; + virtual Error RemovePublisher(const char *channel_name, + int32_t publisher_id) = 0; + virtual Error RemoveSubscriber(const char *channel_name, + int32_t subscriber_id) = 0; + + // Gives the server the descriptor of a memfd buffer that this client + // created. The client must own a publisher on the channel. + virtual Error RegisterBuffer(const ClientBuffer &buffer, int fd) = 0; + // Fetches a buffer that its creator registered. Returns kOk with + // reply.found false when it hasn't been registered yet. + virtual Error GetBuffer(const BufferRequest &request, BufferReply &reply) = 0; + + // Detail for the last handshake failure that had one: the server's reason + // for kServerRejected, or which buffer was too small for kCapacityExceeded. + virtual const char *LastServerError() const = 0; +}; + +} // namespace asil +} // namespace subspace diff --git a/asil_client/shm_layout.h b/asil_client/shm_layout.h new file mode 100644 index 00000000..2f8e8a8c --- /dev/null +++ b/asil_client/shm_layout.h @@ -0,0 +1,77 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +// Names for the shared-memory protocol. The types live in common/shm_layout.h +// and are the same types the regular client uses. The layout is valid on +// 32-bit targets: size_t fields are padded so 64-bit atomics stay aligned. + +#pragma once + +#include "common/shm_layout.h" + +namespace subspace { +namespace asil { +namespace shm { + +using ::subspace::ActivationTracker; +using ::subspace::AvailableSlotQueueIndex; +using ::subspace::AvailableSlotsOffset; +using ::subspace::BitsToWords; +using ::subspace::BufferControlBlock; +using ::subspace::BuildRefsBitField; +using ::subspace::CcbSize; +using ::subspace::ChannelControlBlock; +using ::subspace::ChannelCounters; +using ::subspace::FreeSlotsOffset; +using ::subspace::InPlaceSlotQueue; +using ::subspace::MessagePrefix; +using ::subspace::MessageSlot; +using ::subspace::OrdinalAccumulator; +using ::subspace::PrefixSize; +using ::subspace::RefsVchanId; +using ::subspace::RetiredSlotsOffset; +using ::subspace::SizeofAtomicBitSet; +using ::subspace::SlotQueueArenaOffset; +using ::subspace::SlotQueueEntry; +using ::subspace::SlotQueueIndexOffset; +using ::subspace::SubscriberCleanupGeneration; +using ::subspace::SubscriberCounter; +using ::subspace::SystemControlBlock; +using SlotQueue = ::subspace::InPlaceSlotQueue; + +using ::subspace::kChannelControlBlockVersion; +using ::subspace::kInvalidSlotQueueOffset; +using ::subspace::kMaxBuffers; +using ::subspace::kMaxChannelName; +using ::subspace::kMaxChannels; +using ::subspace::kMaxSlotOwners; +using ::subspace::kMaxSlotQueueCasAttempts; +using ::subspace::kMaxVchanId; +using ::subspace::kMessageActivate; +using ::subspace::kMessageHasChecksum; +using ::subspace::kMessageIsActivation; +using ::subspace::kMessageSeen; +using ::subspace::kMessageSeenByReliable; +using ::subspace::kOrdinalMask; +using ::subspace::kOrdinalShift; +using ::subspace::kPubOwned; +using ::subspace::kRefCountMask; +using ::subspace::kRefsMask; +using ::subspace::kReliableRefCountShift; +using ::subspace::kPendingMask; +using ::subspace::kPendingShift; +using ::subspace::PendingCount; +using ::subspace::kVchanIdMask; +using ::subspace::kVchanIdShift; + +inline size_t SizeofBitset(size_t bits) { + return ::subspace::SizeofAtomicBitSet(bits); +} + +constexpr int64_t Aligned64(int64_t v) { return ::subspace::Aligned<64>(v); } + +} // namespace shm +} // namespace asil +} // namespace subspace diff --git a/asil_client/split_buffer.h b/asil_client/split_buffer.h new file mode 100644 index 00000000..1d320c08 --- /dev/null +++ b/asil_client/split_buffer.h @@ -0,0 +1,78 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +// Split buffer channels keep the message prefixes in one shared memory object +// and each slot's payload in its own. The ASIL client maps all of them when a +// publisher or subscriber opens, into slot storage that the caller provides. + +#pragma once + +#include "asil_client/error.h" + +#include + +namespace subspace { +namespace asil { + +// How the creator of a split buffer allocated it. The values match the +// ClientBufferAllocator enum in proto/subspace.proto. +enum class BufferAllocator : int32_t { + kUnspecified = 0, + kMemfd = 1, + kSplitShm = 2, + // A custom allocator: mapping the slot needs a SplitBufferAllocator. + kSplitCallback = 3, + kSplitBufferFreeTest = 4, +}; + +// What the server knows about one split buffer slot. +struct SplitBufferInfo { + // The channel that owns the buffers: the multiplexer of a virtual channel. + const char *channel_name = nullptr; + uint64_t session_id = 0; + uint32_t buffer_index = 0; + uint32_t slot_id = 0; + uint64_t full_size = 0; + uint64_t allocation_size = 0; + // Defined by the allocator that created the slot. + uint64_t handle = 0; + int64_t map_offset = 0; + BufferAllocator allocator = BufferAllocator::kUnspecified; + // The descriptor the creator registered with the server, or -1. It is + // valid only during the map callback. + int fd = -1; +}; + +struct SplitBufferMapping { + void *address = nullptr; + // 0 from a map callback means the slot's payload size. + uint64_t size = 0; + // For the allocator's use. + void *private_data = nullptr; +}; + +// Maps slots that a custom allocator created. Both functions are called +// only from Open() and Close(), with the context given here. +struct SplitBufferAllocator { + Error (*map)(void *context, const SplitBufferInfo &info, + SplitBufferMapping &mapping) = nullptr; + void (*unmap)(void *context, const SplitBufferInfo &info, + const SplitBufferMapping &mapping) = nullptr; + void *context = nullptr; +}; + +// The mapping of one slot's payload. The caller provides an array of at +// least the channel's num_slots of these, which must outlive the publisher or +// subscriber. +struct SplitSlot { + SplitBufferInfo info; + SplitBufferMapping mapping; + // The allocator mapped the slot; otherwise the client mapped its + // descriptor. + bool allocator_mapped = false; +}; + +} // namespace asil +} // namespace subspace diff --git a/asil_client/stress_test.cc b/asil_client/stress_test.cc new file mode 100644 index 00000000..cf91b333 --- /dev/null +++ b/asil_client/stress_test.cc @@ -0,0 +1,835 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +// Stress tests for the ASIL client, in the shape of client/stress_test.cc. +// +// An ASIL client, publisher, or subscriber is used by one thread at a time, so +// each thread owns the objects it publishes or reads with. There is no +// coroutine test and no shared-client thread-safety test: the ASIL client has +// neither interface. Channels are created on demand. A publisher opens before +// its subscriber so the subscriber has buffers to map. Slot counts stay ahead +// of the messages still in the channel, so an unreliable publisher does not +// overwrite a message the subscriber has not read yet. + +#include "client/test_fixture.h" + +#include "absl/strings/str_format.h" +#include "asil_client/client.h" +#include "asil_client/phaser_connection.h" +#include "asil_client/publisher.h" +#include "asil_client/shm_layout.h" +#include "asil_client/subscriber.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +namespace asil = ::subspace::asil; + +int Scaled(int normal, int low) { + static const bool low_resource = [] { + struct rlimit limit; + if (getrlimit(RLIMIT_NOFILE, &limit) == 0 && + limit.rlim_cur != RLIM_INFINITY && limit.rlim_cur < 4096) { + return true; + } +#ifdef __linux__ + std::ifstream file("/proc/sys/vm/max_map_count"); + uint64_t value = 0; + if ((file >> value) && value < 262144) { + return true; + } +#endif + return false; + }(); + return low_resource ? low : normal; +} + +struct AsilLink { + // Destroyed last: publishers and subscribers are declared after these in + // the groups below, so they close while the connection is still open. + std::unique_ptr connection; + std::unique_ptr client; +}; + +bool ConnectAsil(const std::string &socket, const std::string &name, + AsilLink &link) { + link.connection = std::make_unique(); + if (link.connection->Connect(socket.c_str()) != asil::Error::kOk) { + ADD_FAILURE() << "connect " << name; + return false; + } + link.client = std::make_unique(); + if (asil::Error error = link.client->Init(*link.connection, name.c_str()); + error != asil::Error::kOk) { + ADD_FAILURE() << "init " << name << ": " << asil::ErrorString(error) + << " " << link.client->LastServerError(); + return false; + } + return true; +} + +void Fail(std::atomic &failures, const std::string &why) { + if (failures.fetch_add(1, std::memory_order_relaxed) == 0) { + ADD_FAILURE() << why; + } +} + +// Publishes sequence numbers 0 .. count-1. A reliable publisher's Buffer() +// is null while a reliable subscriber still holds every slot; wait for one. +bool PublishSequences(asil::Publisher &publisher, int count, + std::atomic &failures) { + for (uint32_t sequence = 0; sequence < static_cast(count); + ++sequence) { + if (failures.load(std::memory_order_relaxed) != 0) { + return false; + } + void *buffer = publisher.Buffer(); + while (buffer == nullptr) { + if (publisher.Wait(10000) != asil::Error::kOk) { + Fail(failures, absl::StrFormat("publisher %s waited 10s for a slot", + publisher.Name())); + return false; + } + buffer = publisher.Buffer(); + } + std::memcpy(buffer, &sequence, sizeof(sequence)); + if (asil::Error error = publisher.Publish(sizeof(sequence)); + error != asil::Error::kOk) { + Fail(failures, absl::StrFormat("publish %s sequence %u: %s", + publisher.Name(), sequence, + asil::ErrorString(error))); + return false; + } + } + return true; +} + +// Reads count messages whose payloads are 0 .. count-1, in order. Activation +// messages are skipped by ReadMessage. +bool ReadSequences(asil::Subscriber &subscriber, int count, + std::atomic &failures) { + uint32_t expect = 0; + while (expect < static_cast(count)) { + if (failures.load(std::memory_order_relaxed) != 0) { + return false; + } + asil::Message message; + if (asil::Error error = subscriber.ReadMessage(message); + error != asil::Error::kOk) { + Fail(failures, absl::StrFormat("read %s: %s", subscriber.Name(), + asil::ErrorString(error))); + return false; + } + if (message.length == 0) { + if (subscriber.Wait(10000) != asil::Error::kOk) { + Fail(failures, absl::StrFormat( + "subscriber %s waited 10s, saw %u of %d", + subscriber.Name(), expect, count)); + return false; + } + continue; + } + uint32_t sequence = 0; + if (message.length != sizeof(sequence)) { + Fail(failures, absl::StrFormat("subscriber %s length %zu", + subscriber.Name(), message.length)); + return false; + } + std::memcpy(&sequence, message.data, sizeof(sequence)); + if (sequence != expect || message.dropped != 0) { + Fail(failures, absl::StrFormat( + "subscriber %s sequence %u, expected %u, dropped %u", + subscriber.Name(), sequence, expect, message.dropped)); + return false; + } + ++expect; + } + return true; +} + +asil::PublisherOptions PubOptions(int64_t slot_size, int32_t num_slots) { + asil::PublisherOptions options; + options.slot_size = slot_size; + options.num_slots = num_slots; + return options; +} + +class AsilStressTest : public SubspaceTestBase {}; + +// Many clients, each with many channels. One thread publishes a client's +// channels and another reads them, through a second ASIL client. +TEST_F(AsilStressTest, Threads) { + const int kNumClients = Scaled(8, 2); + const int kNumChannels = Scaled(32, 4); + const int kNumMessages = Scaled(100, 20); + const int kNumSlots = kNumMessages + 2; + + struct Group { + AsilLink link; + std::vector names; + std::vector> publishers; + std::vector> subscribers; + }; + std::vector publishers(kNumClients); + std::vector subscribers(kNumClients); + + for (int client = 0; client < kNumClients; ++client) { + ASSERT_TRUE(ConnectAsil(Socket(), absl::StrFormat("asil-pub-%d", client), + publishers[client].link)); + ASSERT_TRUE(ConnectAsil(Socket(), absl::StrFormat("asil-sub-%d", client), + subscribers[client].link)); + for (int channel = 0; channel < kNumChannels; ++channel) { + publishers[client].names.push_back( + absl::StrFormat("/asil_stress/threads/%d/%d", client, channel)); + auto &name = publishers[client].names.back(); + auto publisher = std::make_unique(); + ASSERT_EQ(asil::Error::kOk, + publishers[client].link.client->CreatePublisher( + name.c_str(), PubOptions(64, kNumSlots), *publisher)) + << publishers[client].link.client->LastServerError(); + publishers[client].publishers.push_back(std::move(publisher)); + + auto subscriber = std::make_unique(); + ASSERT_EQ(asil::Error::kOk, + subscribers[client].link.client->CreateSubscriber( + name.c_str(), {}, *subscriber)) + << subscribers[client].link.client->LastServerError(); + subscribers[client].subscribers.push_back(std::move(subscriber)); + } + } + + std::atomic failures{0}; + std::vector threads; + threads.reserve(kNumClients * 2); + for (int client = 0; client < kNumClients; ++client) { + threads.emplace_back([&, client] { + for (int channel = 0; channel < kNumChannels; ++channel) { + if (!PublishSequences(*publishers[client].publishers[channel], + kNumMessages, failures)) { + return; + } + } + }); + threads.emplace_back([&, client] { + for (int channel = 0; channel < kNumChannels; ++channel) { + if (!ReadSequences(*subscribers[client].subscribers[channel], + kNumMessages, failures)) { + return; + } + } + }); + } + for (std::thread &thread : threads) { + thread.join(); + } + EXPECT_EQ(0, failures.load()); +} + +// A reliable publisher blocks while the subscriber holds its messages. The +// subscriber keeps kMaxActive of them, checks that the held payloads stay +// intact, then releases them so the publisher can continue. +TEST_F(AsilStressTest, ActiveMessages) { + constexpr int kMaxActive = 32; + const int kNumMessages = Scaled(400, 64); + const int kNumSlots = kMaxActive + 4; + constexpr char kChannel[] = "/asil_stress/active"; + + AsilLink publisher_link; + AsilLink subscriber_link; + ASSERT_TRUE(ConnectAsil(Socket(), "asil-active-pub", publisher_link)); + ASSERT_TRUE(ConnectAsil(Socket(), "asil-active-sub", subscriber_link)); + + asil::PublisherOptions options = PubOptions(64, kNumSlots); + options.reliable = true; + asil::Publisher publisher; + ASSERT_EQ(asil::Error::kOk, publisher_link.client->CreatePublisher( + kChannel, options, publisher)); + asil::SubscriberOptions subscriber_options; + subscriber_options.reliable = true; + subscriber_options.max_active_messages = kMaxActive; + asil::Subscriber subscriber; + ASSERT_EQ(asil::Error::kOk, subscriber_link.client->CreateSubscriber( + kChannel, subscriber_options, subscriber)); + + std::atomic failures{0}; + std::thread publisher_thread([&] { + PublishSequences(publisher, kNumMessages, failures); + }); + + // Each held message with the sequence it carried when it was read. + struct Held { + asil::Message message; + uint32_t sequence; + }; + std::vector held; + held.reserve(kMaxActive); + uint32_t expect = 0; + while (expect < static_cast(kNumMessages) && + failures.load(std::memory_order_relaxed) == 0) { + if (subscriber.NumActiveMessages() == kMaxActive) { + // The payloads must still hold what they held when they were read: the + // publisher may not overwrite a message the subscriber holds. + for (const Held &h : held) { + uint32_t sequence = 0; + if (h.message.length != sizeof(sequence)) { + Fail(failures, "held message has the wrong length"); + break; + } + std::memcpy(&sequence, h.message.data, sizeof(sequence)); + if (sequence != h.sequence) { + Fail(failures, absl::StrFormat("held sequence %u changed to %u", + h.sequence, sequence)); + break; + } + } + subscriber.ReleaseMessage(); + held.clear(); + } + asil::Message message; + if (asil::Error error = subscriber.ReadMessage(message); + error != asil::Error::kOk) { + Fail(failures, absl::StrFormat("active read: %s", asil::ErrorString(error))); + break; + } + if (message.length == 0) { + if (subscriber.Wait(10000) != asil::Error::kOk) { + Fail(failures, absl::StrFormat("active subscriber waited 10s at %u", + expect)); + break; + } + continue; + } + uint32_t sequence = 0; + std::memcpy(&sequence, message.data, sizeof(sequence)); + if (sequence != expect || message.dropped != 0) { + Fail(failures, absl::StrFormat("active sequence %u, expected %u", + sequence, expect)); + break; + } + held.push_back(Held{message, sequence}); + ++expect; + } + subscriber.ReleaseMessage(); + publisher_thread.join(); + EXPECT_EQ(0, failures.load()); + EXPECT_EQ(static_cast(kNumMessages), expect); +} + +// Publishers on many virtual channels, one subscriber on the multiplexer. +TEST_F(AsilStressTest, VirtualChannels) { + const int kNumThreads = Scaled(4, 2); + const int kVchansPerThread = Scaled(16, 4); + const int kNumMessages = Scaled(20, 8); + const int kNumVchans = kNumThreads * kVchansPerThread; + // Every publisher holds one slot besides the messages it has published, and + // the subscriber may not have read any of them yet. + const int kNumSlots = kNumVchans * kNumMessages + kNumVchans; + const std::string mux = "/asil_stress/virtual"; + + struct Group { + AsilLink link; + std::vector> publishers; + }; + std::vector groups(kNumThreads); + asil::PublisherOptions options = PubOptions(128, kNumSlots); + options.mux = mux.c_str(); + for (int thread = 0; thread < kNumThreads; ++thread) { + ASSERT_TRUE(ConnectAsil(Socket(), absl::StrFormat("asil-vpub-%d", thread), + groups[thread].link)); + for (int vchan = 0; vchan < kVchansPerThread; ++vchan) { + const std::string name = + absl::StrFormat("/asil_stress/virtual/%d/%d", thread, vchan); + auto publisher = std::make_unique(); + ASSERT_EQ(asil::Error::kOk, + groups[thread].link.client->CreatePublisher( + name.c_str(), options, *publisher)) + << groups[thread].link.client->LastServerError(); + groups[thread].publishers.push_back(std::move(publisher)); + } + } + + AsilLink subscriber_link; + ASSERT_TRUE(ConnectAsil(Socket(), "asil-vmux", subscriber_link)); + asil::Subscriber subscriber; + ASSERT_EQ(asil::Error::kOk, subscriber_link.client->CreateSubscriber( + mux.c_str(), {}, subscriber)); + + std::atomic failures{0}; + std::vector threads; + for (int thread = 0; thread < kNumThreads; ++thread) { + threads.emplace_back([&, thread] { + for (const std::unique_ptr &publisher : + groups[thread].publishers) { + if (!PublishSequences(*publisher, kNumMessages, failures)) { + return; + } + } + }); + } + + std::vector next(asil::shm::kMaxVchanId + 1, 0); + const int expected = kNumVchans * kNumMessages; + int got = 0; + while (got < expected && failures.load(std::memory_order_relaxed) == 0) { + asil::Message message; + if (subscriber.ReadMessage(message) != asil::Error::kOk) { + Fail(failures, "virtual read failed"); + break; + } + if (message.length == 0) { + if (subscriber.Wait(10000) != asil::Error::kOk) { + Fail(failures, absl::StrFormat("mux subscriber waited 10s, saw %d of %d", + got, expected)); + break; + } + continue; + } + uint32_t sequence = 0; + if (message.length != sizeof(sequence) || message.vchan_id < 0 || + message.vchan_id >= asil::shm::kMaxVchanId) { + Fail(failures, "virtual message has a bad length or vchan"); + break; + } + std::memcpy(&sequence, message.data, sizeof(sequence)); + if (sequence != static_cast(next[message.vchan_id]) || + message.dropped != 0) { + Fail(failures, absl::StrFormat("vchan %d sequence %u, expected %d", + message.vchan_id, sequence, + next[message.vchan_id])); + break; + } + ++next[message.vchan_id]; + ++got; + } + for (std::thread &thread : threads) { + thread.join(); + } + EXPECT_EQ(0, failures.load()); + EXPECT_EQ(expected, got); +} + +// Large slots, one publisher thread for a handful of channels and one +// subscriber thread polling all of them. +TEST_F(AsilStressTest, ManyChannels) { + const int kNumThreads = Scaled(8, 2); + const int kChannelsPerThread = Scaled(4, 2); + const int kNumChannels = kNumThreads * kChannelsPerThread; + const int kNumMessages = Scaled(30, 8); + const int kNumSlots = kNumMessages + 2; + constexpr int kSlotSize = 32768; + + struct Group { + AsilLink link; + std::vector names; + std::vector> publishers; + }; + std::vector groups(kNumThreads); + std::vector names; + names.reserve(kNumChannels); + for (int thread = 0; thread < kNumThreads; ++thread) { + ASSERT_TRUE(ConnectAsil(Socket(), absl::StrFormat("asil-mpub-%d", thread), + groups[thread].link)); + for (int channel = 0; channel < kChannelsPerThread; ++channel) { + names.push_back( + absl::StrFormat("/asil_stress/many/%d/%d", thread, channel)); + groups[thread].names.push_back(names.back()); + auto publisher = std::make_unique(); + ASSERT_EQ(asil::Error::kOk, + groups[thread].link.client->CreatePublisher( + names.back().c_str(), PubOptions(kSlotSize, kNumSlots), + *publisher)); + groups[thread].publishers.push_back(std::move(publisher)); + } + } + + AsilLink subscriber_link; + ASSERT_TRUE(ConnectAsil(Socket(), "asil-many-sub", subscriber_link)); + std::vector> subscribers; + subscribers.reserve(kNumChannels); + for (const std::string &name : names) { + auto subscriber = std::make_unique(); + ASSERT_EQ(asil::Error::kOk, subscriber_link.client->CreateSubscriber( + name.c_str(), {}, *subscriber)); + subscribers.push_back(std::move(subscriber)); + } + + std::atomic failures{0}; + std::vector publishers_threads; + for (int thread = 0; thread < kNumThreads; ++thread) { + publishers_threads.emplace_back([&, thread] { + for (int channel = 0; channel < kChannelsPerThread; ++channel) { + for (uint32_t sequence = 0; sequence < static_cast(kNumMessages); + ++sequence) { + if (failures.load(std::memory_order_relaxed) != 0) { + return; + } + asil::Publisher &publisher = *groups[thread].publishers[channel]; + void *buffer = publisher.Buffer(); + if (buffer == nullptr) { + Fail(failures, "many-channel publisher has no slot"); + return; + } + std::memset(buffer, 0xda, kSlotSize); + std::memcpy(buffer, &sequence, sizeof(sequence)); + if (publisher.Publish(kSlotSize) != asil::Error::kOk) { + Fail(failures, "many-channel publish failed"); + return; + } + std::this_thread::sleep_for(std::chrono::microseconds(200)); + } + } + }); + } + + std::vector expect(kNumChannels, 0); + int got = 0; + const int expected = kNumChannels * kNumMessages; + std::vector fds; + fds.reserve(subscribers.size()); + for (const std::unique_ptr &subscriber : subscribers) { + fds.push_back(pollfd{subscriber->PollFd(), POLLIN, 0}); + } + auto last_progress = std::chrono::steady_clock::now(); + while (got < expected && failures.load(std::memory_order_relaxed) == 0) { + bool progress = false; + for (int channel = 0; channel < kNumChannels; ++channel) { + for (;;) { + asil::Message message; + if (subscribers[channel]->ReadMessage(message) != asil::Error::kOk) { + Fail(failures, "many-channel read failed"); + break; + } + if (message.length == 0) { + break; + } + uint32_t sequence = 0; + std::memcpy(&sequence, message.data, sizeof(sequence)); + if (message.length != kSlotSize || sequence != expect[channel] || + message.dropped != 0) { + Fail(failures, absl::StrFormat("channel %d sequence %u, expected %u", + channel, sequence, expect[channel])); + break; + } + ++expect[channel]; + ++got; + progress = true; + } + } + if (got >= expected || failures.load(std::memory_order_relaxed) != 0) { + break; + } + // Time out on lack of progress, not only on a quiet poll: a readable fd + // that delivers nothing would otherwise spin forever. + const auto now = std::chrono::steady_clock::now(); + if (progress) { + last_progress = now; + } else if (now - last_progress > std::chrono::seconds(10)) { + Fail(failures, absl::StrFormat( + "many-channel subscriber made no progress for 10s, " + "saw %d of %d", + got, expected)); + break; + } + (void)poll(fds.data(), fds.size(), 100); + } + for (std::thread &thread : publishers_threads) { + thread.join(); + } + EXPECT_EQ(0, failures.load()); + EXPECT_EQ(expected, got); +} + +// ASIL and standard clients publish and read the same channels at once, in +// both directions. A separate channel checks that ASIL publishers fill the +// queues of standard subscribers. +TEST_F(AsilStressTest, MixedWithStandardClient) { + const int kNumChannels = Scaled(16, 4); + const int kNumMessages = Scaled(80, 20); + const int kNumSlots = kNumMessages + 2; + const int kNumQueuePublishers = Scaled(4, 2); + const int kNumQueueSubscribers = Scaled(8, 2); + const int kQueueMessages = Scaled(1000, 100); + constexpr int kQueueSlots = 128; + + struct Direction { + std::string name; + AsilLink asil; + std::shared_ptr standard; + std::unique_ptr asil_publisher; + std::unique_ptr asil_subscriber; + std::optional standard_publisher; + std::optional standard_subscriber; + }; + + std::vector asil_to_std(kNumChannels); + std::vector std_to_asil(kNumChannels); + for (int channel = 0; channel < kNumChannels; ++channel) { + Direction &to_std = asil_to_std[channel]; + to_std.name = absl::StrFormat("/asil_stress/mix/to_std/%d", channel); + ASSERT_TRUE(ConnectAsil(Socket(), absl::StrFormat("mix-pub-%d", channel), + to_std.asil)); + to_std.asil_publisher = std::make_unique(); + ASSERT_EQ(asil::Error::kOk, to_std.asil.client->CreatePublisher( + to_std.name.c_str(), + PubOptions(64, kNumSlots), + *to_std.asil_publisher)); + absl::StatusOr> standard_subscriber_client = + subspace::Client::Create(Socket(), + absl::StrFormat("mix-std-sub-%d", channel)); + ASSERT_OK(standard_subscriber_client); + to_std.standard = *std::move(standard_subscriber_client); + subspace::SubscriberOptions subscriber_options; + subscriber_options.SetLogDroppedMessages(false); + absl::StatusOr standard_subscriber = + to_std.standard->CreateSubscriber(to_std.name, subscriber_options); + ASSERT_OK(standard_subscriber); + to_std.standard_subscriber = *std::move(standard_subscriber); + + Direction &to_asil = std_to_asil[channel]; + to_asil.name = absl::StrFormat("/asil_stress/mix/to_asil/%d", channel); + absl::StatusOr> standard_publisher_client = + subspace::Client::Create(Socket(), + absl::StrFormat("mix-std-pub-%d", channel)); + ASSERT_OK(standard_publisher_client); + to_asil.standard = *std::move(standard_publisher_client); + absl::StatusOr standard_publisher = + to_asil.standard->CreatePublisher( + to_asil.name, subspace::PublisherOptions() + .SetSlotSize(64) + .SetNumSlots(kNumSlots) + .SetFixedSize(true)); + ASSERT_OK(standard_publisher); + to_asil.standard_publisher = *std::move(standard_publisher); + ASSERT_TRUE(ConnectAsil(Socket(), absl::StrFormat("mix-sub-%d", channel), + to_asil.asil)); + to_asil.asil_subscriber = std::make_unique(); + ASSERT_EQ(asil::Error::kOk, to_asil.asil.client->CreateSubscriber( + to_asil.name.c_str(), {}, + *to_asil.asil_subscriber)); + } + + constexpr char kQueue[] = "/asil_stress/mix/queue"; + struct Payload { + uint64_t magic; + uint32_t publisher; + uint32_t sequence; + uint64_t checksum; + }; + constexpr uint64_t kMagic = 0x4153494c51554555ULL; + std::vector queue_links(kNumQueuePublishers); + std::vector> queue_publishers( + kNumQueuePublishers); + for (int publisher = 0; publisher < kNumQueuePublishers; ++publisher) { + ASSERT_TRUE(ConnectAsil(Socket(), + absl::StrFormat("mix-qpub-%d", publisher), + queue_links[publisher])); + asil::PublisherOptions options = PubOptions(64, kQueueSlots); + options.subscriber_queue_arena_size = + subspace::kDefaultSubscriberQueueArenaSize; + queue_publishers[publisher] = std::make_unique(); + ASSERT_EQ(asil::Error::kOk, + queue_links[publisher].client->CreatePublisher( + kQueue, options, *queue_publishers[publisher])) + << queue_links[publisher].client->LastServerError(); + } + std::vector> queue_clients; + std::vector queue_subscribers; + for (int subscriber = 0; subscriber < kNumQueueSubscribers; ++subscriber) { + absl::StatusOr> queue_client = + subspace::Client::Create(Socket(), + absl::StrFormat("mix-qsub-%d", subscriber)); + ASSERT_OK(queue_client); + queue_clients.push_back(*std::move(queue_client)); + subspace::SubscriberOptions options; + options.SetSubscriberQueueSize(1 << (subscriber % 7)); + options.SetLogDroppedMessages(false); + absl::StatusOr queue_subscriber = + queue_clients.back()->CreateSubscriber(kQueue, options); + ASSERT_OK(queue_subscriber); + queue_subscribers.push_back(*std::move(queue_subscriber)); + } + + std::atomic failures{0}; + std::atomic queues_done{false}; + std::vector queue_received(kNumQueueSubscribers, 0); + std::vector threads; + + for (int channel = 0; channel < kNumChannels; ++channel) { + threads.emplace_back([&, channel] { + PublishSequences(*asil_to_std[channel].asil_publisher, kNumMessages, + failures); + }); + threads.emplace_back([&, channel] { + subspace::Subscriber &subscriber = + *asil_to_std[channel].standard_subscriber; + uint32_t expect = 0; + while (expect < static_cast(kNumMessages) && + failures.load(std::memory_order_relaxed) == 0) { + absl::StatusOr message = subscriber.ReadMessage(); + if (!message.ok()) { + Fail(failures, message.status().ToString()); + return; + } + if (message->length == 0) { + if (!subscriber.Wait().ok()) { + Fail(failures, "standard subscriber wait failed"); + return; + } + continue; + } + uint32_t sequence = 0; + std::memcpy(&sequence, message->buffer, sizeof(sequence)); + if (sequence != expect) { + Fail(failures, absl::StrFormat("standard subscriber sequence %u", + sequence)); + return; + } + ++expect; + } + }); + threads.emplace_back([&, channel] { + subspace::Publisher &publisher = *std_to_asil[channel].standard_publisher; + for (uint32_t sequence = 0; sequence < static_cast(kNumMessages); + ++sequence) { + if (failures.load(std::memory_order_relaxed) != 0) { + return; + } + absl::StatusOr buffer = publisher.GetMessageBuffer(); + if (!buffer.ok() || *buffer == nullptr) { + Fail(failures, "standard publisher has no buffer"); + return; + } + std::memcpy(*buffer, &sequence, sizeof(sequence)); + if (!publisher.PublishMessage(sizeof(sequence)).ok()) { + Fail(failures, "standard publish failed"); + return; + } + } + }); + threads.emplace_back([&, channel] { + ReadSequences(*std_to_asil[channel].asil_subscriber, kNumMessages, + failures); + }); + } + + for (int subscriber = 0; subscriber < kNumQueueSubscribers; ++subscriber) { + threads.emplace_back([&, subscriber] { + std::vector last(kNumQueuePublishers, -1); + auto take = [&](const subspace::Message &message) { + if (message.length != sizeof(Payload)) { + Fail(failures, "queue message has the wrong length"); + return; + } + Payload payload; + std::memcpy(&payload, message.buffer, sizeof(payload)); + const uint64_t checksum = + payload.magic ^ + (static_cast(payload.publisher) << 32) ^ payload.sequence; + if (payload.magic != kMagic || payload.checksum != checksum || + payload.publisher >= static_cast(kNumQueuePublishers)) { + Fail(failures, "queue message is corrupt"); + return; + } + if (static_cast(payload.sequence) <= + last[payload.publisher]) { + Fail(failures, "queue sequence went backwards"); + return; + } + last[payload.publisher] = payload.sequence; + ++queue_received[subscriber]; + }; + while (failures.load(std::memory_order_relaxed) == 0) { + absl::StatusOr message = + queue_subscribers[subscriber].ReadMessage(); + if (!message.ok()) { + Fail(failures, message.status().ToString()); + return; + } + if (message->length == 0) { + if (queues_done.load(std::memory_order_acquire)) { + break; + } + (void)queue_subscribers[subscriber].Wait(std::chrono::milliseconds(100)); + continue; + } + take(*message); + } + for (;;) { + absl::StatusOr message = + queue_subscribers[subscriber].ReadMessage(); + if (!message.ok() || message->length == 0) { + break; + } + take(*message); + } + }); + } + for (int publisher = 0; publisher < kNumQueuePublishers; ++publisher) { + threads.emplace_back([&, publisher] { + for (uint32_t sequence = 0; + sequence < static_cast(kQueueMessages); ++sequence) { + if (failures.load(std::memory_order_relaxed) != 0) { + return; + } + asil::Publisher &pub = *queue_publishers[publisher]; + void *buffer = pub.Buffer(); + if (buffer == nullptr) { + Fail(failures, "queue publisher has no slot"); + return; + } + Payload payload = { + kMagic, static_cast(publisher), sequence, + kMagic ^ (static_cast(publisher) << 32) ^ sequence}; + std::memcpy(buffer, &payload, sizeof(payload)); + if (pub.Publish(sizeof(payload)) != asil::Error::kOk) { + Fail(failures, "queue publish failed"); + return; + } + } + }); + } + + // Queue subscribers are still running when the publishers finish. Setting + // queues_done first would let them stop between a publish and the matching + // read; joining them first deadlocks, because they wait for the flag. + const int queue_subscriber_begin = static_cast(threads.size()) - + kNumQueueSubscribers - kNumQueuePublishers; + const int queue_publisher_begin = + static_cast(threads.size()) - kNumQueuePublishers; + for (int i = 0; i < queue_subscriber_begin; ++i) { + threads[i].join(); + } + for (int i = queue_publisher_begin; i < static_cast(threads.size()); + ++i) { + threads[i].join(); + } + queues_done.store(true, std::memory_order_release); + for (int i = queue_subscriber_begin; i < queue_publisher_begin; ++i) { + threads[i].join(); + } + EXPECT_EQ(0, failures.load()); + for (int received : queue_received) { + EXPECT_GT(received, 0); + } +} + +} // namespace + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/asil_client/subscriber.cc b/asil_client/subscriber.cc new file mode 100644 index 00000000..b7dab53d --- /dev/null +++ b/asil_client/subscriber.cc @@ -0,0 +1,435 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +// The reading side of the shared memory protocol. Taking, releasing and +// skipping messages uses common/subscribe.h, as the standard client does. +// The subscriber's available-slot bitset is the record of unread messages. +// A subscriber queue, when the channel has one, only holds hints, so the +// subscriber leaves it to the publishers. + +#include "asil_client/subscriber.h" + +#include "asil_client/client.h" +#include "common/message_checksum.h" +#include "common/subscribe.h" + +namespace subspace { +namespace asil { + +namespace { + +constexpr int kMaxClaimAttempts = 1000; + +bool ValidVchanId(int vchan_id) { + return vchan_id >= -1 && vchan_id < shm::kMaxVchanId; +} + +} // namespace + +SubscriberRequest Subscriber::BuildRequest() const { + SubscriberRequest request; + request.channel_name = name_; + request.type = options_.type; + request.max_active_messages = options_.max_active_messages; + request.reliable = options_.reliable; + request.mux = options_.mux; + request.vchan_id = options_.vchan_id; + return request; +} + +Error Subscriber::Open(Client &client, const char *channel_name, + const SubscriberOptions &options) { + if (client_ != nullptr) { + return Error::kAlreadyInitialized; + } + if (!client.Initialized()) { + return Error::kNotInitialized; + } + if (options.max_active_messages < 1 || + options.max_active_messages > kMaxActiveMessages || + !ValidVchanId(options.vchan_id)) { + return Error::kInvalidArgument; + } + if (Error e = internal::CopyName(channel_name, name_); e != Error::kOk) { + return e; + } + if (Error e = internal::CopyName( + options.mux != nullptr ? options.mux : channel_name, resolved_name_); + e != Error::kOk) { + return e; + } + options_ = options; + SubscriberReply reply; + reply.reliable_publisher_triggers = &reliable_publishers_; + reply.retirement_triggers = &retirement_triggers_; + if (Error e = client.connection_->CreateSubscriber(BuildRequest(), reply); + e != Error::kOk) { + Reset(); + return e; + } + client_ = &client; + channel_id_ = reply.channel_id; + subscriber_id_ = reply.subscriber_id; + vchan_id_ = reply.vchan_id; + num_pub_updates_ = static_cast(reply.num_pub_updates); + trigger_ = static_cast(reply.trigger); + poll_ = static_cast(reply.poll); + buffer_context_.channel_name = resolved_name_; + buffer_context_.session_id = client.session_id_; + buffer_context_.user_id = client.user_id_; + buffer_context_.group_id = client.group_id_; + buffer_context_.connection = client.connection_; + + Error e = Error::kOk; + if (channel_id_ < 0 || channel_id_ >= shm::kMaxChannels || + subscriber_id_ < 0 || subscriber_id_ >= shm::kMaxSlotOwners || + !ValidVchanId(vchan_id_)) { + e = Error::kProtocolError; + } + if (e == Error::kOk) { + // A channel without a layout has no buffers either. + e = reply.num_slots > 0 ? MapChannel(reply) : Error::kNoBuffers; + } + if (e != Error::kOk) { + (void)Close(); + return e; + } + // Wake the reader for messages published before it joined. + internal::Trigger(trigger_.Get()); + return Error::kOk; +} + +Error Subscriber::MapChannel(SubscriberReply &reply) { + if (Error e = + memory_.Map(client_->scb_, reply.ccb.Get(), reply.bcb.Get(), + reply.num_slots, reply.checksum_size, reply.metadata_size, + reply.subscriber_queue_arena_size, &buffer_context_); + e != Error::kOk) { + return e; + } + if (reply.use_split_buffers) { + return memory_.AttachSplitBuffers( + /*writable=*/false, options_.split_slots, options_.split_slot_capacity, + options_.split_allocator); + } + return memory_.AttachBuffer(/*writable=*/false); +} + +void Subscriber::Reset() { + memory_.Unmap(); + reliable_publishers_.Clear(); + retirement_triggers_.Clear(); + trigger_.Reset(); + poll_.Reset(); + client_ = nullptr; + num_held_ = 0; + for (uint64_t &ordinal : last_ordinals_) { + ordinal = 0; + } + channel_id_ = -1; + subscriber_id_ = -1; + vchan_id_ = -1; +} + +Error Subscriber::Close() { + if (client_ == nullptr) { + return Error::kOk; + } + ReleaseMessage(); + const Error e = client_->connection_->RemoveSubscriber(name_, subscriber_id_); + Reset(); + return e; +} + +Error Subscriber::Wait(int timeout_ms) { + if (client_ == nullptr) { + return Error::kNotInitialized; + } + return internal::WaitReadable(poll_.Get(), timeout_ms); +} + +void Subscriber::ReleaseHeld(int index) { + ReleaseSlot(held_[index].slot); + held_[index] = held_[--num_held_]; + held_[num_held_] = Held(); +} + +void Subscriber::ReleaseMessage() { + while (num_held_ > 0) { + ReleaseHeld(num_held_ - 1); + } +} + +Error Subscriber::ReleaseMessage(const Message &message) { + for (int i = 0; i < num_held_; i++) { + if (held_[i].slot->id == message.slot_id && + held_[i].ordinal == message.ordinal) { + ReleaseHeld(i); + return Error::kOk; + } + } + return Error::kInvalidArgument; +} + +void Subscriber::ReleaseSlot(shm::MessageSlot *slot) { + const ReleasedMessage result = ReleaseMessageReference( + memory_, slot, subscriber_id_, options_.reliable); + if (!result.released) { + return; + } + if (result.retired) { + memory_.TriggerRetirement(retirement_triggers_, result.retirement_slot_id); + } + if (options_.reliable) { + // A reliable publisher may be waiting for this slot. + TriggerReliablePublishers(); + } +} + +// Fetches new trigger fds when publishers have changed. +Error Subscriber::RefreshTriggers() { + const uint16_t updates = client_->scb_->counters[channel_id_].num_pub_updates; + if (updates == num_pub_updates_) { + return Error::kOk; + } + TriggersReply reply; + reply.reliable_publisher_triggers = &reliable_publishers_; + reply.retirement_triggers = &retirement_triggers_; + const Error e = client_->connection_->GetTriggers(name_, reply); + if (e == Error::kOk) { + num_pub_updates_ = updates; + } + return e; +} + +void Subscriber::TriggerReliablePublishers() const { + for (int i = 0; i < reliable_publishers_.Size(); i++) { + internal::Trigger(reliable_publishers_.Get(i)); + } +} + +// The ordinal of the published message in slot if this subscriber receives +// it, otherwise 0. +uint64_t Subscriber::VisibleOrdinal(const shm::MessageSlot *slot) const { + const uint64_t ordinal = CommittedOrdinal(slot); + if (ordinal == 0 || + !VirtualChannelsMatch(vchan_id_, + slot->vchan_id.load(std::memory_order_relaxed))) { + return 0; + } + return ordinal; +} + +bool Subscriber::Claim(shm::MessageSlot *slot, uint64_t ordinal) { + return ClaimMessageReference(memory_, slot, subscriber_id_, + options_.reliable, ordinal, + slot->vchan_id.load(std::memory_order_relaxed)); +} + +// Finds the oldest unread message and takes a reference to it. +Subscriber::Find Subscriber::FindNext(shm::MessageSlot *&slot) { + BitsetView available = memory_.AvailableSlots(subscriber_id_); + for (int attempt = 0; attempt < kMaxClaimAttempts; attempt++) { + shm::MessageSlot *best = nullptr; + uint64_t best_ordinal = 0; + uint64_t best_timestamp = 0; + available.Traverse([&](int i) { + shm::MessageSlot *s = memory_.Slot(i); + const uint64_t ordinal = VisibleOrdinal(s); + if (ordinal == 0) { + return; + } + const uint64_t timestamp = s->timestamp.load(std::memory_order_relaxed); + if (best == nullptr || + DeliveredBefore(timestamp, ordinal, best_timestamp, best_ordinal)) { + best = s; + best_ordinal = ordinal; + best_timestamp = timestamp; + } + }); + if (best == nullptr) { + return Find::kNone; + } + if (Claim(best, best_ordinal)) { + slot = best; + return Find::kFound; + } + // A publisher reclaimed the slot. Look again. + } + return Find::kNone; +} + +// Finds the newest unread message and takes a reference to it. +Subscriber::Find Subscriber::FindNewest(shm::MessageSlot *&slot) { + BitsetView available = memory_.AvailableSlots(subscriber_id_); + for (int attempt = 0; attempt < kMaxClaimAttempts; attempt++) { + shm::MessageSlot *best = nullptr; + uint64_t best_ordinal = 0; + uint64_t best_timestamp = 0; + available.Traverse([&](int i) { + shm::MessageSlot *s = memory_.Slot(i); + const uint64_t ordinal = VisibleOrdinal(s); + if (ordinal == 0) { + return; + } + const uint64_t timestamp = s->timestamp.load(std::memory_order_relaxed); + if (best == nullptr || + DeliveredBefore(best_timestamp, best_ordinal, timestamp, ordinal)) { + best = s; + best_ordinal = ordinal; + best_timestamp = timestamp; + } + }); + if (best == nullptr) { + return Find::kNone; + } + if (Claim(best, best_ordinal)) { + slot = best; + return Find::kFound; + } + } + return Find::kNone; +} + +// Marks every unread message older than newest as read. +void Subscriber::ClearOlder(const shm::MessageSlot *newest) { + BitsetView available = memory_.AvailableSlots(subscriber_id_); + const uint64_t newest_ordinal = + newest->ordinal.load(std::memory_order_relaxed); + const uint64_t newest_timestamp = + newest->timestamp.load(std::memory_order_relaxed); + bool marked_seen = false; + available.Traverse([&](int i) { + if (i == newest->id) { + return; + } + shm::MessageSlot *s = memory_.Slot(i); + const uint64_t ordinal = VisibleOrdinal(s); + if (ordinal == 0) { + return; + } + const uint64_t timestamp = s->timestamp.load(std::memory_order_relaxed); + if (!DeliveredBefore(timestamp, ordinal, newest_timestamp, + newest_ordinal)) { + return; + } + if (SkipUnreadMessage(memory_, s, subscriber_id_, options_.reliable, + ordinal, + s->vchan_id.load(std::memory_order_relaxed))) { + marked_seen |= options_.reliable; + } + }); + if (marked_seen) { + TriggerReliablePublishers(); + } +} + +bool Subscriber::ChecksumValid(const shm::MessageSlot *slot, + size_t length) const { + return MessageChecksumMatches(memory_.Prefix(slot), memory_.Payload(slot), + length, memory_.ChecksumSize(), + memory_.MetadataSize()); +} + +Error Subscriber::ReadMessage(Message &message, ReadMode mode) { + message = Message(); + if (client_ == nullptr) { + return Error::kNotInitialized; + } + internal::ClearTrigger(poll_.Get()); + const bool single = options_.max_active_messages == 1; + // A reliable subscriber keeps its last message until it has the next one, + // which stops a reliable publisher overtaking it. + const bool keep_previous = single && options_.reliable; + if (single && !keep_previous) { + ReleaseMessage(); + } else if (!single && num_held_ >= options_.max_active_messages) { + return Error::kActiveMessageLimit; + } + if (Error e = RefreshTriggers(); e != Error::kOk) { + return e; + } + BitsetView available = memory_.AvailableSlots(subscriber_id_); + for (int attempt = 0; attempt < kMaxClaimAttempts; attempt++) { + shm::MessageSlot *slot = nullptr; + const Find found = + mode == ReadMode::kReadNext ? FindNext(slot) : FindNewest(slot); + if (found == Find::kNone) { + // Out of messages: tell reliable publishers there is room. + TriggerReliablePublishers(); + return Error::kOk; + } + const uint64_t ordinal = slot->ordinal.load(std::memory_order_relaxed); + const size_t length = + static_cast(slot->message_size.load(std::memory_order_relaxed)); + const int vchan_id = slot->vchan_id.load(std::memory_order_relaxed); + const bool mapped = memory_.InMappedBuffer(slot); + + if (mode == ReadMode::kReadNewest) { + ClearOlder(slot); + } + available.Clear(slot->id); + MarkMessageSeen(slot, options_.reliable); + + uint64_t unused_last_ordinal = 0; + uint64_t &last_ordinal = ValidVchanId(vchan_id) + ? last_ordinals_[vchan_id + 1] + : unused_last_ordinal; + if (!mapped) { + if (ordinal > last_ordinal) { + last_ordinal = ordinal; + } + ReleaseSlot(slot); + return Error::kBufferNotMapped; + } + const shm::MessagePrefix *prefix = memory_.Prefix(slot); + const bool is_activation = (prefix->flags & shm::kMessageActivate) != 0; + if (length == 0 || (is_activation && !options_.pass_activation)) { + if (ordinal > last_ordinal) { + last_ordinal = ordinal; + } + ReleaseSlot(slot); + continue; + } + if (mode == ReadMode::kReadNext && last_ordinal != 0 && + ordinal > last_ordinal + 1) { + message.dropped = static_cast(ordinal - last_ordinal - 1); + memory_.Ccb()->total_drops += message.dropped; + } + if (ordinal > last_ordinal) { + last_ordinal = ordinal; + } + const bool checksum_error = + options_.checksum && (prefix->flags & shm::kMessageHasChecksum) != 0 && + !ChecksumValid(slot, length); + if (checksum_error && !options_.pass_checksum_errors) { + ReleaseSlot(slot); + message = Message(); + return Error::kChecksumMismatch; + } + if (keep_previous) { + ReleaseMessage(); + } + held_[num_held_++] = Held{slot, ordinal}; + message.data = memory_.Payload(slot); + message.length = length; + message.ordinal = ordinal; + message.timestamp = slot->timestamp.load(std::memory_order_relaxed); + message.slot_id = slot->id; + message.vchan_id = vchan_id; + message.is_activation = is_activation; + message.checksum_error = checksum_error; + if (memory_.MetadataSize() > 0) { + message.metadata = reinterpret_cast(&prefix->checksum) + + memory_.ChecksumSize(); + message.metadata_length = static_cast(memory_.MetadataSize()); + } + return Error::kOk; + } + return Error::kOk; +} + +} // namespace asil +} // namespace subspace diff --git a/asil_client/subscriber.h b/asil_client/subscriber.h new file mode 100644 index 00000000..4c674616 --- /dev/null +++ b/asil_client/subscriber.h @@ -0,0 +1,161 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +#pragma once + +#include "asil_client/channel_memory.h" +#include "asil_client/error.h" +#include "asil_client/server_connection.h" +#include "asil_client/unique_fd.h" + +#include +#include + +namespace subspace { +namespace asil { + +class Client; + +// The most messages that one subscriber can hold at once. +constexpr int kMaxActiveMessages = 64; + +struct SubscriberOptions { + const char *type = nullptr; + // Verify message checksums. + bool checksum = false; + // Deliver a message whose checksum is wrong, with checksum_error set, + // rather than failing the read. + bool pass_checksum_errors = false; + // Deliver activation messages. + bool pass_activation = false; + // Reliable publishers wait for this subscriber to read every message. + bool reliable = false; + // Subscribe to a virtual channel of this multiplexer. vchan_id -1 lets the + // server choose the channel's id. To read every virtual channel, subscribe + // to the multiplexer itself. + const char *mux = nullptr; + int32_t vchan_id = -1; + // How many messages the subscriber can hold, up to kMaxActiveMessages. + // With 1, each read releases the previous message. With more, messages are + // held until ReleaseMessage(). + int32_t max_active_messages = 1; + // For a channel with split buffers: room for the channel's num_slots slot + // mappings, and the allocator for slots that a custom allocator created. + SplitSlot *split_slots = nullptr; + int32_t split_slot_capacity = 0; + SplitBufferAllocator split_allocator; +}; + +enum class ReadMode { + kReadNext, + kReadNewest, +}; + +// A message in shared memory. The pointers stay valid until the message is +// released: by the next read when max_active_messages is 1, otherwise by +// ReleaseMessage(), and always by Close(). +struct Message { + const void *data = nullptr; + size_t length = 0; // 0 when there was no message. + uint64_t ordinal = 0; + uint64_t timestamp = 0; + int32_t slot_id = -1; + // The virtual channel the message was published on, or -1. + int32_t vchan_id = -1; + bool is_activation = false; + bool checksum_error = false; + // Messages missed since the previous read on the same virtual channel, for + // kReadNext. + uint32_t dropped = 0; + const void *metadata = nullptr; + size_t metadata_length = 0; +}; + +// A subscriber to a fixed-size channel. +// +// A subscriber is not thread safe and must not outlive its Client. It holds +// a table of the last ordinal seen on each virtual channel, about 8 KB. +class Subscriber { +public: + Subscriber() = default; + ~Subscriber() { (void)Close(); } + Subscriber(const Subscriber &) = delete; + Subscriber &operator=(const Subscriber &) = delete; + + Error Open(Client &client, const char *channel_name, + const SubscriberOptions &options); + // Removes the subscriber from the server. Safe to call more than once. + Error Close(); + bool IsOpen() const { return client_ != nullptr; } + + // Reads a message. Returns kOk with message.length == 0 when there is no + // message, and kActiveMessageLimit when the subscriber already holds + // max_active_messages messages. If a publisher has joined since the last + // read this asks the server for its trigger fds first. The channel's + // buffers are mapped by Open(), so this maps nothing. + Error ReadMessage(Message &message, ReadMode mode = ReadMode::kReadNext); + // Releases every message the subscriber holds. + void ReleaseMessage(); + // Releases one message. Returns kInvalidArgument if the subscriber doesn't + // hold it. + Error ReleaseMessage(const Message &message); + int NumActiveMessages() const { return num_held_; } + + // Readable when there may be messages to read. + int PollFd() const { return poll_.Get(); } + // Waits until PollFd() is readable. A negative timeout waits forever. + Error Wait(int timeout_ms); + + bool IsReliable() const { return options_.reliable; } + // The subscriber's virtual channel id, or -1. + int VirtualChannelId() const { return vchan_id_; } + const char *Name() const { return name_; } + +private: + enum class Find { kFound, kNone }; + + struct Held { + shm::MessageSlot *slot = nullptr; + uint64_t ordinal = 0; + }; + + SubscriberRequest BuildRequest() const; + Error MapChannel(SubscriberReply &reply); + Error RefreshTriggers(); + uint64_t VisibleOrdinal(const shm::MessageSlot *slot) const; + Find FindNext(shm::MessageSlot *&slot); + Find FindNewest(shm::MessageSlot *&slot); + bool Claim(shm::MessageSlot *slot, uint64_t ordinal); + void ClearOlder(const shm::MessageSlot *newest); + void ReleaseSlot(shm::MessageSlot *slot); + void ReleaseHeld(int index); + bool ChecksumValid(const shm::MessageSlot *slot, size_t length) const; + void TriggerReliablePublishers() const; + void Reset(); + + Client *client_ = nullptr; + internal::ChannelMemory memory_; + internal::BufferContext buffer_context_; + char name_[kMaxChannelNameLength + 1] = {}; + // The channel that owns the shared memory: the multiplexer of a virtual + // channel. + char resolved_name_[kMaxChannelNameLength + 1] = {}; + SubscriberOptions options_; + int32_t channel_id_ = -1; + int32_t subscriber_id_ = -1; + int32_t vchan_id_ = -1; + uint16_t num_pub_updates_ = 0; + UniqueFd trigger_; + UniqueFd poll_; + Held held_[kMaxActiveMessages]; + int num_held_ = 0; + // The newest ordinal read on each virtual channel, indexed by vchan_id + 1. + uint64_t last_ordinals_[shm::kMaxVchanId + 1] = {}; + TriggerFdList reliable_publishers_; + TriggerFdList retirement_triggers_; +}; + +} // namespace asil +} // namespace subspace diff --git a/asil_client/unique_fd.h b/asil_client/unique_fd.h new file mode 100644 index 00000000..19cc30c2 --- /dev/null +++ b/asil_client/unique_fd.h @@ -0,0 +1,81 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +#pragma once + +#include + +namespace subspace { +namespace asil { + +// An owned file descriptor, closed on destruction. +class UniqueFd { +public: + UniqueFd() = default; + explicit UniqueFd(int fd) : fd_(fd) {} + ~UniqueFd() { Reset(); } + + UniqueFd(const UniqueFd &) = delete; + UniqueFd &operator=(const UniqueFd &) = delete; + + UniqueFd(UniqueFd &&other) noexcept : fd_(other.Release()) {} + UniqueFd &operator=(UniqueFd &&other) noexcept { + if (this != &other) { + Reset(other.Release()); + } + return *this; + } + + int Get() const { return fd_; } + bool Valid() const { return fd_ >= 0; } + + int Release() { + const int fd = fd_; + fd_ = -1; + return fd; + } + + void Reset(int fd = -1) { + if (fd_ >= 0) { + (void)::close(fd_); + } + fd_ = fd; + } + +private: + int fd_ = -1; +}; + +// A fixed-capacity list of owned file descriptors. +template class FdList { +public: + static constexpr int Capacity() { return kCapacity; } + + // Takes ownership of fd. Returns false, closing fd, if the list is full. + bool Add(UniqueFd fd) { + if (count_ >= kCapacity) { + return false; + } + fds_[count_++] = static_cast(fd); + return true; + } + + void Clear() { + for (int i = 0; i < count_; i++) { + fds_[i].Reset(); + } + count_ = 0; + } + + int Size() const { return count_; } + int Get(int i) const { return fds_[i].Get(); } + +private: + UniqueFd fds_[kCapacity]; + int count_ = 0; +}; + +} // namespace asil +} // namespace subspace diff --git a/c_client/subspace.cc b/c_client/subspace.cc index 2d01c9f6..314035f3 100644 --- a/c_client/subspace.cc +++ b/c_client/subspace.cc @@ -576,6 +576,13 @@ subspace_publisher_options_default(SubspaceSlotSize slot_size, int num_slots) { return options; } +SubspacePublisherOptions subspace_publisher_options_server_defined(void) { + SubspacePublisherOptions options = subspace_publisher_options_default(0, 0); + options.checksum_size = 0; + options.server_defined = true; + return options; +} + SubspaceSubscriber subspace_create_subscriber(SubspaceClient client, const char *channel_name, SubspaceSubscriberOptions options) { @@ -648,7 +655,8 @@ SubspacePublisher subspace_create_publisher(SubspaceClient client, .SetMaxPublishers(options.max_publishers) .SetUseSplitBuffers(options.use_split_buffers) .SetSplitBuffersOverBridge(options.split_buffers_over_bridge) - .SetSplitBufferCallbacks(ToCppSplitCallbacks(options.split_callbacks)); + .SetSplitBufferCallbacks(ToCppSplitCallbacks(options.split_callbacks)) + .SetServerDefined(options.server_defined); subspace_clear_error(); SubspacePublisher publisher; memset(&publisher, 0, sizeof(publisher)); diff --git a/c_client/subspace.h b/c_client/subspace.h index 1244d9c8..83ed94aa 100644 --- a/c_client/subspace.h +++ b/c_client/subspace.h @@ -318,6 +318,12 @@ typedef struct { bool split_buffers_over_bridge; int32_t max_publishers; SubspaceSplitBufferCallbacks split_callbacks; + // The channel is in the server's static channel config, which defines its + // layout. Publishers on static channels must set this and leave + // slot_size, num_slots, fixed_size, checksum_size, metadata_size, + // subscriber_queue_arena_size and use_split_buffers zero. Use + // subspace_publisher_options_server_defined() to get such options. + bool server_defined; } SubspacePublisherOptions; typedef struct { @@ -437,6 +443,9 @@ bool subspace_get_all_channel_stats(SubspaceClient client, SubspaceSubscriberOptions subspace_subscriber_options_default(void); SubspacePublisherOptions subspace_publisher_options_default(SubspaceSlotSize slot_size, int num_slots); +// Options for a publisher on a static channel, whose layout the server +// defines. +SubspacePublisherOptions subspace_publisher_options_server_defined(void); // Create a subscriber or publisher. If the subscriber or publisher is created // OK, the 'subscriber' or 'publisher' pointer will be non-null. If there is diff --git a/client/Android.bp b/client/Android.bp index 01daef2a..97808b0f 100644 --- a/client/Android.bp +++ b/client/Android.bp @@ -11,18 +11,19 @@ cc_library_shared { "message.cc", "publisher.cc", "subscriber.cc", - "checksum.cc", - "arm_crc32.S", ], export_include_dirs: ["."], include_dirs: ["external/subspace"], static_libs: [ + "libsubspace_crc32", "libsubspace_common", "libsubspace_proto", + "libsubspace_phaser", "libcoroutines", "libcpp_toolbelt", "libabsl", ], + export_static_lib_headers: ["libsubspace_phaser"], shared_libs: [ "libprotobuf-cpp-full", "liblog", diff --git a/client/BUILD.bazel b/client/BUILD.bazel index 1d5b9e90..21bfc753 100644 --- a/client/BUILD.bazel +++ b/client/BUILD.bazel @@ -10,8 +10,6 @@ cc_library( "message.cc", "publisher.cc", "subscriber.cc", - "checksum.cc", - "arm_crc32.S", ], hdrs = [ "client.h", @@ -25,9 +23,12 @@ cc_library( strip_include_prefix = ".", include_prefix = "subspace/client", deps = [ + "//common:crc32", + "//common:server_wire", "//common:subspace_common", "//common/async:async", "//proto:subspace_cc_proto", + "//proto:subspace_phaser", "@abseil-cpp//absl/container:flat_hash_map", "@abseil-cpp//absl/container:flat_hash_set", "@abseil-cpp//absl/status", @@ -116,9 +117,18 @@ cc_test( "@googletest//:gtest", "@coroutines//:co", ] + select({ - "//:macos_arm64": ["//plugins:nop_plugin_lib"], - "//:macos_x86_64": ["//plugins:nop_plugin_lib"], - "//:macos_default": ["//plugins:nop_plugin_lib"], + "//:macos_arm64": [ + "//plugins:nop_plugin_lib", + "//plugins:split_buffer_free_test_plugin_lib", + ], + "//:macos_x86_64": [ + "//plugins:nop_plugin_lib", + "//plugins:split_buffer_free_test_plugin_lib", + ], + "//:macos_default": [ + "//plugins:nop_plugin_lib", + "//plugins:split_buffer_free_test_plugin_lib", + ], "//conditions:default": [], }), ) diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 41b7c238..6286541b 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -13,25 +13,20 @@ add_library(subspace_client STATIC publisher.h subscriber.cc subscriber.h - checksum.cc checksum.h - arm_crc32.S ) target_include_directories(subspace_client PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ) -# Set the assembly file to use ASM language (CMake will handle C preprocessor automatically for .S files) -set_source_files_properties(arm_crc32.S PROPERTIES - LANGUAGE ASM -) - # Link against other internal libraries (e.g., common) or external dependencies if needed: target_link_libraries(subspace_client PUBLIC subspace_common + subspace_crc32 subspace_async subspace_proto + subspace_phaser absl::flags absl::flat_hash_map absl::flat_hash_set @@ -50,6 +45,13 @@ add_test(NAME client_test COMMAND client_test) set_tests_properties(client_test PROPERTIES WORKING_DIRECTORY "${CMAKE_BINARY_DIR}" ) +if(APPLE) + # Linked first so the static libraries below resolve their references. + target_link_libraries(client_test PUBLIC + nop_plugin_lib + split_buffer_free_test_plugin_lib + ) +endif() target_link_libraries(client_test PUBLIC subspace_client subspace_common diff --git a/client/checksum.h b/client/checksum.h index 7ddc508c..0cc9b0d3 100644 --- a/client/checksum.h +++ b/client/checksum.h @@ -5,20 +5,15 @@ #pragma once #include "absl/types/span.h" +#include "common/crc32.h" + #include #include #include #include -// Undefine this if you don't want to use hardware CRC32 instructions -#define SUBSPACE_HARDWARE_CRC 1 - namespace subspace { -extern "C" { -uint32_t SubspaceCRC32(uint32_t crc, const uint8_t *data, size_t length); -} - // The callback receives the data to be checksummed and a writable region // where the checksum should be stored. The default CRC32 implementation // writes 4 bytes; custom callbacks may use the full region. diff --git a/client/client.cc b/client/client.cc index f7d8ff48..98bcc279 100644 --- a/client/client.cc +++ b/client/client.cc @@ -6,7 +6,7 @@ #include "absl/strings/str_format.h" #include "client.h" #include "common/syscall_shim.h" -#include "proto/subspace.pb.h" +#include "common/server_wire.h" #include "toolbelt/clock.h" #include "toolbelt/hexdump.h" #include "toolbelt/mutex.h" @@ -24,7 +24,7 @@ namespace subspace { namespace { -void FillInitRequest(InitRequest *init, const std::string &client_name) { +void FillInitRequest(phaser::InitRequest *init, const std::string &client_name) { init->set_client_name(client_name); init->set_max_channels(kMaxChannels); init->set_max_slot_owners(kMaxSlotOwners); @@ -49,35 +49,37 @@ void ConfigureQnxClockPeriod() { } #endif -ClientBufferAllocatorKind FromProtoAllocator(ClientBufferAllocator allocator) { +ClientBufferAllocatorKind +FromProtoAllocator(phaser::ClientBufferAllocator allocator) { switch (allocator) { - case CLIENT_BUFFER_ALLOCATOR_ANDROID_MEMFD: + case phaser::CLIENT_BUFFER_ALLOCATOR_ANDROID_MEMFD: return ClientBufferAllocatorKind::kAndroidMemfd; - case CLIENT_BUFFER_ALLOCATOR_SPLIT_SHM: + case phaser::CLIENT_BUFFER_ALLOCATOR_SPLIT_SHM: return ClientBufferAllocatorKind::kSplitShm; - case CLIENT_BUFFER_ALLOCATOR_SPLIT_CALLBACK: + case phaser::CLIENT_BUFFER_ALLOCATOR_SPLIT_CALLBACK: return ClientBufferAllocatorKind::kSplitCallback; - case CLIENT_BUFFER_ALLOCATOR_SPLIT_BUFFER_FREE_TEST: + case phaser::CLIENT_BUFFER_ALLOCATOR_SPLIT_BUFFER_FREE_TEST: return ClientBufferAllocatorKind::kSplitBufferFreeTest; - case CLIENT_BUFFER_ALLOCATOR_UNSPECIFIED: + case phaser::CLIENT_BUFFER_ALLOCATOR_UNSPECIFIED: default: return ClientBufferAllocatorKind::kUnspecified; } } -ClientBufferAllocator ToProtoAllocator(ClientBufferAllocatorKind allocator) { +phaser::ClientBufferAllocator +ToProtoAllocator(ClientBufferAllocatorKind allocator) { switch (allocator) { case ClientBufferAllocatorKind::kAndroidMemfd: - return CLIENT_BUFFER_ALLOCATOR_ANDROID_MEMFD; + return phaser::CLIENT_BUFFER_ALLOCATOR_ANDROID_MEMFD; case ClientBufferAllocatorKind::kSplitShm: - return CLIENT_BUFFER_ALLOCATOR_SPLIT_SHM; + return phaser::CLIENT_BUFFER_ALLOCATOR_SPLIT_SHM; case ClientBufferAllocatorKind::kSplitCallback: - return CLIENT_BUFFER_ALLOCATOR_SPLIT_CALLBACK; + return phaser::CLIENT_BUFFER_ALLOCATOR_SPLIT_CALLBACK; case ClientBufferAllocatorKind::kSplitBufferFreeTest: - return CLIENT_BUFFER_ALLOCATOR_SPLIT_BUFFER_FREE_TEST; + return phaser::CLIENT_BUFFER_ALLOCATOR_SPLIT_BUFFER_FREE_TEST; case ClientBufferAllocatorKind::kUnspecified: default: - return CLIENT_BUFFER_ALLOCATOR_UNSPECIFIED; + return phaser::CLIENT_BUFFER_ALLOCATOR_UNSPECIFIED; } } } // namespace @@ -106,7 +108,7 @@ static uint64_t GetThreadId() { } static void ToProto(const ClientBufferHandleMetadata &metadata, - ClientBufferHandleMetadataProto *proto) { + phaser::ClientBufferHandleMetadataProto *proto) { proto->set_channel_name(metadata.channel_name); proto->set_session_id(metadata.session_id); proto->set_buffer_index(metadata.buffer_index); @@ -122,7 +124,7 @@ static void ToProto(const ClientBufferHandleMetadata &metadata, } static ClientBufferHandleMetadata -FromProto(const ClientBufferHandleMetadataProto &proto) { +FromProto(const phaser::ClientBufferHandleMetadataProto &proto) { ClientBufferHandleMetadata metadata; metadata.channel_name = proto.channel_name(); metadata.session_id = proto.session_id(); @@ -248,9 +250,9 @@ absl::Status ClientImpl::Init(const std::string &server_socket, name_ = client_name; socket_name_ = server_socket; - Request req; + phaser::Request req; FillInitRequest(req.mutable_init(), client_name); - Response resp; + phaser::Response resp; std::vector fds; fds.reserve(100); status = SendRequestReceiveResponse(req, resp, fds); @@ -442,8 +444,19 @@ ClientImpl::CreatePublisher(const std::string &channel_name, if (absl::Status status = CheckConnected(); !status.ok()) { return status; } - if (opts.MaxOutstandingSlotLeases() < 1 || - opts.MaxOutstandingSlotLeases() > opts.NumSlots()) { + if (opts.ServerDefined()) { + if (opts.slot_size != 0 || opts.num_slots != 0 || opts.fixed_size || + opts.checksum_size != 0 || opts.metadata_size != 0 || + opts.subscriber_queue_arena_size != 0 || opts.use_split_buffers) { + return absl::InvalidArgumentError(absl::StrFormat( + "Publisher on %s is server defined, so it can't set the slot size, " + "number of slots, fixed size, checksum size, metadata size, " + "subscriber queue arena size or split buffers", + channel_name)); + } + // The server checks the leases against the channel's slots. + } else if (opts.MaxOutstandingSlotLeases() < 1 || + opts.MaxOutstandingSlotLeases() > opts.NumSlots()) { return absl::InvalidArgumentError( "MaxOutstandingSlotLeases must be between 1 and NumSlots"); } @@ -456,29 +469,29 @@ ClientImpl::CreatePublisher(const std::string &channel_name, "Slot size %d for channel %s exceeds its maximum slot size of %d bytes", opts.slot_size, channel_name, opts.max_slot_size)); } - Request req; + phaser::Request req; FillCreatePublisherRequest(req.mutable_create_publisher(), channel_name, opts, -1); // Send request to server and wait for response. - Response resp; + phaser::Response resp; std::vector fds; fds.reserve(100); if (absl::Status status = SendRequestReceiveResponse(req, resp, fds); !status.ok()) { return status; } - auto &pub_resp = resp.create_publisher(); + const auto &pub_resp = resp.create_publisher(); if (!pub_resp.error().empty()) { return absl::InternalError(pub_resp.error()); } auto remove_server_publisher = [&]() { - Request remove_req; + phaser::Request remove_req; auto *cmd = remove_req.mutable_remove_publisher(); cmd->set_channel_name(channel_name); cmd->set_publisher_id(pub_resp.publisher_id()); - Response remove_resp; + phaser::Response remove_resp; std::vector remove_fds; (void)SendRequestReceiveResponse(remove_req, remove_resp, remove_fds); }; @@ -491,11 +504,20 @@ ClientImpl::CreatePublisher(const std::string &channel_name, if (pub_resp.num_slots() > 0) { channel_opts.num_slots = pub_resp.num_slots(); } + if (opts.ServerDefined()) { + channel_opts.slot_size = pub_resp.slot_size(); + channel_opts.fixed_size = pub_resp.is_fixed_size(); + channel_opts.checksum_size = pub_resp.checksum_size(); + channel_opts.metadata_size = pub_resp.metadata_size(); + channel_opts.subscriber_queue_arena_size = + pub_resp.subscriber_queue_arena_size(); + channel_opts.use_split_buffers = pub_resp.use_split_buffers(); + } std::shared_ptr channel = std::make_shared( channel_name, channel_opts.num_slots, pub_resp.subscriber_queue_size(), pub_resp.subscriber_queue_arena_size(), pub_resp.channel_id(), pub_resp.publisher_id(), pub_resp.vchan_id(), session_id_, - pub_resp.type(), channel_opts, + std::string(pub_resp.type()), channel_opts, [this](Channel *c) { return CheckReload(static_cast(c)); }, @@ -515,8 +537,10 @@ ClientImpl::CreatePublisher(const std::string &channel_name, uint32_t buffer_index) { return UnregisterClientBuffer(channel_name, session_id, buffer_index); }); - int32_t cs = opts.ChecksumSize() > 0 ? opts.ChecksumSize() : 4; - int32_t ms = opts.MetadataSize() > 0 ? opts.MetadataSize() : 0; + int32_t cs = + channel_opts.ChecksumSize() > 0 ? channel_opts.ChecksumSize() : 4; + int32_t ms = + channel_opts.MetadataSize() > 0 ? channel_opts.MetadataSize() : 0; channel->SetChecksumSize(cs); channel->SetMetadataSize(ms); channel->SetPrefixSize(Channel::ComputePrefixSize(cs, ms)); @@ -542,7 +566,7 @@ ClientImpl::CreatePublisher(const std::string &channel_name, } if (absl::Status status = - channel->CreateOrAttachBuffers(Aligned(opts.slot_size)); + channel->CreateOrAttachBuffers(Aligned(channel_opts.slot_size)); !status.ok()) { remove_server_publisher(); return status; @@ -611,12 +635,12 @@ ClientImpl::CreateSubscriber(const std::string &channel_name, "at least 0, not %g", opts.StuckWarningGracePeriod())); } - Request req; + phaser::Request req; FillCreateSubscriberRequest(req.mutable_create_subscriber(), channel_name, opts, -1); // Send request to server and wait for response. - Response resp; + phaser::Response resp; std::vector fds; fds.reserve(100); if (absl::Status status = SendRequestReceiveResponse(req, resp, fds); @@ -624,7 +648,7 @@ ClientImpl::CreateSubscriber(const std::string &channel_name, return status; } - auto &sub_resp = resp.create_subscriber(); + const auto &sub_resp = resp.create_subscriber(); if (!sub_resp.error().empty()) { return absl::InternalError(sub_resp.error()); } @@ -636,14 +660,15 @@ ClientImpl::CreateSubscriber(const std::string &channel_name, const std::string mapped_channel_name = sub_resp.resolved_channel_name().empty() ? channel_name - : sub_resp.resolved_channel_name(); + : std::string(sub_resp.resolved_channel_name()); std::shared_ptr channel = std::make_shared( mapped_channel_name, sub_resp.num_slots(), sub_resp.default_subscriber_queue_size(), sub_resp.subscriber_queue_arena_size(), sub_resp.subscriber_queue_size(), sub_resp.channel_id(), - sub_resp.subscriber_id(), sub_resp.vchan_id(), session_id_, sub_resp.type(), + sub_resp.subscriber_id(), sub_resp.vchan_id(), session_id_, + std::string(sub_resp.type()), subscriber_options, [this](Channel *c) { return CheckReload(static_cast(c)); @@ -1804,13 +1829,13 @@ absl::Status ClientImpl::ReloadSubscriber(SubscriberImpl *subscriber) { if (absl::Status status = CheckConnected(); !status.ok()) { return status; } - Request req; + phaser::Request req; FillCreateSubscriberRequest(req.mutable_create_subscriber(), subscriber->RequestName(), subscriber->options_, subscriber->GetSubscriberId()); // Send request to server and wait for response. - Response resp; + phaser::Response resp; std::vector fds; fds.reserve(100); if (absl::Status status = SendRequestReceiveResponse(req, resp, fds); @@ -1818,7 +1843,7 @@ absl::Status ClientImpl::ReloadSubscriber(SubscriberImpl *subscriber) { return status; } - auto &sub_resp = resp.create_subscriber(); + const auto &sub_resp = resp.create_subscriber(); if (!sub_resp.error().empty()) { return absl::InternalError(sub_resp.error()); } @@ -1835,7 +1860,7 @@ absl::Status ClientImpl::ReloadSubscriber(SubscriberImpl *subscriber) { } if (!sub_resp.type().empty()) { - subscriber->SetType(sub_resp.type()); + subscriber->SetType(std::string(sub_resp.type())); } subscriber->options_.use_split_buffers = sub_resp.use_split_buffers(); subscriber->SetNumSlots(sub_resp.num_slots()); @@ -1901,12 +1926,12 @@ ClientImpl::ReloadSubscribersIfNecessary(PublisherImpl *publisher) { // We do have updates, get a new list of subscriber for // the channel. - Request req; + phaser::Request req; auto *cmd = req.mutable_get_triggers(); cmd->set_channel_name(publisher->Name()); // Send request to server and wait for response. - Response resp; + phaser::Response resp; std::vector fds; fds.reserve(100); if (absl::Status status = SendRequestReceiveResponse(req, resp, fds); @@ -1914,7 +1939,7 @@ ClientImpl::ReloadSubscribersIfNecessary(PublisherImpl *publisher) { return status; } - auto &sub_resp = resp.get_triggers(); + const auto &sub_resp = resp.get_triggers(); // Add all subscriber triggers fds to the publisher channel. publisher->ClearSubscribers(); for (auto index : sub_resp.sub_trigger_fd_indexes()) { @@ -1944,12 +1969,12 @@ ClientImpl::ReloadReliablePublishersIfNecessary(SubscriberImpl *subscriber) { } // We do have updates, get a new list of subscriber for // the channel. - Request req; + phaser::Request req; auto *cmd = req.mutable_get_triggers(); cmd->set_channel_name(subscriber->Name()); // Send request to server and wait for response. - Response resp; + phaser::Response resp; std::vector fds; fds.reserve(100); if (absl::Status status = SendRequestReceiveResponse(req, resp, fds); @@ -1957,7 +1982,7 @@ ClientImpl::ReloadReliablePublishersIfNecessary(SubscriberImpl *subscriber) { return status; } - auto &sub_resp = resp.get_triggers(); + const auto &sub_resp = resp.get_triggers(); // Add all subscriber triggers fds to the publisher channel. subscriber->ClearPublishers(); for (auto index : sub_resp.reliable_pub_trigger_fd_indexes()) { @@ -2038,13 +2063,13 @@ absl::Status ClientImpl::RemovePublisher(PublisherImpl *publisher) { if (!socket_.Connected()) { return RemoveChannel(publisher); } - Request req; + phaser::Request req; auto *cmd = req.mutable_remove_publisher(); cmd->set_channel_name(publisher->Name()); cmd->set_publisher_id(publisher->GetPublisherId()); // Send request to server and wait for response. - Response response; + phaser::Response response; std::vector fds; fds.reserve(100); if (absl::Status status = SendRequestReceiveResponse(req, response, fds); @@ -2052,7 +2077,7 @@ absl::Status ClientImpl::RemovePublisher(PublisherImpl *publisher) { return RemoveChannel(publisher); } - auto &resp = response.remove_publisher(); + const auto &resp = response.remove_publisher(); if (!resp.error().empty()) { return absl::InternalError(resp.error()); } @@ -2064,14 +2089,14 @@ absl::Status ClientImpl::RemoveSubscriber(SubscriberImpl *subscriber) { if (!socket_.Connected()) { return RemoveChannel(subscriber); } - Request req; + phaser::Request req; auto *cmd = req.mutable_remove_subscriber(); cmd->set_channel_name(subscriber->RequestName()); cmd->set_subscriber_id(subscriber->GetSubscriberId()); cmd->set_telemetry(subscriber->options_.Telemetry()); // Send request to server and wait for response. - Response response; + phaser::Response response; std::vector fds; fds.reserve(100); if (absl::Status status = SendRequestReceiveResponse(req, response, fds); @@ -2079,7 +2104,7 @@ absl::Status ClientImpl::RemoveSubscriber(SubscriberImpl *subscriber) { return RemoveChannel(subscriber); } - auto &resp = response.remove_subscriber(); + const auto &resp = response.remove_subscriber(); if (!resp.error().empty()) { return absl::InternalError(resp.error()); } @@ -2107,19 +2132,19 @@ ClientImpl::GetChannelInfo(const std::string &channel) { if (absl::Status status = CheckConnected(); !status.ok()) { return status; } - Request req; + phaser::Request req; auto *cmd = req.mutable_get_channel_info(); cmd->set_channel_name(channel); // Send request to server and wait for response. - Response response; + phaser::Response response; std::vector fds; if (absl::Status status = SendRequestReceiveResponse(req, response, fds); !status.ok()) { return status; } - auto &resp = response.get_channel_info(); + const auto &resp = response.get_channel_info(); if (!resp.error().empty()) { return absl::InternalError(resp.error()); } @@ -2128,7 +2153,7 @@ ClientImpl::GetChannelInfo(const std::string &channel) { return absl::InternalError("Invalid response for getChannelInfo"); } ChannelInfo result; - const ChannelInfoProto &info = resp.channels()[0]; + const phaser::ChannelInfoProto info = resp.channels(0); result.channel_name = info.name(); result.num_publishers = info.num_pubs(); result.num_subscribers = info.num_subs(); @@ -2152,22 +2177,22 @@ absl::StatusOr> ClientImpl::GetChannelInfo() { if (absl::Status status = CheckConnected(); !status.ok()) { return status; } - Request req; + phaser::Request req; [[maybe_unused]] auto cmd = req.mutable_get_channel_info(); // Send request to server and wait for response. - Response response; + phaser::Response response; std::vector fds; if (absl::Status status = SendRequestReceiveResponse(req, response, fds); !status.ok()) { return status; } - auto &resp = response.get_channel_info(); + const auto &resp = response.get_channel_info(); if (!resp.error().empty()) { return absl::InternalError(resp.error()); } std::vector r; - for (auto &info : resp.channels()) { + for (const auto &info : resp.channels()) { ChannelInfo result; result.channel_name = info.name(); result.num_publishers = info.num_pubs(); @@ -2204,18 +2229,18 @@ ClientImpl::GetChannelStats(const std::string &channel) { if (absl::Status status = CheckConnected(); !status.ok()) { return status; } - Request req; + phaser::Request req; auto *cmd = req.mutable_get_channel_stats(); cmd->set_channel_name(channel); // Send request to server and wait for response. - Response response; + phaser::Response response; std::vector fds; if (absl::Status status = SendRequestReceiveResponse(req, response, fds); !status.ok()) { return status; } - auto &resp = response.get_channel_stats(); + const auto &resp = response.get_channel_stats(); if (!resp.error().empty()) { return absl::InternalError(resp.error()); } @@ -2224,7 +2249,7 @@ ClientImpl::GetChannelStats(const std::string &channel) { return absl::InternalError("Invalid response for getChannelStats"); } ChannelStats result; - const ChannelStatsProto &stats = resp.channels()[0]; + const phaser::ChannelStatsProto stats = resp.channels(0); result.channel_name = stats.channel_name(); result.total_bytes = stats.total_bytes(); result.total_messages = stats.total_messages(); @@ -2239,22 +2264,22 @@ absl::StatusOr> ClientImpl::GetChannelStats() { return status; } - Request req; + phaser::Request req; [[maybe_unused]] auto cmd = req.mutable_get_channel_stats(); // Send request to server and wait for response. - Response response; + phaser::Response response; std::vector fds; if (absl::Status status = SendRequestReceiveResponse(req, response, fds); !status.ok()) { return status; } - auto &resp = response.get_channel_stats(); + const auto &resp = response.get_channel_stats(); if (!resp.error().empty()) { return absl::InternalError(resp.error()); } std::vector r; - for (auto &stats : resp.channels()) { + for (const auto &stats : resp.channels()) { ChannelStats result; result.channel_name = stats.channel_name(); result.total_bytes = stats.total_bytes(); @@ -2295,29 +2320,34 @@ absl::Status ClientImpl::ResizeChannel(PublisherImpl *publisher, return publisher->CreateOrAttachBuffers(Aligned(new_slot_size)); } -void ClientImpl::FillCreatePublisherRequest(CreatePublisherRequest *cmd, - const std::string &channel_name, - const PublisherOptions &opts, - int publisher_id) { +void ClientImpl::FillCreatePublisherRequest( + phaser::CreatePublisherRequest *cmd, const std::string &channel_name, + const PublisherOptions &opts, int publisher_id) { cmd->set_channel_name(channel_name); - cmd->set_slot_size(Aligned(opts.slot_size)); - cmd->set_num_slots(opts.num_slots); + // A server defined publisher's options hold the layout from the server, + // which it must not send back. + if (opts.ServerDefined()) { + cmd->set_server_defined(true); + } else { + cmd->set_slot_size(Aligned(opts.slot_size)); + cmd->set_num_slots(opts.num_slots); + cmd->set_is_fixed_size(opts.IsFixedSize()); + cmd->set_checksum_size(opts.ChecksumSize()); + cmd->set_metadata_size(opts.MetadataSize()); + cmd->set_use_split_buffers(opts.UseSplitBuffers()); + cmd->set_subscriber_queue_arena_size(opts.SubscriberQueueArenaSize()); + } cmd->set_is_local(opts.IsLocal()); cmd->set_is_reliable(opts.IsReliable()); cmd->set_is_bridge(opts.IsBridge()); cmd->set_for_tunnel(opts.ForTunnel()); - cmd->set_is_fixed_size(opts.IsFixedSize()); cmd->set_type(opts.Type()); cmd->set_mux(opts.Mux()); cmd->set_vchan_id(opts.VchanId()); cmd->set_notify_retirement(opts.notify_retirement); - cmd->set_checksum_size(opts.ChecksumSize()); - cmd->set_metadata_size(opts.MetadataSize()); cmd->set_publisher_id(publisher_id); cmd->set_max_publishers(opts.MaxPublishers()); - cmd->set_use_split_buffers(opts.UseSplitBuffers()); cmd->set_split_buffers_over_bridge(opts.SplitBuffersOverBridge()); - cmd->set_subscriber_queue_arena_size(opts.SubscriberQueueArenaSize()); cmd->set_process_id(static_cast(getpid())); cmd->set_max_outstanding_slot_leases(opts.MaxOutstandingSlotLeases()); // Align the cap the same way as the slot size so that a publisher asking for @@ -2327,7 +2357,7 @@ void ClientImpl::FillCreatePublisherRequest(CreatePublisherRequest *cmd, } void ClientImpl::ApplyPublisherResponseFds( - PublisherImpl *publisher, const CreatePublisherResponse &resp, + PublisherImpl *publisher, const phaser::CreatePublisherResponse &resp, std::vector &fds) { publisher->SetTriggerFd(std::move(fds[resp.pub_trigger_fd_index()])); publisher->SetPollFd(std::move(fds[resp.pub_poll_fd_index()])); @@ -2350,10 +2380,9 @@ void ClientImpl::ApplyPublisherResponseFds( publisher->SetNumUpdates(resp.num_sub_updates()); } -void ClientImpl::FillCreateSubscriberRequest(CreateSubscriberRequest *cmd, - const std::string &channel_name, - const SubscriberOptions &opts, - int subscriber_id) { +void ClientImpl::FillCreateSubscriberRequest( + phaser::CreateSubscriberRequest *cmd, const std::string &channel_name, + const SubscriberOptions &opts, int subscriber_id) { cmd->set_channel_name(channel_name); cmd->set_subscriber_id(subscriber_id); cmd->set_is_reliable(opts.IsReliable()); @@ -2371,7 +2400,7 @@ void ClientImpl::FillCreateSubscriberRequest(CreateSubscriberRequest *cmd, } void ClientImpl::ApplySubscriberResponseFds( - SubscriberImpl *subscriber, const CreateSubscriberResponse &resp, + SubscriberImpl *subscriber, const phaser::CreateSubscriberResponse &resp, std::vector &fds) { subscriber->SetTriggerFd(std::move(fds[resp.trigger_fd_index()])); subscriber->SetPollFd(std::move(fds[resp.poll_fd_index()])); @@ -2405,9 +2434,9 @@ absl::Status ClientImpl::Reconnect() { return status; } - Request init_req; + phaser::Request init_req; FillInitRequest(init_req.mutable_init(), name_); - Response init_resp; + phaser::Response init_resp; std::vector init_fds; init_fds.reserve(100); status = SendRequestReceiveResponse(init_req, init_resp, init_fds); @@ -2453,21 +2482,21 @@ bool ClientImpl::ShouldReconnect(const absl::Status &failure) const { } absl::Status ClientImpl::ReregisterPublisher(PublisherImpl *publisher) { - Request req; + phaser::Request req; FillCreatePublisherRequest(req.mutable_create_publisher(), publisher->Name(), publisher->options_, publisher->GetPublisherId()); req.mutable_create_publisher()->set_active_queue_publish_depth( publisher->ActiveQueuePublishDepth()); - Response resp; + phaser::Response resp; std::vector fds; fds.reserve(100); if (absl::Status status = SendRequestReceiveResponse(req, resp, fds); !status.ok()) { return status; } - auto &pub_resp = resp.create_publisher(); + const auto &pub_resp = resp.create_publisher(); if (!pub_resp.error().empty()) { return absl::InternalError(pub_resp.error()); } @@ -2477,19 +2506,19 @@ absl::Status ClientImpl::ReregisterPublisher(PublisherImpl *publisher) { } absl::Status ClientImpl::ReregisterSubscriber(SubscriberImpl *subscriber) { - Request req; + phaser::Request req; FillCreateSubscriberRequest(req.mutable_create_subscriber(), subscriber->Name(), subscriber->options_, subscriber->GetSubscriberId()); - Response resp; + phaser::Response resp; std::vector fds; fds.reserve(100); if (absl::Status status = SendRequestReceiveResponse(req, resp, fds); !status.ok()) { return status; } - auto &sub_resp = resp.create_subscriber(); + const auto &sub_resp = resp.create_subscriber(); if (!sub_resp.error().empty()) { return absl::InternalError(sub_resp.error()); } @@ -2499,21 +2528,20 @@ absl::Status ClientImpl::ReregisterSubscriber(SubscriberImpl *subscriber) { } absl::Status ClientImpl::SendRequestReceiveResponse( - const Request &req, Response &response, + const phaser::Request &req, phaser::Response &response, std::vector &fds, const std::vector &send_fds) { { - size_t msg_len = req.ByteSizeLong(); - std::vector send_msg(sizeof(int32_t) + msg_len); - char *sendbuf = send_msg.data() + sizeof(int32_t); - - if (!req.SerializeToArray(sendbuf, msg_len)) { - return absl::InternalError("Failed to serialize request"); + ServerWire wire; + absl::StatusOr msg_len = wire.Serialize(req); + if (!msg_len.ok()) { + return absl::InternalError(absl::StrFormat( + "Failed to serialize request: %s", msg_len.status().message())); } absl::StatusOr n = - socket_.SendMessage(sendbuf, msg_len, SocketContext()); + socket_.SendMessage(wire.Payload(), *msg_len, SocketContext()); if (!n.ok()) { socket_.Close(); if (ShouldReconnect(n.status())) { @@ -2547,10 +2575,12 @@ absl::Status ClientImpl::SendRequestReceiveResponse( } return recv_msg.status(); } - if (!response.ParseFromArray(recv_msg->data(), - static_cast(recv_msg->size()))) { + if (absl::Status status = ServerWire::Decode( + recv_msg->data(), recv_msg->size(), response); + !status.ok()) { socket_.Close(); - return absl::InternalError("Failed to parse response"); + return absl::InternalError( + absl::StrFormat("Failed to parse response: %s", status.message())); } absl::Status s = socket_.ReceiveFds(fds, SocketContext()); @@ -2562,17 +2592,18 @@ absl::Status ClientImpl::SendRequestReceiveResponse( } absl::Status ClientImpl::SendOneWayRequest( - const Request &req, const std::vector &fds) { - size_t msg_len = req.ByteSizeLong(); - std::vector send_msg(sizeof(int32_t) + msg_len); - char *sendbuf = send_msg.data() + sizeof(int32_t); - - if (!req.SerializeToArray(sendbuf, msg_len)) { - return absl::InternalError("Failed to serialize one-way request"); + const phaser::Request &req, + const std::vector &fds) { + ServerWire wire; + absl::StatusOr msg_len = wire.Serialize(req); + if (!msg_len.ok()) { + return absl::InternalError(absl::StrFormat( + "Failed to serialize one-way request: %s", + msg_len.status().message())); } absl::StatusOr n = - socket_.SendMessage(sendbuf, msg_len, SocketContext()); + socket_.SendMessage(wire.Payload(), *msg_len, SocketContext()); if (!n.ok()) { socket_.Close(); if (ShouldReconnect(n.status())) { @@ -2597,7 +2628,7 @@ absl::Status ClientImpl::SendOneWayRequest( absl::Status ClientImpl::RegisterClientBuffer(const ClientBufferHandleMetadata &metadata, const toolbelt::FileDescriptor *fd) { - Request req; + phaser::Request req; auto *register_buffer = req.mutable_register_client_buffer(); ToProto(metadata, register_buffer->mutable_metadata()); std::vector fds; @@ -2606,7 +2637,7 @@ ClientImpl::RegisterClientBuffer(const ClientBufferHandleMetadata &metadata, register_buffer->set_fd_index(0); fds.push_back(*fd); } - Response response; + phaser::Response response; std::vector response_fds; if (absl::Status status = SendRequestReceiveResponse(req, response, response_fds, fds); @@ -2622,13 +2653,13 @@ ClientImpl::RegisterClientBuffer(const ClientBufferHandleMetadata &metadata, absl::StatusOr> ClientImpl::GetClientBuffers(const std::string &channel_name, uint64_t session_id, uint32_t buffer_index) { - Request req; + phaser::Request req; auto *get = req.mutable_get_client_buffers(); get->set_channel_name(channel_name); get->set_session_id(session_id); get->set_buffer_index(buffer_index); - Response response; + phaser::Response response; std::vector fds; if (absl::Status status = SendRequestReceiveResponse(req, response, fds); !status.ok()) { @@ -2643,7 +2674,7 @@ ClientImpl::GetClientBuffers(const std::string &channel_name, } std::vector result; result.reserve(get_resp.metadata_size()); - for (int i = 0; i < get_resp.metadata_size(); ++i) { + for (size_t i = 0; i < get_resp.metadata_size(); ++i) { RegisteredClientBuffer buffer{ .metadata = FromProto(get_resp.metadata(i)), }; @@ -2659,7 +2690,7 @@ ClientImpl::GetClientBuffers(const std::string &channel_name, absl::Status ClientImpl::UnregisterClientBuffer(const std::string &channel_name, uint64_t session_id, uint32_t buffer_index) { - Request req; + phaser::Request req; auto *unregister = req.mutable_unregister_client_buffer(); unregister->set_channel_name(channel_name); unregister->set_session_id(session_id); diff --git a/client/client.h b/client/client.h index 55a74c90..14fadfd6 100644 --- a/client/client.h +++ b/client/client.h @@ -20,7 +20,7 @@ #include "common/async/wait.h" #include "common/channel.h" #include "common/client_buffer.h" -#include "proto/subspace.pb.h" +#include "proto/subspace.phaser.h" #include "toolbelt/fd.h" #include "toolbelt/logging.h" @@ -719,11 +719,11 @@ class ClientImpl : public std::enable_shared_from_this { absl::Status CheckConnected() const; absl::Status SendRequestReceiveResponse( - const Request &req, Response &response, + const phaser::Request &req, phaser::Response &response, std::vector &fds, const std::vector &send_fds = {}); absl::Status - SendOneWayRequest(const Request &req, + SendOneWayRequest(const phaser::Request &req, const std::vector &fds = {}); absl::Status RegisterClientBuffer(const ClientBufferHandleMetadata &metadata, @@ -741,19 +741,19 @@ class ClientImpl : public std::enable_shared_from_this { absl::Status ReregisterPublisher(details::PublisherImpl *publisher); absl::Status ReregisterSubscriber(details::SubscriberImpl *subscriber); - static void FillCreatePublisherRequest(CreatePublisherRequest *cmd, + static void FillCreatePublisherRequest(phaser::CreatePublisherRequest *cmd, const std::string &channel_name, const PublisherOptions &opts, int publisher_id); void ApplyPublisherResponseFds(details::PublisherImpl *publisher, - const CreatePublisherResponse &resp, + const phaser::CreatePublisherResponse &resp, std::vector &fds); - static void FillCreateSubscriberRequest(CreateSubscriberRequest *cmd, + static void FillCreateSubscriberRequest(phaser::CreateSubscriberRequest *cmd, const std::string &channel_name, const SubscriberOptions &opts, int subscriber_id); void ApplySubscriberResponseFds(details::SubscriberImpl *subscriber, - const CreateSubscriberResponse &resp, + const phaser::CreateSubscriberResponse &resp, std::vector &fds); bool CheckReload(details::ClientChannel *channel); diff --git a/client/client_channel.cc b/client/client_channel.cc index 4f478924..a829c2b6 100644 --- a/client/client_channel.cc +++ b/client/client_channel.cc @@ -1205,10 +1205,7 @@ void ClientChannel::TriggerRetirement(int slot_id) { // No retirement triggers, let's avoid locking the mutex. return; } - MessageSlot *slot = GetSlot(slot_id); - if ((slot->flags.load(std::memory_order_relaxed) & - kMessageIsActivation) != 0) { - // Don't retire activation messages. + if (!View().ReportsRetirement(slot_id)) { return; } std::unique_lock lock(retirement_lock_); diff --git a/client/client_channel.h b/client/client_channel.h index 5f3fca8f..8907007f 100644 --- a/client/client_channel.h +++ b/client/client_channel.h @@ -8,6 +8,7 @@ #include "client/options.h" #include "co/coroutine.h" #include "common/channel.h" +#include "common/dynamic_bitset.h" #include "common/client_buffer.h" #include "proto/subspace.pb.h" #include "toolbelt/clock.h" diff --git a/client/client_test.cc b/client/client_test.cc index aaf837d8..1794821e 100644 --- a/client/client_test.cc +++ b/client/client_test.cc @@ -66,6 +66,7 @@ using InetAddress = toolbelt::InetAddress; #ifdef __APPLE__ extern "C" subspace::PluginInterface *NOP_Create(); +extern "C" subspace::PluginInterface *SPLIT_BUFFER_FREE_TEST_Create(); #endif class ClientTest : public SubspaceTestBase {}; @@ -4276,6 +4277,54 @@ TEST_F(ClientTest, ReliablePublisher2) { machine.Run(); } +TEST_F(ClientTest, ReliableReadNewestLetsPublisherReuseSkippedSlots) { + subspace::Client client; + InitClient(client); + + constexpr int kNumSlots = 5; + absl::StatusOr sub = client.CreateSubscriber( + "rel_newest", subspace::SubscriberOptions().SetReliable(true)); + ASSERT_OK(sub); + absl::StatusOr pub = client.CreatePublisher( + "rel_newest", 32, kNumSlots, + subspace::PublisherOptions().SetReliable(true)); + ASSERT_OK(pub); + + auto publish = [&pub]() -> bool { + absl::StatusOr buffer = pub->GetMessageBuffer(); + EXPECT_TRUE(buffer.ok()) << buffer.status(); + if (!buffer.ok() || *buffer == nullptr) { + return false; + } + memcpy(*buffer, "foobar", 6); + absl::StatusOr published = pub->PublishMessage(6); + EXPECT_TRUE(published.ok()) << published.status(); + return true; + }; + + // The activation message and these fill the channel. + for (int i = 0; i < kNumSlots - 1; i++) { + ASSERT_TRUE(publish()) << "publish " << i; + } + ASSERT_FALSE(publish()); + + // Reading the newest message skips the others, so the subscriber has + // finished with every slot but the one it keeps until it reads the next + // message. + { + absl::StatusOr msg = + sub->ReadMessage(subspace::ReadMode::kReadNewest); + ASSERT_OK(msg); + ASSERT_EQ(6, msg->length); + } + + for (int i = 0; i < kNumSlots - 1; i++) { + ASSERT_TRUE(publish()) << "publish " << i; + } + // Now every slot holds a message the subscriber hasn't read. + ASSERT_FALSE(publish()); +} + TEST_F(ClientTest, ReliablePublisherActivation) { subspace::Client client; InitClient(client); @@ -9864,13 +9913,6 @@ TEST_F(PluginTest, HeartbeatPublishes) { class SplitBufferPluginTest : public ::testing::Test { public: static void SetUpTestSuite() { - // The plugin is a shared library. macOS tests link the server into the - // test binary and cannot dlopen it, so the only test in this suite skips. - // Starting a server here and tearing it down immediately races coroutine - // shutdown under AddressSanitizer. -#ifdef __APPLE__ - return; -#else printf("Starting Subspace server with split-buffer test plugin\n"); #if defined(__ANDROID__) char socket_name_template[] = "/data/local/tmp/subspaceXXXXXX"; // NOLINT @@ -9887,8 +9929,15 @@ class SplitBufferPluginTest : public ::testing::Test { /*local=*/true, server_pipe_[1], /*initial_ordinal=*/1, /*wait_for_clients=*/true); +#ifdef __APPLE__ + auto status = server_->LoadBuiltinPlugin( + "SPLIT_BUFFER_FREE_TEST", + std::unique_ptr( + SPLIT_BUFFER_FREE_TEST_Create())); +#else auto status = server_->LoadPlugin( "SPLIT_BUFFER_FREE_TEST", "plugins/split_buffer_free_test_plugin.so"); +#endif if (!status.ok()) { fprintf(stderr, "Failed to load split-buffer test plugin: %s\n", status.ToString().c_str()); @@ -9906,13 +9955,9 @@ class SplitBufferPluginTest : public ::testing::Test { char buf[8]; (void)::read(server_pipe_[0], buf, 8); -#endif } static void TearDownTestSuite() { -#ifdef __APPLE__ - return; -#else printf("Stopping Subspace server with split-buffer test plugin\n"); server_->Stop(); @@ -9921,7 +9966,6 @@ class SplitBufferPluginTest : public ::testing::Test { server_thread_.join(); server_->CleanupAfterSession(); (void)remove(socket_.c_str()); -#endif } void SetUp() override { signal(SIGPIPE, SIG_IGN); } @@ -9938,9 +9982,6 @@ class SplitBufferPluginTest : public ::testing::Test { }; TEST_F(SplitBufferPluginTest, ServerCleanupUsesPluginEndToEnd) { -#ifdef __APPLE__ - GTEST_SKIP() << "split-buffer cleanup test plugin is dlopen-only"; -#else std::string log_path = Socket() + ".split_buffer_free.log"; (void)remove(log_path.c_str()); ASSERT_EQ(0, setenv("SUBSPACE_SPLIT_BUFFER_FREE_TEST_LOG", log_path.c_str(), @@ -10008,7 +10049,6 @@ TEST_F(SplitBufferPluginTest, ServerCleanupUsesPluginEndToEnd) { } } EXPECT_EQ(3, freed_slots); -#endif } int main(int argc, char **argv) { diff --git a/client/options.h b/client/options.h index 0d34756c..9a11b261 100644 --- a/client/options.h +++ b/client/options.h @@ -99,6 +99,17 @@ struct PublisherOptions { } SlotSizeType MaxSlotSize() const { return max_slot_size; } + // The channel is in the server's static channel config, which defines its + // layout. Publishers on static channels must set this, and must leave the + // options that shape the channel's shared memory unset: slot size, number + // of slots, fixed size, checksum size, metadata size, subscriber queue + // arena size and split buffers. The publisher takes them from the server. + PublisherOptions &SetServerDefined(bool v) { + server_defined = v; + return *this; + } + bool ServerDefined() const { return server_defined; } + bool IsLocal() const { return local; } bool IsReliable() const { return reliable; } bool IsFixedSize() const { return fixed_size; } @@ -186,7 +197,7 @@ struct PublisherOptions { bool Checksum() const { return checksum; } // Number of bytes reserved for the checksum starting at the checksum - // field of MessagePrefix. Default is 4 (CRC32). + // field of MessagePrefix. 0, the default, means 4 (CRC32). PublisherOptions &SetChecksumSize(int32_t size) { checksum_size = size; return *this; @@ -280,6 +291,7 @@ struct PublisherOptions { bool bridge = false; bool for_tunnel = false; bool fixed_size = false; + bool server_defined = false; std::string type; bool activate = false; // If true, the channel will be activated even if unreliable. @@ -290,7 +302,7 @@ struct PublisherOptions { int32_t max_outstanding_slot_leases = 1; bool notify_retirement_on_forced_reuse = true; bool checksum = false; - int32_t checksum_size = 4; + int32_t checksum_size = 0; int32_t metadata_size = 0; // See SetPreferRetiredSlots() for description. diff --git a/client/publisher.cc b/client/publisher.cc index fd819ddc..ac367293 100644 --- a/client/publisher.cc +++ b/client/publisher.cc @@ -6,6 +6,8 @@ #include "client/checksum.h" #include "client_channel.h" #include "common/client_buffer.h" +#include "common/message_checksum.h" +#include "common/publish.h" #include "toolbelt/clock.h" #include #include @@ -16,13 +18,28 @@ namespace details { class SubscriberQueuePublishGuard { public: explicit SubscriberQueuePublishGuard(PublisherImpl &publisher) - : publisher_(publisher) { - publisher_.BeginSubscriberQueuePublish(); - } - ~SubscriberQueuePublishGuard() { publisher_.EndSubscriberQueuePublish(); } + : depth_(publisher), + scope_(publisher.GetAvailableSlotQueueIndexAddress(), + publisher.GetPublisherId()) {} + + const SubscriberQueuePublishScope &Scope() const { return scope_; } private: - PublisherImpl &publisher_; + class Depth { + public: + explicit Depth(PublisherImpl &publisher) : publisher_(publisher) { + publisher_.BeginQueuePublishDepth(); + } + ~Depth() { publisher_.EndQueuePublishDepth(); } + + private: + PublisherImpl &publisher_; + }; + + // The depth is counted before shared memory and released after it, so it + // is never less than this publisher's share of active_publishers. + Depth depth_; + SubscriberQueuePublishScope scope_; }; absl::Status PublisherImpl::CreateOrAttachBuffers(uint64_t final_slot_size) { @@ -200,6 +217,34 @@ void PublisherImpl::SetSlotToBiggestBuffer(MessageSlot *slot) { IncrementBufferRefs(new_buffer_index); } +// Other publishers can add buffers that this one hasn't mapped yet, so a +// claimed slot is checked before it's used. +class PublisherImpl::SearchHooks : public SlotSearchHooks { +public: + explicit SearchHooks(PublisherImpl &publisher) : publisher_(publisher) {} + + void BeforeAttempt() { publisher_.CheckReload(); } + bool UsableSlot(MessageSlot *slot) { + return publisher_.ValidateSlotBuffer(slot); + } + void Embargo(int slot_id) { publisher_.embargoed_slots_.Set(slot_id); } + bool Embargoed(int slot_id) const { + return publisher_.embargoed_slots_.IsSet(slot_id); + } + void AssignBuffer(MessageSlot *slot) { + publisher_.SetSlotToBiggestBuffer(slot); + } + MessagePrefix *Prefix(MessageSlot *slot) { return publisher_.Prefix(slot); } + void ForcedReuse(MessageSlot *slot) { + if (publisher_.NotifyRetirementOnForcedReuse()) { + publisher_.TriggerRetirement(slot->id); + } + } + +private: + PublisherImpl &publisher_; +}; + uint64_t PublisherImpl::RegisterLease(MessageSlot *slot) { if (slot == nullptr) { return 0; @@ -257,7 +302,8 @@ MessageSlot *PublisherImpl::ClaimRetiredSlot(int32_t slot_id) { return nullptr; } uint64_t expected = BuildRefsBitField( - slot->ordinal, (old_refs >> kVchanIdShift) & kVchanIdMask, + slot->ordinal.load(std::memory_order_relaxed), + (old_refs >> kVchanIdShift) & kVchanIdMask, (old_refs >> kPendingShift) & kPendingMask); if (!slot->refs.compare_exchange_strong( expected, kPubOwned | uint64_t(publisher_id_), @@ -265,17 +311,8 @@ MessageSlot *PublisherImpl::ClaimRetiredSlot(int32_t slot_id) { return nullptr; } RetiredSlots().Clear(slot_id); - slot->ordinal = 0; - slot->timestamp = 0; - slot->vchan_id = vchan_id_; - SetSlotToBiggestBuffer(slot); - MessagePrefix *prefix = Prefix(slot); - prefix->flags = 0; - prefix->vchan_id = vchan_id_; - ccb_->subscribers.Traverse([this, slot](int sub_id) { - GetAvailableSlots(sub_id).Clear(slot->id); - }); - slot->pending_subs.ClearAll(); + SearchHooks hooks(*this); + ResetClaimedSlot(View(), slot, vchan_id_, hooks); return slot; } @@ -299,9 +336,7 @@ bool PublisherImpl::ReleaseLeasedSlot(MessageSlot *slot) { slot->timestamp = 0; slot->refs.store(0, std::memory_order_release); slot->pending_subs.ClearAll(); - ccb_->subscribers.Traverse([this, slot](int sub_id) { - GetAvailableSlots(sub_id).Clear(slot->id); - }); + ForgetMessage(View(), slot); RetiredSlots().Set(slot->id); return true; } @@ -317,395 +352,25 @@ void PublisherImpl::RetirePublishedSlotImmediately(MessageSlot *slot) { } } -int PublisherImpl::FindRetiredSlotToReuse(bool oldest_first) { - // Normally a slot is only retired once every subscriber has seen and - // dropped it, so the retired pool stays small and taking the lowest-index - // slot keeps the publisher on the cache-hot working set that - // SetPreferRetiredSlots() exists to produce. - if (!oldest_first) { - return RetiredSlots().FindFirstSet(); - } - // With nothing subscribed every slot is retired the instant it is - // published, so the retired pool is the whole ring and the lowest-index - // slot is the one holding the oldest message. Reusing that slot puts it - // straight back at the front of the pool, so the publisher would overwrite - // it forever while the rest of the ring stayed frozen on the messages that - // happened to be published first, and a subscriber attaching later would - // read those rather than recent history. Recycling the oldest message - // rotates through the ring instead. - int oldest = -1; - uint64_t oldest_timestamp = -1ULL; - for (int i = 0; i < num_slots_; i++) { - if (!RetiredSlots().IsSet(i) || embargoed_slots_.IsSet(i)) { - continue; - } - const uint64_t timestamp = - ccb_->slots[i].timestamp.load(std::memory_order_relaxed); - if (timestamp < oldest_timestamp) { - oldest_timestamp = timestamp; - oldest = i; - } - } - return oldest; +SlotSearch PublisherImpl::SearchFor(int owner) const { + SlotSearch search; + search.owner = owner; + search.vchan_id = vchan_id_; + search.prefer_retired = options_.PreferRetiredSlots(); + search.reuse_retired = !ForTunnel(); + return search; } MessageSlot *PublisherImpl::FindFreeSlotUnreliable(int owner) { - int retries = num_slots_ * 1000; - MessageSlot *slot = nullptr; embargoed_slots_.ClearAll(); - constexpr int max_cas_retries = 1000; - int cas_retries = 0; - int retired_slot = -1; - int free_slot = -1; - // See PublisherOptions::SetPreferRetiredSlots() for the rationale. - // When it is set we prefer recycling a retired slot over - // pulling a fresh slot from the never-used pool. Both are equally - // valid for an unreliable publisher (a retired slot has been seen - // by every current subscriber and dropped), but a retired slot's - // pages are already cache-hot from the recent publish/consume - // cycle; a slot out of FreeSlots will demand-fault the kernel into - // allocating new physical pages on first write, which dominates - // wall-time for large payloads. In steady state the publisher - // cycles through a tiny working set of retired slots without ever - // consuming from FreeSlots, while still being able to burst into - // FreeSlots if the subscriber falls behind. - // - // None of that holds with nothing subscribed: a slot is then retired the - // moment it is published, so the publisher would take the slot it just - // wrote back out of the retired pool on the very next publish and never - // touch FreeSlots at all. The ring would hold one message no matter how - // deep it is configured, and there is no publish/consume cycle keeping - // those pages hot to pay for it either. Fill the ring from FreeSlots - // first while idle so that, together with the oldest-first recycling in - // FindRetiredSlotToReuse, it becomes a rolling window of recent messages - // for whoever attaches next. - for (;;) { - slot = nullptr; - retired_slot = -1; - free_slot = -1; - CheckReload(); - // Read the subscriber count off the reloaded CCB rather than caching it - // across the loop, so a subscriber attaching while we retry here is seen. - const bool no_subscribers = NumSubscribers(vchan_id_) == 0; - const bool retired_first = - options_.PreferRetiredSlots() && !no_subscribers; - bool tried_first = false; - if (retired_first) { - retired_slot = FindRetiredSlotToReuse(/*oldest_first=*/no_subscribers); - tried_first = (retired_slot != -1); - } else if (!ccb_->free_slots_exhausted.load(std::memory_order_relaxed)) { - free_slot = FreeSlots().FindFirstSet(); - tried_first = (free_slot != -1); - } - - if (tried_first && retired_first) { - // Claim the retired slot. - if (embargoed_slots_.IsSet(retired_slot)) { - continue; - } - if (!RetiredSlots().ClearWasSet(retired_slot)) { - retired_slot = -1; - continue; - } - slot = &ccb_->slots[retired_slot]; - } else if (tried_first && !retired_first) { - // Claim the free slot. - if (!FreeSlots().ClearWasSet(free_slot)) { - free_slot = -1; - continue; - } - slot = &ccb_->slots[free_slot]; - if (FreeSlots().IsEmpty()) { - ccb_->free_slots_exhausted.store(true, std::memory_order_relaxed); - } - } else if (retired_first && - !ccb_->free_slots_exhausted.load(std::memory_order_relaxed) && - (free_slot = FreeSlots().FindFirstSet()) != -1) { - // Retired pool empty, fall back to FreeSlots. - if (!FreeSlots().ClearWasSet(free_slot)) { - free_slot = -1; - continue; - } - slot = &ccb_->slots[free_slot]; - if (FreeSlots().IsEmpty()) { - ccb_->free_slots_exhausted.store(true, std::memory_order_relaxed); - } - } else if (!retired_first && - (retired_slot = FindRetiredSlotToReuse( - /*oldest_first=*/no_subscribers)) != -1) { - // FreeSlots exhausted (legacy order), fall back to RetiredSlots. - if (embargoed_slots_.IsSet(retired_slot)) { - continue; - } - if (!RetiredSlots().ClearWasSet(retired_slot)) { - retired_slot = -1; - continue; - } - slot = &ccb_->slots[retired_slot]; - } else { - // Find the slot with refs == 0 and the oldest message. - uint64_t earliest_timestamp = -1ULL; - for (int i = 0; i < num_slots_; i++) { - if (embargoed_slots_.IsSet(i)) { - continue; - } - MessageSlot *s = &ccb_->slots[i]; - uint64_t refs = s->refs.load(std::memory_order_relaxed); - if ((refs & kPubOwned) != 0) { - continue; - } - const uint64_t timestamp = - s->timestamp.load(std::memory_order_relaxed); - if ((refs & kRefsMask) == 0 && timestamp < earliest_timestamp) { - slot = s; - earliest_timestamp = timestamp; - } - } - } - - if (slot == nullptr) { - // We are guaranteed to find a slot, but let's not go into an infinite - // loop if something goes wrong. - if (retries-- == 0) { - return nullptr; - } - continue; - } - // Claim the slot by setting the kPubOwned bit and our owner. - uint64_t old_refs = slot->refs.load(std::memory_order_relaxed); - if (retired_slot != -1 && !RefsShowRetired(slot, old_refs)) { - // A stale retired bit, now cleared. The slot may hold the newest - // message. - continue; - } - uint64_t ref = kPubOwned | owner; - uint64_t expected = BuildRefsBitField( - slot->ordinal.load(std::memory_order_relaxed), - (old_refs >> kVchanIdShift) & kVchanIdMask, - (old_refs >> kPendingShift) & kPendingMask); - // Strong, not weak: a weak exchange may fail spuriously (on ARM's - // load/store-exclusive, a page fault between the two clears the - // reservation, which the first write to a slot's page always takes), - // and this loop does not retry the same slot. It goes back to selecting - // one, having already cleared this slot's free or retired bit, so a - // spurious failure leaks the slot from that pool. - if (slot->refs.compare_exchange_strong(expected, ref, - std::memory_order_acquire, - std::memory_order_relaxed)) { - if (!ValidateSlotBuffer(slot)) { - // No buffer for the slot. Embargo the slot so we don't see it again - // this loop and try again. - embargoed_slots_.Set(slot->id); - slot->refs.store(old_refs, std::memory_order_relaxed); - continue; - } - break; - } - if (++cas_retries >= max_cas_retries) { - if (retries-- == 0) { - return nullptr; - } - cas_retries = 0; - std::this_thread::yield(); - } - } - slot->ordinal.store(0, std::memory_order_relaxed); - slot->timestamp.store(0, std::memory_order_relaxed); - slot->vchan_id.store(vchan_id_, std::memory_order_relaxed); - SetSlotToBiggestBuffer(slot); - - MessagePrefix *p = Prefix(slot); - p->flags = 0; - p->vchan_id = vchan_id_; - - // We have a slot. Clear it in all the subscriber bitsets. - ccb_->subscribers.Traverse([this, slot](int sub_id) { - int vid = GetSubVchanId(sub_id); - const int slot_vchan_id = - slot->vchan_id.load(std::memory_order_relaxed); - if (vid != -1 && slot_vchan_id != -1 && vid != slot_vchan_id) { - return; - } - - GetAvailableSlots(sub_id).Clear(slot->id); - }); - - // If we took a slot that wasn't retired we must trigger the retirement fd. - // This happens when we recycle a slot that has not yet been seen by all - // subscribers. - if (free_slot == -1 && retired_slot == -1 && - NotifyRetirementOnForcedReuse()) { - TriggerRetirement(slot->id); - } - return slot; + SearchHooks hooks(*this); + return ClaimSlotUnreliable(View(), SearchFor(owner), hooks); } MessageSlot *PublisherImpl::FindFreeSlotReliable(int owner) { - int retries = num_slots_ * 1000; - MessageSlot *slot = nullptr; - int retired_slot = -1; - int free_slot = -1; embargoed_slots_.ClearAll(); - constexpr int max_cas_retries = 1000; - int cas_retries = 0; - for (;;) { - slot = nullptr; - retired_slot = -1; - free_slot = -1; - CheckReload(); - - // Put all free slots into the active_slots vector. - active_slots_.clear(); - if (!ccb_->free_slots_exhausted.load(std::memory_order_relaxed) && - (free_slot = FreeSlots().FindFirstSet()) != -1) { - // FindFirstSet uses relaxed loads; only the publisher whose - // ClearWasSet returns true actually owns this bit. See - // FindFreeSlotUnreliable for details. - if (!FreeSlots().ClearWasSet(free_slot)) { - free_slot = -1; - continue; - } - if (FreeSlots().IsEmpty()) { - ccb_->free_slots_exhausted.store(true, std::memory_order_relaxed); - } - MessageSlot *s = &ccb_->slots[free_slot]; - - ActiveSlot active_slot = { - s, s->ordinal.load(std::memory_order_relaxed), - s->timestamp.load(std::memory_order_relaxed)}; - active_slots_.push_back(active_slot); - } else if (!ForTunnel() && (retired_slot = RetiredSlots().FindFirstSet()) != -1) { - if (embargoed_slots_.IsSet(retired_slot)) { - continue; - } - if (!RetiredSlots().ClearWasSet(retired_slot)) { - retired_slot = -1; - continue; - } - MessageSlot *s = &ccb_->slots[retired_slot]; - if (!RefsShowRetired(s, s->refs.load(std::memory_order_relaxed))) { - // A stale retired bit, now cleared. - retired_slot = -1; - continue; - } - - ActiveSlot active_slot = { - s, s->ordinal.load(std::memory_order_relaxed), - s->timestamp.load(std::memory_order_relaxed)}; - active_slots_.push_back(active_slot); - } else { - for (int i = 0; i < NumSlots(); i++) { - if (embargoed_slots_.IsSet(i)) { - continue; - } - MessageSlot *s = &ccb_->slots[i]; - uint64_t refs = s->refs.load(std::memory_order_relaxed); - if ((refs & kPubOwned) == 0) { - ActiveSlot active_slot = { - s, s->ordinal.load(std::memory_order_relaxed), - s->timestamp.load(std::memory_order_relaxed)}; - active_slots_.push_back(active_slot); - } - } - } - - // Sort the active slots by timestamp, then slot id, which is the order a - // stable sort of the slot-ordered list gives. std::stable_sort is not - // used because libstdc++ allocates a temporary buffer for it. - std::sort(active_slots_.begin(), active_slots_.end(), - [](const ActiveSlot &a, const ActiveSlot &b) { - if (a.timestamp != b.timestamp) { - return a.timestamp < b.timestamp; - } - return a.slot->id < b.slot->id; - }); - - // Look for a slot with zero refs but don't go past one with non-zero - // reliable ref count. - const bool require_reliable_seen = GetCounters().num_reliable_subs != 0; - for (auto &s : active_slots_) { - uint64_t refs = s.slot->refs.load(std::memory_order_relaxed); - if (((refs >> kReliableRefCountShift) & kRefCountMask) != 0) { - break; - } - // Don't let unreliable subscribers create reliable-publisher - // backpressure. Only reliable subscribers require ordered visibility. - if (require_reliable_seen && s.ordinal != 0 && - (s.slot->flags.load(std::memory_order_relaxed) & - kMessageSeenByReliable) == 0) { - break; - } - // If the refs have no references we can claim it. - if ((refs & kRefsMask) == 0) { - slot = s.slot; - break; - } - } - if (slot == nullptr) { - return nullptr; - } - // Claim the slot by setting the kPubOwned bit. - uint64_t old_refs = slot->refs.load(std::memory_order_relaxed); - uint64_t ref = kPubOwned | owner; - uint64_t expected = BuildRefsBitField( - slot->ordinal.load(std::memory_order_relaxed), - (old_refs >> kVchanIdShift) & kVchanIdMask, - (old_refs >> kPendingShift) & kPendingMask); - // Strong, not weak: a weak exchange may fail spuriously (on ARM's - // load/store-exclusive, a page fault between the two clears the - // reservation, which the first write to a slot's page always takes), - // and this loop does not retry the same slot. It goes back to selecting - // one, having already cleared this slot's free or retired bit, so a - // spurious failure leaks the slot from that pool. - if (slot->refs.compare_exchange_strong(expected, ref, - std::memory_order_acquire, - std::memory_order_relaxed)) { - if (!ValidateSlotBuffer(slot)) { - // No buffer for the slot. Embargo the slot so we don't see it again - // this loop and try again. - embargoed_slots_.Set(slot->id); - slot->refs.store(old_refs, std::memory_order_relaxed); - continue; - } - RetiredSlots().Clear(slot->id); - break; - } - if (++cas_retries >= max_cas_retries) { - if (retries-- == 0) { - return nullptr; - } - cas_retries = 0; - std::this_thread::yield(); - } - } - slot->ordinal.store(0, std::memory_order_relaxed); - slot->timestamp.store(0, std::memory_order_relaxed); - slot->vchan_id.store(vchan_id_, std::memory_order_relaxed); - SetSlotToBiggestBuffer(slot); - - MessagePrefix *p = Prefix(slot); - p->flags = 0; - p->vchan_id = vchan_id_; - - // We have a slot. Clear it in all the subscriber bitsets. - ccb_->subscribers.Traverse([this, slot](int sub_id) { - int vid = GetSubVchanId(sub_id); - const int slot_vchan_id = - slot->vchan_id.load(std::memory_order_relaxed); - if (vid != -1 && slot_vchan_id != -1 && vid != slot_vchan_id) { - return; - } - GetAvailableSlots(sub_id).Clear(slot->id); - }); - - // If we took a slot that wasn't retired we must trigger the retirement fd. - // This happens when we recycle a slot that has not yet been seen by all - // subscribers. - if (free_slot == -1 && retired_slot == -1 && - NotifyRetirementOnForcedReuse()) { - TriggerRetirement(slot->id); - } - return slot; + SearchHooks hooks(*this); + return ClaimSlotReliable(View(), SearchFor(owner), GetCounters(), hooks); } Channel::PublishedMessage PublisherImpl::ActivateSlotAndGetAnother( @@ -715,12 +380,7 @@ Channel::PublishedMessage PublisherImpl::ActivateSlotAndGetAnother( void *buffer = GetBufferAddress(slot); MessagePrefix *prefix = Prefix(slot); - const int initial_vchan_id = - slot->vchan_id.load(std::memory_order_relaxed); - slot->ordinal.store(ccb_->ordinals.Next(initial_vchan_id), - std::memory_order_relaxed); - slot->timestamp.store(toolbelt::Now(), std::memory_order_relaxed); - slot->flags.store(0, std::memory_order_relaxed); + StampSlot(ccb_, slot, toolbelt::Now()); // Copy message parameters into message prefix in buffer. if (omit_prefix) { @@ -735,145 +395,42 @@ Channel::PublishedMessage PublisherImpl::ActivateSlotAndGetAnother( use_prefix_slot_id ? prefix->slot_id : slot->id, std::memory_order_relaxed); } else { - prefix->message_size = - slot->message_size.load(std::memory_order_relaxed); - prefix->ordinal = slot->ordinal.load(std::memory_order_relaxed); - prefix->timestamp = slot->timestamp.load(std::memory_order_relaxed); - prefix->vchan_id = slot->vchan_id.load(std::memory_order_relaxed); - prefix->checksum_size = static_cast(ChecksumSize()); - prefix->metadata_size = static_cast(MetadataSize()); - prefix->flags = 0; - prefix->slot_id = slot->id; - slot->bridged_slot_id.store(slot->id, std::memory_order_relaxed); - if (is_activation) { - prefix->SetIsActivation(); - slot->flags.fetch_or(kMessageIsActivation, std::memory_order_relaxed); - ccb_->activation_tracker.Activate( - slot->vchan_id.load(std::memory_order_relaxed)); - } + FillPrefix(ccb_, slot, prefix, ChecksumSize(), MetadataSize(), + is_activation); if (for_tunnel) { prefix->SetIsCrossMachine(); } if (options_.Checksum()) { prefix->SetHasChecksum(); - auto data = GetMessageChecksumData( - prefix, buffer, slot->message_size.load(std::memory_order_relaxed), - ChecksumSize(), MetadataSize()); - absl::Span cksum = GetChecksumSpan(prefix, ChecksumSize()); + const uint64_t message_size = + slot->message_size.load(std::memory_order_relaxed); if (checksum_callback_ != nullptr) { - checksum_callback_(data.Spans(), cksum); + auto data = GetMessageChecksumData(prefix, buffer, message_size, + ChecksumSize(), MetadataSize()); + checksum_callback_(data.Spans(), + GetChecksumSpan(prefix, ChecksumSize())); } else { - CalculateCRC32Checksum(data.Spans(), cksum); + SetMessageChecksum(prefix, buffer, message_size, ChecksumSize(), + MetadataSize()); } } } - const uint64_t published_ordinal = - slot->ordinal.load(std::memory_order_relaxed); - const uint64_t published_timestamp = - slot->timestamp.load(std::memory_order_relaxed); - const int32_t retirement_slot_id = - slot->bridged_slot_id.load(std::memory_order_relaxed); - const uint64_t cleanup_generation = - SubscriberCleanupGenerationFor(vchan_id_); - - // Tell all subscribers that the slot is available while it remains - // publisher-owned. The kPubOwned bit is the publication commit barrier: - // subscribers preserve the delivery record but cannot claim the slot, and - // server cleanup cannot retire it until all delivery records and accounting - // below are complete. - // - // The available-slot bitset remains authoritative when queue insertion - // fails or entries are evicted. A subscriber can disappear after - // TraverseSeqCst observes its bit, so recheck membership after setting the - // delivery bit. Either this recheck clears a stale write, or the server's - // later ClearWasSet observes it. - SubscriberQueuePublishGuard publish_guard(*this); - std::vector failed_queues; - // The slot is publisher-owned, so a departing subscriber cannot decrement - // pending yet. Record exactly the subscribers who receive this message. - slot->pending_subs.ClearAll(); - ccb_->subscribers.TraverseSeqCst([this, slot, &failed_queues](int sub_id) { - if (vchan_id_ != -1 && GetSubVchanId(sub_id) != -1 && - vchan_id_ != GetSubVchanId(sub_id)) { - return; - } - InPlaceAtomicBitset &available = GetAvailableSlots(sub_id); - available.Set(slot->id); - if (!ccb_->subscribers.IsSetSeqCst(sub_id)) { - available.Clear(slot->id); - // The subscriber ID may have been reused after the first membership - // check. Registration publishes membership before seeding this bit. If - // the new subscriber is already visible, restore the bit that the stale - // cleanup above may have cleared; otherwise its later seed handles the - // in-progress generation. - if (!ccb_->subscribers.IsSetSeqCst(sub_id)) { - return; - } - available.Set(slot->id); - } - slot->pending_subs.Set(sub_id); - - InPlaceSlotQueue *queue = GetAvailableSlotQueueAddress(sub_id); - if (queue != nullptr && - !queue->Push(slot->id, - slot->ordinal.load(std::memory_order_relaxed), - /*report_insertion_failure=*/false, - [this, &available](const QueuedSlot &evicted) { - return ForgetEvictedSlot( - available, evicted, - [this](int32_t retirement_slot_id) { - TriggerRetirement(retirement_slot_id); - }); - })) { - failed_queues.push_back(queue); - } - }); - - // Finish all slot and queue bookkeeping before making the slot claimable. - if (!is_activation) { - const uint64_t message_size = - slot->message_size.load(std::memory_order_relaxed); - ccb_->total_bytes += message_size; - if (message_size > ccb_->max_message_size) { - ccb_->max_message_size = message_size; - } - } - // Commit the publication. pending is the number of obligation bits still - // set: a subscriber who left during the traverse is not in the set, and a - // subscriber who joins afterwards is not either. A subscriber that observes - // the subsequent total_messages increment must also observe this release - // and all preceding delivery-record writes. - int pending = 0; - slot->pending_subs.Traverse([&pending](size_t) { pending++; }); - slot->refs.store(BuildRefsBitField(published_ordinal, vchan_id_, pending), - std::memory_order_release); - - // A subscriber that sees the failure recovers from its bitset, and must find - // this message there. Before the commit its snapshot would skip the slot, - // and it could leave recovery and read this publisher's next message first. - for (InPlaceSlotQueue *queue : failed_queues) { - queue->MarkInsertionFailure(); + PublishedSlot published; + { + SubscriberQueuePublishGuard publish_guard(*this); + published = CommitPublishedSlot(View(), slot, vchan_id_, is_activation, + publish_guard.Scope(), + [this](int32_t retirement_slot_id) { + TriggerRetirement(retirement_slot_id); + }); } - - // SubscriberImpl::NextSlot() uses total_messages as a version stamp for its - // cached active_slots_ snapshot. - ccb_->total_messages.fetch_add(1, std::memory_order_seq_cst); - - // A subscriber removed while the slot was publisher-owned could not - // decrement pending. Drop those obligations now that the message is - // committed. If that was the whole audience, retire the slot. A publish - // that never had subscribers is retired by the lease path instead, so the - // idle ring still fills from the free list. - ReleaseDepartedObligations(slot); - if (!is_activation && - SubscriberCleanupGenerationFor(vchan_id_) != cleanup_generation && - TryRetireSlot(slot)) { - TriggerRetirement(retirement_slot_id); + if (published.retired) { + TriggerRetirement(published.retirement_slot_id); } if (!acquire_next) { - return {nullptr, published_ordinal, published_timestamp}; + return {nullptr, published.ordinal, published.timestamp}; } // A reliable publisher doesn't allocate a slot until it is asked for. @@ -884,7 +441,7 @@ Channel::PublishedMessage PublisherImpl::ActivateSlotAndGetAnother( // Find a new slot.x MessageSlot *new_slot = FindFreeSlotUnreliable(owner); - return {new_slot, published_ordinal, published_timestamp}; + return {new_slot, published.ordinal, published.timestamp}; } } // namespace details diff --git a/client/publisher.h b/client/publisher.h index c775d9ad..a5404f03 100644 --- a/client/publisher.h +++ b/client/publisher.h @@ -6,6 +6,7 @@ #include "client/client_channel.h" #include "client/message.h" +#include "common/slot_search.h" #include @@ -40,12 +41,12 @@ class PublisherImpl : public ClientChannel { return options_.max_slot_size > 0 ? Aligned(options_.max_slot_size) : 0; } bool UsesSplitBuffers() const { return UseSplitBuffers(); } - void BeginSubscriberQueuePublish() { + // The number of publishes to subscriber queues in progress in this process. + // A re-registration reports it so the server can restore active_publishers. + void BeginQueuePublishDepth() { active_queue_publish_depth_.fetch_add(1, std::memory_order_seq_cst); - Channel::BeginSubscriberQueuePublish(publisher_id_); } - void EndSubscriberQueuePublish() { - Channel::EndSubscriberQueuePublish(publisher_id_); + void EndQueuePublishDepth() { active_queue_publish_depth_.fetch_sub(1, std::memory_order_seq_cst); } uint32_t ActiveQueuePublishDepth() const { @@ -58,14 +59,11 @@ class PublisherImpl : public ClientChannel { // triggerfd. void TriggerReliable() { trigger_.Trigger(); } + // Claim a slot for owner using the search in common/slot_search.h, which + // the ASIL client shares. MessageSlot *FindFreeSlotUnreliable(int owner); MessageSlot *FindFreeSlotReliable(int owner); - // Picks the retired slot to recycle next, or -1 if the retired pool holds - // no usable slot. Takes the lowest-index slot unless oldest_first, which - // is what an idle publisher wants; see the definition. - int FindRetiredSlotToReuse(bool oldest_first); - void SetSlotToBiggestBuffer(MessageSlot *slot); absl::Status CreateOrAttachBuffers(uint64_t slot_size); @@ -113,6 +111,10 @@ class PublisherImpl : public ClientChannel { private: friend class ::subspace::ClientImpl; friend class ::subspace::Publisher; + friend class SubscriberQueuePublishGuard; + + class SearchHooks; + SlotSearch SearchFor(int owner) const; bool IsPublisher() const override { return true; } bool IsBridge() const override { return options_.IsBridge(); } diff --git a/client/python/client.cc b/client/python/client.cc index a3006db8..3b00b62f 100644 --- a/client/python/client.cc +++ b/client/python/client.cc @@ -158,6 +158,13 @@ PYBIND11_MODULE(subspace, m) { "Set the number of slots for the publisher.") .def("num_slots", &PublisherOptions::NumSlots, "Get the number of slots for the publisher.") + .def("set_server_defined", &PublisherOptions::SetServerDefined, + "Set for a publisher on a static channel, whose layout the server " + "defines. The slot size, number of slots, fixed size, checksum " + "size, metadata size, subscriber queue arena size and split " + "buffers must then be left unset.") + .def("server_defined", &PublisherOptions::ServerDefined, + "Get whether the server defines the channel's layout.") .def("set_subscriber_queue_arena_size", &PublisherOptions::SetSubscriberQueueArenaSize, "Set the bytes reserved for packed subscriber queues. Queues are " diff --git a/client/subscriber.cc b/client/subscriber.cc index 01e32c42..335bdc0d 100644 --- a/client/subscriber.cc +++ b/client/subscriber.cc @@ -12,10 +12,7 @@ namespace subspace { namespace details { static bool ActiveSlotLess(const ActiveSlot &a, const ActiveSlot &b) { - if (a.timestamp != b.timestamp) { - return a.timestamp < b.timestamp; - } - return a.ordinal < b.ordinal; + return DeliveredBefore(a.timestamp, a.ordinal, b.timestamp, b.ordinal); } void SubscriberImpl::InitActiveMessages() { @@ -50,19 +47,9 @@ void SubscriberImpl::ResetDeliveryState() { queue_drain_tail_valid_ = false; } -// For non-virtual channels both the slots' vchan_id and the subsriber's -// are -1. This is the common case. -// For virtual subscribers, if the slot's vchan_id is -1 it means that -// the message was published direcly to the multiplexer and all subscribers -// should see it. - -// If the subscriber's vchan_id is -1 it means that the subscriber is on the -// multiplexer and should see all messages, regardless of the vchan_id static inline bool VirtualChannelIdMatch(MessageSlot *slot, int vchan_id) { - const int slot_vchan_id = - slot->vchan_id.load(std::memory_order_relaxed); - return vchan_id == -1 || slot_vchan_id == -1 || - slot_vchan_id == vchan_id; + return VirtualChannelsMatch(vchan_id, + slot->vchan_id.load(std::memory_order_relaxed)); } bool SubscriberImpl::AddActiveMessage([[maybe_unused]] MessageSlot *slot) { @@ -98,20 +85,22 @@ std::optional SubscriberImpl::NoteStuckRead(uint64_t now_ns, return stuck_seconds; } -void SubscriberImpl::RemoveActiveMessage(MessageSlot *slot) { - if (slot->sub_owners.ClearWasSet(subscriber_id_)) { - const uint64_t ordinal = slot->ordinal.load(std::memory_order_relaxed); - const int vchan_id = slot->vchan_id.load(std::memory_order_relaxed); - // bridged_slot_id is the slot the original publisher should hear about. - // A bridge copies that id into the slot when it republishes. - const int32_t retirement_slot_id = - slot->bridged_slot_id.load(std::memory_order_relaxed); - if (ReleaseSubscriberObligation(slot, subscriber_id_, IsReliable(), - /*drop_ref=*/true, ordinal, vchan_id) && - TryRetireSlot(slot)) { - TriggerRetirement(retirement_slot_id); - } +void SubscriberImpl::ReleaseSlotReference(MessageSlot *slot) { + const ReleasedMessage result = + ReleaseMessageReference(View(), slot, subscriber_id_, IsReliable()); + if (result.retired) { + // When a slot retires we want to use the slot id that was originally used + // for the message. If the message came in from a bridge we want to + // notify the original sender of the message, not the bridge publisher. + // + // The original slot id is in the message prefix and is copied into the + // slot when the bridge publisher publishes the message. + TriggerRetirement(result.retirement_slot_id); } +} + +void SubscriberImpl::RemoveActiveMessage(MessageSlot *slot) { + ReleaseSlotReference(slot); NoteActiveMessageReleased(); } @@ -347,44 +336,33 @@ void SubscriberImpl::ClaimSlot(MessageSlot *slot, int vchan_id, bool was_newest) { slot->sub_owners.Set(subscriber_id_); if (was_newest) { - InPlaceAtomicBitset &bits = GetAvailableSlots(subscriber_id_); + bool marked_seen = false; for (const ActiveSlot &snapshot : newest_snapshot_) { - bool pinned = snapshot.slot == slot; - if (!pinned) { - pinned = AtomicIncRefCount(snapshot.slot, IsReliable(), 1, - snapshot.ordinal, snapshot.vchan_id, false); + if (snapshot.slot == slot) { + continue; } - if (!pinned) { + if (!SkipUnreadMessage(View(), snapshot.slot, subscriber_id_, + IsReliable(), snapshot.ordinal, + snapshot.vchan_id)) { // The slot was recycled after the ReadNewest snapshot. Its current bit // belongs to the new generation and must remain set. continue; } - bits.Clear(snapshot.slot->id); RememberOrdinal(snapshot.ordinal, snapshot.vchan_id); - if (snapshot.slot != slot) { - AtomicIncRefCount(snapshot.slot, IsReliable(), -1, snapshot.ordinal, - snapshot.vchan_id, false); - } + marked_seen |= IsReliable(); } newest_snapshot_.clear(); - } else { - // Clear the bit in the subscriber bitset. - GetAvailableSlots(subscriber_id_).Clear(slot->id); + if (marked_seen) { + TriggerReliablePublishers(); + } } + GetAvailableSlots(subscriber_id_).Clear(slot->id); RememberOrdinal(slot->ordinal.load(std::memory_order_relaxed), vchan_id); - slot->flags.fetch_or(kMessageSeen, std::memory_order_relaxed); - if (IsReliable()) { - slot->flags.fetch_or(kMessageSeenByReliable, std::memory_order_relaxed); - } + MarkMessageSeen(slot, IsReliable()); } void SubscriberImpl::UnreadSlot(MessageSlot *slot) { - if (slot->sub_owners.ClearWasSet(subscriber_id_)) { - // A publisher evicting a queued slot can clear its bit just before the - // pop. Restore it while the slot is still held so that it stays unread. - GetAvailableSlots(subscriber_id_).Set(slot->id); - DecrementSlotRef(slot, false); - } + UnclaimMessageReference(View(), slot, subscriber_id_, IsReliable()); // A queued hint has already been consumed by NextSlot(). If delivery is // rejected (for example at max_active_messages), the slot remains unread in // the authoritative bitset but is no longer present in the queue. Stay on @@ -418,18 +396,8 @@ uint64_t SubscriberImpl::CollectVisibleSlots(InPlaceAtomicBitset &bits) { return; } MessageSlot *s = &ccb_->slots[i]; - // A publisher reusing the slot zeroes its ordinal and timestamp before - // its bit is cleared, and a claim with ordinal 0 matches whatever is - // published there next, so keep the slot only while it holds the - // message its refs were committed with. - const uint64_t refs = s->refs.load(std::memory_order_acquire); - const uint64_t ordinal = s->ordinal.load(std::memory_order_relaxed); - if ((refs & kPubOwned) != 0 || ordinal == 0 || - (ordinal & kOrdinalMask) != - ((refs >> kOrdinalShift) & kOrdinalMask)) { - return; - } - if (!VirtualChannelIdMatch(s, vchan_id_)) { + const uint64_t ordinal = CommittedOrdinal(s); + if (ordinal == 0 || !VirtualChannelIdMatch(s, vchan_id_)) { return; } if (s->buffer_index.load(std::memory_order_relaxed) == -1) { @@ -498,8 +466,7 @@ SubscriberImpl::FindNextQueuedSlot(uint64_t max_queue_position) { } if (queued.ordinal == 0 || (queued.ordinal & kOrdinalMask) != ref_ordinal || - (vchan_id_ != -1 && ref_vchan_id != -1 && - vchan_id_ != ref_vchan_id)) { + !VirtualChannelsMatch(vchan_id_, ref_vchan_id)) { continue; } if (ref_vchan_id != cached_vchan_id) { @@ -603,16 +570,11 @@ MessageSlot *SubscriberImpl::FindNextVisibleSlot(InPlaceAtomicBitset &bits, return; } MessageSlot *s = &ccb_->slots[i]; - const uint64_t refs = s->refs.load(std::memory_order_acquire); - if ((refs & kPubOwned) != 0) { - return; - } - const uint64_t ordinal = s->ordinal.load(std::memory_order_relaxed); + const uint64_t ordinal = CommittedOrdinal(s); const int slot_vchan_id = s->vchan_id.load(std::memory_order_relaxed); if (ordinal == 0 || ordinal > max_ordinal || - (vchan_id_ != -1 && slot_vchan_id != -1 && - slot_vchan_id != vchan_id_) || + !VirtualChannelsMatch(vchan_id_, slot_vchan_id) || s->buffer_index.load(std::memory_order_relaxed) == -1) { return; } @@ -1007,9 +969,8 @@ MessageSlot *SubscriberImpl::FindActiveSlotByTimestamp( continue; } MessageSlot *s = &ccb_->slots[i]; - uint64_t refs = s->refs.load(std::memory_order_acquire); - const uint64_t ordinal = s->ordinal.load(std::memory_order_relaxed); - if (ordinal != 0 && (refs & kPubOwned) == 0) { + const uint64_t ordinal = CommittedOrdinal(s); + if (ordinal != 0) { buffer.push_back( {s, ordinal, Prefix(s)->timestamp, s->vchan_id.load(std::memory_order_relaxed)}); @@ -1048,11 +1009,7 @@ MessageSlot *SubscriberImpl::FindActiveSlotByTimestamp( false); continue; } - it->slot->flags.fetch_or(kMessageSeen, std::memory_order_relaxed); - if (reliable) { - it->slot->flags.fetch_or(kMessageSeenByReliable, - std::memory_order_relaxed); - } + MarkMessageSeen(it->slot, reliable); it->slot->sub_owners.Set(owner); return it->slot; } diff --git a/client/subscriber.h b/client/subscriber.h index 1cccfaa5..48a74773 100644 --- a/client/subscriber.h +++ b/client/subscriber.h @@ -6,6 +6,7 @@ #include "client/client_channel.h" #include "client/message.h" #include "common/fast_ring_buffer.h" +#include "common/subscribe.h" #include #include #include @@ -173,11 +174,9 @@ class SubscriberImpl : public ClientChannel { /*drop_ref=*/true, ordinal, vchan_id)) { TryRetireSlot(slot); } - slot->flags.fetch_or(kMessageSeen, std::memory_order_relaxed); - if (IsReliable()) { - slot->flags.fetch_or(kMessageSeenByReliable, std::memory_order_relaxed); - } + MarkMessageSeen(slot, IsReliable()); } + void ReleaseSlotReference(MessageSlot *slot); // A subscriber wants to find a slot with a message in it. There are // two ways to get this: // NextSlot: gets the next slot in the active list diff --git a/cmake/apply_patch.cmake b/cmake/apply_patch.cmake new file mode 100644 index 00000000..7864a11a --- /dev/null +++ b/cmake/apply_patch.cmake @@ -0,0 +1,23 @@ +# Applies PATCH_FILE cleanly in the current directory, succeeding if it has +# already been applied in a previous configure run. +if(NOT DEFINED PATCH_FILE) + message(FATAL_ERROR "PATCH_FILE is required") +endif() + +execute_process( + COMMAND git apply --reverse --check "${PATCH_FILE}" + RESULT_VARIABLE already_applied + OUTPUT_QUIET + ERROR_QUIET +) +if(already_applied EQUAL 0) + return() +endif() + +execute_process( + COMMAND git apply "${PATCH_FILE}" + RESULT_VARIABLE apply_result +) +if(NOT apply_result EQUAL 0) + message(FATAL_ERROR "Failed to apply patch ${PATCH_FILE}") +endif() diff --git a/common/Android.bp b/common/Android.bp index 8652bcae..79fca843 100644 --- a/common/Android.bp +++ b/common/Android.bp @@ -2,6 +2,17 @@ // All Rights Reserved // See LICENSE file for licensing information. +cc_library_static { + name: "libsubspace_crc32", + defaults: ["subspace_defaults"], + srcs: [ + "crc32.cc", + "arm_crc32.S", + ], + export_include_dirs: ["."], + include_dirs: ["external/subspace"], +} + cc_library_static { name: "libsubspace_common", defaults: ["subspace_defaults"], @@ -17,6 +28,7 @@ cc_library_static { export_include_dirs: ["."], include_dirs: ["external/subspace"], static_libs: [ + "libsubspace_crc32", "libsubspace_proto", "libcoroutines", "libcpp_toolbelt", diff --git a/common/BUILD.bazel b/common/BUILD.bazel index 135507ed..34646e3b 100644 --- a/common/BUILD.bazel +++ b/common/BUILD.bazel @@ -38,8 +38,8 @@ cc_library( "syscall_shim.cc", ], hdrs = [ - "atomic_bitset.h", "channel.h", + "dynamic_bitset.h", "client_buffer.h", "fast_ring_buffer.h", "split_buffer.h", @@ -59,6 +59,8 @@ cc_library( ":max_channels_setting", ":max_buffers_setting", ":max_slot_owners_setting", + ":shm_layout", + ":shm_protocol", "//proto:subspace_cc_proto", "@abseil-cpp//absl/container:flat_hash_map", "@abseil-cpp//absl/status", @@ -71,6 +73,62 @@ cc_library( ], ) +# Shared-memory protocol types. Header only, and free of Abseil, so the ASIL +# client can include it. +cc_library( + name = "shm_layout", + hdrs = [ + "atomic_bitset.h", + "shm_layout.h", + ], + deps = [ + ":max_buffers_setting", + ":max_channels_setting", + ":max_slot_owners_setting", + ], +) + +# The slot, checksum and publish operations on a mapped channel, shared by the +# standard and ASIL clients. Header only and free of Abseil. +cc_library( + name = "shm_protocol", + hdrs = [ + "bitset_view.h", + "channel_view.h", + "message_checksum.h", + "publish.h", + "slot_search.h", + "subscribe.h", + ], + deps = [ + ":crc32", + ":shm_layout", + ], +) + +# Message checksum. No Abseil, so the ASIL client links the same function as +# the regular client. +cc_library( + name = "crc32", + srcs = [ + "arm_crc32.S", + "crc32.cc", + ], + hdrs = ["crc32.h"], +) + +# Server requests and responses as native Phaser payloads, shared by the +# standard and ASIL clients. +cc_library( + name = "server_wire", + hdrs = ["server_wire.h"], + deps = [ + "//proto:subspace_phaser", + "@abseil-cpp//absl/status", + "@abseil-cpp//absl/status:statusor", + ], +) + cc_test( name = "common_test", size = "small", diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index c97ab2d8..e7635eb4 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -28,6 +28,7 @@ target_link_libraries(subspace_common PUBLIC co subspace_proto protobuf::libprotobuf + subspace_crc32 ) if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND NOT ANDROID) @@ -36,6 +37,15 @@ elseif(ANDROID) target_link_libraries(subspace_common PUBLIC log) endif() +# The message checksum. Linked by the regular client and the ASIL client. +add_library(subspace_crc32 STATIC + crc32.cc + arm_crc32.S +) +set_source_files_properties(arm_crc32.S PROPERTIES + LANGUAGE ASM +) + # --- Async abstraction layer --- # Build-time selectable coroutine/networking backend (see context.h). The # SUBSPACE_CORO_BACKEND macro is set globally in the top-level CMakeLists.txt. diff --git a/client/arm_crc32.S b/common/arm_crc32.S similarity index 97% rename from client/arm_crc32.S rename to common/arm_crc32.S index 7edefc85..c861b235 100644 --- a/client/arm_crc32.S +++ b/common/arm_crc32.S @@ -1,4 +1,5 @@ // Copyright 2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/common/async/async_test.cc b/common/async/async_test.cc index 509e5f42..4f341e5f 100644 --- a/common/async/async_test.cc +++ b/common/async/async_test.cc @@ -1,6 +1,6 @@ // Copyright 2023-2026 David Allison // Asio backend support is Copyright 2026 Cruise LLC -// Tunnel support is Copyright 2026 General Motors LLC +// Tunnel support is Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/common/async/socket.cc b/common/async/socket.cc index 45840c12..406e4ec3 100644 --- a/common/async/socket.cc +++ b/common/async/socket.cc @@ -1,6 +1,6 @@ // Copyright 2023-2026 David Allison // Asio backend support is Copyright 2026 Cruise LLC -// Tunnel support is Copyright 2026 General Motors LLC +// Tunnel support is Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/common/async/socket.h b/common/async/socket.h index fbb4e8f1..5f8b71e4 100644 --- a/common/async/socket.h +++ b/common/async/socket.h @@ -1,6 +1,6 @@ // Copyright 2023-2026 David Allison // Asio backend support is Copyright 2026 Cruise LLC -// Tunnel support is Copyright 2026 General Motors LLC +// Tunnel support is Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/common/async/wait.cc b/common/async/wait.cc index 6d49efe8..ce79d9ed 100644 --- a/common/async/wait.cc +++ b/common/async/wait.cc @@ -1,6 +1,6 @@ // Copyright 2023-2026 David Allison // Asio backend support is Copyright 2026 Cruise LLC -// Tunnel support is Copyright 2026 General Motors LLC +// Tunnel support is Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/common/async/wait.h b/common/async/wait.h index ad9add47..f590127e 100644 --- a/common/async/wait.h +++ b/common/async/wait.h @@ -1,6 +1,6 @@ // Copyright 2023-2026 David Allison // Asio backend support is Copyright 2026 Cruise LLC -// Tunnel support is Copyright 2026 General Motors LLC +// Tunnel support is Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/common/atomic_bitset.h b/common/atomic_bitset.h index ad1d96f9..6df6824c 100644 --- a/common/atomic_bitset.h +++ b/common/atomic_bitset.h @@ -6,9 +6,7 @@ #include #include -#include #include -#include namespace subspace { @@ -129,7 +127,8 @@ template class AtomicBitSet { return -1; } - void Print(std::ostream &os, int start_bit = 0) const { + // Templates so this header needs neither iostream nor std::function. + template void Print(Stream &os, int start_bit = 0) const { // Print the bits with - between each group of 4. size_t start_word = start_bit / 64; start_bit %= 64; @@ -149,13 +148,14 @@ template class AtomicBitSet { // The callback is a template so a walk on the publish path does not allocate // a std::function. The visited bit is shifted out before the next load, so // the callback may clear that bit. - template - void Traverse(Func&& func) const { + template + void Traverse(Fn &&func, + std::memory_order order = std::memory_order_relaxed) const { for (size_t i = 0; i < BitsToWords(num_bits_); i++) { size_t shift = 0; size_t bit = i * 64; while (bit < num_bits_ && shift < 64) { - uint64_t word = bits_[i].load(std::memory_order_relaxed) >> shift; + uint64_t word = bits_[i].load(order) >> shift; size_t n = ffsll(word); if (n == 0) { break; @@ -167,22 +167,8 @@ template class AtomicBitSet { } } - template - void TraverseSeqCst(Func&& func) const { - for (size_t i = 0; i < BitsToWords(num_bits_); i++) { - size_t shift = 0; - size_t bit = i * 64; - while (bit < num_bits_ && shift < 64) { - uint64_t word = bits_[i].load(std::memory_order_seq_cst) >> shift; - size_t n = ffsll(word); - if (n == 0) { - break; - } - bit += n; - func(bit - 1); - shift += n; - } - } + template void TraverseSeqCst(Fn &&func) const { + Traverse(func, std::memory_order_seq_cst); } private: @@ -211,53 +197,4 @@ inline size_t SizeofAtomicBitSet(size_t size_in_bits) { sizeof(std::atomic) * BitsToWords(size_in_bits); } -class DynamicBitSet { -public: - DynamicBitSet() : num_bits_(0), bits_(0) {} - DynamicBitSet(size_t num_bits) - : num_bits_(num_bits), bits_(BitsToWords(num_bits), 0) {} - - void Resize(size_t num_bits) { - num_bits_ = num_bits; - bits_.resize(BitsToWords(num_bits), 0); - } - - void Set(size_t bit) { - size_t word = bit / 64; - size_t offset = bit % 64; - bits_[word] |= 1ULL << offset; - } - - void Clear(size_t bit) { - size_t word = bit / 64; - size_t offset = bit % 64; - bits_[word] &= ~(1ULL << offset); - } - - bool IsSet(size_t bit) const { - size_t word = bit / 64; - size_t offset = bit % 64; - return bits_[word] & (1ULL << offset); - } - - void ClearAll() { - for (size_t i = 0; i < BitsToWords(num_bits_); i++) { - bits_[i] = 0; - } - } - - bool IsEmpty() const { - for (size_t i = 0; i < BitsToWords(num_bits_); i++) { - if (bits_[i] != 0) { - return false; - } - } - return true; - } - -private: - size_t num_bits_; - std::vector bits_; -}; - } // namespace subspace diff --git a/common/bitset_view.h b/common/bitset_view.h new file mode 100644 index 00000000..96cfc623 --- /dev/null +++ b/common/bitset_view.h @@ -0,0 +1,100 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +#pragma once + +#include "common/atomic_bitset.h" + +#include +#include +#include + +namespace subspace { + +// A view of an AtomicBitSet in shared memory. The memory orders match +// AtomicBitSet. The bit count stored in shared memory is ignored; the view +// uses the count it is given, which comes from the server. +class BitsetView { +public: + BitsetView() = default; + BitsetView(void *bitset, int num_bits) + : words_(reinterpret_cast *>( + static_cast(bitset) + sizeof(InPlaceAtomicBitset))), + num_bits_(num_bits) {} + + void Set(int bit) { + words_[bit / 64].fetch_or(Mask(bit), std::memory_order_relaxed); + } + + void Clear(int bit) { + words_[bit / 64].fetch_and(~Mask(bit), std::memory_order_relaxed); + } + + bool SetWasClear(int bit) { + const uint64_t old = + words_[bit / 64].fetch_or(Mask(bit), std::memory_order_release); + return (old & Mask(bit)) == 0; + } + + bool ClearWasSet(int bit) { + const uint64_t old = + words_[bit / 64].fetch_and(~Mask(bit), std::memory_order_acquire); + return (old & Mask(bit)) != 0; + } + + bool IsSet(int bit) const { + return (words_[bit / 64].load(std::memory_order_relaxed) & Mask(bit)) != 0; + } + + bool IsSetSeqCst(int bit) const { + return (words_[bit / 64].load(std::memory_order_seq_cst) & Mask(bit)) != 0; + } + + bool IsEmpty() const { + for (int i = 0; i < NumWords(); i++) { + if (words_[i].load(std::memory_order_relaxed) != 0) { + return false; + } + } + return true; + } + + int FindFirstSet() const { + for (int i = 0; i < NumWords(); i++) { + const uint64_t word = words_[i].load(std::memory_order_relaxed); + if (word != 0) { + const int bit = i * 64 + __builtin_ctzll(word); + return bit < num_bits_ ? bit : -1; + } + } + return -1; + } + + // Calls fn(bit) for each set bit, loading each word once. + template + void Traverse(Fn &&fn, + std::memory_order order = std::memory_order_relaxed) const { + for (int i = 0; i < NumWords(); i++) { + uint64_t word = words_[i].load(order); + while (word != 0) { + const int bit = i * 64 + __builtin_ctzll(word); + if (bit >= num_bits_) { + return; + } + fn(bit); + word &= word - 1; + } + } + } + +private: + static uint64_t Mask(int bit) { return uint64_t{1} << (bit % 64); } + int NumWords() const { return static_cast(BitsToWords(num_bits_)); } + + std::atomic *words_ = nullptr; + int num_bits_ = 0; +}; + +} // namespace subspace diff --git a/common/channel.cc b/common/channel.cc index 8a14bef7..ec399862 100644 --- a/common/channel.cc +++ b/common/channel.cc @@ -221,108 +221,13 @@ std::string DecodedRefsBitField(uint64_t refs) { bool Channel::AtomicIncRefCount(MessageSlot *slot, bool reliable, int inc, uint64_t ordinal, int vchan_id, bool retire, std::function retire_callback) { - for (;;) { - uint64_t ref = slot->refs.load(std::memory_order_relaxed); - if ((ref & kPubOwned) != 0) { - return false; - } - ordinal &= kOrdinalMask; - // Not pub owned. If the ordinal has changed we can't get the slot because - // another message has been published into it. We need to try another slot. - // An ordinal of 0 in the refs field means that the slot was free and we can - // keep trying to use it. - uint64_t ref_ord = (ref >> kOrdinalShift) & kOrdinalMask; - if (ref_ord != 0 && ordinal != 0 && ref_ord != ordinal) { - return false; - } - int ref_vchan_id = (ref >> kVchanIdShift) & kVchanIdMask; - if (ref_vchan_id == (1 << kVchanIdSize) - 1) { - // This is a special case where the vchan_id is invalid. - ref_vchan_id = -1; - } - if (ref_ord != 0 && ordinal != 0 && ref_vchan_id != vchan_id) { - return false; - } - uint64_t new_refs = ref & kRefCountMask; - uint64_t new_reliable_refs = - (ref >> kReliableRefCountShift) & kRefCountMask; - if (inc < 0 && new_refs == 0) { - // Don't try to decrement the refs below zero. How can this happen? - return true; - } - - new_refs += inc; - if (reliable) { - new_reliable_refs += inc; - } - ref &= ~kPubOwned; - int pending = PendingCount(ref); - if (retire && pending > 0) { - pending--; - } - uint64_t new_ref = BuildRefsBitField(ref_ord, ref_vchan_id, pending) | - (new_reliable_refs << kReliableRefCountShift) | new_refs; - if (slot->refs.compare_exchange_weak(ref, new_ref, - std::memory_order_acq_rel, - std::memory_order_relaxed)) { - // A reference dropping to zero retires the slot once every subscriber - // who was delivered the message has finished with it. `retire` covers a - // caller that decremented pending without also dropping a reference. - if ((retire || inc < 0) && new_refs == 0 && new_reliable_refs == 0 && - pending == 0 && RetiredSlots().SetWasClear(slot->id)) { - if (retire_callback) { - retire_callback(); - } - } - return true; - } - // Another subscriber got there before us. Try again. - // Could also be a publisher, in which case the kPubOwned bit will be set. - } -} - -bool Channel::ForgetEvictedSlot( - InPlaceAtomicBitset &bits, const QueuedSlot &evicted, - std::function retire_callback) { - if (evicted.slot_id < 0 || evicted.slot_id >= NumSlots() || - evicted.ordinal == 0) { - return true; - } - MessageSlot *slot = &ccb_->slots[evicted.slot_id]; - const uint64_t refs = slot->refs.load(std::memory_order_acquire); - if ((refs & kPubOwned) != 0) { - return slot->ordinal.load(std::memory_order_relaxed) != evicted.ordinal; - } - if (((refs >> kOrdinalShift) & kOrdinalMask) != - (evicted.ordinal & kOrdinalMask)) { - return true; + bool retired = false; + const bool held = View().AtomicIncRefCount(slot, reliable, inc, ordinal, + vchan_id, retire, &retired); + if (retired && retire_callback) { + retire_callback(); } - int vchan_id = (refs >> kVchanIdShift) & kVchanIdMask; - if (vchan_id == kVchanIdMask) { - vchan_id = -1; - } - // While pinned the slot cannot be reused, so its bit cannot yet belong to a - // newer message. - if (!AtomicIncRefCount(slot, /*reliable=*/false, 1, evicted.ordinal, - vchan_id, false)) { - return true; - } - if (slot->ordinal.load(std::memory_order_relaxed) == evicted.ordinal) { - bits.Clear(slot->id); - } - const int32_t retirement_slot_id = - slot->bridged_slot_id.load(std::memory_order_relaxed); - // A subscriber that retires the slot while it is pinned leaves the ref count - // above zero, so the unpin has to retire it. - const uint64_t unpinned = - slot->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; - if ((unpinned & kRefCountMask) == 0 && - ((unpinned >> kReliableRefCountShift) & kRefCountMask) == 0 && - PendingCount(unpinned) == 0 && - RetiredSlots().SetWasClear(slot->id) && retire_callback) { - retire_callback(retirement_slot_id); - } - return true; + return held; } void MessageSlot::Dump(std::ostream &os) const { @@ -461,149 +366,6 @@ void Channel::CleanupSlots(int owner, bool reliable, bool is_pub, } } -bool Channel::ReleaseSubscriberObligation(MessageSlot *slot, int owner, - bool reliable, bool drop_ref, - uint64_t ordinal, int vchan_id) { - const uint64_t want_ord = ordinal & kOrdinalMask; - for (;;) { - uint64_t ref = slot->refs.load(std::memory_order_acquire); - if ((ref & kPubOwned) != 0) { - if (drop_ref) { - slot->sub_owners.Clear(owner); - } - return false; - } - const uint64_t ref_ord = (ref >> kOrdinalShift) & kOrdinalMask; - int ref_vchan_id = (ref >> kVchanIdShift) & kVchanIdMask; - if (ref_vchan_id == kVchanIdMask) { - ref_vchan_id = -1; - } - if (want_ord != 0 && ref_ord != 0 && ref_ord != want_ord) { - if (drop_ref) { - slot->sub_owners.Clear(owner); - } - return false; - } - if (want_ord != 0 && ref_ord != 0 && ref_vchan_id != vchan_id) { - if (drop_ref) { - slot->sub_owners.Clear(owner); - } - return false; - } - - // Take the obligation before the CAS so two releasers cannot both - // decrement. If the slot changes before the CAS lands, put the bit back - // when it now belongs to a committed newer message. - const bool owed = slot->pending_subs.ClearWasSet(owner); - const uint64_t again = slot->refs.load(std::memory_order_acquire); - if (again != ref) { - if (owed) { - // The bit we cleared may belong to the message a publisher is - // installing. Put it back. ClearAll during that publish wipes a - // restore that still belongs to the previous message, and a restore - // of a bit the publisher just set matches the count it recorded. - slot->pending_subs.Set(owner); - } - if (drop_ref && - ((again & kPubOwned) != 0 || - ((again >> kOrdinalShift) & kOrdinalMask) != want_ord)) { - slot->sub_owners.Clear(owner); - return false; - } - continue; - } - - uint64_t new_refs = ref & kRefCountMask; - uint64_t new_reliable_refs = - (ref >> kReliableRefCountShift) & kRefCountMask; - const bool drop_a_ref = drop_ref && new_refs != 0; - if (drop_a_ref) { - new_refs -= 1; - if (reliable && new_reliable_refs > 0) { - new_reliable_refs -= 1; - } - } - int pending = PendingCount(ref); - if (owed && pending > 0) { - pending--; - } - if (!owed && !drop_a_ref) { - if (drop_ref) { - slot->sub_owners.Clear(owner); - } - return true; - } - const uint64_t new_ref = BuildRefsBitField(ref_ord, ref_vchan_id, pending) | - (new_reliable_refs << kReliableRefCountShift) | - new_refs; - if (slot->refs.compare_exchange_weak(ref, new_ref, - std::memory_order_acq_rel, - std::memory_order_relaxed)) { - if (drop_ref) { - slot->sub_owners.Clear(owner); - } - return true; - } - if (owed) { - slot->pending_subs.Set(owner); - } - } -} - -void Channel::ReleaseDepartedObligations(MessageSlot *slot) { - const uint64_t ordinal = slot->ordinal.load(std::memory_order_relaxed); - const int vchan_id = slot->vchan_id.load(std::memory_order_relaxed); - if (ordinal == 0) { - return; - } - // Release during the walk. Traverse shifts past the bit it just reported - // before loading again, and the release only clears that subscriber's bit. - slot->pending_subs.Traverse([this, slot, ordinal, vchan_id](size_t sub_id) { - if (ccb_->subscribers.IsSet(sub_id)) { - // User IDs are first-fit and shared by every virtual channel on a mux. - // A subscriber removed while this slot was publisher-owned can be - // reissued to a virtual channel that was not delivered the message - // before this commit. That subscriber must not keep the countdown. - const int sub_vchan = ccb_->sub_vchan_ids[sub_id]; - if (sub_vchan == -1 || vchan_id == -1 || sub_vchan == vchan_id) { - return; - } - } - ReleaseSubscriberObligation(slot, static_cast(sub_id), - /*reliable=*/false, /*drop_ref=*/false, ordinal, - vchan_id); - }); -} - -bool Channel::RefsShowRetired(const MessageSlot *slot, uint64_t refs) const { - if ((refs & (kPubOwned | kRefsMask)) != 0) { - return false; - } - if (slot->ordinal.load(std::memory_order_relaxed) == 0) { - return true; - } - return PendingCount(refs) == 0; -} - -bool Channel::TryRetireSlot(MessageSlot *slot) { - if (slot->ordinal.load(std::memory_order_relaxed) == 0) { - return false; - } - - const uint64_t refs = slot->refs.load(std::memory_order_acquire); - if ((refs & kPubOwned) != 0) { - return false; - } - - const uint64_t ref_count = refs & kRefCountMask; - const uint64_t reliable_ref_count = - (refs >> kReliableRefCountShift) & kRefCountMask; - if (ref_count != 0 || reliable_ref_count != 0 || PendingCount(refs) != 0) { - return false; - } - return RetiredSlots().SetWasClear(slot->id); -} - #if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_POSIX absl::StatusOr Channel::PosixSharedMemoryName(const std::string &shadow_file) { diff --git a/common/channel.h b/common/channel.h index 5a0578fa..b89d9083 100644 --- a/common/channel.h +++ b/common/channel.h @@ -11,7 +11,10 @@ #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/types/span.h" -#include "common/atomic_bitset.h" +#include "common/channel_view.h" +#include "common/message_checksum.h" +#include "common/publish.h" +#include "common/shm_layout.h" #include "toolbelt/bitset.h" #include "toolbelt/fd.h" @@ -28,39 +31,6 @@ namespace subspace { -// Shared-memory backends. These name the *mechanism*, not the platform: -// POSIX - a named shm_open object plus a /tmp shadow file. -// LINUX - a named /dev/shm object (mapped by name, server-free). -// MEMFD - an anonymous memfd_create object (no name; the fd is passed to -// other clients via the server). This is a Linux mechanism that -// Android must use because it has no /dev/shm. -#define SUBSPACE_SHMEM_MODE_POSIX 1 -#define SUBSPACE_SHMEM_MODE_LINUX 2 -#define SUBSPACE_SHMEM_MODE_MEMFD 3 - -// The backend is chosen at build time. A build may either define -// SUBSPACE_SHMEM_MODE directly, or (on Linux) define SUBSPACE_LINUX_USE_MEMFD -// to opt the Linux build into the anonymous memfd backend instead of the -// default /dev/shm one. See //:linux_memfd (Bazel) and the -// SUBSPACE_LINUX_USE_MEMFD CMake option. -#ifndef SUBSPACE_SHMEM_MODE -#if defined(__ANDROID__) -// Android has no /dev/shm, so it always uses anonymous memfd shared memory. -#define SUBSPACE_SHMEM_MODE SUBSPACE_SHMEM_MODE_MEMFD -#elif defined(__linux__) -#if defined(SUBSPACE_LINUX_USE_MEMFD) -// Opt-in: anonymous memfd shared memory on Linux (no /dev/shm files). -#define SUBSPACE_SHMEM_MODE SUBSPACE_SHMEM_MODE_MEMFD -#else -// Default on Linux: named /dev/shm shared memory. -#define SUBSPACE_SHMEM_MODE SUBSPACE_SHMEM_MODE_LINUX -#endif -#else -// On other systems, including QNX and macOS, use a /tmp shadow file and -// regular shared memory. -#define SUBSPACE_SHMEM_MODE SUBSPACE_SHMEM_MODE_POSIX -#endif -#endif // Slot sizes are 64 bit internally: the wire protocol, the shared memory // layout and all of the buffer arithmetic use 64 bit values regardless of how @@ -79,587 +49,12 @@ using SlotSizeType = int64_t; using SlotSizeType = int32_t; #endif -// Flag for flags field in MessagePrefix. -constexpr int kMessageActivate = 1; // This is a reliable activation message. -constexpr int kMessageBridged = 2; // This message came from the bridge. -constexpr int kMessageHasChecksum = 4; // This message has a checksum. -constexpr int kMessageCrossMachine = 8; // This is a cross-machine (tunnel) message. - -// The only flags covered by the message checksum. The publisher sets these -// and they never change once the message is published. Every other bit, -// including kMessageBridged, kMessageCrossMachine and any bit a program sets -// itself, can be changed in transit without invalidating the checksum. -constexpr int64_t kChecksummedMessageFlags = - kMessageActivate | kMessageHasChecksum; - -// Maximum values for checksum_size and metadata_size (must fit in uint16_t). -constexpr int32_t kMaxChecksumSize = 0xFFFF; -constexpr int32_t kMaxMetadataSize = 0xFFFF; - -// This is stored immediately before the channel buffer in shared -// memory. It is transferred intact across the TCP bridges. -// 32 bytes long. -// -// Since this is used primarily for channel bridging, we -// include 4 bytes of padding at offset 0 so that that the -// Socket::SendMessage function has somewhere to put the -// length of the message and avoid 2 sends to the socket. -// -// Note that this precludes us mapping the subscriber's -// channel in read-only memory since the bridge will need -// to write to the padding address when it calls -// Socket::SendMessage. -// -// On the receiving end of the bridge, the padding is -// not received and will not be written to. -struct MessagePrefix { - int32_t padding; // Padding for Socket::SendMessage. - int32_t slot_id; // The slot ID this message is in. - uint64_t message_size; - uint64_t ordinal; - uint64_t timestamp; - int64_t flags; - int32_t vchan_id; - uint16_t checksum_size; - uint16_t metadata_size; - uint32_t checksum; - char padding3[64 - 52]; // Align to 64 bytes. - - bool IsActivation() const { return (flags & kMessageActivate) != 0; } - void SetIsActivation() { flags |= kMessageActivate; } - bool IsBridged() const { return (flags & kMessageBridged) != 0; } - void SetIsBridged() { flags |= kMessageBridged; } - bool HasChecksum() const { return (flags & kMessageHasChecksum) != 0; } - void SetHasChecksum() { flags |= kMessageHasChecksum; } - bool IsCrossMachine() const { return (flags & kMessageCrossMachine) != 0; } - void SetIsCrossMachine() { flags |= kMessageCrossMachine; } -}; - -static_assert(sizeof(MessagePrefix) == 64, - "MessagePrefix size is not 64 bytes"); - -// Flags for MessageSlot flags. -constexpr int kMessageSeen = 1; // Message has been seen by any subscriber. -constexpr int kMessageIsActivation = 2; // This is an activation message. -constexpr int kMessageSeenByReliable = - 4; // Message has been seen by a reliable subscriber. - -// Maximum channels in one server session. The system control block in -// shared memory is sized from this, so the server and every client must be -// built with the same value. A downstream Bazel module sets -// subspace.max_channels(count = N) in its root MODULE.bazel. Building this -// repo uses --//:max_channels=N, and CMake uses -DSUBSPACE_MAX_CHANNELS=N. -// N must be a positive multiple of 64 because channel ids are stored in a -// bitset of 64-bit words. -#ifndef SUBSPACE_MAX_CHANNELS -#define SUBSPACE_MAX_CHANNELS 1024 -#endif -constexpr int kMaxChannels = SUBSPACE_MAX_CHANNELS; -static_assert(kMaxChannels > 0 && kMaxChannels % 64 == 0, - "SUBSPACE_MAX_CHANNELS must be a positive multiple of 64"); - -// Maximum publishers plus subscribers per channel. This sizes CCB fields in -// shared memory, so the server and every client must be built with the same -// value. A downstream Bazel module sets subspace.max_slot_owners(count = N) -// in its root MODULE.bazel. Building this repo uses --//:max_slot_owners=N, -// and CMake uses -DSUBSPACE_MAX_SLOT_OWNERS=N. N must be a positive integer. -#ifndef SUBSPACE_MAX_SLOT_OWNERS -#define SUBSPACE_MAX_SLOT_OWNERS 1024 -#endif -constexpr int kMaxSlotOwners = SUBSPACE_MAX_SLOT_OWNERS; -static_assert(kMaxSlotOwners > 0, "SUBSPACE_MAX_SLOT_OWNERS must be positive"); -// Default per-subscriber queue depth used whenever the publisher provisions a -// non-empty arena and the subscriber does not request an override. -constexpr int kDefaultSubscriberQueueSize = 16; -// Standard packed arena size for callers that opt into subscriber queues. This -// fits 100 default-sized (16-entry) queues. Publisher options default to zero, -// which keeps the available-slot bitset path and omits the queue arena. -constexpr uint64_t kDefaultSubscriberQueueArenaSize = 64'000; -constexpr size_t kDefaultMaxAvailableSlotQueueCapacity = 1024; -constexpr size_t kMaxSlotQueueCasAttempts = 64; -// Bumped when the slot retirement field became a publish-time countdown and -// MessageSlot gained the per-subscriber obligation bitset. Older clients must -// not map a version 6 control block. -constexpr uint32_t kChannelControlBlockVersion = 6; -constexpr size_t kMaxChannelControlBlockSize = 1ULL << 30; - -// This limits the number of virtual channels. Each virtual channel -// needs its own ordinal counter in the CCB (8 bytes each). -// This is stored in the refs field as a 10-bit value. If all bits are set -// this indicates -1 (no vchan_id). -constexpr int kMaxVchanId = 1023; - -// Max length of a channel name in shared memory. A name longer -// this this will be truncated but the full name will be available -// in process memory. -constexpr size_t kMaxChannelName = 64; - -// Maximum distinct shared-memory payload segments tracked in the BCB (refs and -// sizes tables). Each slot-size resize can add another segment until -// ccb_->num_buffers reaches this limit. A downstream Bazel module sets -// subspace.max_buffers(count = N) in its root MODULE.bazel. Building this -// repo uses --//:max_buffers=N, and CMake uses -DSUBSPACE_MAX_BUFFERS=N. N -// must be a positive integer. The default (341) yields a 4096-byte BCB on -// typical platforms (4-byte atomic int32 refs plus 8-byte atomic uint64 sizes). -#ifndef SUBSPACE_MAX_BUFFERS -#define SUBSPACE_MAX_BUFFERS 341 -#endif -constexpr size_t kMaxBuffers = SUBSPACE_MAX_BUFFERS; -static_assert(kMaxBuffers > 0, "SUBSPACE_MAX_BUFFERS must be positive"); - -// Ref count bits. -constexpr uint64_t kRefCountMask = 0x3ff; -constexpr uint64_t kRefCountShift = 10; -constexpr uint64_t kReliableRefCountShift = 10; -constexpr uint64_t kPubOwned = 1ULL << 63; -constexpr uint64_t kRefsMask = (1ULL << 20) - 1; // 20 bits -constexpr uint64_t kReliableRefsMask = ((1ULL << 10) - 1) - << kReliableRefCountShift; -// Subscribers who were delivered this message and have not yet finished with -// it. Set to that count when the message is published and decremented as each -// of them releases the slot or disconnects. The slot is retired at zero. -// A subscriber who joins later is not counted, so they cannot hold the slot. -constexpr uint64_t kPendingSize = 10; -constexpr uint64_t kPendingMask = (1ULL << kPendingSize) - 1; -constexpr uint64_t kPendingShift = 20; - -// Virtual channel ID is just above the pending count and is 10 bits long. -constexpr uint64_t kVchanIdShift = kPendingShift + kPendingSize; -constexpr uint64_t kVchanIdSize = 10; -constexpr uint64_t kVchanIdMask = (1ULL << kVchanIdSize) - 1; - -// We put the bottom 23 bits of the ordinal just above the -// vchan ID field. This is to ensure that a publisher -// hasn't published another message in the slot before a subscriber -// increments the ref count. -constexpr uint64_t kOrdinalSize = 23; -constexpr uint64_t kOrdinalMask = (1ULL << kOrdinalSize) - 1; -constexpr uint64_t kOrdinalShift = 40; - -// Combine an ordinal and a vchan_id into a single 64 bit field, shifted -// to the correct position for the refs field. -inline int PendingCount(uint64_t refs) { - return static_cast((refs >> kPendingShift) & kPendingMask); -} - -inline uint64_t BuildRefsBitField(uint64_t ordinal, int vchan_id, int pending) { - return ((ordinal & kOrdinalMask) << kOrdinalShift) | - (ordinal == 0 ? 0 : ((vchan_id & kVchanIdMask) << kVchanIdShift)) | - ((static_cast(pending) & kPendingMask) << kPendingShift); -} std::string DecodedRefsBitField(uint64_t refs); -// Aligned to given power of 2. -template constexpr int64_t Aligned(int64_t v) { - return (v + (alignment - 1)) & ~(alignment - 1); -} void *MapMemory(int fd, size_t size, int prot, const char *purpose); void UnmapMemory(void *p, size_t size, const char *purpose); -// This is a global (to a server) structure in shared memory that holds -// counts for the number of updates to publishers and subscribers on -// that server. The server updates these counts when a publisher or -// subscriber is created or deleted. The purpose is to allow a client -// to check if it needs to update its local information about the -// channel by contacting the server. Things such as trigger file -// descriptors are distributed by the server to clients. -// -// This is in shared memory, but it is only ever written by the -// server. -struct ChannelCounters { - uint16_t num_pub_updates; // Number of updates to publishers. - uint16_t num_sub_updates; // Number of updates to subscribers. - uint16_t num_pubs; // Current number of publishers. - uint16_t num_reliable_pubs; // Current number of reliable publishers. - uint16_t num_subs; // Current number of subscribers. - uint16_t num_reliable_subs; // Current number of reliable subscribers. - uint16_t num_resizes; // Number of times channel has been resized. -}; - -struct SystemControlBlock { - ChannelCounters counters[kMaxChannels]; -}; - -// This is the meta data for a slot. -struct MessageSlot { - std::atomic refs; // Number of subscribers referring to this slot. - std::atomic ordinal; // Message ordinal held currently in slot. - std::atomic message_size; // Size of message held in slot. - int32_t id; // Unique ID for slot (0...num_slots-1). - std::atomic buffer_index; // Index of buffer. - std::atomic vchan_id; // Virtual channel ID. - AtomicBitSet sub_owners; // One bit per subscriber. - std::atomic timestamp; // Timestamp of message. - std::atomic flags; - std::atomic - bridged_slot_id; // Slot ID of other side of bridge. - // Subscribers still obliged to decrement the pending count for the message - // currently in this slot. Empty while a publisher owns the slot. - AtomicBitSet pending_subs; - - void Dump(std::ostream &os) const; -}; -static_assert(offsetof(MessageSlot, refs) == 0); -static_assert(offsetof(MessageSlot, ordinal) == 8); -static_assert(offsetof(MessageSlot, message_size) == 16); -static_assert(offsetof(MessageSlot, id) == 24); -static_assert(offsetof(MessageSlot, buffer_index) == 28); -static_assert(offsetof(MessageSlot, vchan_id) == 30); -static_assert(offsetof(MessageSlot, sub_owners) == 32); -static_assert(offsetof(MessageSlot, timestamp) == - offsetof(MessageSlot, sub_owners) + - sizeof(AtomicBitSet)); -static_assert(offsetof(MessageSlot, flags) == - offsetof(MessageSlot, timestamp) + sizeof(std::atomic)); -static_assert(offsetof(MessageSlot, bridged_slot_id) == - offsetof(MessageSlot, flags) + sizeof(std::atomic)); -static_assert(offsetof(MessageSlot, pending_subs) == - ((offsetof(MessageSlot, bridged_slot_id) + - sizeof(std::atomic) + 7) & - ~size_t{7})); -static_assert(sizeof(MessageSlot) == - offsetof(MessageSlot, pending_subs) + - sizeof(AtomicBitSet)); -// 1024 owners: the original 184-byte slot plus one 136-byte obligation bitset -// placed on an 8-byte boundary (4 bytes of padding after bridged_slot_id). -static_assert(kMaxSlotOwners != 1024 || sizeof(MessageSlot) == 320); - -struct ActiveSlot { - MessageSlot *slot; - uint64_t ordinal; - uint64_t timestamp; - int vchan_id; -}; - -struct QueuedSlot { - int32_t slot_id; - uint64_t ordinal; -}; - -struct SlotQueueEntry { - // Sequence number used to publish an entry after its payload is written and - // to mark it reusable after the consumer has popped it. - std::atomic sequence; - std::atomic ordinal; - std::atomic slot_id; -}; -static_assert(sizeof(SlotQueueEntry) == 24); -static_assert(offsetof(SlotQueueEntry, sequence) == 0); -static_assert(offsetof(SlotQueueEntry, ordinal) == 8); -static_assert(offsetof(SlotQueueEntry, slot_id) == 16); - -// A bounded MPSC queue stored in shared memory after the available-slots -// bitsets. Publishers push slot IDs as they publish; the single owning -// subscriber pops them to avoid scanning its bitset. For unreliable subscribers -// this queue is the hot-path source of truth; the bitset is still maintained for -// reliable mode and diagnostics while the queue path is proven out. -class InPlaceSlotQueue { -public: - InPlaceSlotQueue(size_t capacity, bool drop_oldest = true) { - Init(capacity, drop_oldest); - } - - // Initialize queue metadata and mark every ring entry as free. `capacity` - // is the number of SlotQueueEntry objects laid out immediately after this - // header in shared memory. - void Init(size_t capacity, bool drop_oldest = true) { - capacity_ = capacity; - head_.store(0, std::memory_order_relaxed); - tail_.store(0, std::memory_order_relaxed); - overflow_count_.store(0, std::memory_order_relaxed); - insertion_failed_.store(false, std::memory_order_relaxed); - drop_oldest_ = drop_oldest; - for (size_t i = 0; i < capacity_; i++) { - entries_[i].sequence.store(i, std::memory_order_relaxed); - entries_[i].ordinal.store(0, std::memory_order_relaxed); - entries_[i].slot_id.store(-1, std::memory_order_relaxed); - } - } - - size_t Capacity() const { return capacity_; } - bool DropsOldest() const { return drop_oldest_; } - uint64_t Head() const { return head_.load(std::memory_order_acquire); } - uint64_t Tail() const { return tail_.load(std::memory_order_acquire); } - - // Push a published slot. Multiple publishers may call this concurrently. - // If an explicit queue is full, evict its oldest hint and enqueue the newest - // one. An inherited queue instead rejects the hint so its subscriber recovers - // every unread ordinal from the authoritative bitset. - bool Push(int32_t slot_id, uint64_t ordinal, - bool report_insertion_failure = true) { - return Push(slot_id, ordinal, report_insertion_failure, - [](const QueuedSlot &) { return true; }); - } - - // An evicted message is dropped for the subscriber, but its bit in the - // subscriber's bitset would otherwise let it be read after newer messages. - // `forget` is called with the oldest hint before it leaves the queue so the - // caller can clear that bit. If it returns false the hint stays and the push - // fails. - template - bool Push(int32_t slot_id, uint64_t ordinal, bool report_insertion_failure, - Forget &&forget) { - if (capacity_ == 0) { - if (report_insertion_failure) { - MarkInsertionFailure(); - } - return false; - } - - SlotQueueEntry *entry = nullptr; - uint64_t tail = tail_.load(std::memory_order_relaxed); - for (size_t attempt = 0; attempt < kMaxSlotQueueCasAttempts; ++attempt) { - const uint64_t head = head_.load(std::memory_order_acquire); - if (tail - head >= capacity_) { - // Inherited queues preserve legacy no-drop delivery through the - // authoritative bitset. Do not expose a newer queue entry before the - // subscriber observes the fallback signal. - if (!drop_oldest_) { - if (report_insertion_failure) { - MarkInsertionFailure(); - } - return false; - } - if (!EvictFront(forget)) { - if (report_insertion_failure) { - MarkInsertionFailure(); - } - return false; - } - overflow_count_.fetch_add(1, std::memory_order_release); - tail = tail_.load(std::memory_order_relaxed); - continue; - } - SlotQueueEntry &candidate = entries_[tail % capacity_]; - // A consumer publishes the reusable sequence after advancing head_. It - // may be paused or terminated between those operations. Do not reserve - // the entry until it is reusable: reserving first would force this - // producer to wait indefinitely for that consumer. - if (candidate.sequence.load(std::memory_order_acquire) != tail) { - if (report_insertion_failure) { - MarkInsertionFailure(); - } - return false; - } - if (tail_.compare_exchange_strong(tail, tail + 1, - std::memory_order_acq_rel, - std::memory_order_relaxed)) { - entry = &candidate; - break; - } - } - if (entry == nullptr) { - if (report_insertion_failure) { - MarkInsertionFailure(); - } - return false; - } - - entry->slot_id.store(slot_id, std::memory_order_relaxed); - entry->ordinal.store(ordinal, std::memory_order_relaxed); - entry->sequence.store(tail + 1, std::memory_order_release); - return true; - } - - void MarkInsertionFailure() { - insertion_failed_.store(true, std::memory_order_release); - } - - // Read the oldest queued slot without consuming it. This lets poll-driven - // subscribers stop at the end of a stable drain snapshot without losing the - // first newer message. `position` identifies the entry for PopAt(). - bool TryPeek(QueuedSlot &slot, uint64_t &position) { - if (capacity_ == 0) { - return false; - } - - const uint64_t head = head_.load(std::memory_order_acquire); - SlotQueueEntry &entry = entries_[head % capacity_]; - if (entry.sequence.load(std::memory_order_acquire) != head + 1) { - return false; - } - - QueuedSlot candidate = { - entry.slot_id.load(std::memory_order_relaxed), - entry.ordinal.load(std::memory_order_relaxed), - }; - if (entry.sequence.load(std::memory_order_acquire) != head + 1) { - return false; - } - slot = candidate; - position = head; - return true; - } - - // Consume the entry that TryPeek() returned at `position`. This fails if a - // producer evicted it first, rather than consuming the entry behind it. - bool PopAt(uint64_t position) { - if (capacity_ == 0) { - return false; - } - uint64_t head = position; - if (!head_.compare_exchange_strong(head, position + 1, - std::memory_order_acq_rel, - std::memory_order_relaxed)) { - return false; - } - entries_[position % capacity_].sequence.store(position + capacity_, - std::memory_order_release); - return true; - } - - // Drop the oldest queued slot. The subscriber uses this to discard queued - // hints it no longer needs. - bool DropFront() { - if (capacity_ == 0) { - return false; - } - - uint64_t head = head_.load(std::memory_order_relaxed); - for (size_t attempt = 0; attempt < kMaxSlotQueueCasAttempts; ++attempt) { - SlotQueueEntry &entry = entries_[head % capacity_]; - if (entry.sequence.load(std::memory_order_acquire) != head + 1) { - return false; - } - if (head_.compare_exchange_weak(head, head + 1, - std::memory_order_acq_rel, - std::memory_order_relaxed)) { - entry.sequence.store(head + capacity_, std::memory_order_release); - return true; - } - } - return false; - } - - // Discard a bounded snapshot of queued hints. The available-slot bitset - // remains authoritative, so subscribers use this after switching to bitset - // recovery following queue overflow or insertion failure. - void DiscardAll() { - for (size_t i = 0; i < capacity_; ++i) { - if (!DropFront()) { - return; - } - } - } - - // Pop one slot for the owning subscriber. There is exactly one consumer per - // queue, but producers may advance head_ to evict on overflow, so the - // consumer claims the front entry with a CAS. - bool TryPop(QueuedSlot &slot) { - if (capacity_ == 0) { - return false; - } - - uint64_t head = head_.load(std::memory_order_relaxed); - for (size_t attempt = 0; attempt < kMaxSlotQueueCasAttempts; ++attempt) { - SlotQueueEntry &entry = entries_[head % capacity_]; - if (entry.sequence.load(std::memory_order_acquire) != head + 1) { - return false; - } - QueuedSlot candidate = { - entry.slot_id.load(std::memory_order_relaxed), - entry.ordinal.load(std::memory_order_relaxed), - }; - if (head_.compare_exchange_weak(head, head + 1, - std::memory_order_acq_rel, - std::memory_order_relaxed)) { - slot = candidate; - entry.sequence.store(head + capacity_, std::memory_order_release); - return true; - } - } - return false; - } - - // Return and clear the number of older queued slots evicted to preserve the - // newest data. - uint32_t ConsumeOverflow() { - return overflow_count_.exchange(0, std::memory_order_acq_rel); - } - - uint32_t OverflowCount() const { - return overflow_count_.load(std::memory_order_acquire); - } - - bool ConsumeInsertionFailure() { - return insertion_failed_.exchange(false, std::memory_order_acq_rel); - } - - bool InsertionFailed() const { - return insertion_failed_.load(std::memory_order_acquire); - } - -private: - // Drop the oldest queued slot for a producer that needs room. The subscriber - // can pop past the entry as soon as head_ moves, so `forget` must finish - // first. - template bool EvictFront(Forget &forget) { - uint64_t head = head_.load(std::memory_order_relaxed); - for (size_t attempt = 0; attempt < kMaxSlotQueueCasAttempts; ++attempt) { - SlotQueueEntry &entry = entries_[head % capacity_]; - if (entry.sequence.load(std::memory_order_acquire) != head + 1) { - return false; - } - const QueuedSlot evicted = { - entry.slot_id.load(std::memory_order_relaxed), - entry.ordinal.load(std::memory_order_relaxed), - }; - if (entry.sequence.load(std::memory_order_acquire) != head + 1) { - head = head_.load(std::memory_order_relaxed); - continue; - } - if (!forget(evicted)) { - return false; - } - if (head_.compare_exchange_strong(head, head + 1, - std::memory_order_acq_rel, - std::memory_order_relaxed)) { - entry.sequence.store(head + capacity_, std::memory_order_release); - return true; - } - } - return false; - } - - // Fixed ring capacity for this queue, capped independently of the channel's - // slot count to keep shared-memory usage bounded. - size_t capacity_ = 0; - // Next sequence number the single subscriber will try to pop. - std::atomic head_{0}; - // Next sequence number producers will reserve for Push(). - std::atomic tail_{0}; - std::atomic overflow_count_{0}; - std::atomic insertion_failed_{false}; - // Explicit queues drop their oldest hint on overflow. Inherited queues leave - // the queue unchanged and force the subscriber to recover from its bitset. - bool drop_oldest_ = true; - // Flexible array of `capacity_` entries stored immediately after the header. - SlotQueueEntry entries_[0]; -}; -static_assert(sizeof(InPlaceSlotQueue) == 32); - -inline size_t SizeofSlotQueue(size_t capacity) { - return sizeof(InPlaceSlotQueue) + sizeof(SlotQueueEntry) * capacity; -} - -constexpr uint64_t kInvalidSlotQueueOffset = - std::numeric_limits::max(); - -inline int ResolveSubscriberQueueSize(int num_slots, - int subscriber_queue_size) { - if (num_slots <= 0 || subscriber_queue_size <= 0) { - return 0; - } - return subscriber_queue_size; -} - -struct BufferControlBlock { - std::atomic - refs[kMaxBuffers]; // Number of references to this buffer. - std::atomic - sizes[kMaxBuffers]; // Byte size of this buffer segment. -}; // The data covered by a message checksum, as three spans: // [0] prefix fields before the checksum (slot_id through metadata_size), @@ -674,18 +69,12 @@ class MessageChecksumData { public: MessageChecksumData(const MessagePrefix *prefix, const void *buffer, size_t message_size, int32_t checksum_size, - int32_t metadata_size) { - const auto *base = reinterpret_cast(prefix); - memcpy(prefix_fields_, base + offsetof(MessagePrefix, slot_id), - sizeof(prefix_fields_)); - int64_t flags; - memcpy(&flags, prefix_fields_ + kFlagsOffset, sizeof(flags)); - flags &= kChecksummedMessageFlags; - memcpy(prefix_fields_ + kFlagsOffset, &flags, sizeof(flags)); - spans_ = {absl::Span(prefix_fields_, sizeof(prefix_fields_)), - absl::Span(base + offsetof(MessagePrefix, checksum) + - checksum_size, - metadata_size), + int32_t metadata_size) + : prefix_fields_(prefix) { + spans_ = {absl::Span(prefix_fields_.Data(), + prefix_fields_.Size()), + absl::Span( + ChecksummedMetadata(prefix, checksum_size), metadata_size), absl::Span( reinterpret_cast(buffer), message_size)}; } @@ -698,11 +87,7 @@ class MessageChecksumData { } private: - static constexpr size_t kFlagsOffset = - offsetof(MessagePrefix, flags) - offsetof(MessagePrefix, slot_id); - - uint8_t prefix_fields_[offsetof(MessagePrefix, checksum) - - offsetof(MessagePrefix, slot_id)]; + ChecksummedPrefixFields prefix_fields_; std::array, 3> spans_; }; @@ -746,284 +131,6 @@ GetMetadataSpan(const MessagePrefix *prefix, int32_t checksum_size, } // This counts the number of subscribers given a virtual channel id. -class SubscriberCounter { -public: - SubscriberCounter() { - sequence_.store(0, std::memory_order_relaxed); - ResetCounts(); - } - - SubscriberCounter(const SubscriberCounter &other) { - sequence_.store(0, std::memory_order_relaxed); - for (size_t i = 0; i < num_subs_.size(); ++i) { - num_subs_[i].store( - other.num_subs_[i].load(std::memory_order_acquire), - std::memory_order_relaxed); - } - } - - SubscriberCounter &operator=(const SubscriberCounter &other) { - if (this == &other) { - return *this; - } - const uint64_t sequence = - sequence_.load(std::memory_order_relaxed) & ~uint64_t{1}; - sequence_.store(sequence + 1, std::memory_order_release); - for (size_t i = 0; i < num_subs_.size(); ++i) { - num_subs_[i].store( - other.num_subs_[i].load(std::memory_order_acquire), - std::memory_order_relaxed); - } - sequence_.store(sequence + 2, std::memory_order_release); - return *this; - } - - void Reset() { - BeginWrite(); - ResetCounts(); - EndWrite(); - } - - void AddSubscriber(int vchan_id) { - BeginWrite(); - num_subs_[vchan_id + 1].fetch_add(1, std::memory_order_relaxed); - EndWrite(); - } - - void RemoveSubscriber(int vchan_id) { - BeginWrite(); - num_subs_[vchan_id + 1].fetch_sub(1, std::memory_order_relaxed); - EndWrite(); - } - - // If vchan_id is valid we also count the number of subscribers to the - // multiplexer itself. - int NumSubscribers(int vchan_id) { - for (;;) { - const uint64_t before = sequence_.load(std::memory_order_acquire); - if ((before & 1) != 0) { - // A server process can die between BeginWrite and EndWrite. Treat an - // interrupted update conservatively instead of making surviving - // clients spin forever; the recovered server rebuilds the counter. - return kMaxSlotOwners; - } - const int mux_count = num_subs_[0].load(std::memory_order_relaxed); - const int count = - vchan_id == -1 - ? mux_count - : mux_count + - num_subs_[vchan_id + 1].load(std::memory_order_relaxed); - if (sequence_.load(std::memory_order_acquire) == before) { - return count; - } - } - } - -private: - void BeginWrite() { - sequence_.fetch_add(1, std::memory_order_acq_rel); - } - - void EndWrite() { sequence_.fetch_add(1, std::memory_order_release); } - - void ResetCounts() { - for (auto &count : num_subs_) { - count.store(0, std::memory_order_relaxed); - } - } - - // Vchan ID -1 means invalid vchan ID so we just use element 0 for that. - std::atomic sequence_; - std::array, kMaxVchanId + 1> num_subs_; -}; - -class SubscriberCleanupGeneration { -public: - SubscriberCleanupGeneration() { - for (auto &generation : generations_) { - generation.store(0, std::memory_order_relaxed); - } - } - - void Increment(int vchan_id) { - generations_[vchan_id + 1].fetch_add(1, std::memory_order_release); - } - - uint64_t Get(int vchan_id) const { - const uint64_t mux_generation = - generations_[0].load(std::memory_order_acquire); - if (vchan_id == -1) { - return mux_generation; - } - return mux_generation + - generations_[vchan_id + 1].load(std::memory_order_acquire); - } - -private: - std::array, kMaxVchanId + 1> generations_; -}; - -class OrdinalAccumulator { -public: - void Init(int v) { - for (int i = 0; i < kMaxVchanId + 1; i++) { - ordinals_[i] = v; - } - } - uint64_t Next(int vchan_id) { return ordinals_[vchan_id + 1]++; } - uint64_t PeekNext(int vchan_id) const { - return ordinals_[vchan_id + 1].load(std::memory_order_relaxed); - } - -private: - std::array, kMaxVchanId + 1> ordinals_ = {}; -}; - -class ActivationTracker { -public: - void Activate(int vchan_id) { activations_.Set(vchan_id + 1); } - bool IsActivated(int vchan_id) const { - return activations_.IsSet(vchan_id + 1); - } - -private: - AtomicBitSet activations_; // One bit per vchan_id. -}; - -// The control data for a channel. This memory is -// allocated by the server and mapped into the process -// for all publishers and subscribers. Each mapped CCB is mapped -// at a virtual address chosen by the OS. -// -// This is in shared memory so no pointers are possible. -struct ChannelControlBlock { // a.k.a CCB - char channel_name[kMaxChannelName]; // So that you can see the name in a - // debugger or hexdump. - int num_slots; - int subscriber_queue_size; // Fixed inherited per-subscriber queue capacity. - uint32_t version; - OrdinalAccumulator ordinals; // Ordinal accumulator for virtual channels. - ActivationTracker activation_tracker; // Tracks which vchan_ids have been - // activated by a publisher. - int buffer_index; // Which buffer in buffers array to use. - std::atomic num_buffers; // Size of buffers array in shared memory. - AtomicBitSet subscribers; // One bit per subscriber. - - // Given a subscriber ID, what is the vchan ID associated with it. - std::array sub_vchan_ids; - - SubscriberCounter num_subs; - // Incremented by the server after removing a subscriber and before its - // all-slot retirement scan. Publishers use this to determine whether - // subscriber cleanup raced their publication commit. - SubscriberCleanupGeneration subscriber_cleanup_generation; - - // Statistics counters. - std::atomic total_bytes; - // Number of completed publications, including activation messages. This is - // also the version stamp for subscriber delivery snapshots. - std::atomic total_messages; - std::atomic max_message_size; - std::atomic total_drops; - - // If true there are no more free slots and there's no need to check - // the bitset for them (there will never be another free slot) - std::atomic free_slots_exhausted; - - // Variable number of MessageSlot structs (num_slots long). - MessageSlot slots[0]; - // Followed by: - // AtomicBitSet<0> retiredSlots[num_slots]; - // Followed by: - // AtomicBitSet<0> freeSlots[num_slots]; - // Followed by: - // AtomicBitSet<0> availableSlots[kMaxSlotOwners]; - // Followed by: - // AvailableSlotQueueIndex availableSlotQueueIndex; - // Followed by: - // A packed arena of variable-capacity InPlaceSlotQueue objects. - // -}; -static_assert(offsetof(ChannelControlBlock, version) == 72); -// The Rust client mirrors this struct, so pin the stats block too. Both -// languages must agree or they will read different shared memory. -static_assert(offsetof(ChannelControlBlock, total_messages) == - offsetof(ChannelControlBlock, total_bytes) + 8); -static_assert(offsetof(ChannelControlBlock, max_message_size) == - offsetof(ChannelControlBlock, total_messages) + 8); -static_assert(offsetof(ChannelControlBlock, total_drops) == - offsetof(ChannelControlBlock, max_message_size) + 8); - -// Locates each subscriber's variable-capacity queue in the packed queue arena. -// Offsets are relative to the start of the arena. -struct AvailableSlotQueueIndex { - std::atomic next_offset; - std::array, kMaxSlotOwners> offsets; - std::array, kMaxSlotOwners> active_publishers; -}; -static_assert(offsetof(AvailableSlotQueueIndex, next_offset) == 0); -static_assert(offsetof(AvailableSlotQueueIndex, offsets) == - sizeof(std::atomic)); -static_assert(offsetof(AvailableSlotQueueIndex, active_publishers) == - offsetof(AvailableSlotQueueIndex, offsets) + - sizeof(std::atomic) * kMaxSlotOwners); -static_assert(sizeof(AvailableSlotQueueIndex) == - static_cast(Aligned( - static_cast( - offsetof(AvailableSlotQueueIndex, active_publishers) + - sizeof(std::atomic) * kMaxSlotOwners)))); -static_assert(kMaxSlotOwners != 1024 || - (offsetof(AvailableSlotQueueIndex, active_publishers) == 8200 && - sizeof(AvailableSlotQueueIndex) == 12296)); - -inline size_t AvailableSlotsSize(int num_slots) { - return SizeofAtomicBitSet(num_slots) * kMaxSlotOwners; -} - -inline size_t AvailableSlotQueueIndexSize() { - return Aligned(sizeof(AvailableSlotQueueIndex)); -} - -enum class SlotQueueBlockState : uint32_t { - kAllocated = 0, - kRetired = 1, - kFree = 2, -}; - -struct alignas(64) SlotQueueBlockHeader { - uint64_t block_size = 0; - std::atomic state{ - static_cast(SlotQueueBlockState::kFree)}; - uint32_t reserved = 0; - AtomicBitSet waiting_publishers; -}; -static_assert(offsetof(SlotQueueBlockHeader, waiting_publishers) == 16); -static_assert(sizeof(SlotQueueBlockHeader) == - static_cast(Aligned<64>(static_cast( - offsetof(SlotQueueBlockHeader, waiting_publishers) + - sizeof(AtomicBitSet))))); -static_assert(kMaxSlotOwners != 1024 || sizeof(SlotQueueBlockHeader) == 192); - -inline size_t SlotQueueBlockHeaderSize() { - return Aligned(sizeof(SlotQueueBlockHeader)); -} - -inline size_t SlotQueueBlockSize(size_t capacity) { - return SlotQueueBlockHeaderSize() + Aligned(SizeofSlotQueue(capacity)); -} - -inline size_t CcbSize(int num_slots, uint64_t subscriber_queue_arena_size) { - return Aligned(sizeof(ChannelControlBlock) + - num_slots * sizeof(MessageSlot)) + - Aligned(SizeofAtomicBitSet(num_slots)) * 2 + - AvailableSlotsSize(num_slots) + - AvailableSlotQueueIndexSize() + - static_cast(subscriber_queue_arena_size); -} - -inline size_t CcbSize(int num_slots) { - return CcbSize(num_slots, /*subscriber_queue_arena_size=*/0); -} inline absl::StatusOr CheckedCcbSize(int num_slots, uint64_t subscriber_queue_arena_size) { @@ -1173,13 +280,8 @@ class Channel : public std::enable_shared_from_this { if (ordinal == 0 || buffer_index == -1) { return false; } - const int slot_vchan_id = - slot.vchan_id.load(std::memory_order_relaxed); - if (vchan_id != -1 && slot_vchan_id != -1 && - vchan_id != slot_vchan_id) { - return false; - } - return true; + return VirtualChannelsMatch( + vchan_id, slot.vchan_id.load(std::memory_order_relaxed)); }; uint64_t last_ordinal = 0; @@ -1207,8 +309,10 @@ class Channel : public std::enable_shared_from_this { if (queue != nullptr) { queue->Push(best->id, best->ordinal.load(std::memory_order_relaxed), /*report_insertion_failure=*/true, - [this, &bits](const QueuedSlot &evicted) { - return ForgetEvictedSlot(bits, evicted); + [this, sub_id](const QueuedSlot &evicted) { + return View().ForgetEvictedSlot( + View().AvailableSlots(sub_id), evicted, + [](int32_t) {}); }); } last_ordinal = best->ordinal.load(std::memory_order_relaxed); @@ -1222,9 +326,7 @@ class Channel : public std::enable_shared_from_this { // The result is rounded up to a 64-byte boundary. static int32_t ComputePrefixSize(int32_t checksum_size, int32_t metadata_size) { - return static_cast( - Aligned<64>(offsetof(MessagePrefix, checksum) + checksum_size + - metadata_size)); + return ::subspace::PrefixSize(checksum_size, metadata_size); } // Total prefix area size in bytes (always a multiple of 64). @@ -1283,28 +385,28 @@ class Channel : public std::enable_shared_from_this { void CleanupSlots(int owner, bool reliable, bool is_pub, int vchan_id); - bool TryRetireSlot(MessageSlot *slot); + // The mapped channel control block, for the slot operations shared with + // other clients. + ChannelView View() const { + return ChannelView(ccb_, num_slots_, SubscriberQueueArenaSize()); + } + + bool TryRetireSlot(MessageSlot *slot) { return View().TryRetireSlot(slot); } + + bool RefsShowRetired(const MessageSlot *slot, uint64_t refs) const { + return View().RefsShowRetired(slot, refs); + } - // Drop subscriber `owner`'s obligation to the message in `slot` and, when - // `drop_ref` is set, one reference. Returns false when the slot is - // publisher-owned or holds a different message. Does not set the retired - // bit; the caller uses TryRetireSlot. bool ReleaseSubscriberObligation(MessageSlot *slot, int owner, bool reliable, bool drop_ref, uint64_t ordinal, - int vchan_id); - - // A subscriber removed while this slot was still publisher-owned could not - // decrement pending. Drop those obligations now that the message is - // committed, including an ID reused by a subscriber on a virtual channel - // that was not delivered this message. - void ReleaseDepartedObligations(MessageSlot *slot); + int vchan_id) { + return View().ReleaseSubscriberObligation(slot, owner, reliable, drop_ref, + ordinal, vchan_id); + } - // Whether `refs`, read from `slot`, show a slot that holds no message or one - // that every subscriber delivered at publish time has finished with. A - // slot's retired bit is set after that countdown reaches zero, so a publisher - // can reuse the slot in between and the bit then stands for a message nobody - // has seen. Check the refs before taking a slot for its retired bit. - bool RefsShowRetired(const MessageSlot *slot, uint64_t refs) const; + void ReleaseDepartedObligations(MessageSlot *slot) { + View().ReleaseDepartedObligations(slot); + } int NumSubscribers(int vchan_id) const { return ccb_->num_subs.NumSubscribers(vchan_id); @@ -1336,35 +438,25 @@ class Channel : public std::enable_shared_from_this { uint64_t ordinal, int vchan_id, bool retire, std::function retire_callback = {}); - // Clear the bit in `bits` for a message evicted from that subscriber's - // queue, if the slot still holds it. Returns false while the message is - // still being published, because its slot cannot be pinned until then. If - // the slot retires when it is unpinned, `retire_callback` is called with - // the slot ID to report. - bool ForgetEvictedSlot(InPlaceAtomicBitset &bits, const QueuedSlot &evicted, - std::function retire_callback = {}); - void SetType(std::string type) { type_ = std::move(type); } const std::string Type() const { return type_; } std::string_view TypeView() const { return type_; } char *EndOfSlots() const { - return reinterpret_cast(ccb_) + - Aligned(sizeof(ChannelControlBlock) + - num_slots_ * sizeof(MessageSlot)); + return reinterpret_cast(ccb_) + RetiredSlotsOffset(num_slots_); } char *EndOfRetiredSlots() const { - return EndOfSlots() + Aligned(SizeofAtomicBitSet(num_slots_)); + return reinterpret_cast(ccb_) + FreeSlotsOffset(num_slots_); } char *EndOfFreeSlots() const { - return EndOfRetiredSlots() + Aligned(SizeofAtomicBitSet(num_slots_)); + return reinterpret_cast(ccb_) + AvailableSlotsOffset(num_slots_, 0); } char *EndOfAvailableSlots() const { - return EndOfFreeSlots() + AvailableSlotsSize(num_slots_); + return reinterpret_cast(ccb_) + SlotQueueIndexOffset(num_slots_); } char *EndOfAvailableSlotQueueIndex() const { - return EndOfAvailableSlots() + AvailableSlotQueueIndexSize(); + return reinterpret_cast(ccb_) + SlotQueueArenaOffset(num_slots_); } InPlaceAtomicBitset *RetiredSlotsAddr() { @@ -1397,7 +489,8 @@ class Channel : public std::enable_shared_from_this { InPlaceAtomicBitset *GetAvailableSlotsAddress(int sub_id) { return reinterpret_cast( - EndOfFreeSlots() + SizeofAtomicBitSet(num_slots_) * sub_id); + reinterpret_cast(ccb_) + + AvailableSlotsOffset(num_slots_, sub_id)); } AvailableSlotQueueIndex *GetAvailableSlotQueueIndexAddress() { @@ -1437,22 +530,13 @@ class Channel : public std::enable_shared_from_this { } void BeginSubscriberQueuePublish(int pub_id) { - GetAvailableSlotQueueIndexAddress() - ->active_publishers[pub_id] - .fetch_add(1, std::memory_order_seq_cst); + ::subspace::BeginSubscriberQueuePublish( + GetAvailableSlotQueueIndexAddress(), pub_id); } void EndSubscriberQueuePublish(int pub_id) { - auto &counter = - GetAvailableSlotQueueIndexAddress()->active_publishers[pub_id]; - uint32_t active = counter.load(std::memory_order_seq_cst); - while (active != 0) { - if (counter.compare_exchange_strong(active, active - 1, - std::memory_order_seq_cst, - std::memory_order_seq_cst)) { - return; - } - } + ::subspace::EndSubscriberQueuePublish(GetAvailableSlotQueueIndexAddress(), + pub_id); } bool IsActivated(int vchan_id) const { diff --git a/common/channel_view.h b/common/channel_view.h new file mode 100644 index 00000000..3c7fc268 --- /dev/null +++ b/common/channel_view.h @@ -0,0 +1,361 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +#pragma once + +#include "common/bitset_view.h" +#include "common/shm_layout.h" + +#include +#include +#include + +namespace subspace { + +// Whether a subscriber on sub_vchan_id receives a message published on +// msg_vchan_id. -1 is the multiplexer itself: a subscriber to it receives +// every virtual channel, and a message published to it reaches every +// subscriber. +inline bool VirtualChannelsMatch(int sub_vchan_id, int msg_vchan_id) { + return sub_vchan_id == -1 || msg_vchan_id == -1 || + sub_vchan_id == msg_vchan_id; +} + +// The regions of a mapped channel control block, and the slot operations that +// every client shares. It does not own the mapping. +class ChannelView { +public: + ChannelView() = default; + ChannelView(ChannelControlBlock *ccb, int num_slots, + uint64_t queue_arena_size) + : ccb_(ccb), num_slots_(num_slots), queue_arena_size_(queue_arena_size) {} + + ChannelControlBlock *Ccb() const { return ccb_; } + int NumSlots() const { return num_slots_; } + + MessageSlot *Slot(int id) const { return &ccb_->slots[id]; } + + BitsetView RetiredSlots() const { + return BitsetView(Base() + RetiredSlotsOffset(num_slots_), num_slots_); + } + BitsetView FreeSlots() const { + return BitsetView(Base() + FreeSlotsOffset(num_slots_), num_slots_); + } + BitsetView AvailableSlots(int sub_id) const { + return BitsetView(Base() + AvailableSlotsOffset(num_slots_, sub_id), + num_slots_); + } + BitsetView Subscribers() const { + return BitsetView(&ccb_->subscribers, kMaxSlotOwners); + } + + AvailableSlotQueueIndex *QueueIndex() const { + return reinterpret_cast( + Base() + SlotQueueIndexOffset(num_slots_)); + } + + // The subscriber's queue, or null if it has none or the queue does not fit + // in the arena. + InPlaceSlotQueue *Queue(int sub_id) const { + const uint64_t offset = + QueueIndex()->offsets[sub_id].load(std::memory_order_acquire); + if (offset == kInvalidSlotQueueOffset || offset > queue_arena_size_ || + queue_arena_size_ - offset < sizeof(InPlaceSlotQueue)) { + return nullptr; + } + auto *queue = reinterpret_cast( + Base() + SlotQueueArenaOffset(num_slots_) + offset); + const uint64_t room = queue_arena_size_ - offset - sizeof(InPlaceSlotQueue); + if (queue->Capacity() > room / sizeof(SlotQueueEntry)) { + return nullptr; + } + return queue; + } + + int NumSubscribers(int vchan_id) const { + return ccb_->num_subs.NumSubscribers(vchan_id); + } + + uint64_t CleanupGeneration(int vchan_id) const { + return ccb_->subscriber_cleanup_generation.Get(vchan_id); + } + + // Whether `refs`, read from `slot`, show a slot that holds no message or one + // that every subscriber delivered at publish time has finished with. A + // slot's retired bit is set after that countdown reaches zero, so a publisher + // can reuse the slot in between and the bit then stands for a message nobody + // has seen. Check the refs before taking a slot for its retired bit. + bool RefsShowRetired(const MessageSlot *slot, uint64_t refs) const { + if ((refs & (kPubOwned | kRefsMask)) != 0) { + return false; + } + if (slot->ordinal.load(std::memory_order_relaxed) == 0) { + return true; + } + return PendingCount(refs) == 0; + } + + // Whether retirement listeners are told that slot_id retired. Activation + // messages are not reported. A bridged message names a slot on the other + // side of the bridge, which this channel may not have. + bool ReportsRetirement(int slot_id) const { + return slot_id < 0 || slot_id >= num_slots_ || + (Slot(slot_id)->flags.load(std::memory_order_relaxed) & + kMessageIsActivation) == 0; + } + + // Sets the slot's retired bit if every subscriber has seen and released its + // message. Returns true if this call set it. + bool TryRetireSlot(MessageSlot *slot) const { + if (slot->ordinal.load(std::memory_order_relaxed) == 0) { + return false; + } + const uint64_t refs = slot->refs.load(std::memory_order_acquire); + if ((refs & kPubOwned) != 0) { + return false; + } + const uint64_t ref_count = refs & kRefCountMask; + const uint64_t reliable_ref_count = + (refs >> kReliableRefCountShift) & kRefCountMask; + if (ref_count != 0 || reliable_ref_count != 0 || PendingCount(refs) != 0) { + return false; + } + return RetiredSlots().SetWasClear(slot->id); + } + + // Drop subscriber `owner`'s obligation to the message in `slot` and, when + // `drop_ref` is set, one reference. Returns false when the slot is + // publisher-owned or holds a different message. Does not set the retired + // bit; the caller uses TryRetireSlot. + bool ReleaseSubscriberObligation(MessageSlot *slot, int owner, bool reliable, + bool drop_ref, uint64_t ordinal, + int vchan_id) const { + const uint64_t want_ord = ordinal & kOrdinalMask; + for (;;) { + uint64_t ref = slot->refs.load(std::memory_order_acquire); + if ((ref & kPubOwned) != 0) { + if (drop_ref) { + slot->sub_owners.Clear(owner); + } + return false; + } + const uint64_t ref_ord = (ref >> kOrdinalShift) & kOrdinalMask; + const int ref_vchan_id = RefsVchanId(ref); + if (want_ord != 0 && ref_ord != 0 && ref_ord != want_ord) { + if (drop_ref) { + slot->sub_owners.Clear(owner); + } + return false; + } + if (want_ord != 0 && ref_ord != 0 && ref_vchan_id != vchan_id) { + if (drop_ref) { + slot->sub_owners.Clear(owner); + } + return false; + } + + // Take the obligation before the CAS so two releasers cannot both + // decrement. If the slot changes before the CAS lands, put the bit back + // when it now belongs to a committed newer message. + const bool owed = slot->pending_subs.ClearWasSet(owner); + const uint64_t again = slot->refs.load(std::memory_order_acquire); + if (again != ref) { + if (owed) { + // The bit we cleared may belong to the message a publisher is + // installing. Put it back. ClearAll during that publish wipes a + // restore that still belongs to the previous message, and a restore + // of a bit the publisher just set matches the count it recorded. + slot->pending_subs.Set(owner); + } + if (drop_ref && + ((again & kPubOwned) != 0 || + ((again >> kOrdinalShift) & kOrdinalMask) != want_ord)) { + slot->sub_owners.Clear(owner); + return false; + } + continue; + } + + uint64_t new_refs = ref & kRefCountMask; + uint64_t new_reliable_refs = + (ref >> kReliableRefCountShift) & kRefCountMask; + const bool drop_a_ref = drop_ref && new_refs != 0; + if (drop_a_ref) { + new_refs -= 1; + if (reliable && new_reliable_refs > 0) { + new_reliable_refs -= 1; + } + } + int pending = PendingCount(ref); + if (owed && pending > 0) { + pending--; + } + if (!owed && !drop_a_ref) { + if (drop_ref) { + slot->sub_owners.Clear(owner); + } + return true; + } + const uint64_t new_ref = + BuildRefsBitField(ref_ord, ref_vchan_id, pending) | + (new_reliable_refs << kReliableRefCountShift) | new_refs; + if (slot->refs.compare_exchange_weak(ref, new_ref, + std::memory_order_acq_rel, + std::memory_order_relaxed)) { + if (drop_ref) { + slot->sub_owners.Clear(owner); + } + return true; + } + if (owed) { + slot->pending_subs.Set(owner); + } + } + } + + // A subscriber removed while this slot was still publisher-owned could not + // decrement pending. Drop those obligations now that the message is + // committed, including an ID reused by a subscriber on a virtual channel + // that was not delivered this message. + void ReleaseDepartedObligations(MessageSlot *slot) const { + const uint64_t ordinal = slot->ordinal.load(std::memory_order_relaxed); + const int vchan_id = slot->vchan_id.load(std::memory_order_relaxed); + if (ordinal == 0) { + return; + } + // Release during the walk. Traverse shifts past the bit it just reported + // before loading again, and the release only clears that subscriber's bit. + slot->pending_subs.Traverse([this, slot, ordinal, vchan_id](size_t sub_id) { + if (ccb_->subscribers.IsSet(sub_id)) { + // User IDs are first-fit and shared by every virtual channel on a mux. + // A subscriber removed while this slot was publisher-owned can be + // reissued to a virtual channel that was not delivered the message + // before this commit. That subscriber must not keep the countdown. + const int sub_vchan = ccb_->sub_vchan_ids[sub_id]; + if (sub_vchan == -1 || vchan_id == -1 || sub_vchan == vchan_id) { + return; + } + } + ReleaseSubscriberObligation(slot, static_cast(sub_id), + /*reliable=*/false, /*drop_ref=*/false, + ordinal, vchan_id); + }); + } + + // Adds inc to the slot's reference counts, and to its reliable count if + // reliable, while the slot holds the message with this ordinal and vchan_id. + // An ordinal of 0 matches any message. With retire, also counts a + // subscriber that has finished with the message, and sets *retired if that + // retired the slot. Returns false if the slot no longer holds the message + // or a publisher owns it. + bool AtomicIncRefCount(MessageSlot *slot, bool reliable, int inc, + uint64_t ordinal, int vchan_id, bool retire, + bool *retired) const { + if (retired != nullptr) { + *retired = false; + } + ordinal &= kOrdinalMask; + for (;;) { + uint64_t ref = slot->refs.load(std::memory_order_relaxed); + if ((ref & kPubOwned) != 0) { + return false; + } + // An ordinal of 0 in refs means the slot was free. + const uint64_t ref_ordinal = (ref >> kOrdinalShift) & kOrdinalMask; + const int ref_vchan_id = RefsVchanId(ref); + if (ref_ordinal != 0 && ordinal != 0 && + (ref_ordinal != ordinal || ref_vchan_id != vchan_id)) { + return false; + } + uint64_t refs = ref & kRefCountMask; + uint64_t reliable_refs = (ref >> kReliableRefCountShift) & kRefCountMask; + if (inc < 0 && refs == 0) { + return true; + } + refs = static_cast(static_cast(refs) + inc); + if (reliable) { + reliable_refs = + static_cast(static_cast(reliable_refs) + inc); + } + int pending = PendingCount(ref); + if (retire && pending > 0) { + pending--; + } + const uint64_t new_ref = + BuildRefsBitField(ref_ordinal, ref_vchan_id, pending) | + (reliable_refs << kReliableRefCountShift) | refs; + if (slot->refs.compare_exchange_weak(ref, new_ref, + std::memory_order_acq_rel, + std::memory_order_relaxed)) { + // A reference dropping to zero retires the slot once every subscriber + // who was delivered the message has finished with it. `retire` covers + // a caller that decremented pending without also dropping a reference. + if ((retire || inc < 0) && refs == 0 && reliable_refs == 0 && + pending == 0 && RetiredSlots().SetWasClear(slot->id) && + retired != nullptr) { + *retired = true; + } + return true; + } + // Another subscriber, or a publisher, changed the refs. + } + } + + // Clears the bit in `bits` for a message evicted from that subscriber's + // queue, if the slot still holds it. Returns false while the message is + // still being published, because its slot cannot be pinned until then. If + // the slot retires when it is unpinned, calls `retired` with the slot to + // name to retirement listeners. + template + bool ForgetEvictedSlot(BitsetView bits, const QueuedSlot &evicted, + Retired &&retired) const { + if (evicted.slot_id < 0 || evicted.slot_id >= num_slots_ || + evicted.ordinal == 0) { + return true; + } + MessageSlot *slot = Slot(evicted.slot_id); + const uint64_t refs = slot->refs.load(std::memory_order_acquire); + if ((refs & kPubOwned) != 0) { + return slot->ordinal.load(std::memory_order_relaxed) != evicted.ordinal; + } + if (((refs >> kOrdinalShift) & kOrdinalMask) != + (evicted.ordinal & kOrdinalMask)) { + return true; + } + const int vchan_id = RefsVchanId(refs); + // While pinned the slot cannot be reused, so its bit cannot yet belong to + // a newer message. + if (!AtomicIncRefCount(slot, /*reliable=*/false, 1, evicted.ordinal, + vchan_id, /*retire=*/false, nullptr)) { + return true; + } + if (slot->ordinal.load(std::memory_order_relaxed) == evicted.ordinal) { + bits.Clear(slot->id); + } + const int32_t retirement_slot_id = + slot->bridged_slot_id.load(std::memory_order_relaxed); + // A subscriber that retires the slot while it is pinned leaves the ref + // count above zero, so the unpin has to retire it. + const uint64_t unpinned = + slot->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; + if ((unpinned & kRefCountMask) == 0 && + ((unpinned >> kReliableRefCountShift) & kRefCountMask) == 0 && + PendingCount(unpinned) == 0 && + RetiredSlots().SetWasClear(slot->id)) { + retired(retirement_slot_id); + } + return true; + } + +protected: + ChannelControlBlock *ccb_ = nullptr; + int num_slots_ = 0; + uint64_t queue_arena_size_ = 0; + +private: + char *Base() const { return reinterpret_cast(ccb_); } +}; + +} // namespace subspace diff --git a/client/checksum.cc b/common/crc32.cc similarity index 93% rename from client/checksum.cc rename to common/crc32.cc index 35b1127e..1e533090 100644 --- a/client/checksum.cc +++ b/common/crc32.cc @@ -1,34 +1,38 @@ // Copyright 2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. -#include "client/checksum.h" +#include "common/crc32.h" + #include #include -#include - -namespace subspace { - -extern "C" { // The x86 SSE4.2 CRC32 instruction computes CRC-32C, not the IEEE 802.3 CRC32 -// used by the Rust client and by every other build. x86 always uses the table -// below. The ARM CRC32 instructions compute the IEEE polynomial and are used -// when available. +// used by the Rust client and by every other build, so x86 always uses the +// table below. The ARM CRC32 instructions compute the IEEE polynomial and are +// used when available. #if defined(__aarch64__) && !defined(__ARM_FEATURE_CRC32) // Switch off hardware CRC32 if it is not available on aarch64. #undef SUBSPACE_HARDWARE_CRC #endif - #if defined(SUBSPACE_HARDWARE_CRC) && defined(__aarch64__) - // Whether to use the hand-written assembly version of the CRC32 function // in arm_crc32.S #define ARM_ASM_CRC32 1 - #if !defined(ARM_ASM_CRC32) #include +#endif +#endif + +namespace subspace { + +extern "C" { + +#if defined(SUBSPACE_HARDWARE_CRC) && defined(__aarch64__) + +#if !defined(ARM_ASM_CRC32) uint32_t SubspaceCRC32(uint32_t crc, const uint8_t *data, size_t length) { size_t i = 0; diff --git a/common/crc32.h b/common/crc32.h new file mode 100644 index 00000000..df5463a1 --- /dev/null +++ b/common/crc32.h @@ -0,0 +1,26 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +#pragma once + +#include +#include + +// Undefine this if you don't want to use hardware CRC32 instructions. +#ifndef SUBSPACE_HARDWARE_CRC +#define SUBSPACE_HARDWARE_CRC 1 +#endif + +namespace subspace { + +// CRC32 of a published message, using the IEEE 802.3 polynomial on every +// platform (the same as the Rust client). The ARM CRC32 instructions are IEEE; +// x86 uses a lookup table because its SSE4.2 CRC32 instruction is CRC-32C. +// Pass 0xFFFFFFFF as the first crc and invert the final result. +extern "C" { +uint32_t SubspaceCRC32(uint32_t crc, const uint8_t *data, size_t length); +} + +} // namespace subspace diff --git a/common/dynamic_bitset.h b/common/dynamic_bitset.h new file mode 100644 index 00000000..5a685978 --- /dev/null +++ b/common/dynamic_bitset.h @@ -0,0 +1,65 @@ +// Copyright 2023-2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. +// +// A heap-backed bitset. This is not part of the shared-memory layout. + +#pragma once + +#include "common/atomic_bitset.h" + +#include + +namespace subspace { + +class DynamicBitSet { +public: + DynamicBitSet() : num_bits_(0), bits_(0) {} + DynamicBitSet(size_t num_bits) + : num_bits_(num_bits), bits_(BitsToWords(num_bits), 0) {} + + void Resize(size_t num_bits) { + num_bits_ = num_bits; + bits_.resize(BitsToWords(num_bits), 0); + } + + void Set(size_t bit) { + size_t word = bit / 64; + size_t offset = bit % 64; + bits_[word] |= 1ULL << offset; + } + + void Clear(size_t bit) { + size_t word = bit / 64; + size_t offset = bit % 64; + bits_[word] &= ~(1ULL << offset); + } + + bool IsSet(size_t bit) const { + size_t word = bit / 64; + size_t offset = bit % 64; + return bits_[word] & (1ULL << offset); + } + + void ClearAll() { + for (size_t i = 0; i < BitsToWords(num_bits_); i++) { + bits_[i] = 0; + } + } + + bool IsEmpty() const { + for (size_t i = 0; i < BitsToWords(num_bits_); i++) { + if (bits_[i] != 0) { + return false; + } + } + return true; + } + +private: + size_t num_bits_; + std::vector bits_; +}; + +} // namespace subspace diff --git a/common/message_checksum.h b/common/message_checksum.h new file mode 100644 index 00000000..f75395c9 --- /dev/null +++ b/common/message_checksum.h @@ -0,0 +1,86 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +#pragma once + +#include "common/crc32.h" +#include "common/shm_layout.h" + +#include +#include +#include + +namespace subspace { + +// The prefix fields a message checksum covers: slot_id up to the checksum, +// with flags limited to kChecksummedMessageFlags. The bridge and the tunnel +// set other flags after the checksum is computed. +class ChecksummedPrefixFields { +public: + explicit ChecksummedPrefixFields(const MessagePrefix *prefix) { + std::memcpy(bytes_, + reinterpret_cast(prefix) + + offsetof(MessagePrefix, slot_id), + sizeof(bytes_)); + int64_t flags; + std::memcpy(&flags, bytes_ + kFlagsOffset, sizeof(flags)); + flags &= kChecksummedMessageFlags; + std::memcpy(bytes_ + kFlagsOffset, &flags, sizeof(flags)); + } + + const uint8_t *Data() const { return bytes_; } + static constexpr size_t Size() { return kSize; } + +private: + static constexpr size_t kFlagsOffset = + offsetof(MessagePrefix, flags) - offsetof(MessagePrefix, slot_id); + static constexpr size_t kSize = + offsetof(MessagePrefix, checksum) - offsetof(MessagePrefix, slot_id); + + uint8_t bytes_[kSize]; +}; + +// The user metadata, which follows the checksum storage in the prefix. +inline const uint8_t *ChecksummedMetadata(const MessagePrefix *prefix, + int32_t checksum_size) { + return reinterpret_cast(prefix) + + offsetof(MessagePrefix, checksum) + checksum_size; +} + +// The default message checksum: CRC32 over the checksummed prefix fields, the +// metadata and the payload. +inline uint32_t MessageChecksum(const MessagePrefix *prefix, + const void *payload, size_t payload_size, + int32_t checksum_size, + int32_t metadata_size) { + const ChecksummedPrefixFields fields(prefix); + uint32_t crc = 0xFFFFFFFF; + crc = SubspaceCRC32(crc, fields.Data(), fields.Size()); + crc = SubspaceCRC32(crc, ChecksummedMetadata(prefix, checksum_size), + static_cast(metadata_size)); + crc = SubspaceCRC32(crc, static_cast(payload), + payload_size); + return ~crc; +} + +inline void SetMessageChecksum(MessagePrefix *prefix, const void *payload, + size_t payload_size, int32_t checksum_size, + int32_t metadata_size) { + const uint32_t checksum = MessageChecksum(prefix, payload, payload_size, + checksum_size, metadata_size); + std::memcpy(&prefix->checksum, &checksum, sizeof(checksum)); +} + +inline bool MessageChecksumMatches(const MessagePrefix *prefix, + const void *payload, size_t payload_size, + int32_t checksum_size, + int32_t metadata_size) { + uint32_t stored; + std::memcpy(&stored, &prefix->checksum, sizeof(stored)); + return stored == MessageChecksum(prefix, payload, payload_size, + checksum_size, metadata_size); +} + +} // namespace subspace diff --git a/common/publish.h b/common/publish.h new file mode 100644 index 00000000..f2402523 --- /dev/null +++ b/common/publish.h @@ -0,0 +1,218 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +// Publishing a message into a slot, shared by every client. + +#pragma once + +#include "common/atomic_bitset.h" +#include "common/bitset_view.h" +#include "common/channel_view.h" +#include "common/shm_layout.h" + +#include +#include + +namespace subspace { + +// A publisher counts itself in active_publishers while it may write to +// subscriber queues. The server does not reuse a retired queue while a +// publisher that could still see it is counted. +inline void BeginSubscriberQueuePublish(AvailableSlotQueueIndex *index, + int publisher_id) { + index->active_publishers[publisher_id].fetch_add(1, + std::memory_order_seq_cst); +} + +inline void EndSubscriberQueuePublish(AvailableSlotQueueIndex *index, + int publisher_id) { + // The server zeroes the count when it removes the publisher, so never + // decrement past zero. + std::atomic &counter = index->active_publishers[publisher_id]; + uint32_t active = counter.load(std::memory_order_seq_cst); + while (active != 0 && + !counter.compare_exchange_strong(active, active - 1, + std::memory_order_seq_cst, + std::memory_order_seq_cst)) { + } +} + +// Counts a publisher in active_publishers for its lifetime. +class SubscriberQueuePublishScope { +public: + SubscriberQueuePublishScope(AvailableSlotQueueIndex *index, int publisher_id) + : index_(index), publisher_id_(publisher_id) { + BeginSubscriberQueuePublish(index_, publisher_id_); + } + ~SubscriberQueuePublishScope() { + EndSubscriberQueuePublish(index_, publisher_id_); + } + SubscriberQueuePublishScope(const SubscriberQueuePublishScope &) = delete; + SubscriberQueuePublishScope & + operator=(const SubscriberQueuePublishScope &) = delete; + +private: + AvailableSlotQueueIndex *index_; + int publisher_id_; +}; + +// Gives the message the publisher wrote into slot the next ordinal on the +// slot's virtual channel. +inline void StampSlot(ChannelControlBlock *ccb, MessageSlot *slot, + uint64_t timestamp) { + slot->ordinal.store( + ccb->ordinals.Next(slot->vchan_id.load(std::memory_order_relaxed)), + std::memory_order_relaxed); + slot->timestamp.store(timestamp, std::memory_order_relaxed); + slot->flags.store(0, std::memory_order_relaxed); +} + +// Fills in the prefix of a stamped slot. The caller adds any other flags, +// then the checksum. +inline void FillPrefix(ChannelControlBlock *ccb, MessageSlot *slot, + MessagePrefix *prefix, int32_t checksum_size, + int32_t metadata_size, bool is_activation) { + prefix->message_size = slot->message_size.load(std::memory_order_relaxed); + prefix->ordinal = slot->ordinal.load(std::memory_order_relaxed); + prefix->timestamp = slot->timestamp.load(std::memory_order_relaxed); + prefix->vchan_id = slot->vchan_id.load(std::memory_order_relaxed); + prefix->checksum_size = static_cast(checksum_size); + prefix->metadata_size = static_cast(metadata_size); + prefix->flags = 0; + prefix->slot_id = slot->id; + slot->bridged_slot_id.store(slot->id, std::memory_order_relaxed); + if (is_activation) { + prefix->SetIsActivation(); + slot->flags.fetch_or(kMessageIsActivation, std::memory_order_relaxed); + ccb->activation_tracker.Activate( + slot->vchan_id.load(std::memory_order_relaxed)); + } +} + +struct PublishedSlot { + uint64_t ordinal = 0; + uint64_t timestamp = 0; + // The slot to name to retirement listeners. For a bridged message this is + // the slot on the other side of the bridge. + int32_t retirement_slot_id = -1; + // Whether the commit retired the slot because a subscriber left while it + // was being published. The caller tells retirement listeners. + bool retired = false; +}; + +// Makes the stamped message in slot, which the publisher owns, available to +// the subscribers on vchan_id and then readable. `publishing` must count the +// publisher, because the commit writes to subscriber queues. An older message +// dropped from a full subscriber queue can retire its slot as the commit +// forgets it; `evicted_retired` is called with the slot to name to retirement +// listeners. +template +PublishedSlot +CommitPublishedSlot(const ChannelView &channel, MessageSlot *slot, + int vchan_id, bool is_activation, + const SubscriberQueuePublishScope & /*publishing*/, + EvictedRetired &&evicted_retired) { + ChannelControlBlock *ccb = channel.Ccb(); + PublishedSlot published; + published.ordinal = slot->ordinal.load(std::memory_order_relaxed); + published.timestamp = slot->timestamp.load(std::memory_order_relaxed); + published.retirement_slot_id = + slot->bridged_slot_id.load(std::memory_order_relaxed); + const uint64_t cleanup_generation = channel.CleanupGeneration(vchan_id); + + // The slot is publisher-owned, so a departing subscriber cannot decrement + // pending yet. Record exactly the subscribers who receive this message. + slot->pending_subs.ClearAll(); + + // Tell every subscriber that the slot is available while it is still + // publisher owned. The kPubOwned bit is the commit barrier: subscribers + // keep the delivery record but cannot claim the slot, and server cleanup + // cannot retire it, until the refs store below. + // + // The available-slot bitset is authoritative when a queue rejects or evicts + // a hint. A subscriber can leave after the traversal sees its bit, so check + // membership again after setting the delivery bit. Either the recheck + // clears a stale write, or the server's later ClearWasSet sees it. + const BitsetView subscribers = channel.Subscribers(); + AtomicBitSet failed_queues; + subscribers.Traverse( + [&](int sub_id) { + if (!VirtualChannelsMatch(ccb->sub_vchan_ids[sub_id], vchan_id)) { + return; + } + BitsetView available = channel.AvailableSlots(sub_id); + available.Set(slot->id); + if (!subscribers.IsSetSeqCst(sub_id)) { + available.Clear(slot->id); + // The subscriber ID may have been reused after the first check. + // Registration publishes membership before seeding this bit, so + // restore the bit if the new subscriber is already visible. + if (!subscribers.IsSetSeqCst(sub_id)) { + return; + } + available.Set(slot->id); + } + slot->pending_subs.Set(sub_id); + InPlaceSlotQueue *queue = channel.Queue(sub_id); + if (queue != nullptr && + !queue->Push(slot->id, published.ordinal, + /*report_insertion_failure=*/false, + [&](const QueuedSlot &evicted) { + return channel.ForgetEvictedSlot(available, evicted, + evicted_retired); + })) { + failed_queues.Set(sub_id); + } + }, + std::memory_order_seq_cst); + + // Finish the slot and queue bookkeeping before making the slot claimable. + if (!is_activation) { + const uint64_t message_size = + slot->message_size.load(std::memory_order_relaxed); + ccb->total_bytes += message_size; + if (message_size > ccb->max_message_size) { + ccb->max_message_size = message_size; + } + } + + // Commit. pending is the number of obligation bits still set: a subscriber + // who left during the traverse is not in the set, and a subscriber who joins + // afterwards is not either. A subscriber that sees the total_messages + // increment also sees this release and every delivery record above. + // Subscribers use total_messages as a version stamp for their delivery + // snapshots. + int pending = 0; + slot->pending_subs.Traverse([&pending](size_t) { pending++; }); + slot->refs.store(BuildRefsBitField(published.ordinal, vchan_id, pending), + std::memory_order_release); + + // A subscriber that sees the failure recovers from its bitset, and must find + // this message there. Before the commit its snapshot would skip the slot, + // and it could leave recovery and read this publisher's next message first. + // A subscriber that left since its push failed has no queue to mark. A new + // subscriber with the same ID that is marked only rescans its bitset. + failed_queues.Traverse([&channel](size_t sub_id) { + InPlaceSlotQueue *queue = channel.Queue(static_cast(sub_id)); + if (queue != nullptr) { + queue->MarkInsertionFailure(); + } + }); + ccb->total_messages.fetch_add(1, std::memory_order_seq_cst); + + // A subscriber removed while the slot was publisher-owned could not + // decrement pending. Drop those obligations now that the message is + // committed. If that was the whole audience, retire the slot. A publish + // that never had subscribers is retired by the lease path instead, so the + // idle ring still fills from the free list. + channel.ReleaseDepartedObligations(slot); + if (!is_activation && + channel.CleanupGeneration(vchan_id) != cleanup_generation) { + published.retired = channel.TryRetireSlot(slot); + } + return published; +} + +} // namespace subspace diff --git a/common/server_wire.h b/common/server_wire.h new file mode 100644 index 00000000..47d4f219 --- /dev/null +++ b/common/server_wire.h @@ -0,0 +1,259 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +#pragma once + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "phaser/runtime/wireformat.h" +#include "proto/subspace.phaser.h" + +#include +#include +#include +#include +#include + +namespace subspace { + +// Requests to and responses from the server, as native Phaser payloads. +// The bytes are Data() / ByteSizeLong(): the message buffer itself, with no +// protobuf transcoding. +// +// A ServerWire copies a request into its wire buffer and loads a response +// from received bytes. The Buffers policy decides where messages and wire +// bytes live: +// +// FixedServerWireBuffers holds them inside the object and makes no heap +// allocations, including when something fails. Its errors are process-lifetime +// statuses: the text stays readable through Status::message(), and returning +// one only adjusts a refcount. Requests and responses that don't fit fail +// with kResourceExhausted. NewRequest and NewResponse build messages in a +// single message buffer, so a new message replaces the previous one. +// +// DynamicServerWireBuffers grows its wire buffer to fit each request. Its +// messages are default constructed Phaser messages, which own their storage. +// +// Socket I/O stays with the caller. The length that precedes each message on +// the socket is the caller's to write, and Serialize leaves room for it just +// before the payload. +inline constexpr size_t kServerWireHeaderSize = sizeof(uint32_t); +// Put before the 4-byte header in an 8-byte-aligned buffer so the payload +// after the header is 8-byte aligned too. +inline constexpr size_t kServerWireHeaderPad = + (8 - (kServerWireHeaderSize % 8)) % 8; + +template class FixedServerWireBuffers { +public: + static constexpr size_t kMaxWireSize = kWireSize; + // Report failures with the permanent statuses, which keep their text and + // do not allocate. + static constexpr bool kErrorMessages = false; + + // kSize, because kPerformance builds a template of each message type on + // first use, which allocates from the heap. The handshake messages are + // small, so the simple allocator costs nothing noticeable. + absl::StatusOr NewRequest() { + return phaser::Request::TryCreateMutable(message_, sizeof(message_), + ::phaser::Tuning::kSize); + } + + absl::StatusOr NewResponse() { + return phaser::Response::TryCreateMutable(message_, sizeof(message_), + ::phaser::Tuning::kSize); + } + + // Room for the header and length bytes after it, or nullptr. + char *Wire(size_t length) { + return length <= kWireSize ? wire_ + kServerWireHeaderPad : nullptr; + } + +private: + alignas(8) char message_[kMessageSize]; + alignas(8) char wire_[kServerWireHeaderPad + kServerWireHeaderSize + kWireSize]; +}; + +// Message and wire storage the caller owns. The wire pointer addresses the +// length header, and wire_size is the payload capacity after that header. +class ProvidedServerWireBuffers { +public: + static constexpr bool kErrorMessages = false; + + ProvidedServerWireBuffers() = default; + ProvidedServerWireBuffers(char *message, size_t message_size, char *wire, + size_t wire_size) + : message_(message), + message_size_(message_size), + wire_(wire), + wire_size_(wire_size) {} + + absl::StatusOr NewRequest() { + return phaser::Request::TryCreateMutable(message_, message_size_, + ::phaser::Tuning::kSize); + } + + absl::StatusOr NewResponse() { + return phaser::Response::TryCreateMutable(message_, message_size_, + ::phaser::Tuning::kSize); + } + + char *Wire(size_t length) { return length <= wire_size_ ? wire_ : nullptr; } + +private: + char *message_ = nullptr; + size_t message_size_ = 0; + char *wire_ = nullptr; + size_t wire_size_ = 0; +}; + +class DynamicServerWireBuffers { +public: + static constexpr bool kErrorMessages = true; + + char *Wire(size_t length) { + wire_.resize(kServerWireHeaderSize + length); + return wire_.data(); + } + +private: + std::vector wire_; +}; + +namespace server_wire_internal { + +// Statuses for the fixed-buffer failures. Built once, on the first call, +// which the ASIL connection makes before main. Later calls copy a refcount. +inline absl::Status PermanentError(absl::StatusCode code, + absl::string_view message) { + static const absl::Status build(absl::StatusCode::kResourceExhausted, + "Message is too large to build"); + static const absl::Status send(absl::StatusCode::kResourceExhausted, + "Message is too large to send"); + static const absl::Status not_phaser(absl::StatusCode::kInvalidArgument, + "Not a phaser payload"); + static const absl::Status too_large(absl::StatusCode::kResourceExhausted, + "Phaser payload is too large"); + if (message == "Message is too large to build") { + return build; + } + if (message == "Message is too large to send") { + return send; + } + if (message == "Not a phaser payload") { + return not_phaser; + } + if (message == "Phaser payload is too large") { + return too_large; + } + // A message this function doesn't know. An empty message is inlined, so + // this still doesn't allocate; the text is not available. + return absl::Status(code, absl::string_view()); +} + +} // namespace server_wire_internal + +template class ServerWire { +public: + ServerWire() = default; + explicit ServerWire(Buffers buffers) : buffers_(std::move(buffers)) {} + + absl::StatusOr NewRequest() { return buffers_.NewRequest(); } + absl::StatusOr NewResponse() { + return buffers_.NewResponse(); + } + + // Copies request's native payload into the wire buffer and returns its + // length. The bytes are at Payload(), with kServerWireHeaderSize bytes + // before them. + absl::StatusOr Serialize(const phaser::Request &request) { + return CopyPayload(request); + } + + absl::StatusOr Serialize(const phaser::Response &response) { + return CopyPayload(response); + } + + // The bytes from the last Serialize. + char *Payload() const { return payload_; } + + // Room for a response of length bytes, or nullptr if it doesn't fit. + char *ResponseBuffer(size_t length) { + char *wire = buffers_.Wire(length); + return wire == nullptr ? nullptr : wire + kServerWireHeaderSize; + } + + // Loads a native payload into an owned message. + static absl::Status Decode(const char *data, size_t length, + phaser::Response &response) { + return LoadPayload(data, length, response); + } + + static absl::Status Decode(const char *data, size_t length, + phaser::Request &request) { + return LoadPayload(data, length, request); + } + +private: + // An error with message. Fixed buffers reuse a permanent status so the + // text is visible and reporting the error does not allocate. + static absl::Status Error(absl::StatusCode code, absl::string_view message) { + if (!Buffers::kErrorMessages) { + return server_wire_internal::PermanentError(code, message); + } + return absl::Status(code, message); + } + + template + absl::StatusOr CopyPayload(const Message &message) { + if (message.AllocationFailed()) { + return Error(absl::StatusCode::kResourceExhausted, + "Message is too large to build"); + } + const size_t length = message.ByteSizeLong(); + char *wire = buffers_.Wire(length); + if (wire == nullptr) { + return Error(absl::StatusCode::kResourceExhausted, + "Message is too large to send"); + } + payload_ = wire + kServerWireHeaderSize; + if (length != 0) { + std::memcpy(payload_, message.Data(), length); + } + return length; + } + + template + static absl::Status LoadPayload(const char *data, size_t length, + Message &message) { + if (data == nullptr || + !::phaser::internal::IsStructurallyValidPhaser( + absl::Span(data, length))) { + return Error(absl::StatusCode::kInvalidArgument, + "Not a phaser payload"); + } + Message view = Message::CreateReadonly(data, length); + message.Clear(); + if (absl::Status status = message.CloneFrom(view); !status.ok()) { + message.Clear(); + // Phaser's own failure already names the reason, and that status does + // not allocate. An empty message would hide why this failed. + if (!status.message().empty()) { + return status; + } + return Error(status.code(), "Phaser payload is too large"); + } + if (message.AllocationFailed()) { + message.Clear(); + return Error(absl::StatusCode::kResourceExhausted, + "Phaser payload is too large"); + } + return absl::OkStatus(); + } + + Buffers buffers_; + char *payload_ = nullptr; +}; + +} // namespace subspace diff --git a/common/shm_layout.h b/common/shm_layout.h new file mode 100644 index 00000000..c65e9e82 --- /dev/null +++ b/common/shm_layout.h @@ -0,0 +1,957 @@ +// Copyright 2023-2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +// Shared-memory layout used by every Subspace client. This header is the +// protocol: it includes only the C++ standard library so the ASIL client can +// use the same types as the regular client. + +#ifndef _xCOMMON_SHM_LAYOUT_H +#define _xCOMMON_SHM_LAYOUT_H + +#include "common/atomic_bitset.h" + +#include +#include +#include +#include +#include +#include + +namespace subspace { + +// Shared-memory backends. These name the *mechanism*, not the platform: +// POSIX - a named shm_open object plus a /tmp shadow file. +// LINUX - a named /dev/shm object (mapped by name, server-free). +// MEMFD - an anonymous memfd_create object (no name; the fd is passed to +// other clients via the server). This is a Linux mechanism that +// Android must use because it has no /dev/shm. +#define SUBSPACE_SHMEM_MODE_POSIX 1 +#define SUBSPACE_SHMEM_MODE_LINUX 2 +#define SUBSPACE_SHMEM_MODE_MEMFD 3 + +// The backend is chosen at build time. A build may either define +// SUBSPACE_SHMEM_MODE directly, or (on Linux) define SUBSPACE_LINUX_USE_MEMFD +// to opt the Linux build into the anonymous memfd backend instead of the +// default /dev/shm one. See //:linux_memfd (Bazel) and the +// SUBSPACE_LINUX_USE_MEMFD CMake option. +#ifndef SUBSPACE_SHMEM_MODE +#if defined(__ANDROID__) +// Android has no /dev/shm, so it always uses anonymous memfd shared memory. +#define SUBSPACE_SHMEM_MODE SUBSPACE_SHMEM_MODE_MEMFD +#elif defined(__linux__) +#if defined(SUBSPACE_LINUX_USE_MEMFD) +// Opt-in: anonymous memfd shared memory on Linux (no /dev/shm files). +#define SUBSPACE_SHMEM_MODE SUBSPACE_SHMEM_MODE_MEMFD +#else +// Default on Linux: named /dev/shm shared memory. +#define SUBSPACE_SHMEM_MODE SUBSPACE_SHMEM_MODE_LINUX +#endif +#else +// On other systems, including QNX and macOS, use a /tmp shadow file and +// regular shared memory. +#define SUBSPACE_SHMEM_MODE SUBSPACE_SHMEM_MODE_POSIX +#endif +#endif + +// Flag for flags field in MessagePrefix. +constexpr int kMessageActivate = 1; // This is a reliable activation message. +constexpr int kMessageBridged = 2; // This message came from the bridge. +constexpr int kMessageHasChecksum = 4; // This message has a checksum. +constexpr int kMessageCrossMachine = 8; // This is a cross-machine (tunnel) message. + +// The only flags covered by the message checksum. The publisher sets these +// and they never change once the message is published. Every other bit, +// including kMessageBridged, kMessageCrossMachine and any bit a program sets +// itself, can be changed in transit without invalidating the checksum. +constexpr int64_t kChecksummedMessageFlags = + kMessageActivate | kMessageHasChecksum; + +// Maximum values for checksum_size and metadata_size (must fit in uint16_t). +constexpr int32_t kMaxChecksumSize = 0xFFFF; +constexpr int32_t kMaxMetadataSize = 0xFFFF; + +// This is stored immediately before the channel buffer in shared +// memory. It is transferred intact across the TCP bridges. +// 32 bytes long. +// +// Since this is used primarily for channel bridging, we +// include 4 bytes of padding at offset 0 so that that the +// Socket::SendMessage function has somewhere to put the +// length of the message and avoid 2 sends to the socket. +// +// Note that this precludes us mapping the subscriber's +// channel in read-only memory since the bridge will need +// to write to the padding address when it calls +// Socket::SendMessage. +// +// On the receiving end of the bridge, the padding is +// not received and will not be written to. +struct MessagePrefix { + int32_t padding; // Padding for Socket::SendMessage. + int32_t slot_id; // The slot ID this message is in. + uint64_t message_size; + uint64_t ordinal; + uint64_t timestamp; + int64_t flags; + int32_t vchan_id; + uint16_t checksum_size; + uint16_t metadata_size; + uint32_t checksum; + char padding3[64 - 52]; // Align to 64 bytes. + + bool IsActivation() const { return (flags & kMessageActivate) != 0; } + void SetIsActivation() { flags |= kMessageActivate; } + bool IsBridged() const { return (flags & kMessageBridged) != 0; } + void SetIsBridged() { flags |= kMessageBridged; } + bool HasChecksum() const { return (flags & kMessageHasChecksum) != 0; } + void SetHasChecksum() { flags |= kMessageHasChecksum; } + bool IsCrossMachine() const { return (flags & kMessageCrossMachine) != 0; } + void SetIsCrossMachine() { flags |= kMessageCrossMachine; } +}; + +static_assert(sizeof(MessagePrefix) == 64, + "MessagePrefix size is not 64 bytes"); + +// Flags for MessageSlot flags. +constexpr int kMessageSeen = 1; // Message has been seen by any subscriber. +constexpr int kMessageIsActivation = 2; // This is an activation message. +constexpr int kMessageSeenByReliable = + 4; // Message has been seen by a reliable subscriber. + +// Maximum channels in one server session. The system control block in +// shared memory is sized from this, so the server and every client must be +// built with the same value. A downstream Bazel module sets +// subspace.max_channels(count = N) in its root MODULE.bazel. Building this +// repo uses --//:max_channels=N, and CMake uses -DSUBSPACE_MAX_CHANNELS=N. +// N must be a positive multiple of 64 because channel ids are stored in a +// bitset of 64-bit words. +#ifndef SUBSPACE_MAX_CHANNELS +#define SUBSPACE_MAX_CHANNELS 1024 +#endif +constexpr int kMaxChannels = SUBSPACE_MAX_CHANNELS; +static_assert(kMaxChannels > 0 && kMaxChannels % 64 == 0, + "SUBSPACE_MAX_CHANNELS must be a positive multiple of 64"); + +// Maximum publishers plus subscribers per channel. This sizes CCB fields in +// shared memory, so the server and every client must be built with the same +// value. A downstream Bazel module sets subspace.max_slot_owners(count = N) +// in its root MODULE.bazel. Building this repo uses --//:max_slot_owners=N, +// and CMake uses -DSUBSPACE_MAX_SLOT_OWNERS=N. N must be a positive integer. +#ifndef SUBSPACE_MAX_SLOT_OWNERS +#define SUBSPACE_MAX_SLOT_OWNERS 1024 +#endif +constexpr int kMaxSlotOwners = SUBSPACE_MAX_SLOT_OWNERS; +static_assert(kMaxSlotOwners > 0, "SUBSPACE_MAX_SLOT_OWNERS must be positive"); +// Default per-subscriber queue depth used whenever the publisher provisions a +// non-empty arena and the subscriber does not request an override. +constexpr int kDefaultSubscriberQueueSize = 16; +// Standard packed arena size for callers that opt into subscriber queues. This +// fits 100 default-sized (16-entry) queues. Publisher options default to zero, +// which keeps the available-slot bitset path and omits the queue arena. +constexpr uint64_t kDefaultSubscriberQueueArenaSize = 64'000; +constexpr size_t kDefaultMaxAvailableSlotQueueCapacity = 1024; +constexpr size_t kMaxSlotQueueCasAttempts = 64; +// Bumped when the slot retirement field became a publish-time countdown and +// MessageSlot gained the per-subscriber obligation bitset. Older clients must +// not map a version 6 control block. +constexpr uint32_t kChannelControlBlockVersion = 6; +constexpr size_t kMaxChannelControlBlockSize = 1ULL << 30; + +// This limits the number of virtual channels. Each virtual channel +// needs its own ordinal counter in the CCB (8 bytes each). +// This is stored in the refs field as a 10-bit value. If all bits are set +// this indicates -1 (no vchan_id). +constexpr int kMaxVchanId = 1023; + +// Max length of a channel name in shared memory. A name longer +// this this will be truncated but the full name will be available +// in process memory. +constexpr size_t kMaxChannelName = 64; + +// Maximum distinct shared-memory payload segments tracked in the BCB (refs and +// sizes tables). Each slot-size resize can add another segment until +// ccb_->num_buffers reaches this limit. A downstream Bazel module sets +// subspace.max_buffers(count = N) in its root MODULE.bazel. Building this +// repo uses --//:max_buffers=N, and CMake uses -DSUBSPACE_MAX_BUFFERS=N. N +// must be a positive integer. The default (341) yields a 4096-byte BCB on +// typical platforms (4-byte atomic int32 refs plus 8-byte atomic uint64 sizes). +#ifndef SUBSPACE_MAX_BUFFERS +#define SUBSPACE_MAX_BUFFERS 341 +#endif +constexpr size_t kMaxBuffers = SUBSPACE_MAX_BUFFERS; +static_assert(kMaxBuffers > 0, "SUBSPACE_MAX_BUFFERS must be positive"); + +// Ref count bits. +constexpr uint64_t kRefCountMask = 0x3ff; +constexpr uint64_t kRefCountShift = 10; +constexpr uint64_t kReliableRefCountShift = 10; +constexpr uint64_t kPubOwned = 1ULL << 63; +constexpr uint64_t kRefsMask = (1ULL << 20) - 1; // 20 bits +constexpr uint64_t kReliableRefsMask = ((1ULL << 10) - 1) + << kReliableRefCountShift; +// Subscribers who were delivered this message and have not yet finished with +// it. Set to that count when the message is published and decremented as each +// of them releases the slot or disconnects. The slot is retired at zero. +// A subscriber who joins later is not counted, so they cannot hold the slot. +constexpr uint64_t kPendingSize = 10; +constexpr uint64_t kPendingMask = (1ULL << kPendingSize) - 1; +constexpr uint64_t kPendingShift = 20; + +// Virtual channel ID is just above the pending count and is 10 bits long. +constexpr uint64_t kVchanIdShift = kPendingShift + kPendingSize; +constexpr uint64_t kVchanIdSize = 10; +constexpr uint64_t kVchanIdMask = (1ULL << kVchanIdSize) - 1; + +// We put the bottom 23 bits of the ordinal just above the +// vchan ID field. This is to ensure that a publisher +// hasn't published another message in the slot before a subscriber +// increments the ref count. +constexpr uint64_t kOrdinalSize = 23; +constexpr uint64_t kOrdinalMask = (1ULL << kOrdinalSize) - 1; +constexpr uint64_t kOrdinalShift = 40; + +inline int PendingCount(uint64_t refs) { + return static_cast((refs >> kPendingShift) & kPendingMask); +} + +// Combine an ordinal, a vchan_id and a pending count into the refs field. +inline uint64_t BuildRefsBitField(uint64_t ordinal, int vchan_id, int pending) { + return ((ordinal & kOrdinalMask) << kOrdinalShift) | + (ordinal == 0 ? 0 : ((vchan_id & kVchanIdMask) << kVchanIdShift)) | + ((static_cast(pending) & kPendingMask) << kPendingShift); +} + +// Aligned to given power of 2. +template constexpr int64_t Aligned(int64_t v) { + return (v + (alignment - 1)) & ~(alignment - 1); +} + +// This is a global (to a server) structure in shared memory that holds +// counts for the number of updates to publishers and subscribers on +// that server. The server updates these counts when a publisher or +// subscriber is created or deleted. The purpose is to allow a client +// to check if it needs to update its local information about the +// channel by contacting the server. Things such as trigger file +// descriptors are distributed by the server to clients. +// +// This is in shared memory, but it is only ever written by the +// server. +struct ChannelCounters { + uint16_t num_pub_updates; // Number of updates to publishers. + uint16_t num_sub_updates; // Number of updates to subscribers. + uint16_t num_pubs; // Current number of publishers. + uint16_t num_reliable_pubs; // Current number of reliable publishers. + uint16_t num_subs; // Current number of subscribers. + uint16_t num_reliable_subs; // Current number of reliable subscribers. + uint16_t num_resizes; // Number of times channel has been resized. +}; + +struct SystemControlBlock { + ChannelCounters counters[kMaxChannels]; +}; + +// This is the meta data for a slot. +struct MessageSlot { + std::atomic refs; // Number of subscribers referring to this slot. + std::atomic ordinal; // Message ordinal held currently in slot. + std::atomic message_size; // Size of message held in slot. + int32_t id; // Unique ID for slot (0...num_slots-1). + std::atomic buffer_index; // Index of buffer. + std::atomic vchan_id; // Virtual channel ID. + AtomicBitSet sub_owners; // One bit per subscriber. + std::atomic timestamp; // Timestamp of message. + std::atomic flags; + std::atomic + bridged_slot_id; // Slot ID of other side of bridge. + // Subscribers still obliged to decrement the pending count for the message + // currently in this slot. Empty while a publisher owns the slot. + AtomicBitSet pending_subs; + + void Dump(std::ostream &os) const; +}; +static_assert(offsetof(MessageSlot, refs) == 0); +static_assert(offsetof(MessageSlot, ordinal) == 8); +static_assert(offsetof(MessageSlot, message_size) == 16); +static_assert(offsetof(MessageSlot, id) == 24); +static_assert(offsetof(MessageSlot, buffer_index) == 28); +static_assert(offsetof(MessageSlot, vchan_id) == 30); +static_assert(offsetof(MessageSlot, sub_owners) == 32); +static_assert(offsetof(MessageSlot, timestamp) == + offsetof(MessageSlot, sub_owners) + + sizeof(AtomicBitSet)); +static_assert(offsetof(MessageSlot, flags) == + offsetof(MessageSlot, timestamp) + sizeof(std::atomic)); +static_assert(offsetof(MessageSlot, bridged_slot_id) == + offsetof(MessageSlot, flags) + sizeof(std::atomic)); +static_assert(offsetof(MessageSlot, pending_subs) == + ((offsetof(MessageSlot, bridged_slot_id) + + sizeof(std::atomic) + 7) & + ~size_t{7})); +static_assert(sizeof(MessageSlot) == + offsetof(MessageSlot, pending_subs) + + sizeof(AtomicBitSet)); +// 1024 owners: the original 184-byte slot plus one 136-byte obligation bitset +// placed on an 8-byte boundary (4 bytes of padding after bridged_slot_id). +static_assert(kMaxSlotOwners != 1024 || sizeof(MessageSlot) == 320); + +struct ActiveSlot { + MessageSlot *slot; + uint64_t ordinal; + uint64_t timestamp; + int vchan_id; +}; + +struct QueuedSlot { + int32_t slot_id; + uint64_t ordinal; +}; + +struct SlotQueueEntry { + // Sequence number used to publish an entry after its payload is written and + // to mark it reusable after the consumer has popped it. + std::atomic sequence; + std::atomic ordinal; + std::atomic slot_id; +}; +static_assert(sizeof(SlotQueueEntry) == 24); +static_assert(offsetof(SlotQueueEntry, sequence) == 0); +static_assert(offsetof(SlotQueueEntry, ordinal) == 8); +static_assert(offsetof(SlotQueueEntry, slot_id) == 16); + +// A bounded MPSC queue stored in shared memory after the available-slots +// bitsets. Publishers push slot IDs as they publish; the single owning +// subscriber pops them to avoid scanning its bitset. For unreliable subscribers +// this queue is the hot-path source of truth; the bitset is still maintained for +// reliable mode and diagnostics while the queue path is proven out. +class InPlaceSlotQueue { +public: + InPlaceSlotQueue(size_t capacity, bool drop_oldest = true) { + Init(capacity, drop_oldest); + } + + // Initialize queue metadata and mark every ring entry as free. `capacity` + // is the number of SlotQueueEntry objects laid out immediately after this + // header in shared memory. + void Init(size_t capacity, bool drop_oldest = true) { + capacity_ = capacity; + head_.store(0, std::memory_order_relaxed); + tail_.store(0, std::memory_order_relaxed); + overflow_count_.store(0, std::memory_order_relaxed); + insertion_failed_.store(false, std::memory_order_relaxed); + drop_oldest_ = drop_oldest; + for (size_t i = 0; i < capacity_; i++) { + entries_[i].sequence.store(i, std::memory_order_relaxed); + entries_[i].ordinal.store(0, std::memory_order_relaxed); + entries_[i].slot_id.store(-1, std::memory_order_relaxed); + } + } + + size_t Capacity() const { return capacity_; } + bool DropsOldest() const { return drop_oldest_; } + uint64_t Head() const { return head_.load(std::memory_order_acquire); } + uint64_t Tail() const { return tail_.load(std::memory_order_acquire); } + + // Push a published slot. Multiple publishers may call this concurrently. + // If an explicit queue is full, evict its oldest hint and enqueue the newest + // one. An inherited queue instead rejects the hint so its subscriber recovers + // every unread ordinal from the authoritative bitset. + bool Push(int32_t slot_id, uint64_t ordinal, + bool report_insertion_failure = true) { + return Push(slot_id, ordinal, report_insertion_failure, + [](const QueuedSlot &) { return true; }); + } + + // An evicted message is dropped for the subscriber, but its bit in the + // subscriber's bitset would otherwise let it be read after newer messages. + // `forget` is called with the oldest hint before it leaves the queue so the + // caller can clear that bit. If it returns false the hint stays and the push + // fails. + template + bool Push(int32_t slot_id, uint64_t ordinal, bool report_insertion_failure, + Forget &&forget) { + if (capacity_ == 0) { + if (report_insertion_failure) { + MarkInsertionFailure(); + } + return false; + } + + SlotQueueEntry *entry = nullptr; + uint64_t tail = tail_.load(std::memory_order_relaxed); + for (size_t attempt = 0; attempt < kMaxSlotQueueCasAttempts; ++attempt) { + const uint64_t head = head_.load(std::memory_order_acquire); + if (tail - head >= capacity_) { + // Inherited queues preserve legacy no-drop delivery through the + // authoritative bitset. Do not expose a newer queue entry before the + // subscriber observes the fallback signal. + if (!drop_oldest_) { + if (report_insertion_failure) { + MarkInsertionFailure(); + } + return false; + } + if (!EvictFront(forget)) { + if (report_insertion_failure) { + MarkInsertionFailure(); + } + return false; + } + overflow_count_.fetch_add(1, std::memory_order_release); + tail = tail_.load(std::memory_order_relaxed); + continue; + } + SlotQueueEntry &candidate = entries_[tail % capacity_]; + // A consumer publishes the reusable sequence after advancing head_. It + // may be paused or terminated between those operations. Do not reserve + // the entry until it is reusable: reserving first would force this + // producer to wait indefinitely for that consumer. + if (candidate.sequence.load(std::memory_order_acquire) != tail) { + if (report_insertion_failure) { + MarkInsertionFailure(); + } + return false; + } + if (tail_.compare_exchange_strong(tail, tail + 1, + std::memory_order_acq_rel, + std::memory_order_relaxed)) { + entry = &candidate; + break; + } + } + if (entry == nullptr) { + if (report_insertion_failure) { + MarkInsertionFailure(); + } + return false; + } + + entry->slot_id.store(slot_id, std::memory_order_relaxed); + entry->ordinal.store(ordinal, std::memory_order_relaxed); + entry->sequence.store(tail + 1, std::memory_order_release); + return true; + } + + void MarkInsertionFailure() { + insertion_failed_.store(true, std::memory_order_release); + } + + // Read the oldest queued slot without consuming it. This lets poll-driven + // subscribers stop at the end of a stable drain snapshot without losing the + // first newer message. `position` identifies the entry for PopAt(). + bool TryPeek(QueuedSlot &slot, uint64_t &position) { + if (capacity_ == 0) { + return false; + } + + const uint64_t head = head_.load(std::memory_order_acquire); + SlotQueueEntry &entry = entries_[head % capacity_]; + if (entry.sequence.load(std::memory_order_acquire) != head + 1) { + return false; + } + + QueuedSlot candidate = { + entry.slot_id.load(std::memory_order_relaxed), + entry.ordinal.load(std::memory_order_relaxed), + }; + if (entry.sequence.load(std::memory_order_acquire) != head + 1) { + return false; + } + slot = candidate; + position = head; + return true; + } + + // Consume the entry that TryPeek() returned at `position`. This fails if a + // producer evicted it first, rather than consuming the entry behind it. + bool PopAt(uint64_t position) { + if (capacity_ == 0) { + return false; + } + uint64_t head = position; + if (!head_.compare_exchange_strong(head, position + 1, + std::memory_order_acq_rel, + std::memory_order_relaxed)) { + return false; + } + entries_[position % capacity_].sequence.store(position + capacity_, + std::memory_order_release); + return true; + } + + // Drop the oldest queued slot. The subscriber uses this to discard queued + // hints it no longer needs. + bool DropFront() { + if (capacity_ == 0) { + return false; + } + + uint64_t head = head_.load(std::memory_order_relaxed); + for (size_t attempt = 0; attempt < kMaxSlotQueueCasAttempts; ++attempt) { + SlotQueueEntry &entry = entries_[head % capacity_]; + if (entry.sequence.load(std::memory_order_acquire) != head + 1) { + return false; + } + if (head_.compare_exchange_weak(head, head + 1, + std::memory_order_acq_rel, + std::memory_order_relaxed)) { + entry.sequence.store(head + capacity_, std::memory_order_release); + return true; + } + } + return false; + } + + // Discard a bounded snapshot of queued hints. The available-slot bitset + // remains authoritative, so subscribers use this after switching to bitset + // recovery following queue overflow or insertion failure. + void DiscardAll() { + for (size_t i = 0; i < capacity_; ++i) { + if (!DropFront()) { + return; + } + } + } + + // Pop one slot for the owning subscriber. There is exactly one consumer per + // queue, but producers may advance head_ to evict on overflow, so the + // consumer claims the front entry with a CAS. + bool TryPop(QueuedSlot &slot) { + if (capacity_ == 0) { + return false; + } + + uint64_t head = head_.load(std::memory_order_relaxed); + for (size_t attempt = 0; attempt < kMaxSlotQueueCasAttempts; ++attempt) { + SlotQueueEntry &entry = entries_[head % capacity_]; + if (entry.sequence.load(std::memory_order_acquire) != head + 1) { + return false; + } + QueuedSlot candidate = { + entry.slot_id.load(std::memory_order_relaxed), + entry.ordinal.load(std::memory_order_relaxed), + }; + if (head_.compare_exchange_weak(head, head + 1, + std::memory_order_acq_rel, + std::memory_order_relaxed)) { + slot = candidate; + entry.sequence.store(head + capacity_, std::memory_order_release); + return true; + } + } + return false; + } + + // Return and clear the number of older queued slots evicted to preserve the + // newest data. + uint32_t ConsumeOverflow() { + return overflow_count_.exchange(0, std::memory_order_acq_rel); + } + + uint32_t OverflowCount() const { + return overflow_count_.load(std::memory_order_acquire); + } + + bool ConsumeInsertionFailure() { + return insertion_failed_.exchange(false, std::memory_order_acq_rel); + } + + bool InsertionFailed() const { + return insertion_failed_.load(std::memory_order_acquire); + } + +private: + // Drop the oldest queued slot for a producer that needs room. The subscriber + // can pop past the entry as soon as head_ moves, so `forget` must finish + // first. + template bool EvictFront(Forget &forget) { + uint64_t head = head_.load(std::memory_order_relaxed); + for (size_t attempt = 0; attempt < kMaxSlotQueueCasAttempts; ++attempt) { + SlotQueueEntry &entry = entries_[head % capacity_]; + if (entry.sequence.load(std::memory_order_acquire) != head + 1) { + return false; + } + const QueuedSlot evicted = { + entry.slot_id.load(std::memory_order_relaxed), + entry.ordinal.load(std::memory_order_relaxed), + }; + if (entry.sequence.load(std::memory_order_acquire) != head + 1) { + head = head_.load(std::memory_order_relaxed); + continue; + } + if (!forget(evicted)) { + return false; + } + if (head_.compare_exchange_strong(head, head + 1, + std::memory_order_acq_rel, + std::memory_order_relaxed)) { + entry.sequence.store(head + capacity_, std::memory_order_release); + return true; + } + } + return false; + } + + // Fixed ring capacity for this queue, capped independently of the channel's + // slot count to keep shared-memory usage bounded. + size_t capacity_ = 0; + // Next sequence number the single subscriber will try to pop. + std::atomic head_{0}; + // Next sequence number producers will reserve for Push(). + std::atomic tail_{0}; + std::atomic overflow_count_{0}; + std::atomic insertion_failed_{false}; + // Explicit queues drop their oldest hint on overflow. Inherited queues leave + // the queue unchanged and force the subscriber to recover from its bitset. + bool drop_oldest_ = true; + // Flexible array of `capacity_` entries stored immediately after the header. + SlotQueueEntry entries_[0]; +}; +static_assert(sizeof(InPlaceSlotQueue) == 32); + +inline size_t SizeofSlotQueue(size_t capacity) { + return sizeof(InPlaceSlotQueue) + sizeof(SlotQueueEntry) * capacity; +} + +constexpr uint64_t kInvalidSlotQueueOffset = + std::numeric_limits::max(); + +inline int ResolveSubscriberQueueSize(int num_slots, + int subscriber_queue_size) { + if (num_slots <= 0 || subscriber_queue_size <= 0) { + return 0; + } + return subscriber_queue_size; +} + +struct BufferControlBlock { + std::atomic + refs[kMaxBuffers]; // Number of references to this buffer. + std::atomic + sizes[kMaxBuffers]; // Byte size of this buffer segment. +}; + +class SubscriberCounter { +public: + SubscriberCounter() { + sequence_.store(0, std::memory_order_relaxed); + ResetCounts(); + } + + SubscriberCounter(const SubscriberCounter &other) { + sequence_.store(0, std::memory_order_relaxed); + for (size_t i = 0; i < num_subs_.size(); ++i) { + num_subs_[i].store( + other.num_subs_[i].load(std::memory_order_acquire), + std::memory_order_relaxed); + } + } + + SubscriberCounter &operator=(const SubscriberCounter &other) { + if (this == &other) { + return *this; + } + const uint64_t sequence = + sequence_.load(std::memory_order_relaxed) & ~uint64_t{1}; + sequence_.store(sequence + 1, std::memory_order_release); + for (size_t i = 0; i < num_subs_.size(); ++i) { + num_subs_[i].store( + other.num_subs_[i].load(std::memory_order_acquire), + std::memory_order_relaxed); + } + sequence_.store(sequence + 2, std::memory_order_release); + return *this; + } + + void Reset() { + BeginWrite(); + ResetCounts(); + EndWrite(); + } + + void AddSubscriber(int vchan_id) { + BeginWrite(); + num_subs_[vchan_id + 1].fetch_add(1, std::memory_order_relaxed); + EndWrite(); + } + + void RemoveSubscriber(int vchan_id) { + BeginWrite(); + num_subs_[vchan_id + 1].fetch_sub(1, std::memory_order_relaxed); + EndWrite(); + } + + // If vchan_id is valid we also count the number of subscribers to the + // multiplexer itself. + int NumSubscribers(int vchan_id) const { + for (;;) { + const uint64_t before = sequence_.load(std::memory_order_acquire); + if ((before & 1) != 0) { + // A server process can die between BeginWrite and EndWrite. Treat an + // interrupted update conservatively instead of making surviving + // clients spin forever; the recovered server rebuilds the counter. + return kMaxSlotOwners; + } + const int mux_count = num_subs_[0].load(std::memory_order_relaxed); + const int count = + vchan_id == -1 + ? mux_count + : mux_count + + num_subs_[vchan_id + 1].load(std::memory_order_relaxed); + if (sequence_.load(std::memory_order_acquire) == before) { + return count; + } + } + } + +private: + void BeginWrite() { + sequence_.fetch_add(1, std::memory_order_acq_rel); + } + + void EndWrite() { sequence_.fetch_add(1, std::memory_order_release); } + + void ResetCounts() { + for (auto &count : num_subs_) { + count.store(0, std::memory_order_relaxed); + } + } + + // Vchan ID -1 means invalid vchan ID so we just use element 0 for that. + std::atomic sequence_; + std::array, kMaxVchanId + 1> num_subs_; +}; + +class SubscriberCleanupGeneration { +public: + SubscriberCleanupGeneration() { + for (auto &generation : generations_) { + generation.store(0, std::memory_order_relaxed); + } + } + + void Increment(int vchan_id) { + generations_[vchan_id + 1].fetch_add(1, std::memory_order_release); + } + + uint64_t Get(int vchan_id) const { + const uint64_t mux_generation = + generations_[0].load(std::memory_order_acquire); + if (vchan_id == -1) { + return mux_generation; + } + return mux_generation + + generations_[vchan_id + 1].load(std::memory_order_acquire); + } + +private: + std::array, kMaxVchanId + 1> generations_; +}; + +class OrdinalAccumulator { +public: + void Init(int v) { + for (int i = 0; i < kMaxVchanId + 1; i++) { + ordinals_[i] = v; + } + } + uint64_t Next(int vchan_id) { return ordinals_[vchan_id + 1]++; } + uint64_t PeekNext(int vchan_id) const { + return ordinals_[vchan_id + 1].load(std::memory_order_relaxed); + } + +private: + std::array, kMaxVchanId + 1> ordinals_ = {}; +}; + +class ActivationTracker { +public: + void Activate(int vchan_id) { activations_.Set(vchan_id + 1); } + bool IsActivated(int vchan_id) const { + return activations_.IsSet(vchan_id + 1); + } + +private: + AtomicBitSet activations_; // One bit per vchan_id. +}; +static_assert(sizeof(ActivationTracker) == + sizeof(AtomicBitSet)); + +// The control data for a channel. This memory is +// allocated by the server and mapped into the process +// for all publishers and subscribers. Each mapped CCB is mapped +// at a virtual address chosen by the OS. +// +// This is in shared memory so no pointers are possible. +struct ChannelControlBlock { // a.k.a CCB + char channel_name[kMaxChannelName]; // So that you can see the name in a + // debugger or hexdump. + int num_slots; + int subscriber_queue_size; // Fixed inherited per-subscriber queue capacity. + uint32_t version; + OrdinalAccumulator ordinals; // Ordinal accumulator for virtual channels. + ActivationTracker activation_tracker; // Tracks which vchan_ids have been + // activated by a publisher. + int buffer_index; // Which buffer in buffers array to use. + std::atomic num_buffers; // Size of buffers array in shared memory. + AtomicBitSet subscribers; // One bit per subscriber. + + // Given a subscriber ID, what is the vchan ID associated with it. + std::array sub_vchan_ids; + + SubscriberCounter num_subs; + // Incremented by the server after removing a subscriber and before its + // all-slot retirement scan. Publishers use this to determine whether + // subscriber cleanup raced their publication commit. + SubscriberCleanupGeneration subscriber_cleanup_generation; + + // Statistics counters. + std::atomic total_bytes; + // Number of completed publications, including activation messages. This is + // also the version stamp for subscriber delivery snapshots. + std::atomic total_messages; + std::atomic max_message_size; + std::atomic total_drops; + + // If true there are no more free slots and there's no need to check + // the bitset for them (there will never be another free slot) + std::atomic free_slots_exhausted; + + // Variable number of MessageSlot structs (num_slots long). + MessageSlot slots[0]; + // Followed by: + // AtomicBitSet<0> retiredSlots[num_slots]; + // Followed by: + // AtomicBitSet<0> freeSlots[num_slots]; + // Followed by: + // AtomicBitSet<0> availableSlots[kMaxSlotOwners]; + // Followed by: + // AvailableSlotQueueIndex availableSlotQueueIndex; + // Followed by: + // A packed arena of variable-capacity InPlaceSlotQueue objects. + // +}; +static_assert(offsetof(ChannelControlBlock, version) == 72); +// The Rust client mirrors this struct, so pin the stats block too. Both +// languages must agree or they will read different shared memory. +static_assert(offsetof(ChannelControlBlock, total_messages) == + offsetof(ChannelControlBlock, total_bytes) + 8); +static_assert(offsetof(ChannelControlBlock, max_message_size) == + offsetof(ChannelControlBlock, total_messages) + 8); +static_assert(offsetof(ChannelControlBlock, total_drops) == + offsetof(ChannelControlBlock, max_message_size) + 8); + +// Locates each subscriber's variable-capacity queue in the packed queue arena. +// Offsets are relative to the start of the arena. +struct AvailableSlotQueueIndex { + std::atomic next_offset; + std::array, kMaxSlotOwners> offsets; + std::array, kMaxSlotOwners> active_publishers; +}; +static_assert(offsetof(AvailableSlotQueueIndex, next_offset) == 0); +static_assert(offsetof(AvailableSlotQueueIndex, offsets) == + sizeof(std::atomic)); +static_assert(offsetof(AvailableSlotQueueIndex, active_publishers) == + offsetof(AvailableSlotQueueIndex, offsets) + + sizeof(std::atomic) * kMaxSlotOwners); +static_assert(sizeof(AvailableSlotQueueIndex) == + static_cast(Aligned( + static_cast( + offsetof(AvailableSlotQueueIndex, active_publishers) + + sizeof(std::atomic) * kMaxSlotOwners)))); +static_assert(kMaxSlotOwners != 1024 || + (offsetof(AvailableSlotQueueIndex, active_publishers) == 8200 && + sizeof(AvailableSlotQueueIndex) == 12296)); + +inline size_t AvailableSlotsSize(int num_slots) { + return SizeofAtomicBitSet(num_slots) * kMaxSlotOwners; +} + +inline size_t AvailableSlotQueueIndexSize() { + return Aligned(sizeof(AvailableSlotQueueIndex)); +} + +enum class SlotQueueBlockState : uint32_t { + kAllocated = 0, + kRetired = 1, + kFree = 2, +}; + +struct alignas(64) SlotQueueBlockHeader { + uint64_t block_size = 0; + std::atomic state{ + static_cast(SlotQueueBlockState::kFree)}; + uint32_t reserved = 0; + AtomicBitSet waiting_publishers; +}; +static_assert(offsetof(SlotQueueBlockHeader, waiting_publishers) == 16); +static_assert(sizeof(SlotQueueBlockHeader) == + static_cast(Aligned<64>(static_cast( + offsetof(SlotQueueBlockHeader, waiting_publishers) + + sizeof(AtomicBitSet))))); +static_assert(kMaxSlotOwners != 1024 || sizeof(SlotQueueBlockHeader) == 192); + +inline size_t SlotQueueBlockHeaderSize() { + return Aligned(sizeof(SlotQueueBlockHeader)); +} + +inline size_t SlotQueueBlockSize(size_t capacity) { + return SlotQueueBlockHeaderSize() + Aligned(SizeofSlotQueue(capacity)); +} + +inline size_t CcbSize(int num_slots, uint64_t subscriber_queue_arena_size) { + return Aligned(sizeof(ChannelControlBlock) + + num_slots * sizeof(MessageSlot)) + + Aligned(SizeofAtomicBitSet(num_slots)) * 2 + + AvailableSlotsSize(num_slots) + + AvailableSlotQueueIndexSize() + + static_cast(subscriber_queue_arena_size); +} + +inline size_t CcbSize(int num_slots) { + return CcbSize(num_slots, /*subscriber_queue_arena_size=*/0); +} + +// The vchan_id stored in a refs word. All ones means -1. +inline int RefsVchanId(uint64_t refs) { + const uint64_t v = (refs >> kVchanIdShift) & kVchanIdMask; + return v == kVchanIdMask ? -1 : static_cast(v); +} + +// Offsets of the regions that follow the slots in a channel control block: +// retired slots, free slots, one available-slot bitset per subscriber, the +// subscriber queue index and the queue arena. +inline size_t RetiredSlotsOffset(int num_slots) { + return static_cast(Aligned(sizeof(ChannelControlBlock) + + num_slots * sizeof(MessageSlot))); +} + +inline size_t FreeSlotsOffset(int num_slots) { + return RetiredSlotsOffset(num_slots) + + static_cast(Aligned(SizeofAtomicBitSet(num_slots))); +} + +inline size_t AvailableSlotsOffset(int num_slots, int sub_id) { + return FreeSlotsOffset(num_slots) + + static_cast(Aligned(SizeofAtomicBitSet(num_slots))) + + SizeofAtomicBitSet(num_slots) * static_cast(sub_id); +} + +inline size_t SlotQueueIndexOffset(int num_slots) { + return AvailableSlotsOffset(num_slots, kMaxSlotOwners); +} + +inline size_t SlotQueueArenaOffset(int num_slots) { + return SlotQueueIndexOffset(num_slots) + AvailableSlotQueueIndexSize(); +} + +inline int32_t PrefixSize(int32_t checksum_size, int32_t metadata_size) { + return static_cast( + Aligned<64>(offsetof(MessagePrefix, checksum) + checksum_size + + metadata_size)); +} + +} // namespace subspace + +#endif diff --git a/common/slot_search.h b/common/slot_search.h new file mode 100644 index 00000000..096ccca0 --- /dev/null +++ b/common/slot_search.h @@ -0,0 +1,456 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +// Finding and claiming a slot for a publisher's next message, shared by every +// client. + +#pragma once + +#include "common/bitset_view.h" +#include "common/channel_view.h" +#include "common/shm_layout.h" + +#include +#include +#include + +namespace subspace { + +// A client's part in a slot search. A client derives from this, keeps or +// replaces the defaults, and adds: +// +// // Gives the claimed slot the buffer its next message goes in. +// void AssignBuffer(MessageSlot *slot); +// MessagePrefix *Prefix(MessageSlot *slot); +// // The claimed slot held a message that a subscriber might not have read. +// void ForcedReuse(MessageSlot *slot); +// +// The defaults suit a client that maps all of a channel's buffers when it +// opens the channel. +class SlotSearchHooks { +public: + // Called before each attempt to find a slot, for example to map buffers + // that another publisher added. + void BeforeAttempt() {} + // Whether the publisher can use a slot it has claimed. The search gives a + // slot it can't use back and embargoes it for the rest of the search. + bool UsableSlot(MessageSlot * /*slot*/) { return true; } + void Embargo(int /*slot_id*/) {} + bool Embargoed(int /*slot_id*/) const { return false; } +}; + +struct SlotSearch { + // Stored in refs, with kPubOwned, while the publisher owns the slot. + int owner = 0; + int vchan_id = -1; + // An unreliable publisher takes a retired slot before a free one while + // anything subscribes. See PublisherOptions::SetPreferRetiredSlots(). + bool prefer_retired = false; + // Whether a reliable publisher takes retired slots. A tunnel publisher + // doesn't. + bool reuse_retired = true; +}; + +// Clears every subscriber's available bit for slot, whose message is gone. +inline void ForgetMessage(const ChannelView &channel, const MessageSlot *slot) { + channel.Subscribers().Traverse( + [&](int sub_id) { channel.AvailableSlots(sub_id).Clear(slot->id); }); +} + +// Resets a slot the publisher has just claimed for a message on vchan_id. +template +void ResetClaimedSlot(const ChannelView &channel, MessageSlot *slot, + int vchan_id, Hooks &hooks) { + slot->ordinal.store(0, std::memory_order_relaxed); + slot->timestamp.store(0, std::memory_order_relaxed); + slot->vchan_id.store(static_cast(vchan_id), + std::memory_order_relaxed); + hooks.AssignBuffer(slot); + MessagePrefix *prefix = hooks.Prefix(slot); + prefix->flags = 0; + prefix->vchan_id = vchan_id; + slot->pending_subs.ClearAll(); + ForgetMessage(channel, slot); +} + +// The retired slot to reuse next, or -1. +// +// Normally a slot is only retired once every subscriber has seen and dropped +// it, so the retired pool stays small and taking the lowest-index slot keeps +// the publisher on the cache-hot working set that SetPreferRetiredSlots() +// exists to produce. +// +// With nothing subscribed every slot is retired the instant it is published, +// so the retired pool is the whole ring and the lowest-index slot is the one +// holding the oldest message. Reusing that slot puts it straight back at the +// front of the pool, so the publisher would overwrite it forever while the +// rest of the ring stayed frozen on the messages that happened to be +// published first, and a subscriber attaching later would read those rather +// than recent history. With oldest_first, recycling the oldest message +// rotates through the ring instead. +template +int RetiredSlotToReuse(const ChannelView &channel, const Hooks &hooks, + bool oldest_first) { + BitsetView retired = channel.RetiredSlots(); + if (!oldest_first) { + const int first = retired.FindFirstSet(); + if (first == -1 || !hooks.Embargoed(first)) { + return first; + } + for (int i = first + 1; i < channel.NumSlots(); i++) { + if (retired.IsSet(i) && !hooks.Embargoed(i)) { + return i; + } + } + return -1; + } + int oldest = -1; + uint64_t oldest_timestamp = ~uint64_t{0}; + for (int i = 0; i < channel.NumSlots(); i++) { + if (!retired.IsSet(i) || hooks.Embargoed(i)) { + continue; + } + const uint64_t timestamp = + channel.Slot(i)->timestamp.load(std::memory_order_relaxed); + if (timestamp < oldest_timestamp) { + oldest_timestamp = timestamp; + oldest = i; + } + } + return oldest; +} + +namespace slot_search_internal { + +enum class Pick { kTaken, kNone, kRetry }; + +// Takes a slot that has never held a message. +inline Pick TakeFreeSlot(const ChannelView &channel, int &slot_id) { + ChannelControlBlock *ccb = channel.Ccb(); + if (ccb->free_slots_exhausted.load(std::memory_order_relaxed)) { + return Pick::kNone; + } + BitsetView free_slots = channel.FreeSlots(); + slot_id = free_slots.FindFirstSet(); + if (slot_id == -1) { + return Pick::kNone; + } + // FindFirstSet uses relaxed loads, so only the publisher whose ClearWasSet + // returns true owns the bit. + if (!free_slots.ClearWasSet(slot_id)) { + slot_id = -1; + return Pick::kRetry; + } + if (free_slots.IsEmpty()) { + ccb->free_slots_exhausted.store(true, std::memory_order_relaxed); + } + return Pick::kTaken; +} + +// Takes a slot whose message every subscriber has released. The caller +// checks the refs, because the bit can be stale. +template +Pick TakeRetiredSlot(const ChannelView &channel, const Hooks &hooks, + bool oldest_first, int &slot_id) { + slot_id = RetiredSlotToReuse(channel, hooks, oldest_first); + if (slot_id == -1) { + return Pick::kNone; + } + if (!channel.RetiredSlots().ClearWasSet(slot_id)) { + slot_id = -1; + return Pick::kRetry; + } + return Pick::kTaken; +} + +// Takes ownership of slot if its refs are still old_refs with no references. +// +// Strong, not weak: a weak exchange may fail spuriously (on ARM's +// load/store-exclusive, a page fault between the two clears the reservation, +// which the first write to a slot's page always takes), and the claim loops +// do not retry the same slot. They go back to selecting one, having already +// cleared this slot's free or retired bit, so a spurious failure leaks the +// slot from that pool. +inline bool TryClaimSlot(MessageSlot *slot, int owner, uint64_t old_refs) { + uint64_t expected = BuildRefsBitField( + slot->ordinal.load(std::memory_order_relaxed), + static_cast((old_refs >> kVchanIdShift) & kVchanIdMask), + PendingCount(old_refs)); + return slot->refs.compare_exchange_strong( + expected, kPubOwned | static_cast(owner), + std::memory_order_acquire, std::memory_order_relaxed); +} + +// The slot with the oldest message that no subscriber holds. +template +MessageSlot *OldestUnreferencedSlot(const ChannelView &channel, + const Hooks &hooks) { + MessageSlot *oldest = nullptr; + uint64_t oldest_timestamp = ~uint64_t{0}; + for (int i = 0; i < channel.NumSlots(); i++) { + if (hooks.Embargoed(i)) { + continue; + } + MessageSlot *s = channel.Slot(i); + const uint64_t refs = s->refs.load(std::memory_order_relaxed); + if ((refs & kPubOwned) != 0) { + continue; + } + const uint64_t timestamp = s->timestamp.load(std::memory_order_relaxed); + if ((refs & kRefsMask) == 0 && timestamp < oldest_timestamp) { + oldest = s; + oldest_timestamp = timestamp; + } + } + return oldest; +} + +// Slots are ordered by timestamp, then by id. +inline bool Earlier(uint64_t timestamp, int id, uint64_t other_timestamp, + int other_id) { + if (timestamp != other_timestamp) { + return timestamp < other_timestamp; + } + return id < other_id; +} + +// Whether a reliable subscriber still needs the slot's message: it holds the +// message, or reliable subscribers exist and none has seen it. +inline bool NeededByReliable(const MessageSlot *slot, uint64_t refs, + bool require_reliable_seen) { + return ((refs >> kReliableRefCountShift) & kRefCountMask) != 0 || + (require_reliable_seen && + slot->ordinal.load(std::memory_order_relaxed) != 0 && + (slot->flags.load(std::memory_order_relaxed) & + kMessageSeenByReliable) == 0); +} + +inline bool ReliableClaimable(const MessageSlot *slot, + bool require_reliable_seen) { + const uint64_t refs = slot->refs.load(std::memory_order_relaxed); + return !NeededByReliable(slot, refs, require_reliable_seen) && + (refs & kRefsMask) == 0; +} + +// The oldest slot that no subscriber holds and that is older than every slot +// a reliable subscriber still needs, so a reliable publisher never overtakes +// a reliable subscriber. +template +MessageSlot *OldestReliableCandidate(const ChannelView &channel, + const Hooks &hooks, + bool require_reliable_seen) { + int stop = -1; + uint64_t stop_timestamp = 0; + for (int i = 0; i < channel.NumSlots(); i++) { + if (hooks.Embargoed(i)) { + continue; + } + const MessageSlot *s = channel.Slot(i); + const uint64_t refs = s->refs.load(std::memory_order_relaxed); + if ((refs & kPubOwned) != 0 || + !NeededByReliable(s, refs, require_reliable_seen)) { + continue; + } + const uint64_t timestamp = s->timestamp.load(std::memory_order_relaxed); + if (stop == -1 || Earlier(timestamp, i, stop_timestamp, stop)) { + stop = i; + stop_timestamp = timestamp; + } + } + MessageSlot *best = nullptr; + uint64_t best_timestamp = 0; + for (int i = 0; i < channel.NumSlots(); i++) { + if (hooks.Embargoed(i)) { + continue; + } + MessageSlot *s = channel.Slot(i); + const uint64_t refs = s->refs.load(std::memory_order_relaxed); + if ((refs & (kPubOwned | kRefsMask)) != 0) { + continue; + } + const uint64_t timestamp = s->timestamp.load(std::memory_order_relaxed); + if (stop != -1 && !Earlier(timestamp, i, stop_timestamp, stop)) { + continue; + } + if (best == nullptr || Earlier(timestamp, i, best_timestamp, best->id)) { + best = s; + best_timestamp = timestamp; + } + } + return best; +} + +constexpr int kMaxCasRetries = 1000; + +// Counts a failed claim. Returns false when the search should give up. +inline bool BackOff(int &cas_retries, int &retries) { + if (++cas_retries < kMaxCasRetries) { + return true; + } + if (retries-- == 0) { + return false; + } + cas_retries = 0; + (void)sched_yield(); + return true; +} + +} // namespace slot_search_internal + +// Claims a slot for an unreliable publisher's next message and resets it. +// Returns null only if the search keeps failing. +// +// With prefer_retired a retired slot comes before a free one. Both are +// equally valid for an unreliable publisher (a retired slot has been seen by +// every current subscriber and dropped), but a retired slot's pages are +// already cache-hot from the recent publish/consume cycle; a free slot will +// demand-fault the kernel into allocating new physical pages on first write, +// which dominates wall-time for large payloads. In steady state the +// publisher cycles through a tiny working set of retired slots without ever +// consuming free slots, while still being able to burst into them if the +// subscriber falls behind. +// +// None of that holds with nothing subscribed: a slot is then retired the +// moment it is published, so the publisher would take the slot it just wrote +// back out of the retired pool on the very next publish and never touch the +// free slots at all. The ring would hold one message no matter how deep it +// is configured. So free slots come first while idle, and together with the +// oldest-first recycling in RetiredSlotToReuse the ring becomes a rolling +// window of recent messages for whoever attaches next. +template +MessageSlot *ClaimSlotUnreliable(const ChannelView &channel, + const SlotSearch &search, Hooks &hooks) { + using namespace slot_search_internal; + int retries = channel.NumSlots() * 1000; + int cas_retries = 0; + MessageSlot *slot = nullptr; + int free_slot = -1; + int retired_slot = -1; + for (;;) { + slot = nullptr; + free_slot = -1; + retired_slot = -1; + hooks.BeforeAttempt(); + // Read the subscriber count on each attempt, so a subscriber attaching + // while we retry is seen. + const bool no_subscribers = channel.NumSubscribers(search.vchan_id) == 0; + Pick pick; + if (search.prefer_retired && !no_subscribers) { + pick = TakeRetiredSlot(channel, hooks, /*oldest_first=*/false, + retired_slot); + if (pick == Pick::kNone) { + pick = TakeFreeSlot(channel, free_slot); + } + } else { + pick = TakeFreeSlot(channel, free_slot); + if (pick == Pick::kNone) { + pick = TakeRetiredSlot(channel, hooks, /*oldest_first=*/no_subscribers, + retired_slot); + } + } + if (pick == Pick::kRetry) { + continue; + } + slot = pick == Pick::kTaken + ? channel.Slot(free_slot != -1 ? free_slot : retired_slot) + : OldestUnreferencedSlot(channel, hooks); + if (slot == nullptr) { + // There is always a slot, but don't loop forever if something is wrong. + if (retries-- == 0) { + return nullptr; + } + continue; + } + const uint64_t old_refs = slot->refs.load(std::memory_order_relaxed); + if (retired_slot != -1 && !channel.RefsShowRetired(slot, old_refs)) { + // A stale retired bit, now cleared. The slot may hold the newest + // message. + continue; + } + if (TryClaimSlot(slot, search.owner, old_refs)) { + if (!hooks.UsableSlot(slot)) { + slot->refs.store(old_refs, std::memory_order_relaxed); + hooks.Embargo(slot->id); + continue; + } + break; + } + if (!BackOff(cas_retries, retries)) { + return nullptr; + } + } + ResetClaimedSlot(channel, slot, search.vchan_id, hooks); + if (free_slot == -1 && retired_slot == -1) { + hooks.ForcedReuse(slot); + } + return slot; +} + +// Claims a slot for a reliable publisher's next message and resets it. +// Returns null when every slot holds a message that a reliable subscriber +// still needs; a reliable subscriber triggers the publisher when it releases +// one. +template +MessageSlot *ClaimSlotReliable(const ChannelView &channel, + const SlotSearch &search, + const ChannelCounters &counters, Hooks &hooks) { + using namespace slot_search_internal; + int retries = channel.NumSlots() * 1000; + int cas_retries = 0; + MessageSlot *slot = nullptr; + int free_slot = -1; + int retired_slot = -1; + for (;;) { + slot = nullptr; + free_slot = -1; + retired_slot = -1; + hooks.BeforeAttempt(); + const bool require_reliable_seen = counters.num_reliable_subs != 0; + Pick pick = TakeFreeSlot(channel, free_slot); + if (pick == Pick::kNone && search.reuse_retired) { + pick = TakeRetiredSlot(channel, hooks, /*oldest_first=*/false, + retired_slot); + } + if (pick == Pick::kRetry) { + continue; + } + if (pick == Pick::kTaken) { + slot = channel.Slot(free_slot != -1 ? free_slot : retired_slot); + const uint64_t refs = slot->refs.load(std::memory_order_relaxed); + if (retired_slot != -1 && !channel.RefsShowRetired(slot, refs)) { + // A stale retired bit, now cleared. + continue; + } + if (!ReliableClaimable(slot, require_reliable_seen)) { + return nullptr; + } + } else { + slot = OldestReliableCandidate(channel, hooks, require_reliable_seen); + if (slot == nullptr) { + return nullptr; + } + } + const uint64_t old_refs = slot->refs.load(std::memory_order_relaxed); + if (TryClaimSlot(slot, search.owner, old_refs)) { + if (!hooks.UsableSlot(slot)) { + slot->refs.store(old_refs, std::memory_order_relaxed); + hooks.Embargo(slot->id); + continue; + } + channel.RetiredSlots().Clear(slot->id); + break; + } + if (!BackOff(cas_retries, retries)) { + return nullptr; + } + } + ResetClaimedSlot(channel, slot, search.vchan_id, hooks); + if (free_slot == -1 && retired_slot == -1) { + hooks.ForcedReuse(slot); + } + return slot; +} + +} // namespace subspace diff --git a/common/subscribe.h b/common/subscribe.h new file mode 100644 index 00000000..d26f0f2c --- /dev/null +++ b/common/subscribe.h @@ -0,0 +1,142 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +// The steps of reading a message that every client shares: taking and +// releasing a reference, recording the subscriber as an owner, and marking a +// message seen. + +#pragma once + +#include "common/bitset_view.h" +#include "common/channel_view.h" +#include "common/shm_layout.h" + +#include +#include + +namespace subspace { + +// Messages are delivered in timestamp order, then ordinal order. +inline bool DeliveredBefore(uint64_t timestamp, uint64_t ordinal, + uint64_t other_timestamp, uint64_t other_ordinal) { + if (timestamp != other_timestamp) { + return timestamp < other_timestamp; + } + return ordinal < other_ordinal; +} + +// The ordinal of the published message in slot, or 0 if the slot holds none +// or a publisher owns it. A publisher reusing the slot zeroes its ordinal and +// timestamp before its bit is cleared, and a claim with ordinal 0 matches +// whatever is published there next, so a slot counts only while it holds the +// message its refs were committed with. +inline uint64_t CommittedOrdinal(const MessageSlot *slot) { + const uint64_t refs = slot->refs.load(std::memory_order_acquire); + const uint64_t ordinal = slot->ordinal.load(std::memory_order_relaxed); + if ((refs & kPubOwned) != 0 || ordinal == 0 || + (ordinal & kOrdinalMask) != ((refs >> kOrdinalShift) & kOrdinalMask)) { + return 0; + } + return ordinal; +} + +// Takes a reference to the message with this ordinal and vchan_id in slot, +// and records the subscriber as an owner so that the server can release the +// reference if the process dies. Returns false if the slot no longer holds +// the message. +inline bool ClaimMessageReference(const ChannelView &channel, + MessageSlot *slot, int subscriber_id, + bool reliable, uint64_t ordinal, + int vchan_id) { + if (!channel.AtomicIncRefCount(slot, reliable, 1, ordinal, vchan_id, + /*retire=*/false, nullptr)) { + return false; + } + slot->sub_owners.Set(subscriber_id); + return true; +} + +// Gives back a reference from ClaimMessageReference for a message the +// subscriber is not delivering, so the message stays unread. +inline void UnclaimMessageReference(const ChannelView &channel, + MessageSlot *slot, int subscriber_id, + bool reliable) { + if (slot->sub_owners.ClearWasSet(subscriber_id)) { + // A publisher evicting a queued slot can clear its bit just before the + // subscriber pops it. Restore the bit while the slot is still held. + channel.AvailableSlots(subscriber_id).Set(slot->id); + (void)channel.AtomicIncRefCount( + slot, reliable, -1, slot->ordinal.load(std::memory_order_relaxed), + slot->vchan_id.load(std::memory_order_relaxed), /*retire=*/false, + nullptr); + } +} + +struct ReleasedMessage { + // The subscriber held a reference to the message. + bool released = false; + // The release retired the slot. The caller tells retirement listeners + // about retirement_slot_id: for a bridged message, the slot on the other + // side of the bridge. + bool retired = false; + int32_t retirement_slot_id = -1; +}; + +// Releases the subscriber's reference to the message in slot, which it has +// finished with. +inline ReleasedMessage ReleaseMessageReference(const ChannelView &channel, + MessageSlot *slot, + int subscriber_id, + bool reliable) { + ReleasedMessage result; + if (!slot->sub_owners.ClearWasSet(subscriber_id)) { + return result; + } + result.released = true; + const uint64_t ordinal = slot->ordinal.load(std::memory_order_relaxed); + const int vchan_id = slot->vchan_id.load(std::memory_order_relaxed); + const int32_t retirement_slot_id = + slot->bridged_slot_id.load(std::memory_order_relaxed); + if (channel.ReleaseSubscriberObligation(slot, subscriber_id, reliable, + /*drop_ref=*/true, ordinal, + vchan_id) && + channel.TryRetireSlot(slot)) { + result.retired = true; + result.retirement_slot_id = retirement_slot_id; + } + return result; +} + +// A reliable publisher doesn't overtake a message until a reliable subscriber +// has seen it. +inline void MarkMessageSeen(MessageSlot *slot, bool reliable) { + slot->flags.fetch_or(reliable ? kMessageSeen | kMessageSeenByReliable + : kMessageSeen, + std::memory_order_relaxed); +} + +// Marks a message that the subscriber is skipping, because it read a newer +// one, as read. The reference held meanwhile stops a publisher recycling the +// slot from losing the bit for its new message. A reliable subscriber marks +// the message seen, so that a reliable publisher doesn't wait for it to be +// read; the caller then triggers reliable publishers. Returns false if the +// slot no longer holds the message. +inline bool SkipUnreadMessage(const ChannelView &channel, MessageSlot *slot, + int subscriber_id, bool reliable, + uint64_t ordinal, int vchan_id) { + if (!channel.AtomicIncRefCount(slot, reliable, 1, ordinal, vchan_id, + /*retire=*/false, nullptr)) { + return false; + } + channel.AvailableSlots(subscriber_id).Clear(slot->id); + if (reliable) { + MarkMessageSeen(slot, reliable); + } + (void)channel.AtomicIncRefCount(slot, reliable, -1, ordinal, vchan_id, + /*retire=*/false, nullptr); + return true; +} + +} // namespace subspace diff --git a/docs/android.md b/docs/android.md index dab8202a..fed70418 100644 --- a/docs/android.md +++ b/docs/android.md @@ -184,15 +184,18 @@ executable. The `android_libs/` approach works for `/data/local/tmp/` binaries. Subspace can also be cross-compiled for Android using CMake with the NDK toolchain. CMake fetches the same third-party dependencies with -`FetchContent`, but protobuf code generation requires a host-native `protoc` -that matches the protobuf version used by the Android build. +`FetchContent`, but code generation runs on the host. It needs a host-native +`protoc` that matches the protobuf version used by the Android build, and a +host-native phaser plugin (`protoc-gen-phaser`) for the C++ clients' server +messages. ```bash export ANDROID_NDK_HOME=/path/to/ndk -# Build a host protoc matching Subspace's protobuf dependency. +# Build a host protoc matching Subspace's protobuf dependency, and the phaser +# plugin. cmake -S . -B build/host-protoc -DCMAKE_BUILD_TYPE=Release -cmake --build build/host-protoc --target protoc --parallel +cmake --build build/host-protoc --target protoc protoc-gen-phaser --parallel cmake -S . -B build/android \ -DCMAKE_TOOLCHAIN_FILE=$ANDROID_NDK_HOME/build/cmake/android.toolchain.cmake \ @@ -200,7 +203,8 @@ cmake -S . -B build/android \ -DANDROID_PLATFORM=android-28 \ -DANDROID_STL=c++_shared \ -DCMAKE_BUILD_TYPE=Release \ - -DPROTOC_EXECUTABLE="$PWD/build/host-protoc/_deps/protobuf-build/protoc" + -DPROTOC_EXECUTABLE="$PWD/build/host-protoc/_deps/protobuf-build/protoc" \ + -DPHASER_PLUGIN_EXECUTABLE="$PWD/build/host-protoc/_deps/phaser-build/protoc-gen-phaser" cmake --build build/android --parallel ``` @@ -240,6 +244,9 @@ Place the subspace source tree in your AOSP checkout (e.g., | `libsubspace_server` | static lib | Server implementation | | `subspace_server` | binary | Standalone server daemon | | `libsubspace_proto` | static lib | Protobuf message definitions | +| `libsubspace_phaser` | static lib | Phaser message definitions for the C++ clients | +| `libsubspace_asil_client` | static lib | ASIL client core (no exceptions, no RTTI) | +| `libsubspace_asil_phaser_connection` | static lib | ASIL client's server connection | | `libsubspace_jni` | shared lib | JNI bindings for Java clients | | `subspace-java` | java lib | Java client wrapper | | `subspace_java_client_test` | java binary | Device-side Java integration test | @@ -256,16 +263,20 @@ files with the `subspace_rpc` plugin via a `genrule` (see ### External Dependencies -Subspace requires two external libraries that must also be present in the AOSP -tree: +Subspace requires three external libraries that must also be present in the +AOSP tree: 1. **coroutines** (`external/coroutines/`) — https://github.com/dallison/coroutines 2. **cpp_toolbelt** (`external/cpp_toolbelt/`) — https://github.com/dallison/cpp_toolbelt - -Example Blueprint files for both are provided in -`external/coroutines/Android.bp.example` and -`external/cpp_toolbelt/Android.bp.example` within this repository. Copy these to -`Android.bp` in the respective source trees in your AOSP checkout. +3. **phaser** (`external/phaser/`) — https://github.com/dallison/phaser + +Example Blueprint files for all three are provided in +`external/coroutines/Android.bp.example`, +`external/cpp_toolbelt/Android.bp.example` and +`external/phaser/Android.bp.example` within this repository. Copy these to +`Android.bp` in the respective source trees in your AOSP checkout. The phaser +file defines the `libphaser_runtime` library and the `protoc-gen-phaser` host +plugin. ### AOSP Dependencies diff --git a/docs/asil-client.md b/docs/asil-client.md new file mode 100644 index 00000000..a67982cd --- /dev/null +++ b/docs/asil-client.md @@ -0,0 +1,406 @@ +# ASIL Client + +The ASIL client in `asil_client/` is a Subspace client for safety-related +software. It publishes and reads messages on the same channels as the +standard C++, C, Python and Rust clients, using the same shared memory +protocol, so an ASIL process and a standard process can share a channel in +either direction. + +It works with any server. A server running a +[static channel config](../README.md#static-channel-config) creates the +configured channels before any client connects and keeps their layout fixed. +ASIL and standard publishers share those channels when both set +`server_defined`. A standard publisher can still create a channel that isn't +configured, by specifying its layout, and an ASIL subscriber can subscribe to +it. An ASIL publisher cannot create or join a channel that isn't configured +while a static config is loaded. On a server with no static config, an ASIL +publisher can create a channel by specifying its layout. + +## Design Rules + +- **C++17, the standard library and POSIX.** The core library shares the + shared-memory protocol in `common/` with the regular client: the memory + layout (`shm_layout.h`), the slot, retirement and reference count + operations (`channel_view.h`), finding a slot to publish in + (`slot_search.h`), publishing it (`publish.h`), taking, releasing and + skipping messages (`subscribe.h`) and the message checksum + (`message_checksum.h`). Those are themselves only the + standard library and POSIX, and the core is compiled with + `-fno-exceptions -fno-rtti`. The server connection adds + [phaser](https://github.com/dallison/phaser) and is built the same way. +- **Errors are values.** Every operation that can fail returns + `subspace::asil::Error`. `ErrorString()` describes a code, and + `Client::LastServerError()` gives the detail: the server's reason for + `Error::kServerRejected`, or which buffer a request or response did not + fit for `Error::kCapacityExceeded`. +- **No heap allocation.** The client, publishers and subscribers allocate no + memory, and neither does `PhaserServerConnection` while it talks to the + server. +- **Resources are acquired when an object opens.** A publisher or + subscriber maps all of its channel's shared memory in `Open()`. Publishing + and reading make no `mmap`, `shm_open` or other shared memory calls. An + ASIL publisher creates a channel's buffer only when it is the first + publisher and the server has no static config. With a config loaded it + publishes only on the configured channels, whose buffers the server has + already created. After `Open()` the server is involved only when a + publisher or subscriber refreshes its trigger file descriptors because + another process joined or left the channel, and on `Close()`. +- **Fixed capacities.** Channel names hold up to 255 characters and each + trigger list holds up to 1024 file descriptors. A request or response to + the server holds up to 16 KB in wire format unless + `PhaserServerConnection` is constructed with a larger size. Exceeding + the size returns `Error::kCapacityExceeded`. `max_active_messages` is at + most 64. + A subscriber keeps the newest ordinal of every virtual channel, which makes + it about 8 KB, so keep subscribers in static storage or inside long-lived + objects. +- **Single threaded objects.** A `Client`, `Publisher` or `Subscriber` is used + by one thread at a time. The `ServerConnection` outlives the `Client`, and + the `Client` outlives its publishers and subscribers. + +## Scope + +The ASIL client shares channels with the standard clients for: + +- Unreliable and reliable publishers and subscribers. +- Virtual channels on a multiplexer, and subscribers to a whole multiplexer. +- Subscribers that hold several messages at once (`max_active_messages`). +- Subscriber queues: an ASIL publisher fills the queues of standard + subscribers that use them. +- Split buffers, including slots that a standard publisher's custom + allocator created. +- POSIX shared memory on macOS and QNX, `/dev/shm` on Linux, and the memfd + backend (always used on Android, and selected on Linux with + `SUBSPACE_LINUX_USE_MEMFD`). +- Checksums, user metadata, `kReadNext` and `kReadNewest`, dropped message + counting and activation messages. + +### Channel Buffers + +A publisher or subscriber maps one of the channel's message buffers, the +newest, when it opens. A server with a static channel config creates every +configured channel's buffers when it starts, so ASIL publishers and +subscribers can open those in any order. A channel that isn't configured, and +any channel on a server that creates channels on demand, has buffers once its +first publisher opens. Until then an ASIL subscriber's `Open()` returns +`Error::kNoBuffers`. An ASIL publisher creates that buffer only on a server +with no static config; with a config loaded it can publish only on the +configured channels. + +ASIL publishers always use fixed-size slots, so a channel never resizes while +one is open. A standard publisher can resize a channel that only it +publishes on, which gives the channel a new buffer. An ASIL subscriber that +opened before the resize can't read the messages in the new buffer. +`ReadMessage` skips each of them and returns `Error::kBufferNotMapped`. An +ASIL publisher or subscriber that opens after the resize uses the new buffer. + +### Split Buffers + +A channel with split buffers keeps the message prefixes in one shared memory +object and each slot's payload in its own. The ASIL client maps all of them +in `Open()`, into an array of `SplitSlot` that the caller provides in +`split_slots`, with its length in `split_slot_capacity`. The array needs at +least the channel's `num_slots` entries, or `Open()` returns +`Error::kCapacityExceeded`. It must outlive the publisher or subscriber. +An ASIL publisher sets `use_split_buffers` and maps the channel's existing +buffers; it never creates split buffers. + +A static channel or multiplexer has split buffers when its config sets +`use_split_buffers`, and the server creates them. A `server_defined` +publisher learns from the server whether the channel has split buffers, and +needs `split_slots` when it does. On a server that creates channels on +demand, the first standard publisher creates them. + +A standard publisher can create its slots with a custom allocator. To map +those slots, set `split_allocator` to C functions that map and unmap a slot, +with a context pointer. `map` gets the slot's `SplitBufferInfo`: the +allocator's handle, sizes and the descriptor the creator registered, if any. +`Open()` calls `map` for each slot, and `Close()` calls `unmap`. Without +`split_allocator.map`, such a channel returns `Error::kUnsupported`. + +```cpp +asil::Error MapSlot(void *context, const asil::SplitBufferInfo &info, + asil::SplitBufferMapping &mapping) { + mapping.address = static_cast(context)->Find(info.handle); + return mapping.address != nullptr ? asil::Error::kOk + : asil::Error::kInvalidArgument; +} + +asil::SplitSlot slots[16]; +asil::SubscriberOptions options; +options.split_slots = slots; +options.split_slot_capacity = 16; +options.split_allocator.map = MapSlot; +options.split_allocator.context = &pool; +``` + +## Building + +Bazel: + +``` +bazelisk build //asil_client:asil_client //asil_client:phaser_connection +bazelisk test //asil_client:all +``` + +| Target | Contents | Dependencies | +|---|---|---| +| `//asil_client:asil_client` | Client, publisher, subscriber, shared memory | C++17, POSIX | +| `//asil_client:phaser_connection` | The standard server handshake | `asil_client`, `//common:server_wire` | +| `//common:server_wire` | Server request and response encoding, shared with the standard client | `//proto:subspace_phaser` | +| `//proto:subspace_phaser` | Phaser messages generated from `subspace.proto` | phaser runtime, Abseil, cpp_toolbelt | + +CMake builds the same libraries as `subspace_asil_client`, +`subspace_asil_phaser_connection` and `subspace_phaser`, with the tests +`asil_layout_test` and `asil_client_test`. It also builds `asil_stress_test`, +which is not registered with ctest. The Bazel target +`//asil_client:stress_test` is tagged manual, so `bazel test //...` skips it. +Phaser is fetched with +`FetchContent`, and its `protoc-gen-phaser` plugin is built for the host. A +cross-compile needs a host plugin passed as `-DPHASER_PLUGIN_EXECUTABLE`; see +[the Android CMake build](android.md#building-with-cmake). + +Soong builds `libsubspace_asil_client`, `libsubspace_asil_phaser_connection` +and `libsubspace_phaser`, using the phaser modules from +`external/phaser/Android.bp.example`. + +The core library takes `SUBSPACE_MAX_CHANNELS` from the same build setting as +the server, because it sizes the shared system control block. + +## The Server Connection + +The client talks to the server through the abstract `ServerConnection` in +`asil_client/server_connection.h`. It has one call for each request the +client makes: `Init`, `CreatePublisher`, `CreateSubscriber`, `GetTriggers`, +`RemovePublisher` and `RemoveSubscriber`, plus `RegisterBuffer` and +`GetBuffer`, which pass buffer file descriptors between processes through the +server. `GetBuffer` fetches one buffer: a channel's single buffer for the +memfd backend, or the prefixes or one slot of a split buffer set, so that +each response stays small. + +`PhaserServerConnection` implements it with the server's standard protocol: +a 4-byte length followed by the Phaser message buffer itself (`Data()` / +`ByteSizeLong()`), with file descriptors passed by `SCM_RIGHTS`. That is +Phaser's zero-copy form. The server receives the same bytes it receives +from the standard C++ client and the Rust client, with no protobuf +transcoding. `ServerWire` in `common/server_wire.h` builds the message for +both C++ clients. The standard client gives it growable buffers. The ASIL +connection gives it fixed buffers: it builds each request in a fixed buffer, +sends that buffer, and loads the response back into it, so a handshake does +not allocate. The message buffer and the wire buffer are both 16 KB and +live inside the object. Pass a larger size to the constructor when a +channel opened through the client needs a bigger handshake. That storage +is allocated once, in the constructor, and both buffers use that size. The +default buffers take about 32 KB, so keep the connection in static storage +or inside a long-lived object. A system with its own qualified transport +can replace it with another implementation of `ServerConnection`. + +## Example + +This example gives each channel its layout, which an ASIL publisher can do +on a server with no static config. On a configured channel the publisher +sets `server_defined` instead, as shown under Publishers. + +```cpp +#include "asil_client/client.h" +#include "asil_client/phaser_connection.h" + +#include + +namespace asil = subspace::asil; + +asil::PhaserServerConnection connection; + +asil::Error Run() { + if (asil::Error e = connection.Connect("/tmp/subspace"); + e != asil::Error::kOk) { + return e; + } + asil::Client client; + if (asil::Error e = client.Init(connection, "controller"); + e != asil::Error::kOk) { + return e; + } + + asil::PublisherOptions pub_options; + pub_options.slot_size = 256; + pub_options.num_slots = 8; + pub_options.checksum = true; + asil::Publisher publisher; + if (asil::Error e = + client.CreatePublisher("/vehicle/command", pub_options, publisher); + e != asil::Error::kOk) { + return e; + } + + asil::SubscriberOptions sub_options; + sub_options.checksum = true; + asil::Subscriber subscriber; + if (asil::Error e = + client.CreateSubscriber("/vehicle/state", sub_options, subscriber); + e != asil::Error::kOk) { + return e; + } + + void *buffer = publisher.Buffer(); + if (buffer == nullptr) { + return asil::Error::kNoSlot; + } + std::memcpy(buffer, "go", 2); + if (asil::Error e = publisher.Publish(2); e != asil::Error::kOk) { + return e; + } + + if (asil::Error e = subscriber.Wait(/*timeout_ms=*/100); + e == asil::Error::kTimeout) { + return asil::Error::kOk; + } else if (e != asil::Error::kOk) { + return e; + } + asil::Message msg; + for (;;) { + if (asil::Error e = subscriber.ReadMessage(msg); e != asil::Error::kOk) { + return e; + } + if (msg.length == 0) { + break; + } + // msg.data stays valid until the next ReadMessage or ReleaseMessage. + } + return asil::Error::kOk; +} +``` + +## Publishers + +`PublisherOptions` gives the slot size, number of slots, checksum size, +metadata size, subscriber queue arena size, split buffer setting and type. +`subscriber_queue_arena_size` must match the channel's other publishers. + +On a static channel the server defines the layout. The publisher sets +`server_defined` and leaves `slot_size`, `num_slots`, `checksum_size`, +`metadata_size`, `subscriber_queue_arena_size` and `use_split_buffers` at +zero. `Open()` returns `Error::kInvalidArgument` if any of them is set, and +`Error::kServerRejected` if the channel is static and `server_defined` isn't +set, if `server_defined` is set and the channel isn't static, or if a static +config is loaded and the publisher gives its own layout for a channel that +isn't configured. The publisher then takes its layout from the server: + +```c++ +asil::PublisherOptions options; +options.server_defined = true; +options.type = "State"; +asil::Publisher pub; +asil::Error error = client.CreatePublisher("/vehicle/state", options, pub); +``` + +`Buffer()` returns the payload of the slot the publisher holds, and +`Metadata()` returns its metadata area. `Publish(size)` sends the message and +claims the next slot. It fills in an optional `PublishedMessage` with the +message's ordinal and timestamp. When `checksum` is set the publisher +computes the same CRC32 as the standard clients. When `activate` is set the +publisher sends the channel's activation message if no publisher has sent one. + +A publisher joining a channel whose slots a standard publisher has grown uses +the channel's newest buffer, so `SlotSize()` can be larger than the requested +size. + +### Reliable Publishers + +With `reliable` set, the publisher never overwrites a message that a +reliable subscriber hasn't read. It sends an activation message when it +opens, which every reliable subscriber holds until it reads further. +`Buffer()` returns null while the channel has no subscribers, and while every +slot holds a message a reliable subscriber still needs. `PollFd()` becomes +readable when a reliable subscriber releases a message, and +`Wait(timeout_ms)` polls it: + +```cpp +void *buffer = publisher.Buffer(); +while (buffer == nullptr) { + if (asil::Error e = publisher.Wait(/*timeout_ms=*/100); + e != asil::Error::kOk) { + return e; + } + buffer = publisher.Buffer(); +} +``` + +### Virtual Channels + +Set `mux` to the multiplexer's name to publish on one of its virtual +channels. The server assigns the virtual channel id unless `vchan_id` gives +one. `VirtualChannelId()` returns it. + +## Subscribers + +`ReadMessage(msg, mode)` fills in a `Message` with the payload, length, +ordinal, timestamp, slot, virtual channel id, metadata and the number of +messages dropped since the previous one. A length of 0 means there was +nothing to read. `PollFd()` is readable when messages may be waiting, and +`Wait(timeout_ms)` polls it. + +With `checksum` set, a message with a bad checksum returns +`Error::kChecksumMismatch`. With `pass_checksum_errors` also set, it is +delivered with `checksum_error` set. Activation messages are skipped unless +`pass_activation` is set. + + +### Holding Messages + +By default a subscriber holds one message, and reading the next releases it. +With `max_active_messages` set to more than 1, every message read stays valid +until it is released. `ReleaseMessage(msg)` releases one message and +`ReleaseMessage()` releases them all. When the subscriber holds +`max_active_messages` messages, `ReadMessage` returns +`Error::kActiveMessageLimit`. + +### Reliable Subscribers + +With `reliable` set, reliable publishers wait for the subscriber to read each +message. A reliable subscriber that holds one message keeps it until it has +read the next one, so a publisher can never take every slot. Reading with +`kReadNewest` marks the skipped messages as read, which lets reliable +publishers reuse their slots. + +### Virtual Channels and Multiplexers + +Set `mux` to subscribe to a virtual channel. Subscribing to the multiplexer +itself delivers the messages of all its virtual channels, with each message's +`vchan_id`. Each virtual channel has its own ordinals, so dropped messages +are counted per virtual channel. + +### Subscriber Queues + +An ASIL subscriber reads the channel's record of unread messages directly, +so it works on channels with subscriber queues without using one. ASIL +publishers add every message to the queues of the standard subscribers that +have them. + +## Testing + +`layout_test` checks the shared-memory code that both clients use, on a +channel control block in process memory. It checks the delivery of a +published message to each subscriber's bitset and queue, the byte counts and +the commit, and that a queue that does not fit in the queue arena is ignored. +For the slot search it checks that a stale retired bit on an unread message +doesn't give that slot away, the order in which free, retired and in-use slots +are taken, that a slot the client can't use is given back, and that a reliable +publisher neither takes a held slot nor overtakes a message no reliable +subscriber has seen. It checks releasing, retiring and skipping messages. +It also checks that the shared checksum matches the standard client's, and +that the flags the bridge and the tunnel set after publishing do not +invalidate it. + +`asil_client_test` exchanges messages between the ASIL client and the +standard client in both directions. One server runs a static channel config, +for reliable channels, virtual channels, held messages, split buffers, +subscribers that open before any publisher, and channels a standard publisher +creates beside that config. A second server creates channels +on demand, for channels created by ASIL publishers, resized channels, +subscriber queues, custom split buffer allocators and subscribers that open +before a channel has buffers. The +test also checks that setting up and closing a publisher and a subscriber +makes no heap allocations, and that a request or response too large for its +buffer returns `Error::kCapacityExceeded`, with the reason in +`LastServerError()`, and leaves the connection usable. diff --git a/docs/c-client.md b/docs/c-client.md index 7c9214ae..ee5d15f8 100644 --- a/docs/c-client.md +++ b/docs/c-client.md @@ -85,10 +85,18 @@ opts.metadata_size = 32; SubspacePublisher pub = subspace_create_publisher(client, "my_channel", opts); ``` +On a server with a [static channel config](../README.md#static-channel-config), +start with `subspace_publisher_options_server_defined()` instead. It sets +`server_defined` and leaves every layout option (`slot_size`, `num_slots`, +`fixed_size`, `checksum_size`, `metadata_size`, +`subscriber_queue_arena_size` and `use_split_buffers`) at zero, as the server +requires on a static channel. + Important publisher options: | Field | Purpose | | --- | --- | +| `server_defined` | Take the channel layout from the server's static channel config. Required on static channels and rejected on others. | | `slot_size`, `num_slots` | Initial payload slot size and fixed slot count. `slot_size` is a `SubspaceSlotSize`, which is `int32_t` unless the library and your code are both built with `SUBSPACE_64BIT_SLOT_SIZE`; see [Slot Sizes](slot-sizes.md#64-bit-slot-sizes). | | `local` | Keep the channel local to this server. | | `reliable` | Wait for free slots instead of overwriting unread messages. | diff --git a/docs/checksums-and-metadata.md b/docs/checksums-and-metadata.md index 8ae8c2ed..137c179d 100644 --- a/docs/checksums-and-metadata.md +++ b/docs/checksums-and-metadata.md @@ -92,9 +92,10 @@ By default, `checksum_size` is 4 and the built-in IEEE 802.3 CRC32 is used: - **`VerifyCRC32Checksum()`** — recomputes CRC32 and compares against the stored 4 bytes. -ARM builds use the hardware CRC32 instructions when available -(`SUBSPACE_HARDWARE_CRC`). x86 always uses the lookup table: the SSE4.2 CRC32 -instruction computes CRC-32C, which does not match this polynomial. +These functions use ARM hardware CRC instructions when available +(`SUBSPACE_HARDWARE_CRC`), with a software fallback. Both compute the IEEE +802.3 polynomial. x86 always uses the software table, because its SSE4.2 +CRC32 instruction computes CRC-32C, a different checksum. ### Larger Checksums diff --git a/docs/client_design.md b/docs/client_design.md index e2b4da10..fe606075 100644 --- a/docs/client_design.md +++ b/docs/client_design.md @@ -68,7 +68,7 @@ directly through shared memory using lock-free atomic operations. 3. On success, the server responds with a session ID and transmits the SCB file descriptor via `SCM_RIGHTS`. 4. The client maps the SCB into its address space. -5. All subsequent requests (CreatePublisher, CreateSubscriber, etc.) use the same socket with a 4-byte length prefix + serialized protobuf, followed by file descriptor transfer for shared memory regions. +5. All subsequent requests (CreatePublisher, CreateSubscriber, etc.) use the same socket with a 4-byte length prefix plus the native Phaser payload, followed by file descriptor transfer for shared memory regions. ### 2.3 Thread Safety diff --git a/docs/rust-client.md b/docs/rust-client.md index 39871ad1..326d2c47 100644 --- a/docs/rust-client.md +++ b/docs/rust-client.md @@ -180,10 +180,11 @@ let msg = subscriber | `max_outstanding_slot_leases` | 1 | Maximum unpublished slots owned through explicit leases. | | `notify_retirement_on_forced_reuse` | true | Emit retirement notifications when an unreliable publisher forcibly reuses an unread slot. | | `checksum` | false | Compute CRC32 checksums on published messages. | -| `checksum_size` | 4 | Bytes reserved for checksums (default: 4 for CRC32). | +| `checksum_size` | 0 | Bytes reserved for checksums; 0 means 4, for CRC32. | | `metadata_size` | 0 | Bytes reserved in each message prefix for user metadata. | | `use_split_buffers` | false | Store message prefixes separately from payload buffers using the built-in split shared-memory allocator. | | `split_buffers_over_bridge` | false | Ask receiving bridge servers to create their mirror publisher with split payload buffers. | +| `server_defined` | false | Take the layout from the server's [static channel config](../README.md#static-channel-config). Required on static channels, which reject `slot_size`, `num_slots`, `fixed_size`, `checksum_size`, `metadata_size`, `subscriber_queue_arena_size` and `use_split_buffers`. | | `split_buffer_callbacks` | none | Optional external allocator callbacks for split payload buffers. Publishers use `allocate`/`free`; subscribers use `map`/`unmap`. | All options use a builder pattern: @@ -432,9 +433,9 @@ bazelisk test //rust_client:client_test bazelisk test //rust_client:latency_test ``` -The build uses `prost` for protobuf code generation (via a `build.rs` script) -and communicates with the server using the same protobuf wire format as the C++ -client. +The build uses `prost` for protobuf messages that travel on channels, such as +telemetry and split-buffer metadata files. The client-server socket uses the +native Phaser payload, the same bytes the C++ clients send. ## Architecture diff --git a/docs/server-architecture.md b/docs/server-architecture.md index 70aa5f72..4c667f5c 100644 --- a/docs/server-architecture.md +++ b/docs/server-architecture.md @@ -74,7 +74,8 @@ Each channel requires three shared memory regions, created via `shm_open()` (POS - One per channel. - Contains: channel name, num_slots, ordinals, activation tracker. -- CCB version 5 uses atomic slot metadata and subscriber counters. +- CCB version 6 uses atomic slot metadata, subscriber counters, and a + publish-time delivery countdown in each slot. `total_messages` advances for every completed publication, including activation messages, and also versions subscriber delivery snapshots. @@ -295,6 +296,8 @@ server/ ├── client_handler.h/cc # Client connection handler ├── server_channel.h/cc # ServerChannel and its users ├── shadow_replicator.h/cc # Replication to the shadow process +├── static_config.h/cc # Static channel config parsing and validation +├── config_format.h # Config file format, chosen by extension ├── tunnel.h/cc # Tunnel discovery and bridging ├── tunnel_config.h/cc # Tunnel configuration parsing and validation ├── tunnel_protocol.h/cc # Tunnel wire format diff --git a/docs/tunnel.md b/docs/tunnel.md index 9f4f6d30..84eb0732 100644 --- a/docs/tunnel.md +++ b/docs/tunnel.md @@ -65,12 +65,23 @@ Two command line flags control the tunnel: | Flag | Meaning | |------|---------| | `--tunnel` | Turn on tunnel discovery and bridging. | -| `--tunnel_config=` | The tunnel configuration file, in protobuf text format. Required with `--tunnel`. | +| `--tunnel_config=` | The tunnel configuration file. A name ending in `.pb` or `.binpb` is protobuf wire format; any other name is protobuf text format. Required with `--tunnel`. | ```bash subspace_server --tunnel --tunnel_config=/etc/subspace/tunnel.textproto ``` +A generated configuration can be a wire-format file instead, named with a +`.pb` or `.binpb` extension. Encode a text file with `protoc`: + +```bash +protoc -I proto --encode=subspace.TunnelConfig proto/tunnel_config.proto \ + < tunnel.textproto > /etc/subspace/tunnel.pb +``` + +Either format is validated the same way. A wire-format file that has a field +this build doesn't know is rejected, as a text file with an unknown field is. + `--tunnel_config` without `--tunnel` is ignored with a warning. `--local --tunnel` turns off native discovery and bridging and runs only the tunnel. diff --git a/external/phaser/Android.bp.example b/external/phaser/Android.bp.example new file mode 100644 index 00000000..7d853e8d --- /dev/null +++ b/external/phaser/Android.bp.example @@ -0,0 +1,59 @@ +// Android.bp for phaser (https://github.com/dallison/phaser). +// Place this file alongside the phaser source tree at external/phaser/ in +// your AOSP checkout. + +// Runtime library linked by phaser-generated code. +cc_library_static { + name: "libphaser_runtime", + srcs: [ + "phaser/runtime/md5.cc", + "phaser/runtime/message.cc", + "phaser/runtime/phaser_bank.cc", + ], + export_include_dirs: ["."], + cflags: [ + "-std=c++17", + "-Wall", + "-Wno-unused-parameter", + ], + static_libs: [ + "libcpp_toolbelt", + "libabsl", + ], + export_static_lib_headers: [ + "libcpp_toolbelt", + "libabsl", + ], + stl: "c++_shared", + min_sdk_version: "28", + compile_multilib: "64", +} + +// The protoc plugin. It runs on the build host during code generation. +cc_binary_host { + name: "protoc-gen-phaser", + srcs: [ + "phaser/compiler/enum_gen.cc", + "phaser/compiler/gen.cc", + "phaser/compiler/main.cc", + "phaser/compiler/message_gen.cc", + "phaser/options.proto", + ], + proto: { + type: "full", + include_dirs: ["external/protobuf/src"], + }, + local_include_dirs: ["."], + cflags: [ + "-Wall", + "-Wno-unused-parameter", + ], + cpp_std: "c++17", + cppflags: ["-fexceptions"], + rtti: true, + static_libs: [ + "libprotoc", + "libprotobuf-cpp-full", + "libabsl", + ], +} diff --git a/patches/phaser_armhf_payload_buffer.patch b/patches/phaser_armhf_payload_buffer.patch new file mode 100644 index 00000000..8d81c3b1 --- /dev/null +++ b/patches/phaser_armhf_payload_buffer.patch @@ -0,0 +1,84 @@ +diff --git a/phaser/phaser_library.bzl b/phaser/phaser_library.bzl +index 704d5d6..d4bbc3a 100644 +--- a/phaser/phaser_library.bzl ++++ b/phaser/phaser_library.bzl +@@ -551,6 +551,9 @@ def phaser_library( + cc_library( + name = name, + alwayslink = True, ++ # Static archives keep bank static initializers linked on armhf (QEMU ++ # would not run registrars in un-loaded shared objects). ++ linkstatic = True, + copts = copts, + srcs = [srcs], + hdrs = [hdrs], +diff --git a/phaser/runtime/payload_buffer.cc b/phaser/runtime/payload_buffer.cc +index bedb83a..77ec883 100644 +--- a/phaser/runtime/payload_buffer.cc ++++ b/phaser/runtime/payload_buffer.cc +@@ -320,14 +320,9 @@ void PayloadBuffer::CheckFreeList() { + } + + void PayloadBuffer::InitFreeList() { +- char *end_of_header = reinterpret_cast(this + 1); +- size_t header_size = sizeof(PayloadBuffer); +- if (IsMoveable()) { +- end_of_header += +- sizeof(Resizer *); // Room for resizer function for movable buffers. +- header_size += sizeof(Resizer *); +- } +- FreeBlockHeader *f = reinterpret_cast(end_of_header); ++ const uint32_t header_size = AlignedPayloadHeaderSize(IsMoveable()); ++ char *start_of_free = reinterpret_cast(this) + header_size; ++ FreeBlockHeader *f = reinterpret_cast(start_of_free); + f->length = full_size - header_size; + f->next = 0; + free_list = ToOffset(f); +diff --git a/phaser/runtime/payload_buffer.h b/phaser/runtime/payload_buffer.h +index 8042312..082c5e3 100644 +--- a/phaser/runtime/payload_buffer.h ++++ b/phaser/runtime/payload_buffer.h +@@ -141,6 +141,9 @@ struct PayloadBuffer { + BufferOffset metadata; // Offset to message metadata. + BufferOffset + bitmaps[kNumBitmapRuns]; // Free list head for each small block class. ++ // Explicit tail padding so the header is 48 bytes on 32- and 64-bit hosts ++ // without changing field offsets. ++ uint32_t header_padding[2] = {0, 0}; + + // Initialize a new PayloadBuffer at this with a message of the + // given size. This is a fixed size buffer. +@@ -607,6 +610,19 @@ struct PayloadBuffer { + } + }; + ++static_assert(sizeof(PayloadBuffer) == 48, ++ "PayloadBuffer wire layout must match on all platforms"); ++ ++// Bytes reserved before the heap/free list: fixed 48-byte header plus an ++// optional movable resizer pointer, rounded up to 8-byte alignment. ++inline uint32_t AlignedPayloadHeaderSize(bool movable) { ++ uint32_t n = static_cast(sizeof(PayloadBuffer)); ++ if (movable) { ++ n += static_cast(sizeof(Resizer *)); ++ } ++ return (n + 7u) & ~7u; ++} ++ + // A string to be copied into a buffer. It can be in that buffer, which + // allocating can move, so it is found again there by its offset. + class StringSource { +diff --git a/phaser/runtime/wireformat.h b/phaser/runtime/wireformat.h +index f937071..27b6c79 100644 +--- a/phaser/runtime/wireformat.h ++++ b/phaser/runtime/wireformat.h +@@ -79,8 +79,7 @@ inline bool IsStructurallyValidPhaser(absl::Span data) { + } + + const size_t minimum_header = +- sizeof(::phaser::PayloadBuffer) + +- (movable ? sizeof(::phaser::Resizer*) : 0); ++ ::phaser::AlignedPayloadHeaderSize(movable); + const uint32_t message = LoadWireUint32(data, kMessageOffset); + const uint32_t hwm = LoadWireUint32(data, kHwmOffset); + const uint32_t full_size = LoadWireUint32(data, kFullSizeOffset); diff --git a/plugins/BUILD.bazel b/plugins/BUILD.bazel index 431b7e64..820bc999 100644 --- a/plugins/BUILD.bazel +++ b/plugins/BUILD.bazel @@ -27,10 +27,11 @@ cc_binary( linkshared = True, ) -# Static library version of the NOP plugin for linking directly into binaries. -# On macOS, dlopen'd plugins get their own copy of thread-local variables -# (like co::self), breaking the coroutine scheduler. Linking the plugin -# statically avoids that by keeping a single copy of the coroutines library. +# Static library versions of the test plugins for linking directly into +# binaries. On macOS, dlopen'd plugins get their own copy of thread-local +# variables (like co::self), breaking the coroutine scheduler. Linking the +# plugin statically avoids that by keeping a single copy of the coroutines +# library. cc_library( name = "nop_plugin_lib", srcs = ["nop_plugin.cc"], @@ -43,3 +44,13 @@ cc_library( ], alwayslink = True, ) + +cc_library( + name = "split_buffer_free_test_plugin_lib", + srcs = ["split_buffer_free_test_plugin.cc"], + deps = [ + "//server:server", + "@abseil-cpp//absl/status", + ], + alwayslink = True, +) diff --git a/plugins/CMakeLists.txt b/plugins/CMakeLists.txt index 064c28f0..c90d102c 100644 --- a/plugins/CMakeLists.txt +++ b/plugins/CMakeLists.txt @@ -12,7 +12,7 @@ target_include_directories(nop_plugin PRIVATE $ ) -add_dependencies(nop_plugin subspace_proto) +add_dependencies(nop_plugin subspace_proto subspace_phaser) if(ANDROID) # Android's lld requires all symbols resolved at link time for .so files @@ -41,6 +41,10 @@ else() absl::status absl::str_format ) + if(APPLE) + # The server provides these symbols when it loads the plugin. + target_link_options(nop_plugin PRIVATE "LINKER:-undefined,dynamic_lookup") + endif() endif() set_target_properties(nop_plugin PROPERTIES @@ -49,6 +53,39 @@ set_target_properties(nop_plugin PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/plugins" ) +if(APPLE) + # A plugin loaded with dlopen gets its own thread-local co::self, so the + # client test links these libraries and calls their *_Create() functions + # directly. + add_library(nop_plugin_lib STATIC + nop_plugin.cc + ) + target_include_directories(nop_plugin_lib PRIVATE + ${CMAKE_BINARY_DIR} + $ + $ + $ + $ + $ + $ + ) + add_dependencies(nop_plugin_lib subspace_proto subspace_phaser) + + add_library(split_buffer_free_test_plugin_lib STATIC + split_buffer_free_test_plugin.cc + ) + target_include_directories(split_buffer_free_test_plugin_lib PRIVATE + ${CMAKE_BINARY_DIR} + $ + $ + $ + $ + $ + ) + add_dependencies(split_buffer_free_test_plugin_lib + subspace_proto subspace_phaser) +endif() + add_library(split_buffer_free_test_plugin MODULE split_buffer_free_test_plugin.cc ) @@ -62,7 +99,7 @@ target_include_directories(split_buffer_free_test_plugin PRIVATE $ ) -add_dependencies(split_buffer_free_test_plugin subspace_proto) +add_dependencies(split_buffer_free_test_plugin subspace_proto subspace_phaser) if(ANDROID) target_link_libraries(split_buffer_free_test_plugin PRIVATE @@ -87,6 +124,11 @@ else() target_link_libraries(split_buffer_free_test_plugin PRIVATE absl::status ) + if(APPLE) + # The server provides these symbols when it loads the plugin. + target_link_options(split_buffer_free_test_plugin PRIVATE + "LINKER:-undefined,dynamic_lookup") + endif() endif() set_target_properties(split_buffer_free_test_plugin PROPERTIES diff --git a/proto/BUILD.bazel b/proto/BUILD.bazel index cc6e26bd..9fc8077c 100644 --- a/proto/BUILD.bazel +++ b/proto/BUILD.bazel @@ -1,5 +1,6 @@ load("@protobuf//bazel:proto_library.bzl", "proto_library") load("@protobuf//bazel:cc_proto_library.bzl", "cc_proto_library") +load("@phaser//phaser:phaser_library.bzl", "phaser_library") package(default_visibility = ["//visibility:public"]) @@ -16,6 +17,33 @@ cc_proto_library( deps = [":subspace_proto"], ) +# Phaser messages for subspace.proto in namespace subspace::phaser. They are +# built in caller-provided buffers without heap allocation and converted to and +# from protobuf wire format. +phaser_library( + name = "subspace_phaser", + add_namespace = "phaser", + copts = [ + "-fno-exceptions", + "-fno-rtti", + ], + deps = [":subspace_proto"], +) + +# C frontend for the Rust client. The socket carries the native Phaser payload +# from this crate. The extra namespace keeps these C++ symbols distinct from +# //proto:subspace_phaser, which the C++ clients also link into the Rust tests. +# Exceptions stay enabled because the C handle allocates with try/catch. +# direct_header_symlinks is off so this target can share the proto with the +# protobuf-frontend library above. +phaser_library( + name = "subspace_phaser_c", + add_namespace = "phaser_c", + direct_header_symlinks = False, + rust = True, + deps = [":subspace_proto"], +) + proto_library( name = "tunnel_proto", srcs = [ @@ -29,4 +57,3 @@ cc_proto_library( name = "tunnel_cc_proto", deps = [":tunnel_proto"], ) - diff --git a/proto/CMakeLists.txt b/proto/CMakeLists.txt index 83ef042e..9660b8cd 100644 --- a/proto/CMakeLists.txt +++ b/proto/CMakeLists.txt @@ -95,3 +95,24 @@ target_link_libraries(subspace_proto PUBLIC protobuf::libprotobuf ) +# Phaser messages for the clients' server requests and responses. The socket +# carries the native Phaser payload. Cross-compiles need a host plugin in +# PHASER_PLUGIN_EXECUTABLE. +if(CMAKE_CROSSCOMPILING AND NOT PHASER_PLUGIN_EXECUTABLE) + message(FATAL_ERROR + "Cross-compiling needs a host protoc-gen-phaser in " + "-DPHASER_PLUGIN_EXECUTABLE.") +endif() +set(SUBSPACE_PHASER_PROTOC) +if(CMAKE_CROSSCOMPILING) + set(SUBSPACE_PHASER_PROTOC PROTOC ${PROTOC_EXECUTABLE}) +endif() +phaser_add_library(subspace_phaser + PROTOS proto/subspace.proto + IMPORTS google/protobuf/any.proto + IMPORT_DIRS ${CMAKE_SOURCE_DIR} ${protobuf_SOURCE_DIR}/src + ADD_NAMESPACE phaser + COMPILE_OPTIONS -fno-exceptions -fno-rtti + ${SUBSPACE_PHASER_PROTOC} +) + diff --git a/proto/subspace.proto b/proto/subspace.proto index fd550338..b9b7a7c0 100644 --- a/proto/subspace.proto +++ b/proto/subspace.proto @@ -14,6 +14,9 @@ message InitRequest { int32 max_channels = 2; int32 max_slot_owners = 3; int32 max_buffers = 4; + // Set by the ASIL client. With a static channel config loaded, an ASIL + // publisher can use only the configured channels. + bool asil = 5; } // All Request and Response messages are carried over a Unix Domain @@ -60,6 +63,11 @@ message CreatePublisherRequest { // Upper bound on the channel's slot size, already aligned. 0 means // unlimited. int64 max_slot_size = 23; + // The channel is in the server's static channel config, which defines its + // layout. Publishers on static channels must set this and leave + // num_slots, slot_size, is_fixed_size, checksum_size, metadata_size, + // subscriber_queue_arena_size and use_split_buffers unset. + bool server_defined = 24; } message CreatePublisherResponse { @@ -81,6 +89,13 @@ message CreatePublisherResponse { // Slots in the channel, which can exceed the requested num_slots when the // channel already exists. The CCB layout depends on it. int32 num_slots = 16; + // The rest of the channel's layout, which a server_defined publisher takes + // from here. + int64 slot_size = 17; + int32 checksum_size = 18; + int32 metadata_size = 19; + bool use_split_buffers = 20; + bool is_fixed_size = 21; } // This is used both to create a new subscriber and to reload @@ -220,6 +235,12 @@ message GetClientBuffersRequest { string channel_name = 1; uint64 session_id = 2; uint32 buffer_index = 3; + // If filter_slot is set, only the buffer matching is_prefix and slot_id is + // returned. This keeps responses small for channels with many split + // buffer slots. + bool filter_slot = 4; + bool is_prefix = 5; + uint32 slot_id = 6; } message GetClientBuffersResponse { @@ -666,3 +687,53 @@ message Telemetry { repeated Drop drops = 3; repeated Resize resizes = 4; } + +// A server given a StaticChannelConfig (subspace_server --channel_config, in +// protobuf text format) creates its channels before it accepts any clients. +// Clients can then use only these channels and the server's own +// /subspace/ChannelDirectory and /subspace/Statistics. The channels stay for +// the life of the server and their layout is fixed: publishers must be fixed +// size and match the configured slot size, number of slots, checksum size, +// metadata size and split buffer mode. The server creates each channel's +// buffers when it starts, so subscribers can map them before any publisher +// exists. +message StaticMultiplexer { + string name = 1; + int32 slot_size = 2; + int32 num_slots = 3; + // Type of the data on this multiplexer. Bytes, the same as the type on + // the wire: a short name, or an opaque blob such as ROS metadata or a + // protobuf descriptor. In text format a quoted string is those bytes, + // and escapes such as \377 carry bytes that are not text. + bytes type = 4; + int32 checksum_size = 5; // 0 means the default of 4 bytes. + int32 metadata_size = 6; + // Message payloads are in shared memory of their own, one for each slot. + bool use_split_buffers = 7; +} + +message StaticChannel { + string name = 1; + // A channel on a multiplexer leaves slot_size, num_slots, type, + // checksum_size, metadata_size and use_split_buffers unset and takes them + // from the multiplexer. type is bytes, the same as the type on the wire: + // a short name, or an opaque blob such as ROS metadata or a protobuf + // descriptor. In text format a quoted string is those bytes, and escapes + // such as \377 carry bytes that are not text. + int32 slot_size = 2; + int32 num_slots = 3; + bytes type = 4; + int32 checksum_size = 5; // 0 means the default of 4 bytes. + int32 metadata_size = 6; + // Name of an entry in StaticChannelConfig.multiplexers. + string mux = 7; + // Virtual channel id on the multiplexer. Only used when mux is set. + int32 vchan_id = 8; + // Message payloads are in shared memory of their own, one for each slot. + bool use_split_buffers = 9; +} + +message StaticChannelConfig { + repeated StaticMultiplexer multiplexers = 1; + repeated StaticChannel channels = 2; +} diff --git a/proto/tunnel_config.proto b/proto/tunnel_config.proto index 47b1fc58..2bb6c97c 100644 --- a/proto/tunnel_config.proto +++ b/proto/tunnel_config.proto @@ -1,4 +1,4 @@ -// Copyright 2026 General Motors LLC +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/proto/tunnel_discovery.proto b/proto/tunnel_discovery.proto index 24df98b8..f59ed317 100644 --- a/proto/tunnel_discovery.proto +++ b/proto/tunnel_discovery.proto @@ -1,4 +1,4 @@ -// Copyright 2026 General Motors LLC +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/proto/tunnel_handshake.proto b/proto/tunnel_handshake.proto index c5fd8791..d695eeef 100644 --- a/proto/tunnel_handshake.proto +++ b/proto/tunnel_handshake.proto @@ -1,4 +1,4 @@ -// Copyright 2026 General Motors LLC +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/rust_client/BUILD.bazel b/rust_client/BUILD.bazel index 84830645..77fbe697 100644 --- a/rust_client/BUILD.bazel +++ b/rust_client/BUILD.bazel @@ -33,6 +33,7 @@ rust_library( aliases = aliases(), deps = all_crate_deps(normal = True) + [ ":build_script", + "//proto:subspace_phaser_c_rs", ], ) diff --git a/rust_client/CMakeLists.txt b/rust_client/CMakeLists.txt index 82fb84a7..a92a6c66 100644 --- a/rust_client/CMakeLists.txt +++ b/rust_client/CMakeLists.txt @@ -25,15 +25,55 @@ else() set(CARGO_TARGET_DIR "debug") endif() +# The client sends the server native Phaser payloads, built through phaser's C +# frontend. The phaser_c crate includes the generated Rust bindings. Cargo +# cannot follow CMake's static libraries, so their C++ code and everything it +# uses are linked into one shared library. +phaser_add_library(subspace_phaser_c + PROTOS proto/subspace.proto + IMPORTS google/protobuf/any.proto + IMPORT_DIRS ${CMAKE_SOURCE_DIR} ${protobuf_SOURCE_DIR}/src + ADD_NAMESPACE phaser_c + RUST +) +if(NOT EXISTS "${CMAKE_CURRENT_BINARY_DIR}/subspace_phaser_c_rust.cc") + file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/subspace_phaser_c_rust.cc" "") +endif() +add_library(subspace_phaser_c_rust SHARED + "${CMAKE_CURRENT_BINARY_DIR}/subspace_phaser_c_rust.cc" +) +# Nothing in the shared library calls the C API, so the linker would drop it. +if(APPLE) + set(SUBSPACE_PHASER_C_WHOLE + -Wl,-force_load,$ + -Wl,-force_load,$) +else() + set(SUBSPACE_PHASER_C_WHOLE + -Wl,--whole-archive + $ + $ + -Wl,--no-whole-archive) +endif() +target_link_libraries(subspace_phaser_c_rust PRIVATE + ${SUBSPACE_PHASER_C_WHOLE} + subspace_phaser_c +) + +set(SUBSPACE_CARGO_ENV + SUBSPACE_MAX_CHANNELS=${SUBSPACE_MAX_CHANNELS} + SUBSPACE_MAX_SLOT_OWNERS=${SUBSPACE_MAX_SLOT_OWNERS} + SUBSPACE_MAX_BUFFERS=${SUBSPACE_MAX_BUFFERS} + SUBSPACE_PHASER_C_RS=$ + SUBSPACE_PHASER_C_LIB_DIR=$ +) + add_custom_target(subspace_client_rust ALL - COMMAND ${CMAKE_COMMAND} -E env - SUBSPACE_MAX_CHANNELS=${SUBSPACE_MAX_CHANNELS} - SUBSPACE_MAX_SLOT_OWNERS=${SUBSPACE_MAX_SLOT_OWNERS} - SUBSPACE_MAX_BUFFERS=${SUBSPACE_MAX_BUFFERS} + COMMAND ${CMAKE_COMMAND} -E env ${SUBSPACE_CARGO_ENV} ${CARGO_EXECUTABLE} build ${CARGO_BUILD_FLAG} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} COMMENT "Building Rust client library via Cargo" ) +add_dependencies(subspace_client_rust subspace_phaser_c_rust) # The Rust client opens named /dev/shm buffers and cannot consume buffers # created by a server using the anonymous memfd backend. This mirrors the Bazel @@ -50,6 +90,6 @@ else() WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} ) set_tests_properties(rust_client_test PROPERTIES - ENVIRONMENT "PATH=$:$ENV{PATH};SUBSPACE_MAX_CHANNELS=${SUBSPACE_MAX_CHANNELS};SUBSPACE_MAX_SLOT_OWNERS=${SUBSPACE_MAX_SLOT_OWNERS};SUBSPACE_MAX_BUFFERS=${SUBSPACE_MAX_BUFFERS}" + ENVIRONMENT "PATH=$:$ENV{PATH};${SUBSPACE_CARGO_ENV}" ) endif() diff --git a/rust_client/Cargo.lock b/rust_client/Cargo.lock index aae3132f..4ea8a9f6 100644 --- a/rust_client/Cargo.lock +++ b/rust_client/Cargo.lock @@ -414,9 +414,14 @@ dependencies = [ "prost", "prost-build", "prost-types", + "subspace_phaser_c", "thiserror", ] +[[package]] +name = "subspace_phaser_c" +version = "2.2.0" + [[package]] name = "syn" version = "2.0.116" diff --git a/rust_client/Cargo.toml b/rust_client/Cargo.toml index aa8c56d2..2d33dbfe 100644 --- a/rust_client/Cargo.toml +++ b/rust_client/Cargo.toml @@ -12,6 +12,7 @@ prost-types = "0.13" thiserror = "2" log = "0.4" libc = "0.2" +subspace_phaser_c = { path = "phaser_c" } [build-dependencies] prost-build = "0.13" diff --git a/rust_client/build.rs b/rust_client/build.rs index 2fea3924..f5a4d7cc 100644 --- a/rust_client/build.rs +++ b/rust_client/build.rs @@ -58,6 +58,13 @@ fn main() -> Result<(), Box> { ); println!("cargo:rustc-env=SUBSPACE_MAX_BUFFERS={max_buffers}"); + // Under Cargo the phaser bindings link a shared library from the CMake + // build, which the tests find through this rpath. Bazel links them + // statically. + if let Ok(dir) = std::env::var("DEP_SUBSPACE_PHASER_C_RUST_LIB_DIR") { + println!("cargo:rustc-link-arg=-Wl,-rpath,{dir}"); + } + let proto_file = std::env::var("SUBSPACE_PROTO_FILE") .unwrap_or_else(|_| "../proto/subspace.proto".into()); diff --git a/rust_client/phaser_c/Cargo.toml b/rust_client/phaser_c/Cargo.toml new file mode 100644 index 00000000..8d57929b --- /dev/null +++ b/rust_client/phaser_c/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "subspace_phaser_c" +version = "2.2.0" +edition = "2021" +description = "Phaser bindings for the Subspace server messages, generated by the CMake build" +license = "Proprietary" +publish = false +links = "subspace_phaser_c_rust" diff --git a/rust_client/phaser_c/build.rs b/rust_client/phaser_c/build.rs new file mode 100644 index 00000000..4ead84b7 --- /dev/null +++ b/rust_client/phaser_c/build.rs @@ -0,0 +1,23 @@ +// Copyright 2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +// CMake generates the bindings with phaser_add_library and links their C++ +// code, with everything it uses, into one shared library. Bazel builds this +// crate from //proto:subspace_phaser_c_rs instead. + +fn required(var: &str) -> String { + println!("cargo:rerun-if-env-changed={var}"); + std::env::var(var) + .unwrap_or_else(|_| panic!("{var} is not set: build the Rust client with CMake or Bazel")) +} + +fn main() { + let source = required("SUBSPACE_PHASER_C_RS"); + let lib_dir = required("SUBSPACE_PHASER_C_LIB_DIR"); + println!("cargo:rustc-env=SUBSPACE_PHASER_C_RS={source}"); + println!("cargo:rustc-link-search=native={lib_dir}"); + println!("cargo:rustc-link-lib=dylib=subspace_phaser_c_rust"); + // Dependents read this as DEP_SUBSPACE_PHASER_C_RUST_LIB_DIR. + println!("cargo:lib_dir={lib_dir}"); +} diff --git a/rust_client/phaser_c/src/lib.rs b/rust_client/phaser_c/src/lib.rs new file mode 100644 index 00000000..7697b8fc --- /dev/null +++ b/rust_client/phaser_c/src/lib.rs @@ -0,0 +1,14 @@ +// Copyright 2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +// The attributes in phaser's rust_crate_attributes.rs, which the generated +// bindings need on their crate root. +#![allow( + non_camel_case_types, + non_snake_case, + non_upper_case_globals, + dead_code +)] + +include!(env!("SUBSPACE_PHASER_C_RS")); diff --git a/rust_client/src/client.rs b/rust_client/src/client.rs index 95b4fe2e..a7b185c3 100644 --- a/rust_client/src/client.rs +++ b/rust_client/src/client.rs @@ -1184,40 +1184,38 @@ impl Client { let socket = SocketConnection::connect(server_socket)?; // Send Init request. - let req = proto::Request { - request: Some(proto::request::Request::Init(proto::InitRequest { - client_name: client_name.to_string(), - max_channels: MAX_CHANNELS as i32, - max_slot_owners: MAX_SLOT_OWNERS as i32, - max_buffers: MAX_BUFFERS as i32, - })), - }; + let mut req = phaser_request(); + { + let mut init = req.mutable_init(); + init.set_client_name(client_name); + init.set_max_channels(MAX_CHANNELS as i32); + init.set_max_slot_owners(MAX_SLOT_OWNERS as i32); + init.set_max_buffers(MAX_BUFFERS as i32); + } socket.send_request(&req)?; let (resp, fds) = socket.receive_response()?; - let init = match resp.response { - Some(proto::response::Response::Init(init)) => init, - _ => { - return Err(SubspaceError::Internal( - "Unexpected response to Init".into(), - )) - } - }; + if resp.response_case() != RESP_INIT { + return Err(SubspaceError::Internal( + "Unexpected response to Init".into(), + )); + } + let init = resp.init(); - if !init.error.is_empty() { - return Err(SubspaceError::Internal(init.error)); + if !init.error().is_empty() { + return Err(SubspaceError::Internal(init.error())); } - let scb_fd = fds[init.scb_fd_index as usize]; + let scb_fd = fds[init.scb_fd_index() as usize]; Ok(Self { inner: Arc::new(Mutex::new(ClientInner { socket, name: client_name.to_string(), - session_id: init.session_id as u64, + session_id: init.session_id() as u64, scb_fd, - server_user_id: init.user_id, - server_group_id: init.group_id, + server_user_id: init.user_id(), + server_group_id: init.group_id(), debug: false, })), }) @@ -1234,7 +1232,25 @@ impl Client { ) -> Result { let mut client = self.inner.lock().unwrap(); - if opts.max_outstanding_slot_leases < 1 || opts.max_outstanding_slot_leases > opts.num_slots + if opts.server_defined { + if opts.slot_size != 0 + || opts.num_slots != 0 + || opts.fixed_size + || opts.checksum_size != 0 + || opts.metadata_size != 0 + || opts.subscriber_queue_arena_size != 0 + || opts.use_split_buffers + { + return Err(SubspaceError::InvalidArgument(format!( + "Publisher on {} is server defined, so it can't set the slot size, \ + number of slots, fixed size, checksum size, metadata size, \ + subscriber queue arena size or split buffers", + channel_name + ))); + } + // The server checks the leases against the channel's slots. + } else if opts.max_outstanding_slot_leases < 1 + || opts.max_outstanding_slot_leases > opts.num_slots { return Err(SubspaceError::InvalidArgument( "MaxOutstandingSlotLeases must be between 1 and NumSlots".into(), @@ -1255,116 +1271,122 @@ impl Client { let slot_size = aligned64(opts.slot_size as i64); - let req = proto::Request { - request: Some(proto::request::Request::CreatePublisher( - proto::CreatePublisherRequest { - channel_name: channel_name.to_string(), - slot_size, - num_slots: opts.num_slots, - is_local: opts.local, - is_reliable: opts.reliable, - is_bridge: opts.bridge, - is_fixed_size: opts.fixed_size, - for_tunnel: opts.for_tunnel, - r#type: opts.channel_type.as_bytes().to_vec(), - mux: opts.mux.clone(), - vchan_id: opts.vchan_id, - notify_retirement: opts.notify_retirement, - checksum_size: opts.checksum_size, - metadata_size: opts.metadata_size, - use_split_buffers: opts.use_split_buffers, - split_buffers_over_bridge: opts.split_buffers_over_bridge, - subscriber_queue_arena_size: opts.subscriber_queue_arena_size, - max_publishers: 0, - publisher_id: -1, - process_id: std::process::id() as u64, - max_outstanding_slot_leases: opts.max_outstanding_slot_leases, - active_queue_publish_depth: 0, - // Align the cap the same way as the slot size so that a - // publisher asking for slot_size == max_slot_size isn't - // rejected by its own limit. - max_slot_size: if opts.max_slot_size > 0 { - aligned64(opts.max_slot_size) - } else { - 0 - }, - }, - )), - }; + let mut req = phaser_request(); + { + let mut create = req.mutable_create_publisher(); + create.set_channel_name(channel_name); + create.set_slot_size(slot_size); + create.set_num_slots(opts.num_slots); + create.set_is_local(opts.local); + create.set_is_reliable(opts.reliable); + create.set_is_bridge(opts.bridge); + create.set_is_fixed_size(opts.fixed_size); + create.set_for_tunnel(opts.for_tunnel); + create.set_type(opts.channel_type.as_bytes()); + create.set_mux(&opts.mux); + create.set_vchan_id(opts.vchan_id); + create.set_notify_retirement(opts.notify_retirement); + create.set_checksum_size(opts.checksum_size); + create.set_metadata_size(opts.metadata_size); + create.set_use_split_buffers(opts.use_split_buffers); + create.set_split_buffers_over_bridge(opts.split_buffers_over_bridge); + create.set_subscriber_queue_arena_size(opts.subscriber_queue_arena_size); + create.set_max_publishers(0); + create.set_publisher_id(-1); + create.set_process_id(std::process::id() as u64); + create.set_max_outstanding_slot_leases(opts.max_outstanding_slot_leases); + create.set_active_queue_publish_depth(0); + // Align the cap the same way as the slot size so that a + // publisher asking for slot_size == max_slot_size isn't + // rejected by its own limit. + create.set_max_slot_size(if opts.max_slot_size > 0 { + aligned64(opts.max_slot_size) + } else { + 0 + }); + create.set_server_defined(opts.server_defined); + } let (resp, fds) = send_request_receive_response(&mut client, &req)?; - let pub_resp = match resp.response { - Some(proto::response::Response::CreatePublisher(r)) => r, - _ => { - return Err(SubspaceError::Internal( - "Unexpected response to CreatePublisher".into(), - )) - } - }; + if resp.response_case() != RESP_CREATE_PUBLISHER { + return Err(SubspaceError::Internal( + "Unexpected response to CreatePublisher".into(), + )); + } + let pub_resp = resp.create_publisher(); - if !pub_resp.error.is_empty() { - return Err(SubspaceError::ServerError(pub_resp.error)); + if !pub_resp.error().is_empty() { + return Err(SubspaceError::ServerError(pub_resp.error())); } // A publisher may join an existing channel with fewer slots than it // has. The CCB layout is sized by the channel's slot count, so map // with that. Servers that predate num_slots in the response send zero. let mut channel_opts = opts.clone(); - if pub_resp.num_slots > 0 { - channel_opts.num_slots = pub_resp.num_slots; - } + if pub_resp.num_slots() > 0 { + channel_opts.num_slots = pub_resp.num_slots(); + } + if opts.server_defined { + channel_opts.slot_size = pub_resp.slot_size(); + channel_opts.fixed_size = pub_resp.is_fixed_size(); + channel_opts.checksum_size = pub_resp.checksum_size(); + channel_opts.metadata_size = pub_resp.metadata_size(); + channel_opts.subscriber_queue_arena_size = pub_resp.subscriber_queue_arena_size(); + channel_opts.use_split_buffers = pub_resp.use_split_buffers(); + } + let slot_size = aligned64(channel_opts.slot_size); + let use_split_buffers = channel_opts.use_split_buffers; + let cs = if channel_opts.checksum_size > 0 { + channel_opts.checksum_size + } else { + 4 + }; + let ms = if channel_opts.metadata_size > 0 { + channel_opts.metadata_size + } else { + 0 + }; let mut pub_impl = PublisherImpl::new( channel_name.to_string(), channel_opts.num_slots, - pub_resp.subscriber_queue_size, - pub_resp.subscriber_queue_arena_size, - pub_resp.channel_id, - pub_resp.publisher_id, - pub_resp.vchan_id, + pub_resp.subscriber_queue_size(), + pub_resp.subscriber_queue_arena_size(), + pub_resp.channel_id(), + pub_resp.publisher_id(), + pub_resp.vchan_id(), client.session_id, - String::from_utf8_lossy(&pub_resp.r#type).to_string(), + String::from_utf8_lossy(&pub_resp.type_()).into_owned(), channel_opts, ); - pub_impl.channel.use_split_buffers = opts.use_split_buffers; + pub_impl.channel.use_split_buffers = use_split_buffers; pub_impl.channel.split_buffer_callbacks = opts.split_buffer_callbacks.clone(); - - { - let cs = if opts.checksum_size > 0 { - opts.checksum_size - } else { - 4 - }; - let ms = if opts.metadata_size > 0 { - opts.metadata_size - } else { - 0 - }; - pub_impl.channel.checksum_size = cs; - pub_impl.channel.metadata_size = ms; - pub_impl.channel.prefix_size = compute_prefix_size(cs, ms); - } + pub_impl.channel.checksum_size = cs; + pub_impl.channel.metadata_size = ms; + pub_impl.channel.prefix_size = compute_prefix_size(cs, ms); let prot = ProtFlags::PROT_READ | ProtFlags::PROT_WRITE; pub_impl.channel.map( client.scb_fd, - fds[pub_resp.ccb_fd_index as usize], - fds[pub_resp.bcb_fd_index as usize], + fds[pub_resp.ccb_fd_index() as usize], + fds[pub_resp.bcb_fd_index() as usize], prot, )?; pub_impl.create_or_attach_buffers(slot_size as u64)?; register_pending_client_buffers(&mut client, &mut pub_impl.channel)?; - pub_impl.trigger_fd = fds[pub_resp.pub_trigger_fd_index as usize]; - pub_impl.poll_fd = fds[pub_resp.pub_poll_fd_index as usize]; + pub_impl.trigger_fd = fds[pub_resp.pub_trigger_fd_index() as usize]; + pub_impl.poll_fd = fds[pub_resp.pub_poll_fd_index() as usize]; pub_impl.subscriber_trigger_fds.clear(); - for &idx in &pub_resp.sub_trigger_fd_indexes { - pub_impl.subscriber_trigger_fds.push(fds[idx as usize]); + for i in 0..pub_resp.sub_trigger_fd_indexes_size() { + pub_impl + .subscriber_trigger_fds + .push(fds[pub_resp.sub_trigger_fd_indexes(i) as usize]); } - pub_impl.channel.num_updates = pub_resp.num_sub_updates as u16; + pub_impl.channel.num_updates = pub_resp.num_sub_updates() as u16; if !opts.reliable { let owner = pub_impl.publisher_id; @@ -1383,12 +1405,14 @@ impl Client { activate_reliable_channel(&mut pub_impl)?; } - if pub_resp.retirement_fd_index != -1 { - pub_impl.retirement_fd = fds[pub_resp.retirement_fd_index as usize]; + if pub_resp.retirement_fd_index() != -1 { + pub_impl.retirement_fd = fds[pub_resp.retirement_fd_index() as usize]; } pub_impl.retirement_trigger_fds.clear(); - for &idx in &pub_resp.retirement_fd_indexes { - pub_impl.retirement_trigger_fds.push(fds[idx as usize]); + for i in 0..pub_resp.retirement_fd_indexes_size() { + pub_impl + .retirement_trigger_fds + .push(fds[pub_resp.retirement_fd_indexes(i) as usize]); } pub_impl.trigger_subscribers(); @@ -1426,61 +1450,57 @@ impl Client { ))); } - let req = proto::Request { - request: Some(proto::request::Request::CreateSubscriber( - proto::CreateSubscriberRequest { - channel_name: channel_name.to_string(), - subscriber_id: -1, - is_reliable: opts.reliable, - is_bridge: opts.bridge, - for_tunnel: opts.for_tunnel, - telemetry: opts.telemetry, - r#type: opts.channel_type.as_bytes().to_vec(), - max_active_messages: opts.max_active_messages, - mux: opts.mux.clone(), - vchan_id: opts.vchan_id, - subscriber_queue_size: opts.subscriber_queue_size, - process_id: std::process::id() as u64, - max_subscribers: opts.max_subscribers, - is_local: opts.local, - }, - )), - }; + let mut req = phaser_request(); + { + let mut create = req.mutable_create_subscriber(); + create.set_channel_name(channel_name); + create.set_subscriber_id(-1); + create.set_is_reliable(opts.reliable); + create.set_is_bridge(opts.bridge); + create.set_for_tunnel(opts.for_tunnel); + create.set_telemetry(opts.telemetry); + create.set_type(opts.channel_type.as_bytes()); + create.set_max_active_messages(opts.max_active_messages); + create.set_mux(&opts.mux); + create.set_vchan_id(opts.vchan_id); + create.set_subscriber_queue_size(opts.subscriber_queue_size); + create.set_process_id(std::process::id() as u64); + create.set_max_subscribers(opts.max_subscribers); + create.set_is_local(opts.local); + } let (resp, fds) = send_request_receive_response(&mut client, &req)?; - let sub_resp = match resp.response { - Some(proto::response::Response::CreateSubscriber(r)) => r, - _ => { - return Err(SubspaceError::Internal( - "Unexpected response to CreateSubscriber".into(), - )) - } - }; + if resp.response_case() != RESP_CREATE_SUBSCRIBER { + return Err(SubspaceError::Internal( + "Unexpected response to CreateSubscriber".into(), + )); + } + let sub_resp = resp.create_subscriber(); - if !sub_resp.error.is_empty() { - return Err(SubspaceError::ServerError(sub_resp.error)); + if !sub_resp.error().is_empty() { + return Err(SubspaceError::ServerError(sub_resp.error())); } let request_name = channel_name.to_string(); let channel_name = - resolved_subscriber_channel_name(&request_name, &sub_resp.resolved_channel_name); + resolved_subscriber_channel_name(&request_name, &sub_resp.resolved_channel_name()); let mut sub_impl = SubscriberImpl::new( request_name, channel_name, - sub_resp.num_slots, - sub_resp.default_subscriber_queue_size, - sub_resp.subscriber_queue_arena_size, - sub_resp.subscriber_queue_size, - sub_resp.channel_id, - sub_resp.subscriber_id, - sub_resp.vchan_id, + sub_resp.num_slots(), + sub_resp.default_subscriber_queue_size(), + sub_resp.subscriber_queue_arena_size(), + sub_resp.subscriber_queue_size(), + sub_resp.channel_id(), + sub_resp.subscriber_id(), + sub_resp.vchan_id(), client.session_id, - String::from_utf8_lossy(&sub_resp.r#type).to_string(), + String::from_utf8_lossy(&sub_resp.type_()).to_string(), opts.clone(), ); - sub_impl.channel.use_split_buffers = sub_resp.use_split_buffers; + sub_impl.channel.use_split_buffers = sub_resp.use_split_buffers(); sub_impl.channel.split_buffer_callbacks = opts.split_buffer_callbacks.clone(); let prot = if opts.bridge || opts.read_write { @@ -1489,24 +1509,24 @@ impl Client { ProtFlags::PROT_READ | ProtFlags::PROT_WRITE // CCB needs write for atomic ops }; - sub_impl.channel.num_slots = sub_resp.num_slots; - sub_impl.channel.subscriber_queue_size = sub_resp.default_subscriber_queue_size; + sub_impl.channel.num_slots = sub_resp.num_slots(); + sub_impl.channel.subscriber_queue_size = sub_resp.default_subscriber_queue_size(); sub_impl.channel.subscriber_queue_arena_size = - sub_resp.subscriber_queue_arena_size; - sub_impl.subscriber_queue_size = sub_resp.subscriber_queue_size; + sub_resp.subscriber_queue_arena_size(); + sub_impl.subscriber_queue_size = sub_resp.subscriber_queue_size(); sub_impl .channel .embargoed_slots - .resize(sub_resp.num_slots as usize); + .resize(sub_resp.num_slots() as usize); { - let cs = if sub_resp.checksum_size > 0 { - sub_resp.checksum_size + let cs = if sub_resp.checksum_size() > 0 { + sub_resp.checksum_size() } else { 4 }; - let ms = if sub_resp.metadata_size > 0 { - sub_resp.metadata_size + let ms = if sub_resp.metadata_size() > 0 { + sub_resp.metadata_size() } else { 0 }; @@ -1518,31 +1538,33 @@ impl Client { sub_impl.channel.map( client.scb_fd, - fds[sub_resp.ccb_fd_index as usize], - fds[sub_resp.bcb_fd_index as usize], + fds[sub_resp.ccb_fd_index() as usize], + fds[sub_resp.bcb_fd_index() as usize], prot, )?; sub_impl.attach_buffers()?; sub_impl.remember_published_ordinals(); - sub_impl.trigger_fd = fds[sub_resp.trigger_fd_index as usize]; - sub_impl.poll_fd = fds[sub_resp.poll_fd_index as usize]; + sub_impl.trigger_fd = fds[sub_resp.trigger_fd_index() as usize]; + sub_impl.poll_fd = fds[sub_resp.poll_fd_index() as usize]; { let mut pub_fds = sub_impl.reliable_publisher_fds.lock().unwrap(); pub_fds.clear(); - for &idx in &sub_resp.reliable_pub_trigger_fd_indexes { - pub_fds.push(fds[idx as usize]); + for i in 0..sub_resp.reliable_pub_trigger_fd_indexes_size() { + pub_fds.push(fds[sub_resp.reliable_pub_trigger_fd_indexes(i) as usize]); } } sub_impl.retirement_trigger_fds.clear(); - for &idx in &sub_resp.retirement_fd_indexes { - sub_impl.retirement_trigger_fds.push(fds[idx as usize]); + for i in 0..sub_resp.retirement_fd_indexes_size() { + sub_impl + .retirement_trigger_fds + .push(fds[sub_resp.retirement_fd_indexes(i) as usize]); } - sub_impl.channel.num_updates = sub_resp.num_pub_updates as u16; + sub_impl.channel.num_updates = sub_resp.num_pub_updates() as u16; sub_impl.trigger(); let sub_arc = Arc::new(Mutex::new(sub_impl)); @@ -1560,125 +1582,48 @@ impl Client { pub fn get_channel_info(&self, channel_name: &str) -> Result { let mut client = self.inner.lock().unwrap(); - let req = proto::Request { - request: Some(proto::request::Request::GetChannelInfo( - proto::GetChannelInfoRequest { - channel_name: channel_name.to_string(), - }, - )), - }; + let mut req = phaser_request(); + req.mutable_get_channel_info() + .set_channel_name(channel_name); let (resp, _fds) = send_request_receive_response(&mut client, &req)?; - let info_resp = match resp.response { - Some(proto::response::Response::GetChannelInfo(r)) => r, - _ => { - return Err(SubspaceError::Internal( - "Unexpected response to GetChannelInfo".into(), - )) - } - }; - if !info_resp.error.is_empty() { - return Err(SubspaceError::ServerError(info_resp.error)); - } - if info_resp.channels.len() != 1 { + let info_resp = expect_channel_info(&resp)?; + if info_resp.channels_size() != 1 { return Err(SubspaceError::Internal( "Invalid response for GetChannelInfo".into(), )); } - let info = &info_resp.channels[0]; - Ok(ChannelInfo { - channel_name: info.name.clone(), - num_publishers: info.num_pubs, - num_subscribers: info.num_subs, - num_bridge_pubs: info.num_bridge_pubs, - num_bridge_subs: info.num_bridge_subs, - channel_type: String::from_utf8_lossy(&info.r#type).to_string(), - slot_size: info.slot_size as u64, - num_slots: info.num_slots, - subscriber_queue_size: info.subscriber_queue_size, - subscriber_queue_arena_size: info.subscriber_queue_arena_size, - reliable: info.is_reliable, - is_local: info.is_local, - }) + let info = channel_info_from(&info_resp.channels(0)); + Ok(info) } pub fn get_all_channel_info(&self) -> Result> { let mut client = self.inner.lock().unwrap(); - let req = proto::Request { - request: Some(proto::request::Request::GetChannelInfo( - proto::GetChannelInfoRequest { - channel_name: String::new(), - }, - )), - }; + let mut req = phaser_request(); + req.mutable_get_channel_info().set_channel_name(""); let (resp, _fds) = send_request_receive_response(&mut client, &req)?; - let info_resp = match resp.response { - Some(proto::response::Response::GetChannelInfo(r)) => r, - _ => { - return Err(SubspaceError::Internal( - "Unexpected response to GetChannelInfo".into(), - )) - } - }; - if !info_resp.error.is_empty() { - return Err(SubspaceError::ServerError(info_resp.error)); - } - Ok(info_resp - .channels - .iter() - .map(|info| ChannelInfo { - channel_name: info.name.clone(), - num_publishers: info.num_pubs, - num_subscribers: info.num_subs, - num_bridge_pubs: info.num_bridge_pubs, - num_bridge_subs: info.num_bridge_subs, - channel_type: String::from_utf8_lossy(&info.r#type).to_string(), - slot_size: info.slot_size as u64, - num_slots: info.num_slots, - subscriber_queue_size: info.subscriber_queue_size, - subscriber_queue_arena_size: info.subscriber_queue_arena_size, - reliable: info.is_reliable, - is_local: info.is_local, - }) + let info_resp = expect_channel_info(&resp)?; + Ok((0..info_resp.channels_size()) + .map(|i| channel_info_from(&info_resp.channels(i))) .collect()) } pub fn get_channel_stats(&self, channel_name: &str) -> Result { let mut client = self.inner.lock().unwrap(); - let req = proto::Request { - request: Some(proto::request::Request::GetChannelStats( - proto::GetChannelStatsRequest { - channel_name: channel_name.to_string(), - }, - )), - }; + let mut req = phaser_request(); + req.mutable_get_channel_stats() + .set_channel_name(channel_name); let (resp, _fds) = send_request_receive_response(&mut client, &req)?; - let stats_resp = match resp.response { - Some(proto::response::Response::GetChannelStats(r)) => r, - _ => { - return Err(SubspaceError::Internal( - "Unexpected response to GetChannelStats".into(), - )) - } - }; - if !stats_resp.error.is_empty() { - return Err(SubspaceError::ServerError(stats_resp.error)); - } - if stats_resp.channels.len() != 1 { + let stats_resp = expect_channel_stats(&resp)?; + if stats_resp.channels_size() != 1 { return Err(SubspaceError::Internal( "Invalid response for GetChannelStats".into(), )); } - let s = &stats_resp.channels[0]; - Ok(ChannelStats { - channel_name: s.channel_name.clone(), - total_bytes: s.total_bytes as u64, - total_messages: s.total_messages as u64, - max_message_size: s.max_message_size as u64, - is_local: s.is_local, - }) + let stats = channel_stats_from(&stats_resp.channels(0)); + Ok(stats) } pub fn channel_exists(&self, channel_name: &str) -> Result { @@ -1691,71 +1636,137 @@ impl Client { pub fn get_all_channel_stats(&self) -> Result> { let mut client = self.inner.lock().unwrap(); - let req = proto::Request { - request: Some(proto::request::Request::GetChannelStats( - proto::GetChannelStatsRequest { - channel_name: String::new(), - }, - )), - }; + let mut req = phaser_request(); + req.mutable_get_channel_stats().set_channel_name(""); let (resp, _fds) = send_request_receive_response(&mut client, &req)?; - let stats_resp = match resp.response { - Some(proto::response::Response::GetChannelStats(r)) => r, - _ => { - return Err(SubspaceError::Internal( - "Unexpected response to GetChannelStats".into(), - )) - } - }; - if !stats_resp.error.is_empty() { - return Err(SubspaceError::ServerError(stats_resp.error)); - } - Ok(stats_resp - .channels - .iter() - .map(|s| ChannelStats { - channel_name: s.channel_name.clone(), - total_bytes: s.total_bytes as u64, - total_messages: s.total_messages as u64, - max_message_size: s.max_message_size as u64, - is_local: s.is_local, - }) + let stats_resp = expect_channel_stats(&resp)?; + Ok((0..stats_resp.channels_size()) + .map(|i| channel_stats_from(&stats_resp.channels(i))) .collect()) } } // ── Internal helper functions ─────────────────────────────────────────────── +const RESP_INIT: i32 = 1; +const RESP_CREATE_PUBLISHER: i32 = 2; +const RESP_CREATE_SUBSCRIBER: i32 = 3; +const RESP_GET_TRIGGERS: i32 = 4; +const RESP_REMOVE_PUBLISHER: i32 = 5; +const RESP_REMOVE_SUBSCRIBER: i32 = 6; +const RESP_GET_CHANNEL_INFO: i32 = 7; +const RESP_GET_CHANNEL_STATS: i32 = 8; +const RESP_REGISTER_CLIENT_BUFFER: i32 = 10; + +fn phaser_request() -> subspace_phaser_c::Request<'static> { + subspace_phaser_c::Request::new(8192) +} + +fn channel_info_from(info: &subspace_phaser_c::ChannelInfoProto<'_>) -> ChannelInfo { + ChannelInfo { + channel_name: info.name(), + num_publishers: info.num_pubs(), + num_subscribers: info.num_subs(), + num_bridge_pubs: info.num_bridge_pubs(), + num_bridge_subs: info.num_bridge_subs(), + channel_type: String::from_utf8_lossy(&info.type_()).into_owned(), + slot_size: info.slot_size() as u64, + num_slots: info.num_slots(), + subscriber_queue_size: info.subscriber_queue_size(), + subscriber_queue_arena_size: info.subscriber_queue_arena_size(), + reliable: info.is_reliable(), + is_local: info.is_local(), + } +} + +fn channel_stats_from(stats: &subspace_phaser_c::ChannelStatsProto<'_>) -> ChannelStats { + ChannelStats { + channel_name: stats.channel_name(), + total_bytes: stats.total_bytes() as u64, + total_messages: stats.total_messages() as u64, + max_message_size: stats.max_message_size() as u64, + is_local: stats.is_local(), + } +} + +fn expect_channel_info<'a>( + resp: &'a subspace_phaser_c::Response<'static>, +) -> Result> { + if resp.response_case() != RESP_GET_CHANNEL_INFO { + return Err(SubspaceError::Internal( + "Unexpected response to GetChannelInfo".into(), + )); + } + let info = resp.get_channel_info(); + if !info.error().is_empty() { + return Err(SubspaceError::ServerError(info.error())); + } + Ok(info) +} + +fn expect_channel_stats<'a>( + resp: &'a subspace_phaser_c::Response<'static>, +) -> Result> { + if resp.response_case() != RESP_GET_CHANNEL_STATS { + return Err(SubspaceError::Internal( + "Unexpected response to GetChannelStats".into(), + )); + } + let stats = resp.get_channel_stats(); + if !stats.error().is_empty() { + return Err(SubspaceError::ServerError(stats.error())); + } + Ok(stats) +} + fn send_request_receive_response( client: &mut ClientInner, - req: &proto::Request, -) -> Result<(proto::Response, Vec)> { + req: &subspace_phaser_c::Request, +) -> Result<(subspace_phaser_c::Response<'static>, Vec)> { client.socket.send_request(req)?; client.socket.receive_response() } +fn fill_buffer_metadata( + dst: &mut subspace_phaser_c::ClientBufferHandleMetadataProto, + src: &proto::ClientBufferHandleMetadataProto, +) { + dst.set_channel_name(&src.channel_name); + dst.set_session_id(src.session_id); + dst.set_buffer_index(src.buffer_index); + dst.set_slot_id(src.slot_id); + dst.set_is_prefix(src.is_prefix); + dst.set_full_size(src.full_size); + dst.set_allocation_size(src.allocation_size); + dst.set_handle(src.handle); + dst.set_shadow_file(&src.shadow_file); + dst.set_object_name(&src.object_name); + dst.set_allocator(subspace_phaser_c::ClientBufferAllocator(src.allocator)); + dst.set_map_offset(src.map_offset); +} + fn register_pending_client_buffers(client: &mut ClientInner, channel: &mut Channel) -> Result<()> { let registrations = std::mem::take(&mut channel.pending_client_buffer_registrations); for metadata in registrations { - let req = proto::Request { - request: Some(proto::request::Request::RegisterClientBuffer( - proto::RegisterClientBufferRequest { - metadata: Some(metadata), - has_fd: false, - fd_index: 0, - }, - )), - }; + let mut req = phaser_request(); + { + let mut register = req.mutable_register_client_buffer(); + { + let mut dst = register.mutable_metadata(); + fill_buffer_metadata(&mut dst, &metadata); + } + register.set_has_fd(false); + register.set_fd_index(0); + } client.socket.send_request(&req)?; let (resp, _fds) = client.socket.receive_response()?; - match resp.response { - Some(proto::response::Response::RegisterClientBuffer(r)) => { - if !r.error.is_empty() { - return Err(SubspaceError::ServerError(r.error)); - } - } - _ => return Err(SubspaceError::Internal("Unexpected response".into())), + if resp.response_case() != RESP_REGISTER_CLIENT_BUFFER { + return Err(SubspaceError::Internal("Unexpected response".into())); + } + let registered = resp.register_client_buffer(); + if !registered.error().is_empty() { + return Err(SubspaceError::ServerError(registered.error())); } } Ok(()) @@ -1767,15 +1778,13 @@ fn unregister_client_buffer_request( session_id: u64, buffer_index: u32, ) -> Result<()> { - let req = proto::Request { - request: Some(proto::request::Request::UnregisterClientBuffer( - proto::UnregisterClientBufferRequest { - channel_name: channel_name.to_string(), - session_id, - buffer_index, - }, - )), - }; + let mut req = phaser_request(); + { + let mut unregister = req.mutable_unregister_client_buffer(); + unregister.set_channel_name(channel_name); + unregister.set_session_id(session_id); + unregister.set_buffer_index(buffer_index); + } client.socket.send_request(&req) } @@ -2023,31 +2032,28 @@ fn reload_subscriber(client: &mut ClientInner, sub: &mut SubscriberImpl) -> Resu if sub.channel.num_updates == updates { return Ok(()); } - let req = proto::Request { - request: Some(proto::request::Request::CreateSubscriber( - proto::CreateSubscriberRequest { - channel_name: sub.request_name.clone(), - subscriber_id: sub.subscriber_id, - mux: sub.options.mux.clone(), - subscriber_queue_size: sub.options.subscriber_queue_size, - telemetry: sub.options.telemetry, - process_id: std::process::id() as u64, - ..Default::default() - }, - )), - }; + let mut req = phaser_request(); + { + let mut create = req.mutable_create_subscriber(); + create.set_channel_name(&sub.request_name); + create.set_subscriber_id(sub.subscriber_id); + create.set_mux(&sub.options.mux); + create.set_subscriber_queue_size(sub.options.subscriber_queue_size); + create.set_telemetry(sub.options.telemetry); + create.set_process_id(std::process::id() as u64); + } let (resp, fds) = send_request_receive_response(client, &req)?; - let sub_resp = match resp.response { - Some(proto::response::Response::CreateSubscriber(r)) => r, - _ => return Err(SubspaceError::Internal("Unexpected response".into())), - }; - if !sub_resp.error.is_empty() { - return Err(SubspaceError::ServerError(sub_resp.error)); + if resp.response_case() != RESP_CREATE_SUBSCRIBER { + return Err(SubspaceError::Internal("Unexpected response".into())); + } + let sub_resp = resp.create_subscriber(); + if !sub_resp.error().is_empty() { + return Err(SubspaceError::ServerError(sub_resp.error())); } - if !sub_resp.resolved_channel_name.is_empty() { - sub.channel.name = sub_resp.resolved_channel_name.clone(); + if !sub_resp.resolved_channel_name().is_empty() { + sub.channel.name = sub_resp.resolved_channel_name().clone(); } // A subscriber-created placeholder is the only case where the server @@ -2058,27 +2064,27 @@ fn reload_subscriber(client: &mut ClientInner, sub: &mut SubscriberImpl) -> Resu sub.reset_delivery_state(); sub.channel.unmap(); } - if !sub_resp.r#type.is_empty() { - sub.channel.channel_type = String::from_utf8_lossy(&sub_resp.r#type).to_string(); + if !sub_resp.type_().is_empty() { + sub.channel.channel_type = String::from_utf8_lossy(&sub_resp.type_()).to_string(); } - sub.channel.num_slots = sub_resp.num_slots; - sub.channel.subscriber_queue_size = sub_resp.default_subscriber_queue_size; + sub.channel.num_slots = sub_resp.num_slots(); + sub.channel.subscriber_queue_size = sub_resp.default_subscriber_queue_size(); sub.channel.subscriber_queue_arena_size = - sub_resp.subscriber_queue_arena_size; - sub.subscriber_queue_size = sub_resp.subscriber_queue_size; + sub_resp.subscriber_queue_arena_size(); + sub.subscriber_queue_size = sub_resp.subscriber_queue_size(); sub.channel .embargoed_slots - .resize(sub_resp.num_slots as usize); - sub.channel.use_split_buffers = sub_resp.use_split_buffers; + .resize(sub_resp.num_slots() as usize); + sub.channel.use_split_buffers = sub_resp.use_split_buffers(); { - let cs = if sub_resp.checksum_size > 0 { - sub_resp.checksum_size + let cs = if sub_resp.checksum_size() > 0 { + sub_resp.checksum_size() } else { 4 }; - let ms = if sub_resp.metadata_size > 0 { - sub_resp.metadata_size + let ms = if sub_resp.metadata_size() > 0 { + sub_resp.metadata_size() } else { 0 }; @@ -2092,28 +2098,29 @@ fn reload_subscriber(client: &mut ClientInner, sub: &mut SubscriberImpl) -> Resu let prot = ProtFlags::PROT_READ | ProtFlags::PROT_WRITE; sub.channel.map( client.scb_fd, - fds[sub_resp.ccb_fd_index as usize], - fds[sub_resp.bcb_fd_index as usize], + fds[sub_resp.ccb_fd_index() as usize], + fds[sub_resp.bcb_fd_index() as usize], prot, )?; } sub.attach_buffers()?; - sub.trigger_fd = fds[sub_resp.trigger_fd_index as usize]; - sub.poll_fd = fds[sub_resp.poll_fd_index as usize]; + sub.trigger_fd = fds[sub_resp.trigger_fd_index() as usize]; + sub.poll_fd = fds[sub_resp.poll_fd_index() as usize]; { let mut pub_fds = sub.reliable_publisher_fds.lock().unwrap(); pub_fds.clear(); - for &idx in &sub_resp.reliable_pub_trigger_fd_indexes { - pub_fds.push(fds[idx as usize]); + for i in 0..sub_resp.reliable_pub_trigger_fd_indexes_size() { + pub_fds.push(fds[sub_resp.reliable_pub_trigger_fd_indexes(i) as usize]); } } sub.retirement_trigger_fds.clear(); - for &idx in &sub_resp.retirement_fd_indexes { - sub.retirement_trigger_fds.push(fds[idx as usize]); + for i in 0..sub_resp.retirement_fd_indexes_size() { + sub.retirement_trigger_fds + .push(fds[sub_resp.retirement_fd_indexes(i) as usize]); } if remap_ccb { @@ -2136,28 +2143,28 @@ fn reload_subscribers_if_necessary( } publisher.channel.num_updates = updates; - let req = proto::Request { - request: Some(proto::request::Request::GetTriggers( - proto::GetTriggersRequest { - channel_name: publisher.channel.name.clone(), - }, - )), - }; + let mut req = phaser_request(); + req.mutable_get_triggers() + .set_channel_name(&publisher.channel.name); let (resp, fds) = send_request_receive_response(client, &req)?; - let trig_resp = match resp.response { - Some(proto::response::Response::GetTriggers(r)) => r, - _ => return Err(SubspaceError::Internal("Unexpected response".into())), - }; + if resp.response_case() != RESP_GET_TRIGGERS { + return Err(SubspaceError::Internal("Unexpected response".into())); + } + let trig_resp = resp.get_triggers(); publisher.subscriber_trigger_fds.clear(); - for &idx in &trig_resp.sub_trigger_fd_indexes { - publisher.subscriber_trigger_fds.push(fds[idx as usize]); + for i in 0..trig_resp.sub_trigger_fd_indexes_size() { + publisher + .subscriber_trigger_fds + .push(fds[trig_resp.sub_trigger_fd_indexes(i) as usize]); } publisher.retirement_trigger_fds.clear(); - for &idx in &trig_resp.retirement_fd_indexes { - publisher.retirement_trigger_fds.push(fds[idx as usize]); + for i in 0..trig_resp.retirement_fd_indexes_size() { + publisher + .retirement_trigger_fds + .push(fds[trig_resp.retirement_fd_indexes(i) as usize]); } Ok(()) @@ -2175,31 +2182,29 @@ fn reload_reliable_publishers_if_necessary( } subscriber.channel.num_updates = updates; - let req = proto::Request { - request: Some(proto::request::Request::GetTriggers( - proto::GetTriggersRequest { - channel_name: subscriber.channel.name.clone(), - }, - )), - }; + let mut req = phaser_request(); + req.mutable_get_triggers() + .set_channel_name(&subscriber.channel.name); let (resp, fds) = send_request_receive_response(client, &req)?; - let trig_resp = match resp.response { - Some(proto::response::Response::GetTriggers(r)) => r, - _ => return Err(SubspaceError::Internal("Unexpected response".into())), - }; + if resp.response_case() != RESP_GET_TRIGGERS { + return Err(SubspaceError::Internal("Unexpected response".into())); + } + let trig_resp = resp.get_triggers(); { let mut pub_fds = subscriber.reliable_publisher_fds.lock().unwrap(); pub_fds.clear(); - for &idx in &trig_resp.reliable_pub_trigger_fd_indexes { - pub_fds.push(fds[idx as usize]); + for i in 0..trig_resp.reliable_pub_trigger_fd_indexes_size() { + pub_fds.push(fds[trig_resp.reliable_pub_trigger_fd_indexes(i) as usize]); } } subscriber.retirement_trigger_fds.clear(); - for &idx in &trig_resp.retirement_fd_indexes { - subscriber.retirement_trigger_fds.push(fds[idx as usize]); + for i in 0..trig_resp.retirement_fd_indexes_size() { + subscriber + .retirement_trigger_fds + .push(fds[trig_resp.retirement_fd_indexes(i) as usize]); } Ok(()) @@ -2262,19 +2267,18 @@ fn remove_publisher_request( channel_name: &str, publisher_id: i32, ) -> Result<()> { - let req = proto::Request { - request: Some(proto::request::Request::RemovePublisher( - proto::RemovePublisherRequest { - channel_name: channel_name.to_string(), - publisher_id, - }, - )), - }; + let mut req = phaser_request(); + { + let mut remove = req.mutable_remove_publisher(); + remove.set_channel_name(channel_name); + remove.set_publisher_id(publisher_id); + } client.socket.send_request(&req)?; let (resp, _fds) = client.socket.receive_response()?; - if let Some(proto::response::Response::RemovePublisher(r)) = resp.response { - if !r.error.is_empty() { - return Err(SubspaceError::ServerError(r.error)); + if resp.response_case() == RESP_REMOVE_PUBLISHER { + let removed = resp.remove_publisher(); + if !removed.error().is_empty() { + return Err(SubspaceError::ServerError(removed.error())); } } Ok(()) @@ -2286,20 +2290,19 @@ fn remove_subscriber_request( subscriber_id: i32, opts: &SubscriberOptions, ) -> Result<()> { - let req = proto::Request { - request: Some(proto::request::Request::RemoveSubscriber( - proto::RemoveSubscriberRequest { - channel_name: channel_name.to_string(), - subscriber_id, - telemetry: opts.telemetry, - }, - )), - }; + let mut req = phaser_request(); + { + let mut remove = req.mutable_remove_subscriber(); + remove.set_channel_name(channel_name); + remove.set_subscriber_id(subscriber_id); + remove.set_telemetry(opts.telemetry); + } client.socket.send_request(&req)?; let (resp, _fds) = client.socket.receive_response()?; - if let Some(proto::response::Response::RemoveSubscriber(r)) = resp.response { - if !r.error.is_empty() { - return Err(SubspaceError::ServerError(r.error)); + if resp.response_case() == RESP_REMOVE_SUBSCRIBER { + let removed = resp.remove_subscriber(); + if !removed.error().is_empty() { + return Err(SubspaceError::ServerError(removed.error())); } } Ok(()) diff --git a/rust_client/src/options.rs b/rust_client/src/options.rs index c477c84a..d90a7aff 100644 --- a/rust_client/src/options.rs +++ b/rust_client/src/options.rs @@ -24,6 +24,8 @@ pub struct PublisherOptions { pub bridge: bool, pub for_tunnel: bool, pub fixed_size: bool, + /// See `set_server_defined`. + pub server_defined: bool, /// See `set_max_slot_size`. 0 means unlimited. pub max_slot_size: i64, pub channel_type: String, @@ -52,6 +54,7 @@ impl Default for PublisherOptions { bridge: false, for_tunnel: false, fixed_size: false, + server_defined: false, max_slot_size: 0, channel_type: String::new(), activate: false, @@ -61,7 +64,8 @@ impl Default for PublisherOptions { max_outstanding_slot_leases: 1, notify_retirement_on_forced_reuse: true, checksum: false, - checksum_size: 4, + // 0 means 4 bytes. + checksum_size: 0, metadata_size: 0, use_split_buffers: false, split_buffers_over_bridge: false, @@ -112,6 +116,16 @@ impl PublisherOptions { self } + /// The channel is in the server's static channel config, which defines + /// its layout. Publishers on static channels must set this and leave the + /// slot size, number of slots, fixed size, checksum size, metadata size, + /// subscriber queue arena size and split buffers unset. The publisher + /// takes them from the server. + pub fn set_server_defined(mut self, v: bool) -> Self { + self.server_defined = v; + self + } + /// Upper bound on how large the channel's slots may become. 0 (the /// default) means no limit. When set, the initial slot size must not /// exceed it, asking `get_message_buffer` for a larger buffer fails diff --git a/rust_client/src/socket.rs b/rust_client/src/socket.rs index 28ebe8e3..e2b84674 100644 --- a/rust_client/src/socket.rs +++ b/rust_client/src/socket.rs @@ -4,12 +4,10 @@ // See LICENSE file for licensing information. use crate::error::{Result, SubspaceError}; -use crate::proto; use nix::sys::socket::{ connect, recvmsg, sendmsg, socket, AddressFamily, ControlMessage, ControlMessageOwned, MsgFlags, SockFlag, SockType, UnixAddr, }; -use prost::Message; use std::io::{IoSlice, IoSliceMut}; use std::os::fd::AsRawFd; use std::os::unix::io::RawFd; @@ -55,21 +53,21 @@ impl SocketConnection { self.fd } - pub fn send_request(&self, req: &proto::Request) -> Result<()> { - let msg_len = req.encoded_len(); - let mut buf = vec![0u8; 4 + msg_len]; + pub fn send_request(&self, req: &subspace_phaser_c::Request) -> Result<()> { + let payload = req.native_payload(); + let mut buf = vec![0u8; 4 + payload.len()]; // Length prefix in network byte order (big-endian). - let len_be = (msg_len as u32).to_be_bytes(); + let len_be = (payload.len() as u32).to_be_bytes(); buf[..4].copy_from_slice(&len_be); - req.encode(&mut &mut buf[4..])?; + buf[4..].copy_from_slice(&payload); send_fully(self.fd, &buf)?; Ok(()) } - pub fn receive_response(&self) -> Result<(proto::Response, Vec)> { - // 1. Read length-prefixed protobuf response. + pub fn receive_response(&self) -> Result<(subspace_phaser_c::Response<'static>, Vec)> { + // 1. Read the length-prefixed native Phaser response. let mut len_buf = [0u8; 4]; recv_fully(self.fd, &mut len_buf)?; let length = u32::from_be_bytes(len_buf) as usize; @@ -77,7 +75,12 @@ impl SocketConnection { let mut data = vec![0u8; length]; recv_fully(self.fd, &mut data)?; - let response = proto::Response::decode(&data[..])?; + let mut response = subspace_phaser_c::Response::new(length.max(64)); + if !response.parse_native_payload(&data) { + return Err(SubspaceError::Internal( + "Failed to parse native Phaser response".into(), + )); + } // 2. Receive file descriptors via SCM_RIGHTS. let fds = self.receive_fds()?; diff --git a/scripts/build-arm32-colima.sh b/scripts/build-arm32-colima.sh index b08cfc13..5591f1f4 100755 --- a/scripts/build-arm32-colima.sh +++ b/scripts/build-arm32-colima.sh @@ -3,8 +3,8 @@ # # Colima only hosts aarch64 and x86_64 VMs, and Bazel does not ship a 32-bit # ARM binary, so this uses the aarch64 Colima VM to run an Ubuntu container -# that cross-compiles with CMake. A host protoc is built first so it matches -# the protobuf version fetched for the target. +# that cross-compiles with CMake. A host protoc and protoc-gen-phaser are +# built first so they match the protobuf and phaser fetched for the target. # # Usage, from the repo root: # scripts/build-arm32-colima.sh @@ -44,16 +44,17 @@ docker run --rm \ # pointing at protoc-. Follow that symlink rather than requiring # a regular file of exactly that name. protoc=build/host-protoc/_deps/protobuf-build/protoc - if [[ ! -e \"\$protoc\" ]]; then + phaser=build/host-protoc/_deps/phaser-build/protoc-gen-phaser + if [[ ! -e \"\$protoc\" || ! -e \"\$phaser\" ]]; then cmake -S . -B build/host-protoc \ -G Ninja \ -DCMAKE_BUILD_TYPE=Release \ -DSUBSPACE_ASIO_RPC=OFF \ -DSUBSPACE_CO20_RPC=OFF - cmake --build build/host-protoc --target protoc --parallel + cmake --build build/host-protoc --target protoc protoc-gen-phaser --parallel fi - if [[ ! -e \"\$protoc\" ]]; then - echo 'host protoc was not produced' >&2 + if [[ ! -e \"\$protoc\" || ! -e \"\$phaser\" ]]; then + echo 'host protoc or protoc-gen-phaser was not produced' >&2 exit 1 fi echo \"Using host protoc: \$protoc\" @@ -63,6 +64,7 @@ docker run --rm \ -DCMAKE_TOOLCHAIN_FILE=/src/cmake/toolchains/linux-armhf.cmake \ -DCMAKE_BUILD_TYPE=Release \ -DPROTOC_EXECUTABLE=/src/\$protoc \ + -DPHASER_PLUGIN_EXECUTABLE=/src/\$phaser \ -DSUBSPACE_ASIO_RPC=OFF cmake --build build/armhf --parallel readelf -h build/armhf/server/subspace_server diff --git a/server/Android.bp b/server/Android.bp index 7ed7dba5..14de647b 100644 --- a/server/Android.bp +++ b/server/Android.bp @@ -18,6 +18,7 @@ cc_library_static { "client_handler.cc", "server_channel.cc", "shadow_replicator.cc", + "static_config.cc", "tunnel.cc", "tunnel_config.cc", "tunnel_protocol.cc", diff --git a/server/BUILD.bazel b/server/BUILD.bazel index e923f41c..0537133f 100644 --- a/server/BUILD.bazel +++ b/server/BUILD.bazel @@ -17,6 +17,7 @@ cc_library( "client_handler.cc", "server_channel.cc", "shadow_replicator.cc", + "static_config.cc", "tunnel.cc", ], hdrs = [ @@ -25,19 +26,25 @@ cc_library( "server_channel.h", "plugin.h", "shadow_replicator.h", + "config_format.h", + "static_config.h", "tunnel.h", ], deps = [ ":tunnel_wire", + "//common:server_wire", "//common:subspace_common", "//common/async:async", "//client:subspace_client", + "//proto:subspace_cc_proto", "//proto:tunnel_cc_proto", "@abseil-cpp//absl/container:flat_hash_map", "@abseil-cpp//absl/container:flat_hash_set", "@abseil-cpp//absl/status", "@abseil-cpp//absl/status:statusor", + "@abseil-cpp//absl/strings", "@abseil-cpp//absl/strings:str_format", + "@protobuf//:protobuf", "@abseil-cpp//absl/flags:flag", "@abseil-cpp//absl/flags:parse", "@coroutines//co:co", @@ -51,6 +58,7 @@ cc_library( "tunnel_protocol.cc", ], hdrs = [ + "config_format.h", "tunnel_config.h", "tunnel_protocol.h", ], @@ -188,6 +196,23 @@ cc_binary( }), ) +cc_test( + name = "static_config_test", + size = "small", + srcs = ["static_config_test.cc"], + deps = [ + ":server", + "//client:subspace_client", + "//client:test_fixture", + "//common:server_wire", + "@abseil-cpp//absl/status", + "@abseil-cpp//absl/status:status_matchers", + "@abseil-cpp//absl/status:statusor", + "@googletest//:gtest", + "@coroutines//:co", + ], +) + cc_test( name = "mtls_test", size = "medium", @@ -233,6 +258,7 @@ cc_test( ":server", "//client:subspace_client", "//client:test_fixture", + "//common:server_wire", "@abseil-cpp//absl/status", "@abseil-cpp//absl/status:status_matchers", "@googletest//:gtest", diff --git a/server/CMakeLists.txt b/server/CMakeLists.txt index 38858b98..39dc103a 100644 --- a/server/CMakeLists.txt +++ b/server/CMakeLists.txt @@ -7,6 +7,9 @@ add_library(libserver STATIC server_channel.h shadow_replicator.cc shadow_replicator.h + config_format.h + static_config.cc + static_config.h server.cc server.h server_bridge.cc diff --git a/server/client_handler.cc b/server/client_handler.cc index 63811f60..cb934590 100644 --- a/server/client_handler.cc +++ b/server/client_handler.cc @@ -6,13 +6,15 @@ #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" #include "client_handler.h" +#include "common/server_wire.h" #include "server/server.h" +#include #include namespace subspace { namespace { -ClientBufferAllocatorKind FromProtoAllocator(ClientBufferAllocator allocator) { +ClientBufferAllocatorKind FromProtoAllocator(int allocator) { switch (allocator) { case CLIENT_BUFFER_ALLOCATOR_ANDROID_MEMFD: return ClientBufferAllocatorKind::kAndroidMemfd; @@ -45,7 +47,7 @@ ClientBufferAllocator ToProtoAllocator(ClientBufferAllocatorKind allocator) { } ClientBufferHandleMetadata -FromProto(const ClientBufferHandleMetadataProto &proto) { +FromProto(const subspace::phaser::ClientBufferHandleMetadataProto &proto) { ClientBufferHandleMetadata metadata; metadata.channel_name = proto.channel_name(); metadata.session_id = proto.session_id(); @@ -57,13 +59,13 @@ FromProto(const ClientBufferHandleMetadataProto &proto) { metadata.handle = static_cast(proto.handle()); metadata.shadow_file = proto.shadow_file(); metadata.object_name = proto.object_name(); - metadata.allocator = FromProtoAllocator(proto.allocator()); + metadata.allocator = FromProtoAllocator(static_cast(proto.allocator())); metadata.map_offset = proto.map_offset(); return metadata; } void ToProto(const ClientBufferHandleMetadata &metadata, - ClientBufferHandleMetadataProto *proto) { + subspace::phaser::ClientBufferHandleMetadataProto *proto) { proto->set_channel_name(metadata.channel_name); proto->set_session_id(metadata.session_id); proto->set_buffer_index(metadata.buffer_index); @@ -74,12 +76,14 @@ void ToProto(const ClientBufferHandleMetadata &metadata, proto->set_handle(static_cast(metadata.handle)); proto->set_shadow_file(metadata.shadow_file); proto->set_object_name(metadata.object_name); - proto->set_allocator(ToProtoAllocator(metadata.allocator)); + proto->set_allocator(static_cast( + ToProtoAllocator(metadata.allocator))); proto->set_map_offset(metadata.map_offset); } SplitBufferOptions -FromPublisherSplitBufferRequest(const CreatePublisherRequest &req) { +FromPublisherSplitBufferRequest( + const subspace::phaser::CreatePublisherRequest &req) { return {.use_split_buffers = req.use_split_buffers(), .split_buffers_over_bridge = req.split_buffers_over_bridge()}; } @@ -93,29 +97,28 @@ void ClientHandler::Run(async::Context ctx) { // bytes of the buffer are used by SendMessage and ReceiveMessage // for the length of the data. for (;;) { - subspace::Request request; - - { - absl::StatusOr> receive_buffer = - socket_.ReceiveVariableLengthMessage(ctx); - if (!receive_buffer.ok()) { - return; - } - if (receive_buffer->empty()) { - // Connection closed. - return; - } - if (!request.ParseFromArray(receive_buffer->data(), - int(receive_buffer->size()))) { - server_->logger_.Log(toolbelt::LogLevel::kError, - "Failed to parse request\n"); - return; - } + absl::StatusOr> receive_buffer = + socket_.ReceiveVariableLengthMessage(ctx); + if (!receive_buffer.ok()) { + return; + } + if (receive_buffer->empty()) { + // Connection closed. + return; + } + subspace::phaser::Request request; + if (absl::Status status = ServerWire::Decode( + receive_buffer->data(), receive_buffer->size(), request); + !status.ok()) { + server_->logger_.Log(toolbelt::LogLevel::kError, + "Failed to parse request\n"); + return; } std::vector fds; - subspace::Response response; - if (request.request_case() == subspace::Request::kRegisterClientBuffer) { + subspace::phaser::Response response; + if (request.request_case() == + subspace::phaser::Request::kRegisterClientBufferFieldNumber) { std::vector register_fds; if (request.register_client_buffer().has_fd()) { if (absl::Status s = socket_.ReceiveFds(register_fds, ctx); @@ -137,7 +140,7 @@ void ClientHandler::Run(async::Context ctx) { response.mutable_register_client_buffer(); } } else if (request.request_case() == - subspace::Request::kUnregisterClientBuffer) { + subspace::phaser::Request::kUnregisterClientBufferFieldNumber) { if (absl::Status s = HandleUnregisterClientBuffer(request.unregister_client_buffer()); !s.ok()) { @@ -153,17 +156,16 @@ void ClientHandler::Run(async::Context ctx) { } } - size_t msglen = response.ByteSizeLong(); - std::vector send_buffer(sizeof(int32_t) + msglen); - if (!response.SerializeToArray(send_buffer.data() + sizeof(int32_t), - msglen)) { + ServerWire wire; + absl::StatusOr msglen = wire.Serialize(response); + if (!msglen.ok()) { server_->logger_.Log(toolbelt::LogLevel::kError, - "Failed to serialize response\n"); + "Failed to encode response\n"); return; } absl::StatusOr n_sent = socket_.SendMessage( - send_buffer.data() + sizeof(int32_t), msglen, ctx); + wire.Payload(), *msglen, ctx); if (!n_sent.ok()) { return; } @@ -176,65 +178,65 @@ void ClientHandler::Run(async::Context ctx) { } absl::Status -ClientHandler::HandleMessage(const subspace::Request &req, - subspace::Response &resp, +ClientHandler::HandleMessage(const subspace::phaser::Request &req, + subspace::phaser::Response &resp, std::vector &fds) { switch (req.request_case()) { - case subspace::Request::kInit: + case subspace::phaser::Request::kInitFieldNumber: HandleInit(req.init(), resp.mutable_init(), fds); break; - case subspace::Request::kCreatePublisher: + case subspace::phaser::Request::kCreatePublisherFieldNumber: HandleCreatePublisher(req.create_publisher(), resp.mutable_create_publisher(), fds); break; - case subspace::Request::kCreateSubscriber: + case subspace::phaser::Request::kCreateSubscriberFieldNumber: HandleCreateSubscriber(req.create_subscriber(), resp.mutable_create_subscriber(), fds); break; - case subspace::Request::kGetTriggers: + case subspace::phaser::Request::kGetTriggersFieldNumber: HandleGetTriggers(req.get_triggers(), resp.mutable_get_triggers(), fds); break; - case subspace::Request::kRemovePublisher: + case subspace::phaser::Request::kRemovePublisherFieldNumber: HandleRemovePublisher(req.remove_publisher(), resp.mutable_remove_publisher(), fds); break; - case subspace::Request::kRemoveSubscriber: + case subspace::phaser::Request::kRemoveSubscriberFieldNumber: HandleRemoveSubscriber(req.remove_subscriber(), resp.mutable_remove_subscriber(), fds); break; - case subspace::Request::kGetChannelInfo: + case subspace::phaser::Request::kGetChannelInfoFieldNumber: HandleGetChannelInfo(req.get_channel_info(), resp.mutable_get_channel_info(), fds); break; - case subspace::Request::kGetChannelStats: + case subspace::phaser::Request::kGetChannelStatsFieldNumber: HandleGetChannelStats(req.get_channel_stats(), resp.mutable_get_channel_stats(), fds); break; - case subspace::Request::kGetClientBuffers: + case subspace::phaser::Request::kGetClientBuffersFieldNumber: HandleGetClientBuffers(req.get_client_buffers(), resp.mutable_get_client_buffers(), fds); break; - case subspace::Request::kRegisterClientBuffer: + case subspace::phaser::Request::kRegisterClientBufferFieldNumber: return HandleRegisterClientBuffer(req.register_client_buffer(), fds); - case subspace::Request::kUnregisterClientBuffer: + case subspace::phaser::Request::kUnregisterClientBufferFieldNumber: return HandleUnregisterClientBuffer(req.unregister_client_buffer()); - case subspace::Request::REQUEST_NOT_SET: + case 0: return absl::InternalError("Protocol error: unknown request"); } return absl::OkStatus(); } absl::Status ClientHandler::HandleRegisterClientBuffer( - const subspace::RegisterClientBufferRequest &req, + const subspace::phaser::RegisterClientBufferRequest &req, std::vector &fds) { ClientBufferHandleMetadata metadata = FromProto(req.metadata()); if (metadata.session_id != server_->GetSessionId()) { @@ -269,24 +271,12 @@ absl::Status ClientHandler::HandleRegisterClientBuffer( } fd = std::move(fds[size_t(req.fd_index())]); } - channel->RegisterClientBuffer(metadata, std::move(fd)); - server_->ForEachShadow([&](const std::unique_ptr &shadow) { - const auto matches = - channel->FindClientBuffers(metadata.session_id, metadata.buffer_index); - for (const RegisteredClientBuffer *buffer : matches) { - if (buffer->metadata.slot_id == metadata.slot_id && - buffer->metadata.is_prefix == metadata.is_prefix) { - shadow->SendRegisterClientBuffer(buffer->metadata, buffer->fd); - return; - } - } - shadow->SendRegisterClientBuffer(metadata); - }); + server_->RegisterClientBuffer(channel, std::move(metadata), std::move(fd)); return absl::OkStatus(); } absl::Status ClientHandler::HandleUnregisterClientBuffer( - const subspace::UnregisterClientBufferRequest &req) { + const subspace::phaser::UnregisterClientBufferRequest &req) { if (req.session_id() != server_->GetSessionId()) { return absl::OkStatus(); } @@ -305,15 +295,16 @@ absl::Status ClientHandler::HandleUnregisterClientBuffer( } channel->UnregisterClientBuffer(req.session_id(), req.buffer_index()); server_->ForEachShadow([&](const std::unique_ptr &shadow) { - shadow->SendUnregisterClientBuffer(req.channel_name(), req.session_id(), + shadow->SendUnregisterClientBuffer(std::string(req.channel_name()), + req.session_id(), req.buffer_index()); }); return absl::OkStatus(); } void ClientHandler::HandleGetClientBuffers( - const subspace::GetClientBuffersRequest &req, - subspace::GetClientBuffersResponse *response, + const subspace::phaser::GetClientBuffersRequest &req, + subspace::phaser::GetClientBuffersResponse *response, std::vector &fds) { ServerChannel *channel = server_->FindChannel(req.channel_name()); if (channel == nullptr) { @@ -326,7 +317,12 @@ void ClientHandler::HandleGetClientBuffers( } for (const RegisteredClientBuffer *buffer : channel->FindClientBuffers(req.session_id(), req.buffer_index())) { - ToProto(buffer->metadata, response->add_metadata()); + if (req.filter_slot() && (buffer->metadata.is_prefix != req.is_prefix() || + buffer->metadata.slot_id != req.slot_id())) { + continue; + } + auto metadata = response->add_metadata(); + ToProto(buffer->metadata, &metadata); if (buffer->fd.Valid()) { response->add_fd_indexes(static_cast(fds.size())); fds.push_back(buffer->fd); @@ -336,8 +332,8 @@ void ClientHandler::HandleGetClientBuffers( } } -void ClientHandler::HandleInit(const subspace::InitRequest &req, - subspace::InitResponse *response, +void ClientHandler::HandleInit(const subspace::phaser::InitRequest &req, + subspace::phaser::InitResponse *response, std::vector &fds) { std::vector mismatches; if (req.max_channels() != kMaxChannels) { @@ -365,15 +361,98 @@ void ClientHandler::HandleInit(const subspace::InitRequest &req, response->set_scb_fd_index(0); fds.push_back(server_->scb_fd_); client_name_ = req.client_name(); + asil_client_ = req.asil(); response->set_session_id(server_->GetSessionId()); response->set_user_id(getuid()); response->set_group_id(getgid()); } void ClientHandler::HandleCreatePublisher( - const subspace::CreatePublisherRequest &req, - subspace::CreatePublisherResponse *response, + const subspace::phaser::CreatePublisherRequest &request, + subspace::phaser::CreatePublisherResponse *response, std::vector &fds) { + // A static channel's layout comes from the config, so its publishers set + // server_defined instead and the request is completed from the channel. + const ServerChannel *existing = server_->FindChannel(request.channel_name()); + const bool is_static = existing != nullptr && existing->IsStatic(); + if (is_static && !request.server_defined()) { + response->set_error(absl::StrFormat( + "Publishers on static channel %s must set server_defined", + request.channel_name())); + return; + } + if (!is_static && request.server_defined()) { + response->set_error(absl::StrFormat( + "Channel %s isn't in the static channel config, so its publishers " + "can't set server_defined", + request.channel_name())); + return; + } + // Configured channels are shared by both client types, and both must set + // server_defined, which the checks above enforce. A channel that isn't + // configured can be created by a standard publisher that specifies its + // layout. An ASIL publisher cannot create or join one. + if (server_->HasStaticChannelConfig() && !is_static && asil_client_) { + response->set_error(absl::StrFormat( + "ASIL publishers can only use channels in the static channel config; " + "%s isn't configured", + request.channel_name())); + return; + } + subspace::phaser::CreatePublisherRequest server_defined_req; + if (is_static) { + std::vector layout_fields; + if (request.num_slots() != 0) { + layout_fields.push_back("num_slots"); + } + if (request.slot_size() != 0) { + layout_fields.push_back("slot_size"); + } + if (request.is_fixed_size()) { + layout_fields.push_back("fixed_size"); + } + if (request.checksum_size() != 0) { + layout_fields.push_back("checksum_size"); + } + if (request.metadata_size() != 0) { + layout_fields.push_back("metadata_size"); + } + if (request.subscriber_queue_arena_size() != 0) { + layout_fields.push_back("subscriber_queue_arena_size"); + } + if (request.use_split_buffers()) { + layout_fields.push_back("use_split_buffers"); + } + if (!layout_fields.empty()) { + response->set_error(absl::StrFormat( + "Static channel %s has a layout defined by the server; its " + "publishers can't set %s", + request.channel_name(), absl::StrJoin(layout_fields, ", "))); + return; + } + const ServerChannel *layout_channel = + existing->IsVirtual() + ? static_cast(existing)->GetMux() + : existing; + if (absl::Status status = server_defined_req.CloneFrom(request); + !status.ok() || server_defined_req.AllocationFailed()) { + response->set_error("Failed to copy the static publisher request"); + return; + } + server_defined_req.set_num_slots(existing->NumSlots()); + server_defined_req.set_slot_size(existing->SlotSize()); + server_defined_req.set_is_fixed_size(true); + server_defined_req.set_checksum_size(existing->ChecksumSize()); + server_defined_req.set_metadata_size(existing->MetadataSize()); + server_defined_req.set_subscriber_queue_arena_size( + existing->SubscriberQueueArenaSize()); + server_defined_req.set_use_split_buffers( + layout_channel->HasSplitBufferOptions() && + layout_channel->GetSplitBufferOptions().use_split_buffers); + } + const subspace::phaser::CreatePublisherRequest &req = + is_static ? server_defined_req : request; + if (req.num_slots() <= 0 || req.slot_size() <= 0) { response->set_error("num_slots and slot_size must be greater than 0"); return; @@ -469,14 +548,15 @@ void ClientHandler::HandleCreatePublisher( server_->logger_.Log(toolbelt::LogLevel::kDebug, "Publisher %s is creating new channel %s with size " "%lld/%d and type length %zu (total of %zu channels)", - client_name_.c_str(), req.channel_name().c_str(), + client_name_.c_str(), std::string(req.channel_name()).c_str(), static_cast(req.slot_size()), req.num_slots(), req.type().size(), server_->GetNumChannels()); absl::StatusOr ch = server_->CreateChannel( - req.channel_name(), req.slot_size(), req.num_slots(), - req.subscriber_queue_arena_size(), req.mux(), req.vchan_id(), - req.type(), /*hidden=*/false, /*telemetry_target=*/{}, cs, ms); + std::string(req.channel_name()), req.slot_size(), req.num_slots(), + req.subscriber_queue_arena_size(), std::string(req.mux()), + req.vchan_id(), std::string(req.type()), /*hidden=*/false, + /*telemetry_target=*/{}, cs, ms); if (!ch.ok()) { response->set_error(ch.status().ToString()); return; @@ -491,7 +571,7 @@ void ClientHandler::HandleCreatePublisher( toolbelt::LogLevel::kDebug, "Publisher %s is remapping placeholder channel %s with size %lld/%d " "and type length %zu (total of %zu channels)", - client_name_.c_str(), req.channel_name().c_str(), + client_name_.c_str(), std::string(req.channel_name()).c_str(), static_cast(req.slot_size()), req.num_slots(), req.type().size(), server_->GetNumChannels()); // Establish the layout before allocating. Allocation is what makes the @@ -579,7 +659,7 @@ void ClientHandler::HandleCreatePublisher( return; } if (channel->Type().empty()) { - channel->SetType(req.type()); + channel->SetType(std::string(req.type())); } int num_pubs, num_subs, num_bridge_pubs, num_bridge_subs; @@ -603,7 +683,9 @@ void ClientHandler::HandleCreatePublisher( } // Check consistency of publisher parameters. if (num_pubs > 0) { - if (req.is_fixed_size() != channel->IsFixedSize()) { + const ServerChannel::SharedPublisherTraits traits = + channel->GetSharedPublisherTraits(); + if (req.is_fixed_size() != traits.fixed_size) { response->set_error( absl::StrFormat("Inconsistent publisher parameters for channel %s: " "all publishers must be either fixed size or not", @@ -625,7 +707,7 @@ void ClientHandler::HandleCreatePublisher( } if (slot_size_changed) { if (slot_size_changed) { - if (channel->IsFixedSize()) { + if (traits.fixed_size) { // Fixed size channels cannot change size. response->set_error(absl::StrFormat( "Failed to add publisher to fixed size channel %s with different " @@ -644,7 +726,7 @@ void ClientHandler::HandleCreatePublisher( // Local subscribers don't count here: they make the channel local // without constraining publishers. - if (channel->HasLocalPublisher() != req.is_local()) { + if (traits.local != req.is_local()) { response->set_error( absl::StrFormat("Inconsistent publisher parameters for channel %s: " "all publishers must be either local or not", @@ -712,7 +794,7 @@ void ClientHandler::HandleCreatePublisher( server_->logger_.Log(toolbelt::LogLevel::kDebug, "Client %s reclaiming publisher %d on channel %s", client_name_.c_str(), req.publisher_id(), - req.channel_name().c_str()); + std::string(req.channel_name()).c_str()); } } @@ -732,7 +814,7 @@ void ClientHandler::HandleCreatePublisher( } server_->logger_.Log(toolbelt::LogLevel::kDebug, "Client %s creating publisher on channel %s: VM: %s", - client_name_.c_str(), req.channel_name().c_str(), + client_name_.c_str(), std::string(req.channel_name()).c_str(), GetTotalVM().c_str()); // Create the publisher. absl::StatusOr publisher = channel->AddPublisher( @@ -758,7 +840,7 @@ void ClientHandler::HandleCreatePublisher( server_->SendChannelDirectory(); if (!req.is_bridge() && req.is_local()) { - server_->SendAdvertise(req.channel_name(), req.is_reliable()); + server_->SendAdvertise(std::string(req.channel_name()), req.is_reliable()); } if (req.notify_retirement()) { @@ -790,6 +872,13 @@ void ClientHandler::HandleCreatePublisher( response->set_subscriber_queue_arena_size( channel->SubscriberQueueArenaSize()); response->set_num_slots(channel->NumSlots()); + response->set_slot_size(channel->SlotSize()); + response->set_checksum_size(channel->ChecksumSize()); + response->set_metadata_size(channel->MetadataSize()); + response->set_use_split_buffers( + split_channel->HasSplitBufferOptions() && + split_channel->GetSplitBufferOptions().use_split_buffers); + response->set_is_fixed_size(req.is_fixed_size()); const SharedMemoryFds &channel_fds = channel->GetFds(); response->set_ccb_fd_index(0); @@ -846,8 +935,8 @@ void ClientHandler::HandleCreatePublisher( } void ClientHandler::HandleCreateSubscriber( - const subspace::CreateSubscriberRequest &req, - subspace::CreateSubscriberResponse *response, + const subspace::phaser::CreateSubscriberRequest &req, + subspace::phaser::CreateSubscriberResponse *response, std::vector &fds) { if (req.subscriber_queue_size() < 0) { response->set_error("subscriber_queue_size must be >= 0"); @@ -878,14 +967,14 @@ void ClientHandler::HandleCreateSubscriber( return; } absl::StatusOr telemetry_channel = - server_->FindOrCreateTelemetryChannel(req.channel_name()); + server_->FindOrCreateTelemetryChannel(std::string(req.channel_name())); if (!telemetry_channel.ok()) { response->set_error(telemetry_channel.status().ToString()); return; } channel = *telemetry_channel; } else { - channel = server_->FindTelemetryChannel(req.channel_name()); + channel = server_->FindTelemetryChannel(std::string(req.channel_name())); if (channel == nullptr) { response->set_error( absl::StrFormat("No telemetry channel for %s", req.channel_name())); @@ -900,15 +989,18 @@ void ClientHandler::HandleCreateSubscriber( return; } if (channel == nullptr) { - // No channel exists, map an empty channel. + // No channel exists, map an empty channel. Any subscriber may do this, + // including on a server with a static config and including an ASIL + // subscriber. A publisher still has to establish the layout. server_->logger_.Log( toolbelt::LogLevel::kDebug, "Subscriber %s is creating new placeholder channel %s " "with type length %zu (total of %zu channels)", - client_name_.c_str(), req.channel_name().c_str(), req.type().size(), + client_name_.c_str(), std::string(req.channel_name()).c_str(), req.type().size(), server_->GetNumChannels()); absl::StatusOr ch = server_->CreateChannel( - req.channel_name(), 0, 0, 0, req.mux(), req.vchan_id(), req.type()); + std::string(req.channel_name()), 0, 0, 0, std::string(req.mux()), + req.vchan_id(), std::string(req.type())); if (!ch.ok()) { response->set_error(ch.status().ToString()); return; @@ -926,7 +1018,7 @@ void ClientHandler::HandleCreateSubscriber( return; } if (channel->Type().empty()) { - channel->SetType(req.type()); + channel->SetType(std::string(req.type())); } } } @@ -1011,7 +1103,7 @@ void ClientHandler::HandleCreateSubscriber( server_->logger_.Log(toolbelt::LogLevel::kDebug, "Client %s reclaiming subscriber %d on channel %s", client_name_.c_str(), req.subscriber_id(), - req.channel_name().c_str()); + std::string(req.channel_name()).c_str()); } } else { if (!req.is_reliable()) { @@ -1028,7 +1120,7 @@ void ClientHandler::HandleCreateSubscriber( // Create the subscriber. server_->logger_.Log(toolbelt::LogLevel::kDebug, "Client %s creating subscriber on channel %s: VM: %s", - client_name_.c_str(), req.channel_name().c_str(), + client_name_.c_str(), std::string(req.channel_name()).c_str(), GetTotalVM().c_str()); absl::StatusOr subscriber = channel->AddSubscriber( this, req.is_reliable(), req.is_bridge(), req.for_tunnel(), @@ -1132,13 +1224,13 @@ void ClientHandler::HandleCreateSubscriber( if (!req.is_bridge() && !req.telemetry()) { // Send Query to subscribe to public channels on other servers. - server_->SendQuery(req.channel_name()); + server_->SendQuery(std::string(req.channel_name())); } } void ClientHandler::HandleGetTriggers( - const subspace::GetTriggersRequest &req, - subspace::GetTriggersResponse *response, + const subspace::phaser::GetTriggersRequest &req, + subspace::phaser::GetTriggersResponse *response, std::vector &fds) { ServerChannel *channel = server_->FindChannel(req.channel_name()); if (channel == nullptr) { @@ -1186,8 +1278,8 @@ void ClientHandler::HandleGetTriggers( } void ClientHandler::HandleRemovePublisher( - const subspace::RemovePublisherRequest &req, - subspace::RemovePublisherResponse *response, + const subspace::phaser::RemovePublisherRequest &req, + subspace::phaser::RemovePublisherResponse *response, [[maybe_unused]] std::vector &fds) { ServerChannel *channel = server_->FindChannel(req.channel_name()); if (channel == nullptr) { @@ -1199,11 +1291,12 @@ void ClientHandler::HandleRemovePublisher( } void ClientHandler::HandleRemoveSubscriber( - const subspace::RemoveSubscriberRequest &req, - subspace::RemoveSubscriberResponse *response, + const subspace::phaser::RemoveSubscriberRequest &req, + subspace::phaser::RemoveSubscriberResponse *response, [[maybe_unused]] std::vector &fds) { ServerChannel *channel = - req.telemetry() ? server_->FindTelemetryChannel(req.channel_name()) + req.telemetry() + ? server_->FindTelemetryChannel(std::string(req.channel_name())) : server_->FindChannel(req.channel_name()); if (channel == nullptr) { response->set_error( @@ -1214,15 +1307,14 @@ void ClientHandler::HandleRemoveSubscriber( } void ClientHandler::HandleGetChannelInfo( - const subspace::GetChannelInfoRequest &req, - subspace::GetChannelInfoResponse *response, + const subspace::phaser::GetChannelInfoRequest &req, + subspace::phaser::GetChannelInfoResponse *response, [[maybe_unused]] std::vector &fds) { if (req.channel_name().empty()) { // All channels. - auto result = response->mutable_channels(); - - server_->ForeachChannel([result](ServerChannel *channel) { - channel->GetChannelInfo(result->Add()); + server_->ForeachChannel([response](ServerChannel *channel) { + auto info = response->add_channels(); + channel->GetChannelInfo(&info); }); return; } @@ -1232,20 +1324,19 @@ void ClientHandler::HandleGetChannelInfo( absl::StrFormat("No such channel %s", req.channel_name())); return; } - auto info = response->mutable_channels(); - channel->GetChannelInfo(info->Add()); + auto info = response->add_channels(); + channel->GetChannelInfo(&info); } void ClientHandler::HandleGetChannelStats( - const subspace::GetChannelStatsRequest &req, - subspace::GetChannelStatsResponse *response, + const subspace::phaser::GetChannelStatsRequest &req, + subspace::phaser::GetChannelStatsResponse *response, [[maybe_unused]] std::vector &fds) { if (req.channel_name().empty()) { // All channels. - auto result = response->mutable_channels(); - - server_->ForeachChannel([result](ServerChannel *channel) { - channel->GetChannelStats(result->Add()); + server_->ForeachChannel([response](ServerChannel *channel) { + auto stats = response->add_channels(); + channel->GetChannelStats(&stats); }); return; } @@ -1255,8 +1346,8 @@ void ClientHandler::HandleGetChannelStats( absl::StrFormat("No such channel %s", req.channel_name())); return; } - auto info = response->mutable_channels(); - channel->GetChannelStats(info->Add()); + auto stats = response->add_channels(); + channel->GetChannelStats(&stats); } std::string ClientHandler::GetTotalVM() { diff --git a/server/client_handler.h b/server/client_handler.h index 778baaba..015a51a1 100644 --- a/server/client_handler.h +++ b/server/client_handler.h @@ -11,6 +11,7 @@ #include "common/channel.h" #include "co/coroutine.h" #include "proto/subspace.pb.h" +#include "proto/subspace.phaser.h" #include "toolbelt/sockets.h" #include #include @@ -35,50 +36,53 @@ class ClientHandler { private: std::string GetTotalVM(); - absl::Status HandleMessage(const subspace::Request &req, - subspace::Response &resp, + absl::Status HandleMessage(const subspace::phaser::Request &req, + subspace::phaser::Response &resp, std::vector &fds); // These individual handler functions set any errors in the response // message instead of returning them to the caller. This allows the // connection to remain open to the client and the client will be // able to display or handle the error as appropriate. - void HandleInit(const subspace::InitRequest &req, - subspace::InitResponse *response, + void HandleInit(const subspace::phaser::InitRequest &req, + subspace::phaser::InitResponse *response, std::vector &fds); - void HandleCreatePublisher(const subspace::CreatePublisherRequest &req, - subspace::CreatePublisherResponse *response, + void HandleCreatePublisher(const subspace::phaser::CreatePublisherRequest &request, + subspace::phaser::CreatePublisherResponse *response, std::vector &fds); - void HandleCreateSubscriber(const subspace::CreateSubscriberRequest &req, - subspace::CreateSubscriberResponse *response, + void HandleCreateSubscriber(const subspace::phaser::CreateSubscriberRequest &req, + subspace::phaser::CreateSubscriberResponse *response, std::vector &fds); - void HandleGetTriggers(const subspace::GetTriggersRequest &req, - subspace::GetTriggersResponse *response, + void HandleGetTriggers(const subspace::phaser::GetTriggersRequest &req, + subspace::phaser::GetTriggersResponse *response, std::vector &fds); - void HandleRemovePublisher(const subspace::RemovePublisherRequest &req, - subspace::RemovePublisherResponse *response, + void HandleRemovePublisher(const subspace::phaser::RemovePublisherRequest &req, + subspace::phaser::RemovePublisherResponse *response, std::vector &fds); - void HandleRemoveSubscriber(const subspace::RemoveSubscriberRequest &req, - subspace::RemoveSubscriberResponse *response, + void HandleRemoveSubscriber(const subspace::phaser::RemoveSubscriberRequest &req, + subspace::phaser::RemoveSubscriberResponse *response, std::vector &fds); - void HandleGetChannelInfo(const subspace::GetChannelInfoRequest &req, - subspace::GetChannelInfoResponse *response, + void HandleGetChannelInfo(const subspace::phaser::GetChannelInfoRequest &req, + subspace::phaser::GetChannelInfoResponse *response, std::vector &fds); - void HandleGetChannelStats(const subspace::GetChannelStatsRequest &req, - subspace::GetChannelStatsResponse *response, + void HandleGetChannelStats(const subspace::phaser::GetChannelStatsRequest &req, + subspace::phaser::GetChannelStatsResponse *response, std::vector &fds); absl::Status - HandleRegisterClientBuffer(const subspace::RegisterClientBufferRequest &req, + HandleRegisterClientBuffer(const subspace::phaser::RegisterClientBufferRequest &req, std::vector &fds); absl::Status HandleUnregisterClientBuffer( - const subspace::UnregisterClientBufferRequest &req); - void HandleGetClientBuffers(const subspace::GetClientBuffersRequest &req, - subspace::GetClientBuffersResponse *response, + const subspace::phaser::UnregisterClientBufferRequest &req); + void HandleGetClientBuffers(const subspace::phaser::GetClientBuffersRequest &req, + subspace::phaser::GetClientBuffersResponse *response, std::vector &fds); Server *server_; async::UnixSocket socket_; std::string client_name_; + // Set from InitRequest.asil. With a static channel config, this connection's + // publishers can use only the configured channels. + bool asil_client_ = false; }; } // namespace subspace diff --git a/server/config_format.h b/server/config_format.h new file mode 100644 index 00000000..43ad19f1 --- /dev/null +++ b/server/config_format.h @@ -0,0 +1,74 @@ +// Copyright 2026 David Allison +// Copyright 2026 General Motors +// All Rights Reserved +// See LICENSE file for licensing information. + +#pragma once + +#include "google/protobuf/descriptor.h" +#include "google/protobuf/message.h" +#include +#include + +namespace subspace { + +// Reports whether the message, or any message inside it, has a field this +// build doesn't know. The text format rejects those, so the wire format does +// too, rather than dropping them. +inline bool HasUnknownFields(const google::protobuf::Message &message) { + const google::protobuf::Reflection *reflection = message.GetReflection(); + if (!reflection->GetUnknownFields(message).empty()) { + return true; + } + const google::protobuf::Descriptor *descriptor = message.GetDescriptor(); + for (int i = 0; i < descriptor->field_count(); i++) { + const google::protobuf::FieldDescriptor *field = descriptor->field(i); + if (field->cpp_type() != + google::protobuf::FieldDescriptor::CPPTYPE_MESSAGE) { + continue; + } + if (field->is_repeated()) { + const int count = reflection->FieldSize(message, field); + for (int j = 0; j < count; j++) { + if (HasUnknownFields( + reflection->GetRepeatedMessage(message, field, j))) { + return true; + } + } + } else if (reflection->HasField(message, field) && + HasUnknownFields(reflection->GetMessage(message, field))) { + return true; + } + } + return false; +} + +// A configuration file is protobuf text unless its extension is .pb or +// .binpb, which is the wire format. The comparison ignores case. A name +// with any other extension, or none, is text. +inline bool ConfigFileIsText(std::string_view path) { + const size_t slash = path.find_last_of('/'); + const std::string_view base = + slash == std::string_view::npos ? path : path.substr(slash + 1); + const size_t dot = base.find_last_of('.'); + if (dot == std::string_view::npos || dot + 1 >= base.size()) { + return true; + } + const std::string_view ext = base.substr(dot + 1); + auto same = [](std::string_view a, std::string_view b) { + if (a.size() != b.size()) { + return false; + } + for (size_t i = 0; i < a.size(); i++) { + const unsigned char ca = static_cast(a[i]); + const unsigned char cb = static_cast(b[i]); + if (std::tolower(ca) != std::tolower(cb)) { + return false; + } + } + return true; + }; + return !same(ext, "pb") && !same(ext, "binpb"); +} + +} // namespace subspace diff --git a/server/main.cc b/server/main.cc index 66e2d904..d19c46af 100644 --- a/server/main.cc +++ b/server/main.cc @@ -1,5 +1,5 @@ // Copyright 2023-2026 David Allison -// Tunnel support is Copyright 2026 General Motors LLC +// Tunnel support is Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. @@ -7,6 +7,7 @@ #include "absl/flags/parse.h" #include "proto/tunnel_config.pb.h" #include "server.h" +#include "server/static_config.h" #include "server/tunnel_config.h" #include #include @@ -95,12 +96,21 @@ ABSL_FLAG(std::string, shadow_socket, "", "Primary shadow process Unix socket (empty = disabled)"); ABSL_FLAG(std::string, secondary_shadow_socket, "", "Secondary shadow process Unix socket (empty = disabled)"); +ABSL_FLAG(std::string, channel_config, "", + "StaticChannelConfig file. A name ending in .pb or .binpb is " + "protobuf wire format; any other name is protobuf text format. The " + "server creates those channels at startup and fixes their layout. " + "Standard " + "publishers can still create other channels, and any subscriber can " + "use them; ASIL publishers cannot (empty = every channel is created " + "on demand)"); ABSL_FLAG(bool, tunnel, false, "Run discovery and bridging compatible with the cruise tunnel " "alongside the native kind. Requires --tunnel_config."); ABSL_FLAG(std::string, tunnel_config, "", - "Tunnel configuration file in protobuf text format. See " - "docs/tunnel.md."); + "Tunnel configuration file. A name ending in .pb or .binpb is " + "protobuf wire format; any other name is protobuf text format. " + "See docs/tunnel.md."); ABSL_FLAG(std::string, mtls_cert, "", "PEM certificate for mutual TLS on bridge and tunnel connections. " "Requires --mtls_key, --mtls_ca, and a server built with mTLS."); @@ -287,6 +297,21 @@ int main(int argc, char **argv) { server->SetShadowSockets(absl::GetFlag(FLAGS_shadow_socket), absl::GetFlag(FLAGS_secondary_shadow_socket)); + if (const std::string &channel_config = absl::GetFlag(FLAGS_channel_config); + !channel_config.empty()) { + absl::StatusOr config = + subspace::ReadStaticChannelConfig(channel_config); + if (!config.ok()) { + fprintf(stderr, "%s\n", config.status().ToString().c_str()); + exit(1); + } + if (absl::Status status = server->SetStaticChannelConfig(*std::move(config)); + !status.ok()) { + fprintf(stderr, "%s\n", status.ToString().c_str()); + exit(1); + } + } + const std::string tunnel_config_path = absl::GetFlag(FLAGS_tunnel_config); if (absl::GetFlag(FLAGS_tunnel)) { if (tunnel_config_path.empty()) { diff --git a/server/plugin_bridge_test.cc b/server/plugin_bridge_test.cc index 1c7a423c..185d4a12 100644 --- a/server/plugin_bridge_test.cc +++ b/server/plugin_bridge_test.cc @@ -1,4 +1,4 @@ -// Copyright 2026 General Motors LLC +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/server/server.cc b/server/server.cc index 7922925f..d4b657ad 100644 --- a/server/server.cc +++ b/server/server.cc @@ -1,7 +1,7 @@ // Copyright 2023-2026 David Allison // All Rights Reserved // Shadow support is Copyright 2026 Cruise LLC -// Tunnel support is Copyright 2026 General Motors LLC +// Tunnel support is Copyright 2026 General Motors // See LICENSE file for licensing information. #include "server/server.h" @@ -623,6 +623,12 @@ absl::Status Server::Run(int num_asio_threads) { s.ToString().c_str())); } + // Before any client is handled, so no client sees a static channel missing + // or as a placeholder. + if (absl::Status s = CreateStaticChannels(); !s.ok()) { + return s; + } + char hostname[256] = "local"; if (!local_) { if (gethostname(hostname, sizeof(hostname)) == -1) { diff --git a/server/server.h b/server/server.h index 0e777bac..0a79c22f 100644 --- a/server/server.h +++ b/server/server.h @@ -1,5 +1,5 @@ // Copyright 2023-2026 David Allison -// Tunnel support is Copyright 2026 General Motors LLC +// Tunnel support is Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. @@ -7,6 +7,7 @@ #define _xSERVERSERVER_H #include "absl/container/flat_hash_map.h" +#include #include "absl/container/flat_hash_set.h" #include "absl/status/status.h" #include "absl/status/statusor.h" @@ -33,6 +34,7 @@ #include #include #include +#include #include namespace subspace { @@ -128,6 +130,18 @@ class Server { void SetShadowSocket(const std::string &socket_name); void SetShadowSockets(const std::string &primary, const std::string &secondary); + + // Call before Run(). Run() creates the configured channels before it + // accepts any clients. Publishers on those channels must set + // server_defined. A standard publisher can still create a channel that + // isn't configured by specifying its layout, and any subscriber can + // subscribe to one. An ASIL publisher cannot. Fails if the config isn't + // valid. + absl::Status SetStaticChannelConfig(StaticChannelConfig config); + bool HasStaticChannelConfig() const { return static_config_.has_value(); } + // The channels the server publishes itself, which a static channel config + // doesn't list. + static bool IsServerChannelName(const std::string &channel_name); void SimulateCrash() { simulate_crash_ = true; for (auto &[name, ch] : channels_) { @@ -153,6 +167,12 @@ class Server { uint64_t GetSessionId() const { return session_id_; } + // Records a buffer that a publisher, or the server for a static channel, + // has created, and replicates it to the shadows. + void RegisterClientBuffer(ServerChannel *channel, + ClientBufferHandleMetadata metadata, + toolbelt::FileDescriptor fd); + absl::StatusOr CreateBridgeNotificationPipe(); struct BridgePortRange { @@ -270,7 +290,7 @@ class Server { absl::Status RemapChannel(ServerChannel *channel, int64_t slot_size, int num_slots, uint64_t subscriber_queue_arena_size); - ServerChannel *FindChannel(const std::string &channel_name); + ServerChannel *FindChannel(std::string_view channel_name); void RemoveChannel(ServerChannel *channel); private: @@ -327,6 +347,16 @@ class Server { absl::Status RecoverFromShadow(RecoveredState &state); + // Creates the static config's channels, or checks that channels recovered + // from a shadow match it, and marks them static. + absl::Status CreateStaticChannels(); + + // Creates the buffers of a static channel or multiplexer, as its first + // publisher would, so that subscribers can map them before any publisher + // exists. + absl::Status CreateStaticBuffers(ServerChannel *channel, int64_t slot_size, + bool use_split_buffers); + // Public iteration excludes internal telemetry transport channels. void ForeachChannel(std::function func); bool IsPublicChannel(const ServerChannel *channel) const { @@ -417,7 +447,9 @@ class Server { bool split_buffers_over_bridge, toolbelt::InetAddress publisher, bool local_has_split_options, - bool local_use_split_buffers); + bool local_use_split_buffers, + bool local_is_static, std::string static_mux, + int static_vchan_id); void RetirementCoroutine( async::Context ctx, const std::string &channel_name, toolbelt::FileDescriptor &&retirement_fd, @@ -547,6 +579,7 @@ class Server { ChecksumCallback checksum_callback_; toolbelt::TriggerFd shutdown_trigger_fd_; std::string machine_name_; + std::optional static_config_; // Lifetime counters of each channel at the previous published Statistics // message, or at the creation of a virtual channel. Used on the client diff --git a/server/server_bridge.cc b/server/server_bridge.cc index 0d08e601..8fb7165f 100644 --- a/server/server_bridge.cc +++ b/server/server_bridge.cc @@ -1,7 +1,7 @@ // Copyright 2023-2026 David Allison // All Rights Reserved // Shadow support is Copyright 2026 Cruise LLC -// Tunnel support is Copyright 2026 General Motors LLC +// Tunnel support is Copyright 2026 General Motors // See LICENSE file for licensing information. #include "server/server.h" diff --git a/server/server_bridge_receiver.cc b/server/server_bridge_receiver.cc index b5cb7876..bd2163f0 100644 --- a/server/server_bridge_receiver.cc +++ b/server/server_bridge_receiver.cc @@ -1,7 +1,7 @@ // Copyright 2023-2026 David Allison // All Rights Reserved // Shadow support is Copyright 2026 Cruise LLC -// Tunnel support is Copyright 2026 General Motors LLC +// Tunnel support is Copyright 2026 General Motors // See LICENSE file for licensing information. #include "server/server.h" @@ -225,7 +225,10 @@ void Server::BridgeReceiverCoroutine(async::Context ctx, bool split_buffers_over_bridge, toolbelt::InetAddress publisher, bool local_has_split_options, - bool local_use_split_buffers) { + bool local_use_split_buffers, + bool local_is_static, + std::string static_mux, + int static_vchan_id) { // bridged_publishers_ and channels_ are owned by the client strand, but this // coroutine runs on the parallel io_context. Post the teardown bookkeeping // onto the strand (capturing everything by value, since the guard's members @@ -378,17 +381,29 @@ void Server::BridgeReceiverCoroutine(async::Context ctx, if (bridge_ms < 0) { bridge_ms = 0; } - absl::StatusOr pub = client.CreatePublisher( - channel_name, subscribed.slot_size(), subscribed.num_slots(), + PublisherOptions bridge_options = PublisherOptions() - .SetSubscriberQueueArenaSize( - subscribed.subscriber_queue_arena_size()) .SetReliable(subscribed.reliable()) .SetBridge(true) - .SetNotifyRetirement(subscribed.notify_retirement()) - .SetChecksumSize(bridge_cs) - .SetMetadataSize(bridge_ms) - .SetUseSplitBuffers(bridge_publisher_split_buffers)); + .SetNotifyRetirement(subscribed.notify_retirement()); + // A static channel keeps the layout from this server's config. Whether it + // is static was read on the client strand; this coroutine must not look the + // channel up. + if (local_is_static) { + bridge_options.SetServerDefined(true).SetUseSplitBuffers(false); + if (!static_mux.empty()) { + bridge_options.SetMux(static_mux).SetVchanId(static_vchan_id); + } + } else { + bridge_options.SetSlotSize(subscribed.slot_size()) + .SetNumSlots(subscribed.num_slots()) + .SetSubscriberQueueArenaSize(subscribed.subscriber_queue_arena_size()) + .SetChecksumSize(bridge_cs) + .SetMetadataSize(bridge_ms) + .SetUseSplitBuffers(bridge_publisher_split_buffers); + } + absl::StatusOr pub = + client.CreatePublisher(channel_name, bridge_options); if (!pub.ok()) { logger_.Log(toolbelt::LogLevel::kError, "Failed to create bridge publisher for %s: %s", diff --git a/server/server_bridge_transmitter.cc b/server/server_bridge_transmitter.cc index be3e9f03..f4fdafb6 100644 --- a/server/server_bridge_transmitter.cc +++ b/server/server_bridge_transmitter.cc @@ -1,7 +1,7 @@ // Copyright 2023-2026 David Allison // All Rights Reserved // Shadow support is Copyright 2026 Cruise LLC -// Tunnel support is Copyright 2026 General Motors LLC +// Tunnel support is Copyright 2026 General Motors // See LICENSE file for licensing information. #include "server/server.h" diff --git a/server/server_channel.cc b/server/server_channel.cc index 6edbb454..5ea5e420 100644 --- a/server/server_channel.cc +++ b/server/server_channel.cc @@ -8,6 +8,7 @@ #include "server/server.h" #include #include +#include #include #include #if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_MEMFD @@ -1268,7 +1269,7 @@ void ServerChannel::RemoveUser(Server *server, int user_id) { users_.erase(it); // The telemetry coroutine removes its hidden channel after its publisher is // fully destroyed. - if (IsEmpty() && !IsTelemetryChannel()) { + if (IsEmpty() && !IsTelemetryChannel() && !IsStatic()) { server->RemoveChannel(this); } server->SendChannelDirectory(); @@ -1550,7 +1551,8 @@ absl::Status ServerChannel::CapacityError(const CapacityInfo &info) const { return absl::InternalError(message); } -void ServerChannel::GetChannelInfo(subspace::ChannelInfoProto *info) { +template +void ServerChannel::FillChannelInfo(Info *info) { info->set_name(Name()); info->set_slot_size(SlotSize()); info->set_num_slots(NumSlots()); @@ -1574,27 +1576,47 @@ void ServerChannel::GetChannelInfo(subspace::ChannelInfoProto *info) { info->set_is_local(IsLocal()); if (IsVirtual()) { info->set_is_virtual(true); - VirtualChannel *vchan = static_cast(this); info->set_vchan_id(GetVirtualChannelId()); - info->set_mux(vchan->GetMux()->Name()); + info->set_mux(static_cast(this)->GetMux()->Name()); } for (const auto &[id, user] : users_) { if (user == nullptr || user->GetHandler() == nullptr) { continue; } - ChannelParticipantInfoProto *participant = info->add_participants(); - participant->set_id(id); - participant->set_pid(user->ProcessId()); - participant->set_program_name(user->GetHandler()->ClientName()); - participant->set_is_publisher(user->IsPublisher()); - participant->set_is_subscriber(user->IsSubscriber()); - participant->set_is_reliable(user->IsReliable()); - participant->set_is_bridge(user->IsBridge()); - participant->set_for_tunnel(user->ForTunnel()); + auto participant = info->add_participants(); + const int participant_id = id; + const User *participant_user = user.get(); + auto fill = [&](auto *out) { + out->set_id(participant_id); + out->set_pid(participant_user->ProcessId()); + out->set_program_name(participant_user->GetHandler()->ClientName()); + out->set_is_publisher(participant_user->IsPublisher()); + out->set_is_subscriber(participant_user->IsSubscriber()); + out->set_is_reliable(participant_user->IsReliable()); + out->set_is_bridge(participant_user->IsBridge()); + out->set_for_tunnel(participant_user->ForTunnel()); + }; + if constexpr (std::is_pointer_v) { + fill(participant); + } else { + fill(&participant); + } } } +template void ServerChannel::FillChannelInfo(subspace::ChannelInfoProto *); +template void +ServerChannel::FillChannelInfo(subspace::phaser::ChannelInfoProto *); + +void ServerChannel::GetChannelInfo(subspace::ChannelInfoProto *info) { + FillChannelInfo(info); +} + +void ServerChannel::GetChannelInfo(subspace::phaser::ChannelInfoProto *info) { + FillChannelInfo(info); +} + std::vector ServerChannel::GetResizeInfo() const { std::vector info; // Derive the resize information from the bcb contents. Since the server @@ -1620,7 +1642,8 @@ std::vector ServerChannel::GetResizeInfo() const { return info; } -void ServerChannel::GetChannelStats(subspace::ChannelStatsProto *stats) { +template +void ServerChannel::FillChannelStats(Stats *stats) { stats->set_channel_name(Name()); uint64_t total_bytes, total_messages; uint64_t max_message_size; @@ -1644,6 +1667,18 @@ void ServerChannel::GetChannelStats(subspace::ChannelStatsProto *stats) { stats->set_is_local(IsLocal()); } +template void ServerChannel::FillChannelStats(subspace::ChannelStatsProto *); +template void +ServerChannel::FillChannelStats(subspace::phaser::ChannelStatsProto *); + +void ServerChannel::GetChannelStats(subspace::ChannelStatsProto *stats) { + FillChannelStats(stats); +} + +void ServerChannel::GetChannelStats(subspace::phaser::ChannelStatsProto *stats) { + FillChannelStats(stats); +} + ChannelCounters &ServerChannel::RecordUpdate(bool is_pub, bool add, bool reliable) { SystemControlBlock *scb = GetScb(); @@ -1750,6 +1785,18 @@ void ChannelMultiplexer::CountUsers(int &num_pubs, int &num_subs, num_tunnel_subs += total_tunnel_subs; } +ServerChannel::SharedPublisherTraits +ChannelMultiplexer::GetSharedPublisherTraits() const { + SharedPublisherTraits traits = ServerChannel::GetSharedPublisherTraits(); + for (const VirtualChannel *vchan : virtual_channels_) { + const SharedPublisherTraits v = + vchan->ServerChannel::GetSharedPublisherTraits(); + traits.fixed_size |= v.fixed_size; + traits.local |= v.local; + } + return traits; +} + void ChannelMultiplexer::CountCapacityUsage( int &max_active_messages, int &max_outstanding_slot_leases) const { ServerChannel::CountCapacityUsage(max_active_messages, diff --git a/server/server_channel.h b/server/server_channel.h index 022a74fd..6b2e5694 100644 --- a/server/server_channel.h +++ b/server/server_channel.h @@ -12,6 +12,7 @@ #include "common/channel.h" #include "common/client_buffer.h" #include "proto/subspace.pb.h" +#include "proto/subspace.phaser.h" #include "toolbelt/bitset.h" #include "toolbelt/fd.h" #include "toolbelt/logging.h" @@ -238,6 +239,10 @@ class ServerChannel : public Channel { bool IsHidden() const { return hidden_; } bool IsTelemetryChannel() const { return !telemetry_target_.empty(); } const std::string &TelemetryTarget() const { return telemetry_target_; } + // A static channel comes from the server's static channel config. It + // keeps its layout and stays when it has no publishers or subscribers. + void SetStatic(bool v) { static_ = v; } + bool IsStatic() const { return static_; } absl::StatusOr AddPublisher(ClientHandler *handler, bool is_reliable, bool is_local, @@ -326,6 +331,16 @@ class ServerChannel : public Channel { int &max_outstanding_slot_leases) const; virtual void GetChannelInfo(subspace::ChannelInfoProto *info); virtual void GetChannelStats(subspace::ChannelStatsProto *stats); + void GetChannelInfo(subspace::phaser::ChannelInfoProto *info); + void GetChannelStats(subspace::phaser::ChannelStatsProto *stats); + + private: + template + void FillChannelInfo(Info *info); + template + void FillChannelStats(Stats *stats); + + public: void TriggerAllSubscribers(); std::vector GetResizeInfo() const; @@ -456,6 +471,16 @@ class ServerChannel : public Channel { bool IsReliable() const; bool IsFixedSize() const; + // Properties that every publisher sharing this channel's buffers must agree + // on. The virtual channels of a multiplexer all share its buffers. + struct SharedPublisherTraits { + bool fixed_size = false; + bool local = false; + }; + virtual SharedPublisherTraits GetSharedPublisherTraits() const { + return {IsFixedSize(), HasLocalPublisher()}; + } + bool HasSplitBufferOptions() const { return split_buffer_options_set_; } const SplitBufferOptions &GetSplitBufferOptions() const { return split_buffer_options_; @@ -541,6 +566,7 @@ class ServerChannel : public Channel { bool local_latched_ = false; bool skip_cleanup_ = false; bool hidden_ = false; + bool static_ = false; std::string telemetry_target_; int session_id_; mutable int64_t last_known_slot_size_ = 0; @@ -592,6 +618,7 @@ class ChannelMultiplexer : public ServerChannel { int &num_tunnel_subs) const override; void CountCapacityUsage(int &max_active_messages, int &max_outstanding_slot_leases) const override; + SharedPublisherTraits GetSharedPublisherTraits() const override; private: int next_vchan_id_ = 0; @@ -637,6 +664,9 @@ class VirtualChannel : public ServerChannel { mux_->CountUsers(num_pubs, num_subs, num_bridge_pubs, num_bridge_subs, num_tunnel_pubs, num_tunnel_subs); } + SharedPublisherTraits GetSharedPublisherTraits() const override { + return mux_->GetSharedPublisherTraits(); + } ChannelMultiplexer *GetMux() const { return mux_; } int GetVirtualChannelId() const override { return vchan_id_; } diff --git a/server/server_channels.cc b/server/server_channels.cc index 4f9f6f60..e0f573a0 100644 --- a/server/server_channels.cc +++ b/server/server_channels.cc @@ -1,7 +1,7 @@ // Copyright 2023-2026 David Allison // All Rights Reserved // Shadow support is Copyright 2026 Cruise LLC -// Tunnel support is Copyright 2026 General Motors LLC +// Tunnel support is Copyright 2026 General Motors // See LICENSE file for licensing information. #include "server/server.h" @@ -9,12 +9,21 @@ #include "client/client.h" #include "proto/subspace.pb.h" #include "server/client_handler.h" +#include "server/static_config.h" #include "server/tunnel.h" #include "toolbelt/clock.h" +#include #include namespace subspace { +namespace { + +constexpr char kChannelDirectoryChannel[] = "/subspace/ChannelDirectory"; +constexpr char kStatisticsChannel[] = "/subspace/Statistics"; + +} // namespace + void Server::ForeachChannel(std::function func) { for (auto &channel : channels_) { if (IsPublicChannel(channel.second.get())) { @@ -42,6 +51,7 @@ Server::CreateMultiplexer(const std::string &channel_name, int64_t slot_size, *channel_id, channel_name, num_slots, subscriber_queue_size, subscriber_queue_arena_size, std::move(type), session_id_, logger_); channel->SetDebug(logger_.GetLogLevel() <= toolbelt::LogLevel::kVerboseDebug); + channel->SetLastKnownSlotSize(slot_size); // Establish the prefix layout before allocating. Allocation is what makes // the channel visible: it is immediately followed by replication to the // shadows, which copy the checksum and metadata sizes off the channel and @@ -245,14 +255,221 @@ absl::Status Server::RemapChannel(ServerChannel *channel, int64_t slot_size, return absl::OkStatus(); } -ServerChannel *Server::FindChannel(const std::string &channel_name) { - auto it = channels_.find(channel_name); +ServerChannel *Server::FindChannel(std::string_view channel_name) { + auto it = channels_.find(std::string(channel_name)); if (it == channels_.end()) { return nullptr; } return it->second.get(); } +absl::Status Server::SetStaticChannelConfig(StaticChannelConfig config) { + if (absl::Status s = ValidateStaticChannelConfig(config); !s.ok()) { + return s; + } + static_config_ = std::move(config); + return absl::OkStatus(); +} + +bool Server::IsServerChannelName(const std::string &channel_name) { + return channel_name == kChannelDirectoryChannel || + channel_name == kStatisticsChannel; +} + +void Server::RegisterClientBuffer(ServerChannel *channel, + ClientBufferHandleMetadata metadata, + toolbelt::FileDescriptor fd) { + channel->RegisterClientBuffer(metadata, std::move(fd)); + ForEachShadow([&](const std::unique_ptr &shadow) { + const auto matches = + channel->FindClientBuffers(metadata.session_id, metadata.buffer_index); + for (const RegisteredClientBuffer *buffer : matches) { + if (buffer->metadata.slot_id == metadata.slot_id && + buffer->metadata.is_prefix == metadata.is_prefix) { + shadow->SendRegisterClientBuffer(buffer->metadata, buffer->fd); + return; + } + } + shadow->SendRegisterClientBuffer(metadata); + }); +} + +absl::Status Server::CreateStaticBuffers(ServerChannel *channel, + int64_t slot_size, + bool use_split_buffers) { + if (absl::Status s = channel->ValidateOrSetSplitBufferOptions( + {.use_split_buffers = use_split_buffers}, + /*set_if_missing=*/use_split_buffers, "static channel config"); + !s.ok()) { + return s; + } + if (channel->GetCcb()->num_buffers.load(std::memory_order_acquire) > 0) { + // Recovered from a shadow with its buffers. + return absl::OkStatus(); + } + // A publisher that is never registered with the channel creates the + // buffers through the same code as a client's first publisher. The + // buffers outlive it: named shared memory stays until the session is + // cleaned up, and the channel keeps the registered file descriptors. + details::PublisherImpl creator( + channel->Name(), channel->NumSlots(), channel->SubscriberQueueSize(), + channel->SubscriberQueueArenaSize(), channel->GetChannelId(), + /*publisher_id=*/-1, /*vchan_id=*/-1, session_id_, channel->Type(), + PublisherOptions() + .SetSlotSize(slot_size) + .SetNumSlots(channel->NumSlots()) + .SetFixedSize(true) + .SetUseSplitBuffers(use_split_buffers), + /*reload=*/nullptr, static_cast(getuid()), + static_cast(getgid())); + creator.SetChecksumSize(channel->ChecksumSize()); + creator.SetMetadataSize(channel->MetadataSize()); + creator.SetPrefixSize(channel->PrefixSize()); + creator.SetClientBufferRegistrationCallback( + [this, channel](const ClientBufferHandleMetadata &metadata, + const toolbelt::FileDescriptor *fd) { + RegisterClientBuffer(channel, metadata, + fd != nullptr ? *fd : toolbelt::FileDescriptor()); + return absl::OkStatus(); + }); + creator.SetClientBufferLookupCallback( + [channel](const std::string &, uint64_t session_id, + uint32_t buffer_index) + -> absl::StatusOr> { + std::vector buffers; + for (const RegisteredClientBuffer *buffer : + channel->FindClientBuffers(session_id, buffer_index)) { + buffers.push_back(*buffer); + } + return buffers; + }); + const SharedMemoryFds &fds = channel->GetFds(); + if (absl::Status s = creator.Map(SharedMemoryFds(fds.ccb, fds.bcb), scb_fd_); + !s.ok()) { + return s; + } + return creator.CreateOrAttachBuffers(slot_size); +} + +absl::Status Server::CreateStaticChannels() { + if (!static_config_.has_value()) { + return absl::OkStatus(); + } + // A server restarted from a shadow already has the channels; they must + // still be the ones configured. + auto check_recovered = [](const ServerChannel *channel, bool is_mux, + const std::string &mux, int vchan_id, + int64_t slot_size, int num_slots, + int32_t checksum_size, + int32_t metadata_size) -> absl::Status { + const bool matches = + !channel->IsPlaceholder() && channel->IsMux() == is_mux && + channel->IsVirtual() == !mux.empty() && + (mux.empty() || + (static_cast(channel)->GetMux()->Name() == + mux && + channel->GetVirtualChannelId() == vchan_id)) && + channel->SlotSize() == slot_size && channel->NumSlots() == num_slots && + channel->ChecksumSize() == checksum_size && + channel->MetadataSize() == metadata_size; + if (!matches) { + return absl::FailedPreconditionError(absl::StrFormat( + "Channel %s recovered from the shadow doesn't match the static " + "channel config", + channel->Name())); + } + return absl::OkStatus(); + }; + auto checksum_or_default = [](int32_t checksum_size) { + return checksum_size == 0 ? 4 : checksum_size; + }; + + absl::flat_hash_map muxes; + for (const StaticMultiplexer &m : static_config_->multiplexers()) { + muxes[m.name()] = &m; + const int64_t slot_size = Aligned(m.slot_size()); + const int32_t checksum_size = checksum_or_default(m.checksum_size()); + ServerChannel *mux = FindChannel(m.name()); + if (mux == nullptr) { + absl::StatusOr created = + CreateMultiplexer(m.name(), slot_size, m.num_slots(), 0, m.type(), + checksum_size, m.metadata_size()); + if (!created.ok()) { + return absl::InternalError( + absl::StrFormat("Failed to create static multiplexer %s: %s", + m.name(), created.status().ToString())); + } + mux = *created; + } else if (absl::Status s = check_recovered( + mux, /*is_mux=*/true, "", -1, slot_size, m.num_slots(), + checksum_size, m.metadata_size()); + !s.ok()) { + return s; + } + mux->SetStatic(true); + if (absl::Status s = + CreateStaticBuffers(mux, slot_size, m.use_split_buffers()); + !s.ok()) { + return absl::InternalError( + absl::StrFormat("Failed to create buffers for static multiplexer " + "%s: %s", + m.name(), s.ToString())); + } + } + + for (const StaticChannel &c : static_config_->channels()) { + const StaticMultiplexer *mux = + c.mux().empty() ? nullptr : muxes.at(c.mux()); + const int64_t slot_size = + Aligned(mux != nullptr ? mux->slot_size() : c.slot_size()); + const int num_slots = mux != nullptr ? mux->num_slots() : c.num_slots(); + const int32_t checksum_size = checksum_or_default( + mux != nullptr ? mux->checksum_size() : c.checksum_size()); + const int32_t metadata_size = + mux != nullptr ? mux->metadata_size() : c.metadata_size(); + const int vchan_id = mux != nullptr ? c.vchan_id() : -1; + ServerChannel *channel = FindChannel(c.name()); + if (channel == nullptr) { + // A virtual channel takes its layout from the multiplexer, which + // already has it. + absl::StatusOr created = + mux != nullptr + ? CreateChannel(c.name(), 0, 0, 0, c.mux(), vchan_id, "") + : CreateChannel(c.name(), slot_size, num_slots, 0, "", -1, + c.type(), /*hidden=*/false, + /*telemetry_target=*/{}, checksum_size, + metadata_size); + if (!created.ok()) { + return absl::InternalError( + absl::StrFormat("Failed to create static channel %s: %s", + c.name(), created.status().ToString())); + } + channel = *created; + } else if (absl::Status s = check_recovered( + channel, /*is_mux=*/false, c.mux(), vchan_id, slot_size, + num_slots, checksum_size, metadata_size); + !s.ok()) { + return s; + } + channel->SetStatic(true); + if (mux == nullptr) { + if (absl::Status s = + CreateStaticBuffers(channel, slot_size, c.use_split_buffers()); + !s.ok()) { + return absl::InternalError(absl::StrFormat( + "Failed to create buffers for static channel %s: %s", c.name(), + s.ToString())); + } + } + } + logger_.Log(toolbelt::LogLevel::kInfo, + "Static channel config: %d channels and %d multiplexers", + static_config_->channels_size(), + static_config_->multiplexers_size()); + SendChannelDirectory(); + return absl::OkStatus(); +} + void Server::RemoveChannel(ServerChannel *channel) { const bool telemetry = channel->IsTelemetryChannel(); const std::string telemetry_target = @@ -281,7 +498,7 @@ void Server::RemoveChannel(ServerChannel *channel) { auto vchan = static_cast(it->second.get()); ChannelMultiplexer *mux = vchan->GetMux(); mux->RemoveVirtualChannel(vchan); - if (mux->IsEmpty()) { + if (mux->IsEmpty() && !mux->IsStatic()) { RemoveChannel(mux); } } @@ -293,7 +510,8 @@ void Server::RemoveAllUsersFor(ClientHandler *handler) { std::vector empty_channels; for (auto &channel : channels_) { channel.second->RemoveAllUsersFor(this, handler); - if (channel.second->IsEmpty() && !channel.second->IsTelemetryChannel()) { + if (channel.second->IsEmpty() && !channel.second->IsTelemetryChannel() && + !channel.second->IsStatic()) { empty_channels.push_back(channel.second.get()); } } @@ -318,7 +536,7 @@ void Server::ChannelDirectoryCoroutine(async::Context ctx) { constexpr int kDirectoryNumSlots = 32; absl::StatusOr channel_directory = client.CreatePublisher( - "/subspace/ChannelDirectory", kDirectorySlotSize, kDirectoryNumSlots, + kChannelDirectoryChannel, kDirectorySlotSize, kDirectoryNumSlots, PublisherOptions() .SetType("subspace.ChannelDirectory") .SetUseSplitBuffers(false)); @@ -386,7 +604,7 @@ void Server::StatisticsCoroutine(async::Context ctx) { constexpr int kStatsNumSlots = 32; absl::StatusOr pub = client.CreatePublisher( - "/subspace/Statistics", kStatsSlotSize, kStatsNumSlots, + kStatisticsChannel, kStatsSlotSize, kStatsNumSlots, PublisherOptions() .SetType("subspace.Statistics") .SetUseSplitBuffers(false)); @@ -398,7 +616,7 @@ void Server::StatisticsCoroutine(async::Context ctx) { } auto delivered_statistics_messages = [this]() -> uint64_t { - auto it = channels_.find("/subspace/Statistics"); + auto it = channels_.find(kStatisticsChannel); if (it == channels_.end()) { return 0; } diff --git a/server/server_discovery.cc b/server/server_discovery.cc index 3e604f1a..a5c537ac 100644 --- a/server/server_discovery.cc +++ b/server/server_discovery.cc @@ -1,7 +1,7 @@ // Copyright 2023-2026 David Allison // All Rights Reserved // Shadow support is Copyright 2026 Cruise LLC -// Tunnel support is Copyright 2026 General Motors LLC +// Tunnel support is Copyright 2026 General Motors // See LICENSE file for licensing information. #include "server/server.h" @@ -352,14 +352,23 @@ void Server::SubscribeOverBridge(ServerChannel *channel, bool reliable, const bool local_use_split_buffers = local_has_split_options && split_channel->GetSplitBufferOptions().use_split_buffers; + const bool local_is_static = channel->IsStatic(); + std::string static_mux; + int static_vchan_id = -1; + if (local_is_static && channel->IsVirtual()) { + const VirtualChannel *vchan = static_cast(channel); + static_mux = vchan->GetMux()->Name(); + static_vchan_id = vchan->GetVirtualChannelId(); + } std::string channel_name = channel->Name(); runtime_.SpawnOnNewStrand( [this, channel_name, reliable, split_buffers_over_bridge, publisher, - local_has_split_options, local_use_split_buffers](async::Context ctx) { + local_has_split_options, local_use_split_buffers, local_is_static, + static_mux, static_vchan_id](async::Context ctx) { BridgeReceiverCoroutine(ctx, channel_name, reliable, split_buffers_over_bridge, publisher, - local_has_split_options, - local_use_split_buffers); + local_has_split_options, local_use_split_buffers, + local_is_static, static_mux, static_vchan_id); }, {.name = absl::StrFormat("Bridge receiver for %s", channel_name), .interrupt_fd = shutdown_trigger_fd_.GetPollFd().Fd()}); diff --git a/server/server_plugins.cc b/server/server_plugins.cc index 6962b9f9..c3cbabb7 100644 --- a/server/server_plugins.cc +++ b/server/server_plugins.cc @@ -1,7 +1,7 @@ // Copyright 2023-2026 David Allison // All Rights Reserved // Shadow support is Copyright 2026 Cruise LLC -// Tunnel support is Copyright 2026 General Motors LLC +// Tunnel support is Copyright 2026 General Motors // See LICENSE file for licensing information. #include "server/server.h" diff --git a/server/server_shadow.cc b/server/server_shadow.cc index b7d83e5a..1c41a9de 100644 --- a/server/server_shadow.cc +++ b/server/server_shadow.cc @@ -1,7 +1,7 @@ // Copyright 2023-2026 David Allison // All Rights Reserved // Shadow support is Copyright 2026 Cruise LLC -// Tunnel support is Copyright 2026 General Motors LLC +// Tunnel support is Copyright 2026 General Motors // See LICENSE file for licensing information. #include "server/server.h" diff --git a/server/server_telemetry.cc b/server/server_telemetry.cc index 17af184b..27c6ee7d 100644 --- a/server/server_telemetry.cc +++ b/server/server_telemetry.cc @@ -1,7 +1,7 @@ // Copyright 2023-2026 David Allison // All Rights Reserved // Shadow support is Copyright 2026 Cruise LLC -// Tunnel support is Copyright 2026 General Motors LLC +// Tunnel support is Copyright 2026 General Motors // See LICENSE file for licensing information. #include "server/server.h" diff --git a/server/server_test.cc b/server/server_test.cc index 8a6efe4e..2d2ef850 100644 --- a/server/server_test.cc +++ b/server/server_test.cc @@ -13,7 +13,9 @@ #include "common/channel.h" #include "absl/status/status.h" #include "absl/status/statusor.h" +#include "common/server_wire.h" #include "proto/subspace.pb.h" +#include "proto/subspace.phaser.h" #include "toolbelt/fd.h" #include "toolbelt/sockets.h" #include @@ -43,7 +45,7 @@ #endif namespace { -void FillMatchingInitBuildConfig(subspace::InitRequest *init) { +void FillMatchingInitBuildConfig(subspace::phaser::InitRequest *init) { init->set_max_channels(subspace::kMaxChannels); init->set_max_slot_owners(subspace::kMaxSlotOwners); init->set_max_buffers(static_cast(subspace::kMaxBuffers)); @@ -60,7 +62,7 @@ class RawConnection { } absl::Status Init(const std::string &client_name = "raw_test") { - subspace::Request req; + subspace::phaser::Request req; req.mutable_init()->set_client_name(client_name); FillMatchingInitBuildConfig(req.mutable_init()); auto result = Send(req); @@ -74,22 +76,21 @@ class RawConnection { uint64_t SessionId() const { return session_id_; } absl::StatusOr< - std::pair>> - Send(const subspace::Request &req) { + std::pair>> + Send(const subspace::phaser::Request &req) { return SendWithFds(req, {}); } absl::StatusOr< - std::pair>> - SendWithFds(const subspace::Request &req, + std::pair>> + SendWithFds(const subspace::phaser::Request &req, const std::vector &send_fds) { - size_t msg_len = req.ByteSizeLong(); - std::vector buf(sizeof(int32_t) + msg_len); - char *payload = buf.data() + sizeof(int32_t); - if (!req.SerializeToArray(payload, msg_len)) { - return absl::InternalError("Failed to serialize request"); + subspace::ServerWire wire; + absl::StatusOr msg_len = wire.Serialize(req); + if (!msg_len.ok()) { + return msg_len.status(); } - auto n = socket_.SendMessage(payload, msg_len); + auto n = socket_.SendMessage(wire.Payload(), *msg_len); if (!n.ok()) { return n.status(); } @@ -103,9 +104,12 @@ class RawConnection { if (!recv.ok()) { return recv.status(); } - subspace::Response resp; - if (!resp.ParseFromArray(recv->data(), static_cast(recv->size()))) { - return absl::InternalError("Failed to parse response"); + subspace::phaser::Response resp; + if (absl::Status status = subspace::ServerWire< + subspace::DynamicServerWireBuffers>::Decode(recv->data(), + recv->size(), resp); + !status.ok()) { + return status; } std::vector fds; @@ -118,11 +122,11 @@ class RawConnection { // Build a RegisterClientBuffer request for the given (channel, session, // buffer_index, slot_id). When send_fd is true a backing fd is attached and // fd_index is used as-is (allowing tests to inject an out-of-range index). - subspace::Request + subspace::phaser::Request MakeRegisterRequest(const std::string &channel, uint64_t session_id, uint32_t buffer_index, uint32_t slot_id, bool has_fd, int fd_index) { - subspace::Request req; + subspace::phaser::Request req; auto *r = req.mutable_register_client_buffer(); auto *m = r->mutable_metadata(); m->set_channel_name(channel); @@ -134,10 +138,10 @@ class RawConnection { return req; } - subspace::Request MakeUnregisterRequest(const std::string &channel, + subspace::phaser::Request MakeUnregisterRequest(const std::string &channel, uint64_t session_id, uint32_t buffer_index) { - subspace::Request req; + subspace::phaser::Request req; auto *u = req.mutable_unregister_client_buffer(); u->set_channel_name(channel); u->set_session_id(session_id); @@ -150,26 +154,25 @@ class RawConnection { // same connection so the caller can observe the resulting server state. The // ordered processing on a single connection guarantees the one-way request // has been handled by the time the query returns. - absl::StatusOr - SendOneWayThenGetBuffers(const subspace::Request &one_way, + absl::StatusOr + SendOneWayThenGetBuffers(const subspace::phaser::Request &one_way, const std::string &channel, uint64_t session_id, uint32_t buffer_index) { - size_t msg_len = one_way.ByteSizeLong(); - std::vector buf(sizeof(int32_t) + msg_len); - char *payload = buf.data() + sizeof(int32_t); - if (!one_way.SerializeToArray(payload, msg_len)) { - return absl::InternalError("Failed to serialize request"); + subspace::ServerWire wire; + absl::StatusOr msg_len = wire.Serialize(one_way); + if (!msg_len.ok()) { + return msg_len.status(); } - if (auto n = socket_.SendMessage(payload, msg_len); !n.ok()) { + if (auto n = socket_.SendMessage(wire.Payload(), *msg_len); !n.ok()) { return n.status(); } return GetClientBuffers(channel, session_id, buffer_index); } - absl::StatusOr + absl::StatusOr GetClientBuffers(const std::string &channel, uint64_t session_id, uint32_t buffer_index) { - subspace::Request req; + subspace::phaser::Request req; auto *g = req.mutable_get_client_buffers(); g->set_channel_name(channel); g->set_session_id(session_id); @@ -178,11 +181,19 @@ class RawConnection { if (!result.ok()) { return result.status(); } - return result->first.get_client_buffers(); + // The getter is a view into the response. Copy it into an owned message + // before the response is destroyed. + subspace::phaser::GetClientBuffersResponse buffers; + if (absl::Status status = buffers.CloneFrom(result->first.get_client_buffers()); + !status.ok() || buffers.AllocationFailed()) { + return status.ok() ? absl::InternalError("Failed to copy client buffers") + : status; + } + return buffers; } // Convenience: create a publisher and return the response. - std::pair> + std::pair> CreatePublisher(const std::string &channel, int slot_size = 64, int num_slots = 4, const std::string &type = "", bool reliable = false, bool is_local = true, @@ -191,7 +202,7 @@ class RawConnection { bool notify_retirement = false, int checksum_size = 0, int metadata_size = 0, int max_publishers = 0, uint64_t subscriber_queue_arena_size = 0) { - subspace::Request req; + subspace::phaser::Request req; auto *cmd = req.mutable_create_publisher(); cmd->set_channel_name(channel); cmd->set_slot_size(slot_size); @@ -214,13 +225,13 @@ class RawConnection { } // Convenience: create a subscriber and return the response. - std::pair> + std::pair> CreateSubscriber(const std::string &channel, const std::string &type = "", bool reliable = false, int max_active_messages = 4, const std::string &mux = "", int vchan_id = 0, bool for_tunnel = false, int subscriber_queue_size = 0) { - subspace::Request req; + subspace::phaser::Request req; auto *cmd = req.mutable_create_subscriber(); cmd->set_channel_name(channel); cmd->set_type(type); @@ -250,7 +261,7 @@ TEST_F(ServerTest, InitSuccess) { RawConnection conn; ASSERT_OK(conn.Connect(Socket())); - subspace::Request req; + subspace::phaser::Request req; req.mutable_init()->set_client_name("test_init"); FillMatchingInitBuildConfig(req.mutable_init()); auto result = conn.Send(req); @@ -266,7 +277,7 @@ TEST_F(ServerTest, InitRejectsBuildConfigMismatch) { RawConnection conn; ASSERT_OK(conn.Connect(Socket())); - subspace::Request req; + subspace::phaser::Request req; req.mutable_init()->set_client_name("mismatch"); FillMatchingInitBuildConfig(req.mutable_init()); req.mutable_init()->set_max_channels(subspace::kMaxChannels + 64); @@ -380,6 +391,28 @@ TEST_F(ServerTest, CreateSubscriberSuccess) { // CreatePublisher error paths // --------------------------------------------------------------------------- +TEST_F(ServerTest, ServerDefinedNeedsStaticChannel) { + RawConnection conn; + ASSERT_OK(conn.Connect(Socket())); + ASSERT_OK(conn.Init()); + + // Neither a new channel nor an existing one on a server without a static + // channel config has a layout that the server defines. + conn.CreatePublisher("server_defined_ch"); + for (const char *channel : {"server_defined_new", "server_defined_ch"}) { + subspace::phaser::Request req; + subspace::phaser::CreatePublisherRequest *cmd = req.mutable_create_publisher(); + cmd->set_channel_name(channel); + cmd->set_server_defined(true); + cmd->set_publisher_id(-1); + auto result = conn.Send(req); + ASSERT_OK(result); + EXPECT_THAT(result->first.create_publisher().error(), + ::testing::HasSubstr("can't set server_defined")) + << channel; + } +} + TEST_F(ServerTest, PubTypeMismatch) { RawConnection conn; ASSERT_OK(conn.Connect(Socket())); @@ -735,7 +768,7 @@ TEST_F(ServerTest, SubInvalidReclaim) { conn.CreatePublisher("sub_reclaim_ch", 64, 4); // Try to reclaim a subscriber with an invalid ID. - subspace::Request req; + subspace::phaser::Request req; auto *cmd = req.mutable_create_subscriber(); cmd->set_channel_name("sub_reclaim_ch"); cmd->set_subscriber_id(9999); @@ -755,7 +788,7 @@ TEST_F(ServerTest, GetTriggersNoSuchChannel) { ASSERT_OK(conn.Connect(Socket())); ASSERT_OK(conn.Init()); - subspace::Request req; + subspace::phaser::Request req; req.mutable_get_triggers()->set_channel_name("nonexistent_triggers"); auto result = conn.Send(req); ASSERT_OK(result); @@ -771,7 +804,7 @@ TEST_F(ServerTest, GetTriggersSuccess) { conn.CreatePublisher("triggers_ch", 64, 4, "", /*reliable=*/true); conn.CreateSubscriber("triggers_ch"); - subspace::Request req; + subspace::phaser::Request req; req.mutable_get_triggers()->set_channel_name("triggers_ch"); auto result = conn.Send(req); ASSERT_OK(result); @@ -787,7 +820,7 @@ TEST_F(ServerTest, RemovePublisherNoSuchChannel) { ASSERT_OK(conn.Connect(Socket())); ASSERT_OK(conn.Init()); - subspace::Request req; + subspace::phaser::Request req; auto *cmd = req.mutable_remove_publisher(); cmd->set_channel_name("ghost_channel"); cmd->set_publisher_id(0); @@ -802,7 +835,7 @@ TEST_F(ServerTest, RemoveSubscriberNoSuchChannel) { ASSERT_OK(conn.Connect(Socket())); ASSERT_OK(conn.Init()); - subspace::Request req; + subspace::phaser::Request req; auto *cmd = req.mutable_remove_subscriber(); cmd->set_channel_name("ghost_channel_sub"); cmd->set_subscriber_id(0); @@ -821,7 +854,7 @@ TEST_F(ServerTest, RemovePublisherSuccess) { ASSERT_TRUE(create_resp.create_publisher().error().empty()); int pub_id = create_resp.create_publisher().publisher_id(); - subspace::Request req; + subspace::phaser::Request req; auto *cmd = req.mutable_remove_publisher(); cmd->set_channel_name("rm_pub_ch"); cmd->set_publisher_id(pub_id); @@ -839,7 +872,7 @@ TEST_F(ServerTest, RemoveSubscriberSuccess) { ASSERT_TRUE(create_resp.create_subscriber().error().empty()); int sub_id = create_resp.create_subscriber().subscriber_id(); - subspace::Request req; + subspace::phaser::Request req; auto *cmd = req.mutable_remove_subscriber(); cmd->set_channel_name("rm_sub_ch"); cmd->set_subscriber_id(sub_id); @@ -854,7 +887,7 @@ TEST_F(ServerTest, RemovePublisherInvalidId) { ASSERT_OK(conn.Init()); conn.CreatePublisher("rm_inval_pub", 64, 4); - subspace::Request req; + subspace::phaser::Request req; auto *cmd = req.mutable_remove_publisher(); cmd->set_channel_name("rm_inval_pub"); cmd->set_publisher_id(9999); @@ -875,7 +908,7 @@ TEST_F(ServerTest, GetChannelInfoByName) { conn.CreatePublisher("info_ch", 128, 8, "info_type"); - subspace::Request req; + subspace::phaser::Request req; req.mutable_get_channel_info()->set_channel_name("info_ch"); auto result = conn.Send(req); ASSERT_OK(result); @@ -894,7 +927,7 @@ TEST_F(ServerTest, GetChannelInfoNoSuchChannel) { ASSERT_OK(conn.Connect(Socket())); ASSERT_OK(conn.Init()); - subspace::Request req; + subspace::phaser::Request req; req.mutable_get_channel_info()->set_channel_name("no_such_info"); auto result = conn.Send(req); ASSERT_OK(result); @@ -910,7 +943,7 @@ TEST_F(ServerTest, GetChannelInfoAll) { conn.CreatePublisher("allinfo1", 64, 4); conn.CreatePublisher("allinfo2", 64, 4); - subspace::Request req; + subspace::phaser::Request req; req.mutable_get_channel_info(); auto result = conn.Send(req); ASSERT_OK(result); @@ -930,14 +963,14 @@ TEST_F(ServerTest, GetChannelInfoReportsIsLocal) { conn.CreatePublisher("public_info_ch", 64, 4, "", /*reliable=*/false, /*is_local=*/false); - subspace::Request local_req; + subspace::phaser::Request local_req; local_req.mutable_get_channel_info()->set_channel_name("local_info_ch"); auto local = conn.Send(local_req); ASSERT_OK(local); ASSERT_EQ(1, local->first.get_channel_info().channels_size()); EXPECT_TRUE(local->first.get_channel_info().channels(0).is_local()); - subspace::Request public_req; + subspace::phaser::Request public_req; public_req.mutable_get_channel_info()->set_channel_name("public_info_ch"); auto pub = conn.Send(public_req); ASSERT_OK(pub); @@ -956,7 +989,7 @@ TEST_F(ServerTest, GetChannelStatsByName) { conn.CreatePublisher("stats_ch", 256, 4); - subspace::Request req; + subspace::phaser::Request req; req.mutable_get_channel_stats()->set_channel_name("stats_ch"); auto result = conn.Send(req); ASSERT_OK(result); @@ -971,7 +1004,7 @@ TEST_F(ServerTest, GetChannelStatsNoSuchChannel) { ASSERT_OK(conn.Connect(Socket())); ASSERT_OK(conn.Init()); - subspace::Request req; + subspace::phaser::Request req; req.mutable_get_channel_stats()->set_channel_name("no_such_stats"); auto result = conn.Send(req); ASSERT_OK(result); @@ -987,7 +1020,7 @@ TEST_F(ServerTest, GetChannelStatsAll) { conn.CreatePublisher("allstats_s1", 64, 4); conn.CreatePublisher("allstats_s2", 64, 4); - subspace::Request req; + subspace::phaser::Request req; req.mutable_get_channel_stats(); auto result = conn.Send(req); ASSERT_OK(result); @@ -1006,14 +1039,14 @@ TEST_F(ServerTest, GetChannelStatsReportsIsLocal) { conn.CreatePublisher("public_stats_ch", 64, 4, "", /*reliable=*/false, /*is_local=*/false); - subspace::Request local_req; + subspace::phaser::Request local_req; local_req.mutable_get_channel_stats()->set_channel_name("local_stats_ch"); auto local = conn.Send(local_req); ASSERT_OK(local); ASSERT_EQ(1, local->first.get_channel_stats().channels_size()); EXPECT_TRUE(local->first.get_channel_stats().channels(0).is_local()); - subspace::Request public_req; + subspace::phaser::Request public_req; public_req.mutable_get_channel_stats()->set_channel_name("public_stats_ch"); auto pub = conn.Send(public_req); ASSERT_OK(pub); diff --git a/server/static_config.cc b/server/static_config.cc new file mode 100644 index 00000000..287fb635 --- /dev/null +++ b/server/static_config.cc @@ -0,0 +1,190 @@ +// Copyright 2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +#include "server/static_config.h" + +#include "server/config_format.h" + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/strings/match.h" +#include "absl/strings/str_format.h" +#include "common/channel.h" +#include "google/protobuf/text_format.h" +#include +#include +#include + +namespace subspace { + +namespace { + +absl::Status ConfigError(const std::string &message) { + return absl::InvalidArgumentError("Static channel config: " + message); +} + +absl::Status ValidateName(const std::string &name, + absl::flat_hash_set &names) { + if (name.empty()) { + return ConfigError("every channel and multiplexer needs a name"); + } + if (absl::StartsWith(name, kServerChannelPrefix)) { + return ConfigError(absl::StrFormat( + "%s uses the server's reserved prefix %s", name, kServerChannelPrefix)); + } + if (!names.insert(name).second) { + return ConfigError(absl::StrFormat("%s is configured more than once", name)); + } + return absl::OkStatus(); +} + +absl::Status ValidateLayout(const std::string &name, int32_t slot_size, + int32_t num_slots, int32_t checksum_size, + int32_t metadata_size) { + if (slot_size <= 0 || num_slots <= 0) { + return ConfigError(absl::StrFormat( + "%s needs a slot_size and num_slots greater than 0, not %d and %d", + name, slot_size, num_slots)); + } + if (checksum_size < 0 || checksum_size > kMaxChecksumSize) { + return ConfigError( + absl::StrFormat("%s has checksum_size %d; it must be from 0 to %d", + name, checksum_size, kMaxChecksumSize)); + } + if (metadata_size < 0 || metadata_size > kMaxMetadataSize) { + return ConfigError( + absl::StrFormat("%s has metadata_size %d; it must be from 0 to %d", + name, metadata_size, kMaxMetadataSize)); + } + return absl::OkStatus(); +} + +} // namespace + +absl::Status ValidateStaticChannelConfig(const StaticChannelConfig &config) { + absl::flat_hash_set names; + // Virtual channel ids in use on each multiplexer. + absl::flat_hash_map> mux_vchan_ids; + + for (const StaticMultiplexer &mux : config.multiplexers()) { + if (absl::Status s = ValidateName(mux.name(), names); !s.ok()) { + return s; + } + if (absl::Status s = + ValidateLayout(mux.name(), mux.slot_size(), mux.num_slots(), + mux.checksum_size(), mux.metadata_size()); + !s.ok()) { + return s; + } + mux_vchan_ids[mux.name()]; + } + + for (const StaticChannel &channel : config.channels()) { + if (absl::Status s = ValidateName(channel.name(), names); !s.ok()) { + return s; + } + if (channel.mux().empty()) { + if (channel.vchan_id() != 0) { + return ConfigError(absl::StrFormat( + "%s has a vchan_id but no mux", channel.name())); + } + if (absl::Status s = ValidateLayout( + channel.name(), channel.slot_size(), channel.num_slots(), + channel.checksum_size(), channel.metadata_size()); + !s.ok()) { + return s; + } + continue; + } + auto ids = mux_vchan_ids.find(channel.mux()); + if (ids == mux_vchan_ids.end()) { + return ConfigError( + absl::StrFormat("%s uses mux %s, which isn't a configured " + "multiplexer", + channel.name(), channel.mux())); + } + if (channel.slot_size() != 0 || channel.num_slots() != 0 || + !channel.type().empty() || channel.checksum_size() != 0 || + channel.metadata_size() != 0 || channel.use_split_buffers()) { + return ConfigError(absl::StrFormat( + "%s is on mux %s and takes its slot_size, num_slots, type, " + "checksum_size, metadata_size and use_split_buffers from it; leave " + "them unset", + channel.name(), channel.mux())); + } + if (channel.vchan_id() < 0 || channel.vchan_id() >= kMaxVchanId) { + return ConfigError( + absl::StrFormat("%s has vchan_id %d; it must be from 0 to %d", + channel.name(), channel.vchan_id(), kMaxVchanId - 1)); + } + if (!ids->second.insert(channel.vchan_id()).second) { + return ConfigError(absl::StrFormat( + "%s reuses vchan_id %d on mux %s", channel.name(), + channel.vchan_id(), channel.mux())); + } + } + return absl::OkStatus(); +} + +absl::StatusOr +ParseStaticChannelConfig(const std::string &text) { + StaticChannelConfig config; + if (!google::protobuf::TextFormat::ParseFromString(text, &config)) { + return ConfigError("invalid protobuf text format"); + } + if (absl::Status s = ValidateStaticChannelConfig(config); !s.ok()) { + return s; + } + return config; +} + +namespace { + +absl::StatusOr ReadConfigFile(const std::string &filename) { + std::ifstream in(filename, std::ios::binary); + if (!in) { + return absl::NotFoundError(absl::StrFormat( + "Static channel config: can't open %s", filename)); + } + std::stringstream contents; + contents << in.rdbuf(); + if (in.bad()) { + return absl::InternalError(absl::StrFormat( + "Static channel config: can't read %s", filename)); + } + return contents.str(); +} + +} // namespace + +absl::StatusOr +ReadStaticChannelConfig(const std::string &filename) { + absl::StatusOr bytes = ReadConfigFile(filename); + if (!bytes.ok()) { + return bytes.status(); + } + absl::StatusOr config; + if (ConfigFileIsText(filename)) { + config = ParseStaticChannelConfig(*bytes); + } else { + StaticChannelConfig parsed; + if (!parsed.ParseFromString(*bytes)) { + config = ConfigError("invalid protobuf wire format"); + } else if (HasUnknownFields(parsed)) { + config = ConfigError("unknown field in protobuf wire format"); + } else if (absl::Status s = ValidateStaticChannelConfig(parsed); !s.ok()) { + config = s; + } else { + config = std::move(parsed); + } + } + if (!config.ok()) { + return absl::Status(config.status().code(), + absl::StrFormat("%s: %s", filename, + config.status().message())); + } + return config; +} + +} // namespace subspace diff --git a/server/static_config.h b/server/static_config.h new file mode 100644 index 00000000..98afc47e --- /dev/null +++ b/server/static_config.h @@ -0,0 +1,32 @@ +// Copyright 2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +#ifndef _xSERVERSTATIC_CONFIG_H +#define _xSERVERSTATIC_CONFIG_H + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "proto/subspace.pb.h" +#include + +namespace subspace { + +// Prefix of the channels the server creates for itself. A static channel +// config can't use it. +inline constexpr char kServerChannelPrefix[] = "/subspace/"; + +// Parses a StaticChannelConfig in protobuf text format and validates it. +absl::StatusOr +ParseStaticChannelConfig(const std::string &text); + +// Reads, parses and validates a StaticChannelConfig file. A name ending in +// .pb or .binpb is protobuf wire format. Any other name is text format. +absl::StatusOr +ReadStaticChannelConfig(const std::string &filename); + +absl::Status ValidateStaticChannelConfig(const StaticChannelConfig &config); + +} // namespace subspace + +#endif // _xSERVERSTATIC_CONFIG_H diff --git a/server/static_config_test.cc b/server/static_config_test.cc new file mode 100644 index 00000000..8d8660d9 --- /dev/null +++ b/server/static_config_test.cc @@ -0,0 +1,668 @@ +// Copyright 2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +// Tests for a server started with a static channel config: the configured +// channels exist before any client connects and their layout is fixed. +// A standard publisher can still create a channel that isn't configured, +// and any subscriber can subscribe to one. + +#include "client/test_fixture.h" + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_format.h" +#include "common/server_wire.h" +#include "proto/subspace.pb.h" +#include "proto/subspace.phaser.h" +#include "server/static_config.h" +#include "toolbelt/sockets.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +using ::absl_testing::StatusIs; +using ::testing::HasSubstr; + +constexpr char kConfig[] = R"pb( + multiplexers { name: "/static/mux" slot_size: 128 num_slots: 8 type: "Mux" } + channels { name: "/static/a" slot_size: 256 num_slots: 8 type: "A" } + channels { name: "/static/meta" slot_size: 64 num_slots: 4 metadata_size: 16 } + channels { name: "/static/v1" mux: "/static/mux" vchan_id: 3 } + channels { name: "/static/v2" mux: "/static/mux" vchan_id: 7 } + channels { + name: "/static/split" + slot_size: 256 + num_slots: 4 + use_split_buffers: true + } + multiplexers { + name: "/static/split_mux" + slot_size: 128 + num_slots: 4 + use_split_buffers: true + } + channels { name: "/static/sv" mux: "/static/split_mux" vchan_id: 1 } + channels { + name: "/static/blob" + slot_size: 64 + num_slots: 4 + type: "\377\000State\200" + } +)pb"; + +// The bytes in /static/blob's type: 0xFF, 0x00, "State", 0x80. +const std::string kBlobType("\xff\x00State\x80", 8); + +subspace::PublisherOptions ServerDefined() { + return subspace::PublisherOptions().SetServerDefined(true); +} + +// Sends a request the way the clients do, bypassing the client library's own +// checks, and returns the server's response. +absl::StatusOr Transact(toolbelt::UnixSocket &socket, + const subspace::phaser::Request &req) { + subspace::ServerWire wire; + absl::StatusOr length = wire.Serialize(req); + if (!length.ok()) { + return length.status(); + } + if (absl::StatusOr n = socket.SendMessage(wire.Payload(), *length); + !n.ok()) { + return n.status(); + } + absl::StatusOr> received = + socket.ReceiveVariableLengthMessage(); + if (!received.ok()) { + return received.status(); + } + subspace::phaser::Response response; + if (absl::Status status = subspace::ServerWire< + subspace::DynamicServerWireBuffers>::Decode(received->data(), + received->size(), + response); + !status.ok()) { + return status; + } + std::vector fds; + if (absl::Status status = socket.ReceiveFds(fds); !status.ok()) { + return status; + } + return response; +} + +void Publish(subspace::Publisher &pub, const std::string &text) { + absl::StatusOr buffer = pub.GetMessageBuffer(); + ASSERT_OK(buffer); + memcpy(*buffer, text.data(), text.size()); + ASSERT_OK(pub.PublishMessage(static_cast(text.size()))); +} + +class StaticConfigTest : public ::testing::Test { +public: + static void SetUpTestSuite() { +#if defined(__ANDROID__) + char socket_name_template[] = "/data/local/tmp/subspaceXXXXXX"; // NOLINT +#else + char socket_name_template[] = "/tmp/subspaceXXXXXX"; // NOLINT +#endif + ::close(mkstemp(&socket_name_template[0])); + socket_ = &socket_name_template[0]; + + (void)pipe(server_pipe_); + + server_ = std::make_unique( + engine_, socket_, "", 0, 0, + /*local=*/true, server_pipe_[1], /*initial_ordinal=*/1, + /*wait_for_clients=*/true); + absl::StatusOr config = + subspace::ParseStaticChannelConfig(kConfig); + ASSERT_OK(config); + ASSERT_OK(server_->SetStaticChannelConfig(*std::move(config))); + + server_thread_ = std::thread([]() { + absl::Status s = server_->Run(); + if (!s.ok()) { + fprintf(stderr, "Error running Subspace server: %s\n", + s.ToString().c_str()); + exit(1); + } + }); + + char buf[8]; + (void)::read(server_pipe_[0], buf, 8); + } + + static void TearDownTestSuite() { + server_->Stop(); + + char buf[8]; + (void)::read(server_pipe_[0], buf, 8); + server_thread_.join(); + server_->CleanupAfterSession(); + (void)remove(socket_.c_str()); + } + + void SetUp() override { + signal(SIGPIPE, SIG_IGN); + ASSERT_OK(client_.Init(socket_)); + } + + subspace::Client &Client() { return client_; } + static const std::string &Socket() { return socket_; } + +private: + inline static subspace::async::RuntimeEngine engine_; + inline static std::string socket_; + inline static int server_pipe_[2]; + inline static std::unique_ptr server_; + inline static std::thread server_thread_; + + subspace::Client client_; +}; + +TEST(StaticConfigParseTest, ParsesValidConfig) { + absl::StatusOr config = + subspace::ParseStaticChannelConfig(kConfig); + ASSERT_OK(config); + EXPECT_EQ(2, config->multiplexers_size()); + EXPECT_EQ(7, config->channels_size()); + EXPECT_EQ(kBlobType, config->channels(6).type()); +} + +TEST(StaticConfigParseTest, TypeIsOpaqueBytes) { + // A quoted name and an opaque blob with non-text bytes are the same bytes + // field. + absl::StatusOr named = + subspace::ParseStaticChannelConfig( + R"pb(channels { name: "/n" slot_size: 64 num_slots: 4 type: "State" })pb"); + ASSERT_OK(named); + EXPECT_EQ("State", named->channels(0).type()); + + absl::StatusOr blob = + subspace::ParseStaticChannelConfig(R"pb( + channels { + name: "/b" + slot_size: 64 + num_slots: 4 + type: "\377\000State\200" + } + )pb"); + ASSERT_OK(blob); + EXPECT_EQ(kBlobType, blob->channels(0).type()); +} + +TEST(StaticConfigParseTest, RejectsInvalidConfigs) { + const std::vector> cases = { + {R"pb(channels { nme: "/x" })pb", "invalid protobuf text format"}, + {R"pb(channels { slot_size: 64 num_slots: 4 })pb", "needs a name"}, + {R"pb(channels { name: "/subspace/x" slot_size: 64 num_slots: 4 })pb", + "reserved prefix"}, + {R"pb(channels { name: "/x" slot_size: 64 num_slots: 4 } + channels { name: "/x" slot_size: 64 num_slots: 4 })pb", + "more than once"}, + {R"pb(multiplexers { name: "/x" slot_size: 64 num_slots: 4 } + channels { name: "/x" slot_size: 64 num_slots: 4 })pb", + "more than once"}, + {R"pb(channels { name: "/x" num_slots: 4 })pb", + "greater than 0"}, + {R"pb(channels { name: "/x" slot_size: 64 })pb", "greater than 0"}, + {R"pb(channels { name: "/x" slot_size: 64 num_slots: 4 + checksum_size: -1 })pb", + "checksum_size -1"}, + {R"pb(channels { name: "/x" slot_size: 64 num_slots: 4 + metadata_size: 100000 })pb", + "metadata_size 100000"}, + {R"pb(channels { name: "/x" slot_size: 64 num_slots: 4 vchan_id: 2 })pb", + "vchan_id but no mux"}, + {R"pb(channels { name: "/v" mux: "/m" })pb", + "isn't a configured multiplexer"}, + {R"pb(multiplexers { name: "/m" slot_size: 64 num_slots: 4 } + channels { name: "/v" mux: "/m" slot_size: 64 })pb", + "leave them unset"}, + {R"pb(multiplexers { name: "/m" slot_size: 64 num_slots: 4 } + channels { name: "/v" mux: "/m" use_split_buffers: true })pb", + "leave them unset"}, + {R"pb(multiplexers { name: "/m" slot_size: 64 num_slots: 4 } + channels { name: "/v" mux: "/m" vchan_id: 1023 })pb", + "vchan_id 1023"}, + {R"pb(multiplexers { name: "/m" slot_size: 64 num_slots: 4 } + channels { name: "/v1" mux: "/m" vchan_id: 1 } + channels { name: "/v2" mux: "/m" vchan_id: 1 })pb", + "reuses vchan_id 1"}, + }; + for (const auto &[text, error] : cases) { + absl::StatusOr config = + subspace::ParseStaticChannelConfig(text); + ASSERT_FALSE(config.ok()) << text; + EXPECT_THAT(config.status().message(), HasSubstr(error)) << text; + } +} + +// A file the test removes when it is destroyed. +struct TempConfig { + std::string path; + ~TempConfig() { + if (!path.empty()) { + ::unlink(path.c_str()); + } + } +}; + +TempConfig MakeTempConfig(const char *suffix) { +#if defined(__ANDROID__) + std::string pattern = "/data/local/tmp/static_cfgXXXXXX"; +#else + std::string pattern = "/tmp/static_cfgXXXXXX"; +#endif + std::vector name(pattern.begin(), pattern.end()); + name.push_back('\0'); + const int fd = ::mkstemp(name.data()); + EXPECT_GE(fd, 0); + if (fd >= 0) { + ::close(fd); + } + std::string path(name.data()); + std::string named = path + suffix; + EXPECT_EQ(0, ::rename(path.c_str(), named.c_str())); + return TempConfig{named}; +} + +bool WriteConfig(const std::string &path, const std::string &bytes) { + std::ofstream out(path, std::ios::binary); + out.write(bytes.data(), static_cast(bytes.size())); + return out.good(); +} + +TEST(StaticConfigParseTest, ExtensionSelectsTextOrWire) { + absl::StatusOr parsed = + subspace::ParseStaticChannelConfig(kConfig); + ASSERT_OK(parsed); + std::string wire; + ASSERT_TRUE(parsed->SerializeToString(&wire)); + + TempConfig text = MakeTempConfig(".textproto"); + TempConfig wire_file = MakeTempConfig(".pb"); + TempConfig binpb = MakeTempConfig(".BINPB"); + TempConfig other = MakeTempConfig(".cfg"); + ASSERT_FALSE(text.path.empty()); + ASSERT_TRUE(WriteConfig(text.path, kConfig)); + ASSERT_TRUE(WriteConfig(wire_file.path, wire)); + ASSERT_TRUE(WriteConfig(binpb.path, wire)); + ASSERT_TRUE(WriteConfig(other.path, kConfig)); + + absl::StatusOr from_text = + subspace::ReadStaticChannelConfig(text.path); + ASSERT_OK(from_text); + EXPECT_EQ(kBlobType, from_text->channels(6).type()); + + absl::StatusOr from_wire = + subspace::ReadStaticChannelConfig(wire_file.path); + ASSERT_OK(from_wire); + EXPECT_EQ(kBlobType, from_wire->channels(6).type()); + + absl::StatusOr from_binpb = + subspace::ReadStaticChannelConfig(binpb.path); + ASSERT_OK(from_binpb); + EXPECT_EQ(parsed->channels_size(), from_binpb->channels_size()); + + absl::StatusOr from_cfg = + subspace::ReadStaticChannelConfig(other.path); + ASSERT_OK(from_cfg); + + ASSERT_TRUE(WriteConfig(text.path, wire)); + EXPECT_THAT(subspace::ReadStaticChannelConfig(text.path), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("text format"))); + ASSERT_TRUE(WriteConfig(wire_file.path, kConfig)); + EXPECT_THAT(subspace::ReadStaticChannelConfig(wire_file.path), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("wire format"))); +} + +TEST(StaticConfigParseTest, WireFormatRejectsUnknownFields) { + absl::StatusOr parsed = + subspace::ParseStaticChannelConfig(kConfig); + ASSERT_OK(parsed); + std::string wire; + ASSERT_TRUE(parsed->SerializeToString(&wire)); + // Field 999, varint 1: a field this build doesn't have. + wire.append("\xb8\x3e\x01", 3); + + TempConfig file = MakeTempConfig(".pb"); + ASSERT_TRUE(WriteConfig(file.path, wire)); + EXPECT_THAT(subspace::ReadStaticChannelConfig(file.path), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("unknown field"))); +} + +TEST(StaticConfigParseTest, ReadMissingFile) { + absl::StatusOr config = + subspace::ReadStaticChannelConfig("/no/such/static_config.textproto"); + ASSERT_FALSE(config.ok()); + EXPECT_THAT(config.status().message(), HasSubstr("can't open")); +} + +TEST_F(StaticConfigTest, ChannelsExistBeforeAnyClient) { + absl::StatusOr info = + Client().GetChannelInfo("/static/a"); + ASSERT_OK(info); + EXPECT_EQ(256u, info->slot_size); + EXPECT_EQ(8, info->num_slots); + EXPECT_EQ("A", info->type); + EXPECT_EQ(0, info->num_publishers); + EXPECT_EQ(0, info->num_subscribers); + + absl::StatusOr vchan_info = + Client().GetChannelInfo("/static/v2"); + ASSERT_OK(vchan_info); + EXPECT_EQ(128u, vchan_info->slot_size); + EXPECT_EQ(8, vchan_info->num_slots); + EXPECT_EQ("Mux", vchan_info->type); + + absl::StatusOr blob_info = + Client().GetChannelInfo("/static/blob"); + ASSERT_OK(blob_info); + EXPECT_EQ(kBlobType, blob_info->type); +} + +TEST_F(StaticConfigTest, OpaqueTypeMustMatch) { + absl::StatusOr mismatch = Client().CreatePublisher( + "/static/blob", + ServerDefined().SetType(std::string("\xff\x00Other\x80", 8))); + ASSERT_FALSE(mismatch.ok()); + EXPECT_THAT(mismatch.status().message(), + HasSubstr("Inconsistent channel types")); + + absl::StatusOr pub = Client().CreatePublisher( + "/static/blob", ServerDefined().SetType(kBlobType)); + ASSERT_OK(pub); + EXPECT_EQ(kBlobType, std::string(pub->TypeView())); +} + +TEST_F(StaticConfigTest, SubscriberBeforePublisher) { + absl::StatusOr sub = + Client().CreateSubscriber("/static/a"); + ASSERT_OK(sub); + EXPECT_EQ(8, sub->NumSlots()); + + absl::StatusOr pub = + Client().CreatePublisher("/static/a", ServerDefined()); + ASSERT_OK(pub); + Publish(*pub, "hello"); + + absl::StatusOr msg = sub->ReadMessage(); + ASSERT_OK(msg); + ASSERT_EQ(5, msg->length); + EXPECT_EQ("hello", + std::string(static_cast(msg->buffer), msg->length)); +} + +TEST_F(StaticConfigTest, SplitBuffersCreatedByServer) { + absl::StatusOr sub = + Client().CreateSubscriber("/static/split"); + ASSERT_OK(sub); + EXPECT_TRUE(sub->UsesSplitBuffers()); + + absl::StatusOr pub = + Client().CreatePublisher("/static/split", ServerDefined()); + ASSERT_OK(pub); + EXPECT_TRUE(pub->UsesSplitBuffers()); + EXPECT_EQ(256, pub->SlotSize()); + EXPECT_EQ(4, pub->NumSlots()); + for (int i = 0; i < 6; i++) { + std::string text = absl::StrFormat("split %d", i); + Publish(*pub, text); + absl::StatusOr msg = sub->ReadMessage(); + ASSERT_OK(msg); + EXPECT_EQ(text, + std::string(static_cast(msg->buffer), msg->length)); + } +} + +TEST_F(StaticConfigTest, SplitBufferVirtualChannel) { + absl::StatusOr sub = Client().CreateSubscriber( + "/static/sv", subspace::SubscriberOptions().SetMux("/static/split_mux")); + ASSERT_OK(sub); + EXPECT_TRUE(sub->UsesSplitBuffers()); + + absl::StatusOr pub = Client().CreatePublisher( + "/static/sv", ServerDefined().SetMux("/static/split_mux")); + ASSERT_OK(pub); + EXPECT_TRUE(pub->UsesSplitBuffers()); + Publish(*pub, "vchan"); + absl::StatusOr msg = sub->ReadMessage(); + ASSERT_OK(msg); + EXPECT_EQ("vchan", + std::string(static_cast(msg->buffer), msg->length)); +} + +TEST_F(StaticConfigTest, PublishersMustBeServerDefined) { + // A publisher that gives the configured layout itself is still rejected. + absl::StatusOr pub = Client().CreatePublisher( + "/static/a", 256, 8, subspace::PublisherOptions().SetFixedSize(true)); + ASSERT_FALSE(pub.ok()); + EXPECT_THAT(pub.status().message(), HasSubstr("must set server_defined")); + + // The client rejects layout options alongside server_defined. + for (const subspace::PublisherOptions &options : + {ServerDefined().SetSlotSize(256), ServerDefined().SetNumSlots(8), + ServerDefined().SetFixedSize(true), ServerDefined().SetChecksumSize(4), + ServerDefined().SetMetadataSize(16), + ServerDefined().SetSubscriberQueueArenaSize(4096), + ServerDefined().SetUseSplitBuffers(true)}) { + pub = Client().CreatePublisher("/static/a", options); + ASSERT_FALSE(pub.ok()); + EXPECT_EQ(absl::StatusCode::kInvalidArgument, pub.status().code()); + EXPECT_THAT(pub.status().message(), HasSubstr("is server defined")); + } +} + +TEST_F(StaticConfigTest, ServerRejectsLayoutFromServerDefinedPublishers) { + toolbelt::UnixSocket socket; + ASSERT_OK(socket.Connect(Socket())); + subspace::phaser::Request init; + init.mutable_init()->set_client_name("raw"); + ASSERT_OK(Transact(socket, init)); + + const std::vector< + std::pair> + cases = { + {"num_slots", + [](subspace::phaser::CreatePublisherRequest *r) { r->set_num_slots(8); }}, + {"slot_size", + [](subspace::phaser::CreatePublisherRequest *r) { r->set_slot_size(256); }}, + {"fixed_size", + [](subspace::phaser::CreatePublisherRequest *r) { + r->set_is_fixed_size(true); + }}, + {"checksum_size", + [](subspace::phaser::CreatePublisherRequest *r) { + r->set_checksum_size(4); + }}, + {"metadata_size", + [](subspace::phaser::CreatePublisherRequest *r) { + r->set_metadata_size(16); + }}, + {"subscriber_queue_arena_size", + [](subspace::phaser::CreatePublisherRequest *r) { + r->set_subscriber_queue_arena_size(4096); + }}, + {"use_split_buffers", + [](subspace::phaser::CreatePublisherRequest *r) { + r->set_use_split_buffers(true); + }}, + }; + for (const auto &[field, set] : cases) { + subspace::phaser::Request req; + subspace::phaser::CreatePublisherRequest *cmd = req.mutable_create_publisher(); + cmd->set_channel_name("/static/a"); + cmd->set_server_defined(true); + cmd->set_publisher_id(-1); + set(cmd); + absl::StatusOr response = Transact(socket, req); + ASSERT_OK(response); + EXPECT_THAT(response->create_publisher().error(), + HasSubstr("can't set " + field)) + << field; + } +} + +TEST_F(StaticConfigTest, PublisherTakesLayoutFromServer) { + absl::StatusOr pub = + Client().CreatePublisher("/static/meta", ServerDefined()); + ASSERT_OK(pub); + EXPECT_EQ(64, pub->SlotSize()); + EXPECT_EQ(4, pub->NumSlots()); + EXPECT_EQ(4, pub->ChecksumSize()); + EXPECT_EQ(16, pub->MetadataSize()); + EXPECT_FALSE(pub->UsesSplitBuffers()); + // The layout is fixed, so the publisher can't grow its slots. + EXPECT_FALSE(pub->GetMessageBuffer(128).ok()); + + // A second publisher is accepted after the first has created the + // channel's buffers. + absl::StatusOr first = + Client().CreatePublisher("/static/a", ServerDefined()); + ASSERT_OK(first); + Publish(*first, "x"); + absl::StatusOr second = + Client().CreatePublisher("/static/a", ServerDefined()); + ASSERT_OK(second); +} + +TEST_F(StaticConfigTest, UnconfiguredChannels) { + // server_defined is only for a channel the config created. + absl::StatusOr defined = + Client().CreatePublisher("/not/configured", ServerDefined()); + ASSERT_FALSE(defined.ok()); + EXPECT_THAT(defined.status().message(), + HasSubstr("isn't in the static channel config")); + + // A virtual channel on a configured multiplexer must be configured too + // when the publisher asks the server for the layout. + defined = Client().CreatePublisher("/static/v9", + ServerDefined().SetMux("/static/mux")); + ASSERT_FALSE(defined.ok()); + EXPECT_THAT(defined.status().message(), + HasSubstr("isn't in the static channel config")); + + // A subscriber can open a channel the config doesn't list, before any + // publisher has created it. + absl::StatusOr early = + Client().CreateSubscriber("/dynamic/early"); + ASSERT_OK(early); + + // A standard publisher that specifies the layout creates the channel. + absl::StatusOr pub = + Client().CreatePublisher("/dynamic/a", 128, 4); + ASSERT_OK(pub); + absl::StatusOr sub = + Client().CreateSubscriber("/dynamic/a"); + ASSERT_OK(sub); + Publish(*pub, "dynamic"); + absl::StatusOr msg = sub->ReadMessage(); + ASSERT_OK(msg); + EXPECT_EQ("dynamic", + std::string(static_cast(msg->buffer), msg->length)); + + absl::StatusOr later = + Client().CreatePublisher("/dynamic/early", 64, 4); + ASSERT_OK(later); + Publish(*later, "after"); + msg = early->ReadMessage(); + ASSERT_OK(msg); + EXPECT_EQ("after", + std::string(static_cast(msg->buffer), msg->length)); +} + +TEST_F(StaticConfigTest, ChannelsOutliveTheirUsers) { + { + absl::StatusOr pub = + Client().CreatePublisher("/static/a", ServerDefined()); + ASSERT_OK(pub); + absl::StatusOr sub = + Client().CreateSubscriber("/static/a"); + ASSERT_OK(sub); + Publish(*pub, "before"); + } + absl::StatusOr info = + Client().GetChannelInfo("/static/a"); + ASSERT_OK(info); + EXPECT_EQ(0, info->num_publishers); + EXPECT_EQ(0, info->num_subscribers); + EXPECT_EQ(256u, info->slot_size); + EXPECT_EQ(8, info->num_slots); + + absl::StatusOr pub = + Client().CreatePublisher("/static/a", ServerDefined()); + ASSERT_OK(pub); + absl::StatusOr sub = + Client().CreateSubscriber("/static/a"); + ASSERT_OK(sub); + Publish(*pub, "after"); + absl::StatusOr msg = + sub->ReadMessage(subspace::ReadMode::kReadNewest); + ASSERT_OK(msg); + EXPECT_EQ("after", + std::string(static_cast(msg->buffer), msg->length)); +} + +TEST_F(StaticConfigTest, VirtualChannels) { + absl::StatusOr sub = Client().CreateSubscriber( + "/static/v1", subspace::SubscriberOptions().SetMux("/static/mux")); + ASSERT_OK(sub); + EXPECT_EQ(3, sub->VirtualChannelId()); + + absl::StatusOr pub = Client().CreatePublisher( + "/static/v1", ServerDefined().SetMux("/static/mux")); + ASSERT_OK(pub); + EXPECT_EQ(128, pub->SlotSize()); + EXPECT_EQ(8, pub->NumSlots()); + EXPECT_EQ(3, pub->VirtualChannelId()); + Publish(*pub, "virtual"); + + absl::StatusOr msg = sub->ReadMessage(); + ASSERT_OK(msg); + EXPECT_EQ("virtual", + std::string(static_cast(msg->buffer), msg->length)); + + // Publishers on other virtual channels of the multiplexer share its + // buffers, so they are also fixed size. + absl::StatusOr other = Client().CreatePublisher( + "/static/v2", ServerDefined().SetMux("/static/mux")); + ASSERT_OK(other); + EXPECT_EQ(7, other->VirtualChannelId()); +} + +TEST_F(StaticConfigTest, ServerChannelsArePublished) { + for (const char *name : + {"/subspace/ChannelDirectory", "/subspace/Statistics"}) { + int num_publishers = 0; + for (int i = 0; i < 100 && num_publishers == 0; i++) { + absl::StatusOr info = + Client().GetChannelInfo(name); + if (info.ok()) { + num_publishers = info->num_publishers; + } + if (num_publishers == 0) { + std::this_thread::sleep_for(std::chrono::milliseconds(50)); + } + } + EXPECT_EQ(1, num_publishers) << name; + } +} + +} // namespace + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/server/tunnel.cc b/server/tunnel.cc index 0e63a1bf..09f423b5 100644 --- a/server/tunnel.cc +++ b/server/tunnel.cc @@ -1,4 +1,4 @@ -// Copyright 2026 General Motors LLC +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. @@ -444,9 +444,7 @@ TunnelManager::PlanIngress(const Handshake &handshake, options.SetBridge(true) .SetForTunnel(true) .SetReliable(transport.is_reliable()) - .SetType(handshake.channel_type()) - .SetChecksumSize(plan.checksum_size) - .SetMetadataSize(plan.metadata_size); + .SetType(handshake.channel_type()); // The publisher must agree with the channel as it exists here or the server // refuses it. Message sizes don't depend on the handshake: the publisher @@ -455,6 +453,24 @@ TunnelManager::PlanIngress(const Handshake &handshake, if (!server_->IsPublicChannel(channel)) { channel = nullptr; } + if (channel != nullptr && channel->IsStatic()) { + // The config owns the layout, so this publisher must not send slot, + // checksum, metadata or split-buffer settings. + options.SetServerDefined(true).SetUseSplitBuffers(false); + if (!channel->Type().empty() && + channel->Type() != handshake.channel_type()) { + options.SetType(""); + } + if (channel->IsVirtual()) { + VirtualChannel *vchan = static_cast(channel); + options.SetMux(vchan->GetMux()->Name()) + .SetVchanId(vchan->GetVirtualChannelId()); + } + return plan; + } + + options.SetChecksumSize(plan.checksum_size) + .SetMetadataSize(plan.metadata_size); if (channel == nullptr) { auto route = receive_routes_.find(plan.topic); if (route != receive_routes_.end() && !route->second.mux.empty()) { diff --git a/server/tunnel.h b/server/tunnel.h index f235529e..0ad2c265 100644 --- a/server/tunnel.h +++ b/server/tunnel.h @@ -1,4 +1,4 @@ -// Copyright 2026 General Motors LLC +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/server/tunnel_config.cc b/server/tunnel_config.cc index 2cff4ea5..d2b6a005 100644 --- a/server/tunnel_config.cc +++ b/server/tunnel_config.cc @@ -1,9 +1,11 @@ -// Copyright 2026 General Motors LLC +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. #include "server/tunnel_config.h" +#include "server/config_format.h" + #include "absl/container/flat_hash_set.h" #include "absl/strings/str_format.h" #include "absl/strings/str_join.h" @@ -94,7 +96,7 @@ absl::StatusOr ParseTunnelConfig(std::string_view text, } absl::StatusOr LoadTunnelConfig(const std::string &path) { - std::ifstream in(path); + std::ifstream in(path, std::ios::binary); if (!in) { return absl::NotFoundError(absl::StrFormat( "can't open tunnel configuration %s: %s", path, strerror(errno))); @@ -105,7 +107,19 @@ absl::StatusOr LoadTunnelConfig(const std::string &path) { return absl::InternalError( absl::StrFormat("can't read tunnel configuration %s", path)); } - return ParseTunnelConfig(text.str(), path); + if (ConfigFileIsText(path)) { + return ParseTunnelConfig(text.str(), path); + } + TunnelConfig config; + if (!config.ParseFromString(text.str())) { + return absl::InvalidArgumentError( + absl::StrFormat("%s: invalid protobuf wire format", path)); + } + if (HasUnknownFields(config)) { + return absl::InvalidArgumentError(absl::StrFormat( + "%s: unknown field in protobuf wire format", path)); + } + return config; } std::string TunnelDeviceName(const TunnelConfig &config, diff --git a/server/tunnel_config.h b/server/tunnel_config.h index 658f7542..99704a26 100644 --- a/server/tunnel_config.h +++ b/server/tunnel_config.h @@ -1,4 +1,4 @@ -// Copyright 2026 General Motors LLC +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. @@ -19,7 +19,8 @@ inline constexpr int kDefaultTunnelDiscoveryRefreshSecs = 5; absl::StatusOr ParseTunnelConfig(std::string_view text, std::string_view source); -// Reads and parses the tunnel configuration file at `path`. +// Reads and parses the tunnel configuration file at `path`. A name ending +// in .pb or .binpb is protobuf wire format. Any other name is text format. absl::StatusOr LoadTunnelConfig(const std::string &path); // The device name this server announces to tunnel peers: the configured diff --git a/server/tunnel_config_test.cc b/server/tunnel_config_test.cc index b59bb821..151d0c23 100644 --- a/server/tunnel_config_test.cc +++ b/server/tunnel_config_test.cc @@ -1,4 +1,4 @@ -// Copyright 2026 General Motors LLC +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. @@ -225,5 +225,72 @@ TEST(TunnelConfigTest, LoadsFile) { EXPECT_THAT(LoadTunnelConfig(path), StatusIs(absl::StatusCode::kNotFound)); } +TEST(TunnelConfigTest, ExtensionSelectsTextOrWire) { + absl::StatusOr parsed = ParseTunnelConfig(kGoodConfig, "text"); + ASSERT_THAT(parsed, IsOk()); + std::string wire; + ASSERT_TRUE(parsed->SerializeToString(&wire)); + + char text_template[] = TUNNEL_TEST_TMP "/tunnel_cfg_textXXXXXX"; + char wire_template[] = TUNNEL_TEST_TMP "/tunnel_cfg_wireXXXXXX"; + const int text_fd = mkstemp(text_template); + const int wire_fd = mkstemp(wire_template); + ASSERT_GE(text_fd, 0); + ASSERT_GE(wire_fd, 0); + close(text_fd); + close(wire_fd); + const std::string text_path = std::string(text_template) + ".textproto"; + const std::string wire_path = std::string(wire_template) + ".pb"; + ASSERT_EQ(0, rename(text_template, text_path.c_str())); + ASSERT_EQ(0, rename(wire_template, wire_path.c_str())); + + { + std::ofstream out(text_path, std::ios::binary); + out << kGoodConfig; + std::ofstream wire_out(wire_path, std::ios::binary); + wire_out.write(wire.data(), static_cast(wire.size())); + } + absl::StatusOr from_text = LoadTunnelConfig(text_path); + ASSERT_THAT(from_text, IsOk()); + EXPECT_EQ(from_text->device_name(), "alpha"); + absl::StatusOr from_wire = LoadTunnelConfig(wire_path); + ASSERT_THAT(from_wire, IsOk()); + EXPECT_EQ(from_wire->device_name(), "alpha"); + + { + std::ofstream out(wire_path, std::ios::binary); + out << kGoodConfig; + } + EXPECT_THAT(LoadTunnelConfig(wire_path), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("wire format"))); + unlink(text_path.c_str()); + unlink(wire_path.c_str()); +} + +TEST(TunnelConfigTest, WireFormatRejectsUnknownFields) { + absl::StatusOr parsed = ParseTunnelConfig(kGoodConfig, "text"); + ASSERT_THAT(parsed, IsOk()); + std::string wire; + ASSERT_TRUE(parsed->SerializeToString(&wire)); + // Field 999, varint 1: a field this build doesn't have. + wire.append("\xb8\x3e\x01", 3); + + char path[] = TUNNEL_TEST_TMP "/tunnel_cfg_unknownXXXXXX"; + const int fd = mkstemp(path); + ASSERT_GE(fd, 0); + close(fd); + const std::string named = std::string(path) + ".pb"; + ASSERT_EQ(0, rename(path, named.c_str())); + { + std::ofstream out(named, std::ios::binary); + out.write(wire.data(), static_cast(wire.size())); + } + EXPECT_THAT(LoadTunnelConfig(named), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("unknown field"))); + unlink(named.c_str()); +} + } // namespace } // namespace subspace diff --git a/server/tunnel_fake_peer_test.cc b/server/tunnel_fake_peer_test.cc index a0bdde12..1b8ab696 100644 --- a/server/tunnel_fake_peer_test.cc +++ b/server/tunnel_fake_peer_test.cc @@ -1,4 +1,4 @@ -// Copyright 2026 General Motors LLC +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/server/tunnel_protocol.cc b/server/tunnel_protocol.cc index 94fceefe..9f774792 100644 --- a/server/tunnel_protocol.cc +++ b/server/tunnel_protocol.cc @@ -1,4 +1,4 @@ -// Copyright 2026 General Motors LLC +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/server/tunnel_protocol.h b/server/tunnel_protocol.h index 0cfb9279..7c1c2dcd 100644 --- a/server/tunnel_protocol.h +++ b/server/tunnel_protocol.h @@ -1,4 +1,4 @@ -// Copyright 2026 General Motors LLC +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/server/tunnel_protocol_test.cc b/server/tunnel_protocol_test.cc index 176b27e4..da47047f 100644 --- a/server/tunnel_protocol_test.cc +++ b/server/tunnel_protocol_test.cc @@ -1,4 +1,4 @@ -// Copyright 2026 General Motors LLC +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/server/tunnel_stress_test.cc b/server/tunnel_stress_test.cc index 701713c6..a4eaff28 100644 --- a/server/tunnel_stress_test.cc +++ b/server/tunnel_stress_test.cc @@ -1,4 +1,4 @@ -// Copyright 2026 General Motors LLC +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/server/tunnel_test.cc b/server/tunnel_test.cc index 946e5ed2..7425858d 100644 --- a/server/tunnel_test.cc +++ b/server/tunnel_test.cc @@ -1,4 +1,4 @@ -// Copyright 2026 General Motors LLC +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/server/tunnel_test_util.h b/server/tunnel_test_util.h index b4689396..72501c82 100644 --- a/server/tunnel_test_util.h +++ b/server/tunnel_test_util.h @@ -1,4 +1,4 @@ -// Copyright 2026 General Motors LLC +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information.