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 Java and Kotlin apps
Mohit Mishrada4002e4e6f4
diff --git a/README.md b/README.mdindex e014307..202dd50 100644--- a/README.md+++ b/README.md@@ -101,7 +101,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 | ✅ |-| Java 22+ (`java App.java`, Maven, Gradle) | the same C bridge, through the FFM API | ✅ |+| 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` | ✅ || PHP 8.1+ (`php app.php`) | the same C bridge, through PHP's FFI extension (`extension=ffi`) | ✅ |diff --git a/src/backend.rs b/src/backend.rsindex f3e8e0d..eebe38f 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::CSharp)+ matches!(self, Lang::Python | Lang::Node | Lang::Go | Lang::Java | Lang::Kotlin | Lang::CSharp)}/// `duration` (see stops_after_duration): stop the app after that many seconds.@@ -150,13 +150,13 @@ impl Lang {Lang::Python => python::profile(ctx, exe, args, duration),Lang::Node => node::profile(ctx, exe, args, duration),Lang::Ruby => ruby::profile(ctx, exe, args),- Lang::Java => java::profile(ctx, exe, args),+ Lang::Java => java::profile(ctx, exe, args, duration),Lang::Go => golang::profile(ctx, exe, args, duration),Lang::Php => php::profile(ctx, exe, args),Lang::C | Lang::Cpp => cfamily::profile(ctx, exe, args, self),Lang::CSharp => csharp::profile(ctx, exe, args, duration),Lang::R => r::profile(ctx, exe, args),- Lang::Kotlin => kotlin::profile(ctx, exe, args),+ Lang::Kotlin => kotlin::profile(ctx, exe, args, duration),}}diff --git a/src/java.rs b/src/java.rsindex fded5c6..162a385 100644--- a/src/java.rs+++ b/src/java.rs@@ -15,7 +15,7 @@ use std::collections::{HashMap, HashSet};use std::fs;use std::path::{Path, PathBuf};use std::process::{Command, Stdio};-use std::time::Instant;+use std::time::{Duration, Instant};const DESCRIBE: &str = include_str!("java/Describe.java");pub(crate) const JSON: &str = include_str!("java/Json.java");@@ -251,16 +251,17 @@ pub(crate) fn app_command(program: &str, args: &[String]) -> Command {cmd}-pub fn profile(ctx: &Ctx, program: &str, args: &[String]) -> Result<Profile> {- profile_with(ctx, program, args, |java| describe(ctx, java, &sources(&ctx.root, program, args)?))+pub fn profile(ctx: &Ctx, program: &str, args: &[String], duration: Option<f64>) -> Result<Profile> {+ profile_with(ctx, program, args, duration, |java| describe(ctx, java, &sources(&ctx.root, program, args)?))}/// Profile the app with Flight Recorder and rank the methods `describe` finds in its sources-/// (given the JDK that runs the build).+/// (given the JDK that runs the build). `duration`: stop the app after that many seconds.pub(crate) fn profile_with(ctx: &Ctx,program: &str,args: &[String],+ duration: Option<f64>,describe: impl FnOnce(&str) -> Result<Vec<Method>>,) -> Result<Profile> {let build = runner(program) != Some(Runner::Source);@@ -268,8 +269,11 @@ pub(crate) fn profile_with(let jfr_dir = ctx.fast.join("jfr");let _ = fs::remove_dir_all(&jfr_dir);fs::create_dir_all(&jfr_dir)?;+ // with --duration, the recording also ends (and is written) on its own after that long: where+ // the app can't be asked to close (a console app on Windows), it's then stopped without losing it+ let window = duration.map(|d| format!(",duration={}s", d.ceil() as u64)).unwrap_or_default();let flags = format!(- "-XX:StartFlightRecording:filename={}/%p.jfr,settings=profile -Xlog:jfr+startup=error",+ "-XX:StartFlightRecording:filename={}/%p.jfr,settings=profile{window} -Xlog:jfr+startup=error",util::forward_slashes(&jfr_dir));let mut cmd = if build { app_command(program, args) } else { Command::new(program) };@@ -281,9 +285,15 @@ pub(crate) fn profile_with(cmd.args(flags.split(' ')).args(args);}let started = Instant::now();- let run = output(cmd.current_dir(&ctx.root).env(DISABLE_ENV, "1").stdin(Stdio::null()), program)?;+ // asked to close (SIGTERM) at the end, the JVM runs its shutdown hooks and writes the recording+ let (run, stopped) = util::output_for(+ cmd.current_dir(&ctx.root).env(DISABLE_ENV, "1").stdin(Stdio::null()),+ program,+ duration.map(|d| Duration::from_secs_f64(d.ceil() + 2.0)),+ Duration::from_secs(15),+ )?;let wall = started.elapsed().as_secs_f64();- ensure!(run.status.success(), "the app failed ({}):\n{}", run.status, tail(&combined(&run), 30));+ ensure!(stopped || run.status.success(), "the app failed ({}):\n{}", run.status, tail(&combined(&run), 30));let mut events = Vec::new();let mut unreadable = None;for f in fs::read_dir(&jfr_dir)?.flatten().map(|e| e.path()).filter(|p| p.extension().is_some_and(|x| x == "jfr")) {@@ -602,6 +612,27 @@ mod tests {}}+ #[test]+ fn duration_stops_an_app_that_runs_until_closed() {+ if !Command::new("java").arg("-version").output().is_ok_and(|o| o.status.success()) {+ eprintln!("no java on PATH, skipping");+ return;+ }+ let dir = std::env::temp_dir().join(format!("fa-java-duration-test-{}", std::process::id()));+ fs::create_dir_all(&dir).unwrap();+ // a server's shape: work, forever+ let app = "public class App {\n static long work(int n) {\n long s = 0;\n for (int i = 0; i < n; i++) s += (long) i * i % 7;\n return s;\n }\n\n public static void main(String[] args) throws Exception {\n long sink = 0;\n while (true) {\n sink += work(20_000_000);\n Thread.sleep(1);\n }\n }\n}\n";+ fs::write(dir.join("App.java"), app).unwrap();+ let ctx = Ctx::open(&dir).unwrap();+ let started = Instant::now();+ let p = profile(&ctx, "java", &["App.java".into()], Some(3.0));+ 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" && f.cumtime > 0.0), "{:?}", p.functions);+ assert!(took < 25.0, "{took}");+ }+#[test]fn java_types_map_to_rust() {assert_eq!(rust_type("int[][]").as_deref(), Some("Vec<Vec<i32>>"));diff --git a/src/kotlin.rs b/src/kotlin.rsindex 63c36db..bd0f8cd 100644--- a/src/kotlin.rs+++ b/src/kotlin.rs@@ -549,8 +549,8 @@ fn describe(ctx: &Ctx) -> Result<Vec<Method>> {Ok(files.iter().flat_map(|f| describe_file(f)).collect())}-pub fn profile(ctx: &Ctx, program: &str, args: &[String]) -> Result<Profile> {- java::profile_with(ctx, program, args, |_| describe(ctx))+pub fn profile(ctx: &Ctx, program: &str, args: &[String], duration: Option<f64>) -> Result<Profile> {+ java::profile_with(ctx, program, args, duration, |_| describe(ctx))}// ------------------------------------------------------------------ editing the sourcediff --git a/src/main.rs b/src/main.rsindex ed98bad..d435aab 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, C#: servers and GUIs that don't exit)+ /// Stop the app after this many seconds and rank what ran (Python, Node, Go, Java, Kotlin, 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 e62a2f3..04fb179 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 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 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 c93bad5..0a7006c 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 and C# apps only so far");+ ensure!(lang.stops_after_duration(), "--duration works for Python, JavaScript/TypeScript, Go, Java, Kotlin 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)?;