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 PHP apps
Mohit Mishra1cf279c6b9dc
diff --git a/README.md b/README.mdindex c606e02..080fbbf 100644--- a/README.md+++ b/README.md@@ -104,7 +104,7 @@ Or wire it up by hand:| 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`) | ✅ |+| PHP 8.1+ (`php app.php`) | the same C bridge, through PHP's FFI extension (`extension=ffi`); servers: `scan --duration 30` (with `pcntl`) | ✅ || C and C++ (gcc, clang or Intel oneAPI icx/icpx: `clang -O2 main.c lib.c`) | the same C bridge, through LoadLibrary or dlopen | ✅ || C# / .NET 8+ (`dotnet run -c Release`) | the same C bridge, through NativeLibrary; profiled with EventPipe, nothing to install; GUIs and servers: `scan --duration 30` | ✅ || R 4.0+ (`Rscript app.R`) | the same C bridge, through base R's `.C()`; profiled with Rprof, no packages or R headers needed | ✅ |diff --git a/src/backend.rs b/src/backend.rsindex 1ef878e..00ead4d 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::Ruby | Lang::CSharp)+ matches!(self, Lang::Python | Lang::Node | Lang::Go | Lang::Java | Lang::Kotlin | Lang::Ruby | Lang::Php | Lang::CSharp)}/// `duration` (see stops_after_duration): stop the app after that many seconds.@@ -152,7 +152,7 @@ impl Lang {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),+ Lang::Php => php::profile(ctx, exe, args, duration),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),diff --git a/src/main.rs b/src/main.rsindex f6e68cc..54d6e6d 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, Ruby, 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, PHP, 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 b4d6643..0e25da2 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, Ruby 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, PHP and C#: stop the app after this many seconds (GUIs, servers)" }, "path": path }),json!(["command"])),tool(diff --git a/src/php.rs b/src/php.rsindex 73a3271..daee577 100644--- a/src/php.rs+++ b/src/php.rs@@ -14,6 +14,7 @@ use std::collections::BTreeMap;use std::fs;use std::path::{Path, PathBuf};use std::process::{Command, Stdio};+use std::time::Duration;const DESCRIBE: &str = include_str!("php/describe.php");const PROF: &str = include_str!("php/prof.php");@@ -148,7 +149,22 @@ fn run_php(args: &[String],env: &[(&str, &Path)],) -> Result<std::process::Output> {+ Ok(run_php_for(ctx, php, prepend, args, env, None)?.0)+}++/// run_php, ending the app after `duration` seconds (and stopping it from outside 15s later).+fn run_php_for(+ ctx: &Ctx,+ php: &str,+ prepend: &Path,+ args: &[String],+ env: &[(&str, &Path)],+ duration: Option<f64>,+) -> Result<(std::process::Output, bool)> {let mut cmd = Command::new(php);+ if let Some(d) = duration {+ cmd.env("FAST_ANYTHING_STOP_AFTER_MS", ((d * 1000.0) as u64).to_string());+ }cmd.arg("-d")// quoted, as an ini value: a path can hold characters ini syntax reads as operators (~ in// Windows short names, like C:\Users\RUNNER~1)@@ -160,10 +176,16 @@ fn run_php(for (k, v) in env {cmd.env(k, v);}- output(&mut cmd, "php")+ util::output_for(+ &mut cmd,+ "php",+ duration.map(|d| Duration::from_secs_f64(d.ceil() + 15.0)),+ Duration::from_secs(10),+ )}-pub fn profile(ctx: &Ctx, php: &str, args: &[String]) -> Result<Profile> {+/// `duration`: end the app after that many seconds (servers that run until closed).+pub fn profile(ctx: &Ctx, php: &str, args: &[String], duration: Option<f64>) -> Result<Profile> {let funcs = describe(ctx, php, &source_files(&ctx.root, entry(args)?))?;let mut by_file: BTreeMap<&Path, Vec<(usize, String)>> = BTreeMap::new();for (i, f) in funcs.iter().enumerate() {@@ -183,9 +205,10 @@ pub fn profile(ctx: &Ctx, php: &str, args: &[String]) -> Result<Profile> {let text = fs::read_to_string(path)?;patches.write(path, &insert_at(&text, at))?;}- let run = run_php(ctx, php, &prof, args, &[("FAST_ANYTHING_PROF_OUT", &out)]);+ let run = run_php_for(ctx, php, &prof, args, &[("FAST_ANYTHING_PROF_OUT", &out)], duration);patches.restore()?;- let run = run?;+ let (run, killed) = run?;+ ensure!(!killed, "the app was still running 15s after --duration: PHP needs the pcntl extension for it");ensure!(run.status.success(), "the app failed ({}):\n{}", run.status, tail(&combined(&run), 30));let result: Value = serde_json::from_str(&fs::read_to_string(&out).context("the profiler wrote nothing")?)?;let wall = result["wall"].as_f64().unwrap_or(0.0);@@ -412,6 +435,28 @@ mod tests {assert_eq!(after, app);}+ #[test]+ fn duration_ends_an_app_that_runs_until_closed() {+ let pcntl = Command::new("php").args(["-r", "echo function_exists('pcntl_alarm') ? 1 : 0;"]).output();+ if !pcntl.is_ok_and(|o| o.status.success() && o.stdout == b"1") {+ eprintln!("no php with pcntl on PATH, skipping");+ return;+ }+ let dir = std::env::temp_dir().join(format!("fa-php-duration-test-{}", std::process::id()));+ fs::create_dir_all(&dir).unwrap();+ // a server's shape: some work, then a long blocking wait+ let app = "<?php\nfunction work(int $n): int\n{\n $s = 0;\n for ($i = 0; $i < $n; $i++) $s += $i * $i % 7;\n return $s;\n}\n\nfor ($k = 0; $k < 3; $k++) work(300000);\nsleep(3600);\n";+ fs::write(dir.join("app.php"), app).unwrap();+ let ctx = Ctx::open(&dir).unwrap();+ let p = profile(&ctx, "php", &["app.php".into()], Some(1.0));+ let after = fs::read_to_string(dir.join("app.php")).unwrap();+ 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);+ assert_eq!(after, app);+ }+#[test]fn the_recorder_adds_edge_cases() {use serde_json::json;diff --git a/src/php/prof.php b/src/php/prof.phpindex 2bbde1b..6bf062a 100644--- a/src/php/prof.php+++ b/src/php/prof.php@@ -30,6 +30,15 @@ final class FastAnythingProf}FastAnythingProf::$started = hrtime(true);+// scan --duration: a server runs until closed, so end it after that long (exit runs the shutdown+// function below). Needs pcntl; without it, scan stops the app from outside and says so.+$__faStop = (int) getenv('FAST_ANYTHING_STOP_AFTER_MS');+if ($__faStop > 0 && function_exists('pcntl_alarm')) {+ pcntl_async_signals(true);+ pcntl_signal(SIGALRM, fn() => exit(0));+ pcntl_alarm(max(1, (int) ceil($__faStop / 1000)));+}+unset($__faStop);register_shutdown_function(function () {$wall = (hrtime(true) - FastAnythingProf::$started) / 1e9;$stats = [];diff --git a/src/pipeline.rs b/src/pipeline.rsindex 420a392..516ab58 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, Ruby and C# apps only so far");+ ensure!(lang.stops_after_duration(), "--duration works for Python, JavaScript/TypeScript, Go, Java, Kotlin, Ruby, PHP 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)?;