server_context.h 25 KB

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