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
13const DEFAULT_POLL_INTERVAL: Duration = Duration::from_millis(200);
17
18pub 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 pub fn with_app(mut self, app: AppHandle) -> Self {
35 self.apps.push(app);
36 self
37 }
38}
39
40#[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
54pub struct DevReloadBuilder {
56 directory: PathBuf,
57 poll_interval: Duration,
58 on_error: ErrorCallback,
59}
60
61impl DevReloadBuilder {
62 pub fn poll_interval(mut self, interval: Duration) -> Self {
64 self.poll_interval = interval;
65 self
66 }
67
68 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 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
114pub struct DevReload<S> {
129 shared: Arc<Shared<S>>,
130 task: JoinHandle<()>,
131}
132
133impl DevReload<()> {
134 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 pub fn service(&self) -> DevService<S> {
147 DevService::new(self.shared.clone())
148 }
149
150 pub fn current(&self) -> S {
152 self.shared.current().0
153 }
154
155 pub fn reloads(&self) -> Reloads {
157 let mut tokens = self.shared.token.subscribe();
158 tokens.mark_unchanged();
159 Reloads { tokens }
160 }
161
162 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
181pub struct Reloads {
184 tokens: watch::Receiver<String>,
185}
186
187impl Reloads {
188 #[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 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 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 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 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#[derive(Clone, Copy, PartialEq, Eq)]
296struct Stamp {
297 modified: SystemTime,
298 len: u64,
299}
300
301impl Stamp {
302 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}