agntcy-slim-session 0.3.0

SLIM session internal implementation.
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
// Copyright AGNTCY Contributors (https://github.com/agntcy)
// SPDX-License-Identifier: Apache-2.0

// Standard library imports
use std::sync::Arc;

// Third-party crates
use async_trait::async_trait;
use tokio::time::{self, Duration};
use tokio_util::sync::CancellationToken;
use tracing::trace;

#[async_trait]
pub trait TimerObserver {
    async fn on_timeout(&self, timer_id: u32, timeouts: u32);
    async fn on_failure(&self, timer_id: u32, timeouts: u32);
    async fn on_stop(&self, timer_id: u32);
}

#[derive(Debug, Clone)]
pub enum TimerType {
    Constant = 0,
    Exponential = 1,
}

#[derive(Debug)]
pub struct Timer {
    /// timer id
    timer_id: u32,

    /// timer type
    timer_type: TimerType,

    /// constant timer: timer duration
    /// exponential timer: min timer duration. at every new timer the duration is computers as last_duration * 2
    duration: Duration,

    /// constant timer: None
    /// exponential timer: maximum timer duration. once the duration reaches this time it will not be encreased anymore
    max_duration: Option<Duration>,

    /// if not None, it indicates the maximum number of retryes before call on_failure
    /// if set to None the timer will go on forever unless cancelled
    max_retries: Option<u32>,

    /// token used to cancel the timer
    cancellation_token: CancellationToken,
}

impl Timer {
    pub fn new(
        timer_id: u32,
        timer_type: TimerType,
        duration: Duration,
        max_duration: Option<Duration>,
        max_retries: Option<u32>,
    ) -> Self {
        Timer {
            timer_id,
            timer_type,
            duration,
            max_duration,
            max_retries,
            cancellation_token: CancellationToken::new(),
        }
    }

    pub fn start<T: TimerObserver + Send + Sync + 'static>(&self, observer: Arc<T>) {
        let timer_id = self.timer_id;
        let timer_type = self.timer_type.clone();
        let duration = self.duration;
        let max_retries = self.max_retries;
        let max_duration = self.max_duration;
        let cancellation_token = self.cancellation_token.clone();

        tokio::spawn(async move {
            let mut retry = 0;
            let mut timeouts = 0;
            let mut last_duration = duration;

            trace!(%timer_id, "timer started");
            loop {
                let timer_duration = match timer_type {
                    TimerType::Constant => {
                        trace!(
                            %timer_id, next_ms = duration.as_millis(),
                            "constant timer",
                        );
                        duration
                    }
                    TimerType::Exponential => {
                        let mut d = duration;
                        if timeouts != 0 {
                            d = last_duration * 2;
                        }
                        match max_duration {
                            None => {
                                trace!(
                                    %timer_id, next_ms = d.as_millis(),
                                    "exponential timer",
                                );
                                last_duration = d;
                                d
                            }
                            Some(max_d) => {
                                if d > max_d {
                                    trace!(
                                        %timer_id,
                                        next_ms = max_d.as_millis(),
                                        "exponential timer (use max duration)",
                                    );
                                    last_duration = max_d;
                                    max_d
                                } else {
                                    trace!(
                                        %timer_id, next_ms = max_d.as_millis(),
                                        "exponential timer",
                                    );
                                    last_duration = d;
                                    d
                                }
                            }
                        }
                    }
                };

                let timer = time::sleep(timer_duration);
                tokio::pin!(timer);

                tokio::select! {
                    _ = timer.as_mut() => {
                        timeouts += 1;
                        match max_retries {
                            Some(max) => {
                                if retry < max {
                                    observer.on_timeout(timer_id, timeouts).await
                                } else {
                                    observer.on_failure(timer_id, timeouts).await;
                                    break;
                                }
                            }
                            None => observer.on_timeout(timer_id, timeouts).await
                        }
                        retry += 1;
                    },
                    _ = cancellation_token.cancelled() => {
                        observer.on_stop(timer_id).await;
                        break;
                    },
                }
            }
        });
    }

    pub fn stop(&mut self) {
        self.cancellation_token.cancel();
        self.cancellation_token = CancellationToken::new();
    }

    pub fn reset<T: TimerObserver + Send + Sync + 'static>(&mut self, observer: Arc<T>) {
        self.stop();
        self.start(observer);
    }

    pub fn get_id(&self) -> u32 {
        self.timer_id
    }
}

impl Drop for Timer {
    fn drop(&mut self) {
        self.cancellation_token.cancel();
    }
}

// tests
#[cfg(test)]
mod tests {
    use tracing::debug;
    use tracing_test::traced_test;

    use super::*;

    struct Observer {
        id: u32,
    }

    #[async_trait]
    impl TimerObserver for Observer {
        async fn on_timeout(&self, timer_id: u32, timeouts: u32) {
            debug!(
                %timeouts, %timer_id,
                "timeout occurred, retry",
            );
        }

        async fn on_failure(&self, timer_id: u32, timeouts: u32) {
            debug!(
                %timeouts, %timer_id,
                "timeout occurred, stop retry",
            );
        }

        async fn on_stop(&self, timer_id: u32) {
            debug!(%timer_id, "timer cancelled");
        }
    }

    #[tokio::test]
    #[traced_test]
    async fn test_timer() {
        let o = Arc::new(Observer { id: 10 });
        let t = Timer::new(
            o.id,
            TimerType::Constant,
            Duration::from_millis(100),
            None,
            Some(3),
        );

        t.start(o);

        time::sleep(Duration::from_millis(500)).await;

        // check logs to validate the test
        let expected_msg = "timeout occurred, retry timeouts=1 timer_id=10";
        assert!(logs_contain(expected_msg));
        let expected_msg = "timeout occurred, retry timeouts=2 timer_id=10";
        assert!(logs_contain(expected_msg));
        let expected_msg = "timeout occurred, retry timeouts=3 timer_id=10";
        assert!(logs_contain(expected_msg));
        let expected_msg = "timeout occurred, stop retry timeouts=4 timer_id=10";
        assert!(logs_contain(expected_msg));

        let o = Arc::new(Observer { id: 20 });
        let t = Timer::new(
            o.id,
            TimerType::Exponential,
            Duration::from_millis(100),
            Some(Duration::from_millis(400)),
            Some(3),
        );

        t.start(o);
        time::sleep(Duration::from_millis(1200)).await;

        let expected_msg = "exponential timer timer_id=20 next_ms=400";
        assert!(logs_contain(expected_msg));
        let expected_msg = "exponential timer timer_id=20 next_ms=400";
        assert!(logs_contain(expected_msg));
        let expected_msg = "exponential timer timer_id=20 next_ms=400";
        assert!(logs_contain(expected_msg));
        let expected_msg = "exponential timer (use max duration) timer_id=20 next_ms=400";
        assert!(logs_contain(expected_msg));
        let expected_msg = "timeout occurred, stop retry timeouts=4 timer_id=20";
        assert!(logs_contain(expected_msg));

        let o = Arc::new(Observer { id: 30 });
        let mut t = Timer::new(
            o.id,
            TimerType::Exponential,
            Duration::from_millis(100),
            None,
            None,
        );

        t.start(o);

        time::sleep(Duration::from_millis(2000)).await;
        t.stop();
        time::sleep(Duration::from_millis(500)).await;
        let expected_msg = "exponential timer timer_id=30 next_ms=400";
        assert!(logs_contain(expected_msg));
        let expected_msg = "exponential timer timer_id=30 next_ms=800";
        assert!(logs_contain(expected_msg));
        let expected_msg = "exponential timer timer_id=30 next_ms=1600";
        assert!(logs_contain(expected_msg));
        let expected_msg = "exponential timer timer_id=30 next_ms=800";
        assert!(logs_contain(expected_msg));
        let expected_msg = "exponential timer timer_id=30 next_ms=1600";
        assert!(logs_contain(expected_msg));
        let expected_msg = "timer cancelled timer_id=30";
        assert!(logs_contain(expected_msg))
    }

    #[tokio::test]
    #[traced_test]
    async fn test_timer_stop() {
        let o = Arc::new(Observer { id: 10 });

        let mut t = Timer::new(
            o.id,
            TimerType::Constant,
            Duration::from_millis(100),
            None,
            Some(5),
        );

        t.start(o);

        time::sleep(Duration::from_millis(350)).await;

        t.stop();

        time::sleep(Duration::from_millis(500)).await;

        // check logs to validate the test
        let expected_msg = "timeout occurred, retry timeouts=1 timer_id=10";
        assert!(logs_contain(expected_msg));
        let expected_msg = "timeout occurred, retry timeouts=2 timer_id=10";
        assert!(logs_contain(expected_msg));
        let expected_msg = "timeout occurred, retry timeouts=3 timer_id=10";
        assert!(logs_contain(expected_msg));
        let expected_msg = "timer cancelled timer_id=10";
        assert!(logs_contain(expected_msg));
    }

    #[tokio::test]
    #[traced_test]
    async fn test_multiple_timers() {
        let o1 = Arc::new(Observer { id: 1 });
        let o2 = Arc::new(Observer { id: 2 });
        let o3 = Arc::new(Observer { id: 3 });

        let mut t1 = Timer::new(
            o1.id,
            TimerType::Constant,
            Duration::from_millis(100),
            None,
            Some(5),
        );
        let mut t2 = Timer::new(
            o2.id,
            TimerType::Constant,
            Duration::from_millis(200),
            None,
            Some(5),
        );
        let mut t3 = Timer::new(
            o3.id,
            TimerType::Constant,
            Duration::from_millis(200),
            None,
            Some(5),
        );

        t1.start(o1);
        t2.start(o2);
        t3.start(o3);

        time::sleep(Duration::from_millis(700)).await;

        t1.stop();
        t2.stop();
        t3.stop();

        time::sleep(Duration::from_millis(500)).await;

        // timeouts after 100ms
        let expected_msg = "timeout occurred, retry timeouts=1 timer_id=1";
        assert!(logs_contain(expected_msg));

        // timeouts after 200ms
        let expected_msg = "timeout occurred, retry timeouts=1 timer_id=2";
        assert!(logs_contain(expected_msg));
        let expected_msg = "timeout occurred, retry timeouts=1 timer_id=3";
        assert!(logs_contain(expected_msg));
        let expected_msg = "timeout occurred, retry timeouts=2 timer_id=1";
        assert!(logs_contain(expected_msg));

        // timeouts after 300ms
        let expected_msg = "timeout occurred, retry timeouts=3 timer_id=1";
        assert!(logs_contain(expected_msg));

        // timeouts after 400ms
        let expected_msg = "timeout occurred, retry timeouts=2 timer_id=2";
        assert!(logs_contain(expected_msg));
        let expected_msg = "timeout occurred, retry timeouts=2 timer_id=3";
        assert!(logs_contain(expected_msg));
        let expected_msg = "timeout occurred, retry timeouts=4 timer_id=1";
        assert!(logs_contain(expected_msg));

        // timeouts after 500ms
        let expected_msg = "timeout occurred, retry timeouts=4 timer_id=1";
        assert!(logs_contain(expected_msg));

        // timeouts after 600ms
        let expected_msg = "timeout occurred, retry timeouts=3 timer_id=2";
        assert!(logs_contain(expected_msg));
        let expected_msg = "timeout occurred, retry timeouts=3 timer_id=3";
        assert!(logs_contain(expected_msg));
        let expected_msg = "timeout occurred, retry timeouts=5 timer_id=1";
        assert!(logs_contain(expected_msg));

        // timeouts after 700ms
        let expected_msg = "timeout occurred, stop retry timeouts=6 timer_id=1";
        assert!(logs_contain(expected_msg));

        // stop timer 2 and 3
        let expected_msg = "timer cancelled timer_id=2";
        assert!(logs_contain(expected_msg));
        let expected_msg = "timer cancelled timer_id=3";
        assert!(logs_contain(expected_msg));
    }

    #[tokio::test]
    #[traced_test]
    async fn test_timer_reset() {
        let o = Arc::new(Observer { id: 10 });

        let mut t = Timer::new(
            o.id,
            TimerType::Constant,
            Duration::from_millis(100),
            None,
            Some(5),
        );

        t.start(o.clone());

        time::sleep(Duration::from_millis(350)).await;

        let expected_msg = "timeout occurred, retry timeouts=3 timer_id=10";
        assert!(logs_contain(expected_msg));

        t.reset(o.clone());

        time::sleep(Duration::from_millis(250)).await;

        let expected_msg = "timeout occurred, retry timeouts=2 timer_id=10";
        assert!(logs_contain(expected_msg));

        t.reset(o.clone());

        time::sleep(Duration::from_millis(700)).await;

        let expected_msg = "timeout occurred, stop retry timeouts=6 timer_id=10";
        assert!(logs_contain(expected_msg));

        t.reset(o);

        time::sleep(Duration::from_millis(700)).await;

        let expected_msg = "timeout occurred, stop retry timeouts=6 timer_id=10";
        assert!(logs_contain(expected_msg));
    }

    #[tokio::test]
    #[traced_test]
    async fn test_timer_reset_without_start() {
        let o = Arc::new(Observer { id: 10 });

        let mut t = Timer::new(
            o.id,
            TimerType::Constant,
            Duration::from_millis(100),
            None,
            Some(5),
        );

        t.reset(o);

        time::sleep(Duration::from_millis(350)).await;

        let expected_msg = "timeout occurred, retry timeouts=3 timer_id=10";
        assert!(logs_contain(expected_msg));
    }
}