use super::{
events::{Control, DevEvent, OutputStream, Status},
output::{tracing_line, Decoder, MAX_LINE_BYTES},
platform,
watcher::SourceWatcher,
};
use anyhow::{anyhow, Context, Result};
use capy_cli::FrontendDriver;
use capy_core::AppConfig;
use std::{
io::{BufRead, Seek},
path::{Path, PathBuf},
process::{Command, ExitStatus, Stdio},
sync::Arc,
time::Duration,
};
use tokio::{
io::{AsyncRead, AsyncReadExt},
sync::{mpsc, watch},
task::JoinSet,
};
#[derive(Clone, Debug)]
pub struct Definition {
pub id: usize,
pub name: String,
pub command: String,
pub url: Option<String>,
pub restartable: bool,
}
pub enum Recipe {
Backend {
root: PathBuf,
config: Box<AppConfig>,
logs: usize,
},
Frontend {
root: PathBuf,
driver: FrontendDriver,
origin: String,
port: u16,
},
}
pub struct Process {
pub definition: Definition,
pub recipe: Option<Recipe>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Request {
Run,
Restart(u64),
Shutdown,
}
enum Stop {
Restart,
Shutdown,
Exit(ExitStatus),
Error(anyhow::Error),
}
impl From<anyhow::Error> for Stop {
fn from(error: anyhow::Error) -> Self {
Self::Error(error)
}
}
impl From<std::io::Error> for Stop {
fn from(error: std::io::Error) -> Self {
Self::Error(error.into())
}
}
type Step<T> = std::result::Result<T, Stop>;
pub struct DevSupervisor {
processes: Vec<Process>,
events: mpsc::Sender<DevEvent>,
controls: mpsc::Receiver<Control>,
color: bool,
}
impl DevSupervisor {
pub fn new(
processes: Vec<Process>,
events: mpsc::Sender<DevEvent>,
controls: mpsc::Receiver<Control>,
color: bool,
) -> Self {
Self {
processes,
events,
controls,
color,
}
}
pub async fn run(mut self) -> Result<u8> {
let (backend_id, root) = self
.processes
.iter()
.find_map(|process| match &process.recipe {
Some(Recipe::Backend { root, .. }) => Some((process.definition.id, root.clone())),
_ => None,
})
.context("Development session has no backend")?;
let watcher = SourceWatcher::new(root).await?;
let (changes_tx, mut changes) = mpsc::channel(1);
let (watch_stop, mut watch_stopped) = watch::channel(());
let (installed, installed_rx) = watch::channel(
!self
.processes
.iter()
.any(|p| matches!(p.recipe, Some(Recipe::Frontend { .. }))),
);
let (backend, backend_rx) = watch::channel(false);
let mut workers = JoinSet::new();
let mut controls = Vec::new();
for process in self.processes {
let Some(recipe) = process.recipe else {
continue;
};
let (control, rx) = watch::channel(Request::Run);
controls.push((process.definition.id, control));
let worker = Worker {
id: process.definition.id,
events: self.events.clone(),
control: rx,
color: self.color,
};
workers.spawn(worker.run(
recipe,
installed.clone(),
installed_rx.clone(),
backend.clone(),
backend_rx.clone(),
));
}
workers.spawn(async move {
tokio::select! {
biased;
_ = watch_stopped.changed() => Ok(0),
result = watcher.run(changes_tx) => result.map(|()| 0),
}
});
let mut result = Ok(0);
let mut stopping = false;
let mut generation = 0;
while !workers.is_empty() {
tokio::select! {
Some(()) = changes.recv(), if !stopping => {
generation += 1;
if let Some((_, tx)) = controls.iter().find(|(id, _)| *id == backend_id) {
let _ = tx.send(Request::Restart(generation));
}
}
request = self.controls.recv(), if !stopping => {
match request {
Some(Control::Restart(id)) => {
generation += 1;
if let Some((_, tx)) = controls.iter().find(|(key, _)| *key == id) { let _ = tx.send(Request::Restart(generation)); }
}
Some(Control::Shutdown) | None => stopping = true,
}
}
done = workers.join_next() => {
match done {
Some(Ok(Ok(code))) if !stopping => { result = Ok(code); stopping = true; }
Some(Ok(Err(error))) if !stopping => { result = Err(error); stopping = true; }
Some(Err(error)) if !stopping => { result = Err(error.into()); stopping = true; }
_ => {}
}
}
}
if stopping {
let _ = watch_stop.send(());
for (_, tx) in &controls {
let _ = tx.send(Request::Shutdown);
}
}
}
result
}
}
struct Worker {
id: usize,
events: mpsc::Sender<DevEvent>,
control: watch::Receiver<Request>,
color: bool,
}
impl Worker {
async fn emit(&self, event: DevEvent) {
let _ = self.events.send(event).await;
}
async fn status(&self, status: Status) {
self.emit(DevEvent::Status {
id: self.id,
status,
})
.await;
}
async fn message(&self, text: &str) {
self.emit(DevEvent::Output(Arc::new(Decoder::default().line(
self.id,
OutputStream::System,
text,
))))
.await;
}
fn request(&mut self) -> Stop {
match *self.control.borrow_and_update() {
Request::Restart(_) => Stop::Restart,
_ => Stop::Shutdown,
}
}
async fn gate(&mut self, gate: &mut watch::Receiver<bool>) -> Step<()> {
while !*gate.borrow_and_update() {
tokio::select! {
result = gate.changed() => { result.map_err(|_| anyhow!("Development startup was cancelled"))?; }
_ = self.control.changed() => return Err(self.request()),
}
}
Ok(())
}
async fn run(
mut self,
recipe: Recipe,
installed: watch::Sender<bool>,
mut installed_rx: watch::Receiver<bool>,
backend: watch::Sender<bool>,
mut backend_rx: watch::Receiver<bool>,
) -> Result<u8> {
let mut restarting = false;
if matches!(recipe, Recipe::Backend { .. }) {
self.message("Watching Rust sources and Cargo.toml for changes…")
.await;
}
loop {
self.status(if restarting {
Status::Restarting
} else {
Status::Starting
})
.await;
let outcome = match &recipe {
Recipe::Backend { root, config, logs } => {
match self.gate(&mut installed_rx).await {
Ok(()) => self.backend(root, config, *logs, &backend).await,
Err(stop) => Err(stop),
}
}
Recipe::Frontend {
root,
driver,
origin,
port,
} => {
self.frontend(root, *driver, origin, *port, &installed, &mut backend_rx)
.await
}
};
match outcome {
Err(Stop::Restart) => {
restarting = true;
self.message("Restarting…").await;
}
Err(Stop::Shutdown) => {
self.status(Status::Stopped).await;
return Ok(0);
}
Err(Stop::Exit(status)) => {
self.status(Status::Failed {
code: status.code(),
})
.await;
self.message(&format!(
"Process exited ({status}). Stopping the application."
))
.await;
return Ok(exit_number(status).max(1));
}
Err(Stop::Error(error)) => {
self.status(Status::Failed { code: None }).await;
self.message(&format!("{error:#}")).await;
return Err(error);
}
Ok(()) => return Err(anyhow!("Development process stopped unexpectedly")),
}
}
}
async fn backend(
&mut self,
root: &Path,
config: &AppConfig,
logs: usize,
ready: &watch::Sender<bool>,
) -> Step<()> {
self.message("Resolving application binary · cargo metadata")
.await;
let mut metadata = tempfile::tempfile()?;
let mut command = Command::new("cargo");
command
.args(["metadata", "--no-deps", "--format-version=1"])
.current_dir(root)
.stdout(Stdio::from(metadata.try_clone()?));
self.compile(command).await?;
metadata.rewind()?;
let data: serde_json::Value =
serde_json::from_reader(metadata).context("Invalid Cargo metadata")?;
let bin = select_binary(root, &data)?;
self.message(&format!("Compiling {bin} · cargo build"))
.await;
let mut artifacts = tempfile::tempfile()?;
let mut command = Command::new("cargo");
command
.args([
"build",
"--bin",
&bin,
"--message-format=json-render-diagnostics",
])
.current_dir(root)
.stdout(Stdio::from(artifacts.try_clone()?));
self.compile(command).await?;
artifacts.rewind()?;
let mut executable = None;
for line in std::io::BufReader::new(artifacts).lines() {
let item: serde_json::Value =
serde_json::from_str(&line?).context("Invalid Cargo artifact")?;
if item["reason"] == "compiler-artifact" && item["target"]["name"] == bin {
if let Some(path) = item["executable"].as_str() {
executable = Some(PathBuf::from(path));
}
}
}
let executable = executable.context("Cargo did not produce an application binary")?;
let types = capy_cli::ProjectConfig::load(root)?.frontend.driver == FrontendDriver::React;
let generation = crate::contracts::Generation::new(root, types)?;
let mut export = Command::new(&executable);
export
.arg("__capy_contract")
.current_dir(root)
.env("APP_ENVIRONMENT", "development");
generation.capture(&mut export)?;
self.compile(export).await?;
if let Some(command) = generation.types_command()? {
self.compile(command).await?;
}
if generation.finish(false)? {
self.message("API contracts regenerated").await;
}
let mut command = Command::new(executable);
command
.arg("serve")
.current_dir(root)
.env("CAPY_DEV", "1")
.env("CAPY_DEV_LOG", "1")
.env("APP_ENVIRONMENT", "development")
.env("SERVER_HOST", config.host())
.env("SERVER_PORT", config.port().to_string());
self.message("Starting application · development").await;
let status = self
.execute(command, true, Some(logs), Some(ready), None)
.await?;
Err(Stop::Exit(status))
}
async fn frontend(
&mut self,
root: &Path,
driver: FrontendDriver,
origin: &str,
port: u16,
installed: &watch::Sender<bool>,
backend: &mut watch::Receiver<bool>,
) -> Step<()> {
if let Some(command) = driver.install_command(root) {
self.message("Installing frontend dependencies…").await;
self.checked(command, true, None, None).await?;
}
installed.send_replace(true);
self.gate(backend).await?;
let command = driver
.dev_command(root, origin, port)
.context("No frontend development command")?;
let status = self.execute(command, true, None, None, Some(port)).await?;
Err(Stop::Exit(status))
}
async fn compile(&mut self, command: Command) -> Step<()> {
let status = self.execute(command, false, None, None, None).await?;
if status.success() {
Ok(())
} else {
self.status(Status::Failed {
code: status.code(),
})
.await;
self.message("Build failed. Waiting for source changes to retry…")
.await;
let _ = self.control.changed().await;
Err(self.request())
}
}
async fn checked(
&mut self,
command: Command,
stdout: bool,
logs: Option<usize>,
port: Option<u16>,
) -> Step<()> {
let status = self.execute(command, stdout, logs, None, port).await?;
if status.success() {
Ok(())
} else {
Err(Stop::Exit(status))
}
}
async fn execute(
&mut self,
mut command: Command,
stdout: bool,
logs: Option<usize>,
ready: Option<&watch::Sender<bool>>,
port: Option<u16>,
) -> Step<ExitStatus> {
if self.control.has_changed().unwrap_or(true) {
return Err(self.request());
}
command.stdin(Stdio::null()).stderr(Stdio::piped());
if stdout {
command.stdout(Stdio::piped());
}
if self.color {
command
.env("FORCE_COLOR", "1")
.env("CARGO_TERM_COLOR", "always");
} else {
command
.env("NO_COLOR", "1")
.env("FORCE_COLOR", "0")
.env("CARGO_TERM_COLOR", "never");
}
let program = command.get_program().to_string_lossy().into_owned();
let mut child = platform::Child::spawn(&mut command.into())
.with_context(|| format!("Could not start {program}"))?;
let mut readers = JoinSet::new();
if let Some(pipe) = child.stdout() {
readers.spawn(pump(
pipe,
self.id,
logs,
OutputStream::Stdout,
self.events.clone(),
));
}
if let Some(pipe) = child.stderr() {
readers.spawn(pump(
pipe,
self.id,
logs,
OutputStream::Stderr,
self.events.clone(),
));
}
if ready.is_some() || port.is_some() {
self.status(Status::Running { pid: child.id() }).await;
}
if let Some(ready) = ready {
ready.send_replace(true);
if let Some(logs) = logs {
self.emit(DevEvent::Status {
id: logs,
status: Status::Running { pid: None },
})
.await;
}
}
let mut tick = tokio::time::interval(Duration::from_millis(50));
tick.set_missed_tick_behavior(tokio::time::MissedTickBehavior::Skip);
let started = tokio::time::Instant::now();
let mut frontend_ready = port.is_none();
let result = loop {
tokio::select! {
_ = self.control.changed() => {
let request = self.request();
if matches!(request, Stop::Restart) { self.status(Status::Restarting).await; }
child.stop().await;
break Err(request);
}
_ = tick.tick() => {
if let Some(status) = child.try_wait()? { child.kill(); break Ok(status); }
if !frontend_ready {
let port = port.expect("frontend port exists until ready");
if tokio::time::timeout(Duration::from_millis(25), tokio::net::TcpStream::connect(("127.0.0.1", port))).await.is_ok_and(|v| v.is_ok()) {
self.message(&format!("✓ Frontend ready · http://127.0.0.1:{port}")).await;
frontend_ready = true;
} else if started.elapsed() > Duration::from_secs(60) {
child.stop().await;
break Err(Stop::Error(anyhow!("Vite did not become ready on http://127.0.0.1:{port}. Check frontend output and vite.config.ts.")));
}
}
}
done = readers.join_next(), if !readers.is_empty() => {
match done {
Some(Ok(Ok(()))) => {},
Some(Ok(Err(error))) => { child.stop().await; break Err(Stop::Error(error)); },
Some(Err(error)) => { child.stop().await; break Err(Stop::Error(error.into())); },
None => {},
}
}
}
};
let _ = tokio::time::timeout(Duration::from_secs(1), async {
while readers.join_next().await.is_some() {}
})
.await;
if let Some(logs) = logs {
self.emit(DevEvent::Status {
id: logs,
status: Status::Stopped,
})
.await;
}
result
}
}
fn select_binary(root: &Path, metadata: &serde_json::Value) -> Result<String> {
let manifest = root.join("Cargo.toml").canonicalize()?;
let package = metadata["packages"]
.as_array()
.context("Cargo metadata has no packages")?
.iter()
.find(|p| {
p["manifest_path"]
.as_str()
.is_some_and(|s| Path::new(s) == manifest)
})
.context("Cannot locate application package in Cargo metadata")?;
let bins: Vec<_> = package["targets"]
.as_array()
.context("Cargo metadata has no targets")?
.iter()
.filter(|t| {
t["kind"]
.as_array()
.is_some_and(|k| k.iter().any(|k| k == "bin"))
})
.filter_map(|t| t["name"].as_str())
.collect();
if let Some(default) = package["default_run"].as_str() {
Ok(default.to_owned())
} else if bins.len() == 1 {
Ok(bins[0].to_owned())
} else {
Err(anyhow!("Application has multiple binaries. Set `package.default-run` in Cargo.toml for `capy dev`."))
}
}
async fn pump(
mut pipe: impl AsyncRead + Unpin,
id: usize,
logs: Option<usize>,
stream: OutputStream,
events: mpsc::Sender<DevEvent>,
) -> Result<()> {
let mut bytes = [0; 4096];
let mut line = Vec::new();
let mut truncated = false;
let mut decoder = Decoder::default();
let mut last_cr = false;
loop {
let n = pipe.read(&mut bytes).await?;
if n == 0 {
if !line.is_empty() || truncated {
publish(&mut decoder, &events, id, logs, stream, &line, truncated).await;
}
break;
}
for &byte in &bytes[..n] {
if byte == b'\n' || byte == b'\r' {
if !(last_cr && byte == b'\n') {
publish(&mut decoder, &events, id, logs, stream, &line, truncated).await;
}
line.clear();
truncated = false;
} else if line.len() < MAX_LINE_BYTES {
line.push(byte);
} else {
truncated = true;
}
last_cr = byte == b'\r';
}
}
Ok(())
}
async fn publish(
decoder: &mut Decoder,
events: &mpsc::Sender<DevEvent>,
id: usize,
logs: Option<usize>,
stream: OutputStream,
bytes: &[u8],
truncated: bool,
) {
let raw = String::from_utf8_lossy(bytes);
let (source, text) = if let Some((server, text)) = logs.and_then(|_| tracing_line(&raw)) {
(if server { id } else { logs.unwrap_or(id) }, text)
} else {
(id, raw.into_owned())
};
let mut line = decoder.line(source, stream, &text);
if truncated {
line.text.push_str(" … [line truncated]");
line.styled
.spans
.push(ratatui::text::Span::raw(" … [line truncated]"));
}
let _ = events.send(DevEvent::Output(Arc::new(line))).await;
}
pub fn exit_number(status: ExitStatus) -> u8 {
#[cfg(unix)]
{
use std::os::unix::process::ExitStatusExt;
status
.code()
.unwrap_or_else(|| 128 + status.signal().unwrap_or(1)) as u8
}
#[cfg(not(unix))]
{
u8::try_from(status.code().unwrap_or(1)).unwrap_or(1)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn output_handles_cr_invalid_utf8_partial_lines_and_bounds() {
let (tx, mut rx) = mpsc::channel(8);
let mut data = b"one\r\ntwo\rthree\n\xff\n".to_vec();
data.extend(vec![b'x'; MAX_LINE_BYTES + 100]);
pump(&data[..], 0, None, OutputStream::Stdout, tx)
.await
.unwrap();
let mut lines = vec![];
while let Some(DevEvent::Output(line)) = rx.recv().await {
lines.push(line.text.clone());
}
assert_eq!(&lines[..4], ["one", "two", "three", "�"]);
assert!(lines[4].ends_with("[line truncated]"));
assert!(lines[4].len() < MAX_LINE_BYTES + 30);
}
}