GRPC C++  1.30.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 ClientContext;
53 class CompletionQueue;
54 class Server;
55 template <class W, class R>
56 class ServerAsyncReader;
57 template <class W>
58 class ServerAsyncWriter;
59 template <class W>
61 template <class W, class R>
63 template <class R>
64 class ServerReader;
65 template <class W>
66 class ServerWriter;
67 
68 namespace internal {
69 template <class ServiceType, class RequestType, class ResponseType>
71 template <class RequestType, class ResponseType>
72 class CallbackUnaryHandler;
73 template <class RequestType, class ResponseType>
74 class CallbackClientStreamingHandler;
75 template <class RequestType, class ResponseType>
76 class CallbackServerStreamingHandler;
77 template <class RequestType, class ResponseType>
78 class CallbackBidiHandler;
79 template <class ServiceType, class RequestType, class ResponseType>
81 template <class ServiceType, class RequestType, class ResponseType>
82 class RpcMethodHandler;
83 template <class Base>
84 class FinishOnlyReactor;
85 template <class W, class R>
86 class ServerReaderWriterBody;
87 template <class ServiceType, class RequestType, class ResponseType>
89 class ServerReactor;
90 template <class Streamer, bool WriteNeeded>
92 template <::grpc::StatusCode code>
93 class ErrorMethodHandler;
94 } // namespace internal
95 
96 } // namespace grpc_impl
97 namespace grpc {
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 grpc::string& key, const grpc::string& value);
155 
175  void AddTrailingMetadata(const grpc::string& key, const grpc::string& value);
176 
180  bool IsCancelled() const;
181 
198  void TryCancel() const;
199 
209  const std::multimap<grpc::string_ref, grpc::string_ref>& client_metadata()
210  const {
211  return *client_metadata_.map();
212  }
213 
216  return compression_level_;
217  }
218 
223  compression_level_set_ = true;
224  compression_level_ = level;
225  }
226 
230  bool compression_level_set() const { return compression_level_set_; }
231 
237  return compression_algorithm_;
238  }
243 
245  void SetLoadReportingCosts(const std::vector<grpc::string>& cost_data);
246 
250  std::shared_ptr<const ::grpc::AuthContext> auth_context() const {
251  if (auth_context_.get() == nullptr) {
252  auth_context_ = ::grpc::CreateAuthContext(call_);
253  }
254  return auth_context_;
255  }
256 
261  grpc::string peer() const;
262 
264  const struct census_context* census_context() const;
265 
268  grpc_call* c_call() { return call_; }
269 
270  protected:
276  void AsyncNotifyWhenDone(void* tag) {
277  has_notify_when_done_tag_ = true;
278  async_notify_when_done_tag_ = tag;
279  }
280 
286  return message_allocator_state_;
287  }
288 
306  // Short-circuit the case where a default reactor was already set up by
307  // the TestPeer.
308  if (test_unary_ != nullptr) {
309  return reinterpret_cast<Reactor*>(&default_reactor_);
310  }
311  new (&default_reactor_) Reactor;
312 #ifndef NDEBUG
313  bool old = false;
314  assert(default_reactor_used_.compare_exchange_strong(
315  old, true, std::memory_order_relaxed));
316 #else
317  default_reactor_used_.store(true, std::memory_order_relaxed);
318 #endif
319  return reinterpret_cast<Reactor*>(&default_reactor_);
320  }
321 
325 
326  private:
327  friend class ::grpc::testing::InteropServerContextInspector;
328  friend class ::grpc::testing::ServerContextTestSpouse;
329  friend class ::grpc::testing::DefaultReactorTestPeer;
330  friend class ::grpc::ServerInterface;
332  template <class W, class R>
334  template <class W>
336  template <class W>
338  template <class W, class R>
340  template <class R>
342  template <class W>
344  template <class W, class R>
345  friend class ::grpc_impl::internal::ServerReaderWriterBody;
346  template <class ServiceType, class RequestType, class ResponseType>
348  template <class ServiceType, class RequestType, class ResponseType>
350  template <class ServiceType, class RequestType, class ResponseType>
352  template <class Streamer, bool WriteNeeded>
354  template <class RequestType, class ResponseType>
355  friend class ::grpc_impl::internal::CallbackUnaryHandler;
356  template <class RequestType, class ResponseType>
357  friend class ::grpc_impl::internal::CallbackClientStreamingHandler;
358  template <class RequestType, class ResponseType>
359  friend class ::grpc_impl::internal::CallbackServerStreamingHandler;
360  template <class RequestType, class ResponseType>
361  friend class ::grpc_impl::internal::CallbackBidiHandler;
362  template <::grpc::StatusCode code>
364  template <class Base>
365  friend class ::grpc_impl::internal::FinishOnlyReactor;
367  friend class ::grpc::GenericServerContext;
368 #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
369  friend class ::grpc::GenericCallbackServerContext;
370 #else
371  friend class ::grpc::experimental::GenericCallbackServerContext;
372 #endif
373 
376  ServerContextBase& operator=(const ServerContextBase&);
377 
378  class CompletionOp;
379 
380  void BeginCompletionOp(
381  ::grpc::internal::Call* call, std::function<void(bool)> callback,
382  ::grpc_impl::internal::ServerCallbackCall* callback_controller);
384  ::grpc::internal::CompletionQueueTag* GetCompletionOpTag();
385 
386  void set_call(grpc_call* call) { call_ = call; }
387 
388  void BindDeadlineAndMetadata(gpr_timespec deadline, grpc_metadata_array* arr);
389 
390  void Clear();
391 
392  void Setup(gpr_timespec deadline);
393 
394  uint32_t initial_metadata_flags() const { return 0; }
395 
396  ::grpc::experimental::ServerRpcInfo* set_server_rpc_info(
397  const char* method, ::grpc::internal::RpcMethod::RpcType type,
398  const std::vector<std::unique_ptr<
400  if (creators.size() != 0) {
401  rpc_info_ = new ::grpc::experimental::ServerRpcInfo(this, method, type);
402  rpc_info_->RegisterInterceptors(creators);
403  }
404  return rpc_info_;
405  }
406 
407  void set_message_allocator_state(
408  ::grpc::experimental::RpcAllocatorState* allocator_state) {
409  message_allocator_state_ = allocator_state;
410  }
411 
412  CompletionOp* completion_op_;
413  bool has_notify_when_done_tag_;
414  void* async_notify_when_done_tag_;
416 
417  gpr_timespec deadline_;
418  grpc_call* call_;
420  bool sent_initial_metadata_;
421  mutable std::shared_ptr<const ::grpc::AuthContext> auth_context_;
422  mutable ::grpc::internal::MetadataMap client_metadata_;
423  std::multimap<grpc::string, grpc::string> initial_metadata_;
424  std::multimap<grpc::string, grpc::string> trailing_metadata_;
425 
426  bool compression_level_set_;
427  grpc_compression_level compression_level_;
428  grpc_compression_algorithm compression_algorithm_;
429 
432  pending_ops_;
433  bool has_pending_ops_;
434 
436  ::grpc::experimental::RpcAllocatorState* message_allocator_state_ = nullptr;
437 
438  class Reactor : public ServerUnaryReactor {
439  public:
440  void OnCancel() override {}
441  void OnDone() override {}
442  // Override InternalInlineable for this class since its reactions are
443  // trivial and thus do not need to be run from the executor (triggering a
444  // thread hop). This should only be used by internal reactors (thus the
445  // name) and not by user application code.
446  bool InternalInlineable() override { return true; }
447  };
448 
449  void SetupTestDefaultReactor(std::function<void(::grpc::Status)> func) {
450  test_unary_.reset(new TestServerCallbackUnary(this, std::move(func)));
451  }
452  bool test_status_set() const {
453  return (test_unary_ != nullptr) && test_unary_->status_set();
454  }
455  ::grpc::Status test_status() const { return test_unary_->status(); }
456 
457  class TestServerCallbackUnary : public ::grpc_impl::ServerCallbackUnary {
458  public:
459  TestServerCallbackUnary(ServerContextBase* ctx,
460  std::function<void(::grpc::Status)> func)
461  : reactor_(ctx->DefaultReactor()), func_(std::move(func)) {
462  this->BindReactor(reactor_);
463  }
464  void Finish(::grpc::Status s) override {
465  status_ = s;
466  func_(std::move(s));
467  status_set_.store(true, std::memory_order_release);
468  }
469  void SendInitialMetadata() override {}
470 
471  bool status_set() const {
472  return status_set_.load(std::memory_order_acquire);
473  }
474  ::grpc::Status status() const { return status_; }
475 
476  private:
477  void CallOnDone() override {}
478  ::grpc_impl::internal::ServerReactor* reactor() override {
479  return reactor_;
480  }
481 
482  ::grpc_impl::ServerUnaryReactor* const reactor_;
483  std::atomic_bool status_set_{false};
484  ::grpc::Status status_;
485  const std::function<void(::grpc::Status s)> func_;
486  };
487 
488  typename std::aligned_storage<sizeof(Reactor), alignof(Reactor)>::type
489  default_reactor_;
490  std::atomic_bool default_reactor_used_{false};
491  std::unique_ptr<TestServerCallbackUnary> test_unary_;
492 };
493 
511  public:
512  ServerContext() {} // for async calls
513 
531 
532  // Sync/CQ-based Async ServerContext only
534 
535  private:
536  // Constructor for internal use by server only
539  : ServerContextBase(deadline, arr) {}
540 
541  // CallbackServerContext only
544 
546  ServerContext(const ServerContext&) = delete;
547  ServerContext& operator=(const ServerContext&) = delete;
548 };
549 
551  public:
555 
573 
574  // CallbackServerContext only
577 
578  private:
579  // Sync/CQ-based Async ServerContext only
581 
584  CallbackServerContext& operator=(const CallbackServerContext&) = delete;
585 };
586 
587 } // namespace grpc_impl
588 
589 static_assert(std::is_base_of<::grpc_impl::ServerContextBase,
590  ::grpc_impl::ServerContext>::value,
591  "improper base class");
592 static_assert(std::is_base_of<::grpc_impl::ServerContextBase,
594  "improper base class");
595 static_assert(sizeof(::grpc_impl::ServerContextBase) ==
596  sizeof(::grpc_impl::ServerContext),
597  "wrong size");
598 static_assert(sizeof(::grpc_impl::ServerContextBase) ==
600  "wrong size");
601 
602 #endif // GRPCPP_IMPL_CODEGEN_SERVER_CONTEXT_IMPL_H
grpc_impl::ServerContextBase::AddTrailingMetadata
void AddTrailingMetadata(const grpc::string &key, const grpc::string &value)
Add the (key, value) pair to the initial metadata associated with a server call.
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::compression_algorithm
grpc_compression_algorithm compression_algorithm() const
Return the compression algorithm the server call will request be used.
Definition: server_context_impl.h:236
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:222
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:305
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:849
status.h
grpc::internal::CallOpSendMessage
Definition: call_op_set.h:286
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
grpc::CompletionQueue
::grpc_impl::CompletionQueue CompletionQueue
Definition: completion_queue.h:26
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::ServerUnaryReactor
Definition: server_callback_impl.h:693
server_callback_impl.h
grpc::internal::Call
Straightforward wrapping of the C call object.
Definition: call.h:38
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:250
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:216
grpc_impl::ServerContextBase::SetLoadReportingCosts
void SetLoadReportingCosts(const std::vector< grpc::string > &cost_data)
Set the serialized load reporting costs in cost_data for the call.
grpc_impl::CallbackServerContext
Definition: server_context_impl.h:550
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::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:510
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:209
grpc::CreateAuthContext
std::shared_ptr< const AuthContext > CreateAuthContext(grpc_call *call)
grpc_impl::ServerContextBase::AddInitialMetadata
void AddInitialMetadata(const grpc::string &key, const grpc::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::ServerReader
::grpc_impl::ServerReader< R > ServerReader
Definition: sync_stream.h:75
grpc_impl::ServerContextBase::IsCancelled
bool IsCancelled() const
IsCancelled is always safe to call when using sync or callback API.
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:276
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:215
grpc_impl::ServerCallbackUnary
Definition: server_callback_impl.h:191
grpc_impl::CompletionQueue
A thin wrapper around grpc_completion_queue (see src/core/lib/surface/completion_queue....
Definition: completion_queue_impl.h:103
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::string
std::string string
Definition: config.h:35
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:512
grpc_impl::ServerContextBase::c_call
grpc_call * c_call()
Should be used for framework-level extensions only.
Definition: server_context_impl.h:268
grpc::ClientContext
::grpc_impl::ClientContext ClientContext
Definition: client_context.h:26
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:285
message_allocator.h
grpc_impl::ServerContextBase::peer
grpc::string peer() const
Return the peer uri in a string.
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:554
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:230