hyprstream_metrics_api/metrics/
producer.rs1#![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
21pub 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
30pub 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 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 pub fn with_default_tenant(mut self, tenant: impl Into<String>) -> Self {
57 self.default_tenant = Some(tenant.into());
58 self
59 }
60
61 pub async fn init(&self) -> Result<(), Status> {
64 super::create_schema_v2_tables(&*self.backend).await
65 }
66
67 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 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 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 pub fn calibration(&self) -> CalibrationStore<B> {
131 CalibrationStore::new(Arc::clone(&self.backend))
132 }
133
134 pub fn decision_batches(&self) -> DecisionBatchStore<B> {
136 DecisionBatchStore::new(Arc::clone(&self.backend))
137 }
138}