1use crate::ids::{EndpointCall, EndpointCallKind};
11use std::{cell::RefCell, collections::HashMap};
12
13thread_local! {
14 #[cfg(not(test))]
16 pub static PERF_LAST: RefCell<u64> = RefCell::new(perf_counter());
17
18 #[cfg(test)]
20 pub static PERF_LAST: RefCell<u64> = const { RefCell::new(0) };
21
22 static PERF_TABLE: RefCell<HashMap<PerfKey, PerfSlot>> = RefCell::new(HashMap::new());
24
25 static PERF_STACK: RefCell<Vec<PerfFrame>> = const { RefCell::new(Vec::new()) };
28}
29
30#[must_use]
54#[cfg_attr(not(target_arch = "wasm32"), expect(clippy::missing_const_for_fn))]
55pub fn perf_counter() -> u64 {
56 #[cfg(target_arch = "wasm32")]
57 {
58 ic_cdk::api::performance_counter(1)
59 }
60
61 #[cfg(not(target_arch = "wasm32"))]
62 {
63 0
64 }
65}
66
67#[derive(Clone, Eq, Hash, Ord, PartialEq, PartialOrd)]
73pub enum PerfKey {
74 Endpoint {
75 kind: EndpointCallKind,
76 name: String,
77 },
78 Checkpoint {
79 scope: String,
80 label: String,
81 },
82}
83
84struct PerfFrame {
90 start: u64,
91 child_instructions: u64,
92}
93
94#[derive(Default)]
99struct PerfSlot {
100 count: u64,
101 total_instructions: u64,
102}
103
104impl PerfSlot {
105 const fn increment(&mut self, delta: u64) {
106 self.count = self.count.saturating_add(1);
107 self.total_instructions = self.total_instructions.saturating_add(delta);
108 }
109}
110
111#[derive(Clone)]
117pub struct PerfEntry {
118 pub key: PerfKey,
119 pub count: u64,
120 pub total_instructions: u64,
121}
122
123pub fn record(key: PerfKey, delta: u64) {
125 PERF_TABLE.with(|table| {
126 let mut table = table.borrow_mut();
127 table.entry(key).or_default().increment(delta);
128 });
129}
130
131pub fn record_endpoint_call(call: EndpointCall, delta_instructions: u64) {
132 record(
133 PerfKey::Endpoint {
134 kind: call.kind,
135 name: call.endpoint.name.to_string(),
136 },
137 delta_instructions,
138 );
139}
140
141pub fn record_checkpoint(scope: &str, label: &str, delta_instructions: u64) {
142 record(
143 PerfKey::Checkpoint {
144 scope: scope.to_string(),
145 label: label.to_string(),
146 },
147 delta_instructions,
148 );
149}
150
151pub(crate) fn enter_endpoint() {
153 enter_endpoint_at(perf_counter());
154}
155
156pub(crate) fn exit_endpoint(call: EndpointCall) {
158 exit_endpoint_at(call, perf_counter());
159}
160
161fn enter_endpoint_at(start: u64) {
162 PERF_STACK.with(|stack| {
163 let mut stack = stack.borrow_mut();
164
165 if let Some(last) = stack.last()
167 && start < last.start
168 {
169 stack.clear();
170 }
171
172 stack.push(PerfFrame {
173 start,
174 child_instructions: 0,
175 });
176 });
177}
178
179fn exit_endpoint_at(call: EndpointCall, end: u64) {
180 PERF_STACK.with(|stack| {
181 let mut stack = stack.borrow_mut();
182 let Some(frame) = stack.pop() else {
183 record_endpoint_call(call, end);
184 return;
185 };
186
187 let total = end.saturating_sub(frame.start);
188 let exclusive = total.saturating_sub(frame.child_instructions);
189
190 if let Some(parent) = stack.last_mut() {
191 parent.child_instructions = parent.child_instructions.saturating_add(total);
192 }
193
194 record_endpoint_call(call, exclusive);
195 });
196}
197
198#[must_use]
201pub fn entries() -> Vec<PerfEntry> {
202 PERF_TABLE.with(|table| {
203 let table = table.borrow();
204
205 let mut out: Vec<PerfEntry> = table
206 .iter()
207 .map(|(key, slot)| PerfEntry {
208 key: key.clone(),
209 count: slot.count,
210 total_instructions: slot.total_instructions,
211 })
212 .collect();
213
214 out.sort_by(|a, b| a.key.cmp(&b.key));
215 out
216 })
217}
218
219#[cfg(test)]
224pub fn reset() {
225 PERF_TABLE.with(|t| t.borrow_mut().clear());
226 PERF_LAST.with(|last| *last.borrow_mut() = 0);
227 PERF_STACK.with(|stack| stack.borrow_mut().clear());
228}
229
230#[cfg(test)]
231mod tests {
232 use super::*;
233
234 fn checkpoint_at(now: u64) {
235 PERF_LAST.with(|last| *last.borrow_mut() = now);
236 }
237
238 fn call(name: &'static str, kind: EndpointCallKind) -> EndpointCall {
239 EndpointCall {
240 endpoint: crate::ids::EndpointId::new(name),
241 kind,
242 }
243 }
244
245 fn entry_for(kind: EndpointCallKind, label: &str) -> PerfEntry {
246 entries()
247 .into_iter()
248 .find(|entry| {
249 matches!(
250 &entry.key,
251 PerfKey::Endpoint {
252 kind: entry_kind,
253 name
254 } if *entry_kind == kind && name == label
255 )
256 })
257 .expect("expected perf entry to exist")
258 }
259
260 fn checkpoint_entry_for(scope: &str, label: &str) -> PerfEntry {
261 entries()
262 .into_iter()
263 .find(|entry| {
264 matches!(
265 &entry.key,
266 PerfKey::Checkpoint {
267 scope: entry_scope,
268 label: entry_label,
269 } if entry_scope == scope && entry_label == label
270 )
271 })
272 .expect("expected checkpoint perf entry to exist")
273 }
274
275 #[test]
276 fn nested_endpoints_record_exclusive_totals() {
277 reset();
278
279 enter_endpoint_at(100);
280 checkpoint_at(140);
281
282 enter_endpoint_at(200);
283 checkpoint_at(230);
284 exit_endpoint_at(call("child", EndpointCallKind::Query), 260);
285
286 exit_endpoint_at(call("parent", EndpointCallKind::Update), 300);
287
288 let parent = entry_for(EndpointCallKind::Update, "parent");
289 let child = entry_for(EndpointCallKind::Query, "child");
290
291 assert_eq!(child.count, 1);
292 assert_eq!(child.total_instructions, 60);
293 assert_eq!(parent.count, 1);
294 assert_eq!(parent.total_instructions, 140);
295 }
296
297 #[test]
298 fn endpoint_perf_keys_preserve_call_kind() {
299 reset();
300
301 record_endpoint_call(call("same_name", EndpointCallKind::Query), 10);
302 record_endpoint_call(call("same_name", EndpointCallKind::QueryComposite), 20);
303 record_endpoint_call(call("same_name", EndpointCallKind::Update), 30);
304
305 assert_eq!(
306 entry_for(EndpointCallKind::Query, "same_name").total_instructions,
307 10
308 );
309 assert_eq!(
310 entry_for(EndpointCallKind::QueryComposite, "same_name").total_instructions,
311 20
312 );
313 assert_eq!(
314 entry_for(EndpointCallKind::Update, "same_name").total_instructions,
315 30
316 );
317 }
318
319 #[test]
320 fn checkpoints_record_scope_and_label() {
321 reset();
322
323 record_checkpoint("workflow::bootstrap", "load_cfg", 120);
324 record_checkpoint("workflow::bootstrap", "load_cfg", 80);
325
326 let checkpoint = checkpoint_entry_for("workflow::bootstrap", "load_cfg");
327
328 assert_eq!(checkpoint.count, 2);
329 assert_eq!(checkpoint.total_instructions, 200);
330 }
331}