Class PeerClient
Defined in File peer_client.hpp
Class Documentation
-
class PeerClient
HTTP client for communicating with a peer gateway instance.
PeerClient wraps cpp-httplib to provide typed access to a peer gateway’s REST API. It supports health checking, entity fetching, transparent request forwarding (proxy), and JSON fan-out queries.
Thread safety: The healthy_ flag is atomic. Client creation is lazy and guarded by a mutex. All public methods are safe to call from any thread.
Public Functions
-
PeerClient(const std::string &url, const std::string &name, int timeout_ms, bool forward_auth = false)
Construct a PeerClient for a peer gateway.
- Parameters:
url – Base URL of the peer (e.g., “http://localhost:8081”)
name – Human-readable peer name (e.g., “subsystem_b”)
timeout_ms – Connection and read timeout in milliseconds
forward_auth – Whether to forward Authorization headers to this peer
-
const std::string &url() const
Get the peer base URL.
-
const std::string &name() const
Get the peer name.
-
bool is_healthy() const
Check if the peer was healthy at last health check.
-
void check_health()
Perform a health check against the peer.
GETs /api/v1/health on the peer. Sets the internal healthy_ flag based on whether a 200 response was received.
-
tl::expected<PeerEntities, std::string> fetch_entities()
Fetch all entity collections from the peer.
GETs /api/v1/areas, /api/v1/components, /api/v1/apps, /api/v1/functions and parses the items[] arrays. Each entity’s source is set to “peer:<name>”.
- Returns:
PeerEntities on success, error message on failure
-
void forward_request(const httplib::Request &req, httplib::Response &res)
Forward an HTTP request transparently to the peer (proxy)
Copies method, path, body, and Content-Type from the incoming request. Forwards the Authorization header only if forward_auth is enabled. Copies the peer’s response status, headers, and body back to the outgoing response.
On connection failure, returns 502 with x-medkit-peer-unavailable error.
- Parameters:
req – Incoming HTTP request to forward
res – Outgoing HTTP response to populate
-
tl::expected<nlohmann::json, std::string> forward_and_get_json(const std::string &method, const std::string &path, const std::string &auth_header = "")
Forward a request and parse the JSON response.
Used for fan-out merge scenarios where the aggregator needs to combine JSON results from multiple peers.
- Parameters:
method – HTTP method (e.g., “GET”)
path – Request path (e.g., “/api/v1/components/abc/data”)
auth_header – Authorization header value (empty to omit)
- Returns:
Parsed JSON on success, error message on failure
-
PeerClient(const std::string &url, const std::string &name, int timeout_ms, bool forward_auth = false)