VLink  2.3.0
A high-performance communication middleware
server-inl.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 #pragma once
25 
26 #include <memory>
27 #include <string>
28 #include <utility>
29 
30 #include "../base/cpu_profiler_guard.h"
31 #include "../base/logger.h"
32 #include "../impl/url.h"
33 #include "../serializer.h"
34 #include "../server.h"
35 
36 namespace vlink {
37 
38 template <typename ReqT, typename RespT, SecurityType SecT>
40  const std::string& url_str, InitType type) {
41  return std::make_unique<Server<ReqT, RespT, SecT>>(url_str, type);
42 }
43 
44 template <typename ReqT, typename RespT, SecurityType SecT>
46  const std::string& url_str, InitType type) {
47  return std::make_shared<Server<ReqT, RespT, SecT>>(url_str, type);
48 }
49 
50 template <typename ReqT, typename RespT, SecurityType SecT>
51 template <typename ConfT, typename>
52 inline Server<ReqT, RespT, SecT>::Server(const ConfT& conf, InitType type) {
53  static_assert(ConfT::get_allow_impl_type() & kImplType, "Conf does not support server mode.");
54 
55  if VUNLIKELY (!conf.parse(kImplType) || !conf.is_valid()) {
56  VLOG_F(conf, " server configuration is invalid or could not be parsed.");
57  return;
58  }
59 
60  this->impl_ = conf.create_server();
61 
62  if VUNLIKELY (!this->impl_) {
63  VLOG_F(conf, " server implementation not available for this transport.");
64  return;
65  }
66 
67  this->impl_->transport_type = conf.get_transport_type();
68  this->impl_->ser_type = Serializer::get_serialized_type<kReqType, ReqT>();
69 
70  if constexpr (kHasResp) {
71  const auto resp_ser_type = Serializer::get_serialized_type<kRespType, RespT>();
72 
73  if (!this->impl_->ser_type.empty() || !resp_ser_type.empty()) {
74  this->impl_->ser_type += "|" + resp_ser_type;
75  }
76  }
77 
78  {
79  constexpr auto kReqSchemaType = Serializer::get_schema_type<kReqType, ReqT>();
80  constexpr auto kRespSchemaType = Serializer::get_schema_type<kRespType, RespT>();
81 
82  if constexpr (kHasResp && kReqSchemaType != kRespSchemaType) {
83  this->impl_->schema_type = SchemaType::kUnknown;
84  } else {
85  this->impl_->schema_type = kReqSchemaType;
86  }
87  }
88 
89  this->impl_->is_cdr_type = Serializer::is_cdr_type<ReqT>();
90  this->impl_->is_resp_type = kHasResp;
91  if constexpr (kHasResp) {
92  this->impl_->is_resp_cdr_type = Serializer::is_cdr_type<RespT>();
93  }
94 
95  if constexpr (std::is_same_v<ConfT, Url>) {
96  this->impl_->url = conf.get_str();
97  }
98 
99  if constexpr (SecT == SecurityType::kWithSecurity) {
100  this->impl_->is_security_type = true;
101  }
102 
103  if VLIKELY (type == InitType::kWithInit) {
104  this->init(); // NOLINT(clang-analyzer-optin.cplusplus.VirtualCall)
105  }
106 }
107 
108 template <typename ReqT, typename RespT, SecurityType SecT>
109 inline Server<ReqT, RespT, SecT>::Server(const std::string& url_str, InitType type)
110  : Server<ReqT, RespT, SecT>(Url(url_str), type) {}
111 
112 template <typename ReqT, typename RespT, SecurityType SecT>
114  static_assert(!kHasResp, "Reply not supported; use listen(ReqRespCallback&&) instead.");
115 
116  this->impl_->is_sync_type = true;
117 
118  return listen_bytes([this, callback = std::move(callback)](uint64_t, const Bytes& req_data, Bytes*) {
119 #ifndef VLINK_DISABLE_PROFILER
120  CpuProfilerGuard profiler_guard(this->impl_->profiler.get());
121 #endif
122 
123  if constexpr (std::is_same_v<ReqT, Bytes>) {
124  (void)this;
125 
126  callback(req_data);
127  } else {
128  auto req = this->template get_default_value<ReqT>();
129 
130  if VUNLIKELY (!Serializer::deserialize<kReqType>(req_data, req, this->impl_->transport_type)) {
131  VLOG_T("Server deserialize failed, url: ", this->impl_->url, ".");
132  return;
133  }
134 
135  callback(req);
136  }
137  });
138 }
139 
140 template <typename ReqT, typename RespT, SecurityType SecT>
142  static_assert(kHasResp, "Must have reply.");
143 
144  this->impl_->is_sync_type = true;
145 
146  return listen_bytes([this, callback = std::move(callback)](uint64_t req_id, const Bytes& req_data, Bytes* resp_data) {
147 #ifndef VLINK_DISABLE_PROFILER
148  CpuProfilerGuard profiler_guard(this->impl_->profiler.get());
149 #endif
150 
151  if VUNLIKELY (!resp_data) {
152  VLOG_E("Server resp_data pointer is null.");
153  return;
154  }
155 
156  if constexpr (std::is_same_v<ReqT, Bytes> && std::is_same_v<RespT, Bytes>) {
157  (void)this;
158 
159  callback(req_data, *resp_data);
160 
161  reply_bytes<true>(req_id, *resp_data, true, resp_data);
162  } else {
163  auto req = this->template get_default_value<ReqT>();
164  auto resp = this->template get_default_value<RespT>();
165 
166  if constexpr (std::is_same_v<ReqT, Bytes>) {
167  req.shallow_copy(req_data);
168  } else if VUNLIKELY (!Serializer::deserialize<kReqType>(req_data, req, this->impl_->transport_type)) {
169  VLOG_T("Server deserialize failed, url: ", this->impl_->url, ".");
170  return;
171  }
172 
173  callback(req, resp);
174  const bool use_loan = SecT != SecurityType::kWithSecurity && this->is_support_loan_;
175 
176  if constexpr (std::is_same_v<RespT, Bytes>) {
177  if (resp.is_owner() || resp.is_loaned()) {
178  *resp_data = std::move(resp);
179  } else {
180  *resp_data = resp;
181  }
182  } else if VUNLIKELY (!Serializer::serialize_to_transport<kRespType>(
183  resp, *resp_data, this->impl_->transport_type, use_loan,
184  [this](size_t size) { return this->impl_->loan(size); })) {
185  VLOG_T("Server serialize failed, url: ", this->impl_->url, ".");
186 
187  if constexpr (SecT != SecurityType::kWithSecurity) {
188  if (this->is_support_loan_) {
189  this->impl_->return_loan(*resp_data);
190  }
191  }
192 
193  return;
194  }
195 
196  reply_bytes<true>(req_id, *resp_data, true, resp_data);
197  }
198  });
199 }
200 
201 template <typename ReqT, typename RespT, SecurityType SecT>
203  static_assert(kHasResp, "Must have reply.");
204 
205  this->impl_->is_sync_type = false;
206 
207  return listen_bytes([this, callback = std::move(callback)](uint64_t req_id, const Bytes& req_data, Bytes*) {
208 #ifndef VLINK_DISABLE_PROFILER
209  CpuProfilerGuard profiler_guard(this->impl_->profiler.get());
210 #endif
211 
212  if constexpr (std::is_same_v<ReqT, Bytes>) {
213  (void)this;
214 
215  callback(req_id, req_data);
216  } else {
217  auto req = this->template get_default_value<ReqT>();
218 
219  if VUNLIKELY (!Serializer::deserialize<kReqType>(req_data, req, this->impl_->transport_type)) {
220  VLOG_T("Server deserialize failed, url: ", this->impl_->url, ".");
221  return;
222  }
223 
224  callback(req_id, req);
225  }
226  });
227 }
228 
229 template <typename ReqT, typename RespT, SecurityType SecT>
230 inline bool Server<ReqT, RespT, SecT>::reply(uint64_t req_id, const RespT& resp) {
231  static_assert(kHasResp, "Reply requires a response type.");
232 
233  if VUNLIKELY (!this->impl_->is_listened) {
234  VLOG_F("Server::reply() requires listen() to be called first.");
235  return false;
236  }
237 
238  if VUNLIKELY (this->impl_->is_sync_type) {
239  VLOG_F("Server::reply() is not available in synchronous listen mode.");
240  return false;
241  }
242 
243  if constexpr (std::is_same_v<RespT, Bytes>) {
244  return reply_bytes<false>(req_id, resp, false);
245  } else {
246  Bytes resp_data;
247  const bool use_loan = SecT != SecurityType::kWithSecurity && this->is_support_loan_;
248 
249  if VUNLIKELY (!Serializer::serialize_to_transport<kRespType>(
250  resp, resp_data, this->impl_->transport_type, use_loan,
251  [this](size_t size) { return this->impl_->loan(size); })) {
252  VLOG_T("Server serialize failed, url: ", this->impl_->url, ".");
253 
254  if constexpr (SecT != SecurityType::kWithSecurity) {
255  if (this->is_support_loan_) {
256  this->impl_->return_loan(resp_data);
257  }
258  }
259 
260  return false;
261  }
262 
263  bool ret = reply_bytes<false>(req_id, resp_data, false);
264 
265  return ret;
266  }
267 }
268 
269 template <typename ReqT, typename RespT, SecurityType SecT>
270 inline bool Server<ReqT, RespT, SecT>::has_clients() const {
271  return this->impl_->has_clients();
272 }
273 
274 template <typename ReqT, typename RespT, SecurityType SecT>
275 inline bool Server<ReqT, RespT, SecT>::listen_bytes(NodeImpl::ReqRespCallback&& callback) {
276  if VUNLIKELY (!this->has_inited_.load(std::memory_order_acquire)) {
277  VLOG_F("Server::listen_bytes() called before init().");
278  return false;
279  }
280 
281  if VUNLIKELY (this->impl_->is_listened) {
282  VLOG_F("Server has already been listened, url: ", this->impl_->url, ".");
283  return false;
284  }
285 
286  bool ret = this->impl_->listen(
287  [this, callback = std::move(callback)](uint64_t req_id, const Bytes& req_data, Bytes* resp_data) {
288  if constexpr (SecT == SecurityType::kWithSecurity) {
289  Bytes sec_req_data;
290 
291  if VUNLIKELY (!this->impl_->security || !this->impl_->security->decrypt(req_data, sec_req_data)) {
292  VLOG_T("Server decrypt failed, url: ", this->impl_->url, ".");
293  return;
294  }
295 
296  this->invoke_callback(callback, req_id, sec_req_data, resp_data);
297  } else {
298  this->impl_->try_record(ActionType::kServerRequest, req_data);
299 
300  this->invoke_callback(callback, req_id, req_data, resp_data);
301  }
302  });
303 
304  this->impl_->is_listened = ret;
305 
306  return ret;
307 }
308 
309 template <typename ReqT, typename RespT, SecurityType SecT>
310 template <bool HasPtrT>
311 inline bool Server<ReqT, RespT, SecT>::reply_bytes(uint64_t req_id, const Bytes& resp_data, bool is_sync,
312  [[maybe_unused]] Bytes* resp_data_ptr) {
313  if VUNLIKELY (!this->has_inited_.load(std::memory_order_acquire)) {
314  VLOG_F("Server::reply_bytes() called before init().");
315  }
316 
317  if constexpr (SecT == SecurityType::kWithSecurity) {
318  Bytes sec_resp_data;
319 
320  if VUNLIKELY (!this->impl_->security || !this->impl_->security->encrypt(resp_data, sec_resp_data)) {
321  if constexpr (HasPtrT) {
322  resp_data_ptr->clear();
323  }
324 
325  VLOG_T("Server encrypt failed, url: ", this->impl_->url, ".");
326  return false;
327  }
328 
329  if constexpr (HasPtrT) {
330  *resp_data_ptr = std::move(sec_resp_data);
331  return this->impl_->reply(req_id, *resp_data_ptr, is_sync);
332  }
333 
334  return this->impl_->reply(req_id, sec_resp_data, is_sync);
335  } else {
336  if constexpr (HasPtrT) {
337  *resp_data_ptr = resp_data;
338  }
339 
340  this->impl_->try_record(ActionType::kServerResponse, resp_data);
341 
342  return this->impl_->reply(req_id, resp_data, is_sync);
343  }
344 }
345 
346 template <typename ReqT, typename RespT>
347 template <typename SecurityConfigT>
349  const std::string& url_str, SecurityConfigT&& sec_cfg, InitType type) {
350  static_assert(std::is_same_v<std::decay_t<SecurityConfigT>, Security::Config>,
351  "SecurityConfigT must be Security::Config.");
352 
353  return std::make_unique<SecurityServer<ReqT, RespT>>(url_str, std::forward<SecurityConfigT>(sec_cfg), type);
354 }
355 
356 template <typename ReqT, typename RespT>
357 template <typename SecurityConfigT>
359  const std::string& url_str, SecurityConfigT&& sec_cfg, InitType type) {
360  static_assert(std::is_same_v<std::decay_t<SecurityConfigT>, Security::Config>,
361  "SecurityConfigT must be Security::Config.");
362 
363  return std::make_shared<SecurityServer<ReqT, RespT>>(url_str, std::forward<SecurityConfigT>(sec_cfg), type);
364 }
365 
366 template <typename ReqT, typename RespT>
367 template <typename ConfT, typename SecurityConfigT, typename>
368 inline SecurityServer<ReqT, RespT>::SecurityServer(const ConfT& conf, SecurityConfigT&& sec_cfg, InitType type)
369  : Server<ReqT, RespT, SecurityType::kWithSecurity>(conf, InitType::kWithoutInit) {
370  static_assert(std::is_same_v<std::decay_t<SecurityConfigT>, Security::Config>,
371  "SecurityConfigT must be Security::Config.");
372 
373  this->enable_security(std::forward<SecurityConfigT>(sec_cfg));
374 
375  if VLIKELY (type == InitType::kWithInit) {
376  this->init(); // NOLINT(clang-analyzer-optin.cplusplus.VirtualCall)
377  }
378 }
379 
380 template <typename ReqT, typename RespT>
381 template <typename SecurityConfigT>
382 inline SecurityServer<ReqT, RespT>::SecurityServer(const std::string& url_str, SecurityConfigT&& sec_cfg, InitType type)
383  : Server<ReqT, RespT, SecurityType::kWithSecurity>(url_str, InitType::kWithoutInit) {
384  static_assert(std::is_same_v<std::decay_t<SecurityConfigT>, Security::Config>,
385  "SecurityConfigT must be Security::Config.");
386 
387  this->enable_security(std::forward<SecurityConfigT>(sec_cfg));
388 
389  if VLIKELY (type == InitType::kWithInit) {
390  this->init(); // NOLINT(clang-analyzer-optin.cplusplus.VirtualCall)
391  }
392 }
393 
394 } // namespace vlink
#define VLOG_E(...)
Definition: logger.h:904
#define VLOG_F(...)
Definition: logger.h:906
#define VLOG_T(...)
Definition: logger.h:896
#define VUNLIKELY(...)
Short alias for VLINK_UNLIKELY.
Definition: macros.h:292
#define VLIKELY(...)
Short alias for VLINK_LIKELY.
Definition: macros.h:284