GRPC C++  1.85.0
method_handler.h
Go to the documentation of this file.
1 //
2 //
3 // Copyright 2015 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_SUPPORT_METHOD_HANDLER_H
20 #define GRPCPP_SUPPORT_METHOD_HANDLER_H
21 
22 #include <grpc/byte_buffer.h>
26 
27 #include "absl/base/optimization.h"
28 #include "absl/log/absl_check.h"
29 
30 namespace grpc {
31 
32 namespace internal {
33 
34 // Invoke the method handler, fill in the status, and
35 // return whether or not we finished safely (without an exception).
36 // Note that exception handling is 0-cost in most compiler/library
37 // implementations (except when an exception is actually thrown),
38 // so this process doesn't require additional overhead in the common case.
39 // Additionally, we don't need to return if we caught an exception or not;
40 // the handling is the same in either case.
41 template <class Callable>
43 #if GRPC_ALLOW_EXCEPTIONS
44  try {
45  return handler();
46  } catch (...) {
48  "Unexpected error in RPC handling");
49  }
50 #else // GRPC_ALLOW_EXCEPTIONS
51  return handler();
52 #endif // GRPC_ALLOW_EXCEPTIONS
53 }
54 
58 
59 template <class ResponseType>
61  ResponseType* rsp, grpc::Status& status) {
62  ABSL_CHECK(!param.server_context->sent_initial_metadata_);
66  ops;
67  ops.SendInitialMetadata(&param.server_context->initial_metadata_,
68  param.server_context->initial_metadata_flags());
70  ops.set_compression_level(param.server_context->compression_level());
71  }
72  if (status.ok()) {
73  status = ops.SendMessagePtr(rsp, param.server_context->memory_allocator());
74  }
75  ops.ServerSendStatus(&param.server_context->trailing_metadata_, status);
76  ops.FillOps(param.call);
77  param.call->cq()->Pluck(&ops);
78 }
79 
83 template <class RequestType>
85  RequestType* request) {
86  grpc::ByteBuffer buf;
87  buf.set_buffer(req);
88  *status = grpc::Deserialize(&buf, static_cast<RequestType*>(request));
89  buf.Release();
90  if (status->ok()) {
91  return request;
92  }
93  return nullptr;
94 }
95 
97 template <class ServiceType, class RequestType, class ResponseType,
98  class BaseRequestType = RequestType,
99  class BaseResponseType = ResponseType>
100 class RpcMethodHandler : public grpc::internal::MethodHandler {
101  public:
103  std::function<grpc::Status(ServiceType*, grpc::ServerContext*,
104  const RequestType*, ResponseType*)>
105  func,
106  ServiceType* service)
107  : func_(func), service_(service) {}
108 
109  void RunHandler(const HandlerParameter& param) final {
110  ResponseType rsp;
111  grpc::Status status = param.status;
112  if (status.ok()) {
113  status = CatchingFunctionHandler([this, &param, &rsp] {
114  return func_(service_,
115  static_cast<grpc::ServerContext*>(param.server_context),
116  static_cast<RequestType*>(param.request), &rsp);
117  });
118  static_cast<RequestType*>(param.request)->~RequestType();
119  }
120  UnaryRunHandlerHelper(param, static_cast<BaseResponseType*>(&rsp), status);
121  }
122 
124  grpc::Status* status, void** /*handler_data*/) final {
125  auto* request =
126  new (grpc_call_arena_alloc(call, sizeof(RequestType))) RequestType;
127  void* result = UnaryDeserializeHelper(
128  req, status, static_cast<BaseRequestType*>(request));
129  if (ABSL_PREDICT_FALSE(result == nullptr)) {
130  request->~RequestType();
131  }
132  return result;
133  }
134 
135  private:
137  std::function<grpc::Status(ServiceType*, grpc::ServerContext*,
138  const RequestType*, ResponseType*)>
139  func_;
140  // The class the above handler function lives in.
141  ServiceType* service_;
142 };
143 
145 template <class ServiceType, class RequestType, class ResponseType>
146 class ClientStreamingHandler : public grpc::internal::MethodHandler {
147  public:
149  std::function<grpc::Status(ServiceType*, grpc::ServerContext*,
150  ServerReader<RequestType>*, ResponseType*)>
151  func,
152  ServiceType* service)
153  : func_(func), service_(service) {}
154 
155  void RunHandler(const HandlerParameter& param) final {
157  param.call, static_cast<grpc::ServerContext*>(param.server_context));
158  ResponseType rsp;
159  grpc::Status status =
160  CatchingFunctionHandler([this, &param, &reader, &rsp] {
161  return func_(service_,
162  static_cast<grpc::ServerContext*>(param.server_context),
163  &reader, &rsp);
164  });
165 
169  ops;
170  if (!param.server_context->sent_initial_metadata_) {
171  ops.SendInitialMetadata(&param.server_context->initial_metadata_,
172  param.server_context->initial_metadata_flags());
173  if (param.server_context->compression_level_set()) {
174  ops.set_compression_level(param.server_context->compression_level());
175  }
176  }
177  if (status.ok()) {
178  status =
179  ops.SendMessagePtr(&rsp, param.server_context->memory_allocator());
180  }
181  ops.ServerSendStatus(&param.server_context->trailing_metadata_, status);
182  ops.FillOps(param.call);
183  param.call->cq()->Pluck(&ops);
184  }
185 
186  private:
187  std::function<grpc::Status(ServiceType*, grpc::ServerContext*,
188  ServerReader<RequestType>*, ResponseType*)>
189  func_;
190  ServiceType* service_;
191 };
192 
194 template <class ServiceType, class RequestType, class ResponseType>
195 class ServerStreamingHandler : public grpc::internal::MethodHandler {
196  public:
198  ServiceType*, grpc::ServerContext*,
199  const RequestType*, ServerWriter<ResponseType>*)>
200  func,
201  ServiceType* service)
202  : func_(func), service_(service) {}
203 
204  void RunHandler(const HandlerParameter& param) final {
205  grpc::Status status = param.status;
206  if (status.ok()) {
208  param.call, static_cast<grpc::ServerContext*>(param.server_context));
209  status = CatchingFunctionHandler([this, &param, &writer] {
210  return func_(service_,
211  static_cast<grpc::ServerContext*>(param.server_context),
212  static_cast<RequestType*>(param.request), &writer);
213  });
214  static_cast<RequestType*>(param.request)->~RequestType();
215  }
216 
219  ops;
220  if (!param.server_context->sent_initial_metadata_) {
221  ops.SendInitialMetadata(&param.server_context->initial_metadata_,
222  param.server_context->initial_metadata_flags());
223  if (param.server_context->compression_level_set()) {
224  ops.set_compression_level(param.server_context->compression_level());
225  }
226  }
227  ops.ServerSendStatus(&param.server_context->trailing_metadata_, status);
228  ops.FillOps(param.call);
229  if (param.server_context->has_pending_ops_) {
230  param.call->cq()->Pluck(&param.server_context->pending_ops_);
231  }
232  param.call->cq()->Pluck(&ops);
233  }
234 
236  grpc::Status* status, void** /*handler_data*/) final {
237  grpc::ByteBuffer buf;
238  buf.set_buffer(req);
239  auto* request =
240  new (grpc_call_arena_alloc(call, sizeof(RequestType))) RequestType();
241  *status = grpc::Deserialize(&buf, request);
242  buf.Release();
243  if (status->ok()) {
244  return request;
245  }
246  request->~RequestType();
247  return nullptr;
248  }
249 
250  private:
251  std::function<grpc::Status(ServiceType*, grpc::ServerContext*,
252  const RequestType*, ServerWriter<ResponseType>*)>
253  func_;
254  ServiceType* service_;
255 };
256 
264 template <class Streamer, bool WriteNeeded>
265 class TemplatedBidiStreamingHandler : public grpc::internal::MethodHandler {
266  public:
268  std::function<grpc::Status(grpc::ServerContext*, Streamer*)> func)
269  : func_(func), write_needed_(WriteNeeded) {}
270 
271  void RunHandler(const HandlerParameter& param) final {
272  Streamer stream(param.call,
273  static_cast<grpc::ServerContext*>(param.server_context));
274  grpc::Status status = CatchingFunctionHandler([this, &param, &stream] {
275  return func_(static_cast<grpc::ServerContext*>(param.server_context),
276  &stream);
277  });
278 
281  ops;
282  if (!param.server_context->sent_initial_metadata_) {
283  ops.SendInitialMetadata(&param.server_context->initial_metadata_,
284  param.server_context->initial_metadata_flags());
285  if (param.server_context->compression_level_set()) {
286  ops.set_compression_level(param.server_context->compression_level());
287  }
288  if (write_needed_ && status.ok()) {
289  // If we needed a write but never did one, we need to mark the
290  // status as a fail
292  "Service did not provide response message");
293  }
294  }
295  ops.ServerSendStatus(&param.server_context->trailing_metadata_, status);
296  ops.FillOps(param.call);
297  if (param.server_context->has_pending_ops_) {
298  param.call->cq()->Pluck(&param.server_context->pending_ops_);
299  }
300  param.call->cq()->Pluck(&ops);
301  }
302 
303  private:
304  std::function<grpc::Status(grpc::ServerContext*, Streamer*)> func_;
305  const bool write_needed_;
306 };
307 
308 template <class ServiceType, class RequestType, class ResponseType>
309 class BidiStreamingHandler
310  : public TemplatedBidiStreamingHandler<
311  ServerReaderWriter<ResponseType, RequestType>, false> {
312  public:
314  ServiceType*, grpc::ServerContext*,
316  func,
317  ServiceType* service)
318  // TODO(vjpai): When gRPC supports C++14, move-capture func in the below
320  ServerReaderWriter<ResponseType, RequestType>, false>(
321  [func, service](
322  grpc::ServerContext* ctx,
323  ServerReaderWriter<ResponseType, RequestType>* streamer) {
324  return func(service, ctx, streamer);
325  }) {}
326 };
327 
328 template <class RequestType, class ResponseType>
331  ServerUnaryStreamer<RequestType, ResponseType>, true> {
332  public:
334  std::function<
337  func)
339  ServerUnaryStreamer<RequestType, ResponseType>, true>(
340  std::move(func)) {}
341 };
342 
343 template <class RequestType, class ResponseType>
346  ServerSplitStreamer<RequestType, ResponseType>, false> {
347  public:
349  std::function<
352  func)
354  ServerSplitStreamer<RequestType, ResponseType>, false>(
355  std::move(func)) {}
356 };
357 
360 template <grpc::StatusCode code>
361 class ErrorMethodHandler : public grpc::internal::MethodHandler {
362  public:
363  explicit ErrorMethodHandler(const std::string& message) : message_(message) {}
364 
365  template <class T>
366  static void FillOps(grpc::ServerContextBase* context,
367  const std::string& message, T* ops) {
368  grpc::Status status(code, message);
369  if (!context->sent_initial_metadata_) {
370  ops->SendInitialMetadata(&context->initial_metadata_,
371  context->initial_metadata_flags());
372  if (context->compression_level_set()) {
373  ops->set_compression_level(context->compression_level());
374  }
375  context->MarkInitialMetadataSent();
376  }
377  ops->ServerSendStatus(&context->trailing_metadata_, status);
378  }
379 
380  void RunHandler(const HandlerParameter& param) final {
383  ops;
384  FillOps(param.server_context, message_, &ops);
385  ops.FillOps(param.call);
386  param.call->cq()->Pluck(&ops);
387  }
388 
389  void* Deserialize(grpc_call* /*call*/, grpc_byte_buffer* req,
390  grpc::Status* /*status*/, void** /*handler_data*/) final {
391  // We have to destroy any request payload
392  if (req != nullptr) {
394  }
395  return nullptr;
396  }
397 
398  private:
399  const std::string message_;
400 };
401 
402 typedef ErrorMethodHandler<grpc::StatusCode::UNIMPLEMENTED>
406 
407 } // namespace internal
408 } // namespace grpc
409 
410 #endif // GRPCPP_SUPPORT_METHOD_HANDLER_H
grpc::internal::Call::cq
grpc::CompletionQueue * cq() const
Definition: call.h:56
grpc::internal::ClientStreamingHandler::RunHandler
void RunHandler(const HandlerParameter &param) final
Definition: method_handler.h:155
grpc::internal::ServerStreamingHandler::ServerStreamingHandler
ServerStreamingHandler(std::function< grpc::Status(ServiceType *, grpc::ServerContext *, const RequestType *, ServerWriter< ResponseType > *)> func, ServiceType *service)
Definition: method_handler.h:197
grpc_call_arena_alloc
GRPCAPI void * grpc_call_arena_alloc(grpc_call *call, size_t size)
Allocate memory in the grpc_call arena: this memory is automatically discarded at call completion.
grpc::ServerContext
A ServerContext or CallbackServerContext allows the code implementing a service handler to:
Definition: server_context.h:701
grpc::internal::CallOpServerSendStatus
Definition: call_op_set.h:656
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: completion_queue.h:97
grpc::Deserialize
auto Deserialize(BufferPtr buffer, Message *msg)
Definition: serialization_traits.h:120
grpc::internal::CallOpSendMessage
Definition: call_op_set.h:287
grpc::internal::TemplatedBidiStreamingHandler::TemplatedBidiStreamingHandler
TemplatedBidiStreamingHandler(std::function< grpc::Status(grpc::ServerContext *, Streamer *)> func)
Definition: method_handler.h:267
grpc::internal::ErrorMethodHandler
General method handler class for errors that prevent real method use e.g., handle unknown method by r...
Definition: completion_queue.h:81
grpc::internal::MethodHandler::HandlerParameter
Definition: rpc_service_method.h:43
grpc::internal::ServerStreamingHandler::RunHandler
void RunHandler(const HandlerParameter &param) final
Definition: method_handler.h:204
grpc::ServerWriter
Synchronous (blocking) server-side API for doing for doing a server-streaming RPCs,...
Definition: completion_queue.h:62
grpc::internal::SplitServerStreamingHandler
Definition: method_handler.h:344
grpc::internal::ClientStreamingHandler::ClientStreamingHandler
ClientStreamingHandler(std::function< grpc::Status(ServiceType *, grpc::ServerContext *, ServerReader< RequestType > *, ResponseType *)> func, ServiceType *service)
Definition: method_handler.h:148
grpc_byte_buffer_destroy
GRPCAPI void grpc_byte_buffer_destroy(grpc_byte_buffer *bb)
Destroys byte_buffer deallocating all its memory.
grpc::internal::TemplatedBidiStreamingHandler::RunHandler
void RunHandler(const HandlerParameter &param) final
Definition: method_handler.h:271
grpc::internal::RpcMethodHandler::RpcMethodHandler
RpcMethodHandler(std::function< grpc::Status(ServiceType *, grpc::ServerContext *, const RequestType *, ResponseType *)> func, ServiceType *service)
Definition: method_handler.h:102
grpc::ServerContextBase
Base class of ServerContext.
Definition: server_context.h:193
rpc_service_method.h
grpc::internal::RpcMethodHandler::Deserialize
void * Deserialize(grpc_call *call, grpc_byte_buffer *req, grpc::Status *status, void **) final
Definition: method_handler.h:123
grpc::ServerContextBase::memory_allocator
grpc_event_engine::experimental::MemoryAllocator * memory_allocator()
Definition: server_context.h:369
grpc::internal::CallOpSendInitialMetadata
Definition: call_op_set.h:217
grpc::internal::CallOpServerSendStatus::ServerSendStatus
void ServerSendStatus(std::multimap< std::string, std::string > *trailing_metadata, const Status &status)
Definition: call_op_set.h:660
grpc::internal::MethodHandler::HandlerParameter::call
Call *const call
Definition: rpc_service_method.h:64
grpc::Status::ok
bool ok() const
Is the status OK?
Definition: status.h:124
grpc::ServerSplitStreamer
A class to represent a flow-controlled server-side streaming call.
Definition: sync_stream.h:901
grpc::Status
Did it work? If it didn't, why?
Definition: status.h:34
grpc::internal::ResourceExhaustedHandler
ErrorMethodHandler< grpc::StatusCode::RESOURCE_EXHAUSTED > ResourceExhaustedHandler
Definition: method_handler.h:405
grpc::ServerReader
Synchronous (blocking) server-side API for doing client-streaming RPCs, where the incoming message st...
Definition: completion_queue.h:60
grpc::internal::UnaryDeserializeHelper
void * UnaryDeserializeHelper(grpc_byte_buffer *, grpc::Status *, RequestType *)
A helper function with reduced templating to do deserializing.
Definition: method_handler.h:84
grpc_call
struct grpc_call grpc_call
A Call represents an RPC.
Definition: grpc_types.h:68
grpc_byte_buffer
Definition: grpc_types.h:41
grpc::ByteBuffer
A sequence of bytes.
Definition: byte_buffer.h:67
grpc::internal::BidiStreamingHandler::BidiStreamingHandler
BidiStreamingHandler(std::function< grpc::Status(ServiceType *, grpc::ServerContext *, ServerReaderWriter< ResponseType, RequestType > *)> func, ServiceType *service)
Definition: method_handler.h:313
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:320
grpc::internal::MethodHandler
Base class for running an RPC handler.
Definition: rpc_service_method.h:40
byte_buffer.h
grpc::ServerReaderWriter
Synchronous (blocking) server-side API for a bidirectional streaming call, where the incoming message...
Definition: sync_stream.h:794
grpc::internal::MethodHandler::HandlerParameter::server_context
grpc::ServerContextBase *const server_context
Definition: rpc_service_method.h:65
grpc::internal::TemplatedBidiStreamingHandler
A wrapper class of an application provided bidi-streaming handler.
Definition: completion_queue.h:79
sync_stream.h
byte_buffer.h
grpc::internal::ErrorMethodHandler::ErrorMethodHandler
ErrorMethodHandler(const std::string &message)
Definition: method_handler.h:363
std
Definition: async_unary_call.h:410
grpc::ServerContextBase::MarkInitialMetadataSent
void MarkInitialMetadataSent()
Definition: server_context.h:424
grpc::internal::ErrorMethodHandler::RunHandler
void RunHandler(const HandlerParameter &param) final
Definition: method_handler.h:380
grpc::internal::StreamedUnaryHandler::StreamedUnaryHandler
StreamedUnaryHandler(std::function< grpc::Status(grpc::ServerContext *, ServerUnaryStreamer< RequestType, ResponseType > *)> func)
Definition: method_handler.h:333
grpc::internal::ErrorMethodHandler::FillOps
static void FillOps(grpc::ServerContextBase *context, const std::string &message, T *ops)
Definition: method_handler.h:366
grpc::internal::CatchingFunctionHandler
::grpc::Status CatchingFunctionHandler(Callable &&handler)
Definition: method_handler.h:42
grpc::ServerUnaryStreamer
A class to represent a flow-controlled unary call.
Definition: sync_stream.h:835
grpc::internal::RpcMethodHandler::RunHandler
void RunHandler(const HandlerParameter &param) final
Definition: method_handler.h:109
grpc::UNKNOWN
@ UNKNOWN
Unknown error.
Definition: status_code_enum.h:37
grpc::internal::UnknownMethodHandler
ErrorMethodHandler< grpc::StatusCode::UNIMPLEMENTED > UnknownMethodHandler
Definition: method_handler.h:403
grpc::ByteBuffer::Release
void Release()
Forget underlying byte buffer without destroying Use this only for un-owned byte buffers.
Definition: byte_buffer.h:151
grpc::internal::StreamedUnaryHandler
Definition: method_handler.h:329
grpc::internal::UnaryRunHandlerHelper
void UnaryRunHandlerHelper(const grpc::internal::MethodHandler::HandlerParameter &, ResponseType *, grpc::Status &)
A helper function with reduced templating to do the common work needed to actually send the server re...
Definition: method_handler.h:60
grpc::protobuf::util::Status
::absl::Status Status
Definition: config_protobuf.h:107
grpc::internal::SplitServerStreamingHandler::SplitServerStreamingHandler
SplitServerStreamingHandler(std::function< grpc::Status(grpc::ServerContext *, ServerSplitStreamer< RequestType, ResponseType > *)> func)
Definition: method_handler.h:348
grpc::internal::ErrorMethodHandler::Deserialize
void * Deserialize(grpc_call *, grpc_byte_buffer *req, grpc::Status *, void **) final
Definition: method_handler.h:389
grpc::internal::ServerStreamingHandler::Deserialize
void * Deserialize(grpc_call *call, grpc_byte_buffer *req, grpc::Status *status, void **) final
Definition: method_handler.h:235
grpc::INTERNAL
@ INTERNAL
Internal errors.
Definition: status_code_enum.h:121
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:305