From 789b4358d7c519156e5f8351c76d75827bd2833b Mon Sep 17 00:00:00 2001 From: SoleyRan Date: Wed, 4 Nov 2026 10:34:30 +0800 Subject: [PATCH 1/6] feat: service list and service call in puppet_master_topic service list --system FILE shows each service the system's nodes declare, its request and reply types, transport, which components serve and call it, and whether a server is up, with its instance id and the age of its newest heartbeat. It reads only the presence topics, so it creates no client and no reply topic. service call SERVICE --system FILE sends one request (--data TEXT, --hex HEX, or none) through an ordinary service::Client and prints the reply's size, round trip, and bytes, or exits with 1 and the call's status. Both work on shared memory and, when built with it, FastDDS. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 12 + docs/launcher.md | 35 ++- docs/services.md | 3 + test/topic_tool_fastdds_test.cpp | 49 +++- test/topic_tool_test.cpp | 116 ++++++++- tools/puppet_master_topic.cpp | 435 ++++++++++++++++++++++++++++++- 6 files changed, 635 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cc77036..53b0272 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,18 @@ each minor release may break the API and the ABI: the shared libraries carry the minor version in their soname (`libpuppet_master.so.0.4`), and `find_package(PuppetMaster 0.4)` accepts only 0.4.x. +## Unreleased + +### Added + +- **Service commands in the topic tool.** `puppet_master_topic service list + --system FILE` shows each service the system declares, who serves and + calls it, and whether its server is up, from the presence topic alone. + `service call SERVICE --system FILE` sends one request (`--data TEXT` or + `--hex HEX`) through an ordinary client and prints the reply, or exits + with 1 and the call's status. Both work on shared memory and, when built + with it, FastDDS. See [Services](docs/launcher.md#services). + ## 0.4.0 Rebuild everything that links PuppetMaster: the soname is now diff --git a/docs/launcher.md b/docs/launcher.md index 681e105..f7330d6 100644 --- a/docs/launcher.md +++ b/docs/launcher.md @@ -186,8 +186,9 @@ In C++, `configuration::Supervisor` in `puppet_master_topic` looks at the shared-memory topics of a running system, and its FastDDS topics when built with that adapter (see -[FastDDS Topics](#fastdds-topics)). It is built and installed with the JSON -and shared-memory adapters. +[FastDDS Topics](#fastdds-topics)), and at its services (see +[Services](#services)). It is built and installed with the JSON and +shared-memory adapters. ```bash puppet_master_topic list @@ -248,6 +249,36 @@ The tool also records and replays topics: See [Recordings](recording.md). +### Services + +The tool also looks at a system's services and calls them. Both commands +need `--system FILE`; `--domain N` picks the domain as for topics. + +```bash +puppet_master_topic service list --system system.json +puppet_master_topic service call /map/query --system system.json --data "a b" --text +puppet_master_topic service call /map/query --system system.json --hex "01 00 2a" +``` + +| Command | Effect | +|---|---| +| `service list` | each service the manifest's nodes declare: request and reply types, transport, which components serve and call it, and whether a server is up, with its instance id and the age of its newest heartbeat | +| `service call SERVICE` | send one request, the bytes of `--data TEXT`, of `--hex HEX`, or none, and print the reply's size, round trip, and bytes (in hex, or `--text`; all of them unless `--bytes N`) | + +`service list` reads each service's presence topic only, so it creates no +client and no reply topic. It listens for three heartbeat intervals (at +least 1 s on FastDDS, for discovery), or `--timeout-ms N`. A server is +`down` when no heartbeat arrived in that time, and `stopped` when it said +goodbye while the tool listened; one that stopped earlier shows as `down`. +Clients send no heartbeats, so `clients` lists the components that declare +the service, not the processes running. + +`service call` uses an ordinary `service::Client`, so the server handles the +request like any other. It waits up to `--timeout-ms N` (2000 by default) +for a server and its reply, then exits with 1 and the call's status, such as +`unavailable` (no live server), `deadline_exceeded`, or the handler's own +error and message. Requests carry raw bytes: encode typed requests yourself. + ## Library Helpers These are in the core library and need no JSON: diff --git a/docs/services.md b/docs/services.md index c367ee1..80728a6 100644 --- a/docs/services.md +++ b/docs/services.md @@ -349,6 +349,9 @@ configured request or reply descriptor that differs from the types' codecs, naming both versions. `--describe` lists services and which components serve and call them. +`puppet_master_topic service list` shows the same for a running system, +with whether each server is up, and `service call` sends a request from the +command line; see [Topic Tool](launcher.md#services). `validate --system` checks them across processes like topics: the same contract (types, versions, encoding, transport) everywhere, exactly one serving process, which is how a second server is caught before it runs, and diff --git a/test/topic_tool_fastdds_test.cpp b/test/topic_tool_fastdds_test.cpp index ed6629d..5737517 100644 --- a/test/topic_tool_fastdds_test.cpp +++ b/test/topic_tool_fastdds_test.cpp @@ -4,6 +4,7 @@ // // puppet_master_topic_fastdds_test +#include #include #include #include @@ -17,12 +18,16 @@ #include #include +#include +#include #include namespace config = puppet_master::configuration; namespace core = puppet_master::core; namespace fastdds = puppet_master::transport::fastdds; namespace fs = std::filesystem; +namespace runtime = puppet_master::runtime; +namespace service = puppet_master::service; namespace transport = puppet_master::transport; using namespace std::chrono_literals; @@ -60,10 +65,13 @@ class Fixture { WriteFile(root_ / "share/test_interfaces/topics.json", R"({"topics": [{"id": "text", "name": ")" + topic_ + R"(", "message_type": "test.Text", "transport": "fastdds", - "message_policy": {"delivery": "reliable"}}]})"); + "message_policy": {"delivery": "reliable"}}], + "services": [{"id": "echo", "name": ")" + topic_ + R"(/echo", "transport": "fastdds", + "request_type": "test.EchoRequest", "reply_type": "test.EchoReply"}]})"); WriteFile(root_ / "share/producer/producer.json", R"({ "imports": ["test_interfaces/topics.json"], - "components": [{"name": "producer", "writers": ["text"], "triggers": [{"kind": "manual"}]}]})"); + "components": [{"name": "producer", "writers": ["text"], "servers": ["echo"], + "triggers": [{"kind": "manual"}]}]})"); WriteFile(root_ / "system.json", R"({ "name": "topic_fastdds_test", "config_paths": ["share"], "nodes": [{"name": "producer", "executable": "producer_node", "config": "producer/producer.json"}]})"); @@ -238,6 +246,42 @@ void TestRecordInfoReplay(Fixture& fixture, const std::string& tool) } } +// A FastDDS service served from this process, seen and called by the tool. +void TestService(Fixture& fixture, const std::string& tool) +{ + const auto name = fixture.topic() + "/echo"; + runtime::RuntimeOptions options; + options.register_inmemory_transport = false; + auto context = runtime::RuntimeContext::Create(options); + assert(context.ok()); + fastdds::Options dds; + dds.domain_id = kDomain; + dds.participant_name = "topic_tool_service_test"; + assert(fastdds::RegisterTransport(*context.value(), core::TransportName::Create("dds").value(), dds).ok()); + service::ServiceSpec spec(core::TopicName::Create(name).value()); + spec.transport = core::TransportKind::kFastDds; + spec.request = transport::MessageDescriptor {"test.EchoRequest", "application/octet-stream", 0}; + spec.reply = transport::MessageDescriptor {"test.EchoReply", "application/octet-stream", 0}; + auto server = service::Server::Create(*context.value(), spec, [](const service::Request& request) { + transport::ByteBuffer reply(request.payload.begin(), request.payload.end()); + std::reverse(reply.begin(), reply.end()); + return core::Result(std::move(reply)); + }); + assert(server.ok()); + + auto run = fixture.Run({tool, "service", "list", "--system", fixture.system(), "--domain", "79"}, 0ms); + assert(run.exit.success()); + assert(Contains(run.output, name + " request test.EchoRequest (application/octet-stream), reply " + "test.EchoReply (application/octet-stream) fastdds domain 79")); + assert(Contains(run.output, " server: up, instance ")); + + run = fixture.Run({tool, "service", "call", name, "--system", fixture.system(), "--domain", "79", "--data", + "abc", "--text", "--timeout-ms", "5000"}, + 0ms); + assert(run.exit.success()); + assert(Contains(run.output, " ms cba")); +} + } // namespace int main(int argc, char** argv) @@ -253,6 +297,7 @@ int main(int argc, char** argv) TestEcho(fixture, tool); TestHz(fixture, tool); TestRecordInfoReplay(fixture, tool); + TestService(fixture, tool); std::cout << "topic tool FastDDS tests passed\n"; return 0; diff --git a/test/topic_tool_test.cpp b/test/topic_tool_test.cpp index 8e958b3..3ea33b9 100644 --- a/test/topic_tool_test.cpp +++ b/test/topic_tool_test.cpp @@ -4,10 +4,13 @@ // puppet_master_topic_tool_test #include +#include #include #include #include +#include #include +#include #include #include #include @@ -15,11 +18,15 @@ #include #include +#include +#include #include namespace config = puppet_master::configuration; namespace core = puppet_master::core; namespace fs = std::filesystem; +namespace runtime = puppet_master::runtime; +namespace service = puppet_master::service; namespace shm = puppet_master::transport::shm; namespace transport = puppet_master::transport; @@ -53,16 +60,20 @@ class Fixture { Fixture() : stamp_(std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())), root_(fs::temp_directory_path() / ("pm_topic_tool_" + stamp_)), - topic_("/pm_topic_test/text_" + stamp_) + topic_("/pm_topic_test/text_" + stamp_), + service_("/pm_topic_test/echo_" + stamp_) { WriteFile(root_ / "share/test_interfaces/topics.json", - R"({"topics": [{"id": "text", "name": ")" + topic_ + R"(", "message_type": "test.Text"}]})"); + R"({"topics": [{"id": "text", "name": ")" + topic_ + R"(", "message_type": "test.Text"}], + "services": [{"id": "echo", "name": ")" + service_ + + R"(", "request_type": "test.EchoRequest", "reply_type": "test.EchoReply"}]})"); WriteFile(root_ / "share/producer/producer.json", R"({ "imports": ["test_interfaces/topics.json"], - "components": [{"name": "producer", "writers": ["text"], "triggers": [{"kind": "manual"}]}]})"); + "components": [{"name": "producer", "writers": ["text"], "servers": ["echo"], + "triggers": [{"kind": "manual"}]}]})"); WriteFile(root_ / "share/consumer/consumer.json", R"({ "imports": ["test_interfaces/topics.json"], - "components": [{"name": "consumer", "readers": ["text"], + "components": [{"name": "consumer", "readers": ["text"], "clients": ["echo"], "triggers": [{"kind": "data", "data_topics": ["text"]}]}]})"); WriteFile(root_ / "deploy.json", R"({"defaults": {"transport": "shm", "transport_parameters": {"domain_id": 77}}, @@ -104,11 +115,25 @@ class Fixture { std::string File(const std::string& name) const { return (root_ / name).string(); } + // The echo service as the system declares it. + service::ServiceSpec Service() const + { + service::ServiceSpec spec(core::TopicName::Create(service_).value()); + spec.transport = core::TransportKind::kIpc; + spec.request = transport::MessageDescriptor {"test.EchoRequest", "application/octet-stream", 0}; + spec.reply = transport::MessageDescriptor {"test.EchoReply", "application/octet-stream", 0}; + return spec; + } + + const std::string& service_name() const noexcept { return service_; } + ~Fixture() { writer_.reset(); transport_.reset(); shm::RemoveSegment(kDomain, topic_); + shm::RemoveSegment(kDomain, service_ + "/request"); + shm::RemoveSegment(kDomain, service_ + "/presence"); std::error_code ignored; fs::remove_all(root_, ignored); } @@ -164,6 +189,7 @@ class Fixture { std::string stamp_; fs::path root_; std::string topic_; + std::string service_; std::unique_ptr transport_; transport::WriterPtr writer_; int runs_ {0}; @@ -305,6 +331,87 @@ void TestRecordInfoReplay(Fixture& fixture, const std::string& tool) assert(run.exit.code == 2); } +std::string Hex16(std::uint64_t value) +{ + std::ostringstream text; + text << std::hex << std::setw(16) << std::setfill('0') << value; + return text.str(); +} + +void TestServices(Fixture& fixture, const std::string& tool) +{ + const auto& name = fixture.service_name(); + + // No server yet: declared, but down. + auto run = fixture.Run({tool, "service", "list", "--system", fixture.system()}, 0ms); + assert(run.exit.success()); + assert(Contains(run.output, name + " request test.EchoRequest (application/octet-stream), reply " + "test.EchoReply (application/octet-stream) shm domain 77")); + assert(Contains(run.output, " server: down (no heartbeat in 300 ms)")); + assert(Contains(run.output, " servers: producer/producer")); + assert(Contains(run.output, " clients: consumer/consumer")); + + // A server in this process: upper-cases the request, refuses "fail". + runtime::RuntimeOptions options; + options.register_inmemory_transport = false; + auto context = runtime::RuntimeContext::Create(options); + assert(context.ok()); + shm::Options shm_options; + shm_options.domain_id = kDomain; + assert(shm::RegisterTransport(*context.value(), core::TransportName::Create("shm").value(), shm_options).ok()); + auto server = service::Server::Create(*context.value(), fixture.Service(), [](const service::Request& request) { + std::string text(request.payload.begin(), request.payload.end()); + if (text == "fail") { + return core::Result::FromStatus(core::Status::InvalidArgument("no fail")); + } + for (auto& c : text) { + c = static_cast(std::toupper(static_cast(c))); + } + return core::Result(transport::ByteBuffer(text.begin(), text.end())); + }); + assert(server.ok()); + const auto instance = Hex16(server.value()->instance_id()); + + run = fixture.Run({tool, "service", "list", "--system", fixture.system()}, 0ms); + assert(run.exit.success()); + assert(Contains(run.output, " server: up, instance " + instance + ", heartbeat ")); + + run = fixture.Run({tool, "service", "call", name, "--system", fixture.system(), "--data", "hi there", "--text"}, + 0ms); + assert(run.exit.success()); + assert(Contains(run.output, "call " + name + ": server " + instance + ", request 8 B")); + assert(Contains(run.output, "reply 8 B in ")); + assert(Contains(run.output, " ms HI THERE")); + + run = fixture.Run({tool, "service", "call", name, "--system", fixture.system(), "--hex", "68:69"}, 0ms); + assert(run.exit.success()); + assert(Contains(run.output, " ms 48 49")); + + // The handler's error, with its message. + run = fixture.Run({tool, "service", "call", name, "--system", fixture.system(), "--data", "fail"}, 0ms); + assert(run.exit.code == 1); + assert(Contains(run.output, "invalid_argument: no fail")); + + run = fixture.Run({tool, "service", "call", "/pm_topic_test/nobody", "--system", fixture.system()}, 0ms); + assert(run.exit.code == 1); + assert(Contains(run.output, "declares service /pm_topic_test/nobody")); + run = fixture.Run({tool, "service", "list"}, 0ms); + assert(run.exit.code == 2); + assert(Contains(run.output, "needs --system FILE")); + run = fixture.Run({tool, "service", "call", name, "--system", fixture.system(), "--hex", "6"}, 0ms); + assert(run.exit.code == 2); + + // Stopped: a call fails at once instead of timing out. + server.value()->Close(); + run = fixture.Run({tool, "service", "list", "--system", fixture.system()}, 0ms); + assert(run.exit.success()); + assert(!Contains(run.output, " server: up")); + run = fixture.Run( + {tool, "service", "call", name, "--system", fixture.system(), "--data", "x", "--timeout-ms", "500"}, 0ms); + assert(run.exit.code == 1); + assert(Contains(run.output, "unavailable: ")); +} + #if !defined(_WIN32) void TestListFromSegments(Fixture& fixture, const std::string& tool) { @@ -341,6 +448,7 @@ int main(int argc, char** argv) TestHz(fixture, tool); TestErrors(fixture, tool); TestRecordInfoReplay(fixture, tool); + TestServices(fixture, tool); #if !defined(_WIN32) // Segment headers can only be read on Linux. TestListFromSegments(fixture, tool); diff --git a/tools/puppet_master_topic.cpp b/tools/puppet_master_topic.cpp index 3ef6896..c6a19ba 100644 --- a/tools/puppet_master_topic.cpp +++ b/tools/puppet_master_topic.cpp @@ -15,15 +15,24 @@ // their domain from --domain (default 0); FastDDS carries no writer sequence // or publish time, so losses and latency are not shown for them, and rates // and intervals are by arrival. +// +// puppet_master_topic service list --system system.json +// puppet_master_topic service call /map/query --system system.json --data "a b" +// +// service list reads each service's presence topic only, so it changes +// nothing. service call sends one real request through a service::Client, so +// the server handles it like any other. #include #include +#include #include #include #include #include #include #include +#include #include #include #include @@ -36,6 +45,8 @@ #include #include +#include +#include #include #include #ifdef PUPPETMASTER_TOPIC_WITH_FASTDDS @@ -44,6 +55,8 @@ namespace config = puppet_master::configuration; namespace core = puppet_master::core; +namespace runtime = puppet_master::runtime; +namespace service = puppet_master::service; namespace shm = puppet_master::transport::shm; namespace transport = puppet_master::transport; #ifdef PUPPETMASTER_TOPIC_WITH_FASTDDS @@ -97,21 +110,34 @@ int Usage(std::ostream& out) << " named) at their recorded pace\n" << " --rate X replay: X times the recorded pace; 0 publishes at once\n" << " info the topics, message counts, and length of a recording\n" + << " puppet_master_topic service list --system FILE [--domain N] [--timeout-ms N]\n" + << " puppet_master_topic service call --system FILE [--domain N]\n" + << " [--data TEXT | --hex HEX] [--timeout-ms N]\n" + << " [--bytes N] [--text]\n" + << " service list the system's services, who serves and calls them, and whether a\n" + << " server is up, from its heartbeats; listens --timeout-ms (default:\n" + << " three heartbeat intervals, at least 1 s on FastDDS)\n" + << " service call send one request, TEXT's bytes, HEX's (\"68 69\"), or none, and print\n" + << " the reply; fails with the call's status (--timeout-ms, default 2000)\n" << "Ctrl+C stops echo, hz, record, and replay.\n"; return 2; } struct Arguments { std::string command; - std::vector topics; + std::string subcommand; // service: list or call + std::vector topics; // service call: the service std::string file; // record: -o; replay, info: the first operand std::string system; std::optional domain; std::uint64_t count {0}; milliseconds timeout {0}; + bool timeout_set {false}; + transport::ByteBuffer data; // service call: the request milliseconds window {1000}; milliseconds duration {0}; std::uint64_t bytes {32}; + bool bytes_set {false}; bool text {false}; double rate {1.0}; }; @@ -135,6 +161,30 @@ bool ParseNumber(const std::string& text, std::uint64_t& value) return true; } +// "68 69", "6869", or "68:69": pairs of hex digits; spaces and colons are +// ignored. +bool ParseHex(const std::string& text, transport::ByteBuffer& bytes) +{ + std::string digits; + for (const char c : text) { + if (c == ' ' || c == ':') { + continue; + } + if (!std::isxdigit(static_cast(c))) { + return false; + } + digits += c; + } + if (digits.size() % 2 != 0) { + return false; + } + bytes.clear(); + for (std::size_t index = 0; index < digits.size(); index += 2) { + bytes.push_back(static_cast(std::stoul(digits.substr(index, 2), nullptr, 16))); + } + return true; +} + // Returns 0 when the arguments are good, else the exit code. int Parse(int argc, char** argv, Arguments& args) { @@ -146,13 +196,23 @@ int Parse(int argc, char** argv, Arguments& args) Usage(std::cout); return -1; } - const std::set commands {"list", "echo", "hz", "record", "replay", "info"}; + const std::set commands {"list", "echo", "hz", "record", "replay", "info", "service"}; if (commands.count(args.command) == 0) { return Usage(std::cerr); } + int first = 2; + if (args.command == "service") { + if (argc < 3 || (std::string(argv[2]) != "list" && std::string(argv[2]) != "call")) { + return Usage(std::cerr); + } + args.subcommand = argv[2]; + first = 3; + } const bool echo = args.command == "echo"; const bool record = args.command == "record"; - for (int index = 2; index < argc; ++index) { + const bool call = args.subcommand == "call"; + bool has_data = false; + for (int index = first; index < argc; ++index) { const std::string argument = argv[index]; const bool has_value = index + 1 < argc; std::uint64_t number = 0; @@ -176,18 +236,33 @@ int Parse(int argc, char** argv, Arguments& args) return 2; } args.count = number; - } else if (argument == "--timeout-ms" && args.command == "echo") { + } else if (argument == "--timeout-ms" && (echo || args.command == "service")) { if (!numeric("--timeout-ms")) { return 2; } args.timeout = milliseconds(number); - } else if (argument == "--bytes" && args.command == "echo") { + args.timeout_set = true; + } else if (argument == "--bytes" && (echo || call)) { if (!numeric("--bytes")) { return 2; } args.bytes = number; - } else if (argument == "--text" && args.command == "echo") { + args.bytes_set = true; + } else if (argument == "--text" && (echo || call)) { args.text = true; + } else if ((argument == "--data" || argument == "--hex") && call && has_value) { + if (has_data) { + std::cerr << "give --data or --hex once\n"; + return 2; + } + has_data = true; + const std::string value = argv[++index]; + if (argument == "--data") { + args.data.assign(value.begin(), value.end()); + } else if (!ParseHex(value, args.data)) { + std::cerr << "--hex needs pairs of hex digits, such as \"68 69\"\n"; + return 2; + } } else if (argument == "--window-ms" && args.command == "hz") { if (!numeric("--window-ms") || number == 0) { return 2; @@ -206,7 +281,8 @@ int Parse(int argc, char** argv, Arguments& args) return 2; } ++index; - } else if (!argument.empty() && argument[0] != '-' && args.command != "list") { + } else if (!argument.empty() && argument[0] != '-' && args.command != "list" && + args.subcommand != "list") { const bool takes_file = args.command == "replay" || args.command == "info"; if (takes_file && args.file.empty()) { args.file = argument; @@ -219,6 +295,19 @@ int Parse(int argc, char** argv, Arguments& args) return Usage(std::cerr); } } + if (args.command == "service") { + if (call && args.topics.size() != 1) { + return Usage(std::cerr); + } + if (args.system.empty()) { + std::cerr << "service " << args.subcommand << " needs --system FILE\n"; + return 2; + } + if (call && !args.bytes_set) { + args.bytes = std::numeric_limits::max(); // a reply is shown whole + } + return 0; + } const bool one_topic = echo || args.command == "hz"; if ((one_topic && args.topics.size() != 1) || ((record || args.command == "replay" || args.command == "info") && args.file.empty())) { @@ -1269,6 +1358,335 @@ int Info(const Arguments& args) return 0; } +// --- services ----------------------------------------------------------- + +// A service the manifest's nodes declare, with what is needed to reach it. +struct ServiceInfo { + explicit ServiceInfo(service::ServiceSpec spec_in) : spec(std::move(spec_in)) {} + + service::ServiceSpec spec; + core::DomainId domain {0}; + // The ring sizes of its topics, from the first node that declares it. + shm::Options shm_options; + // "node/component". + std::set servers; + std::set clients; +}; + +using Services = core::Result>; + +bool SameContract(const service::ServiceSpec& lhs, const service::ServiceSpec& rhs) +{ + return lhs.transport == rhs.transport && lhs.request == rhs.request && lhs.reply == rhs.reply && + lhs.queue_depth == rhs.queue_depth && lhs.heartbeat_interval == rhs.heartbeat_interval; +} + +// Every service the manifest's nodes declare, with the deployment's +// transport settings, and which components serve and call it. +Services ServicesFromSystem(const Arguments& args) +{ + auto manifest = config::LoadSystemManifest(args.system); + if (!manifest.ok()) { + return Services::FromStatus(manifest.status()); + } + auto nodes = config::LoadSystemNodes(manifest.value()); + if (!nodes.ok()) { + return Services::FromStatus(nodes.status()); + } + std::map by_name; + for (const auto& node : nodes.value()) { + auto options = shm::OptionsFromProject(node.project); + if (!options.ok()) { + return Services::FromStatus(core::Status::Error( + options.status().code(), "node " + node.name + ": " + options.status().message())); + } + std::map names; // service id -> wire name + for (const auto& declared : node.project.services) { + auto spec = declared.ToServiceSpec(); + if (!spec.ok()) { + return Services::FromStatus(core::Status::Error( + spec.status().code(), "node " + node.name + ": " + spec.status().message())); + } + names[declared.id] = declared.name; + // As for topics: a FastDDS domain is chosen in code, so it comes + // from --domain (default 0). + const core::DomainId domain = args.domain ? *args.domain + : declared.transport == core::TransportKind::kFastDds + ? 0 + : options.value().domain_id; + const auto found = by_name.find(declared.name); + if (found == by_name.end()) { + ServiceInfo info(std::move(spec).value()); + info.domain = domain; + info.shm_options = options.value(); + info.shm_options.domain_id = domain; + by_name.emplace(declared.name, std::move(info)); + } else if (!SameContract(found->second.spec, spec.value()) || found->second.domain != domain) { + return Services::FromStatus(core::Status::InvalidArgument( + "service " + declared.name + " is declared differently in node " + node.name + + "; run puppet_master_config system validate")); + } + } + for (const auto& component : node.project.components) { + for (const auto* ids : {&component.servers, &component.clients}) { + for (const auto& id : *ids) { + const auto name = names.find(id); + if (name == names.end()) { + continue; + } + auto& info = by_name.find(name->second)->second; + (ids == &component.servers ? info.servers : info.clients) + .insert(node.name + "/" + component.name); + } + } + } + } + std::vector services; + for (auto& entry : by_name) { + services.push_back(std::move(entry.second)); + } + return Services(std::move(services)); +} + +std::string TransportText(core::TransportKind kind, core::DomainId domain) +{ + if (kind == core::TransportKind::kIpc) { + return "shm domain " + std::to_string(domain); + } + if (kind == core::TransportKind::kFastDds) { + return "fastdds domain " + std::to_string(domain); + } + return core::ToString(kind); +} + +std::string Hex16(std::uint64_t value) +{ + std::ostringstream text; + text << std::hex << std::setw(16) << std::setfill('0') << value; + return text.str(); +} + +// A reader of the service's presence topic only: no client, no reply topic. +core::Result WatchPresence(Transports& transports, const ServiceInfo& info) +{ + using ResultType = core::Result; + if (!Readable(info.spec.transport)) { + return ResultType::FromStatus(core::Status::Unsupported( + std::string("it uses the ") + core::ToString(info.spec.transport) + " transport; " + kReadableTransports)); + } + auto endpoints = service::EndpointsFor(info.spec); + if (!endpoints.ok()) { + return ResultType::FromStatus(endpoints.status()); + } + const auto& presence = endpoints.value().presence; + TopicInfo topic; + topic.name = presence.topic.name.str(); + topic.transport = info.spec.transport; + topic.descriptor = presence.message; + topic.geometry = info.shm_options.ForTopic(topic.name); + topic.domain = info.domain; + auto owner = transports.For(topic); + if (!owner.ok()) { + return ResultType::FromStatus(owner.status()); + } + auto reader = owner.value()->CreateReader(presence); + if (!reader.ok()) { + return ResultType::FromStatus(reader.status()); + } + Subscription subscription; + subscription.owner = owner.value(); + subscription.carried = CarriedBy(topic.transport); + subscription.reader = reader.value(); + return ResultType(std::move(subscription)); +} + +// What the presence topic said while the tool listened. +struct Presence { + std::optional subscription; + std::string problem; // why it could not be watched + std::uint64_t instance {0}; + bool goodbye {false}; + std::optional heard; // newest heartbeat or goodbye +}; + +// Reads the heartbeats that arrived; each is {u64 instance, u64 sequence}, +// little-endian, and sequence 0 is the server's goodbye. +void Poll(Presence& presence) +{ + for (auto message = presence.subscription->reader->Read(); message.ok(); + message = presence.subscription->reader->Read()) { + const auto& payload = message.value().payload; + if (payload.size() != 16) { + continue; + } + std::uint64_t instance = 0; + std::uint64_t sequence = 0; + for (int index = 7; index >= 0; --index) { + instance = (instance << 8) | payload[static_cast(index)]; + sequence = (sequence << 8) | payload[static_cast(8 + index)]; + } + presence.instance = instance; + presence.goodbye = sequence == 0; + presence.heard = Clock::now(); + } +} + +int ServiceList(const Arguments& args) +{ + auto services = ServicesFromSystem(args); + if (!services.ok()) { + std::cerr << services.status().ToString() << '\n'; + return 1; + } + if (services.value().empty()) { + std::cout << "no services\n"; + return 0; + } + + // Long enough to see a heartbeat of every live server, and on FastDDS + // for discovery first. + core::Nanoseconds listen {0}; + for (const auto& info : services.value()) { + listen = std::max(listen, 3 * info.spec.heartbeat_interval); + if (info.spec.transport == core::TransportKind::kFastDds) { + listen = std::max(listen, std::chrono::seconds(1)); + } + } + if (args.timeout_set) { + listen = args.timeout; + } + + Transports transports; + std::vector presences(services.value().size()); + for (std::size_t index = 0; index < presences.size(); ++index) { + auto watched = WatchPresence(transports, services.value()[index]); + if (watched.ok()) { + presences[index].subscription = std::move(watched).value(); + } else { + presences[index].problem = watched.status().message(); + } + } + const auto deadline = Clock::now() + std::chrono::duration_cast(listen); + while (!g_stop.load() && Clock::now() < deadline) { + bool all_heard = true; + for (auto& presence : presences) { + if (presence.subscription) { + Poll(presence); + all_heard = all_heard && presence.heard.has_value(); + } + } + if (all_heard) { + break; + } + std::this_thread::sleep_for(milliseconds(10)); + } + + const auto now = Clock::now(); + for (std::size_t index = 0; index < presences.size(); ++index) { + const auto& info = services.value()[index]; + const auto& presence = presences[index]; + std::cout << info.spec.name.str() << " request " << info.spec.request.ToString() << ", reply " + << info.spec.reply.ToString() << " " << TransportText(info.spec.transport, info.domain) << '\n'; + std::cout << " server: "; + if (!presence.subscription) { + std::cout << "unknown (" << presence.problem << ")"; + } else if (!presence.heard) { + std::cout << "down (no heartbeat in " << std::chrono::duration_cast(listen).count() + << " ms)"; + } else if (presence.goodbye) { + std::cout << "stopped (instance " << Hex16(presence.instance) << " said goodbye)"; + } else { + std::cout << "up, instance " << Hex16(presence.instance) << ", heartbeat " + << std::chrono::duration_cast(now - *presence.heard).count() << " ms ago"; + } + std::cout << '\n'; + std::cout << " servers: " << Join(info.servers) << '\n'; + std::cout << " clients: " << Join(info.clients) << '\n'; + } + return 0; +} + +int ServiceCall(const Arguments& args) +{ + auto services = ServicesFromSystem(args); + if (!services.ok()) { + std::cerr << services.status().ToString() << '\n'; + return 1; + } + const auto& name = args.topics.front(); + const auto found = std::find_if(services.value().begin(), services.value().end(), + [&name](const ServiceInfo& info) { return info.spec.name.str() == name; }); + if (found == services.value().end()) { + std::cerr << "not_found: no node of " << args.system << " declares service " << name << '\n'; + return 1; + } + const auto& info = *found; + if (!Readable(info.spec.transport)) { + std::cerr << "unsupported: service " << name << " uses the " << core::ToString(info.spec.transport) + << " transport; " << kReadableTransports << '\n'; + return 1; + } + + // A runtime of its own with the one transport the service runs on, so + // the client below is an ordinary one. + runtime::RuntimeOptions options; + options.register_inmemory_transport = false; + auto created = runtime::RuntimeContext::Create(options); + if (!created.ok()) { + std::cerr << created.status().ToString() << '\n'; + return 1; + } + auto& context = *created.value(); + const auto transport_name = core::TransportName::Create("puppet_master_topic").value(); + transport::TransportPtr backend; + if (info.spec.transport == core::TransportKind::kIpc) { + backend = std::make_shared(transport_name, info.shm_options); + } +#ifdef PUPPETMASTER_TOPIC_WITH_FASTDDS + else { + fastdds::Options dds; + dds.domain_id = info.domain; + dds.participant_name = "puppet_master_topic"; + backend = std::make_shared(transport_name, dds); + } +#endif + auto status = context.RegisterTransport(backend); + if (!status.ok()) { + std::cerr << status.ToString() << '\n'; + return 1; + } + + auto client = service::Client::Create(context, info.spec); + if (!client.ok()) { + std::cerr << client.status().ToString() << '\n'; + return 1; + } + const auto timeout = args.timeout_set ? args.timeout : milliseconds(2000); + const auto started = Clock::now(); + auto server = client.value()->WaitForService(timeout); + if (!server.ok()) { + std::cerr << server.status().ToString() << '\n'; + return 1; + } + std::cerr << "call " << name << ": server " << Hex16(server.value().instance_id) << ", request " + << args.data.size() << " B" << std::endl; + const auto left = std::max(timeout - (Clock::now() - started), milliseconds(1)); + const auto sent = Clock::now(); + auto reply = client.value()->Call(transport::ByteView(args.data), + std::chrono::duration_cast(left)); + const auto took = Clock::now() - sent; + if (!reply.ok()) { + std::cerr << reply.status().ToString() << '\n'; + return 1; + } + std::cout << "reply " << reply.value().size() << " B in " << std::fixed << std::setprecision(1) + << Microseconds(std::chrono::duration_cast(took)) / 1000.0 << " ms"; + std::cout.unsetf(std::ios::floatfield); + PrintPayload(reply.value(), args); + std::cout << std::endl; + return 0; +} + } // namespace int main(int argc, char** argv) @@ -1295,5 +1713,8 @@ int main(int argc, char** argv) if (args.command == "record") { return Record(args); } + if (args.command == "service") { + return args.subcommand == "list" ? ServiceList(args) : ServiceCall(args); + } return args.command == "replay" ? Replay(args) : Info(args); } From ffc766353ad892a71fb747f3bc678b446cf04f6d Mon Sep 17 00:00:00 2001 From: SoleyRan Date: Wed, 4 Nov 2026 15:40:36 +0800 Subject: [PATCH 2/6] feat: service list shows servers that stopped before it started shm::ReadNewestMessage reads the newest message of a topic from its segment without attaching, so no writer or reader notices and readers created later still start after it. On Windows, SharedRegion::OpenReadOnly now maps an existing region with FILE_MAP_READ instead of returning Unsupported. When service list hears no heartbeat on a shm service, it reads the last presence message left in the segment: a goodbye shows the server as stopped, and a stale heartbeat as down without a goodbye, with its age. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 6 ++ docs/launcher.md | 14 ++- docs/shm-transport.md | 7 ++ .../transport/shm/shm_transport.h | 11 +++ src/transport/shm/platform.h | 2 +- src/transport/shm/platform_windows.cpp | 27 +++++- src/transport/shm/segment.cpp | 88 ++++++++++++++++--- src/transport/shm/segment.h | 12 +++ src/transport/shm/shm_transport.cpp | 37 ++++++++ test/shm_transport_test.cpp | 43 +++++++++ test/topic_tool_test.cpp | 21 ++++- tools/puppet_master_topic.cpp | 83 ++++++++++++++--- 12 files changed, 316 insertions(+), 35 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 53b0272..2864dae 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,12 @@ the minor version in their soname (`libpuppet_master.so.0.4`), and `--hex HEX`) through an ordinary client and prints the reply, or exits with 1 and the call's status. Both work on shared memory and, when built with it, FastDDS. See [Services](docs/launcher.md#services). +- `shm::ReadNewestMessage(domain, endpoint)` reads the newest message of a + topic from its segment without attaching, so no writer or reader notices. + `service list` uses it on shared memory to tell a server that said goodbye + (`stopped`) from one whose heartbeats stopped without one (`down`, with + its last heartbeat's age), also when the server stopped before the tool + started. See [Segment Lifetime](docs/shm-transport.md#segment-lifetime). ## 0.4.0 diff --git a/docs/launcher.md b/docs/launcher.md index f7330d6..77e952d 100644 --- a/docs/launcher.md +++ b/docs/launcher.md @@ -267,9 +267,17 @@ puppet_master_topic service call /map/query --system system.json --hex "01 00 2a `service list` reads each service's presence topic only, so it creates no client and no reply topic. It listens for three heartbeat intervals (at -least 1 s on FastDDS, for discovery), or `--timeout-ms N`. A server is -`down` when no heartbeat arrived in that time, and `stopped` when it said -goodbye while the tool listened; one that stopped earlier shows as `down`. +least 1 s on FastDDS, for discovery), or `--timeout-ms N`. When no heartbeat +arrives in that time, on shared memory it reads the last presence message +left in the topic's segment (`shm::ReadNewestMessage`, without attaching): + +| `server:` | Meaning | +|---|---| +| `up, instance ID, heartbeat N ms ago` | a heartbeat within three intervals | +| `stopped (instance ID said goodbye N ms ago)` | the server closed in order | +| `down (instance ID stopped without a goodbye; last heartbeat N ms ago)` | its heartbeats stopped: a crash, a kill, or a server too busy to keep its interval | +| `down (no heartbeat in N ms)` | nothing to read: never started, on FastDDS, or on Windows after its last process closed the topic | + Clients send no heartbeats, so `clients` lists the components that declare the service, not the processes running. diff --git a/docs/shm-transport.md b/docs/shm-transport.md index f7232ad..6a4f8f4 100644 --- a/docs/shm-transport.md +++ b/docs/shm-transport.md @@ -203,6 +203,13 @@ shares it with processes started later. The same operations are available in C++ as `shm::ListSegments` and `shm::RemoveUnusedSegments`. On Windows they return `Unsupported`, since there is nothing left over to clean. +`shm::ReadNewestMessage(domain, endpoint)` returns the newest message of one +topic, read from its segment the same way: without attaching, so no writer +or reader notices, and readers created later still start after it. Tools use +it for the last word of a writer that may have stopped, such as a service's +final heartbeat or goodbye. On Linux the segment, and so the message, outlive +their processes; on Windows only while some process has the topic open. + ## Limits - Same host only. Use the FastDDS adapter across hosts. diff --git a/include/puppet_master/transport/shm/shm_transport.h b/include/puppet_master/transport/shm/shm_transport.h index 98aed96..e0acc85 100644 --- a/include/puppet_master/transport/shm/shm_transport.h +++ b/include/puppet_master/transport/shm/shm_transport.h @@ -100,6 +100,17 @@ PUPPET_MASTER_API const char* ToString(SegmentInfo::State state) noexcept; PUPPET_MASTER_API core::Result> ListSegments( std::optional domain_id = std::nullopt); +// The newest message written to a topic on this host, read from its segment +// without attaching, so no running process notices: for tools that want the +// last word of a writer that may have stopped. Its sequence and source +// timestamp are the writer's (the steady clock, which every process on the +// host shares); reception_timestamp is when it was read. Empty if nothing was +// written yet. NotFound if the topic has no segment, which on Windows means +// no process has it open; InvalidArgument if the segment carries another +// message descriptor than `endpoint`. +PUPPET_MASTER_API core::Result> ReadNewestMessage( + core::DomainId domain_id, const EndpointConfig& endpoint); + // Removes the listed segments that no live process uses (kUnused, // kUninitialized, kIncompatible) and returns them. Segments in use are never // removed. A process that attaches between the check and the removal keeps diff --git a/src/transport/shm/platform.h b/src/transport/shm/platform.h index b080177..6b267d3 100644 --- a/src/transport/shm/platform.h +++ b/src/transport/shm/platform.h @@ -44,7 +44,7 @@ class SharedRegion { static core::Status Remove(const std::string& name); // Maps an existing region read-only, for inspection. NotFound if it does - // not exist. Unsupported on Windows. + // not exist. On Windows a region exists only while a process has it open. static core::Result> OpenReadOnly(const std::string& name); // Names of the regions this layer created in `domain` (every domain if diff --git a/src/transport/shm/platform_windows.cpp b/src/transport/shm/platform_windows.cpp index 3ca3240..34e9724 100644 --- a/src/transport/shm/platform_windows.cpp +++ b/src/transport/shm/platform_windows.cpp @@ -109,10 +109,31 @@ core::Status SharedRegion::Remove(const std::string& /*name*/) return core::Status::Ok(); } -core::Result> SharedRegion::OpenReadOnly(const std::string& /*name*/) +core::Result> SharedRegion::OpenReadOnly(const std::string& name) { - return core::Result>::FromStatus( - core::Status::Unsupported("shm segment inspection is not supported on Windows")); + using ResultType = core::Result>; + HANDLE mapping = OpenFileMappingW(FILE_MAP_READ, FALSE, Widen(name).c_str()); + if (mapping == nullptr) { + if (GetLastError() == ERROR_FILE_NOT_FOUND) { + return ResultType::FromStatus(core::Status::NotFound("no shared region " + name)); + } + return ResultType::FromStatus(core::Status::Unavailable(LastErrorMessage("OpenFileMappingW"))); + } + void* data = MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0); + if (data == nullptr) { + auto status = core::Status::Unavailable(LastErrorMessage("MapViewOfFile")); + CloseHandle(mapping); + return ResultType::FromStatus(std::move(status)); + } + // The view is the whole mapping, rounded up to whole pages. + MEMORY_BASIC_INFORMATION info {}; + if (VirtualQuery(data, &info, sizeof(info)) == 0) { + auto status = core::Status::Unavailable(LastErrorMessage("VirtualQuery")); + UnmapViewOfFile(data); + CloseHandle(mapping); + return ResultType::FromStatus(std::move(status)); + } + return ResultType(std::unique_ptr(new SharedRegion(data, info.RegionSize, false, mapping))); } core::Result> SharedRegion::List(std::optional /*domain*/) diff --git a/src/transport/shm/segment.cpp b/src/transport/shm/segment.cpp index 8a3190b..adf0e53 100644 --- a/src/transport/shm/segment.cpp +++ b/src/transport/shm/segment.cpp @@ -490,32 +490,29 @@ void Segment::ReclaimDeadParticipants() noexcept } } -core::Result InspectSegment(const std::string& name) +namespace { + +SegmentInspection Inspect(const SharedRegion& region) { - using ResultType = core::Result; - auto region = SharedRegion::OpenReadOnly(name); - if (!region.ok()) { - return ResultType::FromStatus(region.status()); - } SegmentInspection inspection; - inspection.size = region.value()->size(); + inspection.size = region.size(); if (inspection.size < HeaderSize()) { inspection.state = inspection.size == 0 ? SegmentInspection::State::kUninitialized : SegmentInspection::State::kIncompatible; inspection.problem = inspection.size == 0 ? "never sized" : "smaller than a segment header"; - return ResultType(std::move(inspection)); + return inspection; } - const auto& header = *static_cast(region.value()->data()); + const auto& header = *static_cast(region.data()); if (header.magic.load(std::memory_order_acquire) != kMagic) { inspection.state = SegmentInspection::State::kUninitialized; inspection.problem = "header never published"; - return ResultType(std::move(inspection)); + return inspection; } if (header.layout_version != kLayoutVersion || header.header_size != HeaderSize()) { inspection.state = SegmentInspection::State::kIncompatible; inspection.problem = "layout version " + std::to_string(header.layout_version) + ", expected " + std::to_string(kLayoutVersion); - return ResultType(std::move(inspection)); + return inspection; } inspection.topic = LoadName(header.topic_name); inspection.descriptor = StoredDescriptor(header); @@ -528,7 +525,74 @@ core::Result InspectSegment(const std::string& name) inspection.participants.push_back(ProcessIdentity { entry.pid.load(std::memory_order_relaxed), entry.start_time.load(std::memory_order_relaxed)}); } - return ResultType(std::move(inspection)); + return inspection; +} + +// The newest committed message, by the reader's seqlock protocol. A slot the +// writers overwrite while it is copied is retried a few times, then given up. +std::optional ReadNewest(const SharedRegion& region, const SegmentInspection& inspection) +{ + const auto& geometry = inspection.geometry; + const auto stride = SlotStride(geometry.slot_payload_size); + const auto size = SegmentSize(geometry); + if (stride == 0 || geometry.slot_count == 0 || size == 0 || region.size() < size) { + return std::nullopt; + } + const auto& header = *static_cast(region.data()); + const auto* slots = static_cast(region.data()) + HeaderSize(); + for (int attempt = 0; attempt < 16; ++attempt) { + const std::uint64_t newest = header.write_seq.load(std::memory_order_acquire); + if (newest == 0) { + return std::nullopt; + } + const unsigned char* slot = slots + static_cast(newest % geometry.slot_count) * stride; + const auto* slot_header = reinterpret_cast(slot); + const std::uint64_t before = slot_header->seq.load(std::memory_order_acquire); + if (before != newest) { + continue; // a writer moved on; take the new newest + } + const std::uint64_t payload_size = slot_header->payload_size.load(std::memory_order_relaxed); + const std::int64_t timestamp = slot_header->source_timestamp_ns.load(std::memory_order_relaxed); + if (payload_size > geometry.slot_payload_size) { + continue; + } + Message message; + message.payload.resize(static_cast(payload_size)); + CopyFromShared(message.payload.data(), slot + kSlotPayloadOffset, static_cast(payload_size)); + std::atomic_thread_fence(std::memory_order_acquire); + if (slot_header->seq.load(std::memory_order_relaxed) != before) { + continue; + } + message.metadata.sequence = newest; + message.metadata.source_timestamp = core::TimePoint(core::Nanoseconds(timestamp)); + return message; + } + return std::nullopt; +} + +} // namespace + +core::Result InspectSegment(const std::string& name) +{ + auto region = SharedRegion::OpenReadOnly(name); + if (!region.ok()) { + return core::Result::FromStatus(region.status()); + } + return core::Result(Inspect(*region.value())); +} + +core::Result ReadNewestInSegment(const std::string& name) +{ + auto region = SharedRegion::OpenReadOnly(name); + if (!region.ok()) { + return core::Result::FromStatus(region.status()); + } + NewestMessage newest; + newest.inspection = Inspect(*region.value()); + if (newest.inspection.state == SegmentInspection::State::kValid) { + newest.message = ReadNewest(*region.value(), newest.inspection); + } + return core::Result(std::move(newest)); } } // namespace puppet_master::transport::shm::detail diff --git a/src/transport/shm/segment.h b/src/transport/shm/segment.h index 40d059b..d3848f2 100644 --- a/src/transport/shm/segment.h +++ b/src/transport/shm/segment.h @@ -4,6 +4,7 @@ #include #include #include +#include #include #include @@ -115,6 +116,17 @@ struct SegmentInspection { // Maps `name` read-only and reads its header. NotFound if it does not exist. core::Result InspectSegment(const std::string& name); +// The header and the newest committed message of a segment, read like +// InspectSegment: without attaching, so no running process notices. +struct NewestMessage { + SegmentInspection inspection; + // None if nothing was written yet, the segment is not valid, or writers + // kept overwriting the slot while it was copied. + std::optional message; +}; + +core::Result ReadNewestInSegment(const std::string& name); + // Result of one reader pass over the ring. struct ReadOutcome { bool has_message {false}; diff --git a/src/transport/shm/shm_transport.cpp b/src/transport/shm/shm_transport.cpp index 3572b89..e1981ec 100644 --- a/src/transport/shm/shm_transport.cpp +++ b/src/transport/shm/shm_transport.cpp @@ -671,6 +671,43 @@ core::Result> ListSegments(std::optional> ReadNewestMessage(core::DomainId domain_id, const EndpointConfig& endpoint) +{ + using ResultType = core::Result>; + auto status = endpoint.Validate(); + if (!status.ok()) { + return ResultType::FromStatus(std::move(status)); + } + const auto& topic = endpoint.topic.name.str(); + auto newest = detail::ReadNewestInSegment(detail::ObjectName(domain_id, topic)); + if (!newest.ok()) { + if (newest.status().code() == core::StatusCode::kNotFound) { + return ResultType::FromStatus(core::Status::NotFound("no shm segment for topic " + topic)); + } + return ResultType::FromStatus(newest.status()); + } + const auto& inspection = newest.value().inspection; + if (inspection.state != detail::SegmentInspection::State::kValid) { + return ResultType::FromStatus( + core::Status::FailedPrecondition("shm segment of topic " + topic + ": " + inspection.problem)); + } + if (inspection.topic != topic) { + return ResultType::FromStatus( + core::Status::FailedPrecondition("shm segment of topic " + topic + " belongs to " + inspection.topic)); + } + if (inspection.descriptor != endpoint.message) { + return ResultType::FromStatus(core::Status::InvalidArgument( + "shm topic " + topic + " carries " + inspection.descriptor.ToString() + ", not " + + endpoint.message.ToString())); + } + if (!newest.value().message) { + return ResultType(std::optional()); + } + auto message = std::move(*newest.value().message); + message.metadata.reception_timestamp = Now(); + return ResultType(std::optional(std::move(message))); +} + core::Result> RemoveUnusedSegments(std::optional domain_id) { using ResultType = core::Result>; diff --git a/test/shm_transport_test.cpp b/test/shm_transport_test.cpp index 7330776..b74bcf9 100644 --- a/test/shm_transport_test.cpp +++ b/test/shm_transport_test.cpp @@ -700,6 +700,48 @@ void TopicIsReleasedWithItsLastEndpoint() assert(shm_transport->Close().ok()); } +// The newest message is read from the segment without attaching: readers +// created afterwards still start after it. Linux keeps the segment after its +// last process closes it, so the last message stays readable there. +void ReadNewestMessageWithoutAttaching() +{ + const TopicCleanup cleanup {UniqueTopic("newest")}; + const auto endpoint = Endpoint(cleanup.topic); + assert(shm::ReadNewestMessage(kDomain, endpoint).status().code() == core::StatusCode::kNotFound); + + auto shm_transport = MakeTransport(); + auto writer = shm_transport->CreateWriter(endpoint); + assert(writer.ok()); + auto empty = shm::ReadNewestMessage(kDomain, endpoint); + assert(empty.ok() && !empty.value()); + + // More than a ring, so the newest slot is not the first. + for (int index = 0; index < 20; ++index) { + Write(*writer.value(), "msg " + std::to_string(index)); + } + auto newest = shm::ReadNewestMessage(kDomain, endpoint); + assert(newest.ok() && newest.value()); + assert(Text(*newest.value()) == "msg 19"); + assert(newest.value()->metadata.sequence == 20); + const auto age = newest.value()->metadata.reception_timestamp - newest.value()->metadata.source_timestamp; + assert(age >= core::Nanoseconds::zero() && age < 10s); + + assert(shm::ReadNewestMessage(kDomain, Endpoint(cleanup.topic, {}, "test.Other")).status().code() == + core::StatusCode::kInvalidArgument); + + auto reader = shm_transport->CreateReader(endpoint); + assert(reader.ok()); + assert(!reader.value()->Read().ok()); + +#ifndef _WIN32 + reader.value().reset(); + writer.value().reset(); + assert(shm_transport->Close().ok()); + auto after = shm::ReadNewestMessage(kDomain, endpoint); + assert(after.ok() && after.value() && Text(*after.value()) == "msg 19"); +#endif +} + constexpr int kCrossProcessMessages = 200; // Child: publish until the parent acknowledges every message. @@ -835,6 +877,7 @@ int main(int argc, char** argv) RuntimeRegistration(); WriteWithFillsInPlace(); TopicIsReleasedWithItsLastEndpoint(); + ReadNewestMessageWithoutAttaching(); PrefixOptions(); ReaderOwnedTopicBelongsToItsReader(); CrashedReaderTopicIsRemovedByLastWriter(argv[0]); diff --git a/test/topic_tool_test.cpp b/test/topic_tool_test.cpp index 3ea33b9..2bc4cc2 100644 --- a/test/topic_tool_test.cpp +++ b/test/topic_tool_test.cpp @@ -401,15 +401,32 @@ void TestServices(Fixture& fixture, const std::string& tool) run = fixture.Run({tool, "service", "call", name, "--system", fixture.system(), "--hex", "6"}, 0ms); assert(run.exit.code == 2); - // Stopped: a call fails at once instead of timing out. + // Stopped in order before the tool started: its goodbye is still the + // newest presence message, which the tool reads from the segment. A + // presence writer kept open keeps the segment alive on Windows too. + const auto endpoints = service::EndpointsFor(fixture.Service()); + assert(endpoints.ok()); + auto presence = context.value()->CreateWriter(endpoints.value().presence); + assert(presence.ok()); server.value()->Close(); run = fixture.Run({tool, "service", "list", "--system", fixture.system()}, 0ms); assert(run.exit.success()); - assert(!Contains(run.output, " server: up")); + assert(Contains(run.output, " server: stopped (instance " + instance + " said goodbye ")); run = fixture.Run( {tool, "service", "call", name, "--system", fixture.system(), "--data", "x", "--timeout-ms", "500"}, 0ms); assert(run.exit.code == 1); assert(Contains(run.output, "unavailable: ")); + + // Gone without a goodbye, as after a crash: its last heartbeat, a second + // old, is the newest presence message. + unsigned char heartbeat[16] = {0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x08, 5}; + transport::WriteOptions old; + old.source_timestamp = std::chrono::time_point_cast(core::SteadyClock::now() - 1s); + assert(presence.value()->Write(transport::ByteView::From(heartbeat, sizeof(heartbeat)), old).ok()); + run = fixture.Run({tool, "service", "list", "--system", fixture.system()}, 0ms); + assert(run.exit.success()); + assert(Contains(run.output, + " server: down (instance 0877665544332211 stopped without a goodbye; last heartbeat ")); } #if !defined(_WIN32) diff --git a/tools/puppet_master_topic.cpp b/tools/puppet_master_topic.cpp index c6a19ba..36a3690 100644 --- a/tools/puppet_master_topic.cpp +++ b/tools/puppet_master_topic.cpp @@ -1509,28 +1509,78 @@ struct Presence { std::optional heard; // newest heartbeat or goodbye }; -// Reads the heartbeats that arrived; each is {u64 instance, u64 sequence}, -// little-endian, and sequence 0 is the server's goodbye. +// A presence message is {u64 instance, u64 sequence}, little-endian, and +// sequence 0 is the server's goodbye. +struct Heartbeat { + std::uint64_t instance {0}; + bool goodbye {false}; +}; + +std::optional DecodeHeartbeat(const transport::ByteBuffer& payload) +{ + if (payload.size() != 16) { + return std::nullopt; + } + std::uint64_t instance = 0; + std::uint64_t sequence = 0; + for (int index = 7; index >= 0; --index) { + instance = (instance << 8) | payload[static_cast(index)]; + sequence = (sequence << 8) | payload[static_cast(8 + index)]; + } + return Heartbeat {instance, sequence == 0}; +} + +// Reads the heartbeats that arrived. void Poll(Presence& presence) { for (auto message = presence.subscription->reader->Read(); message.ok(); message = presence.subscription->reader->Read()) { - const auto& payload = message.value().payload; - if (payload.size() != 16) { + const auto heartbeat = DecodeHeartbeat(message.value().payload); + if (!heartbeat) { continue; } - std::uint64_t instance = 0; - std::uint64_t sequence = 0; - for (int index = 7; index >= 0; --index) { - instance = (instance << 8) | payload[static_cast(index)]; - sequence = (sequence << 8) | payload[static_cast(8 + index)]; - } - presence.instance = instance; - presence.goodbye = sequence == 0; + presence.instance = heartbeat->instance; + presence.goodbye = heartbeat->goodbye; presence.heard = Clock::now(); } } +// For a shm service whose server was not heard: the last presence message +// left in its segment, read without attaching. A goodbye means it stopped in +// order; a heartbeat, that it stopped without one (a crash, a kill) or that +// it is alive but slower than its interval. Empty if there is none to read. +std::string LastWord(const ServiceInfo& info) +{ + if (info.spec.transport != core::TransportKind::kIpc) { + return {}; + } + auto endpoints = service::EndpointsFor(info.spec); + if (!endpoints.ok()) { + return {}; + } + auto newest = shm::ReadNewestMessage(info.domain, endpoints.value().presence); + if (!newest.ok() || !newest.value()) { + return {}; + } + const auto& message = *newest.value(); + const auto heartbeat = DecodeHeartbeat(message.payload); + if (!heartbeat) { + return {}; + } + // Both stamps are on the steady clock every process on the host shares. + const auto age = std::chrono::duration_cast( + message.metadata.reception_timestamp - message.metadata.source_timestamp); + const auto ago = std::to_string(std::max(age.count(), 0)) + " ms ago"; + if (heartbeat->goodbye) { + return "stopped (instance " + Hex16(heartbeat->instance) + " said goodbye " + ago + ")"; + } + if (age <= 3 * info.spec.heartbeat_interval) { + return "up, instance " + Hex16(heartbeat->instance) + ", heartbeat " + ago; + } + return "down (instance " + Hex16(heartbeat->instance) + " stopped without a goodbye; last heartbeat " + ago + + ")"; +} + int ServiceList(const Arguments& args) { auto services = ServicesFromSystem(args); @@ -1591,8 +1641,13 @@ int ServiceList(const Arguments& args) if (!presence.subscription) { std::cout << "unknown (" << presence.problem << ")"; } else if (!presence.heard) { - std::cout << "down (no heartbeat in " << std::chrono::duration_cast(listen).count() - << " ms)"; + const auto last = LastWord(info); + if (!last.empty()) { + std::cout << last; + } else { + std::cout << "down (no heartbeat in " << std::chrono::duration_cast(listen).count() + << " ms)"; + } } else if (presence.goodbye) { std::cout << "stopped (instance " << Hex16(presence.instance) << " said goodbye)"; } else { From ff7e3f3fb9f5e072f40dd23a4892ec08a77a7eaf Mon Sep 17 00:00:00 2001 From: SoleyRan Date: Wed, 4 Nov 2026 16:04:15 +0800 Subject: [PATCH 3/6] feat: encode and decode PortableCodec messages field by field tools/portable_fields.{h,cpp} turn typed field values given as text (bool, i8-i64, u8-u64, f32, f64, string, with [] for a vector or [N] for an array) into PortableCodec's wire format, and decode a message back into one text per field, for tools that do not have the message's C++ type. Decoding fails with DataLoss in the same cases as the codec. The test compares the bytes with PortableCodec on a struct with every field type and a nested type, both ways, and covers out-of-range values and corrupt bytes. It needs only the core library, so it runs in every build. Co-Authored-By: Claude Opus 5.5 --- test/CMakeLists.txt | 18 ++ test/portable_fields_test.cpp | 261 +++++++++++++++++++ tools/CMakeLists.txt | 1 + tools/portable_fields.cpp | 478 ++++++++++++++++++++++++++++++++++ tools/portable_fields.h | 50 ++++ 5 files changed, 808 insertions(+) create mode 100644 test/portable_fields_test.cpp create mode 100644 tools/portable_fields.cpp create mode 100644 tools/portable_fields.h diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt index ed0177d..32cd653 100644 --- a/test/CMakeLists.txt +++ b/test/CMakeLists.txt @@ -494,6 +494,24 @@ if(PUPPETMASTER_ENABLE_GOODLOG) ) endif() +# The topic tool's field encoder, against PortableCodec. Needs only the core. +add_executable(puppet_master_portable_fields_test + portable_fields_test.cpp + ${PROJECT_SOURCE_DIR}/tools/portable_fields.cpp +) + +target_include_directories(puppet_master_portable_fields_test PRIVATE ${PROJECT_SOURCE_DIR}/tools) + +target_link_libraries(puppet_master_portable_fields_test + PRIVATE + PuppetMaster::PuppetMaster +) + +add_test( + NAME puppet_master.portable_fields + COMMAND puppet_master_portable_fields_test +) + add_executable(puppet_master_fastdds_policy_mapping_test fastdds_policy_mapping_test.cpp ) diff --git a/test/portable_fields_test.cpp b/test/portable_fields_test.cpp new file mode 100644 index 0000000..ed19499 --- /dev/null +++ b/test/portable_fields_test.cpp @@ -0,0 +1,261 @@ +// The tools' field-by-field encoder and decoder against PortableCodec: the +// same values must give the same bytes, and the codec's bytes must decode to +// the same values. + +#include +#include +#include +#include +#include +#include + +#include + +#include "portable_fields.h" + +namespace core = puppet_master::core; +namespace tools = puppet_master::tools; +namespace transport = puppet_master::transport; + +namespace { + +struct Inner { + std::uint16_t id {0}; + std::string label; +}; + +struct Sample { + bool flag {false}; + std::int8_t i8 {0}; + std::int16_t i16 {0}; + std::int32_t i32 {0}; + std::int64_t i64 {0}; + std::uint8_t u8 {0}; + std::uint16_t u16 {0}; + std::uint32_t u32 {0}; + std::uint64_t u64 {0}; + float f32 {0}; + double f64 {0}; + std::string text; + std::vector counts; + std::array position {}; + std::vector names; + Inner inner; +}; + +} // namespace + +template <> +struct puppet_master::transport::PortableFields { + template + static void Visit(Message& inner, Visitor&& field) + { + field(inner.id); + field(inner.label); + } +}; + +template <> +struct puppet_master::transport::PortableFields { + template + static void Visit(Message& sample, Visitor&& field) + { + field(sample.flag); + field(sample.i8); + field(sample.i16); + field(sample.i32); + field(sample.i64); + field(sample.u8); + field(sample.u16); + field(sample.u32); + field(sample.u64); + field(sample.f32); + field(sample.f64); + field(sample.text); + field(sample.counts); + field(sample.position); + field(sample.names); + field(sample.inner); + } +}; + +template <> +struct puppet_master::transport::MessageTypeName { + static constexpr const char* value = "test.Sample"; +}; + +template <> +struct puppet_master::transport::Codec : transport::PortableCodec {}; + +namespace { + +tools::FieldType Type(const char* text) +{ + auto type = tools::ParseFieldType(text); + assert(type.ok()); + return type.value(); +} + +transport::ByteBuffer Encode(const Sample& sample) +{ + using Codec = transport::Codec; + transport::ByteBuffer bytes(Codec::MaxSize(sample)); + auto used = Codec::Encode(sample, transport::MutableByteView(bytes.data(), bytes.size())); + assert(used.ok()); + bytes.resize(used.value()); + return bytes; +} + +struct Field { + const char* type; + const char* value; // as given on the command line + const char* decoded; // as printed +}; + +// The fields of Sample, Inner's flattened, in wire order. +const std::vector kFields { + {"bool", "true", "true"}, + {"i8", "-128", "-128"}, + {"i16", "-300", "-300"}, + {"i32", "123456", "123456"}, + {"i64", "-9000000000", "-9000000000"}, + {"u8", "255", "255"}, + {"u16", "0xBEEF", "48879"}, + {"u32", "4000000000", "4000000000"}, + {"u64", "18446744073709551615", "18446744073709551615"}, + {"f32", "1.5", "1.5"}, + {"f64", " -2.25 ", "-2.25"}, + {"string", "hi, \"you\"\n", "\"hi, \\\"you\\\"\\x0a\""}, + {"u32[]", "1, 2,3", "[1, 2, 3]"}, + {"f64[3]", "0.5,1,-3e2", "[0.5, 1, -300]"}, + {"string[]", "a,b c", "[\"a\", \"b c\"]"}, + {"u16", "7", "7"}, + {"string", "", "\"\""}, +}; + +Sample MakeSample() +{ + Sample sample; + sample.flag = true; + sample.i8 = -128; + sample.i16 = -300; + sample.i32 = 123456; + sample.i64 = -9000000000LL; + sample.u8 = 255; + sample.u16 = 0xBEEF; + sample.u32 = 4000000000U; + sample.u64 = 18446744073709551615ULL; + sample.f32 = 1.5F; + sample.f64 = -2.25; + sample.text = "hi, \"you\"\n"; + sample.counts = {1, 2, 3}; + sample.position = {0.5, 1, -300}; + sample.names = {"a", "b c"}; + sample.inner.id = 7; + return sample; +} + +void SameBytesAsTheCodec() +{ + transport::ByteBuffer encoded; + for (const auto& field : kFields) { + assert(tools::EncodeField(Type(field.type), field.value, encoded).ok()); + } + assert(encoded == Encode(MakeSample())); +} + +void DecodesTheCodecsBytes() +{ + std::vector types; + for (const auto& field : kFields) { + types.push_back(Type(field.type)); + } + const auto bytes = Encode(MakeSample()); + auto decoded = tools::DecodeFields(types, transport::ByteView(bytes)); + assert(decoded.ok()); + assert(decoded.value().size() == kFields.size()); + for (std::size_t index = 0; index < kFields.size(); ++index) { + if (decoded.value()[index] != kFields[index].decoded) { + std::cerr << "field " << index << ": " << decoded.value()[index] << '\n'; + } + assert(decoded.value()[index] == kFields[index].decoded); + } + + // A field list that differs from the writer's fails, as in the codec. + types.pop_back(); + auto short_list = tools::DecodeFields(types, transport::ByteView(bytes)); + assert(short_list.status().code() == core::StatusCode::kDataLoss); + assert(short_list.status().message().find("4 bytes left over") != std::string::npos); + types.push_back(Type("string")); + types.push_back(Type("u8")); + auto long_list = tools::DecodeFields(types, transport::ByteView(bytes)); + assert(long_list.status().code() == core::StatusCode::kDataLoss); + assert(long_list.status().message().find("field 18 (u8): message ends inside a field") != std::string::npos); +} + +void FieldTypes() +{ + for (const auto* good : {"bool", "u64", "f32[]", "string[]", "i16[4]", "u8[0x10]"}) { + assert(tools::ParseFieldType(good).ok()); + } + for (const auto* bad : {"", "u128", "int", "u8[0]", "u8[-1]", "bool[", "f64]", "u8[x]", "Pose"}) { + assert(tools::ParseFieldType(bad).status().code() == core::StatusCode::kInvalidArgument); + } + assert(tools::ToString(Type("u8[0x10]")) == "u8[16]"); + assert(tools::ToString(Type(" f64[] ")) == "f64[]"); +} + +void BadValues() +{ + const auto fails = [](const char* type, const char* value) { + transport::ByteBuffer bytes; + return tools::EncodeField(Type(type), value, bytes).code() == core::StatusCode::kInvalidArgument; + }; + assert(fails("u8", "256")); + assert(fails("u8", "-1")); + assert(fails("i8", "128")); + assert(fails("i8", "-129")); + assert(fails("u16", "0x10000")); + assert(fails("u64", "18446744073709551616")); + assert(fails("i32", "1.5")); + assert(fails("i32", "")); + assert(fails("bool", "yes")); + assert(fails("f32", "1e40")); + assert(fails("f64", "1e400")); + assert(fails("f64", "x")); + assert(fails("f64[3]", "1,2")); + assert(fails("u8[]", "1,,2")); + + // An empty vector is a zero count; i8 -128 is its two's complement. + transport::ByteBuffer bytes; + assert(tools::EncodeField(Type("u32[]"), "", bytes).ok()); + assert(tools::EncodeField(Type("i8"), "-128", bytes).ok()); + assert((bytes == transport::ByteBuffer {0, 0, 0, 0, 0x80})); +} + +void BadBytes() +{ + const auto decode = [](const char* type, transport::ByteBuffer bytes) { + return tools::DecodeFields({Type(type)}, transport::ByteView(bytes)); + }; + assert(decode("bool", {2}).status().code() == core::StatusCode::kDataLoss); + assert(decode("u32", {1, 2}).status().code() == core::StatusCode::kDataLoss); + // A count larger than what is left fails before allocating. + assert(decode("u64[]", {0xff, 0xff, 0xff, 0x7f}).status().code() == core::StatusCode::kDataLoss); + assert(decode("string", {5, 0, 0, 0, 'a'}).status().code() == core::StatusCode::kDataLoss); + auto empty = tools::DecodeFields({}, transport::ByteView()); + assert(empty.ok() && empty.value().empty()); +} + +} // namespace + +int main() +{ + SameBytesAsTheCodec(); + DecodesTheCodecsBytes(); + FieldTypes(); + BadValues(); + BadBytes(); + std::cout << "portable fields tests passed\n"; + return 0; +} diff --git a/tools/CMakeLists.txt b/tools/CMakeLists.txt index bae680b..4340d67 100644 --- a/tools/CMakeLists.txt +++ b/tools/CMakeLists.txt @@ -47,6 +47,7 @@ install( if(TARGET PuppetMaster::ShmAdapter) add_executable(puppet_master_topic puppet_master_topic.cpp + portable_fields.cpp ) target_link_libraries(puppet_master_topic diff --git a/tools/portable_fields.cpp b/tools/portable_fields.cpp new file mode 100644 index 0000000..8dc4958 --- /dev/null +++ b/tools/portable_fields.cpp @@ -0,0 +1,478 @@ +#include "portable_fields.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace puppet_master::tools { + +namespace { + +using transport::ByteBuffer; +using transport::ByteView; + +struct ScalarName { + const char* name; + Scalar scalar; +}; + +constexpr ScalarName kScalars[] = { + {"bool", Scalar::kBool}, {"i8", Scalar::kI8}, {"i16", Scalar::kI16}, {"i32", Scalar::kI32}, + {"i64", Scalar::kI64}, {"u8", Scalar::kU8}, {"u16", Scalar::kU16}, {"u32", Scalar::kU32}, + {"u64", Scalar::kU64}, {"f32", Scalar::kF32}, {"f64", Scalar::kF64}, {"string", Scalar::kString}, +}; + +const char* NameOf(Scalar scalar) +{ + for (const auto& entry : kScalars) { + if (entry.scalar == scalar) { + return entry.name; + } + } + return "?"; +} + +// Bytes on the wire; a string's is its count, before the bytes. +std::size_t WidthOf(Scalar scalar) +{ + switch (scalar) { + case Scalar::kBool: + case Scalar::kI8: + case Scalar::kU8: + return 1; + case Scalar::kI16: + case Scalar::kU16: + return 2; + case Scalar::kI32: + case Scalar::kU32: + case Scalar::kF32: + case Scalar::kString: + return 4; + case Scalar::kI64: + case Scalar::kU64: + case Scalar::kF64: + return 8; + } + return 1; +} + +bool IsSigned(Scalar scalar) +{ + return scalar == Scalar::kI8 || scalar == Scalar::kI16 || scalar == Scalar::kI32 || scalar == Scalar::kI64; +} + +void Put(std::uint64_t bits, std::size_t width, ByteBuffer& out) +{ + for (std::size_t index = 0; index < width; ++index) { + out.push_back(static_cast(bits >> (8 * index))); + } +} + +std::string_view Trim(std::string_view text) +{ + while (!text.empty() && (text.front() == ' ' || text.front() == '\t')) { + text.remove_prefix(1); + } + while (!text.empty() && (text.back() == ' ' || text.back() == '\t')) { + text.remove_suffix(1); + } + return text; +} + +// Decimal with an optional sign, or 0x hex, within `width` bytes. `bits` +// gets the two's complement of a negative value. +bool ParseInteger(std::string_view text, bool is_signed, std::size_t width, std::uint64_t& bits) +{ + bool negative = false; + if (!text.empty() && (text.front() == '-' || text.front() == '+')) { + negative = text.front() == '-'; + text.remove_prefix(1); + } + if (negative && !is_signed) { + return false; + } + std::uint64_t base = 10; + if (text.size() > 2 && text[0] == '0' && (text[1] == 'x' || text[1] == 'X')) { + base = 16; + text.remove_prefix(2); + } + if (text.empty()) { + return false; + } + std::uint64_t magnitude = 0; + for (const char c : text) { + std::uint64_t digit = 0; + if (c >= '0' && c <= '9') { + digit = static_cast(c - '0'); + } else if (base == 16 && c >= 'a' && c <= 'f') { + digit = static_cast(c - 'a' + 10); + } else if (base == 16 && c >= 'A' && c <= 'F') { + digit = static_cast(c - 'A' + 10); + } else { + return false; + } + if (magnitude > (std::numeric_limits::max() - digit) / base) { + return false; + } + magnitude = magnitude * base + digit; + } + const auto bit_width = 8 * width; + if (is_signed) { + const std::uint64_t limit = std::uint64_t {1} << (bit_width - 1); // |minimum| + if (negative ? magnitude > limit : magnitude >= limit) { + return false; + } + bits = negative ? ~magnitude + 1 : magnitude; + return true; + } + if (bit_width < 64 && (magnitude >> bit_width) != 0) { + return false; + } + bits = magnitude; + return true; +} + +bool ParseFloat(std::string_view text, double& value) +{ + if (text.empty() || text.front() == ' ' || text.front() == '\t') { + return false; + } + const std::string copy(text); + char* end = nullptr; + errno = 0; + value = std::strtod(copy.c_str(), &end); + return end == copy.c_str() + copy.size() && !(errno == ERANGE && std::isinf(value)); +} + +// Empty on success, else why `text` is not a `scalar`. +std::string EncodeScalar(Scalar scalar, std::string_view text, ByteBuffer& out) +{ + switch (scalar) { + case Scalar::kBool: + if (text == "true" || text == "1") { + out.push_back(1); + return {}; + } + if (text == "false" || text == "0") { + out.push_back(0); + return {}; + } + return "not true, false, 1, or 0"; + case Scalar::kString: + if (text.size() > std::numeric_limits::max()) { + return "longer than 2^32-1 bytes"; + } + Put(text.size(), 4, out); + out.insert(out.end(), text.begin(), text.end()); + return {}; + case Scalar::kF32: + case Scalar::kF64: { + double value = 0; + if (!ParseFloat(text, value)) { + return "not a number"; + } + if (scalar == Scalar::kF64) { + std::uint64_t bits = 0; + std::memcpy(&bits, &value, sizeof(bits)); + Put(bits, 8, out); + return {}; + } + if (std::isfinite(value) && std::fabs(value) > static_cast(std::numeric_limits::max())) { + return "out of range for f32"; + } + const auto narrow = static_cast(value); + std::uint32_t bits = 0; + std::memcpy(&bits, &narrow, sizeof(bits)); + Put(bits, 4, out); + return {}; + } + default: { + std::uint64_t bits = 0; + if (!ParseInteger(text, IsSigned(scalar), WidthOf(scalar), bits)) { + return std::string("not a ") + NameOf(scalar) + " (decimal or 0x hex, in range)"; + } + Put(bits, WidthOf(scalar), out); + return {}; + } + } +} + +std::vector SplitCommas(std::string_view text) +{ + std::vector parts; + if (text.empty()) { + return parts; + } + std::size_t start = 0; + while (true) { + const auto comma = text.find(',', start); + parts.push_back(text.substr(start, comma == std::string_view::npos ? std::string_view::npos : comma - start)); + if (comma == std::string_view::npos) { + return parts; + } + start = comma + 1; + } +} + +// The shortest decimal that reads back as the same value. +std::string FormatFloat(double value, bool single) +{ + if (std::isnan(value)) { + return "nan"; + } + if (std::isinf(value)) { + return value < 0 ? "-inf" : "inf"; + } + char text[64]; + int precision = 1; + for (; precision < 17; ++precision) { + std::snprintf(text, sizeof(text), "%.*g", precision, value); + const double back = std::strtod(text, nullptr); + if (single ? static_cast(back) == static_cast(value) : back == value) { + break; + } + } + // %g switches to an exponent once the integer part has more digits than + // the precision: print -300, not -3e+02, while the digits stay exact. + const int exponent = value == 0 ? 0 : static_cast(std::floor(std::log10(std::fabs(value)))); + if (exponent >= precision && exponent < 17) { + precision = exponent + 1; + } + std::snprintf(text, sizeof(text), "%.*g", precision, value); + return text; +} + +std::string Quote(const core::Byte* data, std::size_t size) +{ + std::string text = "\""; + for (std::size_t index = 0; index < size; ++index) { + const auto byte = data[index]; + if (byte == '"' || byte == '\\') { + text += '\\'; + text += static_cast(byte); + } else if (byte >= 0x20 && byte < 0x7f) { + text += static_cast(byte); + } else { + char escaped[8]; + std::snprintf(escaped, sizeof(escaped), "\\x%02x", static_cast(byte)); + text += escaped; + } + } + return text + "\""; +} + +class Decoder { +public: + explicit Decoder(ByteView bytes) : bytes_(bytes) {} + + core::Status Field(const FieldType& type, std::string& text) + { + if (type.shape == FieldType::Shape::kOne) { + return One(type.scalar, text); + } + std::size_t count = type.length; + if (type.shape == FieldType::Shape::kVector) { + std::uint64_t bits = 0; + auto status = Take(4, bits); + if (!status.ok()) { + return status; + } + count = static_cast(bits); + // Each element takes at least one byte (a string, its count). + if (count > (bytes_.size() - offset_) / WidthOf(type.scalar)) { + return core::Status::DataLoss("element count " + std::to_string(count) + " exceeds the message"); + } + } + text = "["; + for (std::size_t index = 0; index < count; ++index) { + std::string element; + auto status = One(type.scalar, element); + if (!status.ok()) { + return status; + } + text += (index == 0 ? "" : ", ") + element; + } + text += "]"; + return core::Status::Ok(); + } + + std::size_t left() const noexcept { return bytes_.size() - offset_; } + +private: + core::Status Take(std::size_t width, std::uint64_t& bits) + { + if (left() < width) { + return core::Status::DataLoss("message ends inside a field"); + } + bits = 0; + for (std::size_t index = 0; index < width; ++index) { + bits |= static_cast(bytes_.data()[offset_ + index]) << (8 * index); + } + offset_ += width; + return core::Status::Ok(); + } + + core::Status One(Scalar scalar, std::string& text) + { + std::uint64_t bits = 0; + auto status = Take(WidthOf(scalar), bits); + if (!status.ok()) { + return status; + } + switch (scalar) { + case Scalar::kBool: + if (bits > 1) { + return core::Status::DataLoss("bool byte is " + std::to_string(bits)); + } + text = bits == 1 ? "true" : "false"; + return core::Status::Ok(); + case Scalar::kString: { + const auto size = static_cast(bits); + if (size > left()) { + return core::Status::DataLoss("element count " + std::to_string(size) + " exceeds the message"); + } + text = Quote(bytes_.data() + offset_, size); + offset_ += size; + return core::Status::Ok(); + } + case Scalar::kF32: { + const auto narrow_bits = static_cast(bits); + float value = 0; + std::memcpy(&value, &narrow_bits, sizeof(value)); + text = FormatFloat(value, true); + return core::Status::Ok(); + } + case Scalar::kF64: { + double value = 0; + std::memcpy(&value, &bits, sizeof(value)); + text = FormatFloat(value, false); + return core::Status::Ok(); + } + default: + break; + } + if (IsSigned(scalar)) { + const auto width = 8 * WidthOf(scalar); + // Sign-extend from the field's width. + const auto shift = 64 - width; + const auto value = static_cast(bits << shift) >> shift; + text = std::to_string(value); + } else { + text = std::to_string(bits); + } + return core::Status::Ok(); + } + + ByteView bytes_; + std::size_t offset_ {0}; +}; + +} // namespace + +core::Result ParseFieldType(std::string_view text) +{ + using ResultType = core::Result; + const auto invalid = [&text] { + return ResultType::FromStatus(core::Status::InvalidArgument( + "field type " + std::string(text) + + " is not bool, i8-i64, u8-u64, f32, f64, or string, optionally with [] or [N]")); + }; + FieldType type; + auto name = Trim(text); + const auto bracket = name.find('['); + if (bracket != std::string_view::npos) { + if (name.back() != ']') { + return invalid(); + } + const auto inside = name.substr(bracket + 1, name.size() - bracket - 2); + name = name.substr(0, bracket); + if (inside.empty()) { + type.shape = FieldType::Shape::kVector; + } else { + std::uint64_t length = 0; + if (inside.front() == '+' || !ParseInteger(inside, false, 4, length) || length == 0) { + return invalid(); + } + type.shape = FieldType::Shape::kArray; + type.length = static_cast(length); + } + } + for (const auto& entry : kScalars) { + if (name == entry.name) { + type.scalar = entry.scalar; + return ResultType(type); + } + } + return invalid(); +} + +std::string ToString(const FieldType& type) +{ + std::string text = NameOf(type.scalar); + if (type.shape == FieldType::Shape::kVector) { + text += "[]"; + } else if (type.shape == FieldType::Shape::kArray) { + text += "[" + std::to_string(type.length) + "]"; + } + return text; +} + +core::Status EncodeField(const FieldType& type, std::string_view value, ByteBuffer& out) +{ + const auto failed = [&type](const std::string& element, const std::string& why) { + return core::Status::InvalidArgument(ToString(type) + " value \"" + element + "\": " + why); + }; + if (type.shape == FieldType::Shape::kOne) { + // Strings are taken as they are; numbers may have spaces around them. + const auto text = type.scalar == Scalar::kString ? value : Trim(value); + const auto why = EncodeScalar(type.scalar, text, out); + return why.empty() ? core::Status::Ok() : failed(std::string(value), why); + } + const auto elements = SplitCommas(value); + if (type.shape == FieldType::Shape::kArray && elements.size() != type.length) { + return failed(std::string(value), + "has " + std::to_string(elements.size()) + " elements, not " + std::to_string(type.length)); + } + if (type.shape == FieldType::Shape::kVector) { + if (elements.size() > std::numeric_limits::max()) { + return failed(std::string(value), "more than 2^32-1 elements"); + } + Put(elements.size(), 4, out); + } + for (const auto element : elements) { + const auto text = type.scalar == Scalar::kString ? element : Trim(element); + const auto why = EncodeScalar(type.scalar, text, out); + if (!why.empty()) { + return failed(std::string(element), why); + } + } + return core::Status::Ok(); +} + +core::Result> DecodeFields(const std::vector& types, ByteView bytes) +{ + using ResultType = core::Result>; + Decoder decoder(bytes); + std::vector fields; + for (std::size_t index = 0; index < types.size(); ++index) { + std::string text; + auto status = decoder.Field(types[index], text); + if (!status.ok()) { + return ResultType::FromStatus(core::Status::DataLoss( + "field " + std::to_string(index + 1) + " (" + ToString(types[index]) + "): " + status.message())); + } + fields.push_back(std::move(text)); + } + if (decoder.left() != 0) { + return ResultType::FromStatus(core::Status::DataLoss( + std::to_string(decoder.left()) + " bytes left over after " + std::to_string(types.size()) + + " fields; the reply has other fields")); + } + return ResultType(std::move(fields)); +} + +} // namespace puppet_master::tools diff --git a/tools/portable_fields.h b/tools/portable_fields.h new file mode 100644 index 0000000..f36e20d --- /dev/null +++ b/tools/portable_fields.h @@ -0,0 +1,50 @@ +#pragma once + +// Encodes and decodes PortableCodec messages field by field from text, for +// tools that do not have the message's C++ type. The wire format is that of +// puppet_master/transport/portable_codec.h; see docs/typed-messages.md. + +#include +#include +#include +#include + +#include +#include +#include + +namespace puppet_master::tools { + +enum class Scalar { kBool, kI8, kI16, kI32, kI64, kU8, kU16, kU32, kU64, kF32, kF64, kString }; + +// One field: a scalar or a string, a vector of them ("u32[]": a u32 count, +// then the elements), or a fixed array ("f64[3]": the elements only). A +// nested type with PortableFields is its fields in order on the wire, so it +// is written as those fields. +struct FieldType { + enum class Shape { kOne, kVector, kArray }; + + Scalar scalar {Scalar::kU8}; + Shape shape {Shape::kOne}; + std::size_t length {0}; // kArray +}; + +// "bool", "i8" to "i64", "u8" to "u64", "f32", "f64", or "string", with "[]" +// for a vector or "[N]" for an array. +core::Result ParseFieldType(std::string_view text); +std::string ToString(const FieldType& type); + +// Appends `value` encoded as `type`. Integers are decimal or 0x hex; bools +// true, false, 1, or 0; strings are taken as they are. A vector's or array's +// elements are separated by commas, so string elements cannot contain one; +// an empty value is an empty vector. +core::Status EncodeField(const FieldType& type, std::string_view value, transport::ByteBuffer& out); + +// Decodes `bytes` as `types` in order, into one text per field: numbers in +// decimal, strings quoted with \xNN for bytes that are not printable, +// vectors and arrays as "[a, b]". DataLoss, as PortableCodec, if the bytes +// end inside a field, a count exceeds them, a bool is not 0 or 1, or bytes +// are left over. +core::Result> DecodeFields(const std::vector& types, transport::ByteView bytes); + +} // namespace puppet_master::tools From 199312b1c78cf086ff8e83e5c4e2ca8885c5831b Mon Sep 17 00:00:00 2001 From: SoleyRan Date: Wed, 4 Nov 2026 16:38:48 +0800 Subject: [PATCH 4/6] feat: typed requests and replies in service call service call --field TYPE:VALUE builds a portable-codec request field by field, in the order of the type's PortableFields, and --reply-fields TYPE,... decodes the reply into one line per field. A reply that does not match the list exits with 1, names the first failing field or the bytes left over, and prints the reply's bytes. --field cannot be mixed with --data or --hex. The topic tool test now strips '\r' from the tool's output, which ends lines with "\r\n" on Windows, and calls a real PortableCodec service. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 5 + docs/launcher.md | 50 +++++++++- test/topic_tool_test.cpp | 175 ++++++++++++++++++++++++++++++++-- tools/portable_fields.cpp | 3 + tools/puppet_master_topic.cpp | 72 +++++++++++++- 5 files changed, 294 insertions(+), 11 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2864dae..5f8a7c6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -22,6 +22,11 @@ the minor version in their soname (`libpuppet_master.so.0.4`), and (`stopped`) from one whose heartbeats stopped without one (`down`, with its last heartbeat's age), also when the server stopped before the tool started. See [Segment Lifetime](docs/shm-transport.md#segment-lifetime). +- **Typed service calls.** `service call --field TYPE:VALUE` builds a + portable-codec request field by field (`bool`, `i8`-`i64`, `u8`-`u64`, + `f32`, `f64`, `string`, with `[]` for a vector or `[N]` for an array), and + `--reply-fields TYPE,...` decodes the reply into one line per field. See + [Typed Requests](docs/launcher.md#typed-requests). ## 0.4.0 diff --git a/docs/launcher.md b/docs/launcher.md index 77e952d..a3f72dc 100644 --- a/docs/launcher.md +++ b/docs/launcher.md @@ -263,7 +263,7 @@ puppet_master_topic service call /map/query --system system.json --hex "01 00 2a | Command | Effect | |---|---| | `service list` | each service the manifest's nodes declare: request and reply types, transport, which components serve and call it, and whether a server is up, with its instance id and the age of its newest heartbeat | -| `service call SERVICE` | send one request, the bytes of `--data TEXT`, of `--hex HEX`, or none, and print the reply's size, round trip, and bytes (in hex, or `--text`; all of them unless `--bytes N`) | +| `service call SERVICE` | send one request, the bytes of `--data TEXT`, of `--hex HEX`, of `--field TYPE:VALUE`s (see [Typed Requests](#typed-requests)), or none, and print the reply's size, round trip, and bytes (in hex, or `--text`; all of them unless `--bytes N`), or its fields with `--reply-fields` | `service list` reads each service's presence topic only, so it creates no client and no reply topic. It listens for three heartbeat intervals (at @@ -285,7 +285,53 @@ the service, not the processes running. request like any other. It waits up to `--timeout-ms N` (2000 by default) for a server and its reply, then exits with 1 and the call's status, such as `unavailable` (no live server), `deadline_exceeded`, or the handler's own -error and message. Requests carry raw bytes: encode typed requests yourself. +error and message. + +#### Typed Requests + +For a service whose messages use the [portable codec](typed-messages.md#portable-codec), +`--field TYPE:VALUE` builds the request field by field, in the order of the +type's `PortableFields`, and `--reply-fields TYPE,...` decodes the reply the +same way. The tool has no C++ types of its own, so the field list is yours to +match: + +```bash +# struct PoseQuery { std::string frame; std::uint32_t id; std::vector weights; }; +# struct Pose { double x, y; std::string frame; std::array covariance; bool valid; }; +puppet_master_topic service call /map/pose --system system.json \ + --field string:map --field u32:7 --field "f64[]:1, 2.5" \ + --reply-fields "f64,f64,string,f32[2],bool" +``` + +```text +call /map/pose: server 7763ad3f9789659a, request 31 B +reply 32 B in 0.6 ms + 1 f64: 10.5 + 2 f64: 3.5 + 3 string: "map" + 4 f32[2]: [0.25, -1] + 5 bool: true +``` + +| Type | Value | +|---|---| +| `bool` | `true`, `false`, `1`, or `0` | +| `i8` `i16` `i32` `i64`, `u8` `u16` `u32` `u64` | decimal or `0x` hex, within the type's range | +| `f32`, `f64` | a decimal number, such as `1.5` or `-3e2` | +| `string` | the rest of the argument, as it is | +| `T[]` | a vector: elements separated by commas; empty for none | +| `T[N]` | an array of exactly N elements | + +A field of a nested type is its own fields in order, so list those. Enums are +their underlying integer type. String elements of a vector cannot contain a +comma. + +A request missing a field comes back as the server's decode error +(`data_loss: ...: message ends inside a field`). A reply that does not match +`--reply-fields` exits with 1, names the first field that failed or the bytes +left over, and prints the reply's bytes so the list can be corrected. A +change to a message's fields also changes its version, so check the +`request` and `reply` versions `service list` shows. ## Library Helpers diff --git a/test/topic_tool_test.cpp b/test/topic_tool_test.cpp index 2bc4cc2..3c26328 100644 --- a/test/topic_tool_test.cpp +++ b/test/topic_tool_test.cpp @@ -3,6 +3,8 @@ // // puppet_master_topic_tool_test +#include +#include #include #include #include @@ -20,6 +22,8 @@ #include #include #include +#include +#include #include namespace config = puppet_master::configuration; @@ -32,6 +36,63 @@ namespace transport = puppet_master::transport; using namespace std::chrono_literals; +// The typed service's messages, with PortableCodec, as a component would +// declare them. +struct PoseQuery { + std::string frame; + std::uint32_t id {0}; + std::vector weights; +}; + +struct Pose { + double x {0}; + double y {0}; + std::string frame; + std::array covariance {}; + bool valid {false}; +}; + +template <> +struct puppet_master::transport::PortableFields { + template + static void Visit(Message& query, Visitor&& field) + { + field(query.frame); + field(query.id); + field(query.weights); + } +}; + +template <> +struct puppet_master::transport::PortableFields { + template + static void Visit(Message& pose, Visitor&& field) + { + field(pose.x); + field(pose.y); + field(pose.frame); + field(pose.covariance); + field(pose.valid); + } +}; + +template <> +struct puppet_master::transport::MessageTypeName { + static constexpr const char* value = "test.PoseQuery"; + static constexpr std::uint32_t version = 1; +}; + +template <> +struct puppet_master::transport::MessageTypeName { + static constexpr const char* value = "test.Pose"; + static constexpr std::uint32_t version = 1; +}; + +template <> +struct puppet_master::transport::Codec : puppet_master::transport::PortableCodec {}; +template <> +struct puppet_master::transport::Codec : puppet_master::transport::PortableCodec {}; + namespace { constexpr core::DomainId kDomain = 77; @@ -41,10 +102,14 @@ bool Contains(const std::string& text, const std::string& part) return text.find(part) != std::string::npos; } +// Without '\r': on Windows the tool's text-mode output ends lines with +// "\r\n", and the checks below match on "\n". std::string ReadFile(const fs::path& path) { std::ifstream in(path, std::ios::binary); - return std::string(std::istreambuf_iterator(in), std::istreambuf_iterator()); + std::string text(std::istreambuf_iterator(in), std::istreambuf_iterator{}); + text.erase(std::remove(text.begin(), text.end(), '\r'), text.end()); + return text; } void WriteFile(const fs::path& path, const std::string& text) @@ -61,15 +126,20 @@ class Fixture { : stamp_(std::to_string(std::chrono::steady_clock::now().time_since_epoch().count())), root_(fs::temp_directory_path() / ("pm_topic_tool_" + stamp_)), topic_("/pm_topic_test/text_" + stamp_), - service_("/pm_topic_test/echo_" + stamp_) + service_("/pm_topic_test/echo_" + stamp_), + pose_service_("/pm_topic_test/pose_" + stamp_) { WriteFile(root_ / "share/test_interfaces/topics.json", R"({"topics": [{"id": "text", "name": ")" + topic_ + R"(", "message_type": "test.Text"}], "services": [{"id": "echo", "name": ")" + service_ + - R"(", "request_type": "test.EchoRequest", "reply_type": "test.EchoReply"}]})"); + R"(", "request_type": "test.EchoRequest", "reply_type": "test.EchoReply"}, + {"id": "pose", "name": ")" + pose_service_ + + R"(", "request_type": "test.PoseQuery", "request_version": 1, + "reply_type": "test.Pose", "reply_version": 1, + "encoding": "application/x-puppetmaster-portable"}]})"); WriteFile(root_ / "share/producer/producer.json", R"({ "imports": ["test_interfaces/topics.json"], - "components": [{"name": "producer", "writers": ["text"], "servers": ["echo"], + "components": [{"name": "producer", "writers": ["text"], "servers": ["echo", "pose"], "triggers": [{"kind": "manual"}]}]})"); WriteFile(root_ / "share/consumer/consumer.json", R"({ "imports": ["test_interfaces/topics.json"], @@ -126,14 +196,17 @@ class Fixture { } const std::string& service_name() const noexcept { return service_; } + const std::string& pose_service_name() const noexcept { return pose_service_; } ~Fixture() { writer_.reset(); transport_.reset(); shm::RemoveSegment(kDomain, topic_); - shm::RemoveSegment(kDomain, service_ + "/request"); - shm::RemoveSegment(kDomain, service_ + "/presence"); + for (const auto* name : {&service_, &pose_service_}) { + shm::RemoveSegment(kDomain, *name + "/request"); + shm::RemoveSegment(kDomain, *name + "/presence"); + } std::error_code ignored; fs::remove_all(root_, ignored); } @@ -190,6 +263,7 @@ class Fixture { fs::path root_; std::string topic_; std::string service_; + std::string pose_service_; std::unique_ptr transport_; transport::WriterPtr writer_; int runs_ {0}; @@ -429,6 +503,94 @@ void TestServices(Fixture& fixture, const std::string& tool) " server: down (instance 0877665544332211 stopped without a goodbye; last heartbeat ")); } +// A PortableCodec service: the tool encodes the request from --field values +// and decodes the reply with --reply-fields, with no C++ types of its own. +void TestTypedService(Fixture& fixture, const std::string& tool) +{ + const auto& name = fixture.pose_service_name(); + runtime::RuntimeOptions options; + options.register_inmemory_transport = false; + auto context = runtime::RuntimeContext::Create(options); + assert(context.ok()); + shm::Options shm_options; + shm_options.domain_id = kDomain; + assert(shm::RegisterTransport(*context.value(), core::TransportName::Create("shm").value(), shm_options).ok()); + auto server = service::MakeTypedServer(*context.value(), + service::TypedServiceSpec(core::TopicName::Create(name).value(), core::TransportKind::kIpc), + [](const PoseQuery& query) { + if (query.frame == "fail") { + return core::Result::FromStatus(core::Status::InvalidArgument("no frame fail")); + } + Pose pose; + pose.x = query.id * 1.5; + for (const auto weight : query.weights) { + pose.y += weight; + } + pose.frame = query.frame; + pose.covariance = {0.25F, -1.0F}; + pose.valid = !query.frame.empty(); + return core::Result(pose); + }); + assert(server.ok()); + + const std::vector base {tool, "service", "call", name, "--system", fixture.system()}; + const auto with = [&base](std::initializer_list extra) { + auto command = base; + command.insert(command.end(), extra); + return command; + }; + const std::string reply_fields = "f64,f64,string,f32[2],bool"; + + auto run = fixture.Run(with({"--field", "string:map", "--field", "u32:7", "--field", "f64[]:1, 2.5", + "--reply-fields", reply_fields}), + 0ms); + assert(run.exit.success()); + // 4 + 3 bytes of string, 4 of u32, 4 + 2 x 8 of f64[]. + assert(Contains(run.output, "request 31 B")); + assert(Contains(run.output, " 1 f64: 10.5\n")); + assert(Contains(run.output, " 2 f64: 3.5\n")); + assert(Contains(run.output, " 3 string: \"map\"\n")); + assert(Contains(run.output, " 4 f32[2]: [0.25, -1]\n")); + assert(Contains(run.output, " 5 bool: true\n")); + + // Without --reply-fields the reply is shown as bytes. + run = fixture.Run(with({"--field", "string:", "--field", "u32:0", "--field", "f64[]:"}), 0ms); + assert(run.exit.success()); + // 8 + 8 of f64, 4 of an empty string, 2 x 4 of f32, 1 of bool. + assert(Contains(run.output, "reply 29 B in ")); + + // A reply field list that does not match: the bytes, and a failure. + run = fixture.Run(with({"--field", "string:map", "--field", "u32:7", "--field", "f64[]:", "--reply-fields", + "f64,f64"}), + 0ms); + assert(run.exit.code == 1); + // A 32-byte reply, of which two f64 take 16. + assert(Contains(run.output, "data_loss: 16 bytes left over after 2 fields")); + + // A request missing a field: the server's decode error comes back. + run = fixture.Run(with({"--field", "string:map"}), 0ms); + assert(run.exit.code == 1); + assert(Contains(run.output, "data_loss: test.PoseQuery: portable decoding: message ends inside a field")); + + // The handler's own error. + run = fixture.Run(with({"--field", "string:fail", "--field", "u32:1", "--field", "f64[]:"}), 0ms); + assert(run.exit.code == 1); + assert(Contains(run.output, "invalid_argument: no frame fail")); + + // Bad arguments are refused before anything is sent. + for (const auto& bad : std::vector> { + with({"--field", "u8:300"}), + with({"--field", "nope"}), + with({"--field", "u128:1"}), + with({"--data", "x", "--field", "u8:1"}), + with({"--field", "u8:1", "--hex", "01"}), + with({"--reply-fields", "f64,,bool"}), + }) { + run = fixture.Run(bad, 0ms); + assert(run.exit.code == 2); + } +} + #if !defined(_WIN32) void TestListFromSegments(Fixture& fixture, const std::string& tool) { @@ -466,6 +628,7 @@ int main(int argc, char** argv) TestErrors(fixture, tool); TestRecordInfoReplay(fixture, tool); TestServices(fixture, tool); + TestTypedService(fixture, tool); #if !defined(_WIN32) // Segment headers can only be read on Linux. TestListFromSegments(fixture, tool); diff --git a/tools/portable_fields.cpp b/tools/portable_fields.cpp index 8dc4958..13f62a5 100644 --- a/tools/portable_fields.cpp +++ b/tools/portable_fields.cpp @@ -383,6 +383,9 @@ core::Result ParseFieldType(std::string_view text) }; FieldType type; auto name = Trim(text); + if (name.empty()) { + return ResultType::FromStatus(core::Status::InvalidArgument("empty field type")); + } const auto bracket = name.find('['); if (bracket != std::string_view::npos) { if (name.back() != ']') { diff --git a/tools/puppet_master_topic.cpp b/tools/puppet_master_topic.cpp index 36a3690..56b001a 100644 --- a/tools/puppet_master_topic.cpp +++ b/tools/puppet_master_topic.cpp @@ -49,6 +49,8 @@ #include #include #include + +#include "portable_fields.h" #ifdef PUPPETMASTER_TOPIC_WITH_FASTDDS #include #endif @@ -112,13 +114,18 @@ int Usage(std::ostream& out) << " info the topics, message counts, and length of a recording\n" << " puppet_master_topic service list --system FILE [--domain N] [--timeout-ms N]\n" << " puppet_master_topic service call --system FILE [--domain N]\n" - << " [--data TEXT | --hex HEX] [--timeout-ms N]\n" + << " [--data TEXT | --hex HEX | --field TYPE:VALUE...]\n" + << " [--reply-fields TYPE,...] [--timeout-ms N]\n" << " [--bytes N] [--text]\n" << " service list the system's services, who serves and calls them, and whether a\n" << " server is up, from its heartbeats; listens --timeout-ms (default:\n" << " three heartbeat intervals, at least 1 s on FastDDS)\n" << " service call send one request, TEXT's bytes, HEX's (\"68 69\"), or none, and print\n" << " the reply; fails with the call's status (--timeout-ms, default 2000)\n" + << " --field T:V service call: a request field in PortableCodec's wire order, repeated;\n" + << " T is bool, i8-i64, u8-u64, f32, f64, or string, with [] for a\n" + << " vector or [N] for an array (elements separated by commas)\n" + << " --reply-fields service call: decode the reply as these types, one per field\n" << "Ctrl+C stops echo, hz, record, and replay.\n"; return 2; } @@ -134,6 +141,8 @@ struct Arguments { milliseconds timeout {0}; bool timeout_set {false}; transport::ByteBuffer data; // service call: the request + bool typed_request {false}; // service call: data came from --field + std::vector reply_fields; // service call: --reply-fields milliseconds window {1000}; milliseconds duration {0}; std::uint64_t bytes {32}; @@ -250,9 +259,49 @@ int Parse(int argc, char** argv, Arguments& args) args.bytes_set = true; } else if (argument == "--text" && (echo || call)) { args.text = true; + } else if (argument == "--field" && call && has_value) { + if (has_data && !args.typed_request) { + std::cerr << "give --data, --hex, or --field, not several\n"; + return 2; + } + has_data = true; + args.typed_request = true; + const std::string value = argv[++index]; + const auto colon = value.find(':'); + auto type = puppet_master::tools::ParseFieldType( + colon == std::string::npos ? std::string_view(value) : std::string_view(value).substr(0, colon)); + if (colon == std::string::npos || !type.ok()) { + std::cerr << "--field needs TYPE:VALUE" + << (type.ok() ? std::string() : "; " + type.status().message()) << '\n'; + return 2; + } + auto status = puppet_master::tools::EncodeField( + type.value(), std::string_view(value).substr(colon + 1), args.data); + if (!status.ok()) { + std::cerr << "--field " << value << ": " << status.message() << '\n'; + return 2; + } + } else if (argument == "--reply-fields" && call && has_value) { + const std::string value = argv[++index]; + std::size_t start = 0; + while (true) { + const auto comma = value.find(',', start); + const auto part = + value.substr(start, comma == std::string::npos ? std::string::npos : comma - start); + auto type = puppet_master::tools::ParseFieldType(part); + if (!type.ok()) { + std::cerr << "--reply-fields: " << type.status().message() << '\n'; + return 2; + } + args.reply_fields.push_back(type.value()); + if (comma == std::string::npos) { + break; + } + start = comma + 1; + } } else if ((argument == "--data" || argument == "--hex") && call && has_value) { if (has_data) { - std::cerr << "give --data or --hex once\n"; + std::cerr << "give --data, --hex, or --field, not several\n"; return 2; } has_data = true; @@ -1737,8 +1786,25 @@ int ServiceCall(const Arguments& args) std::cout << "reply " << reply.value().size() << " B in " << std::fixed << std::setprecision(1) << Microseconds(std::chrono::duration_cast(took)) / 1000.0 << " ms"; std::cout.unsetf(std::ios::floatfield); - PrintPayload(reply.value(), args); + if (args.reply_fields.empty()) { + PrintPayload(reply.value(), args); + std::cout << std::endl; + return 0; + } std::cout << std::endl; + auto fields = puppet_master::tools::DecodeFields(args.reply_fields, transport::ByteView(reply.value())); + if (!fields.ok()) { + // The reply arrived; show its bytes so the field list can be fixed. + std::cerr << "reply " << info.spec.reply.ToString() << ": " << fields.status().ToString() << '\n'; + PrintPayload(reply.value(), args); + std::cout << std::endl; + return 1; + } + for (std::size_t index = 0; index < fields.value().size(); ++index) { + std::cout << " " << index + 1 << " " << puppet_master::tools::ToString(args.reply_fields[index]) << ": " + << fields.value()[index] << '\n'; + } + std::cout << std::flush; return 0; } From e91533df688e9d4d5aee2ed12d86738ac910702e Mon Sep 17 00:00:00 2001 From: SoleyRan Date: Thu, 5 Nov 2026 11:28:43 +0800 Subject: [PATCH 5/6] ci: key the FastDDS cache on the OS release and system libraries The FastDDS jobs failed with "libtinyxml2.so.10: cannot open shared object file": ubuntu-latest moved to a newer Ubuntu, but the cache key used runner.os, which stays "Linux", so a FastDDS built on Ubuntu 24.04 was restored onto a runner with another tinyxml2. Every test linking FastDDS failed to load, including topic_tool through puppet_master_topic. The key now includes the OS ID and version and a hash of the installed libtinyxml2-dev and libssl-dev versions, so a changed image rebuilds FastDDS instead of restoring a build that cannot load. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a2d7a3d..8920129 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -186,12 +186,24 @@ jobs: sudo apt-get update sudo apt-get install -y libasio-dev libtinyxml2-dev libssl-dev ninja-build nlohmann-json3-dev + # FastDDS links the system's tinyxml2 and OpenSSL, so a cached build + # only works on the same OS release with the same library versions. + # runner.os alone stays "Linux" when ubuntu-latest moves to a newer + # Ubuntu, which once restored a build whose libtinyxml2 was gone. + - name: Fingerprint system libraries + id: system + run: | + . /etc/os-release + libs=$(dpkg-query -W -f='${Package}=${Version} ' libtinyxml2-dev libssl-dev) + echo "$ID $VERSION_ID: $libs" + echo "key=$ID-$VERSION_ID-$(echo "$libs" | sha256sum | cut -c1-12)" >> "$GITHUB_OUTPUT" + - name: Cache FastDDS id: cache-deps uses: actions/cache@v4 with: path: ${{ env.DEPS_PREFIX }} - key: fastdds-${{ runner.os }}-${{ matrix.fastdds }}-${{ matrix.fastcdr }}-v1 + key: fastdds-${{ steps.system.outputs.key }}-${{ matrix.fastdds }}-${{ matrix.fastcdr }}-v1 - name: Build FastDDS from source if: steps.cache-deps.outputs.cache-hit != 'true' From e55a069328f077a078c8a79ecc313f0404843a15 Mon Sep 17 00:00:00 2001 From: SoleyRan Date: Thu, 5 Nov 2026 11:44:35 +0800 Subject: [PATCH 6/6] ci: run the FastDDS jobs on ubuntu-24.04 ubuntu-latest moved past Ubuntu 24.04 and now ships GCC 15, which cannot build FastDDS 2.14.4: its DDSSQLFilter headers use uint8_t and uint64_t without including , which GCC 15's standard headers no longer pull in. With the cache key now tied to the OS release, the job rebuilt FastDDS from source and failed there. Pin the FastDDS jobs to ubuntu-24.04, where both FastDDS versions in the matrix build and pass, and rename them to match. The other jobs stay on ubuntu-latest, where PuppetMaster itself builds with GCC 15. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 8920129..abb53f9 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -165,9 +165,12 @@ jobs: timeout 300s "$integration/check_version_skew.sh" "$GITHUB_WORKSPACE/json-install" \ "$GITHUB_WORKSPACE/skew" "$config_tool" + # Pinned: FastDDS 2.14 does not build with GCC 15 (its headers use + # uint8_t without ), which ubuntu-latest ships since it moved + # past Ubuntu 24.04. fastdds: - name: ubuntu-latest (FastDDS ${{ matrix.fastdds }}) - runs-on: ubuntu-latest + name: ubuntu-24.04 (FastDDS ${{ matrix.fastdds }}) + runs-on: ubuntu-24.04 strategy: fail-fast: false matrix: