Skip to main content

fetchlet_http/dev/
reload.rs

1use std::future::Future;
2use std::path::{Path, PathBuf};
3use std::sync::{Arc, PoisonError, RwLock};
4use std::time::{Duration, SystemTime, UNIX_EPOCH};
5
6use fetchlet::AppHandle;
7use tokio::sync::watch;
8use tokio::task::JoinHandle;
9
10use super::service::DevService;
11use crate::{Artifact, ArtifactError, BoxError};
12
13/// How often the manifest is checked by default. A rebuild is noticed within
14/// this interval; checking reads one file's metadata, so a short interval
15/// costs little.
16const DEFAULT_POLL_INTERVAL: Duration = Duration::from_millis(200);
17
18/// What one build of the artifact serves: a service and the applications it
19/// uses, which are shut down when a later build replaces them.
20pub struct Generation<S> {
21    service: S,
22    apps: Vec<AppHandle>,
23}
24
25impl<S> Generation<S> {
26    pub fn new(service: S) -> Self {
27        Self {
28            service,
29            apps: Vec::new(),
30        }
31    }
32
33    /// Shut `app` down when this generation is replaced or the reload stops.
34    pub fn with_app(mut self, app: AppHandle) -> Self {
35        self.apps.push(app);
36        self
37    }
38}
39
40/// A failure while loading a new build. The previous generation keeps
41/// serving.
42#[derive(Debug, thiserror::Error)]
43pub enum ReloadError {
44    #[error(transparent)]
45    Artifact(#[from] ArtifactError),
46    #[error("could not start the new build: {0}")]
47    Build(BoxError),
48    #[error("could not shut down the previous build: {0}")]
49    Shutdown(fetchlet::Error),
50}
51
52type ErrorCallback = Arc<dyn Fn(&ReloadError) + Send + Sync>;
53
54/// Settings for [`DevReload`].
55pub struct DevReloadBuilder {
56    directory: PathBuf,
57    poll_interval: Duration,
58    on_error: ErrorCallback,
59}
60
61impl DevReloadBuilder {
62    /// How often `fetchlet.json` is checked for a new build. 200 ms by default.
63    pub fn poll_interval(mut self, interval: Duration) -> Self {
64        self.poll_interval = interval;
65        self
66    }
67
68    /// Report failed reloads. By default they are written to standard error.
69    pub fn on_error(mut self, callback: impl Fn(&ReloadError) + Send + Sync + 'static) -> Self {
70        self.on_error = Arc::new(callback);
71        self
72    }
73
74    /// Open the artifact, build the first generation with `build`, and start
75    /// watching for new builds. Fails when the first generation fails.
76    pub async fn start<S, F, Fut, E>(self, build: F) -> Result<DevReload<S>, ReloadError>
77    where
78        S: Clone + Send + Sync + 'static,
79        F: Fn(Artifact) -> Fut + Send + Sync + 'static,
80        Fut: Future<Output = Result<Generation<S>, E>> + Send + 'static,
81        E: Into<BoxError> + 'static,
82    {
83        let manifest = self.directory.join("fetchlet.json");
84        let stamp = Stamp::read(&manifest);
85        let first = build(Artifact::open(&self.directory)?)
86            .await
87            .map_err(|error| ReloadError::Build(error.into()))?;
88        let process = SystemTime::now()
89            .duration_since(UNIX_EPOCH)
90            .unwrap_or_default()
91            .as_nanos();
92        let (token, _) = watch::channel(format!("{process:x}-0"));
93        let shared = Arc::new(Shared {
94            current: RwLock::new(Current {
95                service: first.service,
96                apps: first.apps,
97            }),
98            token,
99        });
100        let task = tokio::spawn(watch_builds(Watch {
101            directory: self.directory,
102            manifest,
103            stamp,
104            poll_interval: self.poll_interval,
105            on_error: self.on_error,
106            shared: shared.clone(),
107            build,
108            process,
109        }));
110        Ok(DevReload { shared, task })
111    }
112}
113
114/// Serves an artifact while it is rebuilt, for development.
115///
116/// A build tool such as `vite build --watch` rewrites the artifact directory
117/// and writes `fetchlet.json` last. When the manifest changes, `DevReload`
118/// opens the artifact again, builds a new [`Generation`] with the caller's
119/// function, serves it from then on and shuts the previous applications down
120/// after their accepted calls finish. A failed reload is reported and the
121/// previous generation keeps serving.
122///
123/// [`DevReload::service`] serves the current generation and reloads browsers
124/// that show one of its HTML pages when a new one starts. A host that serves
125/// without a Tower service, such as a webview URI scheme, takes
126/// [`DevReload::current`] for each request and reloads its views when
127/// [`DevReload::reloads`] reports a new generation.
128pub struct DevReload<S> {
129    shared: Arc<Shared<S>>,
130    task: JoinHandle<()>,
131}
132
133impl DevReload<()> {
134    /// Watch the artifact in `directory`.
135    pub fn watch(directory: impl Into<PathBuf>) -> DevReloadBuilder {
136        DevReloadBuilder {
137            directory: directory.into(),
138            poll_interval: DEFAULT_POLL_INTERVAL,
139            on_error: Arc::new(|error| eprintln!("fetchlet reload failed: {error}")),
140        }
141    }
142}
143
144impl<S: Clone> DevReload<S> {
145    /// A service that dispatches each request to the current generation.
146    pub fn service(&self) -> DevService<S> {
147        DevService::new(self.shared.clone())
148    }
149
150    /// The service of the generation being served.
151    pub fn current(&self) -> S {
152        self.shared.current().0
153    }
154
155    /// Changes of generation from now on.
156    pub fn reloads(&self) -> Reloads {
157        let mut tokens = self.shared.token.subscribe();
158        tokens.mark_unchanged();
159        Reloads { tokens }
160    }
161
162    /// Stop watching and shut down the current generation's applications.
163    /// Requests that reach the generation afterwards fail as calls to a shut
164    /// down application do.
165    pub async fn shutdown(&self) -> Result<(), ReloadError> {
166        self.task.abort();
167        let apps = std::mem::take(&mut self.shared.write().apps);
168        for app in apps {
169            app.shutdown().await.map_err(ReloadError::Shutdown)?;
170        }
171        Ok(())
172    }
173}
174
175impl<S> Drop for DevReload<S> {
176    fn drop(&mut self) {
177        self.task.abort();
178    }
179}
180
181/// Reports each new generation of a [`DevReload`], for hosts that reload
182/// their views themselves.
183pub struct Reloads {
184    tokens: watch::Receiver<String>,
185}
186
187impl Reloads {
188    /// A stream that is already closed (never announces reloads), for an axum
189    /// webview serving an embedded artifact.
190    #[cfg(all(feature = "axum", fetchlet_engine))]
191    pub(crate) fn closed() -> Self {
192        let (_sender, tokens) = watch::channel(String::new());
193        Self { tokens }
194    }
195
196    /// Wait until a new generation serves. Generations that start while the
197    /// caller is not waiting are reported once. `None` once the `DevReload`
198    /// and its services are gone.
199    pub async fn next(&mut self) -> Option<()> {
200        self.tokens.changed().await.ok()
201    }
202}
203
204pub(super) struct Shared<S> {
205    current: RwLock<Current<S>>,
206    /// Identifies the generation being served, so browsers can tell when it
207    /// changes. It includes the process start, so a restarted server reloads
208    /// pages too.
209    pub(super) token: watch::Sender<String>,
210}
211
212struct Current<S> {
213    service: S,
214    apps: Vec<AppHandle>,
215}
216
217impl<S: Clone> Shared<S> {
218    /// The current service and its token.
219    pub(super) fn current(&self) -> (S, String) {
220        let current = self.current.read().unwrap_or_else(PoisonError::into_inner);
221        (current.service.clone(), self.token.borrow().clone())
222    }
223
224    fn write(&self) -> std::sync::RwLockWriteGuard<'_, Current<S>> {
225        self.current.write().unwrap_or_else(PoisonError::into_inner)
226    }
227}
228
229struct Watch<S, F> {
230    directory: PathBuf,
231    manifest: PathBuf,
232    stamp: Option<Stamp>,
233    poll_interval: Duration,
234    on_error: ErrorCallback,
235    shared: Arc<Shared<S>>,
236    build: F,
237    process: u128,
238}
239
240async fn watch_builds<S, F, Fut, E>(mut watch: Watch<S, F>)
241where
242    S: Clone + Send + Sync + 'static,
243    F: Fn(Artifact) -> Fut + Send + Sync + 'static,
244    Fut: Future<Output = Result<Generation<S>, E>> + Send + 'static,
245    E: Into<BoxError> + 'static,
246{
247    let mut generation = 0u64;
248    loop {
249        tokio::time::sleep(watch.poll_interval).await;
250        // A missing manifest is a build in progress; wait for it to return.
251        let Some(stamp) = Stamp::read(&watch.manifest) else {
252            continue;
253        };
254        if watch.stamp == Some(stamp) {
255            continue;
256        }
257        watch.stamp = Some(stamp);
258        let next = match Artifact::open(&watch.directory) {
259            Ok(artifact) => (watch.build)(artifact)
260                .await
261                .map_err(|error| ReloadError::Build(error.into())),
262            Err(error) => Err(error.into()),
263        };
264        let next = match next {
265            Ok(next) => next,
266            Err(error) => {
267                (watch.on_error)(&error);
268                continue;
269            }
270        };
271        generation += 1;
272        let previous = {
273            let mut current = watch.shared.write();
274            current.service = next.service;
275            std::mem::replace(&mut current.apps, next.apps)
276        };
277        watch
278            .shared
279            .token
280            .send_replace(format!("{:x}-{generation}", watch.process));
281        let on_error = watch.on_error.clone();
282        tokio::spawn(async move {
283            for app in previous {
284                if let Err(error) = app.shutdown().await {
285                    on_error(&ReloadError::Shutdown(error));
286                }
287            }
288        });
289    }
290}
291
292/// What identifies one write of the manifest. The build replaces the file
293/// even when its content is unchanged, so the modification time changes
294/// with every build.
295#[derive(Clone, Copy, PartialEq, Eq)]
296struct Stamp {
297    modified: SystemTime,
298    len: u64,
299}
300
301impl Stamp {
302    /// `None` while the manifest cannot be read, such as between a build
303    /// removing and replacing it.
304    fn read(path: &Path) -> Option<Self> {
305        let metadata = std::fs::metadata(path).ok()?;
306        Some(Self {
307            modified: metadata.modified().ok()?,
308            len: metadata.len(),
309        })
310    }
311}