You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

client_context.h 22 kB

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