volo-thrift 0.12.5

Thrift RPC framework implementation of volo.
Documentation
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
use std::time::Duration;

use chrono::{DateTime, Local};
use paste::paste;
use pilota::thrift::TMessageIdentifier;
use volo::{
    FastStr,
    context::{Context, Reusable, Role, RpcCx, RpcInfo},
    newtype_impl_context,
};

use crate::{BizError, client::CallOpt, protocol::TMessageType};

macro_rules! stat_impl {
    ($t: ident) => {
        paste! {
            /// This is unstable now and may be changed in the future.
            #[inline]
            pub fn $t(&self) -> Option<DateTime<Local>> {
                self.$t
            }

            /// This is unstable now and may be changed in the future.
            #[doc(hidden)]
            #[inline]
            pub fn [<set_$t>](&mut self, t: DateTime<Local>) {
                self.$t = Some(t)
            }

            /// This is unstable now and may be changed in the future.
            #[inline]
            pub fn [<record_ $t>](&mut self) {
                self.$t = Some(Local::now())
            }
        }
    };
}

#[derive(Default, Clone, Debug, Copy)]
pub struct ServerTransportInfo {
    conn_reset: bool,
}

impl ServerTransportInfo {
    #[inline]
    pub fn is_conn_reset(&self) -> bool {
        self.conn_reset
    }

    #[inline]
    pub fn set_conn_reset(&mut self, reset: bool) {
        self.conn_reset = reset
    }

    #[inline]
    pub fn reset(&mut self) {
        *self = Self { ..Self::default() }
    }
}

/// This is unstable now and may be changed in the future.
#[derive(Debug, Default, Clone)]
pub struct CommonStats {
    // if there's a length-prefixed transport, we can get the read time
    read_start_at: Option<DateTime<Local>>,
    read_end_at: Option<DateTime<Local>>,

    decode_start_at: Option<DateTime<Local>>,
    decode_end_at: Option<DateTime<Local>>,
    encode_start_at: Option<DateTime<Local>>,
    encode_end_at: Option<DateTime<Local>>,
    write_start_at: Option<DateTime<Local>>,
    write_end_at: Option<DateTime<Local>>,

    // size
    read_size: Option<usize>, /* only applicable to length-prefixed transport such as TTHeader
                               * and Framed */
    write_size: Option<usize>,

    // biz error
    biz_error: Option<BizError>,
}

impl CommonStats {
    stat_impl!(read_start_at);
    stat_impl!(read_end_at);
    stat_impl!(decode_start_at);
    stat_impl!(decode_end_at);
    stat_impl!(encode_start_at);
    stat_impl!(encode_end_at);
    stat_impl!(write_start_at);
    stat_impl!(write_end_at);

    #[inline]
    pub fn read_size(&self) -> Option<usize> {
        self.read_size
    }

    #[inline]
    pub fn set_read_size(&mut self, size: usize) {
        self.read_size = Some(size)
    }

    #[inline]
    pub fn write_size(&self) -> Option<usize> {
        self.write_size
    }

    #[inline]
    pub fn set_write_size(&mut self, size: usize) {
        self.write_size = Some(size)
    }

    #[doc(hidden)]
    #[inline]
    pub fn biz_error(&self) -> &Option<BizError> {
        &self.biz_error
    }

    #[doc(hidden)]
    #[inline]
    pub fn set_biz_error(&mut self, biz_error: BizError) {
        self.biz_error = Some(biz_error);
    }

    #[inline]
    pub fn reset(&mut self) {
        *self = Self { ..Self::default() }
    }
}

/// This is unstable now and may be changed in the future.
#[derive(Debug, Default, Clone)]
pub struct ServerStats {
    process_start_at: Option<DateTime<Local>>,
    process_end_at: Option<DateTime<Local>>,
}

impl ServerStats {
    stat_impl!(process_start_at);
    stat_impl!(process_end_at);

    #[inline]
    pub fn reset(&mut self) {
        self.process_start_at = None;
        self.process_end_at = None;
    }
}

/// This is unstable now and may be changed in the future.
#[derive(Debug, Default, Clone)]
pub struct ClientStats {
    make_transport_start_at: Option<DateTime<Local>>,
    make_transport_end_at: Option<DateTime<Local>>,
}

impl ClientStats {
    stat_impl!(make_transport_start_at);
    stat_impl!(make_transport_end_at);

    #[inline]
    pub fn reset(&mut self) {
        self.make_transport_start_at = None;
        self.make_transport_end_at = None;
    }
}

#[derive(Default, Clone, Debug)]
pub struct PooledTransport {
    pub should_reuse: bool,
}

impl PooledTransport {
    #[inline]
    pub fn set_reuse(&mut self, should_reuse: bool) {
        if !self.should_reuse && should_reuse {
            panic!("cannot reuse a transport which should_reuse is false");
        }
        self.should_reuse = should_reuse;
    }
}

#[derive(Debug, Clone)]
pub struct ClientCxInner {
    pub seq_id: i32,
    pub message_type: TMessageType,
    pub transport: PooledTransport,
    /// The IDL service name to send via TTHeader `isn` field, used for multi-service routing.
    pub idl_service_name: Option<FastStr>,
    /// This is unstable now and may be changed in the future.
    pub stats: ClientStats,
    /// This is unstable now and may be changed in the future.
    pub common_stats: CommonStats,
}

#[derive(Debug, Clone, Default)]
pub struct ServerCxInner {
    pub seq_id: Option<i32>,
    pub req_msg_type: Option<TMessageType>,
    pub msg_type: Option<TMessageType>,
    pub transport: ServerTransportInfo,
    /// The IDL service name from TTHeader `isn` field, used for multi-service routing.
    pub idl_service_name: Option<FastStr>,
    /// This is unstable now and may be changed in the future.
    pub stats: ServerStats,
    /// This is unstable now and may be changed in the future.
    pub common_stats: CommonStats,
}

#[derive(Debug)]
pub struct ClientContext(pub(crate) RpcCx<ClientCxInner, Config>);

newtype_impl_context!(ClientContext, Config, 0);

impl ClientContext {
    #[inline]
    pub fn new(seq_id: i32, ri: RpcInfo<Config>, msg_type: TMessageType) -> Self {
        Self(RpcCx::new(
            ri,
            ClientCxInner {
                seq_id,
                message_type: msg_type,
                transport: PooledTransport { should_reuse: true },
                idl_service_name: None,
                stats: ClientStats::default(),
                common_stats: CommonStats::default(),
            },
        ))
    }

    #[inline]
    pub fn reset(&mut self, seq_id: i32, msg_type: TMessageType) {
        self.seq_id = seq_id;
        self.message_type = msg_type;
        self.transport.should_reuse = true;
        self.idl_service_name = None;
        self.stats.reset();
        self.common_stats.reset();
        // self.0 is RpcCx, this reset will clear rpcinfo and extension
        self.0.reset(self.0.inner.clone());
    }
}

impl std::ops::Deref for ClientContext {
    type Target = RpcCx<ClientCxInner, Config>;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl std::ops::DerefMut for ClientContext {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

thread_local! {
    #[doc(hidden)]
    /// This should only be used in the generated code.
    pub static CLIENT_CONTEXT_CACHE: std::cell::RefCell<Vec<ClientContext>> = std::cell::RefCell::new(Vec::with_capacity(128));
}

thread_local! {
    pub(crate) static SERVER_CONTEXT_CACHE: std::cell::RefCell<Vec<ServerContext>> = std::cell::RefCell::new(Vec::with_capacity(128));
}

#[derive(Debug)]
pub struct ServerContext(pub(crate) RpcCx<ServerCxInner, Config>);

impl Default for ServerContext {
    #[inline]
    fn default() -> Self {
        Self(RpcCx::new(
            RpcInfo::with_role(Role::Server),
            Default::default(),
        ))
    }
}

newtype_impl_context!(ServerContext, Config, 0);

impl std::ops::Deref for ServerContext {
    type Target = RpcCx<ServerCxInner, Config>;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl std::ops::DerefMut for ServerContext {
    #[inline]
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

pub trait ThriftContext: volo::context::Context<Config = Config> + Send + 'static {
    fn encode_conn_reset(&self) -> bool;
    fn set_conn_reset_by_ttheader(&mut self, reset: bool);
    fn handle_decoded_msg_ident(&mut self, ident: &TMessageIdentifier);
    fn seq_id(&self) -> i32;
    fn msg_type(&self) -> TMessageType;
    /// This is unstable now and may be changed in the future.
    #[doc(hidden)]
    fn stats(&self) -> &CommonStats;
    /// This is unstable now and may be changed in the future.
    #[doc(hidden)]
    fn stats_mut(&mut self) -> &mut CommonStats;

    /// Gets the IDL service name from TTHeader `isn` field.
    /// Used for multi-service routing.
    fn idl_service_name(&self) -> Option<&FastStr>;

    /// Sets the IDL service name from TTHeader `isn` field.
    /// Used for multi-service routing.
    fn set_idl_service_name(&mut self, _name: FastStr);
}

impl ThriftContext for ClientContext {
    #[inline]
    fn encode_conn_reset(&self) -> bool {
        false
    }

    #[inline]
    fn set_conn_reset_by_ttheader(&mut self, reset: bool) {
        self.transport.set_reuse(!reset);
    }

    #[inline]
    fn handle_decoded_msg_ident(&mut self, _ident: &TMessageIdentifier) {}

    #[inline]
    fn seq_id(&self) -> i32 {
        self.seq_id
    }

    #[inline]
    fn msg_type(&self) -> TMessageType {
        self.message_type
    }

    #[inline]
    fn stats(&self) -> &CommonStats {
        &self.common_stats
    }

    #[inline]
    fn stats_mut(&mut self) -> &mut CommonStats {
        &mut self.common_stats
    }

    #[inline]
    fn idl_service_name(&self) -> Option<&FastStr> {
        self.idl_service_name.as_ref()
    }

    #[inline]
    fn set_idl_service_name(&mut self, name: FastStr) {
        self.idl_service_name = Some(name);
    }
}

impl ThriftContext for ServerContext {
    #[inline]
    fn encode_conn_reset(&self) -> bool {
        self.transport.is_conn_reset()
    }

    #[inline]
    fn set_conn_reset_by_ttheader(&mut self, reset: bool) {
        self.transport.set_conn_reset(reset)
    }

    #[inline]
    fn handle_decoded_msg_ident(&mut self, ident: &TMessageIdentifier) {
        self.seq_id = Some(ident.sequence_number);
        self.req_msg_type = Some(ident.message_type);
        self.rpc_info_mut().set_method(ident.name.clone());
    }

    #[inline]
    fn seq_id(&self) -> i32 {
        self.seq_id.unwrap_or(0)
    }

    #[inline]
    fn msg_type(&self) -> TMessageType {
        self.msg_type.expect("`msg_type` should be set.")
    }

    #[inline]
    fn stats(&self) -> &CommonStats {
        &self.common_stats
    }

    #[inline]
    fn stats_mut(&mut self) -> &mut CommonStats {
        &mut self.common_stats
    }

    #[inline]
    fn idl_service_name(&self) -> Option<&FastStr> {
        self.idl_service_name.as_ref()
    }

    #[inline]
    fn set_idl_service_name(&mut self, name: FastStr) {
        self.idl_service_name = Some(name);
    }
}

const DEFAULT_RPC_TIMEOUT: Duration = Duration::from_secs(1);
const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_millis(50);
const DEFAULT_READ_WRITE_TIMEOUT: Duration = Duration::from_secs(1);

#[derive(Debug, Default, Clone, Copy)]
pub struct Config {
    rpc_timeout: Option<Duration>,
    connect_timeout: Option<Duration>,
    read_write_timeout: Option<Duration>,
}

impl Config {
    #[inline]
    pub fn new() -> Self {
        Self {
            rpc_timeout: None,
            connect_timeout: None,
            read_write_timeout: None,
        }
    }

    #[inline]
    pub fn rpc_timeout(&self) -> Option<Duration> {
        self.rpc_timeout
    }

    /// Sets the rpc timeout.
    ///
    /// This can be set both by the client builder and the CallOpt.
    #[inline]
    pub fn set_rpc_timeout(&mut self, rpc_timeout: Option<Duration>) {
        self.rpc_timeout = rpc_timeout;
    }

    #[inline]
    pub fn rpc_timeout_or_default(&self) -> Duration {
        self.rpc_timeout.unwrap_or(DEFAULT_RPC_TIMEOUT)
    }

    #[inline]
    pub fn connect_timeout(&self) -> Option<Duration> {
        self.connect_timeout
    }

    #[inline]
    pub fn connect_timeout_or_default(&self) -> Duration {
        self.connect_timeout.unwrap_or(DEFAULT_CONNECT_TIMEOUT)
    }

    /// Sets the connect timeout.
    #[inline]
    pub fn set_connect_timeout(&mut self, timeout: Option<Duration>) {
        self.connect_timeout = timeout;
    }

    #[inline]
    pub fn read_write_timeout(&self) -> Option<Duration> {
        self.read_write_timeout
    }

    #[inline]
    pub fn read_write_timeout_or_default(&self) -> Duration {
        self.read_write_timeout
            .unwrap_or(DEFAULT_READ_WRITE_TIMEOUT)
    }

    #[inline]
    /// Sets the read write timeout(a.k.a. IO timeout).
    pub(crate) fn set_read_write_timeout(&mut self, timeout: Option<Duration>) {
        self.read_write_timeout = timeout;
    }

    #[inline]
    pub fn merge(&mut self, other: Self) {
        if let Some(t) = other.rpc_timeout {
            self.rpc_timeout = Some(t);
        }
        if let Some(t) = other.connect_timeout {
            self.connect_timeout = Some(t);
        }
        if let Some(t) = other.read_write_timeout {
            self.read_write_timeout = Some(t);
        }
    }
}

impl Reusable for Config {
    fn clear(&mut self) {
        self.rpc_timeout = None;
        self.connect_timeout = None;
        self.read_write_timeout = None;
    }
}

impl ::volo::client::Apply<ClientContext> for CallOpt {
    type Error = crate::ClientError;

    #[inline]
    fn apply(self, cx: &mut ClientContext) -> Result<(), Self::Error> {
        let caller = cx.rpc_info.caller_mut();
        if !self.caller_faststr_tags.is_empty() {
            caller.faststr_tags.extend(self.caller_faststr_tags);
        }
        if !self.caller_tags.is_empty() {
            caller.tags.extend(self.caller_tags);
        }

        let callee = cx.rpc_info.callee_mut();
        if !self.callee_faststr_tags.is_empty() {
            callee.faststr_tags.extend(self.callee_faststr_tags);
        }
        if !self.callee_tags.is_empty() {
            callee.tags.extend(self.callee_tags);
        }
        if let Some(addr) = self.address {
            callee.set_address(addr);
        }
        cx.rpc_info.config_mut().merge(self.config);
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::{Role, RpcInfo};
    use crate::context::ClientContext;

    #[test]
    fn test_rpcinfo() {
        let ri = &ClientContext::new(
            1,
            RpcInfo::with_role(Role::Client),
            pilota::thrift::TMessageType::Call,
        )
        .rpc_info;
        println!("{ri:?}");
    }
}