From 26154351d2178b9466bc6259e0c5613aca7a94b1 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Thu, 8 Oct 2026 18:18:41 -0700 Subject: [PATCH 01/21] Add a static channel config to the server subspace_server --channel_config=FILE reads a StaticChannelConfig in protobuf text format and creates its channels and multiplexers before the server accepts any clients, so a subscriber that starts first gets the full channel layout instead of a placeholder. With a config loaded, clients can use only the configured channels and the server's own /subspace/ChannelDirectory and /subspace/Statistics. The configured channels stay when they have no users, and their layout is fixed: publishers must be fixed size and match the configured slot size, number of slots, checksum size and metadata size. Channels recovered from a shadow must match the config. A multiplexer with no publishers now reports its slot size. --- CHANGELOG.md | 9 + README.md | 33 ++++ proto/subspace.proto | 37 ++++ server/Android.bp | 1 + server/BUILD.bazel | 21 +++ server/CMakeLists.txt | 2 + server/client_handler.cc | 51 ++++++ server/main.cc | 20 +++ server/server.cc | 135 +++++++++++++- server/server.h | 15 ++ server/server_channel.cc | 2 +- server/server_channel.h | 5 + server/static_config.cc | 157 ++++++++++++++++ server/static_config.h | 31 ++++ server/static_config_test.cc | 335 +++++++++++++++++++++++++++++++++++ 15 files changed, 849 insertions(+), 5 deletions(-) create mode 100644 server/static_config.cc create mode 100644 server/static_config.h create mode 100644 server/static_config_test.cc diff --git a/CHANGELOG.md b/CHANGELOG.md index 72d5e24d..04bf5fdc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,15 @@ ## Unreleased +### Static Channel Config +- `subspace_server --channel_config=FILE` reads a `StaticChannelConfig` in + protobuf text format and creates its channels and multiplexers before the + server accepts clients. Clients can then use only those channels and the + server's own, the channels stay when they have no users, and their layout + is fixed: publishers must be fixed size and match the configured slot + size, number of slots, checksum size and metadata size. +- A multiplexer with no publishers now reports its slot size. + ### Stuck Subscriber Warning - A subscriber now logs an error when a message has been waiting for 5 seconds that it can't read because it already holds `max_active_messages` diff --git a/README.md b/README.md index ff7c8436..de4f2d4c 100644 --- a/README.md +++ b/README.md @@ -2008,6 +2008,38 @@ 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`) in 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 } +``` + +The server creates every configured channel before it accepts clients, so a +subscriber that starts first gets the full channel layout instead of a +placeholder. With a config loaded: + +- Clients can use only the configured channels and the server's own + `/subspace/ChannelDirectory` and `/subspace/Statistics`. Creating a + publisher or subscriber for any other channel fails. +- Configured channels stay for the life of the server, including when they + have no publishers or subscribers. +- The layout is fixed. Publishers must be fixed size (`SetFixedSize(true)`) + and match the configured slot size, number of slots, checksum size and + metadata size. +- A channel on a multiplexer takes its slot size, number of slots, type and + prefix layout 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. + ## Shadow Server (Crash Recovery) Subspace supports a **shadow process** that mirrors the server's channel, @@ -2083,6 +2115,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` text format file. See [Static Channel Config](#static-channel-config). | ### Shadow Flags diff --git a/proto/subspace.proto b/proto/subspace.proto index bcfc681b..8741ba4d 100644 --- a/proto/subspace.proto +++ b/proto/subspace.proto @@ -647,3 +647,40 @@ 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 and +// metadata size. +message StaticMultiplexer { + string name = 1; + int32 slot_size = 2; + int32 num_slots = 3; + string type = 4; + int32 checksum_size = 5; // 0 means the default of 4 bytes. + int32 metadata_size = 6; +} + +message StaticChannel { + string name = 1; + // A channel on a multiplexer leaves slot_size, num_slots, type, + // checksum_size and metadata_size unset and takes them from the + // multiplexer. + int32 slot_size = 2; + int32 num_slots = 3; + string 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 StaticChannelConfig { + repeated StaticMultiplexer multiplexers = 1; + repeated StaticChannel channels = 2; +} diff --git a/server/Android.bp b/server/Android.bp index 410318f3..e770d9c8 100644 --- a/server/Android.bp +++ b/server/Android.bp @@ -10,6 +10,7 @@ cc_library_static { "client_handler.cc", "server_channel.cc", "shadow_replicator.cc", + "static_config.cc", ], export_include_dirs: ["."], include_dirs: ["external/subspace"], diff --git a/server/BUILD.bazel b/server/BUILD.bazel index 50f0db9e..61df9b31 100644 --- a/server/BUILD.bazel +++ b/server/BUILD.bazel @@ -9,6 +9,7 @@ cc_library( "client_handler.cc", "server_channel.cc", "shadow_replicator.cc", + "static_config.cc", ], hdrs = [ "server.h", @@ -16,16 +17,20 @@ cc_library( "server_channel.h", "plugin.h", "shadow_replicator.h", + "static_config.h", ], deps = [ "//common:subspace_common", "//common/async:async", "//client:subspace_client", + "//proto:subspace_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", @@ -61,6 +66,22 @@ cc_binary( }), ) +cc_test( + name = "static_config_test", + size = "small", + srcs = ["static_config_test.cc"], + deps = [ + ":server", + "//client:subspace_client", + "//client:test_fixture", + "@abseil-cpp//absl/status", + "@abseil-cpp//absl/status:status_matchers", + "@abseil-cpp//absl/status:statusor", + "@googletest//:gtest", + "@coroutines//:co", + ], +) + cc_test( name = "server_test", size = "small", diff --git a/server/CMakeLists.txt b/server/CMakeLists.txt index 0bb18283..c4945fc2 100644 --- a/server/CMakeLists.txt +++ b/server/CMakeLists.txt @@ -7,6 +7,8 @@ add_library(libserver STATIC server_channel.h shadow_replicator.cc shadow_replicator.h + static_config.cc + static_config.h server.cc server.h plugin.h diff --git a/server/client_handler.cc b/server/client_handler.cc index b42b0ad1..cbf733f6 100644 --- a/server/client_handler.cc +++ b/server/client_handler.cc @@ -11,6 +11,22 @@ namespace subspace { namespace { +// With a static channel config, clients can't create channels other than the +// server's own. Sets the response error and returns false for one they +// can't create. +template +bool StaticConfigAllowsNewChannel(const Server &server, + const std::string &channel_name, + Response *response) { + if (!server.HasStaticChannelConfig() || + Server::IsServerChannelName(channel_name)) { + return true; + } + response->set_error(absl::StrFormat( + "Channel %s isn't in the static channel config", channel_name)); + return false; +} + ClientBufferAllocatorKind FromProtoAllocator(ClientBufferAllocator allocator) { switch (allocator) { case CLIENT_BUFFER_ALLOCATOR_ANDROID_MEMFD: @@ -441,6 +457,37 @@ void ClientHandler::HandleCreatePublisher( absl::StrFormat("No such channel %s", req.channel_name())); return; } + if (channel == nullptr && + !StaticConfigAllowsNewChannel(*server_, req.channel_name(), response)) { + return; + } + if (channel != nullptr && channel->IsStatic()) { + // Resizing happens in the publisher, so only a fixed size publisher keeps + // the configured layout. + if (!req.is_fixed_size()) { + response->set_error(absl::StrFormat( + "Publishers on static channel %s must be fixed size", + req.channel_name())); + return; + } + if (req.slot_size() != channel->SlotSize() || + req.num_slots() != channel->NumSlots()) { + response->set_error(absl::StrFormat( + "Static channel %s has %d slots of %d bytes, not %d slots of %d " + "bytes", + req.channel_name(), channel->NumSlots(), channel->SlotSize(), + req.num_slots(), req.slot_size())); + return; + } + if (cs != channel->ChecksumSize() || ms != channel->MetadataSize()) { + response->set_error(absl::StrFormat( + "Static channel %s has checksum_size %d and metadata_size %d, not " + "%d and %d", + req.channel_name(), channel->ChecksumSize(), channel->MetadataSize(), + cs, ms)); + return; + } + } if (channel == nullptr) { server_->logger_.Log(toolbelt::LogLevel::kDebug, "Publisher %s is creating new channel %s with size " @@ -876,6 +923,10 @@ void ClientHandler::HandleCreateSubscriber( return; } if (channel == nullptr) { + if (!StaticConfigAllowsNewChannel(*server_, req.channel_name(), + response)) { + return; + } // No channel exists, map an empty channel. server_->logger_.Log( toolbelt::LogLevel::kDebug, diff --git a/server/main.cc b/server/main.cc index 13a29ad0..68bb1e15 100644 --- a/server/main.cc +++ b/server/main.cc @@ -5,6 +5,7 @@ #include "absl/flags/flag.h" #include "absl/flags/parse.h" #include "server.h" +#include "server/static_config.h" #include #include #include @@ -92,6 +93,10 @@ 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 in protobuf text format. The server " + "creates its channels at startup, fixes their layout and allows no " + "others (empty = channels are created on demand)"); // Look up this host's local vsock context id (CID) so we can advertise it to // bridge peers. Only meaningful on Linux with vsock support. @@ -271,6 +276,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); + } + } + #if SUBSPACE_CORO_BACKEND == SUBSPACE_CORO_BACKEND_ASIO int num_asio_threads = absl::GetFlag(FLAGS_num_asio_threads); if (num_asio_threads < 1) { diff --git a/server/server.cc b/server/server.cc index d64ea278..bbd51983 100644 --- a/server/server.cc +++ b/server/server.cc @@ -10,6 +10,7 @@ #include "client_handler.h" #include "common/split_buffer.h" #include "proto/subspace.pb.h" +#include "server/static_config.h" #include "toolbelt/clock.h" #include "toolbelt/hexdump.h" #include "toolbelt/sockets.h" @@ -41,6 +42,9 @@ bool ShouldClosePluginsOnShutdown() { return close_plugins_on_shutdown; } static constexpr int kTelemetrySlotSize = 1024; static constexpr int kTelemetryNumSlots = 32; +static constexpr char kChannelDirectoryChannel[] = "/subspace/ChannelDirectory"; +static constexpr char kStatisticsChannel[] = "/subspace/Statistics"; + static const ServerChannel *SplitBufferOptionsChannel( const ServerChannel *channel) { if (channel->IsVirtual()) { @@ -1006,6 +1010,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) { @@ -1223,6 +1233,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 @@ -1383,6 +1394,121 @@ Server::CreateChannel(const std::string &channel_name, int64_t slot_size, return channel; } +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; +} + +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); + } + + 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); + } + 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(); +} + uint64_t Server::GetVirtualMemoryUsage() const { uint64_t size = 0; for (const auto &channel : channels_) { @@ -2153,7 +2279,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); } } @@ -2182,7 +2308,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()); } } @@ -2207,7 +2334,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)); @@ -2270,7 +2397,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)); diff --git a/server/server.h b/server/server.h index 28e3ec9b..cfa7aeea 100644 --- a/server/server.h +++ b/server/server.h @@ -30,6 +30,7 @@ #include #include #include +#include #include namespace subspace { @@ -111,6 +112,15 @@ 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, and from then on clients can use only those channels + // and the server's own. 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_) { @@ -299,6 +309,10 @@ 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(); + // Public iteration excludes internal telemetry transport channels. void ForeachChannel(std::function func); bool IsPublicChannel(const ServerChannel *channel) const { @@ -500,6 +514,7 @@ class Server { std::vector> plugins_; toolbelt::TriggerFd shutdown_trigger_fd_; std::string machine_name_; + std::optional static_config_; bool publish_server_channels_ = true; BridgePortRange bridge_port_range_; bool bridge_ports_fallback_to_ephemeral_ = false; diff --git a/server/server_channel.cc b/server/server_channel.cc index b5cfa031..80f8ff59 100644 --- a/server/server_channel.cc +++ b/server/server_channel.cc @@ -1156,7 +1156,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(); diff --git a/server/server_channel.h b/server/server_channel.h index b2e1e782..0a06b5d4 100644 --- a/server/server_channel.h +++ b/server/server_channel.h @@ -238,6 +238,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, @@ -534,6 +538,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; diff --git a/server/static_config.cc b/server/static_config.cc new file mode 100644 index 00000000..2407e072 --- /dev/null +++ b/server/static_config.cc @@ -0,0 +1,157 @@ +// Copyright 2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +#include "server/static_config.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 + +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) { + return ConfigError(absl::StrFormat( + "%s is on mux %s and takes its slot_size, num_slots, type, " + "checksum_size and metadata_size 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; +} + +absl::StatusOr +ReadStaticChannelConfig(const std::string &filename) { + std::ifstream in(filename); + if (!in) { + return absl::NotFoundError(absl::StrFormat( + "Static channel config: can't open %s", filename)); + } + std::stringstream text; + text << in.rdbuf(); + absl::StatusOr config = + ParseStaticChannelConfig(text.str()); + 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..e3fe8d02 --- /dev/null +++ b/server/static_config.h @@ -0,0 +1,31 @@ +// 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 text format file. +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..f6ac933c --- /dev/null +++ b/server/static_config_test.cc @@ -0,0 +1,335 @@ +// 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, they are the only channels +// clients can use, and their layout is fixed. + +#include "client/test_fixture.h" + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "server/static_config.h" +#include +#include +#include +#include +#include +#include + +namespace { + +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 } +)pb"; + +subspace::PublisherOptions FixedSize() { + return subspace::PublisherOptions().SetFixedSize(true); +} + +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_; } + +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(1, config->multiplexers_size()); + EXPECT_EQ(4, config->channels_size()); +} + +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" 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; + } +} + +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); +} + +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", 256, 8, FixedSize()); + 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, UnconfiguredChannelsAreRejected) { + absl::StatusOr pub = + Client().CreatePublisher("/not/configured", 64, 4, FixedSize()); + ASSERT_FALSE(pub.ok()); + EXPECT_THAT(pub.status().message(), + HasSubstr("isn't in the static channel config")); + + absl::StatusOr sub = + Client().CreateSubscriber("/not/configured"); + ASSERT_FALSE(sub.ok()); + EXPECT_THAT(sub.status().message(), + HasSubstr("isn't in the static channel config")); + + // A virtual channel on a configured multiplexer must be configured too. + pub = Client().CreatePublisher("/static/v9", 128, 8, + FixedSize().SetMux("/static/mux")); + ASSERT_FALSE(pub.ok()); + EXPECT_THAT(pub.status().message(), + HasSubstr("isn't in the static channel config")); +} + +TEST_F(StaticConfigTest, PublisherLayoutMustMatch) { + absl::StatusOr pub = Client().CreatePublisher( + "/static/a", 256, 8, subspace::PublisherOptions()); + ASSERT_FALSE(pub.ok()); + EXPECT_THAT(pub.status().message(), HasSubstr("must be fixed size")); + + for (auto [slot_size, num_slots] : + std::vector>{{512, 8}, {128, 8}, {256, 16}, + {256, 4}}) { + pub = Client().CreatePublisher("/static/a", slot_size, num_slots, + FixedSize()); + ASSERT_FALSE(pub.ok()) << slot_size << "/" << num_slots; + EXPECT_THAT(pub.status().message(), + HasSubstr("has 8 slots of 256 bytes")); + } + + pub = Client().CreatePublisher("/static/meta", 64, 4, FixedSize()); + ASSERT_FALSE(pub.ok()); + EXPECT_THAT(pub.status().message(), + HasSubstr("checksum_size 4 and metadata_size 16, not 4 and 0")); + pub = Client().CreatePublisher("/static/meta", 64, 4, + FixedSize().SetMetadataSize(16)); + ASSERT_OK(pub); + + // A matching second publisher is accepted after the first has created the + // channel's buffers. + absl::StatusOr first = + Client().CreatePublisher("/static/a", 256, 8, FixedSize()); + ASSERT_OK(first); + Publish(*first, "x"); + absl::StatusOr second = + Client().CreatePublisher("/static/a", 256, 8, FixedSize()); + ASSERT_OK(second); +} + +TEST_F(StaticConfigTest, ChannelsOutliveTheirUsers) { + { + absl::StatusOr pub = + Client().CreatePublisher("/static/a", 256, 8, FixedSize()); + 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", 256, 8, FixedSize()); + 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", 256, 8, FixedSize().SetMux("/static/mux")); + ASSERT_FALSE(pub.ok()); + EXPECT_THAT(pub.status().message(), HasSubstr("has 8 slots of 128 bytes")); + + pub = Client().CreatePublisher("/static/v1", 128, 8, + FixedSize().SetMux("/static/mux")); + ASSERT_OK(pub); + 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)); +} + +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(); +} From f06c6ae5e4375a19c8c9869e2e7c5f3b54eefa50 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Fri, 9 Oct 2026 11:27:53 -0700 Subject: [PATCH 02/21] Add the ASIL client asil_client/ is a C++17 client for safety-related software. It shares unreliable, fixed-size 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 makes no heap allocations. - Publishers support checksums, metadata and activation messages. Subscribers support kReadNext and kReadNewest, dropped message counts, checksum checking and activation messages. - The server handshake is behind the ServerConnection interface. PhaserServerConnection implements the standard protocol with phaser messages in fixed buffers, sent and received in protobuf wire format, so the server sees the same bytes as from the other clients. - Bazel, CMake and Soong build phaser and generate subspace_phaser from subspace.proto. Android CMake cross-compiles take a host protoc-gen-phaser in PHASER_PLUGIN_EXECUTABLE. - Bazel moves to Abseil 20250814.1, protobuf 33.4, cpp_toolbelt 2.1.6 and phaser 2.1.3, with cpp_toolbelt and phaser pinned by git_override until they are in the Bazel Central Registry. CMake uses the same commits. - layout_test checks the ASIL client's view of shared memory against common/channel.h. asil_client_test exchanges messages with the standard client in both directions, checks that setup and teardown make no heap allocations, and checks that an oversized request leaves the connection usable. It is skipped on memfd builds, which the ASIL client doesn't support yet. --- .cursor/skills/subspace-builds/SKILL.md | 5 +- .github/workflows/ci.yml | 7 +- Android.bp | 58 ++ CHANGELOG.md | 18 + CMakeLists.txt | 16 +- MODULE.bazel | 28 +- README.md | 4 + asil_client/Android.bp | 36 ++ asil_client/BUILD.bazel | 88 +++ asil_client/CMakeLists.txt | 53 ++ asil_client/asil_client_test.cc | 691 ++++++++++++++++++++++++ asil_client/bitset.h | 101 ++++ asil_client/channel_memory.cc | 565 +++++++++++++++++++ asil_client/channel_memory.h | 114 ++++ asil_client/checksum.cc | 44 ++ asil_client/checksum.h | 19 + asil_client/client.cc | 44 ++ asil_client/client.h | 75 +++ asil_client/error.cc | 47 ++ asil_client/error.h | 50 ++ asil_client/layout_test.cc | 197 +++++++ asil_client/phaser_connection.cc | 537 ++++++++++++++++++ asil_client/phaser_connection.h | 76 +++ asil_client/publisher.cc | 408 ++++++++++++++ asil_client/publisher.h | 98 ++++ asil_client/server_connection.h | 111 ++++ asil_client/shm_layout.h | 236 ++++++++ asil_client/subscriber.cc | 396 ++++++++++++++ asil_client/subscriber.h | 111 ++++ asil_client/unique_fd.h | 80 +++ docs/android.md | 34 +- docs/asil-client.md | 206 +++++++ external/phaser/Android.bp.example | 59 ++ proto/BUILD.bazel | 13 + proto/CMakeLists.txt | 23 + 35 files changed, 4627 insertions(+), 21 deletions(-) create mode 100644 asil_client/Android.bp create mode 100644 asil_client/BUILD.bazel create mode 100644 asil_client/CMakeLists.txt create mode 100644 asil_client/asil_client_test.cc create mode 100644 asil_client/bitset.h create mode 100644 asil_client/channel_memory.cc create mode 100644 asil_client/channel_memory.h create mode 100644 asil_client/checksum.cc create mode 100644 asil_client/checksum.h create mode 100644 asil_client/client.cc create mode 100644 asil_client/client.h create mode 100644 asil_client/error.cc create mode 100644 asil_client/error.h create mode 100644 asil_client/layout_test.cc create mode 100644 asil_client/phaser_connection.cc create mode 100644 asil_client/phaser_connection.h create mode 100644 asil_client/publisher.cc create mode 100644 asil_client/publisher.h create mode 100644 asil_client/server_connection.h create mode 100644 asil_client/shm_layout.h create mode 100644 asil_client/subscriber.cc create mode 100644 asil_client/subscriber.h create mode 100644 asil_client/unique_fd.h create mode 100644 docs/asil-client.md create mode 100644 external/phaser/Android.bp.example diff --git a/.cursor/skills/subspace-builds/SKILL.md b/.cursor/skills/subspace-builds/SKILL.md index 2515a740..31a17abd 100644 --- a/.cursor/skills/subspace-builds/SKILL.md +++ b/.cursor/skills/subspace-builds/SKILL.md @@ -68,7 +68,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 \ @@ -76,7 +76,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/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2960d0a4..9b21da80 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -470,10 +470,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: | @@ -483,7 +483,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 d518f1aa..a453a483 100644 --- a/Android.bp +++ b/Android.bp @@ -47,3 +47,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 04bf5fdc..4cb601be 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,24 @@ size, number of slots, checksum size and metadata size. - A multiplexer with no publishers now reports its slot size. +### ASIL Client +- `asil_client/` is a new C++17 client for safety-related software. It + shares unreliable, fixed-size 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 in protobuf wire format, so the handshake makes no heap + allocations either. See `docs/asil-client.md`. +- Bazel, CMake and Soong build phaser and generate `subspace_phaser` from + `subspace.proto`. Android CMake cross-compiles take a host + `protoc-gen-phaser` in `PHASER_PLUGIN_EXECUTABLE`. +- Abseil 20250814.1, protobuf 33.4, cpp_toolbelt 2.1.6 and phaser 2.1.3 in + the Bazel build. CMake uses cpp_toolbelt 2.1.6. + ### Stuck Subscriber Warning - A subscriber now logs an error when a message has been waiting for 5 seconds that it can't read because it already holds `max_active_messages` diff --git a/CMakeLists.txt b/CMakeLists.txt index d506b5d4..4c56c196 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -144,7 +144,8 @@ endif() FetchContent_Declare( cpp_toolbelt GIT_REPOSITORY https://github.com/dallison/cpp_toolbelt.git - GIT_TAG 2.1.2 + # cpp_toolbelt 2.1.6, as in the git_override in MODULE.bazel. + GIT_TAG 86b45cdd3da46a97a4476be2f2a61909677284a2 CMAKE_ARGS -DCMAKE_OSX_ARCHITECTURES="${CMAKE_OSX_ARCHITECTURES}" ) @@ -165,6 +166,18 @@ 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 ASIL client talks to the server with phaser messages held in fixed +# buffers. 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 2.1.3, as in the git_override in MODULE.bazel. + GIT_TAG 3d5eca68b74da5ad982a2768b9b54da728fd17f7 +) +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 @@ -256,6 +269,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 2c54ab4f..eb0332cd 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -11,9 +11,16 @@ 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 = "abseil-cpp", version = "20250814.1") bazel_dep(name = "googletest", version = "1.17.0") -bazel_dep(name = "protobuf", version = "33.2") +bazel_dep(name = "protobuf", version = "33.4") + +# Phaser asks for protobuf 34.1, whose rules_android dependency breaks the +# Android SDK toolchain here. +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") @@ -21,7 +28,22 @@ bazel_dep(name = "rules_pkg", version = "1.0.1") bazel_dep(name = "rules_android_ndk", version = "0.1.5") bazel_dep(name = "zlib", version = "1.3.1.bcr.5") bazel_dep(name = "coroutines", version = "3.3.5") -bazel_dep(name = "cpp_toolbelt", version = "2.1.3") +bazel_dep(name = "cpp_toolbelt", version = "2.1.6") +bazel_dep(name = "phaser", version = "2.1.3") + +# Remove once cpp_toolbelt 2.1.6 and phaser 2.1.3 are in the Bazel Central +# Registry. +git_override( + module_name = "cpp_toolbelt", + commit = "86b45cdd3da46a97a4476be2f2a61909677284a2", + remote = "https://github.com/dallison/cpp_toolbelt.git", +) + +git_override( + module_name = "phaser", + commit = "3d5eca68b74da5ad982a2768b9b54da728fd17f7", + remote = "https://github.com/dallison/phaser.git", +) bazel_dep(name = "rules_python", version = "1.7.0") # Boost (for asio_rpc) diff --git a/README.md b/README.md index de4f2d4c..4844e80c 100644 --- a/README.md +++ b/README.md @@ -50,6 +50,7 @@ See the file docs/subspace.pdf for full documentation. Additional documentation - [Slot Sizes](docs/slot-sizes.md) - [Channel Limit](docs/max-channels.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) @@ -2040,6 +2041,9 @@ placeholder. With a config loaded: - 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, diff --git a/asil_client/Android.bp b/asil_client/Android.bp new file mode 100644 index 00000000..7706cb1d --- /dev/null +++ b/asil_client/Android.bp @@ -0,0 +1,36 @@ +// Copyright 2026 David Allison +// 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", + "checksum.cc", + "client.cc", + "error.cc", + "publisher.cc", + "subscriber.cc", + ], + include_dirs: ["external/subspace"], + cppflags: ["-fno-exceptions"], + rtti: false, +} + +// 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..dab9dc9f --- /dev/null +++ b/asil_client/BUILD.bazel @@ -0,0 +1,88 @@ +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", + "checksum.cc", + "client.cc", + "error.cc", + "publisher.cc", + "subscriber.cc", + ], + hdrs = [ + "bitset.h", + "channel_memory.h", + "checksum.h", + "client.h", + "error.h", + "publisher.h", + "server_connection.h", + "shm_layout.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:max_channels_setting"], +) + +# The standard server handshake, using Phaser messages in fixed buffers and +# protobuf wire format. +cc_library( + name = "phaser_connection", + srcs = ["phaser_connection.cc"], + hdrs = ["phaser_connection.h"], + copts = [ + "-fno-exceptions", + "-fno-rtti", + ], + deps = [ + ":asil_client", + "//proto:subspace_phaser", + ], +) + +cc_test( + name = "layout_test", + size = "small", + srcs = ["layout_test.cc"], + deps = [ + ":asil_client", + "//client:subspace_client", + "//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", + ], +) diff --git a/asil_client/CMakeLists.txt b/asil_client/CMakeLists.txt new file mode 100644 index 00000000..8bff0e59 --- /dev/null +++ b/asil_client/CMakeLists.txt @@ -0,0 +1,53 @@ +# 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 + checksum.cc + client.cc + error.cc + publisher.cc + subscriber.cc +) +target_compile_options(subspace_asil_client PRIVATE -fno-exceptions -fno-rtti) +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 server connection needs the phaser messages, which proto/ skips when +# cross-compiling without a host phaser plugin. +if(NOT TARGET subspace_phaser) + message(STATUS "Skipping the ASIL server connection: subspace_phaser is not available.") + return() +endif() + +# 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 +) diff --git a/asil_client/asil_client_test.cc b/asil_client/asil_client_test.cc new file mode 100644 index 00000000..50d86e88 --- /dev/null +++ b/asil_client/asil_client_test.cc @@ -0,0 +1,691 @@ +// Copyright 2026 David Allison +// 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/subscriber.h" +#include "server/static_config.h" +#include +#include +#include +#include +#include +#include + +namespace { +// Counts heap allocations made by this thread while counting is set. +thread_local bool counting_allocations = false; +thread_local int allocations = 0; +} // namespace + +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); } + +namespace { + +namespace asil = ::subspace::asil; +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/no_alloc" slot_size: 64 num_slots: 4 } + channels { name: "/asil/oversize" slot_size: 64 num_slots: 4 } +)pb"; + +subspace::PublisherOptions FixedSize() { + return subspace::PublisherOptions().SetFixedSize(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; +} + +class AsilClientTest : 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 { +#if ASIL_SHM_MODE == ASIL_SHM_MEMFD + GTEST_SKIP() << "The ASIL client does not support the memfd backend"; +#endif + 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")); + } + + subspace::Client &Std() { return std_client_; } + asil::Client &Asil() { return asil_client_; } + asil::PhaserServerConnection &Connection() { return connection_; } + +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 std_client_; + asil::PhaserServerConnection connection_; + asil::Client asil_client_; +}; + +TEST_F(AsilClientTest, AsilPublisherStandardSubscriber) { + absl::StatusOr sub = + Std().CreateSubscriber("/asil/to_std"); + ASSERT_OK(sub); + + asil::Publisher pub; + asil::PublisherOptions options = AsilPubOptions(256, 8); + 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", 256, 8, FixedSize()); + 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", AsilPubOptions(64, 4), 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", AsilPubOptions(64, 4), 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 = AsilPubOptions(128, 4); + 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", 128, 4, FixedSize().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; + asil::PublisherOptions options = AsilPubOptions(64, 8); + options.metadata_size = 16; + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/asil/meta", options, 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", 64, 8, FixedSize().SetMetadataSize(16)); + 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", 64, 8, FixedSize()); + 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", 64, 4, FixedSize()); + 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", AsilPubOptions(64, 4), 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 = AsilPubOptions(64, 4); + 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", AsilPubOptions(64, 4), 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", 64, 4, FixedSize()); + 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) { + asil::Publisher pub; + EXPECT_EQ(asil::Error::kServerRejected, + Asil().CreatePublisher("/asil/reject", AsilPubOptions(128, 4), pub)); + EXPECT_THAT(Asil().LastServerError(), HasSubstr("has 4 slots of 64 bytes")); + EXPECT_FALSE(pub.IsOpen()); + + EXPECT_EQ(asil::Error::kServerRejected, + Asil().CreatePublisher("/asil/unknown", AsilPubOptions(64, 4), pub)); + EXPECT_THAT(Asil().LastServerError(), + HasSubstr("isn't in the static channel config")); + + asil::Subscriber sub; + EXPECT_EQ(asil::Error::kServerRejected, + Asil().CreateSubscriber("/asil/unknown", {}, sub)); + + EXPECT_EQ(asil::Error::kInvalidArgument, + Asil().CreatePublisher("/asil/reject", AsilPubOptions(0, 4), pub)); + EXPECT_EQ(asil::Error::kCapacityExceeded, + Asil().CreatePublisher(std::string(300, 'x').c_str(), + AsilPubOptions(64, 4), pub)); + + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/asil/reject", AsilPubOptions(64, 4), pub)); + EXPECT_EQ(asil::Error::kAlreadyInitialized, + Asil().CreatePublisher("/asil/reject", AsilPubOptions(64, 4), pub)); + EXPECT_EQ(asil::Error::kMessageTooLarge, pub.Publish(65)); + + asil::Client uninitialized; + asil::Publisher other; + EXPECT_EQ(asil::Error::kNotInitialized, + uninitialized.CreatePublisher("/asil/reject", + AsilPubOptions(64, 4), other)); +} + +TEST_F(AsilClientTest, VirtualChannelsAreUnsupported) { + asil::Subscriber sub; + const asil::Error e = Asil().CreateSubscriber("/asil/v1", {}, sub); + EXPECT_NE(asil::Error::kOk, e); + EXPECT_FALSE(sub.IsOpen()); +} + +TEST_F(AsilClientTest, CloseRemovesFromServer) { + asil::Publisher pub; + asil::Subscriber sub; + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/asil/close", AsilPubOptions(64, 4), 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", AsilPubOptions(64, 4), 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; + allocations = 0; + counting_allocations = true; + int *volatile counted = new int(1); + counting_allocations = false; + delete counted; + ASSERT_EQ(1, allocations); + + allocations = 0; + counting_allocations = true; + const asil::Error pub_error = + Asil().CreatePublisher("/asil/no_alloc", AsilPubOptions(64, 4), 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(); + counting_allocations = false; + + 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, allocations); +} + +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_TRUE(Connection().Connected()); + + asil::TriggerFdList subscribers; + reply.subscriber_triggers = &subscribers; + EXPECT_EQ(asil::Error::kOk, + Connection().GetTriggers("/asil/oversize", reply)); +} + +} // namespace + +int main(int argc, char **argv) { + testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} diff --git a/asil_client/bitset.h b/asil_client/bitset.h new file mode 100644 index 00000000..fcdeac82 --- /dev/null +++ b/asil_client/bitset.h @@ -0,0 +1,101 @@ +// Copyright 2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +#pragma once + +#include "asil_client/shm_layout.h" + +#include +#include +#include + +namespace subspace { +namespace asil { + +// A view of an AtomicBitSet in shared memory. The memory orders match +// common/atomic_bitset.h. The bit count stored in shared memory is ignored; +// the view uses the count the server reported for the channel. +class BitsetView { +public: + BitsetView() = default; + BitsetView(void *bitset, int num_bits) + : words_(reinterpret_cast *>( + static_cast(bitset) + sizeof(size_t))), + 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(shm::BitsToWords(num_bits_)); } + + std::atomic *words_ = nullptr; + int num_bits_ = 0; +}; + +} // namespace asil +} // namespace subspace diff --git a/asil_client/channel_memory.cc b/asil_client/channel_memory.cc new file mode 100644 index 00000000..747d33ea --- /dev/null +++ b/asil_client/channel_memory.cc @@ -0,0 +1,565 @@ +// Copyright 2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +#include "asil_client/channel_memory.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace subspace { +namespace asil { +namespace internal { + +namespace { + +constexpr size_t kMaxCcbSize = size_t{1} << 30; + +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); +} + +#if ASIL_SHM_MODE != ASIL_SHM_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 ASIL_SHM_MODE == ASIL_SHM_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's length is the buffer's true size. Only the first +// publisher sets it. +Error CreateShadowFile(const char *shadow_file, uint64_t size) { + const int fd = ::open(shadow_file, O_RDWR | O_CREAT | O_CLOEXEC, 0666); + if (fd < 0) { + return Error::kSharedMemoryError; + } + struct stat st; + Error e = Error::kOk; + if (::fstat(fd, &st) != 0) { + e = Error::kSharedMemoryError; + } else if (st.st_size == 0 && + ::ftruncate(fd, static_cast(size)) != 0) { + e = Error::kSharedMemoryError; + } + (void)::close(fd); + return e; +} +#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 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) { + if (ccb_ != nullptr) { + return Error::kAlreadyInitialized; + } + if (num_slots <= 0) { + // The channel has no layout yet. Static channels always have one. + return Error::kUnsupported; + } + const size_t ccb_size = shm::CcbSize(num_slots, 0); + 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); + ccb_size_ = ccb_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() { + if (buffer_ != nullptr) { + (void)::munmap(buffer_, buffer_size_); + buffer_ = nullptr; + buffer_size_ = 0; + slot_size_ = 0; + } + 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; + num_slots_ = 0; +} + +Error ChannelMemory::BufferName(const char *channel_name, uint64_t session_id, + char (&out)[kMaxChannelNameLength + 64]) const { + char sanitized[kMaxChannelNameLength + 1]; + if (Error e = CopyName(channel_name, sanitized); e != Error::kOk) { + return e; + } + for (char *p = sanitized; *p != '\0'; p++) { + if (*p == '/') { + *p = '.'; + } + } +#if ASIL_SHM_MODE == ASIL_SHM_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(session_id), sanitized, 0); + if (n < 0 || static_cast(n) >= sizeof(out)) { + return Error::kCapacityExceeded; + } + return Error::kOk; +} + +Error ChannelMemory::MapBuffer(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 < 100; 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; + } + buffer_ = static_cast(p); + buffer_size_ = size; + slot_size_ = static_cast((size - prefixes) / + static_cast(num_slots_)); + return Error::kOk; +} + +Error ChannelMemory::CreateOrAttachBuffer(const char *channel_name, + uint64_t session_id, + int64_t slot_size, int32_t user_id, + int32_t group_id) { + if (ccb_ == nullptr) { + return Error::kNotInitialized; + } + if (buffer_ != nullptr) { + return Error::kAlreadyInitialized; + } + int num_buffers = ccb_->num_buffers.load(std::memory_order_relaxed); + if (num_buffers > 1) { + // The channel has been resized. + return Error::kUnsupported; + } + const uint64_t full_size = + static_cast(num_slots_) * + (static_cast(slot_size) + static_cast(prefix_size_)); + + char name[kMaxChannelNameLength + 64]; + if (Error e = BufferName(channel_name, session_id, name); e != Error::kOk) { + return e; + } + const bool root = ::getuid() == 0; + uint64_t size = full_size; +#if ASIL_SHM_MODE == ASIL_SHM_POSIX + if (Error e = CreateShadowFile(name, full_size); e != Error::kOk) { + return e; + } + char shm_name[64]; + if (Error e = PosixShmName(name, shm_name); e != Error::kOk) { + return e; + } + int fd = OpenShm(shm_name, O_RDWR | O_CREAT | O_EXCL); + if (fd >= 0) { + if (::ftruncate(fd, static_cast(full_size)) != 0 || + ::chmod(name, 0777) != 0 || + (root && ::chown(name, static_cast(user_id), + static_cast(group_id)) != 0)) { + (void)::close(fd); + return Error::kSharedMemoryError; + } + } else if (errno == EEXIST) { + fd = OpenShm(shm_name, O_RDWR); + struct stat st; + if (fd < 0 || ::stat(name, &st) != 0) { + if (fd >= 0) { + (void)::close(fd); + } + return Error::kSharedMemoryError; + } + size = static_cast(st.st_size); + } else { + return Error::kSharedMemoryError; + } +#elif ASIL_SHM_MODE == ASIL_SHM_LINUX + int fd = OpenShm(name, O_RDWR | O_CREAT | O_EXCL); + if (fd >= 0) { + char path[kMaxChannelNameLength + 80]; + (void)std::snprintf(path, sizeof(path), "/dev/shm/%s", name); + if (::ftruncate(fd, static_cast(full_size)) != 0 || + ::chmod(path, 0777) != 0 || + (root && ::chown(path, static_cast(user_id), + static_cast(group_id)) != 0)) { + (void)::close(fd); + return Error::kSharedMemoryError; + } + } else if (errno == EEXIST) { + fd = OpenShm(name, O_RDWR); + if (fd < 0) { + return Error::kSharedMemoryError; + } + size = 0; + for (int attempt = 0; attempt < 100 && size == 0; attempt++) { + struct stat st; + if (::fstat(fd, &st) != 0) { + (void)::close(fd); + return Error::kSharedMemoryError; + } + size = static_cast(st.st_size); + if (size == 0) { + SleepMillisecond(); + } + } + } else { + return Error::kSharedMemoryError; + } +#else + (void)root; + (void)size; + (void)user_id; + (void)group_id; + // Memfd buffers are passed between clients by the server. + return Error::kUnsupported; +#endif +#if ASIL_SHM_MODE != ASIL_SHM_MEMFD + const Error e = MapBuffer(fd, size, PROT_READ | PROT_WRITE); + (void)::close(fd); + if (e != Error::kOk) { + return e; + } + if (slot_size_ != slot_size) { + Unmap(); + return Error::kLayoutMismatch; + } + bcb_->sizes[0].store(size, std::memory_order_relaxed); + while (!ccb_->num_buffers.compare_exchange_strong( + num_buffers, 1, std::memory_order_release, std::memory_order_relaxed)) { + if (num_buffers > 1) { + Unmap(); + return Error::kUnsupported; + } + } + return Error::kOk; +#endif +} + +Error ChannelMemory::AttachBuffer(const char *channel_name, + uint64_t session_id) { + if (ccb_ == nullptr) { + return Error::kNotInitialized; + } + if (buffer_ != nullptr) { + return Error::kOk; + } + const int num_buffers = ccb_->num_buffers.load(std::memory_order_acquire); + if (num_buffers == 0) { + return Error::kOk; + } + if (num_buffers > 1) { + return Error::kUnsupported; + } + char name[kMaxChannelNameLength + 64]; + if (Error e = BufferName(channel_name, session_id, name); e != Error::kOk) { + return e; + } +#if ASIL_SHM_MODE == ASIL_SHM_POSIX + char shm_name[64]; + if (Error e = PosixShmName(name, shm_name); e != Error::kOk) { + return e; + } + const int fd = OpenShm(shm_name, O_RDONLY); + struct stat st; + if (fd < 0 || ::stat(name, &st) != 0) { + if (fd >= 0) { + (void)::close(fd); + } + return Error::kSharedMemoryError; + } +#elif ASIL_SHM_MODE == ASIL_SHM_LINUX + const int fd = OpenShm(name, O_RDONLY); + struct stat st; + if (fd < 0 || ::fstat(fd, &st) != 0) { + if (fd >= 0) { + (void)::close(fd); + } + return Error::kSharedMemoryError; + } +#else + return Error::kUnsupported; +#endif +#if ASIL_SHM_MODE != ASIL_SHM_MEMFD + Error e = Error::kOk; + if (st.st_size > 0) { + e = MapBuffer(fd, static_cast(st.st_size), PROT_READ); + } + (void)::close(fd); + return e; +#endif +} + +shm::MessageSlot *ChannelMemory::Slot(int id) const { + auto *slots = reinterpret_cast( + reinterpret_cast(ccb_) + sizeof(shm::ChannelControlBlock)); + return &slots[id]; +} + +shm::MessagePrefix *ChannelMemory::Prefix(const shm::MessageSlot *slot) const { + const int64_t stride = prefix_size_ + shm::Aligned64(slot_size_); + return reinterpret_cast(buffer_ + stride * slot->id); +} + +char *ChannelMemory::Payload(const shm::MessageSlot *slot) const { + return reinterpret_cast(Prefix(slot)) + prefix_size_; +} + +BitsetView ChannelMemory::RetiredSlots() const { + return BitsetView(reinterpret_cast(ccb_) + + shm::RetiredSlotsOffset(num_slots_), + num_slots_); +} + +BitsetView ChannelMemory::FreeSlots() const { + return BitsetView(reinterpret_cast(ccb_) + + shm::FreeSlotsOffset(num_slots_), + num_slots_); +} + +BitsetView ChannelMemory::AvailableSlots(int sub_id) const { + return BitsetView(reinterpret_cast(ccb_) + + shm::AvailableSlotsOffset(num_slots_, sub_id), + num_slots_); +} + +BitsetView ChannelMemory::Subscribers() const { + return BitsetView(&ccb_->subscribers, shm::kMaxSlotOwners); +} + +shm::AvailableSlotQueueIndex *ChannelMemory::QueueIndex() const { + return reinterpret_cast( + reinterpret_cast(ccb_) + shm::SlotQueueIndexOffset(num_slots_)); +} + +int ChannelMemory::NumSubscribers(int vchan_id) const { + const shm::SubscriberCounter &counter = ccb_->num_subs; + for (;;) { + const uint64_t before = counter.sequence.load(std::memory_order_acquire); + if ((before & 1) != 0) { + // A server died while updating the count. + return shm::kMaxSlotOwners; + } + const int mux_count = counter.counts[0].load(std::memory_order_relaxed); + const int count = + vchan_id == -1 + ? mux_count + : mux_count + + counter.counts[vchan_id + 1].load(std::memory_order_relaxed); + if (counter.sequence.load(std::memory_order_acquire) == before) { + return count; + } + } +} + +uint64_t ChannelMemory::CleanupGeneration(int vchan_id) const { + const uint64_t mux_generation = + ccb_->subscriber_cleanup_generation[0].load(std::memory_order_acquire); + if (vchan_id == -1) { + return mux_generation; + } + return mux_generation + ccb_->subscriber_cleanup_generation[vchan_id + 1].load( + std::memory_order_acquire); +} + +bool ChannelMemory::AtomicIncRefCount(shm::MessageSlot *slot, int inc, + uint64_t ordinal, int vchan_id, + bool retire, bool *retired) { + if (retired != nullptr) { + *retired = false; + } + ordinal &= shm::kOrdinalMask; + for (;;) { + uint64_t ref = slot->refs.load(std::memory_order_relaxed); + if ((ref & shm::kPubOwned) != 0) { + return false; + } + const uint64_t ref_ordinal = (ref >> shm::kOrdinalShift) & shm::kOrdinalMask; + const int ref_vchan_id = shm::RefsVchanId(ref); + if (ref_ordinal != 0 && ordinal != 0 && + (ref_ordinal != ordinal || ref_vchan_id != vchan_id)) { + return false; + } + uint64_t refs = ref & shm::kRefCountMask; + const uint64_t reliable_refs = + (ref >> shm::kReliableRefCountShift) & shm::kRefCountMask; + if (inc < 0 && refs == 0) { + return true; + } + refs = static_cast(static_cast(refs) + inc); + uint64_t retired_refs = + (ref >> shm::kRetiredRefsShift) & shm::kRetiredRefsMask; + if (retire) { + retired_refs++; + } + const uint64_t new_ref = + shm::BuildRefsBitField(ref_ordinal, ref_vchan_id, retired_refs) | + (reliable_refs << shm::kReliableRefCountShift) | refs; + if (slot->refs.compare_exchange_weak(ref, new_ref, + std::memory_order_acq_rel, + std::memory_order_relaxed)) { + if (retire && refs == 0 && reliable_refs == 0 && + retired_refs >= + static_cast(NumSubscribers(ref_vchan_id)) && + RetiredSlots().SetWasClear(slot->id) && retired != nullptr) { + *retired = true; + } + return true; + } + } +} + +bool ChannelMemory::TryRetireSlot(shm::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 & shm::kPubOwned) != 0) { + return false; + } + const uint64_t ref_count = refs & shm::kRefCountMask; + const uint64_t reliable_ref_count = + (refs >> shm::kReliableRefCountShift) & shm::kRefCountMask; + const uint64_t retired_refs = + (refs >> shm::kRetiredRefsShift) & shm::kRetiredRefsMask; + if (ref_count != 0 || reliable_ref_count != 0 || + retired_refs < + static_cast(NumSubscribers(shm::RefsVchanId(refs)))) { + return false; + } + return RetiredSlots().SetWasClear(slot->id); +} + +void ChannelMemory::TriggerRetirement(const TriggerFdList &triggers, + int32_t slot_id) const { + if (triggers.Size() == 0) { + return; + } + if (slot_id >= 0 && slot_id < num_slots_ && + (Slot(slot_id)->flags.load(std::memory_order_relaxed) & + shm::kMessageIsActivation) != 0) { + 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..ae5bea78 --- /dev/null +++ b/asil_client/channel_memory.h @@ -0,0 +1,114 @@ +// Copyright 2026 David Allison +// 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/bitset.h" +#include "asil_client/error.h" +#include "asil_client/server_connection.h" +#include "asil_client/shm_layout.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); + +// Copies name into a fixed buffer. +Error CopyName(const char *name, char (&out)[kMaxChannelNameLength + 1]); + +class ChannelMemory { +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. + Error Map(shm::SystemControlBlock *scb, int ccb_fd, int bcb_fd, + int num_slots, int32_t checksum_size, int32_t metadata_size); + void Unmap(); + + // Publishers create the channel's buffer, or attach to the buffer another + // publisher created. The buffer's slot size must be slot_size. + Error CreateOrAttachBuffer(const char *channel_name, uint64_t session_id, + int64_t slot_size, int32_t user_id, + int32_t group_id); + // Subscribers attach to the buffer read-only once a publisher has made it. + // Returns kOk without a buffer when there isn't one yet. + Error AttachBuffer(const char *channel_name, uint64_t session_id); + bool HasBuffer() const { return buffer_ != nullptr; } + + int NumSlots() const { return num_slots_; } + int64_t SlotSize() const { return slot_size_; } + int32_t ChecksumSize() const { return checksum_size_; } + int32_t MetadataSize() const { return metadata_size_; } + + shm::ChannelControlBlock *Ccb() const { return ccb_; } + shm::BufferControlBlock *Bcb() const { return bcb_; } + const shm::ChannelCounters &Counters(int channel_id) const { + return scb_->counters[channel_id]; + } + + shm::MessageSlot *Slot(int id) const; + shm::MessagePrefix *Prefix(const shm::MessageSlot *slot) const; + char *Payload(const shm::MessageSlot *slot) const; + + BitsetView RetiredSlots() const; + BitsetView FreeSlots() const; + BitsetView AvailableSlots(int sub_id) const; + BitsetView Subscribers() const; + shm::AvailableSlotQueueIndex *QueueIndex() const; + + int NumSubscribers(int vchan_id) const; + uint64_t CleanupGeneration(int vchan_id) const; + + // Channel::AtomicIncRefCount. Sets *retired when this call retired the + // slot. + bool AtomicIncRefCount(shm::MessageSlot *slot, int inc, uint64_t ordinal, + int vchan_id, bool retire, bool *retired); + // Channel::TryRetireSlot. + bool TryRetireSlot(shm::MessageSlot *slot); + + // 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(const char *channel_name, uint64_t session_id, + char (&out)[kMaxChannelNameLength + 64]) const; + Error MapBuffer(int fd, uint64_t size, int prot); + + shm::SystemControlBlock *scb_ = nullptr; + shm::ChannelControlBlock *ccb_ = nullptr; + shm::BufferControlBlock *bcb_ = nullptr; + size_t ccb_size_ = 0; + int num_slots_ = 0; + int32_t checksum_size_ = 4; + int32_t metadata_size_ = 0; + int32_t prefix_size_ = 64; + + char *buffer_ = nullptr; + uint64_t buffer_size_ = 0; + int64_t slot_size_ = 0; +}; + +} // namespace internal +} // namespace asil +} // namespace subspace diff --git a/asil_client/checksum.cc b/asil_client/checksum.cc new file mode 100644 index 00000000..b0ecbaba --- /dev/null +++ b/asil_client/checksum.cc @@ -0,0 +1,44 @@ +// Copyright 2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +#include "asil_client/checksum.h" + +#include + +namespace subspace { +namespace asil { + +namespace { + +#if defined(__x86_64__) && defined(__SSE4_2__) +constexpr uint32_t kPolynomial = 0x82F63B78; // CRC32C. +#else +constexpr uint32_t kPolynomial = 0xEDB88320; // IEEE 802.3. +#endif + +constexpr std::array MakeTable() { + std::array table = {}; + for (uint32_t i = 0; i < 256; i++) { + uint32_t crc = i; + for (int bit = 0; bit < 8; bit++) { + crc = (crc & 1) != 0 ? (crc >> 1) ^ kPolynomial : crc >> 1; + } + table[i] = crc; + } + return table; +} + +constexpr std::array kTable = MakeTable(); + +} // namespace + +uint32_t Crc32(uint32_t crc, const uint8_t *data, size_t length) { + for (size_t i = 0; i < length; i++) { + crc = (crc >> 8) ^ kTable[(crc ^ data[i]) & 0xFF]; + } + return crc; +} + +} // namespace asil +} // namespace subspace diff --git a/asil_client/checksum.h b/asil_client/checksum.h new file mode 100644 index 00000000..689687a0 --- /dev/null +++ b/asil_client/checksum.h @@ -0,0 +1,19 @@ +// Copyright 2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +#pragma once + +#include +#include + +namespace subspace { +namespace asil { + +// The CRC32 that the standard client puts in message prefixes. x86-64 builds +// with SSE4.2 use the CRC32C polynomial; all other builds use the IEEE 802.3 +// polynomial. Pass 0xFFFFFFFF as the first crc and invert the final result. +uint32_t Crc32(uint32_t crc, const uint8_t *data, size_t length); + +} // namespace asil +} // namespace subspace diff --git a/asil_client/client.cc b/asil_client/client.cc new file mode 100644 index 00000000..3d97ab53 --- /dev/null +++ b/asil_client/client.cc @@ -0,0 +1,44 @@ +// Copyright 2026 David Allison +// 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..b7cef1c7 --- /dev/null +++ b/asil_client/client.h @@ -0,0 +1,75 @@ +// Copyright 2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +// A Subspace client for safety-related software. +// +// The client publishes and reads messages on unreliable, fixed-size channels, +// 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. Memory is allocated only by the +// ServerConnection while it talks to the server; publishing and reading +// messages allocate nothing. +// +// 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); + } + + // Why the server rejected the last request that returned kServerRejected. + 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..edf14209 --- /dev/null +++ b/asil_client/error.cc @@ -0,0 +1,47 @@ +// Copyright 2026 David Allison +// 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"; + } + 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..fae48eae --- /dev/null +++ b/asil_client/error.h @@ -0,0 +1,50 @@ +// Copyright 2026 David Allison +// 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, +}; + +// 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..bc5295d0 --- /dev/null +++ b/asil_client/layout_test.cc @@ -0,0 +1,197 @@ +// Copyright 2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +// Checks that the ASIL client's view of shared memory matches +// common/channel.h, and that its checksum matches the standard client's. + +#include "asil_client/checksum.h" +#include "asil_client/shm_layout.h" +#include "client/checksum.h" +#include "common/channel.h" + +#include +#include +#include +#include +#include +#include + +namespace { + +namespace shm = ::subspace::asil::shm; + +#define EXPECT_SAME_OFFSET(type, field) \ + EXPECT_EQ(offsetof(::subspace::type, field), offsetof(shm::type, field)) \ + << #type "::" #field + +TEST(LayoutTest, Constants) { + EXPECT_EQ(::subspace::kMaxChannels, shm::kMaxChannels); + EXPECT_EQ(::subspace::kMaxSlotOwners, shm::kMaxSlotOwners); + EXPECT_EQ(::subspace::kMaxVchanId, shm::kMaxVchanId); + EXPECT_EQ(static_cast(::subspace::kMaxBuffers), shm::kMaxBuffers); + EXPECT_EQ(::subspace::kChannelControlBlockVersion, + shm::kChannelControlBlockVersion); + EXPECT_EQ(::subspace::kInvalidSlotQueueOffset, shm::kInvalidSlotQueueOffset); + EXPECT_EQ(::subspace::kMessageActivate, shm::kMessageActivate); + EXPECT_EQ(::subspace::kMessageHasChecksum, shm::kMessageHasChecksum); + EXPECT_EQ(static_cast(::subspace::kMessageSeen), + shm::kMessageSeen); + EXPECT_EQ(static_cast(::subspace::kMessageIsActivation), + shm::kMessageIsActivation); + EXPECT_EQ(::subspace::kPubOwned, shm::kPubOwned); + EXPECT_EQ(::subspace::kRefsMask, shm::kRefsMask); + EXPECT_EQ(::subspace::kRefCountMask, shm::kRefCountMask); + EXPECT_EQ(::subspace::kReliableRefCountShift, shm::kReliableRefCountShift); + EXPECT_EQ(::subspace::kRetiredRefsShift, shm::kRetiredRefsShift); + EXPECT_EQ(::subspace::kRetiredRefsMask, shm::kRetiredRefsMask); + EXPECT_EQ(::subspace::kVchanIdShift, shm::kVchanIdShift); + EXPECT_EQ(::subspace::kVchanIdMask, shm::kVchanIdMask); + EXPECT_EQ(::subspace::kOrdinalShift, shm::kOrdinalShift); + EXPECT_EQ(::subspace::kOrdinalMask, shm::kOrdinalMask); +} + +TEST(LayoutTest, MessagePrefix) { + EXPECT_EQ(sizeof(::subspace::MessagePrefix), sizeof(shm::MessagePrefix)); + EXPECT_SAME_OFFSET(MessagePrefix, slot_id); + EXPECT_SAME_OFFSET(MessagePrefix, message_size); + EXPECT_SAME_OFFSET(MessagePrefix, ordinal); + EXPECT_SAME_OFFSET(MessagePrefix, timestamp); + EXPECT_SAME_OFFSET(MessagePrefix, flags); + EXPECT_SAME_OFFSET(MessagePrefix, vchan_id); + EXPECT_SAME_OFFSET(MessagePrefix, checksum_size); + EXPECT_SAME_OFFSET(MessagePrefix, metadata_size); + EXPECT_SAME_OFFSET(MessagePrefix, checksum); +} + +TEST(LayoutTest, MessageSlot) { + EXPECT_EQ(sizeof(::subspace::MessageSlot), sizeof(shm::MessageSlot)); + EXPECT_SAME_OFFSET(MessageSlot, refs); + EXPECT_SAME_OFFSET(MessageSlot, ordinal); + EXPECT_SAME_OFFSET(MessageSlot, message_size); + EXPECT_SAME_OFFSET(MessageSlot, id); + EXPECT_SAME_OFFSET(MessageSlot, buffer_index); + EXPECT_SAME_OFFSET(MessageSlot, vchan_id); + EXPECT_SAME_OFFSET(MessageSlot, sub_owners); + EXPECT_SAME_OFFSET(MessageSlot, timestamp); + EXPECT_SAME_OFFSET(MessageSlot, flags); + EXPECT_SAME_OFFSET(MessageSlot, bridged_slot_id); +} + +TEST(LayoutTest, ControlBlocks) { + EXPECT_EQ(sizeof(::subspace::ChannelCounters), sizeof(shm::ChannelCounters)); + EXPECT_SAME_OFFSET(ChannelCounters, num_pub_updates); + EXPECT_SAME_OFFSET(ChannelCounters, num_sub_updates); + EXPECT_EQ(sizeof(::subspace::SystemControlBlock), + sizeof(shm::SystemControlBlock)); + EXPECT_EQ(sizeof(::subspace::BufferControlBlock), + sizeof(shm::BufferControlBlock)); + EXPECT_SAME_OFFSET(BufferControlBlock, sizes); + EXPECT_EQ(sizeof(::subspace::AvailableSlotQueueIndex), + sizeof(shm::AvailableSlotQueueIndex)); + EXPECT_SAME_OFFSET(AvailableSlotQueueIndex, offsets); + EXPECT_SAME_OFFSET(AvailableSlotQueueIndex, active_publishers); +} + +TEST(LayoutTest, ChannelControlBlock) { + EXPECT_EQ(sizeof(::subspace::ChannelControlBlock), + sizeof(shm::ChannelControlBlock)); + EXPECT_EQ(offsetof(::subspace::ChannelControlBlock, slots), + sizeof(shm::ChannelControlBlock)); + EXPECT_SAME_OFFSET(ChannelControlBlock, num_slots); + EXPECT_SAME_OFFSET(ChannelControlBlock, subscriber_queue_size); + EXPECT_SAME_OFFSET(ChannelControlBlock, version); + EXPECT_SAME_OFFSET(ChannelControlBlock, ordinals); + EXPECT_SAME_OFFSET(ChannelControlBlock, activation_tracker); + EXPECT_SAME_OFFSET(ChannelControlBlock, buffer_index); + EXPECT_SAME_OFFSET(ChannelControlBlock, num_buffers); + EXPECT_SAME_OFFSET(ChannelControlBlock, subscribers); + EXPECT_SAME_OFFSET(ChannelControlBlock, sub_vchan_ids); + EXPECT_SAME_OFFSET(ChannelControlBlock, num_subs); + EXPECT_SAME_OFFSET(ChannelControlBlock, subscriber_cleanup_generation); + EXPECT_SAME_OFFSET(ChannelControlBlock, total_bytes); + EXPECT_SAME_OFFSET(ChannelControlBlock, total_messages); + EXPECT_SAME_OFFSET(ChannelControlBlock, max_message_size); + EXPECT_SAME_OFFSET(ChannelControlBlock, total_drops); + EXPECT_SAME_OFFSET(ChannelControlBlock, free_slots_exhausted); + EXPECT_EQ(sizeof(::subspace::SubscriberCounter), + sizeof(shm::SubscriberCounter)); + EXPECT_EQ(sizeof(::subspace::OrdinalAccumulator), + sizeof(shm::ChannelControlBlock::ordinals)); + EXPECT_EQ(sizeof(::subspace::ActivationTracker), + sizeof(shm::ChannelControlBlock::activation_tracker)); + EXPECT_EQ(sizeof(::subspace::SubscriberCleanupGeneration), + sizeof(shm::ChannelControlBlock::subscriber_cleanup_generation)); +} + +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::CcbSize(num_slots, 0), ::subspace::CcbSize(num_slots, 0)); + EXPECT_EQ(shm::CcbSize(num_slots, 64000), + ::subspace::CcbSize(num_slots, 64000)); + } +} + +TEST(LayoutTest, PrefixSize) { + for (int32_t checksum_size : {0, 4, 16, 17}) { + for (int32_t metadata_size : {0, 1, 16, 100}) { + EXPECT_EQ(shm::PrefixSize(checksum_size, metadata_size), + ::subspace::Channel::ComputePrefixSize(checksum_size, + metadata_size)); + } + } +} + +TEST(LayoutTest, RefsBitField) { + for (uint64_t ordinal : {0ULL, 1ULL, 12345ULL, (1ULL << 23) + 7}) { + for (int vchan_id : {-1, 0, 5, 1022}) { + for (int retired : {0, 1, 1023}) { + EXPECT_EQ(shm::BuildRefsBitField(ordinal, vchan_id, retired), + ::subspace::BuildRefsBitField(ordinal, vchan_id, retired)); + } + } + } +} + +TEST(ChecksumTest, MatchesStandardClient) { + std::mt19937 random(42); + for (size_t length : {0, 1, 3, 4, 7, 8, 9, 63, 64, 1000}) { + SCOPED_TRACE(length); + std::vector data(length); + for (uint8_t &byte : data) { + byte = static_cast(random()); + } + std::array, 3> spans = { + absl::Span(data.data(), length / 3), + absl::Span(data.data() + length / 3, length / 3), + absl::Span(data.data() + 2 * (length / 3), + length - 2 * (length / 3))}; + uint32_t expected = 0; + ::subspace::CalculateCRC32Checksum( + spans, absl::Span(reinterpret_cast(&expected), + sizeof(expected))); + uint32_t crc = 0xFFFFFFFF; + for (const auto &span : spans) { + crc = ::subspace::asil::Crc32(crc, span.data(), span.size()); + } + EXPECT_EQ(expected, ~crc); + } +} + +} // namespace diff --git a/asil_client/phaser_connection.cc b/asil_client/phaser_connection.cc new file mode 100644 index 00000000..71b9909c --- /dev/null +++ b/asil_client/phaser_connection.cc @@ -0,0 +1,537 @@ +// Copyright 2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +#include "asil_client/phaser_connection.h" + +#include "proto/subspace.phaser.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace subspace { +namespace asil { + +namespace wire = ::subspace::phaser; + +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; +} + +} // namespace + +Error PhaserServerConnection::Connect(const char *socket_name) { + 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; +} + +Error PhaserServerConnection::Rejected(const char *message, size_t length) { + if (length > sizeof(last_error_) - 1) { + length = sizeof(last_error_) - 1; + } + std::memcpy(last_error_, message, length); + last_error_[length] = '\0'; + return Error::kServerRejected; +} + +// Sends the length-prefixed request in wire_. +Error PhaserServerConnection::Send(size_t length) { + const uint32_t network_length = htonl(static_cast(length)); + std::memcpy(wire_, &network_length, sizeof(network_length)); + if (!SendFully(socket_.Get(), wire_, sizeof(network_length) + length)) { + return Error::kConnectionFailed; + } + return Error::kOk; +} + +// 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(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); + char *const data = wire_ + sizeof(uint32_t); + if (length <= kWireBufferSize) { + return ReceiveFully(socket_.Get(), data, length) ? Error::kOk + : Error::kConnectionFailed; + } + for (size_t remaining = length; remaining > 0;) { + const size_t chunk = + remaining < kWireBufferSize ? remaining : kWireBufferSize; + if (!ReceiveFully(socket_.Get(), data, chunk)) { + return Error::kConnectionFailed; + } + remaining -= chunk; + } + 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. +template +Error PhaserServerConnection::Transact(Build build, Read read) { + if (!socket_.Valid()) { + return Error::kNotInitialized; + } + fds_.Clear(); + size_t length = 0; + { + absl::StatusOr request = + wire::Request::TryCreateMutable(message_, sizeof(message_)); + if (!request.ok()) { + return Error::kCapacityExceeded; + } + build(*request); + if (request->AllocationFailed()) { + return Error::kCapacityExceeded; + } + ::phaser::ProtoBuffer out(wire_ + sizeof(uint32_t), kWireBufferSize); + if (!request->Serialize(out).ok()) { + return Error::kCapacityExceeded; + } + length = out.Size(); + } + + Error e = Send(length); + if (e == Error::kOk) { + e = Receive(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::Response::TryCreateMutable(message_, sizeof(message_)); + if (!response.ok()) { + fds_.Clear(); + return Error::kCapacityExceeded; + } + ::phaser::ProtoBuffer in(static_cast(wire_ + sizeof(uint32_t)), + length); + if (absl::Status status = response->Deserialize(in); !status.ok()) { + fds_.Clear(); + 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) { + request.mutable_init()->set_client_name(View(client_name)); + }, + [&](const wire::Response &response) { + if (!response.has_init()) { + return Error::kProtocolError; + } + const wire::InitResponse &init = response.init(); + 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(true); + if (request.type != nullptr) { + cmd->set_type(View(request.type)); + } + cmd->set_vchan_id(-1); + cmd->set_checksum_size(request.checksum_size); + cmd->set_metadata_size(request.metadata_size); + 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(); + 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 = 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); + if (request.type != nullptr) { + cmd->set_type(View(request.type)); + } + cmd->set_max_active_messages(request.max_active_messages); + cmd->set_vchan_id(-1); + 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; + }); +} + +} // namespace asil +} // namespace subspace diff --git a/asil_client/phaser_connection.h b/asil_client/phaser_connection.h new file mode 100644 index 00000000..09dee295 --- /dev/null +++ b/asil_client/phaser_connection.h @@ -0,0 +1,76 @@ +// Copyright 2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +#pragma once + +#include "asil_client/server_connection.h" + +#include +#include + +namespace subspace { +namespace asil { + +// The standard Subspace protocol: protobuf requests and responses over the +// server's Unix socket, with file descriptors passed as SCM_RIGHTS. Requests +// and responses are Phaser messages held in buffers inside this object and +// converted to and from protobuf wire format, so the handshake makes no heap +// allocations. A request or response that does not fit fails with +// kCapacityExceeded. +// +// The object holds about 60 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: + // Protobuf wire bytes for one request or response. + static constexpr size_t kWireBufferSize = 16 * 1024; + // The decoded request or response. + static constexpr size_t kMessageBufferSize = 32 * 1024; + // 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() = default; + ~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; + + const char *LastServerError() const override { return last_error_; } + + using ReceivedFds = FdList; + +private: + template + Error Transact(Build build, Read read); + Error Send(size_t length); + Error Receive(size_t &length); + Error ReceiveFds(); + Error Rejected(const char *message, size_t length); + + UniqueFd socket_; + ReceivedFds fds_; + char last_error_[256] = {}; + alignas(8) char wire_[sizeof(uint32_t) + kWireBufferSize]; + alignas(8) char message_[kMessageBufferSize]; +}; + +} // namespace asil +} // namespace subspace diff --git a/asil_client/publisher.cc b/asil_client/publisher.cc new file mode 100644 index 00000000..b59c495d --- /dev/null +++ b/asil_client/publisher.cc @@ -0,0 +1,408 @@ +// Copyright 2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +// The publishing side of the shared memory protocol. This follows +// PublisherImpl::FindFreeSlotUnreliable and +// PublisherImpl::ActivateSlotAndGetAnother in client/publisher.cc. + +#include "asil_client/publisher.h" + +#include "asil_client/checksum.h" +#include "asil_client/client.h" + +#include +#include + +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.slot_size <= 0 || options.num_slots <= 0 || + !ValidLayoutSize(options.checksum_size) || + !ValidLayoutSize(options.metadata_size)) { + return Error::kInvalidArgument; + } + if (Error e = internal::CopyName(channel_name, name_); e != Error::kOk) { + return e; + } + const int64_t slot_size = shm::Aligned64(options.slot_size); + + PublisherRequest request; + request.channel_name = name_; + request.slot_size = slot_size; + request.num_slots = options.num_slots; + request.type = options.type; + request.checksum_size = options.checksum_size; + request.metadata_size = options.metadata_size; + 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; + num_sub_updates_ = static_cast(reply.num_sub_updates); + checksum_ = options.checksum; + + Error e = Error::kOk; + if (reply.vchan_id != -1 || reply.subscriber_queue_arena_size != 0 || + channel_id_ < 0 || channel_id_ >= shm::kMaxChannels || + publisher_id_ < 0 || publisher_id_ >= shm::kMaxSlotOwners) { + e = Error::kUnsupported; + } + 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, + options.checksum_size, options.metadata_size); + } + if (e == Error::kOk) { + e = memory_.CreateOrAttachBuffer(name_, client.session_id_, slot_size, + client.user_id_, client.group_id_); + } + if (e == Error::kOk) { + slot_ = FindFreeSlot(); + if (slot_ == nullptr) { + e = Error::kNoSlot; + } + } + if (e != Error::kOk) { + (void)Close(); + return e; + } + BitsetView activations(&memory_.Ccb()->activation_tracker, + shm::kMaxVchanId + 1); + if (options.activate && !activations.IsSet(0)) { + slot_->message_size.store(1, std::memory_order_relaxed); + PublishSlot(slot_, /*is_activation=*/true, nullptr); + slot_ = FindFreeSlot(); + } + TriggerSubscribers(); + return Error::kOk; +} + +void Publisher::Reset() { + memory_.Unmap(); + subscriber_triggers_.Clear(); + retirement_triggers_.Clear(); + client_ = nullptr; + slot_ = nullptr; + channel_id_ = -1; + publisher_id_ = -1; +} + +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; +} + +bool Publisher::HoldSlot() { + if (slot_ == nullptr && client_ != nullptr) { + 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); + slot_ = 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)); + } +} + +int Publisher::FindRetiredSlotToReuse(bool oldest_first) const { + BitsetView retired = memory_.RetiredSlots(); + if (!oldest_first) { + return retired.FindFirstSet(); + } + // With no subscribers every slot retires as soon as it is published, so + // reuse the oldest to keep a window of recent messages for late joiners. + int oldest = -1; + uint64_t oldest_timestamp = ~uint64_t{0}; + for (int i = 0; i < memory_.NumSlots(); i++) { + if (!retired.IsSet(i)) { + continue; + } + const uint64_t timestamp = + memory_.Slot(i)->timestamp.load(std::memory_order_relaxed); + if (timestamp < oldest_timestamp) { + oldest_timestamp = timestamp; + oldest = i; + } + } + return oldest; +} + +shm::MessageSlot *Publisher::FindFreeSlot() { + shm::ChannelControlBlock *ccb = memory_.Ccb(); + BitsetView free_slots = memory_.FreeSlots(); + BitsetView retired_slots = memory_.RetiredSlots(); + const uint64_t owner = shm::kPubOwned | static_cast(publisher_id_); + constexpr int kMaxCasRetries = 1000; + int retries = memory_.NumSlots() * 1000; + int cas_retries = 0; + shm::MessageSlot *slot = nullptr; + int free_slot = -1; + int retired_slot = -1; + for (;;) { + slot = nullptr; + free_slot = -1; + retired_slot = -1; + const bool no_subscribers = memory_.NumSubscribers(-1) == 0; + if (!ccb->free_slots_exhausted.load(std::memory_order_relaxed) && + (free_slot = free_slots.FindFirstSet()) != -1) { + if (!free_slots.ClearWasSet(free_slot)) { + continue; + } + slot = memory_.Slot(free_slot); + if (free_slots.IsEmpty()) { + ccb->free_slots_exhausted.store(true, std::memory_order_relaxed); + } + } else if ((retired_slot = FindRetiredSlotToReuse(no_subscribers)) != -1) { + if (!retired_slots.ClearWasSet(retired_slot)) { + continue; + } + slot = memory_.Slot(retired_slot); + } else { + // Recycle the oldest message that no subscriber holds. + uint64_t earliest = ~uint64_t{0}; + for (int i = 0; i < memory_.NumSlots(); i++) { + shm::MessageSlot *s = memory_.Slot(i); + const uint64_t refs = s->refs.load(std::memory_order_relaxed); + if ((refs & shm::kPubOwned) != 0) { + continue; + } + const uint64_t timestamp = s->timestamp.load(std::memory_order_relaxed); + if ((refs & shm::kRefsMask) == 0 && timestamp < earliest) { + slot = s; + earliest = timestamp; + } + } + } + if (slot == nullptr) { + if (retries-- == 0) { + return nullptr; + } + continue; + } + const uint64_t old_refs = slot->refs.load(std::memory_order_relaxed); + uint64_t expected = shm::BuildRefsBitField( + slot->ordinal.load(std::memory_order_relaxed), + static_cast((old_refs >> shm::kVchanIdShift) & shm::kVchanIdMask), + (old_refs >> shm::kRetiredRefsShift) & shm::kRetiredRefsMask); + if (slot->refs.compare_exchange_weak(expected, owner, + std::memory_order_acquire, + std::memory_order_relaxed)) { + break; + } + if (++cas_retries >= kMaxCasRetries) { + if (retries-- == 0) { + return nullptr; + } + cas_retries = 0; + (void)::sched_yield(); + } + } + slot->ordinal.store(0, std::memory_order_relaxed); + slot->timestamp.store(0, std::memory_order_relaxed); + slot->vchan_id.store(-1, std::memory_order_relaxed); + SetSlotBuffer(slot); + shm::MessagePrefix *prefix = memory_.Prefix(slot); + prefix->flags = 0; + prefix->vchan_id = -1; + + memory_.Subscribers().Traverse( + [this, slot](int sub_id) { memory_.AvailableSlots(sub_id).Clear(slot->id); }); + + if (free_slot == -1 && retired_slot == -1) { + // A message that some subscriber hasn't seen is being overwritten. + memory_.TriggerRetirement(retirement_triggers_, slot->id); + } + return slot; +} + +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 < shm::kMaxBuffers && + bcb->refs[old_index].load(std::memory_order_relaxed) > 0) { + bcb->refs[old_index]--; + } + slot->buffer_index.store(0, std::memory_order_relaxed); + bcb->refs[0]++; +} + +void Publisher::PublishSlot(shm::MessageSlot *slot, bool is_activation, + PublishedMessage *published) { + shm::ChannelControlBlock *ccb = memory_.Ccb(); + shm::MessagePrefix *prefix = memory_.Prefix(slot); + const uint64_t ordinal = ccb->ordinals[0].fetch_add(1); + const uint64_t timestamp = internal::Now(); + const uint64_t message_size = + slot->message_size.load(std::memory_order_relaxed); + slot->ordinal.store(ordinal, std::memory_order_relaxed); + slot->timestamp.store(timestamp, std::memory_order_relaxed); + slot->flags.store(0, std::memory_order_relaxed); + + prefix->message_size = message_size; + prefix->ordinal = ordinal; + prefix->timestamp = timestamp; + prefix->vchan_id = -1; + prefix->checksum_size = static_cast(memory_.ChecksumSize()); + prefix->metadata_size = static_cast(memory_.MetadataSize()); + prefix->flags = 0; + prefix->slot_id = slot->id; + slot->bridged_slot_id.store(slot->id, std::memory_order_relaxed); + if (is_activation) { + prefix->flags |= shm::kMessageActivate; + slot->flags.fetch_or(shm::kMessageIsActivation, std::memory_order_relaxed); + BitsetView(&ccb->activation_tracker, shm::kMaxVchanId + 1).Set(0); + } + if (checksum_) { + prefix->flags |= shm::kMessageHasChecksum; + const auto *base = reinterpret_cast(prefix); + uint32_t crc = 0xFFFFFFFF; + crc = Crc32(crc, base + offsetof(shm::MessagePrefix, slot_id), + offsetof(shm::MessagePrefix, checksum) - + offsetof(shm::MessagePrefix, slot_id)); + crc = Crc32(crc, + base + offsetof(shm::MessagePrefix, checksum) + + memory_.ChecksumSize(), + static_cast(memory_.MetadataSize())); + crc = Crc32(crc, reinterpret_cast(memory_.Payload(slot)), + message_size); + crc = ~crc; + std::memcpy(&prefix->checksum, &crc, sizeof(crc)); + } + + const uint64_t cleanup_generation = memory_.CleanupGeneration(-1); + + // The server uses this count to tell when no publisher can be writing to a + // subscriber queue. + std::atomic &active_publishers = + memory_.QueueIndex()->active_publishers[publisher_id_]; + active_publishers.fetch_add(1, std::memory_order_seq_cst); + + // Mark the message available to every subscriber while the slot is still + // publisher owned. A subscriber can leave between the traversal and the + // set, so check membership again afterwards. + memory_.Subscribers().Traverse( + [this, slot](int sub_id) { + BitsetView available = memory_.AvailableSlots(sub_id); + BitsetView subscribers = memory_.Subscribers(); + available.Set(slot->id); + if (!subscribers.IsSetSeqCst(sub_id)) { + available.Clear(slot->id); + if (!subscribers.IsSetSeqCst(sub_id)) { + return; + } + available.Set(slot->id); + } + }, + std::memory_order_seq_cst); + + if (!is_activation) { + ccb->total_bytes += message_size; + if (message_size > ccb->max_message_size) { + ccb->max_message_size = message_size; + } + } + + // Releasing publisher ownership makes the message readable. + slot->refs.store(shm::BuildRefsBitField(ordinal, -1, 0), + std::memory_order_release); + ccb->total_messages.fetch_add(1, std::memory_order_seq_cst); + + // A subscriber removed while publishing lowers the retirement threshold. + if (!is_activation && memory_.CleanupGeneration(-1) != cleanup_generation && + memory_.TryRetireSlot(slot)) { + memory_.TriggerRetirement(retirement_triggers_, slot->id); + } + + uint32_t active = active_publishers.load(std::memory_order_seq_cst); + while (active != 0 && !active_publishers.compare_exchange_strong( + active, active - 1, std::memory_order_seq_cst)) { + } + if (published != nullptr) { + published->ordinal = ordinal; + published->timestamp = timestamp; + } +} + +} // namespace asil +} // namespace subspace diff --git a/asil_client/publisher.h b/asil_client/publisher.h new file mode 100644 index 00000000..4328ebac --- /dev/null +++ b/asil_client/publisher.h @@ -0,0 +1,98 @@ +// Copyright 2026 David Allison +// 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 +#include + +namespace subspace { +namespace asil { + +class Client; + +struct PublisherOptions { + // The channel layout. On a server with a static channel config these must + // match the configured channel. + 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. + bool activate = false; +}; + +struct PublishedMessage { + uint64_t ordinal = 0; + uint64_t timestamp = 0; +}; + +// An unreliable publisher for a fixed-size channel. It always holds a slot to +// write the next message into. +// +// 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 every slot is in use. + 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 every slot is in use. + 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); + + const char *Name() const { return name_; } + +private: + bool HoldSlot(); + Error RefreshTriggers(); + shm::MessageSlot *FindFreeSlot(); + int FindRetiredSlotToReuse(bool oldest_first) const; + 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_; + char name_[kMaxChannelNameLength + 1] = {}; + int32_t channel_id_ = -1; + int32_t publisher_id_ = -1; + uint16_t num_sub_updates_ = 0; + bool checksum_ = false; + shm::MessageSlot *slot_ = nullptr; + 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..9545c610 --- /dev/null +++ b/asil_client/server_connection.h @@ -0,0 +1,111 @@ +// Copyright 2026 David Allison +// 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, and to fetch trigger file descriptors when the +// set of publishers or subscribers on a channel changes. 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/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; +}; + +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; + UniqueFd ccb; + UniqueFd bcb; + // 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; +}; + +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; +}; + +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; + + // The server's message for the last request that returned kServerRejected. + 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..253823e6 --- /dev/null +++ b/asil_client/shm_layout.h @@ -0,0 +1,236 @@ +// Copyright 2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +// The Subspace shared memory layout as seen by the ASIL client. +// +// These structures mirror common/channel.h byte for byte so that the ASIL +// client can share channels with the standard clients. They are declared +// here, rather than included, so that the ASIL client depends only on the C++ +// standard library and POSIX. layout_test.cc checks every size and offset +// against common/channel.h. + +#pragma once + +#include +#include +#include + +// The shared memory backend. This follows the selection in common/channel.h. +#define ASIL_SHM_POSIX 1 +#define ASIL_SHM_LINUX 2 +#define ASIL_SHM_MEMFD 3 + +#if defined(SUBSPACE_SHMEM_MODE) +#define ASIL_SHM_MODE SUBSPACE_SHMEM_MODE +#elif defined(__ANDROID__) +#define ASIL_SHM_MODE ASIL_SHM_MEMFD +#elif defined(__linux__) && defined(SUBSPACE_LINUX_USE_MEMFD) +#define ASIL_SHM_MODE ASIL_SHM_MEMFD +#elif defined(__linux__) +#define ASIL_SHM_MODE ASIL_SHM_LINUX +#else +#define ASIL_SHM_MODE ASIL_SHM_POSIX +#endif + +#ifndef SUBSPACE_MAX_CHANNELS +#define SUBSPACE_MAX_CHANNELS 1024 +#endif + +namespace subspace { +namespace asil { +namespace shm { + +static_assert(sizeof(void *) == 8, "Subspace shared memory needs 64 bits"); + +constexpr int kMaxChannels = SUBSPACE_MAX_CHANNELS; +constexpr int kMaxSlotOwners = 1024; +constexpr int kMaxVchanId = 1023; +constexpr int kMaxBuffers = 1024; +constexpr size_t kMaxChannelName = 64; +constexpr uint32_t kChannelControlBlockVersion = 5; +constexpr uint64_t kInvalidSlotQueueOffset = ~uint64_t{0}; + +// MessagePrefix flags. +constexpr int64_t kMessageActivate = 1; +constexpr int64_t kMessageHasChecksum = 4; + +// MessageSlot flags. +constexpr uint32_t kMessageSeen = 1; +constexpr uint32_t kMessageIsActivation = 2; + +// Fields of MessageSlot::refs. +constexpr uint64_t kRefCountMask = 0x3ff; +constexpr uint64_t kReliableRefCountShift = 10; +constexpr uint64_t kPubOwned = uint64_t{1} << 63; +constexpr uint64_t kRefsMask = (uint64_t{1} << 20) - 1; +constexpr uint64_t kRetiredRefsMask = (uint64_t{1} << 10) - 1; +constexpr uint64_t kRetiredRefsShift = 20; +constexpr uint64_t kVchanIdMask = (uint64_t{1} << 10) - 1; +constexpr uint64_t kVchanIdShift = 30; +constexpr uint64_t kOrdinalMask = (uint64_t{1} << 23) - 1; +constexpr uint64_t kOrdinalShift = 40; + +inline uint64_t BuildRefsBitField(uint64_t ordinal, int vchan_id, + uint64_t retired_refs) { + const uint64_t vchan_bits = + ordinal == 0 ? 0 + : ((static_cast(vchan_id) & kVchanIdMask) + << kVchanIdShift); + return ((ordinal & kOrdinalMask) << kOrdinalShift) | vchan_bits | + ((retired_refs & kRetiredRefsMask) << kRetiredRefsShift); +} + +// The vchan_id stored in refs, where all ones means -1. +inline int RefsVchanId(uint64_t refs) { + const uint64_t v = (refs >> kVchanIdShift) & kVchanIdMask; + return v == kVchanIdMask ? -1 : static_cast(v); +} + +constexpr int64_t Aligned64(int64_t v) { return (v + 63) & ~int64_t{63}; } + +constexpr size_t BitsToWords(size_t bits) { + return bits == 0 ? 0 : ((bits - 1) / 64) + 1; +} + +// AtomicBitSet: the bit count followed by the words. +constexpr size_t SizeofBitset(size_t bits) { + return sizeof(size_t) + sizeof(uint64_t) * BitsToWords(bits); +} + +template struct FixedBitset { + size_t num_bits; + std::atomic words[BitsToWords(kBits)]; +}; + +struct MessagePrefix { + int32_t padding; + int32_t slot_id; + 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[12]; +}; +static_assert(sizeof(MessagePrefix) == 64); +static_assert(offsetof(MessagePrefix, slot_id) == 4); +static_assert(offsetof(MessagePrefix, checksum) == 48); + +struct ChannelCounters { + uint16_t num_pub_updates; + uint16_t num_sub_updates; + uint16_t num_pubs; + uint16_t num_reliable_pubs; + uint16_t num_subs; + uint16_t num_reliable_subs; + uint16_t num_resizes; +}; +static_assert(sizeof(ChannelCounters) == 14); + +struct SystemControlBlock { + ChannelCounters counters[kMaxChannels]; +}; + +struct MessageSlot { + std::atomic refs; + std::atomic ordinal; + std::atomic message_size; + int32_t id; + std::atomic buffer_index; + std::atomic vchan_id; + FixedBitset sub_owners; + std::atomic timestamp; + std::atomic flags; + std::atomic bridged_slot_id; +}; +static_assert(sizeof(MessageSlot) == 184); +static_assert(offsetof(MessageSlot, id) == 24); +static_assert(offsetof(MessageSlot, sub_owners) == 32); +static_assert(offsetof(MessageSlot, timestamp) == 168); +static_assert(offsetof(MessageSlot, bridged_slot_id) == 180); + +struct SubscriberCounter { + std::atomic sequence; + std::atomic counts[kMaxVchanId + 1]; +}; + +struct ChannelControlBlock { + char channel_name[kMaxChannelName]; + int32_t num_slots; + int32_t subscriber_queue_size; + uint32_t version; + std::atomic ordinals[kMaxVchanId + 1]; + FixedBitset activation_tracker; + int32_t buffer_index; + std::atomic num_buffers; + FixedBitset subscribers; + int16_t sub_vchan_ids[kMaxSlotOwners]; + SubscriberCounter num_subs; + std::atomic subscriber_cleanup_generation[kMaxVchanId + 1]; + std::atomic total_bytes; + std::atomic total_messages; + std::atomic max_message_size; + std::atomic total_drops; + std::atomic free_slots_exhausted; + // Followed by num_slots MessageSlots. +}; +static_assert(offsetof(ChannelControlBlock, version) == 72); + +struct AvailableSlotQueueIndex { + std::atomic next_offset; + std::atomic offsets[kMaxSlotOwners]; + std::atomic active_publishers[kMaxSlotOwners]; +}; +static_assert(sizeof(AvailableSlotQueueIndex) == 12296); + +struct BufferControlBlock { + std::atomic refs[kMaxBuffers]; + std::atomic sizes[kMaxBuffers]; +}; + +// Offsets of the regions that follow the slots in the CCB. A CCB holds the +// header and slots, the retired and free slot bitsets, one available-slot +// bitset per subscriber, the subscriber queue index and the queue arena. +inline size_t RetiredSlotsOffset(int num_slots) { + return static_cast( + Aligned64(static_cast(sizeof(ChannelControlBlock) + + num_slots * sizeof(MessageSlot)))); +} + +inline size_t FreeSlotsOffset(int num_slots) { + return RetiredSlotsOffset(num_slots) + + static_cast(Aligned64( + static_cast(SizeofBitset(num_slots)))); +} + +inline size_t AvailableSlotsOffset(int num_slots, int sub_id) { + return FreeSlotsOffset(num_slots) + + static_cast(Aligned64( + static_cast(SizeofBitset(num_slots)))) + + SizeofBitset(num_slots) * static_cast(sub_id); +} + +inline size_t SlotQueueIndexOffset(int num_slots) { + return AvailableSlotsOffset(num_slots, kMaxSlotOwners); +} + +inline size_t CcbSize(int num_slots, uint64_t subscriber_queue_arena_size) { + return SlotQueueIndexOffset(num_slots) + + static_cast( + Aligned64(static_cast(sizeof(AvailableSlotQueueIndex)))) + + static_cast(subscriber_queue_arena_size); +} + +inline int32_t PrefixSize(int32_t checksum_size, int32_t metadata_size) { + return static_cast(Aligned64( + static_cast(offsetof(MessagePrefix, checksum)) + checksum_size + + metadata_size)); +} + +} // namespace shm +} // namespace asil +} // namespace subspace diff --git a/asil_client/subscriber.cc b/asil_client/subscriber.cc new file mode 100644 index 00000000..749c644e --- /dev/null +++ b/asil_client/subscriber.cc @@ -0,0 +1,396 @@ +// Copyright 2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +// The reading side of the shared memory protocol. This follows +// SubscriberImpl::NextSlot, LastSlot, ClaimSlot and RemoveActiveMessage in +// client/subscriber.cc, using the subscriber's available-slot bitset as the +// record of unread messages. + +#include "asil_client/subscriber.h" + +#include "asil_client/checksum.h" +#include "asil_client/client.h" + +#include +#include +#include + +namespace subspace { +namespace asil { + +namespace { + +constexpr int kMaxClaimAttempts = 1000; + +// Messages are ordered by timestamp, then ordinal. +bool Before(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; +} + +BitsetView Owners(shm::MessageSlot *slot) { + return BitsetView(&slot->sub_owners, shm::kMaxSlotOwners); +} + +} // namespace + +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 (Error e = internal::CopyName(channel_name, name_); e != Error::kOk) { + return e; + } + SubscriberRequest request; + request.channel_name = name_; + request.type = options.type; + request.max_active_messages = 1; + SubscriberReply reply; + reply.reliable_publisher_triggers = &reliable_publishers_; + reply.retirement_triggers = &retirement_triggers_; + if (Error e = client.connection_->CreateSubscriber(request, reply); + e != Error::kOk) { + Reset(); + return e; + } + client_ = &client; + options_ = options; + channel_id_ = reply.channel_id; + subscriber_id_ = reply.subscriber_id; + num_pub_updates_ = static_cast(reply.num_pub_updates); + trigger_ = static_cast(reply.trigger); + poll_ = static_cast(reply.poll); + + Error e = Error::kOk; + if (reply.vchan_id != -1 || reply.use_split_buffers || + reply.subscriber_queue_size != 0 || + reply.subscriber_queue_arena_size != 0 || channel_id_ < 0 || + channel_id_ >= shm::kMaxChannels || subscriber_id_ < 0 || + subscriber_id_ >= shm::kMaxSlotOwners) { + e = Error::kUnsupported; + } + if (e == Error::kOk) { + e = memory_.Map(client.scb_, reply.ccb.Get(), reply.bcb.Get(), + reply.num_slots, reply.checksum_size, reply.metadata_size); + } + if (e == Error::kOk) { + e = memory_.AttachBuffer(name_, client.session_id_); + } + if (e != Error::kOk) { + (void)Close(); + return e; + } + // Wake the reader for messages published before it joined. + internal::Trigger(trigger_.Get()); + return Error::kOk; +} + +void Subscriber::Reset() { + memory_.Unmap(); + reliable_publishers_.Clear(); + retirement_triggers_.Clear(); + trigger_.Reset(); + poll_.Reset(); + client_ = nullptr; + held_ = nullptr; + last_ordinal_ = 0; + channel_id_ = -1; + subscriber_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; + } + struct pollfd fd = {poll_.Get(), POLLIN, 0}; + for (;;) { + const int n = ::poll(&fd, 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; + } + } +} + +void Subscriber::ReleaseMessage() { + if (held_ != nullptr) { + ReleaseSlot(held_); + held_ = nullptr; + } +} + +void Subscriber::ReleaseSlot(shm::MessageSlot *slot) { + if (!Owners(slot).ClearWasSet(subscriber_id_)) { + return; + } + bool retired = false; + (void)memory_.AtomicIncRefCount( + slot, -1, slot->ordinal.load(std::memory_order_relaxed), + slot->vchan_id.load(std::memory_order_relaxed), /*retire=*/true, + &retired); + if (retired) { + memory_.TriggerRetirement( + retirement_triggers_, + slot->bridged_slot_id.load(std::memory_order_relaxed)); + } +} + +Error Subscriber::RefreshTriggers() { + const uint16_t updates = memory_.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)); + } +} + +// 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); + if ((s->refs.load(std::memory_order_acquire) & shm::kPubOwned) != 0) { + return; + } + const uint64_t ordinal = s->ordinal.load(std::memory_order_relaxed); + if (ordinal == 0 || + s->buffer_index.load(std::memory_order_relaxed) != 0) { + return; + } + const uint64_t timestamp = s->timestamp.load(std::memory_order_relaxed); + if (best == nullptr || + Before(timestamp, ordinal, best_timestamp, best_ordinal)) { + best = s; + best_ordinal = ordinal; + best_timestamp = timestamp; + } + }); + if (best == nullptr) { + return Find::kNone; + } + if (memory_.AtomicIncRefCount( + best, 1, best_ordinal, + best->vchan_id.load(std::memory_order_relaxed), false, nullptr)) { + // Record ownership so that the server can release the reference if this + // process dies. + Owners(best).Set(subscriber_id_); + 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); + if ((s->refs.load(std::memory_order_acquire) & shm::kPubOwned) != 0) { + return; + } + const uint64_t ordinal = s->ordinal.load(std::memory_order_relaxed); + if (ordinal == 0 || + s->buffer_index.load(std::memory_order_relaxed) != 0) { + return; + } + const uint64_t timestamp = s->timestamp.load(std::memory_order_relaxed); + if (best == nullptr || + Before(best_timestamp, best_ordinal, timestamp, ordinal)) { + best = s; + best_ordinal = ordinal; + best_timestamp = timestamp; + } + }); + if (best == nullptr) { + return Find::kNone; + } + if (memory_.AtomicIncRefCount( + best, 1, best_ordinal, + best->vchan_id.load(std::memory_order_relaxed), false, nullptr)) { + Owners(best).Set(subscriber_id_); + slot = best; + return Find::kFound; + } + } + return Find::kNone; +} + +// Marks every unread message older than newest as read. Each slot is pinned +// while its bit is cleared so that a publisher recycling it can't lose the +// bit for the new message. +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); + available.Traverse([&](int i) { + if (i == newest->id) { + return; + } + shm::MessageSlot *s = memory_.Slot(i); + if ((s->refs.load(std::memory_order_acquire) & shm::kPubOwned) != 0) { + return; + } + const uint64_t ordinal = s->ordinal.load(std::memory_order_relaxed); + const uint64_t timestamp = s->timestamp.load(std::memory_order_relaxed); + if (ordinal == 0 || + !Before(timestamp, ordinal, newest_timestamp, newest_ordinal)) { + return; + } + const int vchan_id = s->vchan_id.load(std::memory_order_relaxed); + if (memory_.AtomicIncRefCount(s, 1, ordinal, vchan_id, false, nullptr)) { + available.Clear(i); + (void)memory_.AtomicIncRefCount(s, -1, ordinal, vchan_id, false, + nullptr); + } + }); +} + +bool Subscriber::ChecksumValid(const shm::MessageSlot *slot, + size_t length) const { + const shm::MessagePrefix *prefix = memory_.Prefix(slot); + const auto *base = reinterpret_cast(prefix); + uint32_t crc = 0xFFFFFFFF; + crc = Crc32(crc, base + offsetof(shm::MessagePrefix, slot_id), + offsetof(shm::MessagePrefix, checksum) - + offsetof(shm::MessagePrefix, slot_id)); + crc = Crc32(crc, + base + offsetof(shm::MessagePrefix, checksum) + + memory_.ChecksumSize(), + static_cast(memory_.MetadataSize())); + crc = Crc32(crc, reinterpret_cast(memory_.Payload(slot)), + length); + uint32_t stored; + std::memcpy(&stored, &prefix->checksum, sizeof(stored)); + return stored == ~crc; +} + +Error Subscriber::ReadMessage(Message &message, ReadMode mode) { + message = Message(); + if (client_ == nullptr) { + return Error::kNotInitialized; + } + internal::ClearTrigger(poll_.Get()); + ReleaseMessage(); + if (Error e = RefreshTriggers(); e != Error::kOk) { + return e; + } + if (Error e = memory_.AttachBuffer(name_, client_->session_id_); + e != Error::kOk) { + return e; + } + if (!memory_.HasBuffer()) { + return Error::kOk; + } + 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 shm::MessagePrefix *prefix = memory_.Prefix(slot); + 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 bool is_activation = (prefix->flags & shm::kMessageActivate) != 0; + + if (mode == ReadMode::kReadNewest) { + ClearOlder(slot); + } + available.Clear(slot->id); + slot->flags.fetch_or(shm::kMessageSeen, std::memory_order_relaxed); + + 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; + } + held_ = slot; + 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.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..f72a3da7 --- /dev/null +++ b/asil_client/subscriber.h @@ -0,0 +1,111 @@ +// Copyright 2026 David Allison +// 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 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; +}; + +enum class ReadMode { + kReadNext, + kReadNewest, +}; + +// A message in shared memory. The pointers stay valid until the next read, +// ReleaseMessage() or 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; + bool is_activation = false; + bool checksum_error = false; + // Messages missed since the previous read, for kReadNext. + uint32_t dropped = 0; + const void *metadata = nullptr; + size_t metadata_length = 0; +}; + +// An unreliable subscriber. It holds at most one message; reading the next +// message releases the previous one. +// +// A subscriber is not thread safe and must not outlive its Client. +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. If a publisher has joined since the last read this asks the + // server for its trigger fds first. + Error ReadMessage(Message &message, ReadMode mode = ReadMode::kReadNext); + // Releases the message from the last read. + void ReleaseMessage(); + + // 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); + + const char *Name() const { return name_; } + +private: + enum class Find { kFound, kNone }; + + Error RefreshTriggers(); + Find FindNext(shm::MessageSlot *&slot); + Find FindNewest(shm::MessageSlot *&slot); + void ClearOlder(const shm::MessageSlot *newest); + void ReleaseSlot(shm::MessageSlot *slot); + bool ChecksumValid(const shm::MessageSlot *slot, size_t length) const; + void TriggerReliablePublishers() const; + void Reset(); + + Client *client_ = nullptr; + internal::ChannelMemory memory_; + char name_[kMaxChannelNameLength + 1] = {}; + SubscriberOptions options_; + int32_t channel_id_ = -1; + int32_t subscriber_id_ = -1; + uint16_t num_pub_updates_ = 0; + UniqueFd trigger_; + UniqueFd poll_; + shm::MessageSlot *held_ = nullptr; + uint64_t last_ordinal_ = 0; + 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..fbc39744 --- /dev/null +++ b/asil_client/unique_fd.h @@ -0,0 +1,80 @@ +// Copyright 2026 David Allison +// 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/docs/android.md b/docs/android.md index dab8202a..584cc7d3 100644 --- a/docs/android.md +++ b/docs/android.md @@ -184,15 +184,17 @@ 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 ASIL client's 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 +202,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 +243,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 ASIL client | +| `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 +262,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..1617086d --- /dev/null +++ b/docs/asil-client.md @@ -0,0 +1,206 @@ +# 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 is designed for a server running a [static channel config](../README.md#static-channel-config), +where every channel exists before any client connects and keeps a fixed +layout. + +## Design Rules + +- **C++17, the standard library and POSIX.** The core library has no other + dependencies and 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 server's reason for + `Error::kServerRejected`. +- **No heap allocation.** The client, publishers and subscribers allocate no + memory, and neither does `PhaserServerConnection` while it talks to the + server. The server is involved when a client, publisher or subscriber is + set up or closed, and when a publisher or subscriber refreshes its trigger + file descriptors after another process joins or leaves the channel. +- **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. Exceeding any of these returns + `Error::kCapacityExceeded`. +- **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 provides unreliable publishers and subscribers on +fixed-size, non-virtual channels: + +- Each channel has one buffer, which is what fixed-size channels use. +- A subscriber holds at most one message. Reading the next message releases + the previous one. +- Checksums, user metadata, `kReadNext` and `kReadNewest`, dropped message + counting and activation messages work with both clients. + +Reliable publishers and subscribers, virtual channels, subscriber queues, +split buffers and the memfd backend (always used on Android, and selected on +Linux with `SUBSPACE_LINUX_USE_MEMFD`) return `Error::kUnsupported`. +Channels created by standard publishers that resize their slots also have +more than one buffer and are rejected the same way. + +## 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`, `//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`. 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). Without one, the +cross-compile builds only the core library. + +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`. + +`PhaserServerConnection` implements it with the server's standard protocol: +length-prefixed messages in protobuf wire format on the server's Unix socket, +with file descriptors passed by `SCM_RIGHTS`. The server receives the same +bytes it receives from the standard clients. The connection builds each +request as a phaser message in a fixed buffer inside the object, serializes +it to protobuf wire format, and decodes the response into the same buffer, +so it needs neither the protobuf library nor the heap. The buffers take +about 60 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 + +```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 and type. On a static channel these must match the config. + +`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. + +## Subscribers + +`ReadMessage(msg, mode)` fills in a `Message` with the payload, length, +ordinal, timestamp, slot, 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. + +## Testing + +`layout_test` compares every size, offset and constant in +`asil_client/shm_layout.h` with `common/channel.h`, and checks that the +checksum matches the standard client's. `asil_client_test` runs a server with +a static channel config and exchanges messages between the ASIL client and the +standard client in both directions. It also checks that setting up and +closing a publisher and a subscriber makes no heap allocations, and that a +request too large for the wire buffer returns `Error::kCapacityExceeded` and +leaves the connection usable. It is skipped on memfd builds. 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/proto/BUILD.bazel b/proto/BUILD.bazel index ef45e13e..ff50834a 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,3 +17,15 @@ 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"], +) diff --git a/proto/CMakeLists.txt b/proto/CMakeLists.txt index 46036cc0..db9e1bfd 100644 --- a/proto/CMakeLists.txt +++ b/proto/CMakeLists.txt @@ -93,3 +93,26 @@ target_link_libraries(subspace_proto PUBLIC protobuf::libprotobuf ) +# Phaser messages for the ASIL client's server connection. They are sent and +# received in protobuf wire format, so the server sees the same bytes as from +# any other client. Cross-compiles need a host plugin in +# PHASER_PLUGIN_EXECUTABLE; without one the ASIL server connection is skipped. +if(CMAKE_CROSSCOMPILING AND NOT PHASER_PLUGIN_EXECUTABLE) + message(STATUS + "Skipping subspace_phaser: cross-compiling without " + "-DPHASER_PLUGIN_EXECUTABLE.") + return() +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} +) + From 3d78953dcc47cc7d125fcf860a9dfb55f8b959e3 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Fri, 9 Oct 2026 16:43:33 -0700 Subject: [PATCH 03/21] Map ASIL buffers at open and support split buffers The server now creates the message buffers of every static channel and multiplexer when it starts, through the same code as a standard first publisher, so subscribers can map them before any publisher exists. A static channel or multiplexer with use_split_buffers gets split buffers, which the server creates, and publishers whose split setting differs from the config are rejected. GetClientBuffersRequest can ask for one prefix or slot of a split buffer set. ASIL publishers and subscribers map all of a channel's shared memory in Open(), and publishing and reading make no shared memory calls. They map the channel's newest buffer; the resize, placeholder remap and 16-buffer table are gone. A subscriber on a channel without buffers gets kNoBuffers, and a message in a buffer created by a resize after the subscriber opened returns kBufferNotMapped. The ASIL client also supports split buffers, mapping each slot into an array the caller provides. Slots from a standard publisher's custom allocator are mapped through C map/unmap callbacks with a context. The ASIL client also gains reliable publishers and subscribers, virtual channels, multiple held messages, subscriber queues and the memfd backend, and the server checks fixed size and locality across the virtual channels of a multiplexer. --- CHANGELOG.md | 28 +- README.md | 16 +- asil_client/BUILD.bazel | 1 + asil_client/asil_client_test.cc | 781 +++++++++++++++++++++++++++++-- asil_client/channel_memory.cc | 639 ++++++++++++++++++------- asil_client/channel_memory.h | 96 +++- asil_client/client.h | 13 +- asil_client/error.cc | 6 + asil_client/error.h | 8 + asil_client/layout_test.cc | 83 +++- asil_client/phaser_connection.cc | 149 +++++- asil_client/phaser_connection.h | 5 +- asil_client/publisher.cc | 310 ++++++++++-- asil_client/publisher.h | 56 ++- asil_client/server_connection.h | 58 ++- asil_client/shm_layout.h | 62 ++- asil_client/split_buffer.h | 77 +++ asil_client/subscriber.cc | 271 +++++++---- asil_client/subscriber.h | 71 ++- docs/asil-client.md | 203 ++++++-- proto/subspace.proto | 20 +- server/client_handler.cc | 38 +- server/server.cc | 92 ++++ server/server.h | 12 + server/server_channel.cc | 12 + server/server_channel.h | 14 + server/static_config.cc | 5 +- server/static_config_test.cc | 78 ++- 28 files changed, 2722 insertions(+), 482 deletions(-) create mode 100644 asil_client/split_buffer.h diff --git a/CHANGELOG.md b/CHANGELOG.md index 4cb601be..73a78a4d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,11 +10,24 @@ is fixed: publishers must be fixed size and match the configured slot size, number of slots, checksum size and metadata size. - 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. Publishers whose split buffer + setting differs from the config are rejected. +- `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 unreliable, fixed-size channels with the standard clients through - the same shared memory protocol, using only the standard library and + 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 @@ -23,6 +36,17 @@ implements the standard protocol with phaser messages in fixed buffers, sent and received in protobuf wire format, 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`. - Bazel, CMake and Soong build phaser and generate `subspace_phaser` from `subspace.proto`. Android CMake cross-compiles take a host `protoc-gen-phaser` in `PHASER_PLUGIN_EXECUTABLE`. diff --git a/README.md b/README.md index 4844e80c..8cc73630 100644 --- a/README.md +++ b/README.md @@ -2023,9 +2023,10 @@ channels { name: "/sensors/lidar" mux: "/sensors" vchan_id: 0 } channels { name: "/sensors/radar" mux: "/sensors" vchan_id: 1 } ``` -The server creates every configured channel before it accepts clients, so a -subscriber that starts first gets the full channel layout instead of a -placeholder. With a config loaded: +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: - Clients can use only the configured channels and the server's own `/subspace/ChannelDirectory` and `/subspace/Statistics`. Creating a @@ -2035,8 +2036,13 @@ placeholder. With a config loaded: - The layout is fixed. Publishers must be fixed size (`SetFixedSize(true)`) and match the configured slot size, number of slots, checksum size and metadata size. -- A channel on a multiplexer takes its slot size, number of slots, type and - prefix layout from the multiplexer and needs an explicit `vchan_id`. +- `use_split_buffers: true` gives a channel or multiplexer + [split buffers](docs/split-buffers.md), which the server creates. + Publishers must set `SetUseSplitBuffers(true)` on these channels and leave + it unset on the others. +- 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. diff --git a/asil_client/BUILD.bazel b/asil_client/BUILD.bazel index dab9dc9f..3c53448b 100644 --- a/asil_client/BUILD.bazel +++ b/asil_client/BUILD.bazel @@ -23,6 +23,7 @@ cc_library( "publisher.h", "server_connection.h", "shm_layout.h", + "split_buffer.h", "subscriber.h", "unique_fd.h", ], diff --git a/asil_client/asil_client_test.cc b/asil_client/asil_client_test.cc index 50d86e88..df5b659b 100644 --- a/asil_client/asil_client_test.cc +++ b/asil_client/asil_client_test.cc @@ -15,10 +15,13 @@ #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 @@ -67,8 +70,40 @@ constexpr char kConfig[] = R"pb( 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/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() { @@ -139,9 +174,11 @@ asil::PublisherOptions AsilPubOptions(int64_t slot_size, int32_t num_slots) { return options; } -class AsilClientTest : public ::testing::Test { +// 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: - static void SetUpTestSuite() { + void Start(const char *config) { #if defined(__ANDROID__) char socket_name_template[] = "/data/local/tmp/subspaceXXXXXX"; // NOLINT #else @@ -156,12 +193,14 @@ class AsilClientTest : public ::testing::Test { 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))); + if (config != nullptr) { + absl::StatusOr parsed = + subspace::ParseStaticChannelConfig(config); + ASSERT_OK(parsed); + ASSERT_OK(server_->SetStaticChannelConfig(*std::move(parsed))); + } - server_thread_ = std::thread([]() { + server_thread_ = std::thread([this]() { absl::Status s = server_->Run(); if (!s.ok()) { fprintf(stderr, "Error running Subspace server: %s\n", @@ -174,42 +213,73 @@ class AsilClientTest : public ::testing::Test { (void)::read(server_pipe_[0], buf, 8); } - static void TearDownTestSuite() { + 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()); } - void SetUp() override { -#if ASIL_SHM_MODE == ASIL_SHM_MEMFD - GTEST_SKIP() << "The ASIL client does not support the memfd backend"; -#endif - 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")); - } + 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_; } -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_; +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()); } + +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"); @@ -272,8 +342,7 @@ TEST_F(AsilClientTest, StandardPublisherAsilSubscriber) { TEST_F(AsilClientTest, AsilToAsilWithWait) { asil::Subscriber sub; - ASSERT_EQ(asil::Error::kOk, - Asil().CreateSubscriber("/asil/wait", {}, sub)); + ASSERT_EQ(asil::Error::kOk, Asil().CreateSubscriber("/asil/wait", {}, sub)); asil::Publisher pub; ASSERT_EQ(asil::Error::kOk, Asil().CreatePublisher("/asil/wait", AsilPubOptions(64, 4), pub)); @@ -292,8 +361,9 @@ TEST_F(AsilClientTest, AsilToAsilWithWait) { TEST_F(AsilClientTest, SubscriberJoinsAfterPublisher) { asil::Publisher pub; - ASSERT_EQ(asil::Error::kOk, Asil().CreatePublisher( - "/asil/late_sub", AsilPubOptions(64, 4), pub)); + ASSERT_EQ( + asil::Error::kOk, + Asil().CreatePublisher("/asil/late_sub", AsilPubOptions(64, 4), pub)); absl::StatusOr sub = Std().CreateSubscriber("/asil/late_sub"); @@ -327,8 +397,8 @@ 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)); + 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; @@ -406,8 +476,7 @@ TEST_F(AsilClientTest, Metadata) { TEST_F(AsilClientTest, ReadNewest) { asil::Subscriber sub; - ASSERT_EQ(asil::Error::kOk, - Asil().CreateSubscriber("/asil/newest", {}, sub)); + ASSERT_EQ(asil::Error::kOk, Asil().CreateSubscriber("/asil/newest", {}, sub)); absl::StatusOr pub = Std().CreatePublisher("/asil/newest", 64, 8, FixedSize()); ASSERT_OK(pub); @@ -475,8 +544,9 @@ TEST_F(AsilClientTest, StandardSubscriberSeesAsilDrops) { [&dropped](subspace::Subscriber *, int64_t n) { dropped += n; })); asil::Publisher pub; - ASSERT_EQ(asil::Error::kOk, Asil().CreatePublisher( - "/asil/drops_out", AsilPubOptions(64, 4), pub)); + ASSERT_EQ( + asil::Error::kOk, + Asil().CreatePublisher("/asil/drops_out", AsilPubOptions(64, 4), pub)); AsilPublish(pub, "first"); EXPECT_EQ("first", StdRead(*sub).text); @@ -565,19 +635,22 @@ TEST_F(AsilClientTest, HeldMessageIsNotOverwritten) { sub.ReleaseMessage(); asil::Message msg; - ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg, asil::ReadMode::kReadNewest)); + ASSERT_EQ(asil::Error::kOk, + sub.ReadMessage(msg, asil::ReadMode::kReadNewest)); EXPECT_EQ("overwrite 19", Text(msg)); } TEST_F(AsilClientTest, Rejections) { asil::Publisher pub; - EXPECT_EQ(asil::Error::kServerRejected, - Asil().CreatePublisher("/asil/reject", AsilPubOptions(128, 4), pub)); + EXPECT_EQ( + asil::Error::kServerRejected, + Asil().CreatePublisher("/asil/reject", AsilPubOptions(128, 4), pub)); EXPECT_THAT(Asil().LastServerError(), HasSubstr("has 4 slots of 64 bytes")); EXPECT_FALSE(pub.IsOpen()); - EXPECT_EQ(asil::Error::kServerRejected, - Asil().CreatePublisher("/asil/unknown", AsilPubOptions(64, 4), pub)); + EXPECT_EQ( + asil::Error::kServerRejected, + Asil().CreatePublisher("/asil/unknown", AsilPubOptions(64, 4), pub)); EXPECT_THAT(Asil().LastServerError(), HasSubstr("isn't in the static channel config")); @@ -600,15 +673,8 @@ TEST_F(AsilClientTest, Rejections) { asil::Client uninitialized; asil::Publisher other; EXPECT_EQ(asil::Error::kNotInitialized, - uninitialized.CreatePublisher("/asil/reject", - AsilPubOptions(64, 4), other)); -} - -TEST_F(AsilClientTest, VirtualChannelsAreUnsupported) { - asil::Subscriber sub; - const asil::Error e = Asil().CreateSubscriber("/asil/v1", {}, sub); - EXPECT_NE(asil::Error::kOk, e); - EXPECT_FALSE(sub.IsOpen()); + uninitialized.CreatePublisher("/asil/reject", AsilPubOptions(64, 4), + other)); } TEST_F(AsilClientTest, CloseRemovesFromServer) { @@ -683,6 +749,627 @@ TEST_F(AsilClientTest, OversizedRequestKeepsTheConnection) { Connection().GetTriggers("/asil/oversize", reply)); } +// 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(int64_t slot_size, + int32_t num_slots) { + asil::PublisherOptions options = AsilPubOptions(slot_size, num_slots); + 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(64, 4), 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", 64, 4, FixedSize().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(64, 4), 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(64, 4), 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", AsilPubOptions(128, 8), 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 = AsilPubOptions(128, 8); + 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", 128, 8, FixedSize().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", 64, 8, FixedSize()); + 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", 64, 4, FixedSize()); + ASSERT_OK(pub); + StdPublish(*pub, "early"); + ASSERT_EQ(asil::Error::kOk, sub.ReadMessage(msg)); + EXPECT_EQ("early", Text(msg)); +} + +asil::PublisherOptions SplitPubOptions(int64_t slot_size, int32_t num_slots, + asil::SplitSlot *slots) { + asil::PublisherOptions options = AsilPubOptions(slot_size, num_slots); + options.use_split_buffers = true; + options.split_slots = slots; + options.split_slot_capacity = num_slots; + 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(256, 4, pub_slots), 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", 256, 4, + FixedSize().SetUseSplitBuffers(true).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(128, 8, pub_slots); + 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()); + + asil::Publisher pub; + EXPECT_EQ( + asil::Error::kServerRejected, + Asil().CreatePublisher("/asil/split_reject", AsilPubOptions(64, 4), pub)); + EXPECT_THAT(Asil().LastServerError(), HasSubstr("uses split buffers")); + EXPECT_EQ(asil::Error::kServerRejected, + Asil().CreatePublisher("/asil/reject", + SplitPubOptions(64, 4, slots), pub)); + EXPECT_THAT(Asil().LastServerError(), HasSubstr("doesn't use split buffers")); +} + +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) { diff --git a/asil_client/channel_memory.cc b/asil_client/channel_memory.cc index 747d33ea..dfb38f95 100644 --- a/asil_client/channel_memory.cc +++ b/asil_client/channel_memory.cc @@ -9,9 +9,13 @@ #include #include #include +#include #include #include #include +#if ASIL_SHM_MODE == ASIL_SHM_MEMFD +#include +#endif namespace subspace { namespace asil { @@ -20,6 +24,8 @@ 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}; @@ -30,6 +36,11 @@ 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 ASIL_SHM_MODE != ASIL_SHM_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; @@ -76,6 +87,24 @@ Error CreateShadowFile(const char *shadow_file, uint64_t size) { } #endif +#if ASIL_SHM_MODE == ASIL_SHM_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() { @@ -111,6 +140,22 @@ void ClearTrigger(int fd) { #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; @@ -123,17 +168,73 @@ Error CopyName(const char *name, char (&out)[kMaxChannelNameLength + 1]) { return Error::kOk; } +bool PushSlotQueue(shm::SlotQueue *queue, int32_t slot_id, uint64_t ordinal) { + const size_t capacity = queue->capacity; + if (capacity == 0) { + return false; + } + shm::SlotQueueEntry *entries = queue->Entries(); + shm::SlotQueueEntry *entry = nullptr; + uint64_t tail = queue->tail.load(std::memory_order_relaxed); + for (size_t attempt = 0; attempt < shm::kMaxSlotQueueCasAttempts; ++attempt) { + const uint64_t head = queue->head.load(std::memory_order_acquire); + if (tail - head >= capacity) { + if (!queue->drop_oldest) { + return false; + } + // Evict the oldest entry, as InPlaceSlotQueue::DropFront does. + shm::SlotQueueEntry &front = entries[head % capacity]; + uint64_t expected = head; + if (front.sequence.load(std::memory_order_acquire) != head + 1 || + !queue->head.compare_exchange_weak(expected, head + 1, + std::memory_order_acq_rel, + std::memory_order_relaxed)) { + return false; + } + front.sequence.store(head + capacity, std::memory_order_release); + queue->overflow_count.fetch_add(1, std::memory_order_release); + tail = queue->tail.load(std::memory_order_relaxed); + continue; + } + shm::SlotQueueEntry &candidate = entries[tail % capacity]; + if (candidate.sequence.load(std::memory_order_acquire) != tail) { + return false; + } + if (queue->tail.compare_exchange_strong(tail, tail + 1, + std::memory_order_acq_rel, + std::memory_order_relaxed)) { + entry = &candidate; + break; + } + } + if (entry == nullptr) { + 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 MarkSlotQueueInsertionFailure(shm::SlotQueue *queue) { + queue->insertion_failed.store(true, std::memory_order_release); +} + Error ChannelMemory::Map(shm::SystemControlBlock *scb, int ccb_fd, int bcb_fd, int num_slots, int32_t checksum_size, - int32_t metadata_size) { + int32_t metadata_size, + uint64_t subscriber_queue_arena_size, + const BufferContext *context) { if (ccb_ != nullptr) { return Error::kAlreadyInitialized; } - if (num_slots <= 0) { - // The channel has no layout yet. Static channels always have one. - return Error::kUnsupported; + 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, 0); + const size_t ccb_size = shm::CcbSize(num_slots, subscriber_queue_arena_size); if (ccb_size > kMaxCcbSize) { return Error::kLayoutMismatch; } @@ -147,8 +248,8 @@ Error ChannelMemory::Map(shm::SystemControlBlock *scb, int ccb_fd, int bcb_fd, (void)::munmap(ccb, ccb_size); return Error::kLayoutMismatch; } - void *bcb = MapFd(bcb_fd, sizeof(shm::BufferControlBlock), - PROT_READ | PROT_WRITE); + void *bcb = + MapFd(bcb_fd, sizeof(shm::BufferControlBlock), PROT_READ | PROT_WRITE); if (bcb == MAP_FAILED) { (void)::munmap(ccb, ccb_size); return Error::kSharedMemoryError; @@ -156,7 +257,9 @@ Error ChannelMemory::Map(shm::SystemControlBlock *scb, int ccb_fd, int bcb_fd, scb_ = scb; ccb_ = typed_ccb; bcb_ = static_cast(bcb); + context_ = context; ccb_size_ = ccb_size; + queue_arena_size_ = static_cast(subscriber_queue_arena_size); num_slots_ = num_slots; checksum_size_ = checksum_size > 0 ? checksum_size : 4; metadata_size_ = metadata_size > 0 ? metadata_size : 0; @@ -165,12 +268,7 @@ Error ChannelMemory::Map(shm::SystemControlBlock *scb, int ccb_fd, int bcb_fd, } void ChannelMemory::Unmap() { - if (buffer_ != nullptr) { - (void)::munmap(buffer_, buffer_size_); - buffer_ = nullptr; - buffer_size_ = 0; - slot_size_ = 0; - } + UnmapBuffers(); if (bcb_ != nullptr) { (void)::munmap(bcb_, sizeof(shm::BufferControlBlock)); bcb_ = nullptr; @@ -181,13 +279,41 @@ void ChannelMemory::Unmap() { ccb_size_ = 0; } scb_ = nullptr; + context_ = nullptr; + queue_arena_size_ = 0; num_slots_ = 0; } -Error ChannelMemory::BufferName(const char *channel_name, uint64_t session_id, +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(channel_name, sanitized); e != Error::kOk) { + if (Error e = CopyName(context_->channel_name, sanitized); e != Error::kOk) { return e; } for (char *p = sanitized; *p != '\0'; p++) { @@ -200,23 +326,59 @@ Error ChannelMemory::BufferName(const char *channel_name, uint64_t session_id, #else const char *format = "subspace_%llu_%s_%d"; #endif - const int n = - std::snprintf(out, sizeof(out), format, - static_cast(session_id), sanitized, 0); + 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::MapBuffer(int fd, uint64_t size, int prot) { +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 > 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 < 100; attempt++) { + for (int attempt = 0; attempt < kBufferWaitMilliseconds; attempt++) { p = MapFd(fd, static_cast(size), prot); if (p != MAP_FAILED || errno != EINVAL) { break; @@ -227,38 +389,112 @@ Error ChannelMemory::MapBuffer(int fd, uint64_t size, int prot) { if (p == MAP_FAILED) { return Error::kSharedMemoryError; } - buffer_ = static_cast(p); - buffer_size_ = size; + index_ = index; + base_ = static_cast(p); + size_ = size; slot_size_ = static_cast((size - prefixes) / static_cast(num_slots_)); return Error::kOk; } -Error ChannelMemory::CreateOrAttachBuffer(const char *channel_name, - uint64_t session_id, - int64_t slot_size, int32_t user_id, - int32_t group_id) { +// Opens buffer index, which has already been created. +Error ChannelMemory::OpenBuffer(int index, bool writable, UniqueFd &fd, + uint64_t &size) const { +#if ASIL_SHM_MODE == ASIL_SHM_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 ASIL_SHM_MODE == ASIL_SHM_POSIX + char shm_name[64]; + if (Error e = PosixShmName(name, shm_name); e != Error::kOk) { + return e; + } + fd.Reset(OpenShm(shm_name, flags)); + struct stat st; + if (!fd.Valid() || ::stat(name, &st) != 0) { + return Error::kSharedMemoryError; + } + size = static_cast(st.st_size); +#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 (buffer_ != nullptr) { + if (index_ != -1) { return Error::kAlreadyInitialized; } - int num_buffers = ccb_->num_buffers.load(std::memory_order_relaxed); - if (num_buffers > 1) { - // The channel has been resized. - return Error::kUnsupported; + int index = -1; + if (Error e = NewestIndex(index); e != Error::kOk) { + return e; } - const uint64_t full_size = - static_cast(num_slots_) * - (static_cast(slot_size) + static_cast(prefix_size_)); + 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(channel_name, session_id, name); e != Error::kOk) { + if (Error e = BufferName(0, name); e != Error::kOk) { return e; } +#if ASIL_SHM_MODE == ASIL_SHM_MEMFD + UniqueFd fd(CreateMemfd(name, full_size)); + if (!fd.Valid()) { + return Error::kSharedMemoryError; + } +#else const bool root = ::getuid() == 0; - uint64_t size = full_size; #if ASIL_SHM_MODE == ASIL_SHM_POSIX if (Error e = CreateShadowFile(name, full_size); e != Error::kOk) { return e; @@ -267,142 +503,193 @@ Error ChannelMemory::CreateOrAttachBuffer(const char *channel_name, if (Error e = PosixShmName(name, shm_name); e != Error::kOk) { return e; } - int fd = OpenShm(shm_name, O_RDWR | O_CREAT | O_EXCL); - if (fd >= 0) { - if (::ftruncate(fd, static_cast(full_size)) != 0 || - ::chmod(name, 0777) != 0 || - (root && ::chown(name, static_cast(user_id), - static_cast(group_id)) != 0)) { - (void)::close(fd); - return Error::kSharedMemoryError; - } - } else if (errno == EEXIST) { - fd = OpenShm(shm_name, O_RDWR); - struct stat st; - if (fd < 0 || ::stat(name, &st) != 0) { - if (fd >= 0) { - (void)::close(fd); - } - return Error::kSharedMemoryError; - } - size = static_cast(st.st_size); - } else { + 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 (::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)) { return Error::kSharedMemoryError; } -#elif ASIL_SHM_MODE == ASIL_SHM_LINUX - int fd = OpenShm(name, O_RDWR | O_CREAT | O_EXCL); - if (fd >= 0) { - char path[kMaxChannelNameLength + 80]; - (void)std::snprintf(path, sizeof(path), "/dev/shm/%s", name); - if (::ftruncate(fd, static_cast(full_size)) != 0 || - ::chmod(path, 0777) != 0 || - (root && ::chown(path, static_cast(user_id), - static_cast(group_id)) != 0)) { - (void)::close(fd); - return Error::kSharedMemoryError; - } - } else if (errno == EEXIST) { - fd = OpenShm(name, O_RDWR); - if (fd < 0) { - return Error::kSharedMemoryError; - } - size = 0; - for (int attempt = 0; attempt < 100 && size == 0; attempt++) { - struct stat st; - if (::fstat(fd, &st) != 0) { - (void)::close(fd); - return Error::kSharedMemoryError; - } - size = static_cast(st.st_size); - if (size == 0) { - SleepMillisecond(); - } +#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 ASIL_SHM_MODE == ASIL_SHM_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); } - } else { - return Error::kSharedMemoryError; + return e; } -#else - (void)root; - (void)size; - (void)user_id; - (void)group_id; - // Memfd buffers are passed between clients by the server. - return Error::kUnsupported; #endif -#if ASIL_SHM_MODE != ASIL_SHM_MEMFD - const Error e = MapBuffer(fd, size, PROT_READ | PROT_WRITE); - (void)::close(fd); - if (e != Error::kOk) { - return e; + 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 (slot_size_ != slot_size) { - Unmap(); - return Error::kLayoutMismatch; + if (index_ != -1) { + return Error::kAlreadyInitialized; } - bcb_->sizes[0].store(size, std::memory_order_relaxed); - while (!ccb_->num_buffers.compare_exchange_strong( - num_buffers, 1, std::memory_order_release, std::memory_order_relaxed)) { - if (num_buffers > 1) { - Unmap(); - return Error::kUnsupported; + 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::kOk; -#endif + return Error::kSharedMemoryError; } -Error ChannelMemory::AttachBuffer(const char *channel_name, - uint64_t session_id) { +Error ChannelMemory::AttachSplitBuffers(bool writable, SplitSlot *slots, + int32_t capacity, + const SplitBufferAllocator &allocator) { if (ccb_ == nullptr) { return Error::kNotInitialized; } - if (buffer_ != nullptr) { - return Error::kOk; + if (index_ != -1) { + return Error::kAlreadyInitialized; } - const int num_buffers = ccb_->num_buffers.load(std::memory_order_acquire); - if (num_buffers == 0) { - return Error::kOk; + if (slots == nullptr) { + return Error::kInvalidArgument; } - if (num_buffers > 1) { - return Error::kUnsupported; + if (capacity < num_slots_) { + return Error::kCapacityExceeded; } - char name[kMaxChannelNameLength + 64]; - if (Error e = BufferName(channel_name, session_id, name); e != Error::kOk) { + int index = -1; + if (Error e = NewestIndex(index); e != Error::kOk) { return e; } -#if ASIL_SHM_MODE == ASIL_SHM_POSIX - char shm_name[64]; - if (Error e = PosixShmName(name, shm_name); e != Error::kOk) { + 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; } - const int fd = OpenShm(shm_name, O_RDONLY); - struct stat st; - if (fd < 0 || ::stat(name, &st) != 0) { - if (fd >= 0) { - (void)::close(fd); - } + 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; } -#elif ASIL_SHM_MODE == ASIL_SHM_LINUX - const int fd = OpenShm(name, O_RDONLY); - struct stat st; - if (fd < 0 || ::fstat(fd, &st) != 0) { - if (fd >= 0) { - (void)::close(fd); + 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; } -#else - return Error::kUnsupported; -#endif -#if ASIL_SHM_MODE != ASIL_SHM_MEMFD - Error e = Error::kOk; - if (st.st_size > 0) { - e = MapBuffer(fd, static_cast(st.st_size), PROT_READ); + void *p = MapFd(reply.fd.Get(), static_cast(payload_size), prot); + if (p == MAP_FAILED) { + return Error::kSharedMemoryError; } - (void)::close(fd); - return e; -#endif + slot.mapping.address = p; + slot.mapping.size = payload_size; + return Error::kOk; } shm::MessageSlot *ChannelMemory::Slot(int id) const { @@ -412,11 +699,22 @@ shm::MessageSlot *ChannelMemory::Slot(int id) const { } shm::MessagePrefix *ChannelMemory::Prefix(const shm::MessageSlot *slot) const { - const int64_t stride = prefix_size_ + shm::Aligned64(slot_size_); - return reinterpret_cast(buffer_ + stride * slot->id); + 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_; } @@ -447,6 +745,23 @@ shm::AvailableSlotQueueIndex *ChannelMemory::QueueIndex() const { reinterpret_cast(ccb_) + shm::SlotQueueIndexOffset(num_slots_)); } +shm::SlotQueue *ChannelMemory::Queue(int sub_id) const { + const uint64_t offset = + QueueIndex()->offsets[sub_id].load(std::memory_order_acquire); + if (offset == shm::kInvalidSlotQueueOffset || offset > queue_arena_size_ || + queue_arena_size_ - offset < sizeof(shm::SlotQueue)) { + return nullptr; + } + auto *queue = reinterpret_cast( + reinterpret_cast(ccb_) + shm::SlotQueueArenaOffset(num_slots_) + + offset); + const size_t room = queue_arena_size_ - offset - sizeof(shm::SlotQueue); + if (queue->capacity > room / sizeof(shm::SlotQueueEntry)) { + return nullptr; + } + return queue; +} + int ChannelMemory::NumSubscribers(int vchan_id) const { const shm::SubscriberCounter &counter = ccb_->num_subs; for (;;) { @@ -456,11 +771,10 @@ int ChannelMemory::NumSubscribers(int vchan_id) const { return shm::kMaxSlotOwners; } const int mux_count = counter.counts[0].load(std::memory_order_relaxed); - const int count = - vchan_id == -1 - ? mux_count - : mux_count + - counter.counts[vchan_id + 1].load(std::memory_order_relaxed); + const int count = vchan_id == -1 + ? mux_count + : mux_count + counter.counts[vchan_id + 1].load( + std::memory_order_relaxed); if (counter.sequence.load(std::memory_order_acquire) == before) { return count; } @@ -473,12 +787,13 @@ uint64_t ChannelMemory::CleanupGeneration(int vchan_id) const { if (vchan_id == -1) { return mux_generation; } - return mux_generation + ccb_->subscriber_cleanup_generation[vchan_id + 1].load( - std::memory_order_acquire); + return mux_generation + + ccb_->subscriber_cleanup_generation[vchan_id + 1].load( + std::memory_order_acquire); } -bool ChannelMemory::AtomicIncRefCount(shm::MessageSlot *slot, int inc, - uint64_t ordinal, int vchan_id, +bool ChannelMemory::AtomicIncRefCount(shm::MessageSlot *slot, bool reliable, + int inc, uint64_t ordinal, int vchan_id, bool retire, bool *retired) { if (retired != nullptr) { *retired = false; @@ -489,19 +804,24 @@ bool ChannelMemory::AtomicIncRefCount(shm::MessageSlot *slot, int inc, if ((ref & shm::kPubOwned) != 0) { return false; } - const uint64_t ref_ordinal = (ref >> shm::kOrdinalShift) & shm::kOrdinalMask; + const uint64_t ref_ordinal = + (ref >> shm::kOrdinalShift) & shm::kOrdinalMask; const int ref_vchan_id = shm::RefsVchanId(ref); if (ref_ordinal != 0 && ordinal != 0 && (ref_ordinal != ordinal || ref_vchan_id != vchan_id)) { return false; } uint64_t refs = ref & shm::kRefCountMask; - const uint64_t reliable_refs = + uint64_t reliable_refs = (ref >> shm::kReliableRefCountShift) & shm::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); + } uint64_t retired_refs = (ref >> shm::kRetiredRefsShift) & shm::kRetiredRefsMask; if (retire) { @@ -514,8 +834,7 @@ bool ChannelMemory::AtomicIncRefCount(shm::MessageSlot *slot, int inc, std::memory_order_acq_rel, std::memory_order_relaxed)) { if (retire && refs == 0 && reliable_refs == 0 && - retired_refs >= - static_cast(NumSubscribers(ref_vchan_id)) && + retired_refs >= static_cast(NumSubscribers(ref_vchan_id)) && RetiredSlots().SetWasClear(slot->id) && retired != nullptr) { *retired = true; } diff --git a/asil_client/channel_memory.h b/asil_client/channel_memory.h index ae5bea78..3593016a 100644 --- a/asil_client/channel_memory.h +++ b/asil_client/channel_memory.h @@ -11,6 +11,7 @@ #include "asil_client/error.h" #include "asil_client/server_connection.h" #include "asil_client/shm_layout.h" +#include "asil_client/split_buffer.h" #include #include @@ -30,9 +31,28 @@ 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; +}; + +// InPlaceSlotQueue::Push with report_insertion_failure false. +bool PushSlotQueue(shm::SlotQueue *queue, int32_t slot_id, uint64_t ordinal); +// InPlaceSlotQueue::MarkInsertionFailure. +void MarkSlotQueueInsertionFailure(shm::SlotQueue *queue); + class ChannelMemory { public: ChannelMemory() = default; @@ -40,22 +60,38 @@ class ChannelMemory { ChannelMemory(const ChannelMemory &) = delete; ChannelMemory &operator=(const ChannelMemory &) = delete; - // Maps the CCB and BCB. The SCB is mapped by the client. - Error Map(shm::SystemControlBlock *scb, int ccb_fd, int bcb_fd, - int num_slots, int32_t checksum_size, int32_t metadata_size); + // 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(); - - // Publishers create the channel's buffer, or attach to the buffer another - // publisher created. The buffer's slot size must be slot_size. - Error CreateOrAttachBuffer(const char *channel_name, uint64_t session_id, - int64_t slot_size, int32_t user_id, - int32_t group_id); - // Subscribers attach to the buffer read-only once a publisher has made it. - // Returns kOk without a buffer when there isn't one yet. - Error AttachBuffer(const char *channel_name, uint64_t session_id); - bool HasBuffer() const { return buffer_ != nullptr; } + 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_; + } int NumSlots() const { return num_slots_; } + // 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_; } @@ -67,6 +103,8 @@ class ChannelMemory { } shm::MessageSlot *Slot(int id) const; + // 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; @@ -75,14 +113,17 @@ class ChannelMemory { BitsetView AvailableSlots(int sub_id) const; BitsetView Subscribers() const; shm::AvailableSlotQueueIndex *QueueIndex() const; + // The subscriber's queue, or null if it has none. + shm::SlotQueue *Queue(int sub_id) const; int NumSubscribers(int vchan_id) const; uint64_t CleanupGeneration(int vchan_id) const; // Channel::AtomicIncRefCount. Sets *retired when this call retired the // slot. - bool AtomicIncRefCount(shm::MessageSlot *slot, int inc, uint64_t ordinal, - int vchan_id, bool retire, bool *retired); + bool AtomicIncRefCount(shm::MessageSlot *slot, bool reliable, int inc, + uint64_t ordinal, int vchan_id, bool retire, + bool *retired); // Channel::TryRetireSlot. bool TryRetireSlot(shm::MessageSlot *slot); @@ -91,22 +132,37 @@ class ChannelMemory { void TriggerRetirement(const TriggerFdList &triggers, int32_t slot_id) const; private: - Error BufferName(const char *channel_name, uint64_t session_id, - char (&out)[kMaxChannelNameLength + 64]) const; - Error MapBuffer(int fd, uint64_t size, int prot); + 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::ChannelControlBlock *ccb_ = nullptr; shm::BufferControlBlock *bcb_ = nullptr; + const BufferContext *context_ = nullptr; size_t ccb_size_ = 0; + size_t queue_arena_size_ = 0; int num_slots_ = 0; int32_t checksum_size_ = 4; int32_t metadata_size_ = 0; int32_t prefix_size_ = 64; - char *buffer_ = nullptr; - uint64_t buffer_size_ = 0; + // 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 diff --git a/asil_client/client.h b/asil_client/client.h index b7cef1c7..054c0b85 100644 --- a/asil_client/client.h +++ b/asil_client/client.h @@ -4,12 +4,13 @@ // A Subspace client for safety-related software. // -// The client publishes and reads messages on unreliable, fixed-size channels, -// 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. Memory is allocated only by the -// ServerConnection while it talks to the server; publishing and reading -// messages allocate nothing. +// 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. // // subspace::asil::PhaserServerConnection connection; // connection.Connect("/tmp/subspace"); diff --git a/asil_client/error.cc b/asil_client/error.cc index edf14209..8b672716 100644 --- a/asil_client/error.cc +++ b/asil_client/error.cc @@ -39,6 +39,12 @@ const char *ErrorString(Error error) { 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"; } diff --git a/asil_client/error.h b/asil_client/error.h index fae48eae..58290ad8 100644 --- a/asil_client/error.h +++ b/asil_client/error.h @@ -41,6 +41,14 @@ enum class Error : int32_t { 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. diff --git a/asil_client/layout_test.cc b/asil_client/layout_test.cc index bc5295d0..7320a6ef 100644 --- a/asil_client/layout_test.cc +++ b/asil_client/layout_test.cc @@ -5,6 +5,7 @@ // Checks that the ASIL client's view of shared memory matches // common/channel.h, and that its checksum matches the standard client's. +#include "asil_client/channel_memory.h" #include "asil_client/checksum.h" #include "asil_client/shm_layout.h" #include "client/checksum.h" @@ -22,7 +23,7 @@ namespace { namespace shm = ::subspace::asil::shm; #define EXPECT_SAME_OFFSET(type, field) \ - EXPECT_EQ(offsetof(::subspace::type, field), offsetof(shm::type, field)) \ + EXPECT_EQ(offsetof(::subspace::type, field), offsetof(shm::type, field)) \ << #type "::" #field TEST(LayoutTest, Constants) { @@ -35,10 +36,13 @@ TEST(LayoutTest, Constants) { EXPECT_EQ(::subspace::kInvalidSlotQueueOffset, shm::kInvalidSlotQueueOffset); EXPECT_EQ(::subspace::kMessageActivate, shm::kMessageActivate); EXPECT_EQ(::subspace::kMessageHasChecksum, shm::kMessageHasChecksum); - EXPECT_EQ(static_cast(::subspace::kMessageSeen), - shm::kMessageSeen); + EXPECT_EQ(static_cast(::subspace::kMessageSeen), shm::kMessageSeen); EXPECT_EQ(static_cast(::subspace::kMessageIsActivation), shm::kMessageIsActivation); + EXPECT_EQ(static_cast(::subspace::kMessageSeenByReliable), + shm::kMessageSeenByReliable); + EXPECT_EQ(::subspace::kMaxSlotQueueCasAttempts, + shm::kMaxSlotQueueCasAttempts); EXPECT_EQ(::subspace::kPubOwned, shm::kPubOwned); EXPECT_EQ(::subspace::kRefsMask, shm::kRefsMask); EXPECT_EQ(::subspace::kRefCountMask, shm::kRefCountMask); @@ -142,6 +146,9 @@ TEST(LayoutTest, CcbRegions) { 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, 0), ::subspace::CcbSize(num_slots, 0)); EXPECT_EQ(shm::CcbSize(num_slots, 64000), ::subspace::CcbSize(num_slots, 64000)); @@ -151,9 +158,9 @@ TEST(LayoutTest, CcbRegions) { TEST(LayoutTest, PrefixSize) { for (int32_t checksum_size : {0, 4, 16, 17}) { for (int32_t metadata_size : {0, 1, 16, 100}) { - EXPECT_EQ(shm::PrefixSize(checksum_size, metadata_size), - ::subspace::Channel::ComputePrefixSize(checksum_size, - metadata_size)); + EXPECT_EQ( + shm::PrefixSize(checksum_size, metadata_size), + ::subspace::Channel::ComputePrefixSize(checksum_size, metadata_size)); } } } @@ -169,6 +176,70 @@ TEST(LayoutTest, RefsBitField) { } } +TEST(LayoutTest, SlotQueue) { + EXPECT_EQ(sizeof(::subspace::InPlaceSlotQueue), sizeof(shm::SlotQueue)); + EXPECT_EQ(sizeof(::subspace::SlotQueueEntry), sizeof(shm::SlotQueueEntry)); + EXPECT_SAME_OFFSET(SlotQueueEntry, sequence); + EXPECT_SAME_OFFSET(SlotQueueEntry, ordinal); + EXPECT_SAME_OFFSET(SlotQueueEntry, slot_id); +} + +// A queue in a buffer, initialized by the standard client and used through +// both views. +struct QueueMemory { + explicit QueueMemory(size_t capacity, bool drop_oldest) + : memory(::subspace::SizeofSlotQueue(capacity) / sizeof(uint64_t) + 1), + standard(new (memory.data())::subspace::InPlaceSlotQueue(capacity, + drop_oldest)), + asil(reinterpret_cast(memory.data())) {} + + std::vector memory; + ::subspace::InPlaceSlotQueue *standard; + shm::SlotQueue *asil; +}; + +TEST(SlotQueueTest, AsilPushesStandardPops) { + QueueMemory queue(4, /*drop_oldest=*/true); + EXPECT_EQ(4u, queue.asil->capacity); + for (int32_t i = 0; i < 6; i++) { + EXPECT_TRUE( + ::subspace::asil::internal::PushSlotQueue(queue.asil, i, 100 + i)); + } + // The two oldest entries made room for the newest. + EXPECT_EQ(2u, queue.standard->OverflowCount()); + for (int32_t i = 2; i < 6; i++) { + ::subspace::QueuedSlot slot; + ASSERT_TRUE(queue.standard->TryPop(slot)); + EXPECT_EQ(i, slot.slot_id); + EXPECT_EQ(static_cast(100 + i), slot.ordinal); + } + ::subspace::QueuedSlot slot; + EXPECT_FALSE(queue.standard->TryPop(slot)); + + // Entries wrap around the ring. + EXPECT_TRUE(::subspace::asil::internal::PushSlotQueue(queue.asil, 9, 109)); + ASSERT_TRUE(queue.standard->TryPop(slot)); + EXPECT_EQ(9, slot.slot_id); +} + +TEST(SlotQueueTest, InheritedQueueRejectsWhenFull) { + QueueMemory queue(2, /*drop_oldest=*/false); + EXPECT_TRUE(::subspace::asil::internal::PushSlotQueue(queue.asil, 0, 1)); + EXPECT_TRUE(::subspace::asil::internal::PushSlotQueue(queue.asil, 1, 2)); + EXPECT_FALSE(::subspace::asil::internal::PushSlotQueue(queue.asil, 2, 3)); + EXPECT_FALSE(queue.standard->InsertionFailed()); + ::subspace::asil::internal::MarkSlotQueueInsertionFailure(queue.asil); + EXPECT_TRUE(queue.standard->InsertionFailed()); + EXPECT_EQ(0u, queue.standard->OverflowCount()); + + // A standard push is visible to the ASIL view. + QueueMemory other(2, /*drop_oldest=*/true); + ASSERT_TRUE(other.standard->Push(7, 70)); + EXPECT_EQ(1u, other.asil->tail.load()); + EXPECT_EQ(7, other.asil->Entries()[0].slot_id.load()); + EXPECT_EQ(70u, other.asil->Entries()[0].ordinal.load()); +} + TEST(ChecksumTest, MatchesStandardClient) { std::mt19937 random(42); for (size_t length : {0, 1, 3, 4, 7, 8, 9, 63, 64, 1000}) { diff --git a/asil_client/phaser_connection.cc b/asil_client/phaser_connection.cc index 71b9909c..f2e20dc5 100644 --- a/asil_client/phaser_connection.cc +++ b/asil_client/phaser_connection.cc @@ -160,6 +160,38 @@ Error PhaserServerConnection::Send(size_t length) { 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(size_t &length) { @@ -190,8 +222,8 @@ Error PhaserServerConnection::Receive(size_t &length) { // 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))]; + alignas( + struct cmsghdr) char control[CMSG_SPACE(kMaxFdsPerMessage * sizeof(int))]; int32_t received = 0; bool overflow = false; for (;;) { @@ -259,8 +291,9 @@ Error PhaserServerConnection::ReceiveFds() { } // 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) { +Error PhaserServerConnection::Transact(Build build, Read read, int send_fd) { if (!socket_.Valid()) { return Error::kNotInitialized; } @@ -284,6 +317,9 @@ Error PhaserServerConnection::Transact(Build build, Read read) { } Error e = Send(length); + if (e == Error::kOk && send_fd >= 0) { + e = SendFd(send_fd); + } if (e == Error::kOk) { e = Receive(length); } @@ -353,12 +389,19 @@ Error PhaserServerConnection::CreatePublisher(const PublisherRequest &request, cmd->set_slot_size(request.slot_size); cmd->set_num_slots(request.num_slots); cmd->set_is_fixed_size(true); + cmd->set_is_reliable(request.reliable); if (request.type != nullptr) { cmd->set_type(View(request.type)); } - cmd->set_vchan_id(-1); + 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); @@ -385,6 +428,10 @@ Error PhaserServerConnection::CreatePublisher(const PublisherRequest &request, 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); }, @@ -406,11 +453,15 @@ Error PhaserServerConnection::CreateSubscriber(const SubscriberRequest &request, 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); - cmd->set_vchan_id(-1); + 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) { @@ -450,7 +501,9 @@ Error PhaserServerConnection::CreateSubscriber(const SubscriberRequest &request, } if (Error e = FillFdList( fds_, sub.reliable_pub_trigger_fd_indexes_size(), - [&](size_t i) { return sub.reliable_pub_trigger_fd_indexes(i); }, + [&](size_t i) { + return sub.reliable_pub_trigger_fd_indexes(i); + }, reply.reliable_publisher_triggers); e != Error::kOk) { return e; @@ -533,5 +586,89 @@ Error PhaserServerConnection::RemoveSubscriber(const char *channel_name, }); } +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 index 09dee295..f195576f 100644 --- a/asil_client/phaser_connection.h +++ b/asil_client/phaser_connection.h @@ -52,6 +52,8 @@ class PhaserServerConnection : public ServerConnection { 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_; } @@ -59,8 +61,9 @@ class PhaserServerConnection : public ServerConnection { private: template - Error Transact(Build build, Read read); + Error Transact(Build build, Read read, int send_fd = -1); Error Send(size_t length); + Error SendFd(int fd); Error Receive(size_t &length); Error ReceiveFds(); Error Rejected(const char *message, size_t length); diff --git a/asil_client/publisher.cc b/asil_client/publisher.cc index b59c495d..c87aa579 100644 --- a/asil_client/publisher.cc +++ b/asil_client/publisher.cc @@ -3,8 +3,8 @@ // See LICENSE file for licensing information. // The publishing side of the shared memory protocol. This follows -// PublisherImpl::FindFreeSlotUnreliable and -// PublisherImpl::ActivateSlotAndGetAnother in client/publisher.cc. +// PublisherImpl::FindFreeSlotUnreliable, PublisherImpl::FindFreeSlotReliable +// and PublisherImpl::ActivateSlotAndGetAnother in client/publisher.cc. #include "asil_client/publisher.h" @@ -21,6 +21,16 @@ namespace { bool ValidLayoutSize(int32_t size) { return size >= 0 && size <= 0xFFFF; } +// Slots are ordered by timestamp, then by id, as a stable sort by timestamp +// orders them. +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; +} + } // namespace Error Publisher::Open(Client &client, const char *channel_name, @@ -33,12 +43,18 @@ Error Publisher::Open(Client &client, const char *channel_name, } if (options.slot_size <= 0 || options.num_slots <= 0 || !ValidLayoutSize(options.checksum_size) || - !ValidLayoutSize(options.metadata_size)) { + !ValidLayoutSize(options.metadata_size) || 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; + } const int64_t slot_size = shm::Aligned64(options.slot_size); PublisherRequest request; @@ -48,6 +64,11 @@ Error Publisher::Open(Client &client, const char *channel_name, 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_; @@ -59,24 +80,40 @@ Error Publisher::Open(Client &client, const char *channel_name, 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_; Error e = Error::kOk; - if (reply.vchan_id != -1 || reply.subscriber_queue_arena_size != 0 || - channel_id_ < 0 || channel_id_ >= shm::kMaxChannels || - publisher_id_ < 0 || publisher_id_ >= shm::kMaxSlotOwners) { - e = Error::kUnsupported; + 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)) { + 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, - options.checksum_size, options.metadata_size); + options.checksum_size, options.metadata_size, + reply.subscriber_queue_arena_size, &buffer_context_); } if (e == Error::kOk) { - e = memory_.CreateOrAttachBuffer(name_, client.session_id_, slot_size, - client.user_id_, client.group_id_); + e = options.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(); @@ -90,10 +127,12 @@ Error Publisher::Open(Client &client, const char *channel_name, } BitsetView activations(&memory_.Ccb()->activation_tracker, shm::kMaxVchanId + 1); - if (options.activate && !activations.IsSet(0)) { + if (reliable_ || (options.activate && !activations.IsSet(vchan_id_ + 1))) { + // 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_ = FindFreeSlot(); + slot_ = reliable_ ? nullptr : FindFreeSlot(); } TriggerSubscribers(); return Error::kOk; @@ -103,10 +142,13 @@ 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() { @@ -114,16 +156,35 @@ Error Publisher::Close() { return Error::kOk; } // The server releases the slot this publisher holds. - const Error e = - client_->connection_->RemovePublisher(name_, publisher_id_); + 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 && client_ != nullptr) { - slot_ = FindFreeSlot(); + 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; } @@ -158,14 +219,14 @@ Error Publisher::Publish(size_t message_size, PublishedMessage *published) { } slot_->message_size.store(message_size, std::memory_order_relaxed); PublishSlot(slot_, /*is_activation=*/false, published); - slot_ = FindFreeSlot(); + // 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; + const uint16_t updates = memory_.Counters(channel_id_).num_sub_updates; if (updates == num_sub_updates_) { return Error::kOk; } @@ -185,6 +246,10 @@ void Publisher::TriggerSubscribers() const { } } +shm::MessageSlot *Publisher::FindFreeSlot() { + return reliable_ ? FindFreeSlotReliable() : FindFreeSlotUnreliable(); +} + int Publisher::FindRetiredSlotToReuse(bool oldest_first) const { BitsetView retired = memory_.RetiredSlots(); if (!oldest_first) { @@ -208,11 +273,22 @@ int Publisher::FindRetiredSlotToReuse(bool oldest_first) const { return oldest; } -shm::MessageSlot *Publisher::FindFreeSlot() { +// Takes ownership of slot if no other publisher or subscriber has it. +bool Publisher::ClaimSlot(shm::MessageSlot *slot) { + const uint64_t owner = shm::kPubOwned | static_cast(publisher_id_); + const uint64_t old_refs = slot->refs.load(std::memory_order_relaxed); + uint64_t expected = shm::BuildRefsBitField( + slot->ordinal.load(std::memory_order_relaxed), + static_cast((old_refs >> shm::kVchanIdShift) & shm::kVchanIdMask), + (old_refs >> shm::kRetiredRefsShift) & shm::kRetiredRefsMask); + return slot->refs.compare_exchange_weak( + expected, owner, std::memory_order_acquire, std::memory_order_relaxed); +} + +shm::MessageSlot *Publisher::FindFreeSlotUnreliable() { shm::ChannelControlBlock *ccb = memory_.Ccb(); BitsetView free_slots = memory_.FreeSlots(); BitsetView retired_slots = memory_.RetiredSlots(); - const uint64_t owner = shm::kPubOwned | static_cast(publisher_id_); constexpr int kMaxCasRetries = 1000; int retries = memory_.NumSlots() * 1000; int cas_retries = 0; @@ -223,7 +299,7 @@ shm::MessageSlot *Publisher::FindFreeSlot() { slot = nullptr; free_slot = -1; retired_slot = -1; - const bool no_subscribers = memory_.NumSubscribers(-1) == 0; + const bool no_subscribers = memory_.NumSubscribers(vchan_id_) == 0; if (!ccb->free_slots_exhausted.load(std::memory_order_relaxed) && (free_slot = free_slots.FindFirstSet()) != -1) { if (!free_slots.ClearWasSet(free_slot)) { @@ -260,14 +336,7 @@ shm::MessageSlot *Publisher::FindFreeSlot() { } continue; } - const uint64_t old_refs = slot->refs.load(std::memory_order_relaxed); - uint64_t expected = shm::BuildRefsBitField( - slot->ordinal.load(std::memory_order_relaxed), - static_cast((old_refs >> shm::kVchanIdShift) & shm::kVchanIdMask), - (old_refs >> shm::kRetiredRefsShift) & shm::kRetiredRefsMask); - if (slot->refs.compare_exchange_weak(expected, owner, - std::memory_order_acquire, - std::memory_order_relaxed)) { + if (ClaimSlot(slot)) { break; } if (++cas_retries >= kMaxCasRetries) { @@ -278,22 +347,149 @@ shm::MessageSlot *Publisher::FindFreeSlot() { (void)::sched_yield(); } } + PrepareClaimedSlot(slot, free_slot == -1 && retired_slot == -1); + return slot; +} + +// A reliable subscriber still needs a slot that it holds, and, when reliable +// subscribers exist, a message that none of them has seen. +bool Publisher::ReliableClaimable(shm::MessageSlot *slot, + bool require_reliable_seen) const { + const uint64_t refs = slot->refs.load(std::memory_order_relaxed); + if (((refs >> shm::kReliableRefCountShift) & shm::kRefCountMask) != 0) { + return false; + } + if (require_reliable_seen && + slot->ordinal.load(std::memory_order_relaxed) != 0 && + (slot->flags.load(std::memory_order_relaxed) & + shm::kMessageSeenByReliable) == 0) { + return false; + } + return (refs & shm::kRefsMask) == 0; +} + +// The oldest slot that no subscriber holds and that is older than every slot +// a reliable subscriber still needs. +shm::MessageSlot * +Publisher::OldestReliableCandidate(bool require_reliable_seen) const { + int stop = -1; + uint64_t stop_timestamp = 0; + for (int i = 0; i < memory_.NumSlots(); i++) { + shm::MessageSlot *s = memory_.Slot(i); + const uint64_t refs = s->refs.load(std::memory_order_relaxed); + if ((refs & shm::kPubOwned) != 0) { + continue; + } + const bool needed = + ((refs >> shm::kReliableRefCountShift) & shm::kRefCountMask) != 0 || + (require_reliable_seen && + s->ordinal.load(std::memory_order_relaxed) != 0 && + (s->flags.load(std::memory_order_relaxed) & + shm::kMessageSeenByReliable) == 0); + const uint64_t timestamp = s->timestamp.load(std::memory_order_relaxed); + if (needed && (stop == -1 || Earlier(timestamp, i, stop_timestamp, stop))) { + stop = i; + stop_timestamp = timestamp; + } + } + shm::MessageSlot *best = nullptr; + uint64_t best_timestamp = 0; + for (int i = 0; i < memory_.NumSlots(); i++) { + shm::MessageSlot *s = memory_.Slot(i); + const uint64_t refs = s->refs.load(std::memory_order_relaxed); + if ((refs & (shm::kPubOwned | shm::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; +} + +shm::MessageSlot *Publisher::FindFreeSlotReliable() { + shm::ChannelControlBlock *ccb = memory_.Ccb(); + BitsetView free_slots = memory_.FreeSlots(); + BitsetView retired_slots = memory_.RetiredSlots(); + constexpr int kMaxCasRetries = 1000; + int retries = memory_.NumSlots() * 1000; + int cas_retries = 0; + shm::MessageSlot *slot = nullptr; + int free_slot = -1; + int retired_slot = -1; + for (;;) { + slot = nullptr; + free_slot = -1; + retired_slot = -1; + const bool require_reliable_seen = + memory_.Counters(channel_id_).num_reliable_subs != 0; + if (!ccb->free_slots_exhausted.load(std::memory_order_relaxed) && + (free_slot = free_slots.FindFirstSet()) != -1) { + if (!free_slots.ClearWasSet(free_slot)) { + continue; + } + if (free_slots.IsEmpty()) { + ccb->free_slots_exhausted.store(true, std::memory_order_relaxed); + } + // A free slot has never held a message. + slot = memory_.Slot(free_slot); + } else if ((retired_slot = retired_slots.FindFirstSet()) != -1) { + if (!retired_slots.ClearWasSet(retired_slot)) { + continue; + } + slot = memory_.Slot(retired_slot); + if (!ReliableClaimable(slot, require_reliable_seen)) { + // The slot is still retired; it just can't be reused yet. + retired_slots.Set(retired_slot); + return nullptr; + } + } else { + slot = OldestReliableCandidate(require_reliable_seen); + if (slot == nullptr) { + return nullptr; + } + } + if (ClaimSlot(slot)) { + retired_slots.Clear(slot->id); + break; + } + if (++cas_retries >= kMaxCasRetries) { + if (retries-- == 0) { + return nullptr; + } + cas_retries = 0; + (void)::sched_yield(); + } + } + PrepareClaimedSlot(slot, free_slot == -1 && retired_slot == -1); + return slot; +} + +// Resets a slot this publisher has just claimed. forced_reuse is true when +// the slot held a message that a subscriber might not have seen. +void Publisher::PrepareClaimedSlot(shm::MessageSlot *slot, bool forced_reuse) { slot->ordinal.store(0, std::memory_order_relaxed); slot->timestamp.store(0, std::memory_order_relaxed); - slot->vchan_id.store(-1, std::memory_order_relaxed); + slot->vchan_id.store(static_cast(vchan_id_), + std::memory_order_relaxed); SetSlotBuffer(slot); shm::MessagePrefix *prefix = memory_.Prefix(slot); prefix->flags = 0; - prefix->vchan_id = -1; + prefix->vchan_id = vchan_id_; - memory_.Subscribers().Traverse( - [this, slot](int sub_id) { memory_.AvailableSlots(sub_id).Clear(slot->id); }); + // The old message is gone, so no subscriber should look for it. + memory_.Subscribers().Traverse([this, slot](int sub_id) { + memory_.AvailableSlots(sub_id).Clear(slot->id); + }); - if (free_slot == -1 && retired_slot == -1) { - // A message that some subscriber hasn't seen is being overwritten. + if (forced_reuse) { memory_.TriggerRetirement(retirement_triggers_, slot->id); } - return slot; } void Publisher::SetSlotBuffer(shm::MessageSlot *slot) { @@ -303,15 +499,17 @@ void Publisher::SetSlotBuffer(shm::MessageSlot *slot) { bcb->refs[old_index].load(std::memory_order_relaxed) > 0) { bcb->refs[old_index]--; } - slot->buffer_index.store(0, std::memory_order_relaxed); - bcb->refs[0]++; + 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::ChannelControlBlock *ccb = memory_.Ccb(); shm::MessagePrefix *prefix = memory_.Prefix(slot); - const uint64_t ordinal = ccb->ordinals[0].fetch_add(1); + const uint64_t ordinal = ccb->ordinals[vchan_id_ + 1].fetch_add(1); const uint64_t timestamp = internal::Now(); const uint64_t message_size = slot->message_size.load(std::memory_order_relaxed); @@ -322,7 +520,7 @@ void Publisher::PublishSlot(shm::MessageSlot *slot, bool is_activation, prefix->message_size = message_size; prefix->ordinal = ordinal; prefix->timestamp = timestamp; - prefix->vchan_id = -1; + prefix->vchan_id = vchan_id_; prefix->checksum_size = static_cast(memory_.ChecksumSize()); prefix->metadata_size = static_cast(memory_.MetadataSize()); prefix->flags = 0; @@ -331,7 +529,8 @@ void Publisher::PublishSlot(shm::MessageSlot *slot, bool is_activation, if (is_activation) { prefix->flags |= shm::kMessageActivate; slot->flags.fetch_or(shm::kMessageIsActivation, std::memory_order_relaxed); - BitsetView(&ccb->activation_tracker, shm::kMaxVchanId + 1).Set(0); + BitsetView(&ccb->activation_tracker, shm::kMaxVchanId + 1) + .Set(vchan_id_ + 1); } if (checksum_) { prefix->flags |= shm::kMessageHasChecksum; @@ -350,7 +549,7 @@ void Publisher::PublishSlot(shm::MessageSlot *slot, bool is_activation, std::memcpy(&prefix->checksum, &crc, sizeof(crc)); } - const uint64_t cleanup_generation = memory_.CleanupGeneration(-1); + const uint64_t cleanup_generation = memory_.CleanupGeneration(vchan_id_); // The server uses this count to tell when no publisher can be writing to a // subscriber queue. @@ -358,11 +557,18 @@ void Publisher::PublishSlot(shm::MessageSlot *slot, bool is_activation, memory_.QueueIndex()->active_publishers[publisher_id_]; active_publishers.fetch_add(1, std::memory_order_seq_cst); - // Mark the message available to every subscriber while the slot is still - // publisher owned. A subscriber can leave between the traversal and the - // set, so check membership again afterwards. + // Mark the message available to every subscriber on the publisher's + // virtual channel while the slot is still publisher owned. A subscriber + // can leave between the traversal and the set, so check membership again + // afterwards. The bitset is the authoritative record, so a queue that is + // full only loses a hint. memory_.Subscribers().Traverse( - [this, slot](int sub_id) { + [this, slot, ordinal](int sub_id) { + const int sub_vchan_id = memory_.Ccb()->sub_vchan_ids[sub_id]; + if (vchan_id_ != -1 && sub_vchan_id != -1 && + sub_vchan_id != vchan_id_) { + return; + } BitsetView available = memory_.AvailableSlots(sub_id); BitsetView subscribers = memory_.Subscribers(); available.Set(slot->id); @@ -373,6 +579,11 @@ void Publisher::PublishSlot(shm::MessageSlot *slot, bool is_activation, } available.Set(slot->id); } + shm::SlotQueue *queue = memory_.Queue(sub_id); + if (queue != nullptr && + !internal::PushSlotQueue(queue, slot->id, ordinal)) { + internal::MarkSlotQueueInsertionFailure(queue); + } }, std::memory_order_seq_cst); @@ -384,12 +595,13 @@ void Publisher::PublishSlot(shm::MessageSlot *slot, bool is_activation, } // Releasing publisher ownership makes the message readable. - slot->refs.store(shm::BuildRefsBitField(ordinal, -1, 0), + slot->refs.store(shm::BuildRefsBitField(ordinal, vchan_id_, 0), std::memory_order_release); ccb->total_messages.fetch_add(1, std::memory_order_seq_cst); // A subscriber removed while publishing lowers the retirement threshold. - if (!is_activation && memory_.CleanupGeneration(-1) != cleanup_generation && + if (!is_activation && + memory_.CleanupGeneration(vchan_id_) != cleanup_generation && memory_.TryRetireSlot(slot)) { memory_.TriggerRetirement(retirement_triggers_, slot->id); } diff --git a/asil_client/publisher.h b/asil_client/publisher.h index 4328ebac..90701f3c 100644 --- a/asil_client/publisher.h +++ b/asil_client/publisher.h @@ -7,6 +7,7 @@ #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 @@ -26,8 +27,27 @@ struct PublisherOptions { const char *type = nullptr; // Put a checksum in every message. bool checksum = false; - // Publish an activation message if the channel hasn't been activated. + // 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. They must exist already: the server + // creates them for a static channel, otherwise a standard publisher does. + // 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 { @@ -35,8 +55,10 @@ struct PublishedMessage { uint64_t timestamp = 0; }; -// An unreliable publisher for a fixed-size channel. It always holds a slot to -// write the next message into. +// 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 { @@ -52,13 +74,15 @@ class Publisher { Error Close(); bool IsOpen() const { return client_ != nullptr; } - // Where to write the next message, or null if every slot is in use. + // 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 every slot is in use. + // none or no slot is available. void *Metadata(); size_t MetadataSize() const { return static_cast(memory_.MetadataSize()); @@ -69,12 +93,27 @@ class Publisher { // 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(); shm::MessageSlot *FindFreeSlot(); + shm::MessageSlot *FindFreeSlotUnreliable(); + shm::MessageSlot *FindFreeSlotReliable(); + shm::MessageSlot *OldestReliableCandidate(bool require_reliable_seen) const; + bool ReliableClaimable(shm::MessageSlot *slot, + bool require_reliable_seen) const; + bool ClaimSlot(shm::MessageSlot *slot); + void PrepareClaimedSlot(shm::MessageSlot *slot, bool forced_reuse); int FindRetiredSlotToReuse(bool oldest_first) const; void SetSlotBuffer(shm::MessageSlot *slot); void PublishSlot(shm::MessageSlot *slot, bool is_activation, @@ -84,12 +123,19 @@ class Publisher { 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_; }; diff --git a/asil_client/server_connection.h b/asil_client/server_connection.h index 9545c610..40e47cad 100644 --- a/asil_client/server_connection.h +++ b/asil_client/server_connection.h @@ -5,8 +5,9 @@ // 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, and to fetch trigger file descriptors when the -// set of publishers or subscribers on a channel changes. Messages move +// 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. @@ -15,6 +16,7 @@ #include "asil_client/error.h" #include "asil_client/shm_layout.h" +#include "asil_client/split_buffer.h" #include "asil_client/unique_fd.h" #include @@ -39,6 +41,12 @@ struct PublisherRequest { 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; }; struct PublisherReply { @@ -50,6 +58,8 @@ struct PublisherReply { uint64_t subscriber_queue_arena_size = 0; 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; @@ -59,6 +69,10 @@ 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 { @@ -88,6 +102,39 @@ struct TriggersReply { 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; @@ -103,6 +150,13 @@ class ServerConnection { 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; + // The server's message for the last request that returned kServerRejected. virtual const char *LastServerError() const = 0; }; diff --git a/asil_client/shm_layout.h b/asil_client/shm_layout.h index 253823e6..6301fc8d 100644 --- a/asil_client/shm_layout.h +++ b/asil_client/shm_layout.h @@ -58,6 +58,7 @@ constexpr int64_t kMessageHasChecksum = 4; // MessageSlot flags. constexpr uint32_t kMessageSeen = 1; constexpr uint32_t kMessageIsActivation = 2; +constexpr uint32_t kMessageSeenByReliable = 4; // Fields of MessageSlot::refs. constexpr uint64_t kRefCountMask = 0x3ff; @@ -74,9 +75,9 @@ constexpr uint64_t kOrdinalShift = 40; inline uint64_t BuildRefsBitField(uint64_t ordinal, int vchan_id, uint64_t retired_refs) { const uint64_t vchan_bits = - ordinal == 0 ? 0 - : ((static_cast(vchan_id) & kVchanIdMask) - << kVchanIdShift); + ordinal == 0 + ? 0 + : ((static_cast(vchan_id) & kVchanIdMask) << kVchanIdShift); return ((ordinal & kOrdinalMask) << kOrdinalShift) | vchan_bits | ((retired_refs & kRetiredRefsMask) << kRetiredRefsShift); } @@ -192,25 +193,51 @@ struct BufferControlBlock { std::atomic sizes[kMaxBuffers]; }; +// InPlaceSlotQueue: a bounded MPSC ring of published slots for one +// subscriber, in the CCB's queue arena. The entries follow the header. +constexpr size_t kMaxSlotQueueCasAttempts = 64; + +struct SlotQueueEntry { + std::atomic sequence; + std::atomic ordinal; + std::atomic slot_id; +}; +static_assert(sizeof(SlotQueueEntry) == 24); + +struct SlotQueue { + size_t capacity; + std::atomic head; + std::atomic tail; + std::atomic overflow_count; + std::atomic insertion_failed; + bool drop_oldest; + + SlotQueueEntry *Entries() { + return reinterpret_cast(this + 1); + } +}; +static_assert(sizeof(SlotQueue) == 32); +static_assert(offsetof(SlotQueue, overflow_count) == 24); +static_assert(offsetof(SlotQueue, insertion_failed) == 28); + // Offsets of the regions that follow the slots in the CCB. A CCB holds the // header and slots, the retired and free slot bitsets, one available-slot // bitset per subscriber, the subscriber queue index and the queue arena. inline size_t RetiredSlotsOffset(int num_slots) { - return static_cast( - Aligned64(static_cast(sizeof(ChannelControlBlock) + - num_slots * sizeof(MessageSlot)))); + return static_cast(Aligned64(static_cast( + sizeof(ChannelControlBlock) + num_slots * sizeof(MessageSlot)))); } inline size_t FreeSlotsOffset(int num_slots) { return RetiredSlotsOffset(num_slots) + - static_cast(Aligned64( - static_cast(SizeofBitset(num_slots)))); + static_cast( + Aligned64(static_cast(SizeofBitset(num_slots)))); } inline size_t AvailableSlotsOffset(int num_slots, int sub_id) { return FreeSlotsOffset(num_slots) + - static_cast(Aligned64( - static_cast(SizeofBitset(num_slots)))) + + static_cast( + Aligned64(static_cast(SizeofBitset(num_slots)))) + SizeofBitset(num_slots) * static_cast(sub_id); } @@ -218,17 +245,22 @@ inline size_t SlotQueueIndexOffset(int num_slots) { return AvailableSlotsOffset(num_slots, kMaxSlotOwners); } -inline size_t CcbSize(int num_slots, uint64_t subscriber_queue_arena_size) { +// Queue offsets in AvailableSlotQueueIndex are relative to this. +inline size_t SlotQueueArenaOffset(int num_slots) { return SlotQueueIndexOffset(num_slots) + static_cast( - Aligned64(static_cast(sizeof(AvailableSlotQueueIndex)))) + + Aligned64(static_cast(sizeof(AvailableSlotQueueIndex)))); +} + +inline size_t CcbSize(int num_slots, uint64_t subscriber_queue_arena_size) { + return SlotQueueArenaOffset(num_slots) + static_cast(subscriber_queue_arena_size); } inline int32_t PrefixSize(int32_t checksum_size, int32_t metadata_size) { - return static_cast(Aligned64( - static_cast(offsetof(MessagePrefix, checksum)) + checksum_size + - metadata_size)); + return static_cast( + Aligned64(static_cast(offsetof(MessagePrefix, checksum)) + + checksum_size + metadata_size)); } } // namespace shm diff --git a/asil_client/split_buffer.h b/asil_client/split_buffer.h new file mode 100644 index 00000000..8a7d131c --- /dev/null +++ b/asil_client/split_buffer.h @@ -0,0 +1,77 @@ +// Copyright 2026 David Allison +// 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/subscriber.cc b/asil_client/subscriber.cc index 749c644e..4070c1f7 100644 --- a/asil_client/subscriber.cc +++ b/asil_client/subscriber.cc @@ -5,16 +5,15 @@ // The reading side of the shared memory protocol. This follows // SubscriberImpl::NextSlot, LastSlot, ClaimSlot and RemoveActiveMessage in // client/subscriber.cc, using the subscriber's available-slot bitset as the -// record of unread messages. +// 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/checksum.h" #include "asil_client/client.h" -#include #include -#include namespace subspace { namespace asil { @@ -36,8 +35,23 @@ BitsetView Owners(shm::MessageSlot *slot) { return BitsetView(&slot->sub_owners, shm::kMaxSlotOwners); } +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) { @@ -46,43 +60,50 @@ Error Subscriber::Open(Client &client, const char *channel_name, 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; } - SubscriberRequest request; - request.channel_name = name_; - request.type = options.type; - request.max_active_messages = 1; + 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(request, reply); + if (Error e = client.connection_->CreateSubscriber(BuildRequest(), reply); e != Error::kOk) { Reset(); return e; } client_ = &client; - options_ = options; 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 (reply.vchan_id != -1 || reply.use_split_buffers || - reply.subscriber_queue_size != 0 || - reply.subscriber_queue_arena_size != 0 || channel_id_ < 0 || - channel_id_ >= shm::kMaxChannels || subscriber_id_ < 0 || - subscriber_id_ >= shm::kMaxSlotOwners) { - e = Error::kUnsupported; - } - if (e == Error::kOk) { - e = memory_.Map(client.scb_, reply.ccb.Get(), reply.bcb.Get(), - reply.num_slots, reply.checksum_size, reply.metadata_size); + 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) { - e = memory_.AttachBuffer(name_, client.session_id_); + // A channel without a layout has no buffers either. + e = reply.num_slots > 0 ? MapChannel(reply) : Error::kNoBuffers; } if (e != Error::kOk) { (void)Close(); @@ -93,6 +114,22 @@ Error Subscriber::Open(Client &client, const char *channel_name, 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(); @@ -100,10 +137,13 @@ void Subscriber::Reset() { trigger_.Reset(); poll_.Reset(); client_ = nullptr; - held_ = nullptr; - last_ordinal_ = 0; + num_held_ = 0; + for (uint64_t &ordinal : last_ordinals_) { + ordinal = 0; + } channel_id_ = -1; subscriber_id_ = -1; + vchan_id_ = -1; } Error Subscriber::Close() { @@ -111,8 +151,7 @@ Error Subscriber::Close() { return Error::kOk; } ReleaseMessage(); - const Error e = - client_->connection_->RemoveSubscriber(name_, subscriber_id_); + const Error e = client_->connection_->RemoveSubscriber(name_, subscriber_id_); Reset(); return e; } @@ -121,35 +160,40 @@ Error Subscriber::Wait(int timeout_ms) { if (client_ == nullptr) { return Error::kNotInitialized; } - struct pollfd fd = {poll_.Get(), POLLIN, 0}; - for (;;) { - const int n = ::poll(&fd, 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; - } - } + 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() { - if (held_ != nullptr) { - ReleaseSlot(held_); - held_ = nullptr; + 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) { if (!Owners(slot).ClearWasSet(subscriber_id_)) { return; } bool retired = false; (void)memory_.AtomicIncRefCount( - slot, -1, slot->ordinal.load(std::memory_order_relaxed), + slot, options_.reliable, -1, + slot->ordinal.load(std::memory_order_relaxed), slot->vchan_id.load(std::memory_order_relaxed), /*retire=*/true, &retired); if (retired) { @@ -157,10 +201,15 @@ void Subscriber::ReleaseSlot(shm::MessageSlot *slot) { retirement_triggers_, slot->bridged_slot_id.load(std::memory_order_relaxed)); } + 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 = memory_.Counters(channel_id_).num_pub_updates; + const uint16_t updates = client_->scb_->counters[channel_id_].num_pub_updates; if (updates == num_pub_updates_) { return Error::kOk; } @@ -180,6 +229,29 @@ void Subscriber::TriggerReliablePublishers() const { } } +// Whether slot holds a published message for this subscriber's virtual +// channel. A subscriber to a multiplexer sees every virtual channel. +bool Subscriber::Visible(const shm::MessageSlot *slot) const { + if ((slot->refs.load(std::memory_order_acquire) & shm::kPubOwned) != 0 || + slot->ordinal.load(std::memory_order_relaxed) == 0) { + return false; + } + 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_; +} + +// Takes a reference to slot and records it so that the server can release +// the reference if this process dies. +bool Subscriber::Claim(shm::MessageSlot *slot, uint64_t ordinal) { + if (!memory_.AtomicIncRefCount(slot, options_.reliable, 1, ordinal, + slot->vchan_id.load(std::memory_order_relaxed), + false, nullptr)) { + return false; + } + Owners(slot).Set(subscriber_id_); + return true; +} + // Finds the oldest unread message and takes a reference to it. Subscriber::Find Subscriber::FindNext(shm::MessageSlot *&slot) { BitsetView available = memory_.AvailableSlots(subscriber_id_); @@ -189,14 +261,10 @@ Subscriber::Find Subscriber::FindNext(shm::MessageSlot *&slot) { uint64_t best_timestamp = 0; available.Traverse([&](int i) { shm::MessageSlot *s = memory_.Slot(i); - if ((s->refs.load(std::memory_order_acquire) & shm::kPubOwned) != 0) { + if (!Visible(s)) { return; } const uint64_t ordinal = s->ordinal.load(std::memory_order_relaxed); - if (ordinal == 0 || - s->buffer_index.load(std::memory_order_relaxed) != 0) { - return; - } const uint64_t timestamp = s->timestamp.load(std::memory_order_relaxed); if (best == nullptr || Before(timestamp, ordinal, best_timestamp, best_ordinal)) { @@ -208,12 +276,7 @@ Subscriber::Find Subscriber::FindNext(shm::MessageSlot *&slot) { if (best == nullptr) { return Find::kNone; } - if (memory_.AtomicIncRefCount( - best, 1, best_ordinal, - best->vchan_id.load(std::memory_order_relaxed), false, nullptr)) { - // Record ownership so that the server can release the reference if this - // process dies. - Owners(best).Set(subscriber_id_); + if (Claim(best, best_ordinal)) { slot = best; return Find::kFound; } @@ -231,14 +294,10 @@ Subscriber::Find Subscriber::FindNewest(shm::MessageSlot *&slot) { uint64_t best_timestamp = 0; available.Traverse([&](int i) { shm::MessageSlot *s = memory_.Slot(i); - if ((s->refs.load(std::memory_order_acquire) & shm::kPubOwned) != 0) { + if (!Visible(s)) { return; } const uint64_t ordinal = s->ordinal.load(std::memory_order_relaxed); - if (ordinal == 0 || - s->buffer_index.load(std::memory_order_relaxed) != 0) { - return; - } const uint64_t timestamp = s->timestamp.load(std::memory_order_relaxed); if (best == nullptr || Before(best_timestamp, best_ordinal, timestamp, ordinal)) { @@ -250,10 +309,7 @@ Subscriber::Find Subscriber::FindNewest(shm::MessageSlot *&slot) { if (best == nullptr) { return Find::kNone; } - if (memory_.AtomicIncRefCount( - best, 1, best_ordinal, - best->vchan_id.load(std::memory_order_relaxed), false, nullptr)) { - Owners(best).Set(subscriber_id_); + if (Claim(best, best_ordinal)) { slot = best; return Find::kFound; } @@ -263,34 +319,44 @@ Subscriber::Find Subscriber::FindNewest(shm::MessageSlot *&slot) { // Marks every unread message older than newest as read. Each slot is pinned // while its bit is cleared so that a publisher recycling it can't lose the -// bit for the new message. +// bit for the new message. A reliable subscriber also marks the messages +// seen so that a reliable publisher doesn't wait for it to read them. 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); - if ((s->refs.load(std::memory_order_acquire) & shm::kPubOwned) != 0) { + if (!Visible(s)) { return; } const uint64_t ordinal = s->ordinal.load(std::memory_order_relaxed); const uint64_t timestamp = s->timestamp.load(std::memory_order_relaxed); - if (ordinal == 0 || - !Before(timestamp, ordinal, newest_timestamp, newest_ordinal)) { + if (!Before(timestamp, ordinal, newest_timestamp, newest_ordinal)) { return; } const int vchan_id = s->vchan_id.load(std::memory_order_relaxed); - if (memory_.AtomicIncRefCount(s, 1, ordinal, vchan_id, false, nullptr)) { + if (memory_.AtomicIncRefCount(s, options_.reliable, 1, ordinal, vchan_id, + false, nullptr)) { available.Clear(i); - (void)memory_.AtomicIncRefCount(s, -1, ordinal, vchan_id, false, - nullptr); + if (options_.reliable) { + s->flags.fetch_or(shm::kMessageSeen | shm::kMessageSeenByReliable, + std::memory_order_relaxed); + marked_seen = true; + } + (void)memory_.AtomicIncRefCount(s, options_.reliable, -1, ordinal, + vchan_id, false, nullptr); } }); + if (marked_seen) { + TriggerReliablePublishers(); + } } bool Subscriber::ChecksumValid(const shm::MessageSlot *slot, @@ -318,53 +384,70 @@ Error Subscriber::ReadMessage(Message &message, ReadMode mode) { return Error::kNotInitialized; } internal::ClearTrigger(poll_.Get()); - ReleaseMessage(); - if (Error e = RefreshTriggers(); e != Error::kOk) { - return e; + 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 = memory_.AttachBuffer(name_, client_->session_id_); - e != Error::kOk) { + if (Error e = RefreshTriggers(); e != Error::kOk) { return e; } - if (!memory_.HasBuffer()) { - return Error::kOk; - } 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); + 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 shm::MessagePrefix *prefix = memory_.Prefix(slot); 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 bool is_activation = (prefix->flags & shm::kMessageActivate) != 0; + 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); - slot->flags.fetch_or(shm::kMessageSeen, std::memory_order_relaxed); + slot->flags.fetch_or(options_.reliable + ? shm::kMessageSeen | shm::kMessageSeenByReliable + : shm::kMessageSeen, + std::memory_order_relaxed); + 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; + 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); + 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; + if (ordinal > last_ordinal) { + last_ordinal = ordinal; } const bool checksum_error = options_.checksum && (prefix->flags & shm::kMessageHasChecksum) != 0 && @@ -374,12 +457,16 @@ Error Subscriber::ReadMessage(Message &message, ReadMode mode) { message = Message(); return Error::kChecksumMismatch; } - held_ = slot; + 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) { diff --git a/asil_client/subscriber.h b/asil_client/subscriber.h index f72a3da7..9d11ef07 100644 --- a/asil_client/subscriber.h +++ b/asil_client/subscriber.h @@ -17,6 +17,9 @@ 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. @@ -26,6 +29,22 @@ struct SubscriberOptions { 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 { @@ -33,26 +52,30 @@ enum class ReadMode { kReadNewest, }; -// A message in shared memory. The pointers stay valid until the next read, -// ReleaseMessage() or Close(). +// 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, for kReadNext. + // 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; }; -// An unreliable subscriber. It holds at most one message; reading the next -// message releases the previous one. +// A subscriber to a fixed-size channel. // -// A subscriber is not thread safe and must not outlive its Client. +// 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; @@ -67,42 +90,68 @@ class Subscriber { bool IsOpen() const { return client_ != nullptr; } // Reads a message. Returns kOk with message.length == 0 when there is no - // message. If a publisher has joined since the last read this asks the - // server for its trigger fds first. + // 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 the message from the last read. + // 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(); + bool Visible(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_; - shm::MessageSlot *held_ = nullptr; - uint64_t last_ordinal_ = 0; + 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_; }; diff --git a/docs/asil-client.md b/docs/asil-client.md index 1617086d..47cfe6be 100644 --- a/docs/asil-client.md +++ b/docs/asil-client.md @@ -6,9 +6,10 @@ 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 is designed for a server running a [static channel config](../README.md#static-channel-config), -where every channel exists before any client connects and keeps a fixed -layout. +It works with any server. A server running a +[static channel config](../README.md#static-channel-config), where every +channel exists before any client connects and keeps a fixed layout, gives a +safety case the most predictable setup. ## Design Rules @@ -22,33 +23,97 @@ layout. `Error::kServerRejected`. - **No heap allocation.** The client, publishers and subscribers allocate no memory, and neither does `PhaserServerConnection` while it talks to the - server. The server is involved when a client, publisher or subscriber is - set up or closed, and when a publisher or subscriber refreshes its trigger - file descriptors after another process joins or leaves the channel. + server. +- **Resources are acquired when an object opens.** A publisher or + subscriber maps all of its channel's shared memory in `Open()`, and creates + shared memory only when an ASIL publisher is the first on a channel that + isn't static. Publishing and reading make no `mmap`, `shm_open` or other + shared memory calls. 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. Exceeding any of these returns - `Error::kCapacityExceeded`. + the server holds up to 16 KB in wire format. Exceeding any of these + 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 provides unreliable publishers and subscribers on -fixed-size, non-virtual channels: - -- Each channel has one buffer, which is what fixed-size channels use. -- A subscriber holds at most one message. Reading the next message releases - the previous one. +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 work with both clients. + 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 +static channel's buffers when it starts, so ASIL publishers and subscribers +can open in any order. On a server that creates channels on demand, a +channel has buffers once its first publisher opens. Until then an ASIL +subscriber's `Open()` returns `Error::kNoBuffers`. An ASIL publisher that is +first on such a channel creates its buffer. + +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. Publishers must then use +split buffers, and on any other static channel they must not. 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`. -Reliable publishers and subscribers, virtual channels, subscriber queues, -split buffers and the memfd backend (always used on Android, and selected on -Linux with `SUBSPACE_LINUX_USE_MEMFD`) return `Error::kUnsupported`. -Channels created by standard publishers that resize their slots also have -more than one buffer and are rejected the same way. +```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 @@ -85,7 +150,11 @@ the server, because it sizes the shared system control block. 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`. +`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: length-prefixed messages in protobuf wire format on the server's Unix socket, @@ -174,6 +243,7 @@ asil::Error Run() { `PublisherOptions` gives the slot size, number of slots, checksum size, metadata size and type. On a static channel these must match the config. +`subscriber_queue_arena_size` must match the channel's other publishers. `Buffer()` returns the payload of the slot the publisher holds, and `Metadata()` returns its metadata area. `Publish(size)` sends the message and @@ -182,25 +252,96 @@ 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, 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. +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` compares every size, offset and constant in -`asil_client/shm_layout.h` with `common/channel.h`, and checks that the -checksum matches the standard client's. `asil_client_test` runs a server with -a static channel config and exchanges messages between the ASIL client and the -standard client in both directions. It also checks that setting up and -closing a publisher and a subscriber makes no heap allocations, and that a -request too large for the wire buffer returns `Error::kCapacityExceeded` and -leaves the connection usable. It is skipped on memfd builds. +`asil_client/shm_layout.h` with `common/channel.h`, checks that the checksum +matches the standard client's, and passes subscriber queue entries between +the ASIL client and the standard `InPlaceSlotQueue`. + +`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 and +subscribers that open before any publisher. 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 too large for the wire buffer +returns `Error::kCapacityExceeded` and leaves the connection usable. diff --git a/proto/subspace.proto b/proto/subspace.proto index 8741ba4d..29498d17 100644 --- a/proto/subspace.proto +++ b/proto/subspace.proto @@ -212,6 +212,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 { @@ -653,8 +659,10 @@ message Telemetry { // 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 and -// metadata size. +// 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; @@ -662,13 +670,15 @@ message StaticMultiplexer { string 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 and metadata_size unset and takes them from the - // multiplexer. + // checksum_size, metadata_size and use_split_buffers unset and takes them + // from the multiplexer. int32 slot_size = 2; int32 num_slots = 3; string type = 4; @@ -678,6 +688,8 @@ message StaticChannel { 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 { diff --git a/server/client_handler.cc b/server/client_handler.cc index cbf733f6..9ffc57b5 100644 --- a/server/client_handler.cc +++ b/server/client_handler.cc @@ -284,19 +284,7 @@ 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(); } @@ -341,6 +329,10 @@ void ClientHandler::HandleGetClientBuffers( } for (const RegisteredClientBuffer *buffer : channel->FindClientBuffers(req.session_id(), req.buffer_index())) { + if (req.filter_slot() && (buffer->metadata.is_prefix != req.is_prefix() || + buffer->metadata.slot_id != req.slot_id())) { + continue; + } ToProto(buffer->metadata, response->add_metadata()); if (buffer->fd.Valid()) { response->add_fd_indexes(static_cast(fds.size())); @@ -487,6 +479,18 @@ void ClientHandler::HandleCreatePublisher( cs, ms)); return; } + const ServerChannel *layout_channel = + channel->IsVirtual() + ? static_cast(channel)->GetMux() + : channel; + const bool split = layout_channel->HasSplitBufferOptions() && + layout_channel->GetSplitBufferOptions().use_split_buffers; + if (req.use_split_buffers() != split) { + response->set_error(absl::StrFormat( + "Static channel %s %s split buffers", req.channel_name(), + split ? "uses" : "doesn't use")); + return; + } } if (channel == nullptr) { server_->logger_.Log(toolbelt::LogLevel::kDebug, @@ -626,7 +630,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", @@ -648,7 +654,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 " @@ -667,7 +673,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", diff --git a/server/server.cc b/server/server.cc index bbd51983..e1d9b892 100644 --- a/server/server.cc +++ b/server/server.cc @@ -1407,6 +1407,81 @@ bool Server::IsServerChannelName(const std::string &channel_name) { 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(); @@ -1463,6 +1538,14 @@ absl::Status Server::CreateStaticChannels() { 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()) { @@ -1500,6 +1583,15 @@ absl::Status Server::CreateStaticChannels() { 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", diff --git a/server/server.h b/server/server.h index cfa7aeea..bdbc3761 100644 --- a/server/server.h +++ b/server/server.h @@ -146,6 +146,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 { @@ -313,6 +319,12 @@ class Server { // 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 { diff --git a/server/server_channel.cc b/server/server_channel.cc index 80f8ff59..eb9a9ec6 100644 --- a/server/server_channel.cc +++ b/server/server_channel.cc @@ -1638,6 +1638,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 0a06b5d4..67bc773d 100644 --- a/server/server_channel.h +++ b/server/server_channel.h @@ -453,6 +453,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_; @@ -590,6 +600,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; @@ -635,6 +646,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/static_config.cc b/server/static_config.cc index 2407e072..42b63e18 100644 --- a/server/static_config.cc +++ b/server/static_config.cc @@ -103,10 +103,11 @@ absl::Status ValidateStaticChannelConfig(const StaticChannelConfig &config) { } if (channel.slot_size() != 0 || channel.num_slots() != 0 || !channel.type().empty() || channel.checksum_size() != 0 || - channel.metadata_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 and metadata_size from it; leave them unset", + "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) { diff --git a/server/static_config_test.cc b/server/static_config_test.cc index f6ac933c..431e875a 100644 --- a/server/static_config_test.cc +++ b/server/static_config_test.cc @@ -10,6 +10,7 @@ #include "absl/status/status.h" #include "absl/status/statusor.h" +#include "absl/strings/str_format.h" #include "server/static_config.h" #include #include @@ -28,6 +29,19 @@ constexpr char kConfig[] = R"pb( 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 } )pb"; subspace::PublisherOptions FixedSize() { @@ -107,8 +121,8 @@ TEST(StaticConfigParseTest, ParsesValidConfig) { absl::StatusOr config = subspace::ParseStaticChannelConfig(kConfig); ASSERT_OK(config); - EXPECT_EQ(1, config->multiplexers_size()); - EXPECT_EQ(4, config->channels_size()); + EXPECT_EQ(2, config->multiplexers_size()); + EXPECT_EQ(6, config->channels_size()); } TEST(StaticConfigParseTest, RejectsInvalidConfigs) { @@ -139,6 +153,9 @@ TEST(StaticConfigParseTest, RejectsInvalidConfigs) { {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"}, @@ -198,6 +215,56 @@ TEST_F(StaticConfigTest, SubscriberBeforePublisher) { 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", 256, 4, FixedSize().SetUseSplitBuffers(true)); + ASSERT_OK(pub); + EXPECT_TRUE(pub->UsesSplitBuffers()); + 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", 128, 4, + FixedSize().SetMux("/static/split_mux").SetUseSplitBuffers(true)); + ASSERT_OK(pub); + 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, RejectsMismatchedSplitBuffers) { + absl::StatusOr unsplit = + Client().CreatePublisher("/static/split", 256, 4, FixedSize()); + ASSERT_FALSE(unsplit.ok()); + EXPECT_THAT(unsplit.status().message(), HasSubstr("uses split buffers")); + + absl::StatusOr split = Client().CreatePublisher( + "/static/a", 256, 8, FixedSize().SetUseSplitBuffers(true)); + ASSERT_FALSE(split.ok()); + EXPECT_THAT(split.status().message(), + HasSubstr("doesn't use split buffers")); +} + TEST_F(StaticConfigTest, UnconfiguredChannelsAreRejected) { absl::StatusOr pub = Client().CreatePublisher("/not/configured", 64, 4, FixedSize()); @@ -307,6 +374,13 @@ TEST_F(StaticConfigTest, VirtualChannels) { 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", 128, 8, FixedSize().SetMux("/static/mux")); + ASSERT_OK(other); + EXPECT_EQ(7, other->VirtualChannelId()); } TEST_F(StaticConfigTest, ServerChannelsArePublished) { From bdccd144a016d08ed7ba17e6f363b9afad660553 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Sat, 10 Oct 2026 14:48:35 -0700 Subject: [PATCH 04/21] Share phaser server encoding between the C++ clients The standard C++ client now builds its server requests and responses as phaser messages, like the ASIL client. ServerWire in common/server_wire.h serializes requests and decodes responses for both, with growable buffers for the standard client and fixed buffers for the ASIL connection, which still makes no heap allocations. The bytes on the socket are unchanged. CMake now requires PHASER_PLUGIN_EXECUTABLE when cross-compiling, since the standard client needs subspace_phaser. --- CHANGELOG.md | 6 +- CMakeLists.txt | 6 +- asil_client/BUILD.bazel | 2 +- asil_client/CMakeLists.txt | 7 -- asil_client/phaser_connection.cc | 46 +++---- asil_client/phaser_connection.h | 14 +-- client/Android.bp | 2 + client/BUILD.bazel | 2 + client/CMakeLists.txt | 1 + client/client.cc | 209 ++++++++++++++++--------------- client/client.h | 14 +-- common/BUILD.bazel | 12 ++ common/server_wire.h | 115 +++++++++++++++++ docs/android.md | 5 +- docs/asil-client.md | 23 ++-- proto/CMakeLists.txt | 13 +- 16 files changed, 307 insertions(+), 170 deletions(-) create mode 100644 common/server_wire.h diff --git a/CHANGELOG.md b/CHANGELOG.md index 73a78a4d..cbbcb0dc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -47,8 +47,12 @@ 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 bytes on the socket are unchanged. - Bazel, CMake and Soong build phaser and generate `subspace_phaser` from - `subspace.proto`. Android CMake cross-compiles take a host + `subspace.proto`. Android CMake cross-compiles need a host `protoc-gen-phaser` in `PHASER_PLUGIN_EXECUTABLE`. - Abseil 20250814.1, protobuf 33.4, cpp_toolbelt 2.1.6 and phaser 2.1.3 in the Bazel build. CMake uses cpp_toolbelt 2.1.6. diff --git a/CMakeLists.txt b/CMakeLists.txt index 4c56c196..4891443d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -167,8 +167,10 @@ FetchContent_MakeAvailable(protobuf) # These targets can be used directly without find_package # --- External Dependency: phaser (using FetchContent for native CMake) --- -# The ASIL client talks to the server with phaser messages held in fixed -# buffers. Phaser uses the Abseil, cpp_toolbelt and protobuf fetched above. +# 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 diff --git a/asil_client/BUILD.bazel b/asil_client/BUILD.bazel index 3c53448b..d673e5d9 100644 --- a/asil_client/BUILD.bazel +++ b/asil_client/BUILD.bazel @@ -54,7 +54,7 @@ cc_library( ], deps = [ ":asil_client", - "//proto:subspace_phaser", + "//common:server_wire", ], ) diff --git a/asil_client/CMakeLists.txt b/asil_client/CMakeLists.txt index 8bff0e59..e1692392 100644 --- a/asil_client/CMakeLists.txt +++ b/asil_client/CMakeLists.txt @@ -25,13 +25,6 @@ target_link_libraries(asil_layout_test PUBLIC gtest_main ) -# The server connection needs the phaser messages, which proto/ skips when -# cross-compiling without a host phaser plugin. -if(NOT TARGET subspace_phaser) - message(STATUS "Skipping the ASIL server connection: subspace_phaser is not available.") - return() -endif() - # The handshake with the server, using phaser messages in fixed buffers. add_library(subspace_asil_phaser_connection STATIC phaser_connection.cc diff --git a/asil_client/phaser_connection.cc b/asil_client/phaser_connection.cc index f2e20dc5..02b0c5da 100644 --- a/asil_client/phaser_connection.cc +++ b/asil_client/phaser_connection.cc @@ -150,11 +150,12 @@ Error PhaserServerConnection::Rejected(const char *message, size_t length) { return Error::kServerRejected; } -// Sends the length-prefixed request in wire_. +// 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(wire_, &network_length, sizeof(network_length)); - if (!SendFully(socket_.Get(), wire_, sizeof(network_length) + length)) { + std::memcpy(header, &network_length, sizeof(network_length)); + if (!SendFully(socket_.Get(), header, kServerWireHeaderSize + length)) { return Error::kConnectionFailed; } return Error::kOk; @@ -194,22 +195,24 @@ Error PhaserServerConnection::SendFd(int fd) { // 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(size_t &length) { +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); - char *const data = wire_ + sizeof(uint32_t); - if (length <= kWireBufferSize) { - return ReceiveFully(socket_.Get(), data, length) ? Error::kOk - : Error::kConnectionFailed; + if (char *buffer = wire_.ResponseBuffer(length); buffer != nullptr) { + data = buffer; + return ReceiveFully(socket_.Get(), buffer, length) + ? Error::kOk + : Error::kConnectionFailed; } + char *const scratch = wire_.ResponseBuffer(kWireBufferSize); for (size_t remaining = length; remaining > 0;) { const size_t chunk = remaining < kWireBufferSize ? remaining : kWireBufferSize; - if (!ReceiveFully(socket_.Get(), data, chunk)) { + if (!ReceiveFully(socket_.Get(), scratch, chunk)) { return Error::kConnectionFailed; } remaining -= chunk; @@ -300,28 +303,27 @@ Error PhaserServerConnection::Transact(Build build, Read read, int send_fd) { fds_.Clear(); size_t length = 0; { - absl::StatusOr request = - wire::Request::TryCreateMutable(message_, sizeof(message_)); + // 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()) { return Error::kCapacityExceeded; } build(*request); - if (request->AllocationFailed()) { + absl::StatusOr serialized = wire_.Serialize(*request); + if (!serialized.ok()) { return Error::kCapacityExceeded; } - ::phaser::ProtoBuffer out(wire_ + sizeof(uint32_t), kWireBufferSize); - if (!request->Serialize(out).ok()) { - return Error::kCapacityExceeded; - } - length = out.Size(); + 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(length); + e = Receive(data, length); } if (e == Error::kOk || e == Error::kCapacityExceeded) { // The descriptors follow even a response that did not fit. @@ -340,15 +342,13 @@ Error PhaserServerConnection::Transact(Build build, Read read, int send_fd) { return e; } - absl::StatusOr response = - wire::Response::TryCreateMutable(message_, sizeof(message_)); + absl::StatusOr response = wire_.NewResponse(); if (!response.ok()) { fds_.Clear(); return Error::kCapacityExceeded; } - ::phaser::ProtoBuffer in(static_cast(wire_ + sizeof(uint32_t)), - length); - if (absl::Status status = response->Deserialize(in); !status.ok()) { + if (absl::Status status = wire_.Decode(data, length, *response); + !status.ok()) { fds_.Clear(); return status.code() == absl::StatusCode::kResourceExhausted ? Error::kCapacityExceeded diff --git a/asil_client/phaser_connection.h b/asil_client/phaser_connection.h index f195576f..e017f8f6 100644 --- a/asil_client/phaser_connection.h +++ b/asil_client/phaser_connection.h @@ -5,6 +5,7 @@ #pragma once #include "asil_client/server_connection.h" +#include "common/server_wire.h" #include #include @@ -14,10 +15,10 @@ namespace asil { // The standard Subspace protocol: protobuf requests and responses over the // server's Unix socket, with file descriptors passed as SCM_RIGHTS. Requests -// and responses are Phaser messages held in buffers inside this object and -// converted to and from protobuf wire format, so the handshake makes no heap -// allocations. A request or response that does not fit fails with -// kCapacityExceeded. +// and responses are Phaser messages held in a ServerWire with fixed buffers +// inside this object, the same encoding as the standard client uses, so the +// handshake makes no heap allocations. A request or response that does not +// fit fails with kCapacityExceeded. // // The object holds about 60 KB of buffers, so keep it in static storage or // inside a long-lived object rather than on a small stack. @@ -64,15 +65,14 @@ class PhaserServerConnection : public ServerConnection { Error Transact(Build build, Read read, int send_fd = -1); Error Send(size_t length); Error SendFd(int fd); - Error Receive(size_t &length); + Error Receive(const char *&data, size_t &length); Error ReceiveFds(); Error Rejected(const char *message, size_t length); UniqueFd socket_; ReceivedFds fds_; char last_error_[256] = {}; - alignas(8) char wire_[sizeof(uint32_t) + kWireBufferSize]; - alignas(8) char message_[kMessageBufferSize]; + ServerWire> wire_; }; } // namespace asil diff --git a/client/Android.bp b/client/Android.bp index 01daef2a..955902c1 100644 --- a/client/Android.bp +++ b/client/Android.bp @@ -19,10 +19,12 @@ cc_library_shared { static_libs: [ "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 47ad364d..a340655d 100644 --- a/client/BUILD.bazel +++ b/client/BUILD.bazel @@ -25,9 +25,11 @@ cc_library( strip_include_prefix = ".", include_prefix = "subspace/client", deps = [ + "//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", diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 41b7c238..265b2bed 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -32,6 +32,7 @@ target_link_libraries(subspace_client PUBLIC subspace_common subspace_async subspace_proto + subspace_phaser absl::flags absl::flat_hash_map absl::flat_hash_set diff --git a/client/client.cc b/client/client.cc index 860173e0..cc0a96cf 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" @@ -42,35 +42,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 @@ -99,7 +101,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); @@ -115,7 +117,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(); @@ -241,9 +243,9 @@ absl::Status ClientImpl::Init(const std::string &server_socket, name_ = client_name; socket_name_ = server_socket; - Request req; + phaser::Request req; req.mutable_init()->set_client_name(client_name); - Response resp; + phaser::Response resp; std::vector fds; fds.reserve(100); status = SendRequestReceiveResponse(req, resp, fds); @@ -446,29 +448,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); }; @@ -485,7 +487,7 @@ ClientImpl::CreatePublisher(const std::string &channel_name, 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)); }, @@ -601,12 +603,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); @@ -614,7 +616,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()); } @@ -626,14 +628,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)); @@ -1732,13 +1735,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); @@ -1746,7 +1749,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()); } @@ -1761,7 +1764,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()); @@ -1827,12 +1830,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); @@ -1840,7 +1843,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()) { @@ -1870,12 +1873,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); @@ -1883,7 +1886,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()) { @@ -1964,13 +1967,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); @@ -1978,7 +1981,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()); } @@ -1990,14 +1993,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); @@ -2005,7 +2008,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()); } @@ -2033,19 +2036,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()); } @@ -2054,7 +2057,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(); @@ -2078,22 +2081,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(); @@ -2130,18 +2133,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()); } @@ -2150,7 +2153,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(); @@ -2165,22 +2168,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(); @@ -2221,10 +2224,9 @@ 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); @@ -2253,7 +2255,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()])); @@ -2276,10 +2278,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()); @@ -2297,7 +2298,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()])); @@ -2331,9 +2332,9 @@ absl::Status ClientImpl::Reconnect() { return status; } - Request init_req; + phaser::Request init_req; init_req.mutable_init()->set_client_name(name_); - Response init_resp; + phaser::Response init_resp; std::vector init_fds; init_fds.reserve(100); status = SendRequestReceiveResponse(init_req, init_resp, init_fds); @@ -2367,21 +2368,21 @@ absl::Status ClientImpl::Reconnect() { } 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()); } @@ -2391,19 +2392,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()); } @@ -2413,21 +2414,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 (was_connected_ && !reconnecting_) { @@ -2461,10 +2461,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()); @@ -2476,17 +2478,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 (was_connected_ && !reconnecting_) { @@ -2511,7 +2514,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; @@ -2520,7 +2523,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); @@ -2536,13 +2539,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()) { @@ -2557,7 +2560,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)), }; @@ -2573,7 +2576,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 e1044309..b6559d87 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" @@ -712,11 +712,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, @@ -732,19 +732,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/common/BUILD.bazel b/common/BUILD.bazel index e39dadc5..e35b4473 100644 --- a/common/BUILD.bazel +++ b/common/BUILD.bazel @@ -47,6 +47,18 @@ cc_library( ], ) +# Server requests and responses as Phaser messages in protobuf wire format, +# 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/server_wire.h b/common/server_wire.h new file mode 100644 index 00000000..32bed75c --- /dev/null +++ b/common/server_wire.h @@ -0,0 +1,115 @@ +// Copyright 2026 David Allison +// All Rights Reserved +// See LICENSE file for licensing information. + +#pragma once + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "proto/subspace.phaser.h" + +#include +#include +#include + +namespace subspace { + +// Requests to and responses from the server, as Phaser messages sent in +// protobuf wire format. The server, and clients in other languages, see the +// same bytes as from a protobuf client. +// +// A ServerWire serializes requests into its wire buffer and decodes +// responses. The Buffers policy decides where messages and wire bytes live: +// +// FixedServerWireBuffers holds them inside the object and makes no heap +// allocations. 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); + +template class FixedServerWireBuffers { +public: + static constexpr size_t kMaxWireSize = kWireSize; + + absl::StatusOr NewRequest() { + return phaser::Request::TryCreateMutable(message_, sizeof(message_)); + } + + absl::StatusOr NewResponse() { + return phaser::Response::TryCreateMutable(message_, sizeof(message_)); + } + + // Room for the header and length bytes after it, or nullptr. + char *Wire(size_t length) { return length <= kWireSize ? wire_ : nullptr; } + +private: + alignas(8) char message_[kMessageSize]; + alignas(8) char wire_[kServerWireHeaderSize + kWireSize]; +}; + +class DynamicServerWireBuffers { +public: + char *Wire(size_t length) { + wire_.resize(kServerWireHeaderSize + length); + return wire_.data(); + } + +private: + std::vector wire_; +}; + +template class ServerWire { +public: + absl::StatusOr NewRequest() { return buffers_.NewRequest(); } + absl::StatusOr NewResponse() { + return buffers_.NewResponse(); + } + + // Serializes request 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) { + if (request.AllocationFailed()) { + return absl::ResourceExhaustedError("Request is too large to build"); + } + const size_t length = request.SerializedSize(); + char *wire = buffers_.Wire(length); + if (wire == nullptr) { + return absl::ResourceExhaustedError("Request is too large to send"); + } + payload_ = wire + kServerWireHeaderSize; + ::phaser::ProtoBuffer out(payload_, length); + if (absl::Status status = request.Serialize(out); !status.ok()) { + return status; + } + return out.Size(); + } + + // 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; + } + + // Decodes length bytes of a response into response. + static absl::Status Decode(const char *data, size_t length, + phaser::Response &response) { + ::phaser::ProtoBuffer in(data, length); + return response.Deserialize(in); + } + +private: + Buffers buffers_; + char *payload_ = nullptr; +}; + +} // namespace subspace diff --git a/docs/android.md b/docs/android.md index 584cc7d3..fed70418 100644 --- a/docs/android.md +++ b/docs/android.md @@ -186,7 +186,8 @@ Subspace can also be cross-compiled for Android using CMake with the NDK toolchain. CMake fetches the same third-party dependencies with `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 ASIL client's messages. +host-native phaser plugin (`protoc-gen-phaser`) for the C++ clients' server +messages. ```bash export ANDROID_NDK_HOME=/path/to/ndk @@ -243,7 +244,7 @@ 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 ASIL client | +| `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 | diff --git a/docs/asil-client.md b/docs/asil-client.md index 47cfe6be..74591dc0 100644 --- a/docs/asil-client.md +++ b/docs/asil-client.md @@ -127,7 +127,8 @@ 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`, `//proto:subspace_phaser` | +| `//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`, @@ -135,8 +136,7 @@ CMake builds the same libraries as `subspace_asil_client`, `asil_layout_test` and `asil_client_test`. 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). Without one, the -cross-compile builds only the core library. +[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 @@ -159,13 +159,16 @@ each response stays small. `PhaserServerConnection` implements it with the server's standard protocol: length-prefixed messages in protobuf wire format on the server's Unix socket, with file descriptors passed by `SCM_RIGHTS`. The server receives the same -bytes it receives from the standard clients. The connection builds each -request as a phaser message in a fixed buffer inside the object, serializes -it to protobuf wire format, and decodes the response into the same buffer, -so it needs neither the protobuf library nor the heap. The buffers take -about 60 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`. +bytes it receives from the standard clients. Requests and responses are +encoded by `ServerWire` in `common/server_wire.h`, which the standard C++ +client uses too. The standard client gives it growable buffers. The ASIL +connection gives it fixed buffers inside the object: it builds each request +as a phaser message in a fixed buffer, serializes it to protobuf wire format, +and decodes the response into the same buffer, so it needs neither the +protobuf library nor the heap. The buffers take about 60 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 diff --git a/proto/CMakeLists.txt b/proto/CMakeLists.txt index db9e1bfd..a8555564 100644 --- a/proto/CMakeLists.txt +++ b/proto/CMakeLists.txt @@ -93,15 +93,14 @@ target_link_libraries(subspace_proto PUBLIC protobuf::libprotobuf ) -# Phaser messages for the ASIL client's server connection. They are sent and -# received in protobuf wire format, so the server sees the same bytes as from -# any other client. Cross-compiles need a host plugin in -# PHASER_PLUGIN_EXECUTABLE; without one the ASIL server connection is skipped. +# Phaser messages for the clients' server requests and responses. They are +# sent and received in protobuf wire format, so the server sees the same bytes +# as from any other client. Cross-compiles need a host plugin in +# PHASER_PLUGIN_EXECUTABLE. if(CMAKE_CROSSCOMPILING AND NOT PHASER_PLUGIN_EXECUTABLE) - message(STATUS - "Skipping subspace_phaser: cross-compiling without " + message(FATAL_ERROR + "Cross-compiling needs a host protoc-gen-phaser in " "-DPHASER_PLUGIN_EXECUTABLE.") - return() endif() set(SUBSPACE_PHASER_PROTOC) if(CMAKE_CROSSCOMPILING) From e94bdaee975d0dfad193cf2c9f0dfc9fc33b3af7 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Mon, 12 Oct 2026 16:03:11 -0700 Subject: [PATCH 05/21] Require server_defined publishers on static channels A static channel's layout comes from the server's config, so its publishers now set a server_defined option instead of the options that shape the shared memory. The server rejects a publisher on a static channel that leaves out server_defined or sets num_slots, slot_size, fixed_size, checksum_size, metadata_size, subscriber_queue_arena_size or use_split_buffers, and 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 takes its layout from them. The C++, C, Python, Rust and ASIL clients have the option and check it before asking the server. The C++ and Rust default checksum_size is now 0, which means 4 bytes, and a bridge publisher on a static channel is server defined. --- CHANGELOG.md | 21 +++- README.md | 24 +++- asil_client/asil_client_test.cc | 183 ++++++++++++++++----------- asil_client/phaser_connection.cc | 7 +- asil_client/publisher.cc | 41 ++++-- asil_client/publisher.h | 19 ++- asil_client/server_connection.h | 8 ++ c_client/subspace.cc | 10 +- c_client/subspace.h | 9 ++ client/client.cc | 52 ++++++-- client/options.h | 16 ++- client/python/client.cc | 7 ++ docs/asil-client.md | 25 +++- docs/c-client.md | 8 ++ docs/rust-client.md | 3 +- proto/subspace.proto | 12 ++ rust_client/src/client.rs | 62 ++++++--- rust_client/src/options.rs | 16 ++- server/client_handler.cc | 116 +++++++++++------ server/client_handler.h | 2 +- server/server.cc | 30 +++-- server/server_test.cc | 22 ++++ server/static_config_test.cc | 209 +++++++++++++++++++++---------- 23 files changed, 643 insertions(+), 259 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cbbcb0dc..38739165 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,9 +6,21 @@ - `subspace_server --channel_config=FILE` reads a `StaticChannelConfig` in protobuf text format and creates its channels and multiplexers before the server accepts clients. Clients can then use only those channels and the - server's own, the channels stay when they have no users, and their layout - is fixed: publishers must be fixed size and match the configured slot - size, number of slots, checksum size and metadata size. + server's own, the channels stay when they have no users, and the server + defines their layout. +- 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 @@ -19,8 +31,7 @@ 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. Publishers whose split buffer - setting differs from the config are rejected. + split buffers, which the server creates. - `GetClientBuffersRequest` can ask for one prefix or slot of a split buffer set with `filter_slot`, `is_prefix` and `slot_id`. diff --git a/README.md b/README.md index 8cc73630..26280185 100644 --- a/README.md +++ b/README.md @@ -2033,13 +2033,27 @@ loaded: publisher or subscriber for any other channel fails. - Configured channels stay for the life of the server, including when they have no publishers or subscribers. -- The layout is fixed. Publishers must be fixed size (`SetFixedSize(true)`) - and match the configured slot size, number of slots, checksum size and - metadata size. +- 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. - Publishers must set `SetUseSplitBuffers(true)` on these channels and leave - it unset on the others. - 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`. diff --git a/asil_client/asil_client_test.cc b/asil_client/asil_client_test.cc index df5b659b..bd7c5476 100644 --- a/asil_client/asil_client_test.cc +++ b/asil_client/asil_client_test.cc @@ -110,6 +110,11 @@ 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); @@ -174,6 +179,13 @@ asil::PublisherOptions AsilPubOptions(int64_t slot_size, int32_t 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 { @@ -286,7 +298,7 @@ TEST_F(AsilClientTest, AsilPublisherStandardSubscriber) { ASSERT_OK(sub); asil::Publisher pub; - asil::PublisherOptions options = AsilPubOptions(256, 8); + asil::PublisherOptions options = StaticPubOptions(); options.type = "T"; ASSERT_EQ(asil::Error::kOk, Asil().CreatePublisher("/asil/to_std", options, pub)); @@ -324,7 +336,7 @@ TEST_F(AsilClientTest, StandardPublisherAsilSubscriber) { EXPECT_EQ(0u, msg.length); absl::StatusOr pub = - Std().CreatePublisher("/asil/from_std", 256, 8, FixedSize()); + Std().CreatePublisher("/asil/from_std", ServerDefined()); ASSERT_OK(pub); StdPublish(*pub, "alpha"); StdPublish(*pub, "beta"); @@ -345,7 +357,7 @@ TEST_F(AsilClientTest, AsilToAsilWithWait) { ASSERT_EQ(asil::Error::kOk, Asil().CreateSubscriber("/asil/wait", {}, sub)); asil::Publisher pub; ASSERT_EQ(asil::Error::kOk, - Asil().CreatePublisher("/asil/wait", AsilPubOptions(64, 4), pub)); + Asil().CreatePublisher("/asil/wait", StaticPubOptions(), pub)); // Drain the trigger set when the subscriber opened. asil::Message msg; @@ -361,9 +373,8 @@ TEST_F(AsilClientTest, AsilToAsilWithWait) { TEST_F(AsilClientTest, SubscriberJoinsAfterPublisher) { asil::Publisher pub; - ASSERT_EQ( - asil::Error::kOk, - Asil().CreatePublisher("/asil/late_sub", AsilPubOptions(64, 4), pub)); + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/asil/late_sub", StaticPubOptions(), pub)); absl::StatusOr sub = Std().CreateSubscriber("/asil/late_sub"); @@ -382,7 +393,7 @@ TEST_F(AsilClientTest, ChecksumToStandard) { "/asil/sum_to_std", subspace::SubscriberOptions().SetChecksum(true)); ASSERT_OK(sub); asil::Publisher pub; - asil::PublisherOptions options = AsilPubOptions(128, 4); + asil::PublisherOptions options = StaticPubOptions(); options.checksum = true; ASSERT_EQ(asil::Error::kOk, Asil().CreatePublisher("/asil/sum_to_std", options, pub)); @@ -406,7 +417,7 @@ TEST_F(AsilClientTest, ChecksumFromStandard) { lenient, lenient_sub)); absl::StatusOr pub = Std().CreatePublisher( - "/asil/sum_from_std", 128, 4, FixedSize().SetChecksum(true)); + "/asil/sum_from_std", ServerDefined().SetChecksum(true)); ASSERT_OK(pub); StdPublish(*pub, "good"); @@ -440,10 +451,8 @@ TEST_F(AsilClientTest, Metadata) { ASSERT_OK(std_sub); asil::Publisher asil_pub; - asil::PublisherOptions options = AsilPubOptions(64, 8); - options.metadata_size = 16; ASSERT_EQ(asil::Error::kOk, - Asil().CreatePublisher("/asil/meta", options, asil_pub)); + 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"); @@ -452,8 +461,8 @@ TEST_F(AsilClientTest, Metadata) { 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", 64, 8, FixedSize().SetMetadataSize(16)); + absl::StatusOr std_pub = + Std().CreatePublisher("/asil/meta", ServerDefined()); ASSERT_OK(std_pub); absl::StatusOr buffer = std_pub->GetMessageBuffer(); ASSERT_OK(buffer); @@ -478,7 +487,7 @@ TEST_F(AsilClientTest, ReadNewest) { asil::Subscriber sub; ASSERT_EQ(asil::Error::kOk, Asil().CreateSubscriber("/asil/newest", {}, sub)); absl::StatusOr pub = - Std().CreatePublisher("/asil/newest", 64, 8, FixedSize()); + Std().CreatePublisher("/asil/newest", ServerDefined()); ASSERT_OK(pub); StdPublish(*pub, "old"); StdPublish(*pub, "older"); @@ -501,7 +510,7 @@ TEST_F(AsilClientTest, AsilSubscriberCountsDrops) { ASSERT_EQ(asil::Error::kOk, Asil().CreateSubscriber("/asil/drops_in", {}, sub)); absl::StatusOr pub = - Std().CreatePublisher("/asil/drops_in", 64, 4, FixedSize()); + Std().CreatePublisher("/asil/drops_in", ServerDefined()); ASSERT_OK(pub); StdPublish(*pub, "first"); asil::Message msg; @@ -544,9 +553,8 @@ TEST_F(AsilClientTest, StandardSubscriberSeesAsilDrops) { [&dropped](subspace::Subscriber *, int64_t n) { dropped += n; })); asil::Publisher pub; - ASSERT_EQ( - asil::Error::kOk, - Asil().CreatePublisher("/asil/drops_out", AsilPubOptions(64, 4), pub)); + ASSERT_EQ(asil::Error::kOk, + Asil().CreatePublisher("/asil/drops_out", StaticPubOptions(), pub)); AsilPublish(pub, "first"); EXPECT_EQ("first", StdRead(*sub).text); @@ -577,7 +585,7 @@ TEST_F(AsilClientTest, Activation) { Asil().CreateSubscriber("/asil/activate", {}, asil_sub)); asil::Publisher pub; - asil::PublisherOptions options = AsilPubOptions(64, 4); + asil::PublisherOptions options = StaticPubOptions(); options.activate = true; ASSERT_EQ(asil::Error::kOk, Asil().CreatePublisher("/asil/activate", options, pub)); @@ -604,7 +612,7 @@ TEST_F(AsilClientTest, ManyMessagesThroughFewSlots) { ASSERT_OK(std_sub); asil::Publisher pub; ASSERT_EQ(asil::Error::kOk, - Asil().CreatePublisher("/asil/cycle", AsilPubOptions(64, 4), pub)); + Asil().CreatePublisher("/asil/cycle", StaticPubOptions(), pub)); for (int i = 0; i < 200; i++) { const std::string text = "message " + std::to_string(i); @@ -621,7 +629,7 @@ TEST_F(AsilClientTest, HeldMessageIsNotOverwritten) { asil::Subscriber sub; ASSERT_EQ(asil::Error::kOk, Asil().CreateSubscriber("/asil/hold", {}, sub)); absl::StatusOr pub = - Std().CreatePublisher("/asil/hold", 64, 4, FixedSize()); + Std().CreatePublisher("/asil/hold", ServerDefined()); ASSERT_OK(pub); StdPublish(*pub, "held"); asil::Message held; @@ -641,16 +649,15 @@ TEST_F(AsilClientTest, HeldMessageIsNotOverwritten) { } 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(128, 4), pub)); - EXPECT_THAT(Asil().LastServerError(), HasSubstr("has 4 slots of 64 bytes")); + 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", AsilPubOptions(64, 4), pub)); + EXPECT_EQ(asil::Error::kServerRejected, + Asil().CreatePublisher("/asil/unknown", StaticPubOptions(), pub)); EXPECT_THAT(Asil().LastServerError(), HasSubstr("isn't in the static channel config")); @@ -658,30 +665,57 @@ TEST_F(AsilClientTest, Rejections) { EXPECT_EQ(asil::Error::kServerRejected, Asil().CreateSubscriber("/asil/unknown", {}, sub)); - EXPECT_EQ(asil::Error::kInvalidArgument, - Asil().CreatePublisher("/asil/reject", AsilPubOptions(0, 4), pub)); + // 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(), - AsilPubOptions(64, 4), pub)); + StaticPubOptions(), pub)); ASSERT_EQ(asil::Error::kOk, - Asil().CreatePublisher("/asil/reject", AsilPubOptions(64, 4), pub)); + 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", AsilPubOptions(64, 4), pub)); + 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", AsilPubOptions(64, 4), - 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", AsilPubOptions(64, 4), pub)); + Asil().CreatePublisher("/asil/close", StaticPubOptions(), pub)); ASSERT_EQ(asil::Error::kOk, Asil().CreateSubscriber("/asil/close", {}, sub)); absl::StatusOr info = Std().GetChannelInfo("/asil/close"); @@ -701,7 +735,7 @@ TEST_F(AsilClientTest, CloseRemovesFromServer) { // The channel can be used again. ASSERT_EQ(asil::Error::kOk, - Asil().CreatePublisher("/asil/close", AsilPubOptions(64, 4), pub)); + Asil().CreatePublisher("/asil/close", StaticPubOptions(), pub)); ASSERT_EQ(asil::Error::kOk, Asil().CreateSubscriber("/asil/close", {}, sub)); AsilPublish(pub, "again"); asil::Message msg; @@ -722,7 +756,7 @@ TEST_F(AsilClientTest, HandshakeMakesNoHeapAllocations) { allocations = 0; counting_allocations = true; const asil::Error pub_error = - Asil().CreatePublisher("/asil/no_alloc", AsilPubOptions(64, 4), pub); + 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(); @@ -765,9 +799,8 @@ int FillReliable(asil::Publisher &pub, const std::string &prefix, int first) { return n - first; } -asil::PublisherOptions ReliablePubOptions(int64_t slot_size, - int32_t num_slots) { - asil::PublisherOptions options = AsilPubOptions(slot_size, num_slots); +asil::PublisherOptions ReliablePubOptions() { + asil::PublisherOptions options = StaticPubOptions(); options.reliable = true; return options; } @@ -777,9 +810,9 @@ TEST_F(AsilClientTest, ReliableAsilPublisherStandardSubscriber) { "/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(64, 4), 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. @@ -806,7 +839,7 @@ TEST_F(AsilClientTest, StandardReliablePublisherAsilSubscriber) { Asil().CreateSubscriber("/asil/rel_from_std", options, sub)); EXPECT_TRUE(sub.IsReliable()); absl::StatusOr pub = Std().CreatePublisher( - "/asil/rel_from_std", 64, 4, FixedSize().SetReliable(true)); + "/asil/rel_from_std", ServerDefined().SetReliable(true)); ASSERT_OK(pub); int published = 0; @@ -849,9 +882,9 @@ TEST_F(AsilClientTest, ReliableReadNewestFreesSkippedSlots) { 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(64, 4), pub)); + ASSERT_EQ( + asil::Error::kOk, + Asil().CreatePublisher("/asil/rel_newest", ReliablePubOptions(), pub)); ASSERT_EQ(3, FillReliable(pub, "n", 0)); asil::Message msg; @@ -871,9 +904,8 @@ TEST_F(AsilClientTest, ReliableReadNewestFreesSkippedSlots) { TEST_F(AsilClientTest, ReliablePublisherWaitsForSubscriber) { asil::Publisher pub; - ASSERT_EQ( - asil::Error::kOk, - Asil().CreatePublisher("/asil/rel_late", ReliablePubOptions(64, 4), pub)); + ASSERT_EQ(asil::Error::kOk, Asil().CreatePublisher( + "/asil/rel_late", ReliablePubOptions(), pub)); EXPECT_EQ(nullptr, pub.Buffer()); absl::StatusOr sub = Std().CreateSubscriber( @@ -885,9 +917,8 @@ TEST_F(AsilClientTest, ReliablePublisherWaitsForSubscriber) { TEST_F(AsilClientTest, VirtualChannels) { asil::Publisher rejected; - EXPECT_EQ( - asil::Error::kServerRejected, - Asil().CreatePublisher("/asil/v1", AsilPubOptions(128, 8), rejected)); + EXPECT_EQ(asil::Error::kServerRejected, + Asil().CreatePublisher("/asil/v1", StaticPubOptions(), rejected)); asil::Subscriber mux_sub; ASSERT_EQ(asil::Error::kOk, @@ -902,14 +933,14 @@ TEST_F(AsilClientTest, VirtualChannels) { "/asil/v1", subspace::SubscriberOptions().SetMux("/asil/mux")); ASSERT_OK(v1_sub); - asil::PublisherOptions v1_options = AsilPubOptions(128, 8); + 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", 128, 8, FixedSize().SetMux("/asil/mux")); + absl::StatusOr v2_pub = + Std().CreatePublisher("/asil/v2", ServerDefined().SetMux("/asil/mux")); ASSERT_OK(v2_pub); AsilPublish(v1_pub, "a1"); @@ -949,7 +980,7 @@ TEST_F(AsilClientTest, MultipleActiveMessages) { ASSERT_EQ(asil::Error::kOk, Asil().CreateSubscriber("/asil/multi", options, sub)); absl::StatusOr pub = - Std().CreatePublisher("/asil/multi", 64, 8, FixedSize()); + Std().CreatePublisher("/asil/multi", ServerDefined()); ASSERT_OK(pub); for (const char *text : {"a", "b", "c", "d"}) { StdPublish(*pub, text); @@ -992,19 +1023,19 @@ TEST_F(AsilClientTest, SubscriberOpensBeforeAnyPublisher) { EXPECT_EQ(0u, msg.length); absl::StatusOr pub = - Std().CreatePublisher("/asil/early_sub", 64, 4, FixedSize()); + 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)); } -asil::PublisherOptions SplitPubOptions(int64_t slot_size, int32_t num_slots, - asil::SplitSlot *slots) { - asil::PublisherOptions options = AsilPubOptions(slot_size, num_slots); - options.use_split_buffers = true; +// 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 = num_slots; + options.split_slot_capacity = capacity; return options; } @@ -1031,7 +1062,7 @@ TEST_F(AsilClientTest, SplitAsilPublisherStandardSubscriber) { asil::Publisher pub; ASSERT_EQ(asil::Error::kOk, Asil().CreatePublisher("/asil/split_to_std", - SplitPubOptions(256, 4, pub_slots), pub)) + SplitPubOptions(pub_slots, 4), pub)) << Asil().LastServerError(); EXPECT_GE(pub.SlotSize(), 256); for (const asil::SplitSlot &slot : pub_slots) { @@ -1063,8 +1094,7 @@ TEST_F(AsilClientTest, SplitStandardPublisherAsilSubscriber) { ASSERT_EQ(asil::Error::kOk, Asil().CreateSubscriber("/asil/split_from_std", options, sub)); absl::StatusOr pub = Std().CreatePublisher( - "/asil/split_from_std", 256, 4, - FixedSize().SetUseSplitBuffers(true).SetChecksum(true)); + "/asil/split_from_std", ServerDefined().SetChecksum(true)); ASSERT_OK(pub); asil::Message msg; @@ -1087,7 +1117,7 @@ TEST_F(AsilClientTest, SplitVirtualChannel) { EXPECT_EQ(4, sub.VirtualChannelId()); asil::SplitSlot pub_slots[8]; - asil::PublisherOptions pub_options = SplitPubOptions(128, 8, pub_slots); + asil::PublisherOptions pub_options = SplitPubOptions(pub_slots, 8); pub_options.mux = "/asil/split_mux"; asil::Publisher pub; ASSERT_EQ(asil::Error::kOk, @@ -1110,15 +1140,16 @@ TEST_F(AsilClientTest, SplitRejections) { 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::kServerRejected, - Asil().CreatePublisher("/asil/split_reject", AsilPubOptions(64, 4), pub)); - EXPECT_THAT(Asil().LastServerError(), HasSubstr("uses split buffers")); - EXPECT_EQ(asil::Error::kServerRejected, - Asil().CreatePublisher("/asil/reject", - SplitPubOptions(64, 4, slots), pub)); - EXPECT_THAT(Asil().LastServerError(), HasSubstr("doesn't use split buffers")); + 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(AsilDynamicTest, AsilPublisherCreatesChannel) { diff --git a/asil_client/phaser_connection.cc b/asil_client/phaser_connection.cc index 02b0c5da..81cacc49 100644 --- a/asil_client/phaser_connection.cc +++ b/asil_client/phaser_connection.cc @@ -388,7 +388,8 @@ Error PhaserServerConnection::CreatePublisher(const PublisherRequest &request, 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(true); + 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)); @@ -420,6 +421,10 @@ Error PhaserServerConnection::CreatePublisher(const PublisherRequest &request, 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; diff --git a/asil_client/publisher.cc b/asil_client/publisher.cc index c87aa579..5395b69b 100644 --- a/asil_client/publisher.cc +++ b/asil_client/publisher.cc @@ -41,10 +41,18 @@ Error Publisher::Open(Client &client, const char *channel_name, if (!client.Initialized()) { return Error::kNotInitialized; } - if (options.slot_size <= 0 || options.num_slots <= 0 || - !ValidLayoutSize(options.checksum_size) || - !ValidLayoutSize(options.metadata_size) || options.vchan_id < -1 || - options.vchan_id >= shm::kMaxVchanId) { + 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) { @@ -55,11 +63,11 @@ Error Publisher::Open(Client &client, const char *channel_name, e != Error::kOk) { return e; } - const int64_t slot_size = shm::Aligned64(options.slot_size); - PublisherRequest request; request.channel_name = name_; - request.slot_size = slot_size; + 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; @@ -91,22 +99,35 @@ Error Publisher::Open(Client &client, const char *channel_name, 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)) { + (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, - options.checksum_size, options.metadata_size, + checksum_size, metadata_size, reply.subscriber_queue_arena_size, &buffer_context_); } if (e == Error::kOk) { - e = options.use_split_buffers + e = use_split_buffers ? memory_.AttachSplitBuffers( /*writable=*/true, options.split_slots, options.split_slot_capacity, options.split_allocator) diff --git a/asil_client/publisher.h b/asil_client/publisher.h index 90701f3c..14e91122 100644 --- a/asil_client/publisher.h +++ b/asil_client/publisher.h @@ -18,8 +18,14 @@ namespace asil { class Client; struct PublisherOptions { - // The channel layout. On a server with a static channel config these must - // match the configured channel. + // 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. @@ -40,10 +46,11 @@ struct PublisherOptions { // 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. They must exist already: the server - // creates them for a static channel, otherwise a standard publisher does. - // split_slots has room for the channel's num_slots slot mappings, and the - // allocator maps slots that a custom allocator created. + // 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; diff --git a/asil_client/server_connection.h b/asil_client/server_connection.h index 40e47cad..80a84767 100644 --- a/asil_client/server_connection.h +++ b/asil_client/server_connection.h @@ -47,6 +47,9 @@ struct PublisherRequest { 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 { @@ -56,6 +59,11 @@ struct PublisherReply { 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. 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/client.cc b/client/client.cc index cc0a96cf..ec13b0af 100644 --- a/client/client.cc +++ b/client/client.cc @@ -434,8 +434,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"); } @@ -483,6 +494,15 @@ 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(), @@ -507,8 +527,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)); @@ -534,7 +556,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; @@ -2228,24 +2250,30 @@ 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 diff --git a/client/options.h b/client/options.h index 431cb168..106984be 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/python/client.cc b/client/python/client.cc index 312bddf6..48de226c 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/docs/asil-client.md b/docs/asil-client.md index 74591dc0..dd5b026c 100644 --- a/docs/asil-client.md +++ b/docs/asil-client.md @@ -88,9 +88,10 @@ 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. Publishers must then use -split buffers, and on any other static channel they must not. On a server -that creates channels on demand, the first standard publisher creates them. +`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, @@ -245,9 +246,25 @@ asil::Error Run() { ## Publishers `PublisherOptions` gives the slot size, number of slots, checksum size, -metadata size and type. On a static channel these must match the config. +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, or if `server_defined` is set and the channel isn't static. 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 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/rust-client.md b/docs/rust-client.md index 39871ad1..53c66d87 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: diff --git a/proto/subspace.proto b/proto/subspace.proto index 29498d17..888e9764 100644 --- a/proto/subspace.proto +++ b/proto/subspace.proto @@ -52,6 +52,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 { @@ -73,6 +78,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 diff --git a/rust_client/src/client.rs b/rust_client/src/client.rs index 3d596de7..e5ddfcad 100644 --- a/rust_client/src/client.rs +++ b/rust_client/src/client.rs @@ -1209,7 +1209,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(), @@ -1263,6 +1281,7 @@ impl Client { } else { 0 }, + server_defined: opts.server_defined, }, )), }; @@ -1289,6 +1308,26 @@ impl Client { 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, @@ -1301,24 +1340,11 @@ impl Client { String::from_utf8_lossy(&pub_resp.r#type).to_string(), 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( 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/server/client_handler.cc b/server/client_handler.cc index 9ffc57b5..c2cc580c 100644 --- a/server/client_handler.cc +++ b/server/client_handler.cc @@ -4,6 +4,7 @@ #include "server/client_handler.h" #include "absl/strings/str_format.h" +#include "absl/strings/str_join.h" #include "client_handler.h" #include "server/server.h" #include @@ -355,9 +356,76 @@ void ClientHandler::HandleInit(const subspace::InitRequest &req, } void ClientHandler::HandleCreatePublisher( - const subspace::CreatePublisherRequest &req, + const subspace::CreatePublisherRequest &request, subspace::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; + } + subspace::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; + server_defined_req = request; + 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::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; @@ -453,45 +521,6 @@ void ClientHandler::HandleCreatePublisher( !StaticConfigAllowsNewChannel(*server_, req.channel_name(), response)) { return; } - if (channel != nullptr && channel->IsStatic()) { - // Resizing happens in the publisher, so only a fixed size publisher keeps - // the configured layout. - if (!req.is_fixed_size()) { - response->set_error(absl::StrFormat( - "Publishers on static channel %s must be fixed size", - req.channel_name())); - return; - } - if (req.slot_size() != channel->SlotSize() || - req.num_slots() != channel->NumSlots()) { - response->set_error(absl::StrFormat( - "Static channel %s has %d slots of %d bytes, not %d slots of %d " - "bytes", - req.channel_name(), channel->NumSlots(), channel->SlotSize(), - req.num_slots(), req.slot_size())); - return; - } - if (cs != channel->ChecksumSize() || ms != channel->MetadataSize()) { - response->set_error(absl::StrFormat( - "Static channel %s has checksum_size %d and metadata_size %d, not " - "%d and %d", - req.channel_name(), channel->ChecksumSize(), channel->MetadataSize(), - cs, ms)); - return; - } - const ServerChannel *layout_channel = - channel->IsVirtual() - ? static_cast(channel)->GetMux() - : channel; - const bool split = layout_channel->HasSplitBufferOptions() && - layout_channel->GetSplitBufferOptions().use_split_buffers; - if (req.use_split_buffers() != split) { - response->set_error(absl::StrFormat( - "Static channel %s %s split buffers", req.channel_name(), - split ? "uses" : "doesn't use")); - return; - } - } if (channel == nullptr) { server_->logger_.Log(toolbelt::LogLevel::kDebug, "Publisher %s is creating new channel %s with size " @@ -819,6 +848,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); diff --git a/server/client_handler.h b/server/client_handler.h index 778baaba..294a5276 100644 --- a/server/client_handler.h +++ b/server/client_handler.h @@ -46,7 +46,7 @@ class ClientHandler { void HandleInit(const subspace::InitRequest &req, subspace::InitResponse *response, std::vector &fds); - void HandleCreatePublisher(const subspace::CreatePublisherRequest &req, + void HandleCreatePublisher(const subspace::CreatePublisherRequest &request, subspace::CreatePublisherResponse *response, std::vector &fds); void HandleCreateSubscriber(const subspace::CreateSubscriberRequest &req, diff --git a/server/server.cc b/server/server.cc index e1d9b892..2d4c7ce4 100644 --- a/server/server.cc +++ b/server/server.cc @@ -3397,17 +3397,25 @@ 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() - .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)); + PublisherOptions bridge_options = PublisherOptions() + .SetReliable(subscribed.reliable()) + .SetBridge(true) + .SetNotifyRetirement( + subscribed.notify_retirement()); + // A static channel keeps the layout from this server's config. + if (const ServerChannel *local = FindChannel(channel_name); + local != nullptr && local->IsStatic()) { + bridge_options.SetServerDefined(true).SetUseSplitBuffers(false); + } 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_test.cc b/server/server_test.cc index 3b9018d8..91e6cb57 100644 --- a/server/server_test.cc +++ b/server/server_test.cc @@ -316,6 +316,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::Request req; + subspace::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())); diff --git a/server/static_config_test.cc b/server/static_config_test.cc index 431e875a..5cf55fb0 100644 --- a/server/static_config_test.cc +++ b/server/static_config_test.cc @@ -11,7 +11,9 @@ #include "absl/status/status.h" #include "absl/status/statusor.h" #include "absl/strings/str_format.h" +#include "proto/subspace.pb.h" #include "server/static_config.h" +#include "toolbelt/sockets.h" #include #include #include @@ -44,8 +46,39 @@ constexpr char kConfig[] = R"pb( channels { name: "/static/sv" mux: "/static/split_mux" vchan_id: 1 } )pb"; -subspace::PublisherOptions FixedSize() { - return subspace::PublisherOptions().SetFixedSize(true); +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::Request &req) { + std::vector buffer(sizeof(int32_t) + req.ByteSizeLong()); + char *payload = buffer.data() + sizeof(int32_t); + if (!req.SerializeToArray(payload, static_cast(req.ByteSizeLong()))) { + return absl::InternalError("Failed to serialize request"); + } + if (absl::StatusOr n = + socket.SendMessage(payload, req.ByteSizeLong()); + !n.ok()) { + return n.status(); + } + absl::StatusOr> received = + socket.ReceiveVariableLengthMessage(); + if (!received.ok()) { + return received.status(); + } + subspace::Response response; + if (!response.ParseFromArray(received->data(), + static_cast(received->size()))) { + return absl::InternalError("Failed to parse response"); + } + 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) { @@ -106,6 +139,7 @@ class StaticConfigTest : public ::testing::Test { } subspace::Client &Client() { return client_; } + static const std::string &Socket() { return socket_; } private: inline static subspace::async::RuntimeEngine engine_; @@ -204,7 +238,7 @@ TEST_F(StaticConfigTest, SubscriberBeforePublisher) { EXPECT_EQ(8, sub->NumSlots()); absl::StatusOr pub = - Client().CreatePublisher("/static/a", 256, 8, FixedSize()); + Client().CreatePublisher("/static/a", ServerDefined()); ASSERT_OK(pub); Publish(*pub, "hello"); @@ -221,10 +255,12 @@ TEST_F(StaticConfigTest, SplitBuffersCreatedByServer) { ASSERT_OK(sub); EXPECT_TRUE(sub->UsesSplitBuffers()); - absl::StatusOr pub = Client().CreatePublisher( - "/static/split", 256, 4, FixedSize().SetUseSplitBuffers(true)); + 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); @@ -242,9 +278,9 @@ TEST_F(StaticConfigTest, SplitBufferVirtualChannel) { EXPECT_TRUE(sub->UsesSplitBuffers()); absl::StatusOr pub = Client().CreatePublisher( - "/static/sv", 128, 4, - FixedSize().SetMux("/static/split_mux").SetUseSplitBuffers(true)); + "/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); @@ -252,22 +288,103 @@ TEST_F(StaticConfigTest, SplitBufferVirtualChannel) { std::string(static_cast(msg->buffer), msg->length)); } -TEST_F(StaticConfigTest, RejectsMismatchedSplitBuffers) { - absl::StatusOr unsplit = - Client().CreatePublisher("/static/split", 256, 4, FixedSize()); - ASSERT_FALSE(unsplit.ok()); - EXPECT_THAT(unsplit.status().message(), HasSubstr("uses split buffers")); - - absl::StatusOr split = Client().CreatePublisher( - "/static/a", 256, 8, FixedSize().SetUseSplitBuffers(true)); - ASSERT_FALSE(split.ok()); - EXPECT_THAT(split.status().message(), - HasSubstr("doesn't use split buffers")); +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::Request init; + init.mutable_init()->set_client_name("raw"); + ASSERT_OK(Transact(socket, init)); + + const std::vector< + std::pair> + cases = { + {"num_slots", + [](subspace::CreatePublisherRequest *r) { r->set_num_slots(8); }}, + {"slot_size", + [](subspace::CreatePublisherRequest *r) { r->set_slot_size(256); }}, + {"fixed_size", + [](subspace::CreatePublisherRequest *r) { + r->set_is_fixed_size(true); + }}, + {"checksum_size", + [](subspace::CreatePublisherRequest *r) { + r->set_checksum_size(4); + }}, + {"metadata_size", + [](subspace::CreatePublisherRequest *r) { + r->set_metadata_size(16); + }}, + {"subscriber_queue_arena_size", + [](subspace::CreatePublisherRequest *r) { + r->set_subscriber_queue_arena_size(4096); + }}, + {"use_split_buffers", + [](subspace::CreatePublisherRequest *r) { + r->set_use_split_buffers(true); + }}, + }; + for (const auto &[field, set] : cases) { + subspace::Request req; + subspace::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, UnconfiguredChannelsAreRejected) { absl::StatusOr pub = - Client().CreatePublisher("/not/configured", 64, 4, FixedSize()); + Client().CreatePublisher("/not/configured", ServerDefined()); ASSERT_FALSE(pub.ok()); EXPECT_THAT(pub.status().message(), HasSubstr("isn't in the static channel config")); @@ -279,52 +396,17 @@ TEST_F(StaticConfigTest, UnconfiguredChannelsAreRejected) { HasSubstr("isn't in the static channel config")); // A virtual channel on a configured multiplexer must be configured too. - pub = Client().CreatePublisher("/static/v9", 128, 8, - FixedSize().SetMux("/static/mux")); + pub = Client().CreatePublisher("/static/v9", + ServerDefined().SetMux("/static/mux")); ASSERT_FALSE(pub.ok()); EXPECT_THAT(pub.status().message(), HasSubstr("isn't in the static channel config")); } -TEST_F(StaticConfigTest, PublisherLayoutMustMatch) { - absl::StatusOr pub = Client().CreatePublisher( - "/static/a", 256, 8, subspace::PublisherOptions()); - ASSERT_FALSE(pub.ok()); - EXPECT_THAT(pub.status().message(), HasSubstr("must be fixed size")); - - for (auto [slot_size, num_slots] : - std::vector>{{512, 8}, {128, 8}, {256, 16}, - {256, 4}}) { - pub = Client().CreatePublisher("/static/a", slot_size, num_slots, - FixedSize()); - ASSERT_FALSE(pub.ok()) << slot_size << "/" << num_slots; - EXPECT_THAT(pub.status().message(), - HasSubstr("has 8 slots of 256 bytes")); - } - - pub = Client().CreatePublisher("/static/meta", 64, 4, FixedSize()); - ASSERT_FALSE(pub.ok()); - EXPECT_THAT(pub.status().message(), - HasSubstr("checksum_size 4 and metadata_size 16, not 4 and 0")); - pub = Client().CreatePublisher("/static/meta", 64, 4, - FixedSize().SetMetadataSize(16)); - ASSERT_OK(pub); - - // A matching second publisher is accepted after the first has created the - // channel's buffers. - absl::StatusOr first = - Client().CreatePublisher("/static/a", 256, 8, FixedSize()); - ASSERT_OK(first); - Publish(*first, "x"); - absl::StatusOr second = - Client().CreatePublisher("/static/a", 256, 8, FixedSize()); - ASSERT_OK(second); -} - TEST_F(StaticConfigTest, ChannelsOutliveTheirUsers) { { absl::StatusOr pub = - Client().CreatePublisher("/static/a", 256, 8, FixedSize()); + Client().CreatePublisher("/static/a", ServerDefined()); ASSERT_OK(pub); absl::StatusOr sub = Client().CreateSubscriber("/static/a"); @@ -340,7 +422,7 @@ TEST_F(StaticConfigTest, ChannelsOutliveTheirUsers) { EXPECT_EQ(8, info->num_slots); absl::StatusOr pub = - Client().CreatePublisher("/static/a", 256, 8, FixedSize()); + Client().CreatePublisher("/static/a", ServerDefined()); ASSERT_OK(pub); absl::StatusOr sub = Client().CreateSubscriber("/static/a"); @@ -360,13 +442,10 @@ TEST_F(StaticConfigTest, VirtualChannels) { EXPECT_EQ(3, sub->VirtualChannelId()); absl::StatusOr pub = Client().CreatePublisher( - "/static/v1", 256, 8, FixedSize().SetMux("/static/mux")); - ASSERT_FALSE(pub.ok()); - EXPECT_THAT(pub.status().message(), HasSubstr("has 8 slots of 128 bytes")); - - pub = Client().CreatePublisher("/static/v1", 128, 8, - FixedSize().SetMux("/static/mux")); + "/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"); @@ -378,7 +457,7 @@ TEST_F(StaticConfigTest, VirtualChannels) { // Publishers on other virtual channels of the multiplexer share its // buffers, so they are also fixed size. absl::StatusOr other = Client().CreatePublisher( - "/static/v2", 128, 8, FixedSize().SetMux("/static/mux")); + "/static/v2", ServerDefined().SetMux("/static/mux")); ASSERT_OK(other); EXPECT_EQ(7, other->VirtualChannelId()); } From c664b749da9d76f90a9ddba84eb25bcc1a519807 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Thu, 5 Nov 2026 14:47:24 -0800 Subject: [PATCH 06/21] Share the shared memory protocol between the C++ clients and send native Phaser payloads * Send native Phaser payloads between the clients and the server. The C++ clients, the server and the Rust client exchange the Phaser message buffer itself instead of transcoding to protobuf wire format. Phaser 3.1.1 adds copying and parsing that payload from C and Rust. Fixed-buffer errors in the ASIL connection keep their text without allocating, so an oversized request or response says why it failed. * Share the shared memory protocol between the ASIL and standard clients. common/ now holds the memory layout, the channel control block view, the slot search, publishing, taking, releasing and skipping messages, the message checksum and CRC32. Both clients use them, so they can't drift. The ASIL client keeps its no-exception, no-allocation build. Sharing the code fixed these bugs: - The ASIL publisher could reuse a slot with a stale retired bit, losing an unread message, and its checksum didn't mask transport flags. - A reliable subscriber reading the newest message in the standard client didn't mark the skipped messages seen, so a reliable publisher could no longer get a slot once the free slots ran out. - A standard subscriber ignoring an activation message kept its owner bit, so a crash later made the server drop another message's reference. - Retirement notification for a bridged message crashed if its original slot id was beyond this channel's slots. --- CHANGELOG.md | 23 +- CMakeLists.txt | 4 +- MODULE.bazel | 24 +- MODULE.bazel.lock | 264 ++---- asil_client/Android.bp | 2 +- asil_client/BUILD.bazel | 11 +- asil_client/CMakeLists.txt | 2 +- asil_client/asil_client_test.cc | 438 ++++++++- asil_client/channel_memory.cc | 239 +---- asil_client/channel_memory.h | 37 +- asil_client/checksum.cc | 44 - asil_client/checksum.h | 19 - asil_client/client.h | 5 +- asil_client/layout_test.cc | 794 ++++++++++++---- asil_client/phaser_connection.cc | 38 +- asil_client/phaser_connection.h | 21 +- asil_client/publisher.cc | 408 ++------- asil_client/publisher.h | 12 +- asil_client/server_connection.h | 3 +- asil_client/shm_layout.h | 311 ++----- asil_client/subscriber.cc | 135 +-- asil_client/subscriber.h | 2 +- client/Android.bp | 3 +- client/BUILD.bazel | 3 +- client/CMakeLists.txt | 8 +- client/checksum.h | 9 +- client/client_channel.cc | 5 +- client/client_channel.h | 1 + client/client_test.cc | 48 + client/publisher.cc | 579 ++---------- client/publisher.h | 20 +- client/subscriber.cc | 133 +-- client/subscriber.h | 16 +- common/Android.bp | 12 + common/BUILD.bazel | 52 +- common/CMakeLists.txt | 10 + {client => common}/arm_crc32.S | 0 common/atomic_bitset.h | 80 +- asil_client/bitset.h => common/bitset_view.h | 10 +- common/channel.cc | 109 +-- common/channel.h | 896 +------------------ common/channel_view.h | 201 +++++ client/checksum.cc => common/crc32.cc | 4 +- common/crc32.h | 24 + common/dynamic_bitset.h | 64 ++ common/message_checksum.h | 85 ++ common/publish.h | 190 ++++ common/server_wire.h | 158 +++- common/shm_layout.h | 876 ++++++++++++++++++ common/slot_search.h | 447 +++++++++ common/subscribe.h | 135 +++ docs/asil-client.md | 58 +- docs/client_design.md | 2 +- docs/rust-client.md | 6 +- proto/BUILD.bazel | 14 + proto/CMakeLists.txt | 5 +- rust_client/BUILD.bazel | 1 + rust_client/src/client.rs | 771 ++++++++-------- rust_client/src/socket.rs | 23 +- server/BUILD.bazel | 3 + server/client_handler.cc | 217 ++--- server/client_handler.h | 45 +- server/server.h | 3 +- server/server_channel.cc | 61 +- server/server_channel.h | 11 + server/server_channels.cc | 4 +- server/server_test.cc | 123 +-- server/static_config_test.cc | 52 +- 68 files changed, 4564 insertions(+), 3849 deletions(-) delete mode 100644 asil_client/checksum.cc delete mode 100644 asil_client/checksum.h rename {client => common}/arm_crc32.S (100%) rename asil_client/bitset.h => common/bitset_view.h (89%) create mode 100644 common/channel_view.h rename client/checksum.cc => common/crc32.cc (99%) create mode 100644 common/crc32.h create mode 100644 common/dynamic_bitset.h create mode 100644 common/message_checksum.h create mode 100644 common/publish.h create mode 100644 common/shm_layout.h create mode 100644 common/slot_search.h create mode 100644 common/subscribe.h diff --git a/CHANGELOG.md b/CHANGELOG.md index cb190642..fab4f342 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -45,8 +45,8 @@ 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 in protobuf wire format, so the handshake makes no heap - allocations either. See `docs/asil-client.md`. + 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 @@ -61,11 +61,26 @@ - 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 bytes on the socket are unchanged. + 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`. -- Abseil 20250814.1, protobuf 33.4, cpp_toolbelt 2.1.6 and phaser 2.1.3 in +- 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. ### Bridge and Tunnel Plugins diff --git a/CMakeLists.txt b/CMakeLists.txt index 36bc9421..6f7ee795 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -215,8 +215,8 @@ FetchContent_MakeAvailable(protobuf) FetchContent_Declare( phaser GIT_REPOSITORY https://github.com/dallison/phaser.git - # phaser 2.1.3, as in the git_override in MODULE.bazel. - GIT_TAG 3d5eca68b74da5ad982a2768b9b54da728fd17f7 + # phaser 3.1.1, as in the git_override in MODULE.bazel. + GIT_TAG 4b3a80c0c90d51e04d4b27aa8cc32b884f2b6e38 ) FetchContent_MakeAvailable(phaser) diff --git a/MODULE.bazel b/MODULE.bazel index be56999a..05f55d90 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -12,16 +12,17 @@ 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 = "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 = "googletest", version = "1.17.0.bcr.2") bazel_dep(name = "protobuf", version = "33.4") -# Phaser asks for protobuf 34.1, whose rules_android dependency breaks the -# Android SDK toolchain here. +# 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", @@ -34,15 +35,16 @@ bazel_dep(name = "rules_android_ndk", version = "0.1.5") bazel_dep(name = "zlib", version = "1.3.1.bcr.5") bazel_dep(name = "coroutines", version = "3.4.1") bazel_dep(name = "cpp_toolbelt", version = "2.1.6") -bazel_dep(name = "phaser", version = "2.1.3") +bazel_dep(name = "phaser", version = "3.1.1") -# retro 1.1.0 and phaser 2.1.3 are not in the BCR yet; pin them 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", - commit = "3d5eca68b74da5ad982a2768b9b54da728fd17f7", + # Tag 3.1.1. + commit = "4b3a80c0c90d51e04d4b27aa8cc32b884f2b6e38", remote = "https://github.com/dallison/phaser.git", ) @@ -56,7 +58,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( @@ -72,10 +74,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 d67388c8..c8524d67 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -30,13 +30,13 @@ "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", @@ -201,8 +201,8 @@ "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", @@ -238,7 +238,6 @@ "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_java/4.0.0/MODULE.bazel": "5a78a7ae82cd1a33cef56dc578c7d2a46ed0dca12643ee45edbb8417899e6f74", "https://bcr.bazel.build/modules/rules_java/7.10.0/MODULE.bazel": "530c3beb3067e870561739f1144329a21c851ff771cd752a49e06e3dc9c2e71a", @@ -275,11 +274,11 @@ "https://bcr.bazel.build/modules/rules_python/1.3.0/MODULE.bazel": "8361d57eafb67c09b75bf4bbe6be360e1b8f4f18118ab48037f2bd50aa2ccb13", "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", @@ -372,178 +371,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" @@ -572,7 +403,7 @@ }, "@@rules_rust+//crate_universe:extensions.bzl%crate": { "general": { - "bzlTransitiveDigest": "/kTJCghTSUB25TmJ5aQiQx55ccXU8+N6gjYq1sxE8/0=", + "bzlTransitiveDigest": "V6LJL0sbMi82PD2l78ZGHkAk1lDbch9CxK48SWDJ3hs=", "usagesDigest": "elCpzqBbH4Uze4bFcJkhufozV4OiThsWRv8J+c9fLvo=", "recordedInputs": [ "ENV:CARGO_BAZEL_DEBUG \\0", @@ -595,18 +426,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" ], "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}\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 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" } } }, @@ -633,7 +478,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": { @@ -789,7 +634,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": { @@ -906,7 +751,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": { @@ -958,7 +803,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": { @@ -984,7 +829,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": { @@ -1023,7 +868,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": { @@ -1036,7 +881,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": { @@ -1101,7 +946,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": { @@ -1166,7 +1011,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": { @@ -1192,7 +1037,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": { @@ -1205,7 +1050,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": { @@ -1231,7 +1076,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": { @@ -1270,7 +1115,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": { @@ -1413,7 +1258,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": { @@ -1439,7 +1284,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": { @@ -1452,7 +1297,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": { @@ -1491,7 +1336,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" } } } @@ -1499,9 +1344,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+", @@ -1510,6 +1356,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", @@ -1532,6 +1379,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", @@ -1547,13 +1395,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", @@ -1578,11 +1426,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/asil_client/Android.bp b/asil_client/Android.bp index 7706cb1d..4847610f 100644 --- a/asil_client/Android.bp +++ b/asil_client/Android.bp @@ -9,7 +9,6 @@ cc_library_static { defaults: ["subspace_defaults"], srcs: [ "channel_memory.cc", - "checksum.cc", "client.cc", "error.cc", "publisher.cc", @@ -18,6 +17,7 @@ cc_library_static { include_dirs: ["external/subspace"], cppflags: ["-fno-exceptions"], rtti: false, + static_libs: ["libsubspace_crc32"], } // The handshake with the server, using phaser messages in fixed buffers. diff --git a/asil_client/BUILD.bazel b/asil_client/BUILD.bazel index 6d5257c0..d8e2b451 100644 --- a/asil_client/BUILD.bazel +++ b/asil_client/BUILD.bazel @@ -8,16 +8,13 @@ cc_library( name = "asil_client", srcs = [ "channel_memory.cc", - "checksum.cc", "client.cc", "error.cc", "publisher.cc", "subscriber.cc", ], hdrs = [ - "bitset.h", "channel_memory.h", - "checksum.h", "client.h", "error.h", "publisher.h", @@ -40,14 +37,17 @@ cc_library( "//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 -# protobuf wire format. +# 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"], @@ -69,6 +69,7 @@ cc_test( deps = [ ":asil_client", "//client:subspace_client", + "//common:shm_protocol", "//common:subspace_common", "@googletest//:gtest_main", ], diff --git a/asil_client/CMakeLists.txt b/asil_client/CMakeLists.txt index e1692392..0f57c417 100644 --- a/asil_client/CMakeLists.txt +++ b/asil_client/CMakeLists.txt @@ -4,13 +4,13 @@ # built without exceptions or RTTI. add_library(subspace_asil_client STATIC channel_memory.cc - checksum.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() diff --git a/asil_client/asil_client_test.cc b/asil_client/asil_client_test.cc index bd7c5476..7688a8ea 100644 --- a/asil_client/asil_client_test.cc +++ b/asil_client/asil_client_test.cc @@ -18,21 +18,80 @@ #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 namespace { -// Counts heap allocations made by this thread while counting is set. +// 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++; @@ -46,10 +105,12 @@ void *operator new(std::size_t size) { 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( @@ -77,6 +138,9 @@ constexpr char kConfig[] = R"pb( 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 { @@ -276,6 +340,8 @@ class AsilClientTest : public AsilTestBase { static void TearDownTestSuite() { server_.Stop(); } void SetUp() override { Connect(server_.Socket()); } + static const std::string &Socket() { return server_.Socket(); } + private: inline static TestServer server_; }; @@ -746,28 +812,206 @@ TEST_F(AsilClientTest, CloseRemovesFromServer) { TEST_F(AsilClientTest, HandshakeMakesNoHeapAllocations) { asil::Publisher pub; asil::Subscriber sub; - allocations = 0; - counting_allocations = true; + StartCounting(); int *volatile counted = new int(1); - counting_allocations = false; + const int sanity_allocations = StopCounting(); delete counted; - ASSERT_EQ(1, allocations); + ASSERT_EQ(1, sanity_allocations); - allocations = 0; - counting_allocations = true; + 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(); - counting_allocations = false; + 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, allocations); + 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::kServerRejected, 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, OversizedRequestKeepsTheConnection) { @@ -775,6 +1019,7 @@ TEST_F(AsilClientTest, OversizedRequestKeepsTheConnection) { 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; @@ -783,6 +1028,181 @@ TEST_F(AsilClientTest, OversizedRequestKeepsTheConnection) { 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; + std::memcpy(addr.sun_path, socket_name, sizeof(socket_name)); + 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) { + ::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) { diff --git a/asil_client/channel_memory.cc b/asil_client/channel_memory.cc index 03542c04..a52af49e 100644 --- a/asil_client/channel_memory.cc +++ b/asil_client/channel_memory.cc @@ -13,7 +13,7 @@ #include #include #include -#if ASIL_SHM_MODE == ASIL_SHM_MEMFD +#if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_MEMFD #include #endif @@ -41,7 +41,7 @@ uint64_t PageAligned(uint64_t size) { return (size + page - 1) & ~(page - 1); } -#if ASIL_SHM_MODE != ASIL_SHM_MEMFD +#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; @@ -55,7 +55,7 @@ int OpenShm(const char *name, int flags) { } #endif -#if ASIL_SHM_MODE == ASIL_SHM_POSIX +#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; @@ -131,7 +131,7 @@ Error ReadShadowSize(const char *shadow_file, uint64_t &size) { } #endif -#if ASIL_SHM_MODE == ASIL_SHM_MEMFD +#if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_MEMFD int CreateMemfd(const char *name, uint64_t size) { constexpr unsigned int kMemfdCloexec = 1; const int fd = @@ -212,58 +212,6 @@ Error CopyName(const char *name, char (&out)[kMaxChannelNameLength + 1]) { return Error::kOk; } -bool PushSlotQueue(shm::SlotQueue *queue, int32_t slot_id, uint64_t ordinal) { - const size_t capacity = queue->capacity; - if (capacity == 0) { - return false; - } - shm::SlotQueueEntry *entries = queue->Entries(); - shm::SlotQueueEntry *entry = nullptr; - uint64_t tail = queue->tail.load(std::memory_order_relaxed); - for (size_t attempt = 0; attempt < shm::kMaxSlotQueueCasAttempts; ++attempt) { - const uint64_t head = queue->head.load(std::memory_order_acquire); - if (tail - head >= capacity) { - if (!queue->drop_oldest) { - return false; - } - // Evict the oldest entry, as InPlaceSlotQueue::DropFront does. - shm::SlotQueueEntry &front = entries[head % capacity]; - uint64_t expected = head; - if (front.sequence.load(std::memory_order_acquire) != head + 1 || - !queue->head.compare_exchange_weak(expected, head + 1, - std::memory_order_acq_rel, - std::memory_order_relaxed)) { - return false; - } - front.sequence.store(head + capacity, std::memory_order_release); - queue->overflow_count.fetch_add(1, std::memory_order_release); - tail = queue->tail.load(std::memory_order_relaxed); - continue; - } - shm::SlotQueueEntry &candidate = entries[tail % capacity]; - if (candidate.sequence.load(std::memory_order_acquire) != tail) { - return false; - } - if (queue->tail.compare_exchange_strong(tail, tail + 1, - std::memory_order_acq_rel, - std::memory_order_relaxed)) { - entry = &candidate; - break; - } - } - if (entry == nullptr) { - 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 MarkSlotQueueInsertionFailure(shm::SlotQueue *queue) { - queue->insertion_failed.store(true, std::memory_order_release); -} - Error ChannelMemory::Map(shm::SystemControlBlock *scb, int ccb_fd, int bcb_fd, int num_slots, int32_t checksum_size, int32_t metadata_size, @@ -303,7 +251,7 @@ Error ChannelMemory::Map(shm::SystemControlBlock *scb, int ccb_fd, int bcb_fd, bcb_ = static_cast(bcb); context_ = context; ccb_size_ = ccb_size; - queue_arena_size_ = static_cast(subscriber_queue_arena_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; @@ -365,7 +313,7 @@ Error ChannelMemory::BufferName(int index, *p = '.'; } } -#if ASIL_SHM_MODE == ASIL_SHM_POSIX +#if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_POSIX const char *format = "/tmp/subspace_%llu_%s_%d"; #else const char *format = "subspace_%llu_%s_%d"; @@ -384,7 +332,7 @@ Error ChannelMemory::NewestIndex(int &index) const { if (num_buffers <= 0) { return Error::kNoBuffers; } - if (num_buffers > shm::kMaxBuffers) { + if (num_buffers > static_cast(shm::kMaxBuffers)) { return Error::kLayoutMismatch; } index = num_buffers - 1; @@ -444,7 +392,7 @@ Error ChannelMemory::MapBuffer(int index, int fd, uint64_t size, int prot) { // Opens buffer index, which has already been created. Error ChannelMemory::OpenBuffer(int index, bool writable, UniqueFd &fd, uint64_t &size) const { -#if ASIL_SHM_MODE == ASIL_SHM_MEMFD +#if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_MEMFD (void)writable; BufferReply reply; if (Error e = GetRegisteredBuffer(index, /*is_prefix=*/false, 0, reply); @@ -470,7 +418,7 @@ Error ChannelMemory::OpenBuffer(int index, bool writable, UniqueFd &fd, return e; } const int flags = writable ? O_RDWR : O_RDONLY; -#if ASIL_SHM_MODE == ASIL_SHM_POSIX +#if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_POSIX char shm_name[64]; if (Error e = PosixShmName(name, shm_name); e != Error::kOk) { return e; @@ -551,14 +499,14 @@ Error ChannelMemory::CreateBuffer(uint64_t full_size) { if (Error e = BufferName(0, name); e != Error::kOk) { return e; } -#if ASIL_SHM_MODE == ASIL_SHM_MEMFD +#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 ASIL_SHM_MODE == ASIL_SHM_POSIX +#if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_POSIX if (Error e = CreateShadowFile(name); e != Error::kOk) { return e; } @@ -577,7 +525,7 @@ Error ChannelMemory::CreateBuffer(uint64_t full_size) { // EEXIST: another publisher created the buffer. return errno == EEXIST ? Error::kOk : Error::kSharedMemoryError; } -#if ASIL_SHM_MODE == ASIL_SHM_POSIX +#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) { @@ -589,7 +537,7 @@ Error ChannelMemory::CreateBuffer(uint64_t full_size) { ::chmod(path, 0777) != 0 || (root && ::chown(path, static_cast(context_->user_id), static_cast(context_->group_id)) != 0)) { -#if ASIL_SHM_MODE == ASIL_SHM_POSIX +#if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_POSIX (void)::shm_unlink(shm_name); #endif return Error::kSharedMemoryError; @@ -601,7 +549,7 @@ Error ChannelMemory::CreateBuffer(uint64_t full_size) { expected, 1, std::memory_order_release, std::memory_order_relaxed)) { return Error::kOk; } -#if ASIL_SHM_MODE == ASIL_SHM_MEMFD +#if SUBSPACE_SHMEM_MODE == SUBSPACE_SHMEM_MODE_MEMFD ClientBuffer registration; registration.channel_name = context_->channel_name; registration.session_id = context_->session_id; @@ -766,12 +714,6 @@ Error ChannelMemory::MapSplitSlot(int slot_id, uint64_t payload_size, return Error::kOk; } -shm::MessageSlot *ChannelMemory::Slot(int id) const { - auto *slots = reinterpret_cast( - reinterpret_cast(ccb_) + sizeof(shm::ChannelControlBlock)); - return &slots[id]; -} - shm::MessagePrefix *ChannelMemory::Prefix(const shm::MessageSlot *slot) const { if (!InMappedBuffer(slot)) { return nullptr; @@ -792,160 +734,9 @@ char *ChannelMemory::Payload(const shm::MessageSlot *slot) const { return reinterpret_cast(Prefix(slot)) + prefix_size_; } -BitsetView ChannelMemory::RetiredSlots() const { - return BitsetView(reinterpret_cast(ccb_) + - shm::RetiredSlotsOffset(num_slots_), - num_slots_); -} - -BitsetView ChannelMemory::FreeSlots() const { - return BitsetView(reinterpret_cast(ccb_) + - shm::FreeSlotsOffset(num_slots_), - num_slots_); -} - -BitsetView ChannelMemory::AvailableSlots(int sub_id) const { - return BitsetView(reinterpret_cast(ccb_) + - shm::AvailableSlotsOffset(num_slots_, sub_id), - num_slots_); -} - -BitsetView ChannelMemory::Subscribers() const { - return BitsetView(&ccb_->subscribers, shm::kMaxSlotOwners); -} - -shm::AvailableSlotQueueIndex *ChannelMemory::QueueIndex() const { - return reinterpret_cast( - reinterpret_cast(ccb_) + shm::SlotQueueIndexOffset(num_slots_)); -} - -shm::SlotQueue *ChannelMemory::Queue(int sub_id) const { - const uint64_t offset = - QueueIndex()->offsets[sub_id].load(std::memory_order_acquire); - if (offset == shm::kInvalidSlotQueueOffset || offset > queue_arena_size_ || - queue_arena_size_ - offset < sizeof(shm::SlotQueue)) { - return nullptr; - } - auto *queue = reinterpret_cast( - reinterpret_cast(ccb_) + shm::SlotQueueArenaOffset(num_slots_) + - offset); - const size_t room = queue_arena_size_ - offset - sizeof(shm::SlotQueue); - if (queue->capacity > room / sizeof(shm::SlotQueueEntry)) { - return nullptr; - } - return queue; -} - -int ChannelMemory::NumSubscribers(int vchan_id) const { - const shm::SubscriberCounter &counter = ccb_->num_subs; - for (;;) { - const uint64_t before = counter.sequence.load(std::memory_order_acquire); - if ((before & 1) != 0) { - // A server died while updating the count. - return shm::kMaxSlotOwners; - } - const int mux_count = counter.counts[0].load(std::memory_order_relaxed); - const int count = vchan_id == -1 - ? mux_count - : mux_count + counter.counts[vchan_id + 1].load( - std::memory_order_relaxed); - if (counter.sequence.load(std::memory_order_acquire) == before) { - return count; - } - } -} - -uint64_t ChannelMemory::CleanupGeneration(int vchan_id) const { - const uint64_t mux_generation = - ccb_->subscriber_cleanup_generation[0].load(std::memory_order_acquire); - if (vchan_id == -1) { - return mux_generation; - } - return mux_generation + - ccb_->subscriber_cleanup_generation[vchan_id + 1].load( - std::memory_order_acquire); -} - -bool ChannelMemory::AtomicIncRefCount(shm::MessageSlot *slot, bool reliable, - int inc, uint64_t ordinal, int vchan_id, - bool retire, bool *retired) { - if (retired != nullptr) { - *retired = false; - } - ordinal &= shm::kOrdinalMask; - for (;;) { - uint64_t ref = slot->refs.load(std::memory_order_relaxed); - if ((ref & shm::kPubOwned) != 0) { - return false; - } - const uint64_t ref_ordinal = - (ref >> shm::kOrdinalShift) & shm::kOrdinalMask; - const int ref_vchan_id = shm::RefsVchanId(ref); - if (ref_ordinal != 0 && ordinal != 0 && - (ref_ordinal != ordinal || ref_vchan_id != vchan_id)) { - return false; - } - uint64_t refs = ref & shm::kRefCountMask; - uint64_t reliable_refs = - (ref >> shm::kReliableRefCountShift) & shm::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); - } - uint64_t retired_refs = - (ref >> shm::kRetiredRefsShift) & shm::kRetiredRefsMask; - if (retire) { - retired_refs++; - } - const uint64_t new_ref = - shm::BuildRefsBitField(ref_ordinal, ref_vchan_id, retired_refs) | - (reliable_refs << shm::kReliableRefCountShift) | refs; - if (slot->refs.compare_exchange_weak(ref, new_ref, - std::memory_order_acq_rel, - std::memory_order_relaxed)) { - if (retire && refs == 0 && reliable_refs == 0 && - retired_refs >= static_cast(NumSubscribers(ref_vchan_id)) && - RetiredSlots().SetWasClear(slot->id) && retired != nullptr) { - *retired = true; - } - return true; - } - } -} - -bool ChannelMemory::TryRetireSlot(shm::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 & shm::kPubOwned) != 0) { - return false; - } - const uint64_t ref_count = refs & shm::kRefCountMask; - const uint64_t reliable_ref_count = - (refs >> shm::kReliableRefCountShift) & shm::kRefCountMask; - const uint64_t retired_refs = - (refs >> shm::kRetiredRefsShift) & shm::kRetiredRefsMask; - if (ref_count != 0 || reliable_ref_count != 0 || - retired_refs < - static_cast(NumSubscribers(shm::RefsVchanId(refs)))) { - return false; - } - return RetiredSlots().SetWasClear(slot->id); -} - void ChannelMemory::TriggerRetirement(const TriggerFdList &triggers, int32_t slot_id) const { - if (triggers.Size() == 0) { - return; - } - if (slot_id >= 0 && slot_id < num_slots_ && - (Slot(slot_id)->flags.load(std::memory_order_relaxed) & - shm::kMessageIsActivation) != 0) { + if (triggers.Size() == 0 || !ReportsRetirement(slot_id)) { return; } for (int i = 0; i < triggers.Size(); i++) { diff --git a/asil_client/channel_memory.h b/asil_client/channel_memory.h index 3593016a..6d12ecca 100644 --- a/asil_client/channel_memory.h +++ b/asil_client/channel_memory.h @@ -7,11 +7,12 @@ #pragma once -#include "asil_client/bitset.h" #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 @@ -48,12 +49,9 @@ struct BufferContext { ServerConnection *connection = nullptr; }; -// InPlaceSlotQueue::Push with report_insertion_failure false. -bool PushSlotQueue(shm::SlotQueue *queue, int32_t slot_id, uint64_t ordinal); -// InPlaceSlotQueue::MarkInsertionFailure. -void MarkSlotQueueInsertionFailure(shm::SlotQueue *queue); - -class ChannelMemory { +// The slot, bitset and queue operations come from ChannelView, shared with the +// standard client. +class ChannelMemory : public ChannelView { public: ChannelMemory() = default; ~ChannelMemory() { Unmap(); } @@ -90,43 +88,21 @@ class ChannelMemory { slot->buffer_index.load(std::memory_order_relaxed) == index_; } - int NumSlots() const { return num_slots_; } // 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::ChannelControlBlock *Ccb() const { return ccb_; } shm::BufferControlBlock *Bcb() const { return bcb_; } const shm::ChannelCounters &Counters(int channel_id) const { return scb_->counters[channel_id]; } - shm::MessageSlot *Slot(int id) const; // 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; - BitsetView RetiredSlots() const; - BitsetView FreeSlots() const; - BitsetView AvailableSlots(int sub_id) const; - BitsetView Subscribers() const; - shm::AvailableSlotQueueIndex *QueueIndex() const; - // The subscriber's queue, or null if it has none. - shm::SlotQueue *Queue(int sub_id) const; - - int NumSubscribers(int vchan_id) const; - uint64_t CleanupGeneration(int vchan_id) const; - - // Channel::AtomicIncRefCount. Sets *retired when this call retired the - // slot. - bool AtomicIncRefCount(shm::MessageSlot *slot, bool reliable, int inc, - uint64_t ordinal, int vchan_id, bool retire, - bool *retired); - // Channel::TryRetireSlot. - bool TryRetireSlot(shm::MessageSlot *slot); - // Tells publishers that asked for retirement notification that slot_id is // free. void TriggerRetirement(const TriggerFdList &triggers, int32_t slot_id) const; @@ -144,12 +120,9 @@ class ChannelMemory { void UnmapBuffers(); shm::SystemControlBlock *scb_ = nullptr; - shm::ChannelControlBlock *ccb_ = nullptr; shm::BufferControlBlock *bcb_ = nullptr; const BufferContext *context_ = nullptr; size_t ccb_size_ = 0; - size_t queue_arena_size_ = 0; - int num_slots_ = 0; int32_t checksum_size_ = 4; int32_t metadata_size_ = 0; int32_t prefix_size_ = 64; diff --git a/asil_client/checksum.cc b/asil_client/checksum.cc deleted file mode 100644 index b0ecbaba..00000000 --- a/asil_client/checksum.cc +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright 2026 David Allison -// All Rights Reserved -// See LICENSE file for licensing information. - -#include "asil_client/checksum.h" - -#include - -namespace subspace { -namespace asil { - -namespace { - -#if defined(__x86_64__) && defined(__SSE4_2__) -constexpr uint32_t kPolynomial = 0x82F63B78; // CRC32C. -#else -constexpr uint32_t kPolynomial = 0xEDB88320; // IEEE 802.3. -#endif - -constexpr std::array MakeTable() { - std::array table = {}; - for (uint32_t i = 0; i < 256; i++) { - uint32_t crc = i; - for (int bit = 0; bit < 8; bit++) { - crc = (crc & 1) != 0 ? (crc >> 1) ^ kPolynomial : crc >> 1; - } - table[i] = crc; - } - return table; -} - -constexpr std::array kTable = MakeTable(); - -} // namespace - -uint32_t Crc32(uint32_t crc, const uint8_t *data, size_t length) { - for (size_t i = 0; i < length; i++) { - crc = (crc >> 8) ^ kTable[(crc ^ data[i]) & 0xFF]; - } - return crc; -} - -} // namespace asil -} // namespace subspace diff --git a/asil_client/checksum.h b/asil_client/checksum.h deleted file mode 100644 index 689687a0..00000000 --- a/asil_client/checksum.h +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright 2026 David Allison -// All Rights Reserved -// See LICENSE file for licensing information. - -#pragma once - -#include -#include - -namespace subspace { -namespace asil { - -// The CRC32 that the standard client puts in message prefixes. x86-64 builds -// with SSE4.2 use the CRC32C polynomial; all other builds use the IEEE 802.3 -// polynomial. Pass 0xFFFFFFFF as the first crc and invert the final result. -uint32_t Crc32(uint32_t crc, const uint8_t *data, size_t length); - -} // namespace asil -} // namespace subspace diff --git a/asil_client/client.h b/asil_client/client.h index 054c0b85..9215bfab 100644 --- a/asil_client/client.h +++ b/asil_client/client.h @@ -58,7 +58,10 @@ class Client { return subscriber.Open(*this, channel_name, options); } - // Why the server rejected the last request that returned kServerRejected. + // 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: diff --git a/asil_client/layout_test.cc b/asil_client/layout_test.cc index 7320a6ef..2ca2f0a0 100644 --- a/asil_client/layout_test.cc +++ b/asil_client/layout_test.cc @@ -2,131 +2,37 @@ // All Rights Reserved // See LICENSE file for licensing information. -// Checks that the ASIL client's view of shared memory matches -// common/channel.h, and that its checksum matches the standard client's. +// 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/channel_memory.h" -#include "asil_client/checksum.h" #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 #include namespace { namespace shm = ::subspace::asil::shm; - -#define EXPECT_SAME_OFFSET(type, field) \ - EXPECT_EQ(offsetof(::subspace::type, field), offsetof(shm::type, field)) \ - << #type "::" #field - -TEST(LayoutTest, Constants) { - EXPECT_EQ(::subspace::kMaxChannels, shm::kMaxChannels); - EXPECT_EQ(::subspace::kMaxSlotOwners, shm::kMaxSlotOwners); - EXPECT_EQ(::subspace::kMaxVchanId, shm::kMaxVchanId); - EXPECT_EQ(static_cast(::subspace::kMaxBuffers), shm::kMaxBuffers); - EXPECT_EQ(::subspace::kChannelControlBlockVersion, - shm::kChannelControlBlockVersion); - EXPECT_EQ(::subspace::kInvalidSlotQueueOffset, shm::kInvalidSlotQueueOffset); - EXPECT_EQ(::subspace::kMessageActivate, shm::kMessageActivate); - EXPECT_EQ(::subspace::kMessageHasChecksum, shm::kMessageHasChecksum); - EXPECT_EQ(static_cast(::subspace::kMessageSeen), shm::kMessageSeen); - EXPECT_EQ(static_cast(::subspace::kMessageIsActivation), - shm::kMessageIsActivation); - EXPECT_EQ(static_cast(::subspace::kMessageSeenByReliable), - shm::kMessageSeenByReliable); - EXPECT_EQ(::subspace::kMaxSlotQueueCasAttempts, - shm::kMaxSlotQueueCasAttempts); - EXPECT_EQ(::subspace::kPubOwned, shm::kPubOwned); - EXPECT_EQ(::subspace::kRefsMask, shm::kRefsMask); - EXPECT_EQ(::subspace::kRefCountMask, shm::kRefCountMask); - EXPECT_EQ(::subspace::kReliableRefCountShift, shm::kReliableRefCountShift); - EXPECT_EQ(::subspace::kRetiredRefsShift, shm::kRetiredRefsShift); - EXPECT_EQ(::subspace::kRetiredRefsMask, shm::kRetiredRefsMask); - EXPECT_EQ(::subspace::kVchanIdShift, shm::kVchanIdShift); - EXPECT_EQ(::subspace::kVchanIdMask, shm::kVchanIdMask); - EXPECT_EQ(::subspace::kOrdinalShift, shm::kOrdinalShift); - EXPECT_EQ(::subspace::kOrdinalMask, shm::kOrdinalMask); -} - -TEST(LayoutTest, MessagePrefix) { - EXPECT_EQ(sizeof(::subspace::MessagePrefix), sizeof(shm::MessagePrefix)); - EXPECT_SAME_OFFSET(MessagePrefix, slot_id); - EXPECT_SAME_OFFSET(MessagePrefix, message_size); - EXPECT_SAME_OFFSET(MessagePrefix, ordinal); - EXPECT_SAME_OFFSET(MessagePrefix, timestamp); - EXPECT_SAME_OFFSET(MessagePrefix, flags); - EXPECT_SAME_OFFSET(MessagePrefix, vchan_id); - EXPECT_SAME_OFFSET(MessagePrefix, checksum_size); - EXPECT_SAME_OFFSET(MessagePrefix, metadata_size); - EXPECT_SAME_OFFSET(MessagePrefix, checksum); -} - -TEST(LayoutTest, MessageSlot) { - EXPECT_EQ(sizeof(::subspace::MessageSlot), sizeof(shm::MessageSlot)); - EXPECT_SAME_OFFSET(MessageSlot, refs); - EXPECT_SAME_OFFSET(MessageSlot, ordinal); - EXPECT_SAME_OFFSET(MessageSlot, message_size); - EXPECT_SAME_OFFSET(MessageSlot, id); - EXPECT_SAME_OFFSET(MessageSlot, buffer_index); - EXPECT_SAME_OFFSET(MessageSlot, vchan_id); - EXPECT_SAME_OFFSET(MessageSlot, sub_owners); - EXPECT_SAME_OFFSET(MessageSlot, timestamp); - EXPECT_SAME_OFFSET(MessageSlot, flags); - EXPECT_SAME_OFFSET(MessageSlot, bridged_slot_id); -} - -TEST(LayoutTest, ControlBlocks) { - EXPECT_EQ(sizeof(::subspace::ChannelCounters), sizeof(shm::ChannelCounters)); - EXPECT_SAME_OFFSET(ChannelCounters, num_pub_updates); - EXPECT_SAME_OFFSET(ChannelCounters, num_sub_updates); - EXPECT_EQ(sizeof(::subspace::SystemControlBlock), - sizeof(shm::SystemControlBlock)); - EXPECT_EQ(sizeof(::subspace::BufferControlBlock), - sizeof(shm::BufferControlBlock)); - EXPECT_SAME_OFFSET(BufferControlBlock, sizes); - EXPECT_EQ(sizeof(::subspace::AvailableSlotQueueIndex), - sizeof(shm::AvailableSlotQueueIndex)); - EXPECT_SAME_OFFSET(AvailableSlotQueueIndex, offsets); - EXPECT_SAME_OFFSET(AvailableSlotQueueIndex, active_publishers); -} - -TEST(LayoutTest, ChannelControlBlock) { - EXPECT_EQ(sizeof(::subspace::ChannelControlBlock), - sizeof(shm::ChannelControlBlock)); - EXPECT_EQ(offsetof(::subspace::ChannelControlBlock, slots), - sizeof(shm::ChannelControlBlock)); - EXPECT_SAME_OFFSET(ChannelControlBlock, num_slots); - EXPECT_SAME_OFFSET(ChannelControlBlock, subscriber_queue_size); - EXPECT_SAME_OFFSET(ChannelControlBlock, version); - EXPECT_SAME_OFFSET(ChannelControlBlock, ordinals); - EXPECT_SAME_OFFSET(ChannelControlBlock, activation_tracker); - EXPECT_SAME_OFFSET(ChannelControlBlock, buffer_index); - EXPECT_SAME_OFFSET(ChannelControlBlock, num_buffers); - EXPECT_SAME_OFFSET(ChannelControlBlock, subscribers); - EXPECT_SAME_OFFSET(ChannelControlBlock, sub_vchan_ids); - EXPECT_SAME_OFFSET(ChannelControlBlock, num_subs); - EXPECT_SAME_OFFSET(ChannelControlBlock, subscriber_cleanup_generation); - EXPECT_SAME_OFFSET(ChannelControlBlock, total_bytes); - EXPECT_SAME_OFFSET(ChannelControlBlock, total_messages); - EXPECT_SAME_OFFSET(ChannelControlBlock, max_message_size); - EXPECT_SAME_OFFSET(ChannelControlBlock, total_drops); - EXPECT_SAME_OFFSET(ChannelControlBlock, free_slots_exhausted); - EXPECT_EQ(sizeof(::subspace::SubscriberCounter), - sizeof(shm::SubscriberCounter)); - EXPECT_EQ(sizeof(::subspace::OrdinalAccumulator), - sizeof(shm::ChannelControlBlock::ordinals)); - EXPECT_EQ(sizeof(::subspace::ActivationTracker), - sizeof(shm::ChannelControlBlock::activation_tracker)); - EXPECT_EQ(sizeof(::subspace::SubscriberCleanupGeneration), - sizeof(shm::ChannelControlBlock::subscriber_cleanup_generation)); -} +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}) { @@ -149,120 +55,614 @@ TEST(LayoutTest, CcbRegions) { EXPECT_EQ(shm::SlotQueueArenaOffset(num_slots), shm::SlotQueueIndexOffset(num_slots) + ::subspace::AvailableSlotQueueIndexSize()); - EXPECT_EQ(shm::CcbSize(num_slots, 0), ::subspace::CcbSize(num_slots, 0)); EXPECT_EQ(shm::CcbSize(num_slots, 64000), - ::subspace::CcbSize(num_slots, 64000)); + shm::SlotQueueArenaOffset(num_slots) + 64000); } } -TEST(LayoutTest, PrefixSize) { - for (int32_t checksum_size : {0, 4, 16, 17}) { - for (int32_t metadata_size : {0, 1, 16, 100}) { - EXPECT_EQ( - shm::PrefixSize(checksum_size, metadata_size), - ::subspace::Channel::ComputePrefixSize(checksum_size, metadata_size)); +// 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); + } + } + + 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); + } + +private: + struct alignas(64) Block { + char bytes[64]; + }; + std::vector memory_; + ChannelView view_; +}; + +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()); + + EXPECT_EQ(::subspace::BuildRefsBitField(1, 3, 0), + 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, 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; } -TEST(LayoutTest, RefsBitField) { - for (uint64_t ordinal : {0ULL, 1ULL, 12345ULL, (1ULL << 23) + 7}) { - for (int vchan_id : {-1, 0, 5, 1022}) { - for (int retired : {0, 1, 1023}) { - EXPECT_EQ(shm::BuildRefsBitField(ordinal, vchan_id, retired), - ::subspace::BuildRefsBitField(ordinal, vchan_id, retired)); +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); } } } -TEST(LayoutTest, SlotQueue) { - EXPECT_EQ(sizeof(::subspace::InPlaceSlotQueue), sizeof(shm::SlotQueue)); - EXPECT_EQ(sizeof(::subspace::SlotQueueEntry), sizeof(shm::SlotQueueEntry)); - EXPECT_SAME_OFFSET(SlotQueueEntry, sequence); - EXPECT_SAME_OFFSET(SlotQueueEntry, ordinal); - EXPECT_SAME_OFFSET(SlotQueueEntry, 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); } -// A queue in a buffer, initialized by the standard client and used through -// both views. -struct QueueMemory { - explicit QueueMemory(size_t capacity, bool drop_oldest) - : memory(::subspace::SizeofSlotQueue(capacity) / sizeof(uint64_t) + 1), - standard(new (memory.data())::subspace::InPlaceSlotQueue(capacity, - drop_oldest)), - asil(reinterpret_cast(memory.data())) {} +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(); - std::vector memory; - ::subspace::InPlaceSlotQueue *standard; - shm::SlotQueue *asil; -}; + 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()); +} -TEST(SlotQueueTest, AsilPushesStandardPops) { - QueueMemory queue(4, /*drop_oldest=*/true); - EXPECT_EQ(4u, queue.asil->capacity); - for (int32_t i = 0; i < 6; i++) { - EXPECT_TRUE( - ::subspace::asil::internal::PushSlotQueue(queue.asil, i, 100 + i)); +// 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); } - // The two oldest entries made room for the newest. - EXPECT_EQ(2u, queue.standard->OverflowCount()); - for (int32_t i = 2; i < 6; i++) { - ::subspace::QueuedSlot slot; - ASSERT_TRUE(queue.standard->TryPop(slot)); - EXPECT_EQ(i, slot.slot_id); - EXPECT_EQ(static_cast(100 + i), slot.ordinal); + 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())); } - ::subspace::QueuedSlot slot; - EXPECT_FALSE(queue.standard->TryPop(slot)); - // Entries wrap around the ring. - EXPECT_TRUE(::subspace::asil::internal::PushSlotQueue(queue.asil, 9, 109)); - ASSERT_TRUE(queue.standard->TryPop(slot)); - EXPECT_EQ(9, slot.slot_id); + 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(SlotQueueTest, InheritedQueueRejectsWhenFull) { - QueueMemory queue(2, /*drop_oldest=*/false); - EXPECT_TRUE(::subspace::asil::internal::PushSlotQueue(queue.asil, 0, 1)); - EXPECT_TRUE(::subspace::asil::internal::PushSlotQueue(queue.asil, 1, 2)); - EXPECT_FALSE(::subspace::asil::internal::PushSlotQueue(queue.asil, 2, 3)); - EXPECT_FALSE(queue.standard->InsertionFailed()); - ::subspace::asil::internal::MarkSlotQueueInsertionFailure(queue.asil); - EXPECT_TRUE(queue.standard->InsertionFailed()); - EXPECT_EQ(0u, queue.standard->OverflowCount()); - - // A standard push is visible to the ASIL view. - QueueMemory other(2, /*drop_oldest=*/true); - ASSERT_TRUE(other.standard->Push(7, 70)); - EXPECT_EQ(1u, other.asil->tail.load()); - EXPECT_EQ(7, other.asil->Entries()[0].slot_id.load()); - EXPECT_EQ(70u, other.asil->Entries()[0].ordinal.load()); +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, 0), 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 (size_t length : {0, 1, 3, 4, 7, 8, 9, 63, 64, 1000}) { - SCOPED_TRACE(length); - std::vector data(length); - for (uint8_t &byte : data) { - byte = static_cast(random()); - } - std::array, 3> spans = { - absl::Span(data.data(), length / 3), - absl::Span(data.data() + length / 3, length / 3), - absl::Span(data.data() + 2 * (length / 3), - length - 2 * (length / 3))}; - uint32_t expected = 0; - ::subspace::CalculateCRC32Checksum( - spans, absl::Span(reinterpret_cast(&expected), - sizeof(expected))); - uint32_t crc = 0xFFFFFFFF; - for (const auto &span : spans) { - crc = ::subspace::asil::Crc32(crc, span.data(), span.size()); + 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)); + } } - EXPECT_EQ(expected, ~crc); } } +// 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 index 55469550..914b22e1 100644 --- a/asil_client/phaser_connection.cc +++ b/asil_client/phaser_connection.cc @@ -21,6 +21,18 @@ 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) @@ -104,6 +116,7 @@ Error FillFdList(const PhaserServerConnection::ReceivedFds &fds, size_t count, } // namespace Error PhaserServerConnection::Connect(const char *socket_name) { + (void)kPermanentErrorsReady; if (socket_name == nullptr) { return Error::kInvalidArgument; } @@ -142,12 +155,20 @@ Error PhaserServerConnection::Connect(const char *socket_name) { return Error::kOk; } -Error PhaserServerConnection::Rejected(const char *message, size_t length) { - if (length > sizeof(last_error_) - 1) { +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; } - std::memcpy(last_error_, message, length); + 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; } @@ -218,6 +239,8 @@ Error PhaserServerConnection::Receive(const char *&data, size_t &length) { } remaining -= chunk; } + SetLastError("response does not fit the wire buffer", + sizeof("response does not fit the wire buffer") - 1); return Error::kCapacityExceeded; } @@ -308,11 +331,15 @@ Error PhaserServerConnection::Transact(Build build, Read read, int send_fd) { // 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; @@ -346,11 +373,14 @@ Error PhaserServerConnection::Transact(Build build, Read read, int send_fd) { 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; @@ -367,7 +397,7 @@ Error PhaserServerConnection::Init(const char *client_name, InitReply &reply) { init->set_client_name(View(client_name)); init->set_max_channels(shm::kMaxChannels); init->set_max_slot_owners(shm::kMaxSlotOwners); - init->set_max_buffers(shm::kMaxBuffers); + init->set_max_buffers(static_cast(shm::kMaxBuffers)); }, [&](const wire::Response &response) { if (!response.has_init()) { diff --git a/asil_client/phaser_connection.h b/asil_client/phaser_connection.h index e017f8f6..78f05833 100644 --- a/asil_client/phaser_connection.h +++ b/asil_client/phaser_connection.h @@ -13,18 +13,19 @@ namespace subspace { namespace asil { -// The standard Subspace protocol: protobuf 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 with fixed buffers -// inside this object, the same encoding as the standard client uses, so the -// handshake makes no heap allocations. A request or response that does not -// fit fails with kCapacityExceeded. +// 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 with fixed +// buffers inside this object, the same encoding as the standard client uses, +// so a handshake makes no heap allocations, even when it fails. A request or +// response that does not fit fails with kCapacityExceeded, and +// LastServerError() says which buffer it did not fit. // // The object holds about 60 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: - // Protobuf wire bytes for one request or response. + // Native Phaser payload bytes for one request or response. static constexpr size_t kWireBufferSize = 16 * 1024; // The decoded request or response. static constexpr size_t kMessageBufferSize = 32 * 1024; @@ -67,6 +68,12 @@ class PhaserServerConnection : public ServerConnection { 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_; diff --git a/asil_client/publisher.cc b/asil_client/publisher.cc index 5395b69b..9fd02151 100644 --- a/asil_client/publisher.cc +++ b/asil_client/publisher.cc @@ -2,17 +2,16 @@ // All Rights Reserved // See LICENSE file for licensing information. -// The publishing side of the shared memory protocol. This follows -// PublisherImpl::FindFreeSlotUnreliable, PublisherImpl::FindFreeSlotReliable -// and PublisherImpl::ActivateSlotAndGetAnother in client/publisher.cc. +// 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/checksum.h" #include "asil_client/client.h" - -#include -#include +#include "common/message_checksum.h" +#include "common/publish.h" +#include "common/slot_search.h" namespace subspace { namespace asil { @@ -21,16 +20,6 @@ namespace { bool ValidLayoutSize(int32_t size) { return size >= 0 && size <= 0xFFFF; } -// Slots are ordered by timestamp, then by id, as a stable sort by timestamp -// orders them. -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; -} - } // namespace Error Publisher::Open(Client &client, const char *channel_name, @@ -146,9 +135,9 @@ Error Publisher::Open(Client &client, const char *channel_name, (void)Close(); return e; } - BitsetView activations(&memory_.Ccb()->activation_tracker, - shm::kMaxVchanId + 1); - if (reliable_ || (options.activate && !activations.IsSet(vchan_id_ + 1))) { + 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); @@ -267,256 +256,41 @@ void Publisher::TriggerSubscribers() const { } } -shm::MessageSlot *Publisher::FindFreeSlot() { - return reliable_ ? FindFreeSlotReliable() : FindFreeSlotUnreliable(); -} +// 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) {} -int Publisher::FindRetiredSlotToReuse(bool oldest_first) const { - BitsetView retired = memory_.RetiredSlots(); - if (!oldest_first) { - return retired.FindFirstSet(); - } - // With no subscribers every slot retires as soon as it is published, so - // reuse the oldest to keep a window of recent messages for late joiners. - int oldest = -1; - uint64_t oldest_timestamp = ~uint64_t{0}; - for (int i = 0; i < memory_.NumSlots(); i++) { - if (!retired.IsSet(i)) { - continue; - } - const uint64_t timestamp = - memory_.Slot(i)->timestamp.load(std::memory_order_relaxed); - if (timestamp < oldest_timestamp) { - oldest_timestamp = timestamp; - oldest = i; - } + void AssignBuffer(shm::MessageSlot *slot) { publisher_.SetSlotBuffer(slot); } + shm::MessagePrefix *Prefix(shm::MessageSlot *slot) { + return publisher_.memory_.Prefix(slot); } - return oldest; -} - -// Takes ownership of slot if no other publisher or subscriber has it. -bool Publisher::ClaimSlot(shm::MessageSlot *slot) { - const uint64_t owner = shm::kPubOwned | static_cast(publisher_id_); - const uint64_t old_refs = slot->refs.load(std::memory_order_relaxed); - uint64_t expected = shm::BuildRefsBitField( - slot->ordinal.load(std::memory_order_relaxed), - static_cast((old_refs >> shm::kVchanIdShift) & shm::kVchanIdMask), - (old_refs >> shm::kRetiredRefsShift) & shm::kRetiredRefsMask); - return slot->refs.compare_exchange_weak( - expected, owner, std::memory_order_acquire, std::memory_order_relaxed); -} - -shm::MessageSlot *Publisher::FindFreeSlotUnreliable() { - shm::ChannelControlBlock *ccb = memory_.Ccb(); - BitsetView free_slots = memory_.FreeSlots(); - BitsetView retired_slots = memory_.RetiredSlots(); - constexpr int kMaxCasRetries = 1000; - int retries = memory_.NumSlots() * 1000; - int cas_retries = 0; - shm::MessageSlot *slot = nullptr; - int free_slot = -1; - int retired_slot = -1; - for (;;) { - slot = nullptr; - free_slot = -1; - retired_slot = -1; - const bool no_subscribers = memory_.NumSubscribers(vchan_id_) == 0; - if (!ccb->free_slots_exhausted.load(std::memory_order_relaxed) && - (free_slot = free_slots.FindFirstSet()) != -1) { - if (!free_slots.ClearWasSet(free_slot)) { - continue; - } - slot = memory_.Slot(free_slot); - if (free_slots.IsEmpty()) { - ccb->free_slots_exhausted.store(true, std::memory_order_relaxed); - } - } else if ((retired_slot = FindRetiredSlotToReuse(no_subscribers)) != -1) { - if (!retired_slots.ClearWasSet(retired_slot)) { - continue; - } - slot = memory_.Slot(retired_slot); - } else { - // Recycle the oldest message that no subscriber holds. - uint64_t earliest = ~uint64_t{0}; - for (int i = 0; i < memory_.NumSlots(); i++) { - shm::MessageSlot *s = memory_.Slot(i); - const uint64_t refs = s->refs.load(std::memory_order_relaxed); - if ((refs & shm::kPubOwned) != 0) { - continue; - } - const uint64_t timestamp = s->timestamp.load(std::memory_order_relaxed); - if ((refs & shm::kRefsMask) == 0 && timestamp < earliest) { - slot = s; - earliest = timestamp; - } - } - } - if (slot == nullptr) { - if (retries-- == 0) { - return nullptr; - } - continue; - } - if (ClaimSlot(slot)) { - break; - } - if (++cas_retries >= kMaxCasRetries) { - if (retries-- == 0) { - return nullptr; - } - cas_retries = 0; - (void)::sched_yield(); - } + void ForcedReuse(shm::MessageSlot *slot) { + publisher_.memory_.TriggerRetirement(publisher_.retirement_triggers_, + slot->id); } - PrepareClaimedSlot(slot, free_slot == -1 && retired_slot == -1); - return slot; -} -// A reliable subscriber still needs a slot that it holds, and, when reliable -// subscribers exist, a message that none of them has seen. -bool Publisher::ReliableClaimable(shm::MessageSlot *slot, - bool require_reliable_seen) const { - const uint64_t refs = slot->refs.load(std::memory_order_relaxed); - if (((refs >> shm::kReliableRefCountShift) & shm::kRefCountMask) != 0) { - return false; - } - if (require_reliable_seen && - slot->ordinal.load(std::memory_order_relaxed) != 0 && - (slot->flags.load(std::memory_order_relaxed) & - shm::kMessageSeenByReliable) == 0) { - return false; - } - return (refs & shm::kRefsMask) == 0; -} +private: + Publisher &publisher_; +}; -// The oldest slot that no subscriber holds and that is older than every slot -// a reliable subscriber still needs. -shm::MessageSlot * -Publisher::OldestReliableCandidate(bool require_reliable_seen) const { - int stop = -1; - uint64_t stop_timestamp = 0; - for (int i = 0; i < memory_.NumSlots(); i++) { - shm::MessageSlot *s = memory_.Slot(i); - const uint64_t refs = s->refs.load(std::memory_order_relaxed); - if ((refs & shm::kPubOwned) != 0) { - continue; - } - const bool needed = - ((refs >> shm::kReliableRefCountShift) & shm::kRefCountMask) != 0 || - (require_reliable_seen && - s->ordinal.load(std::memory_order_relaxed) != 0 && - (s->flags.load(std::memory_order_relaxed) & - shm::kMessageSeenByReliable) == 0); - const uint64_t timestamp = s->timestamp.load(std::memory_order_relaxed); - if (needed && (stop == -1 || Earlier(timestamp, i, stop_timestamp, stop))) { - stop = i; - stop_timestamp = timestamp; - } - } - shm::MessageSlot *best = nullptr; - uint64_t best_timestamp = 0; - for (int i = 0; i < memory_.NumSlots(); i++) { - shm::MessageSlot *s = memory_.Slot(i); - const uint64_t refs = s->refs.load(std::memory_order_relaxed); - if ((refs & (shm::kPubOwned | shm::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; -} - -shm::MessageSlot *Publisher::FindFreeSlotReliable() { - shm::ChannelControlBlock *ccb = memory_.Ccb(); - BitsetView free_slots = memory_.FreeSlots(); - BitsetView retired_slots = memory_.RetiredSlots(); - constexpr int kMaxCasRetries = 1000; - int retries = memory_.NumSlots() * 1000; - int cas_retries = 0; - shm::MessageSlot *slot = nullptr; - int free_slot = -1; - int retired_slot = -1; - for (;;) { - slot = nullptr; - free_slot = -1; - retired_slot = -1; - const bool require_reliable_seen = - memory_.Counters(channel_id_).num_reliable_subs != 0; - if (!ccb->free_slots_exhausted.load(std::memory_order_relaxed) && - (free_slot = free_slots.FindFirstSet()) != -1) { - if (!free_slots.ClearWasSet(free_slot)) { - continue; - } - if (free_slots.IsEmpty()) { - ccb->free_slots_exhausted.store(true, std::memory_order_relaxed); - } - // A free slot has never held a message. - slot = memory_.Slot(free_slot); - } else if ((retired_slot = retired_slots.FindFirstSet()) != -1) { - if (!retired_slots.ClearWasSet(retired_slot)) { - continue; - } - slot = memory_.Slot(retired_slot); - if (!ReliableClaimable(slot, require_reliable_seen)) { - // The slot is still retired; it just can't be reused yet. - retired_slots.Set(retired_slot); - return nullptr; - } - } else { - slot = OldestReliableCandidate(require_reliable_seen); - if (slot == nullptr) { - return nullptr; - } - } - if (ClaimSlot(slot)) { - retired_slots.Clear(slot->id); - break; - } - if (++cas_retries >= kMaxCasRetries) { - if (retries-- == 0) { - return nullptr; - } - cas_retries = 0; - (void)::sched_yield(); - } - } - PrepareClaimedSlot(slot, free_slot == -1 && retired_slot == -1); - return slot; -} - -// Resets a slot this publisher has just claimed. forced_reuse is true when -// the slot held a message that a subscriber might not have seen. -void Publisher::PrepareClaimedSlot(shm::MessageSlot *slot, bool forced_reuse) { - 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); - SetSlotBuffer(slot); - shm::MessagePrefix *prefix = memory_.Prefix(slot); - prefix->flags = 0; - prefix->vchan_id = vchan_id_; - - // The old message is gone, so no subscriber should look for it. - memory_.Subscribers().Traverse([this, slot](int sub_id) { - memory_.AvailableSlots(sub_id).Clear(slot->id); - }); - - if (forced_reuse) { - memory_.TriggerRetirement(retirement_triggers_, slot->id); +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 < shm::kMaxBuffers && + if (old_index >= 0 && old_index < static_cast(shm::kMaxBuffers) && bcb->refs[old_index].load(std::memory_order_relaxed) > 0) { bcb->refs[old_index]--; } @@ -528,112 +302,30 @@ void Publisher::SetSlotBuffer(shm::MessageSlot *slot) { void Publisher::PublishSlot(shm::MessageSlot *slot, bool is_activation, PublishedMessage *published) { - shm::ChannelControlBlock *ccb = memory_.Ccb(); shm::MessagePrefix *prefix = memory_.Prefix(slot); - const uint64_t ordinal = ccb->ordinals[vchan_id_ + 1].fetch_add(1); - const uint64_t timestamp = internal::Now(); - const uint64_t message_size = - slot->message_size.load(std::memory_order_relaxed); - slot->ordinal.store(ordinal, std::memory_order_relaxed); - slot->timestamp.store(timestamp, std::memory_order_relaxed); - slot->flags.store(0, std::memory_order_relaxed); - - prefix->message_size = message_size; - prefix->ordinal = ordinal; - prefix->timestamp = timestamp; - prefix->vchan_id = vchan_id_; - prefix->checksum_size = static_cast(memory_.ChecksumSize()); - prefix->metadata_size = static_cast(memory_.MetadataSize()); - prefix->flags = 0; - prefix->slot_id = slot->id; - slot->bridged_slot_id.store(slot->id, std::memory_order_relaxed); - if (is_activation) { - prefix->flags |= shm::kMessageActivate; - slot->flags.fetch_or(shm::kMessageIsActivation, std::memory_order_relaxed); - BitsetView(&ccb->activation_tracker, shm::kMaxVchanId + 1) - .Set(vchan_id_ + 1); - } + StampSlot(memory_.Ccb(), slot, internal::Now()); + FillPrefix(memory_.Ccb(), slot, prefix, memory_.ChecksumSize(), + memory_.MetadataSize(), is_activation); if (checksum_) { - prefix->flags |= shm::kMessageHasChecksum; - const auto *base = reinterpret_cast(prefix); - uint32_t crc = 0xFFFFFFFF; - crc = Crc32(crc, base + offsetof(shm::MessagePrefix, slot_id), - offsetof(shm::MessagePrefix, checksum) - - offsetof(shm::MessagePrefix, slot_id)); - crc = Crc32(crc, - base + offsetof(shm::MessagePrefix, checksum) + - memory_.ChecksumSize(), - static_cast(memory_.MetadataSize())); - crc = Crc32(crc, reinterpret_cast(memory_.Payload(slot)), - message_size); - crc = ~crc; - std::memcpy(&prefix->checksum, &crc, sizeof(crc)); - } - - const uint64_t cleanup_generation = memory_.CleanupGeneration(vchan_id_); - - // The server uses this count to tell when no publisher can be writing to a - // subscriber queue. - std::atomic &active_publishers = - memory_.QueueIndex()->active_publishers[publisher_id_]; - active_publishers.fetch_add(1, std::memory_order_seq_cst); - - // Mark the message available to every subscriber on the publisher's - // virtual channel while the slot is still publisher owned. A subscriber - // can leave between the traversal and the set, so check membership again - // afterwards. The bitset is the authoritative record, so a queue that is - // full only loses a hint. - memory_.Subscribers().Traverse( - [this, slot, ordinal](int sub_id) { - const int sub_vchan_id = memory_.Ccb()->sub_vchan_ids[sub_id]; - if (vchan_id_ != -1 && sub_vchan_id != -1 && - sub_vchan_id != vchan_id_) { - return; - } - BitsetView available = memory_.AvailableSlots(sub_id); - BitsetView subscribers = memory_.Subscribers(); - available.Set(slot->id); - if (!subscribers.IsSetSeqCst(sub_id)) { - available.Clear(slot->id); - if (!subscribers.IsSetSeqCst(sub_id)) { - return; - } - available.Set(slot->id); - } - shm::SlotQueue *queue = memory_.Queue(sub_id); - if (queue != nullptr && - !internal::PushSlotQueue(queue, slot->id, ordinal)) { - internal::MarkSlotQueueInsertionFailure(queue); - } - }, - std::memory_order_seq_cst); - - if (!is_activation) { - ccb->total_bytes += message_size; - if (message_size > ccb->max_message_size) { - ccb->max_message_size = message_size; - } + prefix->SetHasChecksum(); + SetMessageChecksum(prefix, memory_.Payload(slot), + slot->message_size.load(std::memory_order_relaxed), + memory_.ChecksumSize(), memory_.MetadataSize()); } - // Releasing publisher ownership makes the message readable. - slot->refs.store(shm::BuildRefsBitField(ordinal, vchan_id_, 0), - std::memory_order_release); - ccb->total_messages.fetch_add(1, std::memory_order_seq_cst); - - // A subscriber removed while publishing lowers the retirement threshold. - if (!is_activation && - memory_.CleanupGeneration(vchan_id_) != cleanup_generation && - memory_.TryRetireSlot(slot)) { - memory_.TriggerRetirement(retirement_triggers_, slot->id); + PublishedSlot result; + { + SubscriberQueuePublishScope publishing(memory_.QueueIndex(), + publisher_id_); + result = CommitPublishedSlot(memory_, slot, vchan_id_, is_activation, + publishing); } - - uint32_t active = active_publishers.load(std::memory_order_seq_cst); - while (active != 0 && !active_publishers.compare_exchange_strong( - active, active - 1, std::memory_order_seq_cst)) { + if (result.retired) { + memory_.TriggerRetirement(retirement_triggers_, result.retirement_slot_id); } if (published != nullptr) { - published->ordinal = ordinal; - published->timestamp = timestamp; + published->ordinal = result.ordinal; + published->timestamp = result.timestamp; } } diff --git a/asil_client/publisher.h b/asil_client/publisher.h index 14e91122..f224dc31 100644 --- a/asil_client/publisher.h +++ b/asil_client/publisher.h @@ -113,15 +113,11 @@ class Publisher { 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(); - shm::MessageSlot *FindFreeSlotUnreliable(); - shm::MessageSlot *FindFreeSlotReliable(); - shm::MessageSlot *OldestReliableCandidate(bool require_reliable_seen) const; - bool ReliableClaimable(shm::MessageSlot *slot, - bool require_reliable_seen) const; - bool ClaimSlot(shm::MessageSlot *slot); - void PrepareClaimedSlot(shm::MessageSlot *slot, bool forced_reuse); - int FindRetiredSlotToReuse(bool oldest_first) const; void SetSlotBuffer(shm::MessageSlot *slot); void PublishSlot(shm::MessageSlot *slot, bool is_activation, PublishedMessage *published); diff --git a/asil_client/server_connection.h b/asil_client/server_connection.h index 80a84767..fd2b9054 100644 --- a/asil_client/server_connection.h +++ b/asil_client/server_connection.h @@ -165,7 +165,8 @@ class ServerConnection { // reply.found false when it hasn't been registered yet. virtual Error GetBuffer(const BufferRequest &request, BufferReply &reply) = 0; - // The server's message for the last request that returned kServerRejected. + // 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; }; diff --git a/asil_client/shm_layout.h b/asil_client/shm_layout.h index 95099d1e..30abfe00 100644 --- a/asil_client/shm_layout.h +++ b/asil_client/shm_layout.h @@ -2,46 +2,12 @@ // All Rights Reserved // See LICENSE file for licensing information. -// The Subspace shared memory layout as seen by the ASIL client. -// -// These structures mirror common/channel.h byte for byte so that the ASIL -// client can share channels with the standard clients. They are declared -// here, rather than included, so that the ASIL client depends only on the C++ -// standard library and POSIX. layout_test.cc checks every size and offset -// against common/channel.h. +// Names for the shared-memory protocol. The types live in common/shm_layout.h +// and are the same types the regular client uses. #pragma once -#include -#include -#include - -// The shared memory backend. This follows the selection in common/channel.h. -#define ASIL_SHM_POSIX 1 -#define ASIL_SHM_LINUX 2 -#define ASIL_SHM_MEMFD 3 - -#if defined(SUBSPACE_SHMEM_MODE) -#define ASIL_SHM_MODE SUBSPACE_SHMEM_MODE -#elif defined(__ANDROID__) -#define ASIL_SHM_MODE ASIL_SHM_MEMFD -#elif defined(__linux__) && defined(SUBSPACE_LINUX_USE_MEMFD) -#define ASIL_SHM_MODE ASIL_SHM_MEMFD -#elif defined(__linux__) -#define ASIL_SHM_MODE ASIL_SHM_LINUX -#else -#define ASIL_SHM_MODE ASIL_SHM_POSIX -#endif - -#ifndef SUBSPACE_MAX_CHANNELS -#define SUBSPACE_MAX_CHANNELS 1024 -#endif -#ifndef SUBSPACE_MAX_SLOT_OWNERS -#define SUBSPACE_MAX_SLOT_OWNERS 1024 -#endif -#ifndef SUBSPACE_MAX_BUFFERS -#define SUBSPACE_MAX_BUFFERS 341 -#endif +#include "common/shm_layout.h" namespace subspace { namespace asil { @@ -49,226 +15,61 @@ namespace shm { static_assert(sizeof(void *) == 8, "Subspace shared memory needs 64 bits"); -constexpr int kMaxChannels = SUBSPACE_MAX_CHANNELS; -constexpr int kMaxSlotOwners = SUBSPACE_MAX_SLOT_OWNERS; -constexpr int kMaxVchanId = 1023; -constexpr int kMaxBuffers = SUBSPACE_MAX_BUFFERS; -constexpr size_t kMaxChannelName = 64; -constexpr uint32_t kChannelControlBlockVersion = 5; -constexpr uint64_t kInvalidSlotQueueOffset = ~uint64_t{0}; - -// MessagePrefix flags. -constexpr int64_t kMessageActivate = 1; -constexpr int64_t kMessageHasChecksum = 4; - -// MessageSlot flags. -constexpr uint32_t kMessageSeen = 1; -constexpr uint32_t kMessageIsActivation = 2; -constexpr uint32_t kMessageSeenByReliable = 4; - -// Fields of MessageSlot::refs. -constexpr uint64_t kRefCountMask = 0x3ff; -constexpr uint64_t kReliableRefCountShift = 10; -constexpr uint64_t kPubOwned = uint64_t{1} << 63; -constexpr uint64_t kRefsMask = (uint64_t{1} << 20) - 1; -constexpr uint64_t kRetiredRefsMask = (uint64_t{1} << 10) - 1; -constexpr uint64_t kRetiredRefsShift = 20; -constexpr uint64_t kVchanIdMask = (uint64_t{1} << 10) - 1; -constexpr uint64_t kVchanIdShift = 30; -constexpr uint64_t kOrdinalMask = (uint64_t{1} << 23) - 1; -constexpr uint64_t kOrdinalShift = 40; - -inline uint64_t BuildRefsBitField(uint64_t ordinal, int vchan_id, - uint64_t retired_refs) { - const uint64_t vchan_bits = - ordinal == 0 - ? 0 - : ((static_cast(vchan_id) & kVchanIdMask) << kVchanIdShift); - return ((ordinal & kOrdinalMask) << kOrdinalShift) | vchan_bits | - ((retired_refs & kRetiredRefsMask) << kRetiredRefsShift); -} - -// The vchan_id stored in refs, where all ones means -1. -inline int RefsVchanId(uint64_t refs) { - const uint64_t v = (refs >> kVchanIdShift) & kVchanIdMask; - return v == kVchanIdMask ? -1 : static_cast(v); -} - -constexpr int64_t Aligned64(int64_t v) { return (v + 63) & ~int64_t{63}; } - -constexpr size_t BitsToWords(size_t bits) { - return bits == 0 ? 0 : ((bits - 1) / 64) + 1; -} - -// AtomicBitSet: the bit count followed by the words. -constexpr size_t SizeofBitset(size_t bits) { - return sizeof(size_t) + sizeof(uint64_t) * BitsToWords(bits); -} - -template struct FixedBitset { - size_t num_bits; - std::atomic words[BitsToWords(kBits)]; -}; - -struct MessagePrefix { - int32_t padding; - int32_t slot_id; - 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[12]; -}; -static_assert(sizeof(MessagePrefix) == 64); -static_assert(offsetof(MessagePrefix, slot_id) == 4); -static_assert(offsetof(MessagePrefix, checksum) == 48); - -struct ChannelCounters { - uint16_t num_pub_updates; - uint16_t num_sub_updates; - uint16_t num_pubs; - uint16_t num_reliable_pubs; - uint16_t num_subs; - uint16_t num_reliable_subs; - uint16_t num_resizes; -}; -static_assert(sizeof(ChannelCounters) == 14); - -struct SystemControlBlock { - ChannelCounters counters[kMaxChannels]; -}; - -struct MessageSlot { - std::atomic refs; - std::atomic ordinal; - std::atomic message_size; - int32_t id; - std::atomic buffer_index; - std::atomic vchan_id; - FixedBitset sub_owners; - std::atomic timestamp; - std::atomic flags; - std::atomic bridged_slot_id; -}; -static_assert(sizeof(MessageSlot) == 184); -static_assert(offsetof(MessageSlot, id) == 24); -static_assert(offsetof(MessageSlot, sub_owners) == 32); -static_assert(offsetof(MessageSlot, timestamp) == 168); -static_assert(offsetof(MessageSlot, bridged_slot_id) == 180); - -struct SubscriberCounter { - std::atomic sequence; - std::atomic counts[kMaxVchanId + 1]; -}; - -struct ChannelControlBlock { - char channel_name[kMaxChannelName]; - int32_t num_slots; - int32_t subscriber_queue_size; - uint32_t version; - std::atomic ordinals[kMaxVchanId + 1]; - FixedBitset activation_tracker; - int32_t buffer_index; - std::atomic num_buffers; - FixedBitset subscribers; - int16_t sub_vchan_ids[kMaxSlotOwners]; - SubscriberCounter num_subs; - std::atomic subscriber_cleanup_generation[kMaxVchanId + 1]; - std::atomic total_bytes; - std::atomic total_messages; - std::atomic max_message_size; - std::atomic total_drops; - std::atomic free_slots_exhausted; - // Followed by num_slots MessageSlots. -}; -static_assert(offsetof(ChannelControlBlock, version) == 72); - -struct AvailableSlotQueueIndex { - std::atomic next_offset; - std::atomic offsets[kMaxSlotOwners]; - std::atomic active_publishers[kMaxSlotOwners]; -}; -static_assert(kMaxSlotOwners != 1024 || - sizeof(AvailableSlotQueueIndex) == 12296); - -struct BufferControlBlock { - std::atomic refs[kMaxBuffers]; - std::atomic sizes[kMaxBuffers]; -}; - -// InPlaceSlotQueue: a bounded MPSC ring of published slots for one -// subscriber, in the CCB's queue arena. The entries follow the header. -constexpr size_t kMaxSlotQueueCasAttempts = 64; - -struct SlotQueueEntry { - std::atomic sequence; - std::atomic ordinal; - std::atomic slot_id; -}; -static_assert(sizeof(SlotQueueEntry) == 24); - -struct SlotQueue { - size_t capacity; - std::atomic head; - std::atomic tail; - std::atomic overflow_count; - std::atomic insertion_failed; - bool drop_oldest; - - SlotQueueEntry *Entries() { - return reinterpret_cast(this + 1); - } -}; -static_assert(sizeof(SlotQueue) == 32); -static_assert(offsetof(SlotQueue, overflow_count) == 24); -static_assert(offsetof(SlotQueue, insertion_failed) == 28); - -// Offsets of the regions that follow the slots in the CCB. A CCB holds the -// header and slots, the retired and free slot bitsets, one available-slot -// bitset per subscriber, the subscriber queue index and the queue arena. -inline size_t RetiredSlotsOffset(int num_slots) { - return static_cast(Aligned64(static_cast( - sizeof(ChannelControlBlock) + num_slots * sizeof(MessageSlot)))); -} - -inline size_t FreeSlotsOffset(int num_slots) { - return RetiredSlotsOffset(num_slots) + - static_cast( - Aligned64(static_cast(SizeofBitset(num_slots)))); -} - -inline size_t AvailableSlotsOffset(int num_slots, int sub_id) { - return FreeSlotsOffset(num_slots) + - static_cast( - Aligned64(static_cast(SizeofBitset(num_slots)))) + - SizeofBitset(num_slots) * static_cast(sub_id); -} - -inline size_t SlotQueueIndexOffset(int num_slots) { - return AvailableSlotsOffset(num_slots, kMaxSlotOwners); +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::kRetiredRefsMask; +using ::subspace::kRetiredRefsShift; +using ::subspace::kVchanIdMask; +using ::subspace::kVchanIdShift; + +inline size_t SizeofBitset(size_t bits) { + return ::subspace::SizeofAtomicBitSet(bits); } -// Queue offsets in AvailableSlotQueueIndex are relative to this. -inline size_t SlotQueueArenaOffset(int num_slots) { - return SlotQueueIndexOffset(num_slots) + - static_cast( - Aligned64(static_cast(sizeof(AvailableSlotQueueIndex)))); -} - -inline size_t CcbSize(int num_slots, uint64_t subscriber_queue_arena_size) { - return SlotQueueArenaOffset(num_slots) + - static_cast(subscriber_queue_arena_size); -} - -inline int32_t PrefixSize(int32_t checksum_size, int32_t metadata_size) { - return static_cast( - Aligned64(static_cast(offsetof(MessagePrefix, checksum)) + - checksum_size + metadata_size)); -} +constexpr int64_t Aligned64(int64_t v) { return ::subspace::Aligned<64>(v); } } // namespace shm } // namespace asil diff --git a/asil_client/subscriber.cc b/asil_client/subscriber.cc index 4070c1f7..e7118953 100644 --- a/asil_client/subscriber.cc +++ b/asil_client/subscriber.cc @@ -2,18 +2,17 @@ // All Rights Reserved // See LICENSE file for licensing information. -// The reading side of the shared memory protocol. This follows -// SubscriberImpl::NextSlot, LastSlot, ClaimSlot and RemoveActiveMessage in -// client/subscriber.cc, using the subscriber's available-slot bitset as the -// record of unread messages. A subscriber queue, when the channel has one, -// only holds hints, so the subscriber leaves it to the publishers. +// 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/checksum.h" #include "asil_client/client.h" - -#include +#include "common/message_checksum.h" +#include "common/subscribe.h" namespace subspace { namespace asil { @@ -22,19 +21,6 @@ namespace { constexpr int kMaxClaimAttempts = 1000; -// Messages are ordered by timestamp, then ordinal. -bool Before(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; -} - -BitsetView Owners(shm::MessageSlot *slot) { - return BitsetView(&slot->sub_owners, shm::kMaxSlotOwners); -} - bool ValidVchanId(int vchan_id) { return vchan_id >= -1 && vchan_id < shm::kMaxVchanId; } @@ -187,19 +173,13 @@ Error Subscriber::ReleaseMessage(const Message &message) { } void Subscriber::ReleaseSlot(shm::MessageSlot *slot) { - if (!Owners(slot).ClearWasSet(subscriber_id_)) { + const ReleasedMessage result = ReleaseMessageReference( + memory_, slot, subscriber_id_, options_.reliable); + if (!result.released) { return; } - bool retired = false; - (void)memory_.AtomicIncRefCount( - slot, options_.reliable, -1, - slot->ordinal.load(std::memory_order_relaxed), - slot->vchan_id.load(std::memory_order_relaxed), /*retire=*/true, - &retired); - if (retired) { - memory_.TriggerRetirement( - retirement_triggers_, - slot->bridged_slot_id.load(std::memory_order_relaxed)); + if (result.retired) { + memory_.TriggerRetirement(retirement_triggers_, result.retirement_slot_id); } if (options_.reliable) { // A reliable publisher may be waiting for this slot. @@ -229,27 +209,22 @@ void Subscriber::TriggerReliablePublishers() const { } } -// Whether slot holds a published message for this subscriber's virtual -// channel. A subscriber to a multiplexer sees every virtual channel. -bool Subscriber::Visible(const shm::MessageSlot *slot) const { - if ((slot->refs.load(std::memory_order_acquire) & shm::kPubOwned) != 0 || - slot->ordinal.load(std::memory_order_relaxed) == 0) { - return false; +// 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; } - 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 ordinal; } -// Takes a reference to slot and records it so that the server can release -// the reference if this process dies. bool Subscriber::Claim(shm::MessageSlot *slot, uint64_t ordinal) { - if (!memory_.AtomicIncRefCount(slot, options_.reliable, 1, ordinal, - slot->vchan_id.load(std::memory_order_relaxed), - false, nullptr)) { - return false; - } - Owners(slot).Set(subscriber_id_); - return true; + 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. @@ -261,13 +236,13 @@ Subscriber::Find Subscriber::FindNext(shm::MessageSlot *&slot) { uint64_t best_timestamp = 0; available.Traverse([&](int i) { shm::MessageSlot *s = memory_.Slot(i); - if (!Visible(s)) { + const uint64_t ordinal = VisibleOrdinal(s); + if (ordinal == 0) { return; } - const uint64_t ordinal = s->ordinal.load(std::memory_order_relaxed); const uint64_t timestamp = s->timestamp.load(std::memory_order_relaxed); if (best == nullptr || - Before(timestamp, ordinal, best_timestamp, best_ordinal)) { + DeliveredBefore(timestamp, ordinal, best_timestamp, best_ordinal)) { best = s; best_ordinal = ordinal; best_timestamp = timestamp; @@ -294,13 +269,13 @@ Subscriber::Find Subscriber::FindNewest(shm::MessageSlot *&slot) { uint64_t best_timestamp = 0; available.Traverse([&](int i) { shm::MessageSlot *s = memory_.Slot(i); - if (!Visible(s)) { + const uint64_t ordinal = VisibleOrdinal(s); + if (ordinal == 0) { return; } - const uint64_t ordinal = s->ordinal.load(std::memory_order_relaxed); const uint64_t timestamp = s->timestamp.load(std::memory_order_relaxed); if (best == nullptr || - Before(best_timestamp, best_ordinal, timestamp, ordinal)) { + DeliveredBefore(best_timestamp, best_ordinal, timestamp, ordinal)) { best = s; best_ordinal = ordinal; best_timestamp = timestamp; @@ -317,10 +292,7 @@ Subscriber::Find Subscriber::FindNewest(shm::MessageSlot *&slot) { return Find::kNone; } -// Marks every unread message older than newest as read. Each slot is pinned -// while its bit is cleared so that a publisher recycling it can't lose the -// bit for the new message. A reliable subscriber also marks the messages -// seen so that a reliable publisher doesn't wait for it to read them. +// 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 = @@ -333,25 +305,19 @@ void Subscriber::ClearOlder(const shm::MessageSlot *newest) { return; } shm::MessageSlot *s = memory_.Slot(i); - if (!Visible(s)) { + const uint64_t ordinal = VisibleOrdinal(s); + if (ordinal == 0) { return; } - const uint64_t ordinal = s->ordinal.load(std::memory_order_relaxed); const uint64_t timestamp = s->timestamp.load(std::memory_order_relaxed); - if (!Before(timestamp, ordinal, newest_timestamp, newest_ordinal)) { + if (!DeliveredBefore(timestamp, ordinal, newest_timestamp, + newest_ordinal)) { return; } - const int vchan_id = s->vchan_id.load(std::memory_order_relaxed); - if (memory_.AtomicIncRefCount(s, options_.reliable, 1, ordinal, vchan_id, - false, nullptr)) { - available.Clear(i); - if (options_.reliable) { - s->flags.fetch_or(shm::kMessageSeen | shm::kMessageSeenByReliable, - std::memory_order_relaxed); - marked_seen = true; - } - (void)memory_.AtomicIncRefCount(s, options_.reliable, -1, ordinal, - vchan_id, false, nullptr); + if (SkipUnreadMessage(memory_, s, subscriber_id_, options_.reliable, + ordinal, + s->vchan_id.load(std::memory_order_relaxed))) { + marked_seen |= options_.reliable; } }); if (marked_seen) { @@ -361,21 +327,9 @@ void Subscriber::ClearOlder(const shm::MessageSlot *newest) { bool Subscriber::ChecksumValid(const shm::MessageSlot *slot, size_t length) const { - const shm::MessagePrefix *prefix = memory_.Prefix(slot); - const auto *base = reinterpret_cast(prefix); - uint32_t crc = 0xFFFFFFFF; - crc = Crc32(crc, base + offsetof(shm::MessagePrefix, slot_id), - offsetof(shm::MessagePrefix, checksum) - - offsetof(shm::MessagePrefix, slot_id)); - crc = Crc32(crc, - base + offsetof(shm::MessagePrefix, checksum) + - memory_.ChecksumSize(), - static_cast(memory_.MetadataSize())); - crc = Crc32(crc, reinterpret_cast(memory_.Payload(slot)), - length); - uint32_t stored; - std::memcpy(&stored, &prefix->checksum, sizeof(stored)); - return stored == ~crc; + return MessageChecksumMatches(memory_.Prefix(slot), memory_.Payload(slot), + length, memory_.ChecksumSize(), + memory_.MetadataSize()); } Error Subscriber::ReadMessage(Message &message, ReadMode mode) { @@ -416,10 +370,7 @@ Error Subscriber::ReadMessage(Message &message, ReadMode mode) { ClearOlder(slot); } available.Clear(slot->id); - slot->flags.fetch_or(options_.reliable - ? shm::kMessageSeen | shm::kMessageSeenByReliable - : shm::kMessageSeen, - std::memory_order_relaxed); + MarkMessageSeen(slot, options_.reliable); uint64_t unused_last_ordinal = 0; uint64_t &last_ordinal = ValidVchanId(vchan_id) diff --git a/asil_client/subscriber.h b/asil_client/subscriber.h index 9d11ef07..d92679e2 100644 --- a/asil_client/subscriber.h +++ b/asil_client/subscriber.h @@ -123,7 +123,7 @@ class Subscriber { SubscriberRequest BuildRequest() const; Error MapChannel(SubscriberReply &reply); Error RefreshTriggers(); - bool Visible(const shm::MessageSlot *slot) const; + 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); diff --git a/client/Android.bp b/client/Android.bp index 955902c1..97808b0f 100644 --- a/client/Android.bp +++ b/client/Android.bp @@ -11,12 +11,11 @@ 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", diff --git a/client/BUILD.bazel b/client/BUILD.bazel index a340655d..7d1ad7ba 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,6 +23,7 @@ cc_library( strip_include_prefix = ".", include_prefix = "subspace/client", deps = [ + "//common:crc32", "//common:server_wire", "//common:subspace_common", "//common/async:async", diff --git a/client/CMakeLists.txt b/client/CMakeLists.txt index 265b2bed..c49bc906 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -13,23 +13,17 @@ 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 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_channel.cc b/client/client_channel.cc index 08ea33b4..13c5baab 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 5bea744e..aca6094a 100644 --- a/client/client_test.cc +++ b/client/client_test.cc @@ -4145,6 +4145,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); diff --git a/client/publisher.cc b/client/publisher.cc index d598591d..a99d076a 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; @@ -250,16 +295,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); - }); + SearchHooks hooks(*this); + ResetClaimedSlot(View(), slot, vchan_id_, hooks); return slot; } @@ -282,9 +319,7 @@ bool PublisherImpl::ReleaseLeasedSlot(MessageSlot *slot) { slot->ordinal = 0; slot->timestamp = 0; slot->refs.store(0, std::memory_order_release); - ccb_->subscribers.Traverse([this, slot](int sub_id) { - GetAvailableSlots(sub_id).Clear(slot->id); - }); + ForgetMessage(View(), slot); RetiredSlots().Set(slot->id); return true; } @@ -300,380 +335,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 >> kRetiredRefsShift) & kRetiredRefsMask); - if (slot->refs.compare_exchange_weak(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. - // std::stable_sort gives consistently better performance than std::sort and - // also is more deterministic in slot ordering. - std::stable_sort(active_slots_.begin(), active_slots_.end(), - [](const ActiveSlot &a, const ActiveSlot &b) { - return a.timestamp < b.timestamp; - }); - - // 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 >> kRetiredRefsShift) & kRetiredRefsMask); - if (slot->refs.compare_exchange_weak(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( @@ -683,12 +363,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) { @@ -703,125 +378,39 @@ 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; - 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); - } - - InPlaceSlotQueue *queue = GetAvailableSlotQueueAddress(sub_id); - if (queue != nullptr && - !queue->Push(slot->id, - slot->ordinal.load(std::memory_order_relaxed), - /*report_insertion_failure=*/false)) { - 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; - } + PublishedSlot published; + { + SubscriberQueuePublishGuard publish_guard(*this); + published = CommitPublishedSlot(View(), slot, vchan_id_, is_activation, + publish_guard.Scope()); } - for (InPlaceSlotQueue *queue : failed_queues) { - queue->MarkInsertionFailure(); - } - - // Commit the publication. A subscriber that observes the subsequent - // total_messages increment must also observe this release and all preceding - // delivery-record writes. PopulateActiveSlots preserves bits for - // publisher-owned slots, and queue consumers leave current-generation - // entries at the head until this store completes. - slot->refs.store(BuildRefsBitField(published_ordinal, vchan_id_, 0), - std::memory_order_release); - - // 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); - - // Subscriber removal and publication commit race safely: the operation that - // happens second re-evaluates retirement using the current subscriber count. - 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. @@ -832,7 +421,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 4a6bacea..f80d8345 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 @@ -39,12 +40,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 { @@ -57,14 +58,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); @@ -112,6 +110,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/subscriber.cc b/client/subscriber.cc index f6b8c32b..871f0ef1 100644 --- a/client/subscriber.cc +++ b/client/subscriber.cc @@ -11,10 +11,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() { @@ -46,19 +43,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) { @@ -94,35 +81,22 @@ std::optional SubscriberImpl::NoteStuckRead(uint64_t now_ns, return stuck_seconds; } -void SubscriberImpl::RemoveActiveMessage(MessageSlot *slot) { - // std::cerr << this << " remove active message " << slot->id << " " - // << slot->ordinal << " refs " << std::hex << slot->refs.load() << - // std::dec << "\n"; - if (slot->sub_owners.ClearWasSet(subscriber_id_)) { - AtomicIncRefCount(slot, IsReliable(), -1, - slot->ordinal.load(std::memory_order_relaxed), - slot->vchan_id.load(std::memory_order_relaxed), true, - [this, slot]() { - // 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. - - // Enable this for debugging slot retirement. - // std::string details = absl::StrFormat( - // "%d: RemoveActiveMessage: %s retiring slot %d ordinal " - // "%d vchan_id %d\n", getpid(), Name(), - // slot->bridged_slot_id, slot->ordinal, - // slot->vchan_id); - // std::cerr << details; - TriggerRetirement(slot->bridged_slot_id.load( - std::memory_order_relaxed)); - }); +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); if (--num_active_messages_ < options_.MaxActiveMessages() && options_.TriggerOnRelease()) { Trigger(); @@ -240,41 +214,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_)) { - 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 @@ -308,18 +274,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) { @@ -386,8 +342,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) { @@ -449,16 +404,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; } @@ -835,9 +785,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)}); @@ -876,11 +825,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 e7c6360c..8257a339 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 @@ -150,12 +151,10 @@ class SubscriberImpl : public ClientChannel { void IgnoreActivation(MessageSlot *slot) { RememberOrdinal(slot->ordinal.load(std::memory_order_relaxed), slot->vchan_id.load(std::memory_order_relaxed)); - DecrementSlotRef(slot, true); - slot->flags.fetch_or(kMessageSeen, std::memory_order_relaxed); - if (IsReliable()) { - slot->flags.fetch_or(kMessageSeenByReliable, std::memory_order_relaxed); - } + MarkMessageSeen(slot, IsReliable()); + ReleaseSlotReference(slot); } + 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 @@ -198,13 +197,6 @@ class SubscriberImpl : public ClientChannel { return m; } - void DecrementSlotRef(MessageSlot *slot, bool retire) { - AtomicIncRefCount(slot, IsReliable(), -1, - slot->ordinal.load(std::memory_order_relaxed) & - kOrdinalMask, - slot->vchan_id.load(std::memory_order_relaxed), retire); - } - bool SlotExpired(MessageSlot *slot, uint32_t ordinal) { return slot->ordinal.load(std::memory_order_relaxed) != ordinal; } 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 70df1bda..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,8 +73,52 @@ cc_library( ], ) -# Server requests and responses as Phaser messages in protobuf wire format, -# shared by the standard and ASIL clients. +# 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"], 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 100% rename from client/arm_crc32.S rename to common/arm_crc32.S diff --git a/common/atomic_bitset.h b/common/atomic_bitset.h index 1335a5e3..9896ba87 100644 --- a/common/atomic_bitset.h +++ b/common/atomic_bitset.h @@ -6,10 +6,7 @@ #include #include -#include -#include #include -#include namespace subspace { @@ -130,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; @@ -147,15 +145,15 @@ template class AtomicBitSet { os << "\n"; } - void Traverse(std::function 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); - // std::cerr << "i: " << i << " word " << std::hex << word << " n " << n - // << std::dec << "\n"; if (n == 0) { break; } @@ -166,21 +164,8 @@ template class AtomicBitSet { } } - void TraverseSeqCst(std::function 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: @@ -198,53 +183,4 @@ inline size_t SizeofAtomicBitSet(size_t size_in_bits) { // An atomic bitset with its bits not stored in the object. using InPlaceAtomicBitset = AtomicBitSet<0>; -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/asil_client/bitset.h b/common/bitset_view.h similarity index 89% rename from asil_client/bitset.h rename to common/bitset_view.h index fcdeac82..d8efd6c7 100644 --- a/asil_client/bitset.h +++ b/common/bitset_view.h @@ -4,18 +4,17 @@ #pragma once -#include "asil_client/shm_layout.h" +#include "common/atomic_bitset.h" #include #include #include namespace subspace { -namespace asil { // A view of an AtomicBitSet in shared memory. The memory orders match -// common/atomic_bitset.h. The bit count stored in shared memory is ignored; -// the view uses the count the server reported for the channel. +// 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; @@ -91,11 +90,10 @@ class BitsetView { private: static uint64_t Mask(int bit) { return uint64_t{1} << (bit % 64); } - int NumWords() const { return static_cast(shm::BitsToWords(num_bits_)); } + int NumWords() const { return static_cast(BitsToWords(num_bits_)); } std::atomic *words_ = nullptr; int num_bits_ = 0; }; -} // namespace asil } // namespace subspace diff --git a/common/channel.cc b/common/channel.cc index 927941d2..d0bab825 100644 --- a/common/channel.cc +++ b/common/channel.cc @@ -221,68 +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 retired_refs = (ref >> kRetiredRefsShift) & kRetiredRefsMask; - if (retire) { - retired_refs++; - } - uint64_t new_ref = BuildRefsBitField(ref_ord, ref_vchan_id, retired_refs) | - (new_reliable_refs << kReliableRefCountShift) | new_refs; - if (slot->refs.compare_exchange_weak(ref, new_ref, - std::memory_order_acq_rel, - std::memory_order_relaxed)) { - // std::string details = absl::StrFormat( - // "%d: AtomicIncRefCount: %s slot %d ordinal %d retired_refs: %d NumSubscribers: %d retire: %d\n", getpid(), Name(), slot->id, ordinal, retired_refs, NumSubscribers(ref_vchan_id), retire); - // std::cerr << details; - if (retire && new_refs == 0 && new_reliable_refs == 0 && - retired_refs >= NumSubscribers(ref_vchan_id) && - RetiredSlots().SetWasClear(slot->id)) { - // All subscribers have seen the slot, retire it. - if (retire_callback) { - // std::cerr << "Calling retire callback for slot " << slot->id - // << std::endl; - 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 retired = false; + const bool held = View().AtomicIncRefCount(slot, reliable, inc, ordinal, + vchan_id, retire, &retired); + if (retired && retire_callback) { + retire_callback(); } + return held; } void MessageSlot::Dump(std::ostream &os) const { @@ -414,48 +359,6 @@ void Channel::CleanupSlots(int owner, bool reliable, bool is_pub, } } -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; - } - int vchan_id = (refs >> kVchanIdShift) & kVchanIdMask; - if (vchan_id == kVchanIdMask) { - vchan_id = -1; - } - const uint64_t retired_refs = (refs >> kRetiredRefsShift) & kRetiredRefsMask; - return retired_refs >= static_cast(NumSubscribers(vchan_id)); -} - -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; - const uint64_t retired_refs = - (refs >> kRetiredRefsShift) & kRetiredRefsMask; - int ref_vchan_id = (refs >> kVchanIdShift) & kVchanIdMask; - if (ref_vchan_id == kVchanIdMask) { - ref_vchan_id = -1; - } - - if (ref_count != 0 || reliable_ref_count != 0 || - retired_refs < static_cast(NumSubscribers(ref_vchan_id))) { - 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 5b7cd116..71fbba40 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,506 +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; -constexpr uint32_t kChannelControlBlockVersion = 5; -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; -constexpr uint64_t kRetiredRefsSize = 10; -constexpr uint64_t kRetiredRefsMask = (1ULL << kRetiredRefsSize) - 1; -constexpr uint64_t kRetiredRefsShift = 20; - -// Virtual channel ID is just above retired refs and is 10 bits long. -constexpr uint64_t kVchanIdShift = kRetiredRefsShift + kRetiredRefsSize; -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 uint64_t BuildRefsBitField(uint64_t ordinal, int vchan_id, - int retired_refs) { - return ((ordinal & kOrdinalMask) << kOrdinalShift) | - (ordinal == 0 ? 0 : ((vchan_id & kVchanIdMask) << kVchanIdShift)) | - ((retired_refs & kRetiredRefsMask) << kRetiredRefsShift); -} 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. - - 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(sizeof(MessageSlot) == offsetof(MessageSlot, bridged_slot_id) + - sizeof(std::atomic)); -// The default owner count keeps the historical shared-memory layout. -static_assert(kMaxSlotOwners != 1024 || sizeof(MessageSlot) == 184); - -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_; } - 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) { - 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 (!DropFront()) { - 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. - bool TryPeek(QueuedSlot &slot) { - 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; - return true; - } - - // Drop the oldest queued slot. Producers use this on overflow, and the - // subscriber uses it to discard stale entries whose slot has been reused. - 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: - // 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), @@ -593,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)}; } @@ -617,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_; }; @@ -665,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) { @@ -1092,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; @@ -1138,9 +321,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). @@ -1199,14 +380,17 @@ 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()); + } - // Whether `refs`, read from `slot`, show a slot that holds no message or one - // that every subscriber has seen and released. A slot's retired bit is set - // after the subscriber retiring it releases it, 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; + bool TryRetireSlot(MessageSlot *slot) { return View().TryRetireSlot(slot); } + + bool RefsShowRetired(const MessageSlot *slot, uint64_t refs) const { + return View().RefsShowRetired(slot, refs); + } int NumSubscribers(int vchan_id) const { return ccb_->num_subs.NumSubscribers(vchan_id); @@ -1244,21 +428,19 @@ class Channel : public std::enable_shared_from_this { 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() { @@ -1291,7 +473,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() { @@ -1331,22 +514,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..bc9cd309 --- /dev/null +++ b/common/channel_view.h @@ -0,0 +1,201 @@ +// Copyright 2026 David Allison +// 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 has seen and released. A slot's retired bit is set + // after the subscriber retiring it releases it, 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; + } + const uint64_t retired_refs = + (refs >> kRetiredRefsShift) & kRetiredRefsMask; + return retired_refs >= + static_cast(NumSubscribers(RefsVchanId(refs))); + } + + // 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; + const uint64_t retired_refs = + (refs >> kRetiredRefsShift) & kRetiredRefsMask; + if (ref_count != 0 || reliable_ref_count != 0 || + retired_refs < + static_cast(NumSubscribers(RefsVchanId(refs)))) { + return false; + } + return RetiredSlots().SetWasClear(slot->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); + } + uint64_t retired_refs = (ref >> kRetiredRefsShift) & kRetiredRefsMask; + if (retire) { + retired_refs++; + } + const uint64_t new_ref = + BuildRefsBitField(ref_ordinal, ref_vchan_id, + static_cast(retired_refs)) | + (reliable_refs << kReliableRefCountShift) | refs; + if (slot->refs.compare_exchange_weak(ref, new_ref, + std::memory_order_acq_rel, + std::memory_order_relaxed)) { + if (retire && refs == 0 && reliable_refs == 0 && + static_cast(retired_refs) >= + NumSubscribers(ref_vchan_id) && + RetiredSlots().SetWasClear(slot->id) && retired != nullptr) { + *retired = true; + } + return true; + } + // Another subscriber, or a publisher, changed the refs. + } + } + +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 99% rename from client/checksum.cc rename to common/crc32.cc index fa564be9..92e07977 100644 --- a/client/checksum.cc +++ b/common/crc32.cc @@ -2,10 +2,10 @@ // All Rights Reserved // See LICENSE file for licensing information. -#include "client/checksum.h" +#include "common/crc32.h" + #include #include -#include namespace subspace { diff --git a/common/crc32.h b/common/crc32.h new file mode 100644 index 00000000..2e1fa947 --- /dev/null +++ b/common/crc32.h @@ -0,0 +1,24 @@ +// Copyright 2026 David Allison +// 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. x86-64 with SSE4.2 uses CRC32C; other builds +// use the IEEE 802.3 polynomial. 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..253576a7 --- /dev/null +++ b/common/dynamic_bitset.h @@ -0,0 +1,64 @@ +// Copyright 2023-2026 David Allison +// 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..1f887e53 --- /dev/null +++ b/common/message_checksum.h @@ -0,0 +1,85 @@ +// Copyright 2026 David Allison +// 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..f9190491 --- /dev/null +++ b/common/publish.h @@ -0,0 +1,190 @@ +// Copyright 2026 David Allison +// 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. +inline PublishedSlot +CommitPublishedSlot(const ChannelView &channel, MessageSlot *slot, + int vchan_id, bool is_activation, + const SubscriberQueuePublishScope & /*publishing*/) { + 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); + + // 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); + } + InPlaceSlotQueue *queue = channel.Queue(sub_id); + if (queue != nullptr && + !queue->Push(slot->id, published.ordinal, + /*report_insertion_failure=*/false)) { + 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; + } + } + // 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(); + } + }); + + // Commit. 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. + slot->refs.store(BuildRefsBitField(published.ordinal, vchan_id, 0), + std::memory_order_release); + ccb->total_messages.fetch_add(1, std::memory_order_seq_cst); + + // Subscriber removal and the commit race safely: whichever happens second + // re-evaluates retirement with the current subscriber count. + 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 index 32bed75c..3116caff 100644 --- a/common/server_wire.h +++ b/common/server_wire.h @@ -6,25 +6,30 @@ #include "absl/status/status.h" #include "absl/status/statusor.h" +#include "phaser/runtime/wireformat.h" #include "proto/subspace.phaser.h" #include #include +#include #include namespace subspace { -// Requests to and responses from the server, as Phaser messages sent in -// protobuf wire format. The server, and clients in other languages, see the -// same bytes as from a protobuf client. +// 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 serializes requests into its wire buffer and decodes -// responses. The Buffers policy decides where messages and wire bytes live: +// 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. 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. +// 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. @@ -37,13 +42,21 @@ inline constexpr size_t kServerWireHeaderSize = sizeof(uint32_t); 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_)); + return phaser::Request::TryCreateMutable(message_, sizeof(message_), + ::phaser::Tuning::kSize); } absl::StatusOr NewResponse() { - return phaser::Response::TryCreateMutable(message_, sizeof(message_)); + return phaser::Response::TryCreateMutable(message_, sizeof(message_), + ::phaser::Tuning::kSize); } // Room for the header and length bytes after it, or nullptr. @@ -56,6 +69,8 @@ template class FixedServerWireBuffers { class DynamicServerWireBuffers { public: + static constexpr bool kErrorMessages = true; + char *Wire(size_t length) { wire_.resize(kServerWireHeaderSize + length); return wire_.data(); @@ -65,6 +80,39 @@ class DynamicServerWireBuffers { 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: absl::StatusOr NewRequest() { return buffers_.NewRequest(); } @@ -72,23 +120,15 @@ template class ServerWire { return buffers_.NewResponse(); } - // Serializes request into the wire buffer and returns its length. The - // bytes are at Payload(), with kServerWireHeaderSize bytes before them. + // 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) { - if (request.AllocationFailed()) { - return absl::ResourceExhaustedError("Request is too large to build"); - } - const size_t length = request.SerializedSize(); - char *wire = buffers_.Wire(length); - if (wire == nullptr) { - return absl::ResourceExhaustedError("Request is too large to send"); - } - payload_ = wire + kServerWireHeaderSize; - ::phaser::ProtoBuffer out(payload_, length); - if (absl::Status status = request.Serialize(out); !status.ok()) { - return status; - } - return out.Size(); + return CopyPayload(request); + } + + absl::StatusOr Serialize(const phaser::Response &response) { + return CopyPayload(response); } // The bytes from the last Serialize. @@ -100,14 +140,74 @@ template class ServerWire { return wire == nullptr ? nullptr : wire + kServerWireHeaderSize; } - // Decodes length bytes of a response into response. + // Loads a native payload into an owned message. static absl::Status Decode(const char *data, size_t length, phaser::Response &response) { - ::phaser::ProtoBuffer in(data, length); - return response.Deserialize(in); + 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; }; diff --git a/common/shm_layout.h b/common/shm_layout.h new file mode 100644 index 00000000..c029458c --- /dev/null +++ b/common/shm_layout.h @@ -0,0 +1,876 @@ +// Copyright 2023-2026 David Allison +// 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; +constexpr uint32_t kChannelControlBlockVersion = 5; +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; +constexpr uint64_t kRetiredRefsSize = 10; +constexpr uint64_t kRetiredRefsMask = (1ULL << kRetiredRefsSize) - 1; +constexpr uint64_t kRetiredRefsShift = 20; + +// Virtual channel ID is just above retired refs and is 10 bits long. +constexpr uint64_t kVchanIdShift = kRetiredRefsShift + kRetiredRefsSize; +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 uint64_t BuildRefsBitField(uint64_t ordinal, int vchan_id, + int retired_refs) { + return ((ordinal & kOrdinalMask) << kOrdinalShift) | + (ordinal == 0 ? 0 : ((vchan_id & kVchanIdMask) << kVchanIdShift)) | + ((retired_refs & kRetiredRefsMask) << kRetiredRefsShift); +} + +// 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. + + 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(sizeof(MessageSlot) == offsetof(MessageSlot, bridged_slot_id) + + sizeof(std::atomic)); +// The default owner count keeps the historical shared-memory layout. +static_assert(kMaxSlotOwners != 1024 || sizeof(MessageSlot) == 184); + +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_; } + 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) { + 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 (!DropFront()) { + 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. + bool TryPeek(QueuedSlot &slot) { + 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; + return true; + } + + // Drop the oldest queued slot. Producers use this on overflow, and the + // subscriber uses it to discard stale entries whose slot has been reused. + 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: + // 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..8eaedc46 --- /dev/null +++ b/common/slot_search.h @@ -0,0 +1,447 @@ +// Copyright 2026 David Allison +// 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; + 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. +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), + static_cast((old_refs >> kRetiredRefsShift) & kRetiredRefsMask)); + return slot->refs.compare_exchange_weak( + 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..f1b2ee0c --- /dev/null +++ b/common/subscribe.h @@ -0,0 +1,135 @@ +// Copyright 2026 David Allison +// 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)) { + (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; + (void)channel.AtomicIncRefCount( + slot, reliable, -1, slot->ordinal.load(std::memory_order_relaxed), + slot->vchan_id.load(std::memory_order_relaxed), /*retire=*/true, + &result.retired); + if (result.retired) { + result.retirement_slot_id = + slot->bridged_slot_id.load(std::memory_order_relaxed); + } + 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/asil-client.md b/docs/asil-client.md index dd5b026c..a15994f0 100644 --- a/docs/asil-client.md +++ b/docs/asil-client.md @@ -13,14 +13,21 @@ safety case the most predictable setup. ## Design Rules -- **C++17, the standard library and POSIX.** The core library has no other - dependencies and is compiled with `-fno-exceptions -fno-rtti`. The server - connection adds [phaser](https://github.com/dallison/phaser) and is built - the same way. +- **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 server's reason for - `Error::kServerRejected`. + `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. @@ -158,15 +165,15 @@ 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: -length-prefixed messages in protobuf wire format on the server's Unix socket, -with file descriptors passed by `SCM_RIGHTS`. The server receives the same -bytes it receives from the standard clients. Requests and responses are -encoded by `ServerWire` in `common/server_wire.h`, which the standard C++ -client uses too. The standard client gives it growable buffers. The ASIL -connection gives it fixed buffers inside the object: it builds each request -as a phaser message in a fixed buffer, serializes it to protobuf wire format, -and decodes the response into the same buffer, so it needs neither the -protobuf library nor the heap. The buffers take about 60 KB, so keep the +length-prefixed native Phaser payloads on the server's Unix socket, with file +descriptors passed by `SCM_RIGHTS`. The server receives the same bytes it +receives from the standard clients. Requests and responses are encoded by +`ServerWire` in `common/server_wire.h`, which the standard C++ client uses +too. The standard client gives it growable buffers. The ASIL connection +gives it fixed buffers inside the object: it builds each request as a phaser +message in a fixed buffer, copies that payload onto the socket, and loads the +response into the same buffer, so it needs neither the protobuf library nor +the heap. The buffers take about 60 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`. @@ -350,10 +357,18 @@ have them. ## Testing -`layout_test` compares every size, offset and constant in -`asil_client/shm_layout.h` with `common/channel.h`, checks that the checksum -matches the standard client's, and passes subscriber queue entries between -the ASIL client and the standard `InPlaceSlotQueue`. +`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, @@ -363,5 +378,6 @@ 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 too large for the wire buffer -returns `Error::kCapacityExceeded` and leaves the connection usable. +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/client_design.md b/docs/client_design.md index b0eadae6..92166797 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 53c66d87..326d2c47 100644 --- a/docs/rust-client.md +++ b/docs/rust-client.md @@ -433,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/proto/BUILD.bazel b/proto/BUILD.bazel index e353439a..9fc8077c 100644 --- a/proto/BUILD.bazel +++ b/proto/BUILD.bazel @@ -30,6 +30,20 @@ phaser_library( 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 = [ diff --git a/proto/CMakeLists.txt b/proto/CMakeLists.txt index 4bd650e9..9660b8cd 100644 --- a/proto/CMakeLists.txt +++ b/proto/CMakeLists.txt @@ -95,9 +95,8 @@ target_link_libraries(subspace_proto PUBLIC protobuf::libprotobuf ) -# Phaser messages for the clients' server requests and responses. They are -# sent and received in protobuf wire format, so the server sees the same bytes -# as from any other client. Cross-compiles need a host plugin in +# 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 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/src/client.rs b/rust_client/src/client.rs index dc2ce30e..b3fa82d1 100644 --- a/rust_client/src/client.rs +++ b/rust_client/src/client.rs @@ -1166,40 +1166,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, })), }) @@ -1255,73 +1253,69 @@ 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 - }, - server_defined: opts.server_defined, - }, - )), - }; + 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; + 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; @@ -1338,13 +1332,13 @@ impl Client { 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 = use_split_buffers; @@ -1356,23 +1350,25 @@ impl Client { 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; @@ -1391,12 +1387,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(); @@ -1434,61 +1432,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 { @@ -1497,24 +1491,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 }; @@ -1526,31 +1520,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)); @@ -1568,125 +1564,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 { @@ -1699,71 +1618,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(()) @@ -1775,15 +1760,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) } @@ -2001,31 +1984,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 @@ -2036,27 +2016,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 }; @@ -2070,28 +2050,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 { @@ -2114,28 +2095,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(()) @@ -2153,31 +2134,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(()) @@ -2240,19 +2219,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(()) @@ -2264,20 +2242,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/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/server/BUILD.bazel b/server/BUILD.bazel index 420c8639..36c6b1e0 100644 --- a/server/BUILD.bazel +++ b/server/BUILD.bazel @@ -31,6 +31,7 @@ cc_library( ], deps = [ ":tunnel_wire", + "//common:server_wire", "//common:subspace_common", "//common/async:async", "//client:subspace_client", @@ -201,6 +202,7 @@ cc_test( ":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", @@ -254,6 +256,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/client_handler.cc b/server/client_handler.cc index 087ede52..30b07e81 100644 --- a/server/client_handler.cc +++ b/server/client_handler.cc @@ -6,7 +6,9 @@ #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 { @@ -17,10 +19,10 @@ namespace { // can't create. template bool StaticConfigAllowsNewChannel(const Server &server, - const std::string &channel_name, + std::string_view channel_name, Response *response) { if (!server.HasStaticChannelConfig() || - Server::IsServerChannelName(channel_name)) { + Server::IsServerChannelName(std::string(channel_name))) { return true; } response->set_error(absl::StrFormat( @@ -28,7 +30,7 @@ bool StaticConfigAllowsNewChannel(const Server &server, return false; } -ClientBufferAllocatorKind FromProtoAllocator(ClientBufferAllocator allocator) { +ClientBufferAllocatorKind FromProtoAllocator(int allocator) { switch (allocator) { case CLIENT_BUFFER_ALLOCATOR_ANDROID_MEMFD: return ClientBufferAllocatorKind::kAndroidMemfd; @@ -61,7 +63,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(); @@ -73,13 +75,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); @@ -90,12 +92,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()}; } @@ -109,29 +113,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); @@ -153,7 +156,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()) { @@ -169,17 +172,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; } @@ -192,65 +194,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()) { @@ -290,7 +292,7 @@ absl::Status ClientHandler::HandleRegisterClientBuffer( } absl::Status ClientHandler::HandleUnregisterClientBuffer( - const subspace::UnregisterClientBufferRequest &req) { + const subspace::phaser::UnregisterClientBufferRequest &req) { if (req.session_id() != server_->GetSessionId()) { return absl::OkStatus(); } @@ -309,15 +311,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) { @@ -334,7 +337,8 @@ void ClientHandler::HandleGetClientBuffers( buffer->metadata.slot_id != req.slot_id())) { continue; } - ToProto(buffer->metadata, response->add_metadata()); + 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); @@ -344,8 +348,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) { @@ -379,8 +383,8 @@ void ClientHandler::HandleInit(const subspace::InitRequest &req, } void ClientHandler::HandleCreatePublisher( - const subspace::CreatePublisherRequest &request, - 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. @@ -399,7 +403,7 @@ void ClientHandler::HandleCreatePublisher( request.channel_name())); return; } - subspace::CreatePublisherRequest server_defined_req; + subspace::phaser::CreatePublisherRequest server_defined_req; if (is_static) { std::vector layout_fields; if (request.num_slots() != 0) { @@ -434,7 +438,11 @@ void ClientHandler::HandleCreatePublisher( existing->IsVirtual() ? static_cast(existing)->GetMux() : existing; - server_defined_req = request; + 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); @@ -446,7 +454,7 @@ void ClientHandler::HandleCreatePublisher( layout_channel->HasSplitBufferOptions() && layout_channel->GetSplitBufferOptions().use_split_buffers); } - const subspace::CreatePublisherRequest &req = + const subspace::phaser::CreatePublisherRequest &req = is_static ? server_defined_req : request; if (req.num_slots() <= 0 || req.slot_size() <= 0) { @@ -548,14 +556,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; @@ -570,7 +579,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 @@ -658,7 +667,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; @@ -793,7 +802,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()); } } @@ -813,7 +822,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( @@ -839,7 +848,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()) { @@ -934,8 +943,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"); @@ -966,14 +975,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())); @@ -997,10 +1006,11 @@ void ClientHandler::HandleCreateSubscriber( 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; @@ -1018,7 +1028,7 @@ void ClientHandler::HandleCreateSubscriber( return; } if (channel->Type().empty()) { - channel->SetType(req.type()); + channel->SetType(std::string(req.type())); } } } @@ -1103,7 +1113,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()) { @@ -1120,7 +1130,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(), @@ -1224,13 +1234,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) { @@ -1278,8 +1288,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) { @@ -1291,11 +1301,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( @@ -1306,15 +1317,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; } @@ -1324,20 +1334,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; } @@ -1347,8 +1356,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 294a5276..d6a94817 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,46 +36,46 @@ 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 &request, - 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_; diff --git a/server/server.h b/server/server.h index 7bcf0cc8..7fc98876 100644 --- a/server/server.h +++ b/server/server.h @@ -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" @@ -286,7 +287,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: diff --git a/server/server_channel.cc b/server/server_channel.cc index 0ae2a3b6..418cd5ea 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 @@ -1499,7 +1500,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()); @@ -1523,27 +1525,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 @@ -1569,7 +1591,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; @@ -1593,6 +1616,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(); diff --git a/server/server_channel.h b/server/server_channel.h index e04afce4..cba8640e 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" @@ -330,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; diff --git a/server/server_channels.cc b/server/server_channels.cc index 0b8084af..b7841c37 100644 --- a/server/server_channels.cc +++ b/server/server_channels.cc @@ -255,8 +255,8 @@ 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; } diff --git a/server/server_test.cc b/server/server_test.cc index b4e781ee..4c02f5e2 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 @@ -40,7 +42,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)); @@ -57,7 +59,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); @@ -71,22 +73,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(); } @@ -100,9 +101,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; @@ -115,11 +119,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); @@ -131,10 +135,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); @@ -147,26 +151,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); @@ -175,11 +178,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, @@ -188,7 +199,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); @@ -211,13 +222,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); @@ -247,7 +258,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); @@ -263,7 +274,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); @@ -354,8 +365,8 @@ TEST_F(ServerTest, ServerDefinedNeedsStaticChannel) { // 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::Request req; - subspace::CreatePublisherRequest *cmd = req.mutable_create_publisher(); + 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); @@ -722,7 +733,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); @@ -742,7 +753,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); @@ -758,7 +769,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); @@ -774,7 +785,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); @@ -789,7 +800,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); @@ -808,7 +819,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); @@ -826,7 +837,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); @@ -841,7 +852,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); @@ -862,7 +873,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); @@ -881,7 +892,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); @@ -897,7 +908,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); @@ -917,14 +928,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); @@ -943,7 +954,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); @@ -958,7 +969,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); @@ -974,7 +985,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); @@ -993,14 +1004,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_test.cc b/server/static_config_test.cc index 5cf55fb0..00860933 100644 --- a/server/static_config_test.cc +++ b/server/static_config_test.cc @@ -11,7 +11,9 @@ #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 @@ -52,15 +54,14 @@ subspace::PublisherOptions ServerDefined() { // 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::Request &req) { - std::vector buffer(sizeof(int32_t) + req.ByteSizeLong()); - char *payload = buffer.data() + sizeof(int32_t); - if (!req.SerializeToArray(payload, static_cast(req.ByteSizeLong()))) { - return absl::InternalError("Failed to serialize request"); +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(payload, req.ByteSizeLong()); + if (absl::StatusOr n = socket.SendMessage(wire.Payload(), *length); !n.ok()) { return n.status(); } @@ -69,10 +70,13 @@ absl::StatusOr Transact(toolbelt::UnixSocket &socket, if (!received.ok()) { return received.status(); } - subspace::Response response; - if (!response.ParseFromArray(received->data(), - static_cast(received->size()))) { - return absl::InternalError("Failed to parse response"); + 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()) { @@ -312,46 +316,46 @@ TEST_F(StaticConfigTest, PublishersMustBeServerDefined) { TEST_F(StaticConfigTest, ServerRejectsLayoutFromServerDefinedPublishers) { toolbelt::UnixSocket socket; ASSERT_OK(socket.Connect(Socket())); - subspace::Request init; + subspace::phaser::Request init; init.mutable_init()->set_client_name("raw"); ASSERT_OK(Transact(socket, init)); const std::vector< - std::pair> + std::pair> cases = { {"num_slots", - [](subspace::CreatePublisherRequest *r) { r->set_num_slots(8); }}, + [](subspace::phaser::CreatePublisherRequest *r) { r->set_num_slots(8); }}, {"slot_size", - [](subspace::CreatePublisherRequest *r) { r->set_slot_size(256); }}, + [](subspace::phaser::CreatePublisherRequest *r) { r->set_slot_size(256); }}, {"fixed_size", - [](subspace::CreatePublisherRequest *r) { + [](subspace::phaser::CreatePublisherRequest *r) { r->set_is_fixed_size(true); }}, {"checksum_size", - [](subspace::CreatePublisherRequest *r) { + [](subspace::phaser::CreatePublisherRequest *r) { r->set_checksum_size(4); }}, {"metadata_size", - [](subspace::CreatePublisherRequest *r) { + [](subspace::phaser::CreatePublisherRequest *r) { r->set_metadata_size(16); }}, {"subscriber_queue_arena_size", - [](subspace::CreatePublisherRequest *r) { + [](subspace::phaser::CreatePublisherRequest *r) { r->set_subscriber_queue_arena_size(4096); }}, {"use_split_buffers", - [](subspace::CreatePublisherRequest *r) { + [](subspace::phaser::CreatePublisherRequest *r) { r->set_use_split_buffers(true); }}, }; for (const auto &[field, set] : cases) { - subspace::Request req; - subspace::CreatePublisherRequest *cmd = req.mutable_create_publisher(); + 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); + absl::StatusOr response = Transact(socket, req); ASSERT_OK(response); EXPECT_THAT(response->create_publisher().error(), HasSubstr("can't set " + field)) From 0fe05c323382177140ff7965a65e6fa2b3c31f35 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Thu, 5 Nov 2026 18:01:32 -0800 Subject: [PATCH 07/21] Fix the CMake, Linux and Android CI builds - crc32.cc included inside namespace subspace, which broke libc++ on Android x86_64, where SSE4.2 is on by default. - The ASIL oversized response test bound a filesystem socket, but Connect() uses the abstract namespace on Linux. On a failed connect it also hung, as closing a socket does not wake accept() on Linux. - The CMake build of the Rust client had no Phaser bindings. It now generates them with phaser's C frontend and links their C++ code into one shared library for Cargo. The new phaser_c crate includes them. - Pin phaser to dallison/phaser#22, which brings phaser's CMake build up to date and adds the C and Rust output. --- .cursor/skills/subspace-clients/SKILL.md | 10 +++-- CHANGELOG.md | 7 +++- CMakeLists.txt | 5 ++- MODULE.bazel | 4 +- MODULE.bazel.lock | 6 +-- asil_client/asil_client_test.cc | 7 ++++ common/crc32.cc | 22 +++++++---- rust_client/CMakeLists.txt | 50 +++++++++++++++++++++--- rust_client/Cargo.lock | 5 +++ rust_client/Cargo.toml | 1 + rust_client/build.rs | 7 ++++ rust_client/phaser_c/Cargo.toml | 8 ++++ rust_client/phaser_c/build.rs | 23 +++++++++++ rust_client/phaser_c/src/lib.rs | 14 +++++++ 14 files changed, 145 insertions(+), 24 deletions(-) create mode 100644 rust_client/phaser_c/Cargo.toml create mode 100644 rust_client/phaser_c/build.rs create mode 100644 rust_client/phaser_c/src/lib.rs 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/CHANGELOG.md b/CHANGELOG.md index affe6dc5..a2edd1b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -80,8 +80,13 @@ - 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. + 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 diff --git a/CMakeLists.txt b/CMakeLists.txt index 6f7ee795..85255263 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -215,8 +215,9 @@ FetchContent_MakeAvailable(protobuf) FetchContent_Declare( phaser GIT_REPOSITORY https://github.com/dallison/phaser.git - # phaser 3.1.1, as in the git_override in MODULE.bazel. - GIT_TAG 4b3a80c0c90d51e04d4b27aa8cc32b884f2b6e38 + # phaser 3.1.1 with the CMake build fixes in dallison/phaser#22, as in the + # git_override in MODULE.bazel. + GIT_TAG a0c1b24794eff9f872c727664841c4c900da074f ) FetchContent_MakeAvailable(phaser) diff --git a/MODULE.bazel b/MODULE.bazel index 9295dd81..2e4ce2f0 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -43,8 +43,8 @@ bazel_dep(name = "rules_python", version = "1.9.0") git_override( module_name = "phaser", - # Tag 3.1.1. - commit = "4b3a80c0c90d51e04d4b27aa8cc32b884f2b6e38", + # Tag 3.1.1 with the CMake build fixes in dallison/phaser#22. + commit = "a0c1b24794eff9f872c727664841c4c900da074f", remote = "https://github.com/dallison/phaser.git", ) diff --git a/MODULE.bazel.lock b/MODULE.bazel.lock index 1af83626..5d0a0029 100644 --- a/MODULE.bazel.lock +++ b/MODULE.bazel.lock @@ -426,8 +426,8 @@ "REPO_MAPPING:rules_rust+,bazel_skylib bazel_skylib+", "REPO_MAPPING:rules_rust+,bazel_tools bazel_tools", "REPO_MAPPING:rules_rust+,rules_cc rules_cc+", - "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": { @@ -436,7 +436,7 @@ "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 = \"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", - "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}\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 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", + "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", diff --git a/asil_client/asil_client_test.cc b/asil_client/asil_client_test.cc index 7688a8ea..df06596e 100644 --- a/asil_client/asil_client_test.cc +++ b/asil_client/asil_client_test.cc @@ -1113,7 +1113,12 @@ TEST_F(AsilClientTest, OversizedResponseMakesNoHeapAllocations) { 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)); @@ -1176,6 +1181,8 @@ TEST_F(AsilClientTest, OversizedResponseMakesNoHeapAllocations) { 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); diff --git a/common/crc32.cc b/common/crc32.cc index 92e07977..5151c8d4 100644 --- a/common/crc32.cc +++ b/common/crc32.cc @@ -7,10 +7,6 @@ #include #include -namespace subspace { - -extern "C" { - #if defined(__x86_64__) && !defined(__SSE4_2__) // On Intel crc is only available when SSE4.2 is enabled #undef SUBSPACE_HARDWARE_CRC @@ -21,15 +17,26 @@ extern "C" { #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 +#elif defined(SUBSPACE_HARDWARE_CRC) && defined(__x86_64__) +// The intrinsics headers include C library headers, which must not be inside +// a namespace. +#include +#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; @@ -54,7 +61,6 @@ uint32_t SubspaceCRC32(uint32_t crc, const uint8_t *data, size_t length) { #endif // !defined(ARM_ASM_CRC32) #elif defined(SUBSPACE_HARDWARE_CRC) && defined(__x86_64__) -#include uint32_t SubspaceCRC32(uint32_t crc, const uint8_t *data, size_t length) { size_t i = 0; // Process 8 bytes at a time. 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")); From 739909ca660a9a4e1610c45a4187ddc1f607cf84 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Thu, 5 Nov 2026 18:11:12 -0800 Subject: [PATCH 08/21] Build the test plugins after the phaser headers The plugins include the server headers, which include the generated subspace_phaser headers, but outside Android they don't link libserver and so could compile before the headers were generated. --- plugins/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/CMakeLists.txt b/plugins/CMakeLists.txt index 064c28f0..98814fa8 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 @@ -62,7 +62,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 From 7537a5d42e8e69ee7b9d72bdf388ad588a0683f7 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Sat, 7 Nov 2026 12:47:21 -0800 Subject: [PATCH 09/21] Make static channel types bytes The type of a channel in a StaticChannelConfig was a string, so it could not hold an opaque blob such as ROS metadata or a protobuf descriptor. Make it bytes, the same as the channel type on the wire. Quoted text still parses to the same bytes, and protobuf text escapes carry blobs. Add a test that a blob type is kept and that a publisher must match it. --- CHANGELOG.md | 5 ++++ README.md | 6 ++++ proto/subspace.proto | 13 +++++++-- server/static_config_test.cc | 53 +++++++++++++++++++++++++++++++++++- 4 files changed, 73 insertions(+), 4 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index a2edd1b0..f28bc496 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -32,6 +32,11 @@ 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`. diff --git a/README.md b/README.md index 59af402b..dfc55908 100644 --- a/README.md +++ b/README.md @@ -2041,6 +2041,12 @@ channels { name: "/sensors/lidar" mux: "/sensors" vchan_id: 0 } channels { name: "/sensors/radar" mux: "/sensors" vchan_id: 1 } ``` +`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 diff --git a/proto/subspace.proto b/proto/subspace.proto index 45a7d653..105c3efa 100644 --- a/proto/subspace.proto +++ b/proto/subspace.proto @@ -698,7 +698,11 @@ message StaticMultiplexer { string name = 1; int32 slot_size = 2; int32 num_slots = 3; - string type = 4; + // 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. @@ -709,10 +713,13 @@ 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. + // 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; - string type = 4; + 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. diff --git a/server/static_config_test.cc b/server/static_config_test.cc index 00860933..1c173a34 100644 --- a/server/static_config_test.cc +++ b/server/static_config_test.cc @@ -46,8 +46,17 @@ constexpr char kConfig[] = R"pb( 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); } @@ -160,7 +169,30 @@ TEST(StaticConfigParseTest, ParsesValidConfig) { subspace::ParseStaticChannelConfig(kConfig); ASSERT_OK(config); EXPECT_EQ(2, config->multiplexers_size()); - EXPECT_EQ(6, config->channels_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) { @@ -233,6 +265,25 @@ TEST_F(StaticConfigTest, ChannelsExistBeforeAnyClient) { 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) { From 136277c2d546fc247ff67679d38d715e7ca79a0a Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Sat, 7 Nov 2026 15:57:54 -0800 Subject: [PATCH 10/21] Fix the macOS CMake plugin build and run SplitBufferPluginTest on macOS - Pass -undefined dynamic_lookup when linking the plugin modules on macOS so server symbols can resolve at load time, matching Linux's --unresolved-symbols=ignore-all. - Build static nop_plugin_lib and split_buffer_free_test_plugin_lib targets on macOS in CMake (and split_buffer_free_test_plugin_lib in Bazel) and link them into client_test, so NOP_Create() resolves and SplitBufferPluginTest can load the split-buffer test plugin via LoadBuiltinPlugin instead of skipping on macOS. --- client/BUILD.bazel | 15 ++++++++++++--- client/CMakeLists.txt | 7 +++++++ client/client_test.cc | 24 ++++++++---------------- plugins/BUILD.bazel | 19 +++++++++++++++---- plugins/CMakeLists.txt | 42 ++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 84 insertions(+), 23 deletions(-) diff --git a/client/BUILD.bazel b/client/BUILD.bazel index 7d1ad7ba..fe96d1c8 100644 --- a/client/BUILD.bazel +++ b/client/BUILD.bazel @@ -95,9 +95,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 c49bc906..6286541b 100644 --- a/client/CMakeLists.txt +++ b/client/CMakeLists.txt @@ -45,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/client_test.cc b/client/client_test.cc index 863512fc..cf76f6ab 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 {}; @@ -9572,13 +9573,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 @@ -9595,8 +9589,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()); @@ -9614,13 +9615,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(); @@ -9629,7 +9626,6 @@ class SplitBufferPluginTest : public ::testing::Test { server_thread_.join(); server_->CleanupAfterSession(); (void)remove(socket_.c_str()); -#endif } void SetUp() override { signal(SIGPIPE, SIG_IGN); } @@ -9646,9 +9642,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(), @@ -9716,7 +9709,6 @@ TEST_F(SplitBufferPluginTest, ServerCleanupUsesPluginEndToEnd) { } } EXPECT_EQ(3, freed_slots); -#endif } int main(int argc, char **argv) { 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 98814fa8..c90d102c 100644 --- a/plugins/CMakeLists.txt +++ b/plugins/CMakeLists.txt @@ -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 ) @@ -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 From c3e247da42f3b7162e4509110857853e088d4b12 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Sun, 8 Nov 2026 13:28:43 -0800 Subject: [PATCH 11/21] Add an ASIL client stress test The ASIL client had no stress test, unlike the standard client. Add asil_client/stress_test.cc, which covers threads, the active message limit, virtual channels, many channels, and mixing with standard clients on the same channels. The active message test checks that a held payload still holds the sequence it was read with, and the many channel test fails when a subscriber makes no progress for 10 seconds, rather than spinning when its fd stays readable. Add it to Bazel as a manual test, so it runs only when named, and to the CMake build as asil_stress_test. Document it in asil-client.md. --- asil_client/BUILD.bazel | 21 + asil_client/CMakeLists.txt | 10 + asil_client/stress_test.cc | 834 +++++++++++++++++++++++++++++++++++++ docs/asil-client.md | 5 +- 4 files changed, 869 insertions(+), 1 deletion(-) create mode 100644 asil_client/stress_test.cc diff --git a/asil_client/BUILD.bazel b/asil_client/BUILD.bazel index d8e2b451..c97b9153 100644 --- a/asil_client/BUILD.bazel +++ b/asil_client/BUILD.bazel @@ -92,3 +92,24 @@ cc_test( "@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 index 0f57c417..582112fd 100644 --- a/asil_client/CMakeLists.txt +++ b/asil_client/CMakeLists.txt @@ -44,3 +44,13 @@ target_link_libraries(asil_client_test PUBLIC 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/stress_test.cc b/asil_client/stress_test.cc new file mode 100644 index 00000000..2b92b64f --- /dev/null +++ b/asil_client/stress_test.cc @@ -0,0 +1,834 @@ +// Copyright 2026 David Allison +// 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/docs/asil-client.md b/docs/asil-client.md index a15994f0..41e5b363 100644 --- a/docs/asil-client.md +++ b/docs/asil-client.md @@ -141,7 +141,10 @@ bazelisk test //asil_client:all 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`. Phaser is fetched with +`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). From d5c35c491c78d630b9988e3f6960d1a4428f5812 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Sun, 8 Nov 2026 17:19:51 -0800 Subject: [PATCH 12/21] Use IEEE CRC32 on x86 and fix asil heap-allocation test under -O2 Checksums: the x86 SSE4.2 _mm_crc32_* instructions compute CRC-32C, not the IEEE 802.3 CRC32 used by the Rust client and by every other build. Builds with SSE4.2 enabled therefore produced checksums that did not verify against the rest. x86 now always uses the IEEE lookup table. ARM hardware CRC32 is IEEE and is unchanged. Note: this changes checksum values for x86 builds with SSE4.2 enabled. Such a build will not interoperate with builds from before this change. asil_client test: the sanity-check allocation was a direct operator new, which an optimized build can lower to malloc, so the counter stayed at 0 and HandshakeMakesNoHeapAllocations failed under -O2. Call operator new through a volatile function pointer so the allocation is always counted. --- CHANGELOG.md | 7 +++++++ asil_client/asil_client_test.cc | 9 +++++++-- common/crc32.cc | 32 +++----------------------------- common/crc32.h | 7 ++++--- docs/checksums-and-metadata.md | 6 ++++-- 5 files changed, 25 insertions(+), 36 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f28bc496..903a53ff 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,13 @@ ## 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` in protobuf text format and creates its channels and multiplexers before the diff --git a/asil_client/asil_client_test.cc b/asil_client/asil_client_test.cc index df06596e..f0584020 100644 --- a/asil_client/asil_client_test.cc +++ b/asil_client/asil_client_test.cc @@ -812,10 +812,15 @@ TEST_F(AsilClientTest, CloseRemovesFromServer) { 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(); - int *volatile counted = new int(1); + void *counted = allocate(sizeof(int)); const int sanity_allocations = StopCounting(); - delete counted; + ::operator delete(counted); ASSERT_EQ(1, sanity_allocations); StartCounting(); diff --git a/common/crc32.cc b/common/crc32.cc index 5151c8d4..a60ebf5f 100644 --- a/common/crc32.cc +++ b/common/crc32.cc @@ -7,11 +7,9 @@ #include #include -#if defined(__x86_64__) && !defined(__SSE4_2__) -// On Intel crc is only available when SSE4.2 is enabled -#undef SUBSPACE_HARDWARE_CRC -#endif - +// The x86 SSE4.2 CRC32 instruction computes CRC-32C, not the IEEE 802.3 CRC32 +// used everywhere else, 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) // Swite off hardware CRC32 if it is not available on aarch64. #undef SUBSPACE_HARDWARE_CRC @@ -24,10 +22,6 @@ #if !defined(ARM_ASM_CRC32) #include #endif -#elif defined(SUBSPACE_HARDWARE_CRC) && defined(__x86_64__) -// The intrinsics headers include C library headers, which must not be inside -// a namespace. -#include #endif namespace subspace { @@ -60,26 +54,6 @@ uint32_t SubspaceCRC32(uint32_t crc, const uint8_t *data, size_t length) { } #endif // !defined(ARM_ASM_CRC32) -#elif defined(SUBSPACE_HARDWARE_CRC) && defined(__x86_64__) -uint32_t SubspaceCRC32(uint32_t crc, const uint8_t *data, size_t length) { - size_t i = 0; - // Process 8 bytes at a time. - for (; i + 8 <= length; i += 8) { - crc = _mm_crc32_u64(crc, *reinterpret_cast(data + i)); - } - // Process remaining 4 bytes. - if (i + 4 <= length) { - crc = _mm_crc32_u32(crc, *reinterpret_cast(data + i)); - i += 4; - } - - // Process remaining bytes one at a time. - for (; i < length; i++) { - crc = _mm_crc32_u8(crc, data[i]); - } - - return crc; -} #else // Vibe-coded Fast CRC32 lookup table (IEEE 802.3 polynomial: 0xEDB88320) static const uint32_t crc32_table[256] = { diff --git a/common/crc32.h b/common/crc32.h index 2e1fa947..3193a600 100644 --- a/common/crc32.h +++ b/common/crc32.h @@ -14,9 +14,10 @@ namespace subspace { -// CRC32 of a published message. x86-64 with SSE4.2 uses CRC32C; other builds -// use the IEEE 802.3 polynomial. Pass 0xFFFFFFFF as the first crc and invert -// the final result. +// 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); } diff --git a/docs/checksums-and-metadata.md b/docs/checksums-and-metadata.md index dc131d2b..0e764b29 100644 --- a/docs/checksums-and-metadata.md +++ b/docs/checksums-and-metadata.md @@ -93,8 +93,10 @@ is used: - **`VerifyCRC32Checksum()`** — recomputes CRC32 and compares against the stored 4 bytes. -These functions use ARM or x86 hardware CRC instructions when available -(`SUBSPACE_HARDWARE_CRC`), with a software fallback. +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 From 7b2245a532c70516bfec531ebd22e0b57788bba4 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Sun, 8 Nov 2026 21:01:24 -0800 Subject: [PATCH 13/21] Let standard publishers create channels beside a static config With a static channel config loaded, the server used to reject every channel the config doesn't list. Now: - Configured channels are shared by standard and ASIL clients. Publishers on them must set server_defined, as before. - A standard publisher can create an unconfigured channel by specifying its layout. The server rejects server_defined on such a channel. - Any subscriber can subscribe to an unconfigured channel, including an ASIL subscriber, which maps no buffers until a publisher creates them. - An ASIL publisher cannot create or join an unconfigured channel while a static config is loaded. The ASIL client sets InitRequest.asil to say so. The flag is advisory: the server trusts the client to set it. InitRequest gets a new field, asil = 5. Older clients don't set it and keep the standard behavior, and older servers ignore it. --- CHANGELOG.md | 8 +++-- README.md | 12 +++++-- asil_client/asil_client_test.cc | 47 ++++++++++++++++++++++++-- asil_client/phaser_connection.cc | 1 + docs/asil-client.md | 33 +++++++++++------- proto/subspace.proto | 3 ++ server/client_handler.cc | 40 +++++++++------------- server/client_handler.h | 3 ++ server/main.cc | 6 ++-- server/server.h | 7 ++-- server/static_config_test.cc | 57 +++++++++++++++++++++++--------- 11 files changed, 152 insertions(+), 65 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 903a53ff..181f34e6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,9 +12,11 @@ ### Static Channel Config - `subspace_server --channel_config=FILE` reads a `StaticChannelConfig` in protobuf text format and creates its channels and multiplexers before the - server accepts clients. Clients can then use only those channels and the - server's own, the channels stay when they have no users, and the server - defines their layout. + server accepts clients. Those 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 diff --git a/README.md b/README.md index dfc55908..257392a4 100644 --- a/README.md +++ b/README.md @@ -2052,9 +2052,15 @@ 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: -- Clients can use only the configured channels and the server's own - `/subspace/ChannelDirectory` and `/subspace/Statistics`. Creating a - publisher or subscriber for any other channel fails. +- 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 diff --git a/asil_client/asil_client_test.cc b/asil_client/asil_client_test.cc index f0584020..722ac3fc 100644 --- a/asil_client/asil_client_test.cc +++ b/asil_client/asil_client_test.cc @@ -727,9 +727,20 @@ TEST_F(AsilClientTest, Rejections) { EXPECT_THAT(Asil().LastServerError(), HasSubstr("isn't in the static channel config")); - asil::Subscriber sub; + // 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++) { @@ -1004,7 +1015,7 @@ TEST_F(AsilClientTest, ErrorsMakeNoHeapAllocations) { EXPECT_EQ(asil::Error::kServerRejected, rejected_pub); EXPECT_EQ(asil::Error::kServerRejected, unknown_pub); - EXPECT_EQ(asil::Error::kServerRejected, unknown_sub); + EXPECT_EQ(asil::Error::kNoBuffers, unknown_sub); EXPECT_EQ(asil::Error::kCapacityExceeded, long_pub); EXPECT_EQ(asil::Error::kCapacityExceeded, oversized); @@ -1584,6 +1595,38 @@ TEST_F(AsilClientTest, SplitRejections) { 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, diff --git a/asil_client/phaser_connection.cc b/asil_client/phaser_connection.cc index 914b22e1..76f56935 100644 --- a/asil_client/phaser_connection.cc +++ b/asil_client/phaser_connection.cc @@ -395,6 +395,7 @@ Error PhaserServerConnection::Init(const char *client_name, InitReply &reply) { [&](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)); diff --git a/docs/asil-client.md b/docs/asil-client.md index 41e5b363..b2948ede 100644 --- a/docs/asil-client.md +++ b/docs/asil-client.md @@ -7,9 +7,14 @@ 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), where every -channel exists before any client connects and keeps a fixed layout, gives a -safety case the most predictable setup. +[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 @@ -70,11 +75,13 @@ The ASIL client shares channels with the standard clients for: 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 -static channel's buffers when it starts, so ASIL publishers and subscribers -can open in any order. On a server that creates channels on demand, a -channel has buffers once its first publisher opens. Until then an ASIL -subscriber's `Open()` returns `Error::kNoBuffers`. An ASIL publisher that is -first on such a channel creates its buffer. +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 @@ -264,8 +271,9 @@ On a static channel the server defines the layout. The publisher sets `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, or if `server_defined` is set and the channel isn't static. The -publisher then takes its layout from the server: +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; @@ -375,8 +383,9 @@ 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 and -subscribers that open before any publisher. A second server creates channels +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 diff --git a/proto/subspace.proto b/proto/subspace.proto index 105c3efa..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 diff --git a/server/client_handler.cc b/server/client_handler.cc index 30b07e81..cb934590 100644 --- a/server/client_handler.cc +++ b/server/client_handler.cc @@ -14,22 +14,6 @@ namespace subspace { namespace { -// With a static channel config, clients can't create channels other than the -// server's own. Sets the response error and returns false for one they -// can't create. -template -bool StaticConfigAllowsNewChannel(const Server &server, - std::string_view channel_name, - Response *response) { - if (!server.HasStaticChannelConfig() || - Server::IsServerChannelName(std::string(channel_name))) { - return true; - } - response->set_error(absl::StrFormat( - "Channel %s isn't in the static channel config", channel_name)); - return false; -} - ClientBufferAllocatorKind FromProtoAllocator(int allocator) { switch (allocator) { case CLIENT_BUFFER_ALLOCATOR_ANDROID_MEMFD: @@ -377,6 +361,7 @@ void ClientHandler::HandleInit(const subspace::phaser::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()); @@ -403,6 +388,17 @@ void ClientHandler::HandleCreatePublisher( 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; @@ -548,10 +544,6 @@ void ClientHandler::HandleCreatePublisher( absl::StrFormat("No such channel %s", req.channel_name())); return; } - if (channel == nullptr && - !StaticConfigAllowsNewChannel(*server_, req.channel_name(), response)) { - return; - } if (channel == nullptr) { server_->logger_.Log(toolbelt::LogLevel::kDebug, "Publisher %s is creating new channel %s with size " @@ -997,11 +989,9 @@ void ClientHandler::HandleCreateSubscriber( return; } if (channel == nullptr) { - if (!StaticConfigAllowsNewChannel(*server_, req.channel_name(), - response)) { - return; - } - // 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 " diff --git a/server/client_handler.h b/server/client_handler.h index d6a94817..015a51a1 100644 --- a/server/client_handler.h +++ b/server/client_handler.h @@ -80,6 +80,9 @@ class ClientHandler { 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/main.cc b/server/main.cc index fa4028e8..c3aa43d4 100644 --- a/server/main.cc +++ b/server/main.cc @@ -98,8 +98,10 @@ ABSL_FLAG(std::string, secondary_shadow_socket, "", "Secondary shadow process Unix socket (empty = disabled)"); ABSL_FLAG(std::string, channel_config, "", "StaticChannelConfig file in protobuf text format. The server " - "creates its channels at startup, fixes their layout and allows no " - "others (empty = channels are created on demand)"); + "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."); diff --git a/server/server.h b/server/server.h index 7fc98876..176bf852 100644 --- a/server/server.h +++ b/server/server.h @@ -132,8 +132,11 @@ class Server { void SetShadowSockets(const std::string &primary, const std::string &secondary); // Call before Run(). Run() creates the configured channels before it - // accepts any clients, and from then on clients can use only those channels - // and the server's own. Fails if the config isn't valid. + // 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 diff --git a/server/static_config_test.cc b/server/static_config_test.cc index 1c173a34..10da2666 100644 --- a/server/static_config_test.cc +++ b/server/static_config_test.cc @@ -3,8 +3,9 @@ // See LICENSE file for licensing information. // Tests for a server started with a static channel config: the configured -// channels exist before any client connects, they are the only channels -// clients can use, and their layout is fixed. +// 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" @@ -437,25 +438,49 @@ TEST_F(StaticConfigTest, PublisherTakesLayoutFromServer) { ASSERT_OK(second); } -TEST_F(StaticConfigTest, UnconfiguredChannelsAreRejected) { - absl::StatusOr pub = +TEST_F(StaticConfigTest, UnconfiguredChannels) { + // server_defined is only for a channel the config created. + absl::StatusOr defined = Client().CreatePublisher("/not/configured", ServerDefined()); - ASSERT_FALSE(pub.ok()); - EXPECT_THAT(pub.status().message(), + ASSERT_FALSE(defined.ok()); + EXPECT_THAT(defined.status().message(), HasSubstr("isn't in the static channel config")); - absl::StatusOr sub = - Client().CreateSubscriber("/not/configured"); - ASSERT_FALSE(sub.ok()); - EXPECT_THAT(sub.status().message(), + // 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 virtual channel on a configured multiplexer must be configured too. - pub = Client().CreatePublisher("/static/v9", - ServerDefined().SetMux("/static/mux")); - ASSERT_FALSE(pub.ok()); - EXPECT_THAT(pub.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) { From f5098a1e5f9e5f9077dc1fc3a6c9ea8bcd61d26b Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Mon, 9 Nov 2026 11:51:22 -0800 Subject: [PATCH 14/21] ASIL client: one 16 KB buffer size for server messages PhaserServerConnection can be constructed with a larger wire buffer size for a channel whose handshake needs more room. The decoded message buffer was a fixed 32 KB, twice the wire buffer. That spare space is never needed: the wire buffer carries the message's ByteSizeLong(), and a message that fills the arena cannot be larger than that. So the message buffer now has the same size as the wire buffer. - The default object keeps both buffers inside the object, 16 KB each. - A larger size allocates both once in the constructor, with the message buffer rounded up to 8 bytes so the wire buffer stays aligned. - Responses that do not fit the wire buffer are still drained, so the stream stays in step. Allocation failure reports kCapacityExceeded. - Adds a test that a 64 KB connection sends and receives a request the default connection cannot hold, with no heap allocations. --- asil_client/asil_client_test.cc | 25 ++++++++++++ asil_client/client.h | 2 + asil_client/phaser_connection.cc | 70 ++++++++++++++++++++++++++++++-- asil_client/phaser_connection.h | 36 +++++++++++----- common/server_wire.h | 37 +++++++++++++++++ docs/asil-client.md | 22 ++++++---- 6 files changed, 171 insertions(+), 21 deletions(-) diff --git a/asil_client/asil_client_test.cc b/asil_client/asil_client_test.cc index 722ac3fc..f45859a0 100644 --- a/asil_client/asil_client_test.cc +++ b/asil_client/asil_client_test.cc @@ -1030,6 +1030,31 @@ TEST_F(AsilClientTest, ErrorsMakeNoHeapAllocations) { 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; diff --git a/asil_client/client.h b/asil_client/client.h index 9215bfab..44f837ec 100644 --- a/asil_client/client.h +++ b/asil_client/client.h @@ -12,6 +12,8 @@ // 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; diff --git a/asil_client/phaser_connection.cc b/asil_client/phaser_connection.cc index 76f56935..7c916967 100644 --- a/asil_client/phaser_connection.cc +++ b/asil_client/phaser_connection.cc @@ -11,6 +11,8 @@ #include #include #include +#include +#include #include #include #include @@ -113,8 +115,58 @@ Error FillFdList(const PhaserServerConnection::ReceivedFds &fds, size_t count, 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_; + 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() - 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_ + 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_; + 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) { @@ -230,10 +282,17 @@ Error PhaserServerConnection::Receive(const char *&data, size_t &length) { ? Error::kOk : Error::kConnectionFailed; } - char *const scratch = wire_.ResponseBuffer(kWireBufferSize); + // 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 < kWireBufferSize ? remaining : kWireBufferSize; + const size_t chunk = remaining < scratch_size ? remaining : scratch_size; if (!ReceiveFully(socket_.Get(), scratch, chunk)) { return Error::kConnectionFailed; } @@ -321,6 +380,11 @@ Error PhaserServerConnection::ReceiveFds() { // 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; } diff --git a/asil_client/phaser_connection.h b/asil_client/phaser_connection.h index 78f05833..42891d85 100644 --- a/asil_client/phaser_connection.h +++ b/asil_client/phaser_connection.h @@ -9,32 +9,40 @@ #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 with fixed -// buffers inside this object, the same encoding as the standard client uses, -// so a handshake makes no heap allocations, even when it fails. A request or +// 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 object holds about 60 KB of buffers, so keep it in static storage or -// inside a long-lived object rather than on a small stack. +// 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: - // Native Phaser payload bytes for one request or response. + // 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; - // The decoded request or response. - static constexpr size_t kMessageBufferSize = 32 * 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() = default; ~PhaserServerConnection() override = default; PhaserServerConnection(const PhaserServerConnection &) = delete; @@ -79,7 +87,15 @@ class PhaserServerConnection : public ServerConnection { UniqueFd socket_; ReceivedFds fds_; char last_error_[256] = {}; - ServerWire> wire_; + 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_[kServerWireHeaderSize + kWireBufferSize]; + ServerWire wire_; }; } // namespace asil diff --git a/common/server_wire.h b/common/server_wire.h index 3116caff..ed07eca2 100644 --- a/common/server_wire.h +++ b/common/server_wire.h @@ -12,6 +12,7 @@ #include #include #include +#include #include namespace subspace { @@ -67,6 +68,39 @@ template class FixedServerWireBuffers { alignas(8) char wire_[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; @@ -115,6 +149,9 @@ inline absl::Status PermanentError(absl::StatusCode code, 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(); diff --git a/docs/asil-client.md b/docs/asil-client.md index b2948ede..25d243d1 100644 --- a/docs/asil-client.md +++ b/docs/asil-client.md @@ -45,8 +45,10 @@ publisher can create a channel by specifying its layout. 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. Exceeding any of these - returns `Error::kCapacityExceeded`. `max_active_messages` is at most 64. + 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. @@ -180,12 +182,16 @@ descriptors passed by `SCM_RIGHTS`. The server receives the same bytes it receives from the standard clients. Requests and responses are encoded by `ServerWire` in `common/server_wire.h`, which the standard C++ client uses too. The standard client gives it growable buffers. The ASIL connection -gives it fixed buffers inside the object: it builds each request as a phaser -message in a fixed buffer, copies that payload onto the socket, and loads the -response into the same buffer, so it needs neither the protobuf library nor -the heap. The buffers take about 60 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 +gives it fixed buffers: it builds each request as a phaser message in a +fixed buffer, copies that payload onto the socket, and loads the response +into the same buffer, so it needs neither the protobuf library nor the heap +while it talks to the server. 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 From ffe9bf971a3923b31a2d62fd74beac9565937deb Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Mon, 9 Nov 2026 13:18:02 -0800 Subject: [PATCH 15/21] Correct asil-client.md for the zero-copy protocol and channel creation - 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. - The server handshake is a 4-byte length followed by the Phaser message buffer itself (Data() / ByteSizeLong()), the same bytes the standard C++ and Rust clients send. The ASIL connection keeps that message in fixed buffers, 16 KB by default. - The example gives each channel its layout, so it applies to a server with no static config, and points at server_defined for a configured channel. --- docs/asil-client.md | 45 +++++++++++++++++++++++++-------------------- 1 file changed, 25 insertions(+), 20 deletions(-) diff --git a/docs/asil-client.md b/docs/asil-client.md index 25d243d1..a67982cd 100644 --- a/docs/asil-client.md +++ b/docs/asil-client.md @@ -37,10 +37,12 @@ publisher can create a channel by specifying its layout. 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()`, and creates - shared memory only when an ASIL publisher is the first on a channel that - isn't static. Publishing and reading make no `mmap`, `shm_open` or other - shared memory calls. After `Open()` the server is involved only when a + 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 @@ -177,25 +179,28 @@ 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: -length-prefixed native Phaser payloads on the server's Unix socket, with file -descriptors passed by `SCM_RIGHTS`. The server receives the same bytes it -receives from the standard clients. Requests and responses are encoded by -`ServerWire` in `common/server_wire.h`, which the standard C++ client uses -too. The standard client gives it growable buffers. The ASIL connection -gives it fixed buffers: it builds each request as a phaser message in a -fixed buffer, copies that payload onto the socket, and loads the response -into the same buffer, so it needs neither the protobuf library nor the heap -while it talks to the server. 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`. +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" From 0950b1edb1e2a6181c913b735b804523937e7b32 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Mon, 9 Nov 2026 13:18:03 -0800 Subject: [PATCH 16/21] Add General Motors copyright and rename the copyright holder Add a General Motors copyright line under the existing header in the ASIL client sources and the new common/ files that the ASIL client shares with the standard client. Rename "General Motors LLC" and "General Motors Inc." to "General Motors" everywhere in the repository. Only comments, copyright headers and documentation change. --- README.md | 2 +- android/CMakeLists.txt | 2 +- android/java/BUILD.bazel | 2 +- android/java/com/subspace/test/SubspaceJavaClientTest.java | 2 +- android/java/subspace_java_client_test.sh | 2 +- asil_client/Android.bp | 1 + asil_client/asil_client_test.cc | 1 + asil_client/channel_memory.cc | 1 + asil_client/channel_memory.h | 1 + asil_client/client.cc | 1 + asil_client/client.h | 1 + asil_client/error.cc | 1 + asil_client/error.h | 1 + asil_client/layout_test.cc | 1 + asil_client/phaser_connection.cc | 1 + asil_client/phaser_connection.h | 1 + asil_client/publisher.cc | 1 + asil_client/publisher.h | 1 + asil_client/server_connection.h | 1 + asil_client/shm_layout.h | 1 + asil_client/split_buffer.h | 1 + asil_client/stress_test.cc | 1 + asil_client/subscriber.cc | 1 + asil_client/subscriber.h | 1 + asil_client/unique_fd.h | 1 + common/arm_crc32.S | 1 + common/async/async_test.cc | 2 +- common/async/socket.cc | 2 +- common/async/socket.h | 2 +- common/async/wait.cc | 2 +- common/async/wait.h | 2 +- common/bitset_view.h | 1 + common/channel_view.h | 1 + common/crc32.cc | 1 + common/crc32.h | 1 + common/dynamic_bitset.h | 1 + common/message_checksum.h | 1 + common/publish.h | 1 + common/server_wire.h | 1 + common/shm_layout.h | 1 + common/slot_search.h | 1 + common/subscribe.h | 1 + proto/tunnel_config.proto | 2 +- proto/tunnel_discovery.proto | 2 +- proto/tunnel_handshake.proto | 2 +- server/main.cc | 2 +- server/plugin_bridge_test.cc | 2 +- server/server.cc | 2 +- server/server.h | 2 +- server/server_bridge.cc | 2 +- server/server_bridge_receiver.cc | 2 +- server/server_bridge_transmitter.cc | 2 +- server/server_channels.cc | 2 +- server/server_discovery.cc | 2 +- server/server_plugins.cc | 2 +- server/server_shadow.cc | 2 +- server/server_telemetry.cc | 2 +- server/tunnel.cc | 2 +- server/tunnel.h | 2 +- server/tunnel_config.cc | 2 +- server/tunnel_config.h | 2 +- server/tunnel_config_test.cc | 2 +- server/tunnel_fake_peer_test.cc | 2 +- server/tunnel_protocol.cc | 2 +- server/tunnel_protocol.h | 2 +- server/tunnel_protocol_test.cc | 2 +- server/tunnel_stress_test.cc | 2 +- server/tunnel_test.cc | 2 +- server/tunnel_test_util.h | 2 +- 69 files changed, 69 insertions(+), 37 deletions(-) diff --git a/README.md b/README.md index 257392a4..c9b106cf 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,7 @@ transported over the network at sub-light speed. ## Acknowledgments Some of the code in this project was contributed by Cruise LLC and by -General Motors Inc. +General Motors. ## Features 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 index 4847610f..f186b638 100644 --- a/asil_client/Android.bp +++ b/asil_client/Android.bp @@ -1,4 +1,5 @@ // Copyright 2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/asil_client/asil_client_test.cc b/asil_client/asil_client_test.cc index f45859a0..6f4da48a 100644 --- a/asil_client/asil_client_test.cc +++ b/asil_client/asil_client_test.cc @@ -1,4 +1,5 @@ // Copyright 2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/asil_client/channel_memory.cc b/asil_client/channel_memory.cc index a52af49e..84646666 100644 --- a/asil_client/channel_memory.cc +++ b/asil_client/channel_memory.cc @@ -1,4 +1,5 @@ // Copyright 2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/asil_client/channel_memory.h b/asil_client/channel_memory.h index 6d12ecca..e49a3067 100644 --- a/asil_client/channel_memory.h +++ b/asil_client/channel_memory.h @@ -1,4 +1,5 @@ // Copyright 2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/asil_client/client.cc b/asil_client/client.cc index 3d97ab53..c4f50290 100644 --- a/asil_client/client.cc +++ b/asil_client/client.cc @@ -1,4 +1,5 @@ // Copyright 2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/asil_client/client.h b/asil_client/client.h index 44f837ec..44f9be30 100644 --- a/asil_client/client.h +++ b/asil_client/client.h @@ -1,4 +1,5 @@ // Copyright 2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/asil_client/error.cc b/asil_client/error.cc index 8b672716..b8b11661 100644 --- a/asil_client/error.cc +++ b/asil_client/error.cc @@ -1,4 +1,5 @@ // Copyright 2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/asil_client/error.h b/asil_client/error.h index 58290ad8..e4bf179a 100644 --- a/asil_client/error.h +++ b/asil_client/error.h @@ -1,4 +1,5 @@ // Copyright 2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/asil_client/layout_test.cc b/asil_client/layout_test.cc index 0ba3c1df..9e0382f9 100644 --- a/asil_client/layout_test.cc +++ b/asil_client/layout_test.cc @@ -1,4 +1,5 @@ // Copyright 2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/asil_client/phaser_connection.cc b/asil_client/phaser_connection.cc index 7c916967..51199151 100644 --- a/asil_client/phaser_connection.cc +++ b/asil_client/phaser_connection.cc @@ -1,4 +1,5 @@ // Copyright 2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/asil_client/phaser_connection.h b/asil_client/phaser_connection.h index 42891d85..948c9f30 100644 --- a/asil_client/phaser_connection.h +++ b/asil_client/phaser_connection.h @@ -1,4 +1,5 @@ // Copyright 2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/asil_client/publisher.cc b/asil_client/publisher.cc index 60354fe2..dd381a4b 100644 --- a/asil_client/publisher.cc +++ b/asil_client/publisher.cc @@ -1,4 +1,5 @@ // Copyright 2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/asil_client/publisher.h b/asil_client/publisher.h index f224dc31..daa8bc36 100644 --- a/asil_client/publisher.h +++ b/asil_client/publisher.h @@ -1,4 +1,5 @@ // Copyright 2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/asil_client/server_connection.h b/asil_client/server_connection.h index fd2b9054..3fe8a4c7 100644 --- a/asil_client/server_connection.h +++ b/asil_client/server_connection.h @@ -1,4 +1,5 @@ // Copyright 2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/asil_client/shm_layout.h b/asil_client/shm_layout.h index 30abfe00..09f1dfe6 100644 --- a/asil_client/shm_layout.h +++ b/asil_client/shm_layout.h @@ -1,4 +1,5 @@ // Copyright 2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/asil_client/split_buffer.h b/asil_client/split_buffer.h index 8a7d131c..1d320c08 100644 --- a/asil_client/split_buffer.h +++ b/asil_client/split_buffer.h @@ -1,4 +1,5 @@ // Copyright 2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/asil_client/stress_test.cc b/asil_client/stress_test.cc index 2b92b64f..cf91b333 100644 --- a/asil_client/stress_test.cc +++ b/asil_client/stress_test.cc @@ -1,4 +1,5 @@ // Copyright 2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/asil_client/subscriber.cc b/asil_client/subscriber.cc index e7118953..b7dab53d 100644 --- a/asil_client/subscriber.cc +++ b/asil_client/subscriber.cc @@ -1,4 +1,5 @@ // Copyright 2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/asil_client/subscriber.h b/asil_client/subscriber.h index d92679e2..4c674616 100644 --- a/asil_client/subscriber.h +++ b/asil_client/subscriber.h @@ -1,4 +1,5 @@ // Copyright 2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/asil_client/unique_fd.h b/asil_client/unique_fd.h index fbc39744..19cc30c2 100644 --- a/asil_client/unique_fd.h +++ b/asil_client/unique_fd.h @@ -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/arm_crc32.S b/common/arm_crc32.S index 7edefc85..c861b235 100644 --- a/common/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/bitset_view.h b/common/bitset_view.h index d8efd6c7..db149476 100644 --- a/common/bitset_view.h +++ b/common/bitset_view.h @@ -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/channel_view.h b/common/channel_view.h index bbd025ba..bd7e5394 100644 --- a/common/channel_view.h +++ b/common/channel_view.h @@ -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/crc32.cc b/common/crc32.cc index a60ebf5f..bee65a17 100644 --- a/common/crc32.cc +++ b/common/crc32.cc @@ -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/crc32.h b/common/crc32.h index 3193a600..df5463a1 100644 --- a/common/crc32.h +++ b/common/crc32.h @@ -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/dynamic_bitset.h b/common/dynamic_bitset.h index 253576a7..5a685978 100644 --- a/common/dynamic_bitset.h +++ b/common/dynamic_bitset.h @@ -1,4 +1,5 @@ // Copyright 2023-2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. // diff --git a/common/message_checksum.h b/common/message_checksum.h index 1f887e53..f75395c9 100644 --- a/common/message_checksum.h +++ b/common/message_checksum.h @@ -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/publish.h b/common/publish.h index eab3801b..6acc090b 100644 --- a/common/publish.h +++ b/common/publish.h @@ -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/server_wire.h b/common/server_wire.h index ed07eca2..403211ee 100644 --- a/common/server_wire.h +++ b/common/server_wire.h @@ -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/shm_layout.h b/common/shm_layout.h index d80f9125..155dc89e 100644 --- a/common/shm_layout.h +++ b/common/shm_layout.h @@ -1,4 +1,5 @@ // Copyright 2023-2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. diff --git a/common/slot_search.h b/common/slot_search.h index 8eaedc46..53954823 100644 --- a/common/slot_search.h +++ b/common/slot_search.h @@ -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/subscribe.h b/common/subscribe.h index 7b47c1b3..8aa1e66e 100644 --- a/common/subscribe.h +++ b/common/subscribe.h @@ -1,4 +1,5 @@ // Copyright 2026 David Allison +// Copyright 2026 General Motors // All Rights Reserved // See LICENSE file for licensing information. 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/server/main.cc b/server/main.cc index c3aa43d4..cb06912a 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. 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 8a16b830..ee198b12 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" diff --git a/server/server.h b/server/server.h index 176bf852..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. 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 46fd383c..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" 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_channels.cc b/server/server_channels.cc index b7841c37..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" diff --git a/server/server_discovery.cc b/server/server_discovery.cc index 4aafb192..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" 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/tunnel.cc b/server/tunnel.cc index 9ff404f0..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. 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..f2577161 100644 --- a/server/tunnel_config.cc +++ b/server/tunnel_config.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_config.h b/server/tunnel_config.h index 658f7542..958fc65f 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. diff --git a/server/tunnel_config_test.cc b/server/tunnel_config_test.cc index b59bb821..12b06e60 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. 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. From 55a8be50594c79097cb245d72d2be466565aa8dc Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Mon, 9 Nov 2026 13:54:25 -0800 Subject: [PATCH 17/21] Accept protobuf wire format for static and tunnel configs --channel_config and --tunnel_config now read a protobuf wire-format file as well as text. The extension decides: a name ending in .pb or .binpb (ignoring case) is wire format, and any other name is text, so existing files keep working. The wire format is strict like the text format. A message with a field this build doesn't know, at any depth, is rejected rather than having the field dropped. Both files are read in binary mode. - server/config_format.h: ConfigFileIsText and HasUnknownFields. - Tests: the extension selects the format, a wire file is rejected when read as text and the reverse, and unknown fields are rejected. - Docs: README, docs/tunnel.md, CHANGELOG and the flag help. --- CHANGELOG.md | 16 +++--- README.md | 6 ++- docs/tunnel.md | 2 +- server/BUILD.bazel | 2 + server/CMakeLists.txt | 1 + server/config_format.h | 74 ++++++++++++++++++++++++++ server/main.cc | 11 ++-- server/static_config.cc | 46 +++++++++++++--- server/static_config.h | 3 +- server/static_config_test.cc | 100 +++++++++++++++++++++++++++++++++++ server/tunnel_config.cc | 18 ++++++- server/tunnel_config.h | 3 +- server/tunnel_config_test.cc | 67 +++++++++++++++++++++++ 13 files changed, 324 insertions(+), 25 deletions(-) create mode 100644 server/config_format.h diff --git a/CHANGELOG.md b/CHANGELOG.md index 181f34e6..f5662cd5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,11 +10,13 @@ unchanged. ### Static Channel Config -- `subspace_server --channel_config=FILE` reads a `StaticChannelConfig` in - protobuf text format and creates its channels and multiplexers before the - server accepts clients. Those 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 +- `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 @@ -138,8 +140,8 @@ ### 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, + `--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 diff --git a/README.md b/README.md index c9b106cf..3f016e6f 100644 --- a/README.md +++ b/README.md @@ -2032,7 +2032,9 @@ hand against servers on two different computers. 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`) in protobuf text format: +(`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" } @@ -2169,7 +2171,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` text format file. See [Static Channel Config](#static-channel-config). | +| `--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/docs/tunnel.md b/docs/tunnel.md index 9f4f6d30..1aa89196 100644 --- a/docs/tunnel.md +++ b/docs/tunnel.md @@ -65,7 +65,7 @@ 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 diff --git a/server/BUILD.bazel b/server/BUILD.bazel index 36c6b1e0..0537133f 100644 --- a/server/BUILD.bazel +++ b/server/BUILD.bazel @@ -26,6 +26,7 @@ cc_library( "server_channel.h", "plugin.h", "shadow_replicator.h", + "config_format.h", "static_config.h", "tunnel.h", ], @@ -57,6 +58,7 @@ cc_library( "tunnel_protocol.cc", ], hdrs = [ + "config_format.h", "tunnel_config.h", "tunnel_protocol.h", ], diff --git a/server/CMakeLists.txt b/server/CMakeLists.txt index dcbf221c..39dc103a 100644 --- a/server/CMakeLists.txt +++ b/server/CMakeLists.txt @@ -7,6 +7,7 @@ add_library(libserver STATIC server_channel.h shadow_replicator.cc shadow_replicator.h + config_format.h static_config.cc static_config.h server.cc 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 cb06912a..d19c46af 100644 --- a/server/main.cc +++ b/server/main.cc @@ -97,8 +97,10 @@ ABSL_FLAG(std::string, shadow_socket, "", ABSL_FLAG(std::string, secondary_shadow_socket, "", "Secondary shadow process Unix socket (empty = disabled)"); ABSL_FLAG(std::string, channel_config, "", - "StaticChannelConfig file in protobuf text format. The server " - "creates those channels at startup and fixes their layout. Standard " + "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)"); @@ -106,8 +108,9 @@ 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."); diff --git a/server/static_config.cc b/server/static_config.cc index 42b63e18..287fb635 100644 --- a/server/static_config.cc +++ b/server/static_config.cc @@ -4,6 +4,8 @@ #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" @@ -12,6 +14,7 @@ #include "google/protobuf/text_format.h" #include #include +#include namespace subspace { @@ -136,17 +139,46 @@ ParseStaticChannelConfig(const std::string &text) { return config; } -absl::StatusOr -ReadStaticChannelConfig(const std::string &filename) { - std::ifstream in(filename); +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 text; - text << in.rdbuf(); - absl::StatusOr config = - ParseStaticChannelConfig(text.str()); + 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, diff --git a/server/static_config.h b/server/static_config.h index e3fe8d02..98afc47e 100644 --- a/server/static_config.h +++ b/server/static_config.h @@ -20,7 +20,8 @@ inline constexpr char kServerChannelPrefix[] = "/subspace/"; absl::StatusOr ParseStaticChannelConfig(const std::string &text); -// Reads, parses and validates a StaticChannelConfig text format file. +// 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); diff --git a/server/static_config_test.cc b/server/static_config_test.cc index 10da2666..8d8660d9 100644 --- a/server/static_config_test.cc +++ b/server/static_config_test.cc @@ -19,13 +19,16 @@ #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( @@ -243,6 +246,103 @@ TEST(StaticConfigParseTest, RejectsInvalidConfigs) { } } +// 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"); diff --git a/server/tunnel_config.cc b/server/tunnel_config.cc index f2577161..d2b6a005 100644 --- a/server/tunnel_config.cc +++ b/server/tunnel_config.cc @@ -4,6 +4,8 @@ #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 958fc65f..99704a26 100644 --- a/server/tunnel_config.h +++ b/server/tunnel_config.h @@ -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 12b06e60..151d0c23 100644 --- a/server/tunnel_config_test.cc +++ b/server/tunnel_config_test.cc @@ -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 From 6e2de6641269b222273dfb1a93c84c2e4c9e1ca5 Mon Sep 17 00:00:00 2001 From: Dave Allison Date: Mon, 9 Nov 2026 13:58:48 -0800 Subject: [PATCH 18/21] Document the wire-format static and tunnel configs - README and docs/tunnel.md: show protoc --encode for producing a .pb file from a text config, and say that unknown fields are rejected in either format. - docs/server-architecture.md: list static_config and config_format.h. - CHANGELOG: rewrap the tunnel_config entry. --- CHANGELOG.md | 5 +++-- README.md | 11 +++++++++++ docs/server-architecture.md | 2 ++ docs/tunnel.md | 11 +++++++++++ 4 files changed, 27 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f5662cd5..e35a91f8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -141,8 +141,9 @@ - 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 - 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 + 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/README.md b/README.md index 3f016e6f..c6688053 100644 --- a/README.md +++ b/README.md @@ -2043,6 +2043,17 @@ 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 diff --git a/docs/server-architecture.md b/docs/server-architecture.md index 70aa5f72..2ac05244 100644 --- a/docs/server-architecture.md +++ b/docs/server-architecture.md @@ -295,6 +295,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 1aa89196..84eb0732 100644 --- a/docs/tunnel.md +++ b/docs/tunnel.md @@ -71,6 +71,17 @@ Two command line flags control the tunnel: 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. From bfe7a2560ef6a33f74f698b4a6e1004b91a8bb00 Mon Sep 17 00:00:00 2001 From: David Allison Date: Sun, 22 Nov 2026 16:31:28 -0800 Subject: [PATCH 19/21] Fix the armhf CMake cross-compile by supplying a host protoc-gen-phaser. The clients now generate Phaser messages, so configure fails unless the host plugin is built and passed in PHASER_PLUGIN_EXECUTABLE. --- .cursor/skills/subspace-builds/SKILL.md | 9 +++++---- .github/workflows/ci.yml | 5 +++-- README.md | 4 ++-- scripts/build-arm32-colima.sh | 14 ++++++++------ 4 files changed, 18 insertions(+), 14 deletions(-) diff --git a/.cursor/skills/subspace-builds/SKILL.md b/.cursor/skills/subspace-builds/SKILL.md index 442f0723..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 ``` diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 75f01342..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 diff --git a/README.md b/README.md index 6eb82f64..9809f89a 100644 --- a/README.md +++ b/README.md @@ -97,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 @@ -108,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`. 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 From 083d70779409e6efbc863b1d1cbb6c9fd43932f6 Mon Sep 17 00:00:00 2001 From: David Allison Date: Sun, 22 Nov 2026 17:27:15 -0800 Subject: [PATCH 20/21] Let the ASIL client build for 32-bit ARM. The shared-memory layout is already padded for armhf, so the pointer-size assert was rejecting a target the protocol supports. --- asil_client/shm_layout.h | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/asil_client/shm_layout.h b/asil_client/shm_layout.h index 124dd944..2f8e8a8c 100644 --- a/asil_client/shm_layout.h +++ b/asil_client/shm_layout.h @@ -4,7 +4,8 @@ // 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. +// 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 @@ -14,8 +15,6 @@ namespace subspace { namespace asil { namespace shm { -static_assert(sizeof(void *) == 8, "Subspace shared memory needs 64 bits"); - using ::subspace::ActivationTracker; using ::subspace::AvailableSlotQueueIndex; using ::subspace::AvailableSlotsOffset; From 3c79a695ae19421977c2f323eadafac3440c5c51 Mon Sep 17 00:00:00 2001 From: David Allison Date: Sun, 22 Nov 2026 18:17:02 -0800 Subject: [PATCH 21/21] Fix 32-bit ARM alignment bugs in BitsetView, Phaser, and wire buffers. --- CMakeLists.txt | 8 ++- MODULE.bazel | 5 +- asil_client/asil_client_test.cc | 13 ++++ asil_client/phaser_connection.cc | 12 ++-- asil_client/phaser_connection.h | 3 +- cmake/apply_patch.cmake | 23 +++++++ common/bitset_view.h | 2 +- common/server_wire.h | 10 ++- patches/phaser_armhf_payload_buffer.patch | 84 +++++++++++++++++++++++ 9 files changed, 147 insertions(+), 13 deletions(-) create mode 100644 cmake/apply_patch.cmake create mode 100644 patches/phaser_armhf_payload_buffer.patch diff --git a/CMakeLists.txt b/CMakeLists.txt index 4c043c8b..9eee8851 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -242,9 +242,13 @@ FetchContent_MakeAvailable(protobuf) FetchContent_Declare( phaser GIT_REPOSITORY https://github.com/dallison/phaser.git - # phaser 3.1.1 with the CMake build fixes in dallison/phaser#22, as in the - # git_override in MODULE.bazel. + # 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) diff --git a/MODULE.bazel b/MODULE.bazel index 14b04930..589bb24d 100644 --- a/MODULE.bazel +++ b/MODULE.bazel @@ -64,8 +64,11 @@ 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. + # 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", ) diff --git a/asil_client/asil_client_test.cc b/asil_client/asil_client_test.cc index 6f4da48a..6a9cf25d 100644 --- a/asil_client/asil_client_test.cc +++ b/asil_client/asil_client_test.cc @@ -30,6 +30,7 @@ #include #include #include +#include #include #include #include @@ -256,6 +257,18 @@ asil::PublisherOptions StaticPubOptions() { 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 diff --git a/asil_client/phaser_connection.cc b/asil_client/phaser_connection.cc index 51199151..c3687787 100644 --- a/asil_client/phaser_connection.cc +++ b/asil_client/phaser_connection.cc @@ -137,28 +137,28 @@ PhaserServerConnection::PhaserServerConnection(size_t wire_buffer_size) : wire_buffer_size), message_buffer_size_(MessageCapacity(wire_buffer_size_)) { char *message = embedded_message_; - char *wire = embedded_wire_; + 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() - kServerWireHeaderSize - - wire_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_ + kServerWireHeaderSize + wire_buffer_size_; + 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_; + wire = allocated_.get() + message_buffer_size_ + kServerWireHeaderPad; message_capacity = message_buffer_size_; } } else if (wire_buffer_size_ < kWireBufferSize) { diff --git a/asil_client/phaser_connection.h b/asil_client/phaser_connection.h index 948c9f30..6b784ddd 100644 --- a/asil_client/phaser_connection.h +++ b/asil_client/phaser_connection.h @@ -95,7 +95,8 @@ class PhaserServerConnection : public ServerConnection { // the embedded arrays. Empty for the default size. std::unique_ptr allocated_; alignas(8) char embedded_message_[kWireBufferSize]; - alignas(8) char embedded_wire_[kServerWireHeaderSize + kWireBufferSize]; + alignas(8) char + embedded_wire_[kServerWireHeaderPad + kServerWireHeaderSize + kWireBufferSize]; ServerWire wire_; }; 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/bitset_view.h b/common/bitset_view.h index db149476..96cfc623 100644 --- a/common/bitset_view.h +++ b/common/bitset_view.h @@ -21,7 +21,7 @@ class BitsetView { BitsetView() = default; BitsetView(void *bitset, int num_bits) : words_(reinterpret_cast *>( - static_cast(bitset) + sizeof(size_t))), + static_cast(bitset) + sizeof(InPlaceAtomicBitset))), num_bits_(num_bits) {} void Set(int bit) { diff --git a/common/server_wire.h b/common/server_wire.h index 403211ee..47d4f219 100644 --- a/common/server_wire.h +++ b/common/server_wire.h @@ -40,6 +40,10 @@ namespace subspace { // 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: @@ -62,11 +66,13 @@ template class FixedServerWireBuffers { } // Room for the header and length bytes after it, or nullptr. - char *Wire(size_t length) { return length <= kWireSize ? wire_ : nullptr; } + char *Wire(size_t length) { + return length <= kWireSize ? wire_ + kServerWireHeaderPad : nullptr; + } private: alignas(8) char message_[kMessageSize]; - alignas(8) char wire_[kServerWireHeaderSize + kWireSize]; + alignas(8) char wire_[kServerWireHeaderPad + kServerWireHeaderSize + kWireSize]; }; // Message and wire storage the caller owns. The wire pointer addresses the 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);