mirror of
https://github.com/csehviktor/status-monitor.git
synced 2026-04-29 00:27:35 +02:00
implement storage + improve code
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use chrono::{DateTime, Utc};
|
||||
use sqlite::SQLiteRepository;
|
||||
use std::sync::Arc;
|
||||
use memory::InMemoryRepository;
|
||||
use async_trait::async_trait;
|
||||
use common::MQTT_SEND_INTERVAL;
|
||||
|
||||
pub mod memory;
|
||||
pub mod sqlite;
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct UptimeModel {
|
||||
pub id: String,
|
||||
pub first_seen: DateTime<Utc>,
|
||||
pub last_seen: DateTime<Utc>,
|
||||
pub message_count: u64,
|
||||
}
|
||||
|
||||
impl Into<UptimeMessage> for UptimeModel {
|
||||
fn into(self) -> UptimeMessage {
|
||||
let duration = Utc::now().signed_duration_since(self.first_seen);
|
||||
let expected_messages = duration.num_seconds() as f64 / MQTT_SEND_INTERVAL as f64;
|
||||
|
||||
let uptime_pct = (self.message_count as f64 / expected_messages * 100.0).min(100.0);
|
||||
|
||||
UptimeMessage {
|
||||
agent: self.id,
|
||||
uptime: uptime_pct,
|
||||
last_seen: self.last_seen,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize, Deserialize)]
|
||||
pub struct UptimeMessage {
|
||||
pub agent: String,
|
||||
pub uptime: f64,
|
||||
pub last_seen: DateTime<Utc>,
|
||||
}
|
||||
|
||||
#[async_trait]
|
||||
pub trait StorageRepository: Send + Sync {
|
||||
async fn record_message(&self, agent: &str) -> anyhow::Result<()>;
|
||||
async fn get_agents(&self) -> anyhow::Result<Vec<UptimeMessage>>;
|
||||
}
|
||||
|
||||
pub enum StorageStrategy {
|
||||
InMemory,
|
||||
SQLite(String),
|
||||
}
|
||||
|
||||
pub struct StorageRepositoryImpl {
|
||||
inner: Arc<dyn StorageRepository>
|
||||
}
|
||||
|
||||
impl StorageRepositoryImpl {
|
||||
pub fn new(strategy: StorageStrategy) -> Self {
|
||||
let inner: Arc<dyn StorageRepository> = match strategy {
|
||||
StorageStrategy::InMemory => Arc::new(InMemoryRepository::new()),
|
||||
StorageStrategy::SQLite(path) => Arc::new(SQLiteRepository::new(path)),
|
||||
};
|
||||
|
||||
Self { inner }
|
||||
}
|
||||
|
||||
pub fn inner(&self) -> Arc<dyn StorageRepository> {
|
||||
self.inner.clone()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user