1use jiff::Timestamp;
8
9use crate::backend::Backend;
10use crate::database::{Database, DbError};
11use crate::query::{db_time, on_pool, sql_text};
12
13#[cfg(test)]
14mod tests;
15
16#[derive(Debug, Clone, PartialEq, Eq)]
18pub struct EndedCount {
19 pub at: Timestamp,
21 pub status: String,
23 pub count: u64,
25}
26
27#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub struct StartLatency {
30 pub at: Timestamp,
32 pub started: u64,
34 pub p50_ms: u64,
36 pub p95_ms: u64,
38}
39
40fn epoch(backend: Backend, column: &str) -> String {
45 match backend {
46 Backend::Sqlite => format!("CAST(strftime('%s', substr({column}, 1, 19)) AS INTEGER)"),
47 Backend::Postgres => format!("CAST(FLOOR(EXTRACT(EPOCH FROM {column})) AS BIGINT)"),
48 }
49}
50
51fn latency_ms(backend: Backend) -> &'static str {
54 match backend {
55 Backend::Sqlite => {
56 "MAX(0, CAST(ROUND((julianday(started_at) - julianday(assigned_at)) * 86400000) \
57 AS INTEGER))"
58 }
59 Backend::Postgres => {
60 "GREATEST(0, CAST(ROUND(EXTRACT(EPOCH FROM (started_at - assigned_at)) * 1000) \
61 AS BIGINT))"
62 }
63 }
64}
65
66fn from_epoch(seconds: i64) -> Result<Timestamp, DbError> {
68 Timestamp::from_second(seconds).map_err(|e| DbError::InvalidData {
69 what: "attempts' bucket",
70 reason: e.to_string(),
71 })
72}
73
74fn ended_query(backend: Backend) -> String {
76 format!(
77 "SELECT ({e} / $3) * $3 AS bucket, status, COUNT(*) FROM attempts \
78 WHERE ended_at >= $1{{ts}} AND ended_at < $2{{ts}} \
79 GROUP BY bucket, status ORDER BY bucket, status",
80 e = epoch(backend, "ended_at"),
81 )
82}
83
84fn latency_query(backend: Backend) -> String {
87 format!(
88 "SELECT bucket, n, \
89 MAX(CASE WHEN k = (n * 50 + 99) / 100 THEN ms END), \
90 MAX(CASE WHEN k = (n * 95 + 99) / 100 THEN ms END) FROM \
91 (SELECT bucket, ms, ROW_NUMBER() OVER (PARTITION BY bucket ORDER BY ms) AS k, \
92 COUNT(*) OVER (PARTITION BY bucket) AS n FROM \
93 (SELECT ({e} / $3) * $3 AS bucket, {ms} AS ms FROM attempts \
94 WHERE started_at >= $1{{ts}} AND started_at < $2{{ts}}) started) ranked \
95 WHERE k = (n * 50 + 99) / 100 OR k = (n * 95 + 99) / 100 \
96 GROUP BY bucket, n ORDER BY bucket",
97 e = epoch(backend, "started_at"),
98 ms = latency_ms(backend),
99 )
100}
101
102impl Database {
103 pub async fn attempts_ended(
110 &self,
111 (from, to): (Timestamp, Timestamp),
112 bucket_s: u32,
113 ) -> Result<Vec<EndedCount>, DbError> {
114 let rows: Vec<(i64, String, i64)> = on_pool!(self, |pool, backend| {
115 sqlx::query_as(sql_text(backend, &ended_query(backend)))
116 .bind(db_time(from))
117 .bind(db_time(to))
118 .bind(i64::from(bucket_s.max(1)))
119 .fetch_all(pool)
120 .await?
121 });
122 rows.into_iter()
123 .map(|(bucket, status, count)| {
124 Ok(EndedCount {
125 at: from_epoch(bucket)?,
126 status,
127 count: u64::try_from(count).unwrap_or(0),
128 })
129 })
130 .collect()
131 }
132
133 pub async fn start_latency(
140 &self,
141 (from, to): (Timestamp, Timestamp),
142 bucket_s: u32,
143 ) -> Result<Vec<StartLatency>, DbError> {
144 let rows: Vec<(i64, i64, Option<i64>, Option<i64>)> = on_pool!(self, |pool, backend| {
145 sqlx::query_as(sql_text(backend, &latency_query(backend)))
146 .bind(db_time(from))
147 .bind(db_time(to))
148 .bind(i64::from(bucket_s.max(1)))
149 .fetch_all(pool)
150 .await?
151 });
152 let ms = |value: Option<i64>| value.and_then(|v| u64::try_from(v).ok()).unwrap_or(0);
153 rows.into_iter()
154 .map(|(bucket, started, p50, p95)| {
155 Ok(StartLatency {
156 at: from_epoch(bucket)?,
157 started: u64::try_from(started).unwrap_or(0),
158 p50_ms: ms(p50),
159 p95_ms: ms(p95),
160 })
161 })
162 .collect()
163 }
164}