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,
};
pub const MAX_POLL_INTERVAL: Duration = Duration::from_hours(24);
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(())
}
#[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)
}
}
#[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(),
}
}
}
#[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",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CommandEffect {
Continue,
PollNow,
Reconnect,
Shutdown,
}
#[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>;
fn poll_interval(&self) -> Option<Duration> {
None
}
}
#[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(())
}
}
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
}
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());
}
}