vertigo_cli/watch/
watch_run.rs

1use notify::RecursiveMode;
2use poem::http::Method;
3use poem::middleware::Cors;
4use poem::{get, listener::TcpListener, EndpointExt, Route, Server};
5use std::path::Path;
6use std::sync::Arc;
7use std::time::Duration;
8use tokio::sync::watch::Sender;
9use tokio::sync::Notify;
10use tokio::time::sleep;
11use tokio_retry::{strategy::FibonacciBackoff, Retry};
12
13use crate::build::{get_workspace, Workspace};
14use crate::commons::spawn::SpawnOwner;
15use crate::watch::sse::handler_sse;
16
17use super::is_http_server_listening::is_http_server_listening;
18use super::watch_opts::WatchOpts;
19
20#[derive(Clone, Debug, Default, PartialEq)]
21pub enum Status {
22    #[default]
23    Building,
24    Version(u32),
25    Errors,
26}
27
28pub async fn run(mut opts: WatchOpts) -> Result<(), i32> {
29    log::info!("watch params => {opts:#?}");
30
31    let ws = get_workspace().expect("Can't read workspace");
32
33    let package_name = match opts.build.package_name.as_deref() {
34        Some(name) => name.to_string(),
35        None => match ws.infer_package_name() {
36            Some(name) => {
37                log::info!("Inferred package name = {}", name);
38                opts.build.package_name = Some(name.clone());
39                name
40            }
41            None => {
42                log::error!(
43                    "Can't find vertigo project in {} (no cdylib member)",
44                    ws.get_root_dir()
45                );
46                return Err(-1);
47            }
48        },
49    };
50
51    log::info!("package_name ==> {package_name:?}");
52
53    let path = ws.find_package_path(&package_name);
54    log::info!("path ==> {path:?}");
55
56    let Some(path) = path else {
57        log::error!("package not found ==> {:?}", opts.build.package_name);
58        return Err(-1);
59    };
60
61    let excludes = [path.join("target"), path.join(opts.common.dest_dir.clone())];
62
63    let notify_build = Arc::new(Notify::new());
64
65    let watch_result = notify::RecommendedWatcher::new(
66        {
67            let notify_build = notify_build.clone();
68
69            move |res: Result<notify::Event, _>| match res {
70                Ok(event) => {
71                    if event.paths.iter().all(|path| {
72                        for exclude_path in &excludes {
73                            if path.starts_with(exclude_path) {
74                                return true;
75                            }
76                        }
77                        false
78                    }) {
79                        return;
80                    }
81                    log::info!("event: {:?}", event);
82                    notify_build.notify_one();
83                }
84                Err(e) => {
85                    log::error!("watch error: {:?}", e);
86                }
87            }
88        },
89        notify::Config::default().with_poll_interval(std::time::Duration::from_millis(200)),
90    );
91
92    let mut watcher = match watch_result {
93        Ok(watcher) => watcher,
94        Err(error) => {
95            log::error!("error watcher => {error}");
96            return Err(-1);
97        }
98    };
99
100    let (tx, rx) = tokio::sync::watch::channel(Status::default());
101    let tx = Arc::new(tx);
102
103    tokio::spawn({
104        let cors_middleware = Cors::new()
105            .allow_methods(vec![Method::GET, Method::POST])
106            .max_age(3600);
107
108        let app = Route::new()
109            .at("/events", get(handler_sse))
110            .with(cors_middleware)
111            .data(rx);
112
113        async move {
114            Server::new(TcpListener::bind("127.0.0.1:5555"))
115                .run(app)
116                .await
117        }
118    });
119
120    use notify::Watcher;
121    watcher.watch(&path, RecursiveMode::Recursive).unwrap();
122
123    for watch_path in &opts.add_watch_path {
124        log::info!("Adding `{watch_path}` to watched directories");
125        watcher
126            .watch(Path::new(watch_path), RecursiveMode::Recursive)
127            .expect("Error adding watch dir");
128    }
129    let mut version = 0;
130
131    loop {
132        version += 1;
133
134        if let Err(err) = tx.send(Status::Building) {
135            log::error!("Can't contact the browser: {err} (Other watch process already running?)");
136            return Err(-2);
137        };
138
139        log::info!("build run ...");
140
141        let spawn = build_and_watch(version, tx.clone(), &opts, &ws);
142        notify_build.notified().await;
143        spawn.off();
144    }
145}
146
147fn build_and_watch(
148    version: u32,
149    tx: Arc<Sender<Status>>,
150    opts: &WatchOpts,
151    ws: &Workspace,
152) -> SpawnOwner {
153    let opts = opts.clone();
154    let ws = ws.clone();
155    SpawnOwner::new(async move {
156        sleep(Duration::from_millis(200)).await;
157
158        match crate::build::run_with_ws(opts.to_build_opts(), &ws) {
159            Ok(()) => {
160                log::info!("build run ok");
161
162                let check_spawn = SpawnOwner::new(async move {
163                    let _ = Retry::spawn(
164                        FibonacciBackoff::from_millis(100).max_delay(Duration::from_secs(4)),
165                        || is_http_server_listening(opts.serve.port),
166                    )
167                    .await;
168
169                    let Ok(()) = tx.send(Status::Version(version)) else {
170                        unreachable!();
171                    };
172                });
173
174                let opts = opts.clone();
175
176                log::info!("serve run ...");
177                let (serve_params, port_watch) = opts.to_serve_opts();
178
179                if let Err(errno) = crate::serve::run(serve_params, Some(port_watch)).await {
180                    panic!("Error {errno} running server")
181                }
182
183                check_spawn.off();
184            }
185            Err(code) => {
186                log::error!("build run failed, exit code={code}");
187
188                let Ok(()) = tx.send(Status::Errors) else {
189                    unreachable!();
190                };
191            }
192        };
193    })
194}