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        let canonical_exclude: Option<PathBuf> =
102            exclude_dir.map(|p: &Path| fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf()));
103        if root.exists() {
104            scan_dir_stamps(
105                root,
106                allowed_exts,
107                canonical_exclude.as_deref(),
108                &mut entries,
109            )?;
110        }
111        Ok(Self { entries })
112    }
113
114    /// Computes added, modified, and removed paths comparing `self` (previous) against `next`.
115    ///
116    /// # Arguments
117    ///
118    /// - `&Self` - Previous snapshot.
119    /// - `&Self` - Freshly scanned snapshot.
120    ///
121    /// # Returns
122    ///
123    /// - `FileChangeSet` - Categorized file differences.
124    #[must_use]
125    pub fn diff(&self, next: &Self) -> FileChangeSet {
126        let mut added: Vec<String> = Vec::new();
127        let mut modified: Vec<String> = Vec::new();
128        let mut removed: Vec<String> = Vec::new();
129        for (path, next_stamp) in next.get_entries().iter() {
130            match self.get_entries().get(path) {
131                None => added.push(path.display().to_string()),
132                Some(prev_stamp) if prev_stamp != next_stamp => {
133                    modified.push(path.display().to_string());
134                }
135                Some(_) => {}
136            }
137        }
138        for path in self.get_entries().keys() {
139            if !next.get_entries().contains_key(path) {
140                removed.push(path.display().to_string());
141            }
142        }
143        FileChangeSet::new(added, modified, removed)
144    }
145}
146
147/// Thread-safe HMR broadcast and OTA bundle coordination for `HmrHub`.
148impl HmrHub {
149    /// Creates a new `HmrHub` initialized at revision `1` with `initial_ota`.
150    ///
151    /// # Arguments
152    ///
153    /// - `OtaBundleState` - Initial signed Dynamic WASM OTA artifact.
154    ///
155    /// # Returns
156    ///
157    /// - `Self` - Initialized hub ready for concurrent access.
158    #[must_use]
159    pub fn new(initial_ota: OtaBundleState) -> Self {
160        Self {
161            revision: AtomicU64::new(1),
162            last_event: Mutex::new(Some(HmrEvent::new(
163                1,
164                HmrEventKind::Reload,
165                MSG_INITIAL_BUILD_READY.to_string(),
166                Vec::new(),
167            ))),
168            ota_state: Mutex::new(initial_ota),
169            running: AtomicBool::new(true),
170        }
171    }
172
173    /// Returns the current monotonic rebuild revision counter.
174    ///
175    /// # Arguments
176    ///
177    /// - `&Self` - Hub reference.
178    ///
179    /// # Returns
180    ///
181    /// - `u64` - Current revision number.
182    #[must_use]
183    pub fn revision(&self) -> u64 {
184        let Self { revision, .. } = self;
185        revision.load(Ordering::Acquire)
186    }
187
188    /// Increments the revision counter and publishes a new `HmrEvent` to all SSE subscribers.
189    ///
190    /// # Arguments
191    ///
192    /// - `&Self` - Hub reference.
193    /// - `HmrEventKind` - Event variant (`Reload`, `OtaUpdate`, or `BuildError`).
194    /// - `String` - Human-readable event description.
195    /// - `Vec<String>` - List of changed source paths.
196    ///
197    /// # Returns
198    ///
199    /// - `u64` - Newly assigned revision number.
200    pub fn publish(&self, kind: HmrEventKind, message: String, changed_files: Vec<String>) -> u64 {
201        let Self {
202            revision,
203            last_event,
204            ..
205        } = self;
206        let next_rev: u64 = revision.fetch_add(1, Ordering::AcqRel) + 1;
207        let ev: HmrEvent = HmrEvent::new(next_rev, kind, message, changed_files);
208        if let Ok(mut guard) = last_event.lock() {
209            *guard = Some(ev);
210        }
211        next_rev
212    }
213
214    /// Replaces the active signed Dynamic WASM OTA bundle served over HTTP.
215    ///
216    /// # Arguments
217    ///
218    /// - `&Self` - Hub reference.
219    /// - `OtaBundleState` - Freshly compiled and signed OTA artifact.
220    pub fn set_ota_state(&self, next_state: OtaBundleState) {
221        let Self { ota_state, .. } = self;
222        if let Ok(mut guard) = ota_state.lock() {
223            *guard = next_state;
224        }
225    }
226
227    /// Returns a cloned copy of the latest published `HmrEvent`.
228    ///
229    /// # Arguments
230    ///
231    /// - `&Self` - Hub reference.
232    ///
233    /// # Returns
234    ///
235    /// - `Option<HmrEvent>` - Latest event snapshot.
236    #[must_use]
237    pub fn current_event(&self) -> Option<HmrEvent> {
238        let Self { last_event, .. } = self;
239        last_event
240            .lock()
241            .ok()
242            .and_then(|g: MutexGuard<'_, Option<HmrEvent>>| g.clone())
243    }
244
245    /// Returns a cloned snapshot of the active OTA manifest and `.wasm` bytes.
246    ///
247    /// # Arguments
248    ///
249    /// - `&Self` - Hub reference.
250    ///
251    /// # Returns
252    ///
253    /// - `Option<OtaBundleState>` - Active OTA artifact if lock is unpoisoned.
254    #[must_use]
255    pub fn ota_snapshot(&self) -> Option<OtaBundleState> {
256        let Self { ota_state, .. } = self;
257        ota_state
258            .lock()
259            .ok()
260            .map(|g: MutexGuard<'_, OtaBundleState>| g.clone())
261    }
262
263    /// Signals all background HTTP and watcher threads to exit cleanly.
264    ///
265    /// # Arguments
266    ///
267    /// - `&Self` - Hub reference.
268    pub fn stop(&self) {
269        let Self { running, .. } = self;
270        running.store(false, Ordering::Release);
271    }
272
273    /// Returns `true` while the dev server has not been shut down.
274    ///
275    /// # Arguments
276    ///
277    /// - `&Self` - Hub reference.
278    ///
279    /// # Returns
280    ///
281    /// - `bool` - Running state flag.
282    #[must_use]
283    pub fn is_running(&self) -> bool {
284        let Self { running, .. } = self;
285        running.load(Ordering::Acquire)
286    }
287}
288
289/// Runtime inspection and graceful shutdown operations for `DevServerHandle`.
290impl DevServerHandle {
291    /// Returns the bound local TCP socket address (`ip:port`).
292    ///
293    /// # Arguments
294    ///
295    /// - `&Self` - Server handle reference.
296    ///
297    /// # Returns
298    ///
299    /// - `SocketAddr` - Bound address.
300    #[must_use]
301    pub fn address(&self) -> SocketAddr {
302        let Self { address, .. } = self;
303        *address
304    }
305
306    /// Returns the base HTTP URL for this running dev server.
307    ///
308    /// # Arguments
309    ///
310    /// - `&Self` - Server handle reference.
311    ///
312    /// # Returns
313    ///
314    /// - `String` - Formatted `http://<ip>:<port>` URL.
315    #[must_use]
316    pub fn url(&self) -> String {
317        format!("http://{}", self.address())
318    }
319
320    /// Returns the current live rebuild revision counter.
321    ///
322    /// # Arguments
323    ///
324    /// - `&Self` - Server handle reference.
325    ///
326    /// # Returns
327    ///
328    /// - `u64` - Active revision number.
329    #[must_use]
330    pub fn revision(&self) -> u64 {
331        let Self { hub, .. } = self;
332        hub.revision()
333    }
334
335    /// Builds a structured `DevServerReport` describing this active server.
336    ///
337    /// # Arguments
338    ///
339    /// - `&Self` - Server handle reference.
340    ///
341    /// # Returns
342    ///
343    /// - `DevServerReport` - Serializable report snapshot.
344    #[must_use]
345    pub fn report(&self) -> DevServerReport {
346        let Self {
347            out_dir,
348            mode,
349            page_count,
350            hub,
351            ..
352        } = self;
353        let base_url: String = self.url();
354        DevServerReport::new(
355            mode.clone(),
356            base_url.clone(),
357            format!("{base_url}{HMR_ENDPOINT}"),
358            format!("{base_url}{OTA_MANIFEST_ENDPOINT}"),
359            out_dir.display().to_string(),
360            hub.revision(),
361            *page_count,
362        )
363    }
364
365    /// Gracefully stops the HTTP listener and file watcher threads and joins them.
366    ///
367    /// # Arguments
368    ///
369    /// - `&Self` - Mutable server handle.
370    pub fn shutdown(&mut self) {
371        let Self {
372            address,
373            hub,
374            http_thread,
375            watch_thread,
376            ..
377        } = self;
378        hub.stop();
379        drop(TcpStream::connect(*address));
380        if let Some(handle) = watch_thread.take() {
381            drop(handle.join());
382        }
383        if let Some(handle) = http_thread.take() {
384            drop(handle.join());
385        }
386    }
387}
388
389/// Ensures background server threads are cleanly stopped when `DevServerHandle` is dropped.
390impl Drop for DevServerHandle {
391    /// Signals shutdown and joins background threads on drop.
392    ///
393    /// # Arguments
394    ///
395    /// - `&Self` - Handle being dropped.
396    fn drop(&mut self) {
397        self.shutdown();
398    }
399}