Skip to main content

hyprstream_metrics_api/
aggregation.rs

1//! Core aggregation framework for time-series data.
2//!
3//! This module provides the foundational types and functionality for aggregating
4//! time-series data. It defines:
5//! - Generic aggregation functions (Sum, Avg, Min, Max, Count)
6//! - Time window specifications (None, Fixed, Sliding)
7//! - Grouping operations
8//! - SQL query generation
9//!
10//! This framework is used by more specific aggregation implementations, such as
11//! the metric-specific aggregation in `crate::metrics::aggregation`.
12
13use serde::{Deserialize, Serialize};
14use std::collections::HashMap;
15use std::fmt::{Display, Formatter};
16use std::time::Duration;
17
18/// Time window for aggregation
19#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
20pub enum TimeWindow {
21    /// No time window, aggregate all data
22    None,
23    /// Fixed time window (e.g., 5 minutes, 1 hour)
24    Fixed(Duration),
25    /// Sliding time window with window size and slide interval
26    Sliding { window: Duration, slide: Duration },
27}
28
29/// Generic aggregation functions that can be applied to time-series data
30#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
31pub enum AggregateFunction {
32    /// Count the number of values
33    Count,
34    /// Sum all values
35    Sum,
36    /// Calculate the average
37    Avg,
38    /// Find the minimum value
39    Min,
40    /// Find the maximum value
41    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/// Grouping specification for aggregation
57#[derive(Debug, Clone, Serialize, Deserialize)]
58pub struct GroupBy {
59    pub columns: Vec<String>,
60    pub time_column: Option<String>,
61}
62
63/// Result of an aggregation operation
64#[derive(Debug, Clone, Serialize, Deserialize)]
65pub struct AggregateResult {
66    /// The aggregated value
67    pub value: f64,
68    /// Group values for each grouping column
69    pub group_values: HashMap<String, String>,
70    /// Optional timestamp for time-based grouping
71    pub timestamp: Option<i64>,
72}
73
74impl TimeWindow {
75    /// Calculates the window boundaries for a given timestamp
76    pub fn window_bounds(&self, timestamp: i64) -> (i64, i64) {
77        match *self {
78            TimeWindow::None => (i64::MIN, i64::MAX),
79            TimeWindow::Fixed(duration) => {
80                // Duration in seconds is always positive, cap at i64::MAX (~292 billion years)
81                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    /// Generates SQL expressions for window boundaries
95    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    /// Generates SQL for the aggregation function
119    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
130/// Builds a SQL query for aggregation.
131///
132/// This is the core query builder used by specific aggregation implementations.
133/// It provides a flexible way to build SQL queries for different types of
134/// time-series data aggregation.
135///
136/// # Arguments
137///
138/// * `table_name` - The source table name
139/// * `function` - The aggregation function to apply
140/// * `group_by` - The grouping specification
141/// * `columns` - The columns to aggregate
142/// * `from_timestamp` - Optional start of the time range
143/// * `to_timestamp` - Optional end of the time range
144///
145/// # Returns
146///
147/// A SQL query string for the specified aggregation
148pub 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    // Build SELECT clause
159    query.push_str("SELECT ");
160
161    // Add group by columns
162    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    // Build the SELECT clause parts
173    let mut select_parts = Vec::new();
174
175    // Add time column if present
176    if let Some(time_col) = &group_by.time_column {
177        select_parts.push(time_col.clone());
178    }
179
180    // Add aggregation function for each column
181    for col in _columns {
182        select_parts.push(function.to_sql(col));
183    }
184
185    // Join all parts with commas
186    query.push_str(&select_parts.join(", "));
187
188    // Add FROM clause
189    query.push_str(&format!(" FROM {table_name}"));
190
191    // Add WHERE clause for timestamp range
192    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    // Add GROUP BY clause
200    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}