Skip to main content

nodejs/stdlib/
perf_hooks.rs

1//! Node `perf_hooks` module.
2//!
3//! Exposes the `performance` object. `performance.now()` returns REAL monotonic
4//! milliseconds elapsed since a process-start reference captured lazily in a
5//! `OnceLock` (`std::time::Instant` — a true monotonic clock, never faked or
6//! fuzzed). `timeOrigin` is the wall-clock time (Unix ms) at that same reference
7//! point, so `timeOrigin + now()` approximates `Date.now()` as Node guarantees.
8//!
9//! `mark`/`measure`/`getEntriesByName`/`getEntriesByType`/`clearMarks` are
10//! implemented against a small in-process entry buffer guarded by a `Mutex`. This
11//! is best-effort: entries accumulate for the life of the process and the buffer
12//! is not bounded (Node's PerformanceObserver / buffered-entry eviction is not
13//! modeled), but marks and measures created and queried within a run behave
14//! correctly.
15//!
16//! `performance` is surfaced as a `Builtin("performance")` namespace value, so
17//! `performance.now()` dispatches through `call_method` → `call_builtin_function`
18//! ("performance.now") → this module's `call`, and `performance.timeOrigin`
19//! reads through `namespace_property` → this module's `constant`. The parent wires
20//! BOTH the `perf_hooks` and `performance` namespaces to `call`/`constant` (see
21//! the wiring note in the accompanying report).
22
23use 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
30/// Methods available on both the `perf_hooks` module and its `performance`
31/// object. (`timeOrigin` is a data property, served by `constant`.)
32pub 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    // Internal hook the `timerify` wrapper calls to deliver its 'function' entry
46    // (hidden `@@` name — not a user-facing method, only reachable by the wrapper).
47    "@@timerify_record",
48];
49
50/// The `performance` instance's methods: the module's, plus the two that
51/// live only on `Performance.prototype`.
52pub 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
70/// Methods dispatched on an `@@native = "Histogram"` object (from
71/// `createHistogram()` / `monitorEventLoopDelay()`; reported to the parent for
72/// `instance_has_method` / `instance_call` wiring).
73pub const HISTOGRAM_METHODS: &[&str] = &[
74    "record",
75    "recordDelta",
76    "reset",
77    "percentile",
78    "add",
79    "enable",
80    "disable",
81];
82
83/// Methods dispatched on an `@@native = "PerformanceObserver"` object.
84pub const PERFORMANCE_OBSERVER_METHODS: &[&str] = &["observe", "disconnect", "takeRecords"];
85
86/// Methods dispatched on an `@@native = "PerformanceObserverEntryList"` object.
87pub const OBSERVER_ENTRY_LIST_METHODS: &[&str] =
88    &["getEntries", "getEntriesByName", "getEntriesByType"];
89
90/// Node's sentinel `min` for an empty histogram (`i64::MAX`).
91const EMPTY_HISTOGRAM_MIN: f64 = 9_223_372_036_854_775_807.0;
92
93thread_local! {
94    /// Live `PerformanceObserver` objects that should be notified when a mark or
95    /// measure is recorded (only ever touched on the thread that owns them).
96    static OBSERVERS: RefCell<Vec<Value>> = const { RefCell::new(Vec::new()) };
97}
98
99/// The process-start reference: a monotonic `Instant` paired with the Unix-epoch
100/// milliseconds at the same moment. Captured once, lazily.
101struct 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
117/// Real monotonic milliseconds since the process-start reference.
118pub(crate) fn now_ms() -> f64 {
119    origin().instant.elapsed().as_secs_f64() * 1000.0
120}
121
122/// A recorded performance entry (`PerformanceEntry` shape).
123#[derive(Clone)]
124struct Entry {
125    name: String,
126    entry_type: &'static str,
127    start_time: f64,
128    duration: f64,
129}
130
131/// The in-process entry buffer (marks + measures), in insertion order.
132fn 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
137/// Non-function properties of `perf_hooks` / `performance`.
138///
139/// `perf_hooks.performance` → the `performance` namespace. `performance.timeOrigin`
140/// → the fixed Unix-ms origin. `perf_hooks.constants` → a (currently empty) map.
141pub 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        // Constructor names, exposed as values so `require('perf_hooks').X`
147        // resolves and `typeof X === 'function'` holds. Only `PerformanceObserver`
148        // is meaningfully instantiable here (see `construct`); the others exist for
149        // name/`instanceof` resolution. Parent wires `PerformanceObserver`
150        // construction into `construct`.
151        "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            // Optional second arg filters by entryType (an explicit `undefined`
171            // means "no filter", matching Node).
172            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        // A real histogram over recorded values (see `histogram_instance_call`).
187        "createHistogram" => Ok(new_histogram()),
188        "eventLoopUtilization" => Ok(event_loop_utilization(args)),
189        // A histogram-shaped monitor. LIMITATION: node-js has no background event-
190        // loop-delay sampler, so this histogram accumulates no samples on its own
191        // (it stays empty until values are `record`ed manually). `enable`/`disable`
192        // are no-ops. Honest empty data, never a fabricated delay distribution.
193        "monitorEventLoopDelay" => Ok(new_histogram()),
194        "timerify" => timerify(args),
195        // node-js records no resource timings (nothing it fetches makes a
196        // `PerformanceResourceTiming`), so there are none to clear and the
197        // buffer they would fill can never overflow: both are the no-ops
198        // node's own are for a process with no resource entries.
199        "clearResourceTimings" | "setResourceTimingBufferSize" => Ok(Value::Undef),
200        "@@timerify_record" => Ok(timerify_record(args)),
201        _ => return None,
202    })
203}
204
205// ── timerify ──────────────────────────────────────────────────────────────────
206// `performance.timerify(fn)` wraps `fn` so each call records a 'function'
207// PerformanceEntry (name = `fn.name`, duration = call time). The wrapper is a REAL
208// JS closure compiled + invoked here (the same re-entrant factory technique
209// `util.promisify` uses), closing over the original function and a native record
210// hook (`Builtin("performance.@@timerify_record")`). Node delivers 'function'
211// entries to subscribed PerformanceObservers only — they are NOT retained on the
212// global timeline (`performance.getEntriesByType('function')` is empty in v26) — so
213// the hook notifies observers without buffering the entry.
214
215/// Compile a single JS expression and run it on the LIVE host, returning its
216/// completion value. Delegates to the frontend's ONE runtime-source evaluator
217/// (`crate::eval_in_global_scope`), which runs the factory in the program's
218/// module scope rather than in the calling function's frame.
219fn 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
235/// `performance.timerify(fn[, options])` → a wrapped `fn` that records a 'function'
236/// `PerformanceEntry` (its call duration) on every invocation.
237fn 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
249/// Native hook invoked by the `timerify` wrapper `(name, startTime, endTime)`:
250/// deliver a 'function' entry (call duration) to subscribed observers. Not stored
251/// on the global timeline — matching Node v26, where function entries reach
252/// observers only.
253fn 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
267/// `new PerformanceObserver(callback)` — build an observer holding its callback,
268/// its subscribed entry types, and a pending-entries buffer. Reported to the
269/// parent for `construct` wiring.
270pub 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
291/// `performance.mark(name)`: record a mark entry at the current time and return a
292/// `PerformanceEntry` for it.
293fn 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
309/// `performance.measure(name, startMark, endMark)`: record a measure spanning two
310/// previously recorded marks (missing marks default to `0`/now), returning its
311/// `PerformanceEntry`.
312fn 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
346/// `clearMarks([name])` / `clearMeasures([name])`: drop entries of the given kind
347/// (all, or only those named `name` when a name is supplied). Returns undefined.
348fn 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
364/// Build a JS array of `PerformanceEntry` objects for the buffered entries
365/// matching `pred`.
366fn 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
377/// Allocate a `PerformanceEntry`-shaped object.
378fn 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
391// ── histogram (createHistogram / monitorEventLoopDelay) ───────────────────────
392
393/// A fresh, empty histogram object. Recorded values accumulate in the hidden
394/// `@@vals` array; the `count`/`min`/`max`/`mean`/`stddev`/`exceeds` data
395/// properties are kept in sync on every `record`, so a plain property read
396/// (`h.min`) returns the right value without a getter.
397fn 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
413/// Dispatch a method on a `Histogram` instance (`@@native = "Histogram"`).
414pub 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        // Record the elapsed time (ms) since the previous `recordDelta` (or since
427        // the histogram was created, for the first call).
428        "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            // `hidden` takes the host itself, so reading it INSIDE `with_host`
441            // borrowed the same RefCell twice and aborted the process with
442            // "RefCell already borrowed" — not a catchable JS error, the whole
443            // runtime died on `histogram.reset()`. Read the handle first, then
444            // borrow to mutate.
445            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            // Merge another histogram's recorded values into this one.
462            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        // Interval-form controls: no background sampler to toggle (see the
471        // `monitorEventLoopDelay` note). Accepted for compatibility.
472        "enable" | "disable" => Ok(Value::Bool(true)),
473        _ => Err(crate::host::type_error(&format!(
474            "{method} is not a function"
475        ))),
476    }
477}
478
479/// Push a recorded value onto the histogram's `@@vals` array.
480fn 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
494/// The recorded values of any histogram object, as `f64`s.
495fn 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
505/// Recompute `count`/`min`/`max`/`mean`/`stddev` from `@@vals` and write them back.
506fn 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
530/// Nearest-rank percentile of the recorded values (empty → 0), matching Node's
531/// integer-valued percentile results for small samples.
532fn 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
544/// A hidden own property of `recv`, if present.
545fn 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
564// ── eventLoopUtilization ──────────────────────────────────────────────────────
565
566/// `performance.eventLoopUtilization([util1[, util2]])` → `{ idle, active,
567/// utilization }`.
568///
569/// LIMITATION (documented, not faked): node-js does not separately instrument the
570/// event loop's idle vs active time. The honest best-effort is `active` = total
571/// milliseconds elapsed since process start (real uptime) and `idle` = 0, so
572/// `utilization` = 1. When a prior result is passed, the numbers are the delta
573/// between it and now (Node's diff form).
574fn 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
603// ── PerformanceObserver ───────────────────────────────────────────────────────
604
605/// Dispatch a method on a `PerformanceObserver` instance.
606pub fn observer_instance_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
607    match method {
608        // `observe({ entryTypes: [...] } | { type: '...' })`: record the subscribed
609        // types and register so future marks/measures notify this observer.
610        "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        // Drain and return the observer's buffered entries.
643        "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
669/// The entry types an `observe(options)` call subscribes to (`entryTypes` array
670/// or a single `type`).
671fn 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
686/// Deliver a just-recorded entry to every subscribed observer.
687///
688/// DEVIATION (documented): Node batches entries and delivers them to the observer
689/// callback asynchronously on a microtask. node-js delivers SYNCHRONOUSLY, one
690/// entry per notification, right after the mark/measure is recorded. The callback
691/// receives `(entryList, observer)` exactly as Node's does.
692fn 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        // Buffer the entry on the observer, then invoke its callback with a
709        // single-entry list.
710        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
731/// Build a `PerformanceObserverEntryList` wrapping `items`.
732fn 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
742/// Dispatch a method on a `PerformanceObserverEntryList` instance.
743pub 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
795/// Heap-identity comparison for two reference values.
796fn same_ref(a: &Value, b: &Value) -> bool {
797    matches!((a, b), (Value::Obj(x), Value::Obj(y)) if x == y)
798}