oculus 0.1.3

Unified telemetry system for monitoring and observability
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
//! User-facing storage facades.
//!
//! Provides ergonomic APIs for storage operations:
//! - `StorageWriter`: Non-blocking writes via async channel
//! - `MetricReader`: Query metrics (series + values JOIN)
//! - `EventReader`: Query events
//! - `StorageAdmin`: Cleanup and maintenance

use std::collections::HashMap;
use std::str::FromStr;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

use chrono::{DateTime, Duration, Utc};
use serde::Serialize;
use sqlx::Row;
use strum_macros::{AsRefStr, EnumString};
use tokio::sync::mpsc::Sender;

use crate::storage::StorageError;
use crate::storage::actor::Command;
use crate::storage::db::SqlitePool;
use crate::storage::types::{
    DynamicTags, Event, EventKind, EventSeverity, EventSource, MetricCategory, MetricSeries,
    MetricValue, StaticTags,
};

// =============================================================================
// Constants
// =============================================================================

const DEFAULT_LIMIT: u32 = 100;
const MAX_LIMIT: u32 = 10_000;
const DEFAULT_RANGE_DAYS: i64 = 30;

// =============================================================================
// Query Types
// =============================================================================

/// Sort order for queries.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, EnumString, AsRefStr)]
#[strum(serialize_all = "lowercase")]
pub enum SortOrder {
    Asc,
    #[default]
    Desc,
}

impl SortOrder {
    fn as_sql(&self) -> &'static str {
        match self {
            Self::Asc => "ASC",
            Self::Desc => "DESC",
        }
    }
}

/// Query for metric values (with series JOIN).
#[derive(Debug, Clone, Default)]
pub struct MetricQuery {
    pub start: Option<DateTime<Utc>>,
    pub end: Option<DateTime<Utc>>,
    pub category: Option<MetricCategory>,
    pub name: Option<String>,
    pub target: Option<String>,
    pub limit: Option<u32>,
    pub order: Option<SortOrder>,
}

/// Query for events.
#[derive(Debug, Clone, Default)]
pub struct EventQuery {
    pub start: Option<DateTime<Utc>>,
    pub end: Option<DateTime<Utc>>,
    pub source: Option<EventSource>,
    pub kind: Option<EventKind>,
    pub severity: Option<EventSeverity>,
    pub limit: Option<u32>,
    pub order: Option<SortOrder>,
}

// =============================================================================
// Result Types
// =============================================================================

/// Joined metric result (series + value).
#[derive(Debug, Clone)]
pub struct MetricResult {
    pub series_id: u64,
    pub category: MetricCategory,
    pub name: String,
    pub target: String,
    pub static_tags: StaticTags,
    pub description: Option<String>,
    pub ts: DateTime<Utc>,
    pub value: f64,
    pub unit: Option<String>,
    pub success: bool,
    pub duration_ms: u32,
    pub dynamic_tags: DynamicTags,
}

/// Statistics for a single category.
#[derive(Debug, Clone, Serialize)]
pub struct CategoryStats {
    pub category: String,
    pub total: u64,
    pub success: u64,
    pub failure: u64,
}

/// Aggregated metric statistics grouped by category and success.
#[derive(Debug, Clone, Serialize)]
pub struct MetricStats {
    pub total: u64,
    pub success_count: u64,
    pub failure_count: u64,
    pub by_category: Vec<CategoryStats>,
}

// =============================================================================
// Writer
// =============================================================================

/// Non-blocking storage writer.
///
/// Uses `try_send` - data is dropped if channel is full.
#[derive(Clone)]
pub struct StorageWriter {
    tx: Sender<Command>,
    dropped_metrics: Arc<AtomicU64>,
}

impl std::fmt::Debug for StorageWriter {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StorageWriter").finish_non_exhaustive()
    }
}

impl StorageWriter {
    pub(crate) fn new(tx: Sender<Command>) -> Self {
        Self {
            tx,
            dropped_metrics: Arc::new(AtomicU64::new(0)),
        }
    }

    /// Get total count of dropped metrics due to channel capacity.
    pub fn dropped_metrics(&self) -> u64 {
        self.dropped_metrics.load(Ordering::Relaxed)
    }

    /// Upsert a metric series.
    pub fn upsert_metric_series(&self, series: MetricSeries) -> Result<(), StorageError> {
        if self
            .tx
            .try_send(Command::UpsertMetricSeries(series))
            .is_err()
        {
            self.dropped_metrics.fetch_add(1, Ordering::Relaxed);
            return Err(StorageError::ChannelSend);
        }
        Ok(())
    }

    /// Insert a metric value.
    pub fn insert_metric_value(&self, value: MetricValue) -> Result<(), StorageError> {
        if self.tx.try_send(Command::InsertMetricValue(value)).is_err() {
            tracing::warn!("Channel full, dropping metric value");
            self.dropped_metrics.fetch_add(1, Ordering::Relaxed);
            return Err(StorageError::ChannelSend);
        }
        Ok(())
    }

    /// Insert a single event.
    pub fn insert_event(&self, event: Event) -> Result<(), StorageError> {
        self.tx.try_send(Command::InsertEvent(event)).map_err(|_| {
            tracing::warn!("Channel full, dropping event");
            StorageError::ChannelSend
        })
    }

    /// Force flush all buffered data immediately.
    pub fn flush(&self) -> Result<(), StorageError> {
        self.tx
            .try_send(Command::Flush)
            .map_err(|_| StorageError::ChannelSend)
    }
}

// =============================================================================
// Readers
// =============================================================================

/// Metric reader (series + values JOIN).
#[derive(Clone)]
pub struct MetricReader {
    pool: Arc<SqlitePool>,
}

impl std::fmt::Debug for MetricReader {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("MetricReader").finish_non_exhaustive()
    }
}

impl MetricReader {
    pub(crate) fn new(pool: Arc<SqlitePool>) -> Self {
        Self { pool }
    }

    /// Query metrics with filters.
    pub async fn query(&self, q: MetricQuery) -> Result<Vec<MetricResult>, StorageError> {
        let now = Utc::now();
        let start = q
            .start
            .unwrap_or_else(|| now - Duration::days(DEFAULT_RANGE_DAYS));
        let end = q.end.unwrap_or(now);
        let limit = q.limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT);
        let order = q.order.unwrap_or_default();

        // Build dynamic query
        let mut sql = String::from(
            "SELECT s.series_id, s.category, s.name, s.target, s.static_tags, s.description,
                    v.ts, v.value, v.unit, v.success, v.duration_ms, v.dynamic_tags
             FROM metric_values v
             JOIN metric_series s ON v.series_id = s.series_id
             WHERE v.ts >= ? AND v.ts <= ?",
        );

        if q.category.is_some() {
            sql.push_str(" AND s.category = ?");
        }
        if q.name.is_some() {
            sql.push_str(" AND s.name = ?");
        }
        if q.target.is_some() {
            sql.push_str(" AND s.target = ?");
        }

        // Note: ORDER BY direction must be embedded (ASC/DESC can't be parameterized),
        // but LIMIT can be safely bound as a parameter
        sql.push_str(&format!(" ORDER BY v.ts {} LIMIT ?", order.as_sql()));

        // Build query with bindings
        let mut query = sqlx::query(&sql)
            .bind(start.timestamp_micros())
            .bind(end.timestamp_micros());

        if let Some(cat) = &q.category {
            query = query.bind(cat.as_ref());
        }
        if let Some(name) = &q.name {
            query = query.bind(name);
        }
        if let Some(target) = &q.target {
            query = query.bind(target);
        }

        // LIMIT must be bound last to match placeholder order in SQL
        query = query.bind(limit as i64);

        let rows = query.fetch_all(self.pool.inner()).await?;

        let results: Vec<MetricResult> = rows
            .into_iter()
            .map(|row| MetricResult {
                series_id: row.get::<i64, _>(0) as u64,
                category: MetricCategory::from_str(row.get::<&str, _>(1))
                    .unwrap_or(MetricCategory::Custom),
                name: row.get(2),
                target: row.get(3),
                static_tags: parse_map(row.get::<Option<&str>, _>(4).unwrap_or("{}")),
                description: row.get(5),
                ts: DateTime::from_timestamp_micros(row.get(6)).unwrap_or(DateTime::UNIX_EPOCH),
                value: row.get(7),
                unit: row.get(8),
                success: row.get::<i32, _>(9) != 0,
                duration_ms: row.get::<Option<i64>, _>(10).unwrap_or(0) as u32,
                dynamic_tags: parse_map(row.get::<Option<&str>, _>(11).unwrap_or("{}")),
            })
            .collect();

        Ok(results)
    }

    /// Get aggregated statistics grouped by category and success.
    pub async fn stats(
        &self,
        start: Option<DateTime<Utc>>,
        end: Option<DateTime<Utc>>,
    ) -> Result<MetricStats, StorageError> {
        let now = Utc::now();
        let start_ts = start.unwrap_or_else(|| now - Duration::days(DEFAULT_RANGE_DAYS));
        let end_ts = end.unwrap_or(now);

        let sql = "SELECT s.category, v.success, COUNT(*) as cnt
                   FROM metric_values v
                   JOIN metric_series s ON v.series_id = s.series_id
                   WHERE v.ts >= ? AND v.ts <= ?
                   GROUP BY s.category, v.success
                   ORDER BY s.category";

        let rows = sqlx::query(sql)
            .bind(start_ts.timestamp_micros())
            .bind(end_ts.timestamp_micros())
            .fetch_all(self.pool.inner())
            .await?;

        // Aggregate into CategoryStats
        let mut category_map: HashMap<String, CategoryStats> = HashMap::new();
        let mut total = 0u64;
        let mut success_count = 0u64;
        let mut failure_count = 0u64;

        for row in rows {
            let cat: String = row.get(0);
            let success: i32 = row.get(1);
            let cnt: i64 = row.get(2);
            let cnt = cnt as u64;

            total += cnt;
            if success != 0 {
                success_count += cnt;
            } else {
                failure_count += cnt;
            }

            let entry = category_map.entry(cat.clone()).or_insert(CategoryStats {
                category: cat,
                total: 0,
                success: 0,
                failure: 0,
            });
            entry.total += cnt;
            if success != 0 {
                entry.success += cnt;
            } else {
                entry.failure += cnt;
            }
        }

        let mut by_category: Vec<CategoryStats> = category_map.into_values().collect();
        by_category.sort_by(|a, b| a.category.cmp(&b.category));

        Ok(MetricStats {
            total,
            success_count,
            failure_count,
            by_category,
        })
    }
}

/// Event reader.
#[derive(Clone)]
pub struct EventReader {
    pool: Arc<SqlitePool>,
}

impl std::fmt::Debug for EventReader {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EventReader").finish_non_exhaustive()
    }
}

impl EventReader {
    pub(crate) fn new(pool: Arc<SqlitePool>) -> Self {
        Self { pool }
    }

    /// Query events with filters.
    pub async fn query(&self, q: EventQuery) -> Result<Vec<Event>, StorageError> {
        let now = Utc::now();
        let start = q
            .start
            .unwrap_or_else(|| now - Duration::days(DEFAULT_RANGE_DAYS));
        let end = q.end.unwrap_or(now);
        let limit = q.limit.unwrap_or(DEFAULT_LIMIT).min(MAX_LIMIT);
        let order = q.order.unwrap_or_default();

        let mut sql = String::from(
            "SELECT id, ts, source, kind, severity, message, payload
             FROM events WHERE ts >= ? AND ts <= ?",
        );

        if q.source.is_some() {
            sql.push_str(" AND source = ?");
        }
        if q.kind.is_some() {
            sql.push_str(" AND kind = ?");
        }
        if q.severity.is_some() {
            sql.push_str(" AND severity = ?");
        }

        // Note: ORDER BY direction must be embedded, but LIMIT is parameterized
        sql.push_str(&format!(" ORDER BY ts {} LIMIT ?", order.as_sql()));

        let mut query = sqlx::query(&sql)
            .bind(start.timestamp_micros())
            .bind(end.timestamp_micros());

        if let Some(src) = &q.source {
            query = query.bind(src.as_ref());
        }
        if let Some(kind) = &q.kind {
            query = query.bind(kind.as_ref());
        }
        if let Some(sev) = &q.severity {
            query = query.bind(sev.as_ref());
        }

        // LIMIT must be bound last to match placeholder order in SQL
        query = query.bind(limit as i64);

        let rows = query.fetch_all(self.pool.inner()).await?;

        let results: Vec<Event> = rows
            .into_iter()
            .map(|row| Event {
                id: Some(row.get::<i64, _>(0)),
                ts: DateTime::from_timestamp_micros(row.get(1)).unwrap_or(DateTime::UNIX_EPOCH),
                source: EventSource::from_str(row.get::<&str, _>(2)).unwrap_or(EventSource::System),
                kind: EventKind::from_str(row.get::<&str, _>(3)).unwrap_or(EventKind::System),
                severity: EventSeverity::from_str(row.get::<&str, _>(4))
                    .unwrap_or(EventSeverity::Info),
                message: row.get(5),
                payload: parse_map(row.get::<Option<&str>, _>(6).unwrap_or("{}")),
            })
            .collect();

        Ok(results)
    }
}

// =============================================================================
// Admin
// =============================================================================

/// Storage administration.
#[derive(Clone)]
pub struct StorageAdmin {
    tx: Sender<Command>,
}

impl std::fmt::Debug for StorageAdmin {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("StorageAdmin").finish_non_exhaustive()
    }
}

impl StorageAdmin {
    pub(crate) fn new(tx: Sender<Command>) -> Self {
        Self { tx }
    }

    pub fn cleanup_metric_values(&self, retention_days: u32) -> Result<(), StorageError> {
        self.tx
            .try_send(Command::CleanupMetricValues { retention_days })
            .map_err(|_| StorageError::ChannelSend)
    }

    pub fn cleanup_events(&self, retention_days: u32) -> Result<(), StorageError> {
        self.tx
            .try_send(Command::CleanupEvents { retention_days })
            .map_err(|_| StorageError::ChannelSend)
    }

    pub fn shutdown(&self) -> Result<(), StorageError> {
        self.tx
            .try_send(Command::Shutdown)
            .map_err(|_| StorageError::ChannelSend)
    }
}

// =============================================================================
// Helpers
// =============================================================================

/// Parse JSON string to BTreeMap.
fn parse_map(s: &str) -> std::collections::BTreeMap<String, String> {
    if s.is_empty() || s == "{}" {
        return std::collections::BTreeMap::new();
    }
    serde_json::from_str(s).unwrap_or_else(|e| {
        tracing::debug!(error = %e, raw = s, "Failed to parse JSON map, returning empty");
        std::collections::BTreeMap::new()
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::storage::actor::DbActor;
    use std::time::Duration;

    #[tokio::test]
    async fn test_metric_roundtrip() {
        let (handle, tx, pool) = DbActor::spawn(
            "sqlite::memory:",
            100,
            crate::storage::actor::DEFAULT_BATCH_SIZE,
            crate::storage::actor::DEFAULT_BATCH_FLUSH_INTERVAL,
        )
        .await
        .unwrap();

        let writer = StorageWriter::new(tx.clone());
        let admin = StorageAdmin::new(tx);

        let series = MetricSeries::new(
            MetricCategory::NetworkTcp,
            "latency",
            "127.0.0.1:6379",
            StaticTags::new(),
            Some("Redis".to_string()),
        );
        let value = MetricValue::new(series.series_id, 42.5, true).with_duration_ms(15);

        writer.upsert_metric_series(series).unwrap();
        writer.insert_metric_value(value).unwrap();
        writer.flush().unwrap();

        // Give actor time to process
        tokio::time::sleep(Duration::from_millis(100)).await;

        admin.shutdown().unwrap();
        handle.await.unwrap();

        let reader = MetricReader::new(pool);
        let results = reader.query(MetricQuery::default()).await.unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].name, "latency");
        assert_eq!(results[0].value, 42.5);
    }

    #[tokio::test]
    async fn test_event_roundtrip() {
        let (handle, tx, pool) = DbActor::spawn(
            "sqlite::memory:",
            100,
            crate::storage::actor::DEFAULT_BATCH_SIZE,
            crate::storage::actor::DEFAULT_BATCH_FLUSH_INTERVAL,
        )
        .await
        .unwrap();

        let writer = StorageWriter::new(tx.clone());
        let admin = StorageAdmin::new(tx);

        let event = Event::new(
            EventSource::System,
            EventKind::System,
            EventSeverity::Info,
            "Started",
        )
        .with_payload("version", "1.0.0");

        writer.insert_event(event).unwrap();

        // Give actor time to process
        tokio::time::sleep(Duration::from_millis(100)).await;

        admin.shutdown().unwrap();
        handle.await.unwrap();

        let reader = EventReader::new(pool);
        let results = reader.query(EventQuery::default()).await.unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].source, EventSource::System);
        assert_eq!(results[0].message, "Started");
    }

    #[tokio::test]
    async fn test_query_filters() {
        let (handle, tx, pool) = DbActor::spawn(
            "sqlite::memory:",
            100,
            crate::storage::actor::DEFAULT_BATCH_SIZE,
            crate::storage::actor::DEFAULT_BATCH_FLUSH_INTERVAL,
        )
        .await
        .unwrap();

        let writer = StorageWriter::new(tx.clone());
        let admin = StorageAdmin::new(tx);

        let tcp = MetricSeries::new(
            MetricCategory::NetworkTcp,
            "latency",
            "host1",
            StaticTags::new(),
            None,
        );
        let crypto = MetricSeries::new(
            MetricCategory::Crypto,
            "price",
            "BTC",
            StaticTags::new(),
            None,
        );

        writer.upsert_metric_series(tcp.clone()).unwrap();
        writer
            .insert_metric_value(MetricValue::new(tcp.series_id, 10.0, true).with_duration_ms(5))
            .unwrap();
        writer.upsert_metric_series(crypto.clone()).unwrap();
        writer
            .insert_metric_value(
                MetricValue::new(crypto.series_id, 100000.0, true).with_duration_ms(50),
            )
            .unwrap();
        writer.flush().unwrap();

        // Give actor time to process
        tokio::time::sleep(Duration::from_millis(100)).await;

        admin.shutdown().unwrap();
        handle.await.unwrap();

        let reader = MetricReader::new(pool);
        let results = reader
            .query(MetricQuery {
                category: Some(MetricCategory::NetworkTcp),
                ..Default::default()
            })
            .await
            .unwrap();

        assert_eq!(results.len(), 1);
        assert_eq!(results[0].name, "latency");
    }
}