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        }
26    }
27}
28
29/// Change-set inspection helpers for `FileChangeSet`.
30impl FileChangeSet {
31    /// Returns `true` when no files were added, modified, or removed.
32    ///
33    /// # Arguments
34    ///
35    /// - `&Self` - File change set reference.
36    ///
37    /// # Returns
38    ///
39    /// - `bool` - Whether the change set is empty.
40    #[must_use]
41    pub fn is_empty(&self) -> bool {
42        self.get_added().is_empty()
43            && self.get_modified().is_empty()
44            && self.get_removed().is_empty()
45    }
46
47    /// Returns a flattened list of every added, modified, and removed file path.
48    ///
49    /// # Arguments
50    ///
51    /// - `&Self` - File change set reference.
52    ///
53    /// # Returns
54    ///
55    /// - `Vec<String>` - Combined changed path list.
56    #[must_use]
57    pub fn all_paths(&self) -> Vec<String> {
58        let mut out: Vec<String> = Vec::with_capacity(
59            self.get_added().len() + self.get_modified().len() + self.get_removed().len(),
60        );
61        out.extend(self.get_added().iter().cloned());
62        out.extend(self.get_modified().iter().cloned());
63        out.extend(self.get_removed().iter().cloned());
64        out
65    }
66}
67
68/// Recursive directory scanning and deterministic diffing for `WatchSnapshot`.
69impl WatchSnapshot {
70    /// Scans `root` recursively collecting modification stamps for files matching `allowed_exts`.
71    ///
72    /// # Arguments
73    ///
74    /// - `&Path` - Root project or documentation directory.
75    /// - `&[&str]` - Allowed lowercase file extensions (for example `["md", "rs"]`).
76    ///
77    /// # Returns
78    ///
79    /// - `io::Result<Self>` - Collected directory snapshot or I/O error.
80    pub fn scan(root: &Path, allowed_exts: &[&str]) -> io::Result<Self> {
81        Self::scan_excluding(root, allowed_exts, None)
82    }
83
84    /// Scans `root` recursively while excluding `exclude_dir` so generated outputs never self-trigger rebuilds.
85    ///
86    /// # Arguments
87    ///
88    /// - `&Path` - Root project or documentation directory.
89    /// - `&[&str]` - Allowed lowercase file extensions.
90    /// - `Option<&Path>` - Optional output directory excluded from watching.
91    ///
92    /// # Returns
93    ///
94    /// - `io::Result<Self>` - Collected directory snapshot or I/O error.
95    pub fn scan_excluding(
96        root: &Path,
97        allowed_exts: &[&str],
98        exclude_dir: Option<&Path>,
99    ) -> io::Result<Self> {
100        let mut entries: BTreeMap<PathBuf, FileStamp> = BTreeMap::new();
101        if !root.exists() {
102            return Ok(Self { entries });
103        }
104        let Some(ex) = exclude_dir else {
105            scan_dir_stamps(root, allowed_exts, None, None, false, &mut entries)?;
106            return Ok(Self { entries });
107        };
108        let (canonical_exclude, exclude_is_canon): (PathBuf, bool) = match fs::canonicalize(ex) {
109            Ok(canon) => (canon, true),
110            Err(_) => (ex.to_path_buf(), false),
111        };
112        let canonical_root: Option<PathBuf> = if exclude_is_canon {
113            fs::canonicalize(root).ok()
114        } else {
115            None
116        };
117        let (canon_dir, check_real_exclude): (Option<&Path>, bool) =
118            if let Some(cr) = canonical_root.as_deref() {
119                if canonical_exclude.starts_with(cr) || cr.starts_with(&canonical_exclude) {
120                    (Some(cr), true)
121                } else {
122                    (None, false)
123                }
124            } else {
125                (None, true)
126            };
127        scan_dir_stamps(
128            root,
129            allowed_exts,
130            Some(canonical_exclude.as_path()),
131            canon_dir,
132            check_real_exclude,
133            &mut entries,
134        )?;
135        Ok(Self { entries })
136    }
137
138    /// Computes added, modified, and removed paths comparing `self` (previous) against `next`.
139    ///
140    /// # Arguments
141    ///
142    /// - `&Self` - Previous snapshot.
143    /// - `&Self` - Freshly scanned snapshot.
144    ///
145    /// # Returns
146    ///
147    /// - `FileChangeSet` - Categorized file differences.
148    #[must_use]
149    pub fn diff(&self, next: &Self) -> FileChangeSet {
150        let mut added: Vec<String> = Vec::new();
151        let mut modified: Vec<String> = Vec::new();
152        let mut removed: Vec<String> = Vec::new();
153        let mut prev_iter: Peekable<btree_map::Iter<'_, PathBuf, FileStamp>> =
154            self.get_entries().iter().peekable();
155        let mut next_iter: Peekable<btree_map::Iter<'_, PathBuf, FileStamp>> =
156            next.get_entries().iter().peekable();
157        while let (Some(&(prev_path, prev_stamp)), Some(&(next_path, next_stamp))) =
158            (prev_iter.peek(), next_iter.peek())
159        {
160            match prev_path.cmp(next_path) {
161                cmp::Ordering::Less => {
162                    removed.push(prev_path.display().to_string());
163                    let _: Option<(&PathBuf, &FileStamp)> = prev_iter.next();
164                }
165                cmp::Ordering::Greater => {
166                    added.push(next_path.display().to_string());
167                    let _: Option<(&PathBuf, &FileStamp)> = next_iter.next();
168                }
169                cmp::Ordering::Equal => {
170                    if prev_stamp != next_stamp {
171                        modified.push(next_path.display().to_string());
172                    }
173                    let _: Option<(&PathBuf, &FileStamp)> = prev_iter.next();
174                    let _: Option<(&PathBuf, &FileStamp)> = next_iter.next();
175                }
176            }
177        }
178        for (prev_path, _) in prev_iter {
179            removed.push(prev_path.display().to_string());
180        }
181        for (next_path, _) in next_iter {
182            added.push(next_path.display().to_string());
183        }
184        FileChangeSet::new(added, modified, removed)
185    }
186}
187
188/// Thread-safe HMR broadcast and OTA bundle coordination for `HmrHub`.
189impl HmrHub {
190    /// Creates a new `HmrHub` initialized at revision `1` with `initial_ota`.
191    ///
192    /// # Arguments
193    ///
194    /// - `OtaBundleState` - Initial signed Dynamic WASM OTA artifact.
195    ///
196    /// # Returns
197    ///
198    /// - `Self` - Initialized hub ready for concurrent access.
199    #[must_use]
200    pub fn new(initial_ota: OtaBundleState) -> Self {
201        Self {
202            revision: AtomicU64::new(1),
203            last_event: Mutex::new(Some(HmrEvent::new(
204                1,
205                HmrEventKind::Reload,
206                MSG_INITIAL_BUILD_READY.to_string(),
207                Vec::new(),
208            ))),
209            ota_state: Mutex::new(initial_ota),
210            running: AtomicBool::new(true),
211        }
212    }
213
214    /// Returns the current monotonic rebuild revision counter.
215    ///
216    /// # Arguments
217    ///
218    /// - `&Self` - Hub reference.
219    ///
220    /// # Returns
221    ///
222    /// - `u64` - Current revision number.
223    #[must_use]
224    pub fn revision(&self) -> u64 {
225        let Self { revision, .. } = self;
226        revision.load(Ordering::Acquire)
227    }
228
229    /// Increments the revision counter and publishes a new `HmrEvent` to all SSE subscribers.
230    ///
231    /// # Arguments
232    ///
233    /// - `&Self` - Hub reference.
234    /// - `HmrEventKind` - Event variant (`Reload`, `OtaUpdate`, or `BuildError`).
235    /// - `String` - Human-readable event description.
236    /// - `Vec<String>` - List of changed source paths.
237    ///
238    /// # Returns
239    ///
240    /// - `u64` - Newly assigned revision number.
241    pub fn publish(&self, kind: HmrEventKind, message: String, changed_files: Vec<String>) -> u64 {
242        let Self {
243            revision,
244            last_event,
245            ..
246        } = self;
247        let next_rev: u64 = revision.fetch_add(1, Ordering::AcqRel) + 1;
248        let ev: HmrEvent = HmrEvent::new(next_rev, kind, message, changed_files);
249        if let Ok(mut guard) = last_event.lock() {
250            *guard = Some(ev);
251        }
252        next_rev
253    }
254
255    /// Replaces the active signed Dynamic WASM OTA bundle served over HTTP.
256    ///
257    /// # Arguments
258    ///
259    /// - `&Self` - Hub reference.
260    /// - `OtaBundleState` - Freshly compiled and signed OTA artifact.
261    pub fn set_ota_state(&self, next_state: OtaBundleState) {
262        let Self { ota_state, .. } = self;
263        if let Ok(mut guard) = ota_state.lock() {
264            *guard = next_state;
265        }
266    }
267
268    /// Returns a cloned copy of the latest published `HmrEvent`.
269    ///
270    /// # Arguments
271    ///
272    /// - `&Self` - Hub reference.
273    ///
274    /// # Returns
275    ///
276    /// - `Option<HmrEvent>` - Latest event snapshot.
277    #[must_use]
278    pub fn current_event(&self) -> Option<HmrEvent> {
279        let Self { last_event, .. } = self;
280        last_event
281            .lock()
282            .ok()
283            .and_then(|g: MutexGuard<'_, Option<HmrEvent>>| g.clone())
284    }
285
286    /// Returns a cloned snapshot of the active OTA manifest and `.wasm` bytes.
287    ///
288    /// # Arguments
289    ///
290    /// - `&Self` - Hub reference.
291    ///
292    /// # Returns
293    ///
294    /// - `Option<OtaBundleState>` - Active OTA artifact if lock is unpoisoned.
295    #[must_use]
296    pub fn ota_snapshot(&self) -> Option<OtaBundleState> {
297        let Self { ota_state, .. } = self;
298        ota_state
299            .lock()
300            .ok()
301            .map(|g: MutexGuard<'_, OtaBundleState>| g.clone())
302    }
303
304    /// Signals all background HTTP and watcher threads to exit cleanly.
305    ///
306    /// # Arguments
307    ///
308    /// - `&Self` - Hub reference.
309    pub fn stop(&self) {
310        let Self { running, .. } = self;
311        running.store(false, Ordering::Release);
312    }
313
314    /// Returns `true` while the dev server has not been shut down.
315    ///
316    /// # Arguments
317    ///
318    /// - `&Self` - Hub reference.
319    ///
320    /// # Returns
321    ///
322    /// - `bool` - Running state flag.
323    #[must_use]
324    pub fn is_running(&self) -> bool {
325        let Self { running, .. } = self;
326        running.load(Ordering::Acquire)
327    }
328}
329
330/// Runtime inspection and graceful shutdown operations for `DevServerHandle`.
331impl DevServerHandle {
332    /// Returns the bound local TCP socket address (`ip:port`).
333    ///
334    /// # Arguments
335    ///
336    /// - `&Self` - Server handle reference.
337    ///
338    /// # Returns
339    ///
340    /// - `SocketAddr` - Bound address.
341    #[must_use]
342    pub fn address(&self) -> SocketAddr {
343        let Self { address, .. } = self;
344        *address
345    }
346
347    /// Returns the base HTTP URL for this running dev server.
348    ///
349    /// # Arguments
350    ///
351    /// - `&Self` - Server handle reference.
352    ///
353    /// # Returns
354    ///
355    /// - `String` - Formatted `http://<ip>:<port>` URL.
356    #[must_use]
357    pub fn url(&self) -> String {
358        format!("http://{}", self.address())
359    }
360
361    /// Returns the current live rebuild revision counter.
362    ///
363    /// # Arguments
364    ///
365    /// - `&Self` - Server handle reference.
366    ///
367    /// # Returns
368    ///
369    /// - `u64` - Active revision number.
370    #[must_use]
371    pub fn revision(&self) -> u64 {
372        let Self { hub, .. } = self;
373        hub.revision()
374    }
375
376    /// Builds a structured `DevServerReport` describing this active server.
377    ///
378    /// # Arguments
379    ///
380    /// - `&Self` - Server handle reference.
381    ///
382    /// # Returns
383    ///
384    /// - `DevServerReport` - Serializable report snapshot.
385    #[must_use]
386    pub fn report(&self) -> DevServerReport {
387        let Self {
388            out_dir,
389            mode,
390            page_count,
391            hub,
392            ..
393        } = self;
394        let base_url: String = self.url();
395        DevServerReport::new(
396            mode.clone(),
397            base_url.clone(),
398            format!("{base_url}{HMR_ENDPOINT}"),
399            format!("{base_url}{OTA_MANIFEST_ENDPOINT}"),
400            out_dir.display().to_string(),
401            hub.revision(),
402            *page_count,
403        )
404    }
405
406    /// Gracefully stops the HTTP listener and file watcher threads and joins them.
407    ///
408    /// # Arguments
409    ///
410    /// - `&Self` - Mutable server handle.
411    pub fn shutdown(&mut self) {
412        let Self {
413            address,
414            hub,
415            http_thread,
416            watch_thread,
417            ..
418        } = self;
419        hub.stop();
420        drop(TcpStream::connect(*address));
421        if let Some(handle) = watch_thread.take() {
422            drop(handle.join());
423        }
424        if let Some(handle) = http_thread.take() {
425            drop(handle.join());
426        }
427    }
428}
429
430/// Ensures background server threads are cleanly stopped when `DevServerHandle` is dropped.
431impl Drop for DevServerHandle {
432    /// Signals shutdown and joins background threads on drop.
433    ///
434    /// # Arguments
435    ///
436    /// - `&Self` - Handle being dropped.
437    fn drop(&mut self) {
438        self.shutdown();
439    }
440}