VLink  2.3.0
A high-performance communication middleware
proxy_server.h
浏览该文件的文档.
1 /*
2  * Copyright (C) 2026 by Thun Lu. All rights reserved.
3  * Author: Thun Lu <thun.lu@zohomail.cn>
4  * Repo: https://github.com/thun-res/vlink
5  * _ __ __ _ __
6  * | | / / / / (_) ____ / /__
7  * | | / / / / / / / __ \ / //_/
8  * | |/ / / /___ / / / / / / / ,<
9  * |___/ /_____/ /_/ /_/ /_/ /_/|_|
10  *
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  * http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  */
23 
24 /**
25  * @file proxy_server.h
26  * @brief Daemon-side half of the VLink proxy subsystem -- one server per process.
27  *
28  * @details
29  * @c ProxyServer is the in-process daemon that mediates between the VLink core (publishers,
30  * subscribers, setters, getters on the local DDS domain) and one or more @c ProxyAPI clients.
31  * It derives from @c MessageLoop, so once @c async_run() is called all scheduled work,
32  * timers, and asynchronous relays run inside the inherited loop's worker thread.
33  *
34  * Behaviourally the server is responsible for the following duties:
35  *
36  * -# Hosts an internal @c DiscoveryViewer that enumerates every active publisher and
37  * subscriber on the DDS domain.
38  * -# Accepts @c Control messages from @c ProxyAPI clients over a security-authenticated
39  * DDS channel and dispatches them to the discovery layer.
40  * -# Broadcasts a 1-second @c Time heartbeat carrying CPU/memory usage, the VLink version
41  * string, hostname, machine ID, and wall-clock plus boot-time.
42  * -# Publishes per-topic statistics -- @c freq, @c rate, @c loss, @c latency -- once per
43  * second through a security-authenticated @c InfoList channel.
44  * -# Relays raw payload bytes from observed publishers and setters back to connected
45  * @c ProxyAPI listeners. In direct mode the data pubs/subs are created by the API
46  * side and the server stays exclusively on the control/discovery path; setter
47  * endpoints are observed with getter semantics so field last-value delivery is
48  * preserved.
49  * -# Optionally launches an embedded Iceoryx RouDi daemon when @c Config::use_iox is
50  * @c true.
51  * -# Loads @c RunablePluginInterface shared-library plugins listed in
52  * @c Config::runnable_list at construction and drives their lifecycle from the
53  * inherited @c MessageLoop callbacks.
54  *
55  * @par Singleton Constraint
56  * Only one @c ProxyServer may exist per operating-system process. A second
57  * construction logs a fatal message and throws before any DDS channels are wired up;
58  * running multiple servers in the same process is not supported and not safe.
59  *
60  * @par Architecture Diagram
61  * @code
62  * +-----------------------+ +---------------------+
63  * | ProxyAPI (Controller) | | ProxyAPI (Listener) |
64  * +-----------+-----------+ +----------+----------+
65  * | |
66  * | HandshakeCli ---[DDS secure]---> HandshakeSrv (issues token)
67  * |<--------------- token --------------|
68  * | ControlPub ---[DDS secure]---> ControlSub (token-stamped)
69  * v v
70  * +-------------------------------------------------------------+
71  * | ProxyServer (this) |
72  * | +-------------------+ +-------------------------------+ |
73  * | | DiscoveryViewer | | Heartbeat / Info / Data path | |
74  * | +-------------------+ +-------------------------------+ |
75  * | ^ | | |
76  * +-------|--------------------------|----------|---------------+
77  * | v v
78  * [VLink core nodes] TimePub / InfoPub ---[DDS secure]--->
79  * DataPub ---[DDS / SHM]--->
80  * @endcode
81  *
82  * @par Authentication Token
83  * At construction the server generates a 128-bit hex session token via
84  * @c vlink::Uuid::random_hex() and exposes it through @c get_token(). The token is a
85  * process-lifetime protocol nonce, @b not a long-term cryptographic key. Clients fetch
86  * it by invoking the handshake RPC over the security-authenticated DDS channel;
87  * subsequent @c Control messages without a matching token are dropped server-side.
88  * Restarting the server invalidates every previously-issued token. Clients re-handshake
89  * after a same-identity token mismatch heartbeat, an identity-mismatch heartbeat that
90  * also carries a different token, or a local reset, before they will accept further
91  * heartbeats or publish new controls.
92  *
93  * @par Runnable Plugin Lifecycle
94  * Plugins named in @c Config::runnable_list are loaded inside the constructor. When
95  * the inherited @c MessageLoop starts (@c on_begin), each plugin's @c on_init() and
96  * @c async_run() are invoked in list order. On loop stop (@c on_end) each plugin's
97  * @c on_deinit(), @c quit(), and @c wait_for_quit() are invoked in the same order.
98  *
99  * @par Environment Variables
100  * | Variable | Meaning |
101  * | ------------------------ | --------------------------------------------------------------- |
102  * | @c VLINK_INTRA_BIND | When set to any value, also subscribe to @c intra:// topics. |
103  * | @c VLINK_DDS_NATIVE_IP | Native-mode DDS bind IP; defaults to @c 127.0.0.1 when unset. |
104  *
105  * @par Example
106  * @code
107  * vlink::ProxyServer::Config cfg;
108  * cfg.dds_impl = "dds";
109  * cfg.domain_id = 0;
110  * cfg.reliable = false;
111  * cfg.async = true;
112  * cfg.use_iox = false;
113  *
114  * vlink::ProxyServer server(cfg);
115  * server.async_run(); // start the inherited MessageLoop in a background thread
116  * // ... application runs ...
117  * server.quit(true);
118  * server.wait_for_quit();
119  * @endcode
120  *
121  * @note
122  * - Construction must happen on the main thread, before any @c ProxyAPI client connects
123  * on the same domain.
124  * - Destruction stops every timer, joins the @c DiscoveryViewer, and releases each DDS
125  * handle in a deterministic order so no dangling callback can fire after teardown.
126  */
127 
128 #pragma once
129 
130 #undef VLINK_PROXY_SERVER_EXPORT
131 #ifdef VLINK_PROXY_SERVER_LIBRARY_STATIC
132 #define VLINK_PROXY_SERVER_EXPORT
133 #elif defined(_WIN32) || defined(__CYGWIN__)
134 #ifdef VLINK_PROXY_SERVER_LIBRARY
135 #define VLINK_PROXY_SERVER_EXPORT __declspec(dllexport)
136 #else
137 #define VLINK_PROXY_SERVER_EXPORT __declspec(dllimport)
138 #endif
139 #else
140 #define VLINK_PROXY_SERVER_EXPORT __attribute__((visibility("default")))
141 #endif
142 
143 #include <cstdint>
144 #include <memory>
145 #include <optional>
146 #include <string>
147 #include <vector>
148 
149 #include "../base/message_loop.h"
150 #include "proxy_api.h"
151 
152 namespace vlink {
153 
154 /**
155  * @class ProxyServer
156  * @brief In-process VLink proxy daemon backed by a @c MessageLoop.
157  *
158  * @details
159  * Owns the discovery layer, the handshake/control/time/info DDS channels, the data
160  * relay path, and any embedded Iceoryx daemon or runnable plugins. Construction
161  * starts the @c DiscoveryViewer and arms the 1-second heartbeat and statistics
162  * timers, but it does @b not start the server's own inherited loop. Those timers
163  * now run on that loop, so @c async_run() (or @c run()) on the @c MessageLoop base
164  * is @b required: without it no heartbeat or @c InfoList is published and every
165  * @c ProxyAPI client reports a disconnect after five seconds. Only one instance is
166  * allowed per process.
167  */
169  public:
170  /**
171  * @struct Config
172  * @brief Construction-time configuration aggregate for @c ProxyServer.
173  *
174  * @details
175  * Every @c reliable, @c enable_tcp, and @c direct flag is echoed inside each @c Time
176  * heartbeat, so connecting @c ProxyAPI clients can verify wire-compatibility and
177  * refuse to attach when their own configuration would deviate.
178  *
179  * | Field | Default | Description |
180  * | -------------------------- | ------- | ----------------------------------------------------------------- |
181  * | @c async | false | Forward data on the MessageLoop thread; false = inline relay. |
182  * | @c reliable | false | Use reliable DDS QoS for data channels. |
183  * | @c enable_tcp | false | Use TCP transport for data channels. |
184  * | @c direct | false | Use SHM (Iceoryx) instead of DDS for data forwarding. |
185  * | @c native_mode | false | Discover locally; bind DDS to @c VLINK_DDS_NATIVE_IP. |
186  * | @c domain_id | 0 | DDS domain ID shared with all clients. |
187  * | @c buf_size | 0 | DDS socket send/receive buffer in bytes; 0 = built-in default. |
188  * | @c mtu_size | 0 | DDS MTU size in bytes; 0 = built-in default. |
189  * | @c max_packet_size | 0 | Maximum relayed payload in MiB; see note below. |
190  * | @c security_key | "" | Security key for control channels; empty = default slot. |
191  * | @c allow_ip | "" | Bind DDS sockets to this IP; empty = any interface. |
192  * | @c peer_ip | "" | Unicast peer IP for discovery; empty = multicast. |
193  * | @c dds_impl | "dds" | DDS implementation: "dds", "ddsc", "ddsr", etc. |
194  * | @c use_iox | false | Launch an embedded Iceoryx RouDi daemon at startup. |
195  * | @c iox_monitoring | true | Enable Iceoryx introspection/monitoring. |
196  * | @c iox_strategy | 3 | Iceoryx memory strategy index passed to @c ShmConf::init_roudi(). |
197  * | @c iox_config | "" | Path to a custom Iceoryx TOML; empty = default. |
198  * | @c runnable_version_major | 1 | Required major ABI version for runnable plugins. |
199  * | @c runnable_version_minor | 0 | Required minor ABI version for runnable plugins. |
200  * | @c runnable_prefix | "" | Library filename prefix for plugin discovery. |
201  * | @c runnable_list | {} | Ordered names of @c RunablePluginInterface plugins to load. |
202  *
203  * @note
204  * @c max_packet_size is interpreted in MiB. The default value @c 0 disables the
205  * payload-size limit. The @c vlink-proxy CLI defaults this field to @c 4.0.
206  */
207  struct Config final {
208  bool async{false}; ///< Forward data asynchronously on the MessageLoop thread.
209  bool reliable{false}; ///< Use reliable DDS QoS; must match every client.
210  bool enable_tcp{false}; ///< Use TCP transport for DDS data channels.
211  bool direct{false}; ///< Use ProxyAPI-managed local SHM channels for data.
212  bool native_mode{false}; ///< Discover locally; bind DDS to VLINK_DDS_NATIVE_IP (default 127.0.0.1).
213  int domain_id{0}; ///< DDS domain ID.
214  uint32_t buf_size{0}; ///< DDS socket buffer in bytes; 0 = default.
215  uint32_t mtu_size{0}; ///< DDS fragment MTU in bytes; 0 = default.
216  double max_packet_size{0}; ///< Maximum relayed payload in MiB; 0 disables the limit.
217  std::string security_key; ///< Security key; empty = default security slot.
218  std::string allow_ip; ///< Local IP for DDS sockets; empty = any.
219  std::string peer_ip; ///< Peer unicast IP for DDS; empty = multicast.
220  std::string dds_impl{"dds"}; ///< DDS implementation transport identifier.
221  bool use_iox{false}; ///< Launch an embedded Iceoryx RouDi.
222  bool iox_monitoring{true}; ///< Enable Iceoryx introspection.
223  int iox_strategy{3}; ///< Iceoryx memory strategy: 1 mini, 2 low, 3 middle, 4 high.
224  std::string iox_config; ///< Iceoryx TOML config path; empty = default.
225  uint16_t runnable_version_major{1}; ///< Required major ABI version for plugins.
226  uint16_t runnable_version_minor{0}; ///< Required minor ABI version for plugins.
227  std::string runnable_prefix; ///< Plugin library filename prefix.
228  std::vector<std::string> runnable_list; ///< Ordered plugin names to load on startup.
229 
230  std::optional<ProxyAPI::Config> bridge; /**< Optional Controller bridge to another non-direct proxy domain. */
231  std::string bridge_filter{
232  "shm://,shm2://,intra://"}; /**< Space/comma URL filters; case-insensitive, empty = all. */
233  bool bridge_subscribe{false}; /**< Forward local publishers to matching remote subscribers. */
234  };
235 
236  /**
237  * @brief Constructs a @c ProxyServer and brings every proxy subsystem online.
238  *
239  * @details
240  * The constructor performs the following steps in order:
241  *
242  * -# Acquires the process-global singleton guard; on contention it logs a fatal
243  * message and throws before touching any DDS handle.
244  * -# Reads @c VLINK_INTRA_BIND and, in native mode, @c VLINK_DDS_NATIVE_IP.
245  * -# When @c config.use_iox is @c true, calls @c init_shm_roudi() to spin up an
246  * embedded Iceoryx RouDi process.
247  * -# Calls @c init_server() to create the handshake, control, time, info, and data
248  * channels, subscribe to @c Control, and arm the heartbeat plus statistics
249  * timers on the server's own inherited loop.
250  * -# Calls @c init_runnable() to load every plugin listed in @c config.runnable_list.
251  *
252  * The inherited @c MessageLoop is @b not started here -- call @c async_run() or
253  * @c run() explicitly. It now drives the heartbeat and statistics timers as well as
254  * asynchronous relays and plugin lifecycle hooks, so leaving it stopped silently
255  * disables the heartbeat.
256  *
257  * @param config Server configuration. See @c Config for per-field semantics.
258  *
259  * @note A second @c ProxyServer in the same process is unsupported and the
260  * constructor throws.
261  */
262  explicit ProxyServer(const Config& config);
263 
264  /**
265  * @brief Destroys the @c ProxyServer in a deterministic shutdown order.
266  *
267  * @details
268  * Requests the inherited @c MessageLoop to stop, waits for it, then stops the proxy
269  * timers, joins the @c DiscoveryViewer, and releases each DDS/SHM handle. When the
270  * loop has been started, runnable plugins receive @c on_deinit(), @c quit(), and
271  * @c wait_for_quit() from @c on_end() before the destructor drops them. The
272  * process-global singleton guard remains set for the rest of the process lifetime.
273  */
274  ~ProxyServer() override;
275 
276  /**
277  * @brief Returns the authentication token issued by this server.
278  *
279  * @details
280  * When @c VLINK_PROXY_ENABLE_HANDSHAKE is non-zero (the default), the token is
281  * generated once at construction via @c vlink::Uuid::random_hex() and remains
282  * constant for the server's lifetime. Clients learn it through the
283  * security-authenticated handshake RPC. The server then validates the token on
284  * every inbound @c Control and echoes it (alongside the server identity) inside
285  * every @c Time heartbeat so clients can detect both server restarts and identity
286  * mismatches. When the macro is @c 0, the token is empty, validation is disabled,
287  * and the handshake channel is not created.
288  *
289  * @return Hex-encoded token string, or empty when handshake is compiled out.
290  *
291  * @note Thread-safe; the returned string is a copy.
292  */
293  [[nodiscard]] std::string get_token() const;
294 
295  protected:
296  size_t get_max_task_count() const override;
297 
298  uint32_t get_max_elapsed_time() const override;
299 
300  void on_begin() override;
301 
302  void on_end() override;
303 
304  void on_task_timeout(MessageLoop::Callback&& callback, uint32_t elapsed_time) override;
305 
306  private:
307  void init_shm_roudi();
308 
309  void init_server();
310 
311  void init_runnable();
312 
313  void init_bridge();
314 
315  void update_bridge(const std::vector<ProxyAPI::Info>& info_list);
316 
317  bool forward_bridge_data(const void* data);
318 
319  void send_time();
320 
321  void send_control(const void* control_data);
322 
323  void update_all();
324 
325  struct Impl;
326  std::unique_ptr<Impl> impl_;
327 
329 };
330 
331 } // namespace vlink
#define VLINK_DISALLOW_COPY_AND_ASSIGN(classname)
Deletes the copy constructor and copy-assignment operator of classname.
Definition: macros.h:174
Client-side C++ API for connecting to a ProxyServer daemon.
#define VLINK_PROXY_SERVER_EXPORT
Definition: proxy_server.h:140