1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
pub mod client;
pub mod server;
use std::fmt::{self, Debug, Display};
use std::pin::Pin;
use std::sync::Arc;
use std::{ptr, slice};
use crate::grpc_sys::{self, grpc_call, grpc_call_error, grpcwrap_batch_context};
use crate::{cq::CompletionQueue, Metadata, MetadataBuilder};
use futures::future::Future;
use futures::ready;
use futures::task::{Context, Poll};
use libc::c_void;
use parking_lot::Mutex;
use crate::buf::{GrpcByteBuffer, GrpcByteBufferReader, GrpcSlice};
use crate::codec::{DeserializeFn, Marshaller, SerializeFn};
use crate::error::{Error, Result};
use crate::grpc_sys::grpc_status_code::*;
use crate::task::{self, BatchFuture, BatchType, CallTag};
#[derive(PartialEq, Eq, Clone, Copy)]
pub struct RpcStatusCode(i32);
impl From<i32> for RpcStatusCode {
fn from(code: i32) -> RpcStatusCode {
RpcStatusCode(code)
}
}
impl From<RpcStatusCode> for i32 {
fn from(code: RpcStatusCode) -> i32 {
code.0
}
}
impl Display for RpcStatusCode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Debug::fmt(self, f)
}
}
macro_rules! status_codes {
(
$(
($num:path, $konst:ident);
)+
) => {
impl RpcStatusCode {
$(
pub const $konst: RpcStatusCode = RpcStatusCode($num);
)+
}
impl Debug for RpcStatusCode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{}-{}",
self.0,
match self {
$(RpcStatusCode($num) => stringify!($konst),)+
RpcStatusCode(_) => "INVALID_STATUS_CODE",
}
)
}
}
}
}
status_codes! {
(GRPC_STATUS_OK, OK);
(GRPC_STATUS_CANCELLED, CANCELLED);
(GRPC_STATUS_UNKNOWN, UNKNOWN);
(GRPC_STATUS_INVALID_ARGUMENT, INVALID_ARGUMENT);
(GRPC_STATUS_DEADLINE_EXCEEDED, DEADLINE_EXCEEDED);
(GRPC_STATUS_NOT_FOUND, NOT_FOUND);
(GRPC_STATUS_ALREADY_EXISTS, ALREADY_EXISTS);
(GRPC_STATUS_PERMISSION_DENIED, PERMISSION_DENIED);
(GRPC_STATUS_RESOURCE_EXHAUSTED, RESOURCE_EXHAUSTED);
(GRPC_STATUS_FAILED_PRECONDITION, FAILED_PRECONDITION);
(GRPC_STATUS_ABORTED, ABORTED);
(GRPC_STATUS_OUT_OF_RANGE, OUT_OF_RANGE);
(GRPC_STATUS_UNIMPLEMENTED, UNIMPLEMENTED);
(GRPC_STATUS_INTERNAL, INTERNAL);
(GRPC_STATUS_UNAVAILABLE, UNAVAILABLE);
(GRPC_STATUS_DATA_LOSS, DATA_LOSS);
(GRPC_STATUS_UNAUTHENTICATED, UNAUTHENTICATED);
(GRPC_STATUS__DO_NOT_USE, DO_NOT_USE);
}
#[derive(Clone, Copy)]
pub enum MethodType {
Unary,
ClientStreaming,
ServerStreaming,
Duplex,
}
pub struct Method<Req, Resp> {
pub ty: MethodType,
pub name: &'static str,
pub req_mar: Marshaller<Req>,
pub resp_mar: Marshaller<Resp>,
}
impl<Req, Resp> Method<Req, Resp> {
#[inline]
pub fn req_ser(&self) -> SerializeFn<Req> {
self.req_mar.ser
}
#[inline]
pub fn req_de(&self) -> DeserializeFn<Req> {
self.req_mar.de
}
#[inline]
pub fn resp_ser(&self) -> SerializeFn<Resp> {
self.resp_mar.ser
}
#[inline]
pub fn resp_de(&self) -> DeserializeFn<Resp> {
self.resp_mar.de
}
}
#[derive(Debug, Clone)]
pub struct RpcStatus {
code: RpcStatusCode,
message: String,
details: Vec<u8>,
}
impl Display for RpcStatus {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
Debug::fmt(self, fmt)
}
}
impl RpcStatus {
pub fn new<T: Into<RpcStatusCode>>(code: T) -> RpcStatus {
RpcStatus::with_message(code, String::new())
}
pub fn with_message<T: Into<RpcStatusCode>>(code: T, message: String) -> RpcStatus {
RpcStatus::with_details(code, message, vec![])
}
pub fn with_details<T: Into<RpcStatusCode>>(
code: T,
message: String,
details: Vec<u8>,
) -> RpcStatus {
RpcStatus {
code: code.into(),
message,
details,
}
}
pub fn ok() -> RpcStatus {
RpcStatus::new(RpcStatusCode::OK)
}
#[inline]
pub fn code(&self) -> RpcStatusCode {
self.code
}
#[inline]
pub fn message(&self) -> &str {
&self.message
}
pub fn details(&self) -> &[u8] {
&self.details
}
}
pub type MessageReader = GrpcByteBufferReader;
pub struct BatchContext {
ctx: *mut grpcwrap_batch_context,
}
impl BatchContext {
pub fn new() -> BatchContext {
BatchContext {
ctx: unsafe { grpc_sys::grpcwrap_batch_context_create() },
}
}
pub fn as_ptr(&self) -> *mut grpcwrap_batch_context {
self.ctx
}
pub fn take_recv_message(&self) -> Option<GrpcByteBuffer> {
let ptr = unsafe { grpc_sys::grpcwrap_batch_context_take_recv_message(self.ctx) };
if ptr.is_null() {
None
} else {
Some(unsafe { GrpcByteBuffer::from_raw(ptr) })
}
}
pub fn rpc_status(&self) -> RpcStatus {
let status = RpcStatusCode(unsafe {
grpc_sys::grpcwrap_batch_context_recv_status_on_client_status(self.ctx)
});
if status == RpcStatusCode::OK {
RpcStatus::ok()
} else {
unsafe {
let mut msg_len = 0;
let details_ptr = grpc_sys::grpcwrap_batch_context_recv_status_on_client_details(
self.ctx,
&mut msg_len,
);
let msg_slice = slice::from_raw_parts(details_ptr as *const _, msg_len);
let message = String::from_utf8_lossy(msg_slice).into_owned();
let m_ptr =
grpc_sys::grpcwrap_batch_context_recv_status_on_client_trailing_metadata(
self.ctx,
);
let metadata = &*(m_ptr as *const Metadata);
let details = metadata.search_binary_error_details().to_vec();
RpcStatus::with_details(status, message, details)
}
}
}
pub fn recv_message(&mut self) -> Option<MessageReader> {
let buf = self.take_recv_message()?;
Some(GrpcByteBufferReader::new(buf))
}
}
impl Drop for BatchContext {
fn drop(&mut self) {
unsafe { grpc_sys::grpcwrap_batch_context_destroy(self.ctx) }
}
}
#[inline]
fn box_batch_tag(tag: CallTag) -> (*mut grpcwrap_batch_context, *mut c_void) {
let tag_box = Box::new(tag);
(
tag_box.batch_ctx().unwrap().as_ptr(),
Box::into_raw(tag_box) as _,
)
}
fn check_run<F>(bt: BatchType, f: F) -> BatchFuture
where
F: FnOnce(*mut grpcwrap_batch_context, *mut c_void) -> grpc_call_error,
{
let (cq_f, tag) = CallTag::batch_pair(bt);
let (batch_ptr, tag_ptr) = box_batch_tag(tag);
let code = f(batch_ptr, tag_ptr);
if code != grpc_call_error::GRPC_CALL_OK {
unsafe {
Box::from_raw(tag_ptr);
}
panic!("create call fail: {:?}", code);
}
cq_f
}
pub struct Call {
pub call: *mut grpc_call,
pub cq: CompletionQueue,
}
unsafe impl Send for Call {}
impl Call {
pub unsafe fn from_raw(call: *mut grpc_sys::grpc_call, cq: CompletionQueue) -> Call {
assert!(!call.is_null());
Call { call, cq }
}
pub fn start_send_message(
&mut self,
msg: &mut GrpcSlice,
write_flags: u32,
initial_meta: bool,
) -> Result<BatchFuture> {
let _cq_ref = self.cq.borrow()?;
let i = if initial_meta { 1 } else { 0 };
let f = check_run(BatchType::Finish, |ctx, tag| unsafe {
grpc_sys::grpcwrap_call_send_message(
self.call,
ctx,
msg.as_mut_ptr(),
write_flags,
i,
tag,
)
});
Ok(f)
}
pub fn start_send_close_client(&mut self) -> Result<BatchFuture> {
let _cq_ref = self.cq.borrow()?;
let f = check_run(BatchType::Finish, |_, tag| unsafe {
grpc_sys::grpcwrap_call_send_close_from_client(self.call, tag)
});
Ok(f)
}
pub fn start_recv_message(&mut self) -> Result<BatchFuture> {
let _cq_ref = self.cq.borrow()?;
let f = check_run(BatchType::Read, |ctx, tag| unsafe {
grpc_sys::grpcwrap_call_recv_message(self.call, ctx, tag)
});
Ok(f)
}
pub fn start_server_side(&mut self) -> Result<BatchFuture> {
let _cq_ref = self.cq.borrow()?;
let f = check_run(BatchType::Finish, |ctx, tag| unsafe {
grpc_sys::grpcwrap_call_start_serverside(self.call, ctx, tag)
});
Ok(f)
}
pub fn start_send_status_from_server(
&mut self,
status: &RpcStatus,
send_empty_metadata: bool,
payload: &mut Option<GrpcSlice>,
write_flags: u32,
) -> Result<BatchFuture> {
let _cq_ref = self.cq.borrow()?;
let send_empty_metadata = if send_empty_metadata { 1 } else { 0 };
let f = check_run(BatchType::Finish, |ctx, tag| unsafe {
let (msg_ptr, msg_len) = if status.code() == RpcStatusCode::OK {
(ptr::null(), 0)
} else {
(status.message.as_ptr(), status.message.len())
};
let payload_p = match payload {
Some(p) => p.as_mut_ptr(),
None => ptr::null_mut(),
};
let mut trailing_metadata = if status.details.is_empty() {
None
} else {
let mut builder = MetadataBuilder::new();
builder.set_binary_error_details(&status.details);
Some(builder.build())
};
grpc_sys::grpcwrap_call_send_status_from_server(
self.call,
ctx,
status.code().into(),
msg_ptr as _,
msg_len,
trailing_metadata
.as_mut()
.map_or_else(ptr::null_mut, |m| m as *mut _ as _),
send_empty_metadata,
payload_p,
write_flags,
tag,
)
});
Ok(f)
}
pub fn abort(self, status: &RpcStatus) {
match self.cq.borrow() {
Err(Error::QueueShutdown) => return,
Err(e) => panic!("unexpected error when aborting call: {:?}", e),
_ => {}
}
let call_ptr = self.call;
let tag = CallTag::abort(self);
let (batch_ptr, tag_ptr) = box_batch_tag(tag);
let code = unsafe {
let (msg_ptr, msg_len) = if status.code() == RpcStatusCode::OK {
(ptr::null(), 0)
} else {
(status.message.as_ptr(), status.message.len())
};
grpc_sys::grpcwrap_call_send_status_from_server(
call_ptr,
batch_ptr,
status.code().into(),
msg_ptr as _,
msg_len,
ptr::null_mut(),
1,
ptr::null_mut(),
0,
tag_ptr as *mut c_void,
)
};
if code != grpc_call_error::GRPC_CALL_OK {
unsafe {
Box::from_raw(tag_ptr);
}
panic!("create call fail: {:?}", code);
}
}
fn cancel(&self) {
match self.cq.borrow() {
Err(Error::QueueShutdown) => return,
Err(e) => panic!("unexpected error when canceling call: {:?}", e),
_ => {}
}
unsafe {
grpc_sys::grpc_call_cancel(self.call, ptr::null_mut());
}
}
}
impl Drop for Call {
fn drop(&mut self) {
unsafe { grpc_sys::grpc_call_unref(self.call) }
}
}
struct ShareCall {
call: Call,
close_f: BatchFuture,
finished: bool,
status: Option<RpcStatus>,
}
impl ShareCall {
fn new(call: Call, close_f: BatchFuture) -> ShareCall {
ShareCall {
call,
close_f,
finished: false,
status: None,
}
}
fn poll_finish(&mut self, cx: &mut Context) -> Poll<Result<Option<MessageReader>>> {
let res = match Pin::new(&mut self.close_f).poll(cx) {
Poll::Ready(Ok(reader)) => {
self.status = Some(RpcStatus::ok());
Poll::Ready(Ok(reader))
}
Poll::Pending => return Poll::Pending,
Poll::Ready(Err(Error::RpcFailure(status))) => {
self.status = Some(status.clone());
Poll::Ready(Err(Error::RpcFailure(status)))
}
res => res,
};
self.finished = true;
res
}
fn check_alive(&mut self) -> Result<()> {
if self.finished {
return Err(Error::RpcFinished(self.status.clone()));
}
task::check_alive(&self.close_f)
}
}
trait ShareCallHolder {
fn call<R, F: FnOnce(&mut ShareCall) -> R>(&mut self, f: F) -> R;
}
impl ShareCallHolder for ShareCall {
fn call<R, F: FnOnce(&mut ShareCall) -> R>(&mut self, f: F) -> R {
f(self)
}
}
impl ShareCallHolder for Arc<Mutex<ShareCall>> {
fn call<R, F: FnOnce(&mut ShareCall) -> R>(&mut self, f: F) -> R {
let mut call = self.lock();
f(&mut call)
}
}
struct StreamingBase {
close_f: Option<BatchFuture>,
msg_f: Option<BatchFuture>,
read_done: bool,
}
impl StreamingBase {
fn new(close_f: Option<BatchFuture>) -> StreamingBase {
StreamingBase {
close_f,
msg_f: None,
read_done: false,
}
}
fn poll<C: ShareCallHolder>(
&mut self,
cx: &mut Context,
call: &mut C,
skip_finish_check: bool,
) -> Poll<Option<Result<MessageReader>>> {
if !skip_finish_check {
let mut finished = false;
if let Some(close_f) = &mut self.close_f {
if Pin::new(close_f).poll(cx)?.is_ready() {
finished = true;
}
}
if finished {
self.close_f.take();
}
}
let mut bytes = None;
if !self.read_done {
if let Some(msg_f) = &mut self.msg_f {
bytes = ready!(Pin::new(msg_f).poll(cx)?);
if bytes.is_none() {
self.read_done = true;
}
}
}
if self.read_done {
if self.close_f.is_none() {
return Poll::Ready(None);
}
return Poll::Pending;
}
self.msg_f.take();
let msg_f = call.call(|c| c.call.start_recv_message())?;
self.msg_f = Some(msg_f);
if bytes.is_none() {
self.poll(cx, call, true)
} else {
Poll::Ready(bytes.map(Ok))
}
}
fn on_drop<C: ShareCallHolder>(&self, call: &mut C) {
if !self.read_done || self.close_f.is_some() {
call.call(|c| c.call.cancel());
}
}
}
#[derive(Default, Clone, Copy)]
pub struct WriteFlags {
flags: u32,
}
impl WriteFlags {
pub fn buffer_hint(mut self, need_buffered: bool) -> WriteFlags {
client::change_flag(
&mut self.flags,
grpc_sys::GRPC_WRITE_BUFFER_HINT,
need_buffered,
);
self
}
pub fn force_no_compress(mut self, no_compress: bool) -> WriteFlags {
client::change_flag(
&mut self.flags,
grpc_sys::GRPC_WRITE_NO_COMPRESS,
no_compress,
);
self
}
pub fn get_buffer_hint(self) -> bool {
(self.flags & grpc_sys::GRPC_WRITE_BUFFER_HINT) != 0
}
pub fn get_force_no_compress(self) -> bool {
(self.flags & grpc_sys::GRPC_WRITE_NO_COMPRESS) != 0
}
}
struct SinkBase {
batch_f: Option<BatchFuture>,
send_metadata: bool,
enhance_buffer_strategy: bool,
buffer: GrpcSlice,
buf_flags: Option<WriteFlags>,
last_buf_hint: bool,
}
impl SinkBase {
fn new(send_metadata: bool) -> SinkBase {
SinkBase {
batch_f: None,
buffer: GrpcSlice::default(),
buf_flags: None,
last_buf_hint: true,
send_metadata,
enhance_buffer_strategy: false,
}
}
fn start_send<T, C: ShareCallHolder>(
&mut self,
call: &mut C,
t: &T,
flags: WriteFlags,
ser: SerializeFn<T>,
) -> Result<()> {
if self.send_metadata {
ser(t, &mut self.buffer);
self.buf_flags = Some(flags);
self.start_send_buffer_message(false, call)?;
self.send_metadata = false;
return Ok(());
}
if self.buf_flags.is_some() {
self.start_send_buffer_message(true, call)?;
}
ser(t, &mut self.buffer);
let hint = flags.get_buffer_hint();
self.last_buf_hint &= hint;
self.buf_flags = Some(flags);
if !self.enhance_buffer_strategy {
self.start_send_buffer_message(hint, call)?;
}
Ok(())
}
#[inline]
fn poll_ready(&mut self, cx: &mut Context) -> Poll<Result<()>> {
match &mut self.batch_f {
None => return Poll::Ready(Ok(())),
Some(f) => {
ready!(Pin::new(f).poll(cx)?);
}
}
self.batch_f.take();
Poll::Ready(Ok(()))
}
#[inline]
fn poll_flush<C: ShareCallHolder>(
&mut self,
cx: &mut Context,
call: &mut C,
) -> Poll<Result<()>> {
if self.batch_f.is_some() {
ready!(self.poll_ready(cx)?);
}
if self.buf_flags.is_some() {
self.start_send_buffer_message(self.last_buf_hint, call)?;
ready!(self.poll_ready(cx)?);
}
self.last_buf_hint = true;
Poll::Ready(Ok(()))
}
#[inline]
fn start_send_buffer_message<C: ShareCallHolder>(
&mut self,
buffer_hint: bool,
call: &mut C,
) -> Result<()> {
assert!(self.batch_f.is_none());
let mut flags = self.buf_flags.clone().unwrap();
flags = flags.buffer_hint(buffer_hint);
let write_f = call.call(|c| {
c.call
.start_send_message(&mut self.buffer, flags.flags, self.send_metadata)
})?;
self.batch_f = Some(write_f);
if !self.buffer.is_inline() {
self.buffer = GrpcSlice::default();
}
self.buf_flags.take();
Ok(())
}
}