diff --git a/CHANGELOG.md b/CHANGELOG.md index 9dba454..d991526 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,11 +2,61 @@ PuppetMaster follows [Semantic Versioning](https://semver.org/). Before 1.0, each minor release may break the API and the ABI: the shared libraries carry -the minor version in their soname (`libpuppet_master.so.0.2`), and -`find_package(PuppetMaster 0.2)` accepts only 0.2.x. +the minor version in their soname (`libpuppet_master.so.0.3`), and +`find_package(PuppetMaster 0.3)` accepts only 0.3.x. ## Unreleased +Breaking wire change for services: upgrade a service's server and all its +clients together. A 0.3 process and a newer one on the same service do not +see each other's heartbeats, so calls between them fail at once with +`Unavailable`. Topics and their data are unchanged; 0.3 and newer processes +still exchange topic messages, and the shared-memory layout version is the +same. + +### Added + +- **Per-client reply topics.** Each service client reads its own reply topic, + `/reply/`, instead of every client + reading every reply. The server opens a writer per client on its first + reply and closes it after `ServerOptions::reply_idle_timeout` (30 s) idle. + `service::ReplyEndpointFor` names a client's topic. See + [Reply Topics](docs/services.md#reply-topics). +- **Reader-owned topics.** `core::TopicSpec::lifetime` with + `TopicLifetime::kReaderOwned`: the reader creates the topic, writers only + attach and get `NotFound` once it is gone, and on shared memory the segment + is removed when the reader closes, or by the last writer after the reader + crashed. See [Endpoint Configuration](docs/transport.md#endpoint-configuration). +- `shm::Options::topic_prefixes` sizes every topic under a name. A service's + deployment settings cover its per-client reply topics this way. +- `RuntimeContext::FindTransport(core::TransportKind)`. + +### Changed + +- Breaking wire: service header version 2, and the presence descriptor is + `service.Presence.v2` version 2. +- Breaking API: `core::TopicSpec` has a new last field, `lifetime`; + `ServerOptions` a new field, `reply_idle_timeout`. +- `ServiceEndpoints::reply` is the base of the per-client reply topics; no + process reads or writes `/reply` itself any more. +- `Client::Close()` also releases the client's reply topic, not only its + destructor. + +### Fixed + +- Every transport now frees a topic in this process when its last reader and + writer close. Before, in-memory and shared-memory transports kept every + topic they had opened, and FastDDS every DDS topic, until the transport + closed, so a process opening many short-lived topics grew without bound. + +## 0.3.0 + +Rebuild everything that links PuppetMaster: the soname is now +`libpuppet_master.so.0.3`, and `find_package(PuppetMaster 0.2)` no longer +finds this release. The shared-memory layout, the service wire protocol, and +the JSON configuration of 0.2 are unchanged, so 0.2 and 0.3 processes still +talk to each other, and 0.2 configurations still load. + ### Added - **Scheduled servers.** `TriggerKind::kService` runs a component when a @@ -54,6 +104,14 @@ the minor version in their soname (`libpuppet_master.so.0.2`), and - The vehicle pipeline example starts its system with `puppet_master_launch`. +### Fixed + +- With `-DBUILD_SHARED_LIBS=ON` on Linux and macOS, the installed tools + failed to start unless `LD_LIBRARY_PATH` pointed at the install's `lib` + directory (since 0.2.0). Installed tools and libraries now carry a + relative RPATH (`$ORIGIN/../lib` and `$ORIGIN`), so they work from any + prefix, including a moved one. Set `CMAKE_INSTALL_RPATH` to override. + ## 0.2.0 ### Added diff --git a/CMakeLists.txt b/CMakeLists.txt index ebe9497..8d1afa7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,7 @@ cmake_minimum_required(VERSION 3.16) project(PuppetMaster - VERSION 0.2.0 + VERSION 0.3.0 DESCRIPTION "A C++ real-time middleware runtime for message-driven components and deterministic task scheduling." HOMEPAGE_URL "https://github.com/SoleyRan/PuppetMaster" LANGUAGES CXX @@ -21,7 +21,8 @@ else() endif() # Before 1.0, every minor release may break the ABI and the API (0.2 added a -# virtual function to transport::Writer, for example), so the shared library +# virtual function to transport::Writer, 0.3 fields to TriggerSpec and +# NodeManifest, for example), so the shared library # soname and the CMake package compatibility both include the minor version. # From 1.0 on, only a major release breaks them. if(PROJECT_VERSION_MAJOR EQUAL 0) @@ -100,6 +101,21 @@ if(PUPPETMASTER_ENABLE_GOODLOG AND NOT TARGET GoodLog::good_log) endif() endif() +# Installed shared libraries find each other, and installed tools find them, +# without LD_LIBRARY_PATH, wherever the prefix is moved: libraries look next +# to themselves, tools in the lib directory next to bin. Windows needs +# nothing, because the DLLs are installed next to the tools in bin. Set +# CMAKE_INSTALL_RPATH to override. +if(PUPPETMASTER_IS_TOP_LEVEL AND NOT WIN32 AND NOT DEFINED CMAKE_INSTALL_RPATH) + if(APPLE) + set(PUPPETMASTER_RPATH_ORIGIN "@loader_path") + else() + set(PUPPETMASTER_RPATH_ORIGIN "$ORIGIN") + endif() + file(RELATIVE_PATH PUPPETMASTER_LIB_FROM_BIN "${CMAKE_INSTALL_FULL_BINDIR}" "${CMAKE_INSTALL_FULL_LIBDIR}") + set(CMAKE_INSTALL_RPATH "${PUPPETMASTER_RPATH_ORIGIN}" "${PUPPETMASTER_RPATH_ORIGIN}/${PUPPETMASTER_LIB_FROM_BIN}") +endif() + add_subdirectory(src) if(PUPPETMASTER_BUILD_DEMOS) diff --git a/README.md b/README.md index a75ed36..8a17481 100644 --- a/README.md +++ b/README.md @@ -117,7 +117,7 @@ shared-memory topics (with the shm adapter too). See Add `-DBUILD_SHARED_LIBS=ON` for shared libraries. Before 1.0 each minor release may break the API and the ABI, so the shared -libraries' soname includes the minor version (`libpuppet_master.so.0.2`) and +libraries' soname includes the minor version (`libpuppet_master.so.0.3`) and the package accepts only the same minor version. Rebuild dependents when upgrading; see [CHANGELOG](CHANGELOG.md). @@ -126,7 +126,7 @@ upgrading; see [CHANGELOG](CHANGELOG.md). After installation, another CMake project can consume PuppetMaster with: ```cmake -find_package(PuppetMaster 0.2 CONFIG REQUIRED) +find_package(PuppetMaster 0.3 CONFIG REQUIRED) target_link_libraries(my_component PRIVATE PuppetMaster::PuppetMaster) ``` diff --git a/docs/services.md b/docs/services.md index 3c11e86..c367ee1 100644 --- a/docs/services.md +++ b/docs/services.md @@ -58,7 +58,7 @@ A service named `/map/query` uses: | Topic | Writer | Reader | Policy | Carries | |---|---|---|---|---| | `/map/query/request` | clients | server | queued | header + request payload | -| `/map/query/reply` | server | clients | queued | header + reply payload | +| `/map/query/reply/` | server | that client | queued | header + reply payload | | `/map/query/presence` | server | clients | latest | server instance id, heartbeat | The request and reply descriptors are those of the payload types, with the @@ -67,13 +67,35 @@ subscriber of the same type cannot read them by accident. Their versions carry over, so a client built against another version of the request type is refused when it is created. +### Reply Topics + +Each client has its own reply topic, named after the service with +`/reply/` and its client id in 16 hex digits, for example +`/map/query/reply/3f2a9c0d11e4b706`. `service::ReplyEndpointFor(spec, +client_id)` returns it. A client receives only its own replies, so the cost +of a reply does not grow with the number of clients, and a busy client cannot +push another client's replies out of a shared queue. + +The topic is reader-owned (`core::TopicLifetime::kReaderOwned`): the client +creates it, and `Client::Close()` removes it. The server opens a writer for a +client on its first reply to that client and keeps it, then closes it after +`ServerOptions::reply_idle_timeout` (30 s) without a reply. On shared memory, +that close also removes the segment of a client that crashed, so no reply +segments are left in `/dev/shm`. + +On FastDDS, a new writer reaches the client's reader only once discovery has +matched them. The server waits for that once per client, at most 1 s or +until the request's deadline. A reply that cannot reach its client, because +the client closed or was never matched, is dropped, and the client times out +with `DeadlineExceeded`. + ### Wire Header Every request and reply starts with a fixed 32-byte header, little-endian: ```text u32 magic "PMRQ" / "PMRP" -u16 header_version 1 +u16 header_version 2 (1 in 0.3 and earlier, with one shared reply topic) u16 status reply only: core::StatusCode of the handler result u64 client_id random per client instance u64 request_id per-client counter, starting at 1 @@ -83,6 +105,13 @@ u64 budget_ns request only: how long the client waits; 0 = no limit A reply with a non-OK status carries the handler's error message as its payload, so the client returns that status with its message. +The presence topic's descriptor is `service.Presence.v2` version 2. A 0.3 +process uses `service.Presence` version 1, so processes of the two protocol +versions never see each other's heartbeats: a call between them fails at once +with `Unavailable`, and on shared memory the second endpoint on the presence +topic is refused when it is created. Upgrade a service's server and clients +together. + ### Presence The server writes `{u64 instance_id, u64 sequence}` on the presence topic at @@ -291,8 +320,9 @@ returns `FailedPrecondition`. Interface files may declare `services` next to `topics`, so the team that serves a service publishes its contract once and every caller imports it. -Deployment files place them by wire name; the settings apply to all three of -the service's topics, and `shm::OptionsFromProject` sizes them: +Deployment files place them by wire name; the settings apply to all of the +service's topics, including every client's reply topic, and +`shm::OptionsFromProject` sizes them: ```json {"services": [{"name": "/map/query", "transport": "shm", @@ -341,9 +371,11 @@ because the map cannot get the worker the planner holds. - Requests and replies are bounded by the transport's message size; on shared memory, by the topic's `slot_payload_size`. -- Every client receives every reply on the service and drops the ones that - are not its own, so very many concurrent clients cost extra copies. This is - the price of running on any pub/sub transport without changes. +- Each client's reply topic costs one ring on shared memory (the service's + `slot_payload_size` x `slot_count`), and one DDS topic and writer per client + on FastDDS, while the client is in use and for `reply_idle_timeout` after. +- The first reply to a new client on FastDDS waits for discovery, usually a + few tens of milliseconds. - A request queue that overflows drops the oldest requests, which their clients see as `DeadlineExceeded`. Size the request topic's queue depth for the expected burst. diff --git a/docs/shm-transport.md b/docs/shm-transport.md index f0ddea1..f7232ad 100644 --- a/docs/shm-transport.md +++ b/docs/shm-transport.md @@ -34,10 +34,14 @@ namespace shm = puppet_master::transport::shm; shm::Options options; options.domain_id = 3; // isolates deployments options.topics["/lidar/points"] = shm::TopicOptions {4 << 20, 8}; // 4 MiB x 8 slots +options.topic_prefixes["/camera/"] = shm::TopicOptions {8 << 20, 4}; // every topic under /camera/ auto status = shm::RegisterTransport(*runtime, name, options); ``` +`ForTopic` takes an exact `topics` entry first, then the longest matching +`topic_prefixes` key, then `default_topic`. + Topics use `core::TransportKind::kIpc`. In configuration files the transport may be written as `"ipc"` or `"shm"`. @@ -67,7 +71,9 @@ options.register_project_transports = [](runtime::RuntimeContext& context, const ``` Because every process reads the same deployment file, they agree on the -geometry of each topic. +geometry of each topic. A service's settings size its request and presence +topics by name and its per-client reply topics by the prefix +`/reply/`. ## Zero-Copy Writes @@ -149,6 +155,19 @@ shm::RemoveSegment(domain_id, "/lidar/points"); or remove `/dev/shm/pm..` by hand. On Windows, a segment is freed when the last process closes it. +Within a process, a topic's segment is unmapped and its participant entry +released when the last reader or writer on it closes. + +A reader-owned topic (`core::TopicLifetime::kReaderOwned`, used for service +reply topics) belongs to its reader. The reader creates the segment. Writers +only attach to it, and get `NotFound` if it does not exist. When the reader +closes, it marks the segment retired and removes its name. Writers still +attached then get `NotFound` on every write, and a new reader under the same +name starts a fresh segment. If the reader crashes, the last writer to +close removes the name once no live process is attached, so no segment is +left behind. The retired flag uses a header word that was reserved before, +so the layout version is unchanged. + ### Listing And Cleaning Up `puppet_master_config shm` inspects this host's segments without attaching to diff --git a/docs/transport.md b/docs/transport.md index 2a218aa..410452f 100644 --- a/docs/transport.md +++ b/docs/transport.md @@ -45,6 +45,20 @@ identifies the payload contract used by a reader or writer: type name, encoding, and an optional version. Every backend rejects an endpoint whose descriptor differs from the one already open on that topic. +`TopicSpec::lifetime` says who a topic belongs to: + +- `kShared` (default): any endpoint creates the topic. +- `kReaderOwned`: the topic belongs to its one reader, such as a service + client's reply topic. The reader creates it. Writers only attach, and fail + with `NotFound` when the reader has not created it or has closed it. What + the topic leaves outside the process, a shared-memory segment, is removed + when the reader closes. In memory and in shared memory. FastDDS leaves + nothing behind and cannot tell a missing reader from an undiscovered one, + so it treats the topic as shared; check `MatchedReaderCount` there. + +Every backend frees a topic, in this process, when its last reader and writer +close, so a process can open many short-lived topics. + ## Reader And Writer `Reader` and `Writer` are pure interfaces: diff --git a/examples/vehicle_pipeline/estimator_node/CMakeLists.txt b/examples/vehicle_pipeline/estimator_node/CMakeLists.txt index a6d0086..52c077d 100644 --- a/examples/vehicle_pipeline/estimator_node/CMakeLists.txt +++ b/examples/vehicle_pipeline/estimator_node/CMakeLists.txt @@ -6,7 +6,7 @@ project(EstimatorNode VERSION 1.0.0 LANGUAGES CXX) include(GNUInstallDirs) -find_package(PuppetMaster 0.2 CONFIG REQUIRED) +find_package(PuppetMaster 0.3 CONFIG REQUIRED) find_package(EstimationInterfaces 1 CONFIG REQUIRED) add_executable(estimator_node src/main.cpp) diff --git a/examples/vehicle_pipeline/monitor_node/CMakeLists.txt b/examples/vehicle_pipeline/monitor_node/CMakeLists.txt index 54bfa4c..8f11c88 100644 --- a/examples/vehicle_pipeline/monitor_node/CMakeLists.txt +++ b/examples/vehicle_pipeline/monitor_node/CMakeLists.txt @@ -6,7 +6,7 @@ project(MonitorNode VERSION 1.0.0 LANGUAGES CXX) include(GNUInstallDirs) -find_package(PuppetMaster 0.2 CONFIG REQUIRED) +find_package(PuppetMaster 0.3 CONFIG REQUIRED) find_package(EstimationInterfaces 1 CONFIG REQUIRED) add_executable(monitor_node src/main.cpp) diff --git a/examples/vehicle_pipeline/sensor_interfaces/CMakeLists.txt b/examples/vehicle_pipeline/sensor_interfaces/CMakeLists.txt index 1ecf038..1a9369f 100644 --- a/examples/vehicle_pipeline/sensor_interfaces/CMakeLists.txt +++ b/examples/vehicle_pipeline/sensor_interfaces/CMakeLists.txt @@ -12,7 +12,7 @@ include(CMakePackageConfigHelpers) set(WHEEL_SPEED_VERSION 2 CACHE STRING "vehicle.WheelSpeed wire format version") set(IMU_SAMPLE_VERSION 1) -find_package(PuppetMaster 0.2 CONFIG REQUIRED) +find_package(PuppetMaster 0.3 CONFIG REQUIRED) set(GENERATED "${CMAKE_CURRENT_BINARY_DIR}/generated") configure_file(include/sensor_interfaces/messages.h.in "${GENERATED}/include/sensor_interfaces/messages.h" @ONLY) @@ -38,7 +38,7 @@ install(EXPORT SensorInterfacesTargets NAMESPACE SensorInterfaces:: DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/SensorInterfaces") file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/SensorInterfacesConfig.cmake" [=[ include(CMakeFindDependencyMacro) -find_dependency(PuppetMaster 0.2 CONFIG) +find_dependency(PuppetMaster 0.3 CONFIG) include("${CMAKE_CURRENT_LIST_DIR}/SensorInterfacesTargets.cmake") ]=]) write_basic_package_version_file("${CMAKE_CURRENT_BINARY_DIR}/SensorInterfacesConfigVersion.cmake" diff --git a/examples/vehicle_pipeline/sensor_node/CMakeLists.txt b/examples/vehicle_pipeline/sensor_node/CMakeLists.txt index c4b2654..34d8500 100644 --- a/examples/vehicle_pipeline/sensor_node/CMakeLists.txt +++ b/examples/vehicle_pipeline/sensor_node/CMakeLists.txt @@ -6,7 +6,7 @@ project(SensorNode VERSION 1.0.0 LANGUAGES CXX) include(GNUInstallDirs) -find_package(PuppetMaster 0.2 CONFIG REQUIRED) +find_package(PuppetMaster 0.3 CONFIG REQUIRED) find_package(SensorInterfaces 2 CONFIG REQUIRED) add_executable(sensor_node src/main.cpp) diff --git a/include/puppet_master/core/types.h b/include/puppet_master/core/types.h index b47254d..03b61f2 100644 --- a/include/puppet_master/core/types.h +++ b/include/puppet_master/core/types.h @@ -53,6 +53,20 @@ enum class DependencyPolicy : std::uint8_t { kAny, }; +// Who a topic belongs to. +enum class TopicLifetime : std::uint8_t { + // Any endpoint creates the topic; it outlives them all. + kShared = 0, + // The topic belongs to its one reader, such as a service client's reply + // topic: the reader creates it, writers only attach to it and fail with + // NotFound when the reader is gone, and what the topic leaves outside the + // process (a shared-memory segment) is removed when the reader closes. + // In memory and in shared memory. FastDDS leaves nothing behind and + // cannot tell a missing reader from an undiscovered one, so it treats + // the topic as shared; use Writer::MatchedReaderCount there. + kReaderOwned, +}; + namespace detail { inline std::string CopyStringView(std::string_view value) @@ -105,6 +119,17 @@ inline const char* ToString(TriggerKind kind) noexcept return "unknown"; } +inline const char* ToString(TopicLifetime lifetime) noexcept +{ + switch (lifetime) { + case TopicLifetime::kShared: + return "shared"; + case TopicLifetime::kReaderOwned: + return "reader_owned"; + } + return "unknown"; +} + inline Status ValidateName(std::string_view kind, std::string_view value) { if (value.empty()) { @@ -213,6 +238,7 @@ struct TopicSpec { TopicName name; TransportKind transport {TransportKind::kInMemory}; MessagePolicy message_policy; + TopicLifetime lifetime {TopicLifetime::kShared}; Status Validate() const { diff --git a/include/puppet_master/runtime/context.h b/include/puppet_master/runtime/context.h index 89bda5f..2755f49 100644 --- a/include/puppet_master/runtime/context.h +++ b/include/puppet_master/runtime/context.h @@ -47,6 +47,8 @@ class RuntimeContext final { core::Status RegisterTransport(transport::TransportPtr transport); core::Result FindTransport(const core::TransportName& name) const; + // The transport CreateReader and CreateWriter use for topics of `kind`. + core::Result FindTransport(core::TransportKind kind) const; std::vector ListTransportNames() const; core::Status RegisterComponent(ComponentSpec spec); diff --git a/include/puppet_master/service/service.h b/include/puppet_master/service/service.h index f66d74b..0a5b241 100644 --- a/include/puppet_master/service/service.h +++ b/include/puppet_master/service/service.h @@ -19,8 +19,9 @@ class RuntimeContext; } // Request/reply services over pub/sub topics. A service `/a/b` uses the -// topics `/a/b/request`, `/a/b/reply`, and `/a/b/presence`, so it works on -// every transport. See docs/services.md. +// topics `/a/b/request` and `/a/b/presence`, and one reply topic per client, +// `/a/b/reply/`, so it works on every transport. +// See docs/services.md. namespace puppet_master::service { struct ServiceSpec { @@ -40,16 +41,23 @@ struct ServiceSpec { PUPPET_MASTER_API core::Status Validate() const; }; -// Endpoints of the three topics, for transports and configuration tools +// Endpoints of the service's topics, for transports and configuration tools // that need to know them, such as a deployment file or ValidateSystem. struct ServiceEndpoints { transport::EndpointConfig request; + // The per-client reply topics share this endpoint, reader-owned, under + // names that append "/" to its name; see ReplyEndpointFor. transport::EndpointConfig reply; transport::EndpointConfig presence; }; PUPPET_MASTER_API core::Result EndpointsFor(const ServiceSpec& spec); +// The reply topic of one client: `/reply/`. The client's reader owns it; the server writes to it. +PUPPET_MASTER_API core::Result ReplyEndpointFor( + const ServiceSpec& spec, std::uint64_t client_id); + struct Request { transport::ByteView payload; std::uint64_t client_id {0}; @@ -76,6 +84,10 @@ enum class ServeMode : std::uint8_t { struct ServerOptions { ServeMode mode {ServeMode::kOwnThread}; + // The server opens a reply writer per client on its first reply and + // closes it after this long without one. Closing it lets the transport + // free the client's reply topic, also when the client crashed. + core::Nanoseconds reply_idle_timeout {std::chrono::seconds(30)}; }; class PUPPET_MASTER_API Server final { diff --git a/include/puppet_master/transport/shm/shm_transport.h b/include/puppet_master/transport/shm/shm_transport.h index 611f83e..98aed96 100644 --- a/include/puppet_master/transport/shm/shm_transport.h +++ b/include/puppet_master/transport/shm/shm_transport.h @@ -39,6 +39,10 @@ struct PUPPET_MASTER_API Options { core::DomainId domain_id {0}; TopicOptions default_topic; std::map topics; // per-topic override by full name + // Override for every topic whose name starts with the key, used when + // `topics` has no entry; the longest matching key wins. A service's + // per-client reply topics, `/reply/`, are sized this way. + std::map topic_prefixes; // Upper bound for one notification wait, so a lost wakeup delays delivery // by at most this interval. core::Nanoseconds wait_poll_interval {std::chrono::milliseconds(50)}; diff --git a/src/runtime/context.cpp b/src/runtime/context.cpp index 7d1e29c..2e3d4f7 100644 --- a/src/runtime/context.cpp +++ b/src/runtime/context.cpp @@ -639,6 +639,11 @@ core::Result RuntimeContext::FindTransport( return impl_->FindTransport(name); } +core::Result RuntimeContext::FindTransport(core::TransportKind kind) const +{ + return impl_->FindTransport(kind); +} + std::vector RuntimeContext::ListTransportNames() const { return impl_->ListTransportNames(); diff --git a/src/service/service.cpp b/src/service/service.cpp index b269ab9..92173b9 100644 --- a/src/service/service.cpp +++ b/src/service/service.cpp @@ -7,6 +7,7 @@ #include #include #include +#include #include #include #include @@ -23,13 +24,24 @@ using transport::ByteView; constexpr std::uint32_t kRequestMagic = 0x51524d50; // "PMRQ", little-endian constexpr std::uint32_t kReplyMagic = 0x50524d50; // "PMRP" -constexpr std::uint16_t kHeaderVersion = 1; +// 2: replies go to each client's own topic, not one shared reply topic. +constexpr std::uint16_t kHeaderVersion = 2; constexpr std::size_t kHeaderSize = 32; constexpr std::size_t kPresenceSize = 16; +// The protocol version is also in the presence type name, so processes of +// different protocol versions do not see each other at all: on FastDDS, +// which matches types by name only, as on the other transports, where the +// endpoint is refused. A call then fails with Unavailable instead of waiting +// for a reply that goes to a topic the other side does not read. +constexpr const char* kPresenceType = "service.Presence.v2"; +constexpr std::uint32_t kPresenceVersion = 2; // Heartbeat sequences start at 1; 0 announces that the server stopped. constexpr std::uint64_t kOfflineSequence = 0; // How often blocking loops wake to notice Close(), at most. constexpr auto kPollInterval = std::chrono::milliseconds(20); +// How long a server waits for a new reply writer to reach its client's +// reader, on transports that discover peers asynchronously. +constexpr auto kReplyMatchTimeout = std::chrono::seconds(1); core::TimePoint Now() { @@ -157,6 +169,27 @@ core::Result SubTopic(const core::TopicName& service, const cha return core::TopicName::Create(service.str() + "/" + suffix); } +std::string Hex16(std::uint64_t value) +{ + static constexpr char kDigits[] = "0123456789abcdef"; + std::string text(16, '0'); + for (std::size_t index = 16; index-- > 0; value >>= 4) { + text[index] = kDigits[value & 0xf]; + } + return text; +} + +// One client's reply topic: the service's reply endpoint, renamed. +core::Result ReplyEndpoint(transport::EndpointConfig base, std::uint64_t client_id) +{ + auto name = core::TopicName::Create(base.topic.name.str() + "/" + Hex16(client_id)); + if (!name.ok()) { + return core::Result::FromStatus(name.status()); + } + base.topic.name = std::move(name).value(); + return core::Result(std::move(base)); +} + std::string Describe(const ServiceSpec& spec) { return "service " + spec.name.str(); @@ -197,7 +230,10 @@ core::Result EndpointsFor(const ServiceSpec& spec) auto request = SubTopic(spec.name, "request"); auto reply = SubTopic(spec.name, "reply"); auto presence = SubTopic(spec.name, "presence"); - for (const auto* name : {&request, &reply, &presence}) { + // The longest name the service uses, so a name too long for its + // per-client reply topics fails here, not at the first client. + auto per_client = SubTopic(spec.name, "reply/0000000000000000"); + for (const auto* name : {&request, &reply, &presence, &per_client}) { if (!name->ok()) { return ResultType::FromStatus(name->status()); } @@ -215,16 +251,30 @@ core::Result EndpointsFor(const ServiceSpec& spec) // lost one, so best effort is enough. core::MessagePolicy latest; + // Replies: each client reads its own topic, which it owns, so it never + // receives other clients' replies, and a busy client cannot push them + // out of a shared queue. return ResultType(ServiceEndpoints { transport::EndpointConfig {core::TopicSpec {request.value(), spec.transport, queued}, Prefixed("service.request:", spec.request)}, - transport::EndpointConfig {core::TopicSpec {reply.value(), spec.transport, queued}, - Prefixed("service.reply:", spec.reply)}, + transport::EndpointConfig { + core::TopicSpec {reply.value(), spec.transport, queued, core::TopicLifetime::kReaderOwned}, + Prefixed("service.reply:", spec.reply)}, transport::EndpointConfig {core::TopicSpec {presence.value(), spec.transport, latest}, - transport::MessageDescriptor {"service.Presence", "application/x-puppetmaster-presence", 1}}, + transport::MessageDescriptor {kPresenceType, "application/x-puppetmaster-presence", + kPresenceVersion}}, }); } +core::Result ReplyEndpointFor(const ServiceSpec& spec, std::uint64_t client_id) +{ + auto endpoints = EndpointsFor(spec); + if (!endpoints.ok()) { + return core::Result::FromStatus(endpoints.status()); + } + return ReplyEndpoint(endpoints.value().reply, client_id); +} + // ---------------------------------------------------------------- Server struct Server::Impl { @@ -242,9 +292,21 @@ struct Server::Impl { std::atomic serving_thread {}; std::uint64_t instance_id {RandomId()}; transport::ReaderPtr requests; - transport::WriterPtr replies; transport::WriterPtr presence; + // Replies go to each client's own topic, through a writer opened on its + // first reply. They use the transport directly, not the runtime, so the + // server holds what it writes through for as long as it lives, and so + // per-client topics do not each add a metrics series. + struct ReplyWriter { + transport::WriterPtr writer; + core::TimePoint last_used; + }; + transport::TransportPtr transport; + std::optional reply_base; + std::mutex reply_mutex; // before `mutex` when both are held + std::map reply_writers; + std::mutex mutex; std::condition_variable wake; // requests arrived, or close std::condition_variable beat; // close, for the heartbeat thread @@ -265,7 +327,50 @@ struct Server::Impl { presence->Write(ByteView(message, sizeof(message))); } - void Reply(const Header& request, core::StatusCode code, ByteView payload) + bool IsClosed() + { + std::lock_guard lock(mutex); + return closed; + } + + // Caller holds reply_mutex. The writer for a client's reply topic, opened + // on first use, or null when the reply cannot reach the client: its topic + // is gone (it closed), or its reader was not matched by `give_up`. + transport::WriterPtr ReplyWriterLocked(std::uint64_t client_id, core::TimePoint give_up) + { + const auto now = Now(); + const auto found = reply_writers.find(client_id); + if (found != reply_writers.end()) { + found->second.last_used = now; + return found->second.writer; + } + auto endpoint = ReplyEndpoint(*reply_base, client_id); + if (!endpoint.ok()) { + return nullptr; + } + auto writer = transport->CreateWriter(endpoint.value()); + if (!writer.ok()) { + return nullptr; // NotFound: the client is gone + } + // A new writer reaches the client's reader only once matched, on + // backends that discover peers asynchronously: wait, once per client. + while (true) { + const auto matched = writer.value()->MatchedReaderCount(); + if (!matched.ok() || matched.value() > 0) { + break; // Unsupported: delivery does not depend on matching + } + if (Now() >= give_up || IsClosed()) { + return nullptr; + } + std::this_thread::sleep_for(std::chrono::milliseconds(2)); + } + reply_writers.emplace(client_id, ReplyWriter {writer.value(), now}); + return writer.value(); + } + + // Sends a reply to its client's topic. A reply that cannot reach the + // client is dropped, as a lost message would be; the client times out. + void Reply(const Header& request, core::TimePoint deadline, core::StatusCode code, ByteView payload) { Header header; header.magic = kReplyMagic; @@ -273,7 +378,41 @@ struct Server::Impl { header.client_id = request.client_id; header.request_id = request.request_id; const auto message = Encode(header, payload); - replies->Write(ByteView(message)); + auto give_up = Now() + kReplyMatchTimeout; + if (deadline != core::TimePoint {}) { + give_up = std::min(give_up, deadline); + } + std::lock_guard lock(reply_mutex); + const auto writer = ReplyWriterLocked(request.client_id, give_up); + if (writer && !writer->Write(ByteView(message)).ok()) { + // The client closed its topic, or the writer broke: forget it, + // so a later request from the same client opens a fresh one. + reply_writers.erase(request.client_id); + } + } + + // From the heartbeat thread: closes writers of clients that have not + // been replied to for reply_idle_timeout. Skips the round when a reply is + // being sent, so a heartbeat never waits for it. + void EvictIdleWriters() + { + std::vector idle; + { + std::unique_lock lock(reply_mutex, std::try_to_lock); + if (!lock.owns_lock()) { + return; + } + const auto cutoff = Now() - options.reply_idle_timeout; + for (auto entry = reply_writers.begin(); entry != reply_writers.end();) { + if (entry->second.last_used < cutoff) { + idle.push_back(std::move(entry->second.writer)); + entry = reply_writers.erase(entry); + } else { + ++entry; + } + } + } + // Closed here, outside the lock: closing may wait on the transport. } // True if the handler ran; false for a request that was dropped @@ -308,10 +447,10 @@ struct Server::Impl { } ++handled; if (result.ok()) { - Reply(header, core::StatusCode::kOk, ByteView(result.value())); + Reply(header, deadline, core::StatusCode::kOk, ByteView(result.value())); } else { const auto& text = result.status().message(); - Reply(header, result.status().code(), + Reply(header, deadline, result.status().code(), ByteView(reinterpret_cast(text.data()), text.size())); } return true; @@ -349,6 +488,7 @@ struct Server::Impl { while (!beat.wait_for(lock, spec.heartbeat_interval, [this] { return closed; })) { lock.unlock(); Announce(); + EvictIdleWriters(); lock.lock(); } } @@ -365,19 +505,36 @@ core::Result> Server::Create( if (!endpoints.ok()) { return ResultType::FromStatus(endpoints.status()); } + if (options.reply_idle_timeout <= core::Nanoseconds::zero()) { + return ResultType::FromStatus(core::Status::InvalidArgument("reply_idle_timeout must be greater than zero")); + } auto impl = std::make_shared(std::move(spec), std::move(handler), options); + const auto failed = [&impl](const core::Status& status) { + return ResultType::FromStatus( + core::Status::Error(status.code(), Describe(impl->spec) + ": " + status.message())); + }; + + // Reply writers are opened per client later; check now that the + // transport takes the reply endpoint, so a bad setup fails here. + auto transport = runtime.FindTransport(impl->spec.transport); + if (!transport.ok()) { + return failed(transport.status()); + } + auto valid = transport.value()->ValidateEndpoint(endpoints.value().reply); + if (!valid.ok()) { + return failed(valid); + } + impl->transport = transport.value(); + impl->reply_base = endpoints.value().reply; auto requests = runtime.CreateReader(endpoints.value().request); - auto replies = runtime.CreateWriter(endpoints.value().reply); auto presence = runtime.CreateWriter(endpoints.value().presence); - for (const core::Status* status : {&requests.status(), &replies.status(), &presence.status()}) { - if (!status->ok()) { - return ResultType::FromStatus(core::Status::Error( - status->code(), Describe(impl->spec) + ": " + status->message())); + for (const core::Status* created : {&requests.status(), &presence.status()}) { + if (!created->ok()) { + return failed(*created); } } impl->requests = std::move(requests).value(); - impl->replies = std::move(replies).value(); impl->presence = std::move(presence).value(); // kCaller: arrival is someone else's to notice (the scheduler's service @@ -522,6 +679,12 @@ void Server::Close() noexcept std::lock_guard serving(impl_->serve_mutex); } impl_->requests->SetDataAvailableCallback({}); + // Release the per-client reply topics; closed outside the lock. + std::map writers; + { + std::lock_guard lock(impl_->reply_mutex); + writers.swap(impl_->reply_writers); + } } // ---------------------------------------------------------------- Client @@ -815,8 +978,13 @@ core::Result> Client::Create(runtime::RuntimeContext& ru auto impl = std::make_shared(std::move(spec)); // Reply and presence readers first, so nothing sent after a request is - // written can be missed by a volatile reader. - auto replies = runtime.CreateReader(endpoints.value().reply); + // written can be missed by a volatile reader. The reply reader creates + // this client's own reply topic, which it owns. + auto reply_endpoint = ReplyEndpoint(endpoints.value().reply, impl->client_id); + if (!reply_endpoint.ok()) { + return ResultType::FromStatus(reply_endpoint.status()); + } + auto replies = runtime.CreateReader(reply_endpoint.value()); auto presence = runtime.CreateReader(endpoints.value().presence); auto requests = runtime.CreateWriter(endpoints.value().request); for (const core::Status* status : {&replies.status(), &presence.status(), &requests.status()}) { @@ -971,6 +1139,11 @@ void Client::Close() noexcept } Impl::Run(cancelled); impl_->replies->SetDataAvailableCallback({}); + // Release the reply reader now, not with the object, so this client's + // reply topic (its segment, in shared memory) goes with Close. Only the + // dispatcher reads it, and it is done: joined above, or this thread, + // running a reply callback after its last read of the loop. + impl_->replies.reset(); } } // namespace puppet_master::service diff --git a/src/transport/fastdds/fastdds_transport.cpp b/src/transport/fastdds/fastdds_transport.cpp index 7615df2..7ba917d 100644 --- a/src/transport/fastdds/fastdds_transport.cpp +++ b/src/transport/fastdds/fastdds_transport.cpp @@ -140,6 +140,8 @@ struct ReaderState { std::uint64_t generation {0}; bool closed {false}; + std::string topic; // the wire name, for the transport's topic sweep + std::mutex shutdown_mutex; std::mutex entity_mutex; dds::Subscriber* subscriber {nullptr}; @@ -176,6 +178,7 @@ struct ReaderState { }; struct WriterState { + std::string topic; // the wire name, for the transport's topic sweep std::mutex mutex; dds::Publisher* publisher {nullptr}; dds::DataWriter* writer {nullptr}; @@ -395,12 +398,42 @@ struct FastDdsTransport::Impl { std::vector> readers; std::vector> writers; + // Caller must hold mutex. Deletes the topics no live reader or writer + // uses, so many short-lived topics do not accumulate in the participant. + // A state still alive counts as a use even after its Shutdown, which is + // conservative: such a topic goes on the next sweep. delete_topic refuses + // a topic that still has DDS entities; that entry is kept. + void SweepTopics() + { + Prune(readers); + Prune(writers); + std::set used; + for (const auto& weak : readers) { + if (auto state = weak.lock()) { + used.insert(state->topic); + } + } + for (const auto& weak : writers) { + if (auto state = weak.lock()) { + used.insert(state->topic); + } + } + for (auto entry = topics.begin(); entry != topics.end();) { + if (used.count(entry->first) == 0 && participant->delete_topic(entry->second.topic) == kRetOk) { + entry = topics.erase(entry); + } else { + ++entry; + } + } + } + // Caller must hold mutex. core::Result EnsureTopic(const EndpointConfig& endpoint) { const std::string topic_name = endpoint.topic.name.str(); const std::string& type_name = endpoint.message.type_name; + SweepTopics(); auto found = topics.find(topic_name); if (found != topics.end()) { if (found->second.message != endpoint.message) { @@ -652,6 +685,7 @@ core::Result FastDdsTransport::CreateReader(const EndpointConfig& end qos.endpoint().history_memory_policy = rtps::PREALLOCATED_WITH_REALLOC_MEMORY_MODE; auto state = std::make_shared(); + state->topic = endpoint.topic.name.str(); state->subscriber = impl_->subscriber; state->reader = impl_->subscriber->create_datareader(topic.value(), qos, &state->listener); if (state->reader == nullptr) { @@ -694,6 +728,7 @@ core::Result FastDdsTransport::CreateWriter(const EndpointConfig& end } auto state = std::make_shared(); + state->topic = endpoint.topic.name.str(); state->publisher = impl_->publisher; state->writer = impl_->publisher->create_datawriter(topic.value(), qos); if (state->writer == nullptr) { diff --git a/src/transport/inmemory/inmemory_transport.cpp b/src/transport/inmemory/inmemory_transport.cpp index c5e63cf..d98f9e7 100644 --- a/src/transport/inmemory/inmemory_transport.cpp +++ b/src/transport/inmemory/inmemory_transport.cpp @@ -4,6 +4,7 @@ #include #include #include +#include #include #include #include @@ -50,6 +51,8 @@ std::size_t QueueCapacity(const core::MessagePolicy& policy) } // namespace +class TopicChannel; + class InMemoryReader final : public Reader { public: class Mailbox { @@ -205,8 +208,9 @@ class InMemoryReader final : public Reader { bool closed_ {false}; }; - explicit InMemoryReader(std::shared_ptr mailbox) - : mailbox_(std::move(mailbox)) + // Holding the channel keeps the topic alive while this reader exists. + InMemoryReader(std::shared_ptr mailbox, std::shared_ptr channel) + : mailbox_(std::move(mailbox)), channel_(std::move(channel)) { } @@ -244,12 +248,13 @@ class InMemoryReader final : public Reader { private: std::shared_ptr mailbox_; + std::shared_ptr channel_; }; class TopicChannel final { public: - TopicChannel(core::TopicName topic, MessageDescriptor descriptor) - : topic_(std::move(topic)), descriptor_(std::move(descriptor)) + TopicChannel(core::TopicName topic, MessageDescriptor descriptor, core::TopicLifetime lifetime) + : topic_(std::move(topic)), descriptor_(std::move(descriptor)), lifetime_(lifetime) { } @@ -258,6 +263,18 @@ class TopicChannel final { return descriptor_; } + core::TopicLifetime lifetime() const noexcept + { + return lifetime_; + } + + // A reader-owned topic whose readers have all gone: writers fail. + bool Gone() + { + std::lock_guard lock(mutex_); + return GoneLocked(); + } + bool MatchesDescriptor(const MessageDescriptor& descriptor) const { return descriptor_ == descriptor; @@ -271,6 +288,7 @@ class TopicChannel final { } readers_.push_back(mailbox); + had_reader_ = true; return core::Status::Ok(); } @@ -289,6 +307,9 @@ class TopicChannel final { if (closed_) { return core::Status::FailedPrecondition("in-memory topic channel is closed: " + topic_.str()); } + if (GoneLocked()) { + return core::Status::NotFound("in-memory topic " + topic_.str() + " was closed by its reader"); + } message.payload = CopyBytes(payload); message.metadata.sequence = next_sequence_++; @@ -334,11 +355,23 @@ class TopicChannel final { } private: + // Gone once it had a reader and every reader has closed. A channel whose + // creating reader has not registered its mailbox yet is not gone. + bool GoneLocked() const + { + if (lifetime_ != core::TopicLifetime::kReaderOwned || !had_reader_) { + return false; + } + return std::none_of(readers_.begin(), readers_.end(), [](const auto& reader) { return !reader.expired(); }); + } + core::TopicName topic_; MessageDescriptor descriptor_; + core::TopicLifetime lifetime_; std::mutex mutex_; std::vector> readers_; core::SequenceNumber next_sequence_ {1}; + bool had_reader_ {false}; bool closed_ {false}; }; @@ -372,7 +405,10 @@ class InMemoryWriter final : public Writer { struct InMemoryTransport::State { mutable std::mutex mutex; - std::map> channels; + // Readers and writers own their channel; the map only finds it, so a + // topic is freed with its last endpoint and many short-lived topics do + // not accumulate. Expired entries are swept on each new endpoint. + std::map> channels; bool open {false}; core::Status Open() @@ -391,7 +427,9 @@ struct InMemoryTransport::State { open = false; for (const auto& entry : channels) { - entry.second->Close(); + if (auto channel = entry.second.lock()) { + channel->Close(); + } } channels.clear(); return core::Status::Ok(); @@ -403,8 +441,11 @@ struct InMemoryTransport::State { return open; } - core::Result> GetOrCreateChannel(const EndpointConfig& endpoint) + // Writers of a reader-owned topic only attach: they fail with NotFound + // when its reader has not created it, or has closed it. + core::Result> GetOrCreateChannel(const EndpointConfig& endpoint, bool writer) { + const bool reader_owned = endpoint.topic.lifetime == core::TopicLifetime::kReaderOwned; auto status = ValidateInMemoryEndpoint(endpoint); if (!status.ok()) { return core::Result>::FromStatus(std::move(status)); @@ -416,19 +457,40 @@ struct InMemoryTransport::State { core::Status::FailedPrecondition("in-memory transport must be open before creating endpoints")); } + for (auto entry = channels.begin(); entry != channels.end();) { + entry = entry->second.expired() ? channels.erase(entry) : std::next(entry); + } + const auto& key = endpoint.topic.name.str(); auto found = channels.find(key); if (found != channels.end()) { - if (!found->second->MatchesDescriptor(endpoint.message)) { - return core::Result>::FromStatus( - core::Status::InvalidArgument( - "in-memory topic " + endpoint.topic.name.str() + " carries " - + found->second->descriptor().ToString() + ", not " + endpoint.message.ToString())); + auto existing = found->second.lock(); + if (existing) { + if (existing->lifetime() != endpoint.topic.lifetime) { + return core::Result>::FromStatus(core::Status::InvalidArgument( + "in-memory topic " + key + " is " + core::ToString(existing->lifetime()) + ", not " + + core::ToString(endpoint.topic.lifetime))); + } + if (!existing->MatchesDescriptor(endpoint.message)) { + return core::Result>::FromStatus( + core::Status::InvalidArgument( + "in-memory topic " + endpoint.topic.name.str() + " carries " + + existing->descriptor().ToString() + ", not " + endpoint.message.ToString())); + } + if (!existing->Gone()) { + return existing; + } + // A new reader of a closed reader-owned topic starts a fresh + // one; writers still holding the old one keep failing. } - return found->second; + channels.erase(found); } - auto channel = std::make_shared(endpoint.topic.name, endpoint.message); + if (writer && reader_owned) { + return core::Result>::FromStatus( + core::Status::NotFound("in-memory topic " + key + " has no reader")); + } + auto channel = std::make_shared(endpoint.topic.name, endpoint.message, endpoint.topic.lifetime); channels.emplace(key, channel); return channel; } @@ -488,7 +550,7 @@ core::Status InMemoryTransport::ValidateEndpoint(const EndpointConfig& endpoint) core::Result InMemoryTransport::CreateReader(const EndpointConfig& endpoint) { - auto channel = state_->GetOrCreateChannel(endpoint); + auto channel = state_->GetOrCreateChannel(endpoint, false); if (!channel.ok()) { return core::Result::FromStatus(channel.status()); } @@ -503,12 +565,13 @@ core::Result InMemoryTransport::CreateReader(const EndpointConfig& en return core::Result::FromStatus(std::move(status)); } - return std::static_pointer_cast(std::make_shared(std::move(mailbox))); + return std::static_pointer_cast( + std::make_shared(std::move(mailbox), std::move(channel).value())); } core::Result InMemoryTransport::CreateWriter(const EndpointConfig& endpoint) { - auto channel = state_->GetOrCreateChannel(endpoint); + auto channel = state_->GetOrCreateChannel(endpoint, true); if (!channel.ok()) { return core::Result::FromStatus(channel.status()); } diff --git a/src/transport/shm/platform.h b/src/transport/shm/platform.h index 65d800b..b080177 100644 --- a/src/transport/shm/platform.h +++ b/src/transport/shm/platform.h @@ -31,10 +31,12 @@ std::string ObjectName(core::DomainId domain, std::string_view topic, std::strin class SharedRegion { public: // Creates the region with at least `size` bytes, or opens an existing one, - // which keeps its original size. Callers validate size() themselves. On - // Linux, waits up to `timeout` for a concurrent creator to size it. + // which keeps its original size. With `create` false it only opens an + // existing one, and is NotFound if there is none. Callers validate size() + // themselves. On Linux, waits up to `timeout` for a concurrent creator to + // size it. static core::Result> CreateOrOpen( - const std::string& name, std::size_t size, core::Nanoseconds timeout); + const std::string& name, std::size_t size, core::Nanoseconds timeout, bool create = true); // Unlinks the name so the next CreateOrOpen creates a fresh region; // existing mappings stay valid. A missing name is not an error. No-op on diff --git a/src/transport/shm/platform_linux.cpp b/src/transport/shm/platform_linux.cpp index 323d458..c6db86c 100644 --- a/src/transport/shm/platform_linux.cpp +++ b/src/transport/shm/platform_linux.cpp @@ -83,7 +83,7 @@ long Futex(std::atomic* word, int op, std::uint32_t value, const } // namespace core::Result> SharedRegion::CreateOrOpen( - const std::string& name, std::size_t size, core::Nanoseconds timeout) + const std::string& name, std::size_t size, core::Nanoseconds timeout, bool create) { using ResultType = core::Result>; if (size == 0) { @@ -91,7 +91,7 @@ core::Result> SharedRegion::CreateOrOpen( } bool created = true; - int fd = shm_open(name.c_str(), O_RDWR | O_CREAT | O_EXCL, 0600); + int fd = create ? shm_open(name.c_str(), O_RDWR | O_CREAT | O_EXCL, 0600) : -1; if (fd >= 0) { if (ftruncate(fd, static_cast(size)) != 0) { const int error = errno; @@ -99,11 +99,15 @@ core::Result> SharedRegion::CreateOrOpen( shm_unlink(name.c_str()); return ResultType::FromStatus(core::Status::ResourceExhausted(ErrnoMessage("ftruncate", error))); } - } else if (errno == EEXIST) { + } else if (!create || errno == EEXIST) { created = false; fd = shm_open(name.c_str(), O_RDWR, 0600); if (fd < 0) { - return ResultType::FromStatus(core::Status::Unavailable(ErrnoMessage("shm_open", errno))); + const int error = errno; + if (!create && error == ENOENT) { + return ResultType::FromStatus(core::Status::NotFound("shared region " + name + " does not exist")); + } + return ResultType::FromStatus(core::Status::Unavailable(ErrnoMessage("shm_open", error))); } // The creator sizes the region right after creating it. const auto deadline = core::SteadyClock::now() + timeout; diff --git a/src/transport/shm/platform_windows.cpp b/src/transport/shm/platform_windows.cpp index 7ecc015..3ca3240 100644 --- a/src/transport/shm/platform_windows.cpp +++ b/src/transport/shm/platform_windows.cpp @@ -52,23 +52,35 @@ std::string EventName(const std::string& base, std::uint32_t index) } // namespace core::Result> SharedRegion::CreateOrOpen( - const std::string& name, std::size_t size, core::Nanoseconds /*timeout*/) + const std::string& name, std::size_t size, core::Nanoseconds /*timeout*/, bool create) { using ResultType = core::Result>; if (size == 0) { return ResultType::FromStatus(core::Status::InvalidArgument("shared region size must be positive")); } - const auto size64 = static_cast(size); - // Page-file backed mappings are created and sized atomically and start - // zero-filled, so there is no creation race to wait out. - HANDLE mapping = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, - static_cast(size64 >> 32), static_cast(size64), - Widen(name).c_str()); - if (mapping == nullptr) { - return ResultType::FromStatus(core::Status::Unavailable(LastErrorMessage("CreateFileMappingW"))); + HANDLE mapping = nullptr; + bool created = false; + if (create) { + const auto size64 = static_cast(size); + // Page-file backed mappings are created and sized atomically and + // start zero-filled, so there is no creation race to wait out. + mapping = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE, + static_cast(size64 >> 32), static_cast(size64), + Widen(name).c_str()); + if (mapping == nullptr) { + return ResultType::FromStatus(core::Status::Unavailable(LastErrorMessage("CreateFileMappingW"))); + } + created = GetLastError() != ERROR_ALREADY_EXISTS; + } else { + mapping = OpenFileMappingW(FILE_MAP_ALL_ACCESS, FALSE, Widen(name).c_str()); + if (mapping == nullptr) { + if (GetLastError() == ERROR_FILE_NOT_FOUND) { + return ResultType::FromStatus(core::Status::NotFound("shared region " + name + " does not exist")); + } + return ResultType::FromStatus(core::Status::Unavailable(LastErrorMessage("OpenFileMappingW"))); + } } - const bool created = GetLastError() != ERROR_ALREADY_EXISTS; void* data = MapViewOfFile(mapping, FILE_MAP_ALL_ACCESS, 0, 0, 0); if (data == nullptr) { diff --git a/src/transport/shm/segment.cpp b/src/transport/shm/segment.cpp index 41d4df3..8a3190b 100644 --- a/src/transport/shm/segment.cpp +++ b/src/transport/shm/segment.cpp @@ -151,7 +151,7 @@ std::uint64_t ClampCursor(std::uint64_t cursor, std::uint64_t newest, std::uint6 core::Result> Segment::Open( core::DomainId domain, const Identity& identity, const SegmentGeometry& geometry, - core::Nanoseconds init_timeout) + core::Nanoseconds init_timeout, bool create) { using ResultType = core::Result>; if (!FitsName(identity.topic) || !FitsName(identity.descriptor.type_name) @@ -165,8 +165,11 @@ core::Result> Segment::Open( } const auto name = ObjectName(domain, identity.topic); - auto region = SharedRegion::CreateOrOpen(name, size, init_timeout); + auto region = SharedRegion::CreateOrOpen(name, size, init_timeout, create); if (!region.ok()) { + if (region.status().code() == core::StatusCode::kNotFound) { + return ResultType::FromStatus(core::Status::NotFound("shm topic " + identity.topic + " does not exist")); + } return ResultType::FromStatus(region.status()); } auto* header = static_cast(region.value()->data()); @@ -188,6 +191,7 @@ core::Result> Segment::Open( return ResultType::FromStatus(std::move(status)); } header->write_seq.store(0, std::memory_order_relaxed); + header->flags.store(0, std::memory_order_relaxed); // Publishing the magic last makes the header visible to openers. header->magic.store(kMagic, std::memory_order_release); } else { @@ -230,6 +234,11 @@ core::Result> Segment::Open( return ResultType::FromStatus(core::Status::FailedPrecondition( "shm segment is smaller than its declared geometry" + RemoveHint(name))); } + // On Windows a retired segment lives on while a writer still holds + // it; it is gone for anyone attaching now. + if ((header->flags.load(std::memory_order_acquire) & kSegmentRetired) != 0) { + return ResultType::FromStatus(core::Status::NotFound("shm topic " + identity.topic + " was closed by its reader")); + } } auto lock = WriterLock::Open(header->lock_storage, name); @@ -445,6 +454,22 @@ std::vector Segment::ActiveParticipants() const return active; } +bool Segment::HasLiveParticipant() noexcept +{ + ReclaimDeadParticipants(); + return !ActiveParticipants().empty(); +} + +void Segment::Retire() noexcept +{ + header_->flags.fetch_or(kSegmentRetired, std::memory_order_acq_rel); +} + +bool Segment::retired() const noexcept +{ + return (header_->flags.load(std::memory_order_acquire) & kSegmentRetired) != 0; +} + void Segment::ReclaimDeadParticipants() noexcept { for (auto& entry : header_->participants) { diff --git a/src/transport/shm/segment.h b/src/transport/shm/segment.h index 92adbdc..40d059b 100644 --- a/src/transport/shm/segment.h +++ b/src/transport/shm/segment.h @@ -25,6 +25,9 @@ inline constexpr std::uint32_t kLayoutVersion = 1; inline constexpr std::size_t kNameCapacity = 256; inline constexpr std::uint64_t kWritingBit = 1ULL << 63; inline constexpr std::size_t kSlotAlignment = 64; +// SegmentHeader::flags: the owning reader of a reader-owned topic closed, and +// the segment's name is being removed; writers still attached stop writing. +inline constexpr std::uint32_t kSegmentRetired = 1; struct SegmentGeometry { std::size_t slot_payload_size {0}; @@ -62,7 +65,9 @@ struct SegmentHeader { char encoding[kNameCapacity]; alignas(kSlotAlignment) std::atomic write_seq; std::atomic notify_word; - std::uint32_t reserved1; + // kSegment* bits. Was reserved (always 0) before 0.4, so the layout + // version stays the same. + std::atomic flags; alignas(WriterLock::kStorageAlignment) unsigned char lock_storage[WriterLock::kStorageSize]; ParticipantEntry participants[kMaxParticipants]; }; @@ -80,6 +85,8 @@ struct SlotHeader { static_assert(std::atomic::is_always_lock_free, "shared atomics must be lock-free"); static_assert(sizeof(std::atomic) == sizeof(std::uint64_t), "shared atomics must be plain words"); +static_assert(std::atomic::is_always_lock_free, "shared atomics must be lock-free"); +static_assert(sizeof(std::atomic) == sizeof(std::uint32_t), "shared atomics must be plain words"); std::size_t SlotStride(std::size_t slot_payload_size); std::size_t HeaderSize(); @@ -124,10 +131,11 @@ class Segment { }; // Creates the segment or attaches to an existing one, verifying that its - // layout, geometry, and identity match. + // layout, geometry, and identity match. With `create` false it only + // attaches, and is NotFound if the segment does not exist. static core::Result> Open( core::DomainId domain, const Identity& identity, const SegmentGeometry& geometry, - core::Nanoseconds init_timeout); + core::Nanoseconds init_timeout, bool create = true); ~Segment(); Segment(const Segment&) = delete; @@ -160,6 +168,14 @@ class Segment { core::Result ClaimParticipant(); void ReleaseParticipant(std::uint32_t index) noexcept; std::vector ActiveParticipants() const; + // Whether any process still running is attached, after reclaiming the + // entries of processes that exited. + bool HasLiveParticipant() noexcept; + + // Reader-owned topics: the owner marks the segment retired before + // removing its name, so writers still attached learn it is gone. + void Retire() noexcept; + bool retired() const noexcept; // Test-only: called inside Publish after the payload copy, before the // commit, with the writer lock held. Crash tests use it to kill a writer diff --git a/src/transport/shm/shm_transport.cpp b/src/transport/shm/shm_transport.cpp index f3933c1..3572b89 100644 --- a/src/transport/shm/shm_transport.cpp +++ b/src/transport/shm/shm_transport.cpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include #include @@ -61,16 +62,18 @@ struct ReaderState { // wakeups and callbacks. class TopicState final { public: + // `create`: whether this endpoint may create the segment. Writers of a + // reader-owned topic may not; they only attach to the reader's. static core::Result> Open( core::DomainId domain, const EndpointConfig& endpoint, const TopicOptions& topic_options, - core::Nanoseconds poll_interval) + core::Nanoseconds poll_interval, bool create) { using ResultType = core::Result>; auto segment = detail::Segment::Open( domain, detail::Segment::Identity {endpoint.topic.name.str(), endpoint.message}, detail::SegmentGeometry {topic_options.slot_payload_size, topic_options.slot_count}, - kSegmentInitTimeout); + kSegmentInitTimeout, create); if (!segment.ok()) { return ResultType::FromStatus(segment.status()); } @@ -85,8 +88,8 @@ class TopicState final { return ResultType::FromStatus(notifier.status()); } return ResultType(std::shared_ptr(new TopicState( - endpoint.message, std::move(segment).value(), participant.value(), std::move(notifier).value(), - poll_interval))); + endpoint.message, endpoint.topic.lifetime, std::move(segment).value(), participant.value(), + std::move(notifier).value(), poll_interval))); } ~TopicState() @@ -98,8 +101,12 @@ class TopicState final { TopicState& operator=(const TopicState&) = delete; const MessageDescriptor& descriptor() const noexcept { return descriptor_; } + core::TopicLifetime lifetime() const noexcept { return lifetime_; } detail::Segment& segment() const noexcept { return *segment_; } bool closed() const noexcept { return closed_.load(std::memory_order_acquire); } + bool reader_owned() const noexcept { return lifetime_ == core::TopicLifetime::kReaderOwned; } + // A reader-owned topic whose reader has gone; it takes no new endpoints. + bool gone() const noexcept { return reader_owned() && segment_->retired(); } core::Status AddReader(const std::shared_ptr& self, const std::shared_ptr& reader) { @@ -108,6 +115,7 @@ class TopicState final { return core::Status::Unavailable("shm topic is closed"); } readers_.push_back(reader); + had_reader_ = true; if (!dispatcher_.joinable()) { dispatcher_ = std::thread(&TopicState::DispatchLoop, std::weak_ptr(self), segment_->WriteSequence()); @@ -115,10 +123,19 @@ class TopicState final { return core::Status::Ok(); } + // The last reader of a reader-owned topic takes the topic with it, even + // while writers in this process still hold it: they fail from now on. void RemoveReader(const std::shared_ptr& reader) { - std::lock_guard lock(mutex_); - readers_.erase(std::remove(readers_.begin(), readers_.end(), reader), readers_.end()); + bool last = false; + { + std::lock_guard lock(mutex_); + readers_.erase(std::remove(readers_.begin(), readers_.end(), reader), readers_.end()); + last = readers_.empty(); + } + if (last && reader_owned()) { + RetireOnce(); + } } core::Status Publish(ByteView payload, WriteOptions options) @@ -126,6 +143,9 @@ class TopicState final { if (closed()) { return core::Status::Unavailable("shm writer is closed"); } + if (gone()) { + return Gone(); + } auto status = payload.Validate(); if (!status.ok()) { return status; @@ -138,6 +158,9 @@ class TopicState final { if (closed()) { return core::Status::Unavailable("shm writer is closed"); } + if (gone()) { + return Gone(); + } if (!fill) { return core::Status::InvalidArgument("fill function must not be empty"); } @@ -148,6 +171,7 @@ class TopicState final { { std::vector> readers; std::thread dispatcher; + bool had_reader = false; { std::lock_guard lock(mutex_); if (closed_.exchange(true, std::memory_order_acq_rel)) { @@ -155,6 +179,7 @@ class TopicState final { } readers.swap(readers_); dispatcher.swap(dispatcher_); + had_reader = had_reader_; } for (const auto& reader : readers) { reader->Close(); @@ -171,12 +196,25 @@ class TopicState final { } } segment_->ReleaseParticipant(participant_); + if (!reader_owned()) { + return; + } + if (!readers.empty() || had_reader) { + RetireOnce(); // closed with the transport, not reader by reader + } else if (!segment_->retired() && !segment_->HasLiveParticipant()) { + // Only writers here, and every process that was attached has + // exited: the reader crashed without retiring its topic. The + // last one out removes the name, so nothing is left behind. + detail::SharedRegion::Remove(segment_->name()); + } } private: - TopicState(MessageDescriptor descriptor, std::shared_ptr segment, std::uint32_t participant, - std::unique_ptr notifier, core::Nanoseconds poll_interval) noexcept + TopicState(MessageDescriptor descriptor, core::TopicLifetime lifetime, std::shared_ptr segment, + std::uint32_t participant, std::unique_ptr notifier, + core::Nanoseconds poll_interval) noexcept : descriptor_(std::move(descriptor)), + lifetime_(lifetime), segment_(std::move(segment)), participant_(participant), notifier_(std::move(notifier)), @@ -184,6 +222,23 @@ class TopicState final { { } + core::Status Gone() const + { + return core::Status::NotFound("shm topic in segment " + segment_->name() + " was closed by its reader"); + } + + // Marks the segment retired, so writers attached in other processes stop, + // wakes them, and removes its name, so none can attach any more. + void RetireOnce() noexcept + { + if (retired_by_me_.exchange(true)) { + return; + } + segment_->Retire(); + notifier_->NotifyAll(segment_->ActiveParticipants()); + detail::SharedRegion::Remove(segment_->name()); + } + static core::TimePoint Timestamp(const WriteOptions& options) { return options.source_timestamp == core::TimePoint {} ? Now() : options.source_timestamp; @@ -258,6 +313,7 @@ class TopicState final { } MessageDescriptor descriptor_; + core::TopicLifetime lifetime_; std::shared_ptr segment_; std::uint32_t participant_; std::unique_ptr notifier_; @@ -265,8 +321,10 @@ class TopicState final { std::mutex mutex_; std::vector> readers_; + bool had_reader_ {false}; // guarded by mutex_ std::thread dispatcher_; std::atomic closed_ {false}; + std::atomic retired_by_me_ {false}; }; class ShmReader final : public Reader { @@ -403,6 +461,12 @@ core::Status Options::Validate() const return core::Status::InvalidArgument(status.message() + " (topic " + entry.first + ")"); } } + for (const auto& entry : topic_prefixes) { + status = entry.second.Validate(); + if (!status.ok()) { + return core::Status::InvalidArgument(status.message() + " (topics under " + entry.first + ")"); + } + } if (wait_poll_interval <= core::Nanoseconds::zero()) { return core::Status::InvalidArgument("shm wait_poll_interval must be greater than zero"); } @@ -412,7 +476,18 @@ core::Status Options::Validate() const const TopicOptions& Options::ForTopic(const std::string& topic) const { const auto found = topics.find(topic); - return found == topics.end() ? default_topic : found->second; + if (found != topics.end()) { + return found->second; + } + const TopicOptions* best = &default_topic; + std::size_t best_length = 0; + for (const auto& [prefix, options] : topic_prefixes) { + if (prefix.size() > best_length && topic.compare(0, prefix.size(), prefix) == 0) { + best = &options; + best_length = prefix.size(); + } + } + return *best; } core::Status RegisterTransport(runtime::RuntimeContext& runtime, core::TransportName name, Options options) @@ -428,24 +503,26 @@ core::Result OptionsFromProject(const configuration::ProjectConfig& pro { using ResultType = core::Result; - // Each ipc topic with settings, plus the three topics of each ipc service - // with settings, which share the service's. + // Each ipc topic with settings, plus the topics of each ipc service with + // settings, which share the service's: request and presence by name, and + // the per-client reply topics by the prefix `/reply/`. struct Entry { std::string label; std::vector topics; const runtime::ParameterMap* parameters; + std::string prefix; }; std::vector entries; for (const auto& topic : project.topics) { if (topic.transport == core::TransportKind::kIpc && !topic.transport_parameters.empty()) { - entries.push_back(Entry {"topic " + topic.name, {topic.name}, &topic.transport_parameters}); + entries.push_back(Entry {"topic " + topic.name, {topic.name}, &topic.transport_parameters, {}}); } } for (const auto& service : project.services) { if (service.transport == core::TransportKind::kIpc && !service.transport_parameters.empty()) { entries.push_back(Entry {"service " + service.name, {service.name + "/request", service.name + "/reply", service.name + "/presence"}, - &service.transport_parameters}); + &service.transport_parameters, service.name + "/reply/"}); } } @@ -497,6 +574,9 @@ core::Result OptionsFromProject(const configuration::ProjectConfig& pro for (const auto& topic : entry_info.topics) { base.topics[topic] = geometry; } + if (!entry_info.prefix.empty()) { + base.topic_prefixes[entry_info.prefix] = geometry; + } } auto status = base.Validate(); if (!status.ok()) { @@ -616,7 +696,10 @@ core::Result> RemoveUnusedSegments(std::optional> topics; + // Readers and writers own their topic; the map only finds it, so a topic + // is unmapped, and its participant entry released, with its last + // endpoint in this process. Expired entries are swept on each new one. + std::map> topics; }; ShmTransport::ShmTransport(core::TransportName name, Options options) @@ -664,14 +747,16 @@ core::Status ShmTransport::Open() core::Status ShmTransport::Close() noexcept { - std::map> topics; + std::map> topics; { std::lock_guard lock(impl_->mutex); impl_->open = false; topics.swap(impl_->topics); } for (auto& entry : topics) { - entry.second->Close(); + if (auto topic = entry.second.lock()) { + topic->Close(); + } } return core::Status::Ok(); } @@ -709,27 +794,49 @@ core::Status ShmTransport::ValidateEndpoint(const EndpointConfig& endpoint) cons namespace { +// Writers of a reader-owned topic only attach: they fail with NotFound when +// its reader has not created it, or has closed it. core::Result> GetOrOpenTopic( - std::mutex& mutex, bool& open, std::map>& topics, - const Options& options, const EndpointConfig& endpoint, const char* what) + std::mutex& mutex, bool& open, std::map>& topics, + const Options& options, const EndpointConfig& endpoint, bool writer) { + const char* what = writer ? "writers" : "readers"; + const bool reader_owned = endpoint.topic.lifetime == core::TopicLifetime::kReaderOwned; using ResultType = core::Result>; std::lock_guard lock(mutex); if (!open) { return ResultType::FromStatus(core::Status::FailedPrecondition( std::string("shm transport must be open before creating ") + what)); } + for (auto entry = topics.begin(); entry != topics.end();) { + entry = entry->second.expired() ? topics.erase(entry) : std::next(entry); + } const auto& key = endpoint.topic.name.str(); const auto found = topics.find(key); if (found != topics.end()) { - if (found->second->descriptor() != endpoint.message) { - return ResultType::FromStatus(core::Status::InvalidArgument( - "shm topic " + key + " carries " + found->second->descriptor().ToString() + ", not " - + endpoint.message.ToString())); + auto existing = found->second.lock(); + if (existing) { + if (existing->lifetime() != endpoint.topic.lifetime) { + return ResultType::FromStatus(core::Status::InvalidArgument( + "shm topic " + key + " is " + core::ToString(existing->lifetime()) + " in this process, not " + + core::ToString(endpoint.topic.lifetime))); + } + if (existing->descriptor() != endpoint.message) { + return ResultType::FromStatus(core::Status::InvalidArgument( + "shm topic " + key + " carries " + existing->descriptor().ToString() + ", not " + + endpoint.message.ToString())); + } + if (!existing->gone()) { + return ResultType(std::move(existing)); + } + // Retired: the old topic stays with the endpoints that still hold + // it. A new reader starts a fresh one under the name, and a new + // writer attaches to that fresh one, or is NotFound. } - return ResultType(found->second); + topics.erase(found); } - auto topic = TopicState::Open(options.domain_id, endpoint, options.ForTopic(key), options.wait_poll_interval); + auto topic = TopicState::Open(options.domain_id, endpoint, options.ForTopic(key), options.wait_poll_interval, + !(writer && reader_owned)); if (!topic.ok()) { return topic; } @@ -745,7 +852,7 @@ core::Result ShmTransport::CreateReader(const EndpointConfig& endpoin if (!status.ok()) { return core::Result::FromStatus(std::move(status)); } - auto topic = GetOrOpenTopic(impl_->mutex, impl_->open, impl_->topics, options_, endpoint, "readers"); + auto topic = GetOrOpenTopic(impl_->mutex, impl_->open, impl_->topics, options_, endpoint, false); if (!topic.ok()) { return core::Result::FromStatus(topic.status()); } @@ -770,7 +877,7 @@ core::Result ShmTransport::CreateWriter(const EndpointConfig& endpoin if (!status.ok()) { return core::Result::FromStatus(std::move(status)); } - auto topic = GetOrOpenTopic(impl_->mutex, impl_->open, impl_->topics, options_, endpoint, "writers"); + auto topic = GetOrOpenTopic(impl_->mutex, impl_->open, impl_->topics, options_, endpoint, true); if (!topic.ok()) { return core::Result::FromStatus(topic.status()); } diff --git a/test/fastdds_transport_test.cpp b/test/fastdds_transport_test.cpp index cd77cdd..559acff 100644 --- a/test/fastdds_transport_test.cpp +++ b/test/fastdds_transport_test.cpp @@ -391,8 +391,36 @@ void ReadWhileListenerRuns() assert(context.value()->Close().ok()); } +// A topic is deleted from the participant with its last endpoint: afterwards +// the name can carry another type, which a live topic refuses. +void TopicIsDeletedWithItsLastEndpoint() +{ + auto fastdds_transport = MakeTransport(); + assert(fastdds_transport->Open().ok()); + const auto first = MakeEndpoint("/fastdds/freed", "test.First"); + const auto second = MakeEndpoint("/fastdds/freed", "test.Second"); + { + auto writer = fastdds_transport->CreateWriter(first); + auto reader = fastdds_transport->CreateReader(first); + assert(writer.ok() && reader.ok()); + assert(fastdds_transport->CreateWriter(second).status().code() == core::StatusCode::kInvalidArgument); + } + auto reused = fastdds_transport->CreateWriter(second); + assert(reused.ok()); + reused.value().reset(); + + // Many short-lived topics, as per-client reply topics are. + for (int index = 0; index < 200; ++index) { + auto writer = fastdds_transport->CreateWriter( + MakeEndpoint("/fastdds/many/" + std::to_string(index), "test.First")); + assert(writer.ok()); + } + assert(fastdds_transport->Close().ok()); +} + int main() { + TopicIsDeletedWithItsLastEndpoint(); RejectsEndpointsBeforeOpen(); RejectsForeignTransportKind(); RejectsUnsupportedOverflowPolicy(); diff --git a/test/inmemory_transport_test.cpp b/test/inmemory_transport_test.cpp index 8668a5a..29f6a90 100644 --- a/test/inmemory_transport_test.cpp +++ b/test/inmemory_transport_test.cpp @@ -297,6 +297,71 @@ void UnboundedQueueKeepsAllMessages() } } // namespace +// A topic is freed with its last endpoint: afterwards the same name can carry +// another type, which a live topic refuses. +void TopicIsFreedWithItsLastEndpoint() +{ + auto transport = MakeOpenTransport(); + const auto endpoint = MakeEndpoint("/inmemory/freed", {}); + auto other = endpoint; + other.message.type_name = "test.Other"; + { + auto writer = transport->CreateWriter(endpoint); + auto reader = transport->CreateReader(endpoint); + assert(writer.ok() && reader.ok()); + assert(transport->CreateReader(other).status().code() == core::StatusCode::kInvalidArgument); + // A reader alone keeps the topic: a writer created later reaches it. + writer.value().reset(); + auto later = transport->CreateWriter(endpoint); + assert(later.ok()); + assert(WriteString(later.value(), "still here").ok()); + assert(ReadString(reader.value()) == "still here"); + } + auto reused = transport->CreateReader(other); + assert(reused.ok()); + + // Many short-lived topics, as per-client reply topics are. + for (int index = 0; index < 1000; ++index) { + auto writer = transport->CreateWriter(MakeEndpoint("/inmemory/many/" + std::to_string(index), {})); + assert(writer.ok()); + } + assert(transport->Close().ok()); +} + +// A reader-owned topic belongs to its reader: writers only attach to it, and +// fail with NotFound once the reader is gone. +void ReaderOwnedTopicBelongsToItsReader() +{ + auto transport = MakeOpenTransport(); + auto endpoint = MakeEndpoint("/inmemory/owned", {}); + endpoint.topic.lifetime = core::TopicLifetime::kReaderOwned; + + assert(transport->CreateWriter(endpoint).status().code() == core::StatusCode::kNotFound); + auto reader = transport->CreateReader(endpoint); + assert(reader.ok()); + auto writer = transport->CreateWriter(endpoint); + assert(writer.ok()); + assert(WriteString(writer.value(), "reply").ok()); + assert(ReadString(reader.value()) == "reply"); + + // The lifetime is part of the topic: a shared endpoint is refused. + const auto shared = MakeEndpoint("/inmemory/owned", {}); + assert(transport->CreateWriter(shared).status().code() == core::StatusCode::kInvalidArgument); + + reader.value().reset(); + assert(WriteString(writer.value(), "late").code() == core::StatusCode::kNotFound); + assert(transport->CreateWriter(endpoint).status().code() == core::StatusCode::kNotFound); + + // A new reader starts a fresh topic; the old writer stays closed out. + auto next = transport->CreateReader(endpoint); + assert(next.ok()); + assert(WriteString(writer.value(), "late").code() == core::StatusCode::kNotFound); + auto fresh = transport->CreateWriter(endpoint); + assert(fresh.ok()); + assert(WriteString(fresh.value(), "again").ok()); + assert(ReadString(next.value()) == "again"); + assert(transport->Close().ok()); +} int main() { @@ -309,5 +374,7 @@ int main() FullReaderDoesNotPreventDeliveryToOtherReaders(); BoundedQueueDropsOldestMessage(); UnboundedQueueKeepsAllMessages(); + TopicIsFreedWithItsLastEndpoint(); + ReaderOwnedTopicBelongsToItsReader(); return 0; } diff --git a/test/json_imports_test.cpp b/test/json_imports_test.cpp index ff4c21d..8c1ed8b 100644 --- a/test/json_imports_test.cpp +++ b/test/json_imports_test.cpp @@ -369,7 +369,9 @@ void ServicesThroughConfiguration() // The deployment sizes all three of the service's shm topics. auto shm_options = shm::OptionsFromProject(server.value()); assert(shm_options.ok()); - for (const char* topic : {"/map/query/request", "/map/query/reply", "/map/query/presence"}) { + // Per-client reply topics, `/reply/`, by prefix. + for (const char* topic : {"/map/query/request", "/map/query/reply", "/map/query/presence", + "/map/query/reply/000000000000002a"}) { assert(shm_options.value().ForTopic(topic).slot_payload_size == 2048); } diff --git a/test/service_test.cpp b/test/service_test.cpp index d08a7dc..ba13cb4 100644 --- a/test/service_test.cpp +++ b/test/service_test.cpp @@ -115,6 +115,15 @@ void SpecValidation() assert(endpoints.value().reply.message.type_name == "service.reply:test.Text"); assert(endpoints.value().request.topic.message_policy.queue_depth == 16); + // Replies go to one topic per client, which the client's reader owns. + assert(endpoints.value().reply.topic.lifetime == core::TopicLifetime::kReaderOwned); + auto own = service::ReplyEndpointFor(spec, 0x2aULL); + assert(own.ok() && own.value().topic.name.str() == "/svc/valid/reply/000000000000002a"); + assert(own.value().message == endpoints.value().reply.message); + // A name too long for its per-client reply topics fails up front. + auto long_spec = Spec("/" + std::string(240, 'n')); + assert(service::EndpointsFor(long_spec).status().code() == core::StatusCode::kInvalidArgument); + auto bad = spec; bad.queue_depth = 0; assert(bad.Validate().code() == core::StatusCode::kInvalidArgument); @@ -127,6 +136,44 @@ void SpecValidation() auto runtime = MakeRuntime(); assert(service::Server::Create(*runtime, spec, {}).status().code() == core::StatusCode::kInvalidArgument); + service::ServerOptions no_idle; + no_idle.reply_idle_timeout = 0ms; + assert(service::Server::Create(*runtime, spec, Reverse, no_idle).status().code() + == core::StatusCode::kInvalidArgument); +} + +// Each client reads only its own reply topic: another client's calls put +// nothing there. +void RepliesReachOnlyTheirClient() +{ + auto runtime = MakeRuntime(); + auto spec = Spec("/svc/own-replies"); + auto server = service::Server::Create(*runtime, spec, Reverse); + auto first = service::Client::Create(*runtime, spec); + auto second = service::Client::Create(*runtime, spec); + assert(server.ok() && first.ok() && second.ok()); + assert(first.value()->client_id() != second.value()->client_id()); + + // A spy on the second client's reply topic sees what that client sees. + auto endpoint = service::ReplyEndpointFor(spec, second.value()->client_id()); + assert(endpoint.ok()); + auto spy = runtime->CreateReader(endpoint.value()); + assert(spy.ok()); + + for (int call = 0; call < 20; ++call) { + auto reply = first.value()->Call(Bytes("abc"), 1s); + assert(reply.ok() && Text(reply.value()) == "cba"); + } + assert(spy.value()->PendingMessageCount().value() == 0); + assert(second.value()->Call(Bytes("xy"), 1s).ok()); + assert(spy.value()->PendingMessageCount().value() == 1); + + // A closed client's topic is gone: a late reply to it is dropped, and + // the server keeps serving the others. + spy.value().reset(); + first.value()->Close(); + assert(second.value()->Call(Bytes("ok"), 1s).ok()); + assert(server.value()->handled_count() == 22); } void CallsAndErrors() @@ -206,7 +253,7 @@ void ManyClientsAndThreads() } // Each reply must reach the call that sent its request, across clients - // that all see every reply and threads that share one client. + // and across threads that share one client. std::atomic correct {0}; std::vector threads; for (int index = 0; index < 6; ++index) { @@ -561,6 +608,7 @@ int main() AsyncServerStops(); TypedServicesAndVersions(); ServicesFromComponentSpec(); + RepliesReachOnlyTheirClient(); std::cout << "service tests passed\n"; return 0; } diff --git a/test/shm_service_test.cpp b/test/shm_service_test.cpp index 0b089a9..6385d55 100644 --- a/test/shm_service_test.cpp +++ b/test/shm_service_test.cpp @@ -82,12 +82,25 @@ int RunServer(const std::string& name) return 0; } +// Child: call once, then wait to be killed, leaving its reply topic behind +// as a crashed client would. +int RunClient(const std::string& name) +{ + auto context = MakeRuntime(); + auto client = service::Client::Create(*context, Spec(name)); + if (!client.ok() || !client.value()->Call(transport::ByteView::From("hi", 2), 5s).ok()) { + return 2; + } + std::this_thread::sleep_for(30s); + return 0; +} + #ifdef _WIN32 using ChildHandle = HANDLE; -ChildHandle StartServer(const std::string& executable, const std::string& name) +ChildHandle StartChild(const std::string& executable, const char* mode, const std::string& name) { - std::string command = "\"" + executable + "\" --server " + name; + std::string command = "\"" + executable + "\" " + mode + " " + name; STARTUPINFOA startup {}; startup.cb = sizeof(startup); PROCESS_INFORMATION process {}; @@ -107,12 +120,12 @@ void Kill(ChildHandle child) #else using ChildHandle = pid_t; -ChildHandle StartServer(const std::string& executable, const std::string& name) +ChildHandle StartChild(const std::string& executable, const char* mode, const std::string& name) { const pid_t pid = fork(); assert(pid >= 0); if (pid == 0) { - execl(executable.c_str(), executable.c_str(), "--server", name.c_str(), nullptr); + execl(executable.c_str(), executable.c_str(), mode, name.c_str(), nullptr); std::_Exit(127); } return pid; @@ -126,6 +139,64 @@ void Kill(ChildHandle child) } #endif +ChildHandle StartServer(const std::string& executable, const std::string& name) +{ + return StartChild(executable, "--server", name); +} + +#ifndef _WIN32 +// Reply segments of `service` on this host, by topic name. +std::vector ReplySegments(const std::string& service) +{ + auto segments = shm::ListSegments(kDomain); + assert(segments.ok()); + std::vector topics; + for (const auto& segment : segments.value()) { + if (segment.topic.rfind(service + "/reply/", 0) == 0) { + topics.push_back(segment.topic); + } + } + return topics; +} + +void WaitUntilNoReplySegments(const std::string& service) +{ + const auto deadline = std::chrono::steady_clock::now() + 5s; + while (!ReplySegments(service).empty()) { + assert(std::chrono::steady_clock::now() < deadline); + std::this_thread::sleep_for(10ms); + } +} + +// A crashed client cannot remove its reply topic. The server closes its +// writer for that client after reply_idle_timeout and, being the last one +// attached, removes the segment, so nothing is left in /dev/shm. +void CrashedClientLeavesNoSegment(const std::string& executable) +{ + const auto name = "/pm/service-crash/" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()); + RemoveSegments(name); + auto context = MakeRuntime(); + service::ServerOptions options; + options.reply_idle_timeout = 100ms; + auto server = service::Server::Create(*context, Spec(name), [](const service::Request& request) { + return core::Result(transport::ByteBuffer(request.payload.begin(), request.payload.end())); + }, options); + assert(server.ok()); + + auto child = StartChild(executable, "--client", name); + const auto deadline = std::chrono::steady_clock::now() + 10s; + while (server.value()->handled_count() == 0) { + assert(std::chrono::steady_clock::now() < deadline); + std::this_thread::sleep_for(5ms); + } + assert(ReplySegments(name).size() == 1); + Kill(child); + WaitUntilNoReplySegments(name); + server.value()->Close(); + RemoveSegments(name); +} +#endif + void CrossProcessCallsAndCrash(const std::string& executable) { const auto name = "/pm/service-test/" + std::to_string(std::chrono::steady_clock::now().time_since_epoch().count()); @@ -164,7 +235,14 @@ void CrossProcessCallsAndCrash(const std::string& executable) auto reply = c.Call(transport::ByteView::From("ok", 2), 2s); assert(reply.ok() && std::string(reply.value().begin(), reply.value().end()) == "ko"); Kill(restarted); +#ifndef _WIN32 + // The client's own reply topic exists while it is open, and goes with it. + assert(ReplySegments(name).size() == 1); +#endif c.Close(); +#ifndef _WIN32 + WaitUntilNoReplySegments(name); +#endif RemoveSegments(name); } @@ -175,7 +253,13 @@ int main(int argc, char** argv) if (argc == 3 && std::string(argv[1]) == "--server") { return RunServer(argv[2]); } + if (argc == 3 && std::string(argv[1]) == "--client") { + return RunClient(argv[2]); + } CrossProcessCallsAndCrash(argv[0]); +#ifndef _WIN32 + CrashedClientLeavesNoSegment(argv[0]); +#endif std::cout << "shm service tests passed\n"; return 0; } diff --git a/test/shm_transport_test.cpp b/test/shm_transport_test.cpp index a9551f7..7330776 100644 --- a/test/shm_transport_test.cpp +++ b/test/shm_transport_test.cpp @@ -1,6 +1,8 @@ +#include #include #include #include +#include #include #include #include @@ -218,7 +220,10 @@ void DescriptorConflicts() { const TopicCleanup cleanup {UniqueTopic("descriptor")}; auto first = MakeTransport(); - assert(first->CreateWriter(Endpoint(cleanup.topic)).ok()); + // Held: a topic is released with its last endpoint, and on Windows the + // segment with its last handle, after which the name is free again. + auto writer = first->CreateWriter(Endpoint(cleanup.topic)); + assert(writer.ok()); auto same_process = first->CreateReader(Endpoint(cleanup.topic, {}, "test.Other")); assert(same_process.status().code() == core::StatusCode::kInvalidArgument); @@ -242,7 +247,9 @@ void VersionConflicts() v3.message.version = 3; auto first = MakeTransport(); - assert(first->CreateWriter(v2).ok()); + // Held, so the v2 topic stays open; see DescriptorConflicts. + auto writer = first->CreateWriter(v2); + assert(writer.ok()); assert(first->CreateReader(v2).ok()); auto same_process = first->CreateReader(v3); assert(same_process.status().code() == core::StatusCode::kInvalidArgument); @@ -513,6 +520,186 @@ int WaitChild(ChildHandle child) } #endif +void KillChild(ChildHandle child) +{ +#ifdef _WIN32 + TerminateProcess(child, 1); + WaitForSingleObject(child, INFINITE); + CloseHandle(child); +#else + int status = 0; + kill(child, SIGKILL); + waitpid(child, &status, 0); +#endif +} + +transport::EndpointConfig Owned(const std::string& topic, core::MessagePolicy policy = {}) +{ + auto endpoint = Endpoint(topic, policy); + endpoint.topic.lifetime = core::TopicLifetime::kReaderOwned; + return endpoint; +} + +// Prefix overrides size every topic under a name, such as a service's +// per-client reply topics; an exact entry and a longer prefix win. +void PrefixOptions() +{ + shm::Options options; + options.topic_prefixes["/svc/"] = shm::TopicOptions {64, 2}; + options.topic_prefixes["/svc/reply/"] = shm::TopicOptions {128, 4}; + options.topics["/svc/reply/special"] = shm::TopicOptions {256, 8}; + assert(options.Validate().ok()); + assert(options.ForTopic("/svc/reply/1").slot_count == 4); + assert(options.ForTopic("/svc/reply/special").slot_count == 8); + assert(options.ForTopic("/svc/request").slot_count == 2); + assert(options.ForTopic("/other").slot_count == options.default_topic.slot_count); + options.topic_prefixes["/bad/"] = shm::TopicOptions {64, 0}; + assert(options.Validate().code() == core::StatusCode::kInvalidArgument); +} + +// A reader-owned topic belongs to its reader: writers only attach to it, and +// fail with NotFound once the reader has closed it, in this process and in +// others (here a second transport, which maps the segment on its own). +void ReaderOwnedTopicBelongsToItsReader() +{ + const auto topic = UniqueTopic("owned"); + TopicCleanup cleanup {topic}; + auto client = MakeTransport(); + auto server = MakeTransport(); + + assert(server->CreateWriter(Owned(topic)).status().code() == core::StatusCode::kNotFound); + auto reader = client->CreateReader(Owned(topic, Queued(4))); + assert(reader.ok()); + auto local = client->CreateWriter(Owned(topic)); + auto remote = server->CreateWriter(Owned(topic)); + assert(local.ok() && remote.ok()); + Write(*remote.value(), "reply"); + auto message = ReadWait(*reader.value()); + assert(message.ok() && Text(message.value()) == "reply"); + + // The lifetime is part of the topic in a process. + assert(client->CreateWriter(Endpoint(topic)).status().code() == core::StatusCode::kInvalidArgument); + + reader.value().reset(); + const auto late = transport::ByteView::From("late", 4); + assert(remote.value()->Write(late).code() == core::StatusCode::kNotFound); + assert(local.value()->Write(late).code() == core::StatusCode::kNotFound); + assert(server->CreateWriter(Owned(topic)).status().code() == core::StatusCode::kNotFound); + assert(client->CreateWriter(Owned(topic)).status().code() == core::StatusCode::kNotFound); + +#ifndef _WIN32 + // A new reader starts a fresh topic; writers of the old one stay out. + // Not on Windows, where the name stays taken until the old segment's + // last handle closes; service clients use a new name each time. + auto next = client->CreateReader(Owned(topic, Queued(4))); + assert(next.ok()); + assert(remote.value()->Write(late).code() == core::StatusCode::kNotFound); + auto fresh = server->CreateWriter(Owned(topic)); + assert(fresh.ok()); + Write(*fresh.value(), "again"); + message = ReadWait(*next.value()); + assert(message.ok() && Text(message.value()) == "again"); +#endif +} + +// Child: own a reader-owned topic until killed. +int RunOwnedReader(const std::string& topic) +{ + auto shm_transport = MakeTransport(); + auto reader = shm_transport->CreateReader(Owned(topic)); + if (!reader.ok()) { + return 2; + } + std::this_thread::sleep_for(30s); + return 0; +} + +// A reader that crashes cannot retire its topic. The last writer out, seeing +// no live process attached, removes it, so no segment is left behind. +void CrashedReaderTopicIsRemovedByLastWriter(const std::string& executable) +{ + const auto topic = UniqueTopic("crashed"); + TopicCleanup cleanup {topic}; + auto child = StartChild(executable, {"--owned-reader", topic}); + auto shm_transport = MakeTransport(); + transport::WriterPtr writer; + const auto deadline = std::chrono::steady_clock::now() + 10s; + while (!writer) { + auto created = shm_transport->CreateWriter(Owned(topic)); + if (created.ok()) { + writer = created.value(); + } else { + assert(created.status().code() == core::StatusCode::kNotFound); + assert(std::chrono::steady_clock::now() < deadline); + std::this_thread::sleep_for(5ms); + } + } + KillChild(child); + Write(*writer, "to nobody"); // not retired: the reader never said goodbye + writer.reset(); + assert(shm_transport->CreateWriter(Owned(topic)).status().code() == core::StatusCode::kNotFound); +} + +#ifndef _WIN32 +// Whether this process holds a participant entry in the topic's segment. +bool Attached(const std::string& topic) +{ + auto segments = shm::ListSegments(kDomain); + assert(segments.ok()); + for (const auto& segment : segments.value()) { + if (segment.topic == topic) { + const auto self = static_cast(getpid()); + return std::find(segment.live_pids.begin(), segment.live_pids.end(), self) != segment.live_pids.end(); + } + } + return false; +} +#endif + +// A topic is released with its last endpoint in this process: the mapping +// and the participant entry go. Linux keeps the segment for other processes; +// Windows frees it with its last handle. +void TopicIsReleasedWithItsLastEndpoint() +{ + auto shm_transport = MakeTransport(); + const auto topic = UniqueTopic("released"); + TopicCleanup cleanup {topic}; + { + auto writer = shm_transport->CreateWriter(Endpoint(topic)); + auto reader = shm_transport->CreateReader(Endpoint(topic)); + assert(writer.ok() && reader.ok()); + // A reader alone keeps the topic: a writer created later reaches it. + writer.value().reset(); + auto later = shm_transport->CreateWriter(Endpoint(topic)); + assert(later.ok()); + Write(*later.value(), "still here"); + auto message = ReadWait(*reader.value()); + assert(message.ok() && Text(message.value()) == "still here"); +#ifndef _WIN32 + assert(Attached(topic)); +#endif + } + // The reader's dispatcher may hold the topic for one more wait. +#ifndef _WIN32 + const auto deadline = std::chrono::steady_clock::now() + 2s; + while (Attached(topic)) { + assert(std::chrono::steady_clock::now() < deadline); + std::this_thread::sleep_for(5ms); + } +#else + // Freed with the last handle, so another geometry is accepted. + shm::Options options; + options.topics[topic] = shm::TopicOptions {128, 4}; + auto other = MakeTransport(options); + const auto deadline = std::chrono::steady_clock::now() + 2s; + while (!other->CreateWriter(Endpoint(topic)).ok()) { + assert(std::chrono::steady_clock::now() < deadline); + std::this_thread::sleep_for(5ms); + } +#endif + assert(shm_transport->Close().ok()); +} + constexpr int kCrossProcessMessages = 200; // Child: publish until the parent acknowledges every message. @@ -631,6 +818,9 @@ int main(int argc, char** argv) if (argc == 3 && std::string(argv[1]) == "--publisher") { return RunPublisher(argv[2]); } + if (argc == 3 && std::string(argv[1]) == "--owned-reader") { + return RunOwnedReader(argv[2]); + } assert(argc == 1); OptionsAndCapabilities(); @@ -644,6 +834,10 @@ int main(int argc, char** argv) ReleaseFromCallback(); RuntimeRegistration(); WriteWithFillsInPlace(); + TopicIsReleasedWithItsLastEndpoint(); + PrefixOptions(); + ReaderOwnedTopicBelongsToItsReader(); + CrashedReaderTopicIsRemovedByLastWriter(argv[0]); CrossProcessDelivery(argv[0]); CrossProcessVersionMismatch(argv[0]); std::cout << "shm transport tests passed\n"; diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index b4f0816..2cf1678 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -1,4 +1,5 @@ -# Command-line tools. They read JSON, so they need the JSON adapter. +# Command-line tools. They read JSON, so they need the JSON adapter. Their +# install RPATH is set in the top-level CMakeLists.txt. add_executable(puppet_master_config puppet_master_config.cpp