-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmock_convertor.rs
More file actions
160 lines (140 loc) · 4.58 KB
/
Copy pathmock_convertor.rs
File metadata and controls
160 lines (140 loc) · 4.58 KB
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
use axum::{
extract::{Query, State},
http::StatusCode,
response::Json,
routing::get,
Router,
};
use chrono::Utc;
use serde::{Deserialize, Serialize};
use serde_yaml::Value;
use std::net::SocketAddr;
use tokio::signal;
#[derive(Deserialize, Debug)]
struct HealthQuery {
environment: String,
service: String,
#[serde(default)]
_from: String,
#[serde(default)]
_to: String,
}
/// Structure of the response which waits reporter.rs
#[derive(Serialize, Debug)]
struct ServiceHealthPoint {
ts: u32,
value: u8,
#[serde(default)]
triggered: Vec<String>,
#[serde(default)]
metric_value: Option<f64>,
}
#[derive(Serialize, Debug)]
struct ServiceHealthResponse {
name: String,
service_category: String,
environment: String,
metrics: Vec<ServiceHealthPoint>,
}
/// Simulated metric generator that autonomously produces metric data
#[derive(Clone)]
struct MetricGenerator {}
impl MetricGenerator {
fn new() -> Self {
MetricGenerator {}
}
/// Generate metrics based on time to simulate autonomous failures.
fn generate_metrics(&self, environment: &str, service: &str) -> (u8, Vec<String>, Option<f64>) {
match (environment, service) {
("production_eu-de", "as") => {
// AS: api_down (weight 2)
// Always failing with 100% failure rate
(2, vec!["as.api_down".to_string()], Some(100.0))
}
("production_eu-de", "deh") => {
// DEH: api_slow (weight 1)
// Always failing with response time above threshold
(1, vec!["deh.api_slow".to_string()], Some(1500.0))
}
("production_eu-de", "css") => {
// CSS: api_down (weight 2)
// Always failing with 100% failure rate
(2, vec!["css.api_down".to_string()], Some(100.0))
}
_ => {
// Unknown service - return OK
(0, vec![], Some(0.0))
}
}
}
}
#[tokio::main]
async fn main() {
let health_config = load_health_metrics("conf.d/health_metrics.yaml")
.expect("Failed to load health_metrics.yaml");
let metric_generator = MetricGenerator::new();
let app = Router::new()
.route("/api/v1/health", get(health_handler))
.with_state((metric_generator, health_config));
let addr = SocketAddr::from(([127, 0, 0, 1], 3005));
println!("Mock convertor listening on {}", addr);
println!("Autonomously simulating component failures...");
axum::Server::bind(&addr)
.serve(app.into_make_service())
.with_graceful_shutdown(shutdown_signal())
.await
.unwrap();
}
async fn health_handler(
State((metric_generator, health_config)): State<(MetricGenerator, Value)>,
Query(params): Query<HealthQuery>,
) -> (StatusCode, Json<ServiceHealthResponse>) {
println!(
"Request: environment={}, service={}",
params.environment, params.service
);
// Get service configuration from health_metrics
let service_config = health_config
.get("health_metrics")
.and_then(|hm| hm.get(¶ms.service));
// Generate autonomous metric data based on time
let (status_weight, triggered_metrics, raw_metric_value) =
metric_generator.generate_metrics(¶ms.environment, ¶ms.service);
let service_category = if let Some(config) = service_config {
config
.get("category")
.and_then(|c| c.as_str())
.unwrap_or("unknown")
.to_string()
} else {
"unknown".to_string()
};
let metric_time = Utc::now().timestamp() as u32;
let response = ServiceHealthResponse {
name: params.service.clone(),
service_category,
environment: params.environment.clone(),
metrics: vec![ServiceHealthPoint {
ts: metric_time,
value: status_weight,
triggered: triggered_metrics.clone(),
metric_value: raw_metric_value,
}],
};
println!(
"Response: status={}, triggered={:?}, metric_value={:?}",
status_weight, triggered_metrics, raw_metric_value
);
(StatusCode::OK, Json(response))
}
fn load_health_metrics(path: &str) -> Result<Value, Box<dyn std::error::Error>> {
let content = std::fs::read_to_string(path)?;
let config: Value = serde_yaml::from_str(&content)?;
Ok(config)
}
async fn shutdown_signal() {
signal::ctrl_c()
.await
.expect("failed to install Ctrl+C handler");
println!("Signal received, shutting down mock server.");
}