1use std::{
2 ffi::OsString,
3 future::Future,
4 path::{Path, PathBuf},
5 process::{ExitStatus, Stdio},
6 sync::mpsc,
7 time::Duration,
8};
9
10use notify::{EventKind, RecommendedWatcher, RecursiveMode, Watcher};
11use thiserror::Error;
12use tokio::process::{Child, Command};
13use tokio::sync::mpsc::{UnboundedReceiver, UnboundedSender, unbounded_channel};
14
15#[derive(Clone, Debug, Eq, PartialEq)]
16pub struct CommandSpec {
17 pub program: PathBuf,
18 pub args: Vec<OsString>,
19}
20
21impl CommandSpec {
22 #[must_use]
23 pub fn new(program: impl Into<PathBuf>) -> Self {
24 Self {
25 program: program.into(),
26 args: Vec::new(),
27 }
28 }
29
30 #[must_use]
31 pub fn arg(mut self, argument: impl Into<OsString>) -> Self {
32 self.args.push(argument.into());
33 self
34 }
35
36 #[must_use]
37 pub fn args(mut self, arguments: impl IntoIterator<Item = impl Into<OsString>>) -> Self {
38 self.args.extend(arguments.into_iter().map(Into::into));
39 self
40 }
41}
42
43#[derive(Clone, Debug)]
44pub struct DevConfig {
45 pub working_directory: PathBuf,
46 pub rust: CommandSpec,
47 pub vite: CommandSpec,
48 pub client_build: CommandSpec,
49 pub renderer_build: CommandSpec,
50 pub build_frontend: bool,
52 pub watch_rust: bool,
54}
55
56impl Default for DevConfig {
57 fn default() -> Self {
58 Self {
59 working_directory: PathBuf::from("."),
60 rust: CommandSpec::new("cargo").args(["run", "--", "serve"]),
61 vite: CommandSpec::new("npm").args(["run", "dev", "--", "--strictPort"]),
62 client_build: CommandSpec::new("npm").args(["run", "build:client"]),
63 renderer_build: CommandSpec::new("npm").args(["run", "build:ssr"]),
64 build_frontend: true,
65 watch_rust: true,
66 }
67 }
68}
69
70impl DevConfig {
71 #[must_use]
72 pub fn working_directory(mut self, directory: impl Into<PathBuf>) -> Self {
73 self.working_directory = directory.into();
74 self
75 }
76
77 #[must_use]
78 pub fn rust(mut self, command: CommandSpec) -> Self {
79 self.rust = command;
80 self
81 }
82
83 #[must_use]
84 pub fn vite(mut self, command: CommandSpec) -> Self {
85 self.vite = command;
86 self
87 }
88
89 #[must_use]
90 pub fn client_build(mut self, command: CommandSpec) -> Self {
91 self.client_build = command;
92 self
93 }
94
95 #[must_use]
96 pub fn renderer_build(mut self, command: CommandSpec) -> Self {
97 self.renderer_build = command;
98 self
99 }
100
101 #[must_use]
102 pub const fn build_frontend(mut self, enabled: bool) -> Self {
103 self.build_frontend = enabled;
104 self
105 }
106
107 #[must_use]
108 pub const fn watch_rust(mut self, enabled: bool) -> Self {
109 self.watch_rust = enabled;
110 self
111 }
112}
113
114pub struct DevSupervisor {
115 config: DevConfig,
116}
117
118impl DevSupervisor {
119 #[must_use]
120 pub fn new(config: DevConfig) -> Self {
121 Self { config }
122 }
123
124 pub async fn run(self) -> Result<(), DevError> {
133 self.run_with_shutdown(async { tokio::signal::ctrl_c().await.map_err(DevError::Signal) })
134 .await
135 }
136
137 pub async fn run_with_shutdown<F>(self, shutdown: F) -> Result<(), DevError>
144 where
145 F: Future<Output = Result<(), DevError>> + Send,
146 {
147 let cwd = self.config.working_directory.clone();
148 let mut vite = spawn("Vite", &self.config.vite, &cwd)?;
149 let mut changes = if self.config.watch_rust {
150 Some(start_rust_watcher(&cwd)?)
151 } else {
152 None
153 };
154 tokio::pin!(shutdown);
155
156 let result = async {
157 loop {
158 self.build_frontend(&cwd).await?;
159 let mut rust = spawn("Rust", &self.config.rust, &cwd)?;
160 if self.config.watch_rust {
161 eprintln!(
162 "px dev: watching application and React sources for rebuilds"
163 );
164 }
165
166 let event = tokio::select! {
167 result = rust.wait() => Event::Rust(result.map_err(DevError::Wait)?),
168 result = vite.wait() => Event::Vite(result.map_err(DevError::Wait)?),
169 result = &mut shutdown => Event::Shutdown(result),
170 changed = recv_change(&mut changes) => {
171 changed?;
172 Event::RustChanged
173 }
174 };
175
176 match event {
177 Event::Shutdown(result) => {
178 terminate(&mut rust).await?;
179 return result;
180 }
181 Event::Vite(status) => {
182 terminate(&mut rust).await?;
183 return Err(DevError::Exited {
184 process: "Vite",
185 status,
186 });
187 }
188 Event::RustChanged => {
189 eprintln!("px dev: Rust source changed — rebuilding…");
190 terminate(&mut rust).await?;
191 drain_changes(&mut changes, Duration::from_millis(400)).await;
192 continue;
193 }
194 Event::Rust(status) => {
195 if !self.config.watch_rust {
196 return Err(DevError::Exited {
197 process: "Rust",
198 status,
199 });
200 }
201 eprintln!(
202 "px dev: Rust process exited ({status}); waiting for source changes…"
203 );
204 let wait = tokio::select! {
205 result = vite.wait() => WaitWhileDown::Vite(result.map_err(DevError::Wait)?),
206 result = &mut shutdown => WaitWhileDown::Shutdown(result),
207 changed = recv_change(&mut changes) => {
208 changed?;
209 WaitWhileDown::Changed
210 }
211 };
212 match wait {
213 WaitWhileDown::Shutdown(result) => return result,
214 WaitWhileDown::Vite(status) => {
215 return Err(DevError::Exited {
216 process: "Vite",
217 status,
218 });
219 }
220 WaitWhileDown::Changed => {
221 drain_changes(&mut changes, Duration::from_millis(400)).await;
222 continue;
223 }
224 }
225 }
226 }
227 }
228 }
229 .await;
230
231 terminate(&mut vite).await?;
232 result
233 }
234
235 async fn build_frontend(&self, cwd: &Path) -> Result<(), DevError> {
236 if !self.config.build_frontend {
237 return Ok(());
238 }
239 run_to_completion("Client build", &self.config.client_build, cwd).await?;
240 run_to_completion("Renderer build", &self.config.renderer_build, cwd).await
241 }
242}
243
244enum Event {
245 Rust(ExitStatus),
246 Vite(ExitStatus),
247 Shutdown(Result<(), DevError>),
248 RustChanged,
249}
250
251enum WaitWhileDown {
252 Vite(ExitStatus),
253 Shutdown(Result<(), DevError>),
254 Changed,
255}
256
257struct RustWatcher {
258 _watcher: RecommendedWatcher,
259 rx: UnboundedReceiver<()>,
260}
261
262fn start_rust_watcher(cwd: &Path) -> Result<RustWatcher, DevError> {
263 let (tx, rx) = unbounded_channel();
264 let (notify_tx, notify_rx) = mpsc::channel();
265 let mut watcher = notify::recommended_watcher(move |result| {
266 let _ = notify_tx.send(result);
267 })
268 .map_err(DevError::Watch)?;
269
270 for relative in ["app", "src", "routes", "config", "database", "views"] {
271 let path = cwd.join(relative);
272 if path.is_dir() {
273 watcher
274 .watch(&path, RecursiveMode::Recursive)
275 .map_err(DevError::Watch)?;
276 }
277 }
278 let cargo_toml = cwd.join("Cargo.toml");
279 if cargo_toml.is_file() {
280 watcher
281 .watch(&cargo_toml, RecursiveMode::NonRecursive)
282 .map_err(DevError::Watch)?;
283 }
284
285 let cwd = cwd.to_path_buf();
286 std::thread::Builder::new()
287 .name("px-dev-rust-watch".into())
288 .spawn(move || watch_loop(cwd, notify_rx, tx))
289 .map_err(|source| DevError::Spawn {
290 process: "RustWatcher",
291 source,
292 })?;
293
294 Ok(RustWatcher {
295 _watcher: watcher,
296 rx,
297 })
298}
299
300fn watch_loop(
301 cwd: PathBuf,
302 notify_rx: mpsc::Receiver<Result<notify::Event, notify::Error>>,
303 tx: UnboundedSender<()>,
304) {
305 while let Ok(result) = notify_rx.recv() {
306 let Ok(event) = result else {
307 continue;
308 };
309 if is_relevant_event(&cwd, &event) {
310 let _ = tx.send(());
311 }
312 }
313}
314
315fn is_relevant_event(cwd: &Path, event: ¬ify::Event) -> bool {
316 match event.kind {
317 EventKind::Modify(_) | EventKind::Create(_) | EventKind::Remove(_) => {}
318 _ => return false,
319 }
320 event
321 .paths
322 .iter()
323 .any(|path| is_watched_rust_path(cwd, path))
324}
325
326fn is_watched_rust_path(cwd: &Path, path: &Path) -> bool {
327 let Ok(relative) = path.strip_prefix(cwd) else {
328 return false;
329 };
330 let mut components = relative.components();
331 let Some(std::path::Component::Normal(first)) = components.next() else {
332 return path.file_name().is_some_and(|name| name == "Cargo.toml");
333 };
334 let first = first.to_string_lossy();
335 matches!(
336 first.as_ref(),
337 "app" | "src" | "routes" | "config" | "database" | "views" | "Cargo.toml"
338 ) && !relative.components().any(
339 |component| matches!(component, std::path::Component::Normal(name) if name == "target"),
340 )
341}
342
343async fn recv_change(changes: &mut Option<RustWatcher>) -> Result<(), DevError> {
344 match changes.as_mut() {
345 Some(watcher) => watcher.rx.recv().await.ok_or(DevError::WatchClosed),
346 None => std::future::pending().await,
347 }
348}
349
350async fn drain_changes(changes: &mut Option<RustWatcher>, window: Duration) {
351 let Some(watcher) = changes.as_mut() else {
352 return;
353 };
354 let deadline = tokio::time::Instant::now() + window;
355 loop {
356 let remaining = deadline.saturating_duration_since(tokio::time::Instant::now());
357 if remaining.is_zero() {
358 break;
359 }
360 match tokio::time::timeout(remaining, watcher.rx.recv()).await {
361 Ok(Some(())) => continue,
362 _ => break,
363 }
364 }
365}
366
367fn spawn(label: &'static str, spec: &CommandSpec, cwd: &Path) -> Result<Child, DevError> {
368 let mut command = Command::new(&spec.program);
369 command
370 .args(&spec.args)
371 .current_dir(cwd)
372 .stdin(Stdio::inherit())
373 .stdout(Stdio::inherit())
374 .stderr(Stdio::inherit())
375 .kill_on_drop(true);
376 #[cfg(unix)]
377 command.process_group(0);
378 command.spawn().map_err(|source| DevError::Spawn {
379 process: label,
380 source,
381 })
382}
383
384async fn run_to_completion(
385 label: &'static str,
386 spec: &CommandSpec,
387 cwd: &Path,
388) -> Result<(), DevError> {
389 let mut child = spawn(label, spec, cwd)?;
390 let status = child.wait().await.map_err(DevError::Wait)?;
391 if status.success() {
392 Ok(())
393 } else {
394 Err(DevError::Exited {
395 process: label,
396 status,
397 })
398 }
399}
400
401#[cfg(unix)]
402async fn terminate(child: &mut Child) -> Result<(), DevError> {
403 use nix::{
404 sys::signal::{Signal, killpg},
405 unistd::Pid,
406 };
407
408 let Some(id) = child.id() else {
409 let _ = child.wait().await.map_err(DevError::Wait)?;
410 return Ok(());
411 };
412 let process_group = Pid::from_raw(i32::try_from(id).map_err(|_| DevError::InvalidProcessId)?);
413 if let Err(error) = killpg(process_group, Signal::SIGTERM)
414 && error != nix::errno::Errno::ESRCH
415 {
416 return Err(DevError::SignalProcess(error));
417 }
418 if tokio::time::timeout(Duration::from_secs(3), child.wait())
419 .await
420 .is_err()
421 {
422 if let Err(error) = killpg(process_group, Signal::SIGKILL)
423 && error != nix::errno::Errno::ESRCH
424 {
425 return Err(DevError::SignalProcess(error));
426 }
427 let _ = child.wait().await.map_err(DevError::Wait)?;
428 }
429 Ok(())
430}
431
432#[cfg(not(unix))]
433async fn terminate(child: &mut Child) -> Result<(), DevError> {
434 if child.id().is_some() {
435 child.start_kill().map_err(DevError::Shutdown)?;
436 }
437 let _ = child.wait().await.map_err(DevError::Wait)?;
438 Ok(())
439}
440
441#[derive(Debug, Error)]
442pub enum DevError {
443 #[error("failed to start the {process} development process: {source}")]
444 Spawn {
445 process: &'static str,
446 source: std::io::Error,
447 },
448 #[error("failed while waiting for a development process: {0}")]
449 Wait(std::io::Error),
450 #[error("failed to stop a development process: {0}")]
451 Shutdown(std::io::Error),
452 #[cfg(unix)]
453 #[error("failed to signal a development process group: {0}")]
454 SignalProcess(nix::errno::Errno),
455 #[error("a development process returned an invalid process id")]
456 InvalidProcessId,
457 #[error("failed to listen for Ctrl-C: {0}")]
458 Signal(std::io::Error),
459 #[error("failed to watch Rust sources for reload: {0}")]
460 Watch(#[from] notify::Error),
461 #[error("Rust file watcher stopped unexpectedly")]
462 WatchClosed,
463 #[error("the {process} development process exited early with {status}")]
464 Exited {
465 process: &'static str,
466 status: ExitStatus,
467 },
468}
469
470#[cfg(test)]
471mod tests {
472 use super::*;
473 use std::{fs, time::Duration};
474
475 fn shell(script: &str) -> CommandSpec {
476 CommandSpec::new("sh").args(["-c", script])
477 }
478
479 #[test]
480 fn default_dev_config_runs_serve_with_watch() {
481 let config = DevConfig::default();
482 assert_eq!(config.rust.program, PathBuf::from("cargo"));
483 assert!(config.watch_rust);
484 assert_eq!(
485 config.rust.args,
486 vec![
487 OsString::from("run"),
488 OsString::from("--"),
489 OsString::from("serve")
490 ]
491 );
492 }
493
494 #[test]
495 fn watched_paths_cover_app_and_react_sources() {
496 let cwd = PathBuf::from("/app");
497 assert!(is_watched_rust_path(
498 &cwd,
499 &cwd.join("app/controllers/home.rs")
500 ));
501 assert!(is_watched_rust_path(&cwd, &cwd.join("Cargo.toml")));
502 assert!(is_watched_rust_path(
503 &cwd,
504 &cwd.join("views/pages/home.tsx")
505 ));
506 assert!(!is_watched_rust_path(
507 &cwd,
508 &cwd.join("target/debug/my-app")
509 ));
510 }
511
512 #[tokio::test]
513 async fn shutdown_stops_and_reaps_both_processes() {
514 let supervisor = DevSupervisor::new(
515 DevConfig::default()
516 .build_frontend(false)
517 .watch_rust(false)
518 .rust(shell("sleep 10 & wait"))
519 .vite(shell("sleep 10 & wait")),
520 );
521 supervisor
522 .run_with_shutdown(async {
523 tokio::time::sleep(Duration::from_millis(50)).await;
524 Ok(())
525 })
526 .await
527 .unwrap();
528 }
529
530 #[tokio::test]
531 async fn one_failed_process_stops_the_other_without_watch() {
532 let supervisor = DevSupervisor::new(
533 DevConfig::default()
534 .build_frontend(false)
535 .watch_rust(false)
536 .rust(shell("exit 7"))
537 .vite(shell("sleep 10")),
538 );
539 let result = supervisor.run_with_shutdown(std::future::pending()).await;
540
541 assert!(matches!(
542 result,
543 Err(DevError::Exited {
544 process: "Rust",
545 status,
546 }) if status.code() == Some(7)
547 ));
548 }
549
550 #[tokio::test]
551 async fn rust_exit_with_watch_waits_for_shutdown_without_failing() {
552 let supervisor = DevSupervisor::new(
553 DevConfig::default()
554 .build_frontend(false)
555 .watch_rust(true)
556 .rust(shell("exit 1"))
557 .vite(shell("sleep 10 & wait")),
558 );
559 supervisor
560 .run_with_shutdown(async {
561 tokio::time::sleep(Duration::from_millis(80)).await;
562 Ok(())
563 })
564 .await
565 .unwrap();
566 }
567
568 #[tokio::test]
569 async fn frontend_builds_run_before_the_backend() {
570 let marker = std::env::temp_dir().join(format!(
571 "phoenix-dev-build-{}-{}.txt",
572 std::process::id(),
573 std::time::SystemTime::now()
574 .duration_since(std::time::UNIX_EPOCH)
575 .unwrap()
576 .as_nanos()
577 ));
578 let marker = marker.to_string_lossy().into_owned();
579 let supervisor = DevSupervisor::new(
580 DevConfig::default()
581 .watch_rust(false)
582 .client_build(shell(&format!("printf client > {marker}")))
583 .renderer_build(shell(&format!("printf renderer >> {marker}")))
584 .rust(shell("sleep 10"))
585 .vite(shell("sleep 10")),
586 );
587 supervisor
588 .run_with_shutdown(async {
589 tokio::time::sleep(Duration::from_millis(80)).await;
590 Ok(())
591 })
592 .await
593 .unwrap();
594 assert_eq!(fs::read_to_string(&marker).unwrap(), "clientrenderer");
595 fs::remove_file(marker).unwrap();
596 }
597}