VLink  2.3.0
A high-performance communication middleware
node.h
Go to the documentation of this file.
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 node.h
26  * @brief Common CRTP base for every VLink communication primitive.
27  *
28  * @details
29  * @c Node<ImplT, SecT> is the polymorphic base class shared by all six
30  * VLink communication primitives. It owns the transport-specific
31  * implementation pointer (@c impl_), drives the node lifecycle, and exposes
32  * the cross-cutting services that every primitive needs: zero-copy loans,
33  * peer-discovery toggling, message-loop attachment, recording, security
34  * installation, profiling, and SSL/TLS configuration.
35  *
36  * @par Class Hierarchy
37  * @verbatim
38  * +--------------------------------------------------------------+
39  * | User-facing primitives |
40  * | Publisher<T> Subscriber<T> Setter<T> Getter<T> |
41  * | Client<Req,Resp> Server<Req,Resp> |
42  * +-----------------------------+--------------------------------+
43  * | inherits
44  * +-----------------------------v--------------------------------+
45  * | Node<ImplT, SecT> |
46  * | lifecycle | loans | properties | profiler | ssl | security |
47  * +-----------------------------+--------------------------------+
48  * | owns std::unique_ptr<ImplT>
49  * +-----------------------------v--------------------------------+
50  * | ImplT (PublisherImpl, SubscriberImpl, SetterImpl, ...) |
51  * +-----------------------------+--------------------------------+
52  * | dispatches to transport
53  * +-----------------------------v--------------------------------+
54  * | Transport back-ends |
55  * | intra | shm | shm2 | dds | ddsc | zenoh | someip | ... |
56  * +--------------------------------------------------------------+
57  * @endverbatim
58  *
59  * @par Lifecycle State Diagram
60  * @verbatim
61  * +------------+ constructor +------------+ init() +------------+
62  * | (uninited) |------------------>| parsed |------------->| active |
63  * | | parse URL / Conf | (impl_) | init_ext | (using API)|
64  * +------------+ +------------+ +------------+
65  * ^ |
66  * | init() | interrupt()
67  * | v
68  * +------+------+ +-------------+
69  * | deinited |<-----------| blocking |
70  * | | deinit() | wait aborts|
71  * +-------------+ +-------------+
72  * |
73  * | destructor (calls deinit if active)
74  * v
75  * destroyed
76  * @endverbatim
77  *
78  * | Step | Method | Notes |
79  * | ----------------- | ----------------------- | ------------------------------------------- |
80  * | Construction | constructor | Parses URL, creates impl via Conf factory. |
81  * | Initialisation | @c init() | Runs impl init + init_ext, samples loans. |
82  * | Active | publish / listen / ... | Normal operation. |
83  * | Interrupt | @c interrupt() | Aborts blocking waits immediately. |
84  * | Deinitialisation | @c deinit() | interrupt() then impl deinit + deinit_ext. |
85  * | Destruction | destructor | Auto-deinits if still active. |
86  *
87  * @par ImplType Roles
88  * | @c ImplType | Primitive that uses it | Direction |
89  * | ------------------- | --------------------------- | -------------- |
90  * | @c kPublisher | @c Publisher<T> | Event write |
91  * | @c kSubscriber | @c Subscriber<T> | Event read |
92  * | @c kClient | @c Client<Req,Resp> | RPC caller |
93  * | @c kServer | @c Server<Req,Resp> | RPC handler |
94  * | @c kSetter | @c Setter<T> | Field write |
95  * | @c kGetter | @c Getter<T> | Field read |
96  *
97  * @par Deferred Initialisation
98  * @code
99  * vlink::Publisher<MyMsg> pub("dds://topic", vlink::InitType::kWithoutInit);
100  * pub.set_ser_type("my.custom.Type");
101  * pub.set_discovery_enabled(false);
102  * pub.init();
103  * @endcode
104  *
105  * @par Security
106  * Use the @c Security* primitive aliases to enable per-message encryption.
107  * The @c Security::Config aggregate is passed as the second constructor
108  * argument; omitting it (or passing an empty aggregate) uses the built-in
109  * default symmetric slot:
110  * @code
111  * vlink::Security::Config cfg;
112  * cfg.key = "my-secret";
113  * vlink::SecurityPublisher<MyMsg> pub("shm://topic", cfg);
114  * @endcode
115  *
116  * @note @c intra:// and @c dds:// CDR payloads do not support per-message
117  * security; constructing a @c Security* primitive there is a fatal.
118  *
119  * @par Zero-copy Loans
120  * On loan-capable transports the loan API avoids extra copies:
121  * @code
122  * vlink::Publisher<vlink::Bytes> pub("shm://topic");
123  * if (pub.is_support_loan()) {
124  * vlink::Bytes buf = pub.loan(payload_size);
125  * write_into(buf);
126  * pub.publish(buf); // loan is returned automatically
127  * }
128  * @endcode
129  *
130  * @tparam ImplT Concrete transport implementation derived from @c NodeImpl.
131  * @tparam SecT Security mode: @c kWithoutSecurity (default) or @c kWithSecurity.
132  *
133  * @see publisher.h, subscriber.h, client.h, server.h, getter.h, setter.h,
134  * extension/security.h, extension/ssl_options.h
135  */
136 
137 #pragma once
138 
139 #include <atomic>
140 #include <memory>
141 #include <mutex>
142 #include <optional>
143 #include <string>
144 
145 #include "./extension/security.h"
146 #include "./impl/node_impl.h"
147 
148 namespace vlink {
149 
150 /**
151  * @class Node
152  * @brief Transport-agnostic CRTP base for all VLink communication primitives.
153  *
154  * @details
155  * Provides the lifecycle, loan, security, property, profiler, message-loop,
156  * recording, discovery, and TLS APIs shared by every primitive in the
157  * library. Subclasses fill in the role-specific operations (publish,
158  * listen, invoke, set, get, etc.).
159  *
160  * @tparam ImplT Concrete implementation class (e.g. @c PublisherImpl).
161  * @tparam SecT Security mode (@c kWithoutSecurity or @c kWithSecurity).
162  */
163 template <typename ImplT, SecurityType SecT>
164 class Node {
165  public:
166  using StatusCallback = NodeImpl::StatusCallback; ///< Handler signature for status-change notifications.
167 
168  /**
169  * @brief Initialises the node and its transport back-end.
170  *
171  * @details
172  * Uses an atomic compare-exchange to guard against double-initialisation.
173  * On success the method runs @c impl_->init() then @c impl_->init_ext()
174  * and finally samples the transport's loan capability flag. Calling
175  * @c init() on an already-initialised node is a no-op.
176  *
177  * @return @c true on first successful initialisation; @c false otherwise.
178  */
179  virtual bool init();
180 
181  /**
182  * @brief Tears the node down and releases all transport resources.
183  *
184  * @details
185  * Atomically guards against double-deinit, then runs @c interrupt(),
186  * @c impl_->deinit(), and @c impl_->deinit_ext(). When safe-quit mode is
187  * active, new data and RPC callbacks are skipped and active ones finish
188  * before transport resources are released. The destructor calls this
189  * automatically so explicit calls are only required for early shutdown.
190  *
191  * @return @c true on first successful deinit; @c false if not initialised.
192  */
193  virtual bool deinit();
194 
195  /**
196  * @brief Aborts any blocking wait on this node.
197  *
198  * @details
199  * Signals the internal interrupted flag and notifies the condition
200  * variable so that @c wait_for_subscribers(), @c wait_for_connected(), and
201  * @c wait_for_value() return immediately with @c false. @c Getter
202  * overrides this to additionally wake its own condition variable used by
203  * @c wait_for_value().
204  */
205  virtual void interrupt();
206 
207  /**
208  * @brief Reports whether @c init() has been successfully called.
209  *
210  * @return @c true when the node is currently in the initialised state.
211  */
212  [[nodiscard]] bool has_inited() const;
213 
214  /**
215  * @brief Reports whether the transport supports zero-copy loaned buffers.
216  *
217  * @details
218  * Delegates to the transport implementation. When loans are supported,
219  * @c publish() / @c set() / @c reply() automatically use them to avoid an
220  * extra memory copy.
221  *
222  * @return @c true if @c loan() / @c return_loan() are meaningful for this transport.
223  */
224  [[nodiscard]] bool is_support_loan() const;
225 
226  /**
227  * @brief Allocates a loaned buffer from the transport memory pool.
228  *
229  * @details
230  * Returns storage of @p size bytes. Zenoh may return owning @c Bytes for
231  * small payloads or while its lazy SHM provider is starting; use
232  * @c Bytes::is_loaned() to distinguish an actual transport loan.
233  * The caller must either pass it to a publish/write call (which returns
234  * the loan automatically) or call @c return_loan() explicitly. Returns
235  * an empty @c Bytes on failure or when the transport has no loan pool.
236  *
237  * @param size Requested byte count; @c 0 is valid for empty messages.
238  * @return Loaned @c Bytes, or an empty @c Bytes on failure.
239  */
240  [[nodiscard]] Bytes loan(int64_t size);
241 
242  /**
243  * @brief Returns a previously loaned buffer to the transport pool.
244  *
245  * @details
246  * Must be called whenever a loan obtained via @c loan() is not consumed by
247  * a publish/write call; failing to return loans can exhaust the shared
248  * memory pool.
249  *
250  * @param bytes The loaned @c Bytes to return.
251  * @return @c true on success; @c false if the buffer is not a valid loan.
252  */
253  bool return_loan(const Bytes& bytes);
254 
255  /**
256  * @brief Suspends message delivery on this node.
257  *
258  * @details
259  * Transport-dependent behaviour: some back-ends buffer incoming messages
260  * while suspended, others drop them. Pair with @c resume().
261  *
262  * @return @c true if suspension succeeded.
263  */
264  bool suspend();
265 
266  /**
267  * @brief Resumes message delivery after a prior @c suspend().
268  *
269  * @return @c true if resumption succeeded.
270  */
271  bool resume();
272 
273  /**
274  * @brief Reports whether the node is currently suspended.
275  *
276  * @return @c true while @c suspend() is in effect.
277  */
278  [[nodiscard]] bool is_suspend() const;
279 
280  /**
281  * @brief Attaches the node to a @c MessageLoop for callback dispatch.
282  *
283  * @details
284  * After attachment, inbound callbacks are posted onto @p message_loop
285  * rather than invoked on the transport delivery thread. This serialises
286  * dispatch onto the loop's thread, which is convenient for
287  * single-threaded user code.
288  *
289  * @param message_loop Pointer to the target @c MessageLoop.
290  * @return @c true on success; @c false if a loop is already attached.
291  */
292  bool attach(class MessageLoop* message_loop);
293 
294  /**
295  * @brief Detaches the node from its current @c MessageLoop.
296  *
297  * @details
298  * After detachment the callback returns to running on the transport
299  * delivery thread.
300  *
301  * @return @c true on success; @c false if no loop was attached.
302  */
303  bool detach();
304 
305  /**
306  * @brief Returns the @c MessageLoop this node is currently attached to.
307  *
308  * @return Pointer to the attached @c MessageLoop, or @c nullptr.
309  */
310  [[nodiscard]] class MessageLoop* get_message_loop() const;
311 
312  /**
313  * @brief Returns the abstract-graph handle for runtime topology inspection.
314  *
315  * @details
316  * The @c AbstractNode pointer is usable with @c AbstractFactory and the
317  * proxy monitoring API to enumerate peer nodes in the same transport
318  * graph.
319  *
320  * @return Non-owning pointer to the @c AbstractNode, or @c nullptr if the
321  * transport does not expose one.
322  */
323  [[nodiscard]] const AbstractNode* get_abstract_node() const;
324 
325  /**
326  * @brief Retrieves the current status object for the requested category.
327  *
328  * @details
329  * Returns a polymorphic shared pointer. The concrete type and set of
330  * supported categories depend on the active transport; an unsupported
331  * @p type yields a @c Status::Unknown instance and logs a warning.
332  *
333  * @param type Status category to retrieve.
334  * @return Shared pointer to status data, or @c Status::Unknown when unsupported.
335  */
336  [[nodiscard]] Status::BasePtr get_status(Status::Type type) const;
337 
338  /**
339  * @brief Registers a handler invoked whenever the node's status changes.
340  *
341  * @details
342  * Only one handler can be registered at a time; subsequent calls replace
343  * the previous handler. The handler receives a @c Status::BasePtr
344  * describing the new state (connected, disconnected, error, etc.).
345  *
346  * @param callback @c void(const Status::BasePtr&) handler.
347  */
348  void register_status_handler(StatusCallback&& callback);
349 
350  /**
351  * @brief Sets a transport-specific string-keyed property.
352  *
353  * @details
354  * Extensibility mechanism for back-end-specific tuning knobs that do not
355  * have a dedicated method. Recognised keys depend on the active
356  * transport.
357  *
358  * @param prop Property key string.
359  * @param value Property value string.
360  */
361  void set_property(const std::string& prop, const std::string& value);
362 
363  /**
364  * @brief Retrieves a previously set transport-specific property value.
365  *
366  * @param prop Property key string.
367  * @return Property value string; empty if the key is unknown.
368  */
369  [[nodiscard]] std::string get_property(const std::string& prop) const;
370 
371  /**
372  * @brief Returns the @c TransportType this node is bound to.
373  *
374  * @return Enumerator such as @c kDds, @c kShm, @c kIntra, etc.
375  */
376  [[nodiscard]] TransportType get_transport_type() const;
377 
378  /**
379  * @brief Returns the URL string used to construct this node.
380  *
381  * @details
382  * Non-empty only when the node was constructed via a URL string or @c Url
383  * object; typed @c ConfT-based construction leaves this empty.
384  *
385  * @return Const reference to the URL string.
386  */
387  [[nodiscard]] const std::string& get_url() const;
388 
389  /**
390  * @brief Enables recording of inbound or outbound messages to a bag file.
391  *
392  * @details
393  * Not supported on @c intra:// nodes (triggers a fatal log). DDS CDR nodes
394  * record the complete payload, including the encapsulation header.
395  * Supported file suffixes are @c .vdb, @c .vdbx, @c .vcap, and @c .vcapx;
396  * an unknown suffix logs an error and disables recording.
397  *
398  * @param path Bag file path on disk.
399  */
400  void set_record_path(const std::string& path);
401 
402  /**
403  * @brief Overrides the runtime wire-metadata identifiers for this node.
404  *
405  * @details
406  * @p ser_type holds the concrete runtime type identifier; @p schema_type
407  * holds the coarse decoder family used by discovery, proxy, and bag
408  * metadata. When @p schema_type is @c SchemaType::kUnknown (the default)
409  * the family is inferred from @p ser_type: a @c "vlink::zerocopy::" prefix
410  * implies @c kZeroCopy, while values such as @c "raw", @c "string",
411  * @c "std::string", @c "text", or @c "json" imply @c kRaw. If no family
412  * can be inferred, an existing @c kRaw or @c kZeroCopy family is reset to
413  * @c kUnknown; any other existing family is preserved. Passing an empty
414  * @p ser_type clears both fields.
415  *
416  * If invoked post-@c init() the transport extension is restarted so that
417  * external metadata stays in sync. A DDS node's raw/CDR mode is part of its
418  * native Topic/DataWriter/DataReader type and therefore cannot be changed
419  * while initialised; neither can the type name of an initialised DDS CDR
420  * node. Call @c deinit() before changing either value, then call @c init()
421  * again.
422  *
423  * @param ser_type Concrete runtime type identifier, or empty to clear.
424  * @param schema_type Optional explicit schema family; default preserves the current family.
425  */
426  void set_ser_type(const std::string& ser_type, SchemaType schema_type = SchemaType::kUnknown);
427 
428  /**
429  * @brief Returns the current concrete runtime type identifier.
430  *
431  * @return Const reference to the type identifier string.
432  */
433  [[nodiscard]] const std::string& get_ser_type() const;
434 
435  /**
436  * @brief Returns the current coarse schema family.
437  *
438  * @return The @c SchemaType stored on the implementation.
439  */
440  [[nodiscard]] SchemaType get_schema_type() const;
441 
442  /**
443  * @brief Toggles peer-discovery on this node.
444  *
445  * @details
446  * Disabling discovery reduces CPU and network overhead for nodes that
447  * never need to locate peers. Reinitialises the transport extension if
448  * invoked post-@c init() so the change takes effect immediately.
449  *
450  * @param enable @c true (default) to enable discovery; @c false to disable.
451  */
452  void set_discovery_enabled(bool enable);
453 
454  /**
455  * @brief Reports whether peer-discovery is currently enabled.
456  *
457  * @return @c true if discovery is active.
458  */
459  [[nodiscard]] bool get_discovery_enabled() const;
460 
461  /**
462  * @brief Binds a Protobuf Arena for arena-allocated message objects.
463  *
464  * @details
465  * Required whenever this node must create a raw Protobuf pointer object
466  * (e.g. a subscriber message, server request/response, client response, or
467  * getter value of type @c MyProto*). The arena must outlive this node.
468  * Forgetting to bind it before the first such operation triggers a fatal
469  * log. Receive paths allocate a distinct message in the arena for each
470  * delivery, so that storage is retained until the caller resets or destroys
471  * the arena.
472  *
473  * @param proto_arena Pointer to a @c google::protobuf::Arena instance (typed as @c void*).
474  */
475  void bind_proto_arena(void* proto_arena);
476 
477  /**
478  * @brief Returns the cumulative CPU-usage ratio sampled by the profiler.
479  *
480  * @details
481  * Reports the percentage of wall-clock time this node has spent in active
482  * publish or receive code since the profiler was started. Available only
483  * when the CPU profiler is built in (@c VLINK_DISABLE_PROFILER not
484  * defined) and global profiling is enabled via the @c VLINK_PROFILER_ENABLE
485  * environment variable. Returns @c -1.0 if no profiler is attached.
486  *
487  * @return CPU usage percentage (may exceed @c 100.0 on multi-core systems);
488  * @c -1.0 if unavailable.
489  */
490  [[nodiscard]] double get_cpu_usage() const;
491 
492  /**
493  * @brief Reports whether safe-quit mode is currently active.
494  *
495  * @details
496  * Safe-quit mode holds a @c std::mutex around data and RPC callbacks. During
497  * @c deinit(), new callbacks are skipped and active callbacks are drained
498  * before transport resources are released.
499  *
500  * @return @c true if the safe-quit mutex is engaged.
501  */
502  [[nodiscard]] bool get_safety_quit() const;
503 
504  /**
505  * @brief Enables or disables safe-quit mode.
506  *
507  * @details
508  * When enabled, an internal @c std::mutex is allocated and locked around
509  * data and RPC callback invocations. Deinitialisation drains active callbacks
510  * before releasing transport resources. Enable when the
511  * node's lifetime is shorter than the callback scope. There is a small
512  * synchronisation overhead; avoid enabling it on hot paths.
513  *
514  * @param safety_quit @c true to enable; @c false to disable (default).
515  */
516  void set_safety_quit(bool safety_quit);
517 
518  /**
519  * @brief Configures transport-layer SSL/TLS encryption for this node.
520  *
521  * @details
522  * Merges the fields of @p options into the node's internal property map
523  * via @c SslOptions::parse_to(). The transport reads the resulting
524  * @c ssl.* properties during @c init() to set up the TLS connection, so
525  * this method must be called before @c init() for the settings to take
526  * effect.
527  *
528  * SSL is considered enabled when @c SslOptions::is_valid() returns
529  * @c true (i.e. at least @c ca_file or @c cert_file is non-empty). Not
530  * all back-ends support TLS; see @c SslOptions for the per-backend
531  * compatibility table. Thread-safe -- the property map is updated under
532  * a mutex.
533  *
534  * @par Example
535  * @code
536  * vlink::Publisher<MyMsg> pub("mqtt://sensor/data", vlink::InitType::kWithoutInit);
537  * vlink::SslOptions ssl;
538  * ssl.ca_file = "/etc/certs/ca.pem";
539  * ssl.cert_file = "/etc/certs/client.pem";
540  * ssl.key_file = "/etc/certs/client-key.pem";
541  * pub.set_ssl_options(ssl);
542  * pub.init();
543  * @endcode
544  *
545  * @param options SSL/TLS configuration to apply.
546  *
547  * @see SslOptions, set_property()
548  */
549  void set_ssl_options(const SslOptions& options);
550 
551  protected:
552  Node();
553 
554  virtual ~Node();
555 
556  /**
557  * @brief Installs a @c Security configuration before transport initialisation.
558  *
559  * @details
560  * Internal helper used by the @c Security* primitive constructors after
561  * @c impl_ has been created but before @c init(). Delegates default
562  * handling, validation, and storage to @c NodeImpl::enable_security().
563  *
564  * @param cfg Security configuration aggregate.
565  * @return @c true when @p cfg (including the default empty case) is usable for this role / transport.
566  */
567  bool enable_security(const Security::Config& cfg);
568 
569  /**
570  * @brief Move overload for construction-time security installation.
571  *
572  * @details
573  * Used when an internal caller owns the config and can forward it without
574  * an extra copy.
575  *
576  * @param cfg Security configuration aggregate to consume.
577  * @return @c true when @p cfg (including the default empty case) is usable for this role / transport.
578  */
579  bool enable_security(Security::Config&& cfg);
580 
581  template <typename CallbackT, typename... ArgsT>
582  void invoke_callback(const CallbackT& callback, ArgsT&&... args);
583 
584  template <typename TypeT>
585  TypeT get_default_value();
586 
587  void* proto_arena_{nullptr};
588  bool is_support_loan_{false};
589 
590  std::atomic_bool has_inited_{false};
591  std::optional<std::mutex> quit_mtx_;
592 
593  std::unique_ptr<ImplT> impl_;
594 
595  private:
597 };
598 
599 } // namespace vlink
600 
601 #include "./internal/node-inl.h"
#define VLINK_DISALLOW_COPY_AND_ASSIGN(classname)
Deletes the copy constructor and copy-assignment operator of classname.
Definition: macros.h:174
Foundational base classes shared by every transport-backed VLink node.
Application-layer authenticated encryption with symmetric, hybrid asymmetric, and pluggable backends.