Replace Duration by TimeDelta for Chrono

This simplifies the code.
This commit is contained in:
Demmie 2024-06-24 01:42:56 -04:00
parent e1d5071869
commit db3d14bf4a
No known key found for this signature in database
GPG Key ID: B06DAA3D432C6E9A
10 changed files with 48 additions and 46 deletions

View File

@ -29,14 +29,17 @@ async fn main() -> anyhow::Result<(), Box<dyn Error>> {
} else {
info!("Sending to server {}:{}", config.host, config.port);
}
info!("Idle timeout: {} seconds", config.idle_timeout.as_secs());
info!(
"Idle timeout: {} seconds",
config.idle_timeout.num_seconds()
);
info!(
"Idle polling period: {} seconds",
config.poll_time_idle.as_secs()
config.poll_time_idle.num_seconds()
);
info!(
"Window polling period: {} seconds",
config.poll_time_window.as_secs()
config.poll_time_window.num_seconds()
);
#[cfg(feature = "bundle")]
let (shutdown_send, mut shutdown_recv) = mpsc::unbounded_channel();

View File

@ -3,8 +3,8 @@ mod file_config;
mod filters;
use self::filters::{Filter, Replacement};
use chrono::Duration;
pub use file_config::FileConfig;
use std::time::Duration;
pub struct Config {
pub port: u16,

View File

@ -1,7 +1,8 @@
use anyhow::{anyhow, Context};
use chrono::TimeDelta;
use serde::Deserialize;
use serde_default::DefaultFromSerde;
use std::{fs, io::ErrorKind, path::PathBuf, time::Duration};
use std::{fs, io::ErrorKind, path::PathBuf};
use crate::config::defaults;
@ -71,16 +72,16 @@ pub struct ClientConfig {
}
impl ClientConfig {
pub fn get_idle_timeout(&self) -> Duration {
Duration::from_secs(u64::from(self.idle_timeout_seconds))
pub fn get_idle_timeout(&self) -> TimeDelta {
TimeDelta::seconds(self.idle_timeout_seconds.into())
}
pub fn get_poll_time_idle(&self) -> Duration {
Duration::from_secs(u64::from(self.poll_time_idle_seconds))
pub fn get_poll_time_idle(&self) -> TimeDelta {
TimeDelta::seconds(self.poll_time_idle_seconds.into())
}
pub fn get_poll_time_window(&self) -> Duration {
Duration::from_secs(u64::from(self.poll_time_window_seconds))
pub fn get_poll_time_window(&self) -> TimeDelta {
TimeDelta::seconds(self.poll_time_window_seconds.into())
}
}

View File

@ -1,7 +1,7 @@
use super::config::Config;
use anyhow::Context;
use aw_client_rust::{AwClient, Event as AwEvent};
use chrono::{DateTime, Duration, Utc};
use chrono::{DateTime, TimeDelta, Utc};
use serde_json::{Map, Value};
use std::error::Error;
use std::future::Future;
@ -61,7 +61,7 @@ impl ReportClient {
&self,
is_idle: bool,
timestamp: DateTime<Utc>,
duration: Duration,
duration: TimeDelta,
) -> anyhow::Result<()> {
let mut data = Map::new();
data.insert(
@ -80,11 +80,10 @@ impl ReportClient {
return Ok(());
}
let pulsetime = (self.config.idle_timeout + self.config.poll_time_idle).as_secs_f64();
let pulsetime = (self.config.idle_timeout + self.config.poll_time_idle).num_seconds();
let request = || {
self.client
.heartbeat(&self.idle_bucket_name, &event, pulsetime)
.heartbeat(&self.idle_bucket_name, &event, pulsetime as f64)
};
Self::run_with_retries(request)
@ -118,7 +117,7 @@ impl ReportClient {
let event = AwEvent {
id: None,
timestamp: Utc::now(),
duration: Duration::zero(),
duration: TimeDelta::zero(),
data,
};
@ -126,10 +125,13 @@ impl ReportClient {
return Ok(());
}
let interval_margin = self.config.poll_time_window.as_secs_f64() + 1.0;
let interval_margin = self.config.poll_time_window.num_seconds() + 1;
let request = || {
self.client
.heartbeat(&self.active_window_bucket_name, &event, interval_margin)
self.client.heartbeat(
&self.active_window_bucket_name,
&event,
interval_margin as f64,
)
};
Self::run_with_retries(request)

View File

@ -28,8 +28,8 @@ pub enum WatcherType {
impl WatcherType {
fn sleep_time(&self, config: &Config) -> Duration {
match self {
WatcherType::Idle => config.poll_time_idle,
WatcherType::ActiveWindow => config.poll_time_window,
WatcherType::Idle => config.poll_time_idle.to_std().unwrap(),
WatcherType::ActiveWindow => config.poll_time_window.to_std().unwrap(),
}
}
}

View File

@ -2,7 +2,6 @@ use super::{gnome_wayland::load_watcher, idle, Watcher};
use crate::report_client::ReportClient;
use anyhow::Context;
use async_trait::async_trait;
use chrono::Duration;
use std::sync::Arc;
use zbus::Connection;
@ -32,7 +31,7 @@ impl IdleWatcher {
#[async_trait]
impl Watcher for IdleWatcher {
async fn new(client: &Arc<ReportClient>) -> anyhow::Result<Self> {
let duration = Duration::from_std(client.config.idle_timeout).unwrap();
let duration = client.config.idle_timeout;
load_watcher(|| async move {
let mut watcher = Self {
dbus_connection: Connection::session().await?,

View File

@ -1,5 +1,5 @@
use crate::report_client::ReportClient;
use chrono::{DateTime, Duration, Utc};
use chrono::{DateTime, TimeDelta, Utc};
use std::{cmp::max, sync::Arc};
pub struct State {
@ -7,14 +7,14 @@ pub struct State {
changed_time: DateTime<Utc>,
is_idle: bool,
is_changed: bool,
idle_timeout: Duration,
idle_timeout: TimeDelta,
idle_start: Option<DateTime<Utc>>,
idle_end: Option<DateTime<Utc>>,
}
impl State {
pub fn new(idle_timeout: Duration) -> Self {
pub fn new(idle_timeout: TimeDelta) -> Self {
Self {
last_input_time: Utc::now(),
changed_time: Utc::now(),
@ -53,7 +53,7 @@ impl State {
client: &Arc<ReportClient>,
) -> anyhow::Result<()> {
let now = Utc::now();
let time_since_input = Duration::seconds(i64::from(seconds_since_input));
let time_since_input = TimeDelta::seconds(i64::from(seconds_since_input));
self.last_input_time = now - time_since_input;
@ -106,11 +106,11 @@ impl State {
self.last_input_time.format("%Y-%m-%d %H:%M:%S"),
);
client
.ping(false, self.last_input_time, Duration::zero())
.ping(false, self.last_input_time, TimeDelta::zero())
.await?;
// ping with timestamp+1ms with the next event (to ensure the latest event gets retrieved by get_event)
self.last_input_time += Duration::milliseconds(1);
self.last_input_time += TimeDelta::milliseconds(1);
client
.ping(true, self.last_input_time, now - self.last_input_time)
.await
@ -121,14 +121,14 @@ impl State {
);
client
.ping(true, self.last_input_time, Duration::zero())
.ping(true, self.last_input_time, TimeDelta::zero())
.await?;
client
.ping(
false,
self.last_input_time + Duration::milliseconds(1),
Duration::zero(),
self.last_input_time + TimeDelta::milliseconds(1),
TimeDelta::zero(),
)
.await
};
@ -149,7 +149,7 @@ impl State {
self.last_input_time.format("%Y-%m-%d %H:%M:%S")
);
client
.ping(false, self.last_input_time, Duration::zero())
.ping(false, self.last_input_time, TimeDelta::zero())
.await
}
}

View File

@ -4,7 +4,7 @@ use super::Watcher;
use crate::report_client::ReportClient;
use anyhow::anyhow;
use async_trait::async_trait;
use chrono::Duration;
use chrono::TimeDelta;
use std::sync::Arc;
use wayland_client::{
globals::GlobalListContents,
@ -28,7 +28,7 @@ impl Drop for WatcherState {
}
impl WatcherState {
fn new(idle_notification: ExtIdleNotificationV1, idle_timeout: Duration) -> Self {
fn new(idle_notification: ExtIdleNotificationV1, idle_timeout: TimeDelta) -> Self {
Self {
idle_notification,
idle_state: idle::State::new(idle_timeout),
@ -79,12 +79,12 @@ impl Watcher for IdleWatcher {
let mut connection: WlEventConnection<WatcherState> = WlEventConnection::connect()?;
connection.get_ext_idle()?;
let timeout = u32::try_from(client.config.idle_timeout.as_secs() * 1000);
let timeout = u32::try_from(client.config.idle_timeout.num_milliseconds());
let mut watcher_state = WatcherState::new(
connection
.get_ext_idle_notification(timeout.unwrap())
.unwrap(),
Duration::from_std(client.config.idle_timeout).unwrap(),
client.config.idle_timeout,
);
connection
.event_queue

View File

@ -4,7 +4,7 @@ use super::Watcher;
use crate::report_client::ReportClient;
use anyhow::anyhow;
use async_trait::async_trait;
use chrono::Duration;
use chrono::TimeDelta;
use std::sync::Arc;
use wayland_client::{
globals::GlobalListContents,
@ -29,7 +29,7 @@ impl Drop for WatcherState {
}
impl WatcherState {
fn new(kwin_idle_timeout: OrgKdeKwinIdleTimeout, idle_timeout: Duration) -> Self {
fn new(kwin_idle_timeout: OrgKdeKwinIdleTimeout, idle_timeout: TimeDelta) -> Self {
Self {
kwin_idle_timeout,
idle_state: idle::State::new(idle_timeout),
@ -80,10 +80,10 @@ impl Watcher for IdleWatcher {
let mut connection: WlEventConnection<WatcherState> = WlEventConnection::connect()?;
connection.get_kwin_idle()?;
let timeout = u32::try_from(client.config.idle_timeout.as_secs() * 1000);
let timeout = u32::try_from(client.config.idle_timeout.num_milliseconds());
let mut watcher_state = WatcherState::new(
connection.get_kwin_idle_timeout(timeout.unwrap()).unwrap(),
Duration::from_std(client.config.idle_timeout).unwrap(),
client.config.idle_timeout,
);
connection
.event_queue

View File

@ -1,5 +1,4 @@
use async_trait::async_trait;
use chrono::Duration;
use super::{idle, x11_connection::X11Client, Watcher};
use crate::report_client::ReportClient;
@ -26,9 +25,7 @@ impl Watcher for IdleWatcher {
Ok(IdleWatcher {
client,
idle_state: idle::State::new(
Duration::from_std(report_client.config.idle_timeout).unwrap(),
),
idle_state: idle::State::new(report_client.config.idle_timeout),
})
}