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.

node: profile and record worker_threads too (#53)

chessMan5e3b48ddc783
diff --git a/src/node.rs b/src/node.rs
index e4ea84a..7c49700 100644
--- a/src/node.rs
+++ b/src/node.rs
@@ -557,6 +557,55 @@ fn without_shim(text: &str, port: &Port) -> String {
mod tests {
use super::*;
+ #[test]
+ fn worker_threads_are_recorded() {
+ 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-workers-{}", std::process::id()));
+ fs::create_dir_all(&dir).unwrap();
+ fs::write(dir.join("recorder.cjs"), RECORDER).unwrap();
+ fs::write(
+ dir.join("lib.cjs"),
+ "function sq(x) {\n return x * x;\n}\nsq = globalThis.__fastAnythingWrap ? globalThis.__fastAnythingWrap(sq) : sq;\nmodule.exports = { sq };\n",
+ )
+ .unwrap();
+ fs::write(
+ dir.join("app.cjs"),
+ "const { Worker, isMainThread, parentPort } = require(\"node:worker_threads\");\n\
+ const { sq } = require(\"./lib.cjs\");\n\
+ if (isMainThread) {\n\
+ \x20 sq(1);\n\
+ \x20 for (let i = 0; i < 2; i++) new Worker(__filename).on(\"message\", (m) => console.log(m));\n\
+ } else {\n\
+ \x20 let t = 0;\n\
+ \x20 for (let i = 0; i < 5; i++) t += sq(i);\n\
+ \x20 parentPort.postMessage(t);\n\
+ }\n",
+ )
+ .unwrap();
+ let out = Command::new("node")
+ .args(["--require", "./recorder.cjs", "app.cjs"])
+ .current_dir(&dir)
+ .env("FAST_ANYTHING_RECORD_OUT", dir.join("rec.jsonl"))
+ .env("FAST_ANYTHING_RECORD_META", dir.join("rec.meta.json"))
+ .env("FAST_ANYTHING_RECORD_LIMIT", "500")
+ .output()
+ .unwrap();
+ let meta = fs::read_to_string(dir.join("rec.meta.json")).unwrap_or_default();
+ let lines = fs::read_to_string(dir.join("rec.jsonl")).unwrap_or_default().lines().count();
+ let leftovers = fs::read_dir(&dir)
+ .unwrap()
+ .filter(|e| e.as_ref().unwrap().file_name().to_string_lossy().contains(".t"))
+ .count();
+ let _ = fs::remove_dir_all(&dir);
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ let meta: Value = serde_json::from_str(&meta).unwrap();
+ assert_eq!((meta["calls"].clone(), lines), (json!(11), 11), "1 call in the main thread, 5 in each worker");
+ assert_eq!(leftovers, 0, "worker files are absorbed and removed");
+ }
+
#[test]
fn maps_typescript() {
assert_eq!(rust_type("number").as_deref(), Some("f64"));
diff --git a/src/node/recorder.cjs b/src/node/recorder.cjs
index 3f04b33..13544ad 100644
--- a/src/node/recorder.cjs
+++ b/src/node/recorder.cjs
@@ -76,7 +76,47 @@ globalThis.__fastAnythingWrap = (fn) =>
return result;
};
+// Each worker thread loads this too (workers inherit --require): it writes its calls next to the main
+// thread's files, and the main thread adds them in when the app exits.
+const { isMainThread, threadId } = require("node:worker_threads");
+const workerFile = (file, id) => `${file}.t${id}`;
+
+function write(outFile, metaFile) {
+ fs.writeFileSync(outFile, kept.map((c) => JSON.stringify(c)).join("\n") + (kept.length ? "\n" : ""));
+ fs.writeFileSync(metaFile, JSON.stringify({ calls, kept: kept.length, skipped, unsupported: [...unsupported], mutates }));
+}
+
+function workerIds() {
+ const dir = require("node:path").dirname(out);
+ const prefix = require("node:path").basename(workerFile(out, ""));
+ return fs.readdirSync(dir).filter((n) => n.startsWith(prefix)).map((n) => n.slice(prefix.length));
+}
+
+if (isMainThread) {
+ for (const id of workerIds()) for (const f of [workerFile(out, id), workerFile(meta, id)]) fs.rmSync(f, { force: true });
+}
+
process.on("exit", () => {
- fs.writeFileSync(out, kept.map((c) => JSON.stringify(c)).join("\n") + (kept.length ? "\n" : ""));
- fs.writeFileSync(meta, JSON.stringify({ calls, kept: kept.length, skipped, unsupported: [...unsupported], mutates }));
+ if (!isMainThread) return write(workerFile(out, threadId), workerFile(meta, threadId));
+ for (const id of workerIds()) {
+ try {
+ const m = JSON.parse(fs.readFileSync(workerFile(meta, id), "utf8"));
+ const cases = fs.readFileSync(workerFile(out, id), "utf8").split("\n").filter((l) => l.trim()).map((l) => JSON.parse(l));
+ calls += m.calls;
+ skipped += m.skipped;
+ for (const u of m.unsupported) unsupported.add(u);
+ mutates = mutates || m.mutates;
+ kept.push(...cases);
+ } catch {} // a worker that was stopped before it finished writing
+ for (const f of [workerFile(out, id), workerFile(meta, id)]) fs.rmSync(f, { force: true });
+ }
+ if (kept.length > limit) {
+ // keep a sample of `limit` calls across all threads
+ for (let i = 0; i < limit; i++) {
+ const j = i + rand(kept.length - i);
+ [kept[i], kept[j]] = [kept[j], kept[i]];
+ }
+ kept.length = limit;
+ }
+ write(out, meta);
});
diff --git a/src/node/runner.mjs b/src/node/runner.mjs
index 741260f..57e557b 100644
--- a/src/node/runner.mjs
+++ b/src/node/runner.mjs
@@ -233,30 +233,32 @@ function projectRelative(root, file) {
function profile(job) {
const names = readdirSync(job.dir).filter((f) => f.endsWith(".cpuprofile"));
if (!names.length) throw new Error("node wrote no .cpuprofile");
- names.sort((a, b) => statSync(path.join(job.dir, b)).size - statSync(path.join(job.dir, a)).size);
- const prof = JSON.parse(readFileSync(path.join(job.dir, names[0]), "utf8"));
-
- const byId = new Map(prof.nodes.map((n) => [n.id, n]));
- const parent = new Map();
- for (const n of prof.nodes) for (const c of n.children || []) parent.set(c, n.id);
- const selfUs = new Map();
- prof.samples.forEach((id, i) => selfUs.set(id, (selfUs.get(id) || 0) + (prof.timeDeltas[i] || 0)));
- const total = (prof.endTime - prof.startTime) / 1e6;
-
+ // one profile per thread (worker_threads) and process: add them all up. The run took as long as
+ // the longest one, the main thread's.
const key = (n) => `${n.callFrame.url}:${n.callFrame.lineNumber}:${n.callFrame.columnNumber}:${n.callFrame.functionName}`;
const funcs = new Map();
- for (const n of prof.nodes) if (!funcs.has(key(n))) funcs.set(key(n), { frame: n.callFrame, self: 0, cum: 0 });
- for (const [id, us] of selfUs) {
- let node = byId.get(id);
- funcs.get(key(node)).self += us;
- const seen = new Set();
- while (node) {
- const k = key(node);
- if (!seen.has(k)) {
- seen.add(k);
- funcs.get(k).cum += us;
+ let total = 0;
+ for (const name of names) {
+ const prof = JSON.parse(readFileSync(path.join(job.dir, name), "utf8"));
+ total = Math.max(total, (prof.endTime - prof.startTime) / 1e6);
+ const byId = new Map(prof.nodes.map((n) => [n.id, n]));
+ const parent = new Map();
+ for (const n of prof.nodes) for (const c of n.children || []) parent.set(c, n.id);
+ const selfUs = new Map();
+ prof.samples.forEach((id, i) => selfUs.set(id, (selfUs.get(id) || 0) + (prof.timeDeltas[i] || 0)));
+ for (const n of prof.nodes) if (!funcs.has(key(n))) funcs.set(key(n), { frame: n.callFrame, self: 0, cum: 0 });
+ for (const [id, us] of selfUs) {
+ let node = byId.get(id);
+ funcs.get(key(node)).self += us;
+ const seen = new Set();
+ while (node) {
+ const k = key(node);
+ if (!seen.has(k)) {
+ seen.add(k);
+ funcs.get(k).cum += us;
+ }
+ node = byId.get(parent.get(node.id));
}
- node = byId.get(parent.get(node.id));
}
}