diff --git a/.gitignore b/.gitignore index 837cfe3..9483f4d 100644 --- a/.gitignore +++ b/.gitignore @@ -16,4 +16,6 @@ dist dist-js !dist-js/*.iife.js .tokensave -.serena \ No newline at end of file +.serena +# local-only test app, not versioned +/examples/svelte-app/ diff --git a/Cargo.lock b/Cargo.lock index 6c91616..a28bc2d 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -94,9 +94,9 @@ dependencies = [ [[package]] name = "async_py" -version = "0.4.1" +version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ed830613c3ffcc75dfa8eb5fa6612920caca9b5e1b1a841d6b6843dd5757f404" +checksum = "b94febd557272c7803b5f493e818a3ebbdb24cd5cb86e4e35a26c339e28c6779" dependencies = [ "dunce", "mt19937", @@ -4900,7 +4900,7 @@ dependencies = [ [[package]] name = "tauri-plugin-python" -version = "0.4.0" +version = "0.4.1" dependencies = [ "async-trait", "async_py", diff --git a/Cargo.toml b/Cargo.toml index bc2d7c6..15dc5de 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "tauri-plugin-python" -version = "0.4.0" +version = "0.4.1" authors = [ "Marco Mengelkoch" ] description = "A tauri 2 plugin to use python code in the backend." keywords = ["rust", "python", "tauri", "gui"] @@ -18,7 +18,7 @@ serde = { version = "1", features = ["derive"] } thiserror = "2" async-trait = "0.1" -async_py = { version = "0.4.1", default-features = false } +async_py = { version = "0.4.2", default-features = false } tokio = { version = "1", features = ["full"] } serde_json = "1.0.136" dunce = "1.0.5" diff --git a/README.md b/README.md index a423323..8cc46d8 100644 --- a/README.md +++ b/README.md @@ -15,7 +15,9 @@ backend and works immediately in `tauri dev`: ```sh npm run tauri add python +npm install tauri-plugin-python-api ``` +`tauri add` only installs the Rust side; the second line adds the JavaScript API. Create `src-tauri/src-python/main.py`: ```python @@ -157,10 +159,16 @@ If `src-python/main.py` doesn't exist, the plugin imports a compiled module name instead: `main.cpython-313-darwin.so`, `main.pyd`, `main.pyc`, …. This lets you ship your code compiled, e.g. with [Nuitka](https://nuitka.net/): ```sh -python -m nuitka --module src-tauri/src-python/main.py --output-dir=src-tauri/src-python +# keep the source outside src-python, e.g. in src-tauri/python-src/main.py +src-tauri/pyembed/python/bin/python3 -m venv .nuitka-venv # same Python as the app (after `setup`) +.nuitka-venv/bin/pip install nuitka +.nuitka-venv/bin/python -m nuitka --module src-tauri/python-src/main.py \ + --output-dir=src-tauri/src-python --remove-output --no-pyi-file ``` -Compiled modules only load into the exact Python version they were built for, so build them with the same -Python version you bundle (see `src-python/.python-version` below). PyO3 backend only. +`main.py` takes precedence, so it must not be in `src-python/` next to the compiled module; everything in +`src-python/` is bundled. Compiled modules only load into the exact Python version they were built for, so +build them with the Python you bundle (see `src-python/.python-version` below). On macOS, run +`tauri-plugin-python-cli sign` afterwards, so they are signed for notarization. PyO3 backend only. ## Example app @@ -171,7 +179,7 @@ Javascript in [examples/plain-javascript](https://github.com/marcomq/tauri-plugi These steps assume that you already have a basic tauri application available. Alternatively, you can immediately start with the application in "example" directory. -- run `npm run tauri add python` +- run `npm run tauri add python` and `npm install tauri-plugin-python-api` - add `src-tauri/src-python/main.py` and modify it according to your needs, for example add ```python # src-tauri/src-python/main.py @@ -263,13 +271,24 @@ When a Python call fails, the plugin returns the error to the frontend (it is th try { await call.greet_python("input value"); } catch (err) { - console.error(err); // contains the Python error message / traceback + console.error(err); // Python error message, with traceback in development builds } ``` -In addition, in **development builds** (`tauri dev`, i.e. any non-release build) the plugin prints the full -error – including the Python traceback – to **stderr**, prefixed with `[tauri-plugin-python]`. Watch the -terminal running `tauri dev` to see it. Release builds do not log, so nothing leaks to end users. +The plugin never shows errors in the UI itself; what the user sees is up to your frontend code. + +In **development builds** (`tauri dev`, i.e. any non-release build) the error contains the full Python +traceback, and the plugin also prints it to **stderr**, prefixed with `[tauri-plugin-python]`. Watch the +terminal running `tauri dev` to see it. **Release builds** drop the traceback and log nothing: the frontend +only receives the last line, e.g. `ValueError: invalid input`, so file paths and source lines don't leak to +end users. + +For errors that only happen in the release build, start the app with `TAURI_PLUGIN_PYTHON_TRACEBACK=1`. +Errors then contain the traceback and are printed to stderr, as in development builds: + +```sh +TAURI_PLUGIN_PYTHON_TRACEBACK=1 ./MyApp.app/Contents/MacOS/MyApp # macOS; on Windows: set the variable, then start the .exe +``` The error message is also prefixed with what the plugin was doing, e.g. `Error calling Python function 'greet_python': ...` or @@ -365,7 +384,7 @@ Notes per platform: `tauri build`; downloads are cached in `~/.cache/tauri-plugin-python-cli`. - **macOS:** notarization requires every native file in the app to be signed. Tauri only signs the main binary, so run `npx tauri-plugin-python-cli sign` (uses `APPLE_SIGNING_IDENTITY`) **before** `tauri build`; it signs - the files in `src-tauri/pyembed`, which tauri then copies into the app. + the native files in `src-tauri/pyembed` and `src-tauri/src-python`, which tauri then copies into the app. - **Windows:** `python3XX.dll` is placed next to the `.exe`, the rest under `pyembed/`. - **Linux:** the runtime lands in `/usr/lib//pyembed/`. - `RUSTFLAGS` in the environment replaces the rpaths from `.cargo/config.toml`; `doctor` warns about it. diff --git a/cli/README.md b/cli/README.md index aa3fffb..6c9018a 100644 --- a/cli/README.md +++ b/cli/README.md @@ -59,6 +59,8 @@ detects the duplicate `malachite-bigint` versions that break the build; Notarization rejects unsigned native files anywhere in the app, and tauri only signs the main binary and frameworks. `sign` signs every Mach-O file in the -bundled Python with `--options runtime --timestamp`, using `--identity` or +bundled Python and in `src-python` (compiled modules, C extensions in a `.venv`) +with `--options runtime --timestamp`, using `--identity` or `APPLE_SIGNING_IDENTITY` (the same variable `tauri build` uses). It signs the -files in `src-tauri/pyembed`, so run it after `setup` and before `tauri build`. +files in `src-tauri/pyembed` and `src-tauri/src-python`, so run it after `setup` +(and after compiling modules) and before `tauri build`. diff --git a/cli/lib/doctor.js b/cli/lib/doctor.js index 9a88152..cd179c4 100644 --- a/cli/lib/doctor.js +++ b/cli/lib/doctor.js @@ -218,10 +218,12 @@ function checkBinaries(srcTauri, os, manifest, report) { const linkage = inspectLinkage(bin, os); if (!linkage) continue; const bundled = linkage.rpaths.some((p) => p.includes(`${PYTHON_DIR}/lib`)); + // A stale dev build is never shipped, so it must not fail the check. + const fail = profile === "debug" ? report.warn : report.error; if (!linkage.libpython) report.warn(`${rel}: no libpython dependency found`); else if (linkage.libpython.startsWith("/")) { - report.error(`${rel}: links the host Python (${linkage.libpython}); rebuild after 'setup'`); - } else if (!bundled) report.error(`${rel}: no rpath to ${PYTHON_DIR}/lib; rebuild after 'setup'`); + fail(`${rel}: links the host Python (${linkage.libpython}); rebuild after 'setup'`); + } else if (!bundled) fail(`${rel}: no rpath to ${PYTHON_DIR}/lib; rebuild after 'setup'`); else report.ok(`${rel}: links ${linkage.libpython} from the bundled Python`); } } diff --git a/cli/lib/sign.js b/cli/lib/sign.js index f1d5b2d..68406e1 100644 --- a/cli/lib/sign.js +++ b/cli/lib/sign.js @@ -49,10 +49,13 @@ export function sign(opts, log = console.log) { if (process.platform !== "darwin") throw new Error("'sign' is only needed (and possible) on macOS"); const identity = opts.identity ?? process.env.APPLE_SIGNING_IDENTITY; if (!identity) throw new Error("Pass --identity or set APPLE_SIGNING_IDENTITY (as for tauri build)"); - const pythonDir = path.join(findSrcTauri(opts.project), PYTHON_DIR); + const srcTauri = findSrcTauri(opts.project); + const pythonDir = path.join(srcTauri, PYTHON_DIR); if (!fs.existsSync(pythonDir)) throw new Error(`${PYTHON_DIR} not found. Run 'setup' first`); + // Compiled modules (Nuitka, Cython) and C extensions in a .venv are bundled from src-python. + const dirs = [pythonDir, path.join(srcTauri, "src-python")].filter((d) => fs.existsSync(d)); - const targets = [...files(pythonDir)].filter(isMachO); + const targets = dirs.flatMap((d) => [...files(d)]).filter(isMachO); const args = ["--force", "--sign", identity]; if (identity !== "-") args.push("--timestamp", "--options", "runtime"); if (opts.entitlements) args.push("--entitlements", opts.entitlements); @@ -60,5 +63,5 @@ export function sign(opts, log = console.log) { const res = spawnSync("codesign", [...args, file], { stdio: "inherit" }); if (res.status !== 0) throw new Error(`codesign failed for ${file}`); } - log(`Signed ${targets.length} files in ${PYTHON_DIR}`); + log(`Signed ${targets.length} files in ${dirs.map((d) => path.relative(srcTauri, d)).join(", ")}`); } diff --git a/cli/package.json b/cli/package.json index cb835df..779746f 100644 --- a/cli/package.json +++ b/cli/package.json @@ -1,6 +1,6 @@ { "name": "tauri-plugin-python-cli", - "version": "0.4.0", + "version": "0.4.1", "author": "Marco Mengelkoch", "description": "Bundle a standalone Python with a tauri-plugin-python app and check the deployment setup.", "type": "module", diff --git a/docs/deploy-macos.md b/docs/deploy-macos.md index 0b9efe6..dbd830f 100644 --- a/docs/deploy-macos.md +++ b/docs/deploy-macos.md @@ -72,9 +72,9 @@ export APPLE_SIGNING_IDENTITY="Developer ID Application: Your Name (TEAMID)" npx tauri-plugin-python-cli sign ``` -This signs every Mach-O file in `src-tauri/pyembed/python` with `--options runtime --timestamp`. Pass -`--entitlements ` if your packages need extra hardened-runtime entitlements. Run `sign` again after each -`setup`. +This signs every Mach-O file in `src-tauri/pyembed/python` and `src-tauri/src-python` (compiled modules, C +extensions in a `.venv`) with `--options runtime --timestamp`. Pass `--entitlements ` if your packages +need extra hardened-runtime entitlements. Run `sign` again after each `setup` and after compiling modules. ## 5. Build diff --git a/package.json b/package.json index 39d9c50..5f1a114 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "tauri-plugin-python-api", - "version": "0.4.0", + "version": "0.4.1", "author": "Marco Mengelkoch", "description": "Javascript package for tauri 2 python plugin.", "type": "module", diff --git a/src/lib.rs b/src/lib.rs index ab10baf..4a9ace0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -75,8 +75,11 @@ sys.stderr = _TauriSafeStream(getattr(sys, "stderr", None)) /// Builds the shared [`PyRunner`], applying the default per-call timeout unless /// the `TAURI_PLUGIN_PYTHON_TIMEOUT_SECS` env var overrides it (`0` = no timeout). +/// Errors include Python tracebacks if [`tracebacks_enabled`]. fn build_runner() -> PyRunner { - let runner = PyRunner::new(); + let runner = PyRunner::new().with_tracebacks(tracebacks_enabled( + std::env::var(TRACEBACK_ENV).ok().as_deref(), + )); match call_timeout( std::env::var("TAURI_PLUGIN_PYTHON_TIMEOUT_SECS") .ok() @@ -87,6 +90,15 @@ fn build_runner() -> PyRunner { } } +const TRACEBACK_ENV: &str = "TAURI_PLUGIN_PYTHON_TRACEBACK"; + +/// Tracebacks are on in debug builds, and in release builds if the +/// `TAURI_PLUGIN_PYTHON_TRACEBACK` env var is `1` or `true`. +fn tracebacks_enabled(env_value: Option<&str>) -> bool { + cfg!(debug_assertions) + || env_value.is_some_and(|v| matches!(v.trim().to_ascii_lowercase().as_str(), "1" | "true")) +} + /// Resolves the per-call timeout from the raw env var value; `None` disables it. fn call_timeout(env_value: Option<&str>) -> Option { match env_value.and_then(|v| v.trim().parse::().ok()) { @@ -111,16 +123,18 @@ struct PluginState { /// Prepends human-readable context to a failing Python operation and, in debug /// builds (`tauri dev`), prints the full detail - including the Python traceback /// carried in the underlying error - to stderr so it is visible in the dev -/// console. The original error message is preserved in the returned error, so it -/// also still reaches the frontend. In release builds nothing is logged. +/// console. The full message, traceback included, also reaches the frontend. +/// Release builds log nothing and their errors carry no traceback, unless +/// `TAURI_PLUGIN_PYTHON_TRACEBACK` enables both (see [`tracebacks_enabled`]). fn py_context>( result: std::result::Result, context: impl FnOnce() -> String, ) -> crate::Result { result.map_err(|err| { let msg = format!("{}: {}", context(), err.into()); - #[cfg(debug_assertions)] - eprintln!("[tauri-plugin-python] {msg}"); + if tracebacks_enabled(std::env::var(TRACEBACK_ENV).ok().as_deref()) { + eprintln!("[tauri-plugin-python] {msg}"); + } Error::String(msg) }) } @@ -290,6 +304,17 @@ enum PythonEntry { Module { name: String, dir: PathBuf }, } +impl std::fmt::Display for PythonEntry { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + PythonEntry::File(path) => write!(f, "'{}'", path.display()), + PythonEntry::Module { name, dir } => { + write!(f, "compiled module '{name}' from '{}'", dir.display()) + } + } + } +} + const ENTRY_MODULE: &str = "main"; /// Prefers `main.py`; otherwise falls back to a compiled `main` module @@ -466,8 +491,9 @@ pub fn init_and_register(python_functions: Vec<&'static str>) -> Tau let mut dir = get_resource_dir(app); let mut entry = find_entry(&dir); if entry.is_none() { - println!( - "Warning: 'src-tauri/main.py' seems not to be registered in 'tauri.conf.json'" + eprintln!( + "[tauri-plugin-python] Warning: no main.py or compiled 'main' module in '{}'; is 'src-python/' listed in bundle.resources of tauri.conf.json?", + dir.display() ); // Release builds must not run Python code from wherever they are started. if cfg!(debug_assertions) { @@ -481,9 +507,9 @@ pub fn init_and_register(python_functions: Vec<&'static str>) -> Tau .block_on(async move { let runner = app.state::().inner(); init_python(runner, dir.to_path_buf()).await; - run_entry(runner, &entry) - .await - .expect("ERROR: Error running 'src-tauri/main.py'"); + if let Err(err) = run_entry(runner, &entry).await { + startup_failed(&format!("Failed to load {entry}"), err); + } register_python_functions( app, python_functions.iter().map(|s| s.to_string()).collect(), @@ -505,13 +531,27 @@ pub fn init_and_register(python_functions: Vec<&'static str>) -> Tau async fn register_python_functions(app: &AppHandle, python_functions: Vec) { for function_name in python_functions { - app.register_function(RegisterRequest { - python_function_call: function_name.clone(), - number_of_args: None, - }) - .await - .unwrap(); + if let Err(err) = app + .register_function(RegisterRequest { + python_function_call: function_name.clone(), + number_of_args: None, + }) + .await + { + startup_failed("Failed to register Python functions", err); + } + } +} + +/// Aborts plugin initialization with a readable message instead of a `Debug`-formatted error. +fn startup_failed(context: &str, err: impl std::fmt::Display) -> ! { + let mut msg = format!("[tauri-plugin-python] {context}: {err}"); + if msg.contains("bad magic number") { + msg.push_str( + "\nHint: the compiled module was built for a different Python version than the one the app runs", + ); } + panic!("{msg}"); } #[cfg(test)] diff --git a/src/tests.rs b/src/tests.rs index c152f99..bf2c1af 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -13,7 +13,7 @@ use tauri::{ /// It also runs some initial Python code to set up a variable and a function for testing. async fn mock_app_handle() -> AppHandle { let app = test::mock_app(); - let runner = PyRunner::new(); + let runner = build_runner(); app.manage(runner); app.manage(PluginState::default()); @@ -395,15 +395,12 @@ async fn test_error_message_propagates_from_called_function() { ); } -// Only the RustPython backend includes a traceback (with line numbers) in the -// error string; PyO3 surfaces just "ExceptionType: message". This pins down that -// running PY_STDIO_GUARD as a *separate* unit beforehand does not shift the line -// numbers reported for subsequently-run user code (the line-3 raise stays line 3). -#[cfg(feature = "rustpython")] +// Pins down that running PY_STDIO_GUARD as a *separate* unit beforehand does not +// shift the line numbers in the traceback of subsequently-run user code. Tracebacks +// are forced on, as `cargo test --release` would otherwise run without them. #[tokio::test] async fn test_error_line_number_not_shifted_by_stdio_guard() { - let app = mock_app_handle().await; - let runner = app.state::().inner(); + let runner = PyRunner::new().with_tracebacks(true); runner.run(PY_STDIO_GUARD).await.unwrap(); let code = "x = 1\ny = 2\nraise ValueError('boom')\n"; let err = runner.run(code).await.unwrap_err().to_string(); diff --git a/src/unit_tests.rs b/src/unit_tests.rs index f95da4c..10a5e7d 100644 --- a/src/unit_tests.rs +++ b/src/unit_tests.rs @@ -340,3 +340,19 @@ mod entry_detection { assert_eq!(find_entry(&dir.path().join("missing")), None); } } + +mod traceback { + use super::*; + + #[test] + fn env_var_enables_tracebacks() { + assert!(tracebacks_enabled(Some("1"))); + assert!(tracebacks_enabled(Some(" TRUE "))); + } + + #[test] + fn without_env_var_only_debug_builds_have_tracebacks() { + assert_eq!(tracebacks_enabled(None), cfg!(debug_assertions)); + assert_eq!(tracebacks_enabled(Some("0")), cfg!(debug_assertions)); + } +}