1use crate::host::{with_host, JsObj};
24use fusevm::Value;
25use indexmap::IndexMap;
26use std::cell::RefCell;
27use std::sync::{Mutex, OnceLock};
28use std::time::Instant;
29
30pub const METHODS: &[&str] = &[
33 "now",
34 "mark",
35 "measure",
36 "getEntriesByName",
37 "getEntriesByType",
38 "getEntries",
39 "clearMarks",
40 "clearMeasures",
41 "createHistogram",
42 "eventLoopUtilization",
43 "monitorEventLoopDelay",
44 "timerify",
45 "@@timerify_record",
48];
49
50pub const PERFORMANCE_METHODS: &[&str] = &[
53 "now",
54 "mark",
55 "measure",
56 "getEntriesByName",
57 "getEntriesByType",
58 "getEntries",
59 "clearMarks",
60 "clearMeasures",
61 "createHistogram",
62 "eventLoopUtilization",
63 "monitorEventLoopDelay",
64 "timerify",
65 "@@timerify_record",
66 "clearResourceTimings",
67 "setResourceTimingBufferSize",
68];
69
70pub const HISTOGRAM_METHODS: &[&str] = &[
74 "record",
75 "recordDelta",
76 "reset",
77 "percentile",
78 "add",
79 "enable",
80 "disable",
81];
82
83pub const PERFORMANCE_OBSERVER_METHODS: &[&str] = &["observe", "disconnect", "takeRecords"];
85
86pub const OBSERVER_ENTRY_LIST_METHODS: &[&str] =
88 &["getEntries", "getEntriesByName", "getEntriesByType"];
89
90const EMPTY_HISTOGRAM_MIN: f64 = 9_223_372_036_854_775_807.0;
92
93thread_local! {
94 static OBSERVERS: RefCell<Vec<Value>> = const { RefCell::new(Vec::new()) };
97}
98
99struct Origin {
102 instant: Instant,
103 unix_ms: f64,
104}
105
106fn origin() -> &'static Origin {
107 static ORIGIN: OnceLock<Origin> = OnceLock::new();
108 ORIGIN.get_or_init(|| Origin {
109 instant: Instant::now(),
110 unix_ms: std::time::SystemTime::now()
111 .duration_since(std::time::UNIX_EPOCH)
112 .map(|d| d.as_secs_f64() * 1000.0)
113 .unwrap_or(0.0),
114 })
115}
116
117pub(crate) fn now_ms() -> f64 {
119 origin().instant.elapsed().as_secs_f64() * 1000.0
120}
121
122#[derive(Clone)]
124struct Entry {
125 name: String,
126 entry_type: &'static str,
127 start_time: f64,
128 duration: f64,
129}
130
131fn entries() -> &'static Mutex<Vec<Entry>> {
133 static ENTRIES: OnceLock<Mutex<Vec<Entry>>> = OnceLock::new();
134 ENTRIES.get_or_init(|| Mutex::new(Vec::new()))
135}
136
137pub fn constant(name: &str) -> Option<Value> {
142 match name {
143 "performance" => Some(with_host(|h| h.alloc(JsObj::Builtin("performance".into())))),
144 "timeOrigin" => Some(Value::Float(origin().unix_ms)),
145 "constants" => Some(with_host(|h| h.new_object(IndexMap::new()))),
146 "Performance"
152 | "PerformanceEntry"
153 | "PerformanceMark"
154 | "PerformanceMeasure"
155 | "PerformanceObserver"
156 | "PerformanceObserverEntryList"
157 | "PerformanceResourceTiming" => Some(with_host(|h| h.alloc(JsObj::Builtin(name.into())))),
158 _ => None,
159 }
160}
161
162pub fn call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
163 Some(match method {
164 "now" => Ok(Value::Float(now_ms())),
165 "mark" => Ok(mark(args)),
166 "measure" => Ok(measure(args)),
167 "getEntries" => Ok(entries_to_array(|_| true)),
168 "getEntriesByName" => {
169 let name = super::arg_str(args, 0);
170 let ty = match args.get(1) {
173 Some(v) if !matches!(v, Value::Undef) => Some(super::arg_str(args, 1)),
174 _ => None,
175 };
176 Ok(entries_to_array(|e| {
177 e.name == name && ty.as_deref().map(|t| t == e.entry_type).unwrap_or(true)
178 }))
179 }
180 "getEntriesByType" => {
181 let ty = super::arg_str(args, 0);
182 Ok(entries_to_array(|e| e.entry_type == ty))
183 }
184 "clearMarks" => Ok(clear("mark", args)),
185 "clearMeasures" => Ok(clear("measure", args)),
186 "createHistogram" => Ok(new_histogram()),
188 "eventLoopUtilization" => Ok(event_loop_utilization(args)),
189 "monitorEventLoopDelay" => Ok(new_histogram()),
194 "timerify" => timerify(args),
195 "clearResourceTimings" | "setResourceTimingBufferSize" => Ok(Value::Undef),
200 "@@timerify_record" => Ok(timerify_record(args)),
201 _ => return None,
202 })
203}
204
205fn run_completion(src: &str) -> Result<Value, String> {
220 crate::eval_internal(src)
221}
222
223const TIMERIFY_SRC: &str = "(function(original, record){\n\
224 var perf = require('perf_hooks').performance;\n\
225 return function(){\n\
226 var start = perf.now();\n\
227 try {\n\
228 return original.apply(this, arguments);\n\
229 } finally {\n\
230 record(original.name || '', start, perf.now());\n\
231 }\n\
232 };\n\
233})";
234
235fn timerify(args: &[Value]) -> Result<Value, String> {
238 let orig = args.first().cloned().unwrap_or(Value::Undef);
239 if !with_host(|h| crate::host::is_callable(h, &orig)) {
240 return Err(crate::host::invalid_arg_type(
241 "fn", "argument", "function", &orig,
242 ));
243 }
244 let factory = run_completion(TIMERIFY_SRC)?;
245 let record = with_host(|h| h.alloc(JsObj::Builtin("performance.@@timerify_record".into())));
246 crate::host::invoke(&factory, vec![orig, record], None)
247}
248
249fn timerify_record(args: &[Value]) -> Value {
254 let name = super::arg_str(args, 0);
255 let start = super::arg_num(args, 1);
256 let end = super::arg_num(args, 2);
257 let e = Entry {
258 name,
259 entry_type: "function",
260 start_time: start,
261 duration: (end - start).max(0.0),
262 };
263 notify_observers(&e);
264 Value::Undef
265}
266
267pub fn construct(name: &str, args: &[Value]) -> Result<Value, String> {
271 match name {
272 "PerformanceObserver" => {
273 let cb = args.first().cloned().unwrap_or(Value::Undef);
274 Ok(with_host(|h| {
275 let types = h.new_array(Vec::new());
276 let buffer = h.new_array(Vec::new());
277 let mut m = IndexMap::new();
278 m.insert("@@native".into(), h.new_str("PerformanceObserver"));
279 m.insert("@@cb".into(), cb);
280 m.insert("@@types".into(), types);
281 m.insert("@@buffer".into(), buffer);
282 h.new_object(m)
283 }))
284 }
285 _ => Err(crate::host::type_error(&format!(
286 "perf_hooks.{name} is not a constructor"
287 ))),
288 }
289}
290
291fn mark(args: &[Value]) -> Value {
294 let name = super::arg_str(args, 0);
295 let start = now_ms();
296 let e = Entry {
297 name,
298 entry_type: "mark",
299 start_time: start,
300 duration: 0.0,
301 };
302 if let Ok(mut buf) = entries().lock() {
303 buf.push(e.clone());
304 }
305 notify_observers(&e);
306 entry_object(&e)
307}
308
309fn measure(args: &[Value]) -> Value {
313 let name = super::arg_str(args, 0);
314 let start_mark = args.get(1).map(|_| super::arg_str(args, 1));
315 let end_mark = args.get(2).map(|_| super::arg_str(args, 2));
316 let mark_time = |m: &Option<String>, default: f64| -> f64 {
317 match m {
318 Some(n) => entries()
319 .lock()
320 .ok()
321 .and_then(|b| {
322 b.iter()
323 .rev()
324 .find(|e| e.entry_type == "mark" && &e.name == n)
325 .map(|e| e.start_time)
326 })
327 .unwrap_or(default),
328 None => default,
329 }
330 };
331 let start = mark_time(&start_mark, 0.0);
332 let end = mark_time(&end_mark, now_ms());
333 let e = Entry {
334 name,
335 entry_type: "measure",
336 start_time: start,
337 duration: (end - start).max(0.0),
338 };
339 if let Ok(mut buf) = entries().lock() {
340 buf.push(e.clone());
341 }
342 notify_observers(&e);
343 entry_object(&e)
344}
345
346fn clear(kind: &'static str, args: &[Value]) -> Value {
349 let name = args.first().map(|_| super::arg_str(args, 0));
350 if let Ok(mut buf) = entries().lock() {
351 buf.retain(|e| {
352 if e.entry_type != kind {
353 return true;
354 }
355 match &name {
356 Some(n) => &e.name != n,
357 None => false,
358 }
359 });
360 }
361 Value::Undef
362}
363
364fn entries_to_array(pred: impl Fn(&Entry) -> bool) -> Value {
367 let matched: Vec<Entry> = entries()
368 .lock()
369 .map(|b| b.iter().filter(|e| pred(e)).cloned().collect())
370 .unwrap_or_default();
371 with_host(|h| {
372 let items: Vec<Value> = matched.iter().map(|e| entry_object_h(h, e)).collect();
373 h.new_array(items)
374 })
375}
376
377fn entry_object(e: &Entry) -> Value {
379 with_host(|h| entry_object_h(h, e))
380}
381
382fn entry_object_h(h: &mut crate::host::JsHost, e: &Entry) -> Value {
383 let mut m = IndexMap::new();
384 m.insert("name".into(), h.new_str(e.name.clone()));
385 m.insert("entryType".into(), h.new_str(e.entry_type));
386 m.insert("startTime".into(), Value::Float(e.start_time));
387 m.insert("duration".into(), Value::Float(e.duration));
388 h.new_object(m)
389}
390
391fn new_histogram() -> Value {
398 with_host(|h| {
399 let vals = h.new_array(Vec::new());
400 let mut m = IndexMap::new();
401 m.insert("@@native".into(), h.new_str("Histogram"));
402 m.insert("@@vals".into(), vals);
403 m.insert("count".into(), Value::Float(0.0));
404 m.insert("min".into(), Value::Float(EMPTY_HISTOGRAM_MIN));
405 m.insert("max".into(), Value::Float(0.0));
406 m.insert("mean".into(), Value::Float(f64::NAN));
407 m.insert("stddev".into(), Value::Float(f64::NAN));
408 m.insert("exceeds".into(), Value::Float(0.0));
409 h.new_object(m)
410 })
411}
412
413pub fn histogram_instance_call(
415 recv: &Value,
416 method: &str,
417 args: &[Value],
418) -> Result<Value, String> {
419 match method {
420 "record" => {
421 let n = super::arg_num(args, 0);
422 push_value(recv, n);
423 update_stats(recv);
424 Ok(Value::Undef)
425 }
426 "recordDelta" => {
429 let now = now_ms();
430 let last = read_hidden_num(recv, "@@last").unwrap_or(now);
431 set_hidden_num(recv, "@@last", now);
432 if read_hidden_num(recv, "@@last_seen").is_some() {
433 push_value(recv, now - last);
434 update_stats(recv);
435 }
436 set_hidden_num(recv, "@@last_seen", 1.0);
437 Ok(Value::Undef)
438 }
439 "reset" => {
440 let vals = hidden(recv, "@@vals");
446 if let Some(vals) = vals {
447 with_host(|h| {
448 if let Some(JsObj::Array(items)) = h.get_mut(&vals) {
449 items.clear();
450 }
451 });
452 }
453 update_stats(recv);
454 Ok(Value::Undef)
455 }
456 "percentile" => {
457 let p = super::arg_num(args, 0);
458 Ok(Value::Float(percentile(recv, p)))
459 }
460 "add" => {
461 if let Some(other) = args.first() {
463 for v in histogram_values(other) {
464 push_value(recv, v);
465 }
466 update_stats(recv);
467 }
468 Ok(Value::Undef)
469 }
470 "enable" | "disable" => Ok(Value::Bool(true)),
473 _ => Err(crate::host::type_error(&format!(
474 "{method} is not a function"
475 ))),
476 }
477}
478
479fn push_value(recv: &Value, n: f64) {
481 with_host(|h| {
482 let v = Value::Float(n);
483 if let Some(vals) = match h.get(recv) {
484 Some(JsObj::Object(p)) => p.get("@@vals").cloned(),
485 _ => None,
486 } {
487 if let Some(JsObj::Array(items)) = h.get_mut(&vals) {
488 items.push(v);
489 }
490 }
491 });
492}
493
494fn histogram_values(recv: &Value) -> Vec<f64> {
496 with_host(|h| match h.get(recv) {
497 Some(JsObj::Object(p)) => match p.get("@@vals").and_then(|a| h.get(a)) {
498 Some(JsObj::Array(items)) => items.iter().map(|v| h.to_number(v)).collect(),
499 _ => Vec::new(),
500 },
501 _ => Vec::new(),
502 })
503}
504
505fn update_stats(recv: &Value) {
507 let vals = histogram_values(recv);
508 let (count, min, max, mean, stddev) = if vals.is_empty() {
509 (0.0, EMPTY_HISTOGRAM_MIN, 0.0, f64::NAN, f64::NAN)
510 } else {
511 let n = vals.len() as f64;
512 let sum: f64 = vals.iter().sum();
513 let mean = sum / n;
514 let var = vals.iter().map(|v| (v - mean).powi(2)).sum::<f64>() / n;
515 let min = vals.iter().cloned().fold(f64::INFINITY, f64::min);
516 let max = vals.iter().cloned().fold(f64::NEG_INFINITY, f64::max);
517 (n, min, max, mean, var.sqrt())
518 };
519 with_host(|h| {
520 if let Some(JsObj::Object(p)) = h.get_mut(recv) {
521 p.insert("count".into(), Value::Float(count));
522 p.insert("min".into(), Value::Float(min));
523 p.insert("max".into(), Value::Float(max));
524 p.insert("mean".into(), Value::Float(mean));
525 p.insert("stddev".into(), Value::Float(stddev));
526 }
527 });
528}
529
530fn percentile(recv: &Value, p: f64) -> f64 {
533 let mut vals = histogram_values(recv);
534 if vals.is_empty() {
535 return 0.0;
536 }
537 vals.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
538 let n = vals.len();
539 let rank = (p / 100.0 * n as f64).ceil() as usize;
540 let idx = rank.clamp(1, n) - 1;
541 vals[idx]
542}
543
544fn hidden(recv: &Value, key: &str) -> Option<Value> {
546 with_host(|h| match h.get(recv) {
547 Some(JsObj::Object(p)) => p.get(key).cloned(),
548 _ => None,
549 })
550}
551
552fn read_hidden_num(recv: &Value, key: &str) -> Option<f64> {
553 hidden(recv, key).map(|v| with_host(|h| h.to_number(&v)))
554}
555
556fn set_hidden_num(recv: &Value, key: &str, n: f64) {
557 with_host(|h| {
558 if let Some(JsObj::Object(p)) = h.get_mut(recv) {
559 p.insert(key.to_string(), Value::Float(n));
560 }
561 });
562}
563
564fn event_loop_utilization(args: &[Value]) -> Value {
575 let active_now = now_ms();
576 let (prev_idle, prev_active) = match args.first() {
577 Some(prev) => (
578 hidden_num(prev, "idle").unwrap_or(0.0),
579 hidden_num(prev, "active").unwrap_or(0.0),
580 ),
581 None => (0.0, 0.0),
582 };
583 let idle = 0.0 - prev_idle;
584 let active = active_now - prev_active;
585 let denom = idle + active;
586 let utilization = if denom > 0.0 { active / denom } else { 0.0 };
587 with_host(|h| {
588 let mut m = IndexMap::new();
589 m.insert("idle".into(), Value::Float(idle));
590 m.insert("active".into(), Value::Float(active));
591 m.insert("utilization".into(), Value::Float(utilization));
592 h.new_object(m)
593 })
594}
595
596fn hidden_num(recv: &Value, key: &str) -> Option<f64> {
597 with_host(|h| match h.get(recv) {
598 Some(JsObj::Object(p)) => p.get(key).map(|v| h.to_number(v)),
599 _ => None,
600 })
601}
602
603pub fn observer_instance_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
607 match method {
608 "observe" => {
611 let opts = args.first().cloned().unwrap_or(Value::Undef);
612 let types = observe_types(&opts);
613 with_host(|h| {
614 let items: Vec<Value> = types.iter().map(|t| h.new_str(t.clone())).collect();
615 let arr = h.new_array(items);
616 if let Some(JsObj::Object(p)) = h.get_mut(recv) {
617 p.insert("@@types".into(), arr);
618 }
619 });
620 OBSERVERS.with(|o| {
621 let mut list = o.borrow_mut();
622 if !list.iter().any(|v| same_ref(v, recv)) {
623 list.push(recv.clone());
624 }
625 });
626 Ok(Value::Undef)
627 }
628 "disconnect" => {
629 OBSERVERS.with(|o| o.borrow_mut().retain(|v| !same_ref(v, recv)));
630 with_host(|h| {
631 if let Some(buf) = match h.get(recv) {
632 Some(JsObj::Object(p)) => p.get("@@buffer").cloned(),
633 _ => None,
634 } {
635 if let Some(JsObj::Array(items)) = h.get_mut(&buf) {
636 items.clear();
637 }
638 }
639 });
640 Ok(Value::Undef)
641 }
642 "takeRecords" => {
644 let taken: Vec<Value> = with_host(|h| match h.get(recv) {
645 Some(JsObj::Object(p)) => match p.get("@@buffer").and_then(|a| h.get(a)) {
646 Some(JsObj::Array(items)) => items.clone(),
647 _ => Vec::new(),
648 },
649 _ => Vec::new(),
650 });
651 with_host(|h| {
652 if let Some(buf) = match h.get(recv) {
653 Some(JsObj::Object(p)) => p.get("@@buffer").cloned(),
654 _ => None,
655 } {
656 if let Some(JsObj::Array(items)) = h.get_mut(&buf) {
657 items.clear();
658 }
659 }
660 });
661 Ok(with_host(|h| h.new_array(taken)))
662 }
663 _ => Err(crate::host::type_error(&format!(
664 "{method} is not a function"
665 ))),
666 }
667}
668
669fn observe_types(opts: &Value) -> Vec<String> {
672 with_host(|h| match h.get(opts) {
673 Some(JsObj::Object(p)) => {
674 if let Some(JsObj::Array(items)) = p.get("entryTypes").and_then(|a| h.get(a)) {
675 items.iter().map(|v| h.str_of(v)).collect()
676 } else if let Some(t) = p.get("type") {
677 vec![h.str_of(t)]
678 } else {
679 Vec::new()
680 }
681 }
682 _ => Vec::new(),
683 })
684}
685
686fn notify_observers(e: &Entry) {
693 let observers: Vec<Value> = OBSERVERS.with(|o| o.borrow().clone());
694 if observers.is_empty() {
695 return;
696 }
697 for obs in observers {
698 let types: Vec<String> = with_host(|h| match h.get(&obs) {
699 Some(JsObj::Object(p)) => match p.get("@@types").and_then(|a| h.get(a)) {
700 Some(JsObj::Array(items)) => items.iter().map(|v| h.str_of(v)).collect(),
701 _ => Vec::new(),
702 },
703 _ => Vec::new(),
704 });
705 if !types.iter().any(|t| t == e.entry_type) {
706 continue;
707 }
708 let entry = entry_object(e);
711 with_host(|h| {
712 if let Some(buf) = match h.get(&obs) {
713 Some(JsObj::Object(p)) => p.get("@@buffer").cloned(),
714 _ => None,
715 } {
716 if let Some(JsObj::Array(items)) = h.get_mut(&buf) {
717 items.push(entry);
718 }
719 }
720 });
721 let cb = with_host(|h| match h.get(&obs) {
722 Some(JsObj::Object(p)) => p.get("@@cb").cloned(),
723 _ => None,
724 });
725 let Some(cb) = cb else { continue };
726 let list = entry_list_object(vec![entry_object(e)]);
727 let _ = crate::host::invoke(&cb, vec![list, obs.clone()], None);
728 }
729}
730
731fn entry_list_object(items: Vec<Value>) -> Value {
733 with_host(|h| {
734 let arr = h.new_array(items);
735 let mut m = IndexMap::new();
736 m.insert("@@native".into(), h.new_str("PerformanceObserverEntryList"));
737 m.insert("@@entries".into(), arr);
738 h.new_object(m)
739 })
740}
741
742pub fn entry_list_instance_call(
744 recv: &Value,
745 method: &str,
746 args: &[Value],
747) -> Result<Value, String> {
748 let items: Vec<Value> = with_host(|h| match h.get(recv) {
749 Some(JsObj::Object(p)) => match p.get("@@entries").and_then(|a| h.get(a)) {
750 Some(JsObj::Array(v)) => v.clone(),
751 _ => Vec::new(),
752 },
753 _ => Vec::new(),
754 });
755 let prop = |v: &Value, key: &str| {
756 with_host(|h| match h.get(v) {
757 Some(JsObj::Object(p)) => p.get(key).map(|x| h.str_of(x)),
758 _ => None,
759 })
760 };
761 match method {
762 "getEntries" => Ok(with_host(|h| h.new_array(items))),
763 "getEntriesByName" => {
764 let name = super::arg_str(args, 0);
765 let ty = match args.get(1) {
766 Some(v) if !matches!(v, Value::Undef) => Some(super::arg_str(args, 1)),
767 _ => None,
768 };
769 let filtered: Vec<Value> = items
770 .into_iter()
771 .filter(|it| {
772 prop(it, "name").as_deref() == Some(name.as_str())
773 && ty
774 .as_deref()
775 .map(|t| prop(it, "entryType").as_deref() == Some(t))
776 .unwrap_or(true)
777 })
778 .collect();
779 Ok(with_host(|h| h.new_array(filtered)))
780 }
781 "getEntriesByType" => {
782 let ty = super::arg_str(args, 0);
783 let filtered: Vec<Value> = items
784 .into_iter()
785 .filter(|it| prop(it, "entryType").as_deref() == Some(ty.as_str()))
786 .collect();
787 Ok(with_host(|h| h.new_array(filtered)))
788 }
789 _ => Err(crate::host::type_error(&format!(
790 "{method} is not a function"
791 ))),
792 }
793}
794
795fn same_ref(a: &Value, b: &Value) -> bool {
797 matches!((a, b), (Value::Obj(x), Value::Obj(y)) if x == y)
798}