ugnos 0.5.0

A high-performance, concurrent time-series database core written in Rust, designed for efficient IoT data ingestion, real-time analytics, and monitoring.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! Prometheus Remote Write ingest: `POST /api/v1/write`.
//!
//! Accepts Snappy-compressed protobuf `WriteRequest` payloads, maps `__name__` → series name,
//! remaining labels → `TagSet`, and sample timestamps (ms) → internal resolution (nanoseconds).
//! Exemplars and histograms in the payload are ignored; only `samples` are ingested.

use std::sync::Arc;

use crate::DbCore;
use crate::error::DbError;
use crate::prometheus;
use crate::telemetry::db_metrics;
use crate::types::{TagSet, Timestamp};
use http::StatusCode;
use prost::Message;

/// Prometheus metric name label; its value becomes the UGNOS series name.
const LABEL_NAME: &str = "__name__";

/// Converts Prometheus remote-write timestamp (milliseconds) to internal resolution (nanoseconds).
#[inline]
fn ms_to_ns(ts_ms: i64) -> Option<Timestamp> {
    u64::try_from(ts_ms).ok().map(|ms| ms * 1_000_000)
}

/// Extracts series name from `__name__` and builds tag set from remaining labels.
/// Returns `None` if `__name__` is missing (invalid series).
fn series_and_tags(labels: &[prometheus::Label]) -> Option<(String, TagSet)> {
    let mut name: Option<String> = None;
    let mut tags = TagSet::new();
    for l in labels {
        if l.name == LABEL_NAME {
            name = Some(l.value.clone());
        } else {
            tags.insert(l.name.clone(), l.value.clone());
        }
    }
    name.map(|n| (n, tags))
}

/// Result of handling a remote write request: status and body for the HTTP response.
#[derive(Debug)]
pub struct RemoteWriteResponse {
    /// HTTP status code.
    pub status: StatusCode,
    /// Response body (plain text, actionable for errors).
    pub body: Vec<u8>,
}

/// Decompresses Snappy-compressed body (raw Snappy format as used by Prometheus).
fn decompress_snappy(encoded: &[u8]) -> Result<Vec<u8>, String> {
    let mut decoder = snap::raw::Decoder::new();
    decoder
        .decompress_vec(encoded)
        .map_err(|e| format!("snappy decompress failed: {}", e))
}

/// Handles a Prometheus Remote Write request: decompresses body, decodes WriteRequest,
/// maps each time series and sample to `DbCore::insert`, and returns the appropriate
/// HTTP status and body.
///
/// **Mapping:** `__name__` → series name; all other labels → `TagSet`; sample timestamp (ms) →
/// internal timestamp (nanoseconds). Exemplars and histograms in the payload are ignored.
///
/// **Errors:** Invalid or empty payload → 400 with actionable message; cardinality limit →
/// 429 with explicit error (metrics emitted in both cases).
pub fn handle_remote_write(body: &[u8], db: &Arc<DbCore>) -> RemoteWriteResponse {
    let decoded = match decompress_snappy(body) {
        Ok(d) => d,
        Err(e) => {
            db_metrics::record_remote_write_rejected("invalid_payload");
            return RemoteWriteResponse {
                status: StatusCode::BAD_REQUEST,
                body: format!("invalid remote write payload: {}", e).into_bytes(),
            };
        }
    };

    let write_req = match prometheus::WriteRequest::decode(decoded.as_slice()) {
        Ok(r) => r,
        Err(e) => {
            db_metrics::record_remote_write_rejected("invalid_payload");
            return RemoteWriteResponse {
                status: StatusCode::BAD_REQUEST,
                body: format!("invalid remote write protobuf: {}", e).into_bytes(),
            };
        }
    };

    let mut points_written: u64 = 0;

    for ts in &write_req.timeseries {
        let (series, tags) = match series_and_tags(&ts.labels) {
            Some(p) => p,
            None => {
                db_metrics::record_remote_write_rejected("invalid_payload");
                return RemoteWriteResponse {
                    status: StatusCode::BAD_REQUEST,
                    body: b"remote write: timeseries missing __name__ label".to_vec(),
                };
            }
        };

        for sample in &ts.samples {
            let timestamp_ns = match ms_to_ns(sample.timestamp) {
                Some(ns) => ns,
                None => {
                    db_metrics::record_remote_write_rejected("invalid_payload");
                    return RemoteWriteResponse {
                        status: StatusCode::BAD_REQUEST,
                        body: format!(
                            "remote write: invalid timestamp ms={} (must be non-negative)",
                            sample.timestamp
                        )
                        .into_bytes(),
                    };
                }
            };

            match db.insert(&series, timestamp_ns, sample.value, tags.clone()) {
                Ok(()) => points_written = points_written.saturating_add(1),
                Err(DbError::SeriesCardinalityLimitExceeded {
                    scope,
                    limit,
                    current,
                }) => {
                    db_metrics::record_cardinality_limit_rejected(&scope);
                    db_metrics::record_remote_write_rejected("cardinality_limit");
                    return RemoteWriteResponse {
                        status: StatusCode::TOO_MANY_REQUESTS,
                        body: format!(
                            "series cardinality limit exceeded: scope={}, current={}, limit={}; points_written={}",
                            scope, current, limit, points_written
                        )
                        .into_bytes(),
                    };
                }
                Err(e) => {
                    db_metrics::record_remote_write_rejected("internal");
                    return RemoteWriteResponse {
                        status: StatusCode::INTERNAL_SERVER_ERROR,
                        body: format!("remote write ingest error: {}", e).into_bytes(),
                    };
                }
            }
        }
    }

    RemoteWriteResponse {
        status: StatusCode::OK,
        body: format!("ok points={}", points_written).into_bytes(),
    }
}

#[cfg(test)]
mod tests {
    use super::{handle_remote_write, ms_to_ns, series_and_tags};
    use crate::DbCore;
    use crate::prometheus::{Label, Sample, TimeSeries, WriteRequest};
    use prost::Message;
    use std::sync::Arc;

    fn encode_snappy(bytes: &[u8]) -> Vec<u8> {
        let mut encoder = snap::raw::Encoder::new();
        encoder.compress_vec(bytes).unwrap()
    }

    #[test]
    fn ms_to_ns_positive() {
        assert_eq!(ms_to_ns(0), Some(0));
        assert_eq!(ms_to_ns(1), Some(1_000_000));
        assert_eq!(ms_to_ns(1000), Some(1_000_000_000));
    }

    #[test]
    fn ms_to_ns_negative_rejected() {
        assert_eq!(ms_to_ns(-1), None);
    }

    #[test]
    fn series_and_tags_extracts_name_and_tags() {
        let labels = [
            Label {
                name: "__name__".to_string(),
                value: "http_requests_total".to_string(),
            },
            Label {
                name: "job".to_string(),
                value: "api".to_string(),
            },
            Label {
                name: "method".to_string(),
                value: "GET".to_string(),
            },
        ];
        let (name, tags) = series_and_tags(&labels).unwrap();
        assert_eq!(name, "http_requests_total");
        assert_eq!(tags.get("job"), Some(&"api".to_string()));
        assert_eq!(tags.get("method"), Some(&"GET".to_string()));
        assert!(!tags.contains_key("__name__"));
    }

    #[test]
    fn series_and_tags_missing_name_returns_none() {
        let labels = [Label {
            name: "job".to_string(),
            value: "api".to_string(),
        }];
        assert!(series_and_tags(&labels).is_none());
    }

    #[test]
    fn roundtrip_decode_snappy_write_request() {
        let wr = WriteRequest {
            timeseries: vec![TimeSeries {
                labels: vec![
                    Label {
                        name: "__name__".to_string(),
                        value: "x".to_string(),
                    },
                    Label {
                        name: "a".to_string(),
                        value: "b".to_string(),
                    },
                ],
                samples: vec![
                    Sample {
                        value: 1.0,
                        timestamp: 1000,
                    },
                    Sample {
                        value: 2.0,
                        timestamp: 2000,
                    },
                ],
            }],
        };
        let mut buf = Vec::new();
        wr.encode(&mut buf).unwrap();
        let compressed = encode_snappy(&buf);
        let decoded = super::decompress_snappy(&compressed).unwrap();
        let parsed = crate::prometheus::WriteRequest::decode(decoded.as_slice()).unwrap();
        assert_eq!(parsed.timeseries.len(), 1);
        assert_eq!(parsed.timeseries[0].labels.len(), 2);
        assert_eq!(parsed.timeseries[0].samples.len(), 2);
    }

    #[test]
    fn handle_remote_write_invalid_snappy_returns_400() {
        let dir = tempfile::tempdir().unwrap();
        let config = crate::DbConfig {
            data_dir: dir.path().to_path_buf(),
            ..Default::default()
        };
        let db = Arc::new(DbCore::with_config(config).unwrap());
        let r = handle_remote_write(b"not snappy", &db);
        assert_eq!(r.status, http::StatusCode::BAD_REQUEST);
        assert!(r.body.starts_with(b"invalid remote write payload"));
    }

    #[test]
    fn handle_remote_write_valid_ingests_points() {
        let dir = tempfile::tempdir().unwrap();
        let config = crate::DbConfig {
            data_dir: dir.path().to_path_buf(),
            ..Default::default()
        };
        let mut db = DbCore::with_config(config).unwrap();
        db.recover().unwrap();
        let db = Arc::new(db);

        let wr = WriteRequest {
            timeseries: vec![TimeSeries {
                labels: vec![
                    Label {
                        name: "__name__".to_string(),
                        value: "metric_a".to_string(),
                    },
                    Label {
                        name: "env".to_string(),
                        value: "test".to_string(),
                    },
                ],
                samples: vec![
                    Sample {
                        value: 42.5,
                        timestamp: 1_000,
                    },
                    Sample {
                        value: 43.0,
                        timestamp: 2_000,
                    },
                ],
            }],
        };
        let mut buf = Vec::new();
        wr.encode(&mut buf).unwrap();
        let body = encode_snappy(&buf);

        let r = handle_remote_write(&body, &db);
        assert_eq!(r.status, http::StatusCode::OK);
        assert!(r.body.starts_with(b"ok points=2"));

        db.flush().unwrap();
        let points = db.query("metric_a", 0..u64::MAX, None).unwrap();
        assert_eq!(points.len(), 2);
        assert_eq!(points[0], (1_000_000_000, 42.5));
        assert_eq!(points[1], (2_000_000_000, 43.0));
    }

    #[test]
    fn handle_remote_write_missing_name_returns_400() {
        let dir = tempfile::tempdir().unwrap();
        let config = crate::DbConfig {
            data_dir: dir.path().to_path_buf(),
            ..Default::default()
        };
        let db = Arc::new(DbCore::with_config(config).unwrap());
        let wr = WriteRequest {
            timeseries: vec![TimeSeries {
                labels: vec![Label {
                    name: "job".to_string(),
                    value: "x".to_string(),
                }],
                samples: vec![Sample {
                    value: 1.0,
                    timestamp: 0,
                }],
            }],
        };
        let mut buf = Vec::new();
        wr.encode(&mut buf).unwrap();
        let body = encode_snappy(&buf);
        let r = handle_remote_write(&body, &db);
        assert_eq!(r.status, http::StatusCode::BAD_REQUEST);
        assert!(
            std::str::from_utf8(&r.body).unwrap().contains("__name__"),
            "body should mention __name__: {:?}",
            std::str::from_utf8(&r.body)
        );
    }

    /// Adversarial: cardinality limit causes 429 and explicit error body.
    #[test]
    fn handle_remote_write_cardinality_limit_returns_429() {
        let dir = tempfile::tempdir().unwrap();
        let config = crate::DbConfig {
            data_dir: dir.path().to_path_buf(),
            max_series_cardinality: Some(1),
            ..Default::default()
        };
        let mut db = DbCore::with_config(config).unwrap();
        db.recover().unwrap();
        let db = Arc::new(db);

        // First series succeeds; second series hits cardinality limit.
        let wr = WriteRequest {
            timeseries: vec![
                TimeSeries {
                    labels: vec![
                        Label {
                            name: "__name__".to_string(),
                            value: "first".to_string(),
                        },
                        Label {
                            name: "a".to_string(),
                            value: "1".to_string(),
                        },
                    ],
                    samples: vec![Sample {
                        value: 1.0,
                        timestamp: 1000,
                    }],
                },
                TimeSeries {
                    labels: vec![
                        Label {
                            name: "__name__".to_string(),
                            value: "second".to_string(),
                        },
                        Label {
                            name: "a".to_string(),
                            value: "2".to_string(),
                        },
                    ],
                    samples: vec![Sample {
                        value: 2.0,
                        timestamp: 2000,
                    }],
                },
            ],
        };
        let mut buf = Vec::new();
        wr.encode(&mut buf).unwrap();
        let body = encode_snappy(&buf);
        let r = handle_remote_write(&body, &db);
        assert_eq!(r.status, http::StatusCode::TOO_MANY_REQUESTS);
        let body_str = std::str::from_utf8(&r.body).unwrap();
        assert!(
            body_str.contains("cardinality limit"),
            "body should mention cardinality limit: {}",
            body_str
        );
        assert!(
            body_str.contains("points_written=1"),
            "body should report points_written before rejection: {}",
            body_str
        );
    }
}