hyprstream_metrics_api/
aggregation.rs1use serde::{Deserialize, Serialize};
14use std::collections::HashMap;
15use std::fmt::{Display, Formatter};
16use std::time::Duration;
17
18#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
20pub enum TimeWindow {
21 None,
23 Fixed(Duration),
25 Sliding { window: Duration, slide: Duration },
27}
28
29#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
31pub enum AggregateFunction {
32 Count,
34 Sum,
36 Avg,
38 Min,
40 Max,
42}
43
44impl Display for AggregateFunction {
45 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
46 match self {
47 AggregateFunction::Count => write!(f, "COUNT"),
48 AggregateFunction::Sum => write!(f, "SUM"),
49 AggregateFunction::Avg => write!(f, "AVG"),
50 AggregateFunction::Min => write!(f, "MIN"),
51 AggregateFunction::Max => write!(f, "MAX"),
52 }
53 }
54}
55
56#[derive(Debug, Clone, Serialize, Deserialize)]
58pub struct GroupBy {
59 pub columns: Vec<String>,
60 pub time_column: Option<String>,
61}
62
63#[derive(Debug, Clone, Serialize, Deserialize)]
65pub struct AggregateResult {
66 pub value: f64,
68 pub group_values: HashMap<String, String>,
70 pub timestamp: Option<i64>,
72}
73
74impl TimeWindow {
75 pub fn window_bounds(&self, timestamp: i64) -> (i64, i64) {
77 match *self {
78 TimeWindow::None => (i64::MIN, i64::MAX),
79 TimeWindow::Fixed(duration) => {
80 let window_size = i64::try_from(duration.as_secs()).unwrap_or(i64::MAX);
82 let window_start = (timestamp / window_size) * window_size;
83 (window_start, window_start + window_size)
84 }
85 TimeWindow::Sliding { window, slide } => {
86 let window_size = i64::try_from(window.as_secs()).unwrap_or(i64::MAX);
87 let slide_size = i64::try_from(slide.as_secs()).unwrap_or(i64::MAX);
88 let current_slide = (timestamp / slide_size) * slide_size;
89 (current_slide, current_slide + window_size)
90 }
91 }
92 }
93
94 pub fn to_sql(&self) -> Option<String> {
96 match *self {
97 TimeWindow::None => None,
98 TimeWindow::Fixed(duration) => {
99 let window_size = duration.as_secs();
100 Some(format!(
101 "(timestamp / {window_size}) * {window_size} as window_start,
102 ((timestamp / {window_size}) + 1) * {window_size} as window_end"
103 ))
104 }
105 TimeWindow::Sliding { window, slide } => {
106 let window_size = window.as_secs();
107 let slide_size = slide.as_secs();
108 Some(format!(
109 "(timestamp / {slide_size}) * {slide_size} as window_start,
110 ((timestamp / {slide_size}) * {slide_size} + {window_size}) as window_end"
111 ))
112 }
113 }
114 }
115}
116
117impl AggregateFunction {
118 pub fn to_sql(&self, column: &str) -> String {
120 match self {
121 AggregateFunction::Sum => format!("SUM({column})"),
122 AggregateFunction::Avg => format!("AVG({column})"),
123 AggregateFunction::Min => format!("MIN({column})"),
124 AggregateFunction::Max => format!("MAX({column})"),
125 AggregateFunction::Count => format!("COUNT({column})"),
126 }
127 }
128}
129
130pub fn build_aggregate_query(
149 table_name: &str,
150 function: AggregateFunction,
151 group_by: &GroupBy,
152 _columns: &[&str],
153 from_timestamp: Option<i64>,
154 to_timestamp: Option<i64>,
155) -> String {
156 let mut query = String::new();
157
158 query.push_str("SELECT ");
160
161 if !group_by.columns.is_empty() {
163 let cols: Vec<&str> = group_by
164 .columns
165 .iter()
166 .map(std::string::String::as_str)
167 .collect();
168 query.push_str(&cols.join(", "));
169 query.push_str(", ");
170 }
171
172 let mut select_parts = Vec::new();
174
175 if let Some(time_col) = &group_by.time_column {
177 select_parts.push(time_col.clone());
178 }
179
180 for col in _columns {
182 select_parts.push(function.to_sql(col));
183 }
184
185 query.push_str(&select_parts.join(", "));
187
188 query.push_str(&format!(" FROM {table_name}"));
190
191 if let Some(from_ts) = from_timestamp {
193 query.push_str(&format!(" WHERE timestamp >= {from_ts}"));
194 if let Some(to_ts) = to_timestamp {
195 query.push_str(&format!(" AND timestamp <= {to_ts}"));
196 }
197 }
198
199 if !group_by.columns.is_empty() || group_by.time_column.is_some() {
201 query.push_str(" GROUP BY ");
202 let mut group_cols = Vec::new();
203
204 if !group_by.columns.is_empty() {
205 let cols: Vec<&str> = group_by
206 .columns
207 .iter()
208 .map(std::string::String::as_str)
209 .collect();
210 group_cols.extend(cols);
211 }
212
213 if let Some(time_col) = &group_by.time_column {
214 group_cols.push(time_col.as_str());
215 }
216
217 query.push_str(&group_cols.join(", "));
218 }
219
220 query
221}