VLink  2.3.0
A high-performance communication middleware
subscriber.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 subscriber.h
26  * @brief Read-side primitive of the VLink event communication model.
27  *
28  * @details
29  * @c Subscriber<MsgT, SecT> attaches a callback to a VLink topic. Each
30  * frame delivered by the transport back-end is deserialised into a @c MsgT
31  * instance and forwarded to the user callback registered via @c listen().
32  * Unlike @c Getter, the subscriber retains no value history -- it simply
33  * forwards every event in delivery order.
34  *
35  * The class is a thin, header-only template wrapper around @c SubscriberImpl.
36  * Codec dispatch is fully resolved at compile time using the type detected
37  * by @c Serializer::get_type_of<MsgT>().
38  *
39  * @par Event-model Delivery Path
40  * @verbatim
41  * Transport Back-end Subscriber<MsgT>
42  * ------------------ -----------------
43  * | inbound frame |
44  * |--------------------------------------> |
45  * | | Serializer::deserialize
46  * | | (per-delivery local value)
47  * | |
48  * | | optional MessageLoop hop
49  * | |
50  * | v
51  * | user callback(const MsgT&)
52  * @endverbatim
53  *
54  * @par Supported Message Types
55  * | Category | Example C++ Type | @c Serializer::Type | Notes |
56  * | ----------------- | -------------------------------- | ------------------- | ------------------------------ |
57  * | Raw bytes | @c Bytes | @c kBytesType | Pass-through to callback. |
58  * | SOME/IP struct | @c VLINK_SOMEIP_FIELDS structure | @c kSomeipType | Field-wise SOME/IP payload. |
59  * | Protobuf value | @c MyProto | @c kProtoType | ParseFromArray path. |
60  * | Protobuf pointer | @c MyProto* | @c kProtoPtrType | Needs @c bind_proto_arena. |
61  * | FlatBuffers obj | @c MyTableT (NativeTable) | @c kFlatTableType | Object API. |
62  * | FlatBuffers ptr | @c MyTable* | @c kFlatPtrType | Zero-copy view of buffer. |
63  * | DDS CDR | FastDDS IDL or ROS2 message type | @c kCdrType | Encapsulated CDR bytes. |
64  * | POD struct | trivial standard-layout type | @c kStandardType | @c sizeof(T) byte copy. |
65  * | String | @c std::string | @c kStringType | Payload-sized byte string. |
66  * | Custom | type with @c operator>>/<< | @c kCustomType | User-supplied codec. |
67  *
68  * Raw Protobuf pointer receivers allocate a distinct message in the bound
69  * Arena for each delivery; that storage remains until the Arena is reset or
70  * destroyed.
71  *
72  * @par Basic Listen Example
73  * @code
74  * vlink::Subscriber<MyMsg> sub("dds://vehicle/speed");
75  * sub.listen([](const MyMsg& msg) { handle(msg); });
76  * @endcode
77  *
78  * @par Callback Dispatch via MessageLoop
79  * @code
80  * vlink::MessageLoop loop;
81  * vlink::Subscriber<MyMsg> sub("dds://vehicle/speed", vlink::InitType::kWithoutInit);
82  * sub.attach(&loop);
83  * sub.init();
84  * sub.listen([](const MyMsg& m) { handle(m); });
85  * loop.run();
86  * @endcode
87  *
88  * @par Zero-copy Intra Transport
89  * When @c MsgT is a shared pointer whose @c element_type derives from
90  * @c IntraDataType (generated via @c VLINK_INTRA_DATA_DECLARE) and the URL
91  * scheme is @c intra://, the shared pointer is forwarded zero-copy to the
92  * callback without serialisation:
93  * @code
94  * VLINK_INTRA_DATA_DECLARE(MyProtoMsg, MyIntra)
95  * vlink::Subscriber<MyIntra> sub("intra://my_topic");
96  * sub.listen([](const MyIntra& data) { use(data); });
97  * @endcode
98  *
99  * @par Latency and Sample-loss Tracking
100  * @code
101  * vlink::Subscriber<MyMsg> sub("dds://my_topic");
102  * sub.set_latency_and_lost_enabled(true);
103  * auto latency_ns = sub.get_latency();
104  * auto stats = sub.get_lost();
105  * @endcode
106  *
107  * @warning For value message types, the deserialised callback argument is a
108  * per-delivery local object whose reference is valid only for the
109  * callback duration. Pointer-view types may instead refer to an
110  * external buffer or arena and follow that storage's lifetime.
111  * Copy retained values into explicitly owned storage. Copying
112  * @c Bytes creates owned storage, and copying an @c IntraData shared
113  * pointer extends that object's lifetime.
114  *
115  * @note Calling @c listen() more than once is a fatal error. The subscriber
116  * must be initialised (either by @c InitType::kWithInit or by explicit
117  * @c init()) before @c listen() is called.
118  *
119  * @see publisher.h, node.h, serializer.h, base/message_loop.h
120  */
121 
122 #pragma once
123 
124 #include <memory>
125 #include <string>
126 #include <type_traits>
127 
128 #include "./base/functional.h"
129 #include "./impl/subscriber_impl.h"
130 #include "./node.h"
131 
132 namespace vlink {
133 
134 /**
135  * @class Subscriber
136  * @brief Type-safe topic listener for the VLink event communication model.
137  *
138  * @details
139  * Inherits the full @c Node API and adds receive-specific operations:
140  * @c listen() to register the user callback and latency / sample-loss
141  * tracking. The transport
142  * implementation (@c SubscriberImpl) is selected by the URL scheme or by
143  * the typed configuration object supplied at construction time.
144  *
145  * @tparam MsgT C++ message type. Must satisfy @c Serializer::is_supported().
146  * @tparam SecT Security mode; defaults to @c SecurityType::kWithoutSecurity.
147  */
148 template <typename MsgT, SecurityType SecT = SecurityType::kWithoutSecurity>
149 class Subscriber : public Node<SubscriberImpl, SecT> {
150  public:
151  using UniquePtr = std::unique_ptr<Subscriber<MsgT, SecT>>; ///< Owning unique-pointer alias.
152  using SharedPtr = std::shared_ptr<Subscriber<MsgT, SecT>>; ///< Owning shared-pointer alias.
153  using MsgCallback = Function<void(const MsgT&)>; ///< User callback signature for received messages.
154 
155  static constexpr ImplType kImplType = kSubscriber; ///< Node role tag (@c kSubscriber).
156  static constexpr Serializer::Type kMsgType = Serializer::get_type_of<MsgT>(); ///< Codec resolved from @c MsgT.
157 
158  static_assert(Serializer::is_supported(kMsgType), "<MsgT> is not a supported Serializer type.");
159 
160  /**
161  * @brief Heap-allocates a @c Subscriber and wraps it in a @c std::unique_ptr.
162  *
163  * @param url_str Topic URL string.
164  * @param type Whether to call @c init() inline; default is @c InitType::kWithInit.
165  * @return Owning @c UniquePtr to the new subscriber.
166  */
167  [[nodiscard]] static UniquePtr create_unique(const std::string& url_str, InitType type = InitType::kWithInit);
168 
169  /**
170  * @brief Heap-allocates a @c Subscriber and wraps it in a @c std::shared_ptr.
171  *
172  * @param url_str Topic URL string.
173  * @param type Whether to call @c init() inline; default is @c InitType::kWithInit.
174  * @return Owning @c SharedPtr to the new subscriber.
175  */
176  [[nodiscard]] static SharedPtr create_shared(const std::string& url_str, InitType type = InitType::kWithInit);
177 
178  /**
179  * @brief Constructs a subscriber from a typed transport configuration object.
180  *
181  * @details
182  * Accepts any @c Conf-derived configuration. A compile-time check enforces
183  * that the configuration permits the subscriber role.
184  *
185  * @tparam ConfT Concrete configuration type derived from @c Conf.
186  * @param conf Populated configuration aggregate.
187  * @param type Whether to call @c init() inline; default is @c InitType::kWithInit.
188  */
189  // NOLINTNEXTLINE(modernize-use-constraints)
190  template <typename ConfT, typename = std::enable_if_t<std::is_base_of_v<Conf, ConfT>>>
191  explicit Subscriber(const ConfT& conf, InitType type = InitType::kWithInit);
192 
193  /**
194  * @brief Constructs a subscriber from a URL string.
195  *
196  * @param url_str Topic URL such as @c "shm://vehicle/speed".
197  * @param type Whether to call @c init() inline; default is @c InitType::kWithInit.
198  */
199  explicit Subscriber(const std::string& url_str, InitType type = InitType::kWithInit);
200 
201  /**
202  * @brief Installs the receive callback that runs for every inbound message.
203  *
204  * @details
205  * The callback is invoked on the transport delivery thread by default; if
206  * the subscriber is @c attach()ed to a @c MessageLoop the callback is
207  * posted onto that loop instead. For @c intra:// transports carrying an
208  * @c IntraDataType shared pointer the value is forwarded zero-copy and
209  * no deserialisation occurs.
210  *
211  * @warning The argument reference is valid only for the duration of the
212  * callback. Value messages use per-delivery local storage, while
213  * pointer-view messages and @c Bytes may refer to external storage.
214  * Copy retained values into explicitly owned storage; copying
215  * @c Bytes creates owned storage, and copying an @c IntraData shared
216  * pointer extends that object's lifetime.
217  *
218  * @note Calling @c listen() more than once is fatal. The subscriber must
219  * be initialised before the first call to @c listen().
220  *
221  * @param callback @c void(const MsgT&) invoked for each received message.
222  * @return @c true if the callback was installed successfully.
223  */
224  bool listen(MsgCallback&& callback);
225 
226  /**
227  * @brief Toggles per-message latency and sample-loss measurement.
228  *
229  * @param enable @c true to begin tracking; @c false to stop.
230  */
231  void set_latency_and_lost_enabled(bool enable);
232 
233  /**
234  * @brief Reports whether latency and sample-loss tracking is currently active.
235  *
236  * @return @c true if @c set_latency_and_lost_enabled(true) was invoked.
237  */
238  [[nodiscard]] bool is_latency_and_lost_enabled() const;
239 
240  /**
241  * @brief Returns the most recent end-to-end latency measurement.
242  *
243  * @details
244  * Computed as receive-timestamp minus source-timestamp on the last
245  * delivered message. Returns @c 0 when tracking is not enabled.
246  *
247  * @return Latency in nanoseconds; @c 0 if disabled.
248  */
249  [[nodiscard]] int64_t get_latency() const;
250 
251  /**
252  * @brief Returns cumulative sample-delivery statistics.
253  *
254  * @return @c SampleLostInfo with total expected and total lost counts.
255  */
256  [[nodiscard]] SampleLostInfo get_lost() const;
257 
258  /**
259  * @brief Marks this subscriber as a field reader.
260  *
261  * @details
262  * Call before @c init() to request field reception on backends that
263  * distinguish field endpoints, including backend-supported late-join
264  * synchronisation, and record received samples as @c ActionType::kGet.
265  * Used by @c TriggerRecorder and
266  * @c vlink-bag record.
267  * This subscriber still delivers callbacks without a public value cache.
268  * After @c init(), only the discovery role changes; the existing transport
269  * endpoint is not migrated. Use @c Getter for a cached @c get() interface.
270  */
271  void mark_as_getter();
272 
273  private:
274  bool listen_bytes(NodeImpl::MsgCallback&& callback);
275 
276  bool listen_intra(MsgCallback&& callback);
277 };
278 
279 /**
280  * @class SecuritySubscriber
281  * @brief Convenience alias of @c Subscriber with per-message decryption enabled.
282  *
283  * @details
284  * Equivalent to @c Subscriber<MsgT, SecurityType::kWithSecurity>. Every
285  * inbound payload is decrypted with the configured @c Security::Config
286  * before the codec dispatcher is invoked.
287  *
288  * @note Security is not supported on @c intra:// or on @c dds:// CDR
289  * payloads.
290  *
291  * @tparam MsgT C++ message type to subscribe.
292  */
293 template <typename MsgT>
294 class SecuritySubscriber : public Subscriber<MsgT, SecurityType::kWithSecurity> {
295  public:
296  using UniquePtr = std::unique_ptr<SecuritySubscriber<MsgT>>; ///< Owning unique-pointer alias.
297  using SharedPtr = std::shared_ptr<SecuritySubscriber<MsgT>>; ///< Owning shared-pointer alias.
298 
299  /**
300  * @brief Heap-allocates a @c SecuritySubscriber and wraps it in a @c std::unique_ptr.
301  *
302  * @tparam SecurityConfigT Forwardable @c Security::Config compatible type.
303  * @param url_str Topic URL string.
304  * @param sec_cfg Security configuration; empty uses the default symmetric slot.
305  * @param type Whether to call @c init() inline; default is @c InitType::kWithInit.
306  * @return Owning @c UniquePtr to the new secure subscriber.
307  */
308  // NOLINTNEXTLINE(modernize-use-constraints)
309  template <typename SecurityConfigT = Security::Config>
310  [[nodiscard]] static UniquePtr create_unique(const std::string& url_str, SecurityConfigT&& sec_cfg = {},
312 
313  /**
314  * @brief Heap-allocates a @c SecuritySubscriber and wraps it in a @c std::shared_ptr.
315  *
316  * @tparam SecurityConfigT Forwardable @c Security::Config compatible type.
317  * @param url_str Topic URL string.
318  * @param sec_cfg Security configuration; empty uses the default symmetric slot.
319  * @param type Whether to call @c init() inline; default is @c InitType::kWithInit.
320  * @return Owning @c SharedPtr to the new secure subscriber.
321  */
322  // NOLINTNEXTLINE(modernize-use-constraints)
323  template <typename SecurityConfigT = Security::Config>
324  [[nodiscard]] static SharedPtr create_shared(const std::string& url_str, SecurityConfigT&& sec_cfg = {},
326 
327  /**
328  * @brief Constructs a @c SecuritySubscriber from a typed configuration object.
329  *
330  * @tparam ConfT Configuration type derived from @c Conf.
331  * @tparam SecurityConfigT Forwardable @c Security::Config compatible type.
332  * @param conf Populated configuration aggregate.
333  * @param sec_cfg Security configuration; empty uses the default symmetric slot.
334  * @param type Whether to call @c init() inline; default is @c InitType::kWithInit.
335  */
336  // NOLINTNEXTLINE(modernize-use-constraints)
337  template <typename ConfT, typename SecurityConfigT = Security::Config,
338  typename = std::enable_if_t<std::is_base_of_v<Conf, ConfT>>>
339  explicit SecuritySubscriber(const ConfT& conf, SecurityConfigT&& sec_cfg = {}, InitType type = InitType::kWithInit);
340 
341  /**
342  * @brief Constructs a @c SecuritySubscriber from a URL string and installs the security configuration.
343  *
344  * @details
345  * Builds the base @c Subscriber in @c kWithoutInit mode, installs @p sec_cfg
346  * via @c enable_security(), then calls @c init() unless deferred. When
347  * @c enable_security() fails to produce a usable @c NodeImpl::security the
348  * subsequent @c init() will fail.
349  *
350  * @tparam SecurityConfigT Forwardable @c Security::Config compatible type.
351  * @param url_str Topic URL string.
352  * @param sec_cfg Security configuration; empty uses the default symmetric slot.
353  * @param type Whether to call @c init() inline; default is @c InitType::kWithInit.
354  */
355  // NOLINTNEXTLINE(modernize-use-constraints)
356  template <typename SecurityConfigT = Security::Config>
357  explicit SecuritySubscriber(const std::string& url_str, SecurityConfigT&& sec_cfg = {},
359 };
360 
361 } // namespace vlink
362 
Pool-backed type-erased callables: copyable vlink::Function and move-only vlink::MoveFunction.
Common CRTP base for every VLink communication primitive.
Transport-neutral base class for every event-model subscriber implementation.