GRPC C++  1.39.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>
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>
89 template <class ServiceType, class RequestType, class ResponseType>
91 class ServerReactor;
92 template <class Streamer, bool WriteNeeded>
94 template <::grpc::StatusCode code>
95 class ErrorMethodHandler;
96 } // namespace internal
97 
98 class ClientContext;
99 class CompletionQueue;
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 
114 
115 namespace internal {
116 class Call;
117 } // namespace internal
118 
119 namespace testing {
120 class InteropServerContextInspector;
121 class ServerContextTestSpouse;
122 class DefaultReactorTestPeer;
123 } // namespace testing
124 
127  public:
129 
131  std::chrono::system_clock::time_point deadline() const {
133  }
134 
136  gpr_timespec raw_deadline() const { return deadline_; }
137 
157  void AddInitialMetadata(const std::string& key, const std::string& value);
158 
178  void AddTrailingMetadata(const std::string& key, const std::string& value);
179 
191  bool IsCancelled() const;
192 
211  void TryCancel() const;
212 
222  const std::multimap<grpc::string_ref, grpc::string_ref>& client_metadata()
223  const {
224  return *client_metadata_.map();
225  }
226 
229  return compression_level_;
230  }
231 
236  compression_level_set_ = true;
237  compression_level_ = level;
238  }
239 
243  bool compression_level_set() const { return compression_level_set_; }
244 
250  return compression_algorithm_;
251  }
256 
258  void SetLoadReportingCosts(const std::vector<std::string>& cost_data);
259 
263  std::shared_ptr<const ::grpc::AuthContext> auth_context() const {
264  if (auth_context_ == nullptr) {
265  auth_context_ = ::grpc::CreateAuthContext(call_.call);
266  }
267  return auth_context_;
268  }
269 
274  std::string peer() const;
275 
277  const struct census_context* census_context() const;
278 
281  grpc_call* c_call() { return call_.call; }
282 
283  protected:
289  void AsyncNotifyWhenDone(void* tag) {
290  has_notify_when_done_tag_ = true;
291  async_notify_when_done_tag_ = tag;
292  }
293 
297  RpcAllocatorState* GetRpcAllocatorState() { return message_allocator_state_; }
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 
337  context_allocator_ = context_allocator;
338  }
339 
340  ContextAllocator* context_allocator() const { return context_allocator_; }
341 
342  private:
343  friend class ::grpc::testing::InteropServerContextInspector;
344  friend class ::grpc::testing::ServerContextTestSpouse;
345  friend class ::grpc::testing::DefaultReactorTestPeer;
346  friend class ::grpc::ServerInterface;
347  friend class ::grpc::Server;
348  template <class W, class R>
349  friend class ::grpc::ServerAsyncReader;
350  template <class W>
351  friend class ::grpc::ServerAsyncWriter;
352  template <class W>
353  friend class ::grpc::ServerAsyncResponseWriter;
354  template <class W, class R>
355  friend class ::grpc::ServerAsyncReaderWriter;
356  template <class R>
357  friend class ::grpc::ServerReader;
358  template <class W>
359  friend class ::grpc::ServerWriter;
360  template <class W, class R>
361  friend class ::grpc::internal::ServerReaderWriterBody;
362  template <class ResponseType>
364  const internal::MethodHandler::HandlerParameter& param, ResponseType* rsp,
365  Status& status);
366  template <class ServiceType, class RequestType, class ResponseType,
367  class BaseRequestType, class BaseResponseType>
368  friend class ::grpc::internal::RpcMethodHandler;
369  template <class ServiceType, class RequestType, class ResponseType>
370  friend class ::grpc::internal::ClientStreamingHandler;
371  template <class ServiceType, class RequestType, class ResponseType>
372  friend class ::grpc::internal::ServerStreamingHandler;
373  template <class Streamer, bool WriteNeeded>
374  friend class ::grpc::internal::TemplatedBidiStreamingHandler;
375  template <class RequestType, class ResponseType>
376  friend class ::grpc::internal::CallbackUnaryHandler;
377  template <class RequestType, class ResponseType>
378  friend class ::grpc::internal::CallbackClientStreamingHandler;
379  template <class RequestType, class ResponseType>
380  friend class ::grpc::internal::CallbackServerStreamingHandler;
381  template <class RequestType, class ResponseType>
382  friend class ::grpc::internal::CallbackBidiHandler;
383  template <::grpc::StatusCode code>
384  friend class ::grpc::internal::ErrorMethodHandler;
385  template <class Base>
386  friend class ::grpc::internal::FinishOnlyReactor;
387  friend class ::grpc::ClientContext;
388  friend class ::grpc::GenericServerContext;
389  friend class ::grpc::GenericCallbackServerContext;
390 
393  ServerContextBase& operator=(const ServerContextBase&);
394 
395  class CompletionOp;
396 
397  void BeginCompletionOp(
398  ::grpc::internal::Call* call, std::function<void(bool)> callback,
399  ::grpc::internal::ServerCallbackCall* callback_controller);
401  ::grpc::internal::CompletionQueueTag* GetCompletionOpTag();
402 
403  void set_call(grpc_call* call) { call_.call = call; }
404 
405  void BindDeadlineAndMetadata(gpr_timespec deadline, grpc_metadata_array* arr);
406 
407  uint32_t initial_metadata_flags() const { return 0; }
408 
409  ::grpc::experimental::ServerRpcInfo* set_server_rpc_info(
410  const char* method, ::grpc::internal::RpcMethod::RpcType type,
411  const std::vector<std::unique_ptr<
413  if (!creators.empty()) {
414  rpc_info_ = new ::grpc::experimental::ServerRpcInfo(this, method, type);
415  rpc_info_->RegisterInterceptors(creators);
416  }
417  return rpc_info_;
418  }
419 
420  void set_message_allocator_state(RpcAllocatorState* allocator_state) {
421  message_allocator_state_ = allocator_state;
422  }
423 
424  void MaybeMarkCancelledOnRead();
425 
426  struct CallWrapper {
427  ~CallWrapper();
428 
429  grpc_call* call = nullptr;
430  };
431 
432  // NOTE: call_ must be the first data member of this object so that its
433  // destructor is the last to be called, since its destructor may unref
434  // the underlying core call which holds the arena that may be used to
435  // hold this object.
436  CallWrapper call_;
437 
438  CompletionOp* completion_op_ = nullptr;
439  bool has_notify_when_done_tag_ = false;
440  void* async_notify_when_done_tag_ = nullptr;
442 
443  gpr_timespec deadline_;
444  ::grpc::CompletionQueue* cq_ = nullptr;
445  bool sent_initial_metadata_ = false;
446  mutable std::shared_ptr<const ::grpc::AuthContext> auth_context_;
447  mutable ::grpc::internal::MetadataMap client_metadata_;
448  std::multimap<std::string, std::string> initial_metadata_;
449  std::multimap<std::string, std::string> trailing_metadata_;
450 
451  bool compression_level_set_ = false;
452  grpc_compression_level compression_level_;
453  grpc_compression_algorithm compression_algorithm_;
454 
457  pending_ops_;
458  bool has_pending_ops_ = false;
459 
460  ::grpc::experimental::ServerRpcInfo* rpc_info_ = nullptr;
461  RpcAllocatorState* message_allocator_state_ = nullptr;
462  ContextAllocator* context_allocator_ = nullptr;
463 
464  class Reactor : public ::grpc::ServerUnaryReactor {
465  public:
466  void OnCancel() override {}
467  void OnDone() override {}
468  // Override InternalInlineable for this class since its reactions are
469  // trivial and thus do not need to be run from the executor (triggering a
470  // thread hop). This should only be used by internal reactors (thus the
471  // name) and not by user application code.
472  bool InternalInlineable() override { return true; }
473  };
474 
475  void SetupTestDefaultReactor(std::function<void(::grpc::Status)> func) {
476  // NOLINTNEXTLINE(modernize-make-unique)
477  test_unary_.reset(new TestServerCallbackUnary(this, std::move(func)));
478  }
479  bool test_status_set() const {
480  return (test_unary_ != nullptr) && test_unary_->status_set();
481  }
482  ::grpc::Status test_status() const { return test_unary_->status(); }
483 
484  class TestServerCallbackUnary : public ::grpc::ServerCallbackUnary {
485  public:
486  TestServerCallbackUnary(ServerContextBase* ctx,
487  std::function<void(::grpc::Status)> func)
488  : reactor_(ctx->DefaultReactor()), func_(std::move(func)) {
489  this->BindReactor(reactor_);
490  }
491  void Finish(::grpc::Status s) override {
492  status_ = s;
493  func_(std::move(s));
494  status_set_.store(true, std::memory_order_release);
495  }
496  void SendInitialMetadata() override {}
497 
498  bool status_set() const {
499  return status_set_.load(std::memory_order_acquire);
500  }
501  ::grpc::Status status() const { return status_; }
502 
503  private:
504  void CallOnDone() override {}
505  ::grpc::internal::ServerReactor* reactor() override { return reactor_; }
506 
507  ::grpc::ServerUnaryReactor* const reactor_;
508  std::atomic_bool status_set_{false};
509  ::grpc::Status status_;
510  const std::function<void(::grpc::Status s)> func_;
511  };
512 
513  typename std::aligned_storage<sizeof(Reactor), alignof(Reactor)>::type
514  default_reactor_;
515  std::atomic_bool default_reactor_used_{false};
516 
517  std::atomic_bool marked_cancelled_{false};
518 
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 
603 
604  // CallbackServerContext only
607 
608  private:
609  // Sync/CQ-based Async ServerContext only
611 
614  CallbackServerContext& operator=(const CallbackServerContext&) = delete;
615 };
616 
623  public:
624  virtual ~ContextAllocator() {}
625 
626  virtual CallbackServerContext* NewCallbackServerContext() { return nullptr; }
627 
629  return nullptr;
630  }
631 
632  virtual void Release(CallbackServerContext*) {}
633 
635 };
636 
637 } // namespace grpc
638 
639 static_assert(
640  std::is_base_of<::grpc::ServerContextBase, ::grpc::ServerContext>::value,
641  "improper base class");
642 static_assert(std::is_base_of<::grpc::ServerContextBase,
643  ::grpc::CallbackServerContext>::value,
644  "improper base class");
645 static_assert(sizeof(::grpc::ServerContextBase) ==
646  sizeof(::grpc::ServerContext),
647  "wrong size");
648 static_assert(sizeof(::grpc::ServerContextBase) ==
649  sizeof(::grpc::CallbackServerContext),
650  "wrong size");
651 
652 #endif // GRPCPP_IMPL_CODEGEN_SERVER_CONTEXT_H
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
Definition: server_context.h:578
CallbackServerContext()
Public constructors are for direct use only by mocking tests.
Definition: server_context.h:582
A ClientContext allows the person implementing a service client to:
Definition: client_context.h:193
A thin wrapper around grpc_completion_queue (see src/core/lib/surface/completion_queue....
Definition: completion_queue.h:102
A CallbackServerContext allows users to use the contents of the CallbackServerContext or GenericCallb...
Definition: server_context.h:622
virtual void Release(GenericCallbackServerContext *)
Definition: server_context.h:634
virtual ~ContextAllocator()
Definition: server_context.h:624
virtual void Release(CallbackServerContext *)
Definition: server_context.h:632
virtual CallbackServerContext * NewCallbackServerContext()
Definition: server_context.h:626
virtual GenericCallbackServerContext * NewGenericCallbackServerContext()
Definition: server_context.h:628
Definition: async_generic_service.h:87
Definition: async_generic_service.h:39
Definition: message_allocator.h:26
Definition: server_callback.h:191
void BindReactor(Reactor *reactor)
Definition: server_callback.h:201
Base class of ServerContext. Experimental until callback API is final.
Definition: server_context.h:126
void set_context_allocator(ContextAllocator *context_allocator)
Definition: server_context.h:336
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:222
std::shared_ptr< const ::grpc::AuthContext > auth_context() const
Return the authentication context for this server call.
Definition: server_context.h:263
void set_compression_algorithm(grpc_compression_algorithm algorithm)
Set algorithm to be the compression algorithm used for the server call.
::grpc::ServerUnaryReactor * DefaultReactor()
Get a library-owned default unary reactor for use in minimal reaction cases.
Definition: server_context.h:315
void set_compression_level(grpc_compression_level level)
Set level to be the compression level used for the server call.
Definition: server_context.h:235
std::string peer() const
Return the peer uri in a string.
grpc_compression_algorithm compression_algorithm() const
Return the compression algorithm the server call will request be used.
Definition: server_context.h:249
void TryCancel() const
Cancel the Call from the server.
void SetLoadReportingCosts(const std::vector< std::string > &cost_data)
Set the serialized load reporting costs in cost_data for the call.
ServerContextBase()
Constructors for use by derived classes.
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:243
std::chrono::system_clock::time_point deadline() const
Return the deadline for the server call.
Definition: server_context.h:131
const struct census_context * census_context() const
Get the census context associated with this server call.
void AddInitialMetadata(const std::string &key, const std::string &value)
Add the (key, value) pair to the initial metadata associated with a server call.
RpcAllocatorState * GetRpcAllocatorState()
NOTE: This is an API for advanced users who need custom allocators.
Definition: server_context.h:297
gpr_timespec raw_deadline() const
Return a gpr_timespec representation of the server call's deadline.
Definition: server_context.h:136
grpc_call * c_call()
Should be used for framework-level extensions only.
Definition: server_context.h:281
grpc_compression_level compression_level() const
Return the compression algorithm to be used by the server call.
Definition: server_context.h:228
void AsyncNotifyWhenDone(void *tag)
Async only.
Definition: server_context.h:289
ContextAllocator * context_allocator() const
Definition: server_context.h:340
void AddTrailingMetadata(const std::string &key, const std::string &value)
Add the (key, value) pair to the initial metadata associated with a server call.
bool IsCancelled() const
Return whether this RPC failed before the server could provide its status back to the client.
ServerContextBase(gpr_timespec deadline, grpc_metadata_array *arr)
A ServerContext or CallbackServerContext allows the code implementing a service handler to:
Definition: server_context.h:538
ServerContext()
Definition: server_context.h:540
std::chrono::system_clock::time_point deadline() const
Return the deadline for the server call.
Definition: server_context.h:131
Represents a gRPC server.
Definition: server.h:59
Definition: server_interface.h:59
Definition: server_callback.h:697
Did it work? If it didn't, why?
Definition: status.h:31
ServerRpcInfo represents the state of a particular RPC as it appears to an interceptor.
Definition: server_interceptor.h:56
Straightforward wrapping of the C call object.
Definition: call.h:35
Definition: call_op_set.h:212
Definition: call_op_set.h:282
Primary implementation of CallOpSetInterface.
Definition: call_op_set.h:867
CallbackWithSuccessTag can be reused multiple times, and will be used in this fashion for streaming o...
Definition: callback_common.h:135
An interface allowing implementors to process and filter event tags.
Definition: completion_queue_tag.h:26
General method handler class for errors that prevent real method use e.g., handle unknown method by r...
Definition: method_handler.h:358
Definition: server_callback.h:768
std::multimap< grpc::string_ref, grpc::string_ref > * map()
Definition: metadata_map.h:66
A wrapper class of an application provided rpc method handler.
Definition: method_handler.h:98
RpcType
Definition: rpc_method.h:31
The base class of ServerCallbackUnary etc.
Definition: server_callback.h:73
Definition: server_callback.h:49
Definition: sync_stream.h:708
A wrapper class of an application provided server streaming handler.
Definition: method_handler.h:189
A wrapper class of an application provided bidi-streaming handler.
Definition: method_handler.h:262
grpc_compression_level
Compression levels allow a party with knowledge of its peer's accepted encodings to request compressi...
Definition: compression_types.h:71
grpc_compression_algorithm
The various compression algorithms supported by gRPC (not sorted by compression level)
Definition: compression_types.h:57
struct grpc_call grpc_call
A Call represents an RPC.
Definition: grpc_types.h:70
::grpc::ServerContextBase ServerContextBase
Definition: server_context.h:108
::grpc::CallbackServerContext CallbackServerContext
Definition: server_context.h:109
void UnaryRunHandlerHelper(const MethodHandler::HandlerParameter &, ResponseType *, Status &)
void UnaryRunHandlerHelper(const ::grpc::internal::MethodHandler::HandlerParameter &, ResponseType *, ::grpc::Status &)
An Alarm posts the user-provided tag to its associated completion queue or invokes the user-provided ...
Definition: alarm.h:33
std::chrono::system_clock::time_point Timespec2Timepoint(gpr_timespec t)
std::shared_ptr< const AuthContext > CreateAuthContext(grpc_call *call)
Definition: async_unary_call.h:398
Analogous to struct timespec.
Definition: gpr_types.h:47
Definition: rpc_service_method.h:41
Definition: grpc_types.h:563
A single metadata element.
Definition: grpc_types.h:519