trunk_build_time/cmd/
serve.rs

1use std::path::PathBuf;
2
3use anyhow::{Context, Result};
4use clap::Args;
5use tokio::sync::broadcast;
6
7use crate::config::{ConfigOpts, ConfigOptsBuild, ConfigOptsServe, ConfigOptsWatch};
8use crate::serve::ServeSystem;
9
10/// Build, watch & serve the Rust WASM app and all of its assets.
11#[derive(Args)]
12#[command(name = "serve")]
13pub struct Serve {
14    #[command(flatten)]
15    pub build: ConfigOptsBuild,
16    #[command(flatten)]
17    pub watch: ConfigOptsWatch,
18    #[command(flatten)]
19    pub serve: ConfigOptsServe,
20}
21
22impl Serve {
23    #[tracing::instrument(level = "trace", skip(self, config))]
24    pub async fn run(self, config: Option<PathBuf>) -> Result<()> {
25        let (shutdown_tx, _) = broadcast::channel(1);
26        let cfg = ConfigOpts::rtc_serve(self.build, self.watch, self.serve, config)?;
27        let system = ServeSystem::new(cfg, shutdown_tx.clone()).await?;
28
29        let system_handle = tokio::spawn(system.run());
30        tokio::signal::ctrl_c()
31            .await
32            .context("error awaiting shutdown signal")?;
33        tracing::debug!("received shutdown signal");
34        shutdown_tx.send(()).ok();
35        drop(shutdown_tx); // Ensure other components see the drop to avoid race conditions.
36        system_handle
37            .await
38            .context("error awaiting system shutdown")??;
39
40        Ok(())
41    }
42}