5946488566eefa894dc754765a399d6ba6da9e56
[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/time.h>
55
56 struct census_context;
57 struct grpc_call;
58
59 namespace grpc {
60
61 class Channel;
62 class ChannelInterface;
63 class CompletionQueue;
64 class CallCredentials;
65 class ClientContext;
66
67 namespace internal {
68 class RpcMethod;
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
82
83 template <class R>
84 class ClientReader;
85 template <class W>
86 class ClientWriter;
87 template <class W, class R>
88 class ClientReaderWriter;
89 template <class R>
90 class ClientAsyncReader;
91 template <class W>
92 class ClientAsyncWriter;
93 template <class W, class R>
94 class ClientAsyncReaderWriter;
95 template <class R>
96 class ClientAsyncResponseReader;
97 class ServerContext;
98
99 /// Options for \a ClientContext::FromServerContext specifying which traits from
100 /// the \a ServerContext to propagate (copy) from it into a new \a
101 /// ClientContext.
102 ///
103 /// \see ClientContext::FromServerContext
104 class PropagationOptions {
105  public:
106   PropagationOptions() : propagate_(GRPC_PROPAGATE_DEFAULTS) {}
107
108   PropagationOptions& enable_deadline_propagation() {
109     propagate_ |= GRPC_PROPAGATE_DEADLINE;
110     return *this;
111   }
112
113   PropagationOptions& disable_deadline_propagation() {
114     propagate_ &= ~GRPC_PROPAGATE_DEADLINE;
115     return *this;
116   }
117
118   PropagationOptions& enable_census_stats_propagation() {
119     propagate_ |= GRPC_PROPAGATE_CENSUS_STATS_CONTEXT;
120     return *this;
121   }
122
123   PropagationOptions& disable_census_stats_propagation() {
124     propagate_ &= ~GRPC_PROPAGATE_CENSUS_STATS_CONTEXT;
125     return *this;
126   }
127
128   PropagationOptions& enable_census_tracing_propagation() {
129     propagate_ |= GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT;
130     return *this;
131   }
132
133   PropagationOptions& disable_census_tracing_propagation() {
134     propagate_ &= ~GRPC_PROPAGATE_CENSUS_TRACING_CONTEXT;
135     return *this;
136   }
137
138   PropagationOptions& enable_cancellation_propagation() {
139     propagate_ |= GRPC_PROPAGATE_CANCELLATION;
140     return *this;
141   }
142
143   PropagationOptions& disable_cancellation_propagation() {
144     propagate_ &= ~GRPC_PROPAGATE_CANCELLATION;
145     return *this;
146   }
147
148   uint32_t c_bitmask() const { return propagate_; }
149
150  private:
151   uint32_t propagate_;
152 };
153
154 namespace testing {
155 class InteropClientContextInspector;
156 }  // namespace testing
157
158 /// A ClientContext allows the person implementing a service client to:
159 ///
160 /// - Add custom metadata key-value pairs that will propagated to the server
161 ///   side.
162 /// - Control call settings such as compression and authentication.
163 /// - Initial and trailing metadata coming from the server.
164 /// - Get performance metrics (ie, census).
165 ///
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).
170 ///
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 {
175  public:
176   ClientContext();
177   ~ClientContext();
178
179   /// Create a new \a ClientContext as a child of an incoming server call,
180   /// according to \a options (\see PropagationOptions).
181   ///
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
185   /// server_context.
186   ///
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());
192
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.
196   ///
197   /// \warning This method should only be called before invoking the rpc.
198   ///
199   /// \param meta_key The metadata key. If \a meta_value is binary data, it must
200   /// end in "-bin".
201   /// \param meta_value The metadata value. If its value is binary, the key name
202   /// must end in "-bin".
203   ///
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);
212
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).
215   ///
216   /// \warning This method should only be called after initial metadata has been
217   /// received. For streaming calls, see \a
218   /// ClientReaderInterface::WaitForInitialMetadata().
219   ///
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();
225   }
226
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).
229   ///
230   /// \warning This method is only callable once the stream has finished.
231   ///
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();
237   }
238
239   /// Set the deadline for the client call.
240   ///
241   /// \warning This method should only be called before invoking the rpc.
242   ///
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();
249   }
250
251   /// EXPERIMENTAL: Indicate that this request is idempotent.
252   /// By default, RPCs are assumed to <i>not</i> be idempotent.
253   ///
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; }
257
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; }
262
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
268   /// call.
269   void set_wait_for_ready(bool wait_for_ready) {
270     wait_for_ready_ = wait_for_ready;
271     wait_for_ready_explicitly_set_ = true;
272   }
273
274   /// DEPRECATED: Use set_wait_for_ready() instead.
275   void set_fail_fast(bool fail_fast) { set_wait_for_ready(!fail_fast); }
276
277   /// Return the deadline for the client call.
278   std::chrono::system_clock::time_point deadline() const {
279     return Timespec2Timepoint(deadline_);
280   }
281
282   /// Return a \a gpr_timespec representation of the client call's deadline.
283   gpr_timespec raw_deadline() const { return deadline_; }
284
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; }
288
289   /// Return the authentication context for this client call.
290   ///
291   /// \see grpc::AuthContext.
292   std::shared_ptr<const AuthContext> auth_context() const {
293     if (auth_context_.get() == nullptr) {
294       auth_context_ = CreateAuthContext(call_);
295     }
296     return auth_context_;
297   }
298
299   /// Set credentials for the client call.
300   ///
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
304   /// call.
305   ///
306   /// \see  https://grpc.io/docs/guides/auth.html
307   void set_credentials(const std::shared_ptr<CallCredentials>& creds) {
308     creds_ = creds;
309   }
310
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_;
316   }
317
318   /// Set \a algorithm to be the compression algorithm used for the client call.
319   ///
320   /// \param algorithm The compression algorithm used for the client call.
321   void set_compression_algorithm(grpc_compression_algorithm algorithm);
322
323   /// Flag whether the initial metadata should be \a corked
324   ///
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
329   /// via Next.
330   ///
331   /// \param corked The flag indicating whether the initial metadata is to be
332   /// corked or not.
333   void set_initial_metadata_corked(bool corked) {
334     initial_metadata_corked_ = corked;
335   }
336
337   /// Return the peer uri in a string.
338   ///
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.
342   ///
343   /// \return The call's peer URI.
344   grpc::string peer() const;
345
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_;
350   }
351
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.
355   ///
356   /// There is no guarantee the call will be cancelled.
357   ///
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).
361   void TryCancel();
362
363   /// Global Callbacks
364   ///
365   /// Can be set exactly once per application to install hooks whenever
366   /// a client context is constructed and destructed.
367   class GlobalCallbacks {
368    public:
369     virtual ~GlobalCallbacks() {}
370     virtual void DefaultConstructor(ClientContext* context) = 0;
371     virtual void Destructor(ClientContext* context) = 0;
372   };
373   static void SetGlobalCallbacks(GlobalCallbacks* callbacks);
374
375   /// Should be used for framework-level extensions only.
376   /// Applications never need to call this method.
377   grpc_call* c_call() { return call_; }
378
379   /// EXPERIMENTAL debugging API
380   ///
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_; }
385
386  private:
387   // Disallow copy and assign.
388   ClientContext(const ClientContext&);
389   ClientContext& operator=(const ClientContext&);
390
391   friend class ::grpc::testing::InteropClientContextInspector;
392   friend class ::grpc::internal::CallOpClientRecvStatus;
393   friend class ::grpc::internal::CallOpRecvInitialMetadata;
394   friend class Channel;
395   template <class R>
396   friend class ::grpc::ClientReader;
397   template <class W>
398   friend class ::grpc::ClientWriter;
399   template <class W, class R>
400   friend class ::grpc::ClientReaderWriter;
401   template <class R>
402   friend class ::grpc::ClientAsyncReader;
403   template <class W>
404   friend class ::grpc::ClientAsyncWriter;
405   template <class W, class R>
406   friend class ::grpc::ClientAsyncReaderWriter;
407   template <class R>
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;
419
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;
423   }
424
425   grpc_call* call() const { return call_; }
426   void set_call(grpc_call* call, const std::shared_ptr<Channel>& channel);
427
428   experimental::ClientRpcInfo* set_client_rpc_info(
429       const char* method, internal::RpcMethod::RpcType type,
430       grpc::ChannelInterface* channel,
431       const std::vector<
432           std::unique_ptr<experimental::ClientInterceptorFactoryInterface>>&
433           creators,
434       size_t interceptor_pos) {
435     rpc_info_ = experimental::ClientRpcInfo(this, type, method, channel);
436     rpc_info_.RegisterInterceptors(creators, interceptor_pos);
437     return &rpc_info_;
438   }
439
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
446                 : 0) |
447            (initial_metadata_corked_ ? GRPC_INITIAL_METADATA_CORKED : 0);
448   }
449
450   grpc::string authority() { return authority_; }
451
452   void SendCancelToInterceptors();
453
454   bool initial_metadata_received_;
455   bool wait_for_ready_;
456   bool wait_for_ready_explicitly_set_;
457   bool idempotent_;
458   bool cacheable_;
459   std::shared_ptr<Channel> channel_;
460   std::mutex mu_;
461   grpc_call* call_;
462   bool call_canceled_;
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_;
471
472   grpc_call* propagate_from_call_;
473   PropagationOptions propagation_options_;
474
475   grpc_compression_algorithm compression_algorithm_;
476   bool initial_metadata_corked_;
477
478   grpc::string debug_error_string_;
479
480   experimental::ClientRpcInfo rpc_info_;
481 };
482
483 }  // namespace grpc
484
485 #endif  // GRPCPP_IMPL_CODEGEN_CLIENT_CONTEXT_H