Skip to content

Don't rewrite it in Rust. Rewrite the 5% that's slow: profile your app, port the hot functions with your coding agent, prove they behave the same. Python, JS/TS, Ruby, Java, Kotlin, Go, PHP, C/C++, C#, R.

scan --duration for Node, Bun and Deno apps

Mohit Mishrae73d01f682b7
diff --git a/README.md b/README.md
index 729436d..f455685 100644
--- a/README.md
+++ b/README.md
@@ -99,7 +99,7 @@ Or wire it up by hand:
| language | binding | status |
|---|---|---|
| Python 3.10+ | PyO3; servers and GUIs: `scan --duration 30` (stops them like Ctrl+C) | ✅ |
-| JavaScript / TypeScript (Node 22+, Bun, Deno 2+: `bun app.ts`, `deno run -A app.ts`) | napi-rs | ✅ |
+| JavaScript / TypeScript (Node 22+, Bun, Deno 2+: `bun app.ts`, `deno run -A app.ts`) | napi-rs; servers: `scan --duration 30` (ends them with `process.exit`) | ✅ |
| Ruby 3.3+ | C ABI + JSON, through Ruby's built-in Fiddle | ✅ |
| Java 22+ (`java App.java`, Maven, Gradle) | the same C bridge, through the FFM API | ✅ |
| Kotlin/JVM (Gradle, `src/main/kotlin`, JDK 22+) | the Java bridge; top-level functions, `object` and companion members, extension functions | ✅ |
diff --git a/src/backend.rs b/src/backend.rs
index cbd92ba..2319066 100644
--- a/src/backend.rs
+++ b/src/backend.rs
@@ -141,14 +141,14 @@ impl Lang {
/// Whether `scan --duration` can stop this language's apps.
pub fn stops_after_duration(self) -> bool {
- matches!(self, Lang::Python | Lang::CSharp)
+ matches!(self, Lang::Python | Lang::Node | Lang::CSharp)
}
/// `duration` (see stops_after_duration): stop the app after that many seconds.
pub fn profile(self, ctx: &Ctx, exe: &str, args: &[String], duration: Option<f64>) -> Result<Profile> {
match self {
Lang::Python => python::profile(ctx, exe, args, duration),
- Lang::Node => node::profile(ctx, exe, args),
+ Lang::Node => node::profile(ctx, exe, args, duration),
Lang::Ruby => ruby::profile(ctx, exe, args),
Lang::Java => java::profile(ctx, exe, args),
Lang::Go => golang::profile(ctx, exe, args),
diff --git a/src/main.rs b/src/main.rs
index d31e29b..e80847d 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -67,7 +67,7 @@ enum Cmd {
},
/// Run your app under a profiler and rank what's worth porting
Scan {
- /// Stop the app after this many seconds and rank what ran (Python, C#: servers and GUIs that don't exit)
+ /// Stop the app after this many seconds and rank what ran (Python, Node, C#: servers and GUIs that don't exit)
#[arg(long, value_name = "SECS")]
duration: Option<f64>,
/// How you run your app, after --
diff --git a/src/mcp.rs b/src/mcp.rs
index edb3722..1051f10 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -23,7 +23,7 @@ fn tools() -> Value {
tool(
"fast_scan",
"Run the app under a profiler and rank functions by time share and portability to Rust.",
- json!({ "command": { "type": "array", "items": { "type": "string" }, "description": "How the app runs, e.g. [\"python\", \"app.py\"] or [\"go\", \"run\", \".\"]" }, "duration": { "type": "number", "description": "Python and C#: stop the app after this many seconds (GUIs, servers)" }, "path": path }),
+ json!({ "command": { "type": "array", "items": { "type": "string" }, "description": "How the app runs, e.g. [\"python\", \"app.py\"] or [\"go\", \"run\", \".\"]" }, "duration": { "type": "number", "description": "Python, Node and C#: stop the app after this many seconds (GUIs, servers)" }, "path": path }),
json!(["command"])
),
tool(
diff --git a/src/node.rs b/src/node.rs
index bf756a0..69c81da 100644
--- a/src/node.rs
+++ b/src/node.rs
@@ -11,9 +11,11 @@ use serde_json::{Value, json};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};
+use std::time::Duration;
const RUNNER: &str = include_str!("node/runner.mjs");
const RECORDER: &str = include_str!("node/recorder.cjs");
+const STOP: &str = include_str!("node/stop.cjs");
pub fn is_node(program: &str) -> bool {
Runtime::of(program).is_some()
@@ -136,20 +138,31 @@ fn runner(ctx: &Ctx, node: &str, mode: &str, job: Value) -> Result<Output> {
Ok(out)
}
-pub fn profile(ctx: &Ctx, node: &str, args: &[String]) -> Result<Profile> {
+/// `duration`: end the app after that many seconds (servers and GUIs that run until closed).
+pub fn profile(ctx: &Ctx, node: &str, args: &[String], duration: Option<f64>) -> Result<Profile> {
let script = entry(args).context("name the script to run, e.g. fast-anything scan -- node app.js")?;
let dir = ctx.fast.join("cpuprof");
let _ = fs::remove_dir_all(&dir);
fs::create_dir_all(&dir)?;
let runtime = runtime_of(node);
let dir_text = dir.to_string_lossy().into_owned();
- let out = output(
- Command::new(node)
- .args(runtime.with(&["--cpu-prof", "--cpu-prof-interval", "250", "--cpu-prof-dir", &dir_text], args))
- .current_dir(&ctx.root)
- .stdin(Stdio::null()),
+ let stop = ctx.fast.join("stop.cjs");
+ let stop_text = stop.to_string_lossy().into_owned();
+ let mut options = vec!["--cpu-prof", "--cpu-prof-interval", "250", "--cpu-prof-dir", &dir_text];
+ let mut cmd = Command::new(node);
+ if let Some(d) = duration {
+ // the app ends itself (process.exit), so the profile is written as on a normal exit
+ fs::write(&stop, STOP)?;
+ options.extend([if runtime == Runtime::Node { "--require" } else { "--preload" }, &stop_text]);
+ cmd.env("FAST_ANYTHING_STOP_AFTER_MS", ((d * 1000.0) as u64).to_string());
+ }
+ let (out, killed) = crate::util::output_for(
+ cmd.args(runtime.with(&options, args)).current_dir(&ctx.root).stdin(Stdio::null()),
runtime.name(),
+ duration.map(|d| Duration::from_secs_f64(d + 15.0)),
+ Duration::from_secs(10),
)?;
+ ensure!(!killed, "the app was still running 15s after --duration: does it call process.exit?");
ensure!(out.status.success(), "the app failed ({}):\n{}", out.status, tail(&combined(&out), 30));
let result = ctx.fast.join("profile.json");
let job = json!({ "root": ctx.root, "dir": dir, "entry": ctx.root.join(script), "out": result });
@@ -1023,6 +1036,27 @@ for (const worst of [
assert_eq!(entry(&args("run app.ts")).map(String::as_str), Some("app.ts"));
}
+ #[test]
+ fn duration_ends_an_app_that_runs_until_closed() {
+ if !Command::new("node").arg("--version").output().is_ok_and(|o| o.status.success()) {
+ eprintln!("no node on PATH, skipping");
+ return;
+ }
+ let dir = std::env::temp_dir().join(format!("fa-node-duration-test-{}", std::process::id()));
+ fs::create_dir_all(&dir).unwrap();
+ // a server's shape: work on a timer, forever
+ let app = "function work(n) {\n let s = 0;\n for (let i = 0; i < n; i++) s += i * i;\n return s;\n}\nsetInterval(() => work(3e6), 5);\n";
+ fs::write(dir.join("app.js"), app).unwrap();
+ let ctx = Ctx::open(&dir).unwrap();
+ let started = std::time::Instant::now();
+ let p = profile(&ctx, "node", &["app.js".into()], Some(1.5));
+ let took = started.elapsed().as_secs_f64();
+ let _ = fs::remove_dir_all(&dir);
+ let p = p.unwrap();
+ assert!(p.functions.iter().any(|f| f.name == "work"), "{:?}", p.functions);
+ assert!(took < 12.0, "{took}");
+ }
+
#[test]
fn worker_threads_are_recorded() {
if !Command::new("node").arg("--version").output().is_ok_and(|o| o.status.success()) {
diff --git a/src/node/stop.cjs b/src/node/stop.cjs
new file mode 100644
index 0000000..2fad1c6
--- /dev/null
+++ b/src/node/stop.cjs
@@ -0,0 +1,10 @@
+// fast-anything: ends the app after FAST_ANYTHING_STOP_AFTER_MS (scan --duration), so --cpu-prof
+// writes the profile of what ran. Preloaded for that run only. Not meant to be used by hand.
+const ms = Number(globalThis.process?.env?.FAST_ANYTHING_STOP_AFTER_MS);
+let main = true;
+try {
+ main = require("node:worker_threads").isMainThread;
+} catch {
+ // no worker_threads: there's only the main thread
+}
+if (ms > 0 && main) setTimeout(() => process.exit(0), ms).unref();
diff --git a/src/pipeline.rs b/src/pipeline.rs
index 14175a5..1d49cbf 100644
--- a/src/pipeline.rs
+++ b/src/pipeline.rs
@@ -36,7 +36,7 @@ pub fn scan(root: &Path, command: Vec<String>, duration: Option<f64>) -> Result<
let lang = crate::cfamily::refine(Lang::detect(&command[0])?, &command[1..]);
let lang = crate::kotlin::refine(lang, &command[0], &ctx.root);
if let Some(d) = duration {
- ensure!(lang.stops_after_duration(), "--duration works for Python and C# apps only so far");
+ ensure!(lang.stops_after_duration(), "--duration works for Python, JavaScript/TypeScript and C# apps only so far");
ensure!(d.is_finite() && d > 0.0, "--duration takes a number of seconds, e.g. --duration 30");
}
let exe = lang.resolve(&command[0], &ctx.root)?;