GRPC C++  1.35.0
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 
104 // TODO(vjpai): Remove namespace experimental when de-experimentalized fully.
105 namespace experimental {
106 
109 
110 } // namespace experimental
111 
112 #ifndef GRPC_CALLBACK_API_NONEXPERIMENTAL
113 namespace experimental {
114 #endif
115 class GenericCallbackServerContext;
116 #ifndef GRPC_CALLBACK_API_NONEXPERIMENTAL
117 } // namespace experimental
118 #endif
119 namespace internal {
120 class Call;
121 } // namespace internal
122 
123 namespace testing {
124 class InteropServerContextInspector;
125 class ServerContextTestSpouse;
126 class DefaultReactorTestPeer;
127 } // namespace testing
128 
131  public:
132  virtual ~ServerContextBase();
133 
135  std::chrono::system_clock::time_point deadline() const {
137  }
138 
140  gpr_timespec raw_deadline() const { return deadline_; }
141 
161  void AddInitialMetadata(const std::string& key, const std::string& value);
162 
182  void AddTrailingMetadata(const std::string& key, const std::string& value);
183 
195  bool IsCancelled() const;
196 
215  void TryCancel() const;
216 
226  const std::multimap<grpc::string_ref, grpc::string_ref>& client_metadata()
227  const {
228  return *client_metadata_.map();
229  }
230 
233  return compression_level_;
234  }
235 
240  compression_level_set_ = true;
241  compression_level_ = level;
242  }
243 
247  bool compression_level_set() const { return compression_level_set_; }
248 
254  return compression_algorithm_;
255  }
260 
262  void SetLoadReportingCosts(const std::vector<std::string>& cost_data);
263 
267  std::shared_ptr<const ::grpc::AuthContext> auth_context() const {
268  if (auth_context_ == nullptr) {
269  auth_context_ = ::grpc::CreateAuthContext(call_.call);
270  }
271  return auth_context_;
272  }
273 
278  std::string peer() const;
279 
281  const struct census_context* census_context() const;
282 
285  grpc_call* c_call() { return call_.call; }
286 
287  protected:
293  void AsyncNotifyWhenDone(void* tag) {
294  has_notify_when_done_tag_ = true;
295  async_notify_when_done_tag_ = tag;
296  }
297 
303  return message_allocator_state_;
304  }
305 
323  // Short-circuit the case where a default reactor was already set up by
324  // the TestPeer.
325  if (test_unary_ != nullptr) {
326  return reinterpret_cast<Reactor*>(&default_reactor_);
327  }
328  new (&default_reactor_) Reactor;
329 #ifndef NDEBUG
330  bool old = false;
331  assert(default_reactor_used_.compare_exchange_strong(
332  old, true, std::memory_order_relaxed));
333 #else
334  default_reactor_used_.store(true, std::memory_order_relaxed);
335 #endif
336  return reinterpret_cast<Reactor*>(&default_reactor_);
337  }
338 
342 
343  private:
344  friend class ::grpc::testing::InteropServerContextInspector;
345  friend class ::grpc::testing::ServerContextTestSpouse;
346  friend class ::grpc::testing::DefaultReactorTestPeer;
347  friend class ::grpc::ServerInterface;
348  friend class ::grpc::Server;
349  template <class W, class R>
350  friend class ::grpc::ServerAsyncReader;
351  template <class W>
352  friend class ::grpc::ServerAsyncWriter;
353  template <class W>
354  friend class ::grpc::ServerAsyncResponseWriter;
355  template <class W, class R>
356  friend class ::grpc::ServerAsyncReaderWriter;
357  template <class R>
358  friend class ::grpc::ServerReader;
359  template <class W>
360  friend class ::grpc::ServerWriter;
361  template <class W, class R>
362  friend class ::grpc::internal::ServerReaderWriterBody;
363  template <class ResponseType>
365  const internal::MethodHandler::HandlerParameter& param, ResponseType* rsp,
366  Status& status);
367  template <class ServiceType, class RequestType, class ResponseType,
368  class BaseRequestType, class BaseResponseType>
369  friend class ::grpc::internal::RpcMethodHandler;
370  template <class ServiceType, class RequestType, class ResponseType>
371  friend class ::grpc::internal::ClientStreamingHandler;
372  template <class ServiceType, class RequestType, class ResponseType>
373  friend class ::grpc::internal::ServerStreamingHandler;
374  template <class Streamer, bool WriteNeeded>
375  friend class ::grpc::internal::TemplatedBidiStreamingHandler;
376  template <class RequestType, class ResponseType>
377  friend class ::grpc::internal::CallbackUnaryHandler;
378  template <class RequestType, class ResponseType>
379  friend class ::grpc::internal::CallbackClientStreamingHandler;
380  template <class RequestType, class ResponseType>
381  friend class ::grpc::internal::CallbackServerStreamingHandler;
382  template <class RequestType, class ResponseType>
383  friend class ::grpc::internal::CallbackBidiHandler;
384  template <::grpc::StatusCode code>
385  friend class ::grpc::internal::ErrorMethodHandler;
386  template <class Base>
387  friend class ::grpc::internal::FinishOnlyReactor;
388  friend class ::grpc::ClientContext;
389  friend class ::grpc::GenericServerContext;
390 #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
391  friend class ::grpc::GenericCallbackServerContext;
392 #else
393  friend class ::grpc::experimental::GenericCallbackServerContext;
394 #endif
395 
398  ServerContextBase& operator=(const ServerContextBase&);
399 
400  class CompletionOp;
401 
402  void BeginCompletionOp(
403  ::grpc::internal::Call* call, std::function<void(bool)> callback,
404  ::grpc::internal::ServerCallbackCall* callback_controller);
406  ::grpc::internal::CompletionQueueTag* GetCompletionOpTag();
407 
408  void set_call(grpc_call* call) { call_.call = call; }
409 
410  void BindDeadlineAndMetadata(gpr_timespec deadline, grpc_metadata_array* arr);
411 
412  uint32_t initial_metadata_flags() const { return 0; }
413 
414  ::grpc::experimental::ServerRpcInfo* set_server_rpc_info(
415  const char* method, ::grpc::internal::RpcMethod::RpcType type,
416  const std::vector<std::unique_ptr<
418  if (!creators.empty()) {
419  rpc_info_ = new ::grpc::experimental::ServerRpcInfo(this, method, type);
420  rpc_info_->RegisterInterceptors(creators);
421  }
422  return rpc_info_;
423  }
424 
425  void set_message_allocator_state(
426  ::grpc::experimental::RpcAllocatorState* allocator_state) {
427  message_allocator_state_ = allocator_state;
428  }
429 
430  struct CallWrapper {
431  ~CallWrapper();
432 
433  grpc_call* call = nullptr;
434  };
435 
436  // NOTE: call_ must be the first data member of this object so that its
437  // destructor is the last to be called, since its destructor may unref
438  // the underlying core call which holds the arena that may be used to
439  // hold this object.
440  CallWrapper call_;
441 
442  CompletionOp* completion_op_ = nullptr;
443  bool has_notify_when_done_tag_ = false;
444  void* async_notify_when_done_tag_ = nullptr;
446 
447  gpr_timespec deadline_;
448  ::grpc::CompletionQueue* cq_ = nullptr;
449  bool sent_initial_metadata_ = false;
450  mutable std::shared_ptr<const ::grpc::AuthContext> auth_context_;
451  mutable ::grpc::internal::MetadataMap client_metadata_;
452  std::multimap<std::string, std::string> initial_metadata_;
453  std::multimap<std::string, std::string> trailing_metadata_;
454 
455  bool compression_level_set_ = false;
456  grpc_compression_level compression_level_;
457  grpc_compression_algorithm compression_algorithm_;
458 
461  pending_ops_;
462  bool has_pending_ops_ = false;
463 
464  ::grpc::experimental::ServerRpcInfo* rpc_info_ = nullptr;
465  ::grpc::experimental::RpcAllocatorState* message_allocator_state_ = nullptr;
466 
467  class Reactor : public ::grpc::ServerUnaryReactor {
468  public:
469  void OnCancel() override {}
470  void OnDone() override {}
471  // Override InternalInlineable for this class since its reactions are
472  // trivial and thus do not need to be run from the executor (triggering a
473  // thread hop). This should only be used by internal reactors (thus the
474  // name) and not by user application code.
475  bool InternalInlineable() override { return true; }
476  };
477 
478  void SetupTestDefaultReactor(std::function<void(::grpc::Status)> func) {
479  // NOLINTNEXTLINE(modernize-make-unique)
480  test_unary_.reset(new TestServerCallbackUnary(this, std::move(func)));
481  }
482  bool test_status_set() const {
483  return (test_unary_ != nullptr) && test_unary_->status_set();
484  }
485  ::grpc::Status test_status() const { return test_unary_->status(); }
486 
487  class TestServerCallbackUnary : public ::grpc::ServerCallbackUnary {
488  public:
489  TestServerCallbackUnary(ServerContextBase* ctx,
490  std::function<void(::grpc::Status)> func)
491  : reactor_(ctx->DefaultReactor()), func_(std::move(func)) {
492  this->BindReactor(reactor_);
493  }
494  void Finish(::grpc::Status s) override {
495  status_ = s;
496  func_(std::move(s));
497  status_set_.store(true, std::memory_order_release);
498  }
499  void SendInitialMetadata() override {}
500 
501  bool status_set() const {
502  return status_set_.load(std::memory_order_acquire);
503  }
504  ::grpc::Status status() const { return status_; }
505 
506  private:
507  void CallOnDone() override {}
508  ::grpc::internal::ServerReactor* reactor() override { return reactor_; }
509 
510  ::grpc::ServerUnaryReactor* const reactor_;
511  std::atomic_bool status_set_{false};
512  ::grpc::Status status_;
513  const std::function<void(::grpc::Status s)> func_;
514  };
515 
516  typename std::aligned_storage<sizeof(Reactor), alignof(Reactor)>::type
517  default_reactor_;
518  std::atomic_bool default_reactor_used_{false};
519  std::unique_ptr<TestServerCallbackUnary> test_unary_;
520 };
521 
539  public:
540  ServerContext() {} // for async calls
541 
559 
560  // Sync/CQ-based Async ServerContext only
562 
563  private:
564  // Constructor for internal use by server only
565  friend class ::grpc::Server;
567  : ServerContextBase(deadline, arr) {}
568 
569  // CallbackServerContext only
572 
574  ServerContext(const ServerContext&) = delete;
575  ServerContext& operator=(const ServerContext&) = delete;
576 };
577 
579  public:
583 
601 
602  // CallbackServerContext only
605 
606  private:
607  // Sync/CQ-based Async ServerContext only
609 
612  CallbackServerContext& operator=(const CallbackServerContext&) = delete;
613 };
614 
615 } // namespace grpc
616 
617 static_assert(
618  std::is_base_of<::grpc::ServerContextBase, ::grpc::ServerContext>::value,
619  "improper base class");
620 static_assert(std::is_base_of<::grpc::ServerContextBase,
621  ::grpc::CallbackServerContext>::value,
622  "improper base class");
623 static_assert(sizeof(::grpc::ServerContextBase) ==
624  sizeof(::grpc::ServerContext),
625  "wrong size");
626 static_assert(sizeof(::grpc::ServerContextBase) ==
627  sizeof(::grpc::CallbackServerContext),
628  "wrong size");
629 
630 #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:538
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:578
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:130
server_interceptor.h
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:107
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:108
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::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:135
grpc::ServerContextBase::raw_deadline
gpr_timespec raw_deadline() const
Return a gpr_timespec representation of the server call's deadline.
Definition: server_context.h:140
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:267
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:247
grpc::ServerContextBase::DefaultReactor
::grpc::ServerUnaryReactor * DefaultReactor()
Get a library-owned default unary reactor for use in minimal reaction cases.
Definition: server_context.h:322
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:582
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:226
string_ref.h
grpc::experimental::ServerInterceptorFactoryInterface
Definition: server_interceptor.h:43
grpc::ServerContextBase::~ServerContextBase
virtual ~ServerContextBase()
callback_common.h
grpc::ServerContextBase::AsyncNotifyWhenDone
void AsyncNotifyWhenDone(void *tag)
Async only.
Definition: server_context.h:293
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::ServerContextBase::GetRpcAllocatorState
::grpc::experimental::RpcAllocatorState * GetRpcAllocatorState()
NOTE: This is an API for advanced users who need custom allocators.
Definition: server_context.h:302
grpc::internal::UnaryRunHandlerHelper
void UnaryRunHandlerHelper(const ::grpc::internal::MethodHandler::HandlerParameter &, ResponseType *, ::grpc::Status &)
grpc::ServerContext::ServerContext
ServerContext()
Definition: server_context.h:540
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:253
grpc::ServerContextBase::c_call
grpc_call * c_call()
Should be used for framework-level extensions only.
Definition: server_context.h:285
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:239
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:232