use std::{collections::BTreeMap, time::Duration};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct ServerTiming {
pub total: Duration,
pub phases: BTreeMap<String, Duration>,
pub cold: bool,
}
impl ServerTiming {
pub fn parse(header: &str) -> Option<Self> {
let mut timing = Self::default();
let mut seen = std::collections::BTreeSet::new();
let mut has_total = false;
for metric in split_quoted(header, b',') {
let params = split_quoted(metric, b';');
let name = trim_blanks(params[0]);
if name.is_empty() || !seen.insert(name) {
continue;
}
if name == "cold" {
timing.cold = true;
continue;
}
match (name, metric_duration(¶ms[1..])) {
(_, None) => {}
("total", Some(duration)) => {
timing.total = duration;
has_total = true;
}
(name, Some(duration)) => {
timing.phases.insert(name.to_owned(), duration);
}
}
}
has_total.then_some(timing)
}
#[cfg_attr(not(feature = "async"), allow(dead_code))]
pub(crate) fn largest_phases(&self, limit: usize) -> Vec<(&str, Duration)> {
let mut phases: Vec<_> = self
.phases
.iter()
.map(|(name, duration)| (name.as_str(), *duration))
.collect();
phases.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
phases.truncate(limit);
phases
}
}
#[cfg_attr(not(feature = "async"), allow(dead_code))]
pub(crate) fn client_overhead(
duration: Duration,
timing: Option<&ServerTiming>,
) -> Option<Duration> {
timing.map(|timing| duration.saturating_sub(timing.total))
}
fn split_quoted(text: &str, separator: u8) -> Vec<&str> {
let mut parts = Vec::new();
let (mut start, mut quoted, mut escaped) = (0, false, false);
for (index, &byte) in text.as_bytes().iter().enumerate() {
if escaped {
escaped = false;
} else if quoted && byte == b'\\' {
escaped = true;
} else if byte == b'"' {
quoted = !quoted;
} else if !quoted && byte == separator {
parts.push(&text[start..index]);
start = index + 1;
}
}
parts.push(&text[start..]);
parts
}
fn trim_blanks(text: &str) -> &str {
text.trim_matches([' ', '\t'])
}
fn metric_duration(params: &[&str]) -> Option<Duration> {
let param = params.iter().find(|param| {
let key = param.split_once('=').map_or(**param, |(key, _)| key);
trim_blanks(key).eq_ignore_ascii_case("dur")
})?;
let value = trim_blanks(param.split_once('=').map_or("", |(_, value)| value));
if !is_decimal(value) {
return None;
}
Duration::try_from_secs_f64(value.parse::<f64>().ok()? / 1000.0).ok()
}
fn is_decimal(value: &str) -> bool {
let (whole, fraction) = match value.split_once('.') {
Some((whole, fraction)) => (whole, Some(fraction)),
None => (value, None),
};
!whole.is_empty()
&& fraction.is_none_or(|fraction| !fraction.is_empty())
&& whole
.bytes()
.chain(fraction.unwrap_or("").bytes())
.all(|byte| byte.is_ascii_digit())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn client_overhead_follows_the_shared_fixture() {
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/testdata/server-timing.json");
let fixture: serde_json::Value =
serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
let millis = |value: &serde_json::Value| {
value
.as_f64()
.map(|ms| Duration::from_secs_f64(ms / 1000.0))
};
for case in fixture["overhead"].as_array().unwrap() {
let timing = ServerTiming::parse(case["header"].as_str().unwrap_or(""));
let duration = millis(&case["durationMs"]).unwrap();
assert_eq!(
client_overhead(duration, timing.as_ref()),
millis(&case["clientOverheadMs"]),
"{case}"
);
}
}
}