implement uptime stats

This commit is contained in:
postscriptum 2026-03-22 23:25:34 +02:00
parent 6be42e596a
commit 29895bf35a
3 changed files with 34 additions and 5 deletions

View file

@ -12,13 +12,13 @@ use log::*;
use opt::{AuthMode, Opt};
use rocket::{State, http::Status, serde::json::Json};
use stats::{Snap, Total};
use std::{future::Future, sync::Arc};
use std::{future::Future, sync::Arc, time::Instant};
use structopt::StructOpt;
use tokio::{net::TcpListener, task};
#[rocket::get("/")]
async fn index(totals: &State<Arc<Total>>) -> Json<Snap> {
Json(totals.inner().snap())
async fn index(totals: &State<Arc<Total>>, startup_time: &State<Instant>) -> Json<Snap> {
Json(totals.inner().snap(startup_time.elapsed().as_secs()))
}
#[rocket::get("/allow/<rule>")]
@ -83,6 +83,7 @@ async fn rocket() -> _ {
})
.manage(list)
.manage(totals)
.manage(Instant::now())
.mount("/", rocket::routes![index, allow, block])
}

View file

@ -18,11 +18,12 @@ impl Total {
..Self::default()
}
}
pub fn snap(&self) -> Snap {
pub fn snap(&self, seconds_from_startup: u64) -> Snap {
Snap::shot(
self.entries.load(Ordering::Relaxed),
self.request.load(Ordering::Relaxed),
self.blocked.load(Ordering::Relaxed),
seconds_from_startup,
)
}
pub fn set_entries(&self, value: u64) {

View file

@ -1,5 +1,30 @@
use rocket::serde::Serialize;
#[derive(Serialize)]
pub struct Up {
seconds: u64,
minutes: u64,
hours: u64,
days: u64,
weeks: u64,
}
impl Up {
pub fn from_startup_seconds(seconds: u64) -> Self {
let minutes = seconds / 60;
let hours = minutes / 60;
let days = hours / 24;
let weeks = days / 7;
Self {
seconds,
minutes,
hours,
days,
weeks,
}
}
}
#[derive(Serialize)]
pub struct Sum {
total: u64,
@ -11,10 +36,11 @@ pub struct Snap {
rules: u64,
request: Sum,
blocked: Sum,
up_time: Up,
}
impl Snap {
pub fn shot(rules: u64, request: u64, blocked: u64) -> Self {
pub fn shot(rules: u64, request: u64, blocked: u64, seconds_from_startup: u64) -> Self {
let blocked_percent = if request > 0 {
blocked as f32 * 100.0 / request as f32
} else {
@ -30,6 +56,7 @@ impl Snap {
total: blocked,
percent: blocked_percent,
},
up_time: Up::from_startup_seconds(seconds_from_startup),
}
}
}