3 * Copyright 2015 gRPC authors.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
19 /// A ClientContext allows the person implementing a service client to:
21 /// - Add custom metadata key-value pairs that will propagated to the server
23 /// - Control call settings such as compression and authentication.
24 /// - Initial and trailing metadata coming from the server.
25 /// - Get performance metrics (ie, census).
27 /// Context settings are only relevant to the call they are invoked with, that
28 /// is to say, they aren't sticky. Some of these settings, such as the
29 /// compression options, can be made persistent at channel construction time
30 /// (see \a grpc::CreateCustomChannel).
32 /// \warning ClientContext instances should \em not be reused across rpcs.
34 #ifndef GRPCPP_IMPL_CODEGEN_CLIENT_CONTEXT_H
35 #define GRPCPP_IMPL_CODEGEN_CLIENT_CONTEXT_H
42 #include <grpc/impl/codegen/compression_types.h>
43 #include <grpc/impl/codegen/propagation_bits.h>
44 #include <grpcpp/impl/codegen/client_interceptor.h>
45 #include <grpcpp/impl/codegen/config.h>
46 #include <grpcpp/impl/codegen/core_codegen_interface.h>
47 #include <grpcpp/impl/codegen/create_auth_context.h>
48 #include <grpcpp/impl/codegen/metadata_map.h>
49 #include <grpcpp/impl/codegen/rpc_method.h>
50 #include <grpcpp/impl/codegen/security/auth_context.h>
51 #include <grpcpp/impl/codegen/slice.h>
52 #include <grpcpp/impl/codegen/status.h>
53 #include <grpcpp/impl/codegen/string_ref.h>
54 #include <grpcpp/impl/codegen/time.h>
56 struct census_context;
62 class ChannelInterface;
63 class CompletionQueue;
64 class CallCredentials;
69 class CallOpClientRecvStatus;
70 class CallOpRecvInitialMetadata;
71 template <class InputMessage, class OutputMessage>
72 class BlockingUnaryCallImpl;
73 template <class InputMessage, class OutputMessage>
74 class CallbackUnaryCallImpl;
75 template <class Request, class Response>
76 class ClientCallbackReaderWriterImpl;
77 template <class Response>
78 class ClientCallbackReaderImpl;
79 template <class Request>
80 class ClientCallbackWriterImpl;
81 } // namespace internal
87 template <class W, class R>
88 class ClientReaderWriter;
90 class ClientAsyncReader;
92 class ClientAsyncWriter;
93 template <class W, class R>
94 class ClientAsyncReaderWriter;
96 class ClientAsyncResponseReader;
99 /// Options for \a ClientContext::FromServerContext specifying which traits from
100 /// the \a ServerContext to propagate (copy) from it into a new \a
103 /// \see ClientContext::FromServerContext
104 class PropagationOptions {
106 PropagationOptions() : propagate_(GRPC_PROPAGATE_DEFAULTS) {}
108 PropagationOptions& enable_deadline_propagation() {
109 propagate_ |= GRPC_PROPAGATE_DEADLINE;
113 PropagationOptions& disable_deadline_propagation() {
114 propagate_ &= ~GRPC_PROPAGATE_DEADLINE;
118 PropagationOptions& enable_census_stats_propagation() {
119 propagate_ |= GRPC_PROPAGATE_CENSUS_STATS_CONTEXT;
123 PropagationOptions& disable_census_stats_propagation() {
124 propagate_ &= ~GRPC_PROPAGATE_CENSUS_STATS_CONTEXT;
128 PropagationOptions& enable_census_tracing_propagation() {
129 propagate_ |= GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT;
133 PropagationOptions& disable_census_tracing_propagation() {
134 propagate_ &= ~GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT;
138 PropagationOptions& enable_cancellation_propagation() {
139 propagate_ |= GRPC_PROPAGATE_CANCELLATION;
143 PropagationOptions& disable_cancellation_propagation() {
144 propagate_ &= ~GRPC_PROPAGATE_CANCELLATION;
148 uint32_t c_bitmask() const { return propagate_; }
155 class InteropClientContextInspector;
156 } // namespace testing
158 /// A ClientContext allows the person implementing a service client to:
160 /// - Add custom metadata key-value pairs that will propagated to the server
162 /// - Control call settings such as compression and authentication.
163 /// - Initial and trailing metadata coming from the server.
164 /// - Get performance metrics (ie, census).
166 /// Context settings are only relevant to the call they are invoked with, that
167 /// is to say, they aren't sticky. Some of these settings, such as the
168 /// compression options, can be made persistent at channel construction time
169 /// (see \a grpc::CreateCustomChannel).
171 /// \warning ClientContext instances should \em not be reused across rpcs.
172 /// \warning The ClientContext instance used for creating an rpc must remain
173 /// alive and valid for the lifetime of the rpc.
174 class ClientContext {
179 /// Create a new \a ClientContext as a child of an incoming server call,
180 /// according to \a options (\see PropagationOptions).
182 /// \param server_context The source server context to use as the basis for
183 /// constructing the client context.
184 /// \param options The options controlling what to copy from the \a
187 /// \return A newly constructed \a ClientContext instance based on \a
188 /// server_context, with traits propagated (copied) according to \a options.
189 static std::unique_ptr<ClientContext> FromServerContext(
190 const ServerContext& server_context,
191 PropagationOptions options = PropagationOptions());
193 /// Add the (\a meta_key, \a meta_value) pair to the metadata associated with
194 /// a client call. These are made available at the server side by the \a
195 /// grpc::ServerContext::client_metadata() method.
197 /// \warning This method should only be called before invoking the rpc.
199 /// \param meta_key The metadata key. If \a meta_value is binary data, it must
201 /// \param meta_value The metadata value. If its value is binary, the key name
202 /// must end in "-bin".
204 /// Metadata must conform to the following format:
205 /// Custom-Metadata -> Binary-Header / ASCII-Header
206 /// Binary-Header -> {Header-Name "-bin" } {binary value}
207 /// ASCII-Header -> Header-Name ASCII-Value
208 /// Header-Name -> 1*( %x30-39 / %x61-7A / "_" / "-" / ".") ; 0-9 a-z _ - .
209 /// ASCII-Value -> 1*( %x20-%x7E ) ; space and printable ASCII
210 void AddMetadata(const grpc::string& meta_key,
211 const grpc::string& meta_value);
213 /// Return a collection of initial metadata key-value pairs. Note that keys
214 /// may happen more than once (ie, a \a std::multimap is returned).
216 /// \warning This method should only be called after initial metadata has been
217 /// received. For streaming calls, see \a
218 /// ClientReaderInterface::WaitForInitialMetadata().
220 /// \return A multimap of initial metadata key-value pairs from the server.
221 const std::multimap<grpc::string_ref, grpc::string_ref>&
222 GetServerInitialMetadata() const {
223 GPR_CODEGEN_ASSERT(initial_metadata_received_);
224 return *recv_initial_metadata_.map();
227 /// Return a collection of trailing metadata key-value pairs. Note that keys
228 /// may happen more than once (ie, a \a std::multimap is returned).
230 /// \warning This method is only callable once the stream has finished.
232 /// \return A multimap of metadata trailing key-value pairs from the server.
233 const std::multimap<grpc::string_ref, grpc::string_ref>&
234 GetServerTrailingMetadata() const {
235 // TODO(yangg) check finished
236 return *trailing_metadata_.map();
239 /// Set the deadline for the client call.
241 /// \warning This method should only be called before invoking the rpc.
243 /// \param deadline the deadline for the client call. Units are determined by
244 /// the type used. The deadline is an absolute (not relative) time.
245 template <typename T>
246 void set_deadline(const T& deadline) {
247 TimePoint<T> deadline_tp(deadline);
248 deadline_ = deadline_tp.raw_time();
251 /// EXPERIMENTAL: Indicate that this request is idempotent.
252 /// By default, RPCs are assumed to <i>not</i> be idempotent.
254 /// If true, the gRPC library assumes that it's safe to initiate
255 /// this RPC multiple times.
256 void set_idempotent(bool idempotent) { idempotent_ = idempotent; }
258 /// EXPERIMENTAL: Set this request to be cacheable.
259 /// If set, grpc is free to use the HTTP GET verb for sending the request,
260 /// with the possibility of receiving a cached response.
261 void set_cacheable(bool cacheable) { cacheable_ = cacheable; }
263 /// EXPERIMENTAL: Trigger wait-for-ready or not on this request.
264 /// See https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md.
265 /// If set, if an RPC is made when a channel's connectivity state is
266 /// TRANSIENT_FAILURE or CONNECTING, the call will not "fail fast",
267 /// and the channel will wait until the channel is READY before making the
269 void set_wait_for_ready(bool wait_for_ready) {
270 wait_for_ready_ = wait_for_ready;
271 wait_for_ready_explicitly_set_ = true;
274 /// DEPRECATED: Use set_wait_for_ready() instead.
275 void set_fail_fast(bool fail_fast) { set_wait_for_ready(!fail_fast); }
277 /// Return the deadline for the client call.
278 std::chrono::system_clock::time_point deadline() const {
279 return Timespec2Timepoint(deadline_);
282 /// Return a \a gpr_timespec representation of the client call's deadline.
283 gpr_timespec raw_deadline() const { return deadline_; }
285 /// Set the per call authority header (see
286 /// https://tools.ietf.org/html/rfc7540#section-8.1.2.3).
287 void set_authority(const grpc::string& authority) { authority_ = authority; }
289 /// Return the authentication context for this client call.
291 /// \see grpc::AuthContext.
292 std::shared_ptr<const AuthContext> auth_context() const {
293 if (auth_context_.get() == nullptr) {
294 auth_context_ = CreateAuthContext(call_);
296 return auth_context_;
299 /// Set credentials for the client call.
301 /// A credentials object encapsulates all the state needed by a client to
302 /// authenticate with a server and make various assertions, e.g., about the
303 /// client’s identity, role, or whether it is authorized to make a particular
306 /// \see https://grpc.io/docs/guides/auth.html
307 void set_credentials(const std::shared_ptr<CallCredentials>& creds) {
311 /// Return the compression algorithm the client call will request be used.
312 /// Note that the gRPC runtime may decide to ignore this request, for example,
313 /// due to resource constraints.
314 grpc_compression_algorithm compression_algorithm() const {
315 return compression_algorithm_;
318 /// Set \a algorithm to be the compression algorithm used for the client call.
320 /// \param algorithm The compression algorithm used for the client call.
321 void set_compression_algorithm(grpc_compression_algorithm algorithm);
323 /// Flag whether the initial metadata should be \a corked
325 /// If \a corked is true, then the initial metadata will be coalesced with the
326 /// write of first message in the stream. As a result, any tag set for the
327 /// initial metadata operation (starting a client-streaming or bidi-streaming
328 /// RPC) will not actually be sent to the completion queue or delivered
331 /// \param corked The flag indicating whether the initial metadata is to be
333 void set_initial_metadata_corked(bool corked) {
334 initial_metadata_corked_ = corked;
337 /// Return the peer uri in a string.
339 /// \warning This value is never authenticated or subject to any security
340 /// related code. It must not be used for any authentication related
341 /// functionality. Instead, use auth_context.
343 /// \return The call's peer URI.
344 grpc::string peer() const;
346 /// Get and set census context.
347 void set_census_context(struct census_context* ccp) { census_context_ = ccp; }
348 struct census_context* census_context() const {
349 return census_context_;
352 /// Send a best-effort out-of-band cancel on the call associated with
353 /// this client context. The call could be in any stage; e.g., if it is
354 /// already finished, it may still return success.
356 /// There is no guarantee the call will be cancelled.
358 /// Note that TryCancel() does not change any of the tags that are pending
359 /// on the completion queue. All pending tags will still be delivered
360 /// (though their ok result may reflect the effect of cancellation).
365 /// Can be set exactly once per application to install hooks whenever
366 /// a client context is constructed and destructed.
367 class GlobalCallbacks {
369 virtual ~GlobalCallbacks() {}
370 virtual void DefaultConstructor(ClientContext* context) = 0;
371 virtual void Destructor(ClientContext* context) = 0;
373 static void SetGlobalCallbacks(GlobalCallbacks* callbacks);
375 /// Should be used for framework-level extensions only.
376 /// Applications never need to call this method.
377 grpc_call* c_call() { return call_; }
379 /// EXPERIMENTAL debugging API
381 /// if status is not ok() for an RPC, this will return a detailed string
382 /// of the gRPC Core error that led to the failure. It should not be relied
383 /// upon for anything other than gaining more debug data in failure cases.
384 grpc::string debug_error_string() const { return debug_error_string_; }
387 // Disallow copy and assign.
388 ClientContext(const ClientContext&);
389 ClientContext& operator=(const ClientContext&);
391 friend class ::grpc::testing::InteropClientContextInspector;
392 friend class ::grpc::internal::CallOpClientRecvStatus;
393 friend class ::grpc::internal::CallOpRecvInitialMetadata;
394 friend class Channel;
396 friend class ::grpc::ClientReader;
398 friend class ::grpc::ClientWriter;
399 template <class W, class R>
400 friend class ::grpc::ClientReaderWriter;
402 friend class ::grpc::ClientAsyncReader;
404 friend class ::grpc::ClientAsyncWriter;
405 template <class W, class R>
406 friend class ::grpc::ClientAsyncReaderWriter;
408 friend class ::grpc::ClientAsyncResponseReader;
409 template <class InputMessage, class OutputMessage>
410 friend class ::grpc::internal::BlockingUnaryCallImpl;
411 template <class InputMessage, class OutputMessage>
412 friend class ::grpc::internal::CallbackUnaryCallImpl;
413 template <class Request, class Response>
414 friend class ::grpc::internal::ClientCallbackReaderWriterImpl;
415 template <class Response>
416 friend class ::grpc::internal::ClientCallbackReaderImpl;
417 template <class Request>
418 friend class ::grpc::internal::ClientCallbackWriterImpl;
420 // Used by friend class CallOpClientRecvStatus
421 void set_debug_error_string(const grpc::string& debug_error_string) {
422 debug_error_string_ = debug_error_string;
425 grpc_call* call() const { return call_; }
426 void set_call(grpc_call* call, const std::shared_ptr<Channel>& channel);
428 experimental::ClientRpcInfo* set_client_rpc_info(
429 const char* method, internal::RpcMethod::RpcType type,
430 grpc::ChannelInterface* channel,
432 std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>&
434 size_t interceptor_pos) {
435 rpc_info_ = experimental::ClientRpcInfo(this, type, method, channel);
436 rpc_info_.RegisterInterceptors(creators, interceptor_pos);
440 uint32_t initial_metadata_flags() const {
441 return (idempotent_ ? GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST : 0) |
442 (wait_for_ready_ ? GRPC_INITIAL_METADATA_WAIT_FOR_READY : 0) |
443 (cacheable_ ? GRPC_INITIAL_METADATA_CACHEABLE_REQUEST : 0) |
444 (wait_for_ready_explicitly_set_
445 ? GRPC_INITIAL_METADATA_WAIT_FOR_READY_EXPLICITLY_SET
447 (initial_metadata_corked_ ? GRPC_INITIAL_METADATA_CORKED : 0);
450 grpc::string authority() { return authority_; }
452 void SendCancelToInterceptors();
454 bool initial_metadata_received_;
455 bool wait_for_ready_;
456 bool wait_for_ready_explicitly_set_;
459 std::shared_ptr<Channel> channel_;
463 gpr_timespec deadline_;
464 grpc::string authority_;
465 std::shared_ptr<CallCredentials> creds_;
466 mutable std::shared_ptr<const AuthContext> auth_context_;
467 struct census_context* census_context_;
468 std::multimap<grpc::string, grpc::string> send_initial_metadata_;
469 mutable internal::MetadataMap recv_initial_metadata_;
470 mutable internal::MetadataMap trailing_metadata_;
472 grpc_call* propagate_from_call_;
473 PropagationOptions propagation_options_;
475 grpc_compression_algorithm compression_algorithm_;
476 bool initial_metadata_corked_;
478 grpc::string debug_error_string_;
480 experimental::ClientRpcInfo rpc_info_;
485 #endif // GRPCPP_IMPL_CODEGEN_CLIENT_CONTEXT_H