device-daemon-core 0.0.2

Reusable async daemon and MQTT infrastructure for device clients
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
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
use anyhow::{bail, Context, Result};
use async_trait::async_trait;
use log::{error, info, warn};
use serde::Serialize;
use std::time::Duration;
use tokio::{
    sync::{mpsc, watch},
    time::Instant,
};

/// Maximum supported polling interval for a managed device daemon.
pub const MAX_POLL_INTERVAL: Duration = Duration::from_hours(24);

/// Validate a configured or runtime polling interval using the shared bound.
pub fn validate_poll_interval(interval: Duration, field: &str) -> Result<()> {
    if interval.is_zero() {
        bail!("{field} must be greater than zero");
    }
    if interval > MAX_POLL_INTERVAL {
        bail!(
            "{field} must not exceed {} seconds",
            MAX_POLL_INTERVAL.as_secs()
        );
    }
    Ok(())
}

/// Reconnection delay policy used after connect and poll failures.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExponentialBackoff {
    pub initial: Duration,
    pub maximum: Duration,
    pub multiplier: u32,
}

impl Default for ExponentialBackoff {
    fn default() -> Self {
        Self {
            initial: Duration::from_secs(1),
            maximum: Duration::from_secs(30),
            multiplier: 2,
        }
    }
}

impl ExponentialBackoff {
    fn validate(self) -> Result<()> {
        if self.initial.is_zero() {
            bail!("Reconnect initial delay must be greater than zero");
        }
        if self.maximum < self.initial {
            bail!("Reconnect maximum delay must be at least the initial delay");
        }
        if self.multiplier < 2 {
            bail!("Reconnect multiplier must be at least 2");
        }
        Ok(())
    }

    fn next(self, current: Duration) -> Duration {
        current
            .checked_mul(self.multiplier)
            .unwrap_or(self.maximum)
            .min(self.maximum)
    }
}

/// Runtime parameters for the common daemon loop.
#[derive(Debug, Clone, Copy)]
pub struct DaemonConfig {
    pub poll_interval: Duration,
    pub operation_timeout: Option<Duration>,
    pub reconnect: ExponentialBackoff,
}

impl Default for DaemonConfig {
    fn default() -> Self {
        Self {
            poll_interval: Duration::from_secs(5),
            operation_timeout: None,
            reconnect: ExponentialBackoff::default(),
        }
    }
}

/// Current device availability, published when it changes.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HardwareStatus {
    Unknown,
    Online,
    Offline,
}

impl HardwareStatus {
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Unknown => "unknown",
            Self::Online => "online",
            Self::Offline => "offline",
        }
    }
}

/// Effect a successfully handled device command has on the polling loop.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CommandEffect {
    /// Keep the current schedule. The device may have changed its poll interval.
    Continue,
    /// Poll immediately.
    PollNow,
    /// Drop the device connection and reconnect.
    Reconnect,
    /// Stop the daemon gracefully.
    Shutdown,
}

/// Device-specific connection, polling, and control operations.
///
/// The adapter owns the concrete protocol client. A failed connect or poll
/// causes the runner to retry with exponential backoff; command validation
/// errors are logged and do not by themselves drop the connection. The adapter
/// can explicitly request reconnection with [`CommandEffect::Reconnect`].
#[async_trait]
pub trait Device<C>: Send {
    type Snapshot: Serialize + Send + Sync;

    async fn connect(&mut self) -> Result<()>;
    async fn poll(&mut self) -> Result<Self::Snapshot>;

    async fn handle_command(&mut self, command: C, connected: bool) -> Result<CommandEffect>;

    /// Allows commands to change the polling interval at runtime.
    fn poll_interval(&self) -> Option<Duration> {
        None
    }
}

/// Output adapter for console, MQTT, or another telemetry transport.
#[async_trait]
pub trait Output<S>: Send {
    async fn publish(&mut self, snapshot: &S) -> Result<()>;

    async fn hardware_status(&mut self, _status: HardwareStatus) -> Result<()> {
        Ok(())
    }

    async fn shutdown(&mut self) -> Result<()> {
        Ok(())
    }
}

/// Run a device daemon until Ctrl-C is received.
pub async fn run<D, O, C>(
    device: D,
    output: O,
    commands: Option<mpsc::Receiver<C>>,
    config: DaemonConfig,
) -> Result<()>
where
    D: Device<C>,
    O: Output<D::Snapshot>,
    C: Send,
{
    let (shutdown_sender, shutdown_receiver) = watch::channel(false);
    let signal_task = tokio::spawn(async move {
        match tokio::signal::ctrl_c().await {
            Ok(()) => {
                let _ = shutdown_sender.send(true);
            }
            Err(error) => {
                warn!("Failed to listen for Ctrl-C: {error}");
                let _ = shutdown_sender.send(true);
            }
        }
    });

    let result = run_with_shutdown(device, output, commands, config, shutdown_receiver).await;
    signal_task.abort();
    let _ = signal_task.await;
    result
}

/// Run a device daemon until the supplied watch channel is set to `true`.
///
/// This entry point is useful for applications with their own shutdown
/// coordinator and makes the runner straightforward to test.
pub async fn run_with_shutdown<D, O, C>(
    mut device: D,
    mut output: O,
    mut commands: Option<mpsc::Receiver<C>>,
    config: DaemonConfig,
    mut shutdown: watch::Receiver<bool>,
) -> Result<()>
where
    D: Device<C>,
    O: Output<D::Snapshot>,
    C: Send,
{
    if let Err(error) = validate_config(config) {
        if let Err(shutdown_error) = output.shutdown().await {
            warn!("Output shutdown failed after invalid daemon configuration: {shutdown_error:#}");
        }
        return Err(error);
    }
    let mut connected = false;
    let mut status = HardwareStatus::Unknown;
    let mut reconnect_delay = config.reconnect.initial;
    let mut next_poll = Instant::now();
    info!("Device daemon started");

    let result = 'daemon: loop {
        if *shutdown.borrow() {
            break 'daemon Ok(());
        }

        if !connected {
            match operation_or_shutdown(config.operation_timeout, device.connect(), &mut shutdown)
                .await
            {
                Ok(Some(())) => {
                    connected = true;
                    next_poll = Instant::now();
                    info!("Device connection established");
                }
                Ok(None) => break 'daemon Ok(()),
                Err(error) => {
                    error!("Device connection failed: {error:#}");
                    if !set_status(
                        &mut output,
                        &mut status,
                        HardwareStatus::Offline,
                        &mut shutdown,
                    )
                    .await
                    {
                        break 'daemon Ok(());
                    }
                    let wait = wait_until(
                        Instant::now() + reconnect_delay,
                        &mut device,
                        &mut commands,
                        &mut shutdown,
                        false,
                        config.poll_interval,
                        config.operation_timeout,
                    )
                    .await;
                    match wait {
                        WaitOutcome::Shutdown => break 'daemon Ok(()),
                        WaitOutcome::Reconnect => {}
                        WaitOutcome::Poll => {}
                    }
                    reconnect_delay = config.reconnect.next(reconnect_delay);
                    continue;
                }
            }
        }

        match wait_until(
            next_poll,
            &mut device,
            &mut commands,
            &mut shutdown,
            connected,
            config.poll_interval,
            config.operation_timeout,
        )
        .await
        {
            WaitOutcome::Shutdown => break 'daemon Ok(()),
            WaitOutcome::Reconnect => {
                connected = false;
                if !set_status(
                    &mut output,
                    &mut status,
                    HardwareStatus::Offline,
                    &mut shutdown,
                )
                .await
                {
                    break 'daemon Ok(());
                }
                reconnect_delay = config.reconnect.initial;
                continue;
            }
            WaitOutcome::Poll => {}
        }

        match operation_or_shutdown(config.operation_timeout, device.poll(), &mut shutdown).await {
            Ok(Some(snapshot)) => {
                reconnect_delay = config.reconnect.initial;
                if !set_status(
                    &mut output,
                    &mut status,
                    HardwareStatus::Online,
                    &mut shutdown,
                )
                .await
                {
                    break 'daemon Ok(());
                }
                match operation_or_shutdown(None, output.publish(&snapshot), &mut shutdown).await {
                    Ok(Some(())) => {}
                    Ok(None) => break 'daemon Ok(()),
                    Err(error) => error!("Failed to publish device state: {error:#}"),
                }

                let interval = device.poll_interval().unwrap_or(config.poll_interval);
                if interval.is_zero() {
                    break 'daemon Err(anyhow::anyhow!(
                        "Device poll interval must be greater than zero"
                    ));
                }
                next_poll = Instant::now() + interval;
            }
            Ok(None) => break 'daemon Ok(()),
            Err(error) => {
                error!("Device poll failed: {error:#}");
                connected = false;
                if !set_status(
                    &mut output,
                    &mut status,
                    HardwareStatus::Offline,
                    &mut shutdown,
                )
                .await
                {
                    break 'daemon Ok(());
                }
                let wait = wait_until(
                    Instant::now() + reconnect_delay,
                    &mut device,
                    &mut commands,
                    &mut shutdown,
                    false,
                    config.poll_interval,
                    config.operation_timeout,
                )
                .await;
                if matches!(wait, WaitOutcome::Shutdown) {
                    break 'daemon Ok(());
                }
                reconnect_delay = config.reconnect.next(reconnect_delay);
            }
        }
    };

    if let Err(error) = output.shutdown().await {
        warn!("Output shutdown failed: {error:#}");
    }
    info!("Device daemon stopped");
    result
}

fn validate_config(config: DaemonConfig) -> Result<()> {
    if config.poll_interval.is_zero() {
        bail!("Polling interval must be greater than zero");
    }
    if config
        .operation_timeout
        .is_some_and(|timeout| timeout.is_zero())
    {
        bail!("Operation timeout must be greater than zero");
    }
    config.reconnect.validate()
}

async fn operation<T, F>(timeout: Option<Duration>, future: F) -> Result<T>
where
    F: std::future::Future<Output = Result<T>>,
{
    match timeout {
        Some(timeout) => tokio::time::timeout(timeout, future)
            .await
            .context("Device operation timed out")?,
        None => future.await,
    }
}

async fn operation_or_shutdown<T, F>(
    timeout: Option<Duration>,
    future: F,
    shutdown: &mut watch::Receiver<bool>,
) -> Result<Option<T>>
where
    F: std::future::Future<Output = Result<T>>,
{
    let operation = operation(timeout, future);
    tokio::pin!(operation);
    loop {
        tokio::select! {
            result = &mut operation => return result.map(Some),
            changed = shutdown.changed() => {
                if changed.is_err() || *shutdown.borrow() {
                    return Ok(None);
                }
            }
        }
    }
}

enum WaitOutcome {
    Poll,
    Reconnect,
    Shutdown,
}

async fn wait_until<D, C>(
    deadline: Instant,
    device: &mut D,
    commands: &mut Option<mpsc::Receiver<C>>,
    shutdown: &mut watch::Receiver<bool>,
    connected: bool,
    default_interval: Duration,
    operation_timeout: Option<Duration>,
) -> WaitOutcome
where
    D: Device<C>,
    C: Send,
{
    let timer = tokio::time::sleep_until(deadline);
    tokio::pin!(timer);

    loop {
        if *shutdown.borrow() {
            return WaitOutcome::Shutdown;
        }

        tokio::select! {
            _ = &mut timer => return WaitOutcome::Poll,
            changed = shutdown.changed() => {
                if changed.is_err() || *shutdown.borrow() {
                    return WaitOutcome::Shutdown;
                }
            }
            command = receive_command(commands), if commands.is_some() => {
                match command {
                    Some(command) => {
                        match operation_or_shutdown(
                            operation_timeout,
                            device.handle_command(command, connected),
                            shutdown,
                        )
                        .await
                        {
                            Ok(Some(CommandEffect::Continue)) => {
                                let interval =
                                    device.poll_interval().unwrap_or(default_interval);
                                if interval.is_zero() {
                                    error!("Ignoring command that set a zero polling interval");
                                } else {
                                    timer.as_mut().reset(Instant::now() + interval);
                                }
                            }
                            Ok(Some(CommandEffect::PollNow)) => return WaitOutcome::Poll,
                            Ok(Some(CommandEffect::Reconnect)) => return WaitOutcome::Reconnect,
                            Ok(Some(CommandEffect::Shutdown)) | Ok(None) => {
                                return WaitOutcome::Shutdown
                            }
                            Err(error) => warn!("Device command failed: {error:#}"),
                        }
                    }
                    None => {
                        warn!("Device command channel closed; continuing without controls");
                        *commands = None;
                    }
                }
            }
        }
    }
}

async fn receive_command<C>(commands: &mut Option<mpsc::Receiver<C>>) -> Option<C> {
    match commands {
        Some(receiver) => receiver.recv().await,
        None => std::future::pending().await,
    }
}

async fn set_status<O, S>(
    output: &mut O,
    previous: &mut HardwareStatus,
    current: HardwareStatus,
    shutdown: &mut watch::Receiver<bool>,
) -> bool
where
    O: Output<S>,
{
    if *previous == current {
        return true;
    }
    match operation_or_shutdown(None, output.hardware_status(current), shutdown).await {
        Ok(Some(())) => *previous = current,
        Ok(None) => return false,
        Err(error) => error!("Failed to publish device availability: {error:#}"),
    }
    true
}

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

    #[derive(Default)]
    struct FakeDevice {
        polls: usize,
        connected: bool,
        interval: Duration,
        commands: Vec<String>,
        failed_connections: usize,
        blocked_poll: bool,
    }

    #[async_trait]
    impl Device<String> for FakeDevice {
        type Snapshot = usize;

        async fn connect(&mut self) -> Result<()> {
            if self.failed_connections > 0 {
                self.failed_connections -= 1;
                anyhow::bail!("temporary connection failure");
            }
            self.connected = true;
            Ok(())
        }

        async fn poll(&mut self) -> Result<Self::Snapshot> {
            if self.blocked_poll {
                return std::future::pending().await;
            }
            self.polls += 1;
            Ok(self.polls)
        }

        async fn handle_command(
            &mut self,
            command: String,
            connected: bool,
        ) -> Result<CommandEffect> {
            self.commands.push(format!("{command}:{connected}"));
            Ok(if command == "poll" {
                CommandEffect::PollNow
            } else {
                CommandEffect::Continue
            })
        }

        fn poll_interval(&self) -> Option<Duration> {
            Some(self.interval)
        }
    }

    #[derive(Clone, Default)]
    struct FakeOutput(Arc<Mutex<Vec<String>>>);

    #[async_trait]
    impl Output<usize> for FakeOutput {
        async fn publish(&mut self, snapshot: &usize) -> Result<()> {
            self.0.lock().unwrap().push(format!("snapshot:{snapshot}"));
            Ok(())
        }

        async fn hardware_status(&mut self, status: HardwareStatus) -> Result<()> {
            self.0
                .lock()
                .unwrap()
                .push(format!("status:{}", status.as_str()));
            Ok(())
        }

        async fn shutdown(&mut self) -> Result<()> {
            self.0.lock().unwrap().push("shutdown".to_owned());
            Ok(())
        }
    }

    struct BlockingPublishOutput(Arc<Mutex<bool>>);

    #[async_trait]
    impl Output<usize> for BlockingPublishOutput {
        async fn publish(&mut self, _: &usize) -> Result<()> {
            std::future::pending().await
        }

        async fn hardware_status(&mut self, _: HardwareStatus) -> Result<()> {
            Ok(())
        }

        async fn shutdown(&mut self) -> Result<()> {
            *self.0.lock().unwrap() = true;
            Ok(())
        }
    }

    #[tokio::test]
    async fn polls_and_shuts_down_cleanly() {
        let device = FakeDevice {
            interval: Duration::from_millis(5),
            ..FakeDevice::default()
        };
        let output = FakeOutput::default();
        let events = output.0.clone();
        let (shutdown_sender, shutdown_receiver) = watch::channel(false);
        let task = tokio::spawn(run_with_shutdown(
            device,
            output,
            None::<mpsc::Receiver<String>>,
            DaemonConfig {
                poll_interval: Duration::from_millis(5),
                ..DaemonConfig::default()
            },
            shutdown_receiver,
        ));

        tokio::time::sleep(Duration::from_millis(25)).await;
        shutdown_sender.send(true).unwrap();
        task.await.unwrap().unwrap();

        let events = events.lock().unwrap();
        assert!(events.iter().any(|event| event == "status:online"));
        assert!(events.iter().any(|event| event.starts_with("snapshot:")));
        assert_eq!(events.last().map(String::as_str), Some("shutdown"));
    }

    #[tokio::test]
    async fn poll_command_interrupts_the_poll_delay() {
        let device = FakeDevice {
            interval: Duration::from_secs(60),
            ..FakeDevice::default()
        };
        let output = FakeOutput::default();
        let events = output.0.clone();
        let (command_sender, command_receiver) = mpsc::channel(2);
        let (shutdown_sender, shutdown_receiver) = watch::channel(false);
        let task = tokio::spawn(run_with_shutdown(
            device,
            output,
            Some(command_receiver),
            DaemonConfig {
                poll_interval: Duration::from_secs(60),
                ..DaemonConfig::default()
            },
            shutdown_receiver,
        ));

        tokio::time::sleep(Duration::from_millis(10)).await;
        command_sender.send("poll".to_owned()).await.unwrap();
        tokio::time::sleep(Duration::from_millis(10)).await;
        shutdown_sender.send(true).unwrap();
        task.await.unwrap().unwrap();

        let snapshot_count = events
            .lock()
            .unwrap()
            .iter()
            .filter(|event| event.starts_with("snapshot:"))
            .count();
        assert!(snapshot_count >= 2);
    }

    #[tokio::test]
    async fn connection_failures_are_retried() {
        let device = FakeDevice {
            interval: Duration::from_millis(2),
            failed_connections: 1,
            ..FakeDevice::default()
        };
        let output = FakeOutput::default();
        let events = output.0.clone();
        let (shutdown_sender, shutdown_receiver) = watch::channel(false);
        let task = tokio::spawn(run_with_shutdown(
            device,
            output,
            None::<mpsc::Receiver<String>>,
            DaemonConfig {
                poll_interval: Duration::from_millis(2),
                reconnect: ExponentialBackoff {
                    initial: Duration::from_millis(2),
                    maximum: Duration::from_millis(8),
                    multiplier: 2,
                },
                ..DaemonConfig::default()
            },
            shutdown_receiver,
        ));

        tokio::time::sleep(Duration::from_millis(20)).await;
        shutdown_sender.send(true).unwrap();
        task.await.unwrap().unwrap();

        assert!(events
            .lock()
            .unwrap()
            .iter()
            .any(|event| event.starts_with("snapshot:")));
    }

    #[tokio::test]
    async fn shutdown_cancels_an_in_flight_poll() {
        let device = FakeDevice {
            blocked_poll: true,
            interval: Duration::from_secs(60),
            ..FakeDevice::default()
        };
        let (shutdown_sender, shutdown_receiver) = watch::channel(false);
        let task = tokio::spawn(run_with_shutdown(
            device,
            FakeOutput::default(),
            None::<mpsc::Receiver<String>>,
            DaemonConfig::default(),
            shutdown_receiver,
        ));

        tokio::time::sleep(Duration::from_millis(5)).await;
        shutdown_sender.send(true).unwrap();
        tokio::time::timeout(Duration::from_millis(100), task)
            .await
            .expect("runner should stop promptly")
            .unwrap()
            .unwrap();
    }

    #[tokio::test]
    async fn shutdown_cancels_an_in_flight_publish() {
        let shutdown_called = Arc::new(Mutex::new(false));
        let (shutdown_sender, shutdown_receiver) = watch::channel(false);
        let task = tokio::spawn(run_with_shutdown(
            FakeDevice::default(),
            BlockingPublishOutput(shutdown_called.clone()),
            None::<mpsc::Receiver<String>>,
            DaemonConfig::default(),
            shutdown_receiver,
        ));

        tokio::time::sleep(Duration::from_millis(5)).await;
        shutdown_sender.send(true).unwrap();
        tokio::time::timeout(Duration::from_millis(100), task)
            .await
            .expect("runner should stop promptly")
            .unwrap()
            .unwrap();
        assert!(*shutdown_called.lock().unwrap());
    }

    #[test]
    fn validates_reconnect_policy_and_poll_interval() {
        assert!(validate_poll_interval(Duration::from_secs(1), "daemon.poll_interval").is_ok());
        assert!(validate_poll_interval(Duration::ZERO, "daemon.poll_interval").is_err());
        assert!(validate_poll_interval(
            MAX_POLL_INTERVAL + Duration::from_secs(1),
            "daemon.poll_interval"
        )
        .is_err());
        assert!(validate_config(DaemonConfig {
            poll_interval: Duration::ZERO,
            ..DaemonConfig::default()
        })
        .is_err());
        assert!(ExponentialBackoff {
            initial: Duration::from_secs(2),
            maximum: Duration::from_secs(1),
            multiplier: 2,
        }
        .validate()
        .is_err());
    }
}