VLink  2.3.0
A high-performance communication middleware
abstract_factory.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 abstract_factory.h
26  * @brief Topic-scoped registration store that fans transport callbacks across @c NodeImpl peers.
27  *
28  * @details
29  * This is an internal implementation header used by the public VLink node templates
30  * (@c Publisher, @c Subscriber, @c Client, @c Server, @c Setter, @c Getter); it should not
31  * be included directly by application code. The header introduces two co-operating
32  * class templates that let several @c NodeImpl instances bound to the same logical
33  * topic share one registration record:
34  *
35  * - @c AbstractObject -- a per-topic record that owns the set of registered
36  * @c NodeImpl pointers together with six callback dictionaries (server connect,
37  * subscriber connect, request/response, serialised message, intra-process message
38  * and transport status).
39  * - @c AbstractFactory -- a thread-safe map keyed on @c FilterT (commonly the
40  * topic URL string) that lazily creates an @c AbstractObject for each key and
41  * reuses it via a cached @c std::weak_ptr until the last owner releases it.
42  *
43  * @par Registration flow
44  * @code
45  * +----------------------+
46  * | AbstractFactory<K> |
47  * | map<K, weak_ptr<O>> |
48  * +----------+-----------+
49  * | get_object<O>(key)
50  * v
51  * +----------------------+
52  * | AbstractObject<K> |
53  * | ImplList |
54  * | ConnectCallbackMap |
55  * | MsgCallbackMap ... |
56  * +----------+-----------+
57  * ^ | ^
58  * add_impl(impl) | | | register_msg_callback(impl, cb)
59  * remove_impl(impl)| | |
60  * | v
61  * +------+--+ +-+--------+ +----------+
62  * | NodeImpl| | NodeImpl | | NodeImpl |
63  * +---------+ +----------+ +----------+
64  * @endcode
65  *
66  * @par Registry keys
67  * | Map field | Callback signature |
68  * | ------------------------------- | ------------------------------------------------- |
69  * | @c server_connect_callback_map_ | @c void(bool) -- server side peer presence change |
70  * | @c sub_connect_callback_map_ | @c void(bool) -- subscriber side presence change |
71  * | @c req_resp_callback_map_ | @c void(uint64_t, const Bytes&, Bytes*) |
72  * | @c msg_callback_map_ | @c void(const Bytes&) |
73  * | @c intra_msg_callback_map_ | @c void(const IntraData&) |
74  * | @c status_callback_map_ | @c void(const Status::BasePtr&) |
75  *
76  * @par Example
77  * @code
78  * struct TopicObject final : vlink::AbstractObject<std::string> {
79  * using AbstractObject::AbstractObject;
80  * };
81  *
82  * vlink::AbstractFactory<std::string> factory;
83  *
84  * auto object = factory.get_object<TopicObject>("dds://my_topic");
85  * object->add_impl(impl);
86  * object->register_msg_callback(impl, [](const vlink::Bytes& bytes) {
87  * // forward each delivery to the owning node
88  * });
89  *
90  * object->traverse_msg_callback([](vlink::NodeImpl*, const vlink::NodeImpl::MsgCallback& cb) {
91  * cb(payload);
92  * });
93  * @endcode
94  *
95  * @note Every public @c AbstractObject method acquires the internal
96  * @c std::recursive_mutex; callbacks invoked through @c traverse_*() execute
97  * under that lock and may re-enter the same @c AbstractObject safely.
98  *
99  * @tparam FilterT Key type used to identify topics inside the factory map.
100  */
101 
102 #pragma once
103 
104 #include <map>
105 #include <memory>
106 #include <mutex>
107 #include <unordered_set>
108 #include <utility>
109 #include <vector>
110 
111 #include "../base/functional.h"
112 #include "../base/logger.h"
113 #include "./node_impl.h"
114 
115 namespace vlink {
116 
117 /**
118  * @class AbstractObject
119  * @brief Topic-scoped fan-out store of @c NodeImpl peers and their callbacks.
120  *
121  * @details
122  * Holds the active @c NodeImpl pointer set together with the six callback
123  * dictionaries documented at file scope and serialises mutation, traversal and
124  * accounting through a @c std::recursive_mutex. The traversal helpers honour
125  * the @c ignore_called() escape hatch so that individual callbacks can opt out
126  * of the "any callback was invoked" accounting tracked by @c has_called().
127  * Mutations that arrive while a traversal is running on the same thread are
128  * deferred: removals queue up and apply once the outermost traversal unwinds,
129  * so a handler that removes its own @c NodeImpl keeps executing on a live
130  * callable without per-entry copies or shared ownership, while node-based
131  * callback storage keeps live traversal iterators valid across registrations.
132  *
133  * @tparam FilterT Key type used by the owning @c AbstractFactory for this object.
134  */
135 template <typename FilterT>
136 class AbstractObject : public AbstractNode {
137  public:
138  using ImplList = std::unordered_set<NodeImpl*>; ///< Set of currently registered @c NodeImpl peers.
139 
140  using ConnectCallbackMap = std::map<NodeImpl*, NodeImpl::ConnectCallback>; ///< Connect handlers per impl.
141  using ReqRespCallbackMap = std::map<NodeImpl*, NodeImpl::ReqRespCallback>; ///< Req/resp callbacks, keyed by impl.
142  using MsgCallbackMap = std::map<NodeImpl*, NodeImpl::MsgCallback>; ///< Message callbacks, keyed by impl.
143  using IntraMsgCallbackMap = std::map<NodeImpl*, NodeImpl::IntraMsgCallback>; ///< Intra-message callbacks.
144  using StatusCallbackMap = std::map<NodeImpl*, NodeImpl::StatusCallback>; ///< Status callbacks per impl.
145 
147  Function<void(NodeImpl*, const NodeImpl::ConnectCallback&)>; ///< Visitor invoked for each connect entry.
149  Function<void(NodeImpl*, const NodeImpl::ReqRespCallback&)>; ///< Visitor invoked for each req/resp entry.
151  Function<void(NodeImpl*, const NodeImpl::MsgCallback&)>; ///< Visitor invoked for each message entry.
153  Function<void(NodeImpl*, const NodeImpl::IntraMsgCallback&)>; ///< Visitor for each intra-message entry.
155  Function<void(NodeImpl*, const NodeImpl::StatusCallback&)>; ///< Visitor invoked for each status entry.
156 
157  /**
158  * @brief Registers @p impl as an active peer on this topic.
159  *
160  * @details
161  * Inserts @p impl into @c impl_list_ and refreshes the cached @c first_impl_
162  * pointer to the latest registrant. The operation is serialised against all
163  * other public methods.
164  *
165  * @param impl Non-owning peer pointer to track.
166  * @return @c true when the pointer was newly inserted; @c false when it was
167  * already present.
168  */
169  bool add_impl(NodeImpl* impl);
170 
171  /**
172  * @brief Removes @p impl from the peer set and forgets every associated callback.
173  *
174  * @details
175  * Erases the pointer from @c impl_list_, reassigns @c first_impl_ if needed
176  * and drops the entry from all six callback dictionaries. Thread-safe.
177  *
178  * @param impl Peer pointer previously passed to @c add_impl().
179  * @return @c true if @p impl was found and removed; @c false otherwise.
180  */
181  bool remove_impl(NodeImpl* impl);
182 
183  /**
184  * @brief Returns the most recently registered peer.
185  *
186  * @details
187  * The "first" pointer follows the latest successful @c add_impl() call. After
188  * a matching @c remove_impl() the cache is repopulated with an arbitrary
189  * remaining peer, or @c nullptr if the set has been drained.
190  *
191  * @return Pointer to the current cached peer; @c nullptr when no peer is registered.
192  */
193  [[nodiscard]] NodeImpl* get_first_impl() const;
194 
195  /**
196  * @brief Tests whether @p impl is currently part of the peer set.
197  *
198  * @param impl Pointer to query.
199  * @return @c true when @p impl is registered, @c false otherwise.
200  */
201  [[nodiscard]] bool is_contains_impl(NodeImpl* impl) const;
202 
203  /**
204  * @brief Indicates whether at least one peer has been registered.
205  *
206  * @return @c true when @c impl_list_ is non-empty.
207  */
208  [[nodiscard]] bool has_impl() const;
209 
210  /**
211  * @brief Stores @p callback as the server-side connect handler for @p impl.
212  *
213  * @param impl Peer that owns @p callback.
214  * @param callback Callable @c void(bool) invoked when a remote client comes or goes.
215  * @return @c true if the entry was inserted; @c false when one was already present.
216  */
218 
219  /**
220  * @brief Stores @p callback as the subscriber-side connect handler for @p impl.
221  *
222  * @param impl Peer that owns @p callback.
223  * @param callback Callable @c void(bool) invoked when a subscriber appears or disappears.
224  * @return @c true if the entry was inserted; @c false when one was already present.
225  */
227 
228  /**
229  * @brief Stores @p callback as the request/response handler for @p impl.
230  *
231  * @param impl Peer that owns @p callback.
232  * @param callback Callable invoked for every incoming RPC request.
233  * @return @c true on insertion; @c false when already registered.
234  */
236 
237  /**
238  * @brief Stores @p callback as the serialised-message handler for @p impl.
239  *
240  * @param impl Peer that owns @p callback.
241  * @param callback Callable @c void(const Bytes&) invoked for every received message.
242  * @return @c true on insertion; @c false when already registered.
243  */
244  bool register_msg_callback(NodeImpl* impl, NodeImpl::MsgCallback&& callback);
245 
246  /**
247  * @brief Stores @p callback as the intra-process message handler for @p impl.
248  *
249  * @param impl Peer that owns @p callback.
250  * @param callback Callable @c void(const IntraData&) invoked for each in-process delivery.
251  * @return @c true on insertion; @c false when already registered.
252  */
254 
255  /**
256  * @brief Stores @p callback as the transport-status handler for @p impl.
257  *
258  * @param impl Peer that owns @p callback.
259  * @param callback Callable invoked when the transport reports a status change.
260  * @return @c true on insertion; @c false when already registered.
261  */
263 
264  /**
265  * @brief Reports whether the server-connect dictionary is empty.
266  *
267  * @return @c true when no server-connect callbacks are registered.
268  */
269  [[nodiscard]] bool server_connect_map_is_empty() const;
270 
271  /**
272  * @brief Reports whether the subscriber-connect dictionary is empty.
273  *
274  * @return @c true when no subscriber-connect callbacks are registered.
275  */
276  [[nodiscard]] bool sub_connect_map_is_empty() const;
277 
278  /**
279  * @brief Reports whether the request/response dictionary is empty.
280  *
281  * @return @c true when no req/resp callbacks are registered.
282  */
283  [[nodiscard]] bool req_resp_map_is_empty() const;
284 
285  /**
286  * @brief Reports whether the serialised-message dictionary is empty.
287  *
288  * @return @c true when no message callbacks are registered.
289  */
290  [[nodiscard]] bool msg_map_is_empty() const;
291 
292  /**
293  * @brief Reports whether the intra-process message dictionary is empty.
294  *
295  * @return @c true when no intra-message callbacks are registered.
296  */
297  [[nodiscard]] bool intra_msg_map_is_empty() const;
298 
299  /**
300  * @brief Reports whether the transport-status dictionary is empty.
301  *
302  * @return @c true when no status callbacks are registered.
303  */
304  [[nodiscard]] bool status_map_is_empty() const;
305 
306  /**
307  * @brief Walks the server-connect dictionary and invokes @p callback for every entry.
308  *
309  * @details
310  * Iteration is performed while holding the recursive mutex. Individual visits
311  * may call @c ignore_called() to keep the current entry from setting the
312  * @c has_called() flag; iteration carries on regardless.
313  *
314  * @param callback Visitor receiving each peer pointer and its stored handler.
315  */
317 
318  /**
319  * @brief Walks the subscriber-connect dictionary and invokes @p callback for every entry.
320  *
321  * @param callback Visitor receiving each peer pointer and its stored handler.
322  */
324 
325  /**
326  * @brief Walks the request/response dictionary and invokes @p callback for every entry.
327  *
328  * @param callback Visitor receiving each peer pointer and its stored handler.
329  */
330  void traverse_req_resp_callback(const FindReqRespCallback& callback);
331 
332  /**
333  * @brief Walks the serialised-message dictionary and invokes @p callback for every entry.
334  *
335  * @param callback Visitor receiving each peer pointer and its stored handler.
336  */
337  void traverse_msg_callback(const FindMsgCallback& callback);
338 
339  /**
340  * @brief Walks the intra-process dictionary and invokes @p callback for every entry.
341  *
342  * @param callback Visitor receiving each peer pointer and its stored handler.
343  */
345 
346  /**
347  * @brief Walks the transport-status dictionary and invokes @p callback for every entry.
348  *
349  * @param callback Visitor receiving each peer pointer and its stored handler.
350  */
351  void traverse_status_callback(const FindStatusCallback& callback);
352 
353  /**
354  * @brief Invokes a registered owner's message handler without copying its state.
355  *
356  * @param owner Node whose message handler is invoked.
357  * @param bytes Payload forwarded to the handler.
358  * @return @c true when the owner is registered and the handler ran.
359  */
360  bool invoke_msg_callback(NodeImpl* owner, const Bytes& bytes);
361 
362  /**
363  * @brief Visits a registered owner's request handler while keeping its registration live.
364  *
365  * @param owner Node whose request handler is visited.
366  * @param callback Visitor receiving the owner and its handler.
367  * @return @c true when the owner is registered and the visitor ran.
368  */
369  bool invoke_req_resp_callback(NodeImpl* owner, const FindReqRespCallback& callback);
370 
371  /**
372  * @brief Runs a callback only while its owner remains registered.
373  *
374  * @param owner Node that must still be registered.
375  * @param callback Work to run under the registration guard.
376  * @return @c true when the owner is registered and the callback ran.
377  */
378  bool invoke_callback(NodeImpl* owner, const Function<void()>& callback);
379 
380  protected:
382 
383  ~AbstractObject() override;
384 
385  [[nodiscard]] bool has_called() const;
386 
387  void ignore_called();
388 
389  private:
390  struct TraverseGuard final {
391  AbstractObject& object;
392 
393  ~TraverseGuard() {
394  --object.traverse_depth_;
395 
396  if VLIKELY (object.traverse_depth_ == 0) {
397  object.apply_deferred_removals();
398  }
399  }
400  };
401 
402  template <typename CallbackMapT, typename CallbackT>
403  bool register_internal_callback(CallbackMapT& map, NodeImpl* impl, CallbackT&& callback);
404 
405  template <typename CallbackMapT>
406  [[nodiscard]] bool is_map_effectively_empty(const CallbackMapT& map) const;
407 
408  template <typename CallbackMapT, typename CallbackT>
409  void traverse_internal_callback(const CallbackMapT& map, const CallbackT& callback);
410 
411  template <typename CallbackMapT, typename CallbackT>
412  bool invoke_internal_callback(const CallbackMapT& map, NodeImpl* owner, const CallbackT& callback);
413 
414  [[nodiscard]] bool is_deferred_removed(NodeImpl* impl) const;
415 
416  void erase_impl_callbacks(NodeImpl* impl);
417 
418  void apply_deferred_removals();
419 
420  bool has_called_{false};
421  bool ignore_called_{false};
422  size_t traverse_depth_{0};
423  ImplList impl_list_;
424  std::vector<NodeImpl*> deferred_remove_list_;
425  mutable std::recursive_mutex mtx_;
426  ConnectCallbackMap server_connect_callback_map_;
427  ConnectCallbackMap sub_connect_callback_map_;
428  ReqRespCallbackMap req_resp_callback_map_;
429  MsgCallbackMap msg_callback_map_;
430  IntraMsgCallbackMap intra_msg_callback_map_;
431  StatusCallbackMap status_callback_map_;
432  NodeImpl* first_impl_{nullptr};
433 
435 };
436 
437 /**
438  * @class AbstractFactory
439  * @brief Lazily allocates and caches @c AbstractObject instances keyed by @c FilterT.
440  *
441  * @details
442  * Holds a @c std::map<FilterT, std::weak_ptr<Object>> so that multiple node
443  * peers requesting the same key reuse the same registration record. The
444  * returned @c std::shared_ptr carries a custom deleter that erases the map
445  * entry when the last owner releases the object, which keeps the lookup map
446  * free of stale @c weak_ptr slots.
447  *
448  * @note The factory itself is non-copyable and non-movable; share it through a
449  * singleton or a per-transport static instance.
450  *
451  * @tparam FilterT Topic-key type (typically @c std::string).
452  */
453 template <typename FilterT>
456  using Map = std::map<FilterT, std::weak_ptr<Object>>;
457  using Set = std::unordered_set<Object*>;
458 
459  public:
460  /**
461  * @brief Tests whether @p ptr corresponds to a live object created by this factory.
462  *
463  * @param ptr Raw pointer to validate.
464  * @return @c true when the object is still alive in this factory; @c false otherwise.
465  */
466  [[nodiscard]] bool has_object(Object* ptr) const;
467 
468  /**
469  * @brief Looks up or creates the @c ObjectT registered against @p filter.
470  *
471  * @details
472  * If the cached @c weak_ptr is still valid, the existing instance is shared
473  * with the caller. Otherwise a new @c ObjectT is allocated (outside the
474  * factory lock so its constructor can re-enter VLink safely), the resulting
475  * @c shared_ptr is given a deleter that removes the cache entry on
476  * destruction, and the value is stored back into the map.
477  *
478  * @tparam ObjectT Concrete subclass of @c AbstractObject<FilterT> to allocate.
479  *
480  * @param filter Key identifying the topic.
481  * @return Shared ownership handle for the cached object.
482  */
483  template <typename ObjectT>
484  [[nodiscard]] std::shared_ptr<ObjectT> get_object(const FilterT& filter);
485 
486  protected:
487  /**
488  * @brief Constructs an empty factory.
489  */
491 
492  /**
493  * @brief Destroys the factory and releases the cache.
494  */
495  virtual ~AbstractFactory();
496 
497  private:
498  Set set_;
499  Map map_;
500  mutable std::mutex mtx_;
501 
503 };
504 
505 ////////////////////////////////////////////////////////////////
506 /// Details
507 ////////////////////////////////////////////////////////////////
508 
509 template <typename FilterT>
511  std::lock_guard lock(mtx_);
512 
513  if VUNLIKELY (is_deferred_removed(impl)) {
514  return false;
515  }
516 
517  first_impl_ = impl;
518 
519  return impl_list_.emplace(impl).second;
520 }
521 
522 template <typename FilterT>
524  std::lock_guard lock(mtx_);
525 
526  if VUNLIKELY (traverse_depth_ != 0) {
527  if VUNLIKELY (impl_list_.find(impl) == impl_list_.end() || is_deferred_removed(impl)) {
528  return false;
529  }
530 
531  deferred_remove_list_.push_back(impl);
532 
533  if (first_impl_ == impl) {
534  first_impl_ = nullptr;
535  }
536 
537  return true;
538  }
539 
540  if VUNLIKELY (impl_list_.erase(impl) == 0) {
541  return false; // LCOV_EXCL_LINE GCOVR_EXCL_LINE
542  }
543 
544  if (first_impl_ == impl) {
545  first_impl_ = impl_list_.empty() ? nullptr : *impl_list_.begin();
546  }
547 
548  erase_impl_callbacks(impl);
549 
550  return true;
551 }
552 
553 template <typename FilterT>
555  std::lock_guard lock(mtx_);
556  return first_impl_;
557 }
558 
559 template <typename FilterT>
561  std::lock_guard lock(mtx_);
562  return impl_list_.find(impl) != impl_list_.end() && !is_deferred_removed(impl);
563 }
564 
565 template <typename FilterT>
567  std::lock_guard lock(mtx_);
568 
569  if VLIKELY (deferred_remove_list_.empty()) {
570  return !impl_list_.empty();
571  }
572 
573  for (auto* impl : impl_list_) {
574  if (!is_deferred_removed(impl)) {
575  return true;
576  }
577  }
578 
579  return false;
580 }
581 
582 template <typename FilterT>
584  NodeImpl::ConnectCallback&& callback) {
585  return register_internal_callback(server_connect_callback_map_, impl, std::move(callback));
586 }
587 
588 template <typename FilterT>
590  NodeImpl::ConnectCallback&& callback) {
591  return register_internal_callback(sub_connect_callback_map_, impl, std::move(callback));
592 }
593 
594 template <typename FilterT>
596  return register_internal_callback(req_resp_callback_map_, impl, std::move(callback));
597 }
598 
599 template <typename FilterT>
601  return register_internal_callback(msg_callback_map_, impl, std::move(callback));
602 }
603 
604 template <typename FilterT>
606  NodeImpl::IntraMsgCallback&& callback) {
607  return register_internal_callback(intra_msg_callback_map_, impl, std::move(callback));
608 }
609 
610 template <typename FilterT>
612  return register_internal_callback(status_callback_map_, impl, std::move(callback));
613 }
614 
615 template <typename FilterT>
617  std::lock_guard lock(this->mtx_);
618  return is_map_effectively_empty(server_connect_callback_map_);
619 }
620 
621 template <typename FilterT>
623  std::lock_guard lock(this->mtx_);
624  return is_map_effectively_empty(sub_connect_callback_map_);
625 }
626 
627 template <typename FilterT>
629  std::lock_guard lock(this->mtx_);
630  return is_map_effectively_empty(req_resp_callback_map_);
631 }
632 
633 template <typename FilterT>
635  std::lock_guard lock(this->mtx_);
636  return is_map_effectively_empty(msg_callback_map_);
637 }
638 
639 template <typename FilterT>
641  std::lock_guard lock(this->mtx_);
642  return is_map_effectively_empty(intra_msg_callback_map_);
643 }
644 
645 template <typename FilterT>
647  std::lock_guard lock(this->mtx_);
648  return is_map_effectively_empty(status_callback_map_);
649 }
650 
651 template <typename FilterT>
653  this->traverse_internal_callback(server_connect_callback_map_, callback);
654 }
655 
656 template <typename FilterT>
658  this->traverse_internal_callback(sub_connect_callback_map_, callback);
659 }
660 
661 template <typename FilterT>
663  this->traverse_internal_callback(req_resp_callback_map_, callback);
664 }
665 
666 template <typename FilterT>
668  this->traverse_internal_callback(msg_callback_map_, callback);
669 }
670 
671 template <typename FilterT>
673  this->traverse_internal_callback(intra_msg_callback_map_, callback);
674 }
675 
676 template <typename FilterT>
678  this->traverse_internal_callback(status_callback_map_, callback);
679 }
680 
681 template <typename FilterT>
682 template <typename CallbackMapT, typename CallbackT>
683 inline bool AbstractObject<FilterT>::invoke_internal_callback(const CallbackMapT& map, NodeImpl* owner,
684  const CallbackT& callback) {
685  std::lock_guard lock(mtx_);
686 
687  auto iter = map.find(owner);
688 
689  if VUNLIKELY (iter == map.end() || is_deferred_removed(owner)) {
690  return false;
691  }
692 
693  ++traverse_depth_;
694 
695  TraverseGuard guard{*this};
696 
697  callback(iter->second);
698 
699  return true;
700 }
701 
702 template <typename FilterT>
704  return invoke_internal_callback(msg_callback_map_, owner, [&bytes](const auto& callback) { callback(bytes); });
705 }
706 
707 template <typename FilterT>
709  return invoke_internal_callback(req_resp_callback_map_, owner,
710  [owner, &callback](const auto& target) { callback(owner, target); });
711 }
712 
713 template <typename FilterT>
714 inline bool AbstractObject<FilterT>::invoke_callback(NodeImpl* owner, const Function<void()>& callback) {
715  std::lock_guard lock(mtx_);
716 
717  if VUNLIKELY (impl_list_.find(owner) == impl_list_.end() || is_deferred_removed(owner)) {
718  return false;
719  }
720 
721  ++traverse_depth_;
722 
723  TraverseGuard guard{*this};
724 
725  callback();
726 
727  return true;
728 }
729 
730 template <typename FilterT>
731 inline AbstractObject<FilterT>::AbstractObject() = default;
732 
733 template <typename FilterT>
735 
736 template <typename FilterT>
738  return has_called_;
739 }
740 
741 template <typename FilterT>
743  ignore_called_ = true;
744 }
745 
746 template <typename FilterT>
747 template <typename CallbackMapT, typename CallbackT>
748 inline bool AbstractObject<FilterT>::register_internal_callback(CallbackMapT& map, NodeImpl* impl,
749  CallbackT&& callback) {
750  std::lock_guard lock(mtx_);
751 
752  if VUNLIKELY (is_deferred_removed(impl)) {
753  return false;
754  }
755 
756  return map.try_emplace(impl, std::forward<CallbackT>(callback)).second;
757 }
758 
759 template <typename FilterT>
760 template <typename CallbackMapT>
761 inline bool AbstractObject<FilterT>::is_map_effectively_empty(const CallbackMapT& map) const {
762  if VLIKELY (deferred_remove_list_.empty()) {
763  return map.empty();
764  }
765 
766  for (const auto& item : map) {
767  if (!is_deferred_removed(item.first)) {
768  return false;
769  }
770  }
771 
772  return true;
773 }
774 
775 template <typename FilterT>
776 template <typename CallbackMapT, typename CallbackT>
777 inline void AbstractObject<FilterT>::traverse_internal_callback(const CallbackMapT& map, const CallbackT& callback) {
778  std::lock_guard lock(mtx_);
779 
780  this->ignore_called_ = false;
781  this->has_called_ = false;
782 
783  ++traverse_depth_;
784 
785  TraverseGuard guard{*this};
786 
787  for (const auto& [impl, target_callback] : map) {
788  if VUNLIKELY (is_deferred_removed(impl)) {
789  continue;
790  }
791 
792  callback(impl, target_callback);
793 
794  if VUNLIKELY (this->ignore_called_) {
795  this->ignore_called_ = false;
796  } else {
797  this->has_called_ = true;
798  }
799  }
800 }
801 
802 template <typename FilterT>
803 inline bool AbstractObject<FilterT>::is_deferred_removed(NodeImpl* impl) const {
804  for (auto* target : deferred_remove_list_) {
805  if (target == impl) {
806  return true;
807  }
808  }
809 
810  return false;
811 }
812 
813 template <typename FilterT>
814 inline void AbstractObject<FilterT>::erase_impl_callbacks(NodeImpl* impl) {
815  server_connect_callback_map_.erase(impl);
816  sub_connect_callback_map_.erase(impl);
817  req_resp_callback_map_.erase(impl);
818  msg_callback_map_.erase(impl);
819  intra_msg_callback_map_.erase(impl);
820  status_callback_map_.erase(impl);
821 }
822 
823 template <typename FilterT>
824 inline void AbstractObject<FilterT>::apply_deferred_removals() {
825  if VLIKELY (deferred_remove_list_.empty()) {
826  return;
827  }
828 
829  for (auto* impl : deferred_remove_list_) {
830  impl_list_.erase(impl);
831  erase_impl_callbacks(impl);
832  }
833 
834  deferred_remove_list_.clear();
835 
836  if (first_impl_ == nullptr && !impl_list_.empty()) {
837  first_impl_ = *impl_list_.begin();
838  }
839 }
840 
841 template <typename FilterT>
843  std::lock_guard lock(mtx_);
844  return set_.count(ptr) > 0;
845 }
846 
847 template <typename FilterT>
848 template <typename ObjectT>
849 inline std::shared_ptr<ObjectT> AbstractFactory<FilterT>::get_object(const FilterT& filter) {
850  static_assert(std::is_base_of_v<Object, ObjectT>, "ObjectT must be derived from AbstractObject");
851  std::shared_ptr<ObjectT> obj;
852  {
853  std::unique_lock lock(mtx_);
854 
855  const auto& deleter = [this, filter](ObjectT* obj) {
856  {
857  std::lock_guard lock(mtx_);
858 
859  set_.erase(obj);
860 
861  auto iter = map_.find(filter);
862 
863  if VUNLIKELY (iter != map_.end() && iter->second.expired()) {
864  map_.erase(iter);
865  }
866  }
867 
868  delete obj;
869  };
870 
871  auto iter = map_.find(filter);
872 
873  if (iter != map_.end()) {
874  obj = std::static_pointer_cast<ObjectT>(iter->second.lock());
875 
876  if VLIKELY (obj) {
877  return obj;
878  }
879 
880  map_.erase(iter); // LCOV_EXCL_LINE GCOVR_EXCL_LINE
881  }
882 
883  {
884  lock.unlock();
885  auto* obj_ptr = new ObjectT(filter);
886  lock.lock();
887 
888  auto [it, inserted] = map_.try_emplace(filter, std::weak_ptr<Object>());
889 
890  if (!inserted) {
891  obj = std::static_pointer_cast<ObjectT>(it->second.lock()); // LCOV_EXCL_LINE GCOVR_EXCL_LINE
892  }
893 
894  if (inserted || !obj) {
895  if (!inserted) {
896  map_.erase(it); // LCOV_EXCL_LINE GCOVR_EXCL_LINE
897  it = map_.try_emplace(filter, std::weak_ptr<Object>()).first; // LCOV_EXCL_LINE GCOVR_EXCL_LINE
898  }
899 
900  obj = std::shared_ptr<ObjectT>(obj_ptr, deleter);
901  it->second = obj;
902  set_.emplace(obj_ptr);
903  } else {
904  delete obj_ptr; // LCOV_EXCL_LINE GCOVR_EXCL_LINE
905  }
906  }
907  return obj;
908  }
909 } // LCOV_EXCL_LINE GCOVR_EXCL_LINE
910 
911 template <typename FilterT>
913 
914 template <typename FilterT>
916 
917 } // namespace vlink
#define VUNLIKELY(...)
Short alias for VLINK_UNLIKELY.
Definition: macros.h:292
#define VLIKELY(...)
Short alias for VLINK_LIKELY.
Definition: macros.h:284
#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.