GRPC C++  1.33.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 
46 
47 struct grpc_metadata;
48 struct grpc_call;
49 struct census_context;
50 
51 namespace grpc {
52 template <class W, class R>
53 class ServerAsyncReader;
54 template <class W>
55 class ServerAsyncWriter;
56 template <class W>
57 class ServerAsyncResponseWriter;
58 template <class W, class R>
59 class ServerAsyncReaderWriter;
60 template <class R>
61 class ServerReader;
62 template <class W>
63 class ServerWriter;
64 
65 namespace internal {
66 template <class ServiceType, class RequestType, class ResponseType>
67 class BidiStreamingHandler;
68 template <class RequestType, class ResponseType>
69 class CallbackUnaryHandler;
70 template <class RequestType, class ResponseType>
71 class CallbackClientStreamingHandler;
72 template <class RequestType, class ResponseType>
73 class CallbackServerStreamingHandler;
74 template <class RequestType, class ResponseType>
75 class CallbackBidiHandler;
76 template <class ServiceType, class RequestType, class ResponseType>
77 class ClientStreamingHandler;
78 template <class ServiceType, class RequestType, class ResponseType>
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 
93 class ClientContext;
94 class CompletionQueue;
95 class GenericServerContext;
96 class Server;
97 class ServerInterface;
98 
99 // TODO(vjpai): Remove namespace experimental when de-experimentalized fully.
100 namespace experimental {
101 
104 
105 } // namespace experimental
106 
107 #ifndef GRPC_CALLBACK_API_NONEXPERIMENTAL
108 namespace experimental {
109 #endif
110 class GenericCallbackServerContext;
111 #ifndef GRPC_CALLBACK_API_NONEXPERIMENTAL
112 } // namespace experimental
113 #endif
114 namespace internal {
115 class Call;
116 } // namespace internal
117 
118 namespace testing {
119 class InteropServerContextInspector;
120 class ServerContextTestSpouse;
121 class DefaultReactorTestPeer;
122 } // namespace testing
123 
126  public:
127  virtual ~ServerContextBase();
128 
130  std::chrono::system_clock::time_point deadline() const {
132  }
133 
135  gpr_timespec raw_deadline() const { return deadline_; }
136 
156  void AddInitialMetadata(const std::string& key, const std::string& value);
157 
177  void AddTrailingMetadata(const std::string& key, const std::string& value);
178 
190  bool IsCancelled() const;
191 
210  void TryCancel() const;
211 
221  const std::multimap<grpc::string_ref, grpc::string_ref>& client_metadata()
222  const {
223  return *client_metadata_.map();
224  }
225 
228  return compression_level_;
229  }
230 
235  compression_level_set_ = true;
236  compression_level_ = level;
237  }
238 
242  bool compression_level_set() const { return compression_level_set_; }
243 
249  return compression_algorithm_;
250  }
255 
257  void SetLoadReportingCosts(const std::vector<std::string>& cost_data);
258 
262  std::shared_ptr<const ::grpc::AuthContext> auth_context() const {
263  if (auth_context_.get() == nullptr) {
264  auth_context_ = ::grpc::CreateAuthContext(call_.call);
265  }
266  return auth_context_;
267  }
268 
273  std::string peer() const;
274 
276  const struct census_context* census_context() const;
277 
280  grpc_call* c_call() { return call_.call; }
281 
282  protected:
288  void AsyncNotifyWhenDone(void* tag) {
289  has_notify_when_done_tag_ = true;
290  async_notify_when_done_tag_ = tag;
291  }
292 
298  return message_allocator_state_;
299  }
300 
318  // Short-circuit the case where a default reactor was already set up by
319  // the TestPeer.
320  if (test_unary_ != nullptr) {
321  return reinterpret_cast<Reactor*>(&default_reactor_);
322  }
323  new (&default_reactor_) Reactor;
324 #ifndef NDEBUG
325  bool old = false;
326  assert(default_reactor_used_.compare_exchange_strong(
327  old, true, std::memory_order_relaxed));
328 #else
329  default_reactor_used_.store(true, std::memory_order_relaxed);
330 #endif
331  return reinterpret_cast<Reactor*>(&default_reactor_);
332  }
333 
337 
338  private:
339  friend class ::grpc::testing::InteropServerContextInspector;
340  friend class ::grpc::testing::ServerContextTestSpouse;
341  friend class ::grpc::testing::DefaultReactorTestPeer;
342  friend class ::grpc::ServerInterface;
343  friend class ::grpc::Server;
344  template <class W, class R>
345  friend class ::grpc::ServerAsyncReader;
346  template <class W>
347  friend class ::grpc::ServerAsyncWriter;
348  template <class W>
349  friend class ::grpc::ServerAsyncResponseWriter;
350  template <class W, class R>
351  friend class ::grpc::ServerAsyncReaderWriter;
352  template <class R>
353  friend class ::grpc::ServerReader;
354  template <class W>
355  friend class ::grpc::ServerWriter;
356  template <class W, class R>
357  friend class ::grpc::internal::ServerReaderWriterBody;
358  template <class ServiceType, class RequestType, class ResponseType>
359  friend class ::grpc::internal::RpcMethodHandler;
360  template <class ServiceType, class RequestType, class ResponseType>
361  friend class ::grpc::internal::ClientStreamingHandler;
362  template <class ServiceType, class RequestType, class ResponseType>
363  friend class ::grpc::internal::ServerStreamingHandler;
364  template <class Streamer, bool WriteNeeded>
365  friend class ::grpc::internal::TemplatedBidiStreamingHandler;
366  template <class RequestType, class ResponseType>
367  friend class ::grpc::internal::CallbackUnaryHandler;
368  template <class RequestType, class ResponseType>
369  friend class ::grpc::internal::CallbackClientStreamingHandler;
370  template <class RequestType, class ResponseType>
371  friend class ::grpc::internal::CallbackServerStreamingHandler;
372  template <class RequestType, class ResponseType>
373  friend class ::grpc::internal::CallbackBidiHandler;
374  template <::grpc::StatusCode code>
375  friend class ::grpc::internal::ErrorMethodHandler;
376  template <class Base>
377  friend class ::grpc::internal::FinishOnlyReactor;
378  friend class ::grpc::ClientContext;
379  friend class ::grpc::GenericServerContext;
380 #ifdef GRPC_CALLBACK_API_NONEXPERIMENTAL
381  friend class ::grpc::GenericCallbackServerContext;
382 #else
383  friend class ::grpc::experimental::GenericCallbackServerContext;
384 #endif
385 
388  ServerContextBase& operator=(const ServerContextBase&);
389 
390  class CompletionOp;
391 
392  void BeginCompletionOp(
393  ::grpc::internal::Call* call, std::function<void(bool)> callback,
394  ::grpc::internal::ServerCallbackCall* callback_controller);
396  ::grpc::internal::CompletionQueueTag* GetCompletionOpTag();
397 
398  void set_call(grpc_call* call) { call_.call = call; }
399 
400  void BindDeadlineAndMetadata(gpr_timespec deadline, grpc_metadata_array* arr);
401 
402  uint32_t initial_metadata_flags() const { return 0; }
403 
404  ::grpc::experimental::ServerRpcInfo* set_server_rpc_info(
405  const char* method, ::grpc::internal::RpcMethod::RpcType type,
406  const std::vector<std::unique_ptr<
408  if (creators.size() != 0) {
409  rpc_info_ = new ::grpc::experimental::ServerRpcInfo(this, method, type);
410  rpc_info_->RegisterInterceptors(creators);
411  }
412  return rpc_info_;
413  }
414 
415  void set_message_allocator_state(
416  ::grpc::experimental::RpcAllocatorState* allocator_state) {
417  message_allocator_state_ = allocator_state;
418  }
419 
420  struct CallWrapper {
421  ~CallWrapper();
422 
423  grpc_call* call = nullptr;
424  };
425 
426  // NOTE: call_ must be the first data member of this object so that its
427  // destructor is the last to be called, since its destructor may unref
428  // the underlying core call which holds the arena that may be used to
429  // hold this object.
430  CallWrapper call_;
431 
432  CompletionOp* completion_op_ = nullptr;
433  bool has_notify_when_done_tag_ = false;
434  void* async_notify_when_done_tag_ = nullptr;
436 
437  gpr_timespec deadline_;
438  ::grpc::CompletionQueue* cq_ = nullptr;
439  bool sent_initial_metadata_ = false;
440  mutable std::shared_ptr<const ::grpc::AuthContext> auth_context_;
441  mutable ::grpc::internal::MetadataMap client_metadata_;
442  std::multimap<std::string, std::string> initial_metadata_;
443  std::multimap<std::string, std::string> trailing_metadata_;
444 
445  bool compression_level_set_ = false;
446  grpc_compression_level compression_level_;
447  grpc_compression_algorithm compression_algorithm_;
448 
451  pending_ops_;
452  bool has_pending_ops_ = false;
453 
454  ::grpc::experimental::ServerRpcInfo* rpc_info_ = nullptr;
455  ::grpc::experimental::RpcAllocatorState* message_allocator_state_ = nullptr;
456 
457  class Reactor : public ::grpc::ServerUnaryReactor {
458  public:
459  void OnCancel() override {}
460  void OnDone() override {}
461  // Override InternalInlineable for this class since its reactions are
462  // trivial and thus do not need to be run from the executor (triggering a
463  // thread hop). This should only be used by internal reactors (thus the
464  // name) and not by user application code.
465  bool InternalInlineable() override { return true; }
466  };
467 
468  void SetupTestDefaultReactor(std::function<void(::grpc::Status)> func) {
469  test_unary_.reset(new TestServerCallbackUnary(this, std::move(func)));
470  }
471  bool test_status_set() const {
472  return (test_unary_ != nullptr) && test_unary_->status_set();
473  }
474  ::grpc::Status test_status() const { return test_unary_->status(); }
475 
476  class TestServerCallbackUnary : public ::grpc::ServerCallbackUnary {
477  public:
478  TestServerCallbackUnary(ServerContextBase* ctx,
479  std::function<void(::grpc::Status)> func)
480  : reactor_(ctx->DefaultReactor()), func_(std::move(func)) {
481  this->BindReactor(reactor_);
482  }
483  void Finish(::grpc::Status s) override {
484  status_ = s;
485  func_(std::move(s));
486  status_set_.store(true, std::memory_order_release);
487  }
488  void SendInitialMetadata() override {}
489 
490  bool status_set() const {
491  return status_set_.load(std::memory_order_acquire);
492  }
493  ::grpc::Status status() const { return status_; }
494 
495  private:
496  void CallOnDone() override {}
497  ::grpc::internal::ServerReactor* reactor() override { return reactor_; }
498 
499  ::grpc::ServerUnaryReactor* const reactor_;
500  std::atomic_bool status_set_{false};
501  ::grpc::Status status_;
502  const std::function<void(::grpc::Status s)> func_;
503  };
504 
505  typename std::aligned_storage<sizeof(Reactor), alignof(Reactor)>::type
506  default_reactor_;
507  std::atomic_bool default_reactor_used_{false};
508  std::unique_ptr<TestServerCallbackUnary> test_unary_;
509 };
510 
528  public:
529  ServerContext() {} // for async calls
530 
548 
549  // Sync/CQ-based Async ServerContext only
551 
552  private:
553  // Constructor for internal use by server only
554  friend class ::grpc::Server;
556  : ServerContextBase(deadline, arr) {}
557 
558  // CallbackServerContext only
561 
563  ServerContext(const ServerContext&) = delete;
564  ServerContext& operator=(const ServerContext&) = delete;
565 };
566 
568  public:
572 
590 
591  // CallbackServerContext only
594 
595  private:
596  // Sync/CQ-based Async ServerContext only
598 
601  CallbackServerContext& operator=(const CallbackServerContext&) = delete;
602 };
603 
604 } // namespace grpc
605 
606 static_assert(
607  std::is_base_of<::grpc::ServerContextBase, ::grpc::ServerContext>::value,
608  "improper base class");
609 static_assert(std::is_base_of<::grpc::ServerContextBase,
610  ::grpc::CallbackServerContext>::value,
611  "improper base class");
612 static_assert(sizeof(::grpc::ServerContextBase) ==
613  sizeof(::grpc::ServerContext),
614  "wrong size");
615 static_assert(sizeof(::grpc::ServerContextBase) ==
616  sizeof(::grpc::CallbackServerContext),
617  "wrong size");
618 
619 #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: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::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:527
time.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:850
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:567
grpc::internal::CallOpSendMessage
Definition: call_op_set.h:287
grpc_metadata_array
Definition: grpc_types.h:541
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:125
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:217
grpc::ServerContextBase::ServerContextBase
ServerContextBase()
Constructors for use by derived classes.
grpc::experimental::ServerContextBase
::grpc::ServerContextBase ServerContextBase
Definition: server_context.h:102
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:103
grpc::Status
Did it work? If it didn't, why?
Definition: status.h:31
grpc_metadata
A single metadata element.
Definition: grpc_types.h:497
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:130
grpc::ServerContextBase::raw_deadline
gpr_timespec raw_deadline() const
Return a gpr_timespec representation of the server call's deadline.
Definition: server_context.h:135
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:262
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:242
grpc::ServerContextBase::DefaultReactor
::grpc::ServerUnaryReactor * DefaultReactor()
Get a library-owned default unary reactor for use in minimal reaction cases.
Definition: server_context.h:317
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:571
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::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:221
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:288
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:301
create_auth_context.h
grpc::ServerContextBase::peer
std::string peer() const
Return the peer uri in a string.
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:96
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:297
grpc::ServerContext::ServerContext
ServerContext()
Definition: server_context.h:529
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:248
grpc::ServerContextBase::c_call
grpc_call * c_call()
Should be used for framework-level extensions only.
Definition: server_context.h:280
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:234
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:227