GRPC C++  1.32.0
server_context_impl.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_IMPL_H
20 #define GRPCPP_IMPL_CODEGEN_SERVER_CONTEXT_IMPL_H
21 
22 #include <atomic>
23 #include <cassert>
24 #include <map>
25 #include <memory>
26 #include <type_traits>
27 #include <vector>
28 
30 
46 
47 struct grpc_metadata;
48 struct grpc_call;
49 struct census_context;
50 
51 namespace grpc_impl {
52 class Server;
53 template <class W, class R>
54 class ServerAsyncReader;
55 template <class W>
56 class ServerAsyncWriter;
57 template <class W>
59 template <class W, class R>
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>
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>
79 template <class ServiceType, class RequestType, class ResponseType>
80 class RpcMethodHandler;
81 template <class Base>
82 class FinishOnlyReactor;
83 template <class W, class R>
84 class ServerReaderWriterBody;
85 template <class ServiceType, class RequestType, class ResponseType>
87 class ServerReactor;
88 template <class Streamer, bool WriteNeeded>
90 template <::grpc::StatusCode code>
91 class ErrorMethodHandler;
92 } // namespace internal
93 
94 } // namespace grpc_impl
95 namespace grpc {
96 class ClientContext;
97 class CompletionQueue;
98 class GenericServerContext;
99 class ServerInterface;
100 
101 #ifndef GRPC_CALLBACK_API_NONEXPERIMENTAL
102 namespace experimental {
103 #endif
104 class GenericCallbackServerContext;
105 #ifndef GRPC_CALLBACK_API_NONEXPERIMENTAL
106 } // namespace experimental
107 #endif
108 namespace internal {
109 class Call;
110 } // namespace internal
111 
112 namespace testing {
113 class InteropServerContextInspector;
114 class ServerContextTestSpouse;
115 class DefaultReactorTestPeer;
116 } // namespace testing
117 
118 } // namespace grpc
119 
120 namespace grpc_impl {
121 
124  public:
125  virtual ~ServerContextBase();
126 
128  std::chrono::system_clock::time_point deadline() const {
130  }
131 
133  gpr_timespec raw_deadline() const { return deadline_; }
134 
154  void AddInitialMetadata(const std::string& key, const std::string& value);
155 
175  void AddTrailingMetadata(const std::string& key, const std::string& value);
176 
188  bool IsCancelled() const;
189 
208  void TryCancel() const;
209 
219  const std::multimap<grpc::string_ref, grpc::string_ref>& client_metadata()
220  const {
221  return *client_metadata_.map();
222  }
223 
226  return compression_level_;
227  }
228 
233  compression_level_set_ = true;
234  compression_level_ = level;
235  }
236 
240  bool compression_level_set() const { return compression_level_set_; }
241 
247  return compression_algorithm_;
248  }
253 
255  void SetLoadReportingCosts(const std::vector<std::string>& cost_data);
256 
260  std::shared_ptr<const ::grpc::AuthContext> auth_context() const {
261  if (auth_context_.get() == nullptr) {
262  auth_context_ = ::grpc::CreateAuthContext(call_);
263  }
264  return auth_context_;
265  }
266 
271  std::string peer() const;
272 
274  const struct census_context* census_context() const;
275 
278  grpc_call* c_call() { return call_; }
279 
280  protected:
286  void AsyncNotifyWhenDone(void* tag) {
287  has_notify_when_done_tag_ = true;
288  async_notify_when_done_tag_ = tag;
289  }
290 
296  return message_allocator_state_;
297  }
298 
316  // Short-circuit the case where a default reactor was already set up by
317  // the TestPeer.
318  if (test_unary_ != nullptr) {
319  return reinterpret_cast<Reactor*>(&default_reactor_);
320  }
321  new (&default_reactor_) Reactor;
322 #ifndef NDEBUG
323  bool old = false;
324  assert(default_reactor_used_.compare_exchange_strong(
325  old, true, std::memory_order_relaxed));
326 #else
327  default_reactor_used_.store(true, std::memory_order_relaxed);
328 #endif
329  return reinterpret_cast<Reactor*>(&default_reactor_);
330  }
331 
335 
336  private:
337  friend class ::grpc::testing::InteropServerContextInspector;
338  friend class ::grpc::testing::ServerContextTestSpouse;
339  friend class ::grpc::testing::DefaultReactorTestPeer;
340  friend class ::grpc::ServerInterface;
342  template <class W, class R>
344  template <class W>
346  template <class W>
348  template <class W, class R>
350  template <class R>
352  template <class W>
354  template <class W, class R>
355  friend class ::grpc_impl::internal::ServerReaderWriterBody;
356  template <class ServiceType, class RequestType, class ResponseType>
358  template <class ServiceType, class RequestType, class ResponseType>
360  template <class ServiceType, class RequestType, class ResponseType>
362  template <class Streamer, bool WriteNeeded>
364  template <class RequestType, class ResponseType>
365  friend class ::grpc_impl::internal::CallbackUnaryHandler;
366  template <class RequestType, class ResponseType>
367  friend class ::grpc_impl::internal::CallbackClientStreamingHandler;
368  template <class RequestType, class ResponseType>
369  friend class ::grpc_impl::internal::CallbackServerStreamingHandler;
370  template <class RequestType, class ResponseType>
371  friend class ::grpc_impl::internal::CallbackBidiHandler;
372  template <::grpc::StatusCode code>
374  template <class Base>
375  friend class ::grpc_impl::internal::FinishOnlyReactor;
376  friend class ::grpc::ClientContext;
377  friend class ::grpc::GenericServerContext;
378 #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
379  friend class ::grpc::GenericCallbackServerContext;
380 #else
381  friend class ::grpc::experimental::GenericCallbackServerContext;
382 #endif
383 
386  ServerContextBase& operator=(const ServerContextBase&);
387 
388  class CompletionOp;
389 
390  void BeginCompletionOp(
391  ::grpc::internal::Call* call, std::function<void(bool)> callback,
392  ::grpc_impl::internal::ServerCallbackCall* callback_controller);
394  ::grpc::internal::CompletionQueueTag* GetCompletionOpTag();
395 
396  void set_call(grpc_call* call) { call_ = call; }
397 
398  void BindDeadlineAndMetadata(gpr_timespec deadline, grpc_metadata_array* arr);
399 
400  void Clear();
401 
402  void Setup(gpr_timespec deadline);
403 
404  uint32_t initial_metadata_flags() const { return 0; }
405 
406  ::grpc::experimental::ServerRpcInfo* set_server_rpc_info(
407  const char* method, ::grpc::internal::RpcMethod::RpcType type,
408  const std::vector<std::unique_ptr<
410  if (creators.size() != 0) {
411  rpc_info_ = new ::grpc::experimental::ServerRpcInfo(this, method, type);
412  rpc_info_->RegisterInterceptors(creators);
413  }
414  return rpc_info_;
415  }
416 
417  void set_message_allocator_state(
418  ::grpc::experimental::RpcAllocatorState* allocator_state) {
419  message_allocator_state_ = allocator_state;
420  }
421 
422  CompletionOp* completion_op_;
423  bool has_notify_when_done_tag_;
424  void* async_notify_when_done_tag_;
426 
427  gpr_timespec deadline_;
428  grpc_call* call_;
430  bool sent_initial_metadata_;
431  mutable std::shared_ptr<const ::grpc::AuthContext> auth_context_;
432  mutable ::grpc::internal::MetadataMap client_metadata_;
433  std::multimap<std::string, std::string> initial_metadata_;
434  std::multimap<std::string, std::string> trailing_metadata_;
435 
436  bool compression_level_set_;
437  grpc_compression_level compression_level_;
438  grpc_compression_algorithm compression_algorithm_;
439 
442  pending_ops_;
443  bool has_pending_ops_;
444 
446  ::grpc::experimental::RpcAllocatorState* message_allocator_state_ = nullptr;
447 
448  class Reactor : public ServerUnaryReactor {
449  public:
450  void OnCancel() override {}
451  void OnDone() override {}
452  // Override InternalInlineable for this class since its reactions are
453  // trivial and thus do not need to be run from the executor (triggering a
454  // thread hop). This should only be used by internal reactors (thus the
455  // name) and not by user application code.
456  bool InternalInlineable() override { return true; }
457  };
458 
459  void SetupTestDefaultReactor(std::function<void(::grpc::Status)> func) {
460  test_unary_.reset(new TestServerCallbackUnary(this, std::move(func)));
461  }
462  bool test_status_set() const {
463  return (test_unary_ != nullptr) && test_unary_->status_set();
464  }
465  ::grpc::Status test_status() const { return test_unary_->status(); }
466 
467  class TestServerCallbackUnary : public ::grpc_impl::ServerCallbackUnary {
468  public:
469  TestServerCallbackUnary(ServerContextBase* ctx,
470  std::function<void(::grpc::Status)> func)
471  : reactor_(ctx->DefaultReactor()), func_(std::move(func)) {
472  this->BindReactor(reactor_);
473  }
474  void Finish(::grpc::Status s) override {
475  status_ = s;
476  func_(std::move(s));
477  status_set_.store(true, std::memory_order_release);
478  }
479  void SendInitialMetadata() override {}
480 
481  bool status_set() const {
482  return status_set_.load(std::memory_order_acquire);
483  }
484  ::grpc::Status status() const { return status_; }
485 
486  private:
487  void CallOnDone() override {}
488  ::grpc_impl::internal::ServerReactor* reactor() override {
489  return reactor_;
490  }
491 
492  ::grpc_impl::ServerUnaryReactor* const reactor_;
493  std::atomic_bool status_set_{false};
494  ::grpc::Status status_;
495  const std::function<void(::grpc::Status s)> func_;
496  };
497 
498  typename std::aligned_storage<sizeof(Reactor), alignof(Reactor)>::type
499  default_reactor_;
500  std::atomic_bool default_reactor_used_{false};
501  std::unique_ptr<TestServerCallbackUnary> test_unary_;
502 };
503 
521  public:
522  ServerContext() {} // for async calls
523 
541 
542  // Sync/CQ-based Async ServerContext only
544 
545  private:
546  // Constructor for internal use by server only
549  : ServerContextBase(deadline, arr) {}
550 
551  // CallbackServerContext only
554 
556  ServerContext(const ServerContext&) = delete;
557  ServerContext& operator=(const ServerContext&) = delete;
558 };
559 
561  public:
565 
583 
584  // CallbackServerContext only
587 
588  private:
589  // Sync/CQ-based Async ServerContext only
591 
594  CallbackServerContext& operator=(const CallbackServerContext&) = delete;
595 };
596 
597 } // namespace grpc_impl
598 
599 static_assert(std::is_base_of<::grpc_impl::ServerContextBase,
600  ::grpc_impl::ServerContext>::value,
601  "improper base class");
602 static_assert(std::is_base_of<::grpc_impl::ServerContextBase,
604  "improper base class");
605 static_assert(sizeof(::grpc_impl::ServerContextBase) ==
606  sizeof(::grpc_impl::ServerContext),
607  "wrong size");
608 static_assert(sizeof(::grpc_impl::ServerContextBase) ==
610  "wrong size");
611 
612 #endif // GRPCPP_IMPL_CODEGEN_SERVER_CONTEXT_IMPL_H
grpc::internal::CallbackWithSuccessTag
CallbackWithSuccessTag can be reused multiple times, and will be used in this fashion for streaming o...
Definition: callback_common.h:136
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_impl::ServerContextBase::peer
std::string peer() const
Return the peer uri in a string.
grpc_impl::ServerContextBase::compression_algorithm
grpc_compression_algorithm compression_algorithm() const
Return the compression algorithm the server call will request be used.
Definition: server_context_impl.h:246
grpc_impl::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_impl.h:232
grpc::internal::RpcMethodHandler
::grpc_impl::internal::RpcMethodHandler< ServiceType, RequestType, ResponseType > RpcMethodHandler
Definition: method_handler.h:36
grpc_impl::ServerContextBase::~ServerContextBase
virtual ~ServerContextBase()
time.h
grpc_impl::ServerContextBase::DefaultReactor
::grpc_impl::ServerUnaryReactor * DefaultReactor()
Get a library-owned default unary reactor for use in minimal reaction cases.
Definition: server_context_impl.h:315
grpc::internal::TemplatedBidiStreamingHandler
::grpc_impl::internal::TemplatedBidiStreamingHandler< Streamer, WriteNeeded > TemplatedBidiStreamingHandler
Definition: method_handler.h:50
grpc
This header provides an object that reads bytes directly from a grpc::ByteBuffer, via the ZeroCopyInp...
Definition: alarm.h:24
grpc::internal::CallOpSet
Primary implementation of CallOpSetInterface.
Definition: call_op_set.h:850
status.h
grpc::internal::CallOpSendMessage
Definition: call_op_set.h:287
grpc_metadata_array
Definition: grpc_types.h:546
grpc_impl::ServerCallbackUnary::BindReactor
void BindReactor(Reactor *reactor)
Definition: server_callback_impl.h:201
grpc::ServerAsyncResponseWriter
::grpc_impl::ServerAsyncResponseWriter< W > ServerAsyncResponseWriter
Definition: async_unary_call.h:34
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::ServerAsyncReader
::grpc_impl::ServerAsyncReader< W, R > ServerAsyncReader
Definition: async_stream.h:63
grpc_impl::ServerContextBase::SetLoadReportingCosts
void SetLoadReportingCosts(const std::vector< std::string > &cost_data)
Set the serialized load reporting costs in cost_data for the call.
grpc_impl::ServerUnaryReactor
Definition: server_callback_impl.h:693
server_callback_impl.h
grpc::internal::Call
Straightforward wrapping of the C call object.
Definition: call.h:35
auth_context.h
server_interceptor.h
grpc_impl::ServerContextBase::auth_context
std::shared_ptr< const ::grpc::AuthContext > auth_context() const
Return the authentication context for this server call.
Definition: server_context_impl.h:260
grpc_impl::ServerContextBase
Base class of ServerContext. Experimental until callback API is final.
Definition: server_context_impl.h:123
grpc::internal::CallOpSendInitialMetadata
Definition: call_op_set.h:217
grpc_impl::CallbackServerContext
Definition: server_context_impl.h:560
grpc::Server
::grpc_impl::Server Server
Definition: server.h:26
grpc::experimental::RpcAllocatorState
Definition: message_allocator.h:29
grpc_impl::ServerContextBase::ServerContextBase
ServerContextBase()
Constructors for use by derived classes.
grpc::ServerAsyncReaderWriter
::grpc_impl::ServerAsyncReaderWriter< W, R > ServerAsyncReaderWriter
Definition: async_stream.h:76
grpc_impl::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_impl::ServerContextBase::TryCancel
void TryCancel() const
Cancel the Call from the server.
metadata_map.h
grpc::ServerWriter
::grpc_impl::ServerWriter< W > ServerWriter
Definition: sync_stream.h:81
grpc::internal::MetadataMap::map
std::multimap< grpc::string_ref, grpc::string_ref > * map()
Definition: metadata_map.h:66
grpc::Status
Did it work? If it didn't, why?
Definition: status.h:31
grpc_impl::ServerContext
A ServerContext or CallbackServerContext allows the code implementing a service handler to:
Definition: server_context_impl.h:520
grpc_metadata
A single metadata element.
Definition: grpc_types.h:502
grpc::internal::ServerStreamingHandler
::grpc_impl::internal::ServerStreamingHandler< ServiceType, RequestType, ResponseType > ServerStreamingHandler
Definition: method_handler.h:46
grpc::internal::BidiStreamingHandler
::grpc_impl::internal::BidiStreamingHandler< ServiceType, RequestType, ResponseType > BidiStreamingHandler
Definition: method_handler.h:31
grpc_impl::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_impl.h:219
grpc::CreateAuthContext
std::shared_ptr< const AuthContext > CreateAuthContext(grpc_call *call)
grpc_call
struct grpc_call grpc_call
A Call represents an RPC.
Definition: grpc_types.h:70
completion_queue_tag.h
grpc_impl::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::ServerReader
::grpc_impl::ServerReader< R > ServerReader
Definition: sync_stream.h:75
grpc_impl::ServerContextBase::IsCancelled
bool IsCancelled() const
Return whether this RPC failed before the server could provide its status back to the client.
grpc_impl::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::experimental::ServerUnaryReactor
::grpc_impl::ServerUnaryReactor ServerUnaryReactor
Definition: server_callback.h:51
grpc_impl::ServerContextBase::raw_deadline
gpr_timespec raw_deadline() const
Return a gpr_timespec representation of the server call's deadline.
Definition: server_context_impl.h:133
grpc::internal::RpcMethod::RpcType
RpcType
Definition: rpc_method.h:31
grpc::experimental::ServerRpcInfo
ServerRpcInfo represents the state of a particular RPC as it appears to an interceptor.
Definition: server_interceptor.h:60
grpc::internal::CompletionQueueTag
An interface allowing implementors to process and filter event tags.
Definition: completion_queue_tag.h:26
compression_types.h
grpc_impl::internal::ServerCallbackCall
The base class of ServerCallbackUnary etc.
Definition: server_callback_impl.h:72
grpc_impl::internal::ServerReactor
Definition: server_callback_impl.h:48
string_ref.h
grpc::experimental::ServerInterceptorFactoryInterface
Definition: server_interceptor.h:47
grpc_impl::ServerContextBase::AsyncNotifyWhenDone
void AsyncNotifyWhenDone(void *tag)
Async only.
Definition: server_context_impl.h:286
callback_common.h
grpc_impl::ServerContextBase::compression_level
grpc_compression_level compression_level() const
Return the compression algorithm to be used by the server call.
Definition: server_context_impl.h:225
grpc_impl::ServerCallbackUnary
Definition: server_callback_impl.h:191
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_impl.h:301
grpc_impl::ServerContextBase::census_context
const struct census_context * census_context() const
Get the census context associated with this server call.
create_auth_context.h
grpc_impl::ServerContextBase::deadline
std::chrono::system_clock::time_point deadline() const
Return the deadline for the server call.
Definition: server_context_impl.h:128
grpc::CompletionQueue
A thin wrapper around grpc_completion_queue (see src/core/lib/surface/completion_queue....
Definition: completion_queue.h:99
grpc_impl
An Alarm posts the user-provided tag to its associated completion queue or invokes the user-provided ...
Definition: alarm_impl.h:33
grpc_impl::ServerContext::ServerContext
ServerContext()
Definition: server_context_impl.h:522
grpc_impl::ServerContextBase::c_call
grpc_call * c_call()
Should be used for framework-level extensions only.
Definition: server_context_impl.h:278
grpc::ServerAsyncWriter
::grpc_impl::ServerAsyncWriter< W > ServerAsyncWriter
Definition: async_stream.h:69
gpr_timespec
Analogous to struct timespec.
Definition: gpr_types.h:47
grpc::internal::ErrorMethodHandler
::grpc_impl::internal::ErrorMethodHandler< code > ErrorMethodHandler
Definition: method_handler.h:62
grpc_impl::ServerContextBase::GetRpcAllocatorState
::grpc::experimental::RpcAllocatorState * GetRpcAllocatorState()
NOTE: This is an API for advanced users who need custom allocators.
Definition: server_context_impl.h:295
message_allocator.h
grpc::internal::ClientStreamingHandler
::grpc_impl::internal::ClientStreamingHandler< ServiceType, RequestType, ResponseType > ClientStreamingHandler
Definition: method_handler.h:41
grpc::Timespec2Timepoint
std::chrono::system_clock::time_point Timespec2Timepoint(gpr_timespec t)
grpc_impl::CallbackServerContext::CallbackServerContext
CallbackServerContext()
Public constructors are for direct use only by mocking tests.
Definition: server_context_impl.h:564
grpc_impl::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_impl.h:240