1use anyhow::{bail, Context, Result};
2use async_trait::async_trait;
3use log::{error, info, warn};
4use serde::Serialize;
5use std::time::Duration;
6use tokio::{
7 sync::{mpsc, watch},
8 time::Instant,
9};
10
11pub const MAX_POLL_INTERVAL: Duration = Duration::from_hours(24);
13
14pub fn validate_poll_interval(interval: Duration, field: &str) -> Result<()> {
16 if interval.is_zero() {
17 bail!("{field} must be greater than zero");
18 }
19 if interval > MAX_POLL_INTERVAL {
20 bail!(
21 "{field} must not exceed {} seconds",
22 MAX_POLL_INTERVAL.as_secs()
23 );
24 }
25 Ok(())
26}
27
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
30pub struct ExponentialBackoff {
31 pub initial: Duration,
32 pub maximum: Duration,
33 pub multiplier: u32,
34}
35
36impl Default for ExponentialBackoff {
37 fn default() -> Self {
38 Self {
39 initial: Duration::from_secs(1),
40 maximum: Duration::from_secs(30),
41 multiplier: 2,
42 }
43 }
44}
45
46impl ExponentialBackoff {
47 fn validate(self) -> Result<()> {
48 if self.initial.is_zero() {
49 bail!("Reconnect initial delay must be greater than zero");
50 }
51 if self.maximum < self.initial {
52 bail!("Reconnect maximum delay must be at least the initial delay");
53 }
54 if self.multiplier < 2 {
55 bail!("Reconnect multiplier must be at least 2");
56 }
57 Ok(())
58 }
59
60 fn next(self, current: Duration) -> Duration {
61 current
62 .checked_mul(self.multiplier)
63 .unwrap_or(self.maximum)
64 .min(self.maximum)
65 }
66}
67
68#[derive(Debug, Clone, Copy)]
70pub struct DaemonConfig {
71 pub poll_interval: Duration,
72 pub operation_timeout: Option<Duration>,
73 pub reconnect: ExponentialBackoff,
74}
75
76impl Default for DaemonConfig {
77 fn default() -> Self {
78 Self {
79 poll_interval: Duration::from_secs(5),
80 operation_timeout: None,
81 reconnect: ExponentialBackoff::default(),
82 }
83 }
84}
85
86#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub enum HardwareStatus {
89 Unknown,
90 Online,
91 Offline,
92}
93
94impl HardwareStatus {
95 pub const fn as_str(self) -> &'static str {
96 match self {
97 Self::Unknown => "unknown",
98 Self::Online => "online",
99 Self::Offline => "offline",
100 }
101 }
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub enum CommandEffect {
107 Continue,
109 PollNow,
111 Reconnect,
113 Shutdown,
115}
116
117#[async_trait]
124pub trait Device<C>: Send {
125 type Snapshot: Serialize + Send + Sync;
126
127 async fn connect(&mut self) -> Result<()>;
128 async fn poll(&mut self) -> Result<Self::Snapshot>;
129
130 async fn handle_command(&mut self, command: C, connected: bool) -> Result<CommandEffect>;
131
132 fn poll_interval(&self) -> Option<Duration> {
134 None
135 }
136}
137
138#[async_trait]
140pub trait Output<S>: Send {
141 async fn publish(&mut self, snapshot: &S) -> Result<()>;
142
143 async fn hardware_status(&mut self, _status: HardwareStatus) -> Result<()> {
144 Ok(())
145 }
146
147 async fn shutdown(&mut self) -> Result<()> {
148 Ok(())
149 }
150}
151
152pub async fn run<D, O, C>(
154 device: D,
155 output: O,
156 commands: Option<mpsc::Receiver<C>>,
157 config: DaemonConfig,
158) -> Result<()>
159where
160 D: Device<C>,
161 O: Output<D::Snapshot>,
162 C: Send,
163{
164 let (shutdown_sender, shutdown_receiver) = watch::channel(false);
165 let signal_task = tokio::spawn(async move {
166 match tokio::signal::ctrl_c().await {
167 Ok(()) => {
168 let _ = shutdown_sender.send(true);
169 }
170 Err(error) => {
171 warn!("Failed to listen for Ctrl-C: {error}");
172 let _ = shutdown_sender.send(true);
173 }
174 }
175 });
176
177 let result = run_with_shutdown(device, output, commands, config, shutdown_receiver).await;
178 signal_task.abort();
179 let _ = signal_task.await;
180 result
181}
182
183pub async fn run_with_shutdown<D, O, C>(
188 mut device: D,
189 mut output: O,
190 mut commands: Option<mpsc::Receiver<C>>,
191 config: DaemonConfig,
192 mut shutdown: watch::Receiver<bool>,
193) -> Result<()>
194where
195 D: Device<C>,
196 O: Output<D::Snapshot>,
197 C: Send,
198{
199 if let Err(error) = validate_config(config) {
200 if let Err(shutdown_error) = output.shutdown().await {
201 warn!("Output shutdown failed after invalid daemon configuration: {shutdown_error:#}");
202 }
203 return Err(error);
204 }
205 let mut connected = false;
206 let mut status = HardwareStatus::Unknown;
207 let mut reconnect_delay = config.reconnect.initial;
208 let mut next_poll = Instant::now();
209 info!("Device daemon started");
210
211 let result = 'daemon: loop {
212 if *shutdown.borrow() {
213 break 'daemon Ok(());
214 }
215
216 if !connected {
217 match operation_or_shutdown(config.operation_timeout, device.connect(), &mut shutdown)
218 .await
219 {
220 Ok(Some(())) => {
221 connected = true;
222 next_poll = Instant::now();
223 info!("Device connection established");
224 }
225 Ok(None) => break 'daemon Ok(()),
226 Err(error) => {
227 error!("Device connection failed: {error:#}");
228 if !set_status(
229 &mut output,
230 &mut status,
231 HardwareStatus::Offline,
232 &mut shutdown,
233 )
234 .await
235 {
236 break 'daemon Ok(());
237 }
238 let wait = wait_until(
239 Instant::now() + reconnect_delay,
240 &mut device,
241 &mut commands,
242 &mut shutdown,
243 false,
244 config.poll_interval,
245 config.operation_timeout,
246 )
247 .await;
248 match wait {
249 WaitOutcome::Shutdown => break 'daemon Ok(()),
250 WaitOutcome::Reconnect => {}
251 WaitOutcome::Poll => {}
252 }
253 reconnect_delay = config.reconnect.next(reconnect_delay);
254 continue;
255 }
256 }
257 }
258
259 match wait_until(
260 next_poll,
261 &mut device,
262 &mut commands,
263 &mut shutdown,
264 connected,
265 config.poll_interval,
266 config.operation_timeout,
267 )
268 .await
269 {
270 WaitOutcome::Shutdown => break 'daemon Ok(()),
271 WaitOutcome::Reconnect => {
272 connected = false;
273 if !set_status(
274 &mut output,
275 &mut status,
276 HardwareStatus::Offline,
277 &mut shutdown,
278 )
279 .await
280 {
281 break 'daemon Ok(());
282 }
283 reconnect_delay = config.reconnect.initial;
284 continue;
285 }
286 WaitOutcome::Poll => {}
287 }
288
289 match operation_or_shutdown(config.operation_timeout, device.poll(), &mut shutdown).await {
290 Ok(Some(snapshot)) => {
291 reconnect_delay = config.reconnect.initial;
292 if !set_status(
293 &mut output,
294 &mut status,
295 HardwareStatus::Online,
296 &mut shutdown,
297 )
298 .await
299 {
300 break 'daemon Ok(());
301 }
302 match operation_or_shutdown(None, output.publish(&snapshot), &mut shutdown).await {
303 Ok(Some(())) => {}
304 Ok(None) => break 'daemon Ok(()),
305 Err(error) => error!("Failed to publish device state: {error:#}"),
306 }
307
308 let interval = device.poll_interval().unwrap_or(config.poll_interval);
309 if interval.is_zero() {
310 break 'daemon Err(anyhow::anyhow!(
311 "Device poll interval must be greater than zero"
312 ));
313 }
314 next_poll = Instant::now() + interval;
315 }
316 Ok(None) => break 'daemon Ok(()),
317 Err(error) => {
318 error!("Device poll failed: {error:#}");
319 connected = false;
320 if !set_status(
321 &mut output,
322 &mut status,
323 HardwareStatus::Offline,
324 &mut shutdown,
325 )
326 .await
327 {
328 break 'daemon Ok(());
329 }
330 let wait = wait_until(
331 Instant::now() + reconnect_delay,
332 &mut device,
333 &mut commands,
334 &mut shutdown,
335 false,
336 config.poll_interval,
337 config.operation_timeout,
338 )
339 .await;
340 if matches!(wait, WaitOutcome::Shutdown) {
341 break 'daemon Ok(());
342 }
343 reconnect_delay = config.reconnect.next(reconnect_delay);
344 }
345 }
346 };
347
348 if let Err(error) = output.shutdown().await {
349 warn!("Output shutdown failed: {error:#}");
350 }
351 info!("Device daemon stopped");
352 result
353}
354
355fn validate_config(config: DaemonConfig) -> Result<()> {
356 if config.poll_interval.is_zero() {
357 bail!("Polling interval must be greater than zero");
358 }
359 if config
360 .operation_timeout
361 .is_some_and(|timeout| timeout.is_zero())
362 {
363 bail!("Operation timeout must be greater than zero");
364 }
365 config.reconnect.validate()
366}
367
368async fn operation<T, F>(timeout: Option<Duration>, future: F) -> Result<T>
369where
370 F: std::future::Future<Output = Result<T>>,
371{
372 match timeout {
373 Some(timeout) => tokio::time::timeout(timeout, future)
374 .await
375 .context("Device operation timed out")?,
376 None => future.await,
377 }
378}
379
380async fn operation_or_shutdown<T, F>(
381 timeout: Option<Duration>,
382 future: F,
383 shutdown: &mut watch::Receiver<bool>,
384) -> Result<Option<T>>
385where
386 F: std::future::Future<Output = Result<T>>,
387{
388 let operation = operation(timeout, future);
389 tokio::pin!(operation);
390 loop {
391 tokio::select! {
392 result = &mut operation => return result.map(Some),
393 changed = shutdown.changed() => {
394 if changed.is_err() || *shutdown.borrow() {
395 return Ok(None);
396 }
397 }
398 }
399 }
400}
401
402enum WaitOutcome {
403 Poll,
404 Reconnect,
405 Shutdown,
406}
407
408async fn wait_until<D, C>(
409 deadline: Instant,
410 device: &mut D,
411 commands: &mut Option<mpsc::Receiver<C>>,
412 shutdown: &mut watch::Receiver<bool>,
413 connected: bool,
414 default_interval: Duration,
415 operation_timeout: Option<Duration>,
416) -> WaitOutcome
417where
418 D: Device<C>,
419 C: Send,
420{
421 let timer = tokio::time::sleep_until(deadline);
422 tokio::pin!(timer);
423
424 loop {
425 if *shutdown.borrow() {
426 return WaitOutcome::Shutdown;
427 }
428
429 tokio::select! {
430 _ = &mut timer => return WaitOutcome::Poll,
431 changed = shutdown.changed() => {
432 if changed.is_err() || *shutdown.borrow() {
433 return WaitOutcome::Shutdown;
434 }
435 }
436 command = receive_command(commands), if commands.is_some() => {
437 match command {
438 Some(command) => {
439 match operation_or_shutdown(
440 operation_timeout,
441 device.handle_command(command, connected),
442 shutdown,
443 )
444 .await
445 {
446 Ok(Some(CommandEffect::Continue)) => {
447 let interval =
448 device.poll_interval().unwrap_or(default_interval);
449 if interval.is_zero() {
450 error!("Ignoring command that set a zero polling interval");
451 } else {
452 timer.as_mut().reset(Instant::now() + interval);
453 }
454 }
455 Ok(Some(CommandEffect::PollNow)) => return WaitOutcome::Poll,
456 Ok(Some(CommandEffect::Reconnect)) => return WaitOutcome::Reconnect,
457 Ok(Some(CommandEffect::Shutdown)) | Ok(None) => {
458 return WaitOutcome::Shutdown
459 }
460 Err(error) => warn!("Device command failed: {error:#}"),
461 }
462 }
463 None => {
464 warn!("Device command channel closed; continuing without controls");
465 *commands = None;
466 }
467 }
468 }
469 }
470 }
471}
472
473async fn receive_command<C>(commands: &mut Option<mpsc::Receiver<C>>) -> Option<C> {
474 match commands {
475 Some(receiver) => receiver.recv().await,
476 None => std::future::pending().await,
477 }
478}
479
480async fn set_status<O, S>(
481 output: &mut O,
482 previous: &mut HardwareStatus,
483 current: HardwareStatus,
484 shutdown: &mut watch::Receiver<bool>,
485) -> bool
486where
487 O: Output<S>,
488{
489 if *previous == current {
490 return true;
491 }
492 match operation_or_shutdown(None, output.hardware_status(current), shutdown).await {
493 Ok(Some(())) => *previous = current,
494 Ok(None) => return false,
495 Err(error) => error!("Failed to publish device availability: {error:#}"),
496 }
497 true
498}
499
500#[cfg(test)]
501mod tests {
502 use super::*;
503 use std::sync::{Arc, Mutex};
504
505 #[derive(Default)]
506 struct FakeDevice {
507 polls: usize,
508 connected: bool,
509 interval: Duration,
510 commands: Vec<String>,
511 failed_connections: usize,
512 blocked_poll: bool,
513 }
514
515 #[async_trait]
516 impl Device<String> for FakeDevice {
517 type Snapshot = usize;
518
519 async fn connect(&mut self) -> Result<()> {
520 if self.failed_connections > 0 {
521 self.failed_connections -= 1;
522 anyhow::bail!("temporary connection failure");
523 }
524 self.connected = true;
525 Ok(())
526 }
527
528 async fn poll(&mut self) -> Result<Self::Snapshot> {
529 if self.blocked_poll {
530 return std::future::pending().await;
531 }
532 self.polls += 1;
533 Ok(self.polls)
534 }
535
536 async fn handle_command(
537 &mut self,
538 command: String,
539 connected: bool,
540 ) -> Result<CommandEffect> {
541 self.commands.push(format!("{command}:{connected}"));
542 Ok(if command == "poll" {
543 CommandEffect::PollNow
544 } else {
545 CommandEffect::Continue
546 })
547 }
548
549 fn poll_interval(&self) -> Option<Duration> {
550 Some(self.interval)
551 }
552 }
553
554 #[derive(Clone, Default)]
555 struct FakeOutput(Arc<Mutex<Vec<String>>>);
556
557 #[async_trait]
558 impl Output<usize> for FakeOutput {
559 async fn publish(&mut self, snapshot: &usize) -> Result<()> {
560 self.0.lock().unwrap().push(format!("snapshot:{snapshot}"));
561 Ok(())
562 }
563
564 async fn hardware_status(&mut self, status: HardwareStatus) -> Result<()> {
565 self.0
566 .lock()
567 .unwrap()
568 .push(format!("status:{}", status.as_str()));
569 Ok(())
570 }
571
572 async fn shutdown(&mut self) -> Result<()> {
573 self.0.lock().unwrap().push("shutdown".to_owned());
574 Ok(())
575 }
576 }
577
578 struct BlockingPublishOutput(Arc<Mutex<bool>>);
579
580 #[async_trait]
581 impl Output<usize> for BlockingPublishOutput {
582 async fn publish(&mut self, _: &usize) -> Result<()> {
583 std::future::pending().await
584 }
585
586 async fn hardware_status(&mut self, _: HardwareStatus) -> Result<()> {
587 Ok(())
588 }
589
590 async fn shutdown(&mut self) -> Result<()> {
591 *self.0.lock().unwrap() = true;
592 Ok(())
593 }
594 }
595
596 #[tokio::test]
597 async fn polls_and_shuts_down_cleanly() {
598 let device = FakeDevice {
599 interval: Duration::from_millis(5),
600 ..FakeDevice::default()
601 };
602 let output = FakeOutput::default();
603 let events = output.0.clone();
604 let (shutdown_sender, shutdown_receiver) = watch::channel(false);
605 let task = tokio::spawn(run_with_shutdown(
606 device,
607 output,
608 None::<mpsc::Receiver<String>>,
609 DaemonConfig {
610 poll_interval: Duration::from_millis(5),
611 ..DaemonConfig::default()
612 },
613 shutdown_receiver,
614 ));
615
616 tokio::time::sleep(Duration::from_millis(25)).await;
617 shutdown_sender.send(true).unwrap();
618 task.await.unwrap().unwrap();
619
620 let events = events.lock().unwrap();
621 assert!(events.iter().any(|event| event == "status:online"));
622 assert!(events.iter().any(|event| event.starts_with("snapshot:")));
623 assert_eq!(events.last().map(String::as_str), Some("shutdown"));
624 }
625
626 #[tokio::test]
627 async fn poll_command_interrupts_the_poll_delay() {
628 let device = FakeDevice {
629 interval: Duration::from_secs(60),
630 ..FakeDevice::default()
631 };
632 let output = FakeOutput::default();
633 let events = output.0.clone();
634 let (command_sender, command_receiver) = mpsc::channel(2);
635 let (shutdown_sender, shutdown_receiver) = watch::channel(false);
636 let task = tokio::spawn(run_with_shutdown(
637 device,
638 output,
639 Some(command_receiver),
640 DaemonConfig {
641 poll_interval: Duration::from_secs(60),
642 ..DaemonConfig::default()
643 },
644 shutdown_receiver,
645 ));
646
647 tokio::time::sleep(Duration::from_millis(10)).await;
648 command_sender.send("poll".to_owned()).await.unwrap();
649 tokio::time::sleep(Duration::from_millis(10)).await;
650 shutdown_sender.send(true).unwrap();
651 task.await.unwrap().unwrap();
652
653 let snapshot_count = events
654 .lock()
655 .unwrap()
656 .iter()
657 .filter(|event| event.starts_with("snapshot:"))
658 .count();
659 assert!(snapshot_count >= 2);
660 }
661
662 #[tokio::test]
663 async fn connection_failures_are_retried() {
664 let device = FakeDevice {
665 interval: Duration::from_millis(2),
666 failed_connections: 1,
667 ..FakeDevice::default()
668 };
669 let output = FakeOutput::default();
670 let events = output.0.clone();
671 let (shutdown_sender, shutdown_receiver) = watch::channel(false);
672 let task = tokio::spawn(run_with_shutdown(
673 device,
674 output,
675 None::<mpsc::Receiver<String>>,
676 DaemonConfig {
677 poll_interval: Duration::from_millis(2),
678 reconnect: ExponentialBackoff {
679 initial: Duration::from_millis(2),
680 maximum: Duration::from_millis(8),
681 multiplier: 2,
682 },
683 ..DaemonConfig::default()
684 },
685 shutdown_receiver,
686 ));
687
688 tokio::time::sleep(Duration::from_millis(20)).await;
689 shutdown_sender.send(true).unwrap();
690 task.await.unwrap().unwrap();
691
692 assert!(events
693 .lock()
694 .unwrap()
695 .iter()
696 .any(|event| event.starts_with("snapshot:")));
697 }
698
699 #[tokio::test]
700 async fn shutdown_cancels_an_in_flight_poll() {
701 let device = FakeDevice {
702 blocked_poll: true,
703 interval: Duration::from_secs(60),
704 ..FakeDevice::default()
705 };
706 let (shutdown_sender, shutdown_receiver) = watch::channel(false);
707 let task = tokio::spawn(run_with_shutdown(
708 device,
709 FakeOutput::default(),
710 None::<mpsc::Receiver<String>>,
711 DaemonConfig::default(),
712 shutdown_receiver,
713 ));
714
715 tokio::time::sleep(Duration::from_millis(5)).await;
716 shutdown_sender.send(true).unwrap();
717 tokio::time::timeout(Duration::from_millis(100), task)
718 .await
719 .expect("runner should stop promptly")
720 .unwrap()
721 .unwrap();
722 }
723
724 #[tokio::test]
725 async fn shutdown_cancels_an_in_flight_publish() {
726 let shutdown_called = Arc::new(Mutex::new(false));
727 let (shutdown_sender, shutdown_receiver) = watch::channel(false);
728 let task = tokio::spawn(run_with_shutdown(
729 FakeDevice::default(),
730 BlockingPublishOutput(shutdown_called.clone()),
731 None::<mpsc::Receiver<String>>,
732 DaemonConfig::default(),
733 shutdown_receiver,
734 ));
735
736 tokio::time::sleep(Duration::from_millis(5)).await;
737 shutdown_sender.send(true).unwrap();
738 tokio::time::timeout(Duration::from_millis(100), task)
739 .await
740 .expect("runner should stop promptly")
741 .unwrap()
742 .unwrap();
743 assert!(*shutdown_called.lock().unwrap());
744 }
745
746 #[test]
747 fn validates_reconnect_policy_and_poll_interval() {
748 assert!(validate_poll_interval(Duration::from_secs(1), "daemon.poll_interval").is_ok());
749 assert!(validate_poll_interval(Duration::ZERO, "daemon.poll_interval").is_err());
750 assert!(validate_poll_interval(
751 MAX_POLL_INTERVAL + Duration::from_secs(1),
752 "daemon.poll_interval"
753 )
754 .is_err());
755 assert!(validate_config(DaemonConfig {
756 poll_interval: Duration::ZERO,
757 ..DaemonConfig::default()
758 })
759 .is_err());
760 assert!(ExponentialBackoff {
761 initial: Duration::from_secs(2),
762 maximum: Duration::from_secs(1),
763 multiplier: 2,
764 }
765 .validate()
766 .is_err());
767 }
768}