server_context.h 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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. #ifndef GRPCPP_SERVER_CONTEXT_H
  19. #define GRPCPP_SERVER_CONTEXT_H
  20. #include <grpc/support/port_platform.h>
  21. #include <atomic>
  22. #include <cassert>
  23. #include <map>
  24. #include <memory>
  25. #include <type_traits>
  26. #include <vector>
  27. #include <grpc/grpc.h>
  28. #include <grpc/impl/compression_types.h>
  29. #include <grpcpp/impl/call.h>
  30. #include <grpcpp/impl/call_op_set.h>
  31. #include <grpcpp/impl/codegen/create_auth_context.h>
  32. #include <grpcpp/impl/codegen/metadata_map.h>
  33. #include <grpcpp/impl/completion_queue_tag.h>
  34. #include <grpcpp/impl/metadata_map.h>
  35. #include <grpcpp/impl/rpc_service_method.h>
  36. #include <grpcpp/security/auth_context.h>
  37. #include <grpcpp/support/callback_common.h>
  38. #include <grpcpp/support/config.h>
  39. #include <grpcpp/support/message_allocator.h>
  40. #include <grpcpp/support/server_callback.h>
  41. #include <grpcpp/support/server_interceptor.h>
  42. #include <grpcpp/support/status.h>
  43. #include <grpcpp/support/string_ref.h>
  44. #include <grpcpp/support/time.h>
  45. struct grpc_metadata;
  46. struct grpc_call;
  47. struct census_context;
  48. namespace grpc {
  49. template <class W, class R>
  50. class ServerAsyncReader;
  51. template <class W>
  52. class ServerAsyncWriter;
  53. template <class W>
  54. class ServerAsyncResponseWriter;
  55. template <class W, class R>
  56. class ServerAsyncReaderWriter;
  57. template <class R>
  58. class ServerReader;
  59. template <class W>
  60. class ServerWriter;
  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 CallMetricRecorder;
  109. class ServerMetricRecorder;
  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 TString& key, const TString& 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 TString& key, const TString& 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<TString>& 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. TString 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. /// Prevent copying.
  371. ServerContextBase(const ServerContextBase&);
  372. ServerContextBase& operator=(const ServerContextBase&);
  373. class CompletionOp;
  374. void BeginCompletionOp(
  375. grpc::internal::Call* call, std::function<void(bool)> callback,
  376. grpc::internal::ServerCallbackCall* callback_controller);
  377. /// Return the tag queued by BeginCompletionOp()
  378. grpc::internal::CompletionQueueTag* GetCompletionOpTag();
  379. void set_call(grpc_call* call, bool call_metric_recording_enabled,
  380. experimental::ServerMetricRecorder* server_metric_recorder) {
  381. call_.call = call;
  382. if (call_metric_recording_enabled) {
  383. CreateCallMetricRecorder(server_metric_recorder);
  384. }
  385. }
  386. void BindDeadlineAndMetadata(gpr_timespec deadline, grpc_metadata_array* arr);
  387. uint32_t initial_metadata_flags() const { return 0; }
  388. grpc::experimental::ServerRpcInfo* set_server_rpc_info(
  389. const char* method, grpc::internal::RpcMethod::RpcType type,
  390. const std::vector<std::unique_ptr<
  391. grpc::experimental::ServerInterceptorFactoryInterface>>& creators) {
  392. if (!creators.empty()) {
  393. rpc_info_ = new grpc::experimental::ServerRpcInfo(this, method, type);
  394. rpc_info_->RegisterInterceptors(creators);
  395. }
  396. return rpc_info_;
  397. }
  398. void set_message_allocator_state(RpcAllocatorState* allocator_state) {
  399. message_allocator_state_ = allocator_state;
  400. }
  401. void MaybeMarkCancelledOnRead() {
  402. if (grpc_call_failed_before_recv_message(call_.call)) {
  403. marked_cancelled_.store(true, std::memory_order_release);
  404. }
  405. }
  406. // This should be called only once and only when call metric recording is
  407. // enabled.
  408. void CreateCallMetricRecorder(
  409. experimental::ServerMetricRecorder* server_metric_recorder = nullptr);
  410. struct CallWrapper {
  411. ~CallWrapper();
  412. grpc_call* call = nullptr;
  413. };
  414. // NOTE: call_ must be the first data member of this object so that its
  415. // destructor is the last to be called, since its destructor may unref
  416. // the underlying core call which holds the arena that may be used to
  417. // hold this object.
  418. CallWrapper call_;
  419. CompletionOp* completion_op_ = nullptr;
  420. bool has_notify_when_done_tag_ = false;
  421. void* async_notify_when_done_tag_ = nullptr;
  422. grpc::internal::CallbackWithSuccessTag completion_tag_;
  423. gpr_timespec deadline_;
  424. grpc::CompletionQueue* cq_ = nullptr;
  425. bool sent_initial_metadata_ = false;
  426. mutable std::shared_ptr<const grpc::AuthContext> auth_context_;
  427. mutable grpc::internal::MetadataMap client_metadata_;
  428. std::multimap<TString, TString> initial_metadata_;
  429. std::multimap<TString, TString> trailing_metadata_;
  430. bool compression_level_set_ = false;
  431. grpc_compression_level compression_level_;
  432. grpc_compression_algorithm compression_algorithm_;
  433. grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
  434. grpc::internal::CallOpSendMessage>
  435. pending_ops_;
  436. bool has_pending_ops_ = false;
  437. grpc::experimental::ServerRpcInfo* rpc_info_ = nullptr;
  438. RpcAllocatorState* message_allocator_state_ = nullptr;
  439. ContextAllocator* context_allocator_ = nullptr;
  440. experimental::CallMetricRecorder* call_metric_recorder_ = nullptr;
  441. class Reactor : public grpc::ServerUnaryReactor {
  442. public:
  443. void OnCancel() override {}
  444. void OnDone() override {}
  445. // Override InternalInlineable for this class since its reactions are
  446. // trivial and thus do not need to be run from the executor (triggering a
  447. // thread hop). This should only be used by internal reactors (thus the
  448. // name) and not by user application code.
  449. bool InternalInlineable() override { return true; }
  450. };
  451. void SetupTestDefaultReactor(std::function<void(grpc::Status)> func) {
  452. // NOLINTNEXTLINE(modernize-make-unique)
  453. test_unary_.reset(new TestServerCallbackUnary(this, std::move(func)));
  454. }
  455. bool test_status_set() const {
  456. return (test_unary_ != nullptr) && test_unary_->status_set();
  457. }
  458. grpc::Status test_status() const { return test_unary_->status(); }
  459. class TestServerCallbackUnary : public grpc::ServerCallbackUnary {
  460. public:
  461. TestServerCallbackUnary(ServerContextBase* ctx,
  462. std::function<void(grpc::Status)> func)
  463. : reactor_(ctx->DefaultReactor()), func_(std::move(func)) {
  464. this->BindReactor(reactor_);
  465. }
  466. void Finish(grpc::Status s) override {
  467. status_ = s;
  468. func_(std::move(s));
  469. status_set_.store(true, std::memory_order_release);
  470. }
  471. void SendInitialMetadata() override {}
  472. bool status_set() const {
  473. return status_set_.load(std::memory_order_acquire);
  474. }
  475. grpc::Status status() const { return status_; }
  476. private:
  477. void CallOnDone() override {}
  478. grpc::internal::ServerReactor* reactor() override { return reactor_; }
  479. grpc::ServerUnaryReactor* const reactor_;
  480. std::atomic_bool status_set_{false};
  481. grpc::Status status_;
  482. const std::function<void(grpc::Status s)> func_;
  483. };
  484. typename std::aligned_storage<sizeof(Reactor), alignof(Reactor)>::type
  485. default_reactor_;
  486. std::atomic_bool default_reactor_used_{false};
  487. std::atomic_bool marked_cancelled_{false};
  488. std::unique_ptr<TestServerCallbackUnary> test_unary_;
  489. };
  490. /// A ServerContext or CallbackServerContext allows the code implementing a
  491. /// service handler to:
  492. ///
  493. /// - Add custom initial and trailing metadata key-value pairs that will
  494. /// propagated to the client side.
  495. /// - Control call settings such as compression and authentication.
  496. /// - Access metadata coming from the client.
  497. /// - Get performance metrics (ie, census).
  498. ///
  499. /// Context settings are only relevant to the call handler they are supplied to,
  500. /// that is to say, they aren't sticky across multiple calls. Some of these
  501. /// settings, such as the compression options, can be made persistent at server
  502. /// construction time by specifying the appropriate \a ChannelArguments
  503. /// to a \a grpc::ServerBuilder, via \a ServerBuilder::AddChannelArgument.
  504. ///
  505. /// \warning ServerContext instances should \em not be reused across rpcs.
  506. class ServerContext : public ServerContextBase {
  507. public:
  508. ServerContext() {} // for async calls
  509. using ServerContextBase::AddInitialMetadata;
  510. using ServerContextBase::AddTrailingMetadata;
  511. using ServerContextBase::auth_context;
  512. using ServerContextBase::c_call;
  513. using ServerContextBase::census_context;
  514. using ServerContextBase::client_metadata;
  515. using ServerContextBase::compression_algorithm;
  516. using ServerContextBase::compression_level;
  517. using ServerContextBase::compression_level_set;
  518. using ServerContextBase::deadline;
  519. using ServerContextBase::IsCancelled;
  520. using ServerContextBase::peer;
  521. using ServerContextBase::raw_deadline;
  522. using ServerContextBase::set_compression_algorithm;
  523. using ServerContextBase::set_compression_level;
  524. using ServerContextBase::SetLoadReportingCosts;
  525. using ServerContextBase::TryCancel;
  526. // Sync/CQ-based Async ServerContext only
  527. using ServerContextBase::AsyncNotifyWhenDone;
  528. private:
  529. // Constructor for internal use by server only
  530. friend class grpc::Server;
  531. ServerContext(gpr_timespec deadline, grpc_metadata_array* arr)
  532. : ServerContextBase(deadline, arr) {}
  533. // CallbackServerContext only
  534. using ServerContextBase::DefaultReactor;
  535. using ServerContextBase::GetRpcAllocatorState;
  536. /// Prevent copying.
  537. ServerContext(const ServerContext&) = delete;
  538. ServerContext& operator=(const ServerContext&) = delete;
  539. };
  540. class CallbackServerContext : public ServerContextBase {
  541. public:
  542. /// Public constructors are for direct use only by mocking tests. In practice,
  543. /// these objects will be owned by the library.
  544. CallbackServerContext() {}
  545. using ServerContextBase::AddInitialMetadata;
  546. using ServerContextBase::AddTrailingMetadata;
  547. using ServerContextBase::auth_context;
  548. using ServerContextBase::c_call;
  549. using ServerContextBase::census_context;
  550. using ServerContextBase::client_metadata;
  551. using ServerContextBase::compression_algorithm;
  552. using ServerContextBase::compression_level;
  553. using ServerContextBase::compression_level_set;
  554. using ServerContextBase::context_allocator;
  555. using ServerContextBase::deadline;
  556. using ServerContextBase::IsCancelled;
  557. using ServerContextBase::peer;
  558. using ServerContextBase::raw_deadline;
  559. using ServerContextBase::set_compression_algorithm;
  560. using ServerContextBase::set_compression_level;
  561. using ServerContextBase::set_context_allocator;
  562. using ServerContextBase::SetLoadReportingCosts;
  563. using ServerContextBase::TryCancel;
  564. // CallbackServerContext only
  565. using ServerContextBase::DefaultReactor;
  566. using ServerContextBase::GetRpcAllocatorState;
  567. private:
  568. // Sync/CQ-based Async ServerContext only
  569. using ServerContextBase::AsyncNotifyWhenDone;
  570. /// Prevent copying.
  571. CallbackServerContext(const CallbackServerContext&) = delete;
  572. CallbackServerContext& operator=(const CallbackServerContext&) = delete;
  573. };
  574. /// A CallbackServerContext allows users to use the contents of the
  575. /// CallbackServerContext or GenericCallbackServerContext structure for the
  576. /// callback API.
  577. /// The library will invoke the allocator any time a new call is initiated.
  578. /// and call the Release method after the server OnDone.
  579. class ContextAllocator {
  580. public:
  581. virtual ~ContextAllocator() {}
  582. virtual CallbackServerContext* NewCallbackServerContext() { return nullptr; }
  583. virtual GenericCallbackServerContext* NewGenericCallbackServerContext() {
  584. return nullptr;
  585. }
  586. virtual void Release(CallbackServerContext*) {}
  587. virtual void Release(GenericCallbackServerContext*) {}
  588. };
  589. } // namespace grpc
  590. static_assert(
  591. std::is_base_of<grpc::ServerContextBase, grpc::ServerContext>::value,
  592. "improper base class");
  593. static_assert(std::is_base_of<grpc::ServerContextBase,
  594. grpc::CallbackServerContext>::value,
  595. "improper base class");
  596. static_assert(sizeof(grpc::ServerContextBase) == sizeof(grpc::ServerContext),
  597. "wrong size");
  598. static_assert(sizeof(grpc::ServerContextBase) ==
  599. sizeof(grpc::CallbackServerContext),
  600. "wrong size");
  601. #endif // GRPCPP_SERVER_CONTEXT_H