Skip to content

armgit / raea

Public Imported from GitHub
0

Render Anything Engine: tell your AI what to make. Videos, motion graphics, 3D and games as React and TypeScript, rendered on your own GPU. Rust + Bevy, macOS, Linux and Windows.

A page's JS engine gives its free pages back every 5 s, and with RAEA_INSPECT its heap is logged and JavaScriptCore's context inspectable

shinyobjectz4b1cb9ec9ac8
diff --git a/runtime/dom/src/host.rs b/runtime/dom/src/host.rs
index eca0e792..1b8473ff 100644
--- a/runtime/dom/src/host.rs
+++ b/runtime/dom/src/host.rs
@@ -71,6 +71,8 @@ pub struct Root {
frames_seen: std::collections::HashSet<(NodeId, String)>,
/// a context call committed the JS's writes before the drain did (PageSync::commit)
synced: bool,
+ /// its JS engine's free pages given back, and with RAEA_INSPECT its heap logged (raea_runtime_jsengine::Upkeep)
+ upkeep: raea_runtime_js::js::Upkeep,
}
/// What a root's JS calls lend its context host calls (raea_runtime_js::calls::on_sync_ctx: style.computed's resolve, a
diff --git a/runtime/dom/src/host/frames.rs b/runtime/dom/src/host/frames.rs
index df4891a9..658c77c5 100644
--- a/runtime/dom/src/host/frames.rs
+++ b/runtime/dom/src/host/frames.rs
@@ -107,7 +107,7 @@ pub(crate) fn root_on(world: &mut World, page: Entity, nodes: Nodes, w: u32, h:
}
scripts.extend(preamble.iter().enumerate().map(|(i, s)| (s.clone(), format!("preamble{i}.js"))));
scripts.push((code.to_string(), "bundle.js".into()));
- let mut root = Root { page, js, out, nodes, queue: Vec::new(), ticking: false, clicks: 1, capture: None, hover_frozen: None, medias: Default::default(), views: Default::default(), fonts_wait: None, bevy_ui: false, placed_videos: false, frame, frames_seen: Default::default(), synced: false };
+ let mut root = Root { page, js, out, nodes, queue: Vec::new(), ticking: false, clicks: 1, capture: None, hover_frozen: None, medias: Default::default(), views: Default::default(), fonts_wait: None, bevy_ui: false, placed_videos: false, frame, frames_seen: Default::default(), synced: false, upkeep: raea_runtime_js::js::Upkeep::from_env() };
for (src, name) in &scripts {
root.js(world, |js| js.eval(src, name)).map_err(|e| format!("{name}: {e}"))?;
}
diff --git a/runtime/dom/src/host/step.rs b/runtime/dom/src/host/step.rs
index 77caedd5..8c274430 100644
--- a/runtime/dom/src/host/step.rs
+++ b/runtime/dom/src/host/step.rs
@@ -56,6 +56,8 @@ pub fn step(world: &mut World) {
committed |= drain(world, r);
}
r.js(world, |js| js.idle());
+ // (no host calls in it: a collection, the engine's pages, its heap's numbers)
+ r.upkeep.tick(r.js.as_mut());
if let Some(f) = &r.frame {
swap_frame(world, r.page, f);
}
diff --git a/runtime/js/src/js.rs b/runtime/js/src/js.rs
index 3af8aaf2..19490908 100644
--- a/runtime/js/src/js.rs
+++ b/runtime/js/src/js.rs
@@ -10,7 +10,7 @@
use std::cell::RefCell;
use std::rc::Rc;
-pub use raea_runtime_jsengine::{Arg, Engine, JsEngine, now_ms};
+pub use raea_runtime_jsengine::{Arg, Engine, JsEngine, Upkeep, now_ms};
use raea_runtime_jsengine::{Native, Ret, arg, clock};
/// What a root's JS handed the host since it was last drained.
diff --git a/runtime/jsengine/src/jsc.rs b/runtime/jsengine/src/jsc.rs
index 5bd6d072..16937d98 100644
--- a/runtime/jsengine/src/jsc.rs
+++ b/runtime/jsengine/src/jsc.rs
@@ -20,6 +20,14 @@ unsafe extern "C" {
}
const RTLD_DEFAULT: *mut c_void = -2isize as *mut c_void;
+/// A call JavaScriptCore exports without declaring it (not in the SDK's headers, or newer than it), looked up by name:
+/// None where this system has none. `F` is its `unsafe extern "C" fn` type.
+fn spi<F: Copy>(name: &std::ffi::CStr) -> Option<F> {
+ let p = unsafe { dlsym(RTLD_DEFAULT, name.as_ptr()) };
+ // SAFETY: a symbol of that name is that function, and F is a function pointer, the size of p
+ (!p.is_null()).then(|| unsafe { std::mem::transmute_copy::<*mut c_void, F>(&p) })
+}
+
#[link(name = "CoreFoundation", kind = "framework")]
unsafe extern "C" {
static kCFRunLoopDefaultMode: *const c_void;
@@ -71,6 +79,7 @@ unsafe extern "C" {
fn JSValueMakeUndefined(ctx: Ctx) -> Val;
fn JSObjectMakeError(ctx: Ctx, argc: usize, argv: *const Val, exception: *mut Val) -> Obj;
fn JSGarbageCollect(ctx: Ctx);
+ fn JSValueCreateJSONString(ctx: Ctx, value: Val, indent: u32, exception: *mut Val) -> Str;
fn JSContextGetGroup(ctx: Ctx) -> *const c_void;
fn JSValueUnprotect(ctx: Ctx, v: Val);
fn JSClassCreate(definition: *const ClassDefinition) -> *mut c_void;
@@ -182,10 +191,7 @@ pub fn options() {
pub fn release_free_memory() -> Option<f64> {
type Release = unsafe extern "C" fn();
static RELEASE: std::sync::OnceLock<Option<Release>> = std::sync::OnceLock::new();
- let f = RELEASE.get_or_init(|| unsafe {
- let p = dlsym(RTLD_DEFAULT, c"_ZN3WTF27releaseFastMallocFreeMemoryEv".as_ptr());
- (!p.is_null()).then(|| std::mem::transmute::<*mut c_void, Release>(p))
- });
+ let f = RELEASE.get_or_init(|| spi(c"_ZN3WTF27releaseFastMallocFreeMemoryEv"));
let f = (*f)?;
let t = std::time::Instant::now();
unsafe { f() };
@@ -285,7 +291,11 @@ impl Default for Context {
impl Context {
pub fn new() -> Context {
options();
- Context { ctx: unsafe { JSGlobalContextCreate(null_mut()) } }
+ let ctx = unsafe { JSGlobalContextCreate(null_mut()) };
+ if crate::inspect() {
+ inspect::inspectable(ctx);
+ }
+ Context { ctx }
}
fn c(&self) -> Ctx {
@@ -376,12 +386,8 @@ impl Context {
unsafe extern "C" fn stop(_: Ctx, _: *mut c_void) -> bool {
true
}
- unsafe {
- let p = dlsym(RTLD_DEFAULT, c"JSContextGroupSetExecutionTimeLimit".as_ptr());
- if !p.is_null() {
- let f = std::mem::transmute::<*mut c_void, SetLimit>(p);
- f(JSContextGetGroup(self.c()), limit.as_secs_f64(), Some(stop), null_mut());
- }
+ if let Some(f) = spi::<SetLimit>(c"JSContextGroupSetExecutionTimeLimit") {
+ unsafe { f(JSContextGetGroup(self.c()), limit.as_secs_f64(), Some(stop), null_mut()) };
}
}
@@ -402,10 +408,7 @@ impl Context {
pub fn collect_young(&self) -> bool {
type Eden = unsafe extern "C" fn(Ctx);
static EDEN: std::sync::OnceLock<Option<Eden>> = std::sync::OnceLock::new();
- let f = EDEN.get_or_init(|| unsafe {
- let p = dlsym(RTLD_DEFAULT, c"JSSynchronousEdenCollectForDebugging".as_ptr());
- (!p.is_null()).then(|| std::mem::transmute::<*mut c_void, Eden>(p))
- });
+ let f = EDEN.get_or_init(|| spi(c"JSSynchronousEdenCollectForDebugging"));
match f {
Some(f) => {
unsafe { f(self.c()) };
@@ -437,10 +440,7 @@ impl Context {
pub fn collect(&self) {
type Sync = unsafe extern "C" fn(Ctx);
static SYNC: std::sync::OnceLock<Option<Sync>> = std::sync::OnceLock::new();
- let f = SYNC.get_or_init(|| unsafe {
- let p = dlsym(RTLD_DEFAULT, c"JSSynchronousGarbageCollectForDebugging".as_ptr());
- (!p.is_null()).then(|| std::mem::transmute::<*mut c_void, Sync>(p))
- });
+ let f = SYNC.get_or_init(|| spi(c"JSSynchronousGarbageCollectForDebugging"));
unsafe {
match f {
Some(f) => f(self.c()),
@@ -464,4 +464,5 @@ impl Drop for Context {
pub mod modules;
mod host;
+mod inspect;
pub use host::Jsc;
diff --git a/runtime/jsengine/src/jsc/host.rs b/runtime/jsengine/src/jsc/host.rs
index b05f2df2..6e3359ca 100644
--- a/runtime/jsengine/src/jsc/host.rs
+++ b/runtime/jsengine/src/jsc/host.rs
@@ -75,4 +75,8 @@ impl JsEngine for Jsc {
fn idle(&mut self) {
pump();
}
+
+ fn heap(&mut self) -> Option<String> {
+ self.ctx.heap()
+ }
}
diff --git a/runtime/jsengine/src/jsc/inspect.rs b/runtime/jsengine/src/jsc/inspect.rs
new file mode 100644
index 00000000..86d75cf9
--- /dev/null
+++ b/runtime/jsengine/src/jsc/inspect.rs
@@ -0,0 +1,39 @@
+//! What a JavaScriptCore context holds, for the heap log (crate::Upkeep, RAEA_INSPECT), and the context opened to
+//! Safari's Web Inspector: both through calls the system exports without declaring them (super::spi).
+
+use super::*;
+
+impl Context {
+ /// What the heap holds, as JSON: JavaScriptCore's own statistics (JSGetMemoryUsageStatistics, exported by the system
+ /// though not in its headers: heapSize, heapCapacity, extraMemorySize, objectCount, protectedObjectCount,
+ /// objectTypeCounts by class), found at run time. None where the system doesn't export it.
+ pub fn heap(&self) -> Option<String> {
+ type Stats = unsafe extern "C" fn(Ctx) -> Obj;
+ static STATS: std::sync::OnceLock<Option<Stats>> = std::sync::OnceLock::new();
+ let f = (*STATS.get_or_init(|| spi(c"JSGetMemoryUsageStatistics")))?;
+ unsafe {
+ let stats = f(self.c());
+ if stats.is_null() {
+ return None;
+ }
+ let json = JSValueCreateJSONString(self.c(), stats as Val, 0, null_mut());
+ if json.is_null() {
+ return None;
+ }
+ let v = JSValueMakeString(self.c(), json);
+ JSStringRelease(json);
+ Some(to_string(self.c(), v))
+ }
+ }
+}
+
+/// The context listed in Safari's Develop menu, for its Web Inspector (heap snapshots, what holds an object, the
+/// console), when RAEA_INSPECT is on: JSGlobalContextSetInspectable, macOS 13.3 and later, found at run time so an older
+/// system starts as before.
+pub(super) fn inspectable(ctx: GCtx) {
+ type Set = unsafe extern "C" fn(GCtx, bool);
+ match spi::<Set>(c"JSGlobalContextSetInspectable") {
+ Some(f) => unsafe { f(ctx, true) },
+ None => eprintln!("raea-runtime-jsengine: this system's JavaScriptCore can't be inspected (macOS 13.3 or later)"),
+ }
+}
diff --git a/runtime/jsengine/src/lib.rs b/runtime/jsengine/src/lib.rs
index 94bfc11d..42149aae 100644
--- a/runtime/jsengine/src/lib.rs
+++ b/runtime/jsengine/src/lib.rs
@@ -15,6 +15,8 @@ use std::rc::Rc;
pub mod jsc;
#[cfg(any(feature = "portable", not(target_vendor = "apple")))]
mod quickjs;
+mod upkeep;
+pub use upkeep::{Upkeep, inspect};
/// An argument to a global function.
pub enum Arg<'a> {
@@ -97,6 +99,11 @@ pub trait JsEngine {
}
/// Between frames: the engine's own upkeep (JavaScriptCore's GC timers live on the thread's run loop).
fn idle(&mut self) {}
+ /// What its heap holds now, as one JSON object, for the heap log (Upkeep): JavaScriptCore's statistics (its size and
+ /// objects counted by type), QuickJS's memory usage. None where the engine can't say.
+ fn heap(&mut self) -> Option<String> {
+ None
+ }
}
/// Whether `error` is a run stopped by its time limit (JavaScriptCore's watchdog, QuickJS's interrupt).
diff --git a/runtime/jsengine/src/quickjs.rs b/runtime/jsengine/src/quickjs.rs
index 9042ec85..64575343 100644
--- a/runtime/jsengine/src/quickjs.rs
+++ b/runtime/jsengine/src/quickjs.rs
@@ -158,4 +158,12 @@ impl JsEngine for Quick {
fn collect(&mut self) {
self.rt.run_gc();
}
+
+ fn heap(&mut self) -> Option<String> {
+ let m = self.rt.memory_usage();
+ Some(format!(
+ r#"{{"mallocSize":{},"memoryUsed":{},"objectCount":{},"objectSize":{},"propertyCount":{},"stringCount":{},"stringSize":{},"arrayCount":{},"functionCount":{},"shapeCount":{},"binaryObjectCount":{},"binaryObjectSize":{}}}"#,
+ m.malloc_size, m.memory_used_size, m.obj_count, m.obj_size, m.prop_count, m.str_count, m.str_size, m.array_count, m.js_func_count, m.shape_count, m.binary_object_count, m.binary_object_size
+ ))
+ }
}
diff --git a/runtime/jsengine/src/upkeep.rs b/runtime/jsengine/src/upkeep.rs
new file mode 100644
index 00000000..1b155b19
--- /dev/null
+++ b/runtime/jsengine/src/upkeep.rs
@@ -0,0 +1,94 @@
+//! A page's JS engine looked after between frames, the same on every engine.
+//!
+//! - Its free pages go back to the system every few seconds (RAEA_JSC_RELEASE_S, 5; 0 never), as raea-runtime-react's
+//! JS thread already gives them back. A page's JS didn't: JavaScriptCore keeps what it frees resident until asked,
+//! and the 0.1.6 app's window showed ~300 MB of its JS memory reclaimable and still held (11-16).
+//! - With RAEA_INSPECT on, its heap is logged: every RAEA_JS_HEAP_S seconds (30; 0 never) a full collection, then one
+//! JSON line in ~/.raea/logs/js-heap-<pid>-<n>.jsonl (the process's nth engine). So what a page holds can be read over a
+//! whole session, on any engine, without a debugger: what grows from line to line (JavaScriptCore's
+//! objectTypeCounts, QuickJS's object and string counts) is what it keeps. The collection stops the page's thread
+//! (gc_ms in each line says for how long), which is why the log is off unless asked for.
+
+use std::fs::File;
+use std::io::Write;
+use std::path::PathBuf;
+use std::sync::atomic::{AtomicU32, Ordering};
+use std::time::{Instant, SystemTime, UNIX_EPOCH};
+
+use crate::JsEngine;
+
+/// RAEA_INSPECT is on (set and not "0"): the heap log, and on JavaScriptCore the context listed in Safari's Develop
+/// menu for its Web Inspector.
+pub fn inspect() -> bool {
+ !matches!(std::env::var("RAEA_INSPECT").as_deref(), Err(_) | Ok("" | "0"))
+}
+
+pub struct Upkeep {
+ release_every: f64,
+ released: Instant,
+ heap_every: f64,
+ logged: Instant,
+ log: Option<File>,
+ started: Instant,
+}
+
+impl Upkeep {
+ /// Its settings from the environment; with the heap log on, its file opened (one per engine).
+ pub fn from_env() -> Upkeep {
+ let secs = |k: &str| std::env::var(k).ok().and_then(|v| v.parse::<f64>().ok());
+ let heap_every = secs("RAEA_JS_HEAP_S").unwrap_or(if inspect() { 30.0 } else { 0.0 });
+ let log = if heap_every > 0.0 { open_log() } else { None };
+ let now = Instant::now();
+ Upkeep { release_every: secs("RAEA_JSC_RELEASE_S").unwrap_or(5.0), released: now, heap_every, logged: now, log, started: now }
+ }
+
+ /// Between frames: what's due of the two.
+ pub fn tick(&mut self, js: &mut dyn JsEngine) {
+ if self.release_every > 0.0 && self.released.elapsed().as_secs_f64() >= self.release_every {
+ js.release_memory();
+ self.released = Instant::now();
+ }
+ if self.log.is_some() && self.logged.elapsed().as_secs_f64() >= self.heap_every {
+ self.write(js);
+ self.logged = Instant::now();
+ }
+ }
+
+ fn write(&mut self, js: &mut dyn JsEngine) {
+ let t = Instant::now();
+ js.collect();
+ let gc_ms = t.elapsed().as_secs_f64() * 1e3;
+ let Some(heap) = js.heap() else {
+ eprintln!("raea-runtime-jsengine: {} doesn't say what its heap holds; no heap log", js.name());
+ self.log = None;
+ return;
+ };
+ let at = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
+ let up = self.started.elapsed().as_secs();
+ let engine = js.name();
+ if let Some(f) = self.log.as_mut() {
+ let _ = writeln!(f, r#"{{"at":{at},"up_s":{up},"engine":"{engine}","gc_ms":{gc_ms:.1},"heap":{heap}}}"#);
+ }
+ }
+}
+
+fn open_log() -> Option<File> {
+ static N: AtomicU32 = AtomicU32::new(0);
+ let home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"))?;
+ let dir = PathBuf::from(home).join(".raea").join("logs");
+ if let Err(e) = std::fs::create_dir_all(&dir) {
+ eprintln!("raea-runtime-jsengine: no heap log in {}: {e}", dir.display());
+ return None;
+ }
+ let path = dir.join(format!("js-heap-{}-{}.jsonl", std::process::id(), N.fetch_add(1, Ordering::Relaxed)));
+ match File::options().create(true).append(true).open(&path) {
+ Ok(f) => {
+ eprintln!("raea-runtime-jsengine: the JS heap's log: {}", path.display());
+ Some(f)
+ }
+ Err(e) => {
+ eprintln!("raea-runtime-jsengine: no heap log at {}: {e}", path.display());
+ None
+ }
+ }
+}