Debian Codegraph @

spm-cpp-include/grpcpp/support/method_handler.h

raw
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 <grpcpp/impl/codegen/core_codegen_interface.h>
23 #include <grpcpp/impl/rpc_service_method.h>
24 #include <grpcpp/support/byte_buffer.h>
25 #include <grpcpp/support/sync_stream.h>
26
27 namespace grpc {
28
29 namespace internal {
30
31 // Invoke the method handler, fill in the status, and
32 // return whether or not we finished safely (without an exception).
33 // Note that exception handling is 0-cost in most compiler/library
34 // implementations (except when an exception is actually thrown),
35 // so this process doesn't require additional overhead in the common case.
36 // Additionally, we don't need to return if we caught an exception or not;
37 // the handling is the same in either case.
38 template <class Callable>
39 ::grpc::Status CatchingFunctionHandler(Callable&& handler) {
40 #if GRPC_ALLOW_EXCEPTIONS
41 try {
42 return handler();
43 } catch (...) {
44 return grpc::Status(grpc::StatusCode::UNKNOWN,
45 "Unexpected error in RPC handling");
46 }
47 #else // GRPC_ALLOW_EXCEPTIONS
48 return handler();
49 #endif // GRPC_ALLOW_EXCEPTIONS
50 }
51
52 /// A helper function with reduced templating to do the common work needed to
53 /// actually send the server response. Uses non-const parameter for Status since
54 /// this should only ever be called from the end of the RunHandler method.
55
56 template <class ResponseType>
57 void UnaryRunHandlerHelper(const MethodHandler::HandlerParameter& param,
58 ResponseType* rsp, grpc::Status& status) {
59 GPR_CODEGEN_ASSERT(!param.server_context->sent_initial_metadata_);
60 grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
61 grpc::internal::CallOpSendMessage,
62 grpc::internal::CallOpServerSendStatus>
63 ops;
64 ops.SendInitialMetadata(&param.server_context->initial_metadata_,
65 param.server_context->initial_metadata_flags());
66 if (param.server_context->compression_level_set()) {
67 ops.set_compression_level(param.server_context->compression_level());
68 }
69 if (status.ok()) {
70 status = ops.SendMessagePtr(rsp);
71 }
72 ops.ServerSendStatus(&param.server_context->trailing_metadata_, status);
73 param.call->PerformOps(&ops);
74 param.call->cq()->Pluck(&ops);
75 }
76
77 /// A helper function with reduced templating to do deserializing.
78
79 template <class RequestType>
80 void* UnaryDeserializeHelper(grpc_byte_buffer* req, grpc::Status* status,
81 RequestType* request) {
82 grpc::ByteBuffer buf;
83 buf.set_buffer(req);
84 *status = grpc::SerializationTraits<RequestType>::Deserialize(
85 &buf, static_cast<RequestType*>(request));
86 buf.Release();
87 if (status->ok()) {
88 return request;
89 }
90 request->~RequestType();
91 return nullptr;
92 }
93
94 /// A wrapper class of an application provided rpc method handler.
95 template <class ServiceType, class RequestType, class ResponseType,
96 class BaseRequestType = RequestType,
97 class BaseResponseType = ResponseType>
98 class RpcMethodHandler : public grpc::internal::MethodHandler {
99 public:
100 RpcMethodHandler(
101 std::function<grpc::Status(ServiceType*, grpc::ServerContext*,
102 const RequestType*, ResponseType*)>
103 func,
104 ServiceType* service)
105 : func_(func), service_(service) {}
106
107 void RunHandler(const HandlerParameter& param) final {
108 ResponseType rsp;
109 grpc::Status status = param.status;
110 if (status.ok()) {
111 status = CatchingFunctionHandler([this, &param, &rsp] {
112 return func_(service_,
113 static_cast<grpc::ServerContext*>(param.server_context),
114 static_cast<RequestType*>(param.request), &rsp);
115 });
116 static_cast<RequestType*>(param.request)->~RequestType();
117 }
118 UnaryRunHandlerHelper(param, static_cast<BaseResponseType*>(&rsp), status);
119 }
120
121 void* Deserialize(grpc_call* call, grpc_byte_buffer* req,
122 grpc::Status* status, void** /*handler_data*/) final {
123 auto* request = new (grpc::g_core_codegen_interface->grpc_call_arena_alloc(
124 call, sizeof(RequestType))) RequestType;
125 return UnaryDeserializeHelper(req, status,
126 static_cast<BaseRequestType*>(request));
127 }
128
129 private:
130 /// Application provided rpc handler function.
131 std::function<grpc::Status(ServiceType*, grpc::ServerContext*,
132 const RequestType*, ResponseType*)>
133 func_;
134 // The class the above handler function lives in.
135 ServiceType* service_;
136 };
137
138 /// A wrapper class of an application provided client streaming handler.
139 template <class ServiceType, class RequestType, class ResponseType>
140 class ClientStreamingHandler : public grpc::internal::MethodHandler {
141 public:
142 ClientStreamingHandler(
143 std::function<grpc::Status(ServiceType*, grpc::ServerContext*,
144 ServerReader<RequestType>*, ResponseType*)>
145 func,
146 ServiceType* service)
147 : func_(func), service_(service) {}
148
149 void RunHandler(const HandlerParameter& param) final {
150 ServerReader<RequestType> reader(
151 param.call, static_cast<grpc::ServerContext*>(param.server_context));
152 ResponseType rsp;
153 grpc::Status status =
154 CatchingFunctionHandler([this, &param, &reader, &rsp] {
155 return func_(service_,
156 static_cast<grpc::ServerContext*>(param.server_context),
157 &reader, &rsp);
158 });
159
160 grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
161 grpc::internal::CallOpSendMessage,
162 grpc::internal::CallOpServerSendStatus>
163 ops;
164 if (!param.server_context->sent_initial_metadata_) {
165 ops.SendInitialMetadata(&param.server_context->initial_metadata_,
166 param.server_context->initial_metadata_flags());
167 if (param.server_context->compression_level_set()) {
168 ops.set_compression_level(param.server_context->compression_level());
169 }
170 }
171 if (status.ok()) {
172 status = ops.SendMessagePtr(&rsp);
173 }
174 ops.ServerSendStatus(&param.server_context->trailing_metadata_, status);
175 param.call->PerformOps(&ops);
176 param.call->cq()->Pluck(&ops);
177 }
178
179 private:
180 std::function<grpc::Status(ServiceType*, grpc::ServerContext*,
181 ServerReader<RequestType>*, ResponseType*)>
182 func_;
183 ServiceType* service_;
184 };
185
186 /// A wrapper class of an application provided server streaming handler.
187 template <class ServiceType, class RequestType, class ResponseType>
188 class ServerStreamingHandler : public grpc::internal::MethodHandler {
189 public:
190 ServerStreamingHandler(std::function<grpc::Status(
191 ServiceType*, grpc::ServerContext*,
192 const RequestType*, ServerWriter<ResponseType>*)>
193 func,
194 ServiceType* service)
195 : func_(func), service_(service) {}
196
197 void RunHandler(const HandlerParameter& param) final {
198 grpc::Status status = param.status;
199 if (status.ok()) {
200 ServerWriter<ResponseType> writer(
201 param.call, static_cast<grpc::ServerContext*>(param.server_context));
202 status = CatchingFunctionHandler([this, &param, &writer] {
203 return func_(service_,
204 static_cast<grpc::ServerContext*>(param.server_context),
205 static_cast<RequestType*>(param.request), &writer);
206 });
207 static_cast<RequestType*>(param.request)->~RequestType();
208 }
209
210 grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
211 grpc::internal::CallOpServerSendStatus>
212 ops;
213 if (!param.server_context->sent_initial_metadata_) {
214 ops.SendInitialMetadata(&param.server_context->initial_metadata_,
215 param.server_context->initial_metadata_flags());
216 if (param.server_context->compression_level_set()) {
217 ops.set_compression_level(param.server_context->compression_level());
218 }
219 }
220 ops.ServerSendStatus(&param.server_context->trailing_metadata_, status);
221 param.call->PerformOps(&ops);
222 if (param.server_context->has_pending_ops_) {
223 param.call->cq()->Pluck(&param.server_context->pending_ops_);
224 }
225 param.call->cq()->Pluck(&ops);
226 }
227
228 void* Deserialize(grpc_call* call, grpc_byte_buffer* req,
229 grpc::Status* status, void** /*handler_data*/) final {
230 grpc::ByteBuffer buf;
231 buf.set_buffer(req);
232 auto* request = new (grpc::g_core_codegen_interface->grpc_call_arena_alloc(
233 call, sizeof(RequestType))) RequestType();
234 *status =
235 grpc::SerializationTraits<RequestType>::Deserialize(&buf, request);
236 buf.Release();
237 if (status->ok()) {
238 return request;
239 }
240 request->~RequestType();
241 return nullptr;
242 }
243
244 private:
245 std::function<grpc::Status(ServiceType*, grpc::ServerContext*,
246 const RequestType*, ServerWriter<ResponseType>*)>
247 func_;
248 ServiceType* service_;
249 };
250
251 /// A wrapper class of an application provided bidi-streaming handler.
252 /// This also applies to server-streamed implementation of a unary method
253 /// with the additional requirement that such methods must have done a
254 /// write for status to be ok
255 /// Since this is used by more than 1 class, the service is not passed in.
256 /// Instead, it is expected to be an implicitly-captured argument of func
257 /// (through bind or something along those lines)
258 template <class Streamer, bool WriteNeeded>
259 class TemplatedBidiStreamingHandler : public grpc::internal::MethodHandler {
260 public:
261 explicit TemplatedBidiStreamingHandler(
262 std::function<grpc::Status(grpc::ServerContext*, Streamer*)> func)
263 : func_(func), write_needed_(WriteNeeded) {}
264
265 void RunHandler(const HandlerParameter& param) final {
266 Streamer stream(param.call,
267 static_cast<grpc::ServerContext*>(param.server_context));
268 grpc::Status status = CatchingFunctionHandler([this, &param, &stream] {
269 return func_(static_cast<grpc::ServerContext*>(param.server_context),
270 &stream);
271 });
272
273 grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
274 grpc::internal::CallOpServerSendStatus>
275 ops;
276 if (!param.server_context->sent_initial_metadata_) {
277 ops.SendInitialMetadata(&param.server_context->initial_metadata_,
278 param.server_context->initial_metadata_flags());
279 if (param.server_context->compression_level_set()) {
280 ops.set_compression_level(param.server_context->compression_level());
281 }
282 if (write_needed_ && status.ok()) {
283 // If we needed a write but never did one, we need to mark the
284 // status as a fail
285 status = grpc::Status(grpc::StatusCode::INTERNAL,
286 "Service did not provide response message");
287 }
288 }
289 ops.ServerSendStatus(&param.server_context->trailing_metadata_, status);
290 param.call->PerformOps(&ops);
291 if (param.server_context->has_pending_ops_) {
292 param.call->cq()->Pluck(&param.server_context->pending_ops_);
293 }
294 param.call->cq()->Pluck(&ops);
295 }
296
297 private:
298 std::function<grpc::Status(grpc::ServerContext*, Streamer*)> func_;
299 const bool write_needed_;
300 };
301
302 template <class ServiceType, class RequestType, class ResponseType>
303 class BidiStreamingHandler
304 : public TemplatedBidiStreamingHandler<
305 ServerReaderWriter<ResponseType, RequestType>, false> {
306 public:
307 BidiStreamingHandler(std::function<grpc::Status(
308 ServiceType*, grpc::ServerContext*,
309 ServerReaderWriter<ResponseType, RequestType>*)>
310 func,
311 ServiceType* service)
312 // TODO(vjpai): When gRPC supports C++14, move-capture func in the below
313 : TemplatedBidiStreamingHandler<
314 ServerReaderWriter<ResponseType, RequestType>, false>(
315 [func, service](
316 grpc::ServerContext* ctx,
317 ServerReaderWriter<ResponseType, RequestType>* streamer) {
318 return func(service, ctx, streamer);
319 }) {}
320 };
321
322 template <class RequestType, class ResponseType>
323 class StreamedUnaryHandler
324 : public TemplatedBidiStreamingHandler<
325 ServerUnaryStreamer<RequestType, ResponseType>, true> {
326 public:
327 explicit StreamedUnaryHandler(
328 std::function<
329 grpc::Status(grpc::ServerContext*,
330 ServerUnaryStreamer<RequestType, ResponseType>*)>
331 func)
332 : TemplatedBidiStreamingHandler<
333 ServerUnaryStreamer<RequestType, ResponseType>, true>(
334 std::move(func)) {}
335 };
336
337 template <class RequestType, class ResponseType>
338 class SplitServerStreamingHandler
339 : public TemplatedBidiStreamingHandler<
340 ServerSplitStreamer<RequestType, ResponseType>, false> {
341 public:
342 explicit SplitServerStreamingHandler(
343 std::function<
344 grpc::Status(grpc::ServerContext*,
345 ServerSplitStreamer<RequestType, ResponseType>*)>
346 func)
347 : TemplatedBidiStreamingHandler<
348 ServerSplitStreamer<RequestType, ResponseType>, false>(
349 std::move(func)) {}
350 };
351
352 /// General method handler class for errors that prevent real method use
353 /// e.g., handle unknown method by returning UNIMPLEMENTED error.
354 template <grpc::StatusCode code>
355 class ErrorMethodHandler : public grpc::internal::MethodHandler {
356 public:
357 explicit ErrorMethodHandler(const std::string& message) : message_(message) {}
358
359 template <class T>
360 static void FillOps(grpc::ServerContextBase* context,
361 const std::string& message, T* ops) {
362 grpc::Status status(code, message);
363 if (!context->sent_initial_metadata_) {
364 ops->SendInitialMetadata(&context->initial_metadata_,
365 context->initial_metadata_flags());
366 if (context->compression_level_set()) {
367 ops->set_compression_level(context->compression_level());
368 }
369 context->sent_initial_metadata_ = true;
370 }
371 ops->ServerSendStatus(&context->trailing_metadata_, status);
372 }
373
374 void RunHandler(const HandlerParameter& param) final {
375 grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
376 grpc::internal::CallOpServerSendStatus>
377 ops;
378 FillOps(param.server_context, message_, &ops);
379 param.call->PerformOps(&ops);
380 param.call->cq()->Pluck(&ops);
381 }
382
383 void* Deserialize(grpc_call* /*call*/, grpc_byte_buffer* req,
384 grpc::Status* /*status*/, void** /*handler_data*/) final {
385 // We have to destroy any request payload
386 if (req != nullptr) {
387 grpc::g_core_codegen_interface->grpc_byte_buffer_destroy(req);
388 }
389 return nullptr;
390 }
391
392 private:
393 const std::string message_;
394 };
395
396 typedef ErrorMethodHandler<grpc::StatusCode::UNIMPLEMENTED>
397 UnknownMethodHandler;
398 typedef ErrorMethodHandler<grpc::StatusCode::RESOURCE_EXHAUSTED>
399 ResourceExhaustedHandler;
400
401 } // namespace internal
402 } // namespace grpc
403
404 #endif // GRPCPP_SUPPORT_METHOD_HANDLER_H