Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions docs/config/server.rst
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ The gateway can be configured via:
Out-of-range values
-------------------

Every ``server.*``, ``sse.*`` and ``docs.*`` parameter is read once, when the
gateway starts. A later ``ros2 param set`` does not change the running server.

Where a parameter documents a valid range, that range is enforced when the value
is read at startup, and an out-of-range value is never accepted in silence. What
happens next differs by parameter, in one of three ways.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,24 @@

#pragma once

#include <cstdint>
#include <string>
#include <vector>

namespace ros2_medkit_gateway {

/// Raw configuration values the REST layer reads. Clamping happens where the value is used.
struct RestConfig {
int64_t http_thread_pool_size{2};
int64_t keep_alive_timeout_sec{2};
int64_t sse_keepalive_interval_sec{30};
int64_t sse_max_duration_sec{3600};
bool docs_enabled{true};
std::string server_host{"localhost"};
int64_t server_port{8080};
std::string fault_events_topic;
};

/**
* @brief TLS/HTTPS configuration settings
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

#include <httplib.h>

#include <cstdint>
#include <memory>

#include <nlohmann/json.hpp>
Expand Down Expand Up @@ -47,7 +48,8 @@ namespace handlers {
class DocsHandlers {
public:
DocsHandlers(HandlerContext & ctx, GatewayNode & node, PluginManager * plugin_mgr,
const openapi::RouteRegistry * route_registry = nullptr);
const openapi::RouteRegistry * route_registry, bool docs_enabled, std::string server_host,
int64_t server_port);
~DocsHandlers();

/// GET /docs - Root capability description.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,9 +53,10 @@ class HealthHandlers {
/// @param sse_tracker Shared SSE client counter, so /health can report how
/// much of `sse.max_clients` is in use. Optional: a gateway built without
/// one simply omits the field.
/// @param docs_enabled Value of `docs.enabled`; hides the Swagger UI entry when false.
explicit HealthHandlers(HandlerContext & ctx, const openapi::RouteRegistry * route_registry = nullptr,
std::shared_ptr<const SSEClientTracker> sse_tracker = nullptr)
: ctx_(ctx), route_registry_(route_registry), sse_tracker_(std::move(sse_tracker)) {
std::shared_ptr<const SSEClientTracker> sse_tracker = nullptr, bool docs_enabled = true)
: ctx_(ctx), route_registry_(route_registry), sse_tracker_(std::move(sse_tracker)), docs_enabled_(docs_enabled) {
}

/// GET /health - Health check endpoint
Expand All @@ -71,6 +72,7 @@ class HealthHandlers {
HandlerContext & ctx_;
const openapi::RouteRegistry * route_registry_{nullptr};
std::shared_ptr<const SSEClientTracker> sse_tracker_;
bool docs_enabled_;
};

} // namespace handlers
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ class TriggerManager;
class RESTServer {
public:
RESTServer(GatewayNode * node, const std::string & host, int port, const CorsConfig & cors_config,
const AuthConfig & auth_config, const RateLimitConfig & rate_limit_config,
const AuthConfig & auth_config, const RateLimitConfig & rate_limit_config, const RestConfig & rest_config,
const TlsConfig & tls_config = TlsConfig{});
~RESTServer();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,16 +81,19 @@ class SSEFaultHandler {
* @brief Construct SSE fault handler with shared context.
* @param ctx The shared handler context
* @param client_tracker Shared SSE client counter (across all SSE handlers)
* @param fault_events_topic Fully qualified topic the FaultManager publishes fault events on
*/
SSEFaultHandler(HandlerContext & ctx, std::shared_ptr<SSEClientTracker> client_tracker);
SSEFaultHandler(HandlerContext & ctx, std::shared_ptr<SSEClientTracker> client_tracker,
const std::string & fault_events_topic);
/**
* @brief Test-only constructor that overrides the keepalive interval.
* @param ctx The shared handler context
* @param client_tracker Shared SSE client counter (across all SSE handlers)
* @param keepalive_interval Must be positive; non-positive values fall back to the 30s default.
* @param fault_events_topic Fully qualified topic the FaultManager publishes fault events on
*/
SSEFaultHandler(HandlerContext & ctx, std::shared_ptr<SSEClientTracker> client_tracker,
std::chrono::milliseconds keepalive_interval);
std::chrono::milliseconds keepalive_interval, const std::string & fault_events_topic);

/// Destructor. Signals shutdown, then blocks until every stream closure has
/// been destroyed: the per-stream unregister deleter locks queue_mutex_ and
Expand Down
13 changes: 12 additions & 1 deletion src/ros2_medkit_gateway/src/gateway_node.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@
#include "ros2_medkit_gateway/core/faults/fault_scope.hpp"
#include "ros2_medkit_gateway/core/logs/log_scope.hpp"
#include "ros2_medkit_gateway/core/thread_pool_config.hpp"
#include "ros2_medkit_gateway/fault_manager_paths.hpp"
#include "ros2_medkit_gateway/param_utils.hpp"
#include "ros2_medkit_gateway/plugins/ros_plugin_context.hpp"
#include "ros2_medkit_gateway/ros2/ros2_log_sink.hpp"
Expand Down Expand Up @@ -1570,8 +1571,18 @@ GatewayNode::GatewayNode(const rclcpp::NodeOptions & options) : Node("ros2_medki
});

// Start REST server with configured host, port, CORS, auth, and TLS
RestConfig rest_config;
rest_config.http_thread_pool_size = get_parameter("server.http_thread_pool_size").as_int();
rest_config.keep_alive_timeout_sec = get_parameter("server.keep_alive_timeout_sec").as_int();
rest_config.sse_keepalive_interval_sec = get_parameter("sse.keepalive_interval_sec").as_int();
rest_config.sse_max_duration_sec = get_parameter("sse.max_duration_sec").as_int();
rest_config.docs_enabled = get_parameter("docs.enabled").as_bool();
rest_config.server_host = server_host_;
rest_config.server_port = server_port_;
rest_config.fault_events_topic = build_fault_manager_events_topic(this);

rest_server_ = std::make_unique<RESTServer>(this, server_host_, server_port_, cors_config_, auth_config_,
rate_limit_config_, tls_config_);
rate_limit_config_, rest_config, tls_config_);

// Wire trigger handlers into REST server
if (trigger_mgr_) {
Expand Down
16 changes: 5 additions & 11 deletions src/ros2_medkit_gateway/src/http/handlers/docs_handlers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -59,18 +59,12 @@ void DocsHandlers::write_error(httplib::Response & res, int status, const std::s
}

DocsHandlers::DocsHandlers(HandlerContext & ctx, GatewayNode & node, PluginManager * plugin_mgr,
const openapi::RouteRegistry * route_registry)
const openapi::RouteRegistry * route_registry, bool docs_enabled, std::string server_host,
int64_t server_port)
: ctx_(ctx)
, generator_(std::make_unique<openapi::CapabilityGenerator>(ctx, node, plugin_mgr, route_registry))
, docs_enabled_(true) {
// Read docs.enabled parameter if it has been declared
try {
docs_enabled_ = node.get_parameter("docs.enabled").as_bool();
} catch (const std::exception &) {
docs_enabled_ = true; // Parameter may not be declared - default to enabled
} catch (...) {
docs_enabled_ = true;
}
, generator_(std::make_unique<openapi::CapabilityGenerator>(ctx, node, plugin_mgr, route_registry,
std::move(server_host), server_port))
, docs_enabled_(docs_enabled) {
}

DocsHandlers::~DocsHandlers() = default;
Expand Down
10 changes: 1 addition & 9 deletions src/ros2_medkit_gateway/src/http/handlers/health_handlers.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -265,15 +265,7 @@ http::Result<dto::RootOverview> HealthHandlers::get_root(const http::TypedReques
// and it is the only endpoint `docs.enabled` now hides from this list. The
// `/docs` routes stay listed when the capability is off, because they stay
// mounted and answer 501: this list says what is mounted, not what is on.
bool docs_enabled = true;
if (ctx_.node()) {
try {
docs_enabled = ctx_.node()->get_parameter("docs.enabled").as_bool();
} catch (...) {
// Parameter may not be declared - default to true
}
}
if (docs_enabled) {
if (docs_enabled_) {
endpoints.push_back("GET " + std::string(API_BASE_PATH) + "/swagger-ui");
}
#endif
Expand Down
10 changes: 4 additions & 6 deletions src/ros2_medkit_gateway/src/http/handlers/sse_fault_handler.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,6 @@
#include "ros2_medkit_gateway/core/http/error_codes.hpp"
#include "ros2_medkit_gateway/core/http/http_utils.hpp"
#include "ros2_medkit_gateway/core/models/error_info.hpp"
#include "ros2_medkit_gateway/fault_manager_paths.hpp"
#include "ros2_medkit_gateway/gateway_node.hpp"
#include "ros2_medkit_gateway/http/detail/primitives.hpp"
#include "ros2_medkit_gateway/ros2/conversions/fault_msg_conversions.hpp"
Expand All @@ -50,12 +49,13 @@ std::string sanitize_sse_event_type(std::string event_type) {

} // namespace

SSEFaultHandler::SSEFaultHandler(HandlerContext & ctx, std::shared_ptr<SSEClientTracker> client_tracker)
: SSEFaultHandler(ctx, std::move(client_tracker), std::chrono::seconds(kKeepaliveIntervalSec)) {
SSEFaultHandler::SSEFaultHandler(HandlerContext & ctx, std::shared_ptr<SSEClientTracker> client_tracker,
const std::string & fault_events_topic)
: SSEFaultHandler(ctx, std::move(client_tracker), std::chrono::seconds(kKeepaliveIntervalSec), fault_events_topic) {
}

SSEFaultHandler::SSEFaultHandler(HandlerContext & ctx, std::shared_ptr<SSEClientTracker> client_tracker,
std::chrono::milliseconds keepalive_interval)
std::chrono::milliseconds keepalive_interval, const std::string & fault_events_topic)
: ctx_(ctx)
, client_tracker_(std::move(client_tracker))
, keepalive_interval_(keepalive_interval > std::chrono::milliseconds::zero()
Expand All @@ -67,8 +67,6 @@ SSEFaultHandler::SSEFaultHandler(HandlerContext & ctx, std::shared_ptr<SSEClient
keepalive_interval.count(), kKeepaliveIntervalSec);
}

const auto fault_events_topic = build_fault_manager_events_topic(ctx_.node());

// Create subscription to fault events topic
// Use fully qualified topic name since FaultManager publishes on ~/events
subscription_ = ctx_.node()->create_subscription<ros2_medkit_msgs::msg::FaultEvent>(
Expand Down
21 changes: 11 additions & 10 deletions src/ros2_medkit_gateway/src/http/rest_server.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ static_assert(std::is_constructible_v<httplib::Server::ExceptionHandler, Httplib

RESTServer::RESTServer(GatewayNode * node, const std::string & host, int port, const CorsConfig & cors_config,
const AuthConfig & auth_config, const RateLimitConfig & rate_limit_config,
const TlsConfig & tls_config)
const RestConfig & rest_config, const TlsConfig & tls_config)
: node_(node)
, host_(host)
, port_(port)
Expand All @@ -104,13 +104,13 @@ RESTServer::RESTServer(GatewayNode * node, const std::string & host, int port, c
// (default 2s) to recover workers quickly while retaining reuse.
// Both clamps report when they fire: the pool that ends up serving requests
// must be traceable to the config file that asked for it.
const auto requested_pool_size = node_->get_parameter("server.http_thread_pool_size").as_int();
const auto requested_pool_size = rest_config.http_thread_pool_size;
const auto http_thread_pool_size = clamp_thread_count(requested_pool_size, 1, 1024);
if (static_cast<int64_t>(http_thread_pool_size) != requested_pool_size) {
MEDKIT_LOG_WARN(log::Logger("rest_server"), "server.http_thread_pool_size %" PRId64 " clamped to %zu",
requested_pool_size, http_thread_pool_size);
}
const auto requested_keep_alive = node_->get_parameter("server.keep_alive_timeout_sec").as_int();
const auto requested_keep_alive = rest_config.keep_alive_timeout_sec;
const auto keep_alive_timeout_sec = clamp_keep_alive_timeout(requested_keep_alive, 1, 3600);
if (static_cast<int64_t>(keep_alive_timeout_sec) != requested_keep_alive) {
MEDKIT_LOG_WARN(log::Logger("rest_server"), "server.keep_alive_timeout_sec %" PRId64 " clamped to %" PRId64,
Expand Down Expand Up @@ -179,8 +179,8 @@ RESTServer::RESTServer(GatewayNode * node, const std::string & host, int port, c
// HealthHandlers as a null pointer and silently omit the field.
sse_client_tracker_ = node_->get_sse_client_tracker();

health_handlers_ =
std::make_unique<handlers::HealthHandlers>(*handler_ctx_, route_registry_.get(), sse_client_tracker_);
health_handlers_ = std::make_unique<handlers::HealthHandlers>(*handler_ctx_, route_registry_.get(),
sse_client_tracker_, rest_config.docs_enabled);
discovery_handlers_ = std::make_unique<handlers::DiscoveryHandlers>(*handler_ctx_);
data_handlers_ = std::make_unique<handlers::DataHandlers>(*handler_ctx_);
lifecycle_handlers_ = std::make_unique<handlers::LifecycleHandlers>(
Expand All @@ -195,20 +195,20 @@ RESTServer::RESTServer(GatewayNode * node, const std::string & host, int port, c
// disagree with no way to see it from outside.
constexpr int64_t kMinKeepaliveSec = 1;
constexpr int64_t kMaxKeepaliveSec = 3600;
const int64_t keepalive_raw = node_->get_parameter("sse.keepalive_interval_sec").as_int();
const int64_t keepalive_raw = rest_config.sse_keepalive_interval_sec;
const int64_t keepalive_used = std::clamp<int64_t>(keepalive_raw, kMinKeepaliveSec, kMaxKeepaliveSec);
if (keepalive_used != keepalive_raw) {
MEDKIT_LOG_WARN(log::Logger(node_->get_logger().get_name()),
"sse.keepalive_interval_sec %" PRId64 " clamped to %" PRId64, keepalive_raw, keepalive_used);
}
sse_fault_handler_ = std::make_unique<handlers::SSEFaultHandler>(*handler_ctx_, sse_client_tracker_,
std::chrono::seconds(keepalive_used));
sse_fault_handler_ = std::make_unique<handlers::SSEFaultHandler>(
*handler_ctx_, sse_client_tracker_, std::chrono::seconds(keepalive_used), rest_config.fault_events_topic);
bulkdata_handlers_ = std::make_unique<handlers::BulkDataHandlers>(*handler_ctx_);
// Validated as int64 before narrowing: narrowing first wraps a value above
// INT_MAX into a small positive one that passes the check, so 4294967300
// would silently cap every subscription at 4 seconds. The warning names the
// requested value, otherwise the operator cannot tell which value was refused.
const int64_t max_duration_raw = node_->get_parameter("sse.max_duration_sec").as_int();
const int64_t max_duration_raw = rest_config.sse_max_duration_sec;
int max_duration_sec = 3600;
if (max_duration_raw < 1 || max_duration_raw > std::numeric_limits<int>::max()) {
MEDKIT_LOG_WARN(log::Logger("rest_server"),
Expand All @@ -232,7 +232,8 @@ RESTServer::RESTServer(GatewayNode * node, const std::string & host, int port, c
}

docs_handlers_ = std::make_unique<handlers::DocsHandlers>(*handler_ctx_, *node_, node_->get_plugin_manager(),
route_registry_.get());
route_registry_.get(), rest_config.docs_enabled,
rest_config.server_host, rest_config.server_port);

// Set up global error handlers for SOVD GenericError compliance
setup_global_error_handlers();
Expand Down
18 changes: 6 additions & 12 deletions src/ros2_medkit_gateway/src/openapi/capability_generator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -109,12 +109,15 @@ void for_each_operation(nlohmann::json & document, Visitor && visit) {
} // namespace

CapabilityGenerator::CapabilityGenerator(handlers::HandlerContext & ctx, GatewayNode & node, PluginManager * plugin_mgr,
const RouteRegistry * route_registry, DocsCacheBounds bounds)
const RouteRegistry * route_registry, std::string server_host,
int64_t server_port, DocsCacheBounds bounds)
: ctx_(ctx)
, node_(node)
, plugin_mgr_(plugin_mgr)
, route_registry_(route_registry)
, schema_builder_()
, server_host_(std::move(server_host))
, server_port_(server_port)
, bounds_(bounds) {
}

Expand Down Expand Up @@ -1104,17 +1107,8 @@ bool CapabilityGenerator::validate_entity_hierarchy(const ResolvedPath & resolve
// -----------------------------------------------------------------------------

std::string CapabilityGenerator::build_server_url() const {
// Read host/port independently so a missing host doesn't clobber a valid port
std::string host = "localhost";
int port = 8080;
try {
host = node_.get_parameter("server.host").as_string();
} catch (...) {
}
try {
port = static_cast<int>(node_.get_parameter("server.port").as_int());
} catch (...) {
}
std::string host = server_host_;
const int port = static_cast<int>(server_port_);

// Use localhost for display if bound to all interfaces
if (host == "0.0.0.0") {
Expand Down
5 changes: 4 additions & 1 deletion src/ros2_medkit_gateway/src/openapi/capability_generator.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,8 @@ struct DocsCacheBounds {
class CapabilityGenerator {
public:
CapabilityGenerator(handlers::HandlerContext & ctx, GatewayNode & node, PluginManager * plugin_mgr,
const RouteRegistry * route_registry = nullptr, DocsCacheBounds bounds = DocsCacheBounds{});
const RouteRegistry * route_registry, std::string server_host, int64_t server_port,
DocsCacheBounds bounds = DocsCacheBounds{});

/// Number of documents currently cached.
size_t cache_entry_count() const;
Expand Down Expand Up @@ -236,6 +237,8 @@ class CapabilityGenerator {
PluginManager * plugin_mgr_;
const RouteRegistry * route_registry_;
SchemaBuilder schema_builder_;
std::string server_host_;
int64_t server_port_;
DocsCacheBounds bounds_;

// Generation-based document cache - invalidated when entity cache changes.
Expand Down
17 changes: 12 additions & 5 deletions src/ros2_medkit_gateway/test/test_capability_generator.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,9 @@ class CapabilityGeneratorTest : public ::testing::Test {
route_registry_ = std::make_unique<RouteRegistry>();
populate_test_routes(*route_registry_);

generator_ =
std::make_unique<CapabilityGenerator>(*ctx_, *node_, node_->get_plugin_manager(), route_registry_.get());
generator_ = std::make_unique<CapabilityGenerator>(
*ctx_, *node_, node_->get_plugin_manager(), route_registry_.get(),
node_->get_parameter("server.host").as_string(), node_->get_parameter("server.port").as_int());
}

void TearDown() override {
Expand Down Expand Up @@ -758,7 +759,9 @@ TEST_F(CapabilityGeneratorTest, ByteBudgetEvictsBeforeTheEntryCountWould) {
// A budget that fits one document of this size but not two.
openapi::DocsCacheBounds bounds;
bounds.max_bytes = first->size() + 64;
CapabilityGenerator bounded(*ctx_, *node_, node_->get_plugin_manager(), route_registry_.get(), bounds);
CapabilityGenerator bounded(*ctx_, *node_, node_->get_plugin_manager(), route_registry_.get(),
node_->get_parameter("server.host").as_string(),
node_->get_parameter("server.port").as_int(), bounds);

ASSERT_TRUE(bounded.generate_serialized("/areas").has_value());
ASSERT_EQ(bounded.cache_entry_count(), 1u);
Expand All @@ -774,7 +777,9 @@ TEST_F(CapabilityGeneratorTest, ByteBudgetEvictsBeforeTheEntryCountWould) {
TEST_F(CapabilityGeneratorTest, DocumentLargerThanTheBudgetIsServedUncached) {
openapi::DocsCacheBounds bounds;
bounds.max_bytes = 16;
CapabilityGenerator bounded(*ctx_, *node_, node_->get_plugin_manager(), route_registry_.get(), bounds);
CapabilityGenerator bounded(*ctx_, *node_, node_->get_plugin_manager(), route_registry_.get(),
node_->get_parameter("server.host").as_string(),
node_->get_parameter("server.port").as_int(), bounds);

auto document = bounded.generate_serialized("/areas");
ASSERT_TRUE(document.has_value());
Expand All @@ -787,7 +792,9 @@ TEST_F(CapabilityGeneratorTest, DocumentLargerThanTheBudgetIsServedUncached) {
TEST_F(CapabilityGeneratorTest, EntryCountEvictsWhenTheByteBudgetIsSlack) {
openapi::DocsCacheBounds bounds;
bounds.max_entries = 2;
CapabilityGenerator bounded(*ctx_, *node_, node_->get_plugin_manager(), route_registry_.get(), bounds);
CapabilityGenerator bounded(*ctx_, *node_, node_->get_plugin_manager(), route_registry_.get(),
node_->get_parameter("server.host").as_string(),
node_->get_parameter("server.port").as_int(), bounds);

ASSERT_TRUE(bounded.generate_serialized("/areas").has_value());
ASSERT_TRUE(bounded.generate_serialized("/apps").has_value());
Expand Down
Loading
Loading