1 /*
2 *
3 * Copyright 2018 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_CALL_OP_SET_H
20 #define GRPCPP_IMPL_CODEGEN_CALL_OP_SET_H
21
22 #include <cstring>
23 #include <map>
24 #include <memory>
25
26 #include <grpc/impl/codegen/compression_types.h>
27 #include <grpc/impl/codegen/grpc_types.h>
28 #include <grpcpp/impl/codegen/byte_buffer.h>
29 #include <grpcpp/impl/codegen/call.h>
30 #include <grpcpp/impl/codegen/call_hook.h>
31 #include <grpcpp/impl/codegen/call_op_set_interface.h>
32 #include <grpcpp/impl/codegen/client_context.h>
33 #include <grpcpp/impl/codegen/completion_queue.h>
34 #include <grpcpp/impl/codegen/completion_queue_tag.h>
35 #include <grpcpp/impl/codegen/config.h>
36 #include <grpcpp/impl/codegen/core_codegen_interface.h>
37 #include <grpcpp/impl/codegen/intercepted_channel.h>
38 #include <grpcpp/impl/codegen/interceptor_common.h>
39 #include <grpcpp/impl/codegen/serialization_traits.h>
40 #include <grpcpp/impl/codegen/slice.h>
41 #include <grpcpp/impl/codegen/string_ref.h>
42
43 namespace grpc {
44
45 extern CoreCodegenInterface* g_core_codegen_interface;
46
47 namespace internal {
48 class Call;
49 class CallHook;
50
51 // TODO(yangg) if the map is changed before we send, the pointers will be a
52 // mess. Make sure it does not happen.
FillMetadataArray(const std::multimap<std::string,std::string> & metadata,size_t * metadata_count,const std::string & optional_error_details)53 inline grpc_metadata* FillMetadataArray(
54 const std::multimap<std::string, std::string>& metadata,
55 size_t* metadata_count, const std::string& optional_error_details) {
56 *metadata_count = metadata.size() + (optional_error_details.empty() ? 0 : 1);
57 if (*metadata_count == 0) {
58 return nullptr;
59 }
60 grpc_metadata* metadata_array =
61 static_cast<grpc_metadata*>(g_core_codegen_interface->gpr_malloc(
62 (*metadata_count) * sizeof(grpc_metadata)));
63 size_t i = 0;
64 for (auto iter = metadata.cbegin(); iter != metadata.cend(); ++iter, ++i) {
65 metadata_array[i].key = SliceReferencingString(iter->first);
66 metadata_array[i].value = SliceReferencingString(iter->second);
67 }
68 if (!optional_error_details.empty()) {
69 metadata_array[i].key =
70 g_core_codegen_interface->grpc_slice_from_static_buffer(
71 kBinaryErrorDetailsKey, sizeof(kBinaryErrorDetailsKey) - 1);
72 metadata_array[i].value = SliceReferencingString(optional_error_details);
73 }
74 return metadata_array;
75 }
76 } // namespace internal
77
78 /// Per-message write options.
79 class WriteOptions {
80 public:
WriteOptions()81 WriteOptions() : flags_(0), last_message_(false) {}
82
83 /// Clear all flags.
Clear()84 inline void Clear() { flags_ = 0; }
85
86 /// Returns raw flags bitset.
flags()87 inline uint32_t flags() const { return flags_; }
88
89 /// Sets flag for the disabling of compression for the next message write.
90 ///
91 /// \sa GRPC_WRITE_NO_COMPRESS
set_no_compression()92 inline WriteOptions& set_no_compression() {
93 SetBit(GRPC_WRITE_NO_COMPRESS);
94 return *this;
95 }
96
97 /// Clears flag for the disabling of compression for the next message write.
98 ///
99 /// \sa GRPC_WRITE_NO_COMPRESS
clear_no_compression()100 inline WriteOptions& clear_no_compression() {
101 ClearBit(GRPC_WRITE_NO_COMPRESS);
102 return *this;
103 }
104
105 /// Get value for the flag indicating whether compression for the next
106 /// message write is forcefully disabled.
107 ///
108 /// \sa GRPC_WRITE_NO_COMPRESS
get_no_compression()109 inline bool get_no_compression() const {
110 return GetBit(GRPC_WRITE_NO_COMPRESS);
111 }
112
113 /// Sets flag indicating that the write may be buffered and need not go out on
114 /// the wire immediately.
115 ///
116 /// \sa GRPC_WRITE_BUFFER_HINT
set_buffer_hint()117 inline WriteOptions& set_buffer_hint() {
118 SetBit(GRPC_WRITE_BUFFER_HINT);
119 return *this;
120 }
121
122 /// Clears flag indicating that the write may be buffered and need not go out
123 /// on the wire immediately.
124 ///
125 /// \sa GRPC_WRITE_BUFFER_HINT
clear_buffer_hint()126 inline WriteOptions& clear_buffer_hint() {
127 ClearBit(GRPC_WRITE_BUFFER_HINT);
128 return *this;
129 }
130
131 /// Get value for the flag indicating that the write may be buffered and need
132 /// not go out on the wire immediately.
133 ///
134 /// \sa GRPC_WRITE_BUFFER_HINT
get_buffer_hint()135 inline bool get_buffer_hint() const { return GetBit(GRPC_WRITE_BUFFER_HINT); }
136
137 /// corked bit: aliases set_buffer_hint currently, with the intent that
138 /// set_buffer_hint will be removed in the future
set_corked()139 inline WriteOptions& set_corked() {
140 SetBit(GRPC_WRITE_BUFFER_HINT);
141 return *this;
142 }
143
clear_corked()144 inline WriteOptions& clear_corked() {
145 ClearBit(GRPC_WRITE_BUFFER_HINT);
146 return *this;
147 }
148
is_corked()149 inline bool is_corked() const { return GetBit(GRPC_WRITE_BUFFER_HINT); }
150
151 /// last-message bit: indicates this is the last message in a stream
152 /// client-side: makes Write the equivalent of performing Write, WritesDone
153 /// in a single step
154 /// server-side: hold the Write until the service handler returns (sync api)
155 /// or until Finish is called (async api)
set_last_message()156 inline WriteOptions& set_last_message() {
157 last_message_ = true;
158 return *this;
159 }
160
161 /// Clears flag indicating that this is the last message in a stream,
162 /// disabling coalescing.
clear_last_message()163 inline WriteOptions& clear_last_message() {
164 last_message_ = false;
165 return *this;
166 }
167
168 /// Guarantee that all bytes have been written to the socket before completing
169 /// this write (usually writes are completed when they pass flow control).
set_write_through()170 inline WriteOptions& set_write_through() {
171 SetBit(GRPC_WRITE_THROUGH);
172 return *this;
173 }
174
is_write_through()175 inline bool is_write_through() const { return GetBit(GRPC_WRITE_THROUGH); }
176
177 /// Get value for the flag indicating that this is the last message, and
178 /// should be coalesced with trailing metadata.
179 ///
180 /// \sa GRPC_WRITE_LAST_MESSAGE
is_last_message()181 bool is_last_message() const { return last_message_; }
182
183 private:
SetBit(const uint32_t mask)184 void SetBit(const uint32_t mask) { flags_ |= mask; }
185
ClearBit(const uint32_t mask)186 void ClearBit(const uint32_t mask) { flags_ &= ~mask; }
187
GetBit(const uint32_t mask)188 bool GetBit(const uint32_t mask) const { return (flags_ & mask) != 0; }
189
190 uint32_t flags_;
191 bool last_message_;
192 };
193
194 namespace internal {
195
196 /// Default argument for CallOpSet. The Unused parameter is unused by
197 /// the class, but can be used for generating multiple names for the
198 /// same thing.
199 template <int Unused>
200 class CallNoOp {
201 protected:
AddOp(grpc_op *,size_t *)202 void AddOp(grpc_op* /*ops*/, size_t* /*nops*/) {}
FinishOp(bool *)203 void FinishOp(bool* /*status*/) {}
SetInterceptionHookPoint(InterceptorBatchMethodsImpl *)204 void SetInterceptionHookPoint(
205 InterceptorBatchMethodsImpl* /*interceptor_methods*/) {}
SetFinishInterceptionHookPoint(InterceptorBatchMethodsImpl *)206 void SetFinishInterceptionHookPoint(
207 InterceptorBatchMethodsImpl* /*interceptor_methods*/) {}
SetHijackingState(InterceptorBatchMethodsImpl *)208 void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) {
209 }
210 };
211
212 class CallOpSendInitialMetadata {
213 public:
CallOpSendInitialMetadata()214 CallOpSendInitialMetadata() : send_(false) {
215 maybe_compression_level_.is_set = false;
216 }
217
SendInitialMetadata(std::multimap<std::string,std::string> * metadata,uint32_t flags)218 void SendInitialMetadata(std::multimap<std::string, std::string>* metadata,
219 uint32_t flags) {
220 maybe_compression_level_.is_set = false;
221 send_ = true;
222 flags_ = flags;
223 metadata_map_ = metadata;
224 }
225
set_compression_level(grpc_compression_level level)226 void set_compression_level(grpc_compression_level level) {
227 maybe_compression_level_.is_set = true;
228 maybe_compression_level_.level = level;
229 }
230
231 protected:
AddOp(grpc_op * ops,size_t * nops)232 void AddOp(grpc_op* ops, size_t* nops) {
233 if (!send_ || hijacked_) return;
234 grpc_op* op = &ops[(*nops)++];
235 op->op = GRPC_OP_SEND_INITIAL_METADATA;
236 op->flags = flags_;
237 op->reserved = nullptr;
238 initial_metadata_ =
239 FillMetadataArray(*metadata_map_, &initial_metadata_count_, "");
240 op->data.send_initial_metadata.count = initial_metadata_count_;
241 op->data.send_initial_metadata.metadata = initial_metadata_;
242 op->data.send_initial_metadata.maybe_compression_level.is_set =
243 maybe_compression_level_.is_set;
244 if (maybe_compression_level_.is_set) {
245 op->data.send_initial_metadata.maybe_compression_level.level =
246 maybe_compression_level_.level;
247 }
248 }
FinishOp(bool *)249 void FinishOp(bool* /*status*/) {
250 if (!send_ || hijacked_) return;
251 g_core_codegen_interface->gpr_free(initial_metadata_);
252 send_ = false;
253 }
254
SetInterceptionHookPoint(InterceptorBatchMethodsImpl * interceptor_methods)255 void SetInterceptionHookPoint(
256 InterceptorBatchMethodsImpl* interceptor_methods) {
257 if (!send_) return;
258 interceptor_methods->AddInterceptionHookPoint(
259 experimental::InterceptionHookPoints::PRE_SEND_INITIAL_METADATA);
260 interceptor_methods->SetSendInitialMetadata(metadata_map_);
261 }
262
SetFinishInterceptionHookPoint(InterceptorBatchMethodsImpl *)263 void SetFinishInterceptionHookPoint(
264 InterceptorBatchMethodsImpl* /*interceptor_methods*/) {}
265
SetHijackingState(InterceptorBatchMethodsImpl *)266 void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) {
267 hijacked_ = true;
268 }
269
270 bool hijacked_ = false;
271 bool send_;
272 uint32_t flags_;
273 size_t initial_metadata_count_;
274 std::multimap<std::string, std::string>* metadata_map_;
275 grpc_metadata* initial_metadata_;
276 struct {
277 bool is_set;
278 grpc_compression_level level;
279 } maybe_compression_level_;
280 };
281
282 class CallOpSendMessage {
283 public:
CallOpSendMessage()284 CallOpSendMessage() : send_buf_() {}
285
286 /// Send \a message using \a options for the write. The \a options are cleared
287 /// after use.
288 template <class M>
289 Status SendMessage(const M& message,
290 WriteOptions options) GRPC_MUST_USE_RESULT;
291
292 template <class M>
293 Status SendMessage(const M& message) GRPC_MUST_USE_RESULT;
294
295 /// Send \a message using \a options for the write. The \a options are cleared
296 /// after use. This form of SendMessage allows gRPC to reference \a message
297 /// beyond the lifetime of SendMessage.
298 template <class M>
299 Status SendMessagePtr(const M* message,
300 WriteOptions options) GRPC_MUST_USE_RESULT;
301
302 /// This form of SendMessage allows gRPC to reference \a message beyond the
303 /// lifetime of SendMessage.
304 template <class M>
305 Status SendMessagePtr(const M* message) GRPC_MUST_USE_RESULT;
306
307 protected:
AddOp(grpc_op * ops,size_t * nops)308 void AddOp(grpc_op* ops, size_t* nops) {
309 if (msg_ == nullptr && !send_buf_.Valid()) return;
310 if (hijacked_) {
311 serializer_ = nullptr;
312 return;
313 }
314 if (msg_ != nullptr) {
315 GPR_CODEGEN_ASSERT(serializer_(msg_).ok());
316 }
317 serializer_ = nullptr;
318 grpc_op* op = &ops[(*nops)++];
319 op->op = GRPC_OP_SEND_MESSAGE;
320 op->flags = write_options_.flags();
321 op->reserved = nullptr;
322 op->data.send_message.send_message = send_buf_.c_buffer();
323 // Flags are per-message: clear them after use.
324 write_options_.Clear();
325 }
FinishOp(bool * status)326 void FinishOp(bool* status) {
327 if (msg_ == nullptr && !send_buf_.Valid()) return;
328 send_buf_.Clear();
329 if (hijacked_ && failed_send_) {
330 // Hijacking interceptor failed this Op
331 *status = false;
332 } else if (!*status) {
333 // This Op was passed down to core and the Op failed
334 failed_send_ = true;
335 }
336 }
337
SetInterceptionHookPoint(InterceptorBatchMethodsImpl * interceptor_methods)338 void SetInterceptionHookPoint(
339 InterceptorBatchMethodsImpl* interceptor_methods) {
340 if (msg_ == nullptr && !send_buf_.Valid()) return;
341 interceptor_methods->AddInterceptionHookPoint(
342 experimental::InterceptionHookPoints::PRE_SEND_MESSAGE);
343 interceptor_methods->SetSendMessage(&send_buf_, &msg_, &failed_send_,
344 serializer_);
345 }
346
SetFinishInterceptionHookPoint(InterceptorBatchMethodsImpl * interceptor_methods)347 void SetFinishInterceptionHookPoint(
348 InterceptorBatchMethodsImpl* interceptor_methods) {
349 if (msg_ != nullptr || send_buf_.Valid()) {
350 interceptor_methods->AddInterceptionHookPoint(
351 experimental::InterceptionHookPoints::POST_SEND_MESSAGE);
352 }
353 send_buf_.Clear();
354 msg_ = nullptr;
355 // The contents of the SendMessage value that was previously set
356 // has had its references stolen by core's operations
357 interceptor_methods->SetSendMessage(nullptr, nullptr, &failed_send_,
358 nullptr);
359 }
360
SetHijackingState(InterceptorBatchMethodsImpl *)361 void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) {
362 hijacked_ = true;
363 }
364
365 private:
366 const void* msg_ = nullptr; // The original non-serialized message
367 bool hijacked_ = false;
368 bool failed_send_ = false;
369 ByteBuffer send_buf_;
370 WriteOptions write_options_;
371 std::function<Status(const void*)> serializer_;
372 };
373
374 template <class M>
SendMessage(const M & message,WriteOptions options)375 Status CallOpSendMessage::SendMessage(const M& message, WriteOptions options) {
376 write_options_ = options;
377 // Serialize immediately since we do not have access to the message pointer
378 bool own_buf;
379 // TODO(vjpai): Remove the void below when possible
380 // The void in the template parameter below should not be needed
381 // (since it should be implicit) but is needed due to an observed
382 // difference in behavior between clang and gcc for certain internal users
383 Status result = SerializationTraits<M, void>::Serialize(
384 message, send_buf_.bbuf_ptr(), &own_buf);
385 if (!own_buf) {
386 send_buf_.Duplicate();
387 }
388 return result;
389 }
390
391 template <class M>
SendMessage(const M & message)392 Status CallOpSendMessage::SendMessage(const M& message) {
393 return SendMessage(message, WriteOptions());
394 }
395
396 template <class M>
SendMessagePtr(const M * message,WriteOptions options)397 Status CallOpSendMessage::SendMessagePtr(const M* message,
398 WriteOptions options) {
399 msg_ = message;
400 write_options_ = options;
401 // Store the serializer for later since we have access to the message
402 serializer_ = [this](const void* message) {
403 bool own_buf;
404 // TODO(vjpai): Remove the void below when possible
405 // The void in the template parameter below should not be needed
406 // (since it should be implicit) but is needed due to an observed
407 // difference in behavior between clang and gcc for certain internal users
408 Status result = SerializationTraits<M, void>::Serialize(
409 *static_cast<const M*>(message), send_buf_.bbuf_ptr(), &own_buf);
410 if (!own_buf) {
411 send_buf_.Duplicate();
412 }
413 return result;
414 };
415 return Status();
416 }
417
418 template <class M>
SendMessagePtr(const M * message)419 Status CallOpSendMessage::SendMessagePtr(const M* message) {
420 return SendMessagePtr(message, WriteOptions());
421 }
422
423 template <class R>
424 class CallOpRecvMessage {
425 public:
RecvMessage(R * message)426 void RecvMessage(R* message) { message_ = message; }
427
428 // Do not change status if no message is received.
AllowNoMessage()429 void AllowNoMessage() { allow_not_getting_message_ = true; }
430
431 bool got_message = false;
432
433 protected:
AddOp(grpc_op * ops,size_t * nops)434 void AddOp(grpc_op* ops, size_t* nops) {
435 if (message_ == nullptr || hijacked_) return;
436 grpc_op* op = &ops[(*nops)++];
437 op->op = GRPC_OP_RECV_MESSAGE;
438 op->flags = 0;
439 op->reserved = nullptr;
440 op->data.recv_message.recv_message = recv_buf_.c_buffer_ptr();
441 }
442
FinishOp(bool * status)443 void FinishOp(bool* status) {
444 if (message_ == nullptr) return;
445 if (recv_buf_.Valid()) {
446 if (*status) {
447 got_message = *status =
448 SerializationTraits<R>::Deserialize(recv_buf_.bbuf_ptr(), message_)
449 .ok();
450 recv_buf_.Release();
451 } else {
452 got_message = false;
453 recv_buf_.Clear();
454 }
455 } else if (hijacked_) {
456 if (hijacked_recv_message_failed_) {
457 FinishOpRecvMessageFailureHandler(status);
458 } else {
459 // The op was hijacked and it was successful. There is no further action
460 // to be performed since the message is already in its non-serialized
461 // form.
462 }
463 } else {
464 FinishOpRecvMessageFailureHandler(status);
465 }
466 }
467
SetInterceptionHookPoint(InterceptorBatchMethodsImpl * interceptor_methods)468 void SetInterceptionHookPoint(
469 InterceptorBatchMethodsImpl* interceptor_methods) {
470 if (message_ == nullptr) return;
471 interceptor_methods->SetRecvMessage(message_,
472 &hijacked_recv_message_failed_);
473 }
474
SetFinishInterceptionHookPoint(InterceptorBatchMethodsImpl * interceptor_methods)475 void SetFinishInterceptionHookPoint(
476 InterceptorBatchMethodsImpl* interceptor_methods) {
477 if (message_ == nullptr) return;
478 interceptor_methods->AddInterceptionHookPoint(
479 experimental::InterceptionHookPoints::POST_RECV_MESSAGE);
480 if (!got_message) interceptor_methods->SetRecvMessage(nullptr, nullptr);
481 }
SetHijackingState(InterceptorBatchMethodsImpl * interceptor_methods)482 void SetHijackingState(InterceptorBatchMethodsImpl* interceptor_methods) {
483 hijacked_ = true;
484 if (message_ == nullptr) return;
485 interceptor_methods->AddInterceptionHookPoint(
486 experimental::InterceptionHookPoints::PRE_RECV_MESSAGE);
487 got_message = true;
488 }
489
490 private:
491 // Sets got_message and \a status for a failed recv message op
FinishOpRecvMessageFailureHandler(bool * status)492 void FinishOpRecvMessageFailureHandler(bool* status) {
493 got_message = false;
494 if (!allow_not_getting_message_) {
495 *status = false;
496 }
497 }
498
499 R* message_ = nullptr;
500 ByteBuffer recv_buf_;
501 bool allow_not_getting_message_ = false;
502 bool hijacked_ = false;
503 bool hijacked_recv_message_failed_ = false;
504 };
505
506 class DeserializeFunc {
507 public:
508 virtual Status Deserialize(ByteBuffer* buf) = 0;
~DeserializeFunc()509 virtual ~DeserializeFunc() {}
510 };
511
512 template <class R>
513 class DeserializeFuncType final : public DeserializeFunc {
514 public:
DeserializeFuncType(R * message)515 explicit DeserializeFuncType(R* message) : message_(message) {}
Deserialize(ByteBuffer * buf)516 Status Deserialize(ByteBuffer* buf) override {
517 return SerializationTraits<R>::Deserialize(buf->bbuf_ptr(), message_);
518 }
519
~DeserializeFuncType()520 ~DeserializeFuncType() override {}
521
522 private:
523 R* message_; // Not a managed pointer because management is external to this
524 };
525
526 class CallOpGenericRecvMessage {
527 public:
528 template <class R>
RecvMessage(R * message)529 void RecvMessage(R* message) {
530 // Use an explicit base class pointer to avoid resolution error in the
531 // following unique_ptr::reset for some old implementations.
532 DeserializeFunc* func = new DeserializeFuncType<R>(message);
533 deserialize_.reset(func);
534 message_ = message;
535 }
536
537 // Do not change status if no message is received.
AllowNoMessage()538 void AllowNoMessage() { allow_not_getting_message_ = true; }
539
540 bool got_message = false;
541
542 protected:
AddOp(grpc_op * ops,size_t * nops)543 void AddOp(grpc_op* ops, size_t* nops) {
544 if (!deserialize_ || hijacked_) return;
545 grpc_op* op = &ops[(*nops)++];
546 op->op = GRPC_OP_RECV_MESSAGE;
547 op->flags = 0;
548 op->reserved = nullptr;
549 op->data.recv_message.recv_message = recv_buf_.c_buffer_ptr();
550 }
551
FinishOp(bool * status)552 void FinishOp(bool* status) {
553 if (!deserialize_) return;
554 if (recv_buf_.Valid()) {
555 if (*status) {
556 got_message = true;
557 *status = deserialize_->Deserialize(&recv_buf_).ok();
558 recv_buf_.Release();
559 } else {
560 got_message = false;
561 recv_buf_.Clear();
562 }
563 } else if (hijacked_) {
564 if (hijacked_recv_message_failed_) {
565 FinishOpRecvMessageFailureHandler(status);
566 } else {
567 // The op was hijacked and it was successful. There is no further action
568 // to be performed since the message is already in its non-serialized
569 // form.
570 }
571 } else {
572 got_message = false;
573 if (!allow_not_getting_message_) {
574 *status = false;
575 }
576 }
577 }
578
SetInterceptionHookPoint(InterceptorBatchMethodsImpl * interceptor_methods)579 void SetInterceptionHookPoint(
580 InterceptorBatchMethodsImpl* interceptor_methods) {
581 if (!deserialize_) return;
582 interceptor_methods->SetRecvMessage(message_,
583 &hijacked_recv_message_failed_);
584 }
585
SetFinishInterceptionHookPoint(InterceptorBatchMethodsImpl * interceptor_methods)586 void SetFinishInterceptionHookPoint(
587 InterceptorBatchMethodsImpl* interceptor_methods) {
588 if (!deserialize_) return;
589 interceptor_methods->AddInterceptionHookPoint(
590 experimental::InterceptionHookPoints::POST_RECV_MESSAGE);
591 if (!got_message) interceptor_methods->SetRecvMessage(nullptr, nullptr);
592 deserialize_.reset();
593 }
SetHijackingState(InterceptorBatchMethodsImpl * interceptor_methods)594 void SetHijackingState(InterceptorBatchMethodsImpl* interceptor_methods) {
595 hijacked_ = true;
596 if (!deserialize_) return;
597 interceptor_methods->AddInterceptionHookPoint(
598 experimental::InterceptionHookPoints::PRE_RECV_MESSAGE);
599 got_message = true;
600 }
601
602 private:
603 // Sets got_message and \a status for a failed recv message op
FinishOpRecvMessageFailureHandler(bool * status)604 void FinishOpRecvMessageFailureHandler(bool* status) {
605 got_message = false;
606 if (!allow_not_getting_message_) {
607 *status = false;
608 }
609 }
610
611 void* message_ = nullptr;
612 std::unique_ptr<DeserializeFunc> deserialize_;
613 ByteBuffer recv_buf_;
614 bool allow_not_getting_message_ = false;
615 bool hijacked_ = false;
616 bool hijacked_recv_message_failed_ = false;
617 };
618
619 class CallOpClientSendClose {
620 public:
CallOpClientSendClose()621 CallOpClientSendClose() : send_(false) {}
622
ClientSendClose()623 void ClientSendClose() { send_ = true; }
624
625 protected:
AddOp(grpc_op * ops,size_t * nops)626 void AddOp(grpc_op* ops, size_t* nops) {
627 if (!send_ || hijacked_) return;
628 grpc_op* op = &ops[(*nops)++];
629 op->op = GRPC_OP_SEND_CLOSE_FROM_CLIENT;
630 op->flags = 0;
631 op->reserved = nullptr;
632 }
FinishOp(bool *)633 void FinishOp(bool* /*status*/) { send_ = false; }
634
SetInterceptionHookPoint(InterceptorBatchMethodsImpl * interceptor_methods)635 void SetInterceptionHookPoint(
636 InterceptorBatchMethodsImpl* interceptor_methods) {
637 if (!send_) return;
638 interceptor_methods->AddInterceptionHookPoint(
639 experimental::InterceptionHookPoints::PRE_SEND_CLOSE);
640 }
641
SetFinishInterceptionHookPoint(InterceptorBatchMethodsImpl *)642 void SetFinishInterceptionHookPoint(
643 InterceptorBatchMethodsImpl* /*interceptor_methods*/) {}
644
SetHijackingState(InterceptorBatchMethodsImpl *)645 void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) {
646 hijacked_ = true;
647 }
648
649 private:
650 bool hijacked_ = false;
651 bool send_;
652 };
653
654 class CallOpServerSendStatus {
655 public:
CallOpServerSendStatus()656 CallOpServerSendStatus() : send_status_available_(false) {}
657
ServerSendStatus(std::multimap<std::string,std::string> * trailing_metadata,const Status & status)658 void ServerSendStatus(
659 std::multimap<std::string, std::string>* trailing_metadata,
660 const Status& status) {
661 send_error_details_ = status.error_details();
662 metadata_map_ = trailing_metadata;
663 send_status_available_ = true;
664 send_status_code_ = static_cast<grpc_status_code>(status.error_code());
665 send_error_message_ = status.error_message();
666 }
667
668 protected:
AddOp(grpc_op * ops,size_t * nops)669 void AddOp(grpc_op* ops, size_t* nops) {
670 if (!send_status_available_ || hijacked_) return;
671 trailing_metadata_ = FillMetadataArray(
672 *metadata_map_, &trailing_metadata_count_, send_error_details_);
673 grpc_op* op = &ops[(*nops)++];
674 op->op = GRPC_OP_SEND_STATUS_FROM_SERVER;
675 op->data.send_status_from_server.trailing_metadata_count =
676 trailing_metadata_count_;
677 op->data.send_status_from_server.trailing_metadata = trailing_metadata_;
678 op->data.send_status_from_server.status = send_status_code_;
679 error_message_slice_ = SliceReferencingString(send_error_message_);
680 op->data.send_status_from_server.status_details =
681 send_error_message_.empty() ? nullptr : &error_message_slice_;
682 op->flags = 0;
683 op->reserved = nullptr;
684 }
685
FinishOp(bool *)686 void FinishOp(bool* /*status*/) {
687 if (!send_status_available_ || hijacked_) return;
688 g_core_codegen_interface->gpr_free(trailing_metadata_);
689 send_status_available_ = false;
690 }
691
SetInterceptionHookPoint(InterceptorBatchMethodsImpl * interceptor_methods)692 void SetInterceptionHookPoint(
693 InterceptorBatchMethodsImpl* interceptor_methods) {
694 if (!send_status_available_) return;
695 interceptor_methods->AddInterceptionHookPoint(
696 experimental::InterceptionHookPoints::PRE_SEND_STATUS);
697 interceptor_methods->SetSendTrailingMetadata(metadata_map_);
698 interceptor_methods->SetSendStatus(&send_status_code_, &send_error_details_,
699 &send_error_message_);
700 }
701
SetFinishInterceptionHookPoint(InterceptorBatchMethodsImpl *)702 void SetFinishInterceptionHookPoint(
703 InterceptorBatchMethodsImpl* /*interceptor_methods*/) {}
704
SetHijackingState(InterceptorBatchMethodsImpl *)705 void SetHijackingState(InterceptorBatchMethodsImpl* /*interceptor_methods*/) {
706 hijacked_ = true;
707 }
708
709 private:
710 bool hijacked_ = false;
711 bool send_status_available_;
712 grpc_status_code send_status_code_;
713 std::string send_error_details_;
714 std::string send_error_message_;
715 size_t trailing_metadata_count_;
716 std::multimap<std::string, std::string>* metadata_map_;
717 grpc_metadata* trailing_metadata_;
718 grpc_slice error_message_slice_;
719 };
720
721 class CallOpRecvInitialMetadata {
722 public:
CallOpRecvInitialMetadata()723 CallOpRecvInitialMetadata() : metadata_map_(nullptr) {}
724
RecvInitialMetadata(::grpc::ClientContext * context)725 void RecvInitialMetadata(::grpc::ClientContext* context) {
726 context->initial_metadata_received_ = true;
727 metadata_map_ = &context->recv_initial_metadata_;
728 }
729
730 protected:
AddOp(grpc_op * ops,size_t * nops)731 void AddOp(grpc_op* ops, size_t* nops) {
732 if (metadata_map_ == nullptr || hijacked_) return;
733 grpc_op* op = &ops[(*nops)++];
734 op->op = GRPC_OP_RECV_INITIAL_METADATA;
735 op->data.recv_initial_metadata.recv_initial_metadata = metadata_map_->arr();
736 op->flags = 0;
737 op->reserved = nullptr;
738 }
739
FinishOp(bool *)740 void FinishOp(bool* /*status*/) {
741 if (metadata_map_ == nullptr || hijacked_) return;
742 }
743
SetInterceptionHookPoint(InterceptorBatchMethodsImpl * interceptor_methods)744 void SetInterceptionHookPoint(
745 InterceptorBatchMethodsImpl* interceptor_methods) {
746 interceptor_methods->SetRecvInitialMetadata(metadata_map_);
747 }
748
SetFinishInterceptionHookPoint(InterceptorBatchMethodsImpl * interceptor_methods)749 void SetFinishInterceptionHookPoint(
750 InterceptorBatchMethodsImpl* interceptor_methods) {
751 if (metadata_map_ == nullptr) return;
752 interceptor_methods->AddInterceptionHookPoint(
753 experimental::InterceptionHookPoints::POST_RECV_INITIAL_METADATA);
754 metadata_map_ = nullptr;
755 }
756
SetHijackingState(InterceptorBatchMethodsImpl * interceptor_methods)757 void SetHijackingState(InterceptorBatchMethodsImpl* interceptor_methods) {
758 hijacked_ = true;
759 if (metadata_map_ == nullptr) return;
760 interceptor_methods->AddInterceptionHookPoint(
761 experimental::InterceptionHookPoints::PRE_RECV_INITIAL_METADATA);
762 }
763
764 private:
765 bool hijacked_ = false;
766 MetadataMap* metadata_map_;
767 };
768
769 class CallOpClientRecvStatus {
770 public:
CallOpClientRecvStatus()771 CallOpClientRecvStatus()
772 : recv_status_(nullptr), debug_error_string_(nullptr) {}
773
ClientRecvStatus(::grpc::ClientContext * context,Status * status)774 void ClientRecvStatus(::grpc::ClientContext* context, Status* status) {
775 client_context_ = context;
776 metadata_map_ = &client_context_->trailing_metadata_;
777 recv_status_ = status;
778 error_message_ = g_core_codegen_interface->grpc_empty_slice();
779 }
780
781 protected:
AddOp(grpc_op * ops,size_t * nops)782 void AddOp(grpc_op* ops, size_t* nops) {
783 if (recv_status_ == nullptr || hijacked_) return;
784 grpc_op* op = &ops[(*nops)++];
785 op->op = GRPC_OP_RECV_STATUS_ON_CLIENT;
786 op->data.recv_status_on_client.trailing_metadata = metadata_map_->arr();
787 op->data.recv_status_on_client.status = &status_code_;
788 op->data.recv_status_on_client.status_details = &error_message_;
789 op->data.recv_status_on_client.error_string = &debug_error_string_;
790 op->flags = 0;
791 op->reserved = nullptr;
792 }
793
FinishOp(bool *)794 void FinishOp(bool* /*status*/) {
795 if (recv_status_ == nullptr || hijacked_) return;
796 if (static_cast<StatusCode>(status_code_) == StatusCode::OK) {
797 *recv_status_ = Status();
798 GPR_CODEGEN_DEBUG_ASSERT(debug_error_string_ == nullptr);
799 } else {
800 *recv_status_ =
801 Status(static_cast<StatusCode>(status_code_),
802 GRPC_SLICE_IS_EMPTY(error_message_)
803 ? std::string()
804 : std::string(GRPC_SLICE_START_PTR(error_message_),
805 GRPC_SLICE_END_PTR(error_message_)),
806 metadata_map_->GetBinaryErrorDetails());
807 if (debug_error_string_ != nullptr) {
808 client_context_->set_debug_error_string(debug_error_string_);
809 g_core_codegen_interface->gpr_free(
810 const_cast<char*>(debug_error_string_));
811 }
812 }
813 // TODO(soheil): Find callers that set debug string even for status OK,
814 // and fix them.
815 g_core_codegen_interface->grpc_slice_unref(error_message_);
816 }
817
SetInterceptionHookPoint(InterceptorBatchMethodsImpl * interceptor_methods)818 void SetInterceptionHookPoint(
819 InterceptorBatchMethodsImpl* interceptor_methods) {
820 interceptor_methods->SetRecvStatus(recv_status_);
821 interceptor_methods->SetRecvTrailingMetadata(metadata_map_);
822 }
823
SetFinishInterceptionHookPoint(InterceptorBatchMethodsImpl * interceptor_methods)824 void SetFinishInterceptionHookPoint(
825 InterceptorBatchMethodsImpl* interceptor_methods) {
826 if (recv_status_ == nullptr) return;
827 interceptor_methods->AddInterceptionHookPoint(
828 experimental::InterceptionHookPoints::POST_RECV_STATUS);
829 recv_status_ = nullptr;
830 }
831
SetHijackingState(InterceptorBatchMethodsImpl * interceptor_methods)832 void SetHijackingState(InterceptorBatchMethodsImpl* interceptor_methods) {
833 hijacked_ = true;
834 if (recv_status_ == nullptr) return;
835 interceptor_methods->AddInterceptionHookPoint(
836 experimental::InterceptionHookPoints::PRE_RECV_STATUS);
837 }
838
839 private:
840 bool hijacked_ = false;
841 ::grpc::ClientContext* client_context_;
842 MetadataMap* metadata_map_;
843 Status* recv_status_;
844 const char* debug_error_string_;
845 grpc_status_code status_code_;
846 grpc_slice error_message_;
847 };
848
849 template <class Op1 = CallNoOp<1>, class Op2 = CallNoOp<2>,
850 class Op3 = CallNoOp<3>, class Op4 = CallNoOp<4>,
851 class Op5 = CallNoOp<5>, class Op6 = CallNoOp<6>>
852 class CallOpSet;
853
854 /// Primary implementation of CallOpSetInterface.
855 /// Since we cannot use variadic templates, we declare slots up to
856 /// the maximum count of ops we'll need in a set. We leverage the
857 /// empty base class optimization to slim this class (especially
858 /// when there are many unused slots used). To avoid duplicate base classes,
859 /// the template parameter for CallNoOp is varied by argument position.
860 template <class Op1, class Op2, class Op3, class Op4, class Op5, class Op6>
861 class CallOpSet : public CallOpSetInterface,
862 public Op1,
863 public Op2,
864 public Op3,
865 public Op4,
866 public Op5,
867 public Op6 {
868 public:
CallOpSet()869 CallOpSet() : core_cq_tag_(this), return_tag_(this) {}
870 // The copy constructor and assignment operator reset the value of
871 // core_cq_tag_, return_tag_, done_intercepting_ and interceptor_methods_
872 // since those are only meaningful on a specific object, not across objects.
CallOpSet(const CallOpSet & other)873 CallOpSet(const CallOpSet& other)
874 : core_cq_tag_(this),
875 return_tag_(this),
876 call_(other.call_),
877 done_intercepting_(false),
878 interceptor_methods_(InterceptorBatchMethodsImpl()) {}
879
880 CallOpSet& operator=(const CallOpSet& other) {
881 core_cq_tag_ = this;
882 return_tag_ = this;
883 call_ = other.call_;
884 done_intercepting_ = false;
885 interceptor_methods_ = InterceptorBatchMethodsImpl();
886 return *this;
887 }
888
FillOps(Call * call)889 void FillOps(Call* call) override {
890 done_intercepting_ = false;
891 g_core_codegen_interface->grpc_call_ref(call->call());
892 call_ =
893 *call; // It's fine to create a copy of call since it's just pointers
894
895 if (RunInterceptors()) {
896 ContinueFillOpsAfterInterception();
897 } else {
898 // After the interceptors are run, ContinueFillOpsAfterInterception will
899 // be run
900 }
901 }
902
FinalizeResult(void ** tag,bool * status)903 bool FinalizeResult(void** tag, bool* status) override {
904 if (done_intercepting_) {
905 // Complete the avalanching since we are done with this batch of ops
906 call_.cq()->CompleteAvalanching();
907 // We have already finished intercepting and filling in the results. This
908 // round trip from the core needed to be made because interceptors were
909 // run
910 *tag = return_tag_;
911 *status = saved_status_;
912 g_core_codegen_interface->grpc_call_unref(call_.call());
913 return true;
914 }
915
916 this->Op1::FinishOp(status);
917 this->Op2::FinishOp(status);
918 this->Op3::FinishOp(status);
919 this->Op4::FinishOp(status);
920 this->Op5::FinishOp(status);
921 this->Op6::FinishOp(status);
922 saved_status_ = *status;
923 if (RunInterceptorsPostRecv()) {
924 *tag = return_tag_;
925 g_core_codegen_interface->grpc_call_unref(call_.call());
926 return true;
927 }
928 // Interceptors are going to be run, so we can't return the tag just yet.
929 // After the interceptors are run, ContinueFinalizeResultAfterInterception
930 return false;
931 }
932
set_output_tag(void * return_tag)933 void set_output_tag(void* return_tag) { return_tag_ = return_tag; }
934
core_cq_tag()935 void* core_cq_tag() override { return core_cq_tag_; }
936
937 /// set_core_cq_tag is used to provide a different core CQ tag than "this".
938 /// This is used for callback-based tags, where the core tag is the core
939 /// callback function. It does not change the use or behavior of any other
940 /// function (such as FinalizeResult)
set_core_cq_tag(void * core_cq_tag)941 void set_core_cq_tag(void* core_cq_tag) { core_cq_tag_ = core_cq_tag; }
942
943 // This will be called while interceptors are run if the RPC is a hijacked
944 // RPC. This should set hijacking state for each of the ops.
SetHijackingState()945 void SetHijackingState() override {
946 this->Op1::SetHijackingState(&interceptor_methods_);
947 this->Op2::SetHijackingState(&interceptor_methods_);
948 this->Op3::SetHijackingState(&interceptor_methods_);
949 this->Op4::SetHijackingState(&interceptor_methods_);
950 this->Op5::SetHijackingState(&interceptor_methods_);
951 this->Op6::SetHijackingState(&interceptor_methods_);
952 }
953
954 // Should be called after interceptors are done running
ContinueFillOpsAfterInterception()955 void ContinueFillOpsAfterInterception() override {
956 static const size_t MAX_OPS = 6;
957 grpc_op ops[MAX_OPS];
958 size_t nops = 0;
959 this->Op1::AddOp(ops, &nops);
960 this->Op2::AddOp(ops, &nops);
961 this->Op3::AddOp(ops, &nops);
962 this->Op4::AddOp(ops, &nops);
963 this->Op5::AddOp(ops, &nops);
964 this->Op6::AddOp(ops, &nops);
965
966 grpc_call_error err = g_core_codegen_interface->grpc_call_start_batch(
967 call_.call(), ops, nops, core_cq_tag(), nullptr);
968
969 if (err != GRPC_CALL_OK) {
970 // A failure here indicates an API misuse; for example, doing a Write
971 // while another Write is already pending on the same RPC or invoking
972 // WritesDone multiple times
973 // gpr_log(GPR_ERROR, "API misuse of type %s observed",
974 // g_core_codegen_interface->grpc_call_error_to_string(err));
975 GPR_CODEGEN_ASSERT(false);
976 }
977 }
978
979 // Should be called after interceptors are done running on the finalize result
980 // path
ContinueFinalizeResultAfterInterception()981 void ContinueFinalizeResultAfterInterception() override {
982 done_intercepting_ = true;
983 // The following call_start_batch is internally-generated so no need for an
984 // explanatory log on failure.
985 GPR_CODEGEN_ASSERT(g_core_codegen_interface->grpc_call_start_batch(
986 call_.call(), nullptr, 0, core_cq_tag(), nullptr) ==
987 GRPC_CALL_OK);
988 }
989
990 private:
991 // Returns true if no interceptors need to be run
RunInterceptors()992 bool RunInterceptors() {
993 interceptor_methods_.ClearState();
994 interceptor_methods_.SetCallOpSetInterface(this);
995 interceptor_methods_.SetCall(&call_);
996 this->Op1::SetInterceptionHookPoint(&interceptor_methods_);
997 this->Op2::SetInterceptionHookPoint(&interceptor_methods_);
998 this->Op3::SetInterceptionHookPoint(&interceptor_methods_);
999 this->Op4::SetInterceptionHookPoint(&interceptor_methods_);
1000 this->Op5::SetInterceptionHookPoint(&interceptor_methods_);
1001 this->Op6::SetInterceptionHookPoint(&interceptor_methods_);
1002 if (interceptor_methods_.InterceptorsListEmpty()) {
1003 return true;
1004 }
1005 // This call will go through interceptors and would need to
1006 // schedule new batches, so delay completion queue shutdown
1007 call_.cq()->RegisterAvalanching();
1008 return interceptor_methods_.RunInterceptors();
1009 }
1010 // Returns true if no interceptors need to be run
RunInterceptorsPostRecv()1011 bool RunInterceptorsPostRecv() {
1012 // Call and OpSet had already been set on the set state.
1013 // SetReverse also clears previously set hook points
1014 interceptor_methods_.SetReverse();
1015 this->Op1::SetFinishInterceptionHookPoint(&interceptor_methods_);
1016 this->Op2::SetFinishInterceptionHookPoint(&interceptor_methods_);
1017 this->Op3::SetFinishInterceptionHookPoint(&interceptor_methods_);
1018 this->Op4::SetFinishInterceptionHookPoint(&interceptor_methods_);
1019 this->Op5::SetFinishInterceptionHookPoint(&interceptor_methods_);
1020 this->Op6::SetFinishInterceptionHookPoint(&interceptor_methods_);
1021 return interceptor_methods_.RunInterceptors();
1022 }
1023
1024 void* core_cq_tag_;
1025 void* return_tag_;
1026 Call call_;
1027 bool done_intercepting_ = false;
1028 InterceptorBatchMethodsImpl interceptor_methods_;
1029 bool saved_status_;
1030 };
1031
1032 } // namespace internal
1033 } // namespace grpc
1034
1035 #endif // GRPCPP_IMPL_CODEGEN_CALL_OP_SET_H
1036