TEC
A lightweight C++ library enabling safe, efficient execution in multithreaded and concurrent systems.
Loading...
Searching...
No Matches
tec_grpc_client.hpp
Go to the documentation of this file.
1// Time-stamp: <Last changed 2026-02-20 16:19:01 by magnolia>
2/*----------------------------------------------------------------------
3------------------------------------------------------------------------
4Copyright (c) 2020-2026 The Emacs Cat (https://github.com/olddeuteronomy/tec).
5
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12 Unless required by applicable law or agreed to in writing, software
13 distributed under the License is distributed on an "AS IS" BASIS,
14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 See the License for the specific language governing permissions and
16 limitations under the License.
17------------------------------------------------------------------------
18----------------------------------------------------------------------*/
31#pragma once
32
33#include "tec/tec_def.hpp" // IWYU pragma: keep
34#include "tec/tec_status.hpp"
35#include "tec/tec_trace.hpp"
36#include "tec/tec_utils.hpp"
37#include "tec/tec_actor.hpp"
38#include "tec/grpc/tec_grpc.hpp" // IWYU pragma: keep
39
40
41namespace tec {
42
43/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
44*
45* gRPC Client traits
46*
47*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
48
64template <
65 typename TService,
66 typename TGrpcChannel,
67 typename TGrpcClientCredentials,
68 typename TGrpcChannelArguments,
69 typename TGrpcCompressionAlgorithm
70 >
72 typedef TService Service;
73 typedef TGrpcChannel Channel;
74 typedef TGrpcClientCredentials Credentials;
75 typedef TGrpcChannelArguments Arguments;
76 typedef TGrpcCompressionAlgorithm CompressionAlgorithm;
77};
78
79/*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
80*
81* gRPC client
82*
83*~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~*/
84
99template <typename TParams, typename Traits>
100class GrpcClient : public Actor {
101public:
102 typedef Traits traits;
103 typedef TParams Params;
104 typedef typename traits::Service Service;
105 typedef typename traits::Channel Channel;
106 typedef typename traits::Credentials Credentials;
107 typedef typename traits::Arguments Arguments;
108 typedef typename traits::CompressionAlgorithm CompressionAlgorithm;
109
119 std::shared_ptr<Channel> (*fptr)(const std::string&,
120 const std::shared_ptr<Credentials>&,
121 const Arguments&);
122 };
123
124protected:
125 // ── Configuration & state ───────────────────────────────────────────────
126
129
131 std::shared_ptr<Credentials> credentials_;
132
134 std::unique_ptr<typename Service::Stub> stub_;
135
138
140 std::shared_ptr<Channel> channel_;
141
144
145protected:
156 virtual void set_channel_arguments() {
157 TEC_ENTER("GrpcClient::set_channel_arguments");
158
159 // Maximum message size, see tec::kGrpcMaxMessageSize
160 if (params_.max_message_size > 0) {
161 // Convert MB → bytes
162 const int max_size = params_.max_message_size * 1024 * 1024;
163 arguments_.SetMaxSendMessageSize(max_size);
164 arguments_.SetMaxReceiveMessageSize(max_size);
165 }
166 TEC_TRACE("MaxMessageSize is set to {} Mb.", params_.max_message_size);
167
168 // Compression algorithm
169 // GRPC_COMPRESS_NONE = 0, GRPC_COMPRESS_DEFLATE, GRPC_COMPRESS_GZIP, ...
170 if (params_.compression_algorithm > 0) {
171 arguments_.SetCompressionAlgorithm(static_cast<CompressionAlgorithm>(params_.compression_algorithm));
172 }
173 TEC_TRACE("CompressionAlgorithm is set to {}.", params_.compression_algorithm);
174 }
175
176public:
184 GrpcClient(const Params& params,
185 const ChannelBuilder& channel_builder,
186 const std::shared_ptr<Credentials>& credentials)
187 : Actor()
188 , params_{params}
189 , channel_builder_{channel_builder}
190 , credentials_{credentials}
191 {
192 static_assert(
193 std::is_base_of<GrpcClientParams, Params>::value,
194 "Must be derived from tec::GrpcClientParams class");
195 }
196
198 virtual ~GrpcClient() = default;
199
211 void start(Signal* sig_started, Status* status) override {
212 TEC_ENTER("GrpcClient::start");
213 Signal::OnExit on_exit(sig_started);
214
215 // Prepare channel creation arguments
217
218 // Create channel (may return "lame" channel on error)
220 TEC_TRACE("Connecting to {} ...", params_.addr_uri);
221
222 // Wait for connection with timeout
223 auto deadline = std::chrono::system_clock::now() + params_.connect_timeout;
224 if (!channel_->WaitForConnected(deadline)) {
225 std::string msg{format(
226 "It took too long (> {} ms) to reach out the server on \"{}\"",
227 MilliSec{params_.connect_timeout}.count(), params_.addr_uri)};
228 TEC_TRACE("!!! Error: {}.", msg);
229 *status = {msg, Error::Kind::NetErr};
230 return;
231 }
232
233 // Create service stub
234 stub_ = Service::NewStub(channel_);
235 TEC_TRACE("connected to {} OK.", params_.addr_uri);
236 }
237
246 void shutdown(Signal* sig_stopped) override {
247 TEC_ENTER("GrpcClient::shutdown");
248 Signal::OnExit on_exit{sig_stopped};
249 TEC_TRACE("closed OK.");
250 }
251
263 virtual Status process_request(Request request, Reply reply) override {
264 // Must be implemented in derived class.
266 }
267}; // class GrpcClient
268
269} // ::tec
Abstract base class defining the actor lifecycle and request handling interface.
Definition tec_actor.hpp:63
Base class for actor-style asynchronous gRPC clients.
Definition tec_grpc_client.hpp:100
traits::Credentials Credentials
credentials type
Definition tec_grpc_client.hpp:106
void shutdown(Signal *sig_stopped) override
Graceful shutdown hook.
Definition tec_grpc_client.hpp:246
virtual Status process_request(Request request, Reply reply) override
Processes a single request → reply pair.
Definition tec_grpc_client.hpp:263
std::shared_ptr< Credentials > credentials_
Credentials object used to create secure/insecure channels.
Definition tec_grpc_client.hpp:131
traits::Service Service
gRPC service stub type
Definition tec_grpc_client.hpp:104
TParams Params
Configuration parameters type.
Definition tec_grpc_client.hpp:103
ChannelBuilder channel_builder_
Channel creation functor (injected at construction)
Definition tec_grpc_client.hpp:137
GrpcClient(const Params &params, const ChannelBuilder &channel_builder, const std::shared_ptr< Credentials > &credentials)
Constructs a GrpcClient instance.
Definition tec_grpc_client.hpp:184
Arguments arguments_
Channel creation arguments (message size limits, compression, keepalive, etc.)
Definition tec_grpc_client.hpp:143
virtual ~GrpcClient()=default
Virtual destructor (defaulted)
traits::Channel Channel
gRPC channel type
Definition tec_grpc_client.hpp:105
std::unique_ptr< typename Service::Stub > stub_
Owned stub instance — created after successful channel connection.
Definition tec_grpc_client.hpp:134
void start(Signal *sig_started, Status *status) override
Establishes connection to the gRPC server.
Definition tec_grpc_client.hpp:211
traits::CompressionAlgorithm CompressionAlgorithm
compression enum type
Definition tec_grpc_client.hpp:108
traits::Arguments Arguments
channel arguments type
Definition tec_grpc_client.hpp:107
std::shared_ptr< Channel > channel_
Shared pointer to the active gRPC channel.
Definition tec_grpc_client.hpp:140
Params params_
Runtime configuration parameters (address, timeouts, message size, compression, etc....
Definition tec_grpc_client.hpp:128
Traits traits
Traits providing all gRPC-related type aliases.
Definition tec_grpc_client.hpp:102
virtual void set_channel_arguments()
Configures channel arguments before channel creation.
Definition tec_grpc_client.hpp:156
A thread-safe signal mechanism for inter-thread synchronization.
Definition tec_signal.hpp:44
#define TEC_ENTER(name)
Logs an entry message for a named context (e.g., function).
Definition tec_trace.hpp:211
#define TEC_TRACE(...)
Logs a formatted trace message.
Definition tec_trace.hpp:222
@ NetErr
Network-related error.
@ NotImplemented
Not implemented.
Holder for a function pointer that creates a gRPC channel.
Definition tec_grpc_client.hpp:117
std::shared_ptr< Channel >(* fptr)(const std::string &, const std::shared_ptr< Credentials > &, const Arguments &)
Function pointer matching signature of grpc::CreateChannel / CreateCustomChannel / etc.
Definition tec_grpc_client.hpp:119
Helper struct to signal termination on exit.
Definition tec_signal.hpp:110
Type traits / type aliases collection for configuring a gRPC client.
Definition tec_grpc_client.hpp:71
TGrpcCompressionAlgorithm CompressionAlgorithm
supported compression algorithms enum
Definition tec_grpc_client.hpp:76
TService Service
gRPC service stub type
Definition tec_grpc_client.hpp:72
TGrpcChannel Channel
gRPC channel type
Definition tec_grpc_client.hpp:73
TGrpcChannelArguments Arguments
channel creation arguments
Definition tec_grpc_client.hpp:75
TGrpcClientCredentials Credentials
credentials factory type
Definition tec_grpc_client.hpp:74
Core interface for TEC actors with lifecycle management and request processing.
Common definitions and utilities for the tec namespace.
Generic gRPC parameters.
std::any Reply
Type alias for a reply object that can hold any object.
Definition tec_message.hpp:55
std::any Request
Type alias for a request object that can hold any object.
Definition tec_message.hpp:49
std::string format(const T &arg)
Formats a single argument into a string.
Definition tec_print.hpp:171
Defines error handling types and utilities for the tec namespace.
Provides a thread-safe tracing utility for debugging in the tec namespace.
Provides time-related utilities and system information functions for the tec namespace.
std::chrono::milliseconds MilliSec
Type alias for milliseconds duration.
Definition tec_utils.hpp:62