Skip to main content

euv_cli/hot/
impl.rs

1use super::*;
2
3/// Default dev server configuration targeting local Web development with OTA enabled.
4impl Default for DevServerConfig {
5    /// Returns a sensible default `DevServerConfig` bound to `127.0.0.1:8080`.
6    ///
7    /// # Returns
8    ///
9    /// - `Self` - Default development server configuration.
10    fn default() -> Self {
11        Self {
12            target: DevTargetArg::Web,
13            render: RenderArg::Auto,
14            release: false,
15            src_dir: PathBuf::from("."),
16            out_dir: PathBuf::from(OUT_DIR_WEB),
17            title: None,
18            base_url: String::new(),
19            package: None,
20            host: DEFAULT_DEV_HOST.to_string(),
21            port: 8080,
22            poll_ms: 250,
23            enable_ota: true,
24            once: false,
25            hot_ota: false,
26            watch_ota_path: None,
27            ota_store_dir: None,
28            ota_project: DEFAULT_DEV_OTA_PROJECT.to_string(),
29            ota_channel: DEFAULT_DEV_OTA_CHANNEL.to_string(),
30            ota_signing_key: OTA_DEV_SIGNING_KEY.to_string(),
31            ota_route: None,
32            ota_slot: None,
33            debounce_ms: DEFAULT_DEV_DEBOUNCE_MS,
34            coop_coep: false,
35            spa_fallback: true,
36        }
37    }
38}
39
40/// Change-set inspection helpers for `FileChangeSet`.
41impl FileChangeSet {
42    /// Returns `true` when no files were added, modified, or removed.
43    ///
44    /// # Arguments
45    ///
46    /// - `&Self` - File change set reference.
47    ///
48    /// # Returns
49    ///
50    /// - `bool` - Whether the change set is empty.
51    #[must_use]
52    pub fn is_empty(&self) -> bool {
53        self.get_added().is_empty()
54            && self.get_modified().is_empty()
55            && self.get_removed().is_empty()
56    }
57
58    /// Returns a flattened list of every added, modified, and removed file path.
59    ///
60    /// # Arguments
61    ///
62    /// - `&Self` - File change set reference.
63    ///
64    /// # Returns
65    ///
66    /// - `Vec<String>` - Combined changed path list.
67    #[must_use]
68    pub fn all_paths(&self) -> Vec<String> {
69        let mut out: Vec<String> = Vec::with_capacity(
70            self.get_added().len() + self.get_modified().len() + self.get_removed().len(),
71        );
72        out.extend(self.get_added().iter().cloned());
73        out.extend(self.get_modified().iter().cloned());
74        out.extend(self.get_removed().iter().cloned());
75        out
76    }
77
78    /// Merges another `FileChangeSet` into `self`, deduplicating paths cleanly.
79    ///
80    /// # Arguments
81    ///
82    /// - `&Self` - Destination accumulator change set.
83    /// - `Self` - Newly detected file changes to merge.
84    pub fn merge(&mut self, other: Self) {
85        let Self {
86            added,
87            modified,
88            removed,
89        } = self;
90        for path in other.get_added().iter() {
91            if !added.contains(path) {
92                added.push(path.clone());
93            }
94        }
95        for path in other.get_modified().iter() {
96            if !modified.contains(path) {
97                modified.push(path.clone());
98            }
99        }
100        for path in other.get_removed().iter() {
101            if !removed.contains(path) {
102                removed.push(path.clone());
103            }
104        }
105    }
106}
107
108/// Coalescing debounce window operations on `DebouncedWatcher`.
109impl DebouncedWatcher {
110    /// Creates a new `DebouncedWatcher` with a quiet window of `debounce_ms` milliseconds.
111    ///
112    /// # Arguments
113    ///
114    /// - `u64` - Quiet debounce interval in milliseconds (`0` flushes immediately).
115    ///
116    /// # Returns
117    ///
118    /// - `Self` - Empty debounced watcher.
119    #[must_use]
120    pub fn new(debounce_ms: u64) -> Self {
121        Self {
122            debounce_ms,
123            pending: FileChangeSet::default(),
124            last_change_at: None,
125        }
126    }
127
128    /// Records newly detected filesystem changes and restarts the debounce quiet timer.
129    ///
130    /// # Arguments
131    ///
132    /// - `&Self` - Debounced watcher state.
133    /// - `FileChangeSet` - Newly detected file change set.
134    /// - `Instant` - Monotonic timestamp when the change was observed.
135    pub fn record_changes(&mut self, changes: FileChangeSet, now: Instant) {
136        if changes.is_empty() {
137            return;
138        }
139        let Self {
140            pending,
141            last_change_at,
142            ..
143        } = self;
144        pending.merge(changes);
145        *last_change_at = Some(now);
146    }
147
148    /// Returns `true` when one or more file changes are queued awaiting the debounce window.
149    ///
150    /// # Returns
151    ///
152    /// - `bool` - Whether pending changes exist.
153    #[must_use]
154    pub fn has_pending(&self) -> bool {
155        !self.get_pending().is_empty()
156    }
157
158    /// Flushes and returns accumulated changes once the debounce quiet window has elapsed.
159    ///
160    /// # Arguments
161    ///
162    /// - `&Self` - Debounced watcher state.
163    /// - `Instant` - Current monotonic timestamp.
164    ///
165    /// # Returns
166    ///
167    /// - `Option<FileChangeSet>` - Coalesced change set if ready to rebuild.
168    pub fn flush_ready(&mut self, now: Instant) -> Option<FileChangeSet> {
169        let Self {
170            debounce_ms,
171            pending,
172            last_change_at,
173        } = self;
174        let last_seen: Instant = (*last_change_at)?;
175        if pending.is_empty() {
176            *last_change_at = None;
177            return None;
178        }
179        let elapsed_ms: u128 = now.saturating_duration_since(last_seen).as_millis();
180        if elapsed_ms < u128::from(*debounce_ms) {
181            return None;
182        }
183        *last_change_at = None;
184        Some(take(pending))
185    }
186}
187
188/// Zero-flicker build-before-swap coordination for native app hot restarts.
189impl BuildBeforeSwapController {
190    /// Records an initial launched process generation.
191    pub fn mark_initial_launched(&mut self) {
192        let next_gen: u64 = self.get_active_generation().saturating_add(1);
193        let _: &mut Self = self.set_active_generation(next_gen).set_last_error(None);
194    }
195
196    /// Compiles FIRST via `build_fn`; only invokes `stop_old_fn` and `spawn_new_fn` when compilation succeeds.
197    ///
198    /// # Arguments
199    ///
200    /// - `&Self` - Swap controller state.
201    /// - `BuildFn` - Build step executed while the existing process remains running.
202    /// - `StopFn` - Shutdown hook terminating the previous running process.
203    /// - `SpawnFn` - Launch hook starting the newly compiled binary.
204    ///
205    /// # Returns
206    ///
207    /// - `SwapOutcome` - `Swapped` / `LaunchedInitial` on success, or `KeptRunningOnError` when the old app stayed alive.
208    pub fn apply_rebuild<BuildFn, StopFn, SpawnFn>(
209        &mut self,
210        build_fn: BuildFn,
211        stop_old_fn: StopFn,
212        spawn_new_fn: SpawnFn,
213    ) -> SwapOutcome
214    where
215        BuildFn: FnOnce() -> io::Result<()>,
216        StopFn: FnOnce(),
217        SpawnFn: FnOnce() -> io::Result<()>,
218    {
219        if let Err(err) = build_fn() {
220            let err_msg: String = err.to_string();
221            let kept: u64 = self.get_kept_alive_on_error_count().saturating_add(1);
222            let _: &mut Self = self
223                .set_kept_alive_on_error_count(kept)
224                .set_last_error(Some(err_msg.clone()));
225            return SwapOutcome::KeptRunningOnError(err_msg);
226        }
227        let had_active: bool = self.get_active_generation() > 0;
228        if had_active {
229            stop_old_fn();
230        }
231        if let Err(err) = spawn_new_fn() {
232            let err_msg: String = err.to_string();
233            let _: &mut Self = self.set_last_error(Some(err_msg.clone()));
234            return SwapOutcome::KeptRunningOnError(err_msg);
235        }
236        let next_gen: u64 = self.get_active_generation().saturating_add(1);
237        let _: &mut Self = self.set_active_generation(next_gen).set_last_error(None);
238        if had_active {
239            let next_swaps: u64 = self.get_swap_count().saturating_add(1);
240            let _: &mut Self = self.set_swap_count(next_swaps);
241            SwapOutcome::Swapped
242        } else {
243            SwapOutcome::LaunchedInitial
244        }
245    }
246}
247
248/// Safe lifecycle management for spawned child processes preventing orphan leaks.
249impl ChildProcessGuard {
250    /// Terminates any existing child process and takes ownership of `next`.
251    ///
252    /// # Arguments
253    ///
254    /// - `&Self` - Guard owning the current child.
255    /// - `Child` - Newly spawned child process.
256    pub(crate) fn replace(&mut self, next: Child) {
257        self.terminate();
258        let Self { child } = self;
259        *child = Some(next);
260    }
261
262    /// Terminates and reaps the managed child process if currently running.
263    pub(crate) fn terminate(&mut self) {
264        let Self { child } = self;
265        if let Some(mut running) = child.take() {
266            drop(running.kill());
267            drop(running.wait());
268        }
269    }
270}
271
272/// Guarantees zero orphan child processes when `ChildProcessGuard` goes out of scope.
273impl Drop for ChildProcessGuard {
274    /// Terminates and reaps the active child process on drop.
275    fn drop(&mut self) {
276        self.terminate();
277    }
278}
279
280/// Recursive directory scanning and deterministic diffing for `WatchSnapshot`.
281impl WatchSnapshot {
282    /// Scans `root` recursively collecting modification stamps for files matching `allowed_exts`.
283    ///
284    /// # Arguments
285    ///
286    /// - `&Path` - Root project or documentation directory.
287    /// - `&[&str]` - Allowed lowercase file extensions (for example `["md", "rs"]`).
288    ///
289    /// # Returns
290    ///
291    /// - `io::Result<Self>` - Collected directory snapshot or I/O error.
292    pub fn scan(root: &Path, allowed_exts: &[&str]) -> io::Result<Self> {
293        Self::scan_excluding(root, allowed_exts, None)
294    }
295
296    /// Scans `root` recursively while excluding `exclude_dir` so generated outputs never self-trigger rebuilds.
297    ///
298    /// # Arguments
299    ///
300    /// - `&Path` - Root project or documentation directory.
301    /// - `&[&str]` - Allowed lowercase file extensions.
302    /// - `Option<&Path>` - Optional output directory excluded from watching.
303    ///
304    /// # Returns
305    ///
306    /// - `io::Result<Self>` - Collected directory snapshot or I/O error.
307    pub fn scan_excluding(
308        root: &Path,
309        allowed_exts: &[&str],
310        exclude_dir: Option<&Path>,
311    ) -> io::Result<Self> {
312        let mut entries: BTreeMap<PathBuf, FileStamp> = BTreeMap::new();
313        if !root.exists() {
314            return Ok(Self { entries });
315        }
316        let Some(ex) = exclude_dir else {
317            scan_dir_stamps(root, allowed_exts, None, None, false, &mut entries)?;
318            return Ok(Self { entries });
319        };
320        let (canonical_exclude, exclude_is_canon): (PathBuf, bool) = match fs::canonicalize(ex) {
321            Ok(canon) => (canon, true),
322            Err(_) => (ex.to_path_buf(), false),
323        };
324        let canonical_root: Option<PathBuf> = if exclude_is_canon {
325            fs::canonicalize(root).ok()
326        } else {
327            None
328        };
329        let (canon_dir, check_real_exclude): (Option<&Path>, bool) =
330            if let Some(cr) = canonical_root.as_deref() {
331                if canonical_exclude.starts_with(cr) || cr.starts_with(&canonical_exclude) {
332                    (Some(cr), true)
333                } else {
334                    (None, false)
335                }
336            } else {
337                (None, true)
338            };
339        scan_dir_stamps(
340            root,
341            allowed_exts,
342            Some(canonical_exclude.as_path()),
343            canon_dir,
344            check_real_exclude,
345            &mut entries,
346        )?;
347        Ok(Self { entries })
348    }
349
350    /// Computes added, modified, and removed paths comparing `self` (previous) against `next`.
351    ///
352    /// # Arguments
353    ///
354    /// - `&Self` - Previous snapshot.
355    /// - `&Self` - Freshly scanned snapshot.
356    ///
357    /// # Returns
358    ///
359    /// - `FileChangeSet` - Categorized file differences.
360    #[must_use]
361    pub fn diff(&self, next: &Self) -> FileChangeSet {
362        let mut added: Vec<String> = Vec::new();
363        let mut modified: Vec<String> = Vec::new();
364        let mut removed: Vec<String> = Vec::new();
365        let mut prev_iter: Peekable<btree_map::Iter<'_, PathBuf, FileStamp>> =
366            self.get_entries().iter().peekable();
367        let mut next_iter: Peekable<btree_map::Iter<'_, PathBuf, FileStamp>> =
368            next.get_entries().iter().peekable();
369        while let (Some(&(prev_path, prev_stamp)), Some(&(next_path, next_stamp))) =
370            (prev_iter.peek(), next_iter.peek())
371        {
372            match prev_path.cmp(next_path) {
373                cmp::Ordering::Less => {
374                    removed.push(prev_path.display().to_string());
375                    let _: Option<(&PathBuf, &FileStamp)> = prev_iter.next();
376                }
377                cmp::Ordering::Greater => {
378                    added.push(next_path.display().to_string());
379                    let _: Option<(&PathBuf, &FileStamp)> = next_iter.next();
380                }
381                cmp::Ordering::Equal => {
382                    if prev_stamp != next_stamp {
383                        modified.push(next_path.display().to_string());
384                    }
385                    let _: Option<(&PathBuf, &FileStamp)> = prev_iter.next();
386                    let _: Option<(&PathBuf, &FileStamp)> = next_iter.next();
387                }
388            }
389        }
390        for (prev_path, _) in prev_iter {
391            removed.push(prev_path.display().to_string());
392        }
393        for (next_path, _) in next_iter {
394            added.push(next_path.display().to_string());
395        }
396        FileChangeSet::new(added, modified, removed)
397    }
398}
399
400/// Thread-safe HMR broadcast and OTA bundle coordination for `HmrHub`.
401impl HmrHub {
402    /// Creates a new `HmrHub` initialized at revision `1` with `initial_ota`.
403    ///
404    /// # Arguments
405    ///
406    /// - `OtaBundleState` - Initial signed Dynamic WASM OTA artifact.
407    ///
408    /// # Returns
409    ///
410    /// - `Self` - Initialized hub ready for concurrent access.
411    #[must_use]
412    pub fn new(initial_ota: OtaBundleState) -> Self {
413        Self {
414            revision: AtomicU64::new(1),
415            last_event: Mutex::new(Some(HmrEvent::new(
416                1,
417                HmrEventKind::Reload,
418                MSG_INITIAL_BUILD_READY.to_string(),
419                Vec::new(),
420            ))),
421            ota_state: Mutex::new(initial_ota),
422            running: AtomicBool::new(true),
423        }
424    }
425
426    /// Returns the current monotonic rebuild revision counter.
427    ///
428    /// # Arguments
429    ///
430    /// - `&Self` - Hub reference.
431    ///
432    /// # Returns
433    ///
434    /// - `u64` - Current revision number.
435    #[must_use]
436    pub fn revision(&self) -> u64 {
437        let Self { revision, .. } = self;
438        revision.load(Ordering::Acquire)
439    }
440
441    /// Increments the revision counter and publishes a new `HmrEvent` to all SSE subscribers.
442    ///
443    /// # Arguments
444    ///
445    /// - `&Self` - Hub reference.
446    /// - `HmrEventKind` - Event variant (`Reload`, `OtaUpdate`, or `BuildError`).
447    /// - `String` - Human-readable event description.
448    /// - `Vec<String>` - List of changed source paths.
449    ///
450    /// # Returns
451    ///
452    /// - `u64` - Newly assigned revision number.
453    pub fn publish(&self, kind: HmrEventKind, message: String, changed_files: Vec<String>) -> u64 {
454        let Self {
455            revision,
456            last_event,
457            ..
458        } = self;
459        let next_rev: u64 = revision.fetch_add(1, Ordering::AcqRel) + 1;
460        let ui_event: HmrEvent = HmrEvent::new(next_rev, kind, message, changed_files);
461        if let Ok(mut guard) = last_event.lock() {
462            *guard = Some(ui_event);
463        }
464        next_rev
465    }
466
467    /// Replaces the active signed Dynamic WASM OTA bundle served over HTTP.
468    ///
469    /// # Arguments
470    ///
471    /// - `&Self` - Hub reference.
472    /// - `OtaBundleState` - Freshly compiled and signed OTA artifact.
473    pub fn set_ota_state(&self, next_state: OtaBundleState) {
474        let Self { ota_state, .. } = self;
475        if let Ok(mut guard) = ota_state.lock() {
476            *guard = next_state;
477        }
478    }
479
480    /// Returns a cloned copy of the latest published `HmrEvent`.
481    ///
482    /// # Arguments
483    ///
484    /// - `&Self` - Hub reference.
485    ///
486    /// # Returns
487    ///
488    /// - `Option<HmrEvent>` - Latest event snapshot.
489    #[must_use]
490    pub fn current_event(&self) -> Option<HmrEvent> {
491        let Self { last_event, .. } = self;
492        last_event
493            .lock()
494            .ok()
495            .and_then(|event_guard: MutexGuard<'_, Option<HmrEvent>>| event_guard.clone())
496    }
497
498    /// Returns a cloned snapshot of the active OTA manifest and `.wasm` bytes.
499    ///
500    /// # Arguments
501    ///
502    /// - `&Self` - Hub reference.
503    ///
504    /// # Returns
505    ///
506    /// - `Option<OtaBundleState>` - Active OTA artifact if lock is unpoisoned.
507    #[must_use]
508    pub fn ota_snapshot(&self) -> Option<OtaBundleState> {
509        let Self { ota_state, .. } = self;
510        ota_state
511            .lock()
512            .ok()
513            .map(|ota_guard: MutexGuard<'_, OtaBundleState>| ota_guard.clone())
514    }
515
516    /// Signals all background HTTP and watcher threads to exit cleanly.
517    ///
518    /// # Arguments
519    ///
520    /// - `&Self` - Hub reference.
521    pub fn stop(&self) {
522        let Self { running, .. } = self;
523        running.store(false, Ordering::Release);
524    }
525
526    /// Returns `true` while the dev server has not been shut down.
527    ///
528    /// # Arguments
529    ///
530    /// - `&Self` - Hub reference.
531    ///
532    /// # Returns
533    ///
534    /// - `bool` - Running state flag.
535    #[must_use]
536    pub fn is_running(&self) -> bool {
537        let Self { running, .. } = self;
538        running.load(Ordering::Acquire)
539    }
540}
541
542/// Runtime inspection and graceful shutdown operations for `DevServerHandle`.
543impl DevServerHandle {
544    /// Returns the bound local TCP socket address (`ip:port`).
545    ///
546    /// # Arguments
547    ///
548    /// - `&Self` - Server handle reference.
549    ///
550    /// # Returns
551    ///
552    /// - `SocketAddr` - Bound address.
553    #[must_use]
554    pub fn address(&self) -> SocketAddr {
555        let Self { address, .. } = self;
556        *address
557    }
558
559    /// Returns the base HTTP URL for this running dev server.
560    ///
561    /// # Arguments
562    ///
563    /// - `&Self` - Server handle reference.
564    ///
565    /// # Returns
566    ///
567    /// - `String` - Formatted `http://<ip>:<port>` URL.
568    #[must_use]
569    pub fn url(&self) -> String {
570        format!("http://{}", self.address())
571    }
572
573    /// Returns the current live rebuild revision counter.
574    ///
575    /// # Arguments
576    ///
577    /// - `&Self` - Server handle reference.
578    ///
579    /// # Returns
580    ///
581    /// - `u64` - Active revision number.
582    #[must_use]
583    pub fn revision(&self) -> u64 {
584        let Self { hub, .. } = self;
585        hub.revision()
586    }
587
588    /// Returns a reference to the mounted v1 OTA `UpdateStore`.
589    ///
590    /// # Returns
591    ///
592    /// - `&UpdateStore` - Backing v1 OTA store reference.
593    #[must_use]
594    pub fn ota_store(&self) -> &UpdateStore {
595        let Self { ota_store, .. } = self;
596        ota_store
597    }
598
599    /// Returns a reference to the shared `HmrHub`.
600    ///
601    /// # Returns
602    ///
603    /// - `&Arc<HmrHub>` - Shared HMR hub handle.
604    #[must_use]
605    pub fn hub(&self) -> &Arc<HmrHub> {
606        let Self { hub, .. } = self;
607        hub
608    }
609
610    /// Builds a structured `DevServerReport` describing this active server and its v1 OTA endpoints.
611    ///
612    /// # Arguments
613    ///
614    /// - `&Self` - Server handle reference.
615    ///
616    /// # Returns
617    ///
618    /// - `DevServerReport` - Serializable report snapshot.
619    #[must_use]
620    pub fn report(&self) -> DevServerReport {
621        let Self {
622            address,
623            out_dir,
624            mode,
625            page_count,
626            ota_project,
627            ota_channel,
628            hub,
629            ..
630        } = self;
631        let base_url: String = self.url();
632        let manifest_path: String =
633            format!("/v1/projects/{ota_project}/channels/{ota_channel}/manifest");
634        let events_path: String =
635            format!("/v1/projects/{ota_project}/channels/{ota_channel}/events");
636        let bound_port: u16 = address.port();
637        let lan_urls: Vec<String> = detect_lan_ip_addresses()
638            .into_iter()
639            .map(|lan_ip: String| format!("http://{lan_ip}:{bound_port}{manifest_path}"))
640            .collect();
641        let mut report: DevServerReport = DevServerReport::new(
642            mode.clone(),
643            base_url.clone(),
644            format!("{base_url}{HMR_ENDPOINT}"),
645            format!("{base_url}{OTA_MANIFEST_ENDPOINT}"),
646            out_dir.display().to_string(),
647            hub.revision(),
648            *page_count,
649        );
650        let _: &mut DevServerReport = report
651            .set_v1_manifest_url(format!("{base_url}{manifest_path}"))
652            .set_v1_events_url(format!("{base_url}{events_path}"))
653            .set_health_url(format!("{base_url}{UPDATE_ROUTE_HEALTHZ}"))
654            .set_lan_urls(lan_urls)
655            .set_ota_project(ota_project.clone())
656            .set_ota_channel(ota_channel.clone());
657        report
658    }
659
660    /// Gracefully stops the HTTP listener and file watcher threads and joins them.
661    ///
662    /// # Arguments
663    ///
664    /// - `&Self` - Mutable server handle.
665    pub fn shutdown(&mut self) {
666        let Self {
667            address,
668            hub,
669            http_thread,
670            watch_thread,
671            ..
672        } = self;
673        hub.stop();
674        drop(TcpStream::connect(*address));
675        if let Some(handle) = watch_thread.take() {
676            drop(handle.join());
677        }
678        if let Some(handle) = http_thread.take() {
679            drop(handle.join());
680        }
681    }
682}
683
684/// Ensures background server threads are cleanly stopped when `DevServerHandle` is dropped.
685impl Drop for DevServerHandle {
686    /// Signals shutdown and joins background threads on drop.
687    ///
688    /// # Arguments
689    ///
690    /// - `&Self` - Handle being dropped.
691    fn drop(&mut self) {
692        self.shutdown();
693    }
694}