Skip to main content

hyprstream_metrics_api/metrics/
producer.rs

1//! Producer-side write API for schema-v2 metric rows.
2//!
3//! `MetricsProducer` is the first real producer path into the metrics store:
4//! it constructs labeled/tenanted [`MetricRecord`]s (merging configured
5//! defaults) and writes them through any [`StorageBackend`]. The metrics
6//! service's ingest handler is the wire-facing adapter onto the same records;
7//! the serving path (P3.4) emits decision-quality rows the same way.
8
9// tonic::Status is the idiomatic gRPC error type - boxing would break API
10#![allow(clippy::result_large_err)]
11
12use super::calibration::CalibrationStore;
13use super::decision_batch::DecisionBatchStore;
14use super::{create_record_batch, MetricRecord, METRICS_TABLE};
15use crate::storage::StorageBackend;
16use std::collections::BTreeMap;
17use std::sync::Arc;
18use std::time::SystemTime;
19use tonic::Status;
20
21/// Current Unix epoch time in milliseconds (the `MetricRecord.timestamp` unit).
22pub fn now_unix_ms() -> i64 {
23    let ms = SystemTime::now()
24        .duration_since(SystemTime::UNIX_EPOCH)
25        .map(|d| d.as_millis())
26        .unwrap_or(0);
27    i64::try_from(ms).unwrap_or(i64::MAX)
28}
29
30/// Producer of schema-v2 metric rows over any [`StorageBackend`].
31///
32/// Default labels/tenant are merged into every emitted record; per-record
33/// values win on conflict.
34pub struct MetricsProducer<B: StorageBackend> {
35    backend: Arc<B>,
36    default_labels: BTreeMap<String, String>,
37    default_tenant: Option<String>,
38}
39
40impl<B: StorageBackend> MetricsProducer<B> {
41    pub fn new(backend: Arc<B>) -> Self {
42        Self {
43            backend,
44            default_labels: BTreeMap::new(),
45            default_tenant: None,
46        }
47    }
48
49    /// Add a default label applied to every emitted record.
50    pub fn with_default_label(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
51        self.default_labels.insert(key.into(), value.into());
52        self
53    }
54
55    /// Set a default tenant applied to every emitted record.
56    pub fn with_default_tenant(mut self, tenant: impl Into<String>) -> Self {
57        self.default_tenant = Some(tenant.into());
58        self
59    }
60
61    /// Create all schema-v2 tables (`metrics`, `calibration_params`,
62    /// `decision_batches`) and migrate pre-v2 `metrics` tables in place.
63    pub async fn init(&self) -> Result<(), Status> {
64        super::create_schema_v2_tables(&*self.backend).await
65    }
66
67    /// Build a point-sample record (window of one: sum == avg == value) with
68    /// this producer's default labels/tenant pre-applied.
69    pub fn point(&self, metric_id: impl Into<String>, value: f64) -> MetricRecord {
70        MetricRecord {
71            metric_id: metric_id.into(),
72            timestamp: now_unix_ms(),
73            value_running_window_sum: value,
74            value_running_window_avg: value,
75            value_running_window_count: 1,
76            labels: self.default_labels.clone(),
77            tenant_id: self.default_tenant.clone(),
78        }
79    }
80
81    /// Emit one record. Producer defaults fill any label/tenant the record
82    /// does not set itself.
83    pub async fn emit(&self, mut record: MetricRecord) -> Result<(), Status> {
84        for (key, value) in &self.default_labels {
85            record
86                .labels
87                .entry(key.clone())
88                .or_insert_with(|| value.clone());
89        }
90        if record.tenant_id.is_none() {
91            record.tenant_id.clone_from(&self.default_tenant);
92        }
93        if record.metric_id.is_empty() {
94            return Err(Status::invalid_argument("metric_id must not be empty"));
95        }
96        let batch = create_record_batch(&[record])?;
97        self.backend.insert_into_table(METRICS_TABLE, batch).await
98    }
99
100    /// Emit a batch of records (one insert), applying the same default-merge
101    /// as [`emit`](Self::emit).
102    pub async fn emit_all(
103        &self,
104        records: impl IntoIterator<Item = MetricRecord>,
105    ) -> Result<(), Status> {
106        let mut merged = Vec::new();
107        for mut record in records {
108            for (key, value) in &self.default_labels {
109                record
110                    .labels
111                    .entry(key.clone())
112                    .or_insert_with(|| value.clone());
113            }
114            if record.tenant_id.is_none() {
115                record.tenant_id.clone_from(&self.default_tenant);
116            }
117            if record.metric_id.is_empty() {
118                return Err(Status::invalid_argument("metric_id must not be empty"));
119            }
120            merged.push(record);
121        }
122        if merged.is_empty() {
123            return Ok(());
124        }
125        let batch = create_record_batch(&merged)?;
126        self.backend.insert_into_table(METRICS_TABLE, batch).await
127    }
128
129    /// Calibration parameter writer/reader on the same backend (P2.2 re-fit).
130    pub fn calibration(&self) -> CalibrationStore<B> {
131        CalibrationStore::new(Arc::clone(&self.backend))
132    }
133
134    /// Arrow-native decision-batch store on the same backend.
135    pub fn decision_batches(&self) -> DecisionBatchStore<B> {
136        DecisionBatchStore::new(Arc::clone(&self.backend))
137    }
138}