rs3gw 0.2.1

High-Performance AI/HPC Object Storage Gateway powered by scirs2-io
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
//! Observability API handlers for metrics, profiling, and anomaly detection
//!
//! This module provides REST API endpoints for accessing observability data:
//! - `/api/observability/profiling` - CPU, memory, and I/O profiling data
//! - `/api/observability/business-metrics` - Business KPI metrics
//! - `/api/observability/anomalies` - Detected performance anomalies
//! - `/api/observability/resources` - Resource manager statistics
//! - `/api/observability/health` - Comprehensive health check with all metrics

use axum::{
    extract::{Query, State},
    http::StatusCode,
    response::{IntoResponse, Json},
};
use serde::{Deserialize, Serialize};
use std::time::SystemTime;

use crate::AppState;

/// Query parameters for anomaly filtering
#[derive(Debug, Deserialize)]
pub struct AnomalyQuery {
    /// Filter by anomaly type
    pub anomaly_type: Option<String>,
    /// Filter by severity
    pub severity: Option<String>,
    /// Limit number of results
    pub limit: Option<usize>,
}

/// Query parameters for profiling data
#[derive(Debug, Deserialize)]
pub struct ProfilingQuery {
    /// Include pprof format export
    pub pprof: Option<bool>,
}

/// Profiling response with CPU, memory, and I/O stats
#[derive(Debug, Serialize)]
pub struct ProfilingResponse {
    pub timestamp: u64,
    pub cpu: CpuStatsJson,
    pub memory: MemoryStatsJson,
    pub io: IoStatsJson,
    pub pprof_available: bool,
}

#[derive(Debug, Serialize)]
pub struct CpuStatsJson {
    pub utilization_percent: f64,
    pub total_time_seconds: f64,
    pub user_time_seconds: f64,
    pub system_time_seconds: f64,
}

#[derive(Debug, Serialize)]
pub struct MemoryStatsJson {
    pub rss_bytes: u64,
    pub virtual_bytes: u64,
    pub peak_rss_bytes: u64,
}

#[derive(Debug, Serialize)]
pub struct IoStatsJson {
    pub read_operations: u64,
    pub write_operations: u64,
    pub read_bytes: u64,
    pub write_bytes: u64,
    pub avg_read_latency_ms: f64,
    pub avg_write_latency_ms: f64,
}

/// Business metrics response
#[derive(Debug, Serialize)]
pub struct BusinessMetricsResponse {
    pub timestamp: u64,
    pub storage_utilization: StorageUtilizationJson,
    pub data_transfer: DataTransferJson,
    pub request_patterns: RequestPatternsJson,
    pub user_activity: UserActivityJson,
    pub cost_estimation: CostEstimationJson,
}

#[derive(Debug, Serialize)]
pub struct StorageUtilizationJson {
    pub total_buckets: u64,
    pub total_objects: u64,
    pub total_size_bytes: u64,
    pub growth_rate_percent: f64,
}

#[derive(Debug, Serialize)]
pub struct DataTransferJson {
    pub upload_bytes_per_second: f64,
    pub download_bytes_per_second: f64,
    pub bandwidth_utilization_percent: f64,
    pub peak_upload_rate: f64,
    pub peak_download_rate: f64,
}

#[derive(Debug, Serialize)]
pub struct RequestPatternsJson {
    pub total_requests: u64,
    pub success_rate_percent: f64,
    pub error_rate_percent: f64,
    pub p50_latency_ms: f64,
    pub p95_latency_ms: f64,
    pub p99_latency_ms: f64,
}

#[derive(Debug, Serialize)]
pub struct UserActivityJson {
    pub active_users: u64,
    pub engagement_score: f64,
    pub top_users: Vec<String>,
}

#[derive(Debug, Serialize)]
pub struct CostEstimationJson {
    pub storage_cost_usd: f64,
    pub bandwidth_cost_usd: f64,
    pub request_cost_usd: f64,
    pub total_cost_usd: f64,
}

/// Anomaly response
#[derive(Debug, Serialize)]
pub struct AnomalyResponse {
    pub timestamp: u64,
    pub anomalies: Vec<AnomalyJson>,
    pub total_count: usize,
}

#[derive(Debug, Serialize)]
pub struct AnomalyJson {
    pub anomaly_type: String,
    pub severity: String,
    pub value: f64,
    pub threshold: f64,
    pub message: String,
    pub timestamp: u64,
}

/// Resource manager response
#[derive(Debug, Serialize)]
pub struct ResourceStatsResponse {
    pub timestamp: u64,
    pub cpu_utilization_percent: f64,
    pub memory_utilization_percent: f64,
    pub active_threads: usize,
    pub active_requests: usize,
    pub pending_requests: usize,
    pub total_requests: u64,
    pub successful_requests: u64,
    pub failed_requests: u64,
    pub success_rate_percent: f64,
    pub avg_latency_ms: f64,
    pub load_shedding_active: bool,
}

/// Comprehensive health check response
#[derive(Debug, Serialize)]
pub struct HealthCheckResponse {
    pub status: String,
    pub timestamp: u64,
    pub profiling: ProfilingResponse,
    pub resources: ResourceStatsResponse,
    pub anomalies_count: usize,
    pub critical_anomalies_count: usize,
}

/// GET /api/observability/profiling - Get profiling data
pub async fn get_profiling_data(
    State(_state): State<AppState>,
    Query(query): Query<ProfilingQuery>,
) -> impl IntoResponse {
    // Get profiling data from state if available
    // For now, create a mock response since profiler integration is optional
    let timestamp = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();

    let response = ProfilingResponse {
        timestamp,
        cpu: CpuStatsJson {
            utilization_percent: 0.0,
            total_time_seconds: 0.0,
            user_time_seconds: 0.0,
            system_time_seconds: 0.0,
        },
        memory: MemoryStatsJson {
            rss_bytes: 0,
            virtual_bytes: 0,
            peak_rss_bytes: 0,
        },
        io: IoStatsJson {
            read_operations: 0,
            write_operations: 0,
            read_bytes: 0,
            write_bytes: 0,
            avg_read_latency_ms: 0.0,
            avg_write_latency_ms: 0.0,
        },
        pprof_available: query.pprof.unwrap_or(false),
    };

    (StatusCode::OK, Json(response))
}

/// GET /api/observability/business-metrics - Get business metrics
pub async fn get_business_metrics(State(_state): State<AppState>) -> impl IntoResponse {
    let timestamp = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();

    let response = BusinessMetricsResponse {
        timestamp,
        storage_utilization: StorageUtilizationJson {
            total_buckets: 0,
            total_objects: 0,
            total_size_bytes: 0,
            growth_rate_percent: 0.0,
        },
        data_transfer: DataTransferJson {
            upload_bytes_per_second: 0.0,
            download_bytes_per_second: 0.0,
            bandwidth_utilization_percent: 0.0,
            peak_upload_rate: 0.0,
            peak_download_rate: 0.0,
        },
        request_patterns: RequestPatternsJson {
            total_requests: 0,
            success_rate_percent: 0.0,
            error_rate_percent: 0.0,
            p50_latency_ms: 0.0,
            p95_latency_ms: 0.0,
            p99_latency_ms: 0.0,
        },
        user_activity: UserActivityJson {
            active_users: 0,
            engagement_score: 0.0,
            top_users: Vec::new(),
        },
        cost_estimation: CostEstimationJson {
            storage_cost_usd: 0.0,
            bandwidth_cost_usd: 0.0,
            request_cost_usd: 0.0,
            total_cost_usd: 0.0,
        },
    };

    (StatusCode::OK, Json(response))
}

/// GET /api/observability/anomalies - Get detected anomalies
pub async fn get_anomalies(
    State(_state): State<AppState>,
    Query(_query): Query<AnomalyQuery>,
) -> impl IntoResponse {
    let timestamp = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();

    // For now, return empty anomaly list
    // This will be populated when anomaly detector is integrated into AppState
    let response = AnomalyResponse {
        timestamp,
        anomalies: Vec::new(),
        total_count: 0,
    };

    (StatusCode::OK, Json(response))
}

/// GET /api/observability/resources - Get resource manager stats
pub async fn get_resource_stats(State(_state): State<AppState>) -> impl IntoResponse {
    let timestamp = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();

    let response = ResourceStatsResponse {
        timestamp,
        cpu_utilization_percent: 0.0,
        memory_utilization_percent: 0.0,
        active_threads: 0,
        active_requests: 0,
        pending_requests: 0,
        total_requests: 0,
        successful_requests: 0,
        failed_requests: 0,
        success_rate_percent: 0.0,
        avg_latency_ms: 0.0,
        load_shedding_active: false,
    };

    (StatusCode::OK, Json(response))
}

/// GET /api/observability/health - Comprehensive health check
pub async fn get_comprehensive_health(State(_state): State<AppState>) -> impl IntoResponse {
    let timestamp = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .unwrap_or_default()
        .as_secs();

    let profiling = ProfilingResponse {
        timestamp,
        cpu: CpuStatsJson {
            utilization_percent: 0.0,
            total_time_seconds: 0.0,
            user_time_seconds: 0.0,
            system_time_seconds: 0.0,
        },
        memory: MemoryStatsJson {
            rss_bytes: 0,
            virtual_bytes: 0,
            peak_rss_bytes: 0,
        },
        io: IoStatsJson {
            read_operations: 0,
            write_operations: 0,
            read_bytes: 0,
            write_bytes: 0,
            avg_read_latency_ms: 0.0,
            avg_write_latency_ms: 0.0,
        },
        pprof_available: false,
    };

    let resources = ResourceStatsResponse {
        timestamp,
        cpu_utilization_percent: 0.0,
        memory_utilization_percent: 0.0,
        active_threads: 0,
        active_requests: 0,
        pending_requests: 0,
        total_requests: 0,
        successful_requests: 0,
        failed_requests: 0,
        success_rate_percent: 0.0,
        avg_latency_ms: 0.0,
        load_shedding_active: false,
    };

    let response = HealthCheckResponse {
        status: "healthy".to_string(),
        timestamp,
        profiling,
        resources,
        anomalies_count: 0,
        critical_anomalies_count: 0,
    };

    (StatusCode::OK, Json(response))
}

/// GET /api/observability/predictions/storage-growth - Get storage growth predictions
pub async fn get_storage_growth_prediction(State(state): State<AppState>) -> impl IntoResponse {
    match state.predictive_analytics.predict_storage_growth().await {
        Some(prediction) => (StatusCode::OK, Json(serde_json::json!(prediction))),
        None => (
            StatusCode::OK,
            Json(serde_json::json!({
                "current_size": 0,
                "predicted_7d": 0,
                "predicted_30d": 0,
                "predicted_90d": 0,
                "daily_growth_rate": 0.0,
                "confidence": 0.0,
                "trend": "Stable",
                "note": "Insufficient data for prediction (minimum 10 data points required)"
            })),
        ),
    }
}

/// GET /api/observability/predictions/access-patterns - Get access pattern predictions
pub async fn get_access_pattern_prediction(State(state): State<AppState>) -> impl IntoResponse {
    match state.predictive_analytics.predict_access_patterns().await {
        Some(prediction) => (StatusCode::OK, Json(serde_json::json!(prediction))),
        None => (
            StatusCode::OK,
            Json(serde_json::json!({
                "current_rps": 0.0,
                "predicted_1h": 0.0,
                "predicted_24h": 0.0,
                "expected_peak": 0.0,
                "peak_hour": 0,
                "pattern_type": "Stable",
                "confidence": 0.0,
                "note": "Insufficient data for prediction (minimum 24 data points required)"
            })),
        ),
    }
}

/// GET /api/observability/predictions/costs - Get cost forecasts
pub async fn get_cost_forecast(State(state): State<AppState>) -> impl IntoResponse {
    match state.predictive_analytics.forecast_costs().await {
        Some(forecast) => (StatusCode::OK, Json(serde_json::json!(forecast))),
        None => (
            StatusCode::OK,
            Json(serde_json::json!({
                "current_monthly_cost": 0.0,
                "predicted_next_month": 0.0,
                "predicted_3_months": 0.0,
                "predicted_6_months": 0.0,
                "storage_cost": 0.0,
                "bandwidth_cost": 0.0,
                "request_cost": 0.0,
                "growth_rate_percent": 0.0,
                "note": "Insufficient data for forecast"
            })),
        ),
    }
}

/// GET /api/observability/predictions/capacity - Get capacity planning recommendations
pub async fn get_capacity_recommendations(State(state): State<AppState>) -> impl IntoResponse {
    match state.predictive_analytics.capacity_recommendations().await {
        Some(recommendation) => (StatusCode::OK, Json(serde_json::json!(recommendation))),
        None => (
            StatusCode::OK,
            Json(serde_json::json!({
                "current_utilization": 0.0,
                "predicted_30d_utilization": 0.0,
                "predicted_90d_utilization": 0.0,
                "days_until_threshold": null,
                "recommendation": "NoActionNeeded",
                "additional_capacity_needed": null,
                "urgency": "Low",
                "note": "Insufficient data for capacity planning"
            })),
        ),
    }
}

// Integration tests for observability handlers are in tests/observability_tests.rs