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 30 kB

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