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
// /Users/snm/Equicom/workspace/NS/crates/moniof/src/services/http.rs
use crate::config::{MoniOFConfig, global};
use crate::core::stats::QueryStatsHandle;
use crate::core::task_ctx::MONIOF_HANDLE;
use crate::observability::{prom, slack, of};
use actix_web::{
body::MessageBody,
dev::{Service, ServiceRequest, ServiceResponse, Transform},
http::header::{HeaderName, HeaderValue},
Error,
};
use futures_util::future::{ready, LocalBoxFuture, Ready};
use std::{
rc::Rc,
task::{Context, Poll},
time::Instant,
};
use tracing;
pub struct MoniOF {
cfg: MoniOFConfig,
}
impl MoniOF {
pub fn new() -> Self {
Self {
cfg: MoniOFConfig::default(),
}
}
pub fn with_config(cfg: MoniOFConfig) -> Self {
Self { cfg }
}
}
impl<S, B> Transform<S, ServiceRequest> for MoniOF
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
B: MessageBody + 'static,
{
type Response = ServiceResponse<B>;
type Error = Error;
type Transform = MoniOFMiddleware<S>;
type InitError = ();
type Future = Ready<Result<Self::Transform, Self::InitError>>;
fn new_transform(&self, service: S) -> Self::Future {
prom::init_prometheus();
ready(Ok(MoniOFMiddleware {
service: Rc::new(service),
cfg: self.cfg.clone(),
}))
}
}
pub struct MoniOFMiddleware<S> {
pub(crate) service: Rc<S>,
pub(crate) cfg: MoniOFConfig,
}
impl<S, B> Service<ServiceRequest> for MoniOFMiddleware<S>
where
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
B: MessageBody + 'static,
{
type Response = ServiceResponse<B>;
type Error = Error;
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
fn poll_ready(&self, ctx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.service.poll_ready(ctx)
}
fn call(&self, req: ServiceRequest) -> Self::Future {
let svc = self.service.clone();
let cfg = self.cfg.clone();
// capture method for metrics before move
let method = req.method().as_str().to_string();
prom::inc_inflight();
let req_start = Instant::now();
Box::pin(async move {
// per-request query stats handle
let handle = QueryStatsHandle::new();
let handle_for_read = handle.clone();
// install task-local context so mark/mark_latency work
let mut res = MONIOF_HANDLE
.scope(handle, async move {
// inner service call returns Result<ServiceResponse<B>, Error>
svc.call(req).await
})
.await?; // now `?` applies to Result<_, Error>
let req_duration_s = req_start.elapsed().as_secs_f64();
prom::dec_inflight();
// --------------------------
// Read stats for this request
// --------------------------
let stats = handle_for_read.0.lock();
let total = stats.total;
let elapsed_ms = stats.elapsed().whole_milliseconds();
let db_total_ms = stats.total_db_latency_ms;
// most-repeated key (by count)
let mut worst_count: Option<(&String, &usize)> = None;
for (k, v) in &stats.per_key {
if worst_count.map(|(_, c)| v > c).unwrap_or(true) {
worst_count = Some((k, v));
}
}
// slowest key (by max latency)
let mut slowest_key: Option<(&String, &u128)> = None;
for (k, v) in &stats.per_key_max_latency_ms {
if slowest_key.map(|(_, m)| v > m).unwrap_or(true) {
slowest_key = Some((k, v));
}
}
// OF-style / OF-like N+1 suspects (via `of` module)
let n_plus_one_suspects = of::find_suspects(&stats, &cfg);
let status = res.status().as_u16();
prom::observe_request(
&method,
status,
req_duration_s,
(db_total_ms as f64) / 1000.0,
);
// --------------------------
// Response headers
// --------------------------
if cfg.add_response_headers {
let headers = res.headers_mut();
let mut put = |name: &'static str, val: String| {
let name = HeaderName::from_static(name);
if let Ok(hv) = HeaderValue::from_str(&val) {
headers.insert(name, hv);
}
};
put("x-moniof-total", total.to_string());
put("x-moniof-elapsed-ms", elapsed_ms.to_string());
put("x-moniof-db-total-ms", db_total_ms.to_string());
if let Some((k, v)) = slowest_key.as_ref() {
put("x-moniof-slowest-key", (*k).to_string());
put("x-moniof-slowest-latency-ms", (**v).to_string());
}
if cfg.of_mode && !n_plus_one_suspects.is_empty() {
if let Some(top) = n_plus_one_suspects.first() {
put("x-moniof-n-plus-one-key", top.key.clone());
put("x-moniof-n-plus-one-count", top.count.to_string());
put(
"x-moniof-n-plus-one-total-ms",
top.total_latency_ms.to_string(),
);
}
}
}
// --------------------------
// Warnings + Slack alerts (OF-style)
// --------------------------
if cfg.log_warnings {
let mut alerted = false;
// High total query count (possible N+1 overall)
if total > cfg.max_total {
alerted = true;
tracing::warn!(
target = "moniof",
total,
max_total = cfg.max_total,
elapsed_ms,
db_total_ms,
"High DB query count (possible N+1)"
);
}
// Worst key by count (single key repeated a lot)
if let Some((k, v)) = worst_count {
if *v > cfg.max_same_key {
alerted = true;
tracing::warn!(
target = "moniof",
key = %k,
count = %v,
max_same_key = cfg.max_same_key,
"Repeated same DB key (N+1 likely)"
);
}
}
// High cumulative DB latency
if let Some(th) = cfg.warn_total_db_latency_ms {
if db_total_ms >= th {
alerted = true;
tracing::warn!(
target = "moniof",
db_total_ms,
threshold = th,
"High cumulative DB latency in request"
);
}
}
// Suspiciously *low* DB latency (instrumentation/cache sanity)
if let Some(low) = cfg.warn_low_total_db_latency_ms {
if total > 0 && db_total_ms <= low {
alerted = true;
tracing::warn!(
target = "moniof",
total,
db_total_ms,
threshold = low,
"Suspiciously LOW cumulative DB latency (check instrumentation or cache?)"
);
}
}
// Explicit N+1 suspects (OF-style)
if cfg.of_mode && !n_plus_one_suspects.is_empty() {
alerted = true;
for s in &n_plus_one_suspects {
tracing::warn!(
target = "moniof::of",
key = %s.key,
count = %s.count,
total_latency_ms = %s.total_latency_ms,
"Possible N+1 detected (OF-like)"
);
}
}
// Send Slack if any alert fired
if alerted {
let g = global();
if let Some(hook) = g.slack_webhook {
let mut lines = vec![
"⚠️ *moniOF alert*".to_string(),
format!("• status: {}", status),
format!("• method: {}", method),
format!("• total queries: {}", total),
format!("• req elapsed: {:.3}s", req_duration_s),
format!("• db total latency: {} ms", db_total_ms),
];
if let Some((k, v)) = slowest_key.as_ref() {
lines.push(format!("• slowest key: `{}` ({} ms)", k, v));
}
if let Some((k, v)) = worst_count.as_ref() {
lines.push(format!("• worst key (count): `{}` ×{}", k, v));
}
if cfg.of_mode && !n_plus_one_suspects.is_empty() {
lines.push("• *N+1 suspects* (OF-like):".to_string());
for s in &n_plus_one_suspects {
lines.push(format!(
" ↳ `{}` — {}× ({} ms total)",
s.key, s.count, s.total_latency_ms
));
}
}
tokio::spawn(slack::notify(Some(hook), lines.join("\n")));
}
}
}
Ok(res)
})
}
}