Debian Codegraph @

include/grpcpp/impl/codegen/server_callback_handlers.h

raw
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 #ifndef GRPCPP_IMPL_CODEGEN_SERVER_CALLBACK_HANDLERS_H
19 #define GRPCPP_IMPL_CODEGEN_SERVER_CALLBACK_HANDLERS_H
20
21 // IWYU pragma: private
22
23 #include <grpcpp/impl/codegen/message_allocator.h>
24 #include <grpcpp/impl/codegen/rpc_service_method.h>
25 #include <grpcpp/impl/codegen/server_callback.h>
26 #include <grpcpp/impl/codegen/server_context.h>
27 #include <grpcpp/impl/codegen/status.h>
28
29 namespace grpc {
30 namespace internal {
31
32 template <class RequestType, class ResponseType>
33 class CallbackUnaryHandler : public grpc::internal::MethodHandler {
34 public:
35 explicit CallbackUnaryHandler(
36 std::function<ServerUnaryReactor*(grpc::CallbackServerContext*,
37 const RequestType*, ResponseType*)>
38 get_reactor)
39 : get_reactor_(std::move(get_reactor)) {}
40
41 void SetMessageAllocator(
42 MessageAllocator<RequestType, ResponseType>* allocator) {
43 allocator_ = allocator;
44 }
45
46 void RunHandler(const HandlerParameter& param) final {
47 // Arena allocate a controller structure (that includes request/response)
48 grpc::g_core_codegen_interface->grpc_call_ref(param.call->call());
49 auto* allocator_state =
50 static_cast<MessageHolder<RequestType, ResponseType>*>(
51 param.internal_data);
52
53 auto* call = new (grpc::g_core_codegen_interface->grpc_call_arena_alloc(
54 param.call->call(), sizeof(ServerCallbackUnaryImpl)))
55 ServerCallbackUnaryImpl(
56 static_cast<grpc::CallbackServerContext*>(param.server_context),
57 param.call, allocator_state, param.call_requester);
58 param.server_context->BeginCompletionOp(
59 param.call, [call](bool) { call->MaybeDone(); }, call);
60
61 ServerUnaryReactor* reactor = nullptr;
62 if (param.status.ok()) {
63 reactor = grpc::internal::CatchingReactorGetter<ServerUnaryReactor>(
64 get_reactor_,
65 static_cast<grpc::CallbackServerContext*>(param.server_context),
66 call->request(), call->response());
67 }
68
69 if (reactor == nullptr) {
70 // if deserialization or reactor creator failed, we need to fail the call
71 reactor = new (grpc::g_core_codegen_interface->grpc_call_arena_alloc(
72 param.call->call(), sizeof(UnimplementedUnaryReactor)))
73 UnimplementedUnaryReactor(
74 grpc::Status(grpc::StatusCode::UNIMPLEMENTED, ""));
75 }
76
77 /// Invoke SetupReactor as the last part of the handler
78 call->SetupReactor(reactor);
79 }
80
81 void* Deserialize(grpc_call* call, grpc_byte_buffer* req,
82 grpc::Status* status, void** handler_data) final {
83 grpc::ByteBuffer buf;
84 buf.set_buffer(req);
85 RequestType* request = nullptr;
86 MessageHolder<RequestType, ResponseType>* allocator_state;
87 if (allocator_ != nullptr) {
88 allocator_state = allocator_->AllocateMessages();
89 } else {
90 allocator_state =
91 new (grpc::g_core_codegen_interface->grpc_call_arena_alloc(
92 call, sizeof(DefaultMessageHolder<RequestType, ResponseType>)))
93 DefaultMessageHolder<RequestType, ResponseType>();
94 }
95 *handler_data = allocator_state;
96 request = allocator_state->request();
97 *status =
98 grpc::SerializationTraits<RequestType>::Deserialize(&buf, request);
99 buf.Release();
100 if (status->ok()) {
101 return request;
102 }
103 return nullptr;
104 }
105
106 private:
107 std::function<ServerUnaryReactor*(grpc::CallbackServerContext*,
108 const RequestType*, ResponseType*)>
109 get_reactor_;
110 MessageAllocator<RequestType, ResponseType>* allocator_ = nullptr;
111
112 class ServerCallbackUnaryImpl : public ServerCallbackUnary {
113 public:
114 void Finish(grpc::Status s) override {
115 // A callback that only contains a call to MaybeDone can be run as an
116 // inline callback regardless of whether or not OnDone is inlineable
117 // because if the actual OnDone callback needs to be scheduled, MaybeDone
118 // is responsible for dispatching to an executor thread if needed. Thus,
119 // when setting up the finish_tag_, we can set its own callback to
120 // inlineable.
121 finish_tag_.Set(
122 call_.call(),
123 [this](bool) {
124 this->MaybeDone(
125 reactor_.load(std::memory_order_relaxed)->InternalInlineable());
126 },
127 &finish_ops_, /*can_inline=*/true);
128 finish_ops_.set_core_cq_tag(&finish_tag_);
129
130 if (!ctx_->sent_initial_metadata_) {
131 finish_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
132 ctx_->initial_metadata_flags());
133 if (ctx_->compression_level_set()) {
134 finish_ops_.set_compression_level(ctx_->compression_level());
135 }
136 ctx_->sent_initial_metadata_ = true;
137 }
138 // The response is dropped if the status is not OK.
139 if (s.ok()) {
140 finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_,
141 finish_ops_.SendMessagePtr(response()));
142 } else {
143 finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_, s);
144 }
145 finish_ops_.set_core_cq_tag(&finish_tag_);
146 call_.PerformOps(&finish_ops_);
147 }
148
149 void SendInitialMetadata() override {
150 GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_);
151 this->Ref();
152 // The callback for this function should not be marked inline because it
153 // is directly invoking a user-controlled reaction
154 // (OnSendInitialMetadataDone). Thus it must be dispatched to an executor
155 // thread. However, any OnDone needed after that can be inlined because it
156 // is already running on an executor thread.
157 meta_tag_.Set(
158 call_.call(),
159 [this](bool ok) {
160 ServerUnaryReactor* reactor =
161 reactor_.load(std::memory_order_relaxed);
162 reactor->OnSendInitialMetadataDone(ok);
163 this->MaybeDone(/*inlineable_ondone=*/true);
164 },
165 &meta_ops_, /*can_inline=*/false);
166 meta_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
167 ctx_->initial_metadata_flags());
168 if (ctx_->compression_level_set()) {
169 meta_ops_.set_compression_level(ctx_->compression_level());
170 }
171 ctx_->sent_initial_metadata_ = true;
172 meta_ops_.set_core_cq_tag(&meta_tag_);
173 call_.PerformOps(&meta_ops_);
174 }
175
176 private:
177 friend class CallbackUnaryHandler<RequestType, ResponseType>;
178
179 ServerCallbackUnaryImpl(
180 grpc::CallbackServerContext* ctx, grpc::internal::Call* call,
181 MessageHolder<RequestType, ResponseType>* allocator_state,
182 std::function<void()> call_requester)
183 : ctx_(ctx),
184 call_(*call),
185 allocator_state_(allocator_state),
186 call_requester_(std::move(call_requester)) {
187 ctx_->set_message_allocator_state(allocator_state);
188 }
189
190 /// SetupReactor binds the reactor (which also releases any queued
191 /// operations), maybe calls OnCancel if possible/needed, and maybe marks
192 /// the completion of the RPC. This should be the last component of the
193 /// handler.
194 void SetupReactor(ServerUnaryReactor* reactor) {
195 reactor_.store(reactor, std::memory_order_relaxed);
196 this->BindReactor(reactor);
197 this->MaybeCallOnCancel(reactor);
198 this->MaybeDone(reactor->InternalInlineable());
199 }
200
201 const RequestType* request() { return allocator_state_->request(); }
202 ResponseType* response() { return allocator_state_->response(); }
203
204 void CallOnDone() override {
205 reactor_.load(std::memory_order_relaxed)->OnDone();
206 grpc_call* call = call_.call();
207 auto call_requester = std::move(call_requester_);
208 allocator_state_->Release();
209 if (ctx_->context_allocator() != nullptr) {
210 ctx_->context_allocator()->Release(ctx_);
211 }
212 this->~ServerCallbackUnaryImpl(); // explicitly call destructor
213 grpc::g_core_codegen_interface->grpc_call_unref(call);
214 call_requester();
215 }
216
217 ServerReactor* reactor() override {
218 return reactor_.load(std::memory_order_relaxed);
219 }
220
221 grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata>
222 meta_ops_;
223 grpc::internal::CallbackWithSuccessTag meta_tag_;
224 grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
225 grpc::internal::CallOpSendMessage,
226 grpc::internal::CallOpServerSendStatus>
227 finish_ops_;
228 grpc::internal::CallbackWithSuccessTag finish_tag_;
229
230 grpc::CallbackServerContext* const ctx_;
231 grpc::internal::Call call_;
232 MessageHolder<RequestType, ResponseType>* const allocator_state_;
233 std::function<void()> call_requester_;
234 // reactor_ can always be loaded/stored with relaxed memory ordering because
235 // its value is only set once, independently of other data in the object,
236 // and the loads that use it will always actually come provably later even
237 // though they are from different threads since they are triggered by
238 // actions initiated only by the setting up of the reactor_ variable. In
239 // a sense, it's a delayed "const": it gets its value from the SetupReactor
240 // method (not the constructor, so it's not a true const), but it doesn't
241 // change after that and it only gets used by actions caused, directly or
242 // indirectly, by that setup. This comment also applies to the reactor_
243 // variables of the other streaming objects in this file.
244 std::atomic<ServerUnaryReactor*> reactor_;
245 // callbacks_outstanding_ follows a refcount pattern
246 std::atomic<intptr_t> callbacks_outstanding_{
247 3}; // reserve for start, Finish, and CompletionOp
248 };
249 };
250
251 template <class RequestType, class ResponseType>
252 class CallbackClientStreamingHandler : public grpc::internal::MethodHandler {
253 public:
254 explicit CallbackClientStreamingHandler(
255 std::function<ServerReadReactor<RequestType>*(
256 grpc::CallbackServerContext*, ResponseType*)>
257 get_reactor)
258 : get_reactor_(std::move(get_reactor)) {}
259 void RunHandler(const HandlerParameter& param) final {
260 // Arena allocate a reader structure (that includes response)
261 grpc::g_core_codegen_interface->grpc_call_ref(param.call->call());
262
263 auto* reader = new (grpc::g_core_codegen_interface->grpc_call_arena_alloc(
264 param.call->call(), sizeof(ServerCallbackReaderImpl)))
265 ServerCallbackReaderImpl(
266 static_cast<grpc::CallbackServerContext*>(param.server_context),
267 param.call, param.call_requester);
268 // Inlineable OnDone can be false in the CompletionOp callback because there
269 // is no read reactor that has an inlineable OnDone; this only applies to
270 // the DefaultReactor (which is unary).
271 param.server_context->BeginCompletionOp(
272 param.call,
273 [reader](bool) { reader->MaybeDone(/*inlineable_ondone=*/false); },
274 reader);
275
276 ServerReadReactor<RequestType>* reactor = nullptr;
277 if (param.status.ok()) {
278 reactor =
279 grpc::internal::CatchingReactorGetter<ServerReadReactor<RequestType>>(
280 get_reactor_,
281 static_cast<grpc::CallbackServerContext*>(param.server_context),
282 reader->response());
283 }
284
285 if (reactor == nullptr) {
286 // if deserialization or reactor creator failed, we need to fail the call
287 reactor = new (grpc::g_core_codegen_interface->grpc_call_arena_alloc(
288 param.call->call(), sizeof(UnimplementedReadReactor<RequestType>)))
289 UnimplementedReadReactor<RequestType>(
290 grpc::Status(grpc::StatusCode::UNIMPLEMENTED, ""));
291 }
292
293 reader->SetupReactor(reactor);
294 }
295
296 private:
297 std::function<ServerReadReactor<RequestType>*(grpc::CallbackServerContext*,
298 ResponseType*)>
299 get_reactor_;
300
301 class ServerCallbackReaderImpl : public ServerCallbackReader<RequestType> {
302 public:
303 void Finish(grpc::Status s) override {
304 // A finish tag with only MaybeDone can have its callback inlined
305 // regardless even if OnDone is not inlineable because this callback just
306 // checks a ref and then decides whether or not to dispatch OnDone.
307 finish_tag_.Set(
308 call_.call(),
309 [this](bool) {
310 // Inlineable OnDone can be false here because there is
311 // no read reactor that has an inlineable OnDone; this
312 // only applies to the DefaultReactor (which is unary).
313 this->MaybeDone(/*inlineable_ondone=*/false);
314 },
315 &finish_ops_, /*can_inline=*/true);
316 if (!ctx_->sent_initial_metadata_) {
317 finish_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
318 ctx_->initial_metadata_flags());
319 if (ctx_->compression_level_set()) {
320 finish_ops_.set_compression_level(ctx_->compression_level());
321 }
322 ctx_->sent_initial_metadata_ = true;
323 }
324 // The response is dropped if the status is not OK.
325 if (s.ok()) {
326 finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_,
327 finish_ops_.SendMessagePtr(&resp_));
328 } else {
329 finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_, s);
330 }
331 finish_ops_.set_core_cq_tag(&finish_tag_);
332 call_.PerformOps(&finish_ops_);
333 }
334
335 void SendInitialMetadata() override {
336 GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_);
337 this->Ref();
338 // The callback for this function should not be inlined because it invokes
339 // a user-controlled reaction, but any resulting OnDone can be inlined in
340 // the executor to which this callback is dispatched.
341 meta_tag_.Set(
342 call_.call(),
343 [this](bool ok) {
344 ServerReadReactor<RequestType>* reactor =
345 reactor_.load(std::memory_order_relaxed);
346 reactor->OnSendInitialMetadataDone(ok);
347 this->MaybeDone(/*inlineable_ondone=*/true);
348 },
349 &meta_ops_, /*can_inline=*/false);
350 meta_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
351 ctx_->initial_metadata_flags());
352 if (ctx_->compression_level_set()) {
353 meta_ops_.set_compression_level(ctx_->compression_level());
354 }
355 ctx_->sent_initial_metadata_ = true;
356 meta_ops_.set_core_cq_tag(&meta_tag_);
357 call_.PerformOps(&meta_ops_);
358 }
359
360 void Read(RequestType* req) override {
361 this->Ref();
362 read_ops_.RecvMessage(req);
363 call_.PerformOps(&read_ops_);
364 }
365
366 private:
367 friend class CallbackClientStreamingHandler<RequestType, ResponseType>;
368
369 ServerCallbackReaderImpl(grpc::CallbackServerContext* ctx,
370 grpc::internal::Call* call,
371 std::function<void()> call_requester)
372 : ctx_(ctx), call_(*call), call_requester_(std::move(call_requester)) {}
373
374 void SetupReactor(ServerReadReactor<RequestType>* reactor) {
375 reactor_.store(reactor, std::memory_order_relaxed);
376 // The callback for this function should not be inlined because it invokes
377 // a user-controlled reaction, but any resulting OnDone can be inlined in
378 // the executor to which this callback is dispatched.
379 read_tag_.Set(
380 call_.call(),
381 [this, reactor](bool ok) {
382 if (GPR_UNLIKELY(!ok)) {
383 ctx_->MaybeMarkCancelledOnRead();
384 }
385 reactor->OnReadDone(ok);
386 this->MaybeDone(/*inlineable_ondone=*/true);
387 },
388 &read_ops_, /*can_inline=*/false);
389 read_ops_.set_core_cq_tag(&read_tag_);
390 this->BindReactor(reactor);
391 this->MaybeCallOnCancel(reactor);
392 // Inlineable OnDone can be false here because there is no read
393 // reactor that has an inlineable OnDone; this only applies to the
394 // DefaultReactor (which is unary).
395 this->MaybeDone(/*inlineable_ondone=*/false);
396 }
397
398 ~ServerCallbackReaderImpl() {}
399
400 ResponseType* response() { return &resp_; }
401
402 void CallOnDone() override {
403 reactor_.load(std::memory_order_relaxed)->OnDone();
404 grpc_call* call = call_.call();
405 auto call_requester = std::move(call_requester_);
406 if (ctx_->context_allocator() != nullptr) {
407 ctx_->context_allocator()->Release(ctx_);
408 }
409 this->~ServerCallbackReaderImpl(); // explicitly call destructor
410 grpc::g_core_codegen_interface->grpc_call_unref(call);
411 call_requester();
412 }
413
414 ServerReactor* reactor() override {
415 return reactor_.load(std::memory_order_relaxed);
416 }
417
418 grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata>
419 meta_ops_;
420 grpc::internal::CallbackWithSuccessTag meta_tag_;
421 grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
422 grpc::internal::CallOpSendMessage,
423 grpc::internal::CallOpServerSendStatus>
424 finish_ops_;
425 grpc::internal::CallbackWithSuccessTag finish_tag_;
426 grpc::internal::CallOpSet<grpc::internal::CallOpRecvMessage<RequestType>>
427 read_ops_;
428 grpc::internal::CallbackWithSuccessTag read_tag_;
429
430 grpc::CallbackServerContext* const ctx_;
431 grpc::internal::Call call_;
432 ResponseType resp_;
433 std::function<void()> call_requester_;
434 // The memory ordering of reactor_ follows ServerCallbackUnaryImpl.
435 std::atomic<ServerReadReactor<RequestType>*> reactor_;
436 // callbacks_outstanding_ follows a refcount pattern
437 std::atomic<intptr_t> callbacks_outstanding_{
438 3}; // reserve for OnStarted, Finish, and CompletionOp
439 };
440 };
441
442 template <class RequestType, class ResponseType>
443 class CallbackServerStreamingHandler : public grpc::internal::MethodHandler {
444 public:
445 explicit CallbackServerStreamingHandler(
446 std::function<ServerWriteReactor<ResponseType>*(
447 grpc::CallbackServerContext*, const RequestType*)>
448 get_reactor)
449 : get_reactor_(std::move(get_reactor)) {}
450 void RunHandler(const HandlerParameter& param) final {
451 // Arena allocate a writer structure
452 grpc::g_core_codegen_interface->grpc_call_ref(param.call->call());
453
454 auto* writer = new (grpc::g_core_codegen_interface->grpc_call_arena_alloc(
455 param.call->call(), sizeof(ServerCallbackWriterImpl)))
456 ServerCallbackWriterImpl(
457 static_cast<grpc::CallbackServerContext*>(param.server_context),
458 param.call, static_cast<RequestType*>(param.request),
459 param.call_requester);
460 // Inlineable OnDone can be false in the CompletionOp callback because there
461 // is no write reactor that has an inlineable OnDone; this only applies to
462 // the DefaultReactor (which is unary).
463 param.server_context->BeginCompletionOp(
464 param.call,
465 [writer](bool) { writer->MaybeDone(/*inlineable_ondone=*/false); },
466 writer);
467
468 ServerWriteReactor<ResponseType>* reactor = nullptr;
469 if (param.status.ok()) {
470 reactor = grpc::internal::CatchingReactorGetter<
471 ServerWriteReactor<ResponseType>>(
472 get_reactor_,
473 static_cast<grpc::CallbackServerContext*>(param.server_context),
474 writer->request());
475 }
476 if (reactor == nullptr) {
477 // if deserialization or reactor creator failed, we need to fail the call
478 reactor = new (grpc::g_core_codegen_interface->grpc_call_arena_alloc(
479 param.call->call(), sizeof(UnimplementedWriteReactor<ResponseType>)))
480 UnimplementedWriteReactor<ResponseType>(
481 grpc::Status(grpc::StatusCode::UNIMPLEMENTED, ""));
482 }
483
484 writer->SetupReactor(reactor);
485 }
486
487 void* Deserialize(grpc_call* call, grpc_byte_buffer* req,
488 grpc::Status* status, void** /*handler_data*/) final {
489 grpc::ByteBuffer buf;
490 buf.set_buffer(req);
491 auto* request = new (grpc::g_core_codegen_interface->grpc_call_arena_alloc(
492 call, sizeof(RequestType))) RequestType();
493 *status =
494 grpc::SerializationTraits<RequestType>::Deserialize(&buf, request);
495 buf.Release();
496 if (status->ok()) {
497 return request;
498 }
499 request->~RequestType();
500 return nullptr;
501 }
502
503 private:
504 std::function<ServerWriteReactor<ResponseType>*(grpc::CallbackServerContext*,
505 const RequestType*)>
506 get_reactor_;
507
508 class ServerCallbackWriterImpl : public ServerCallbackWriter<ResponseType> {
509 public:
510 void Finish(grpc::Status s) override {
511 // A finish tag with only MaybeDone can have its callback inlined
512 // regardless even if OnDone is not inlineable because this callback just
513 // checks a ref and then decides whether or not to dispatch OnDone.
514 finish_tag_.Set(
515 call_.call(),
516 [this](bool) {
517 // Inlineable OnDone can be false here because there is
518 // no write reactor that has an inlineable OnDone; this
519 // only applies to the DefaultReactor (which is unary).
520 this->MaybeDone(/*inlineable_ondone=*/false);
521 },
522 &finish_ops_, /*can_inline=*/true);
523 finish_ops_.set_core_cq_tag(&finish_tag_);
524
525 if (!ctx_->sent_initial_metadata_) {
526 finish_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
527 ctx_->initial_metadata_flags());
528 if (ctx_->compression_level_set()) {
529 finish_ops_.set_compression_level(ctx_->compression_level());
530 }
531 ctx_->sent_initial_metadata_ = true;
532 }
533 finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_, s);
534 call_.PerformOps(&finish_ops_);
535 }
536
537 void SendInitialMetadata() override {
538 GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_);
539 this->Ref();
540 // The callback for this function should not be inlined because it invokes
541 // a user-controlled reaction, but any resulting OnDone can be inlined in
542 // the executor to which this callback is dispatched.
543 meta_tag_.Set(
544 call_.call(),
545 [this](bool ok) {
546 ServerWriteReactor<ResponseType>* reactor =
547 reactor_.load(std::memory_order_relaxed);
548 reactor->OnSendInitialMetadataDone(ok);
549 this->MaybeDone(/*inlineable_ondone=*/true);
550 },
551 &meta_ops_, /*can_inline=*/false);
552 meta_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
553 ctx_->initial_metadata_flags());
554 if (ctx_->compression_level_set()) {
555 meta_ops_.set_compression_level(ctx_->compression_level());
556 }
557 ctx_->sent_initial_metadata_ = true;
558 meta_ops_.set_core_cq_tag(&meta_tag_);
559 call_.PerformOps(&meta_ops_);
560 }
561
562 void Write(const ResponseType* resp, grpc::WriteOptions options) override {
563 this->Ref();
564 if (options.is_last_message()) {
565 options.set_buffer_hint();
566 }
567 if (!ctx_->sent_initial_metadata_) {
568 write_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
569 ctx_->initial_metadata_flags());
570 if (ctx_->compression_level_set()) {
571 write_ops_.set_compression_level(ctx_->compression_level());
572 }
573 ctx_->sent_initial_metadata_ = true;
574 }
575 // TODO(vjpai): don't assert
576 GPR_CODEGEN_ASSERT(write_ops_.SendMessagePtr(resp, options).ok());
577 call_.PerformOps(&write_ops_);
578 }
579
580 void WriteAndFinish(const ResponseType* resp, grpc::WriteOptions options,
581 grpc::Status s) override {
582 // This combines the write into the finish callback
583 // TODO(vjpai): don't assert
584 GPR_CODEGEN_ASSERT(finish_ops_.SendMessagePtr(resp, options).ok());
585 Finish(std::move(s));
586 }
587
588 private:
589 friend class CallbackServerStreamingHandler<RequestType, ResponseType>;
590
591 ServerCallbackWriterImpl(grpc::CallbackServerContext* ctx,
592 grpc::internal::Call* call, const RequestType* req,
593 std::function<void()> call_requester)
594 : ctx_(ctx),
595 call_(*call),
596 req_(req),
597 call_requester_(std::move(call_requester)) {}
598
599 void SetupReactor(ServerWriteReactor<ResponseType>* reactor) {
600 reactor_.store(reactor, std::memory_order_relaxed);
601 // The callback for this function should not be inlined because it invokes
602 // a user-controlled reaction, but any resulting OnDone can be inlined in
603 // the executor to which this callback is dispatched.
604 write_tag_.Set(
605 call_.call(),
606 [this, reactor](bool ok) {
607 reactor->OnWriteDone(ok);
608 this->MaybeDone(/*inlineable_ondone=*/true);
609 },
610 &write_ops_, /*can_inline=*/false);
611 write_ops_.set_core_cq_tag(&write_tag_);
612 this->BindReactor(reactor);
613 this->MaybeCallOnCancel(reactor);
614 // Inlineable OnDone can be false here because there is no write
615 // reactor that has an inlineable OnDone; this only applies to the
616 // DefaultReactor (which is unary).
617 this->MaybeDone(/*inlineable_ondone=*/false);
618 }
619 ~ServerCallbackWriterImpl() {
620 if (req_ != nullptr) {
621 req_->~RequestType();
622 }
623 }
624
625 const RequestType* request() { return req_; }
626
627 void CallOnDone() override {
628 reactor_.load(std::memory_order_relaxed)->OnDone();
629 grpc_call* call = call_.call();
630 auto call_requester = std::move(call_requester_);
631 if (ctx_->context_allocator() != nullptr) {
632 ctx_->context_allocator()->Release(ctx_);
633 }
634 this->~ServerCallbackWriterImpl(); // explicitly call destructor
635 grpc::g_core_codegen_interface->grpc_call_unref(call);
636 call_requester();
637 }
638
639 ServerReactor* reactor() override {
640 return reactor_.load(std::memory_order_relaxed);
641 }
642
643 grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata>
644 meta_ops_;
645 grpc::internal::CallbackWithSuccessTag meta_tag_;
646 grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
647 grpc::internal::CallOpSendMessage,
648 grpc::internal::CallOpServerSendStatus>
649 finish_ops_;
650 grpc::internal::CallbackWithSuccessTag finish_tag_;
651 grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
652 grpc::internal::CallOpSendMessage>
653 write_ops_;
654 grpc::internal::CallbackWithSuccessTag write_tag_;
655
656 grpc::CallbackServerContext* const ctx_;
657 grpc::internal::Call call_;
658 const RequestType* req_;
659 std::function<void()> call_requester_;
660 // The memory ordering of reactor_ follows ServerCallbackUnaryImpl.
661 std::atomic<ServerWriteReactor<ResponseType>*> reactor_;
662 // callbacks_outstanding_ follows a refcount pattern
663 std::atomic<intptr_t> callbacks_outstanding_{
664 3}; // reserve for OnStarted, Finish, and CompletionOp
665 };
666 };
667
668 template <class RequestType, class ResponseType>
669 class CallbackBidiHandler : public grpc::internal::MethodHandler {
670 public:
671 explicit CallbackBidiHandler(
672 std::function<ServerBidiReactor<RequestType, ResponseType>*(
673 grpc::CallbackServerContext*)>
674 get_reactor)
675 : get_reactor_(std::move(get_reactor)) {}
676 void RunHandler(const HandlerParameter& param) final {
677 grpc::g_core_codegen_interface->grpc_call_ref(param.call->call());
678
679 auto* stream = new (grpc::g_core_codegen_interface->grpc_call_arena_alloc(
680 param.call->call(), sizeof(ServerCallbackReaderWriterImpl)))
681 ServerCallbackReaderWriterImpl(
682 static_cast<grpc::CallbackServerContext*>(param.server_context),
683 param.call, param.call_requester);
684 // Inlineable OnDone can be false in the CompletionOp callback because there
685 // is no bidi reactor that has an inlineable OnDone; this only applies to
686 // the DefaultReactor (which is unary).
687 param.server_context->BeginCompletionOp(
688 param.call,
689 [stream](bool) { stream->MaybeDone(/*inlineable_ondone=*/false); },
690 stream);
691
692 ServerBidiReactor<RequestType, ResponseType>* reactor = nullptr;
693 if (param.status.ok()) {
694 reactor = grpc::internal::CatchingReactorGetter<
695 ServerBidiReactor<RequestType, ResponseType>>(
696 get_reactor_,
697 static_cast<grpc::CallbackServerContext*>(param.server_context));
698 }
699
700 if (reactor == nullptr) {
701 // if deserialization or reactor creator failed, we need to fail the call
702 reactor = new (grpc::g_core_codegen_interface->grpc_call_arena_alloc(
703 param.call->call(),
704 sizeof(UnimplementedBidiReactor<RequestType, ResponseType>)))
705 UnimplementedBidiReactor<RequestType, ResponseType>(
706 grpc::Status(grpc::StatusCode::UNIMPLEMENTED, ""));
707 }
708
709 stream->SetupReactor(reactor);
710 }
711
712 private:
713 std::function<ServerBidiReactor<RequestType, ResponseType>*(
714 grpc::CallbackServerContext*)>
715 get_reactor_;
716
717 class ServerCallbackReaderWriterImpl
718 : public ServerCallbackReaderWriter<RequestType, ResponseType> {
719 public:
720 void Finish(grpc::Status s) override {
721 // A finish tag with only MaybeDone can have its callback inlined
722 // regardless even if OnDone is not inlineable because this callback just
723 // checks a ref and then decides whether or not to dispatch OnDone.
724 finish_tag_.Set(
725 call_.call(),
726 [this](bool) {
727 // Inlineable OnDone can be false here because there is
728 // no bidi reactor that has an inlineable OnDone; this
729 // only applies to the DefaultReactor (which is unary).
730 this->MaybeDone(/*inlineable_ondone=*/false);
731 },
732 &finish_ops_, /*can_inline=*/true);
733 finish_ops_.set_core_cq_tag(&finish_tag_);
734
735 if (!ctx_->sent_initial_metadata_) {
736 finish_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
737 ctx_->initial_metadata_flags());
738 if (ctx_->compression_level_set()) {
739 finish_ops_.set_compression_level(ctx_->compression_level());
740 }
741 ctx_->sent_initial_metadata_ = true;
742 }
743 finish_ops_.ServerSendStatus(&ctx_->trailing_metadata_, s);
744 call_.PerformOps(&finish_ops_);
745 }
746
747 void SendInitialMetadata() override {
748 GPR_CODEGEN_ASSERT(!ctx_->sent_initial_metadata_);
749 this->Ref();
750 // The callback for this function should not be inlined because it invokes
751 // a user-controlled reaction, but any resulting OnDone can be inlined in
752 // the executor to which this callback is dispatched.
753 meta_tag_.Set(
754 call_.call(),
755 [this](bool ok) {
756 ServerBidiReactor<RequestType, ResponseType>* reactor =
757 reactor_.load(std::memory_order_relaxed);
758 reactor->OnSendInitialMetadataDone(ok);
759 this->MaybeDone(/*inlineable_ondone=*/true);
760 },
761 &meta_ops_, /*can_inline=*/false);
762 meta_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
763 ctx_->initial_metadata_flags());
764 if (ctx_->compression_level_set()) {
765 meta_ops_.set_compression_level(ctx_->compression_level());
766 }
767 ctx_->sent_initial_metadata_ = true;
768 meta_ops_.set_core_cq_tag(&meta_tag_);
769 call_.PerformOps(&meta_ops_);
770 }
771
772 void Write(const ResponseType* resp, grpc::WriteOptions options) override {
773 this->Ref();
774 if (options.is_last_message()) {
775 options.set_buffer_hint();
776 }
777 if (!ctx_->sent_initial_metadata_) {
778 write_ops_.SendInitialMetadata(&ctx_->initial_metadata_,
779 ctx_->initial_metadata_flags());
780 if (ctx_->compression_level_set()) {
781 write_ops_.set_compression_level(ctx_->compression_level());
782 }
783 ctx_->sent_initial_metadata_ = true;
784 }
785 // TODO(vjpai): don't assert
786 GPR_CODEGEN_ASSERT(write_ops_.SendMessagePtr(resp, options).ok());
787 call_.PerformOps(&write_ops_);
788 }
789
790 void WriteAndFinish(const ResponseType* resp, grpc::WriteOptions options,
791 grpc::Status s) override {
792 // TODO(vjpai): don't assert
793 GPR_CODEGEN_ASSERT(finish_ops_.SendMessagePtr(resp, options).ok());
794 Finish(std::move(s));
795 }
796
797 void Read(RequestType* req) override {
798 this->Ref();
799 read_ops_.RecvMessage(req);
800 call_.PerformOps(&read_ops_);
801 }
802
803 private:
804 friend class CallbackBidiHandler<RequestType, ResponseType>;
805
806 ServerCallbackReaderWriterImpl(grpc::CallbackServerContext* ctx,
807 grpc::internal::Call* call,
808 std::function<void()> call_requester)
809 : ctx_(ctx), call_(*call), call_requester_(std::move(call_requester)) {}
810
811 void SetupReactor(ServerBidiReactor<RequestType, ResponseType>* reactor) {
812 reactor_.store(reactor, std::memory_order_relaxed);
813 // The callbacks for these functions should not be inlined because they
814 // invoke user-controlled reactions, but any resulting OnDones can be
815 // inlined in the executor to which a callback is dispatched.
816 write_tag_.Set(
817 call_.call(),
818 [this, reactor](bool ok) {
819 reactor->OnWriteDone(ok);
820 this->MaybeDone(/*inlineable_ondone=*/true);
821 },
822 &write_ops_, /*can_inline=*/false);
823 write_ops_.set_core_cq_tag(&write_tag_);
824 read_tag_.Set(
825 call_.call(),
826 [this, reactor](bool ok) {
827 if (GPR_UNLIKELY(!ok)) {
828 ctx_->MaybeMarkCancelledOnRead();
829 }
830 reactor->OnReadDone(ok);
831 this->MaybeDone(/*inlineable_ondone=*/true);
832 },
833 &read_ops_, /*can_inline=*/false);
834 read_ops_.set_core_cq_tag(&read_tag_);
835 this->BindReactor(reactor);
836 this->MaybeCallOnCancel(reactor);
837 // Inlineable OnDone can be false here because there is no bidi
838 // reactor that has an inlineable OnDone; this only applies to the
839 // DefaultReactor (which is unary).
840 this->MaybeDone(/*inlineable_ondone=*/false);
841 }
842
843 void CallOnDone() override {
844 reactor_.load(std::memory_order_relaxed)->OnDone();
845 grpc_call* call = call_.call();
846 auto call_requester = std::move(call_requester_);
847 if (ctx_->context_allocator() != nullptr) {
848 ctx_->context_allocator()->Release(ctx_);
849 }
850 this->~ServerCallbackReaderWriterImpl(); // explicitly call destructor
851 grpc::g_core_codegen_interface->grpc_call_unref(call);
852 call_requester();
853 }
854
855 ServerReactor* reactor() override {
856 return reactor_.load(std::memory_order_relaxed);
857 }
858
859 grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata>
860 meta_ops_;
861 grpc::internal::CallbackWithSuccessTag meta_tag_;
862 grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
863 grpc::internal::CallOpSendMessage,
864 grpc::internal::CallOpServerSendStatus>
865 finish_ops_;
866 grpc::internal::CallbackWithSuccessTag finish_tag_;
867 grpc::internal::CallOpSet<grpc::internal::CallOpSendInitialMetadata,
868 grpc::internal::CallOpSendMessage>
869 write_ops_;
870 grpc::internal::CallbackWithSuccessTag write_tag_;
871 grpc::internal::CallOpSet<grpc::internal::CallOpRecvMessage<RequestType>>
872 read_ops_;
873 grpc::internal::CallbackWithSuccessTag read_tag_;
874
875 grpc::CallbackServerContext* const ctx_;
876 grpc::internal::Call call_;
877 std::function<void()> call_requester_;
878 // The memory ordering of reactor_ follows ServerCallbackUnaryImpl.
879 std::atomic<ServerBidiReactor<RequestType, ResponseType>*> reactor_;
880 // callbacks_outstanding_ follows a refcount pattern
881 std::atomic<intptr_t> callbacks_outstanding_{
882 3}; // reserve for OnStarted, Finish, and CompletionOp
883 };
884 };
885
886 } // namespace internal
887 } // namespace grpc
888
889 #endif // GRPCPP_IMPL_CODEGEN_SERVER_CALLBACK_HANDLERS_H