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.

server_context.h 26 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  1. /*
  2. *
  3. * Copyright 2019 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. #ifndef GRPCPP_IMPL_CODEGEN_SERVER_CONTEXT_H
  19. #define GRPCPP_IMPL_CODEGEN_SERVER_CONTEXT_H
  20. // IWYU pragma: private, include <grpcpp/server_context.h>
  21. #include <grpc/impl/codegen/port_platform.h>
  22. #include <atomic>
  23. #include <cassert>
  24. #include <map>
  25. #include <memory>
  26. #include <type_traits>
  27. #include <vector>
  28. #include <grpc/impl/codegen/compression_types.h>
  29. #include <grpcpp/impl/codegen/call.h>
  30. #include <grpcpp/impl/codegen/call_op_set.h>
  31. #include <grpcpp/impl/codegen/callback_common.h>
  32. #include <grpcpp/impl/codegen/completion_queue_tag.h>
  33. #include <grpcpp/impl/codegen/config.h>
  34. #include <grpcpp/impl/codegen/create_auth_context.h>
  35. #include <grpcpp/impl/codegen/message_allocator.h>
  36. #include <grpcpp/impl/codegen/metadata_map.h>
  37. #include <grpcpp/impl/codegen/rpc_service_method.h>
  38. #include <grpcpp/impl/codegen/security/auth_context.h>
  39. #include <grpcpp/impl/codegen/server_callback.h>
  40. #include <grpcpp/impl/codegen/server_interceptor.h>
  41. #include <grpcpp/impl/codegen/status.h>
  42. #include <grpcpp/impl/codegen/string_ref.h>
  43. #include <grpcpp/impl/codegen/time.h>
  44. struct grpc_metadata;
  45. struct grpc_call;
  46. struct census_context;
  47. namespace grpc {
  48. template <class W, class R>
  49. class ServerAsyncReader;
  50. template <class W>
  51. class ServerAsyncWriter;
  52. template <class W>
  53. class ServerAsyncResponseWriter;
  54. template <class W, class R>
  55. class ServerAsyncReaderWriter;
  56. template <class R>
  57. class ServerReader;
  58. template <class W>
  59. class ServerWriter;
  60. extern CoreCodegenInterface* g_core_codegen_interface;
  61. namespace internal {
  62. template <class ServiceType, class RequestType, class ResponseType>
  63. class BidiStreamingHandler;
  64. template <class RequestType, class ResponseType>
  65. class CallbackUnaryHandler;
  66. template <class RequestType, class ResponseType>
  67. class CallbackClientStreamingHandler;
  68. template <class RequestType, class ResponseType>
  69. class CallbackServerStreamingHandler;
  70. template <class RequestType, class ResponseType>
  71. class CallbackBidiHandler;
  72. template <class ServiceType, class RequestType, class ResponseType>
  73. class ClientStreamingHandler;
  74. template <class ResponseType>
  75. void UnaryRunHandlerHelper(const MethodHandler::HandlerParameter&,
  76. ResponseType*, Status&);
  77. template <class ServiceType, class RequestType, class ResponseType,
  78. class BaseRequestType, class BaseResponseType>
  79. class RpcMethodHandler;
  80. template <class Base>
  81. class FinishOnlyReactor;
  82. template <class W, class R>
  83. class ServerReaderWriterBody;
  84. template <class ServiceType, class RequestType, class ResponseType>
  85. class ServerStreamingHandler;
  86. class ServerReactor;
  87. template <class Streamer, bool WriteNeeded>
  88. class TemplatedBidiStreamingHandler;
  89. template <grpc::StatusCode code>
  90. class ErrorMethodHandler;
  91. } // namespace internal
  92. class ClientContext;
  93. class CompletionQueue;
  94. class GenericServerContext;
  95. class Server;
  96. class ServerInterface;
  97. class ContextAllocator;
  98. class GenericCallbackServerContext;
  99. namespace internal {
  100. class Call;
  101. } // namespace internal
  102. namespace testing {
  103. class InteropServerContextInspector;
  104. class ServerContextTestSpouse;
  105. class DefaultReactorTestPeer;
  106. } // namespace testing
  107. namespace experimental {
  108. class OrcaServerInterceptor;
  109. class CallMetricRecorder;
  110. } // namespace experimental
  111. /// Base class of ServerContext.
  112. class ServerContextBase {
  113. public:
  114. virtual ~ServerContextBase();
  115. /// Return the deadline for the server call.
  116. std::chrono::system_clock::time_point deadline() const {
  117. return grpc::Timespec2Timepoint(deadline_);
  118. }
  119. /// Return a \a gpr_timespec representation of the server call's deadline.
  120. gpr_timespec raw_deadline() const { return deadline_; }
  121. /// Add the (\a key, \a value) pair to the initial metadata
  122. /// associated with a server call. These are made available at the client side
  123. /// by the \a grpc::ClientContext::GetServerInitialMetadata() method.
  124. ///
  125. /// \warning This method should only be called before sending initial metadata
  126. /// to the client (which can happen explicitly, or implicitly when sending a
  127. /// a response message or status to the client).
  128. ///
  129. /// \param key The metadata key. If \a value is binary data, it must
  130. /// end in "-bin".
  131. /// \param value The metadata value. If its value is binary, the key name
  132. /// must end in "-bin".
  133. ///
  134. /// Metadata must conform to the following format:
  135. /**
  136. \verbatim
  137. Custom-Metadata -> Binary-Header / ASCII-Header
  138. Binary-Header -> {Header-Name "-bin" } {binary value}
  139. ASCII-Header -> Header-Name ASCII-Value
  140. Header-Name -> 1*( %x30-39 / %x61-7A / "_" / "-" / ".") ; 0-9 a-z _ - .
  141. ASCII-Value -> 1*( %x20-%x7E ) ; space and printable ASCII
  142. \endverbatim
  143. **/
  144. void AddInitialMetadata(const std::string& key, const std::string& value);
  145. /// Add the (\a key, \a value) pair to the initial metadata
  146. /// associated with a server call. These are made available at the client
  147. /// side by the \a grpc::ClientContext::GetServerTrailingMetadata() method.
  148. ///
  149. /// \warning This method should only be called before sending trailing
  150. /// metadata to the client (which happens when the call is finished and a
  151. /// status is sent to the client).
  152. ///
  153. /// \param key The metadata key. If \a value is binary data,
  154. /// it must end in "-bin".
  155. /// \param value The metadata value. If its value is binary, the key name
  156. /// must end in "-bin".
  157. ///
  158. /// Metadata must conform to the following format:
  159. /**
  160. \verbatim
  161. Custom-Metadata -> Binary-Header / ASCII-Header
  162. Binary-Header -> {Header-Name "-bin" } {binary value}
  163. ASCII-Header -> Header-Name ASCII-Value
  164. Header-Name -> 1*( %x30-39 / %x61-7A / "_" / "-" / ".") ; 0-9 a-z _ - .
  165. ASCII-Value -> 1*( %x20-%x7E ) ; space and printable ASCII
  166. \endverbatim
  167. **/
  168. void AddTrailingMetadata(const std::string& key, const std::string& value);
  169. /// Return whether this RPC failed before the server could provide its status
  170. /// back to the client. This could be because of explicit API cancellation
  171. /// from the client-side or server-side, because of deadline exceeded, network
  172. /// connection reset, HTTP/2 parameter configuration (e.g., max message size,
  173. /// max connection age), etc. It does NOT include failure due to a non-OK
  174. /// status return from the server application's request handler, including
  175. /// Status::CANCELLED.
  176. ///
  177. /// IsCancelled is always safe to call when using sync or callback API.
  178. /// When using async API, it is only safe to call IsCancelled after
  179. /// the AsyncNotifyWhenDone tag has been delivered. Thread-safe.
  180. bool IsCancelled() const;
  181. /// Cancel the Call from the server. This is a best-effort API and
  182. /// depending on when it is called, the RPC may still appear successful to
  183. /// the client. For example, if TryCancel() is called on a separate thread, it
  184. /// might race with the server handler which might return success to the
  185. /// client before TryCancel() was even started by the thread.
  186. ///
  187. /// It is the caller's responsibility to prevent such races and ensure that if
  188. /// TryCancel() is called, the serverhandler must return Status::CANCELLED.
  189. /// The only exception is that if the serverhandler is already returning an
  190. /// error status code, it is ok to not return Status::CANCELLED even if
  191. /// TryCancel() was called.
  192. ///
  193. /// For reasons such as the above, it is generally preferred to explicitly
  194. /// finish an RPC by returning Status::CANCELLED rather than using TryCancel.
  195. ///
  196. /// Note that TryCancel() does not change any of the tags that are pending
  197. /// on the completion queue. All pending tags will still be delivered
  198. /// (though their ok result may reflect the effect of cancellation).
  199. void TryCancel() const;
  200. /// Return a collection of initial metadata key-value pairs sent from the
  201. /// client. Note that keys may happen more than
  202. /// once (ie, a \a std::multimap is returned).
  203. ///
  204. /// It is safe to use this method after initial metadata has been received,
  205. /// Calls always begin with the client sending initial metadata, so this is
  206. /// safe to access as soon as the call has begun on the server side.
  207. ///
  208. /// \return A multimap of initial metadata key-value pairs from the server.
  209. const std::multimap<grpc::string_ref, grpc::string_ref>& client_metadata()
  210. const {
  211. return *client_metadata_.map();
  212. }
  213. /// Return the compression algorithm to be used by the server call.
  214. grpc_compression_level compression_level() const {
  215. return compression_level_;
  216. }
  217. /// Set \a level to be the compression level used for the server call.
  218. ///
  219. /// \param level The compression level used for the server call.
  220. void set_compression_level(grpc_compression_level level) {
  221. compression_level_set_ = true;
  222. compression_level_ = level;
  223. }
  224. /// Return a bool indicating whether the compression level for this call
  225. /// has been set (either implicitly or through a previous call to
  226. /// \a set_compression_level.
  227. bool compression_level_set() const { return compression_level_set_; }
  228. /// Return the compression algorithm the server call will request be used.
  229. /// Note that the gRPC runtime may decide to ignore this request, for example,
  230. /// due to resource constraints, or if the server is aware the client doesn't
  231. /// support the requested algorithm.
  232. grpc_compression_algorithm compression_algorithm() const {
  233. return compression_algorithm_;
  234. }
  235. /// Set \a algorithm to be the compression algorithm used for the server call.
  236. ///
  237. /// \param algorithm The compression algorithm used for the server call.
  238. void set_compression_algorithm(grpc_compression_algorithm algorithm);
  239. /// Set the serialized load reporting costs in \a cost_data for the call.
  240. void SetLoadReportingCosts(const std::vector<std::string>& cost_data);
  241. /// Return the authentication context for this server call.
  242. ///
  243. /// \see grpc::AuthContext.
  244. std::shared_ptr<const grpc::AuthContext> auth_context() const {
  245. if (auth_context_ == nullptr) {
  246. auth_context_ = grpc::CreateAuthContext(call_.call);
  247. }
  248. return auth_context_;
  249. }
  250. /// Return the peer uri in a string.
  251. /// WARNING: this value is never authenticated or subject to any security
  252. /// related code. It must not be used for any authentication related
  253. /// functionality. Instead, use auth_context.
  254. std::string peer() const;
  255. /// Get the census context associated with this server call.
  256. const struct census_context* census_context() const;
  257. /// Should be used for framework-level extensions only.
  258. /// Applications never need to call this method.
  259. grpc_call* c_call() { return call_.call; }
  260. /// Get the \a CallMetricRecorder object for the current RPC.
  261. /// Use it to record metrics during your RPC to send back to the
  262. /// client in order to make load balancing decisions. This will
  263. /// return nullptr if the feature hasn't been enabled using
  264. /// \a EnableCallMetricRecording.
  265. experimental::CallMetricRecorder* ExperimentalGetCallMetricRecorder() {
  266. return call_metric_recorder_;
  267. }
  268. /// EXPERIMENTAL API
  269. /// Returns the call's authority.
  270. grpc::string_ref ExperimentalGetAuthority() const;
  271. protected:
  272. /// Async only. Has to be called before the rpc starts.
  273. /// Returns the tag in completion queue when the rpc finishes.
  274. /// IsCancelled() can then be called to check whether the rpc was cancelled.
  275. /// TODO(vjpai): Fix this so that the tag is returned even if the call never
  276. /// starts (https://github.com/grpc/grpc/issues/10136).
  277. void AsyncNotifyWhenDone(void* tag) {
  278. has_notify_when_done_tag_ = true;
  279. async_notify_when_done_tag_ = tag;
  280. }
  281. /// NOTE: This is an API for advanced users who need custom allocators.
  282. /// Get and maybe mutate the allocator state associated with the current RPC.
  283. /// Currently only applicable for callback unary RPC methods.
  284. RpcAllocatorState* GetRpcAllocatorState() { return message_allocator_state_; }
  285. /// Get a library-owned default unary reactor for use in minimal reaction
  286. /// cases. This supports typical unary RPC usage of providing a response and
  287. /// status. It supports immediate Finish (finish from within the method
  288. /// handler) or delayed Finish (finish called after the method handler
  289. /// invocation). It does not support reacting to cancellation or completion,
  290. /// or early sending of initial metadata. Since this is a library-owned
  291. /// reactor, it should not be delete'd or freed in any way. This is more
  292. /// efficient than creating a user-owned reactor both because of avoiding an
  293. /// allocation and because its minimal reactions are optimized using a core
  294. /// surface flag that allows their reactions to run inline without any
  295. /// thread-hop.
  296. ///
  297. /// This method should not be called more than once or called after return
  298. /// from the method handler.
  299. grpc::ServerUnaryReactor* DefaultReactor() {
  300. // Short-circuit the case where a default reactor was already set up by
  301. // the TestPeer.
  302. if (test_unary_ != nullptr) {
  303. return reinterpret_cast<Reactor*>(&default_reactor_);
  304. }
  305. new (&default_reactor_) Reactor;
  306. #ifndef NDEBUG
  307. bool old = false;
  308. assert(default_reactor_used_.compare_exchange_strong(
  309. old, true, std::memory_order_relaxed));
  310. #else
  311. default_reactor_used_.store(true, std::memory_order_relaxed);
  312. #endif
  313. return reinterpret_cast<Reactor*>(&default_reactor_);
  314. }
  315. /// Constructors for use by derived classes
  316. ServerContextBase();
  317. ServerContextBase(gpr_timespec deadline, grpc_metadata_array* arr);
  318. void set_context_allocator(ContextAllocator* context_allocator) {
  319. context_allocator_ = context_allocator;
  320. }
  321. ContextAllocator* context_allocator() const { return context_allocator_; }
  322. private:
  323. friend class grpc::testing::InteropServerContextInspector;
  324. friend class grpc::testing::ServerContextTestSpouse;
  325. friend class grpc::testing::DefaultReactorTestPeer;
  326. friend class grpc::ServerInterface;
  327. friend class grpc::Server;
  328. template <class W, class R>
  329. friend class grpc::ServerAsyncReader;
  330. template <class W>
  331. friend class grpc::ServerAsyncWriter;
  332. template <class W>
  333. friend class grpc::ServerAsyncResponseWriter;
  334. template <class W, class R>
  335. friend class grpc::ServerAsyncReaderWriter;
  336. template <class R>
  337. friend class grpc::ServerReader;
  338. template <class W>
  339. friend class grpc::ServerWriter;
  340. template <class W, class R>
  341. friend class grpc::internal::ServerReaderWriterBody;
  342. template <class ResponseType>
  343. friend void grpc::internal::UnaryRunHandlerHelper(
  344. const internal::MethodHandler::HandlerParameter& param, ResponseType* rsp,
  345. Status& status);
  346. template <class ServiceType, class RequestType, class ResponseType,
  347. class BaseRequestType, class BaseResponseType>
  348. friend class grpc::internal::RpcMethodHandler;
  349. template <class ServiceType, class RequestType, class ResponseType>
  350. friend class grpc::internal::ClientStreamingHandler;
  351. template <class ServiceType, class RequestType, class ResponseType>
  352. friend class grpc::internal::ServerStreamingHandler;
  353. template <class Streamer, bool WriteNeeded>
  354. friend class grpc::internal::TemplatedBidiStreamingHandler;
  355. template <class RequestType, class ResponseType>
  356. friend class grpc::internal::CallbackUnaryHandler;
  357. template <class RequestType, class ResponseType>
  358. friend class grpc::internal::CallbackClientStreamingHandler;
  359. template <class RequestType, class ResponseType>
  360. friend class grpc::internal::CallbackServerStreamingHandler;
  361. template <class RequestType, class ResponseType>
  362. friend class grpc::internal::CallbackBidiHandler;
  363. template <grpc::StatusCode code>
  364. friend class grpc::internal::ErrorMethodHandler;
  365. template <class Base>
  366. friend class grpc::internal::FinishOnlyReactor;
  367. friend class grpc::ClientContext;
  368. friend class grpc::GenericServerContext;
  369. friend class grpc::GenericCallbackServerContext;
  370. friend class grpc::experimental::OrcaServerInterceptor;
  371. /// Prevent copying.
  372. ServerContextBase(const ServerContextBase&);
  373. ServerContextBase& operator=(const ServerContextBase&);
  374. class CompletionOp;
  375. void BeginCompletionOp(
  376. grpc::internal::Call* call, std::function<void(bool)> callback,
  377. grpc::internal::ServerCallbackCall* callback_controller);
  378. /// Return the tag queued by BeginCompletionOp()
  379. grpc::internal::CompletionQueueTag* GetCompletionOpTag();
  380. void set_call(grpc_call* call) { call_.call = call; }
  381. void BindDeadlineAndMetadata(gpr_timespec deadline, grpc_metadata_array* arr);
  382. uint32_t initial_metadata_flags() const { return 0; }
  383. grpc::experimental::ServerRpcInfo* set_server_rpc_info(
  384. const char* method, grpc::internal::RpcMethod::RpcType type,
  385. const std::vector<std::unique_ptr<
  386. grpc::experimental::ServerInterceptorFactoryInterface>>& creators) {
  387. if (!creators.empty()) {
  388. rpc_info_ = new grpc::experimental::ServerRpcInfo(this, method, type);
  389. rpc_info_->RegisterInterceptors(creators);
  390. }
  391. return rpc_info_;
  392. }
  393. void set_message_allocator_state(RpcAllocatorState* allocator_state) {
  394. message_allocator_state_ = allocator_state;
  395. }
  396. void MaybeMarkCancelledOnRead() {
  397. if (g_core_codegen_interface->grpc_call_failed_before_recv_message(
  398. call_.call)) {
  399. marked_cancelled_.store(true, std::memory_order_release);
  400. }
  401. }
  402. void CreateCallMetricRecorder();
  403. struct CallWrapper {
  404. ~CallWrapper();
  405. grpc_call* call = nullptr;
  406. };
  407. // NOTE: call_ must be the first data member of this object so that its
  408. // destructor is the last to be called, since its destructor may unref
  409. // the underlying core call which holds the arena that may be used to
  410. // hold this object.
  411. CallWrapper call_;
  412. CompletionOp* completion_op_ = nullptr;
  413. bool has_notify_when_done_tag_ = false;
  414. void* async_notify_when_done_tag_ = nullptr;
  415. grpc::internal::CallbackWithSuccessTag completion_tag_;
  416. gpr_timespec deadline_;
  417. grpc::CompletionQueue* cq_ = nullptr;
  418. bool sent_initial_metadata_ = false;
  419. mutable std::shared_ptr<const grpc::AuthContext> auth_context_;
  420. mutable grpc::internal::MetadataMap client_metadata_;
  421. std::multimap<std::string, std::string> initial_metadata_;
  422. std::multimap<std::string, std::string> trailing_metadata_;
  423. bool compression_level_set_ = false;
  424. grpc_compression_level compression_level_;
  425. grpc_compression_algorithm compression_algorithm_;
  426. grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
  427. grpc::internal::CallOpSendMessage>
  428. pending_ops_;
  429. bool has_pending_ops_ = false;
  430. grpc::experimental::ServerRpcInfo* rpc_info_ = nullptr;
  431. RpcAllocatorState* message_allocator_state_ = nullptr;
  432. ContextAllocator* context_allocator_ = nullptr;
  433. experimental::CallMetricRecorder* call_metric_recorder_ = nullptr;
  434. class Reactor : public grpc::ServerUnaryReactor {
  435. public:
  436. void OnCancel() override {}
  437. void OnDone() override {}
  438. // Override InternalInlineable for this class since its reactions are
  439. // trivial and thus do not need to be run from the executor (triggering a
  440. // thread hop). This should only be used by internal reactors (thus the
  441. // name) and not by user application code.
  442. bool InternalInlineable() override { return true; }
  443. };
  444. void SetupTestDefaultReactor(std::function<void(grpc::Status)> func) {
  445. // NOLINTNEXTLINE(modernize-make-unique)
  446. test_unary_.reset(new TestServerCallbackUnary(this, std::move(func)));
  447. }
  448. bool test_status_set() const {
  449. return (test_unary_ != nullptr) && test_unary_->status_set();
  450. }
  451. grpc::Status test_status() const { return test_unary_->status(); }
  452. class TestServerCallbackUnary : public grpc::ServerCallbackUnary {
  453. public:
  454. TestServerCallbackUnary(ServerContextBase* ctx,
  455. std::function<void(grpc::Status)> func)
  456. : reactor_(ctx->DefaultReactor()), func_(std::move(func)) {
  457. this->BindReactor(reactor_);
  458. }
  459. void Finish(grpc::Status s) override {
  460. status_ = s;
  461. func_(std::move(s));
  462. status_set_.store(true, std::memory_order_release);
  463. }
  464. void SendInitialMetadata() override {}
  465. bool status_set() const {
  466. return status_set_.load(std::memory_order_acquire);
  467. }
  468. grpc::Status status() const { return status_; }
  469. private:
  470. void CallOnDone() override {}
  471. grpc::internal::ServerReactor* reactor() override { return reactor_; }
  472. grpc::ServerUnaryReactor* const reactor_;
  473. std::atomic_bool status_set_{false};
  474. grpc::Status status_;
  475. const std::function<void(grpc::Status s)> func_;
  476. };
  477. typename std::aligned_storage<sizeof(Reactor), alignof(Reactor)>::type
  478. default_reactor_;
  479. std::atomic_bool default_reactor_used_{false};
  480. std::atomic_bool marked_cancelled_{false};
  481. std::unique_ptr<TestServerCallbackUnary> test_unary_;
  482. };
  483. /// A ServerContext or CallbackServerContext allows the code implementing a
  484. /// service handler to:
  485. ///
  486. /// - Add custom initial and trailing metadata key-value pairs that will
  487. /// propagated to the client side.
  488. /// - Control call settings such as compression and authentication.
  489. /// - Access metadata coming from the client.
  490. /// - Get performance metrics (ie, census).
  491. ///
  492. /// Context settings are only relevant to the call handler they are supplied to,
  493. /// that is to say, they aren't sticky across multiple calls. Some of these
  494. /// settings, such as the compression options, can be made persistent at server
  495. /// construction time by specifying the appropriate \a ChannelArguments
  496. /// to a \a grpc::ServerBuilder, via \a ServerBuilder::AddChannelArgument.
  497. ///
  498. /// \warning ServerContext instances should \em not be reused across rpcs.
  499. class ServerContext : public ServerContextBase {
  500. public:
  501. ServerContext() {} // for async calls
  502. using ServerContextBase::AddInitialMetadata;
  503. using ServerContextBase::AddTrailingMetadata;
  504. using ServerContextBase::auth_context;
  505. using ServerContextBase::c_call;
  506. using ServerContextBase::census_context;
  507. using ServerContextBase::client_metadata;
  508. using ServerContextBase::compression_algorithm;
  509. using ServerContextBase::compression_level;
  510. using ServerContextBase::compression_level_set;
  511. using ServerContextBase::deadline;
  512. using ServerContextBase::IsCancelled;
  513. using ServerContextBase::peer;
  514. using ServerContextBase::raw_deadline;
  515. using ServerContextBase::set_compression_algorithm;
  516. using ServerContextBase::set_compression_level;
  517. using ServerContextBase::SetLoadReportingCosts;
  518. using ServerContextBase::TryCancel;
  519. // Sync/CQ-based Async ServerContext only
  520. using ServerContextBase::AsyncNotifyWhenDone;
  521. private:
  522. // Constructor for internal use by server only
  523. friend class grpc::Server;
  524. ServerContext(gpr_timespec deadline, grpc_metadata_array* arr)
  525. : ServerContextBase(deadline, arr) {}
  526. // CallbackServerContext only
  527. using ServerContextBase::DefaultReactor;
  528. using ServerContextBase::GetRpcAllocatorState;
  529. /// Prevent copying.
  530. ServerContext(const ServerContext&) = delete;
  531. ServerContext& operator=(const ServerContext&) = delete;
  532. };
  533. class CallbackServerContext : public ServerContextBase {
  534. public:
  535. /// Public constructors are for direct use only by mocking tests. In practice,
  536. /// these objects will be owned by the library.
  537. CallbackServerContext() {}
  538. using ServerContextBase::AddInitialMetadata;
  539. using ServerContextBase::AddTrailingMetadata;
  540. using ServerContextBase::auth_context;
  541. using ServerContextBase::c_call;
  542. using ServerContextBase::census_context;
  543. using ServerContextBase::client_metadata;
  544. using ServerContextBase::compression_algorithm;
  545. using ServerContextBase::compression_level;
  546. using ServerContextBase::compression_level_set;
  547. using ServerContextBase::context_allocator;
  548. using ServerContextBase::deadline;
  549. using ServerContextBase::IsCancelled;
  550. using ServerContextBase::peer;
  551. using ServerContextBase::raw_deadline;
  552. using ServerContextBase::set_compression_algorithm;
  553. using ServerContextBase::set_compression_level;
  554. using ServerContextBase::set_context_allocator;
  555. using ServerContextBase::SetLoadReportingCosts;
  556. using ServerContextBase::TryCancel;
  557. // CallbackServerContext only
  558. using ServerContextBase::DefaultReactor;
  559. using ServerContextBase::GetRpcAllocatorState;
  560. private:
  561. // Sync/CQ-based Async ServerContext only
  562. using ServerContextBase::AsyncNotifyWhenDone;
  563. /// Prevent copying.
  564. CallbackServerContext(const CallbackServerContext&) = delete;
  565. CallbackServerContext& operator=(const CallbackServerContext&) = delete;
  566. };
  567. /// A CallbackServerContext allows users to use the contents of the
  568. /// CallbackServerContext or GenericCallbackServerContext structure for the
  569. /// callback API.
  570. /// The library will invoke the allocator any time a new call is initiated.
  571. /// and call the Release method after the server OnDone.
  572. class ContextAllocator {
  573. public:
  574. virtual ~ContextAllocator() {}
  575. virtual CallbackServerContext* NewCallbackServerContext() { return nullptr; }
  576. virtual GenericCallbackServerContext* NewGenericCallbackServerContext() {
  577. return nullptr;
  578. }
  579. virtual void Release(CallbackServerContext*) {}
  580. virtual void Release(GenericCallbackServerContext*) {}
  581. };
  582. } // namespace grpc
  583. static_assert(
  584. std::is_base_of<grpc::ServerContextBase, grpc::ServerContext>::value,
  585. "improper base class");
  586. static_assert(std::is_base_of<grpc::ServerContextBase,
  587. grpc::CallbackServerContext>::value,
  588. "improper base class");
  589. static_assert(sizeof(grpc::ServerContextBase) == sizeof(grpc::ServerContext),
  590. "wrong size");
  591. static_assert(sizeof(grpc::ServerContextBase) ==
  592. sizeof(grpc::CallbackServerContext),
  593. "wrong size");
  594. #endif // GRPCPP_IMPL_CODEGEN_SERVER_CONTEXT_H