|
| 1 | +use std::fmt::Write as _; |
| 2 | +use std::sync::Arc; |
| 3 | +use std::time::Duration; |
| 4 | + |
| 5 | +use axum::http::Request; |
| 6 | +use axum::middleware::Next; |
| 7 | +use axum::response::Response; |
| 8 | +use hashbrown::HashMap; |
| 9 | +use parking_lot::Mutex; |
| 10 | + |
| 11 | +#[derive(Default, Clone, Debug)] |
| 12 | +pub struct Timings { |
| 13 | + records: Arc<Mutex<HashMap<&'static str, Duration>>>, |
| 14 | +} |
| 15 | + |
| 16 | +impl Timings { |
| 17 | + pub fn record(&self, k: &'static str, d: Duration) { |
| 18 | + self.records.lock().insert(k, d); |
| 19 | + } |
| 20 | + |
| 21 | + fn format(&self) -> String { |
| 22 | + let mut out = String::new(); |
| 23 | + let records = self.records.lock(); |
| 24 | + for (k, v) in records.iter() { |
| 25 | + write!(&mut out, "{k};dur={v:?},").unwrap(); |
| 26 | + } |
| 27 | + out |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +tokio::task_local! { |
| 32 | + pub static TIMINGS: Timings; |
| 33 | +} |
| 34 | + |
| 35 | +#[macro_export] |
| 36 | +macro_rules! record_time { |
| 37 | + ($k:literal; $($rest:tt)*) => { |
| 38 | + { |
| 39 | + let __before__ = std::time::Instant::now(); |
| 40 | + let __ret__ = { |
| 41 | + $($rest)* |
| 42 | + }; |
| 43 | + let _ = $crate::http::user::timing::TIMINGS.try_with(|t| t.record($k, __before__.elapsed())); |
| 44 | + __ret__ |
| 45 | + } |
| 46 | + }; |
| 47 | +} |
| 48 | + |
| 49 | +pub(crate) async fn timings_middleware<B>(request: Request<B>, next: Next<B>) -> Response { |
| 50 | + TIMINGS |
| 51 | + .scope(Default::default(), async move { |
| 52 | + let mut response = record_time! { |
| 53 | + "query_total"; |
| 54 | + next.run(request).await |
| 55 | + }; |
| 56 | + let timings = TIMINGS.get().format(); |
| 57 | + response |
| 58 | + .headers_mut() |
| 59 | + .insert("Server-Timing", timings.parse().unwrap()); |
| 60 | + response |
| 61 | + }) |
| 62 | + .await |
| 63 | +} |
0 commit comments