1use candid::CandidType;
6use canic_cdk::utils::time::now_millis;
7use serde::{Deserialize, Serialize};
8use std::{cell::RefCell, cmp::Ordering, collections::BTreeMap};
9
10#[derive(CandidType, Clone, Debug, Deserialize, Serialize)]
15pub struct EventState {
16 pub ops: EventOps,
17 pub perf: EventPerf,
18 pub entities: BTreeMap<String, EntityCounters>,
19 pub window_start_ms: u64,
20}
21
22impl Default for EventState {
23 fn default() -> Self {
24 Self {
25 ops: EventOps::default(),
26 perf: EventPerf::default(),
27 entities: BTreeMap::new(),
28 window_start_ms: now_millis(),
29 }
30 }
31}
32
33#[derive(CandidType, Clone, Debug, Default, Deserialize, Serialize)]
40pub struct EventOps {
41 pub load_calls: u64,
43 pub save_calls: u64,
44 pub delete_calls: u64,
45
46 pub plan_index: u64,
48 pub plan_keys: u64,
49 pub plan_range: u64,
50 pub plan_full_scan: u64,
51
52 pub rows_loaded: u64,
54 pub rows_scanned: u64,
55 pub rows_deleted: u64,
56
57 pub index_inserts: u64,
59 pub index_removes: u64,
60 pub reverse_index_inserts: u64,
61 pub reverse_index_removes: u64,
62 pub relation_reverse_lookups: u64,
63 pub relation_delete_blocks: u64,
64 pub unique_violations: u64,
65}
66
67#[derive(CandidType, Clone, Debug, Default, Deserialize, Serialize)]
72pub struct EntityCounters {
73 pub load_calls: u64,
74 pub save_calls: u64,
75 pub delete_calls: u64,
76 pub rows_loaded: u64,
77 pub rows_scanned: u64,
78 pub rows_deleted: u64,
79 pub index_inserts: u64,
80 pub index_removes: u64,
81 pub reverse_index_inserts: u64,
82 pub reverse_index_removes: u64,
83 pub relation_reverse_lookups: u64,
84 pub relation_delete_blocks: u64,
85 pub unique_violations: u64,
86}
87
88#[derive(CandidType, Clone, Debug, Default, Deserialize, Serialize)]
95pub struct EventPerf {
96 pub load_inst_total: u128,
98 pub save_inst_total: u128,
99 pub delete_inst_total: u128,
100
101 pub load_inst_max: u64,
103 pub save_inst_max: u64,
104 pub delete_inst_max: u64,
105}
106
107thread_local! {
108 static EVENT_STATE: RefCell<EventState> = RefCell::new(EventState::default());
109}
110
111pub(crate) fn with_state<R>(f: impl FnOnce(&EventState) -> R) -> R {
113 EVENT_STATE.with(|m| f(&m.borrow()))
114}
115
116pub(crate) fn with_state_mut<R>(f: impl FnOnce(&mut EventState) -> R) -> R {
118 EVENT_STATE.with(|m| f(&mut m.borrow_mut()))
119}
120
121pub fn reset() {
123 with_state_mut(|m| *m = EventState::default());
124}
125
126pub fn reset_all() {
128 reset();
129}
130
131#[allow(clippy::missing_const_for_fn)]
133pub fn add_instructions(total: &mut u128, max: &mut u64, delta_inst: u64) {
134 *total = total.saturating_add(u128::from(delta_inst));
135 if delta_inst > *max {
136 *max = delta_inst;
137 }
138}
139
140#[derive(CandidType, Clone, Debug, Default, Deserialize, Serialize)]
146pub struct EventReport {
147 pub counters: Option<EventState>,
149 pub entity_counters: Vec<EntitySummary>,
151}
152
153#[derive(CandidType, Clone, Debug, Default, Deserialize, Serialize)]
158pub struct EntitySummary {
159 pub path: String,
160 pub load_calls: u64,
161 pub delete_calls: u64,
162 pub rows_loaded: u64,
163 pub rows_scanned: u64,
164 pub rows_deleted: u64,
165 pub avg_rows_per_load: f64,
166 pub avg_rows_scanned_per_load: f64,
167 pub avg_rows_per_delete: f64,
168 pub index_inserts: u64,
169 pub index_removes: u64,
170 pub reverse_index_inserts: u64,
171 pub reverse_index_removes: u64,
172 pub relation_reverse_lookups: u64,
173 pub relation_delete_blocks: u64,
174 pub unique_violations: u64,
175}
176
177#[must_use]
179#[allow(clippy::cast_precision_loss)]
180pub fn report() -> EventReport {
181 report_window_start(None)
182}
183
184#[must_use]
194#[allow(clippy::cast_precision_loss)]
195pub fn report_window_start(window_start_ms: Option<u64>) -> EventReport {
196 let snap = with_state(Clone::clone);
197 if let Some(requested_window_start_ms) = window_start_ms
198 && requested_window_start_ms > snap.window_start_ms
199 {
200 return EventReport::default();
201 }
202
203 let mut entity_counters: Vec<EntitySummary> = Vec::new();
204 for (path, ops) in &snap.entities {
205 let avg_load = if ops.load_calls > 0 {
206 ops.rows_loaded as f64 / ops.load_calls as f64
207 } else {
208 0.0
209 };
210 let avg_scanned = if ops.load_calls > 0 {
211 ops.rows_scanned as f64 / ops.load_calls as f64
212 } else {
213 0.0
214 };
215 let avg_delete = if ops.delete_calls > 0 {
216 ops.rows_deleted as f64 / ops.delete_calls as f64
217 } else {
218 0.0
219 };
220
221 entity_counters.push(EntitySummary {
222 path: path.clone(),
223 load_calls: ops.load_calls,
224 delete_calls: ops.delete_calls,
225 rows_loaded: ops.rows_loaded,
226 rows_scanned: ops.rows_scanned,
227 rows_deleted: ops.rows_deleted,
228 avg_rows_per_load: avg_load,
229 avg_rows_scanned_per_load: avg_scanned,
230 avg_rows_per_delete: avg_delete,
231 index_inserts: ops.index_inserts,
232 index_removes: ops.index_removes,
233 reverse_index_inserts: ops.reverse_index_inserts,
234 reverse_index_removes: ops.reverse_index_removes,
235 relation_reverse_lookups: ops.relation_reverse_lookups,
236 relation_delete_blocks: ops.relation_delete_blocks,
237 unique_violations: ops.unique_violations,
238 });
239 }
240
241 entity_counters.sort_by(|a, b| {
242 match b
243 .avg_rows_per_load
244 .partial_cmp(&a.avg_rows_per_load)
245 .unwrap_or(Ordering::Equal)
246 {
247 Ordering::Equal => match b.rows_loaded.cmp(&a.rows_loaded) {
248 Ordering::Equal => a.path.cmp(&b.path),
249 other => other,
250 },
251 other => other,
252 }
253 });
254
255 EventReport {
256 counters: Some(snap),
257 entity_counters,
258 }
259}
260
261#[cfg(test)]
266#[allow(clippy::float_cmp)]
267mod tests {
268 use crate::obs::metrics::{EntityCounters, report, reset_all, with_state, with_state_mut};
269
270 #[test]
271 fn reset_all_clears_state() {
272 with_state_mut(|m| {
273 m.ops.load_calls = 3;
274 m.ops.index_inserts = 2;
275 m.perf.save_inst_max = 9;
276 m.entities.insert(
277 "alpha".to_string(),
278 EntityCounters {
279 load_calls: 1,
280 ..Default::default()
281 },
282 );
283 });
284
285 reset_all();
286
287 with_state(|m| {
288 assert_eq!(m.ops.load_calls, 0);
289 assert_eq!(m.ops.index_inserts, 0);
290 assert_eq!(m.perf.save_inst_max, 0);
291 assert!(m.entities.is_empty());
292 });
293 }
294
295 #[test]
296 fn report_sorts_entities_by_average_rows() {
297 reset_all();
298 with_state_mut(|m| {
299 m.entities.insert(
300 "alpha".to_string(),
301 EntityCounters {
302 load_calls: 2,
303 rows_loaded: 6,
304 ..Default::default()
305 },
306 );
307 m.entities.insert(
308 "beta".to_string(),
309 EntityCounters {
310 load_calls: 1,
311 rows_loaded: 5,
312 ..Default::default()
313 },
314 );
315 m.entities.insert(
316 "gamma".to_string(),
317 EntityCounters {
318 load_calls: 2,
319 rows_loaded: 6,
320 ..Default::default()
321 },
322 );
323 });
324
325 let report = report();
326 let paths: Vec<_> = report
327 .entity_counters
328 .iter()
329 .map(|e| e.path.as_str())
330 .collect();
331
332 assert_eq!(paths, ["beta", "alpha", "gamma"]);
334 assert_eq!(report.entity_counters[0].avg_rows_per_load, 5.0);
335 assert_eq!(report.entity_counters[1].avg_rows_per_load, 3.0);
336 assert_eq!(report.entity_counters[2].avg_rows_per_load, 3.0);
337 }
338}