GRPC C++  1.36.1
server_context.h
Go to the documentation of this file.
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 
19 #ifndef GRPCPP_IMPL_CODEGEN_SERVER_CONTEXT_H
20 #define GRPCPP_IMPL_CODEGEN_SERVER_CONTEXT_H
21 
22 #include <atomic>
23 #include <cassert>
24 #include <map>
25 #include <memory>
26 #include <type_traits>
27 #include <vector>
28 
30 
47 
48 struct grpc_metadata;
49 struct grpc_call;
50 struct census_context;
51 
52 namespace grpc {
53 template <class W, class R>
54 class ServerAsyncReader;
55 template <class W>
56 class ServerAsyncWriter;
57 template <class W>
58 class ServerAsyncResponseWriter;
59 template <class W, class R>
60 class ServerAsyncReaderWriter;
61 template <class R>
62 class ServerReader;
63 template <class W>
64 class ServerWriter;
65 
66 namespace internal {
67 template <class ServiceType, class RequestType, class ResponseType>
68 class BidiStreamingHandler;
69 template <class RequestType, class ResponseType>
70 class CallbackUnaryHandler;
71 template <class RequestType, class ResponseType>
72 class CallbackClientStreamingHandler;
73 template <class RequestType, class ResponseType>
74 class CallbackServerStreamingHandler;
75 template <class RequestType, class ResponseType>
76 class CallbackBidiHandler;
77 template <class ServiceType, class RequestType, class ResponseType>
78 class ClientStreamingHandler;
79 template <class ResponseType>
80 void UnaryRunHandlerHelper(const MethodHandler::HandlerParameter&,
81  ResponseType*, Status&);
82 template <class ServiceType, class RequestType, class ResponseType,
83  class BaseRequestType, class BaseResponseType>
84 class RpcMethodHandler;
85 template <class Base>
86 class FinishOnlyReactor;
87 template <class W, class R>
88 class ServerReaderWriterBody;
89 template <class ServiceType, class RequestType, class ResponseType>
90 class ServerStreamingHandler;
91 class ServerReactor;
92 template <class Streamer, bool WriteNeeded>
93 class TemplatedBidiStreamingHandler;
94 template <::grpc::StatusCode code>
95 class ErrorMethodHandler;
96 } // namespace internal
97 
98 class ClientContext;
99 class CompletionQueue;
100 class GenericServerContext;
101 class Server;
102 class ServerInterface;
103 class ContextAllocator;
104 
105 // TODO(vjpai): Remove namespace experimental when de-experimentalized fully.
106 namespace experimental {
107 
110 
111 } // namespace experimental
112 
113 #ifndef GRPC_CALLBACK_API_NONEXPERIMENTAL
114 namespace experimental {
115 #endif
116 class GenericCallbackServerContext;
117 #ifndef GRPC_CALLBACK_API_NONEXPERIMENTAL
118 } // namespace experimental
119 #endif
120 namespace internal {
121 class Call;
122 } // namespace internal
123 
124 namespace testing {
125 class InteropServerContextInspector;
126 class ServerContextTestSpouse;
127 class DefaultReactorTestPeer;
128 } // namespace testing
129 
132  public:
133  virtual ~ServerContextBase();
134 
136  std::chrono::system_clock::time_point deadline() const {
138  }
139 
141  gpr_timespec raw_deadline() const { return deadline_; }
142 
162  void AddInitialMetadata(const std::string& key, const std::string& value);
163 
183  void AddTrailingMetadata(const std::string& key, const std::string& value);
184 
196  bool IsCancelled() const;
197 
216  void TryCancel() const;
217 
227  const std::multimap<grpc::string_ref, grpc::string_ref>& client_metadata()
228  const {
229  return *client_metadata_.map();
230  }
231 
234  return compression_level_;
235  }
236 
241  compression_level_set_ = true;
242  compression_level_ = level;
243  }
244 
248  bool compression_level_set() const { return compression_level_set_; }
249 
255  return compression_algorithm_;
256  }
261 
263  void SetLoadReportingCosts(const std::vector<std::string>& cost_data);
264 
268  std::shared_ptr<const ::grpc::AuthContext> auth_context() const {
269  if (auth_context_ == nullptr) {
270  auth_context_ = ::grpc::CreateAuthContext(call_.call);
271  }
272  return auth_context_;
273  }
274 
279  std::string peer() const;
280 
282  const struct census_context* census_context() const;
283 
286  grpc_call* c_call() { return call_.call; }
287 
288  protected:
294  void AsyncNotifyWhenDone(void* tag) {
295  has_notify_when_done_tag_ = true;
296  async_notify_when_done_tag_ = tag;
297  }
298 
304  return message_allocator_state_;
305  }
306 
324  // Short-circuit the case where a default reactor was already set up by
325  // the TestPeer.
326  if (test_unary_ != nullptr) {
327  return reinterpret_cast<Reactor*>(&default_reactor_);
328  }
329  new (&default_reactor_) Reactor;
330 #ifndef NDEBUG
331  bool old = false;
332  assert(default_reactor_used_.compare_exchange_strong(
333  old, true, std::memory_order_relaxed));
334 #else
335  default_reactor_used_.store(true, std::memory_order_relaxed);
336 #endif
337  return reinterpret_cast<Reactor*>(&default_reactor_);
338  }
339 
343 
345  context_allocator_ = context_allocator;
346  }
347 
348  ContextAllocator* context_allocator() const { return context_allocator_; }
349 
350  private:
351  friend class ::grpc::testing::InteropServerContextInspector;
352  friend class ::grpc::testing::ServerContextTestSpouse;
353  friend class ::grpc::testing::DefaultReactorTestPeer;
354  friend class ::grpc::ServerInterface;
355  friend class ::grpc::Server;
356  template <class W, class R>
357  friend class ::grpc::ServerAsyncReader;
358  template <class W>
359  friend class ::grpc::ServerAsyncWriter;
360  template <class W>
361  friend class ::grpc::ServerAsyncResponseWriter;
362  template <class W, class R>
363  friend class ::grpc::ServerAsyncReaderWriter;
364  template <class R>
365  friend class ::grpc::ServerReader;
366  template <class W>
367  friend class ::grpc::ServerWriter;
368  template <class W, class R>
369  friend class ::grpc::internal::ServerReaderWriterBody;
370  template <class ResponseType>
372  const internal::MethodHandler::HandlerParameter& param, ResponseType* rsp,
373  Status& status);
374  template <class ServiceType, class RequestType, class ResponseType,
375  class BaseRequestType, class BaseResponseType>
376  friend class ::grpc::internal::RpcMethodHandler;
377  template <class ServiceType, class RequestType, class ResponseType>
378  friend class ::grpc::internal::ClientStreamingHandler;
379  template <class ServiceType, class RequestType, class ResponseType>
380  friend class ::grpc::internal::ServerStreamingHandler;
381  template <class Streamer, bool WriteNeeded>
382  friend class ::grpc::internal::TemplatedBidiStreamingHandler;
383  template <class RequestType, class ResponseType>
384  friend class ::grpc::internal::CallbackUnaryHandler;
385  template <class RequestType, class ResponseType>
386  friend class ::grpc::internal::CallbackClientStreamingHandler;
387  template <class RequestType, class ResponseType>
388  friend class ::grpc::internal::CallbackServerStreamingHandler;
389  template <class RequestType, class ResponseType>
390  friend class ::grpc::internal::CallbackBidiHandler;
391  template <::grpc::StatusCode code>
392  friend class ::grpc::internal::ErrorMethodHandler;
393  template <class Base>
394  friend class ::grpc::internal::FinishOnlyReactor;
395  friend class ::grpc::ClientContext;
396  friend class ::grpc::GenericServerContext;
397 #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
398  friend class ::grpc::GenericCallbackServerContext;
399 #else
400  friend class ::grpc::experimental::GenericCallbackServerContext;
401 #endif
402 
405  ServerContextBase& operator=(const ServerContextBase&);
406 
407  class CompletionOp;
408 
409  void BeginCompletionOp(
410  ::grpc::internal::Call* call, std::function<void(bool)> callback,
411  ::grpc::internal::ServerCallbackCall* callback_controller);
413  ::grpc::internal::CompletionQueueTag* GetCompletionOpTag();
414 
415  void set_call(grpc_call* call) { call_.call = call; }
416 
417  void BindDeadlineAndMetadata(gpr_timespec deadline, grpc_metadata_array* arr);
418 
419  uint32_t initial_metadata_flags() const { return 0; }
420 
421  ::grpc::experimental::ServerRpcInfo* set_server_rpc_info(
422  const char* method, ::grpc::internal::RpcMethod::RpcType type,
423  const std::vector<std::unique_ptr<
425  if (!creators.empty()) {
426  rpc_info_ = new ::grpc::experimental::ServerRpcInfo(this, method, type);
427  rpc_info_->RegisterInterceptors(creators);
428  }
429  return rpc_info_;
430  }
431 
432  void set_message_allocator_state(
433  ::grpc::experimental::RpcAllocatorState* allocator_state) {
434  message_allocator_state_ = allocator_state;
435  }
436 
437  struct CallWrapper {
438  ~CallWrapper();
439 
440  grpc_call* call = nullptr;
441  };
442 
443  // NOTE: call_ must be the first data member of this object so that its
444  // destructor is the last to be called, since its destructor may unref
445  // the underlying core call which holds the arena that may be used to
446  // hold this object.
447  CallWrapper call_;
448 
449  CompletionOp* completion_op_ = nullptr;
450  bool has_notify_when_done_tag_ = false;
451  void* async_notify_when_done_tag_ = nullptr;
453 
454  gpr_timespec deadline_;
455  ::grpc::CompletionQueue* cq_ = nullptr;
456  bool sent_initial_metadata_ = false;
457  mutable std::shared_ptr<const ::grpc::AuthContext> auth_context_;
458  mutable ::grpc::internal::MetadataMap client_metadata_;
459  std::multimap<std::string, std::string> initial_metadata_;
460  std::multimap<std::string, std::string> trailing_metadata_;
461 
462  bool compression_level_set_ = false;
463  grpc_compression_level compression_level_;
464  grpc_compression_algorithm compression_algorithm_;
465 
468  pending_ops_;
469  bool has_pending_ops_ = false;
470 
471  ::grpc::experimental::ServerRpcInfo* rpc_info_ = nullptr;
472  ::grpc::experimental::RpcAllocatorState* message_allocator_state_ = nullptr;
473  ContextAllocator* context_allocator_ = nullptr;
474 
475  class Reactor : public ::grpc::ServerUnaryReactor {
476  public:
477  void OnCancel() override {}
478  void OnDone() override {}
479  // Override InternalInlineable for this class since its reactions are
480  // trivial and thus do not need to be run from the executor (triggering a
481  // thread hop). This should only be used by internal reactors (thus the
482  // name) and not by user application code.
483  bool InternalInlineable() override { return true; }
484  };
485 
486  void SetupTestDefaultReactor(std::function<void(::grpc::Status)> func) {
487  // NOLINTNEXTLINE(modernize-make-unique)
488  test_unary_.reset(new TestServerCallbackUnary(this, std::move(func)));
489  }
490  bool test_status_set() const {
491  return (test_unary_ != nullptr) && test_unary_->status_set();
492  }
493  ::grpc::Status test_status() const { return test_unary_->status(); }
494 
495  class TestServerCallbackUnary : public ::grpc::ServerCallbackUnary {
496  public:
497  TestServerCallbackUnary(ServerContextBase* ctx,
498  std::function<void(::grpc::Status)> func)
499  : reactor_(ctx->DefaultReactor()), func_(std::move(func)) {
500  this->BindReactor(reactor_);
501  }
502  void Finish(::grpc::Status s) override {
503  status_ = s;
504  func_(std::move(s));
505  status_set_.store(true, std::memory_order_release);
506  }
507  void SendInitialMetadata() override {}
508 
509  bool status_set() const {
510  return status_set_.load(std::memory_order_acquire);
511  }
512  ::grpc::Status status() const { return status_; }
513 
514  private:
515  void CallOnDone() override {}
516  ::grpc::internal::ServerReactor* reactor() override { return reactor_; }
517 
518  ::grpc::ServerUnaryReactor* const reactor_;
519  std::atomic_bool status_set_{false};
520  ::grpc::Status status_;
521  const std::function<void(::grpc::Status s)> func_;
522  };
523 
524  typename std::aligned_storage<sizeof(Reactor), alignof(Reactor)>::type
525  default_reactor_;
526  std::atomic_bool default_reactor_used_{false};
527  std::unique_ptr<TestServerCallbackUnary> test_unary_;
528 };
529 
547  public:
548  ServerContext() {} // for async calls
549 
567 
568  // Sync/CQ-based Async ServerContext only
570 
571  private:
572  // Constructor for internal use by server only
573  friend class ::grpc::Server;
575  : ServerContextBase(deadline, arr) {}
576 
577  // CallbackServerContext only
580 
582  ServerContext(const ServerContext&) = delete;
583  ServerContext& operator=(const ServerContext&) = delete;
584 };
585 
587  public:
591 
611 
612  // CallbackServerContext only
615 
616  private:
617  // Sync/CQ-based Async ServerContext only
619 
622  CallbackServerContext& operator=(const CallbackServerContext&) = delete;
623 };
624 
631  public:
632  virtual ~ContextAllocator() {}
633 
634  virtual CallbackServerContext* NewCallbackServerContext() { return nullptr; }
635 
636 #ifndef GRPC_CALLBACK_API_NONEXPERIMENTAL
639  return nullptr;
640  }
641 #else
642  virtual GenericCallbackServerContext* NewGenericCallbackServerContext() {
643  return nullptr;
644  }
645 #endif
646 
647  virtual void Release(CallbackServerContext*) {}
648 
649 #ifndef GRPC_CALLBACK_API_NONEXPERIMENTAL
651 #else
652  virtual void Release(GenericCallbackServerContext*) {}
653 #endif
654 };
655 
656 } // namespace grpc
657 
658 static_assert(
659  std::is_base_of<::grpc::ServerContextBase, ::grpc::ServerContext>::value,
660  "improper base class");
661 static_assert(std::is_base_of<::grpc::ServerContextBase,
662  ::grpc::CallbackServerContext>::value,
663  "improper base class");
664 static_assert(sizeof(::grpc::ServerContextBase) ==
665  sizeof(::grpc::ServerContext),
666  "wrong size");
667 static_assert(sizeof(::grpc::ServerContextBase) ==
668  sizeof(::grpc::CallbackServerContext),
669  "wrong size");
670 
671 #endif // GRPCPP_IMPL_CODEGEN_SERVER_CONTEXT_H
grpc::internal::CallbackWithSuccessTag
CallbackWithSuccessTag can be reused multiple times, and will be used in this fashion for streaming o...
Definition: callback_common.h:137
census_context
struct census_context census_context
A Census Context is a handle used by Census to represent the current tracing and stats collection inf...
Definition: census.h:34
grpc::ServerContextBase::set_compression_algorithm
void set_compression_algorithm(grpc_compression_algorithm algorithm)
Set algorithm to be the compression algorithm used for the server call.
grpc::ServerContextBase::SetLoadReportingCosts
void SetLoadReportingCosts(const std::vector< std::string > &cost_data)
Set the serialized load reporting costs in cost_data for the call.
grpc::ServerContext
A ServerContext or CallbackServerContext allows the code implementing a service handler to:
Definition: server_context.h:546
time.h
rpc_service_method.h
grpc::ServerContextBase::census_context
const struct census_context * census_context() const
Get the census context associated with this server call.
grpc
An Alarm posts the user-provided tag to its associated completion queue or invokes the user-provided ...
Definition: alarm.h:33
grpc::internal::CallOpSet
Primary implementation of CallOpSetInterface.
Definition: call_op_set.h:852
grpc::ServerContextBase::IsCancelled
bool IsCancelled() const
Return whether this RPC failed before the server could provide its status back to the client.
status.h
grpc::CallbackServerContext
Definition: server_context.h:586
grpc::ServerContextBase::set_context_allocator
void set_context_allocator(ContextAllocator *context_allocator)
Definition: server_context.h:344
grpc::internal::CallOpSendMessage
Definition: call_op_set.h:282
grpc::internal::MethodHandler::HandlerParameter
Definition: rpc_service_method.h:41
grpc_metadata_array
Definition: grpc_types.h:548
config.h
grpc_compression_algorithm
grpc_compression_algorithm
The various compression algorithms supported by gRPC (not sorted by compression level)
Definition: compression_types.h:57
grpc::internal::Call
Straightforward wrapping of the C call object.
Definition: call.h:35
auth_context.h
grpc::ServerContextBase
Base class of ServerContext. Experimental until callback API is final.
Definition: server_context.h:131
server_interceptor.h
grpc::ServerContextBase::context_allocator
ContextAllocator * context_allocator() const
Definition: server_context.h:348
grpc::ServerCallbackUnary::BindReactor
void BindReactor(Reactor *reactor)
Definition: server_callback.h:201
server_callback.h
grpc::internal::CallOpSendInitialMetadata
Definition: call_op_set.h:212
grpc::ServerContextBase::ServerContextBase
ServerContextBase()
Constructors for use by derived classes.
grpc::experimental::ServerContextBase
::grpc::ServerContextBase ServerContextBase
Definition: server_context.h:108
grpc::experimental::RpcAllocatorState
Definition: message_allocator.h:29
metadata_map.h
grpc::internal::MetadataMap::map
std::multimap< grpc::string_ref, grpc::string_ref > * map()
Definition: metadata_map.h:66
grpc::experimental::CallbackServerContext
::grpc::CallbackServerContext CallbackServerContext
Definition: server_context.h:109
grpc::Status
Did it work? If it didn't, why?
Definition: status.h:31
grpc_metadata
A single metadata element.
Definition: grpc_types.h:504
grpc::ContextAllocator::Release
virtual void Release(CallbackServerContext *)
Definition: server_context.h:647
grpc::experimental::GenericCallbackServerContext
Definition: async_generic_service.h:91
grpc::internal::ServerCallbackCall
The base class of ServerCallbackUnary etc.
Definition: server_callback.h:72
grpc::CreateAuthContext
std::shared_ptr< const AuthContext > CreateAuthContext(grpc_call *call)
grpc::ServerContextBase::deadline
std::chrono::system_clock::time_point deadline() const
Return the deadline for the server call.
Definition: server_context.h:136
grpc::ServerContextBase::raw_deadline
gpr_timespec raw_deadline() const
Return a gpr_timespec representation of the server call's deadline.
Definition: server_context.h:141
grpc::ServerContextBase::auth_context
std::shared_ptr< const ::grpc::AuthContext > auth_context() const
Return the authentication context for this server call.
Definition: server_context.h:268
grpc::ServerContextBase::AddInitialMetadata
void AddInitialMetadata(const std::string &key, const std::string &value)
Add the (key, value) pair to the initial metadata associated with a server call.
grpc_call
struct grpc_call grpc_call
A Call represents an RPC.
Definition: grpc_types.h:70
completion_queue_tag.h
grpc::ServerContextBase::compression_level_set
bool compression_level_set() const
Return a bool indicating whether the compression level for this call has been set (either implicitly ...
Definition: server_context.h:248
grpc::ServerContextBase::DefaultReactor
::grpc::ServerUnaryReactor * DefaultReactor()
Get a library-owned default unary reactor for use in minimal reaction cases.
Definition: server_context.h:323
grpc::ContextAllocator::NewCallbackServerContext
virtual CallbackServerContext * NewCallbackServerContext()
Definition: server_context.h:634
grpc::internal::RpcMethod::RpcType
RpcType
Definition: rpc_method.h:31
grpc::CallbackServerContext::CallbackServerContext
CallbackServerContext()
Public constructors are for direct use only by mocking tests.
Definition: server_context.h:590
grpc::ServerContextBase::AddTrailingMetadata
void AddTrailingMetadata(const std::string &key, const std::string &value)
Add the (key, value) pair to the initial metadata associated with a server call.
grpc::experimental::ServerRpcInfo
ServerRpcInfo represents the state of a particular RPC as it appears to an interceptor.
Definition: server_interceptor.h:56
grpc::protobuf::util::Status
::google::protobuf::util::Status Status
Definition: config_protobuf.h:91
grpc::internal::CompletionQueueTag
An interface allowing implementors to process and filter event tags.
Definition: completion_queue_tag.h:26
compression_types.h
grpc::ServerContextBase::client_metadata
const std::multimap< grpc::string_ref, grpc::string_ref > & client_metadata() const
Return a collection of initial metadata key-value pairs sent from the client.
Definition: server_context.h:227
grpc::ContextAllocator::Release
virtual void Release(experimental::GenericCallbackServerContext *)
Definition: server_context.h:650
string_ref.h
grpc::experimental::ServerInterceptorFactoryInterface
Definition: server_interceptor.h:43
grpc::ServerContextBase::~ServerContextBase
virtual ~ServerContextBase()
callback_common.h
grpc::ContextAllocator
A CallbackServerContext allows users to use the contents of the CallbackServerContext or GenericCallb...
Definition: server_context.h:630
grpc::ServerContextBase::AsyncNotifyWhenDone
void AsyncNotifyWhenDone(void *tag)
Async only.
Definition: server_context.h:294
port_platform.h
call.h
grpc_compression_level
grpc_compression_level
Compression levels allow a party with knowledge of its peer's accepted encodings to request compressi...
Definition: compression_types.h:71
call_op_set.h
std
Definition: async_unary_call.h:398
create_auth_context.h
grpc::ServerContextBase::peer
std::string peer() const
Return the peer uri in a string.
grpc::internal::UnaryRunHandlerHelper
void UnaryRunHandlerHelper(const MethodHandler::HandlerParameter &, ResponseType *, Status &)
grpc::internal::ServerReactor
Definition: server_callback.h:48
grpc::CompletionQueue
A thin wrapper around grpc_completion_queue (see src/core/lib/surface/completion_queue....
Definition: completion_queue.h:102
grpc::ServerContextBase::TryCancel
void TryCancel() const
Cancel the Call from the server.
grpc::ContextAllocator::~ContextAllocator
virtual ~ContextAllocator()
Definition: server_context.h:632
grpc::ServerContextBase::GetRpcAllocatorState
::grpc::experimental::RpcAllocatorState * GetRpcAllocatorState()
NOTE: This is an API for advanced users who need custom allocators.
Definition: server_context.h:303
grpc::internal::UnaryRunHandlerHelper
void UnaryRunHandlerHelper(const ::grpc::internal::MethodHandler::HandlerParameter &, ResponseType *, ::grpc::Status &)
grpc::ContextAllocator::NewGenericCallbackServerContext
virtual experimental::GenericCallbackServerContext * NewGenericCallbackServerContext()
Definition: server_context.h:638
grpc::ServerContext::ServerContext
ServerContext()
Definition: server_context.h:548
gpr_timespec
Analogous to struct timespec.
Definition: gpr_types.h:47
grpc::ServerCallbackUnary
Definition: server_callback.h:191
grpc::ServerUnaryReactor
Definition: server_callback.h:688
message_allocator.h
grpc::ServerContextBase::compression_algorithm
grpc_compression_algorithm compression_algorithm() const
Return the compression algorithm the server call will request be used.
Definition: server_context.h:254
grpc::ServerContextBase::c_call
grpc_call * c_call()
Should be used for framework-level extensions only.
Definition: server_context.h:286
grpc::Timespec2Timepoint
std::chrono::system_clock::time_point Timespec2Timepoint(gpr_timespec t)
grpc::ServerContextBase::set_compression_level
void set_compression_level(grpc_compression_level level)
Set level to be the compression level used for the server call.
Definition: server_context.h:240
grpc::ServerContextBase::compression_level
grpc_compression_level compression_level() const
Return the compression algorithm to be used by the server call.
Definition: server_context.h:233