otelite-api 0.1.1

Lightweight web dashboard for visualizing OpenTelemetry logs, traces, and metrics
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
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
use crate::server::{AppState, QueryCache};
use axum::{
    extract::{Query, State},
    http::StatusCode,
    response::{IntoResponse, Json},
};
use otelite_core::api::{
    ErrorResponse, HistogramBucket, HistogramValue, MetricResponse, MetricValue, Quantile,
    Resource, SummaryValue,
};
use otelite_core::storage::QueryParams;
use otelite_core::telemetry::metric::MetricType;
use otelite_core::telemetry::Metric;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Query parameters for listing metrics
#[derive(Debug, Deserialize, Serialize, utoipa::IntoParams)]
pub struct MetricsQuery {
    /// Filter by metric name
    pub name: Option<String>,
    /// Filter by resource attribute (format: key=value)
    pub resource: Option<String>,
    /// Start time (nanoseconds since Unix epoch)
    pub start_time: Option<i64>,
    /// End time (nanoseconds since Unix epoch)
    pub end_time: Option<i64>,
    /// Maximum number of metrics to return
    pub limit: Option<usize>,
    /// Offset for pagination
    pub offset: Option<usize>,
}

/// Query parameters for aggregating metrics
#[derive(Debug, Deserialize, Serialize, utoipa::IntoParams)]
pub struct AggregateQuery {
    /// Metric name to aggregate
    pub name: String,
    /// Aggregation function (sum, avg, min, max)
    pub function: String,
    /// Time bucket size in seconds (for time-series aggregation)
    pub bucket_size: Option<i64>,
    /// Start time (nanoseconds since Unix epoch)
    pub start_time: Option<i64>,
    /// End time (nanoseconds since Unix epoch)
    pub end_time: Option<i64>,
}

/// Response structure for aggregated metrics
#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)]
pub struct AggregateResponse {
    pub name: String,
    pub function: String,
    pub result: f64,
    pub count: usize,
    pub buckets: Option<Vec<TimeBucket>>,
}

/// Time bucket for time-series aggregation
#[derive(Debug, Serialize, Deserialize, utoipa::ToSchema)]
pub struct TimeBucket {
    pub timestamp: i64,
    pub value: f64,
    pub count: usize,
}

/// List metrics with optional filtering
#[utoipa::path(
    get,
    path = "/api/metrics",
    params(MetricsQuery),
    responses(
        (status = 200, description = "List of metrics", body = Vec<MetricResponse>),
        (status = 500, description = "Internal server error", body = ErrorResponse)
    ),
    tag = "metrics"
)]
pub async fn list_metrics(
    State(state): State<AppState>,
    Query(query): Query<MetricsQuery>,
) -> Result<Json<Vec<MetricResponse>>, (StatusCode, Json<ErrorResponse>)> {
    // Check cache first
    let cache_key = QueryCache::make_key(&query);
    if let Some(cached) = state.cache.metrics.get(&cache_key) {
        if let Ok(response) = serde_json::from_str(&cached) {
            return Ok(Json(response));
        }
    }

    // Build query parameters
    let mut params = QueryParams::default();

    if let Some(start) = query.start_time {
        params.start_time = Some(start);
    }
    if let Some(end) = query.end_time {
        params.end_time = Some(end);
    }
    if let Some(limit) = query.limit {
        params.limit = Some(limit);
    }

    // Query metrics from storage: use latest-per-name so that high-frequency
    // counters don't push gauges/histograms out of the result window.
    let mut metrics = state
        .storage
        .query_latest_metrics(&params)
        .await
        .map_err(|e| {
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ErrorResponse::storage_error(format!(
                    "query metrics: {}",
                    e
                ))),
            )
        })?;

    // Filter by name if specified
    if let Some(name_filter) = &query.name {
        metrics.retain(|m| m.name.contains(name_filter));
    }

    // Filter by resource if specified
    if let Some(resource_filter) = &query.resource {
        if let Some((key, value)) = resource_filter.split_once('=') {
            metrics.retain(|m| {
                m.resource
                    .as_ref()
                    .and_then(|r| r.attributes.get(key))
                    .map(|v| v == value)
                    .unwrap_or(false)
            });
        }
    }

    // Apply pagination manually
    let offset = query.offset.unwrap_or(0);
    let limit = query.limit.unwrap_or(100);

    let metrics: Vec<_> = metrics.into_iter().skip(offset).take(limit).collect();

    // Convert to response format
    let response: Vec<MetricResponse> = metrics
        .into_iter()
        .map(|metric| {
            let (metric_type_str, value) = match &metric.metric_type {
                MetricType::Gauge(v) => ("gauge", MetricValue::Gauge(*v)),
                MetricType::Counter(v) => ("counter", MetricValue::Counter(*v as i64)),
                MetricType::Histogram {
                    count,
                    sum,
                    buckets,
                } => (
                    "histogram",
                    MetricValue::Histogram(HistogramValue {
                        count: *count,
                        sum: *sum,
                        buckets: buckets
                            .iter()
                            .map(|b| HistogramBucket {
                                upper_bound: b.upper_bound,
                                count: b.count,
                            })
                            .collect(),
                    }),
                ),
                MetricType::Summary {
                    count,
                    sum,
                    quantiles,
                } => (
                    "summary",
                    MetricValue::Summary(SummaryValue {
                        count: *count,
                        sum: *sum,
                        quantiles: quantiles
                            .iter()
                            .map(|q| Quantile {
                                quantile: q.quantile,
                                value: q.value,
                            })
                            .collect(),
                    }),
                ),
            };

            MetricResponse {
                name: metric.name,
                description: metric.description,
                unit: metric.unit,
                metric_type: metric_type_str.to_string(),
                value,
                timestamp: metric.timestamp,
                attributes: metric.attributes,
                resource: metric.resource.map(|r| Resource {
                    attributes: r.attributes,
                }),
            }
        })
        .collect();

    Ok(Json(response))
}

/// Get list of unique metric names
#[utoipa::path(
    get,
    path = "/api/metrics/names",
    responses(
        (status = 200, description = "List of unique metric names", body = Vec<String>),
        (status = 500, description = "Internal server error", body = ErrorResponse)
    ),
    tag = "metrics"
)]
pub async fn list_metric_names(
    State(state): State<AppState>,
) -> Result<Json<Vec<String>>, (StatusCode, Json<ErrorResponse>)> {
    // Query all metrics
    let params = QueryParams::default();
    let metrics = state.storage.query_metrics(&params).await.map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ErrorResponse::storage_error(format!(
                "list metric names: {}",
                e
            ))),
        )
    })?;

    // Extract unique names
    let mut names: Vec<String> = metrics
        .into_iter()
        .map(|m| m.name)
        .collect::<std::collections::HashSet<_>>()
        .into_iter()
        .collect();

    names.sort();
    Ok(Json(names))
}

/// Aggregate metrics by function
#[utoipa::path(
    get,
    path = "/api/metrics/aggregate",
    params(AggregateQuery),
    responses(
        (status = 200, description = "Aggregated metric result", body = AggregateResponse),
        (status = 400, description = "Invalid aggregation function", body = ErrorResponse),
        (status = 404, description = "Metric not found", body = ErrorResponse),
        (status = 500, description = "Internal server error", body = ErrorResponse)
    ),
    tag = "metrics"
)]
pub async fn aggregate_metrics(
    State(state): State<AppState>,
    Query(query): Query<AggregateQuery>,
) -> Result<Json<AggregateResponse>, (StatusCode, Json<ErrorResponse>)> {
    // Check cache first
    let cache_key = QueryCache::make_key(&query);
    if let Some(cached) = state.cache.metrics.get(&cache_key) {
        if let Ok(response) = serde_json::from_str(&cached) {
            return Ok(Json(response));
        }
    }

    // Build query parameters
    let mut params = QueryParams::default();

    if let Some(start) = query.start_time {
        params.start_time = Some(start);
    }
    if let Some(end) = query.end_time {
        params.end_time = Some(end);
    }

    // Query metrics from storage
    let metrics = state.storage.query_metrics(&params).await.map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ErrorResponse::storage_error(format!(
                "aggregate metrics: {}",
                e
            ))),
        )
    })?;

    // Filter by name
    let metrics: Vec<_> = metrics
        .into_iter()
        .filter(|m| m.name == query.name)
        .collect();

    if metrics.is_empty() {
        return Err((
            StatusCode::NOT_FOUND,
            Json(ErrorResponse::not_found(format!("Metric '{}'", query.name))),
        ));
    }

    // Perform aggregation based on function
    let result = match query.function.as_str() {
        "sum" => {
            let mut sum = 0.0;
            let mut count = 0;
            for metric in &metrics {
                match &metric.metric_type {
                    MetricType::Gauge(v) => {
                        sum += v;
                        count += 1;
                    },
                    MetricType::Counter(v) => {
                        sum += *v as f64;
                        count += 1;
                    },
                    MetricType::Histogram { sum: s, .. } => {
                        sum += s;
                        count += 1;
                    },
                    MetricType::Summary { sum: s, .. } => {
                        sum += s;
                        count += 1;
                    },
                }
            }
            AggregateResponse {
                name: query.name.clone(),
                function: "sum".to_string(),
                result: sum,
                count,
                buckets: None,
            }
        },
        "avg" => {
            let mut sum = 0.0;
            let mut count = 0;
            for metric in &metrics {
                match &metric.metric_type {
                    MetricType::Gauge(v) => {
                        sum += v;
                        count += 1;
                    },
                    MetricType::Counter(v) => {
                        sum += *v as f64;
                        count += 1;
                    },
                    MetricType::Histogram {
                        sum: s, count: c, ..
                    } => {
                        sum += s;
                        count += *c as usize;
                    },
                    MetricType::Summary {
                        sum: s, count: c, ..
                    } => {
                        sum += s;
                        count += *c as usize;
                    },
                }
            }
            let avg = if count > 0 { sum / count as f64 } else { 0.0 };
            AggregateResponse {
                name: query.name.clone(),
                function: "avg".to_string(),
                result: avg,
                count,
                buckets: None,
            }
        },
        "min" => {
            let mut min = f64::MAX;
            let mut count = 0;
            for metric in &metrics {
                match &metric.metric_type {
                    MetricType::Gauge(v) => {
                        min = min.min(*v);
                        count += 1;
                    },
                    MetricType::Counter(v) => {
                        min = min.min(*v as f64);
                        count += 1;
                    },
                    _ => {},
                }
            }
            AggregateResponse {
                name: query.name.clone(),
                function: "min".to_string(),
                result: if count > 0 { min } else { 0.0 },
                count,
                buckets: None,
            }
        },
        "max" => {
            let mut max = f64::MIN;
            let mut count = 0;
            for metric in &metrics {
                match &metric.metric_type {
                    MetricType::Gauge(v) => {
                        max = max.max(*v);
                        count += 1;
                    },
                    MetricType::Counter(v) => {
                        max = max.max(*v as f64);
                        count += 1;
                    },
                    _ => {},
                }
            }
            AggregateResponse {
                name: query.name.clone(),
                function: "max".to_string(),
                result: if count > 0 { max } else { 0.0 },
                count,
                buckets: None,
            }
        },
        _ => {
            return Err((
                StatusCode::BAD_REQUEST,
                Json(ErrorResponse::bad_request(format!(
                    "Invalid aggregation function '{}'. Use: sum, avg, min, max",
                    query.function
                ))),
            ))
        },
    };

    // If bucket_size is specified, perform time-series aggregation
    let result = if let Some(bucket_size) = query.bucket_size {
        let bucket_size_ns = bucket_size * 1_000_000_000; // Convert seconds to nanoseconds

        // Group metrics by time bucket
        let mut buckets: HashMap<i64, Vec<&Metric>> = HashMap::new();
        for metric in &metrics {
            let bucket_timestamp = (metric.timestamp / bucket_size_ns) * bucket_size_ns;
            buckets.entry(bucket_timestamp).or_default().push(metric);
        }

        // Aggregate each bucket
        let mut time_buckets: Vec<TimeBucket> = buckets
            .into_iter()
            .map(|(timestamp, bucket_metrics)| {
                let (sum, count) = match query.function.as_str() {
                    "sum" => {
                        let mut sum = 0.0;
                        let mut count = 0;
                        for metric in bucket_metrics {
                            match &metric.metric_type {
                                MetricType::Gauge(v) => {
                                    sum += v;
                                    count += 1;
                                },
                                MetricType::Counter(v) => {
                                    sum += *v as f64;
                                    count += 1;
                                },
                                MetricType::Histogram { sum: s, .. } => {
                                    sum += s;
                                    count += 1;
                                },
                                MetricType::Summary { sum: s, .. } => {
                                    sum += s;
                                    count += 1;
                                },
                            }
                        }
                        (sum, count)
                    },
                    "avg" => {
                        let mut sum = 0.0;
                        let mut count = 0;
                        for metric in bucket_metrics {
                            match &metric.metric_type {
                                MetricType::Gauge(v) => {
                                    sum += v;
                                    count += 1;
                                },
                                MetricType::Counter(v) => {
                                    sum += *v as f64;
                                    count += 1;
                                },
                                MetricType::Histogram {
                                    sum: s, count: c, ..
                                } => {
                                    sum += s;
                                    count += *c as usize;
                                },
                                MetricType::Summary {
                                    sum: s, count: c, ..
                                } => {
                                    sum += s;
                                    count += *c as usize;
                                },
                            }
                        }
                        let avg = if count > 0 { sum / count as f64 } else { 0.0 };
                        (avg, count)
                    },
                    _ => (0.0, 0),
                };

                TimeBucket {
                    timestamp,
                    value: sum,
                    count,
                }
            })
            .collect();

        time_buckets.sort_by_key(|b| b.timestamp);

        AggregateResponse {
            buckets: Some(time_buckets),
            ..result
        }
    } else {
        result
    };

    Ok(Json(result))
}

/// Get time-series data for a specific metric
#[utoipa::path(
    get,
    path = "/api/metrics/{name}/timeseries",
    params(
        ("name" = String, Path, description = "Metric name"),
        ("start_time" = Option<i64>, Query, description = "Start time (nanoseconds since Unix epoch)"),
        ("end_time" = Option<i64>, Query, description = "End time (nanoseconds since Unix epoch)"),
        ("step" = Option<i64>, Query, description = "Time step in seconds (default: 60)")
    ),
    responses(
        (status = 200, description = "Time-series data points", body = Vec<TimeBucket>),
        (status = 404, description = "Metric not found", body = ErrorResponse),
        (status = 500, description = "Internal server error", body = ErrorResponse)
    ),
    tag = "metrics"
)]
pub async fn get_metric_timeseries(
    State(state): State<AppState>,
    axum::extract::Path(name): axum::extract::Path<String>,
    Query(query): Query<TimeseriesQuery>,
) -> Result<Json<Vec<TimeBucket>>, (StatusCode, Json<ErrorResponse>)> {
    // Check cache first
    let cache_key = QueryCache::make_key(&(&name, &query));
    if let Some(cached) = state.cache.metrics.get(&cache_key) {
        if let Ok(response) = serde_json::from_str(&cached) {
            return Ok(Json(response));
        }
    }

    // Build query parameters
    let mut params = QueryParams::default();
    if let Some(start) = query.start_time {
        params.start_time = Some(start);
    }
    if let Some(end) = query.end_time {
        params.end_time = Some(end);
    }

    // Query metrics from storage
    let metrics = state.storage.query_metrics(&params).await.map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ErrorResponse::storage_error(format!(
                "query metric timeseries: {}",
                e
            ))),
        )
    })?;

    // Filter by name
    let metrics: Vec<_> = metrics.into_iter().filter(|m| m.name == name).collect();

    // If time-filtered query is empty, check if metric exists at all (without time filter)
    if metrics.is_empty() {
        let all_params = QueryParams::default();
        let all_metrics = state
            .storage
            .query_metrics(&all_params)
            .await
            .map_err(|e| {
                (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(ErrorResponse::storage_error(format!(
                        "check metric existence: {}",
                        e
                    ))),
                )
            })?;
        let exists = all_metrics.iter().any(|m| m.name == name);
        if !exists {
            return Err((
                StatusCode::NOT_FOUND,
                Json(ErrorResponse::not_found(format!("Metric '{}'", name))),
            ));
        }
        // Metric exists but no data in the requested time window — return empty
        return Ok(Json(vec![]));
    }

    // Group by time buckets
    let step_seconds = query.step.unwrap_or(60);
    let bucket_size_ns = step_seconds * 1_000_000_000;

    let mut buckets: HashMap<i64, Vec<&Metric>> = HashMap::new();
    for metric in &metrics {
        let bucket_timestamp = (metric.timestamp / bucket_size_ns) * bucket_size_ns;
        buckets.entry(bucket_timestamp).or_default().push(metric);
    }

    // Calculate average value per bucket
    let mut time_buckets: Vec<TimeBucket> = buckets
        .into_iter()
        .map(|(timestamp, bucket_metrics)| {
            let mut sum = 0.0;
            let mut count = 0;

            for metric in bucket_metrics {
                match &metric.metric_type {
                    MetricType::Gauge(v) => {
                        sum += v;
                        count += 1;
                    },
                    MetricType::Counter(v) => {
                        sum += *v as f64;
                        count += 1;
                    },
                    MetricType::Histogram {
                        sum: s, count: c, ..
                    } => {
                        sum += s;
                        count += *c as usize;
                    },
                    MetricType::Summary {
                        sum: s, count: c, ..
                    } => {
                        sum += s;
                        count += *c as usize;
                    },
                }
            }

            let value = if count > 0 { sum / count as f64 } else { 0.0 };

            TimeBucket {
                timestamp,
                value,
                count,
            }
        })
        .collect();

    time_buckets.sort_by_key(|b| b.timestamp);

    // Cache the result
    if let Ok(json) = serde_json::to_string(&time_buckets) {
        state.cache.metrics.insert(cache_key, json);
    }

    Ok(Json(time_buckets))
}

/// Query parameters for time-series data
#[derive(Debug, Deserialize, Serialize, utoipa::IntoParams, utoipa::ToSchema)]
pub struct TimeseriesQuery {
    /// Start time (nanoseconds since Unix epoch)
    pub start_time: Option<i64>,
    /// End time (nanoseconds since Unix epoch)
    pub end_time: Option<i64>,
    /// Time step in seconds (default: 60)
    pub step: Option<i64>,
}

/// Export metrics as JSON
#[utoipa::path(
    get,
    path = "/api/metrics/export",
    params(MetricsQuery),
    responses(
        (status = 200, description = "Exported metrics in JSON format"),
        (status = 500, description = "Internal server error", body = ErrorResponse)
    ),
    tag = "metrics"
)]
pub async fn export_metrics(
    State(state): State<AppState>,
    Query(query): Query<MetricsQuery>,
) -> Result<impl IntoResponse, (StatusCode, Json<ErrorResponse>)> {
    // Build query parameters
    let mut params = QueryParams::default();

    if let Some(start) = query.start_time {
        params.start_time = Some(start);
    }
    if let Some(end) = query.end_time {
        params.end_time = Some(end);
    }

    // Query metrics from storage
    let metrics = state.storage.query_metrics(&params).await.map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ErrorResponse::storage_error(format!(
                "export metrics: {}",
                e
            ))),
        )
    })?;

    // Filter by name if specified
    let metrics: Vec<_> = if let Some(name_filter) = &query.name {
        metrics
            .into_iter()
            .filter(|m| m.name.contains(name_filter))
            .collect()
    } else {
        metrics
    };

    // Convert to JSON
    let json = serde_json::to_string_pretty(&metrics).map_err(|e| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            Json(ErrorResponse::internal_error(format!(
                "Failed to serialize metrics: {}",
                e
            ))),
        )
    })?;

    Ok((StatusCode::OK, [("Content-Type", "application/json")], json))
}