VLink  2.3.0
A high-performance communication middleware
publisher.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 publisher.h
26  * @brief Write-side primitive of the VLink event communication model.
27  *
28  * @details
29  * @c Publisher<MsgT, SecT> is the message emitter for VLink topics. Each
30  * call to @c publish() serialises an instance of @c MsgT according to the
31  * compile-time-detected codec and hands the resulting payload to the active
32  * transport back-end, which fans the bytes out to every connected
33  * @c Subscriber that shares the same topic URL.
34  *
35  * The class is a thin, header-only template wrapper around @c PublisherImpl;
36  * all runtime work is delegated to the impl. Codec selection is fully
37  * resolved at compile time so the runtime dispatch is zero-cost.
38  *
39  * @par Event-model Data Flow
40  * @verbatim
41  * Publisher<MsgT> Transport Back-end Subscriber<MsgT>
42  * ---------------- ------------------ -----------------
43  * | | |
44  * |-- publish(msg, force) ---------->| |
45  * | Serializer::serialize | |
46  * | (loan-aware on shm/zenoh) | |
47  * | |--- frame on wire ----------->|
48  * | | |
49  * | | |--> callback
50  * | | | Serializer::
51  * | | | deserialize
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, no codec call. |
58  * | SOME/IP struct | @c VLINK_SOMEIP_FIELDS structure | @c kSomeipType | Field-wise SOME/IP payload. |
59  * | Protobuf value | @c MyProto | @c kProtoType | Uses SerializeToArray. |
60  * | Protobuf pointer | @c MyProto* | @c kProtoPtrType | Caller owns lifetime. |
61  * | FlatBuffers obj | @c MyTableT (NativeTable) | @c kFlatTableType | Object API. |
62  * | FlatBuffers ptr | @c MyTable* (Table pointer) | @c kFlatPtrType | Zero-copy read view. |
63  * | FlatBuffers build | @c MyBuilder (@c fbb_ + Finish) | @c kFlatBuilderType | Finishes builder on publish. |
64  * | DDS CDR | FastDDS IDL or ROS2 message type | @c kCdrType | Encapsulated CDR bytes. |
65  * | POD struct | trivial standard-layout type | @c kStandardType | @c sizeof(T) byte copy. |
66  * | Byte string | @c std::string | @c kStringType | Payload bytes, no validation. |
67  * | Custom | type with @c operator>>/<< | @c kCustomType | User-supplied codec. |
68  *
69  * @par Subscriber Detection
70  * Use the detection API to gate writes on the presence of at least one
71  * matching subscriber. This is purely informational; pass @c force=true to
72  * @c publish() if you wish to write regardless of detection state.
73  *
74  * @code
75  * vlink::Publisher<MyMsg> pub("dds://sensor/imu");
76  *
77  * pub.detect_subscribers([&pub](bool present) {
78  * if (present) { pub.publish(MyMsg{}); }
79  * });
80  *
81  * if (pub.wait_for_subscribers(std::chrono::milliseconds(500))) {
82  * pub.publish(MyMsg{});
83  * }
84  *
85  * if (pub.has_subscribers()) { pub.publish(MyMsg{}); }
86  * @endcode
87  *
88  * @par Zero-copy Loan on Loan-capable Transports
89  * @code
90  * vlink::Publisher<vlink::Bytes> pub("shm://image/raw");
91  * if (pub.is_support_loan()) {
92  * vlink::Bytes buf = pub.loan(sizeof(FrameHeader) + payload_size);
93  * ::memcpy(buf.data(), &header, sizeof(header));
94  * pub.publish(buf);
95  * }
96  * @endcode
97  *
98  * @note Loans bypass an extra copy by writing directly into transport-managed
99  * memory. Loans are not used when security is enabled because
100  * ciphertext length differs from plaintext length.
101  *
102  * @see subscriber.h, node.h, serializer.h, extension/security.h
103  */
104 
105 #pragma once
106 
107 #include <memory>
108 #include <string>
109 #include <type_traits>
110 
111 #include "./impl/publisher_impl.h"
112 #include "./node.h"
113 
114 namespace vlink {
115 
116 /**
117  * @class Publisher
118  * @brief Type-safe topic emitter for the VLink event communication model.
119  *
120  * @details
121  * Inherits the full @c Node API (lifecycle, loans, properties, profiler) and
122  * adds publish-specific operations: subscriber detection, blocking wait, and
123  * the @c publish() entry point itself. The transport implementation
124  * (@c PublisherImpl) is selected by the URL scheme or by the typed
125  * configuration object supplied at construction time.
126  *
127  * @tparam MsgT C++ message type. Must satisfy @c Serializer::is_supported().
128  * @tparam SecT Security mode; defaults to @c SecurityType::kWithoutSecurity.
129  */
130 template <typename MsgT, SecurityType SecT = SecurityType::kWithoutSecurity>
131 class Publisher : public Node<PublisherImpl, SecT> {
132  public:
133  using UniquePtr = std::unique_ptr<Publisher<MsgT, SecT>>; ///< Owning unique-pointer alias.
134  using SharedPtr = std::shared_ptr<Publisher<MsgT, SecT>>; ///< Owning shared-pointer alias.
135  using ConnectCallback = NodeImpl::ConnectCallback; ///< Callback type for subscriber presence transitions.
136 
137  static constexpr ImplType kImplType = kPublisher; ///< Node role tag (@c kPublisher).
138  static constexpr Serializer::Type kMsgType = Serializer::get_type_of<MsgT>(); ///< Codec resolved from @c MsgT.
139 
140  static_assert(Serializer::is_supported(kMsgType), "<MsgT> is not a supported Serializer type.");
141 
142  /**
143  * @brief Heap-allocates a @c Publisher and wraps it in a @c std::unique_ptr.
144  *
145  * @param url_str Topic URL string, e.g. @c "dds://vehicle/speed".
146  * @param type Whether to call @c init() inline; default is @c InitType::kWithInit.
147  * @return Owning @c UniquePtr to the newly constructed publisher.
148  */
149  [[nodiscard]] static UniquePtr create_unique(const std::string& url_str, InitType type = InitType::kWithInit);
150 
151  /**
152  * @brief Heap-allocates a @c Publisher and wraps it in a @c std::shared_ptr.
153  *
154  * @param url_str Topic URL string.
155  * @param type Whether to call @c init() inline; default is @c InitType::kWithInit.
156  * @return Owning @c SharedPtr to the newly constructed publisher.
157  */
158  [[nodiscard]] static SharedPtr create_shared(const std::string& url_str, InitType type = InitType::kWithInit);
159 
160  /**
161  * @brief Constructs a publisher from a typed transport configuration object.
162  *
163  * @details
164  * Accepts any @c Conf-derived configuration (@c DdsConf, @c ShmConf,
165  * @c ZenohConf, etc.). A compile-time check enforces that the chosen
166  * configuration permits the publisher role. Invalid configuration or a
167  * @c nullptr factory result triggers a fatal log.
168  *
169  * @tparam ConfT Concrete configuration type derived from @c Conf.
170  * @param conf Populated configuration aggregate.
171  * @param type Whether to call @c init() inline; default is @c InitType::kWithInit.
172  */
173  // NOLINTNEXTLINE(modernize-use-constraints)
174  template <typename ConfT, typename = std::enable_if_t<std::is_base_of_v<Conf, ConfT>>>
175  explicit Publisher(const ConfT& conf, InitType type = InitType::kWithInit);
176 
177  /**
178  * @brief Constructs a publisher from a URL string.
179  *
180  * @details
181  * The URL scheme selects the transport (e.g. @c "shm://" maps to the
182  * Iceoryx back-end, @c "dds://" maps to FastDDS). Internally the string is
183  * parsed into a @c Url and dispatched to the matching @c ConfT.
184  *
185  * @param url_str Topic URL such as @c "shm://vehicle/speed".
186  * @param type Whether to call @c init() inline; default is @c InitType::kWithInit.
187  */
188  explicit Publisher(const std::string& url_str, InitType type = InitType::kWithInit);
189 
190  /**
191  * @brief Registers a callback invoked whenever subscriber presence transitions.
192  *
193  * @details
194  * The callback fires synchronously immediately if a subscriber is already
195  * present at registration time, then asynchronously each time the matching
196  * subscriber set transitions between empty and non-empty. The boolean is
197  * @c true when at least one peer is present.
198  *
199  * @param callback @c void(bool) callable -- @c true means at least one subscriber.
200  */
201  void detect_subscribers(ConnectCallback&& callback);
202 
203  /**
204  * @brief Blocks until at least one subscriber is detected or @p timeout expires.
205  *
206  * @details
207  * A @p timeout of @c 0 is interpreted as infinite (with a warning log). A
208  * negative value also waits indefinitely. Calling @c interrupt() causes the
209  * wait to abort and return @c false.
210  *
211  * @param timeout Maximum wait duration. Default: @c Timeout::kDefaultInterval.
212  * @return @c true if a subscriber appeared; @c false on timeout or interrupt.
213  */
214  bool wait_for_subscribers(std::chrono::milliseconds timeout = Timeout::kDefaultInterval);
215 
216  /**
217  * @brief Non-blocking query of subscriber presence.
218  *
219  * @return @c true when the transport currently knows of at least one matching subscriber.
220  */
221  [[nodiscard]] bool has_subscribers() const;
222 
223  /**
224  * @brief Serialises and emits @p msg to every connected subscriber.
225  *
226  * @details
227  * Serialisation is dispatched to the codec selected by @c kMsgType. On
228  * loan-capable transports, the backend may provide transport-managed memory
229  * when the final size is available; otherwise serialisation uses owning
230  * storage. Loans are skipped when @c SecT == @c kWithSecurity because the
231  * ciphertext size is unknown ahead of encryption.
232  *
233  * When @c force is @c false (the default) the call is skipped and returns
234  * @c false if no subscribers are present. Pass @c force=true to write
235  * unconditionally, e.g. for bag recording or field-style semantics.
236  *
237  * Over @c intra:// with a message whose @c element_type derives from
238  * @c IntraDataType (declared via @c VLINK_INTRA_DATA_DECLARE) the shared
239  * pointer is forwarded zero-copy and no serialisation occurs.
240  *
241  * @param msg Message to publish.
242  * @param force @c true to publish even when no subscribers are connected.
243  * @return @c true if the transport accepted the message.
244  */
245  bool publish(const MsgT& msg, bool force = false);
246 
247  /**
248  * @brief Publishes the raw payload of a pre-finished @c flatbuffers::FlatBufferBuilder.
249  *
250  * @details
251  * Useful in pipelines where the FlatBuffer is constructed externally and
252  * the bytes can be shallow-borrowed without re-serialisation. The pointer
253  * must reference a builder on which @c Finish() has been called.
254  *
255  * @param fbb Pointer to a finished @c flatbuffers::FlatBufferBuilder.
256  * @param force @c true to publish even when no subscribers are connected.
257  * @return @c true on success.
258  */
259  bool publish_fbb(const void* fbb, bool force = false);
260 
261  /**
262  * @brief Marks this publisher as a field writer.
263  *
264  * @details
265  * Call before @c init() to request field transport settings where supported
266  * and record published samples as @c ActionType::kSet.
267  * After @c init(), only the discovery role changes; the endpoint is not migrated.
268  * Does not add a public value cache; transport history depends on the backend.
269  * Publishing without connected readers still requires @c force=true.
270  * Use @c Setter when latest-value retention and late-getter replay are needed.
271  */
272  void mark_as_setter();
273 
274  private:
275  bool write_bytes(const Bytes& data);
276 
277  bool write_intra(const IntraData& intra_data);
278 };
279 
280 /**
281  * @class SecurityPublisher
282  * @brief Convenience alias of @c Publisher with per-message security enabled.
283  *
284  * @details
285  * Equivalent to @c Publisher<MsgT, SecurityType::kWithSecurity>. Every
286  * outgoing payload is encrypted with the configured @c Security::Config
287  * before transmission; an empty config falls back to the built-in default
288  * symmetric slot.
289  *
290  * @note Security is not supported on @c intra:// or on @c dds:// CDR
291  * payloads -- using a @c SecurityPublisher in those configurations is
292  * a constructor-time fatal.
293  *
294  * @tparam MsgT C++ message type to publish.
295  */
296 template <typename MsgT>
297 class SecurityPublisher : public Publisher<MsgT, SecurityType::kWithSecurity> {
298  public:
299  using UniquePtr = std::unique_ptr<SecurityPublisher<MsgT>>; ///< Owning unique-pointer alias.
300  using SharedPtr = std::shared_ptr<SecurityPublisher<MsgT>>; ///< Owning shared-pointer alias.
301 
302  /**
303  * @brief Heap-allocates a @c SecurityPublisher and wraps it in a @c std::unique_ptr.
304  *
305  * @tparam SecurityConfigT Forwardable @c Security::Config compatible type.
306  * @param url_str Topic URL string.
307  * @param sec_cfg Security configuration; empty uses the default symmetric slot.
308  * @param type Whether to call @c init() inline; default is @c InitType::kWithInit.
309  * @return Owning @c UniquePtr to the new secure publisher.
310  */
311  // NOLINTNEXTLINE(modernize-use-constraints)
312  template <typename SecurityConfigT = Security::Config>
313  [[nodiscard]] static UniquePtr create_unique(const std::string& url_str, SecurityConfigT&& sec_cfg = {},
315 
316  /**
317  * @brief Heap-allocates a @c SecurityPublisher and wraps it in a @c std::shared_ptr.
318  *
319  * @tparam SecurityConfigT Forwardable @c Security::Config compatible type.
320  * @param url_str Topic URL string.
321  * @param sec_cfg Security configuration; empty uses the default symmetric slot.
322  * @param type Whether to call @c init() inline; default is @c InitType::kWithInit.
323  * @return Owning @c SharedPtr to the new secure publisher.
324  */
325  // NOLINTNEXTLINE(modernize-use-constraints)
326  template <typename SecurityConfigT = Security::Config>
327  [[nodiscard]] static SharedPtr create_shared(const std::string& url_str, SecurityConfigT&& sec_cfg = {},
329 
330  /**
331  * @brief Constructs a @c SecurityPublisher from a typed configuration object.
332  *
333  * @details
334  * Constructs the base @c Publisher in @c kWithoutInit mode, installs
335  * @p sec_cfg via @c enable_security(), then runs @c init() unless deferred.
336  * If @c enable_security() fails to populate a usable security object the
337  * subsequent @c init() will fail.
338  *
339  * @tparam ConfT Configuration type derived from @c Conf.
340  * @tparam SecurityConfigT Forwardable @c Security::Config compatible type.
341  * @param conf Populated configuration aggregate.
342  * @param sec_cfg Security configuration; empty uses the default symmetric slot.
343  * @param type Whether to call @c init() inline; default is @c InitType::kWithInit.
344  */
345  // NOLINTNEXTLINE(modernize-use-constraints)
346  template <typename ConfT, typename SecurityConfigT = Security::Config,
347  typename = std::enable_if_t<std::is_base_of_v<Conf, ConfT>>> // NOLINT(modernize-use-constraints)
348  explicit SecurityPublisher(const ConfT& conf, SecurityConfigT&& sec_cfg = {}, InitType type = InitType::kWithInit);
349 
350  /**
351  * @brief Constructs a @c SecurityPublisher from a URL string.
352  *
353  * @tparam SecurityConfigT Forwardable @c Security::Config compatible type.
354  * @param url_str Topic URL string.
355  * @param sec_cfg Security configuration; empty uses the default symmetric slot.
356  * @param type Whether to call @c init() inline; default is @c InitType::kWithInit.
357  */
358  // NOLINTNEXTLINE(modernize-use-constraints)
359  template <typename SecurityConfigT = Security::Config>
360  explicit SecurityPublisher(const std::string& url_str, SecurityConfigT&& sec_cfg = {},
362 };
363 
364 } // namespace vlink
365 
Common CRTP base for every VLink communication primitive.
Transport-neutral base class for every event-model publisher implementation.