From 3b3633f6f5d4275e1f52605807d1c626ed2e6961 Mon Sep 17 00:00:00 2001 From: Djeeberjr Date: Sun, 1 Jun 2025 15:41:24 +0200 Subject: [PATCH] added activity_fairing for webserver --- src/activity_fairing.rs | 46 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/activity_fairing.rs diff --git a/src/activity_fairing.rs b/src/activity_fairing.rs new file mode 100644 index 0000000..ceeb4ce --- /dev/null +++ b/src/activity_fairing.rs @@ -0,0 +1,46 @@ +use std::time::Duration; + +use log::error; +use rocket::{ + Data, Request, + fairing::{Fairing, Info, Kind}, +}; +use tokio::{sync::mpsc, time::timeout}; + +pub struct ActivityNotifier { + pub sender: mpsc::Sender<()>, +} + +#[rocket::async_trait] +impl Fairing for ActivityNotifier { + fn info(&self) -> Info { + Info { + name: "Keeps track of time since the last request", + kind: Kind::Request | Kind::Response, + } + } + + async fn on_request(&self, _: &mut Request<'_>, _: &mut Data<'_>) { + error!("on_request"); + let _ = self.sender.try_send(()); + } +} + +pub fn spawn_idle_watcher(idle_duration: Duration, mut on_idle: F) -> mpsc::Sender<()> +where + F: FnMut() + Send + 'static, +{ + let (tx, mut rx) = mpsc::channel::<()>(100); + + tokio::spawn(async move { + loop { + let idle = timeout(idle_duration, rx.recv()).await; + if idle.is_err() { + // No activity received in the duration + on_idle(); + } + } + }); + + tx +}