Debian Codegraph @

include/grpcpp/support/async_unary_call.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_ASYNC_UNARY_CALL_H
20 #define GRPCPP_SUPPORT_ASYNC_UNARY_CALL_H
21
22 #include <grpc/grpc.h>
23 #include <grpcpp/client_context.h>
24 #include <grpcpp/impl/call.h>
25 #include <grpcpp/impl/call_op_set.h>
26 #include <grpcpp/impl/call_op_set_interface.h>
27 #include <grpcpp/impl/channel_interface.h>
28 #include <grpcpp/impl/codegen/core_codegen_interface.h>
29 #include <grpcpp/impl/service_type.h>
30 #include <grpcpp/server_context.h>
31 #include <grpcpp/support/status.h>
32
33 namespace grpc {
34
35 // Forward declaration for use in Helper class
36 template <class R>
37 class ClientAsyncResponseReader;
38
39 /// An interface relevant for async client side unary RPCs (which send
40 /// one request message to a server and receive one response message).
41 template <class R>
42 class ClientAsyncResponseReaderInterface {
43 public:
44 virtual ~ClientAsyncResponseReaderInterface() {}
45
46 /// Start the call that was set up by the constructor, but only if the
47 /// constructor was invoked through the "Prepare" API which doesn't actually
48 /// start the call
49 virtual void StartCall() = 0;
50
51 /// Request notification of the reading of initial metadata. Completion
52 /// will be notified by \a tag on the associated completion queue.
53 /// This call is optional, but if it is used, it cannot be used concurrently
54 /// with or after the \a Finish method.
55 ///
56 /// \param[in] tag Tag identifying this request.
57 virtual void ReadInitialMetadata(void* tag) = 0;
58
59 /// Request to receive the server's response \a msg and final \a status for
60 /// the call, and to notify \a tag on this call's completion queue when
61 /// finished.
62 ///
63 /// This function will return when either:
64 /// - when the server's response message and status have been received.
65 /// - when the server has returned a non-OK status (no message expected in
66 /// this case).
67 /// - when the call failed for some reason and the library generated a
68 /// non-OK status.
69 ///
70 /// \param[in] tag Tag identifying this request.
71 /// \param[out] status To be updated with the operation status.
72 /// \param[out] msg To be filled in with the server's response message.
73 virtual void Finish(R* msg, grpc::Status* status, void* tag) = 0;
74 };
75
76 namespace internal {
77
78 class ClientAsyncResponseReaderHelper {
79 public:
80 /// Start a call and write the request out if \a start is set.
81 /// \a tag will be notified on \a cq when the call has been started (i.e.
82 /// intitial metadata sent) and \a request has been written out.
83 /// If \a start is not set, the actual call must be initiated by StartCall
84 /// Note that \a context will be used to fill in custom initial metadata
85 /// used to send to the server when starting the call.
86 ///
87 /// Optionally pass in a base class for request and response types so that the
88 /// internal functions and structs can be templated based on that, allowing
89 /// reuse across RPCs (e.g., MessageLite for protobuf). Since constructors
90 /// can't have an explicit template parameter, the last argument is an
91 /// extraneous parameter just to provide the needed type information.
92 template <class R, class W, class BaseR = R, class BaseW = W>
93 static ClientAsyncResponseReader<R>* Create(
94 grpc::ChannelInterface* channel, grpc::CompletionQueue* cq,
95 const grpc::internal::RpcMethod& method, grpc::ClientContext* context,
96 const W& request) /* __attribute__((noinline)) */ {
97 grpc::internal::Call call = channel->CreateCall(method, context, cq);
98 ClientAsyncResponseReader<R>* result =
99 new (grpc::g_core_codegen_interface->grpc_call_arena_alloc(
100 call.call(), sizeof(ClientAsyncResponseReader<R>)))
101 ClientAsyncResponseReader<R>(call, context);
102 SetupRequest<BaseR, BaseW>(
103 call.call(), &result->single_buf_, &result->read_initial_metadata_,
104 &result->finish_, static_cast<const BaseW&>(request));
105
106 return result;
107 }
108
109 // Various helper functions to reduce templating use
110
111 template <class R, class W>
112 static void SetupRequest(
113 grpc_call* call,
114 grpc::internal::CallOpSendInitialMetadata** single_buf_ptr,
115 std::function<void(ClientContext*, internal::Call*,
116 internal::CallOpSendInitialMetadata*, void*)>*
117 read_initial_metadata,
118 std::function<
119 void(ClientContext*, internal::Call*, bool initial_metadata_read,
120 internal::CallOpSendInitialMetadata*,
121 internal::CallOpSetInterface**, void*, Status*, void*)>* finish,
122 const W& request) {
123 using SingleBufType =
124 grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
125 grpc::internal::CallOpSendMessage,
126 grpc::internal::CallOpClientSendClose,
127 grpc::internal::CallOpRecvInitialMetadata,
128 grpc::internal::CallOpRecvMessage<R>,
129 grpc::internal::CallOpClientRecvStatus>;
130 SingleBufType* single_buf =
131 new (grpc::g_core_codegen_interface->grpc_call_arena_alloc(
132 call, sizeof(SingleBufType))) SingleBufType;
133 *single_buf_ptr = single_buf;
134 // TODO(ctiller): don't assert
135 GPR_CODEGEN_ASSERT(single_buf->SendMessage(request).ok());
136 single_buf->ClientSendClose();
137
138 // The purpose of the following functions is to type-erase the actual
139 // templated type of the CallOpSet being used by hiding that type inside the
140 // function definition rather than specifying it as an argument of the
141 // function or a member of the class. The type-erased CallOpSet will get
142 // static_cast'ed back to the real type so that it can be used properly.
143 *read_initial_metadata =
144 [](ClientContext* context, internal::Call* call,
145 internal::CallOpSendInitialMetadata* single_buf_view, void* tag) {
146 auto* single_buf = static_cast<SingleBufType*>(single_buf_view);
147 single_buf->set_output_tag(tag);
148 single_buf->RecvInitialMetadata(context);
149 call->PerformOps(single_buf);
150 };
151
152 // Note that this function goes one step further than the previous one
153 // because it type-erases the message being written down to a void*. This
154 // will be static-cast'ed back to the class specified here by hiding that
155 // class information inside the function definition. Note that this feature
156 // expects the class being specified here for R to be a base-class of the
157 // "real" R without any multiple-inheritance (as applies in protbuf wrt
158 // MessageLite)
159 *finish = [](ClientContext* context, internal::Call* call,
160 bool initial_metadata_read,
161 internal::CallOpSendInitialMetadata* single_buf_view,
162 internal::CallOpSetInterface** finish_buf_ptr, void* msg,
163 Status* status, void* tag) {
164 if (initial_metadata_read) {
165 using FinishBufType =
166 grpc::internal::CallOpSet<grpc::internal::CallOpRecvMessage<R>,
167 grpc::internal::CallOpClientRecvStatus>;
168 FinishBufType* finish_buf =
169 new (grpc::g_core_codegen_interface->grpc_call_arena_alloc(
170 call->call(), sizeof(FinishBufType))) FinishBufType;
171 *finish_buf_ptr = finish_buf;
172 finish_buf->set_output_tag(tag);
173 finish_buf->RecvMessage(static_cast<R*>(msg));
174 finish_buf->AllowNoMessage();
175 finish_buf->ClientRecvStatus(context, status);
176 call->PerformOps(finish_buf);
177 } else {
178 auto* single_buf = static_cast<SingleBufType*>(single_buf_view);
179 single_buf->set_output_tag(tag);
180 single_buf->RecvInitialMetadata(context);
181 single_buf->RecvMessage(static_cast<R*>(msg));
182 single_buf->AllowNoMessage();
183 single_buf->ClientRecvStatus(context, status);
184 call->PerformOps(single_buf);
185 }
186 };
187 }
188
189 static void StartCall(grpc::ClientContext* context,
190 grpc::internal::CallOpSendInitialMetadata* single_buf) {
191 single_buf->SendInitialMetadata(&context->send_initial_metadata_,
192 context->initial_metadata_flags());
193 }
194 };
195
196 // TODO(vjpai): This templated factory is deprecated and will be replaced by
197 //. the non-templated helper as soon as possible.
198 template <class R>
199 class ClientAsyncResponseReaderFactory {
200 public:
201 template <class W>
202 static ClientAsyncResponseReader<R>* Create(
203 grpc::ChannelInterface* channel, grpc::CompletionQueue* cq,
204 const grpc::internal::RpcMethod& method, grpc::ClientContext* context,
205 const W& request, bool start) {
206 auto* result = ClientAsyncResponseReaderHelper::Create<R>(
207 channel, cq, method, context, request);
208 if (start) {
209 result->StartCall();
210 }
211 return result;
212 }
213 };
214
215 } // namespace internal
216
217 /// Async API for client-side unary RPCs, where the message response
218 /// received from the server is of type \a R.
219 template <class R>
220 class ClientAsyncResponseReader final
221 : public ClientAsyncResponseReaderInterface<R> {
222 public:
223 // always allocated against a call arena, no memory free required
224 static void operator delete(void* /*ptr*/, std::size_t size) {
225 GPR_CODEGEN_ASSERT(size == sizeof(ClientAsyncResponseReader));
226 }
227
228 // This operator should never be called as the memory should be freed as part
229 // of the arena destruction. It only exists to provide a matching operator
230 // delete to the operator new so that some compilers will not complain (see
231 // https://github.com/grpc/grpc/issues/11301) Note at the time of adding this
232 // there are no tests catching the compiler warning.
233 static void operator delete(void*, void*) { GPR_CODEGEN_ASSERT(false); }
234
235 void StartCall() override {
236 GPR_CODEGEN_DEBUG_ASSERT(!started_);
237 started_ = true;
238 internal::ClientAsyncResponseReaderHelper::StartCall(context_, single_buf_);
239 }
240
241 /// See \a ClientAsyncResponseReaderInterface::ReadInitialMetadata for
242 /// semantics.
243 ///
244 /// Side effect:
245 /// - the \a ClientContext associated with this call is updated with
246 /// possible initial and trailing metadata sent from the server.
247 void ReadInitialMetadata(void* tag) override {
248 GPR_CODEGEN_DEBUG_ASSERT(started_);
249 GPR_CODEGEN_DEBUG_ASSERT(!context_->initial_metadata_received_);
250 read_initial_metadata_(context_, &call_, single_buf_, tag);
251 initial_metadata_read_ = true;
252 }
253
254 /// See \a ClientAsyncResponseReaderInterface::Finish for semantics.
255 ///
256 /// Side effect:
257 /// - the \a ClientContext associated with this call is updated with
258 /// possible initial and trailing metadata sent from the server.
259 void Finish(R* msg, grpc::Status* status, void* tag) override {
260 GPR_CODEGEN_DEBUG_ASSERT(started_);
261 finish_(context_, &call_, initial_metadata_read_, single_buf_, &finish_buf_,
262 static_cast<void*>(msg), status, tag);
263 }
264
265 private:
266 friend class internal::ClientAsyncResponseReaderHelper;
267 grpc::ClientContext* const context_;
268 grpc::internal::Call call_;
269 bool started_ = false;
270 bool initial_metadata_read_ = false;
271
272 ClientAsyncResponseReader(grpc::internal::Call call,
273 grpc::ClientContext* context)
274 : context_(context), call_(call) {}
275
276 // disable operator new
277 static void* operator new(std::size_t size);
278 static void* operator new(std::size_t /*size*/, void* p) { return p; }
279
280 internal::CallOpSendInitialMetadata* single_buf_;
281 internal::CallOpSetInterface* finish_buf_ = nullptr;
282 std::function<void(ClientContext*, internal::Call*,
283 internal::CallOpSendInitialMetadata*, void*)>
284 read_initial_metadata_;
285 std::function<void(ClientContext*, internal::Call*,
286 bool initial_metadata_read,
287 internal::CallOpSendInitialMetadata*,
288 internal::CallOpSetInterface**, void*, Status*, void*)>
289 finish_;
290 };
291
292 /// Async server-side API for handling unary calls, where the single
293 /// response message sent to the client is of type \a W.
294 template <class W>
295 class ServerAsyncResponseWriter final
296 : public grpc::internal::ServerAsyncStreamingInterface {
297 public:
298 explicit ServerAsyncResponseWriter(grpc::ServerContext* ctx)
299 : call_(nullptr, nullptr, nullptr), ctx_(ctx) {}
300
301 /// See \a ServerAsyncStreamingInterface::SendInitialMetadata for semantics.
302 ///
303 /// Side effect:
304 /// The initial metadata that will be sent to the client from this op will
305 /// be taken from the \a ServerContext associated with the call.
306 ///
307 /// \param[in] tag Tag identifying this request.
308 void SendInitialMetadata(void* tag) override {
309 GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_);
310
311 meta_buf_.set_output_tag(tag);
312 meta_buf_.SendInitialMetadata(&ctx_->initial_metadata_,
313 ctx_->initial_metadata_flags());
314 if (ctx_->compression_level_set()) {
315 meta_buf_.set_compression_level(ctx_->compression_level());
316 }
317 ctx_->sent_initial_metadata_ = true;
318 call_.PerformOps(&meta_buf_);
319 }
320
321 /// Indicate that the stream is to be finished and request notification
322 /// when the server has sent the appropriate signals to the client to
323 /// end the call. Should not be used concurrently with other operations.
324 ///
325 /// \param[in] tag Tag identifying this request.
326 /// \param[in] status To be sent to the client as the result of the call.
327 /// \param[in] msg Message to be sent to the client.
328 ///
329 /// Side effect:
330 /// - also sends initial metadata if not already sent (using the
331 /// \a ServerContext associated with this call).
332 ///
333 /// Note: if \a status has a non-OK code, then \a msg will not be sent,
334 /// and the client will receive only the status with possible trailing
335 /// metadata.
336 ///
337 /// gRPC doesn't take ownership or a reference to msg and status, so it is
338 /// safe to deallocate them once the Finish operation is complete (i.e. a
339 /// result arrives in the completion queue).
340 void Finish(const W& msg, const grpc::Status& status, void* tag) {
341 finish_buf_.set_output_tag(tag);
342 finish_buf_.set_core_cq_tag(&finish_buf_);
343 if (!ctx_->sent_initial_metadata_) {
344 finish_buf_.SendInitialMetadata(&ctx_->initial_metadata_,
345 ctx_->initial_metadata_flags());
346 if (ctx_->compression_level_set()) {
347 finish_buf_.set_compression_level(ctx_->compression_level());
348 }
349 ctx_->sent_initial_metadata_ = true;
350 }
351 // The response is dropped if the status is not OK.
352 if (status.ok()) {
353 finish_buf_.ServerSendStatus(&ctx_->trailing_metadata_,
354 finish_buf_.SendMessage(msg));
355 } else {
356 finish_buf_.ServerSendStatus(&ctx_->trailing_metadata_, status);
357 }
358 call_.PerformOps(&finish_buf_);
359 }
360
361 /// Indicate that the stream is to be finished with a non-OK status,
362 /// and request notification for when the server has finished sending the
363 /// appropriate signals to the client to end the call.
364 /// Should not be used concurrently with other operations.
365 ///
366 /// \param[in] tag Tag identifying this request.
367 /// \param[in] status To be sent to the client as the result of the call.
368 /// - Note: \a status must have a non-OK code.
369 ///
370 /// Side effect:
371 /// - also sends initial metadata if not already sent (using the
372 /// \a ServerContext associated with this call).
373 ///
374 /// gRPC doesn't take ownership or a reference to status, so it is safe to
375 /// deallocate them once the Finish operation is complete (i.e. a result
376 /// arrives in the completion queue).
377 void FinishWithError(const grpc::Status& status, void* tag) {
378 GPR_CODEGEN_ASSERT(!status.ok());
379 finish_buf_.set_output_tag(tag);
380 if (!ctx_->sent_initial_metadata_) {
381 finish_buf_.SendInitialMetadata(&ctx_->initial_metadata_,
382 ctx_->initial_metadata_flags());
383 if (ctx_->compression_level_set()) {
384 finish_buf_.set_compression_level(ctx_->compression_level());
385 }
386 ctx_->sent_initial_metadata_ = true;
387 }
388 finish_buf_.ServerSendStatus(&ctx_->trailing_metadata_, status);
389 call_.PerformOps(&finish_buf_);
390 }
391
392 private:
393 void BindCall(grpc::internal::Call* call) override { call_ = *call; }
394
395 grpc::internal::Call call_;
396 grpc::ServerContext* ctx_;
397 grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata>
398 meta_buf_;
399 grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
400 grpc::internal::CallOpSendMessage,
401 grpc::internal::CallOpServerSendStatus>
402 finish_buf_;
403 };
404
405 } // namespace grpc
406
407 namespace std {
408 template <class R>
409 class default_delete<grpc::ClientAsyncResponseReader<R>> {
410 public:
411 void operator()(void* /*p*/) {}
412 };
413 template <class R>
414 class default_delete<grpc::ClientAsyncResponseReaderInterface<R>> {
415 public:
416 void operator()(void* /*p*/) {}
417 };
418 } // namespace std
419
420 #endif // GRPCPP_SUPPORT_ASYNC_UNARY_CALL_H