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
use std::time::Duration;

#[macro_use(defer)]
extern crate scopeguard;

use crossbeam::channel::Receiver;
use crossbeam::crossbeam_channel::{select, tick, unbounded};
use crossbeam::sync::WaitGroup;
use std::fmt;

use std::error::Error;
use std::result;
use std::thread;

use rand::Rng;
use std::time::Instant;

type Result = result::Result<(), Box<dyn Error>>;

/// Group allows to start a group of threads and wait for their completion.
pub struct Group {
    wg: WaitGroup,
}

impl Group {
    pub fn new() -> Group {
        Group {
            wg: WaitGroup::new(),
        }
    }

    pub fn wait(self) {
        self.wg.wait();
    }

    /// start_with_channel starts f in a new thread in the group.
    /// stop_ch is passed to f as an argument.
    /// f should stop when stop_ch is available.
    pub fn start_with_channel<F>(&self, stop_ch: Receiver<bool>, f: F)
    where
        F: Fn(Receiver<bool>) -> () + 'static + std::marker::Send + std::marker::Sync,
    {
        self.start(move || f(stop_ch.clone()));
    }

    /// start starts f in a new thread in the group.
    pub fn start<F>(&self, f: F)
    where
        F: Fn() -> () + std::marker::Send + 'static,
    {
        let wg = self.wg.clone();
        thread::spawn(move || {
            f();
            drop(wg);
        });
    }
}

/// forever calls f every period for ever.
///
/// forever is syntactic sugar on top of until.
pub fn forever<F>(f: F, period: Duration)
where
    F: Fn() -> (),
{
    let (_s, r) = unbounded();
    until(f, period, r)
}

/// until loops until stop channel is closed, running f every period.
///
/// until is syntactic sugar on top of jitter_until with zero jitter factor and
/// with sliding = true (which means the timer for period starts after the f
/// completes).
pub fn until<F>(f: F, period: Duration, stop_ch: Receiver<bool>)
where
    F: Fn() -> (),
{
    jitter_until(f, period, 0.0, true, stop_ch)
}

/// non_sliding_until loops until stop channel is closed, running f every
/// period.
///
/// non_sliding_until is syntactic sugar on top of jitter_until with zero jitter
/// factor, with sliding = false (meaning the timer for period starts at the same
/// time as the function starts).
pub fn non_sliding_until<F>(f: F, period: Duration, stop_ch: Receiver<bool>)
where
    F: Fn() -> (),
{
    jitter_until(f, period, 0.0, false, stop_ch)
}

/// jitter_until loops until stop channel is closed, running f every period.
///
/// If jitter_factor is positive, the period is jittered before every run of f.
/// If jitter_factor is not positive, the period is unchanged and not jittered.
///
/// If sliding is true, the period is computed after f runs. If it is false then
/// period includes the runtime for f.
///
/// Close stop_ch to stop. f may not be invoked if stop channel is already
/// closed. Pass NeverStop to if you don't want it stop.
pub fn jitter_until<F>(
    f: F,
    period: Duration,
    jitter_factor: f64,
    sliding: bool,
    stop_ch: Receiver<bool>,
) where
    F: Fn() -> (),
{
    backoff_until(
        f,
        JitteredBackoffManager::new_jittered_backoff_manager(period, jitter_factor),
        sliding,
        stop_ch,
    )
}

/// backoff_until loops until stop channel is closed, run f every duration given by BackoffManager.
///
/// If sliding is true, the period is computed after f runs. If it is false then
/// period includes the runtime for f.
pub fn backoff_until<F>(
    f: F,
    mut backoff: Box<dyn BackoffManager>,
    sliding: bool,
    stop_ch: Receiver<bool>,
) where
    F: Fn() -> (),
{
    loop {
        select! {
            recv(stop_ch) -> _ => return ,
            default => {}
        }

        let mut t = backoff.backoff();

        // FIXME handle crach
        // func() {
        //     defer runtime.HandleCrash()
        //     f()
        // }()
        f();
        if sliding {
            t = backoff.backoff();
        }

        // NOTE: b/c there is no priority selection in golang
        // it is possible for this to race, meaning we could
        // trigger t.C and stop_ch, and t.C select falls through.
        // In order to mitigate we re-check stop_ch at the beginning
        // of every loop to prevent extra executions of f().
        select! {
            recv(stop_ch) -> _ =>  return,
            recv(t) ->  _msg => {            }
        }
    }
}

/// jitter returns a Duration between duration and duration + max_factor *
/// duration.
///
/// This allows clients to avoid converging on periodic behavior. If max_factor
/// is 0.0, a suggested default value will be chosen.
pub fn jitter(duration: Duration, max_factor: f64) -> Duration {
    let mut mf = max_factor;
    if mf <= 0.0 {
        mf = 1.0;
    }
    let mut rng = rand::thread_rng();
    Duration::from_nanos((duration.as_nanos() as f64 * (1.0 + rng.gen::<u64>() as f64 * mf)) as u64)
}

/// WaitTimeoutError is returned when the condition exited without success.
#[derive(Debug, Clone)]
struct WaitTimeoutError;

impl fmt::Display for WaitTimeoutError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "timed out waiting for the condition")
    }
}
impl Error for WaitTimeoutError {}

/// run_condition_with_crash_protection runs a ConditionFunc with crash protection
fn run_condition_with_crash_protection<F>(condition: F) -> std::result::Result<bool, Box<dyn Error>>
where
    F: Fn() -> std::result::Result<bool, Box<dyn Error>> + Copy,
{
    // defer runtime.HandleCrash()
    condition()
}

/// Backoff holds parameters applied to a Backoff function.
pub struct Backoff {
    /// The initial duration.
    duration: Duration,
    /// Duration is multiplied by factor each iteration, if factor is not zero
    /// and the limits imposed by steps and cap have not been reached.
    /// Should not be negative.
    /// The jitter does not contribute to the updates to the duration parameter.
    factor: f64,
    /// The sleep at each iteration is the duration plus an additional
    /// amount chosen uniformly at random from the interval between
    /// zero and `jitter*duration`.
    jitter: f64,
    /// The remaining number of iterations in which the duration
    /// parameter may change (but progress can be stopped earlier by
    /// hitting the cap). If not positive, the duration is not
    /// changed. Used for exponential backoff in combination with
    /// factor and cap.
    steps: i32,
    /// A limit on revised values of the duration parameter. If a
    /// multiplication by the factor parameter would make the duration
    /// exceed the cap then the duration is set to the cap and the
    /// steps parameter is set to zero.
    cap: Duration,
}

impl Backoff {
    /// step (1) returns an amount of time to sleep determined by the
    /// original duration and jitter and (2) mutates the provided Backoff
    /// to update its steps and duration.
    pub fn step(&mut self) -> Duration {
        if self.steps < 1 {
            if self.jitter > 0.0 {
                return jitter(self.duration, self.jitter);
            }
            return self.duration;
        }
        self.steps = self.steps - 1;

        let mut duration = self.duration;

        // calculate the next step
        if self.factor != 0.0 {
            self.duration =
                Duration::from_nanos((self.duration.as_nanos() as f64 * self.factor) as u64);
            if !(self.cap.as_nanos() == 0) && self.duration > self.cap {
                self.duration = self.cap;
                self.steps = 0;
            }
        }

        if self.jitter > 0.0 {
            duration = jitter(duration, self.jitter);
        }

        duration
    }
}

/// BackoffManager manages backoff with a particular scheme based on its underlying implementation. It provides
/// an interface to return a timer for backoff, and caller shall backoff until Timer.C() drains. If the second backoff()
/// is called before the timer from the first backoff() call finishes, the first timer will NOT be drained and result in
/// undetermined behavior.
/// The BackoffManager is supposed to be called in a single-threaded environment.
pub trait BackoffManager {
    fn backoff(&mut self) -> Receiver<Instant>;
}

pub struct ExponentialBackoffManager {
    backoff: Backoff,
    last_backoff_start: Instant,
    initial_backoff: Duration,
    backoff_reset_duration: Duration,
}

impl BackoffManager for ExponentialBackoffManager {
    /// Backoff implements BackoffManager.backoff,
    /// it returns a timer so caller can block on the timer for exponential backoff.
    /// The returned timer must be drained before calling backoff() the second time
    fn backoff(&mut self) -> Receiver<Instant> {
        tick(self.get_next_backoff())
    }
}

impl ExponentialBackoffManager {
    /// new_exponential_backoff_manager returns a manager for managing exponential backoff.
    /// Each backoff is jittered and
    /// backoff will not exceed the given max.
    /// If the backoff is not called within reset_duration, the backoff is reset.
    /// This backoff manager is used to reduce load during upstream unhealthiness.
    pub fn new_exponential_backoff_manager(
        init_backoff: Duration,
        max_backoff: Duration,
        reset_duration: Duration,
        backoff_factor: f64,
        jitter: f64,
    ) -> Box<dyn BackoffManager> {
        Box::new(ExponentialBackoffManager {
            backoff: Backoff {
                duration: init_backoff,
                factor: backoff_factor,
                jitter: jitter,

                // the current impl of wait.backoff returns Backoff.duration once steps are used up, which is not
                // what we ideally need here, we set it to max int and assume we will never use up the steps
                steps: std::i32::MAX,
                cap: max_backoff,
            },
            initial_backoff: init_backoff,
            last_backoff_start: Instant::now(),
            backoff_reset_duration: reset_duration,
        })
    }

    fn get_next_backoff(&mut self) -> Duration {
        if Instant::now().duration_since(self.last_backoff_start) > self.backoff_reset_duration {
            self.backoff.steps = std::i32::MAX;
            self.backoff.duration = self.initial_backoff;
        }
        self.last_backoff_start = Instant::now();
        return self.backoff.step();
    }
}

pub struct JitteredBackoffManager {
    duration: Duration,
    jitter: f64,
}

impl BackoffManager for JitteredBackoffManager {
    /// backoff implements BackoffManager.backoff,
    /// it returns a timer so caller can block on the timer for jittered backoff.
    /// The returned timer must be drained before calling backoff() the second time
    fn backoff(&mut self) -> Receiver<Instant> {
        tick(self.get_next_backoff())
    }
}

impl JitteredBackoffManager {
    /// new_jittered_backoff_manager returns a BackoffManager that backoffs with given duration plus given jitter.
    /// If the jitter
    /// is negative, backoff will not be jittered.
    pub fn new_jittered_backoff_manager(
        duration: Duration,
        jitter: f64,
    ) -> Box<dyn BackoffManager> {
        Box::new(JitteredBackoffManager {
            duration: duration,
            jitter: jitter,
        }) as Box<dyn BackoffManager>
    }

    fn get_next_backoff(&self) -> Duration {
        if self.jitter > 0.0 {
            jitter(self.duration, self.jitter)
        } else {
            self.duration
        }
    }
}

/// exponential_backoff repeats a condition check with exponential backoff.
///
/// It repeatedly checks the condition and then sleeps, using `backoff.step()`
/// to determine the length of the sleep and adjust Duration and steps.
/// Stops and returns as soon as:
/// 1. the condition check returns true or an error,
/// 2. `backoff.steps` checks of the condition have been done, or
/// 3. a sleep truncated by the cap on duration has been completed.
/// In case (1) the returned error is what the condition function returned.
/// In all other cases, WaitTimeoutError is returned.
pub fn exponential_backoff<F>(backoff: &mut Backoff, condition: F) -> Result
where
    F: Fn() -> std::result::Result<bool, Box<dyn Error>> + Copy,
{
    while backoff.steps > 0 {
        let ok = run_condition_with_crash_protection(condition)?;
        if ok {
            return Ok(());
        }
        if backoff.steps == 1 {
            break;
        }
        thread::sleep(backoff.step());
    }
    Err(Box::new(WaitTimeoutError))
}

/// poll tries a condition func until it returns true, an error, or the timeout
/// is reached.
///
/// poll always waits the interval before the run of 'condition'.
/// 'condition' will always be invoked at least once.
///
/// Some intervals may be missed if the condition takes too long or the time
/// window is too short.
///
/// If you want to poll something forever, see poll_infinite.
pub fn poll<F>(interval: Duration, timeout: Duration, condition: F) -> Result
where
    F: Fn() -> std::result::Result<bool, Box<dyn Error>> + Copy,
{
    poll_internal(poller(interval, timeout), condition)
}

fn poll_internal<F>(wait: Box<dyn Fn(Receiver<bool>) -> Receiver<bool>>, condition: F) -> Result
where
    F: Fn() -> std::result::Result<bool, Box<dyn Error>> + Copy,
{
    let (_s, r) = unbounded();
    wait_for(wait, condition, r)
}

/// poll_immediate tries a condition func until it returns true, an error, or the timeout
/// is reached.
///
/// poll_immediate always checks 'condition' before waiting for the interval. 'condition'
/// will always be invoked at least once.
///
/// Some intervals may be missed if the condition takes too long or the time
/// window is too short.
///
/// If you want to immediately poll something forever, see poll_immediate_infinite.
pub fn poll_immediate<F>(interval: Duration, timeout: Duration, condition: F) -> Result
where
    F: Fn() -> std::result::Result<bool, Box<dyn Error>> + Copy,
{
    poll_immediate_internal(poller(interval, timeout), condition)
}

fn poll_immediate_internal<F>(
    wait: Box<dyn Fn(Receiver<bool>) -> Receiver<bool>>,
    condition: F,
) -> Result
where
    F: Fn() -> std::result::Result<bool, Box<dyn Error>> + Copy,
{
    let done = run_condition_with_crash_protection(condition)?;
    if done {
        return Ok(());
    }
    poll_internal(wait, condition)
}

/// poll_infinite tries a condition func until it returns true or an error
///
/// poll_infinite always waits the interval before the run of 'condition'.
///
/// Some intervals may be missed if the condition takes too long or the time
/// window is too short.
pub fn poll_infinite<F>(interval: Duration, condition: F) -> Result
where
    F: Fn() -> std::result::Result<bool, Box<dyn Error>> + Copy,
{
    let (_s, r) = unbounded();
    return poll_until(interval, condition, r);
}

/// poll_immediate_infinite tries a condition func until it returns true or an error
///
/// poll_immediate_infinite runs the 'condition' before waiting for the interval.
///
/// Some intervals may be missed if the condition takes too long or the time
/// window is too short.
pub fn poll_immediate_infinite<F>(interval: Duration, condition: F) -> Result
where
    F: Fn() -> std::result::Result<bool, Box<dyn Error>> + Copy,
{
    let done = run_condition_with_crash_protection(condition)?;
    if done {
        return Ok(());
    }
    poll_infinite(interval, condition)
}

/// poll_until tries a condition func until it returns true, an error or stop_ch is
/// closed.
///
/// poll_until always waits interval before the first run of 'condition'.
/// 'condition' will always be invoked at least once.
pub fn poll_until<F>(interval: Duration, condition: F, stop_ch: Receiver<bool>) -> Result
where
    F: Fn() -> std::result::Result<bool, Box<dyn Error>> + Copy,
{
    return wait_for(poller(interval, Duration::new(0, 0)), condition, stop_ch);
}

/// poll_immediate_until tries a condition func until it returns true, an error or stop_ch is closed.
///
/// poll_immediate_until runs the 'condition' before waiting for the interval.
/// 'condition' will always be invoked at least once.
pub fn poll_immediate_until<F>(interval: Duration, condition: F, stop_ch: Receiver<bool>) -> Result
where
    F: Fn() -> std::result::Result<bool, Box<dyn Error>> + Copy,
{
    let done = condition()?;
    if done {
        return Ok(());
    }

    select! {
        recv(stop_ch) -> _ =>   return Err(Box::new(WaitTimeoutError)) ,
        default => return poll_until(interval, condition, stop_ch)
    }
}

/// wait_for continually checks 'fn' as driven by 'wait'.
///
/// wait_for gets a channel from 'wait()', and then invokes 'fn' once for every value
/// placed on the channel and once more when the channel is closed. If the channel is closed
/// and 'fn' returns false without error, wait_for returns WaitTimeoutError.
///
/// If 'fn' returns an error the loop ends and that error is returned. If
/// 'fn' returns true the loop ends and nil is returned.
///
/// WaitTimeoutError will be returned if the 'done' channel is closed without fn ever
/// returning true.
///
/// When the done channel is closed, because the golang `select` statement is
/// "uniform pseudo-random", the `fn` might still run one or multiple time,
/// though eventually `wait_for` will return.
pub fn wait_for<F>(
    wait: Box<dyn Fn(Receiver<bool>) -> Receiver<bool>>,
    func: F,
    done: Receiver<bool>,
) -> Result
where
    F: Fn() -> std::result::Result<bool, Box<dyn Error>> + Copy,
{
    let (s, r) = unbounded();
    let c = wait(r);
    // notify wait thread to quit.
    defer! { drop(s);};
    loop {
        select! {
           recv(c) -> msg => {
            let ok = run_condition_with_crash_protection(func)?;
            if ok {
                return Ok(());
            }
            if msg.is_err() {
                return Err(Box::new(WaitTimeoutError));
            }
        },
            recv(done) -> _ => return Err(Box::new(WaitTimeoutError)),
        }
    }
}

/// poller returns a Box<dyn Fn(Receiver<bool>) -> Receiver<bool>>
/// that will send to the channel every interval until
/// timeout has elapsed and then closes the channel.
///
/// Over very short intervals you may receive no ticks before the channel is
/// closed. A timeout of 0.0 is interpreted as an infinity, and in such a case
/// it would be the caller's responsibility to close the done channel.
/// Failure to do so would result in a leaked goroutine.
///
/// Output ticks are not buffered. If the channel is not ready to receive an
/// item, the tick is skipped.
fn poller(interval: Duration, timeout: Duration) -> Box<dyn Fn(Receiver<bool>) -> Receiver<bool>> {
    let func = move |done: Receiver<bool>| -> Receiver<bool> {
        let (s, r) = unbounded();
        let rr = r.clone();
        thread::spawn(move || {
            let ticker = tick(interval);

            // FIXME: workaround for compile error use of possibly-uninitialized `after`
            let mut after = tick(Duration::from_secs(1000000000));
            if !(timeout.as_nanos() == 0) {
                after = tick(timeout);
            }

            loop {
                select! {
                    recv(ticker) -> _ => {
                        // If the consumer isn't ready for this signal drop it and
                        // check the other channels.
                        s.send(true).unwrap();
                    },
                    recv(after) -> _ => {
                        return
                    },
                    recv(done) -> _ => {
                        return
                    },
                }
            }
        });

        rr
    };

    Box::new(func)
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::{Arc, Mutex};

    #[test]
    fn test_poll() {
        let (s, r) = unbounded();
        let cond_fn = || {
            select! {
                recv(r) -> msg => {
                    if msg.unwrap() == 3 {
                        return Ok(true);
                    }else {
                        return Ok(false);
                    }
                },
                default => {
                    return Ok(false)
                }
                    ,
            }
        };

        thread::spawn(move || {
            for i in 1..4 {
                thread::sleep(Duration::from_millis(20));
                s.send(i).unwrap();
            }
            drop(s);
            println!("sender dropped");
        });

        let ret = poll(
            Duration::from_millis(100),
            Duration::from_millis(300),
            cond_fn,
        );
        assert_eq!(true, ret.is_ok());

        let cond_fn = || Ok(false);
        let ret = poll(
            Duration::from_millis(100),
            Duration::from_millis(300),
            cond_fn,
        );

        assert_eq!(true, ret.is_err());
    }

    #[test]
    fn test_until() {
        let (s, r) = unbounded();

        let counter = Arc::new(Mutex::new(0));

        let counter1 = counter.clone();
        let worker_fn = move || {
            let mut counter = counter1.lock().unwrap();
            *counter += 1;
            println!("do work {}", *counter);
        };

        let counter2 = counter.clone();
        std::thread::spawn(move || loop {
            {
                let counter = counter2.lock().unwrap();
                if *counter > 4 {
                    drop(s);
                    println!("sender dropped");
                    return;
                }
            }

            thread::sleep(Duration::from_millis(10));
        });

        until(worker_fn, Duration::from_millis(10), r);
        let counter = counter.lock().unwrap();
        println!("final counter {}", *counter);
        assert_eq!(true, *counter > 4);
    }

    #[test]
    fn test_xxx() {
        let zero_seconds = Duration::new(0, 0);
        assert_eq!(0, zero_seconds.as_nanos());

        let (s, r) = unbounded();

        thread::spawn(move || {
            s.send(1).unwrap();
            s.send(2).unwrap();
        });

        let msg1 = r.recv().unwrap();
        let msg2 = r.recv().unwrap();

        assert_eq!(msg1 + msg2, 3);
    }

    #[test]
    fn test_groups() {
        let counter = Arc::new(Mutex::new(0));

        let counter1 = counter.clone();
        let worker_fn1 = move || {
            let mut counter = counter1.lock().unwrap();
            *counter += 1;
            thread::sleep(Duration::from_millis(50));
            println!("worker 1 finished");
        };

        let (s, r) = unbounded();
        let counter2 = counter.clone();
        let worker_fn2 = move |x| {
            let mut counter = counter2.lock().unwrap();
            *counter += 1;
            select! {
                recv(x) -> _ => {
                    println!("worker 2 finished");
                }
            }
        };

        thread::spawn(move || {
            thread::sleep(Duration::from_millis(300));
            drop(s);
            println!("notify worker 2 to finish");
        });

        let group = Group::new();

        group.start(worker_fn1);
        println!("worker 1 started");

        group.start_with_channel(r, worker_fn2);
        println!("worker 2 started");

        println!("wait two workeres to finish");
        group.wait();
        println!("two workeres are finished");
    }

    #[test]
    fn test_exponential_backoff_manager() {
        // backoff at least 1ms, 2ms, 4ms, 8ms, 10ms, 10ms, 10ms
        let duration_factors = vec![1, 2, 4, 8, 10, 10, 10];
        let mut backoff_mgr = ExponentialBackoffManager::new_exponential_backoff_manager(
            Duration::from_millis(1),
            Duration::from_millis(10),
            Duration::from_secs(3600),
            2.0,
            0.0,
        );

        for i in duration_factors {
            let start = Instant::now();

            let r = backoff_mgr.backoff();
            select! {
                recv(r) -> _ => {},
            }
            let passed = Instant::now().duration_since(start).as_millis();

            assert_eq!(
                true,
                passed >= i,
                "backoff should be at least {} ms, but got {}",
                i,
                passed
            );
        }
    }

    #[test]
    fn test_jitter_backoff_manager_with_real_clock() {
        let mut backoff_mgr =
            JitteredBackoffManager::new_jittered_backoff_manager(Duration::from_millis(1), 0.0);

        for _ in 0..5 {
            let start = Instant::now();
            let r = backoff_mgr.backoff();
            select! {
                recv(r) -> _ => {},
            }
            let passed = Instant::now().duration_since(start).as_millis();

            assert_eq!(
                true,
                passed >= 1,
                "backoff should be at least 1ms, but got {}",
                passed
            );
        }
    }
}