VLink  2.3.0
A high-performance communication middleware
discovery_viewer.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 discovery_viewer.h
26  * @brief Live aggregator of VLink endpoint announcements emitted by @c DiscoveryReporter.
27  *
28  * @details
29  * @c DiscoveryViewer is the listening counterpart of @c DiscoveryReporter. It joins the
30  * discovery UDP multicast group, decodes incoming announcements, and maintains an
31  * in-memory snapshot of every URL/process currently advertised on the host or network.
32  * It powers @c vlink-cli, dashboards and any custom monitoring tool that needs a live
33  * topology view.
34  *
35  * Filter modes select which announcements survive into the snapshot:
36  *
37  * | Value | Description |
38  * | ------------------- | ---------------------------------------------------------------------------- |
39  * | @c kFilterNone | Keep every announcement regardless of origin |
40  * | @c kFilterAvailable | Drop remote announcements for local-only URL schemes (@c intra, @c shm, ...) |
41  * | @c kFilterNative | Keep only announcements emitted by the same host as the viewer |
42  *
43  * Viewer interaction:
44  *
45  * @verbatim
46  * DiscoveryReporter --(UDP multicast)--> +----------------+ Callback(info_list)
47  * | Viewer | ---------------------> user code
48  * Heartbeat timeout ----+---> | (MessageLoop) | <--- get_info_list()
49  * process_offline() ----+---> +----------------+
50  * @endverbatim
51  *
52  * @par Example
53  * @code
54  * vlink::DiscoveryViewer viewer(vlink::DiscoveryViewer::kFilterAvailable);
55  * viewer.register_callback([](const std::vector<vlink::DiscoveryViewer::Info>& list) {
56  * for (const auto& entry : list) {
57  * VLOG_I("url=", entry.url, " ser=", entry.ser_type,
58  * " hosts=", entry.process_list.size());
59  * }
60  * });
61  * viewer.async_run();
62  * @endcode
63  *
64  * @note The callback runs on the viewer's @c MessageLoop thread; copy the snapshot if it
65  * needs to outlive the call. Endpoints whose heartbeat lapses are pruned automatically.
66  */
67 
68 #pragma once
69 
70 #include <cstdint>
71 #include <memory>
72 #include <string>
73 #include <vector>
74 
75 #include "../base/functional.h"
76 #include "../base/macros.h"
77 #include "../base/message_loop.h"
78 #include "../impl/types.h"
79 
80 namespace vlink {
81 
82 /**
83  * @class DiscoveryViewer
84  * @brief @c MessageLoop-based aggregator of live VLink endpoint announcements.
85  *
86  * @details
87  * Construct with the desired filter and start with @c async_run(). Each viewer is
88  * explicitly owned by the caller; no process-global viewer is exposed. The viewer
89  * rebuilds its @c Info list on demand and notifies the registered callback on its 500 ms
90  * tick whenever the snapshot changed since the previous notification.
91  */
93  public:
94  /**
95  * @brief Selects which announcements contribute to the live snapshot.
96  *
97  * | Value | Effect |
98  * | ----------------- | --------------------------------------------------------------------- |
99  * | kFilterNone | All announcements visible |
100  * | kFilterAvailable | Drop remote announcements for local-only URL schemes |
101  * | kFilterNative | Keep only announcements from the same host |
102  */
103  enum FilterType : uint8_t {
104  kFilterNone = 0, ///< No filtering applied.
105  kFilterAvailable = 1, ///< Drop remote announcements for local-only URL schemes.
106  kFilterNative = 2, ///< Keep only same-host announcements.
107  };
108 
109  /**
110  * @struct Process
111  * @brief Identity of a process that hosts at least one endpoint for a URL.
112  *
113  * @details
114  * Announcements with the same role, host, PID, name and bridge origin share one address list.
115  * Each source address expires independently when its announcements stop.
116  */
117  struct VLINK_EXPORT Process final {
118  uint32_t type{0}; ///< Bitmask of @c ImplType kinds advertised by this process.
119  std::string host; ///< Host name of the process.
120  uint32_t pid{0}; ///< Process identifier.
121  std::string name; ///< Process or application name.
122  std::vector<std::string> ip_list; ///< Live discovery source IPv4 addresses, unique and sorted numerically.
123  double profiler{-1}; ///< CPU usage sample from one live address (-1 when unavailable).
124  bool bridge{false}; /**< Publisher created by proxy forwarding; absent in legacy announcements. */
125 
126  /**
127  * @brief Defines a stable ordering between two process descriptors.
128  *
129  * @details
130  * Sort key is type, then host, name, PID, bridge origin and finally the address list.
131  *
132  * @param target Right-hand operand.
133  * @return @c true when @c *this should appear before @p target.
134  */
135  bool operator<(const Process& target) const noexcept;
136  };
137 
138  /**
139  * @struct Info
140  * @brief One row of the discovery snapshot, describing a URL and its publishers/subscribers.
141  *
142  * @details
143  * Each row aggregates the communication kinds, serialisation type, schema family and
144  * the list of processes that have announced a matching endpoint.
145  */
146  struct VLINK_EXPORT Info final {
147  int sort_index{-1}; ///< Stable sort key assigned internally by the viewer.
148  uint32_t type{0}; ///< Bitmask of @c ImplType kinds for this URL.
149  std::string url; ///< Fully-qualified VLink URL.
150  std::string ser_type; ///< Serialisation type name announced for this URL.
151  SchemaType schema_type{SchemaType::kUnknown}; ///< Coarse schema family derived from announcements.
152  std::vector<Process> process_list; ///< Processes currently hosting this URL.
153 
154  /**
155  * @brief Defines a stable ordering between two snapshot rows.
156  *
157  * @details
158  * Sort key is type, then sort_index, URL, schema family, serialisation type and
159  * finally the process list.
160  *
161  * @param target Right-hand operand.
162  * @return @c true when @c *this should appear before @p target.
163  */
164  bool operator<(const Info& target) const noexcept;
165  };
166 
167  /**
168  * @brief Callback signature delivered when the snapshot changed since the last tick.
169  *
170  * @details
171  * Invoked on the viewer's @c MessageLoop thread with the freshly built list; changes are
172  * coalesced per 500 ms tick, and a newly registered callback receives its first list on the
173  * next tick.
174  */
175  using Callback = Function<void(const std::vector<Info>& info_list)>;
176 
177  /**
178  * @brief Translates a discovery role token to the corresponding @c ImplType bit.
179  *
180  * @param str Role token: @c "Ser", @c "Cli", @c "Pub", @c "Sub", @c "Set" or @c "Get".
181  * @return Matching @c ImplType, or 0 when the token is not recognised.
182  */
183  [[nodiscard]] static ImplType convert_type(std::string_view str);
184 
185  /**
186  * @brief Formats an @c ImplType bitmask as a human-readable label.
187  *
188  * @param type ImplType bitmask.
189  * @return Display string suitable for tooling output.
190  */
191  [[nodiscard]] static std::string convert_type_to_view(uint32_t type);
192 
193  /**
194  * @brief Formats an @c ImplType bitmask together with its process list.
195  *
196  * @param type ImplType bitmask.
197  * @param process_list Processes to include in the display.
198  * @return Combined display string.
199  */
200  [[nodiscard]] static std::string convert_type_to_view(uint32_t type, const std::vector<Process>& process_list);
201 
202  /**
203  * @brief Returns the discovery domain selected by @c VLINK_DISCOVER_DOMAIN.
204  *
205  * @details
206  * The domain isolates the discovery channel so that unrelated deployments sharing one
207  * network never parse each other's announcements. It shifts the UDP port only; the
208  * multicast address and its route stay unchanged. Values that are not a plain decimal
209  * number or fall outside @c [0,255] are rejected and fall back to @c 0, which keeps the
210  * historical port; the @c DiscoveryViewer and @c DiscoveryReporter constructors log the
211  * rejection once. The variable is read once per process, so changing it at runtime has
212  * no effect.
213  *
214  * @return Discovery domain.
215  */
216  [[nodiscard]] static uint32_t get_listen_domain();
217 
218  /**
219  * @brief Returns the UDP multicast/broadcast address used by the discovery subsystem.
220  */
221  [[nodiscard]] static std::string get_listen_address();
222 
223  /**
224  * @brief Returns the UDP port used by the discovery subsystem.
225  *
226  * @return Base port shifted by @c get_listen_domain().
227  */
228  [[nodiscard]] static uint16_t get_listen_port();
229 
230  /**
231  * @brief Builds the viewer with the requested filter mode.
232  *
233  * @param type Filter selecting which announcements survive (default: @c kFilterNone).
234  */
235  explicit DiscoveryViewer(FilterType type = kFilterNone);
236 
237  /**
238  * @brief Stops the viewer loop and releases resources.
239  */
240  ~DiscoveryViewer() override;
241 
242  /**
243  * @brief Registers the callback notified on every snapshot change.
244  *
245  * @details
246  * Replaces any previously installed callback; only the most recent registration
247  * remains effective.
248  *
249  * @param callback Function invoked with the new @c Info list.
250  */
251  void register_callback(Callback&& callback);
252 
253  /**
254  * @brief Returns a copy of the live snapshot at the moment of the call.
255  *
256  * @return Vector of @c Info rows.
257  */
258  [[nodiscard]] std::vector<Info> get_info_list();
259 
260  /**
261  * @brief Resolves the announced serialisation type for @p url.
262  *
263  * @param url Topic URL.
264  * @return Announced serialisation type, or an empty string when unknown.
265  */
266  [[nodiscard]] std::string get_ser_type(const std::string& url) const;
267 
268  /**
269  * @brief Resolves the announced coarse schema family for @p url.
270  *
271  * @param url Topic URL.
272  * @return @c SchemaType, or @c SchemaType::kUnknown when unavailable.
273  */
274  [[nodiscard]] SchemaType get_schema_type(const std::string& url) const;
275 
276  protected:
277  size_t get_max_task_count() const override;
278 
279  uint32_t get_max_elapsed_time() const override;
280 
281  void on_begin() override;
282 
283  void on_end() override;
284 
285  void on_task_timeout(MessageLoop::Callback&& callback, uint32_t elapsed_time) override;
286 
287  private:
288  static void warn_listen_domain();
289 
290  void process_timeout();
291 
292  void process_offline(std::string_view hostname, uint32_t pid, std::string_view process_name);
293 
294  void sort_url(std::vector<std::string>& warnings) const;
295 
296  void refresh_list(std::vector<std::string>& warnings) const;
297 
298  void report_list();
299 
300  struct Impl;
301  std::unique_ptr<Impl> impl_;
302 
303  friend class DiscoveryReporter;
304 
306 };
307 
308 } // namespace vlink
#define VLINK_EXPORT
Definition: macros.h:81
#define VLINK_DISALLOW_COPY_AND_ASSIGN(classname)
Deletes the copy constructor and copy-assignment operator of classname.
Definition: macros.h:174