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.
Rust agent-skillsai-agentsclaude-codeclaude-code-plugincodexdeveloper-toolsffimcpmcp-servernapi-rsnodejsoptimizationperformanceprofilerpyo3pythonrewrite-it-in-rustrubyrusttypescript
scan --duration for Ruby apps
Mohit Mishra30a94a305f08
diff --git a/README.md b/README.mdindex 202dd50..c606e02 100644--- a/README.md+++ b/README.md@@ -100,7 +100,7 @@ Or wire it up by hand:|---|---|---|| 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; servers: `scan --duration 30` (ends them with `process.exit`) | ✅ |-| Ruby 3.3+ | C ABI + JSON, through Ruby's built-in Fiddle | ✅ |+| Ruby 3.3+ | C ABI + JSON, through Ruby's built-in Fiddle; servers: `scan --duration 30` (stops them like Ctrl+C) | ✅ || Java 22+ (`java App.java`, Maven, Gradle) | the same C bridge, through the FFM API; servers: `scan --duration 30` | ✅ || Kotlin/JVM (Gradle, `src/main/kotlin`, JDK 22+) | the Java bridge; top-level functions, `object` and companion members, extension functions | ✅ || Go 1.22+ (`go run .`) | the same C bridge, through the Windows loader or dlopen (cgo); servers: `scan --duration 30` | ✅ |diff --git a/src/backend.rs b/src/backend.rsindex eebe38f..1ef878e 100644--- a/src/backend.rs+++ b/src/backend.rs@@ -141,7 +141,7 @@ impl Lang {/// Whether `scan --duration` can stop this language's apps.pub fn stops_after_duration(self) -> bool {- matches!(self, Lang::Python | Lang::Node | Lang::Go | Lang::Java | Lang::Kotlin | Lang::CSharp)+ matches!(self, Lang::Python | Lang::Node | Lang::Go | Lang::Java | Lang::Kotlin | Lang::Ruby | Lang::CSharp)}/// `duration` (see stops_after_duration): stop the app after that many seconds.@@ -149,7 +149,7 @@ impl Lang {match self {Lang::Python => python::profile(ctx, exe, args, duration),Lang::Node => node::profile(ctx, exe, args, duration),- Lang::Ruby => ruby::profile(ctx, exe, args),+ Lang::Ruby => ruby::profile(ctx, exe, args, duration),Lang::Java => java::profile(ctx, exe, args, duration),Lang::Go => golang::profile(ctx, exe, args, duration),Lang::Php => php::profile(ctx, exe, args),diff --git a/src/main.rs b/src/main.rsindex d435aab..f6e68cc 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 portingScan {- /// Stop the app after this many seconds and rank what ran (Python, Node, Go, Java, Kotlin, C#: servers and GUIs that don't exit)+ /// Stop the app after this many seconds and rank what ran (Python, Node, Go, Java, Kotlin, Ruby, 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.rsindex 04fb179..b4d6643 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, Node, Go, Java, Kotlin 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, Go, Java, Kotlin, Ruby and C#: stop the app after this many seconds (GUIs, servers)" }, "path": path }),json!(["command"])),tool(diff --git a/src/pipeline.rs b/src/pipeline.rsindex 0a7006c..420a392 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, JavaScript/TypeScript, Go, Java, Kotlin and C# apps only so far");+ ensure!(lang.stops_after_duration(), "--duration works for Python, JavaScript/TypeScript, Go, Java, Kotlin, Ruby 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)?;diff --git a/src/ruby.rs b/src/ruby.rsindex 64cab3d..dc4c929 100644--- a/src/ruby.rs+++ b/src/ruby.rs@@ -13,6 +13,7 @@ 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!("ruby/runner.rb");const RECORDER: &str = include_str!("ruby/recorder.rb");@@ -40,12 +41,24 @@ fn main_guard(text: &str) -> Option<usize> {}fn runner(ctx: &Ctx, ruby: &str, mode: &str, job: Value, app_args: &[String]) -> Result<Output> {+ runner_for(ctx, ruby, mode, job, app_args, None)+}++/// runner, stopping the run from outside after `limit` (the app may not stop on Interrupt).+fn runner_for(+ ctx: &Ctx,+ ruby: &str,+ mode: &str,+ job: Value,+ app_args: &[String],+ limit: Option<Duration>,+) -> Result<Output> {let script = ctx.fast.join("runner.rb");fs::write(&script, RUNNER)?;fs::write(ctx.fast.join("recorder.rb"), RECORDER)?;let job_path = ctx.fast.join(format!("job-{mode}.json"));fs::write(&job_path, serde_json::to_vec_pretty(&job)?)?;- let out = output(+ let (out, killed) = crate::util::output_for(Command::new(ruby).arg(&script).arg(mode)@@ -55,16 +68,21 @@ fn runner(ctx: &Ctx, ruby: &str, mode: &str, job: Value, app_args: &[String]) ->.current_dir(&ctx.root).stdin(Stdio::null()),"ruby",+ limit,+ Duration::from_secs(10),)?;+ ensure!(!killed, "the app was still running 15s after --duration: does it stop on Ctrl+C?");if !out.status.success() {bail!("the ruby {mode} step failed ({}):\n{}", out.status, tail(&combined(&out), 30));}Ok(out)}-pub fn profile(ctx: &Ctx, ruby: &str, args: &[String]) -> Result<Profile> {+/// `duration`: interrupt the app after that many seconds (servers and GUIs that run until closed).+pub fn profile(ctx: &Ctx, ruby: &str, args: &[String], duration: Option<f64>) -> Result<Profile> {let result = ctx.fast.join("profile.json");- runner(ctx, ruby, "profile", json!({ "root": ctx.root, "out": result }), args)?;+ let job = json!({ "root": ctx.root, "out": result, "duration": duration });+ runner_for(ctx, ruby, "profile", job, args, duration.map(|d| Duration::from_secs_f64(d + 15.0)))?;serde_json::from_str(&fs::read_to_string(&result)?).context("reading the profile")}@@ -330,6 +348,25 @@ pub fn disable(ctx: &Ctx, port: &Port) -> Result<()> {mod tests {use super::*;+ #[test]+ fn duration_stops_an_app_that_runs_until_closed() {+ if !Command::new("ruby").arg("-v").output().is_ok_and(|o| o.status.success()) {+ eprintln!("no ruby on PATH, skipping");+ return;+ }+ let dir = std::env::temp_dir().join(format!("fa-ruby-duration-test-{}", std::process::id()));+ fs::create_dir_all(&dir).unwrap();+ // a server's shape: some work, then a long blocking wait+ let app = "def work(n)\n (0...n).sum { |i| i * i % 7 }\nend\n\nif __FILE__ == $0\n 3.times { work(200_000) }\n sleep 3600\nend\n";+ fs::write(dir.join("app.rb"), app).unwrap();+ let ctx = Ctx::open(&dir).unwrap();+ let p = profile(&ctx, "ruby", &["app.rb".into()], Some(1.0));+ let _ = fs::remove_dir_all(&dir);+ let p = p.unwrap();+ assert!(p.functions.iter().any(|f| f.name == "work" && f.ncalls == 3), "{:?}", p.functions);+ assert!((0.9..10.0).contains(&p.wall), "{}", p.wall);+ }+#[test]fn ruby_defaults_become_json() {assert_eq!(default_json("2").as_deref(), Some("2"));diff --git a/src/ruby/runner.rb b/src/ruby/runner.rbindex a375e7b..237e39a 100644--- a/src/ruby/runner.rb+++ b/src/ruby/runner.rb@@ -186,8 +186,21 @@ def cmd_profile(job, argv)stack.last[2] += took if stack.lastendend+ # scan --duration: a server or GUI runs until closed, so interrupt it after that long, like Ctrl+C+ stopped = false+ stopper = job["duration"] && Thread.new do+ sleep job["duration"]+ stopped = true+ Thread.main.raise(Interrupt)+ endstarted = Process.clock_gettime(clock)- tracer.enable { run_target(script, rest) }+ begin+ tracer.enable { run_target(script, rest) }+ rescue Interrupt, SystemExit+ raise unless stopped # the app's own, not the one --duration sent+ ensure+ stopper&.kill+ endwall = Process.clock_gettime(clock) - startedrows = stats.filter_map do |(path, name), (calls, own, cum)|