Skip to main content

spectra_core/
query.rs

1//! UI/server boundary query types for Spectra explore views.
2
3use chrono::{DateTime, Utc};
4use serde::{Deserialize, Serialize};
5use serde_json::Value;
6
7/// Metric explore request (host server fn boundary).
8#[derive(Debug, Clone, Serialize, Deserialize)]
9pub struct MetricsQuery {
10    /// Metric family name to query.
11    pub metric: String,
12    /// Inclusive range start timestamp.
13    pub start: DateTime<Utc>,
14    /// Inclusive range end timestamp.
15    pub end: DateTime<Utc>,
16    /// Optional step size in seconds for downsampling.
17    pub step_secs: Option<u64>,
18    /// Label equality matchers applied to the series.
19    pub label_matchers: Vec<LabelMatcher>,
20}
21
22/// Label key-value equality matcher for metric queries.
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct LabelMatcher {
25    /// Label key.
26    pub key: String,
27    /// Label value.
28    pub value: String,
29}
30
31/// One labeled time series returned to the explore UI.
32#[derive(Debug, Clone, Serialize, Deserialize)]
33pub struct TimeSeriesDto {
34    /// Series label set as JSON.
35    pub labels: Value,
36    /// Ordered points in the requested time range.
37    pub points: Vec<MetricPointDto>,
38}
39
40/// Single metric sample in a time series.
41#[derive(Debug, Clone, Serialize, Deserialize)]
42pub struct MetricPointDto {
43    /// Sample timestamp.
44    pub ts: DateTime<Utc>,
45    /// Sample value.
46    pub value: f64,
47}
48
49/// Headline stat card shown above charts.
50#[derive(Debug, Clone, Serialize, Deserialize)]
51pub struct StatCardDto {
52    /// Card label.
53    pub label: String,
54    /// Formatted display value.
55    pub value: String,
56}
57
58/// Metric explore response payload.
59#[derive(Debug, Clone, Serialize, Deserialize)]
60pub struct MetricsQueryResult {
61    /// Time series to render.
62    pub series: Vec<TimeSeriesDto>,
63    /// Headline summary cards.
64    pub headline: Vec<StatCardDto>,
65}
66
67/// Event explore view selection.
68#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
69#[serde(rename_all = "snake_case")]
70pub enum EventExploreView {
71    /// Paginated event log grid.
72    #[default]
73    EventLog,
74    /// Time-bucketed time series.
75    TimeSeries,
76    /// Line chart view.
77    LineChart,
78    /// Pie chart view.
79    PieChart,
80    /// Bar chart view.
81    BarChart,
82}
83
84/// Mirrors MUI `GridPaginationModel`.
85#[derive(Debug, Clone, Serialize, Deserialize)]
86pub struct GridPaginationModel {
87    /// Zero-based page index.
88    pub page: u32,
89    /// Rows per page.
90    pub page_size: u32,
91}
92
93impl Default for GridPaginationModel {
94    fn default() -> Self {
95        Self {
96            page: 0,
97            page_size: 50,
98        }
99    }
100}
101
102/// Sort direction for grid columns.
103#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
104#[serde(rename_all = "lowercase")]
105pub enum GridSortDirection {
106    /// Ascending order.
107    Asc,
108    /// Descending order.
109    Desc,
110}
111
112/// Single column sort specification.
113#[derive(Debug, Clone, Serialize, Deserialize)]
114pub struct GridSortItem {
115    /// Column field name.
116    pub field: String,
117    /// Sort direction.
118    pub sort: GridSortDirection,
119}
120
121/// Logic operator combining multiple grid filters.
122#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
123#[serde(rename_all = "lowercase")]
124pub enum GridLogicOperator {
125    /// All filter items must match.
126    #[default]
127    And,
128    /// Any filter item may match.
129    Or,
130}
131
132/// Filter operator for a single grid column.
133#[derive(Debug, Clone, Serialize, Deserialize)]
134#[serde(rename_all = "snake_case")]
135pub enum GridFilterOperator {
136    /// Exact equality.
137    Equals,
138    /// Inequality.
139    DoesNotEqual,
140    /// Substring containment.
141    Contains,
142    /// Prefix match.
143    StartsWith,
144    /// Suffix match.
145    EndsWith,
146    /// Field is empty or null.
147    IsEmpty,
148    /// Field is non-empty.
149    IsNotEmpty,
150    /// Numeric or lexical greater than.
151    GreaterThan,
152    /// Numeric or lexical greater than or equal.
153    GreaterThanOrEqual,
154    /// Numeric or lexical less than.
155    LessThan,
156    /// Numeric or lexical less than or equal.
157    LessThanOrEqual,
158}
159
160/// One filter predicate on a grid column.
161#[derive(Debug, Clone, Serialize, Deserialize)]
162pub struct GridFilterItem {
163    /// Column field name.
164    pub field: String,
165    /// Comparison operator.
166    pub operator: GridFilterOperator,
167    /// Operand value (type depends on operator).
168    pub value: Value,
169}
170
171/// Full filter model for event log queries.
172#[derive(Debug, Clone, Serialize, Deserialize, Default)]
173pub struct GridFilterModel {
174    /// Structured filter items.
175    pub items: Vec<GridFilterItem>,
176    /// How to combine `items`.
177    #[serde(default)]
178    pub logic_operator: GridLogicOperator,
179    /// Quick-search tokens applied across columns.
180    #[serde(default)]
181    pub quick_filter_values: Vec<String>,
182}
183
184/// Time partition granularity for event queries.
185#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
186#[serde(rename_all = "lowercase")]
187pub enum PartitionKind {
188    /// Hourly partitions.
189    Hourly,
190    /// Daily partitions.
191    Daily,
192}
193
194/// Row-oriented event log query (DataGrid / event log view).
195#[derive(Debug, Clone, Serialize, Deserialize)]
196pub struct EventQuery {
197    /// Event table name.
198    pub table: String,
199    /// Inclusive range start timestamp.
200    pub start: DateTime<Utc>,
201    /// Inclusive range end timestamp.
202    pub end: DateTime<Utc>,
203    /// Optional partition granularity.
204    pub partition: Option<PartitionKind>,
205    /// Pagination settings.
206    pub pagination: GridPaginationModel,
207    /// Column sort order (first entry wins).
208    pub sort: Vec<GridSortItem>,
209    /// Row filter model.
210    pub filter: GridFilterModel,
211}
212
213/// Column descriptor for event log grids.
214#[derive(Debug, Clone, Serialize, Deserialize)]
215pub struct GridColumnDto {
216    /// Field key matching row JSON.
217    pub field: String,
218    /// Human-readable column header.
219    pub header_name: String,
220}
221
222/// One row in an event log grid response.
223#[derive(Debug, Clone, Serialize, Deserialize)]
224pub struct EventGridRow {
225    /// Stable row identifier.
226    pub id: String,
227    /// Event timestamp.
228    pub ts: DateTime<Utc>,
229    /// Event field payload.
230    pub fields: Value,
231}
232
233/// Event log query response payload.
234#[derive(Debug, Clone, Serialize, Deserialize)]
235pub struct EventQueryResult {
236    /// Grid rows for the current page.
237    pub rows: Vec<EventGridRow>,
238    /// Column definitions.
239    pub columns: Vec<GridColumnDto>,
240    /// Total matching row count (may exceed `rows.len()`).
241    pub row_count: u64,
242}
243
244/// Aggregation measure for chart views.
245#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
246#[serde(rename_all = "snake_case")]
247pub enum EventMeasure {
248    /// Count matching rows.
249    Count,
250    /// Sum a numeric field.
251    Sum,
252}
253
254/// Aggregation parameters for event chart queries.
255#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
256pub struct EventAggregationSpec {
257    /// Measure to compute.
258    pub measure: EventMeasure,
259    /// Field to sum when `measure` is [`EventMeasure::Sum`].
260    pub measure_field: Option<String>,
261    /// Time bucket width in seconds for time-series views.
262    pub time_bucket_secs: Option<u64>,
263    /// Field to group by for slice views.
264    pub group_by_field: Option<String>,
265}
266
267/// Event chart aggregate request.
268#[derive(Debug, Clone, Serialize, Deserialize)]
269pub struct EventAggregateRequest {
270    /// Event table name.
271    pub table: String,
272    /// Inclusive range start timestamp.
273    pub start: DateTime<Utc>,
274    /// Inclusive range end timestamp.
275    pub end: DateTime<Utc>,
276    /// Optional partition granularity.
277    pub partition: Option<PartitionKind>,
278    /// Row filter model.
279    pub filter: GridFilterModel,
280    /// Target chart view.
281    pub view: EventExploreView,
282    /// Aggregation specification.
283    pub aggregation: EventAggregationSpec,
284}
285
286/// One slice in a pie or bar chart response.
287#[derive(Debug, Clone, Serialize, Deserialize)]
288pub struct SliceDto {
289    /// Slice label.
290    pub label: String,
291    /// Slice value.
292    pub value: f64,
293}
294
295/// Event aggregate query response (shape depends on view).
296#[derive(Debug, Clone, Serialize, Deserialize)]
297pub enum EventAggregateResult {
298    /// Time-series or line-chart payload.
299    TimeSeries {
300        /// Series to render.
301        series: Vec<TimeSeriesDto>,
302        /// Headline summary cards.
303        headline: Vec<StatCardDto>,
304    },
305    /// Pie or bar chart payload.
306    Slices {
307        /// Category slices.
308        slices: Vec<SliceDto>,
309        /// Headline summary cards.
310        headline: Vec<StatCardDto>,
311    },
312}
313
314/// Schema catalog DTO for spectra-app UI.
315#[derive(Debug, Clone, Serialize, Deserialize)]
316pub struct SchemaListItem {
317    /// Table or metric name.
318    pub table_or_metric: String,
319    /// Optional schema description.
320    pub description: Option<String>,
321    /// `"event"` or `"metric"`.
322    pub logging_kind: String,
323    /// Whether the schema supports explore queries.
324    pub can_query: bool,
325}
326
327/// Full schema detail for the explore UI.
328#[derive(Debug, Clone, Serialize, Deserialize)]
329pub struct SchemaDetailDto {
330    /// Table or metric name.
331    pub table_or_metric: String,
332    /// Optional schema description.
333    pub description: Option<String>,
334    /// `"event"` or `"metric"`.
335    pub logging_kind: String,
336    /// Schema version string.
337    pub version: String,
338    /// Registered field metadata.
339    pub fields: Vec<SchemaFieldDto>,
340    /// Whether the schema supports explore queries.
341    pub can_query: bool,
342}
343
344/// Field metadata in a schema detail response.
345#[derive(Debug, Clone, Serialize, Deserialize)]
346pub struct SchemaFieldDto {
347    /// Field name.
348    pub name: String,
349    /// Rust type name as registered.
350    pub rust_type: String,
351    /// Serialized [`FieldClassification`](crate::FieldClassification) label.
352    pub classification: String,
353}