use std::{io::Write, time::Instant}; use rusqlite::{Connection, params}; use time::{Duration, OffsetDateTime}; // Thank you, cat, for optimizing my query const TOP_TEN_ALL_TIME: &str = "\ SELECT reqs.cnt, agents.agent FROM agents JOIN ( SELECT count(id) as cnt, agent_id FROM requests GROUP BY agent_id ) reqs ON reqs.agent_id=agents.id ORDER BY reqs.cnt DESC LIMIT 10; "; const STYLE: &'static str = include_str!("style.css"); const FAVICON: &'static [u8] = include_bytes!("favicon.gif"); fn main() { let Some(path) = std::env::var("PATH_INFO").ok() else { error_and_die(500, "no path provided"); }; match path.as_ref() { "/stats/favicon.gif" => { println!("Content-Type: image/png\n"); std::io::stdout().write_all(FAVICON).unwrap(); std::process::exit(1); } "/stats" | "/stats/" => (), _ => error_and_die(404, "not found"), } let db_path = std::env::var("CORGI_STATS_DB").ok(); let db = if let Some(path) = db_path { if let Ok(db) = Connection::open(path) { db } else { error_and_die(500, "failed to open database"); } } else { error_and_die(500, "database key not set"); }; let now = OffsetDateTime::now_utc(); let fifteen_ago = now - Duration::minutes(15); let query = "SELECT count(requests.id) AS request_count, agents.agent FROM requests \ INNER JOIN agents ON requests.agent_id = agents.id \ WHERE requests.timestamp > ?1 \ GROUP BY requests.agent_id;"; let start = Instant::now(); let mut prepared = db.prepare(query).unwrap(); let mut agents: Vec<(usize, String)> = prepared .query_map(params![fifteen_ago], |row| Ok((row.get(0)?, row.get(1)?))) .unwrap() .map(|r| r.unwrap()) .collect(); agents.sort_by(|a, b| a.0.cmp(&b.0).reverse()); let mut prepared = db.prepare(TOP_TEN_ALL_TIME).unwrap(); let highest_five: Vec<(usize, String)> = prepared .query_map(params![], |row| Ok((row.get(0)?, row.get(1)?))) .unwrap() .map(|r| r.unwrap()) .collect(); let sum_highest_five = highest_five.iter().fold(0, |acc, (count, _)| acc + count); let elapsed = start.elapsed(); println!("Content-Type: text/html\n"); println!(""); #[rustfmt::skip] println!("
\n\generated in {}ms
", elapsed.as_millis()); #[rustfmt::skip] println!("Requests for the last 15 minutes | \n\ \t||
---|---|---|
# Req. | \n\ \t\tReq/min | \n\ \t\tAgent | \n\ \t
{count} | \n\ \t{:.1} | \n\ \t{agent} | \n\
Top 10 User Agents All Time | \n\ \t||
---|---|---|
# Req. | \n\ \t\t% of 10 | \n\ \t\tAgent | \n\ \t
{count} | \n\ \t{:.1} | \n\ \t{agent} | \n\