diff --git a/README.md b/README.md index 742459c..3389383 100644 --- a/README.md +++ b/README.md @@ -24,6 +24,7 @@ The main usage of `capabilities2` will typically involve creating or customizing | [Interfaces](./docs/interfaces.md) | The main capability specification file | | [Providers](./docs/providers.md) | The capability provider specification file provides a mechanism to operate the capability | | [Semantic Interfaces](./docs/semantic_interfaces.md) | The semantic interface specification file provides a mechanism to redefine a capability with semantic information | +| [Semantic Providers](./docs/semantic_provider.md) | The semantic provider specification file provides a mechanism to redefine a capability provider with semantic information | Runners can be created using the runner API parent classes [here](./capabilities2_runner/readme.md). The capabilities service can be started using the [capabilities2_server](./capabilities2_server/readme.md) package. @@ -50,6 +51,7 @@ ros2 launch capabilities2_server capabilities2_server.launch.py - [Registering a capability](./capabilities2_server/docs/register.md) - [Terminal based capability usage](./capabilities2_server/docs/terminal_usage.md) - [Running test scripts](./docs/run_test_scripts.md) +- [Runnable Information](./docs/runnable.md) ### Docs diff --git a/capabilities2_events/CMakeLists.txt b/capabilities2_events/CMakeLists.txt index fb5ead3..5687dcf 100644 --- a/capabilities2_events/CMakeLists.txt +++ b/capabilities2_events/CMakeLists.txt @@ -12,6 +12,7 @@ endif() # find dependencies find_package(ament_cmake REQUIRED) +find_package(ament_cmake_gtest REQUIRED) find_package(rclcpp REQUIRED) find_package(capabilities2_msgs REQUIRED) @@ -47,6 +48,20 @@ install(TARGETS ${PROJECT_NAME} RUNTIME DESTINATION bin ) +if(BUILD_TESTING) + ament_add_gtest(published_event_test + test/published_event_test.cpp + ) + if(TARGET published_event_test) + target_include_directories(published_event_test PUBLIC include) + target_link_libraries(published_event_test ${PROJECT_NAME}) + ament_target_dependencies(published_event_test + rclcpp + capabilities2_msgs + ) + endif() +endif() + ament_export_include_directories(include) ament_export_dependencies(rclcpp capabilities2_msgs) ament_export_libraries(${PROJECT_NAME}) diff --git a/capabilities2_events/include/capabilities2_events/event_base.hpp b/capabilities2_events/include/capabilities2_events/event_base.hpp index 3c2340e..47809f4 100644 --- a/capabilities2_events/include/capabilities2_events/event_base.hpp +++ b/capabilities2_events/include/capabilities2_events/event_base.hpp @@ -46,7 +46,8 @@ class EventBase typedef capabilities2_events::EventParameters parameter_t; typedef std::string access_id_t; typedef std::string target_instance_id_t; - typedef std::function event_callback_t; + typedef std::function + event_callback_t; public: EventBase() @@ -62,13 +63,14 @@ class EventBase * which lets loosely-coupled capabilities propogate state changes * when a source capability emits an event to a target capability * - * @param connection_id connection identifier (format: "bond_id/trigger_id") + * @param connection_id connection identifier (format: "bond_id/instance_id/target_instance_id") + * @param ownership_id ownership identifier for the connection (used for access control) * @param event_code type of event being emitted * @param source source capability emitting the event * @param target target capability receiving the event * @param callback function to trigger target capability with (capability, parameters, bond_id, target_instance_id) */ - virtual void emit(const std::string& connection_id, const uint8_t& event_code, + virtual void emit(const std::string& connection_id, const std::string& ownership_id, const uint8_t& event_code, const capabilities2_msgs::msg::Capability& source, const capabilities2_msgs::msg::Capability& target, event_callback_t callback) { @@ -84,6 +86,22 @@ class EventBase } } + /** + * @brief Publish an observed event for monitoring/telemetry even when no callback is triggered. + * + * This is used so external observers can see lifecycle events such as STARTED and STOPPED + * even when the plan does not define a matching event connection. + */ + virtual void publish_observed_event(const std::string& ownership_id, const uint8_t& event_code, + const capabilities2_msgs::msg::Capability& source, + const std::string& instance_id) + { + (void)ownership_id; + (void)event_code; + (void)source; + (void)instance_id; + } + /** * @brief on server ready event * diff --git a/capabilities2_events/include/capabilities2_events/event_node.hpp b/capabilities2_events/include/capabilities2_events/event_node.hpp index c18226e..f9dd3e7 100644 --- a/capabilities2_events/include/capabilities2_events/event_node.hpp +++ b/capabilities2_events/include/capabilities2_events/event_node.hpp @@ -40,6 +40,9 @@ class EventNode // connection target capabilities2_msgs::msg::Capability target; + // connection ownership id + std::string ownership_id; + // event callback with signature: (capability, parameters, bond_id) EventBase::event_callback_t callback; }; @@ -72,6 +75,26 @@ class EventNode return; } + std::string ownership_id_for_observation; + + for (const auto& [conn_id, connection] : connections_) + { + size_t first_pos = conn_id.find('/'); + size_t second_pos = conn_id.find('/', first_pos + 1); + + std::string conn_bond_id = (first_pos != std::string::npos) ? conn_id.substr(0, first_pos) : conn_id; + std::string conn_instance_id = + (second_pos != std::string::npos) ? conn_id.substr(first_pos + 1, second_pos - first_pos - 1) : ""; + + if (bond_id == conn_bond_id && instance_id == conn_instance_id) + { + ownership_id_for_observation = connection.ownership_id; + break; + } + } + + event_emitter_->publish_observed_event(ownership_id_for_observation, event_type, source_, instance_id); + // check each connection for (const auto& [conn_id, connection] : connections_) { @@ -109,7 +132,8 @@ class EventNode // modifying execution of other nodes is not owned by this class // this lets the execution flow be made thread-safe // in the scope where the thread is owned - event_emitter_->emit(conn_id, event_type, source_, target_with_params, connection.callback); + event_emitter_->emit(conn_id, connection.ownership_id, event_type, source_, target_with_params, + connection.callback); } } } @@ -147,11 +171,13 @@ class EventNode * @param connection_id unique identifier for the connection (format: "bond_id/trigger_id") * @param type type of event to connect to * @param target target capability to connect to + * @param ownership_id ownership id of the connection (used for access control) * @param event_cb callback to trigger target capability with (capability, parameters, bond_id, target_instance_id) * * @throws event_exception if connection with given id already exists */ - void add_connection(const std::string& connection_id, const capabilities2_msgs::msg::CapabilityEventCode& type, + void add_connection(const std::string& connection_id, const std::string& ownership_id, + const capabilities2_msgs::msg::CapabilityEventCode& type, const capabilities2_msgs::msg::Capability& target, EventBase::event_callback_t event_cb) { // validate connection id @@ -164,6 +190,7 @@ class EventNode EventPipe conn; conn.type = type; conn.target = target; + conn.ownership_id = ownership_id; conn.callback = event_cb; // add connection @@ -224,6 +251,7 @@ class EventNode c.type = connection.type; c.source = source_; c.target = connection.target; + c.ownership_id = connection.ownership_id; conns.push_back(c); } diff --git a/capabilities2_events/include/capabilities2_events/published_event.hpp b/capabilities2_events/include/capabilities2_events/published_event.hpp index 436c864..f86e13a 100644 --- a/capabilities2_events/include/capabilities2_events/published_event.hpp +++ b/capabilities2_events/include/capabilities2_events/published_event.hpp @@ -1,5 +1,10 @@ #pragma once +#include +#include +#include +#include + #include #include @@ -11,17 +16,35 @@ namespace capabilities2_events class PublishedEvent : public EventBase { public: - PublishedEvent(rclcpp::Publisher::SharedPtr event_pub) - : EventBase(), event_pub_(event_pub) + struct SnapshotResult + { + rclcpp::Time stamp; + uint64_t oldest_sequence{ 0 }; + uint64_t latest_sequence{ 0 }; + uint32_t max_events{ 0 }; + bool truncated{ false }; + std::vector events; + }; + + PublishedEvent(rclcpp::Publisher::SharedPtr event_pub, + size_t max_history_size = 100) + : EventBase(), event_pub_(event_pub), max_history_size_(max_history_size) { } ~PublishedEvent() = default; /** - * @brief see EventBase::emit, specialised to publish events + * @brief pverrides EventBase::emit to publish the event to a ROS2 topic + * + * @param connection_id connection identifier (format: "bond_id/instance_id/target_instance_id") + * @param ownership_id ownership identifier for the connection (used for access control) + * @param event_code type of event being emitted + * @param source source capability emitting the event + * @param target target capability receiving the event + * @param callback function to trigger target capability with (capability, parameters, bond_id, target_instance_id) */ - void emit(const std::string& connection_id, const uint8_t& event_code, + void emit(const std::string& connection_id, const std::string& ownership_id, const uint8_t& event_code, const capabilities2_msgs::msg::Capability& source, const capabilities2_msgs::msg::Capability& target, EventBase::event_callback_t callback) override { @@ -29,7 +52,8 @@ class PublishedEvent : public EventBase size_t first_pos = connection_id.find('/'); size_t second_pos = connection_id.find('/', first_pos + 1); - std::string instance_id = (second_pos != std::string::npos) ? connection_id.substr(first_pos + 1, second_pos - first_pos - 1) : ""; + std::string instance_id = + (second_pos != std::string::npos) ? connection_id.substr(first_pos + 1, second_pos - first_pos - 1) : ""; capabilities2_msgs::msg::CapabilityEventStamped event_msg; event_msg.header.stamp = rclcpp::Clock().now(); @@ -37,12 +61,26 @@ class PublishedEvent : public EventBase event_msg.event.code.code = event_code; event_msg.event.connection.source = source; event_msg.event.connection.target = target; + event_msg.event.connection.ownership_id = ownership_id; - // publish event - event_pub_->publish(event_msg); + publish_event(event_msg); // call super - EventBase::emit(connection_id, event_code, source, target, callback); + EventBase::emit(connection_id, ownership_id, event_code, source, target, callback); + } + + void publish_observed_event(const std::string& ownership_id, const uint8_t& event_code, + const capabilities2_msgs::msg::Capability& source, + const std::string& instance_id) override + { + capabilities2_msgs::msg::CapabilityEventStamped event_msg; + event_msg.header.stamp = rclcpp::Clock().now(); + event_msg.event.trigger_id = instance_id; + event_msg.event.code.code = event_code; + event_msg.event.connection.source = source; + event_msg.event.connection.ownership_id = ownership_id; + + publish_event(event_msg); } /** @@ -56,10 +94,11 @@ class PublishedEvent : public EventBase event_msg.header.stamp = rclcpp::Clock().now(); event_msg.event.connection.source.capability = "capabilities2_server"; event_msg.event.connection.source.provider = "capabilities2_server"; + event_msg.event.connection.ownership_id = ""; event_msg.event.code.code = capabilities2_msgs::msg::CapabilityEventCode::SERVER_READY; event_msg.event.description = msg; - event_pub_->publish(event_msg); + publish_event(event_msg); } /** @@ -73,10 +112,11 @@ class PublishedEvent : public EventBase event_msg.header.stamp = rclcpp::Clock().now(); event_msg.event.connection.source.capability = "capabilities2_server"; event_msg.event.connection.source.provider = "capabilities2_server"; + event_msg.event.connection.ownership_id = ""; event_msg.event.code.code = capabilities2_msgs::msg::CapabilityEventCode::LAUNCHED; event_msg.event.description = "Process launched with PID: " + pid; - event_pub_->publish(event_msg); + publish_event(event_msg); } /** @@ -90,10 +130,11 @@ class PublishedEvent : public EventBase event_msg.header.stamp = rclcpp::Clock().now(); event_msg.event.connection.source.capability = "capabilities2_server"; event_msg.event.connection.source.provider = "capabilities2_server"; + event_msg.event.connection.ownership_id = ""; event_msg.event.code.code = capabilities2_msgs::msg::CapabilityEventCode::TERMINATED; event_msg.event.description = "Process terminated with PID: " + pid; - event_pub_->publish(event_msg); + publish_event(event_msg); } void on_triggered(const std::string& trigger_id) @@ -102,10 +143,11 @@ class PublishedEvent : public EventBase event_msg.header.stamp = rclcpp::Clock().now(); event_msg.event.connection.source.capability = "capabilities2_server"; event_msg.event.connection.source.provider = "capabilities2_server"; + event_msg.event.connection.ownership_id = ""; event_msg.event.code.code = capabilities2_msgs::msg::CapabilityEventCode::TRIGGERED; event_msg.event.description = "Triggered event with ID: " + trigger_id; - event_pub_->publish(event_msg); + publish_event(event_msg); } void on_connected(const std::string& source, const std::string& target) @@ -114,10 +156,11 @@ class PublishedEvent : public EventBase event_msg.header.stamp = rclcpp::Clock().now(); event_msg.event.connection.source.capability = "capabilities2_server"; event_msg.event.connection.source.provider = "capabilities2_server"; + event_msg.event.connection.ownership_id = ""; event_msg.event.code.code = capabilities2_msgs::msg::CapabilityEventCode::CONNECTED; event_msg.event.description = "Connected event from " + source + " to " + target; - event_pub_->publish(event_msg); + publish_event(event_msg); } void on_disconnected(const std::string& source, const std::string& target) @@ -126,15 +169,87 @@ class PublishedEvent : public EventBase event_msg.header.stamp = rclcpp::Clock().now(); event_msg.event.connection.source.capability = "capabilities2_server"; event_msg.event.connection.source.provider = "capabilities2_server"; + event_msg.event.connection.ownership_id = ""; event_msg.event.code.code = capabilities2_msgs::msg::CapabilityEventCode::DISCONNECTED; event_msg.event.description = "Disconnected event from " + source + " to " + target; - event_pub_->publish(event_msg); + publish_event(event_msg); + } + + SnapshotResult get_event_snapshot(uint64_t after_sequence, size_t requested_max_events) const + { + SnapshotResult snapshot; + snapshot.max_events = static_cast(max_history_size_); + + std::lock_guard lock(history_mutex_); + + if (event_history_.empty()) + { + snapshot.stamp = rclcpp::Clock().now(); + return snapshot; + } + + snapshot.stamp = event_history_.back().event.header.stamp; + snapshot.oldest_sequence = event_history_.front().sequence; + snapshot.latest_sequence = event_history_.back().sequence; + + const size_t bounded_request_count = requested_max_events > 0 + ? std::min(requested_max_events, max_history_size_) + : max_history_size_; + + snapshot.truncated = after_sequence > 0 && after_sequence + 1 < snapshot.oldest_sequence; + + for (const auto& stored_event : event_history_) + { + if (stored_event.sequence <= after_sequence) + { + continue; + } + + snapshot.events.push_back(stored_event.event); + if (snapshot.events.size() >= bounded_request_count) + { + break; + } + } + + return snapshot; } private: + struct SequencedEvent + { + uint64_t sequence{ 0 }; + capabilities2_msgs::msg::CapabilityEventStamped event; + }; + + void publish_event(const capabilities2_msgs::msg::CapabilityEventStamped& event_msg) + { + if (event_pub_) + { + event_pub_->publish(event_msg); + } + + SequencedEvent stored_event; + + { + std::lock_guard lock(history_mutex_); + stored_event.sequence = next_sequence_++; + stored_event.event = event_msg; + event_history_.push_back(stored_event); + while (event_history_.size() > max_history_size_) + { + event_history_.pop_front(); + } + } + } + // event publisher rclcpp::Publisher::SharedPtr event_pub_; + std::deque event_history_; + mutable std::mutex history_mutex_; + uint64_t next_sequence_{ 1 }; + size_t max_history_size_; }; } // namespace capabilities2_events diff --git a/capabilities2_events/package.xml b/capabilities2_events/package.xml index 0edb36e..ba0469f 100644 --- a/capabilities2_events/package.xml +++ b/capabilities2_events/package.xml @@ -22,6 +22,8 @@ capabilities2_msgs uuid + ament_cmake_gtest + ament_cmake diff --git a/capabilities2_events/test/published_event_test.cpp b/capabilities2_events/test/published_event_test.cpp new file mode 100644 index 0000000..4b49070 --- /dev/null +++ b/capabilities2_events/test/published_event_test.cpp @@ -0,0 +1,63 @@ +#include + +#include + +namespace +{ + +capabilities2_msgs::msg::Capability makeCapability(const std::string& capability, + const std::string& provider, + const std::string& instance_id = "") +{ + capabilities2_msgs::msg::Capability value; + value.capability = capability; + value.provider = provider; + value.instance_id = instance_id; + return value; +} + +} // namespace + +TEST(PublishedEventTest, ReturnsOnlyNewEventsDuringNormalPolling) +{ + capabilities2_events::PublishedEvent publisher({}, 5); + const auto source = makeCapability("nav/MoveBase", "move_base_provider", "instance-1"); + + publisher.publish_observed_event("plan-1", capabilities2_msgs::msg::CapabilityEventCode::TRIGGERED, source, "instance-1"); + publisher.publish_observed_event("plan-1", capabilities2_msgs::msg::CapabilityEventCode::SUCCEEDED, source, "instance-1"); + + const auto initial_snapshot = publisher.get_event_snapshot(0, 10); + ASSERT_EQ(initial_snapshot.events.size(), 2U); + EXPECT_EQ(initial_snapshot.oldest_sequence, 1U); + EXPECT_EQ(initial_snapshot.latest_sequence, 2U); + EXPECT_FALSE(initial_snapshot.truncated); + EXPECT_EQ(initial_snapshot.events.front().event.code.code, capabilities2_msgs::msg::CapabilityEventCode::TRIGGERED); + EXPECT_EQ(initial_snapshot.events.back().event.code.code, capabilities2_msgs::msg::CapabilityEventCode::SUCCEEDED); + + const auto delta_snapshot = publisher.get_event_snapshot(1, 10); + ASSERT_EQ(delta_snapshot.events.size(), 1U); + EXPECT_EQ(delta_snapshot.oldest_sequence, 1U); + EXPECT_EQ(delta_snapshot.latest_sequence, 2U); + EXPECT_FALSE(delta_snapshot.truncated); + EXPECT_EQ(delta_snapshot.events.front().event.code.code, capabilities2_msgs::msg::CapabilityEventCode::SUCCEEDED); +} + +TEST(PublishedEventTest, ReportsTruncationWhenCallerFallsBehindRingBuffer) +{ + capabilities2_events::PublishedEvent publisher({}, 3); + const auto source = makeCapability("nav/MoveBase", "move_base_provider", "instance-1"); + + publisher.publish_observed_event("plan-1", capabilities2_msgs::msg::CapabilityEventCode::TRIGGERED, source, "instance-1"); + publisher.publish_observed_event("plan-1", capabilities2_msgs::msg::CapabilityEventCode::STARTED, source, "instance-1"); + publisher.publish_observed_event("plan-1", capabilities2_msgs::msg::CapabilityEventCode::CONNECTED, source, "instance-1"); + publisher.publish_observed_event("plan-1", capabilities2_msgs::msg::CapabilityEventCode::SUCCEEDED, source, "instance-1"); + publisher.publish_observed_event("plan-1", capabilities2_msgs::msg::CapabilityEventCode::STOPPED, source, "instance-1"); + + const auto snapshot = publisher.get_event_snapshot(1, 10); + ASSERT_EQ(snapshot.events.size(), 3U); + EXPECT_EQ(snapshot.oldest_sequence, 3U); + EXPECT_EQ(snapshot.latest_sequence, 5U); + EXPECT_TRUE(snapshot.truncated); + EXPECT_EQ(snapshot.events.front().event.code.code, capabilities2_msgs::msg::CapabilityEventCode::CONNECTED); + EXPECT_EQ(snapshot.events.back().event.code.code, capabilities2_msgs::msg::CapabilityEventCode::STOPPED); +} \ No newline at end of file diff --git a/capabilities2_msgs/CMakeLists.txt b/capabilities2_msgs/CMakeLists.txt index 3be2079..a1e728d 100644 --- a/capabilities2_msgs/CMakeLists.txt +++ b/capabilities2_msgs/CMakeLists.txt @@ -24,6 +24,7 @@ set(msg_files "msg/CapabilityEventStamped.msg" "msg/CapabilityResponse.msg" "msg/CapabilitySpec.msg" + "msg/RunnableSpec.msg" "msg/NaturalCapability.msg" "msg/Remapping.msg" "msg/RunningCapability.msg" @@ -34,8 +35,10 @@ set(srv_files "srv/ConnectCapability.srv" "srv/EstablishBond.srv" "srv/FreeCapability.srv" + "srv/GetEventSnapshot.srv" "srv/GetCapabilitySpec.srv" "srv/GetCapabilitySpecs.srv" + "srv/GetRunnableSpecs.srv" "srv/GetInterfaces.srv" "srv/GetProviders.srv" "srv/GetRemappings.srv" diff --git a/capabilities2_msgs/msg/CapabilityConnection.msg b/capabilities2_msgs/msg/CapabilityConnection.msg index 11ca06f..e387810 100644 --- a/capabilities2_msgs/msg/CapabilityConnection.msg +++ b/capabilities2_msgs/msg/CapabilityConnection.msg @@ -9,3 +9,6 @@ capabilities2_msgs/Capability source # capability targeted by this connection capabilities2_msgs/Capability target + +# Capability event ownership +string ownership_id \ No newline at end of file diff --git a/capabilities2_msgs/msg/CapabilityEvent.msg b/capabilities2_msgs/msg/CapabilityEvent.msg index 9501444..825f924 100644 --- a/capabilities2_msgs/msg/CapabilityEvent.msg +++ b/capabilities2_msgs/msg/CapabilityEvent.msg @@ -1,6 +1,6 @@ # the capability event message -# identifying name for the source that triggered this event +# id for the instance that triggered this event string trigger_id # event can pass over a connection diff --git a/capabilities2_msgs/msg/CapabilityEventCode.msg b/capabilities2_msgs/msg/CapabilityEventCode.msg index e8fb533..1c57a46 100644 --- a/capabilities2_msgs/msg/CapabilityEventCode.msg +++ b/capabilities2_msgs/msg/CapabilityEventCode.msg @@ -1,20 +1,23 @@ # available events uint8 IDLE=0 # state and general + # runner state events uint8 STARTED=1 # on_started uint8 STOPPED=2 # on_stopped uint8 FAILED=3 # on_failure uint8 SUCCEEDED=4 # on_success + # runner configuration events uint8 CONNECTED=5 uint8 DISCONNECTED=6 uint8 TRIGGERED=7 + # system events uint8 SERVER_READY=8 # server ready uint8 LAUNCHED=9 # process launched uint8 TERMINATED=10 # process terminated - uint8 ERROR=18 # defineable error event + # something out of scope went wrong code uint8 UNDEFINED=19 diff --git a/capabilities2_msgs/msg/RunnableSpec.msg b/capabilities2_msgs/msg/RunnableSpec.msg new file mode 100644 index 0000000..e122c2b --- /dev/null +++ b/capabilities2_msgs/msg/RunnableSpec.msg @@ -0,0 +1,2 @@ +# Raw string content of the spec file +string spec \ No newline at end of file diff --git a/capabilities2_msgs/msg/RunningCapability.msg b/capabilities2_msgs/msg/RunningCapability.msg index d2caadc..f44d36a 100644 --- a/capabilities2_msgs/msg/RunningCapability.msg +++ b/capabilities2_msgs/msg/RunningCapability.msg @@ -1,8 +1,11 @@ # Name and provider of this running capability Capability capability + # Capabilities which depend on this one Capability[] dependent_capabilities + # Message stating what started this capability string started_by + # Process ID of the running provider int32 pid diff --git a/capabilities2_msgs/srv/GetEventSnapshot.srv b/capabilities2_msgs/srv/GetEventSnapshot.srv new file mode 100644 index 0000000..660e95f --- /dev/null +++ b/capabilities2_msgs/srv/GetEventSnapshot.srv @@ -0,0 +1,9 @@ +uint64 after_sequence +uint32 max_events +--- +std_msgs/Header header +uint64 oldest_sequence +uint64 latest_sequence +uint32 max_events +bool truncated +capabilities2_msgs/CapabilityEventStamped[] events \ No newline at end of file diff --git a/capabilities2_msgs/srv/GetRunnableSpecs.srv b/capabilities2_msgs/srv/GetRunnableSpecs.srv new file mode 100644 index 0000000..1ef4753 --- /dev/null +++ b/capabilities2_msgs/srv/GetRunnableSpecs.srv @@ -0,0 +1,4 @@ + +--- +string[] index_of_specs +RunnableSpec[] runnable_specs \ No newline at end of file diff --git a/capabilities2_runner/include/capabilities2_runner/action_runner.hpp b/capabilities2_runner/include/capabilities2_runner/action_runner.hpp index 61f7b8c..0b4e99f 100644 --- a/capabilities2_runner/include/capabilities2_runner/action_runner.hpp +++ b/capabilities2_runner/include/capabilities2_runner/action_runner.hpp @@ -39,26 +39,42 @@ class ActionRunner : public ThreadTriggerRunner * * @param node shared pointer to the capabilities node. Allows to use ros node related functionalities * @param run_config runner configuration loaded from the yaml file - * @param action_name action name used in the yaml file, used to load specific configuration from the run_config + * @param action_name fallback action name used when no matching action resource is available in the run config + * @param action_type action message type used to resolve the remapped action name from the run config */ - virtual void init_action(rclcpp::Node::SharedPtr node, const runner_opts& run_config, const std::string& action_name) + virtual void init_action(rclcpp::Node::SharedPtr node, const runner_opts& run_config, const std::string& action_name, + const std::string& action_type) { // initialize the runner base by storing node pointer and run config init_base(node, run_config); + std::string resolved_action_name = action_name; + try + { + resolved_action_name = get_action_name_by_type(action_type); + RCLCPP_INFO(node_->get_logger(), "resolved action name: %s for type: %s", resolved_action_name.c_str(), + action_type.c_str()); + } + catch (const runner_exception&) + { + // Fall back to the explicit action name for runners that are not backed by interface resources. + RCLCPP_ERROR(node_->get_logger(), "failed to resolve action name for type: %s. using fallback action name: %s", + action_type.c_str(), resolved_action_name.c_str()); + } + // create an action client - action_client_ = rclcpp_action::create_client(node_, action_name); + action_client_ = rclcpp_action::create_client(node_, resolved_action_name); // wait for action server - RCLCPP_INFO(node_->get_logger(), "waiting for action: %s", action_name.c_str()); + RCLCPP_INFO(node_->get_logger(), "waiting for action: %s", resolved_action_name.c_str()); if (!action_client_->wait_for_action_server(std::chrono::seconds(1000))) { - RCLCPP_ERROR(node_->get_logger(), "failed to connect to action: %s", action_name.c_str()); + RCLCPP_ERROR(node_->get_logger(), "failed to connect to action: %s", resolved_action_name.c_str()); throw runner_exception("failed to connect to action server"); } - RCLCPP_INFO(node_->get_logger(), "connected with action: %s", action_name.c_str()); + RCLCPP_INFO(node_->get_logger(), "connected with action: %s", resolved_action_name.c_str()); } /** @@ -155,21 +171,26 @@ class ActionRunner : public ThreadTriggerRunner goal_handle_ = goal_handle; }; - send_goal_options_.feedback_callback = [this, &instance_id]( - typename rclcpp_action::ClientGoalHandle::SharedPtr goal_handle, - const typename ActionT::Feedback::ConstSharedPtr feedback_msg) { - std::string feedback = generate_feedback(feedback_msg); + send_goal_options_.feedback_callback = + [this, &instance_id](typename rclcpp_action::ClientGoalHandle::SharedPtr goal_handle, + const typename ActionT::Feedback::ConstSharedPtr feedback_msg) { + std::string feedback = generate_feedback(feedback_msg); - if (feedback != "") - { - RCLCPP_INFO(node_->get_logger(), "received feedback: %s for instance %s", feedback.c_str(), instance_id.c_str()); - } - }; + if (feedback != "") + { + RCLCPP_INFO(node_->get_logger(), "received feedback: %s for instance %s", feedback.c_str(), + instance_id.c_str()); + } + }; send_goal_options_.result_callback = - [this, &instance_id, &completed, &cv, - &bond_id, &instance_id](const typename rclcpp_action::ClientGoalHandle::WrappedResult& wrapped_result) { + [this, &instance_id, &completed, &cv, &bond_id, + &instance_id](const typename rclcpp_action::ClientGoalHandle::WrappedResult& wrapped_result) { RCLCPP_INFO(node_->get_logger(), "received result for instance %s", instance_id.c_str()); + + result_ = wrapped_result.result; + process_result(result_); + if (wrapped_result.code == rclcpp_action::ResultCode::SUCCEEDED) { RCLCPP_INFO(node_->get_logger(), "action succeeded for instance %s", instance_id.c_str()); @@ -178,13 +199,21 @@ class ActionRunner : public ThreadTriggerRunner } else { - RCLCPP_ERROR(node_->get_logger(), "action failed for instance %s", instance_id.c_str()); + const std::string diagnostic = result_diagnostic(); + if (diagnostic.empty()) + { + RCLCPP_ERROR(node_->get_logger(), "action failed for instance %s", instance_id.c_str()); + } + else + { + RCLCPP_ERROR( + node_->get_logger(), "action failed for instance %s: %s", instance_id.c_str(), diagnostic.c_str()); + } // emit failed event emit_failed(bond_id, instance_id, param_on_failure()); } - result_ = wrapped_result.result; completed = true; cv.notify_all(); }; @@ -223,6 +252,31 @@ class ActionRunner : public ThreadTriggerRunner */ virtual std::string generate_feedback(const typename ActionT::Feedback::ConstSharedPtr msg) = 0; + /** + * @brief Return a diagnostic string for logging action failures. + * + * Derived runners can override this to expose result-specific failure text. + * + * @return Human-readable failure detail. + */ + virtual std::string result_diagnostic() const + { + return ""; + } + + /** + * @brief Process the action result before success or failure events are emitted. + * + * Derived runners can override this hook for side effects such as logging or + * caching derived values. By the time this runs, result_ has already been stored, + * so param_on_success() and param_on_failure() can safely read it. + * + * @param result the received action result + */ + virtual void process_result(typename ActionT::Result::SharedPtr result) + { + } + protected: /**< action client */ typename rclcpp_action::Client::SharedPtr action_client_; @@ -234,9 +288,6 @@ class ActionRunner : public ThreadTriggerRunner /** goal handle parameter to capture goal response from goal_response_callback */ typename rclcpp_action::ClientGoalHandle::SharedPtr goal_handle_; - /** Wrapped Result */ - typename rclcpp_action::ClientGoalHandle::WrappedResult wrapped_result_; - /** Result */ typename ActionT::Result::SharedPtr result_; diff --git a/capabilities2_runner/include/capabilities2_runner/runner_base.hpp b/capabilities2_runner/include/capabilities2_runner/runner_base.hpp index 2aefd08..7e91b31 100644 --- a/capabilities2_runner/include/capabilities2_runner/runner_base.hpp +++ b/capabilities2_runner/include/capabilities2_runner/runner_base.hpp @@ -157,17 +157,19 @@ class RunnerBase : public capabilities2_events::EventNode * extract bond_id for access control * * @param connection_id unique identifier for the connection (format: "bond_id/trigger_id") + * @param ownership_id unique identifier for the ownership of the connection * @param type type of event to connect to * @param target target capability to connect to * @param callback callback to trigger target capability with (capability, parameters, bond_id) */ - void add_connection(const std::string& connection_id, const capabilities2_msgs::msg::CapabilityEventCode& type, + void add_connection(const std::string& connection_id, const std::string& ownership_id, + const capabilities2_msgs::msg::CapabilityEventCode& type, const capabilities2_msgs::msg::Capability& target, std::function callback) { - EventNode::add_connection(connection_id, type, target, callback); + EventNode::add_connection(connection_id, ownership_id, type, target, callback); } /** diff --git a/capabilities2_runner/include/capabilities2_runner/service_runner.hpp b/capabilities2_runner/include/capabilities2_runner/service_runner.hpp index 2a9e9c9..81d8a8c 100644 --- a/capabilities2_runner/include/capabilities2_runner/service_runner.hpp +++ b/capabilities2_runner/include/capabilities2_runner/service_runner.hpp @@ -28,27 +28,42 @@ class ServiceRunner : public ThreadTriggerRunner * * @param node shared pointer to the capabilities node. Allows to use ros node related functionalities * @param run_config runner configuration loaded from the yaml file - * @param service_name action name used in the yaml file, used to load specific configuration from the run_config + * @param service_name fallback service name used when no matching service resource is available in the run config + * @param service_type service message type used to resolve the remapped service name from the run config */ virtual void init_service(rclcpp::Node::SharedPtr node, const runner_opts& run_config, - const std::string& service_name) + const std::string& service_name, const std::string& service_type) { // initialize the runner base by storing node pointer and run config init_base(node, run_config); + std::string resolved_service_name = service_name; + try + { + resolved_service_name = get_service_name_by_type(service_type); + RCLCPP_INFO(node_->get_logger(), "resolved service name: %s for type: %s", resolved_service_name.c_str(), + service_type.c_str()); + } + catch (const runner_exception&) + { + // Fall back to the explicit service name for runners that are not backed by interface resources. + RCLCPP_ERROR(node_->get_logger(), "failed to resolve service name for type: %s. using fallback service name: %s", + service_type.c_str(), resolved_service_name.c_str()); + } + // create a service client - service_client_ = node_->create_client(service_name); + service_client_ = node_->create_client(resolved_service_name); // wait for service server - RCLCPP_INFO(node_->get_logger(), "waiting for service: %s", service_name.c_str()); + RCLCPP_INFO(node_->get_logger(), "waiting for service: %s", resolved_service_name.c_str()); if (!service_client_->wait_for_service(std::chrono::seconds(3))) { - RCLCPP_ERROR(node_->get_logger(), "failed to connect to service: %s", service_name.c_str()); + RCLCPP_ERROR(node_->get_logger(), "failed to connect to service: %s", resolved_service_name.c_str()); throw runner_exception("failed to connect to server"); } - RCLCPP_INFO(node_->get_logger(), "connected with service: %s", service_name.c_str()); + RCLCPP_INFO(node_->get_logger(), "connected with service: %s", resolved_service_name.c_str()); } /** @@ -100,8 +115,9 @@ class ServiceRunner : public ThreadTriggerRunner std::condition_variable cv; bool completed = false; - auto result_future = service_client_->async_send_request( - request_msg, [this, &instance_id, &completed, &bond_id, &cv](typename rclcpp::Client::SharedFuture future) { + auto result_future = + service_client_->async_send_request(request_msg, [this, &instance_id, &completed, &bond_id, + &cv](typename rclcpp::Client::SharedFuture future) { if (!future.valid()) { RCLCPP_ERROR(node_->get_logger(), "get result call failed"); @@ -116,8 +132,14 @@ class ServiceRunner : public ThreadTriggerRunner response_ = future.get(); process_response(response_); - // emit success event - emit_succeeded(bond_id, instance_id, param_on_success()); + if (response_is_success()) + { + emit_succeeded(bond_id, instance_id, param_on_success()); + } + else + { + emit_failed(bond_id, instance_id, param_on_failure()); + } } completed = true; @@ -138,7 +160,7 @@ class ServiceRunner : public ThreadTriggerRunner * * A pattern needs to be implemented in the derived class * - * @param parameters + * @param parameters * @return ServiceT::Request the generated request */ virtual typename ServiceT::Request generate_request(capabilities2_events::EventParameters& parameters) = 0; @@ -153,7 +175,22 @@ class ServiceRunner : public ThreadTriggerRunner * A pattern needs to be implemented in the derived class for processing the response and extracting data if needed, * currently does nothing. */ - virtual void process_response(typename ServiceT::Response::SharedPtr /*response*/) {} + virtual void process_response(typename ServiceT::Response::SharedPtr /*response*/) + { + } + + /** + * @brief Decide whether a completed service response should emit success or failure. + * + * Derived runners can override this to treat semantically invalid responses as failures + * even when the transport-level service call completed successfully. + * + * @return True when the response should emit an on_success event. + */ + virtual bool response_is_success() const + { + return true; + } typename rclcpp::Client::SharedPtr service_client_; typename ServiceT::Response::SharedPtr response_; diff --git a/capabilities2_runner/include/capabilities2_runner/system/get_capability_specs_runner.hpp b/capabilities2_runner/include/capabilities2_runner/system/get_capability_specs_runner.hpp deleted file mode 100644 index 29557d3..0000000 --- a/capabilities2_runner/include/capabilities2_runner/system/get_capability_specs_runner.hpp +++ /dev/null @@ -1,84 +0,0 @@ -#pragma once - -#include -#include - -namespace capabilities2_runner -{ - -/** - * @brief Executor runner class - * - * Class to run capabilities2 executor action based capability - * - */ -class GetCapabilitySpecsRunner : public ServiceRunner -{ -public: - GetCapabilitySpecsRunner() : ServiceRunner() - { - } - - /** - * @brief Starter function for starting the action runner - * - * @param node shared pointer to the capabilities node. Allows to use ros node related functionalities - * @param run_config runner configuration loaded from the yaml file - * @param bond_id unique identifier for the group of connections associated with this runner trigger event - */ - virtual void start(rclcpp::Node::SharedPtr node, const runner_opts& run_config, const std::string& bond_id) override - { - init_service(node, run_config, "/capabilities/get_capability_specs"); - - // emit start event - emit_started(bond_id, "", param_on_started()); - } - -protected: - /** - * @brief This generate goal function overrides the generate_goal() function from ActionRunner() - * @param parameters XMLElement that contains parameters in the format - '' - * @return ActionT::Goal the generated goal - */ - virtual capabilities2_msgs::srv::GetCapabilitySpecs::Request - generate_request(capabilities2_events::EventParameters& parameters) override - { - capabilities2_msgs::srv::GetCapabilitySpecs::Request request; - return request; - } - - /** - * @brief This function overrides the param_on_success() function from RunnerBase to provide specific implementation for the GetCapabilitySpecsRunner - * - * @param parameters EventParameters containing parameters for the trigger event - * @return EventParameters updated parameters for on_success event - */ - virtual capabilities2_events::EventParameters param_on_success() override - { - // Create an Event Parameter with CapabilitySpecs content - std::vector capability_spec_strings; - for (const auto& spec : response_->capability_specs) - { - std::string spec_string = "package: " + spec.package + ", type: " + spec.type + - ", default_provider: " + spec.default_provider + ", content: " + spec.content; - capability_spec_strings.push_back(spec_string); - } - - // Create EventParameters and set the capability specs as a parameter for the on_success event - capabilities2_events::EventParameters parameters; - parameters.set_value("CapabilitySpecs", capability_spec_strings, capabilities2_events::OptionType::VECTOR_STRING); - - RCLCPP_INFO(node_->get_logger(), "GetCapabilitySpecsRunner creating param_on_success with %zu capability specs", capability_spec_strings.size()); - - return parameters; - } - - virtual void process_response(typename capabilities2_msgs::srv::GetCapabilitySpecs::Response::SharedPtr response) override - { - // This function can be used to log the response or perform any additional processing if needed - RCLCPP_INFO(node_->get_logger(), "GetCapabilitySpecsRunner received response with %zu capability specs", response->capability_specs.size()); - } -}; - -} // namespace capabilities2_runner diff --git a/capabilities2_runner/include/capabilities2_runner/topic_runner.hpp b/capabilities2_runner/include/capabilities2_runner/topic_runner.hpp index 795279e..340a730 100644 --- a/capabilities2_runner/include/capabilities2_runner/topic_runner.hpp +++ b/capabilities2_runner/include/capabilities2_runner/topic_runner.hpp @@ -28,17 +28,32 @@ class TopicRunner : public ThreadTriggerRunner * * @param node shared pointer to the capabilities node. Allows to use ros node related functionalities * @param run_config runner configuration loaded from the yaml file - * @param topic_name topic name used in the yaml file, used to load specific configuration from the run_config + * @param topic_name fallback topic name used when no matching topic resource is available in the run config + * @param topic_type topic message type used to resolve the remapped topic name from the run config */ virtual void init_subscriber(rclcpp::Node::SharedPtr node, const runner_opts& run_config, - const std::string& topic_name) + const std::string& topic_name, const std::string& topic_type) { // initialize the runner base by storing node pointer and run config init_base(node, run_config); + std::string resolved_topic_name = topic_name; + try + { + resolved_topic_name = get_topic_name_by_type(topic_type); + RCLCPP_INFO(node_->get_logger(), "resolved topic name: %s for type: %s", resolved_topic_name.c_str(), + topic_type.c_str()); + } + catch (const runner_exception&) + { + // Fall back to the explicit topic name for runners that are not backed by interface resources. + RCLCPP_ERROR(node_->get_logger(), "failed to resolve topic name for type: %s. using fallback topic name: %s", + topic_type.c_str(), resolved_topic_name.c_str()); + } + // create an service client subscription_ = node_->create_subscription( - topic_name, 10, [this](const typename TopicT::SharedPtr msg) { this->callback(msg); }); + resolved_topic_name, 10, [this](const typename TopicT::SharedPtr msg) { this->callback(msg); }); } /** diff --git a/capabilities2_runner/interfaces/GetCapabilitySpecsRunner.yaml b/capabilities2_runner/interfaces/GetCapabilitySpecsRunner.yaml deleted file mode 100644 index 3897e56..0000000 --- a/capabilities2_runner/interfaces/GetCapabilitySpecsRunner.yaml +++ /dev/null @@ -1,34 +0,0 @@ -%YAML 1.1 ---- -name: GetCapabilitySpecsRunner -spec_version: 1.1 -spec_type: interface -description: "This capability depends on the capabilities2 server functionalities and allows an decision making authority such as an LLM extract - capabilities of the robot. The capability can be trigged with an command such as - ''. - This is included in the default starting plan and the decision making authority such as an LLM does not need to include this in any - generated plans. The details for the Capaiblities are stored in a format as follows, - ' - - - name: Navigation - dependencies: - - MapServer - - PathPlanner - - - - - name: ObjectDetection - dependencies: - - Camera - - ImageProcessor - - - ' " - -interface: - services: - "/capabilities/get_capability_specs": - type: "capabilities2_msgs::srv::GetCapabilitySpecs" - description: "This capability focuses on extracting robot's capabilities and transfering them to decision making authority." \ No newline at end of file diff --git a/capabilities2_runner/interfaces/InputMultiplexRunner.yaml b/capabilities2_runner/interfaces/InputMultiplexRunner.yaml index 854c60e..6b4c164 100644 --- a/capabilities2_runner/interfaces/InputMultiplexRunner.yaml +++ b/capabilities2_runner/interfaces/InputMultiplexRunner.yaml @@ -1,13 +1,9 @@ %YAML 1.1 --- name: InputMultiplexRunner -spec_version: 1.1 +spec_version: 1.2 spec_type: interface -description: "This capability combines the results of all input by multiplexing events into a single interface. It allows the robot to wait or - multiple parallel processes at once until completion. This is inserted by the system itself and a decision making authority such - as an LLM does not need to include this in plans generated by it." -interface: - actions: - "empty": - type: std_srvs/action/Empty - description: empty. not used \ No newline at end of file +description: "This capability combines the results of all input by multiplexing events into a + single interface. It allows the robot to wait for multiple parallel processes at + once until completion. This is inserted by the system itself and planning entity + does not need to include this in plans generated by it." \ No newline at end of file diff --git a/capabilities2_runner/package.xml b/capabilities2_runner/package.xml index 6cb0bdc..391d1a4 100644 --- a/capabilities2_runner/package.xml +++ b/capabilities2_runner/package.xml @@ -38,14 +38,5 @@ providers/InputMultiplexRunner.yaml - - - - interfaces/GetCapabilitySpecsRunner.yaml - - - - providers/GetCapabilitySpecsRunner.yaml - diff --git a/capabilities2_runner/plugins.xml b/capabilities2_runner/plugins.xml index 8da5018..a77cd46 100644 --- a/capabilities2_runner/plugins.xml +++ b/capabilities2_runner/plugins.xml @@ -15,9 +15,4 @@ A plugin that provides a dummy-runner to test capabilities2 - - - A plugin that request capabilities from the capabilities server - - diff --git a/capabilities2_runner/providers/GetCapabilitySpecsRunner.yaml b/capabilities2_runner/providers/GetCapabilitySpecsRunner.yaml deleted file mode 100644 index af430f6..0000000 --- a/capabilities2_runner/providers/GetCapabilitySpecsRunner.yaml +++ /dev/null @@ -1,9 +0,0 @@ -# the empty provider -%YAML 1.1 ---- -name: GetCapabilitySpecsRunner -spec_type: provider -spec_version: 1.1 -description: "The capability provider for extracting capabilities from server. This is used to identify the capabilities of the robot" -implements: capabilities2_runner/GetCapabilitySpecsRunner -runner: capabilities2_runner::GetCapabilitySpecsRunner \ No newline at end of file diff --git a/capabilities2_runner/providers/InputMultiplexRunner.yaml b/capabilities2_runner/providers/InputMultiplexRunner.yaml index 23403a1..af03305 100644 --- a/capabilities2_runner/providers/InputMultiplexRunner.yaml +++ b/capabilities2_runner/providers/InputMultiplexRunner.yaml @@ -2,7 +2,7 @@ --- name: InputMultiplexRunner spec_type: provider -spec_version: 1.1 -description: "The capability provider for the capabilities2_runner/InputMultiplexRunner interface" +spec_version: 1.2 +description: "The provider for the capabilities2_runner/InputMultiplexRunner interface" implements: capabilities2_runner/InputMultiplexRunner runner: capabilities2_runner::InputMultiplexRunner \ No newline at end of file diff --git a/capabilities2_runner/src/system/system_runners.cpp b/capabilities2_runner/src/system/system_runners.cpp index c6f2a47..9884bd9 100644 --- a/capabilities2_runner/src/system/system_runners.cpp +++ b/capabilities2_runner/src/system/system_runners.cpp @@ -1,8 +1,6 @@ #include #include -#include #include // register runner plugins -PLUGINLIB_EXPORT_CLASS(capabilities2_runner::GetCapabilitySpecsRunner, capabilities2_runner::RunnerBase); PLUGINLIB_EXPORT_CLASS(capabilities2_runner::InputMultiplexRunner, capabilities2_runner::RunnerBase); \ No newline at end of file diff --git a/capabilities2_server/CMakeLists.txt b/capabilities2_server/CMakeLists.txt index 577cd70..33fad1e 100644 --- a/capabilities2_server/CMakeLists.txt +++ b/capabilities2_server/CMakeLists.txt @@ -15,6 +15,7 @@ find_package(ament_cmake REQUIRED) find_package(rclcpp REQUIRED) find_package(rclcpp_action REQUIRED) find_package(rclcpp_components REQUIRED) +find_package(std_srvs REQUIRED) find_package(bondcpp REQUIRED) find_package(pluginlib REQUIRED) find_package(capabilities2_msgs REQUIRED) @@ -58,6 +59,7 @@ ament_target_dependencies(${PROJECT_NAME}_comp bondcpp pluginlib rclcpp_components + std_srvs capabilities2_msgs capabilities2_events capabilities2_runner @@ -100,6 +102,7 @@ ament_target_dependencies(${PROJECT_NAME}_node rclcpp_action bondcpp pluginlib + std_srvs capabilities2_msgs capabilities2_events capabilities2_runner diff --git a/capabilities2_server/config/capabilities.yaml b/capabilities2_server/config/capabilities.yaml index b0f1a87..f81560a 100644 --- a/capabilities2_server/config/capabilities.yaml +++ b/capabilities2_server/config/capabilities.yaml @@ -3,6 +3,7 @@ loop_rate: 5.0 # Hz db_file: ~/.ros/capabilities/capabilities.sqlite3 rebuild: true # Set to true to rebuild the database + event_history_size: 100 package_paths: # paths to search for capabilities - install/ - /opt/ros/humble/share diff --git a/capabilities2_server/include/capabilities2_server/capabilities_api.hpp b/capabilities2_server/include/capabilities2_server/capabilities_api.hpp index 7413366..31675f9 100644 --- a/capabilities2_server/include/capabilities2_server/capabilities_api.hpp +++ b/capabilities2_server/include/capabilities2_server/capabilities_api.hpp @@ -3,6 +3,7 @@ #include #include #include +#include #include #include @@ -22,8 +23,11 @@ #include #include #include -#include #include +#include + +#include +#include namespace capabilities2_server { @@ -92,7 +96,7 @@ class CapabilitiesAPI } // get the provider specification for the capability - models::run_config_model_t run_config = cap_db_->get_run_config(provider); + models::run_config_model_t run_config = cap_db_->get_run_config(provider, capability); // create a new runner, this call implicitly starts the runner // create a runner id which is the cap name to uniquely identify the runner @@ -101,7 +105,7 @@ class CapabilitiesAPI // TODO: consider the logic for multiple runners per capability try { - runner_cache_.add_runner(node, capability, run_config); + runner_cache_.add_runner(node, capability, run_config, event_); // log RCLCPP_INFO(logging_->get_logger(), "started capability: %s with provider: %s", capability.c_str(), @@ -426,16 +430,30 @@ class CapabilitiesAPI std::vector get_providers(const std::string& interface, const bool& include_semantic) { std::vector providers; + std::unordered_set provider_names; for (const auto& provider : cap_db_->get_providers_by_interface(interface)) { - providers.push_back(provider.header.name); + if (provider_names.insert(provider.header.name).second) + { + providers.push_back(provider.header.name); + } } - // if not include_semantic, remove providers for semantic interfaces - if (!include_semantic) + // Semantic interfaces should inherit providers from the base interface they redefine. + if (include_semantic) { - // TODO: implement + models::semantic_interface_model_t semantic = cap_db_->get_semantic_interface(interface); + if (!semantic.header.name.empty()) + { + for (const auto& provider : cap_db_->get_providers_by_interface(semantic.redefines)) + { + if (provider_names.insert(provider.header.name).second) + { + providers.push_back(provider.header.name); + } + } + } } return providers; @@ -624,6 +642,30 @@ class CapabilitiesAPI return running_capabilities; } + std::map get_runnable_specs() + { + // create message container + std::map runnable_specs; + + auto specs = cap_db_->get_runnable_specs(); + + // for each cap get the running model from db + for (const auto& spec : specs) + { + YAML::Node spec_node = spec.to_yaml(); + + // create a runnable spec msg + capabilities2_msgs::msg::RunnableSpec rs; + + rs.spec = YAML::Dump(spec_node); + + // add runnable spec msg + runnable_specs[spec.interface.name + "|" + spec.provider.name] = rs; + } + + return runnable_specs; + } + /** */ /** diff --git a/capabilities2_server/include/capabilities2_server/capabilities_db.hpp b/capabilities2_server/include/capabilities2_server/capabilities_db.hpp index d48e7ec..51e36cb 100644 --- a/capabilities2_server/include/capabilities2_server/capabilities_db.hpp +++ b/capabilities2_server/include/capabilities2_server/capabilities_db.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -13,6 +14,7 @@ #include #include #include +#include #include namespace capabilities2_server @@ -302,6 +304,7 @@ class CapabilitiesDB : public DBBase { // start with provider and work up the chain models::provider_model_t provider = get_provider(provider_name); + if (provider.header.name.empty()) { // return empty running model @@ -328,26 +331,97 @@ class CapabilitiesDB : public DBBase return running; } - // apply a remapping to a specification model - virtual void apply_remappings(models::specification_model_t& spec, - const models::remappable_base_t& remappable) override + // get runnable capabilities from provider + virtual models::runnable_model_t get_runnable_spec(const std::string& provider_name) override { - for (auto const& param : remappable.remappings.parameters) - { - spec.parameters[param.from].name = param.to; - } - for (auto const& topic : remappable.remappings.topics) - { - spec.topics[topic.from].name = topic.to; - } - for (auto const& service : remappable.remappings.services) + // start with provider and work up the chain + models::provider_model_t provider = get_provider(provider_name); + if (provider.header.name.empty()) { - spec.services[service.from].name = service.to; + // return empty runnable model + return models::runnable_model_t(); } - for (auto const& action : remappable.remappings.actions) + + return build_runnable_spec(provider); + } + + virtual std::vector get_runnable_specs() override + { + std::vector runnable_specs; + + // get all providers + std::vector providers = get_providers(); + + for (const auto& provider : providers) { - spec.actions[action.from].name = action.to; + models::semantic_interface_model_t provider_semantic = get_semantic_interface(provider.implements); + if (!provider_semantic.header.name.empty()) + { + models::runnable_model_t runnable = build_runnable_spec(provider, provider.implements); + if (runnable.is_valid()) + { + runnable_specs.push_back(runnable); + } + continue; + } + + std::vector semantic_interfaces = + get_semantic_interfaces_by_interface(provider.implements); + + if (semantic_interfaces.empty()) + { + models::runnable_model_t runnable = build_runnable_spec(provider); + if (runnable.is_valid()) + { + runnable_specs.push_back(runnable); + } + continue; + } + + for (const auto& semantic_interface : semantic_interfaces) + { + models::runnable_model_t runnable = build_runnable_spec(provider, semantic_interface.header.name); + if (runnable.is_valid()) + { + runnable_specs.push_back(runnable); + } + } } + + return runnable_specs; + } + + // apply a remapping to a specification model + virtual void apply_remappings(models::specification_model_t& spec, + const models::remappable_base_t& remappable) override + { + const auto apply_resource_remappings = [](auto& resources, const auto& remappings) { + for (const auto& remapping : remappings) + { + auto resource = resources.find(remapping.from); + if (resource == resources.end()) + { + resource = std::find_if(resources.begin(), resources.end(), [&remapping](const auto& entry) { + return entry.second.name == remapping.from; + }); + } + + if (resource == resources.end()) + { + continue; + } + + auto remapped_resource = resource->second; + resources.erase(resource); + remapped_resource.name = remapping.to; + resources[remapping.to] = remapped_resource; + } + }; + + apply_resource_remappings(spec.parameters, remappable.remappings.parameters); + apply_resource_remappings(spec.topics, remappable.remappings.topics); + apply_resource_remappings(spec.services, remappable.remappings.services); + apply_resource_remappings(spec.actions, remappable.remappings.actions); } // apply semantics to interface @@ -390,7 +464,8 @@ class CapabilitiesDB : public DBBase } // get run config model - virtual models::run_config_model_t get_run_config(const std::string& provider_name) override + virtual models::run_config_model_t get_run_config(const std::string& provider_name, + const std::string& interface_name = "") override { models::provider_model_t provider = get_provider(provider_name); if (provider.header.name.empty()) @@ -405,6 +480,20 @@ class CapabilitiesDB : public DBBase run_config.started_by = provider_name; run_config.pid = "0"; + // If the caller requested a semantic interface that redefines the provider's base interface, + // apply the semantic remappings before layering provider remappings. + if (!interface_name.empty()) + { + models::semantic_interface_model_t requested_semantic = get_semantic_interface(interface_name); + if (!requested_semantic.header.name.empty() && requested_semantic.redefines == provider.implements) + { + run_config.interface = apply_semantic_remappings(requested_semantic); + run_config.global_namespace = requested_semantic.global_namespace; + apply_remappings(run_config.interface.interface, provider); + return run_config; + } + } + // remap resources run_config.interface = apply_provider_remappings(provider); @@ -469,6 +558,85 @@ class CapabilitiesDB : public DBBase } private: + models::runnable_model_t build_runnable_spec(const models::provider_model_t& provider, + const std::string& interface_name = "") + { + if (provider.header.name.empty()) + { + return models::runnable_model_t(); + } + + models::run_config_model_t run_config = get_run_config(provider.header.name, interface_name); + if (!run_config.is_valid()) + { + return models::runnable_model_t(); + } + + models::runnable_model_t runnable; + runnable.interface = run_config.interface.header; + runnable.provider = provider.header; + runnable.command = rewrite_runner_command(provider.command, runnable.interface.name, runnable.provider.name); + runnable.configuration_parameters = provider.configuration_parameters; + runnable.runtime__input_parameters = provider.runtime__input_parameters; + runnable.runtime__output_parameters = provider.runtime__output_parameters; + runnable.relations = run_config.interface.relations; + + return runnable; + } + + static std::string rewrite_runner_command(const std::string& command, const std::string& interface_name, + const std::string& provider_name) + { + std::string rewritten = rewrite_runner_attribute(command, "interface", interface_name); + rewritten = rewrite_runner_attribute(rewritten, "provider", provider_name); + return rewritten; + } + + static std::string rewrite_runner_attribute(const std::string& command, const std::string& attribute, + const std::string& value) + { + const std::string key = attribute + "="; + const auto key_pos = command.find(key); + if (key_pos == std::string::npos) + { + return command; + } + + const auto value_pos = key_pos + key.size(); + if (value_pos >= command.size()) + { + return command; + } + + std::size_t content_start = value_pos; + char quote = '\0'; + if (command[content_start] == '\'' || command[content_start] == '"') + { + quote = command[content_start]; + ++content_start; + } + + std::size_t content_end = content_start; + if (quote != '\0') + { + content_end = command.find(quote, content_start); + if (content_end == std::string::npos) + { + return command; + } + } + else + { + while (content_end < command.size() && !std::isspace(static_cast(command[content_end])) && + command[content_end] != '>' && command[content_end] != '/') + { + ++content_end; + } + } + + return command.substr(0, content_start) + value + command.substr(content_end); + } + // model conversion helpers models::interface_model_t to_interface(sqlite3_stmt* stmt) { @@ -476,7 +644,8 @@ class CapabilitiesDB : public DBBase interface.header.name = std::string(reinterpret_cast(sqlite3_column_text(stmt, 0))); interface.header.version = sqlite3_column_int(stmt, 1); interface.header.type = std::string(reinterpret_cast(sqlite3_column_text(stmt, 2))); - interface.header.description = from_sql_safe(std::string(reinterpret_cast(sqlite3_column_text(stmt, 3)))); + interface.header.description = + from_sql_safe(std::string(reinterpret_cast(sqlite3_column_text(stmt, 3)))); models::specification_model_t spec; spec.from_yaml(YAML::Load(from_sql_safe(std::string(reinterpret_cast(sqlite3_column_text(stmt, 4)))))); @@ -491,7 +660,8 @@ class CapabilitiesDB : public DBBase semantic_interface.header.name = std::string(reinterpret_cast(sqlite3_column_text(stmt, 0))); semantic_interface.header.version = sqlite3_column_int(stmt, 1); semantic_interface.header.type = std::string(reinterpret_cast(sqlite3_column_text(stmt, 2))); - semantic_interface.header.description = from_sql_safe(std::string(reinterpret_cast(sqlite3_column_text(stmt, 3)))); + semantic_interface.header.description = + from_sql_safe(std::string(reinterpret_cast(sqlite3_column_text(stmt, 3)))); semantic_interface.redefines = std::string(reinterpret_cast(sqlite3_column_text(stmt, 4))); semantic_interface.global_namespace = std::string(reinterpret_cast(sqlite3_column_text(stmt, 5))); semantic_interface.remappings.from_yaml( @@ -506,12 +676,17 @@ class CapabilitiesDB : public DBBase provider.header.name = std::string(reinterpret_cast(sqlite3_column_text(stmt, 0))); provider.header.version = sqlite3_column_int(stmt, 1); provider.header.type = std::string(reinterpret_cast(sqlite3_column_text(stmt, 2))); - provider.header.description = from_sql_safe(std::string(reinterpret_cast(sqlite3_column_text(stmt, 3)))); + provider.header.description = + from_sql_safe(std::string(reinterpret_cast(sqlite3_column_text(stmt, 3)))); provider.implements = std::string(reinterpret_cast(sqlite3_column_text(stmt, 4))); - provider.depends_on = YAML::Load(from_sql_safe(std::string(reinterpret_cast(sqlite3_column_text(stmt, 5))))) - .as>(); - provider.remappings.from_yaml(YAML::Load(from_sql_safe(std::string(reinterpret_cast(sqlite3_column_text(stmt, 6)))))); + provider.depends_on = + YAML::Load(from_sql_safe(std::string(reinterpret_cast(sqlite3_column_text(stmt, 5))))) + .as>(); + provider.remappings.from_yaml( + YAML::Load(from_sql_safe(std::string(reinterpret_cast(sqlite3_column_text(stmt, 6)))))); provider.runner = std::string(reinterpret_cast(sqlite3_column_text(stmt, 7))); + provider.defineable_base_t::from_yaml( + YAML::Load(from_sql_safe(std::string(reinterpret_cast(sqlite3_column_text(stmt, 8)))))); return provider; } diff --git a/capabilities2_server/include/capabilities2_server/capabilities_server.hpp b/capabilities2_server/include/capabilities2_server/capabilities_server.hpp index 2fec6b5..f19d8dd 100644 --- a/capabilities2_server/include/capabilities2_server/capabilities_server.hpp +++ b/capabilities2_server/include/capabilities2_server/capabilities_server.hpp @@ -12,6 +12,8 @@ #include +#include + #include #include @@ -32,6 +34,7 @@ #include #include #include +#include #include #include @@ -98,6 +101,10 @@ class CapabilitiesServer : public rclcpp::Node, public CapabilitiesAPI declare_parameter("package_paths", std::vector()); std::vector package_paths = get_parameter("package_paths").as_string_array(); + declare_parameter("event_history_size", 100); + const int event_history_size = get_parameter("event_history_size").as_int(); + const size_t bounded_event_history_size = event_history_size > 0 ? static_cast(event_history_size) : 100U; + // get full path of db file std::filesystem::path db_path = std::filesystem::absolute(expand_tilde(db_file)); db_file = db_path.string(); @@ -130,9 +137,12 @@ class CapabilitiesServer : public rclcpp::Node, public CapabilitiesAPI // pubs event_pub_ = create_publisher("~/events", 10); - // event publisher uses event subsystem - event_ = std::make_shared(event_pub_); + published_event_ = std::make_shared( + event_pub_, bounded_event_history_size); + event_ = published_event_; + + RCLCPP_INFO(get_logger(), "Capability event history size configured to %zu", bounded_event_history_size); // subs @@ -198,6 +208,10 @@ class CapabilitiesServer : public rclcpp::Node, public CapabilitiesAPI "~/get_capability_specs", std::bind(&CapabilitiesServer::get_capability_specs_cb, this, std::placeholders::_1, std::placeholders::_2)); + get_event_snapshot_srv_ = create_service( + "~/get_event_snapshot", + std::bind(&CapabilitiesServer::get_event_snapshot_cb, this, std::placeholders::_1, std::placeholders::_2)); + get_remappings_srv_ = create_service( "~/get_remappings", std::bind(&CapabilitiesServer::get_remappings_cb, this, std::placeholders::_1, std::placeholders::_2)); @@ -206,6 +220,22 @@ class CapabilitiesServer : public rclcpp::Node, public CapabilitiesAPI "~/get_running_capabilities", std::bind(&CapabilitiesServer::get_running_capabilities_cb, this, std::placeholders::_1, std::placeholders::_2)); + get_runnable_specs_srv_ = create_service( + "~/get_runnable_specs", + std::bind(&CapabilitiesServer::get_runnable_specs_cb, this, std::placeholders::_1, std::placeholders::_2)); + + ready_srv_ = create_service( + "~/ready", + std::bind(&CapabilitiesServer::ready_cb, this, std::placeholders::_1, std::placeholders::_2)); + + const auto interface_count = get_interfaces().size(); + const auto runnable_count = get_runnable_specs().size(); + + ready_ = true; + + RCLCPP_INFO(get_logger(), "loaded %zu interfaces and %zu runnable capabilities", + interface_count, runnable_count); + // log ready RCLCPP_INFO(get_logger(), "capabilities server started"); @@ -474,6 +504,22 @@ class CapabilitiesServer : public rclcpp::Node, public CapabilitiesAPI res->running_capabilities = get_running_capabilities(); } + void get_runnable_specs_cb(const std::shared_ptr req, + std::shared_ptr res) + { + // req is empty + + // set response + // get runnable specs + auto specs = get_runnable_specs(); + + for (const auto& [name, spec] : specs) + { + res->index_of_specs.push_back(name); + res->runnable_specs.push_back(spec); + } + } + private: void load_capabilities(const std::string& package_path) { @@ -724,6 +770,37 @@ class CapabilitiesServer : public rclcpp::Node, public CapabilitiesAPI spec_file_file.close(); } + void ready_cb(const std::shared_ptr req, + std::shared_ptr res) + { + (void)req; + res->success = ready_; + res->message = ready_ ? "capabilities server startup complete" : "capabilities server still loading"; + } + + void get_event_snapshot_cb(const std::shared_ptr req, + std::shared_ptr res) + { + if (!published_event_) + { + res->header.stamp = now(); + res->oldest_sequence = 0; + res->latest_sequence = 0; + res->max_events = 0; + res->truncated = false; + res->events.clear(); + return; + } + + const auto snapshot = published_event_->get_event_snapshot(req->after_sequence, req->max_events); + res->header.stamp = snapshot.stamp; + res->oldest_sequence = snapshot.oldest_sequence; + res->latest_sequence = snapshot.latest_sequence; + res->max_events = snapshot.max_events; + res->truncated = snapshot.truncated; + res->events = snapshot.events; + } + private: // loop hz double loop_hz_; @@ -731,6 +808,7 @@ class CapabilitiesServer : public rclcpp::Node, public CapabilitiesAPI // publishers // event publisher rclcpp::Publisher::SharedPtr event_pub_; + std::shared_ptr published_event_; // services // establish bond @@ -759,10 +837,17 @@ class CapabilitiesServer : public rclcpp::Node, public CapabilitiesAPI rclcpp::Service::SharedPtr get_capability_spec_srv_; // get capability specs rclcpp::Service::SharedPtr get_capability_specs_srv_; + // get event snapshot + rclcpp::Service::SharedPtr get_event_snapshot_srv_; // get remappings rclcpp::Service::SharedPtr get_remappings_srv_; // get running capabilities rclcpp::Service::SharedPtr get_running_capabilities_srv_; + // get runnable specs + rclcpp::Service::SharedPtr get_runnable_specs_srv_; + // ready + rclcpp::Service::SharedPtr ready_srv_; + bool ready_ = false; }; } // namespace capabilities2_server diff --git a/capabilities2_server/include/capabilities2_server/db_base.hpp b/capabilities2_server/include/capabilities2_server/db_base.hpp index 8200a66..91a22a3 100644 --- a/capabilities2_server/include/capabilities2_server/db_base.hpp +++ b/capabilities2_server/include/capabilities2_server/db_base.hpp @@ -6,6 +6,7 @@ #include #include #include +#include #include namespace capabilities2_server @@ -90,7 +91,14 @@ class DBBase virtual models::interface_model_t apply_provider_remappings(models::provider_model_t provider) = 0; // get run config model - virtual models::run_config_model_t get_run_config(const std::string& provider_name) = 0; + virtual models::run_config_model_t get_run_config(const std::string& provider_name, + const std::string& interface_name = "") = 0; + + // get runnable capability from provider + virtual models::runnable_model_t get_runnable_spec(const std::string& provider_name) = 0; + + // get all runnable capabilities + virtual std::vector get_runnable_specs() = 0; // exists in db templated by model type template diff --git a/capabilities2_server/include/capabilities2_server/models/defineable_base.hpp b/capabilities2_server/include/capabilities2_server/models/defineable_base.hpp index 24a68e9..0c98964 100644 --- a/capabilities2_server/include/capabilities2_server/models/defineable_base.hpp +++ b/capabilities2_server/include/capabilities2_server/models/defineable_base.hpp @@ -20,25 +20,118 @@ namespace models */ struct defineable_base_t { - // the definition stored as a string - std::string definition_str = ""; // optional property + std::string command; + std::vector configuration_parameters; + std::vector runtime__input_parameters; + std::vector runtime__output_parameters; + // is the definition valid bool valid = false; void from_yaml(const YAML::Node& node) { - // try get the definition as a string - if (node["definition"]) + // get the definition node + YAML::Node def_node = node["definition"]; + + // if no definition exists, return + if (!def_node) + { + return; + } + + // try get the command as a string + if (def_node["command"]) { - definition_str = node["definition"].as(); + command = def_node["command"].as(); valid = true; } + + // try get the configuration parameters + if (def_node["configuration_parameters"]) + { + for (const auto& param : def_node["configuration_parameters"]) + { + resource_model_t r; + r.from_yaml(param); + configuration_parameters.push_back(r); + } + } + + // get the runtime parameters + YAML::Node runtime_node = def_node["runtime_parameters"]; + + // if no runtime parameters exist, return + if (!runtime_node) + { + return; + } + + // try get the runtime input parameters + if (runtime_node["input"]) + { + for (const auto& param : runtime_node["input"]) + { + resource_model_t r; + r.from_yaml(param); + runtime__input_parameters.push_back(r); + } + } + + // try get the runtime output parameters + if (runtime_node["output"]) + { + for (const auto& param : runtime_node["output"]) + { + resource_model_t r; + r.from_yaml(param); + runtime__output_parameters.push_back(r); + } + } } YAML::Node to_yaml() const { YAML::Node node; - node["definition"] = definition_str; + + // if command exists + if (!command.empty()) + { + node["definition"]["command"] = command; + } + + // if configuration parameters exist + YAML::Node config_params; + if (!configuration_parameters.empty()) + { + for (const auto& param : configuration_parameters) + { + config_params.push_back(param.to_yaml()); + } + node["definition"]["configuration_parameters"] = config_params; + } + + // if runtime input parameters exist + YAML::Node runtime_input_params; + if (!runtime__input_parameters.empty()) + { + for (const auto& param : runtime__input_parameters) + { + runtime_input_params.push_back(param.to_yaml()); + } + node["definition"]["runtime_parameters"]["input"] = runtime_input_params; + } + + // if runtime output parameters exist + YAML::Node runtime_output_params; + if (!runtime__output_parameters.empty()) + { + for (const auto& param : runtime__output_parameters) + { + runtime_output_params.push_back(param.to_yaml()); + } + node["definition"]["runtime_parameters"]["output"] = runtime_output_params; + } + return node; } diff --git a/capabilities2_server/include/capabilities2_server/models/interface.hpp b/capabilities2_server/include/capabilities2_server/models/interface.hpp index f6a47b0..3645c19 100644 --- a/capabilities2_server/include/capabilities2_server/models/interface.hpp +++ b/capabilities2_server/include/capabilities2_server/models/interface.hpp @@ -111,6 +111,11 @@ struct specification_model_t // return node return node; } + + const bool is_initialized() const + { + return !parameters.empty() || !topics.empty() || !services.empty() || !actions.empty(); + } }; /** @@ -128,7 +133,13 @@ struct interface_model_t : public predicateable_base_t void from_yaml(const YAML::Node& node) { header.from_yaml(node); - interface.from_yaml(node["interface"]); + + // if interface exists + if (node["interface"]) + { + interface.from_yaml(node["interface"]); + } + // if relations exist if (node["relations"]) { @@ -144,7 +155,13 @@ struct interface_model_t : public predicateable_base_t YAML::Node to_yaml() const { YAML::Node node = header.to_yaml(); - node["interface"] = interface.to_yaml(); + + // if interface exists + if (interface.is_initialized()) + { + node["interface"] = interface.to_yaml(); + } + // if relations exist if (relations.size() > 0) { diff --git a/capabilities2_server/include/capabilities2_server/models/predicateable_base.hpp b/capabilities2_server/include/capabilities2_server/models/predicateable_base.hpp index 45a2595..7793833 100644 --- a/capabilities2_server/include/capabilities2_server/models/predicateable_base.hpp +++ b/capabilities2_server/include/capabilities2_server/models/predicateable_base.hpp @@ -18,6 +18,36 @@ namespace models struct predicateable_base_t { std::vector relations; + + void from_yaml(const YAML::Node& node) + { + if (!node["relations"]) + { + return; + } + + for (const auto& relation : node["relations"]) + { + predicate_model_t predicate; + predicate.from_yaml(relation); + relations.push_back(predicate); + } + } + + const bool predicated() const + { + return !relations.empty(); + } + + YAML::Node to_yaml() const + { + YAML::Node node; + for (const auto& relation : relations) + { + node.push_back(relation.to_yaml()); + } + return node; + } }; } // namespace models diff --git a/capabilities2_server/include/capabilities2_server/models/provider.hpp b/capabilities2_server/include/capabilities2_server/models/provider.hpp index eb64573..1aa3865 100644 --- a/capabilities2_server/include/capabilities2_server/models/provider.hpp +++ b/capabilities2_server/include/capabilities2_server/models/provider.hpp @@ -27,7 +27,6 @@ struct provider_model_t : public remappable_base_t, public predicateable_base_t, header_model_t header; std::string implements; std::map depends_on; - remappings_model_t remappings; std::string runner; void from_yaml(const YAML::Node& node) @@ -35,15 +34,21 @@ struct provider_model_t : public remappable_base_t, public predicateable_base_t, header.from_yaml(node); implements = node["implements"].as(); runner = node["runner"].as(); - for (const auto& dependency : node["depends_on"]) + if (node["depends_on"]) { - depends_on[dependency.first.as()] = dependency.second["provider"].as(); + for (const auto& dependency : node["depends_on"]) + { + depends_on[dependency.first.as()] = dependency.second["provider"].as(); + } } // if remappings exist if (node["remappings"]) { remappings.from_yaml(node["remappings"]); } + + // relations + predicateable_base_t::from_yaml(node); // definition defineable_base_t::from_yaml(node); @@ -52,6 +57,7 @@ struct provider_model_t : public remappable_base_t, public predicateable_base_t, YAML::Node to_yaml() const { YAML::Node node = header.to_yaml(); + node["implements"] = implements; for (const auto& dependency : depends_on) { @@ -59,10 +65,11 @@ struct provider_model_t : public remappable_base_t, public predicateable_base_t, } node["remappings"] = remappings.to_yaml(); node["runner"] = runner; + // definition if (defined()) { - node["definition"] = definition_str; + node["definition"] = defineable_base_t::to_yaml(); } return node; @@ -80,7 +87,7 @@ struct provider_model_t : public remappable_base_t, public predicateable_base_t, deps["depends_on"] = depends_on; return header.to_sql_values() + ", '" + implements + "', '" + to_sql_safe(YAML::Dump(deps["depends_on"])) + "', '" + - to_sql_safe(YAML::Dump(remappings.to_yaml())) + "', '" + runner + "', '" + definition_str + "'"; + to_sql_safe(YAML::Dump(remappings.to_yaml())) + "', '" + runner + "', '" + to_sql_safe(YAML::Dump(defineable_base_t::to_yaml())) + "'"; } }; diff --git a/capabilities2_server/include/capabilities2_server/models/resource.hpp b/capabilities2_server/include/capabilities2_server/models/resource.hpp index 0bebbdf..e51cf6a 100644 --- a/capabilities2_server/include/capabilities2_server/models/resource.hpp +++ b/capabilities2_server/include/capabilities2_server/models/resource.hpp @@ -1,6 +1,8 @@ #pragma once #include +#include + #include namespace capabilities2_server @@ -22,12 +24,63 @@ struct resource_model_t std::string name; std::string type; std::string description; + std::string semantic_key; + bool required = false; + std::vector satisfiable_from; + std::string fallback_parameter; + std::vector aliases; + bool has_default = false; + std::string default_value; void from_yaml(const YAML::Node& node) { name = node["name"].as(); type = node["type"].as(); description = node["description"].as(); + + if (node["semantic_key"]) + { + semantic_key = node["semantic_key"].as(); + } + + if (node["required"]) + { + required = node["required"].as(); + } + + if (node["satisfiable_from"] && node["satisfiable_from"].IsSequence()) + { + satisfiable_from.clear(); + for (const auto& item : node["satisfiable_from"]) + { + satisfiable_from.push_back(item.as()); + } + } + + if (node["fallback_parameter"]) + { + fallback_parameter = node["fallback_parameter"].as(); + } + + if (node["aliases"] && node["aliases"].IsSequence()) + { + aliases.clear(); + for (const auto& item : node["aliases"]) + { + aliases.push_back(item.as()); + } + } + + if (node["default"]) + { + has_default = true; + default_value = YAML::Dump(node["default"]); + + if (!default_value.empty() && default_value.back() == '\n') + { + default_value.pop_back(); + } + } } YAML::Node to_yaml() const @@ -36,6 +89,47 @@ struct resource_model_t node["name"] = name; node["type"] = type; node["description"] = description; + + if (!semantic_key.empty()) + { + node["semantic_key"] = semantic_key; + } + + if (required) + { + node["required"] = required; + } + + if (!satisfiable_from.empty()) + { + YAML::Node satisfiable_from_node; + for (const auto& source : satisfiable_from) + { + satisfiable_from_node.push_back(source); + } + node["satisfiable_from"] = satisfiable_from_node; + } + + if (!fallback_parameter.empty()) + { + node["fallback_parameter"] = fallback_parameter; + } + + if (!aliases.empty()) + { + YAML::Node aliases_node; + for (const auto& alias : aliases) + { + aliases_node.push_back(alias); + } + node["aliases"] = aliases_node; + } + + if (has_default) + { + node["default"] = YAML::Load(default_value); + } + return node; } }; diff --git a/capabilities2_server/include/capabilities2_server/models/run_config.hpp b/capabilities2_server/include/capabilities2_server/models/run_config.hpp index 10bad85..fb066bc 100644 --- a/capabilities2_server/include/capabilities2_server/models/run_config.hpp +++ b/capabilities2_server/include/capabilities2_server/models/run_config.hpp @@ -68,9 +68,10 @@ struct run_config_model_t : defineable_base_t node["provider"] = provider.to_yaml(); node["interface"] = interface.to_yaml(); + if (defined()) { - node["definition"] = definition_str; + node["definition"] = defineable_base_t::to_yaml(); } node["global_namespace"] = global_namespace; node["runner"] = runner; diff --git a/capabilities2_server/include/capabilities2_server/models/runnable.hpp b/capabilities2_server/include/capabilities2_server/models/runnable.hpp new file mode 100644 index 0000000..8ac5990 --- /dev/null +++ b/capabilities2_server/include/capabilities2_server/models/runnable.hpp @@ -0,0 +1,55 @@ +#pragma once + +#include + +#include +#include +#include +#include + +namespace capabilities2_server +{ +namespace models +{ + +/** + * @brief runnable type + * + * This type represents a runnable instance of a capability with a specific provider + * description and interface. It includes the necessary information to run the capability, + * such as the provider, interface, trigger command and descriptions. + * + */ +struct runnable_model_t : defineable_base_t, predicateable_base_t +{ + header_model_t provider; + header_model_t interface; + + const bool is_valid() const + { + return !interface.name.empty() && !provider.name.empty(); + } + + YAML::Node to_yaml() const + { + YAML::Node node; + + node["provider"] = provider.to_yaml(); + node["interface"] = interface.to_yaml(); + + if (defined()) + { + node["definition"] = defineable_base_t::to_yaml(); + } + + if (predicated()) + { + node["relations"] = predicateable_base_t::to_yaml(); + } + + return node; + } +}; + +} // namespace models +} // namespace capabilities2_server diff --git a/capabilities2_server/include/capabilities2_server/models/semantic_interface.hpp b/capabilities2_server/include/capabilities2_server/models/semantic_interface.hpp index 0a727bd..e6eb319 100644 --- a/capabilities2_server/include/capabilities2_server/models/semantic_interface.hpp +++ b/capabilities2_server/include/capabilities2_server/models/semantic_interface.hpp @@ -26,7 +26,6 @@ struct semantic_interface_model_t : public remappable_base_t, predicateable_base header_model_t header; std::string redefines; std::string global_namespace; - remappings_model_t remappings; void from_yaml(const YAML::Node& node) { diff --git a/capabilities2_server/include/capabilities2_server/runner_cache.hpp b/capabilities2_server/include/capabilities2_server/runner_cache.hpp index 2689b4e..480f4a0 100644 --- a/capabilities2_server/include/capabilities2_server/runner_cache.hpp +++ b/capabilities2_server/include/capabilities2_server/runner_cache.hpp @@ -43,7 +43,8 @@ class RunnerCache * @param run_config run_config of the runner to be loaded */ void add_runner(rclcpp::Node::SharedPtr node, const std::string& capability, - const models::run_config_model_t& run_config) + const models::run_config_model_t& run_config, + std::shared_ptr event_emitter = nullptr) { // if the runner exists then throw an error preserving uniqueness if (running(capability)) @@ -69,6 +70,8 @@ class RunnerCache runner_cache_[capability] = runner_loader_.createSharedInstance(run_config.runner); } + runner_cache_[capability]->enable_events(event_emitter); + // start the runner runner_cache_[capability]->start(node, run_config.to_runner_opts(), ""); } @@ -126,10 +129,10 @@ class RunnerCache { // add connection to the runner // callback signature: (capability, parameters, bond_id, instance_id) - runner_cache_[capability]->add_connection(connection_id, connection.type, connection.target, - std::bind(&capabilities2_server::RunnerCache::trigger_runner, this, - std::placeholders::_1, std::placeholders::_2, - std::placeholders::_3, std::placeholders::_4)); + runner_cache_[capability]->add_connection( + connection_id, connection.ownership_id, connection.type, connection.target, + std::bind(&capabilities2_server::RunnerCache::trigger_runner, this, std::placeholders::_1, + std::placeholders::_2, std::placeholders::_3, std::placeholders::_4)); } catch (const capabilities2_events::event_exception& e) { diff --git a/capabilities2_server/package.xml b/capabilities2_server/package.xml index 311bd15..475c02b 100644 --- a/capabilities2_server/package.xml +++ b/capabilities2_server/package.xml @@ -21,6 +21,7 @@ rclcpp rclcpp_action + std_srvs bondcpp pluginlib rclcpp_components diff --git a/capabilities2_server/test/test.cpp b/capabilities2_server/test/test.cpp index d71963c..0fd783f 100644 --- a/capabilities2_server/test/test.cpp +++ b/capabilities2_server/test/test.cpp @@ -1,61 +1,209 @@ +#include +#include +#include #include -#include -#include +#include -using namespace capabilities2_server; +#include -// testing units -int main(int argc, char** argv) +#include +#include +#include +#include + +namespace +{ + +capabilities2_server::models::interface_model_t load_interface(const std::string& yaml, const std::string& package) +{ + capabilities2_server::models::interface_model_t model; + model.from_yaml(YAML::Load(yaml)); + model.header.name = package + "/" + model.header.name; + return model; +} + +capabilities2_server::models::semantic_interface_model_t load_semantic_interface(const std::string& yaml, + const std::string& package) +{ + capabilities2_server::models::semantic_interface_model_t model; + model.from_yaml(YAML::Load(yaml)); + model.header.name = package + "/" + model.header.name; + return model; +} + +capabilities2_server::models::provider_model_t load_provider(const std::string& yaml, const std::string& package) +{ + capabilities2_server::models::provider_model_t model; + model.from_yaml(YAML::Load(yaml)); + model.header.name = package + "/" + model.header.name; + return model; +} + +} // namespace + +int main() { - rclcpp::init(argc, argv); + const std::filesystem::path db_path = std::filesystem::temp_directory_path() / "capabilities2_runnable_specs.sqlite3"; + std::filesystem::remove(db_path); + + capabilities2_server::CapabilitiesDB db(db_path.string()); + + const std::string waypoint_interface_yaml = R"( +%YAML 1.1 +--- +name: WaypointRunner +spec_version: 1.2 +spec_type: interface +description: Base waypoint interface. +interface: + actions: + "/navigate_to_pose": + type: "nav2_msgs::action::NavigateToPose" + description: "Navigate action" +)"; + + const std::string turtlebot_waypoint_semantic_yaml = R"( +%YAML 1.1 +--- +name: TurtlebotWaypointRunner +spec_type: semantic_interface +spec_version: 1.2 +description: TurtleBot waypoint wrapper. +redefines: test_capabilities/WaypointRunner +global_namespace: turtlebot4 +remappings: + actions: + "/navigate_to_pose": "/turtlebot4/navigate_to_pose" +)"; - // capabilities server - capabilities2_server::CapabilitiesServer node; + const std::string waypoint_provider_yaml = R"( +%YAML 1.1 +--- +name: WaypointRunner +spec_type: provider +spec_version: 1.2 +description: Base waypoint provider. +implements: test_capabilities/WaypointRunner +runner: capabilities2_runner::WaypointRunner +definition: + command: "" + configuration_parameters: + - name: x + type: double + description: X target. + - name: y + type: double + description: Y target. +)"; - // testing - // open yaml file - std::ifstream file("/home/ubuntu/colcon_ws/src/std_capabilities/providers/empty.yaml"); - std::string data{ std::istreambuf_iterator(file), std::istreambuf_iterator() }; + const std::string robotpose_interface_yaml = R"( +%YAML 1.1 +--- +name: RobotPoseRunner +spec_version: 1.2 +spec_type: interface +description: Base robot pose interface. +)"; - // close file - file.close(); + const std::string turtlebot_robotpose_semantic_yaml = R"( +%YAML 1.1 +--- +name: TurtlebotRobotposeRunner +spec_type: semantic_interface +spec_version: 1.2 +description: TurtleBot robot pose wrapper. +redefines: test_capabilities/RobotPoseRunner +global_namespace: turtlebot4 +)"; - // print contents - std::cout << data << std::endl; + const std::string robotpose_provider_yaml = R"( +%YAML 1.1 +--- +name: RobotPoseRunner +spec_type: provider +spec_version: 1.2 +description: Base robot pose provider. +implements: test_capabilities/RobotPoseRunner +runner: capabilities2_runner::RobotPoseRunner +definition: + command: "" + configuration_parameters: + - name: map + type: string + description: Map frame. + - name: odom + type: string + description: Odom frame. + - name: robot + type: string + description: Robot frame. +)"; - // parse yaml - YAML::Node yml = YAML::Load(data); - // std::cout << yml["name"] << std::endl; + const std::string plain_interface_yaml = R"( +%YAML 1.1 +--- +name: PlainRunner +spec_version: 1.2 +spec_type: interface +description: Base plain interface. +)"; - capabilities2_msgs::msg::CapabilitySpec spec; - spec.package = "std_capabilities"; - spec.type = capabilities2_msgs::msg::CapabilitySpec::CAPABILITY_PROVIDER; - spec.content = data; + const std::string plain_provider_yaml = R"( +%YAML 1.1 +--- +name: PlainRunner +spec_type: provider +spec_version: 1.2 +description: Base plain provider. +implements: plain_capabilities/PlainRunner +runner: capabilities2_runner::PlainRunner +definition: + command: "" + configuration_parameters: + - name: value + type: string + description: Plain value. +)"; - for (const auto& s : node.get_semantic_interfaces("std_capabilities/empty")) - { - std::cout << s << std::endl; - } + db.insert_interface(load_interface(waypoint_interface_yaml, "test_capabilities")); + db.insert_semantic_interface(load_semantic_interface(turtlebot_waypoint_semantic_yaml, "test_semantic_capabilities")); + db.insert_provider(load_provider(waypoint_provider_yaml, "test_capabilities")); + db.insert_interface(load_interface(robotpose_interface_yaml, "test_capabilities")); + db.insert_semantic_interface(load_semantic_interface(turtlebot_robotpose_semantic_yaml, "test_semantic_capabilities")); + db.insert_provider(load_provider(robotpose_provider_yaml, "test_capabilities")); + db.insert_interface(load_interface(plain_interface_yaml, "plain_capabilities")); + db.insert_provider(load_provider(plain_provider_yaml, "plain_capabilities")); - for (const auto& p : node.get_providers("std_capabilities/empty", true)) - { - std::cout << p << std::endl; - } + const auto runnable_specs = db.get_runnable_specs(); + assert(runnable_specs.size() == 3); - capabilities2_msgs::msg::CapabilitySpec s = node.get_capability_spec("std_capabilities/empty"); - std::cout << s.content << std::endl; - std::cout << "\n" << std::endl; + const auto find_runnable = [&runnable_specs](const std::string& interface_name, const std::string& provider_name) { + return std::find_if(runnable_specs.begin(), runnable_specs.end(), + [&interface_name, &provider_name](const auto& runnable) { + return runnable.interface.name == interface_name && runnable.provider.name == provider_name; + }); + }; - std::vector specs = node.get_capability_specs(); + const auto turtlebot_waypoint = + find_runnable("test_semantic_capabilities/TurtlebotWaypointRunner", "test_capabilities/WaypointRunner"); + assert(turtlebot_waypoint != runnable_specs.end()); + assert(turtlebot_waypoint->command.find("interface=test_semantic_capabilities/TurtlebotWaypointRunner") != + std::string::npos); + assert(turtlebot_waypoint->command.find("provider=test_capabilities/WaypointRunner") != std::string::npos); - for (const auto& s : specs) - { - std::cout << "package: " << s.package << std::endl; - std::cout << "type: " << s.type << std::endl; - std::cout << "content: " << s.content << std::endl; - } + const auto turtlebot_robotpose = + find_runnable("test_semantic_capabilities/TurtlebotRobotposeRunner", "test_capabilities/RobotPoseRunner"); + assert(turtlebot_robotpose != runnable_specs.end()); + assert(turtlebot_robotpose->command.find("interface=test_semantic_capabilities/TurtlebotRobotposeRunner") != + std::string::npos); + assert(turtlebot_robotpose->command.find("provider=test_capabilities/RobotPoseRunner") != std::string::npos); - rclcpp::shutdown(); + const auto plain_runnable = find_runnable("plain_capabilities/PlainRunner", "plain_capabilities/PlainRunner"); + assert(plain_runnable != runnable_specs.end()); + assert(plain_runnable->command.find("interface=plain_capabilities/PlainRunner") != std::string::npos); + assert(plain_runnable->command.find("provider=plain_capabilities/PlainRunner") != std::string::npos); + std::filesystem::remove(db_path); + std::cout << "Resolved runnable spec test passed" << std::endl; return 0; } diff --git a/docs/interfaces.md b/docs/interfaces.md index 066fdfc..98d1a94 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -12,7 +12,7 @@ An capability interface describes the capability. It relates ROS primitives to t --- name: empty spec_type: interface -spec_version: 1.1 +spec_version: 1.2 description: the empty capability interface helps to test the capability server interface: parameters: diff --git a/docs/models/model.md b/docs/models/model.md new file mode 100644 index 0000000..939314a --- /dev/null +++ b/docs/models/model.md @@ -0,0 +1,186 @@ +```mermaid +erDiagram + %% Qualifier convention used below: + %% PK, FK, NOT NULL, NULLABLE, UNIQUE, CHECK, INDEX, COMPOSITE UNIQUE + + %% Shared supertype for all first-class capability entities + CAPABILITY_ENTITY { + bigint id PK "NOT NULL" + string version "NOT NULL" + string entity_type "NOT NULL, CHECK in ('interface','semantic_interface','provider')" + datetime created_at "NOT NULL" + datetime updated_at "NOT NULL" + datetime deleted_at "NULLABLE, soft delete marker" + } + + %% Contract hierarchy remains separate from providers + CAPABILITY_CONTRACT { + bigint id PK, FK "to CAPABILITY_ENTITY.id, NOT NULL" + string contract_type "NOT NULL, CHECK in ('interface','semantic_interface')" + } + + INTERFACE { + bigint id PK, FK "to CAPABILITY_CONTRACT.id, NOT NULL" + string name UK "NOT NULL" + string description "NULLABLE" + } + + SEMANTIC_INTERFACE { + bigint id PK, FK "to CAPABILITY_CONTRACT.id, NOT NULL" + string name UK "NOT NULL" + string description "NULLABLE" + bigint redefines FK "to INTERFACE.id, NOT NULL" + string global_namespace "NULLABLE" + } + + PROVIDER { + bigint id PK, FK "to CAPABILITY_ENTITY.id, NOT NULL" + string name UK "NOT NULL" + string description "NULLABLE" + bigint implements FK "to CAPABILITY_CONTRACT.id, NOT NULL, INDEX" + string runner "NOT NULL" + } + + %% V1.2 + INTERFACE_RESOURCE { + bigint id PK "NOT NULL" + bigint interface_id FK "to INTERFACE.id, NOT NULL, INDEX" + string resource_kind "NOT NULL, CHECK in ('parameter','topic','service','action')" + string name "NOT NULL" + string type "NOT NULL" + string description "NULLABLE" + } + %% INTERFACE_RESOURCE: COMPOSITE UNIQUE (interface_id, resource_kind, name) + + PROVIDER_REMAPPING { + bigint id PK "NOT NULL" + bigint provider_id FK "to PROVIDER.id, NOT NULL, INDEX" + bigint interface_resource_id FK "to INTERFACE_RESOURCE.id, NOT NULL, INDEX" + string target_name "NOT NULL" + } + %% PROVIDER_REMAPPING: COMPOSITE UNIQUE (provider_id, interface_resource_id) + + SEMANTIC_INTERFACE_REMAPPING { + bigint id PK "NOT NULL" + bigint semantic_interface_id FK "to SEMANTIC_INTERFACE.id, NOT NULL, INDEX" + bigint interface_resource_id FK "to INTERFACE_RESOURCE.id, NOT NULL, INDEX" + string target_name "NOT NULL" + } + %% SEMANTIC_INTERFACE_REMAPPING: COMPOSITE UNIQUE (semantic_interface_id, interface_resource_id) + + %% V2 + PREDICATE { + bigint id PK "NOT NULL" + bigint subject_entity_id FK "to CAPABILITY_ENTITY.id, NOT NULL, INDEX" + string predicate "NOT NULL, INDEX" + bigint object_entity_id FK "to CAPABILITY_ENTITY.id, NOT NULL, INDEX" + } + %% PREDICATE: COMPOSITE UNIQUE (subject_entity_id, predicate, object_entity_id) + + CAPABILITY_SPEC_RAW { + bigint id PK, FK "to CAPABILITY_ENTITY.id, NOT NULL" + string content_hash "NOT NULL, INDEX" + string raw_yaml "NOT NULL" + datetime created_at "NOT NULL" + datetime updated_at "NOT NULL" + } + + DEFAULT_PROVIDER_POLICY { + bigint id PK "NOT NULL" + bigint contract_id FK "to CAPABILITY_CONTRACT.id, NOT NULL, INDEX" + bigint default_provider_id FK "to PROVIDER.id, NOT NULL" + bigint fallback_provider_id FK "to PROVIDER.id, NULLABLE" + } + %% DEFAULT_PROVIDER_POLICY: COMPOSITE UNIQUE (contract_id) + + ASSURANCE { + bigint id PK "NOT NULL" + bigint provider_id FK "to PROVIDER.id, NOT NULL, INDEX" + string metric_name "NOT NULL" + string metric_value "NOT NULL" + string metric_unit "NULLABLE" + datetime measured_at "NOT NULL, INDEX" + } + %% ASSURANCE: COMPOSITE INDEX (provider_id, metric_name, measured_at) + + %% V3 + RUNNING { + bigint id PK "NOT NULL" + bigint interface_contract_id FK "to CAPABILITY_CONTRACT.id, NOT NULL, INDEX" + bigint provider_id FK "to PROVIDER.id, NOT NULL, INDEX" + string started_by "NOT NULL" + string pid "NULLABLE" + string status "NOT NULL, CHECK in ('starting','running','stopping','stopped','failed')" + datetime started_at "NOT NULL, INDEX" + datetime stopped_at "NULLABLE" + } + +%% connection between capabilities (contracts) that can be used for orchestration and composition +%% a connection is made when a connection service request is made by a client with a bond + CONNECTION { + bigint id PK "NOT NULL" + bigint from_contract_id FK "to CAPABILITY_CONTRACT.id, NOT NULL, INDEX" + bigint to_contract_id FK "to CAPABILITY_CONTRACT.id, NOT NULL, INDEX" + string connection_type "NOT NULL" + } + %% CONNECTION: COMPOSITE UNIQUE (from_contract_id, to_contract_id, connection_type) + + DEFINITION { + bigint id PK "NOT NULL" + bigint provider_id FK, UK "to PROVIDER.id, NOT NULL" + string definition_text "NOT NULL" + string format "NOT NULL" + } + + PARAMETER { + bigint id PK "NOT NULL" + bigint running_id FK "to RUNNING.id, NOT NULL, INDEX" + string name "NOT NULL" + string value_type "NOT NULL" + string value_text "NULLABLE" + string source "NULLABLE" + } + %% PARAMETER: COMPOSITE UNIQUE (running_id, name) + + %% One entity record per contract/provider specialization + CAPABILITY_ENTITY ||--|| CAPABILITY_CONTRACT : specializes + CAPABILITY_ENTITY ||--|| PROVIDER : specializes + + %% Contract specializations and implementation binding + CAPABILITY_CONTRACT ||--|| INTERFACE : specializes + CAPABILITY_CONTRACT ||--|| SEMANTIC_INTERFACE : specializes + CAPABILITY_CONTRACT ||--o{ PROVIDER : implemented_by + + %% Interface extension and decomposition + INTERFACE ||--o{ INTERFACE_RESOURCE : has + INTERFACE ||--o{ SEMANTIC_INTERFACE : redefined_by + + %% Remapping ownership + PROVIDER ||--o{ PROVIDER_REMAPPING : remaps + SEMANTIC_INTERFACE ||--o{ SEMANTIC_INTERFACE_REMAPPING : remaps + INTERFACE_RESOURCE ||--o{ PROVIDER_REMAPPING : remapped_from + INTERFACE_RESOURCE ||--o{ SEMANTIC_INTERFACE_REMAPPING : remapped_from + + %% Predicate graph and raw spec history + CAPABILITY_ENTITY ||--o{ PREDICATE : subject + CAPABILITY_ENTITY ||--o{ PREDICATE : object + CAPABILITY_ENTITY ||--o{ CAPABILITY_SPEC_RAW : stores + + %% Default/fallback provider policy per contract + CAPABILITY_CONTRACT ||--o{ DEFAULT_PROVIDER_POLICY : policy + PROVIDER ||--o{ DEFAULT_PROVIDER_POLICY : default + PROVIDER ||--o{ DEFAULT_PROVIDER_POLICY : fallback + + %% Provider telemetry + PROVIDER ||--o{ ASSURANCE : reports + + %% Runtime execution and orchestration + CAPABILITY_CONTRACT ||--o{ RUNNING : runs_as + PROVIDER ||--o{ RUNNING : executes + CAPABILITY_CONTRACT ||--o{ CONNECTION : source + CAPABILITY_CONTRACT ||--o{ CONNECTION : target + + %% Provider definition and runtime parameterization + PROVIDER ||--o| DEFINITION : has + RUNNING ||--o{ PARAMETER : has +``` diff --git a/docs/models/readme.md b/docs/models/readme.md new file mode 100644 index 0000000..6f3e1a8 --- /dev/null +++ b/docs/models/readme.md @@ -0,0 +1,83 @@ +# Capabilities2 Models + +This directory contains the data models used by the Capabilities2 server. + +## Models + +| Model | Description | +|-------|-------------| +| `provider` | Represents a provider of an interface | +| `interface` | Represents a capability interface | +| `semantic_interface` | Represents a semantic capability interface | + +### V1.2 new models (TODO) + +| Model | Description | +|-------|-------------| +| `interface_resources` | Represents a remmapable resource such as topic, service, action | +| `provider_remmapings` | Represents remappings for a provider such as topic, service, action remappings | +| `semantic_interface_remmapings` | Represents remappings for a semantic interface such as topic, service, action remappings | + +### V2 new models (TODO) + +| Model | Description | +|-------|-------------| +| `predicates` | Represents predicates between capabilities | +| `assurances` | Represents assurances for capabilities such as success rate, run time, resource use | + +### V3 new models (TODO)(Proposal) + +| Model | Description | +|-------|-------------| +| `running` | Represents active runners that are executing capabilities | +| `connections` | Represents connections between active runners | +| `definition` | model text defining function of capability | +| `parameters` | parameters of a capability | + +## Traits + +The models can implement various traits to provide additional functionality. The available traits are: + +| Trait | Description | +|-------|-------------| +| `identifiable` | Allows the model to have a unique identifier | +| `modifiable` | Adds created and modified timestamps | +| `soft_deleteable` | Allows the model to be soft deleted | +| `header` | Adds a header to the model including name, description, and version etc. The header uses id, created, and deleted timestamps | +| `remappable` | Allows the model to have remappings | + +### V2 new traits (TODO) + +| Trait | Description | +|-------|-------------| +| `predicateable` | Allows the model to use subject-predicate relationships | +| `assurable` | Adds tracking metrics for capability performance | + +## Relationships + +The models can have relationships with each other. The available relationships are: + +| Relationship | Description | +|--------------|-------------| +| `implements` | A provider implements an interface | +| `depends_on` | A provider depends on another provider | +| `redefines` | A semantic interface redefines an interface | + +### V2 new relationships (TODO) + +| Relationship | Description | +|--------------|-------------| +| `predicate` | A relationship between capabilities defined by a predicate | + +## V2 milestones + +Each milestone will have a testing check gate before moving to the next milestone. The milestones are: + +0. fix sql injection vulnerabilities by changing '+' string concatenation to parameterized queries + 0.1 dont throw away yaml spec not specced yet, (forward compatibility) + 0.2 +1. implement traits in table schema + 1.1 redesign ORM classes to work better with traits and relationships +2. fix current 3 model relations including inheritance relations and move join relations to separate tables rather than sorted in db api handler code + 2.1 add new models from model.erd +3. surface parameterised queries to enable selecting just values from specific columns diff --git a/docs/providers.md b/docs/providers.md index e74bb29..db95c53 100644 --- a/docs/providers.md +++ b/docs/providers.md @@ -12,7 +12,7 @@ A provider is a special implementation of a capability that is specific to the c --- name: empty spec_type: provider -spec_version: 1.1 +spec_version: 1.2 description: the empty capability provider for the empty interface implements: std_capabilities/empty runner: launch/empty.launch.py @@ -39,10 +39,147 @@ relations: object: std_capabilities/not_empty # providers can also have a definition using a snippet of a relevant defining language such as behavior trees -definition: | - - - - - +definition: + command: "" + configuration_parameters: + - name: param1 + type: string + description: static fallback value for the main text input + semantic_key: workflow.text + - name: param2 + type: float + description: local configuration threshold for this provider + semantic_key: provider.threshold + default: 0.5 + runtime_parameters: + input: + - name: param1 + type: string + description: runtime text consumed during execution + semantic_key: workflow.text + required: true + satisfiable_from: [upstream, configuration] + fallback_parameter: param1 + - name: param3 + type: string + description: optional context value produced outside the current capability chain + semantic_key: workflow.context.label + required: false + satisfiable_from: [upstream, external] + output: + - name: param4 + type: float + description: score produced by this provider for downstream consumption + semantic_key: workflow.score + aliases: [score] ``` + +## Parameter Role Fields + +The provider definition separates `configuration_parameters` from `runtime_parameters`. +That split is the primary contract. + +The missing piece is how to describe a runtime input that may also be satisfied by static configuration or a default value. + +The spec keeps the existing sections and adds optional fields to each parameter entry. + +### Optional Fields + +- `semantic_key`: Stable semantic identifier used for cross-capability matching and graph relations. If omitted, `name` is used as the fallback identity. +- `required`: Declares whether the parameter must be satisfied for valid execution. This is primarily meaningful for runtime inputs. +- `satisfiable_from`: Declares allowed sources for satisfying a runtime input. Recommended values are any combination of the following: + - `upstream`: The runtime input may be satisfied by a matching runtime output from an upstream capability. + - `configuration`: The runtime input may be satisfied by a matching configuration parameter from the same provider. + - `external`: The runtime input may be satisfied by an external source outside the current capability chain. + - `default`: The runtime input may be satisfied by a default value declared on the parameter itself or on a fallback configuration parameter. +- `fallback_parameter`: Names the configuration parameter that may satisfy this runtime input when no upstream producer is connected. +- `aliases`: Optional alternative names that may be used during semantic matching or migration. +- `default`: Optional default value when the parameter can be satisfied locally without an upstream producer. + +### Collection Type Convention + +Provider parameter `type` values are stored as free-form strings in the current server implementation. +For collection payloads, use the following explicit convention in YAML: + +- `string[]`: ordered string vector +- `double[]`: ordered floating-point vector +- `int[]`: ordered integer vector +- `boolean[]`: ordered boolean vector + +This convention maps to the event parameter vector variants in `capabilities2_events::OptionType`: + +- `string[]` -> `VECTOR_STRING` +- `double[]` -> `VECTOR_DOUBLE` +- `int[]` -> `VECTOR_INT` +- `boolean[]` -> `VECTOR_BOOL` + +Use YAML sequences for defaults when a collection parameter has a local default, for example `default: []`. + +### Semantics + +- Parameter role is still determined by where the parameter is declared: `configuration_parameters`, `runtime_parameters.input`, or `runtime_parameters.output`. +- Configuration parameters do not create cross-capability data-flow edges by themselves. +- Runtime output to runtime input matches create candidate data-flow edges. +- A runtime input may share the same `name` as a configuration parameter if the runtime input explicitly declares how configuration may satisfy it. +- `semantic_key` is the preferred identity for retrieval and validation. `name` remains the local binding name used by the runner. + +### Example: Common Parameter With Configuration Fallback + +```yaml +definition: + command: "" + configuration_parameters: + - name: text + type: string + description: Static fallback text used when no upstream runtime text is provided. + semantic_key: prompt.text + - name: uuid + type: string + description: Optional cache identifier used to bind prompt state across capabilities. + semantic_key: prompt.cache.uuid + - name: flush + type: boolean + description: Flush the prompt cache after execution. + semantic_key: prompt.cache.flush + default: false + runtime_parameters: + input: + - name: text + type: string + description: Text payload consumed during execution. + semantic_key: prompt.text + required: true + satisfiable_from: [upstream, configuration] + fallback_parameter: text + output: + - name: response + type: string + description: Prompt response returned by the provider. + semantic_key: prompt.response +``` + +### Example: Vector Runtime Output + +```yaml +definition: + runtime_parameters: + output: + - name: joint_names + type: string[] + description: Ordered joint names produced by the runner. + semantic_key: robot.joints.names + - name: joint_positions + type: double[] + description: Ordered joint positions in radians matching joint_names. + semantic_key: robot.joints.positions +``` + +### Interpretation For Common Parameters + +When the same logical datum appears in both config and runtime sections, treat it as one semantic parameter with multiple allowed satisfaction paths: + +- runtime flow is preferred when an upstream capability produces a matching output, +- configuration fallback is allowed only when the runtime input explicitly permits it, +- default satisfaction is allowed only when declared on the receiving parameter or its fallback configuration parameter. + +This keeps execution binding simple while still allowing retrieval and validation to reason about real data flow. diff --git a/docs/runnable.md b/docs/runnable.md new file mode 100644 index 0000000..88bf62f --- /dev/null +++ b/docs/runnable.md @@ -0,0 +1,16 @@ +# Runnable Information + +This provides information about the runnable capabilities in the system. The `get_runnable_specs` service returns runnable specifications for invokable interface and provider pairs. Because ROS service responses do not expose a map type here, the response uses two parallel arrays: + +- `index_of_specs`: keys in the form `interface_name|provider_name` +- `runnable_specs`: matching `RunnableSpec` messages containing the runnable YAML string + +```bash +source install/setup.bash +ros2 launch capabilities2_server capabilities2_server.launch.py +``` + +```bash +source install/setup.bash +ros2 service call /capabilities/get_runnable_specs capabilities2_msgs/srv/GetRunnableSpecs +``` \ No newline at end of file diff --git a/docs/semantic_provider.md b/docs/semantic_provider.md new file mode 100644 index 0000000..d90bd8d --- /dev/null +++ b/docs/semantic_provider.md @@ -0,0 +1,249 @@ +# (Proposed) Semantic Providers + +## Description + +A semantic provider is a provider specialization mechanism. + +It is not the default way to represent an alternative backend or algorithm. A different backend for the same capability should usually be modeled as another ordinary provider of the same interface. + +A semantic provider exists to express a provider-side delta for a specialized capability variant while preserving the standard split between: + +- interface: the capability contract +- semantic interface: a refined or remapped capability contract +- provider: a concrete implementation of a capability contract +- semantic provider: a provider that extends a base provider and explicitly binds to an invokable interface + +This keeps interface semantics separate from implementation choice. + +## When To Use A Semantic Provider + +Use a semantic provider when a specialization must change provider-owned behavior without redefining the entire provider from scratch. + +Typical cases include: + +- different runner implementation +- different `definition.command` +- different configuration defaults +- different dependency selection +- additional provider-level remappings +- a deployment-specific specialization of an existing provider + +Do not use a semantic provider just to represent a different algorithm for the same contract. +If the contract is unchanged and only the implementation differs, create another ordinary provider for the same interface. + +## Model + +The recommended capability model is: + +- base interface: the canonical contract +- semantic interface: a contract refinement or remapped variant of that interface +- provider: a concrete implementation of an interface contract +- semantic provider: a provider specialization that extends a base provider and must still explicitly declare which interface it implements + +This enables the following valid combinations: + +- `interface + provider` +- `semantic interface + provider` +- `semantic interface + semantic provider` + +The following should not be inferred automatically unless explicitly declared as valid: + +- every provider paired with every semantic interface redefining its base interface +- every semantic provider paired with every semantic interface in the same family + +Discovery should surface only interface and provider pairings that the system can prove are invokable. + +## Proposed Spec + +```yaml +%YAML 1.1 +--- +name: turtlebot_waypoint_nav2 +spec_type: semantic_provider +spec_version: 1.0 +description: TurtleBot-specific specialization of the default Nav2 waypoint provider. + +# The semantic provider extends an existing base provider. +extends: nav2_capabilities/WaypointRunner + +# The semantic provider must explicitly bind to the interface contract it implements. +# This may be a base interface or a semantic interface. +implements: turtlebot_capabilities/TurtlebotWaypointRunner + +# Optional override of the runner implementation. +runner: capabilities2_runner::WaypointRunner + +# Optional provider-local remappings layered after interface-side remappings. +remappings: + actions: + "/navigate_to_pose": "/turtlebot4/navigate_to_pose" + +# Optional dependency override. +depends_on: + "nav2_capabilities/Nav2LaunchRunner": + provider: "turtlebot_capabilities/TurtlebotNav2LaunchRunner" + +# Optional provider definition override. +definition: + command: "" + configuration_parameters: + - name: x + type: double + semantic_key: nav2.waypoint.x + description: TurtleBot target x position in meters. + - name: y + type: double + semantic_key: nav2.waypoint.y + description: TurtleBot target y position in meters. +``` + +## Required Fields + +- `name`: semantic provider name +- `spec_type`: must be `semantic_provider` +- `spec_version`: semantic provider schema version +- `extends`: the base provider being specialized +- `implements`: the interface or semantic interface this provider explicitly supports + +## Optional Fields + +- `description` +- `runner` +- `depends_on` +- `remappings` +- `definition` +- `relations` + +## Inheritance Rules + +A semantic provider should inherit from its base provider and then apply its own overrides. + +Recommended precedence, lowest to highest: + +1. base interface +2. semantic interface, if used +3. base provider +4. semantic provider + +This means: + +- interface resources are defined by the base interface +- semantic interface remappings refine the interface-side contract +- provider remappings and provider definition fields come from the base provider +- semantic provider overrides apply last + +## Resolution Rules + +### Runtime Resolution + +The runtime should resolve an invokable capability in this order: + +1. resolve the requested interface or semantic interface +2. resolve the selected provider or semantic provider +3. verify that the provider explicitly implements the requested interface, or that the pairing is explicitly declared valid +4. build the resolved interface view by applying semantic-interface remappings to the base interface +5. build the resolved provider view by inheriting the base provider and applying semantic-provider overrides +6. apply provider-side remappings to the resolved interface view +7. build the run configuration from the resolved interface plus resolved provider + +### Discovery Resolution + +Runnable discovery should enumerate invokable pairs, not raw providers. + +For each ordinary provider: + +1. emit `interface + provider` for the interface explicitly implemented by that provider +2. optionally emit `semantic interface + provider` only when that pairing is explicitly valid by declaration or compatibility policy + +For each semantic provider: + +1. resolve the inherited provider chain +2. emit only the interface named by the semantic provider's `implements` +3. do not infer compatibility with sibling semantic interfaces + +This avoids the incorrect assumption that every semantic variant is valid for every provider variant. + +## Validity Rules + +The system should only expose a runnable spec when the interface and provider pairing can be proven valid. + +Recommended proof rules: + +### `interface + provider` + +Valid when: + +- the provider explicitly implements that interface + +### `semantic interface + provider` + +Valid when: + +- the provider implements the semantic interface's base interface +- the semantic interface redefines that base interface +- the provider does not declare incompatibility +- the system policy allows that inference, or the pairing is explicitly declared + +### `semantic interface + semantic provider` + +Valid when: + +- the semantic provider explicitly declares `implements` equal to that semantic interface +- the semantic provider's `extends` chain resolves successfully +- all inherited and overridden fields remain internally consistent + +This pairing should come from explicit declaration, not inference. + +## Why Explicit `implements` Matters + +A semantic provider must explicitly declare `implements` even though it also declares `extends`. + +That explicit binding prevents ambiguity in cases where: + +- one base provider has several semantic specializations +- multiple semantic interfaces redefine the same base interface +- a semantic provider changes the execution path enough that only one specialization remains valid + +Without explicit `implements`, discovery and runtime would need to guess which semantic contract the provider is meant to satisfy. + +## Recommended Storage Model + +If semantic providers are added to the data model, treat them as provider specializations rather than as semantic interfaces. + +A reasonable conceptual schema is: + +- provider + - `name` + - `implements` + - `runner` + - `depends_on` + - `remappings` + - `definition` +- semantic provider + - `name` + - `extends` + - `implements` + - optional overrides for `runner`, `depends_on`, `remappings`, and `definition` + +This keeps contract-level inheritance separate from implementation-level inheritance. + +## Recommended Constraints + +- a semantic provider should extend exactly one provider +- a semantic provider should implement exactly one interface or semantic interface +- circular provider inheritance should be rejected +- missing `extends` targets should be rejected +- incompatible `implements` chains should be rejected +- dependency override semantics should be deterministic and documented + +## Compatibility Notes + +The standard provider for a capability remains useful and should continue to exist as the canonical, non-specialized implementation. + +This gives a stable baseline: + +- base interface + base provider: standard capability +- semantic interface + base provider: contract specialization without provider specialization +- semantic interface + semantic provider: contract specialization plus provider specialization + +That structure supports deployment-specific tuning without collapsing interface semantics into provider choice. \ No newline at end of file