swadhinbiswas WIP save-point: production hardening, H3 removal, fmt gate, and accumulated phase work · 7/15/2026
2080d40
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
/// Alert severity levels.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AlertSeverity {
Info = 0,
Warning = 1,
Critical = 2,
}
impl std::fmt::Display for AlertSeverity {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
AlertSeverity::Info => write!(f, "info"),
AlertSeverity::Warning => write!(f, "warning"),
AlertSeverity::Critical => write!(f, "critical"),
}
}
}
/// Supported alert notification channel types.
#[derive(Debug, Clone)]
pub enum AlertChannel {
Slack,
PagerDuty,
Generic,
}
/// Configuration for alerting.
#[derive(Debug, Clone)]
pub struct AlertingConfig {
pub webhook_url: Option<String>,
pub min_severity: AlertSeverity,
pub channel: AlertChannel,
pub app_name: String,
}
impl Default for AlertingConfig {
fn default() -> Self {
Self {
webhook_url: None,
min_severity: AlertSeverity::Warning,
channel: AlertChannel::Generic,
app_name: "justapi".to_string(),
}
}
}
impl AlertingConfig {
pub fn new(webhook_url: &str, _channel: AlertChannel) -> Self {
Self { webhook_url: Some(webhook_url.to_string()), ..Default::default() }
}
/// Send an alert. When a webhook_url is configured, dispatches to the
/// appropriate channel. Otherwise, logs the alert at the appropriate level.
pub async fn send_alert(&self, severity: AlertSeverity, message: &str) {
if (severity as u8) < (self.min_severity as u8) {
return;
}
let msg = format!("[{}] {}: {}", self.app_name, severity, message);
match severity {
AlertSeverity::Info => tracing::info!("{}", msg),
AlertSeverity::Warning => tracing::warn!("{}", msg),
AlertSeverity::Critical => tracing::error!("{}", msg),
}
// If a webhook is configured, attempt to deliver
if let Some(ref url) = self.webhook_url {
let payload = match self.channel {
AlertChannel::Slack => build_slack_payload(&self.app_name, &severity, message),
AlertChannel::PagerDuty => {
build_pagerduty_payload(&self.app_name, &severity, message)
}
AlertChannel::Generic => build_generic_payload(&self.app_name, &severity, message),
};
if let Err(e) = post_webhook(url, &payload).await {
tracing::warn!("Failed to send webhook alert: {}", e);
}
}
}
}
fn build_slack_payload(app: &str, severity: &AlertSeverity, message: &str) -> String {
let color = match severity {
AlertSeverity::Info => "#36a64f",
AlertSeverity::Warning => "#ffcc00",
AlertSeverity::Critical => "#ff0000",
};
serde_json::json!({
"attachments": [{
"color": color,
"title": format!("[{}] {} Alert", app, severity),
"text": message,
"ts": unix_timestamp(),
}]
})
.to_string()
}
fn build_pagerduty_payload(app: &str, severity: &AlertSeverity, message: &str) -> String {
let sev = match severity {
AlertSeverity::Info => "info",
AlertSeverity::Warning => "warning",
AlertSeverity::Critical => "critical",
};
serde_json::json!({
"routing_key": "webhook",
"event_action": "trigger",
"payload": {
"summary": message,
"source": app,
"severity": sev,
"custom_details": {
"app": app,
"message": message,
}
}
})
.to_string()
}
fn build_generic_payload(app: &str, severity: &AlertSeverity, message: &str) -> String {
let mut m = serde_json::Map::new();
m.insert("app".into(), serde_json::Value::String(app.into()));
m.insert("severity".into(), serde_json::Value::String(severity.to_string()));
m.insert("message".into(), serde_json::Value::String(message.into()));
m.insert("timestamp".into(), serde_json::Value::Number(unix_timestamp().into()));
serde_json::to_string(&m).unwrap_or_else(|_| "{}".to_string())
}
/// Simple HTTP POST to a webhook URL. Supports HTTP only (not HTTPS).
/// For HTTPS webhooks, use a reverse proxy or local HTTP gateway.
async fn post_webhook(url: &str, body: &str) -> anyhow::Result<()> {
use tokio::io::AsyncWriteExt;
let uri: hyper::http::Uri = url.parse()?;
let scheme = uri.scheme_str().unwrap_or("http");
if scheme != "http" {
return Err(anyhow::anyhow!("webhook URL scheme '{}' not supported (use HTTP)", scheme));
}
let host = uri.host().ok_or_else(|| anyhow::anyhow!("webhook URL missing host"))?;
let port = uri.port_u16().unwrap_or(80);
let path = uri.path_and_query().map(|pq| pq.as_str()).unwrap_or("/");
let mut stream = tokio::net::TcpStream::connect((host, port)).await?;
let request = format!(
"POST {path} HTTP/1.1\r\n\
Host: {host}\r\n\
Content-Type: application/json\r\n\
Content-Length: {len}\r\n\
Connection: close\r\n\
\r\n\
{body}",
path = path,
host = host,
len = body.len(),
body = body,
);
stream.write_all(request.as_bytes()).await?;
stream.flush().await?;
Ok(())
}
fn unix_timestamp() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_build_slack_payload() {
let payload = build_slack_payload("test-app", &AlertSeverity::Critical, "something broke");
assert!(payload.contains("test-app"));
assert!(payload.contains("critical"));
assert!(payload.contains("something broke"));
}
#[test]
fn test_build_pagerduty_payload() {
let payload = build_pagerduty_payload("test-app", &AlertSeverity::Warning, "high latency");
assert!(payload.contains("warning"));
assert!(payload.contains("high latency"));
}
#[test]
fn test_severity_display() {
assert_eq!(AlertSeverity::Info.to_string(), "info");
assert_eq!(AlertSeverity::Critical.to_string(), "critical");
}
#[test]
fn test_severity_filtering() {
let config = AlertingConfig::default();
// Info should be filtered out since default min is Warning
assert!((AlertSeverity::Info as u8) < (config.min_severity as u8));
assert!((AlertSeverity::Warning as u8) >= (config.min_severity as u8));
assert!((AlertSeverity::Critical as u8) >= (config.min_severity as u8));
}
}