999d8fcbfe721b09ecb08b0be09983ecfce07f21
[platform/upstream/grpc.git] / include / grpcpp / impl / codegen / client_context.h
1 /*
2  *
3  * Copyright 2015 gRPC authors.
4  *
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
8  *
9  *     http://www.apache.org/licenses/LICENSE-2.0
10  *
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.
16  *
17  */
18
19 /// A ClientContext allows the person implementing a service client to:
20 ///
21 /// - Add custom metadata key-value pairs that will propagated to the server
22 /// side.
23 /// - Control call settings such as compression and authentication.
24 /// - Initial and trailing metadata coming from the server.
25 /// - Get performance metrics (ie, census).
26 ///
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).
31 ///
32 /// \warning ClientContext instances should \em not be reused across rpcs.
33
34 #ifndef GRPCPP_IMPL_CODEGEN_CLIENT_CONTEXT_H
35 #define GRPCPP_IMPL_CODEGEN_CLIENT_CONTEXT_H
36
37 #include <map>
38 #include <memory>
39 #include <mutex>
40 #include <string>
41
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/sync.h>
55 #include <grpcpp/impl/codegen/time.h>
56
57 struct census_context;
58 struct grpc_call;
59
60 namespace grpc_impl {
61
62 class CallCredentials;
63 class Channel;
64 class CompletionQueue;
65 }  // namespace grpc_impl
66 namespace grpc {
67
68 class ChannelInterface;
69 class ClientContext;
70
71 namespace internal {
72 class RpcMethod;
73 class CallOpClientRecvStatus;
74 class CallOpRecvInitialMetadata;
75 template <class InputMessage, class OutputMessage>
76 class BlockingUnaryCallImpl;
77 template <class InputMessage, class OutputMessage>
78 class CallbackUnaryCallImpl;
79 template <class Request, class Response>
80 class ClientCallbackReaderWriterImpl;
81 template <class Response>
82 class ClientCallbackReaderImpl;
83 template <class Request>
84 class ClientCallbackWriterImpl;
85 class ClientCallbackUnaryImpl;
86 }  // namespace internal
87
88 template <class R>
89 class ClientReader;
90 template <class W>
91 class ClientWriter;
92 template <class W, class R>
93 class ClientReaderWriter;
94 template <class R>
95 class ClientAsyncReader;
96 template <class W>
97 class ClientAsyncWriter;
98 template <class W, class R>
99 class ClientAsyncReaderWriter;
100 template <class R>
101 class ClientAsyncResponseReader;
102 class ServerContext;
103
104 /// Options for \a ClientContext::FromServerContext specifying which traits from
105 /// the \a ServerContext to propagate (copy) from it into a new \a
106 /// ClientContext.
107 ///
108 /// \see ClientContext::FromServerContext
109 class PropagationOptions {
110  public:
111   PropagationOptions() : propagate_(GRPC_PROPAGATE_DEFAULTS) {}
112
113   PropagationOptions& enable_deadline_propagation() {
114     propagate_ |= GRPC_PROPAGATE_DEADLINE;
115     return *this;
116   }
117
118   PropagationOptions& disable_deadline_propagation() {
119     propagate_ &= ~GRPC_PROPAGATE_DEADLINE;
120     return *this;
121   }
122
123   PropagationOptions& enable_census_stats_propagation() {
124     propagate_ |= GRPC_PROPAGATE_CENSUS_STATS_CONTEXT;
125     return *this;
126   }
127
128   PropagationOptions& disable_census_stats_propagation() {
129     propagate_ &= ~GRPC_PROPAGATE_CENSUS_STATS_CONTEXT;
130     return *this;
131   }
132
133   PropagationOptions& enable_census_tracing_propagation() {
134     propagate_ |= GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT;
135     return *this;
136   }
137
138   PropagationOptions& disable_census_tracing_propagation() {
139     propagate_ &= ~GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT;
140     return *this;
141   }
142
143   PropagationOptions& enable_cancellation_propagation() {
144     propagate_ |= GRPC_PROPAGATE_CANCELLATION;
145     return *this;
146   }
147
148   PropagationOptions& disable_cancellation_propagation() {
149     propagate_ &= ~GRPC_PROPAGATE_CANCELLATION;
150     return *this;
151   }
152
153   uint32_t c_bitmask() const { return propagate_; }
154
155  private:
156   uint32_t propagate_;
157 };
158
159 namespace testing {
160 class InteropClientContextInspector;
161 }  // namespace testing
162
163 /// A ClientContext allows the person implementing a service client to:
164 ///
165 /// - Add custom metadata key-value pairs that will propagated to the server
166 ///   side.
167 /// - Control call settings such as compression and authentication.
168 /// - Initial and trailing metadata coming from the server.
169 /// - Get performance metrics (ie, census).
170 ///
171 /// Context settings are only relevant to the call they are invoked with, that
172 /// is to say, they aren't sticky. Some of these settings, such as the
173 /// compression options, can be made persistent at channel construction time
174 /// (see \a grpc::CreateCustomChannel).
175 ///
176 /// \warning ClientContext instances should \em not be reused across rpcs.
177 /// \warning The ClientContext instance used for creating an rpc must remain
178 ///          alive and valid for the lifetime of the rpc.
179 class ClientContext {
180  public:
181   ClientContext();
182   ~ClientContext();
183
184   /// Create a new \a ClientContext as a child of an incoming server call,
185   /// according to \a options (\see PropagationOptions).
186   ///
187   /// \param server_context The source server context to use as the basis for
188   /// constructing the client context.
189   /// \param options The options controlling what to copy from the \a
190   /// server_context.
191   ///
192   /// \return A newly constructed \a ClientContext instance based on \a
193   /// server_context, with traits propagated (copied) according to \a options.
194   static std::unique_ptr<ClientContext> FromServerContext(
195       const ServerContext& server_context,
196       PropagationOptions options = PropagationOptions());
197
198   /// Add the (\a meta_key, \a meta_value) pair to the metadata associated with
199   /// a client call. These are made available at the server side by the \a
200   /// grpc::ServerContext::client_metadata() method.
201   ///
202   /// \warning This method should only be called before invoking the rpc.
203   ///
204   /// \param meta_key The metadata key. If \a meta_value is binary data, it must
205   /// end in "-bin".
206   /// \param meta_value The metadata value. If its value is binary, the key name
207   /// must end in "-bin".
208   ///
209   /// Metadata must conform to the following format:
210   /// Custom-Metadata -> Binary-Header / ASCII-Header
211   /// Binary-Header -> {Header-Name "-bin" } {binary value}
212   /// ASCII-Header -> Header-Name ASCII-Value
213   /// Header-Name -> 1*( %x30-39 / %x61-7A / "_" / "-" / ".") ; 0-9 a-z _ - .
214   /// ASCII-Value -> 1*( %x20-%x7E ) ; space and printable ASCII
215   void AddMetadata(const grpc::string& meta_key,
216                    const grpc::string& meta_value);
217
218   /// Return a collection of initial metadata key-value pairs. Note that keys
219   /// may happen more than once (ie, a \a std::multimap is returned).
220   ///
221   /// \warning This method should only be called after initial metadata has been
222   /// received. For streaming calls, see \a
223   /// ClientReaderInterface::WaitForInitialMetadata().
224   ///
225   /// \return A multimap of initial metadata key-value pairs from the server.
226   const std::multimap<grpc::string_ref, grpc::string_ref>&
227   GetServerInitialMetadata() const {
228     GPR_CODEGEN_ASSERT(initial_metadata_received_);
229     return *recv_initial_metadata_.map();
230   }
231
232   /// Return a collection of trailing metadata key-value pairs. Note that keys
233   /// may happen more than once (ie, a \a std::multimap is returned).
234   ///
235   /// \warning This method is only callable once the stream has finished.
236   ///
237   /// \return A multimap of metadata trailing key-value pairs from the server.
238   const std::multimap<grpc::string_ref, grpc::string_ref>&
239   GetServerTrailingMetadata() const {
240     // TODO(yangg) check finished
241     return *trailing_metadata_.map();
242   }
243
244   /// Set the deadline for the client call.
245   ///
246   /// \warning This method should only be called before invoking the rpc.
247   ///
248   /// \param deadline the deadline for the client call. Units are determined by
249   /// the type used. The deadline is an absolute (not relative) time.
250   template <typename T>
251   void set_deadline(const T& deadline) {
252     TimePoint<T> deadline_tp(deadline);
253     deadline_ = deadline_tp.raw_time();
254   }
255
256   /// EXPERIMENTAL: Indicate that this request is idempotent.
257   /// By default, RPCs are assumed to <i>not</i> be idempotent.
258   ///
259   /// If true, the gRPC library assumes that it's safe to initiate
260   /// this RPC multiple times.
261   void set_idempotent(bool idempotent) { idempotent_ = idempotent; }
262
263   /// EXPERIMENTAL: Set this request to be cacheable.
264   /// If set, grpc is free to use the HTTP GET verb for sending the request,
265   /// with the possibility of receiving a cached response.
266   void set_cacheable(bool cacheable) { cacheable_ = cacheable; }
267
268   /// EXPERIMENTAL: Trigger wait-for-ready or not on this request.
269   /// See https://github.com/grpc/grpc/blob/master/doc/wait-for-ready.md.
270   /// If set, if an RPC is made when a channel's connectivity state is
271   /// TRANSIENT_FAILURE or CONNECTING, the call will not "fail fast",
272   /// and the channel will wait until the channel is READY before making the
273   /// call.
274   void set_wait_for_ready(bool wait_for_ready) {
275     wait_for_ready_ = wait_for_ready;
276     wait_for_ready_explicitly_set_ = true;
277   }
278
279   /// DEPRECATED: Use set_wait_for_ready() instead.
280   void set_fail_fast(bool fail_fast) { set_wait_for_ready(!fail_fast); }
281
282   /// Return the deadline for the client call.
283   std::chrono::system_clock::time_point deadline() const {
284     return Timespec2Timepoint(deadline_);
285   }
286
287   /// Return a \a gpr_timespec representation of the client call's deadline.
288   gpr_timespec raw_deadline() const { return deadline_; }
289
290   /// Set the per call authority header (see
291   /// https://tools.ietf.org/html/rfc7540#section-8.1.2.3).
292   void set_authority(const grpc::string& authority) { authority_ = authority; }
293
294   /// Return the authentication context for this client call.
295   ///
296   /// \see grpc::AuthContext.
297   std::shared_ptr<const AuthContext> auth_context() const {
298     if (auth_context_.get() == nullptr) {
299       auth_context_ = CreateAuthContext(call_);
300     }
301     return auth_context_;
302   }
303
304   /// Set credentials for the client call.
305   ///
306   /// A credentials object encapsulates all the state needed by a client to
307   /// authenticate with a server and make various assertions, e.g., about the
308   /// client’s identity, role, or whether it is authorized to make a particular
309   /// call.
310   ///
311   /// \see  https://grpc.io/docs/guides/auth.html
312   void set_credentials(
313       const std::shared_ptr<grpc_impl::CallCredentials>& creds) {
314     creds_ = creds;
315   }
316
317   /// Return the compression algorithm the client call will request be used.
318   /// Note that the gRPC runtime may decide to ignore this request, for example,
319   /// due to resource constraints.
320   grpc_compression_algorithm compression_algorithm() const {
321     return compression_algorithm_;
322   }
323
324   /// Set \a algorithm to be the compression algorithm used for the client call.
325   ///
326   /// \param algorithm The compression algorithm used for the client call.
327   void set_compression_algorithm(grpc_compression_algorithm algorithm);
328
329   /// Flag whether the initial metadata should be \a corked
330   ///
331   /// If \a corked is true, then the initial metadata will be coalesced with the
332   /// write of first message in the stream. As a result, any tag set for the
333   /// initial metadata operation (starting a client-streaming or bidi-streaming
334   /// RPC) will not actually be sent to the completion queue or delivered
335   /// via Next.
336   ///
337   /// \param corked The flag indicating whether the initial metadata is to be
338   /// corked or not.
339   void set_initial_metadata_corked(bool corked) {
340     initial_metadata_corked_ = corked;
341   }
342
343   /// Return the peer uri in a string.
344   ///
345   /// \warning This value is never authenticated or subject to any security
346   /// related code. It must not be used for any authentication related
347   /// functionality. Instead, use auth_context.
348   ///
349   /// \return The call's peer URI.
350   grpc::string peer() const;
351
352   /// Get and set census context.
353   void set_census_context(struct census_context* ccp) { census_context_ = ccp; }
354   struct census_context* census_context() const {
355     return census_context_;
356   }
357
358   /// Send a best-effort out-of-band cancel on the call associated with
359   /// this client context.  The call could be in any stage; e.g., if it is
360   /// already finished, it may still return success.
361   ///
362   /// There is no guarantee the call will be cancelled.
363   ///
364   /// Note that TryCancel() does not change any of the tags that are pending
365   /// on the completion queue. All pending tags will still be delivered
366   /// (though their ok result may reflect the effect of cancellation).
367   void TryCancel();
368
369   /// Global Callbacks
370   ///
371   /// Can be set exactly once per application to install hooks whenever
372   /// a client context is constructed and destructed.
373   class GlobalCallbacks {
374    public:
375     virtual ~GlobalCallbacks() {}
376     virtual void DefaultConstructor(ClientContext* context) = 0;
377     virtual void Destructor(ClientContext* context) = 0;
378   };
379   static void SetGlobalCallbacks(GlobalCallbacks* callbacks);
380
381   /// Should be used for framework-level extensions only.
382   /// Applications never need to call this method.
383   grpc_call* c_call() { return call_; }
384
385   /// EXPERIMENTAL debugging API
386   ///
387   /// if status is not ok() for an RPC, this will return a detailed string
388   /// of the gRPC Core error that led to the failure. It should not be relied
389   /// upon for anything other than gaining more debug data in failure cases.
390   grpc::string debug_error_string() const { return debug_error_string_; }
391
392  private:
393   // Disallow copy and assign.
394   ClientContext(const ClientContext&);
395   ClientContext& operator=(const ClientContext&);
396
397   friend class ::grpc::testing::InteropClientContextInspector;
398   friend class ::grpc::internal::CallOpClientRecvStatus;
399   friend class ::grpc::internal::CallOpRecvInitialMetadata;
400   friend class ::grpc_impl::Channel;
401   template <class R>
402   friend class ::grpc::ClientReader;
403   template <class W>
404   friend class ::grpc::ClientWriter;
405   template <class W, class R>
406   friend class ::grpc::ClientReaderWriter;
407   template <class R>
408   friend class ::grpc::ClientAsyncReader;
409   template <class W>
410   friend class ::grpc::ClientAsyncWriter;
411   template <class W, class R>
412   friend class ::grpc::ClientAsyncReaderWriter;
413   template <class R>
414   friend class ::grpc::ClientAsyncResponseReader;
415   template <class InputMessage, class OutputMessage>
416   friend class ::grpc::internal::BlockingUnaryCallImpl;
417   template <class InputMessage, class OutputMessage>
418   friend class ::grpc::internal::CallbackUnaryCallImpl;
419   template <class Request, class Response>
420   friend class ::grpc::internal::ClientCallbackReaderWriterImpl;
421   template <class Response>
422   friend class ::grpc::internal::ClientCallbackReaderImpl;
423   template <class Request>
424   friend class ::grpc::internal::ClientCallbackWriterImpl;
425   friend class ::grpc::internal::ClientCallbackUnaryImpl;
426
427   // Used by friend class CallOpClientRecvStatus
428   void set_debug_error_string(const grpc::string& debug_error_string) {
429     debug_error_string_ = debug_error_string;
430   }
431
432   grpc_call* call() const { return call_; }
433   void set_call(grpc_call* call,
434                 const std::shared_ptr<::grpc_impl::Channel>& channel);
435
436   experimental::ClientRpcInfo* set_client_rpc_info(
437       const char* method, internal::RpcMethod::RpcType type,
438       grpc::ChannelInterface* channel,
439       const std::vector<
440           std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>&
441           creators,
442       size_t interceptor_pos) {
443     rpc_info_ = experimental::ClientRpcInfo(this, type, method, channel);
444     rpc_info_.RegisterInterceptors(creators, interceptor_pos);
445     return &rpc_info_;
446   }
447
448   uint32_t initial_metadata_flags() const {
449     return (idempotent_ ? GRPC_INITIAL_METADATA_IDEMPOTENT_REQUEST : 0) |
450            (wait_for_ready_ ? GRPC_INITIAL_METADATA_WAIT_FOR_READY : 0) |
451            (cacheable_ ? GRPC_INITIAL_METADATA_CACHEABLE_REQUEST : 0) |
452            (wait_for_ready_explicitly_set_
453                 ? GRPC_INITIAL_METADATA_WAIT_FOR_READY_EXPLICITLY_SET
454                 : 0) |
455            (initial_metadata_corked_ ? GRPC_INITIAL_METADATA_CORKED : 0);
456   }
457
458   grpc::string authority() { return authority_; }
459
460   void SendCancelToInterceptors();
461
462   bool initial_metadata_received_;
463   bool wait_for_ready_;
464   bool wait_for_ready_explicitly_set_;
465   bool idempotent_;
466   bool cacheable_;
467   std::shared_ptr<::grpc_impl::Channel> channel_;
468   grpc::internal::Mutex mu_;
469   grpc_call* call_;
470   bool call_canceled_;
471   gpr_timespec deadline_;
472   grpc::string authority_;
473   std::shared_ptr<grpc_impl::CallCredentials> creds_;
474   mutable std::shared_ptr<const AuthContext> auth_context_;
475   struct census_context* census_context_;
476   std::multimap<grpc::string, grpc::string> send_initial_metadata_;
477   mutable internal::MetadataMap recv_initial_metadata_;
478   mutable internal::MetadataMap trailing_metadata_;
479
480   grpc_call* propagate_from_call_;
481   PropagationOptions propagation_options_;
482
483   grpc_compression_algorithm compression_algorithm_;
484   bool initial_metadata_corked_;
485
486   grpc::string debug_error_string_;
487
488   experimental::ClientRpcInfo rpc_info_;
489 };
490
491 }  // namespace grpc
492
493 #endif  // GRPCPP_IMPL_CODEGEN_CLIENT_CONTEXT_H