1#![allow(missing_docs)]
7
8use parking_lot::{Mutex, RwLock};
9use std::sync::atomic::{AtomicU64, Ordering};
10
11#[derive(Default)]
13pub struct MetricsRegistry {
14 counters: RwLock<Vec<Counter>>,
15 gauges: RwLock<Vec<Gauge>>,
16 histograms: RwLock<Vec<Histogram>>,
17}
18
19impl MetricsRegistry {
20 pub fn new() -> Self {
22 Self::default()
23 }
24
25 pub fn counter(
27 &self,
28 name: &'static str,
29 help: &'static str,
30 labels: &[(&'static str, &'static str)],
31 ) -> CounterHandle {
32 let mut counters = self.counters.write();
33 let id = counters.len();
34 counters.push(Counter {
35 name: name.into(),
36 help: help.into(),
37 labels: labels.into(),
38 value: AtomicU64::new(0),
39 });
40 CounterHandle { id }
41 }
42
43 pub fn gauge(&self, name: &'static str, help: &'static str, initial: f64) -> GaugeHandle {
45 let mut gauges = self.gauges.write();
46 let id = gauges.len();
47 gauges.push(Gauge {
48 name: name.into(),
49 help: help.into(),
50 value: Mutex::new(initial),
51 });
52 GaugeHandle { id }
53 }
54
55 pub fn histogram(
57 &self,
58 name: &'static str,
59 help: &'static str,
60 buckets: Vec<f64>,
61 ) -> HistogramHandle {
62 let mut histograms = self.histograms.write();
63 let id = histograms.len();
64 let counts: Vec<usize> = vec![0; buckets.len() + 1];
65 histograms.push(Histogram {
66 name: name.into(),
67 help: help.into(),
68 buckets: buckets.clone(),
69 counts: RwLock::new(counts),
70 sum: Mutex::new(0.0),
71 count: Mutex::new(0u64),
72 });
73 HistogramHandle { id, buckets }
74 }
75
76 pub fn export(&self) -> String {
78 let mut out = String::new();
79
80 {
82 let counters = self.counters.read();
83 for c in counters.iter() {
84 out.push_str(&format!("# HELP {} {}\n", c.name, c.help));
85 out.push_str(&format!("# TYPE {} counter\n", c.name));
86 let value = c.value.load(Ordering::Relaxed);
87 let labels_str = if c.labels.is_empty() {
88 String::new()
89 } else {
90 format!(
91 "{{{}}}",
92 c.labels
93 .iter()
94 .map(|(k, v)| format!("{}=\"{}\"", k, v))
95 .collect::<Vec<_>>()
96 .join(",")
97 )
98 };
99 out.push_str(&format!("{}{} {}\n", c.name, labels_str, value));
100 }
101 }
102
103 {
105 let gauges = self.gauges.read();
106 for g in gauges.iter() {
107 out.push_str(&format!("# HELP {} {}\n", g.name, g.help));
108 out.push_str(&format!("# TYPE {} gauge\n", g.name));
109 let value = *g.value.lock();
110 out.push_str(&format!("{} {}\n", g.name, value));
111 }
112 }
113
114 {
116 let histograms = self.histograms.read();
117 for h in histograms.iter() {
118 out.push_str(&format!("# HELP {} {}\n", h.name, h.help));
119 out.push_str(&format!("# TYPE {} histogram\n", h.name));
120 let sum = *h.sum.lock();
121 let count = *h.count.lock();
122 let bucket_values = h.buckets.clone();
123 let counts = h.counts.read();
124 let mut cumulative = 0usize;
125 for (i, _) in bucket_values.iter().enumerate() {
126 cumulative += counts[i];
127 let boundary = bucket_values[i];
128 out.push_str(&format!(
129 "{}{{le=\"{}\"}} {}\n",
130 h.name, boundary, cumulative
131 ));
132 }
133 out.push_str(&format!("{}{{le=\"+Inf\"}} {}\n", h.name, cumulative));
135 out.push_str(&format!("{}_sum {} \n", h.name, sum));
136 out.push_str(&format!("{}_count {} \n", h.name, count));
137 }
138 }
139
140 out
141 }
142}
143
144static REGISTRY: std::sync::OnceLock<MetricsRegistry> = std::sync::OnceLock::new();
146
147pub fn registry() -> &'static MetricsRegistry {
149 REGISTRY.get_or_init(MetricsRegistry::new)
150}
151
152#[derive(Clone)]
153pub struct CounterHandle {
154 id: usize,
155}
156
157impl CounterHandle {
158 pub fn inc(&self) {
160 let r = registry();
161 let counters = r.counters.read();
162 if let Some(c) = counters.get(self.id) {
163 c.value.fetch_add(1, Ordering::Relaxed);
164 }
165 }
166}
167
168#[derive(Clone)]
169pub struct GaugeHandle {
170 id: usize,
171}
172
173impl GaugeHandle {
174 pub fn set(&self, v: f64) {
176 let r = registry();
177 let gauges = r.gauges.read();
178 if let Some(g) = gauges.get(self.id) {
179 *g.value.lock() = v;
180 }
181 }
182
183 pub fn inc(&self) {
185 let r = registry();
186 let gauges = r.gauges.read();
187 if let Some(g) = gauges.get(self.id) {
188 let mut val = g.value.lock();
189 *val += 1.0;
190 }
191 }
192
193 pub fn dec(&self) {
195 let r = registry();
196 let gauges = r.gauges.read();
197 if let Some(g) = gauges.get(self.id) {
198 let mut val = g.value.lock();
199 *val -= 1.0;
200 }
201 }
202}
203
204#[derive(Clone)]
205pub struct HistogramHandle {
206 id: usize,
207 buckets: Vec<f64>,
208}
209
210impl HistogramHandle {
211 pub fn observe(&self, value: f64) {
213 let r = registry();
214 let histograms = r.histograms.read();
215 if let Some(h) = histograms.get(self.id) {
216 {
217 let mut sum = h.sum.lock();
218 *sum += value;
219 }
220 {
221 let mut count = h.count.lock();
222 *count += 1;
223 }
224 {
225 let mut counts = h.counts.write();
226 for (i, boundary) in self.buckets.iter().enumerate() {
227 if value <= *boundary {
228 counts[i] += 1;
229 }
230 }
231 counts[self.buckets.len()] += 1;
233 }
234 }
235 }
236}
237
238struct Counter {
239 name: String,
240 help: String,
241 labels: Vec<(&'static str, &'static str)>,
242 value: AtomicU64,
243}
244
245struct Gauge {
246 name: String,
247 help: String,
248 value: Mutex<f64>,
249}
250
251struct Histogram {
252 name: String,
253 help: String,
254 buckets: Vec<f64>,
255 counts: RwLock<Vec<usize>>,
256 sum: Mutex<f64>,
257 count: Mutex<u64>,
258}
259
260#[derive(Clone)]
262pub struct MetricsHandles {
263 pub agents_forked: CounterHandle,
264 pub agents_completed: CounterHandle,
265 pub agents_failed: CounterHandle,
266 pub orch_duration: HistogramHandle,
267 pub messages: CounterHandle,
268}
269
270impl MetricsHandles {
271 pub fn inc_agents_forked(&self) {
273 self.agents_forked.inc();
274 }
275
276 pub fn inc_agents_completed(&self) {
278 self.agents_completed.inc();
279 }
280
281 pub fn inc_agents_failed(&self) {
283 self.agents_failed.inc();
284 }
285
286 pub fn inc_messages(&self) {
288 self.messages.inc();
289 }
290
291 pub fn observe_orch_duration(&self, value: f64) {
293 self.orch_duration.observe(value);
294 }
295}
296
297static METRICS: std::sync::OnceLock<MetricsHandles> = std::sync::OnceLock::new();
299
300pub fn get_metrics() -> &'static MetricsHandles {
302 METRICS.get_or_init(|| {
303 let r = registry();
304 MetricsHandles {
305 agents_forked: r.counter("oxios_agents_forked_total", "Total agents forked", &[]),
306 agents_completed: r.counter(
307 "oxios_agents_completed_total",
308 "Total agents completed",
309 &[],
310 ),
311 agents_failed: r.counter("oxios_agents_failed_total", "Total agents failed", &[]),
312 orch_duration: r.histogram(
313 "oxios_orchestration_duration_seconds",
314 "Orchestration duration",
315 vec![0.1, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0],
316 ),
317 messages: r.counter("oxios_messages_processed_total", "Messages processed", &[]),
318 }
319 })
320}
321
322pub fn register_builtin_metrics() {
324 let r = registry();
325
326 r.counter("oxios_agents_forked_total", "Total agents forked", &[]);
328 r.gauge("oxios_agents_running", "Currently running agents", 0.0);
329 r.counter(
330 "oxios_agents_completed_total",
331 "Total agents completed",
332 &[],
333 );
334 r.counter("oxios_agents_failed_total", "Total agents failed", &[]);
335
336 r.counter(
338 "oxios_messages_processed_total",
339 "User messages processed",
340 &[],
341 );
342 r.histogram(
343 "oxios_orchestration_duration_seconds",
344 "Full orchestration duration",
345 vec![0.1, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0, 60.0],
346 );
347 r.histogram(
348 "oxios_phase_duration_seconds",
349 "Phase duration",
350 vec![0.01, 0.05, 0.1, 0.5, 1.0, 2.5, 5.0, 10.0],
351 );
352
353 r.counter("oxios_llm_calls_total", "LLM API calls", &[]);
355 r.histogram(
356 "oxios_llm_duration_seconds",
357 "LLM call duration",
358 vec![0.1, 0.5, 1.0, 2.5, 5.0, 10.0, 30.0],
359 );
360 r.counter("oxios_llm_errors_total", "LLM API errors", &[]);
361
362 r.counter("oxios_tool_calls_total", "Tool calls", &[]);
364 r.histogram(
365 "oxios_tool_duration_seconds",
366 "Tool call duration",
367 vec![0.01, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0],
368 );
369 r.counter("oxios_tool_errors_total", "Tool errors", &[]);
370
371 r.gauge("oxios_memory_entries_total", "Total memory entries", 0.0);
373 r.counter("oxios_memory_recall_total", "Memory recall operations", &[]);
374
375 r.counter("oxios_exec_total", "Exec calls", &[]);
377 r.histogram(
378 "oxios_exec_duration_seconds",
379 "Exec duration",
380 vec![0.1, 0.5, 1.0, 5.0, 10.0, 30.0],
381 );
382
383 r.gauge("oxios_active_sessions", "Active sessions", 0.0);
385
386 let _ = get_metrics();
388}