30 #include "../base/cpu_profiler_guard.h"
31 #include "../base/logger.h"
32 #include "../base/memory_resource.h"
33 #include "../client.h"
34 #include "../impl/url.h"
35 #include "../serializer.h"
36 #include "../zerocopy/audio_frame.h"
37 #include "../zerocopy/camera_frame.h"
38 #include "../zerocopy/object_array.h"
39 #include "../zerocopy/occupancy_grid.h"
40 #include "../zerocopy/point_cloud.h"
41 #include "../zerocopy/proxy_data.h"
42 #include "../zerocopy/raw_data.h"
43 #include "../zerocopy/tensor.h"
47 template <
typename ReqT,
typename RespT, SecurityType SecT>
49 const std::string& url_str,
InitType type) {
50 return std::make_unique<Client<ReqT, RespT, SecT>>(url_str, type);
53 template <
typename ReqT,
typename RespT, SecurityType SecT>
55 const std::string& url_str,
InitType type) {
56 return std::make_shared<Client<ReqT, RespT, SecT>>(url_str, type);
59 template <
typename ReqT,
typename RespT, SecurityType SecT>
60 template <
typename ConfT,
typename>
62 static_assert(ConfT::get_allow_impl_type() & kImplType,
"Conf does not support client mode.");
64 if VUNLIKELY (!conf.parse(kImplType) || !conf.is_valid()) {
65 VLOG_F(conf,
" client configuration is invalid or could not be parsed.");
69 this->impl_ = conf.create_client();
72 VLOG_F(conf,
" client implementation not available for this transport.");
76 this->impl_->transport_type = conf.get_transport_type();
77 this->impl_->ser_type = Serializer::get_serialized_type<kReqType, ReqT>();
79 if constexpr (kHasResp) {
80 const auto resp_ser_type = Serializer::get_serialized_type<kRespType, RespT>();
82 if (!this->impl_->ser_type.empty() || !resp_ser_type.empty()) {
83 this->impl_->ser_type +=
"|" + resp_ser_type;
88 constexpr
auto kReqSchemaType = Serializer::get_schema_type<kReqType, ReqT>();
89 constexpr
auto kRespSchemaType = Serializer::get_schema_type<kRespType, RespT>();
91 if constexpr (kHasResp && kReqSchemaType != kRespSchemaType) {
94 this->impl_->schema_type = kReqSchemaType;
98 this->impl_->is_cdr_type = Serializer::is_cdr_type<ReqT>();
99 this->impl_->is_resp_type = kHasResp;
101 if constexpr (kHasResp) {
102 this->impl_->is_resp_cdr_type = Serializer::is_cdr_type<RespT>();
105 if constexpr (std::is_same_v<ConfT, Url>) {
106 this->impl_->url = conf.get_str();
110 this->impl_->is_security_type =
true;
118 template <
typename ReqT,
typename RespT, SecurityType SecT>
120 :
Client<ReqT, RespT, SecT>(
Url(url_str), type) {}
122 template <
typename ReqT,
typename RespT, SecurityType SecT>
125 std::lock_guard lock(future_mtx_);
133 template <
typename ReqT,
typename RespT, SecurityType SecT>
135 this->impl_->detect_connected(std::move(callback));
138 template <
typename ReqT,
typename RespT, SecurityType SecT>
141 VLOG_W(
"Client: Timeout value is 0, using infinite wait instead.");
145 return this->impl_->wait_for_connected(timeout);
148 template <
typename ReqT,
typename RespT, SecurityType SecT>
150 return this->impl_->is_connected();
153 template <
typename ReqT,
typename RespT, SecurityType SecT>
156 VLOG_W(
"Client: Timeout value is 0, using infinite wait instead.");
160 #ifndef VLINK_DISABLE_PROFILER
164 static_assert(kHasResp,
"Invoke requires a response type.");
168 if constexpr (std::is_same_v<ReqT, Bytes> && std::is_same_v<RespT, Bytes>) {
169 bool received =
false;
172 [&resp, &received](
const Bytes& resp_data) {
177 ret = ret && received;
182 if constexpr (std::is_same_v<ReqT, Bytes>) {
185 }
else if VUNLIKELY (!Serializer::serialize_to_transport<kReqType>(
186 req, req_data, this->impl_->transport_type, use_loan,
187 [
this](
size_t size) { return this->impl_->loan(size); })) {
188 VLOG_T(
"Client serialize failed, url: ", this->impl_->url,
".");
191 if (this->is_support_loan_) {
192 this->impl_->return_loan(req_data);
199 bool deserialize_success =
false;
203 [
this, &resp, &deserialize_success](
const Bytes& resp_data) {
204 if VLIKELY (deserialize_response(resp_data, resp)) {
205 deserialize_success =
true;
207 VLOG_T(
"Client deserialize failed, url: ", this->impl_->url,
".");
212 ret = ret && deserialize_success;
218 template <
typename ReqT,
typename RespT, SecurityType SecT>
221 VLOG_W(
"Client: Timeout value is 0, using infinite wait instead.");
225 #ifndef VLINK_DISABLE_PROFILER
229 auto resp = this->
template get_default_value<RespT>();
231 if VLIKELY (invoke(req, resp, timeout)) {
232 return std::make_optional<RespT>(std::move(resp));
238 template <
typename ReqT,
typename RespT, SecurityType SecT>
240 #ifndef VLINK_DISABLE_PROFILER
244 static_assert(kHasResp,
"Invoke requires a response type.");
248 if constexpr (std::is_same_v<ReqT, Bytes> && std::is_same_v<RespT, Bytes>) {
249 ret = call_bytes(req, [callback = std::move(callback)](
const Bytes& resp_data) { callback(resp_data); });
254 if constexpr (std::is_same_v<ReqT, Bytes>) {
256 req.is_loaned() ?
Bytes::loan_internal(req.data(), req.size()) : Bytes::shallow_copy(req.data(), req.size());
257 }
else if VUNLIKELY (!Serializer::serialize_to_transport<kReqType>(
258 req, req_data, this->impl_->transport_type, use_loan,
259 [
this](
size_t size) { return this->impl_->loan(size); })) {
260 VLOG_T(
"Client serialize failed, url: ", this->impl_->url,
".");
263 if (this->is_support_loan_) {
264 this->impl_->return_loan(req_data);
271 ret = call_bytes(req_data, [
this, callback = std::move(callback)](
const Bytes& resp_data) {
273 auto resp = this->
template get_default_value<RespT>();
275 if VUNLIKELY (!Serializer::deserialize<kRespType>(resp_data, resp, this->impl_->transport_type)) {
276 VLOG_T(
"Client deserialize failed, url: ", this->impl_->url,
".");
287 template <
typename ReqT,
typename RespT, SecurityType SecT>
289 #ifndef VLINK_DISABLE_PROFILER
293 static_assert(kHasResp,
"async_invoke requires a response type.");
295 auto pro = MemoryResource::make_shared<std::promise<RespT>>();
296 auto future = pro->get_future();
299 int64_t target_seq = 0;
302 std::lock_guard lock(future_mtx_);
303 target_seq = future_seq_++;
304 future_map_.emplace(target_seq, pro);
307 auto cleanup_on_error = [
this, target_seq, pro](
const std::string& error_str) {
308 std::lock_guard lock(future_mtx_);
309 future_map_.erase(target_seq);
313 }
catch (std::exception&) {
314 pro->set_exception(std::current_exception());
318 if constexpr (std::is_same_v<ReqT, Bytes> && std::is_same_v<RespT, Bytes>) {
319 ret = call_bytes(req, [
this, target_seq](
const Bytes& resp_data) {
320 std::lock_guard lock(future_mtx_);
321 auto it = future_map_.find(target_seq);
323 if VLIKELY (it != future_map_.end()) {
324 it->second->set_value(resp_data);
325 future_map_.erase(it);
332 if constexpr (std::is_same_v<ReqT, Bytes>) {
334 req.is_loaned() ?
Bytes::loan_internal(req.data(), req.size()) : Bytes::shallow_copy(req.data(), req.size());
335 }
else if VUNLIKELY (!Serializer::serialize_to_transport<kReqType>(
336 req, req_data, this->impl_->transport_type, use_loan,
337 [
this](
size_t size) { return this->impl_->loan(size); })) {
338 VLOG_T(
"Client serialize failed, url: ", this->impl_->url,
".");
341 if (this->is_support_loan_) {
342 this->impl_->return_loan(req_data);
346 cleanup_on_error(
"Client async_invoke error (Failed to serialize req)");
350 ret = call_bytes(req_data, [
this, target_seq](
const Bytes& resp_data) {
351 bool convert_success =
false;
353 auto resp = this->
template get_default_value<RespT>();
355 if VLIKELY (deserialize_response(resp_data, resp)) {
356 convert_success =
true;
358 VLOG_T(
"Client deserialize failed, url: ", this->impl_->url,
".");
361 std::lock_guard lock(future_mtx_);
363 auto it = future_map_.find(target_seq);
365 if VLIKELY (it != future_map_.end()) {
367 it->second->set_value(std::move(resp));
370 throw Exception::RuntimeError(
"Client async_invoke error (Failed to deserialize resp)");
371 }
catch (std::exception&) {
372 it->second->set_exception(std::current_exception());
376 future_map_.erase(it);
382 cleanup_on_error(
"Client async_invoke error (Failed to call)");
388 template <
typename ReqT,
typename RespT, SecurityType SecT>
390 #ifndef VLINK_DISABLE_PROFILER
394 static_assert(!kHasResp,
"Send not supported; use invoke() for request-response.");
398 if constexpr (std::is_same_v<ReqT, Bytes>) {
399 ret = call_bytes(req);
404 if VUNLIKELY (!Serializer::serialize_to_transport<kReqType>(
405 req, req_data, this->impl_->transport_type, use_loan,
406 [
this](
size_t size) { return this->impl_->loan(size); })) {
407 VLOG_T(
"Client serialize failed, url: ", this->impl_->url,
".");
410 if (this->is_support_loan_) {
411 this->impl_->return_loan(req_data);
418 ret = call_bytes(req_data);
424 template <
typename ReqT,
typename RespT, SecurityType SecT>
428 if constexpr (std::is_same_v<RealType, zerocopy::RawData> || std::is_same_v<RealType, zerocopy::CameraFrame> ||
429 std::is_same_v<RealType, zerocopy::AudioFrame> || std::is_same_v<RealType, zerocopy::PointCloud> ||
430 std::is_same_v<RealType, zerocopy::Tensor> || std::is_same_v<RealType, zerocopy::OccupancyGrid> ||
431 std::is_same_v<RealType, zerocopy::ObjectArray> || std::is_same_v<RealType, zerocopy::ProxyData>) {
440 if VUNLIKELY (!Serializer::deserialize<kRespType>(data, decoded, this->impl_->transport_type)) {
446 if (decoded.is_owner()) {
447 output = std::move(decoded);
451 return output.deep_copy(decoded);
453 return Serializer::deserialize<kRespType>(data, response, this->impl_->transport_type);
457 template <
typename ReqT,
typename RespT, SecurityType SecT>
458 inline bool Client<ReqT, RespT, SecT>::call_bytes(
const Bytes& req_data,
NodeImpl::MsgCallback&& callback,
459 std::chrono::milliseconds timeout) {
463 if VUNLIKELY (!this->impl_->security || !this->impl_->security->encrypt(req_data, req_sec_data)) {
464 VLOG_T(
"Client encrypt failed, url: ", this->impl_->url,
".");
469 return this->impl_->call(req_sec_data,
nullptr, timeout);
472 return this->impl_->call(
474 [
this, callback = std::move(callback)](
const Bytes& resp_data) {
477 if VUNLIKELY (!this->impl_->security || !this->impl_->security->decrypt(resp_data, resp_sec_data)) {
478 VLOG_T(
"Client decrypt failed, url: ", this->impl_->url,
".");
482 this->invoke_callback(callback, resp_sec_data);
489 return this->impl_->call(req_data,
nullptr, timeout);
492 return this->impl_->call(
494 [
this, callback = std::move(callback)](
const Bytes& resp_data) {
497 this->invoke_callback(callback, resp_data);
503 template <
typename ReqT,
typename RespT>
504 template <
typename SecurityConfigT>
506 const std::string& url_str, SecurityConfigT&& sec_cfg,
InitType type) {
507 static_assert(std::is_same_v<std::decay_t<SecurityConfigT>,
Security::Config>,
508 "SecurityConfigT must be Security::Config.");
510 return std::make_unique<SecurityClient<ReqT, RespT>>(url_str, std::forward<SecurityConfigT>(sec_cfg), type);
513 template <
typename ReqT,
typename RespT>
514 template <
typename SecurityConfigT>
516 const std::string& url_str, SecurityConfigT&& sec_cfg,
InitType type) {
517 static_assert(std::is_same_v<std::decay_t<SecurityConfigT>,
Security::Config>,
518 "SecurityConfigT must be Security::Config.");
520 return std::make_shared<SecurityClient<ReqT, RespT>>(url_str, std::forward<SecurityConfigT>(sec_cfg), type);
523 template <
typename ReqT,
typename RespT>
524 template <
typename ConfT,
typename SecurityConfigT,
typename>
527 static_assert(std::is_same_v<std::decay_t<SecurityConfigT>,
Security::Config>,
528 "SecurityConfigT must be Security::Config.");
537 template <
typename ReqT,
typename RespT>
538 template <
typename SecurityConfigT>
541 static_assert(std::is_same_v<std::decay_t<SecurityConfigT>,
Security::Config>,
542 "SecurityConfigT must be Security::Config.");
Fixed-size 128-byte buffer holder with SBO, five ownership modes and integrated codecs.
Definition: bytes.h:120
bool is_loaned() const noexcept
Reports whether the buffer is an iceoryx loan that VLink must not free.
Definition: bytes.h:869
static Bytes shallow_copy(uint8_t *data, size_t size) noexcept
Wraps an external mutable buffer as a non-owning alias.
static Bytes loan_internal(uint8_t *data, size_t size) noexcept
Wraps an iceoryx-loaned mutable payload as a non-owning, non-aliasing carrier.
Type-safe RPC caller for the VLink method communication model.
Definition: client.h:132
void detect_connected(ConnectCallback &&callback)
Registers a callback invoked when the server-presence state changes.
Definition: client-inl.h:134
std::unique_ptr< Client< ReqT, RespT, SecT > > UniquePtr
Owning unique-pointer alias.
Definition: client.h:134
static SharedPtr create_shared(const std::string &url_str, InitType type=InitType::kWithInit)
Heap-allocates a Client and wraps it in a std::shared_ptr.
Definition: client-inl.h:54
bool wait_for_connected(std::chrono::milliseconds timeout=Timeout::kDefaultInterval)
Blocks until a server is discovered or timeout expires.
Definition: client-inl.h:139
Client(const ConfT &conf, InitType type=InitType::kWithInit)
Constructs a client from a typed transport configuration object.
Definition: client-inl.h:61
static UniquePtr create_unique(const std::string &url_str, InitType type=InitType::kWithInit)
Heap-allocates a Client and wraps it in a std::unique_ptr.
Definition: client-inl.h:48
bool invoke(const ReqT &req, RespT &resp, std::chrono::milliseconds timeout=Timeout::kDefaultInterval)
Synchronous request/response invocation with an output parameter.
Definition: client-inl.h:154
std::future< RespT > async_invoke(const ReqT &req)
Asynchronous future-based invocation.
Definition: client-inl.h:288
~Client() override
Destroys the client and tears down outstanding promises.
Definition: client-inl.h:123
std::shared_ptr< Client< ReqT, RespT, SecT > > SharedPtr
Owning shared-pointer alias.
Definition: client.h:135
bool is_connected() const
Non-blocking query of server presence.
Definition: client-inl.h:149
bool send(const ReqT &req)
Fire-and-forget request emission.
Definition: client-inl.h:389
Scope guard that opens and closes a CpuProfiler active interval.
Definition: cpu_profiler_guard.h:80
Generic runtime failure; thrown by the logger on kFatal messages.
Definition: exception.h:90
Copyable type-erased callable analogue of std::function with a tunable SBO and pool spill.
Definition: functional.h:132
Function< void(const Bytes &)> MsgCallback
Callback delivering a serialised payload to a subscriber or getter.
Definition: node_impl.h:200
bool enable_security(const Security::Config &cfg)
Installs a Security configuration before transport initialisation.
Definition: node-inl.h:331
virtual bool init()
Initialises the node and its transport back-end.
Definition: node-inl.h:40
std::unique_ptr< SecurityClient< ReqT, RespT > > UniquePtr
Owning unique-pointer alias.
Definition: client.h:329
static UniquePtr create_unique(const std::string &url_str, SecurityConfigT &&sec_cfg={}, InitType type=InitType::kWithInit)
Heap-allocates a SecurityClient and wraps it in a std::unique_ptr.
Definition: client-inl.h:505
std::shared_ptr< SecurityClient< ReqT, RespT > > SharedPtr
Owning shared-pointer alias.
Definition: client.h:330
static SharedPtr create_shared(const std::string &url_str, SecurityConfigT &&sec_cfg={}, InitType type=InitType::kWithInit)
Heap-allocates a SecurityClient and wraps it in a std::shared_ptr.
Definition: client-inl.h:515
SecurityClient(const ConfT &conf, SecurityConfigT &&sec_cfg={}, InitType type=InitType::kWithInit)
Constructs a SecurityClient from a typed configuration object.
Definition: client-inl.h:525
#define VLOG_F(...)
Definition: logger.h:906
#define VLOG_W(...)
Definition: logger.h:902
#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
constexpr auto & deref(const T &t) noexcept
Dereferences a value, unwrapping std::shared_ptr when present.
Definition: serializer-inl.h:838
InitType
Selects between immediate and deferred node initialisation.
Definition: types.h:150
@ kWithoutInit
Defer initialisation; call init() manually.
@ kWithInit
Initialise immediately in the constructor.
@ kUnknown
Decoding family unknown.
@ kClientResponse
RPC response observed by a Client node.
@ kClientRequest
RPC request emitted by a Client node.
SecurityType
Compile-time selector for the per-node message security variant.
Definition: types.h:168
@ kWithSecurity
Encrypted and authenticated transport.
Aggregate of every parameter accepted by the Security constructor.
Definition: security.h:164
static constexpr std::chrono::milliseconds kInfinite
Wait indefinitely (negative timeout).
Definition: types.h:256
Detects whether T is (or derives from) a std::shared_ptr specialisation.
Definition: traits.h:203
T Type
Resolved type after optional shared_ptr removal.
Definition: traits.h:220
Conf subclass that routes virtual calls to the transport selected by a URL string.
Definition: url.h:216