diff --git a/Cargo.lock b/Cargo.lock index 9e85b1d2..0d2b007a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -152,6 +152,58 @@ version = "1.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" +[[package]] +name = "axum" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b52af3cb4058c895d37317bb27508dccc8e5f2d39454016b297bf4a400597b8" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + [[package]] name = "base64" version = "0.21.7" @@ -959,6 +1011,7 @@ name = "fastled-cli" version = "2.0.6" dependencies = [ "anyhow", + "axum", "clap", "crossterm", "notify", @@ -969,6 +1022,8 @@ dependencies = [ "strsim", "tar", "tempfile", + "tokio", + "tower-http", "zip", "zstd", ] @@ -1640,12 +1695,24 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "http-range-header" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9171a2ea8a68358193d15dd5d70c1c10a2afc3e7e4c5bc92bc9f025cebd7359c" + [[package]] name = "httparse" version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + [[package]] name = "hyper" version = "1.9.0" @@ -1660,6 +1727,7 @@ dependencies = [ "http", "http-body", "httparse", + "httpdate", "itoa", "pin-project-lite", "smallvec", @@ -2294,6 +2362,12 @@ version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2532096657941c2fea9c289d370a250971c689d4f143798ff67113ec042024a5" +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + [[package]] name = "memchr" version = "2.8.0" @@ -2315,6 +2389,16 @@ version = "0.3.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + [[package]] name = "miniz_oxide" version = "0.8.9" @@ -3101,6 +3185,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94f6cbe86ef3bf18998d9df6e0f3fc1050a8c5efa409bf712e661a4366e010fb" dependencies = [ "once_cell", + "python3-dll-a", "target-lexicon", ] @@ -3139,6 +3224,15 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "python3-dll-a" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d80ba7540edb18890d444c5aa8e1f1f99b1bdf26fb26ae383135325f4a36042b" +dependencies = [ + "cc", +] + [[package]] name = "quick-xml" version = "0.38.4" @@ -3449,7 +3543,7 @@ dependencies = [ "errno", "libc", "linux-raw-sys 0.4.15", - "windows-sys 0.52.0", + "windows-sys 0.59.0", ] [[package]] @@ -3721,6 +3815,17 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + [[package]] name = "serde_repr" version = "0.1.20" @@ -4540,10 +4645,23 @@ dependencies = [ "libc", "mio", "pin-project-lite", + "signal-hook-registry", "socket2", + "tokio-macros", "windows-sys 0.61.2", ] +[[package]] +name = "tokio-macros" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "tokio-native-tls" version = "0.3.1" @@ -4695,6 +4813,7 @@ dependencies = [ "tokio", "tower-layer", "tower-service", + "tracing", ] [[package]] @@ -4705,14 +4824,24 @@ checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" dependencies = [ "bitflags 2.11.0", "bytes", + "futures-core", "futures-util", "http", "http-body", + "http-body-util", + "http-range-header", + "httpdate", "iri-string", + "mime", + "mime_guess", + "percent-encoding", "pin-project-lite", + "tokio", + "tokio-util", "tower", "tower-layer", "tower-service", + "tracing", ] [[package]] @@ -4733,6 +4862,7 @@ version = "0.1.44" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" dependencies = [ + "log", "pin-project-lite", "tracing-core", ] @@ -4827,6 +4957,12 @@ dependencies = [ "unic-common", ] +[[package]] +name = "unicase" +version = "2.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142" + [[package]] name = "unicode-ident" version = "1.0.24" diff --git a/crates/fastled-cli/src/build.rs b/crates/fastled-cli/src/build.rs index 888dfcc9..4b1eec97 100644 --- a/crates/fastled-cli/src/build.rs +++ b/crates/fastled-cli/src/build.rs @@ -8,9 +8,10 @@ //! Rust layer as a thin orchestration shell. //! //! This module is included as a library component; the CLI main loop will -//! integrate it in a later phase. +//! integrate it in a later phase for captured-output builds. -// Not yet wired into the CLI entry point — suppress dead-code warnings. +// The CLI currently uses `run_python_compile()` in main.rs (inherited stdio). +// This module provides a captured-output alternative for future use. #![allow(dead_code)] use std::path::PathBuf; diff --git a/crates/fastled-cli/src/keyboard.rs b/crates/fastled-cli/src/keyboard.rs index e6d5471c..d0dfa7eb 100644 --- a/crates/fastled-cli/src/keyboard.rs +++ b/crates/fastled-cli/src/keyboard.rs @@ -10,9 +10,6 @@ //! The module is included as a library component; the CLI main loop will //! integrate it in a later phase. -// Not yet wired into the CLI entry point — suppress dead-code warnings. -#![allow(dead_code)] - use std::sync::mpsc; use std::thread; use std::time::Duration; @@ -58,6 +55,7 @@ pub fn check_for_space() -> bool { /// Spawn a background thread that continuously reads keyboard events and /// sends them through the returned channel. +#[allow(dead_code)] /// /// The thread exits when the channel receiver is dropped or when a /// `Ctrl+C` / `Esc` event is received. diff --git a/crates/fastled-cli/src/main.rs b/crates/fastled-cli/src/main.rs index fd6ade16..0af92b5f 100644 --- a/crates/fastled-cli/src/main.rs +++ b/crates/fastled-cli/src/main.rs @@ -1,5 +1,5 @@ use clap::Parser; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; use std::process::{Command, ExitCode}; mod archive; @@ -10,6 +10,170 @@ mod server; mod viewer; mod watcher; +// --------------------------------------------------------------------------- +// Build-status IPC (Rust writes, loading page polls) +// --------------------------------------------------------------------------- + +fn write_build_status(output_dir: &Path, status: &str, message: &str) { + let status_file = output_dir.join("build-status.json"); + let json = format!( + r#"{{"status":"{}","message":"{}"}}"#, + status, + message.replace('\\', "\\\\").replace('"', "\\\"") + ); + let _ = std::fs::write(status_file, json); +} + +// --------------------------------------------------------------------------- +// Python compile subprocess (inherits stdio for live output) +// --------------------------------------------------------------------------- + +/// Run `python -m fastled.app --just-compile [flags]`. +/// +/// Returns `true` when the compilation succeeds. The subprocess inherits +/// stdin/stdout/stderr so the user sees live output. +fn run_python_compile(cli: &Cli, extra_args: &[&str]) -> bool { + let python = find_python(); + let mut args = vec![ + "-m".to_string(), + "fastled.app".to_string(), + "--just-compile".to_string(), + ]; + + if let Some(dir) = &cli.directory { + args.push(dir.clone()); + } + + // Build mode + if cli.debug { + args.push("--debug".to_string()); + } else if cli.release { + args.push("--release".to_string()); + } + + if cli.profile { + args.push("--profile".to_string()); + } + if let Some(fp) = &cli.fastled_path { + args.push("--fastled-path".to_string()); + args.push(fp.clone()); + } + + for arg in extra_args { + args.push(arg.to_string()); + } + + match Command::new(&python).args(&args).status() { + Ok(s) => s.success(), + Err(e) => { + eprintln!("fastled: failed to launch `{python} -m fastled.app`: {e}"); + false + } + } +} + +// --------------------------------------------------------------------------- +// Compile + serve + watch (replaces Flask-based flow) +// --------------------------------------------------------------------------- + +/// Compile a sketch, serve the output via the built-in HTTP server, and +/// watch for file changes to trigger recompilation. +/// +/// This replaces the Python Flask server + file watcher loop with a native +/// Rust implementation. +fn compile_and_serve(dir: &str, cli: &Cli) -> ExitCode { + let sketch_dir = PathBuf::from(dir); + if !sketch_dir.is_dir() { + eprintln!("fastled: sketch directory does not exist: {dir}"); + return ExitCode::FAILURE; + } + + let output_dir = sketch_dir.join("fastled_js"); + if let Err(e) = std::fs::create_dir_all(&output_dir) { + eprintln!( + "fastled: could not create output directory {}: {e}", + output_dir.display() + ); + return ExitCode::FAILURE; + } + + // Write initial compiling status for the loading page. + write_build_status(&output_dir, "compiling", "Compiling..."); + + let rt = tokio::runtime::Runtime::new().expect("failed to create tokio runtime"); + rt.block_on(async { + // Start the Rust HTTP server (background tokio task). + let addr = match server::start_server(output_dir.clone(), 0).await { + Ok(a) => a, + Err(e) => { + eprintln!("fastled: failed to start server: {e}"); + return ExitCode::FAILURE; + } + }; + + let url = format!("http://{addr}"); + println!("Serving at {url}"); + open_browser(&url); + + // --- Initial compilation ------------------------------------------------ + let mut extra: Vec<&str> = Vec::new(); + if cli.purge { + extra.push("--purge"); + } + let success = run_python_compile(cli, &extra); + + if success { + write_build_status(&output_dir, "success", "Done"); + } else { + write_build_status(&output_dir, "error", "Compilation failed"); + } + + // --- Watch mode --------------------------------------------------------- + println!("\nWill recompile on sketch changes or space bar press."); + println!("Press Ctrl+C to stop..."); + + let watcher_result = + watcher::FileWatcher::new(sketch_dir.clone(), watcher::DEFAULT_DEBOUNCE_MS); + let mut file_watcher = match watcher_result { + Ok(w) => w, + Err(e) => { + eprintln!("fastled: file watcher failed: {e}"); + tokio::signal::ctrl_c().await.ok(); + return ExitCode::SUCCESS; + } + }; + let rx = file_watcher.start(); + + loop { + let should_rebuild = match rx.recv_timeout(std::time::Duration::from_secs(1)) { + Ok(changed) => { + println!("\nChanges detected in {changed:?}"); + true + } + Err(std::sync::mpsc::RecvTimeoutError::Timeout) => keyboard::check_for_space(), + Err(_) => break, + }; + + if should_rebuild { + println!("Compiling..."); + write_build_status(&output_dir, "compiling", "Recompiling..."); + + let success = run_python_compile(cli, &[]); + if success { + println!("Recompilation successful!"); + write_build_status(&output_dir, "success", "Done"); + } else { + eprintln!("Recompilation failed."); + write_build_status(&output_dir, "error", "Compilation failed"); + } + } + } + + file_watcher.stop(); + ExitCode::SUCCESS + }) +} + /// FastLED WASM compilation CLI. /// /// Thin Rust front-end that mirrors every Python flag, then delegates to @@ -301,6 +465,21 @@ fn main() -> ExitCode { let use_tauri = should_use_tauri_viewer(&cli); + // Normal compilation flow with Rust HTTP server + watch mode. + // This replaces the old Flask-based flow. Conditions: + // - a sketch directory was provided + // - the user did NOT pass --just-compile + // - we are NOT in the Tauri viewer flow (Tauri has its own lifecycle) + // - it's not a non-compile command (--init, --install) + if let Some(ref dir) = cli.directory { + if !cli.just_compile && !use_tauri && cli.init.is_none() && !cli.install { + return compile_and_serve(dir, &cli); + } + } + + // --- Delegate to Python for everything else ------------------------------ + // (--just-compile, --init, --install, Tauri viewer flow, etc.) + if use_tauri { eprintln!("fastled: native Tauri viewer detected — compiling then launching viewer"); } @@ -345,23 +524,14 @@ fn main() -> ExitCode { } } Err(e) => { + // Tauri viewer failed — fall back to Rust HTTP server. eprintln!("fastled: failed to launch Tauri viewer: {e}"); - eprintln!("fastled: falling back to legacy Flask browser"); - // Re-run Python without --just-compile to use Flask fallback. - let fallback_args = rebuild_python_args(&cli, false); - let fallback_status = Command::new(&python) - .args(["-m", "fastled.app"]) - .args(&fallback_args) - .status(); - return match fallback_status { - Ok(s) => ExitCode::from(s.code().unwrap_or(1) as u8), - Err(e2) => { - eprintln!( - "fastled: fallback also failed to launch `{python} -m fastled.app`: {e2}" - ); - ExitCode::FAILURE - } - }; + eprintln!("fastled: falling back to browser"); + // cli.directory must be Some because output_dir_from_cli succeeded. + if let Some(ref dir) = cli.directory { + return compile_and_serve(dir, &cli); + } + return ExitCode::FAILURE; } } } else { diff --git a/crates/fastled-cli/src/server.rs b/crates/fastled-cli/src/server.rs index 4487f57f..d3c32c07 100644 --- a/crates/fastled-cli/src/server.rs +++ b/crates/fastled-cli/src/server.rs @@ -10,10 +10,11 @@ use std::path::PathBuf; use std::sync::Arc; use axum::extract::State; -use axum::http::{header, HeaderValue, StatusCode}; +use axum::http::{header, HeaderValue, Method, StatusCode}; use axum::response::{Html, IntoResponse, Response}; use axum::routing::get; use axum::Router; +use tower_http::cors::{Any, CorsLayer}; use tower_http::set_header::SetResponseHeaderLayer; // --------------------------------------------------------------------------- @@ -165,6 +166,18 @@ pub async fn start_server(serve_dir: PathBuf, port: u16) -> anyhow::Result) -> Self { self.ignored_segments = segments; self diff --git a/pyproject.toml b/pyproject.toml index 8ef1523d..65cb53b0 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -15,11 +15,8 @@ dependencies = [ "httpx>=0.28.1", "watchdog>=6.0.0", "watchfiles>=1.0.5", - "Flask>=3.0.0", - "flask-cors>=4.0.0", "disklru>=2.0.4", "fasteners>=0.20", - "cryptography>=41.0.0", "clang-tool-chain>=1.2.6", "rapidfuzz", "progress", diff --git a/src/fastled/__init__.py b/src/fastled/__init__.py index 268b551d..6899d9c2 100644 --- a/src/fastled/__init__.py +++ b/src/fastled/__init__.py @@ -1,6 +1,6 @@ """FastLED Wasm Compiler package.""" -from multiprocessing import Process +import subprocess from pathlib import Path from .__version__ import __version__ @@ -55,18 +55,18 @@ def spawn_http_server( port: int | None = None, open_browser: bool = True, app: bool = False, - enable_https: bool = False, # Default to HTTP for tests (tests use http:// URLs) - ) -> Process: + enable_https: bool = False, + ) -> subprocess.Popen: + """Spawn the Rust CLI HTTP server as a subprocess.""" from fastled.open_browser import spawn_http_server + del port, enable_https # handled by Rust server (auto-assigns port) if isinstance(directory, str): directory = Path(directory) - proc: Process = spawn_http_server( + proc: subprocess.Popen = spawn_http_server( directory, - port=port, open_browser=open_browser, app=app, - enable_https=enable_https, ) return proc diff --git a/src/fastled/app.py b/src/fastled/app.py index 4b20f0c7..29da625c 100644 --- a/src/fastled/app.py +++ b/src/fastled/app.py @@ -53,32 +53,14 @@ def main() -> int: return 0 if result else 1 if args.serve_dir is not None: - from fastled.open_browser import spawn_http_server - - serve_dir = Path(args.serve_dir) - if not serve_dir.exists(): - print(f"Error: Serve directory does not exist: {serve_dir}") - return 1 - - protocol = "https" if args.enable_https else "http" - proc = spawn_http_server( - serve_dir, - open_browser=False, - app=False, - enable_https=args.enable_https, + # --serve-dir is handled natively by the Rust CLI (main.rs). + # If we reach here, the user called `python -m fastled.app --serve-dir` + # directly, which is no longer supported. + print( + "Error: --serve-dir is now handled by the Rust CLI.\n" + "Use `fastled --serve-dir ` instead." ) - print(f"Serving directory: {serve_dir}") - print(f"Listening on {protocol}://localhost") - try: - proc.join() - except KeyboardInterrupt as ki: - print("\nStopping server...") - handle_keyboard_interrupt(ki) - finally: - if proc.is_alive(): - proc.kill() - proc.join(timeout=5) - return 0 + return 1 # Handle --purge: clear cached FastLED repo and WASM build artifacts if args.purge: diff --git a/src/fastled/compile_native.py b/src/fastled/compile_native.py index b8851dda..32cc7fc7 100644 --- a/src/fastled/compile_native.py +++ b/src/fastled/compile_native.py @@ -10,7 +10,6 @@ from fastled.build_service import BuildService from fastled.build_types import BuildRequest from fastled.emoji_util import EMO -from fastled.interrupts import handle_keyboard_interrupt from fastled.types import BuildMode, CompileResult if TYPE_CHECKING: @@ -93,10 +92,13 @@ def run_native_compile( ) -> int: """ Run native compilation with optional browser and file watching. + + NOTE: The HTTP server and file watching are now handled by the Rust CLI + (compile_and_serve in main.rs). When called via ``--just-compile`` this + function only performs the compilation step and returns immediately. """ - from fastled.filewatcher import DebouncedFileWatcherProcess, FileWatcherProcess - from fastled.keyboard import SpaceBarWatcher - from fastled.open_browser import spawn_http_server + del open_browser, keep_running, enable_https, app # handled by Rust CLI + from fastled.toolchain.emscripten import EmscriptenToolchain toolchain = EmscriptenToolchain(fastled_path=fastled_path) @@ -120,70 +122,4 @@ def run_native_compile( print(f" Strategy: {result.strategy}") print(f" Output: {result.output_dir}") - if not open_browser and not keep_running: - return 0 - - http_proc = None - if open_browser: - http_proc = spawn_http_server( - result.output_dir, - port=None, - open_browser=True, - app=app, - enable_https=enable_https, - sketch_dir=directory, - fastled_path=request.fastled_path, - ) - - if not keep_running: - return 0 - - excluded_patterns = ["fastled_js", ".build"] - debounced_watcher = DebouncedFileWatcherProcess( - FileWatcherProcess(directory, excluded_patterns=excluded_patterns), - ) - - print("\nWill compile on sketch changes or if you hit the space bar.") - print("Press Ctrl+C to stop...") - - try: - while True: - if SpaceBarWatcher.watch_space_bar_pressed(timeout=1.0): - print("\nCompiling...") - result = service.build(request) - if result.success: - print( - f"{EMO('✅', 'SUCCESS:')} Recompilation successful! ({result.strategy})" - ) - else: - print(f"{EMO('❌', 'ERROR:')} Recompilation failed:") - print(result.stdout) - SpaceBarWatcher.watch_space_bar_pressed() - continue - - changed_files = debounced_watcher.get_all_changes() - if changed_files: - sketch_changes = [ - f for f in changed_files if "fastled_js" not in Path(f).parts - ] - if sketch_changes: - print(f"\nChanges detected in {sketch_changes}") - print("Compiling...") - result = service.build(request) - if result.success: - print( - f"{EMO('✅', 'SUCCESS:')} Recompilation successful! ({result.strategy})" - ) - else: - print(f"{EMO('❌', 'ERROR:')} Recompilation failed:") - print(result.stdout) - - except KeyboardInterrupt as ki: - print("\nStopping watch mode...") - handle_keyboard_interrupt(ki) - finally: - debounced_watcher.stop() - if http_proc: - http_proc.kill() - return 0 diff --git a/src/fastled/debug_routes.py b/src/fastled/debug_routes.py deleted file mode 100644 index 03db84dc..00000000 --- a/src/fastled/debug_routes.py +++ /dev/null @@ -1,47 +0,0 @@ -from __future__ import annotations - -from flask import Blueprint, Response, jsonify, make_response, request - -from fastled.debug_symbols import DebugSymbolResolver - - -def create_debug_blueprint( - resolver: DebugSymbolResolver | None, -) -> Blueprint: - debug = Blueprint("fastled_debug", __name__) - - @debug.post("/dwarfsource") - def dwarfsource() -> Response: - if resolver is None: - return make_response( - jsonify({"error": "debug source resolver unavailable"}), 400 - ) - - payload = request.get_json(silent=True) or {} - request_path = payload.get("path") - if not isinstance(request_path, str) or not request_path.strip(): - return make_response(jsonify({"error": "missing path"}), 400) - - try: - source_path = resolver.resolve(request_path, check_exists=True) - return Response(source_path.read_text(), mimetype="text/plain") - except FileNotFoundError as exc: - return make_response(jsonify({"error": str(exc)}), 404) - except ValueError as exc: - return make_response(jsonify({"error": str(exc)}), 400) - - @debug.get("/debug/source-roots") - def source_roots() -> Response: - if resolver is None: - return jsonify({"roots": []}) - - return jsonify( - { - "roots": [ - {"prefix": prefix, "path": str(path)} - for prefix, path in resolver.config.source_roots - ] - } - ) - - return debug diff --git a/src/fastled/open_browser.py b/src/fastled/open_browser.py index c697b89f..0230fa4a 100644 --- a/src/fastled/open_browser.py +++ b/src/fastled/open_browser.py @@ -1,15 +1,12 @@ import atexit -import random import shutil import subprocess import sys import time import weakref -from multiprocessing import Process from pathlib import Path from fastled.interrupts import handle_keyboard_interrupt -from fastled.server_flask import run_flask_in_thread def _find_tauri_viewer() -> Path | None: @@ -77,24 +74,62 @@ def _launch_tauri_viewer(frontend_dir: Path) -> subprocess.Popen | None: return None -DEFAULT_PORT = 8089 # different than live version. -PYTHON_EXE = sys.executable +def _find_fastled_cli() -> Path | None: + """Locate the fastled CLI binary (Rust).""" + exe_name = "fastled.exe" if sys.platform == "win32" else "fastled" + + # 1. Sibling of the running interpreter. + exe_path = Path(sys.executable).resolve() + candidate = exe_path.parent / exe_name + if candidate.is_file(): + return candidate + + # 2. Walk up to find a Cargo workspace root and check target dirs. + search_start = Path(__file__).resolve().parent + current = search_start + for _ in range(10): + cargo_toml = current / "Cargo.toml" + if cargo_toml.is_file(): + for profile in ("debug", "release"): + candidate = current / "target" / profile / exe_name + if candidate.is_file(): + return candidate + target_dir = current / "target" + if target_dir.is_dir(): + for arch_dir in target_dir.iterdir(): + if arch_dir.is_dir() and not arch_dir.name.startswith("."): + for profile in ("debug", "release"): + candidate = arch_dir / profile / exe_name + if candidate.is_file(): + return candidate + break + parent = current.parent + if parent == current: + break + current = parent + + # 3. PATH lookup. + found = shutil.which(exe_name) + if found: + return Path(found) + + return None + # Use a weak reference set to track processes without preventing garbage collection -_WEAK_CLEANUP_SET = weakref.WeakSet() +_WEAK_CLEANUP_SET: weakref.WeakSet = weakref.WeakSet() -def add_cleanup(proc: Process) -> None: +def add_cleanup(proc: subprocess.Popen) -> None: """Add a process to the cleanup list using weak references""" _WEAK_CLEANUP_SET.add(proc) - # Register a cleanup function that checks if the process is still alive def cleanup_if_alive(): - if proc.is_alive(): + if proc.poll() is None: try: proc.terminate() - proc.join(timeout=1.0) - if proc.is_alive(): + proc.wait(timeout=1.0) + if proc.poll() is None: proc.kill() except KeyboardInterrupt as ki: handle_keyboard_interrupt(ki) @@ -104,53 +139,17 @@ def cleanup_if_alive(): atexit.register(cleanup_if_alive) -def is_port_free(port: int) -> bool: - """Check if a port is free""" - import httpx - - try: - # Try HTTPS first, then fall back to HTTP - try: - response = httpx.get(f"https://localhost:{port}", timeout=1, verify=False) - response.raise_for_status() - return False - except (httpx.HTTPError, httpx.ConnectError): - response = httpx.get(f"http://localhost:{port}", timeout=1) - response.raise_for_status() - return False - except (httpx.HTTPError, httpx.ConnectError): - return True - - -def find_free_port(start_port: int) -> int: - """Find a free port starting at start_port""" - for port in range(start_port, start_port + 100, 2): - if is_port_free(port): - print(f"Found free port: {port}") - return port - else: - print(f"Port {port} is in use, finding next") - raise ValueError("Could not find a free port") - - -def wait_for_server(port: int, timeout: int = 15, enable_https: bool = True) -> None: - """Wait for the server to start.""" +def wait_for_server(port: int, timeout: int = 15) -> None: + """Wait for the HTTP server to start.""" import httpx - from httpx import get future_time = time.time() + timeout - protocol = "https" if enable_https else "http" hosts = ["localhost", "127.0.0.1"] while future_time > time.time(): for host in hosts: try: - url = f"{protocol}://{host}:{port}" - verify = ( - False if enable_https else True - ) # Only disable SSL verification for HTTPS - response = get(url, timeout=1, verify=verify) - # Any HTTP response means the server is up, even if - # it returns 500 (e.g., no index.html in served directory) + url = f"http://{host}:{port}" + response = httpx.get(url, timeout=1) if response.status_code < 600: return except httpx.HTTPError: @@ -163,51 +162,52 @@ def spawn_http_server( fastled_js: Path, port: int | None = None, open_browser: bool = True, - app: bool = False, # Deprecated, ignored — Tauri viewer is always tried first + app: bool = False, enable_https: bool = True, sketch_dir: Path | None = None, fastled_path: Path | None = None, -) -> Process: - del app # Unused — kept for backward compatibility - if port is not None and not is_port_free(port): - raise ValueError(f"Port {port} was specified but in use") - if port is None: - offset = random.randint(0, 100) - port = find_free_port(DEFAULT_PORT + offset) - - # Get SSL certificate paths from the fastled assets directory if HTTPS is enabled - certfile: Path | None = None - keyfile: Path | None = None - - if enable_https: - import fastled - - assets_dir = Path(fastled.__file__).parent / "assets" - certfile = assets_dir / "localhost.pem" - keyfile = assets_dir / "localhost-key.pem" - - proc = Process( - target=run_flask_in_thread, - args=( - port, - fastled_js, - certfile, - keyfile, - sketch_dir, - fastled_path, - None, - ), - daemon=True, - ) +) -> subprocess.Popen: + """Spawn the Rust CLI HTTP server as a subprocess. + + This replaces the old Flask-based server. The Rust binary's + ``--serve-dir`` flag starts a native HTTP server. + """ + del app, enable_https, sketch_dir, fastled_path # handled by Rust + + cli = _find_fastled_cli() + if cli is None: + raise RuntimeError("Could not find the fastled CLI binary") + + cmd = [str(cli), "--serve-dir", str(fastled_js)] + + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) add_cleanup(proc) - proc.start() - wait_for_server(port, enable_https=enable_https) - if open_browser: - protocol = "https" if enable_https else "http" - url = f"{protocol}://localhost:{port}" + # Parse the port from server output (e.g. "Serving at http://127.0.0.1:12345") + import re + + actual_port = port + if proc.stdout: + for _ in range(50): # read up to 50 lines looking for the URL + line = proc.stdout.readline().decode("utf-8", errors="replace") + if not line: + break + m = re.search(r"http://[\d.]+:(\d+)", line) + if m: + actual_port = int(m.group(1)) + break + + if actual_port is None: + # Fallback: wait a bit and hope the server is up + time.sleep(1.0) + else: + wait_for_server(actual_port, timeout=15) - # Try Tauri viewer first (native webview), fall back to system browser. + if open_browser: + if actual_port: + url = f"http://localhost:{actual_port}" + else: + url = "http://localhost:8089" tauri_proc = _launch_tauri_viewer(fastled_js) if tauri_proc is not None: print("Opening FastLED sketch in Tauri viewer") @@ -215,30 +215,6 @@ def spawn_http_server( print(f"Opening browser to {url}") import webbrowser - webbrowser.open( - url=url, - new=1, - autoraise=True, - ) - return proc - + webbrowser.open(url=url, new=1, autoraise=True) -if __name__ == "__main__": - import argparse - - parser = argparse.ArgumentParser( - description="Open a browser to the fastled_js directory" - ) - parser.add_argument( - "fastled_js", type=Path, help="Path to the fastled_js directory" - ) - parser.add_argument( - "--port", - type=int, - default=DEFAULT_PORT, - help=f"Port to run the server on (default: {DEFAULT_PORT})", - ) - args = parser.parse_args() - - proc = spawn_http_server(args.fastled_js, args.port, open_browser=True) - proc.join() + return proc diff --git a/src/fastled/server_flask.py b/src/fastled/server_flask.py deleted file mode 100644 index 90702064..00000000 --- a/src/fastled/server_flask.py +++ /dev/null @@ -1,226 +0,0 @@ -import argparse -import logging -import mimetypes -from datetime import datetime, timezone -from multiprocessing import Process -from pathlib import Path - -from flask import Flask, Response, send_from_directory -from flask_cors import CORS - -from fastled.debug_routes import create_debug_blueprint -from fastled.debug_symbols import ( - DebugSymbolResolver, - guess_emsdk_path, - load_debug_symbol_config, -) -from fastled.interrupts import handle_keyboard_interrupt - -_ENABLE_LOGGING = False - -if _ENABLE_LOGGING: - logging.basicConfig( - level=logging.INFO, - format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", - ) - logger = logging.getLogger("flask_server") -else: - logging.getLogger("flask_server").addHandler(logging.NullHandler()) - logging.getLogger("flask_server").propagate = False - logger = logging.getLogger("flask_server") - logger.disabled = True - - -def _check_certificate_expiration( - certfile: Path, -) -> tuple[bool, int | None, str | None]: - try: - from cryptography import x509 - from cryptography.hazmat.backends import default_backend - - with open(certfile, "rb") as handle: - cert = x509.load_pem_x509_certificate(handle.read(), default_backend()) - - expiration_date = cert.not_valid_after_utc - expiration_str = expiration_date.strftime("%Y-%m-%d") - days_remaining = (expiration_date - datetime.now(timezone.utc)).days - return days_remaining > 30, days_remaining, expiration_str - except KeyboardInterrupt as ki: - handle_keyboard_interrupt(ki) - raise - except Exception as exc: - logger.warning(f"Failed to check certificate expiration: {exc}") - return True, None, None - - -def create_app( - fastled_js: Path, - sketch_dir: Path | None = None, - fastled_dir: Path | None = None, - emsdk_path: Path | None = None, -) -> Flask: - app = Flask(__name__) - CORS( - app, - resources={ - r"/*": { - "origins": "*", - "methods": ["GET", "POST", "PUT", "DELETE", "OPTIONS"], - "allow_headers": [ - "Content-Type", - "Authorization", - "X-Requested-With", - ], - } - }, - ) - - fastled_js = fastled_js.resolve() - resolver = None - if sketch_dir is not None: - config = load_debug_symbol_config( - sketch_dir=sketch_dir.resolve(), - fastled_dir=fastled_dir.resolve() if fastled_dir else None, - emsdk_path=emsdk_path.resolve() if emsdk_path else guess_emsdk_path(), - ) - resolver = DebugSymbolResolver(config) - - app.register_blueprint(create_debug_blueprint(resolver)) - - @app.after_request - def add_security_headers(response: Response) -> Response: - response.headers["Cross-Origin-Embedder-Policy"] = "credentialless" - response.headers["Cross-Origin-Opener-Policy"] = "same-origin" - response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" - response.headers["Pragma"] = "no-cache" - response.headers["Expires"] = "0" - return response - - @app.route("/") - def serve_index() -> Response: - return send_from_directory(fastled_js, "index.html") - - @app.route("/") - def serve_files(path: str) -> Response: - file_path = fastled_js / path - if not file_path.exists(): - return Response(f"File not found: {path}", status=404) - - response = send_from_directory(fastled_js, path) - content_type, _ = mimetypes.guess_type(str(file_path)) - if path.endswith(".js"): - content_type = "text/javascript; charset=utf-8" - elif path.endswith(".wasm"): - content_type = "application/wasm" - elif path.endswith(".svg"): - content_type = "image/svg+xml" - if content_type: - response.headers["Content-Type"] = content_type - return response - - return app - - -def _run_flask_server( - fastled_js: Path, - port: int, - certfile: Path | None = None, - keyfile: Path | None = None, - sketch_dir: Path | None = None, - fastled_dir: Path | None = None, - emsdk_path: Path | None = None, -) -> None: - app = create_app( - fastled_js=fastled_js, - sketch_dir=sketch_dir, - fastled_dir=fastled_dir, - emsdk_path=emsdk_path, - ) - - ssl_context = None - if certfile and keyfile: - try: - _check_certificate_expiration(certfile) - ssl_context = (str(certfile), str(keyfile)) - except KeyboardInterrupt as ki: - handle_keyboard_interrupt(ki) - except Exception as exc: - logger.warning(f"Failed to configure HTTPS server: {exc}") - - app.run( - host="127.0.0.1", - port=port, - debug=False, - use_reloader=False, - ssl_context=ssl_context, - ) - - -def run_flask_in_thread( - port: int, - cwd: Path, - certfile: Path | None = None, - keyfile: Path | None = None, - sketch_dir: Path | None = None, - fastled_dir: Path | None = None, - emsdk_path: Path | None = None, -) -> None: - _run_flask_server( - cwd, - port, - certfile, - keyfile, - sketch_dir=sketch_dir, - fastled_dir=fastled_dir, - emsdk_path=emsdk_path, - ) - - -def run_flask_server_process( - port: int, - cwd: Path, - certfile: Path | None = None, - keyfile: Path | None = None, - sketch_dir: Path | None = None, - fastled_dir: Path | None = None, - emsdk_path: Path | None = None, -) -> Process: - process = Process( - target=run_flask_in_thread, - args=(port, cwd, certfile, keyfile, sketch_dir, fastled_dir, emsdk_path), - ) - process.start() - return process - - -def parse_args() -> argparse.Namespace: - parser = argparse.ArgumentParser( - description="Open a browser to the fastled_js directory" - ) - parser.add_argument( - "fastled_js", type=Path, help="Path to the fastled_js directory" - ) - parser.add_argument("--port", "-p", type=int, required=True) - parser.add_argument("--certfile", type=Path) - parser.add_argument("--keyfile", type=Path) - parser.add_argument("--sketch-dir", type=Path, default=None) - parser.add_argument("--fastled-dir", type=Path, default=None) - parser.add_argument("--emsdk-path", type=Path, default=None) - return parser.parse_args() - - -def main() -> None: - args = parse_args() - run_flask_in_thread( - args.port, - args.fastled_js, - args.certfile, - args.keyfile, - sketch_dir=args.sketch_dir, - fastled_dir=args.fastled_dir, - emsdk_path=args.emsdk_path, - ) - - -if __name__ == "__main__": - main() diff --git a/tests/integration/test_animartrix_e2e.py b/tests/integration/test_animartrix_e2e.py index 0bf7308f..f980da06 100644 --- a/tests/integration/test_animartrix_e2e.py +++ b/tests/integration/test_animartrix_e2e.py @@ -77,26 +77,20 @@ async def _verify_browser_no_errors(self) -> None: """Start server, open page in Playwright, and check for JS errors.""" proc = Test.spawn_http_server( FASTLED_JS_DIR, - port=TEST_PORT, open_browser=False, - enable_https=True, + enable_https=False, ) try: - time.sleep(1) - server_url = f"https://localhost:{TEST_PORT}" + time.sleep(2) + # The Rust server auto-assigns a port; use localhost default + server_url = "http://localhost:8089" async with async_playwright() as p: - browser = await p.chromium.launch( - headless=True, - args=[ - "--ignore-certificate-errors", - "--allow-insecure-localhost", - ], - ) + browser = await p.chromium.launch(headless=True) try: - context = await browser.new_context(ignore_https_errors=True) + context = await browser.new_context() page = await context.new_page() # Collect console errors diff --git a/tests/integration/test_microphone_https.py b/tests/integration/test_microphone_https.py index 8c7ce1e1..65680398 100644 --- a/tests/integration/test_microphone_https.py +++ b/tests/integration/test_microphone_https.py @@ -11,7 +11,6 @@ """ import asyncio -import os import random import time import unittest @@ -20,9 +19,6 @@ import pytest from playwright.async_api import async_playwright -# Enable Flask server logging for debugging if needed -os.environ["FLASK_SERVER_LOGGING"] = "0" - from fastled import Test HERE = Path(__file__).parent diff --git a/tests/unit/test_debug_routes.py b/tests/unit/test_debug_routes.py deleted file mode 100644 index fbc2ab2f..00000000 --- a/tests/unit/test_debug_routes.py +++ /dev/null @@ -1,34 +0,0 @@ -from pathlib import Path - -from fastled.server_flask import create_app - - -def test_dwarfsource_route_returns_file_contents(tmp_path: Path) -> None: - sketch_dir = tmp_path / "sketch" - output_dir = sketch_dir / "fastled_js" - output_dir.mkdir(parents=True) - (output_dir / "index.html").write_text("") - source_file = sketch_dir / "demo.cpp" - source_file.write_text("int main() {}") - - app = create_app(output_dir, sketch_dir=sketch_dir) - client = app.test_client() - response = client.post("/dwarfsource", json={"path": "sketchsource/demo.cpp"}) - - assert response.status_code == 200 - assert response.get_data(as_text=True) == "int main() {}" - - -def test_dwarfsource_route_rejects_invalid_requests(tmp_path: Path) -> None: - output_dir = tmp_path / "fastled_js" - output_dir.mkdir() - (output_dir / "index.html").write_text("") - - app = create_app(output_dir, sketch_dir=tmp_path) - client = app.test_client() - - missing_path = client.post("/dwarfsource", json={}) - assert missing_path.status_code == 400 - - traversal = client.post("/dwarfsource", json={"path": "dwarfsource/../secret.txt"}) - assert traversal.status_code == 400