Skip to main content

camel_core/hot_reload/adapters/
reload_watcher.rs

1//! File-watching hot-reload loop.
2//!
3//! Watches YAML/JSON route files for changes and triggers pipeline reloads.
4//!
5//! # Circular dependency avoidance
6//!
7//! `camel-core` cannot depend on `camel-dsl` (which already depends on
8//! `camel-core`). Route discovery is therefore injected via a closure:
9//!
10//! ```ignore
11//! watch_and_reload(dirs, controller, || discover_routes(&patterns)).await?;
12//! ```
13//!
14//! This keeps `camel-core` decoupled while letting `camel-cli` (which has
15//! access to both) wire the pieces together.
16
17use std::collections::{BTreeSet, HashMap, HashSet};
18use std::path::{Component, Path, PathBuf};
19use std::sync::Arc;
20use std::sync::atomic::{AtomicU64, Ordering};
21use std::time::Duration;
22
23use futures::future::BoxFuture;
24use notify::{Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher};
25use tokio::sync::{mpsc, watch};
26use tokio_util::sync::CancellationToken;
27
28use camel_api::{CamelError, RuntimeCommand};
29use camel_component_api::template_reload::TemplateReloadRegistry;
30
31use crate::context::RuntimeExecutionHandle;
32use crate::hot_reload::application::reload::{FunctionReloadContext, ReloadError};
33use crate::hot_reload::application::{
34    compute_reload_actions_from_runtime_snapshot, execute_reload_actions,
35};
36use crate::hot_reload::domain::ReloadAction;
37use crate::lifecycle::application::route_definition::RouteDefinition;
38
39pub struct ReloadWatcher;
40
41impl ReloadWatcher {
42    #[allow(clippy::too_many_arguments)]
43    pub async fn watch_and_reload<F, D, P>(
44        watch_dirs: Vec<PathBuf>,
45        controller: RuntimeExecutionHandle,
46        discover_fn: F,
47        dev_provider: D,
48        publish_script_sources: P,
49        shutdown: Option<CancellationToken>,
50        drain_timeout: Duration,
51        debounce: Duration,
52    ) -> Result<(), CamelError>
53    where
54        F: Fn() -> Result<Vec<RouteDefinition>, CamelError> + Send + Sync + 'static,
55        D: Fn() -> Vec<(String, Vec<(PathBuf, DevSourceKind)>)> + Send + Sync + 'static,
56        P: Fn(&[String], &[String]) + Send + Sync + 'static,
57    {
58        watch_and_reload(
59            watch_dirs,
60            controller,
61            discover_fn,
62            dev_provider,
63            publish_script_sources,
64            shutdown,
65            drain_timeout,
66            debounce,
67        )
68        .await
69    }
70
71    pub fn resolve_watch_dirs(patterns: &[String]) -> Vec<PathBuf> {
72        resolve_watch_dirs(patterns)
73    }
74}
75
76/// Watch directories and reload pipelines when route files or dev-target
77/// sources change.
78///
79/// * `watch_dirs` — route root directories to monitor recursively.
80/// * `controller` — live route controller to apply reload actions to.
81/// * `discover_fn` — called after each debounced route-file event to load
82///   the current set of route definitions from disk.
83/// * `dev_provider` — synchronous snapshot of committed dev targets as
84///   `(route_id, [(path, kind)])` pairs. Parent directories of every source are
85///   watched (non-recursively) so asset edits can trigger a reload: template
86///   sources dispatch a per-route template reload, script sources trigger a
87///   full reload pass.
88/// * `publish_script_sources` — called once after every non-aborted reload pass
89///   with the route ids rebuilt and removed by it. The script watch registry
90///   promotes staged dependencies for rebuilt routes and drops removed ones.
91/// * `shutdown` — optional token; cancel it to stop the watcher gracefully.
92///
93/// The function runs indefinitely until the channel is closed, the shutdown
94/// token is cancelled, or a fatal initialisation error occurs.
95///
96/// # Errors
97///
98/// Returns `Err` only on fatal initialisation failure (watcher cannot be
99/// created, or a route directory cannot be watched). Per-route reload errors
100/// are logged as warnings and do not terminate the loop.
101#[allow(clippy::too_many_arguments)]
102pub async fn watch_and_reload<F, D, P>(
103    watch_dirs: Vec<PathBuf>,
104    controller: RuntimeExecutionHandle,
105    discover_fn: F,
106    dev_provider: D,
107    publish_script_sources: P,
108    shutdown: Option<CancellationToken>,
109    drain_timeout: Duration,
110    debounce: Duration,
111) -> Result<(), CamelError>
112where
113    F: Fn() -> Result<Vec<RouteDefinition>, CamelError> + Send + Sync + 'static,
114    D: Fn() -> Vec<(String, Vec<(PathBuf, DevSourceKind)>)> + Send + Sync + 'static,
115    P: Fn(&[String], &[String]) + Send + Sync + 'static,
116{
117    watch_and_reload_inner(
118        watch_dirs,
119        controller,
120        discover_fn,
121        dev_provider,
122        publish_script_sources,
123        shutdown,
124        drain_timeout,
125        debounce,
126        None,
127        None,
128    )
129    .await
130}
131
132/// Test-only entry point that exposes the watcher readiness and subscription
133/// reconciliation barriers. Production callers use [`watch_and_reload`].
134///
135/// Available to this crate's unit tests and to downstream integration tests
136/// that enable the `test-support` feature. The readiness signal fires after
137/// the initial dev-target subscriptions and reconciliation are applied, so a
138/// real-filesystem test can await it before its first write.
139#[cfg(any(test, feature = "test-support"))]
140#[doc(hidden)]
141#[allow(clippy::too_many_arguments)]
142pub async fn watch_and_reload_with_barriers<F, D, P>(
143    watch_dirs: Vec<PathBuf>,
144    controller: RuntimeExecutionHandle,
145    discover_fn: F,
146    dev_provider: D,
147    publish_script_sources: P,
148    shutdown: Option<CancellationToken>,
149    drain_timeout: Duration,
150    debounce: Duration,
151    ready_tx: watch::Sender<bool>,
152    reconciliation_tx: watch::Sender<u64>,
153) -> Result<(), CamelError>
154where
155    F: Fn() -> Result<Vec<RouteDefinition>, CamelError> + Send + Sync + 'static,
156    D: Fn() -> Vec<(String, Vec<(PathBuf, DevSourceKind)>)> + Send + Sync + 'static,
157    P: Fn(&[String], &[String]) + Send + Sync + 'static,
158{
159    watch_and_reload_inner(
160        watch_dirs,
161        controller,
162        discover_fn,
163        dev_provider,
164        publish_script_sources,
165        shutdown,
166        drain_timeout,
167        debounce,
168        Some(ready_tx),
169        Some(reconciliation_tx),
170    )
171    .await
172}
173
174#[allow(clippy::too_many_arguments)]
175async fn watch_and_reload_inner<F, D, P>(
176    watch_dirs: Vec<PathBuf>,
177    controller: RuntimeExecutionHandle,
178    discover_fn: F,
179    dev_provider: D,
180    publish_script_sources: P,
181    shutdown: Option<CancellationToken>,
182    drain_timeout: Duration,
183    debounce: Duration,
184    ready_tx: Option<watch::Sender<bool>>,
185    reconciliation_tx: Option<watch::Sender<u64>>,
186) -> Result<(), CamelError>
187where
188    F: Fn() -> Result<Vec<RouteDefinition>, CamelError> + Send + Sync + 'static,
189    D: Fn() -> Vec<(String, Vec<(PathBuf, DevSourceKind)>)> + Send + Sync + 'static,
190    P: Fn(&[String], &[String]) + Send + Sync + 'static,
191{
192    let (tx, rx) = mpsc::channel::<notify::Result<Event>>(64);
193
194    let mut watcher = RecommendedWatcher::new(
195        move |res| {
196            let _ = tx.blocking_send(res);
197        },
198        notify::Config::default(),
199    )
200    .map_err(|e| CamelError::RouteError(format!("Failed to create file watcher: {e}")))?;
201
202    if watch_dirs.is_empty() {
203        tracing::warn!("hot-reload: no directories to watch");
204    }
205
206    let route_roots: Vec<PathBuf> = watch_dirs.iter().map(|dir| normalize_path(dir)).collect();
207
208    for dir in &watch_dirs {
209        watcher.watch(dir, RecursiveMode::Recursive).map_err(|e| {
210            CamelError::RouteError(format!("Failed to watch directory {dir:?}: {e}"))
211        })?;
212        tracing::info!("hot-reload: watching {:?}", dir);
213    }
214
215    // Initial dev-target parent subscription. Reconciling from an empty set
216    // keeps the initial pass and every later pass on one code path.
217    let initial_map = DevTargetMap::from_sources(&dev_provider());
218    let mut subscribed: HashSet<PathBuf> = HashSet::new();
219    let initial_parents = wanted_dev_parents(&initial_map, &route_roots);
220    reconcile_subscriptions(&mut watcher, &mut subscribed, initial_parents.clone());
221
222    // Readiness barrier: signal only after the initial subscriptions AND the
223    // initial reconciliation are applied. Real-fs tests await this before any
224    // write, so no edit can precede a subscription.
225    if let Some(tx) = &reconciliation_tx {
226        let _ = tx.send(1);
227    }
228    if let Some(tx) = &ready_tx {
229        let _ = tx.send(true);
230    }
231
232    // Re-derivation channel: `run_reload_loop` publishes the wanted parent
233    // dirs after every re-derivation; the reconciliation loop below applies
234    // them to the watcher.
235    let (parents_tx, parents_rx) = watch::channel(initial_parents);
236
237    // Route-file reload pass: discovery + diff + action execution. Returns the
238    // ids rebuilt and removed by this pass; early-continue paths abort.
239    let discover = Arc::new(discover_fn);
240    let reload_pass = {
241        let controller = controller.clone();
242        move || -> BoxFuture<'static, Result<PassOutcome, CamelError>> {
243            let controller = controller.clone();
244            let discover = Arc::clone(&discover);
245            Box::pin(async move {
246                let new_defs = match discover() {
247                    Ok(defs) => defs,
248                    Err(e) => {
249                        tracing::warn!("hot-reload: route discovery failed: {e}");
250                        return Ok(PassOutcome::aborted_pass());
251                    }
252                };
253
254                // Compute the diff from runtime projection route IDs only.
255                let runtime_route_ids = match controller.runtime_route_ids().await {
256                    Ok(route_ids) => route_ids,
257                    Err(err) => {
258                        tracing::warn!(
259                            error = %err,
260                            "hot-reload: failed to list runtime routes; skipping this reload cycle"
261                        );
262                        return Ok(PassOutcome::aborted_pass());
263                    }
264                };
265                let mut runtime_hashes: HashMap<String, u64> = HashMap::new();
266                for id in &runtime_route_ids {
267                    if let Some(hash) = controller.route_source_hash(id).await {
268                        runtime_hashes.insert(id.clone(), hash);
269                    }
270                }
271
272                let actions = compute_reload_actions_from_runtime_snapshot(
273                    &new_defs,
274                    &runtime_route_ids,
275                    &|route_id: &str| runtime_hashes.get(route_id).copied(),
276                );
277
278                if actions.is_empty() {
279                    tracing::debug!("hot-reload: no route changes detected");
280                    return Ok(PassOutcome::default());
281                }
282
283                tracing::info!("hot-reload: applying {} reload action(s)", actions.len());
284
285                let function_ctx = controller.function_invoker().map(|invoker| {
286                    let generation = invoker.begin_reload();
287                    FunctionReloadContext {
288                        invoker,
289                        generation,
290                    }
291                });
292                // Only successfully rebuilt routes are covered by this pass.
293                // Skip and Remove do not rebuild, and failed actions leave the
294                // prior generation in place, so their assets still need a
295                // template dispatch.
296                let actions_for_derivation = actions.clone();
297                let errors = execute_reload_actions(
298                    actions,
299                    new_defs,
300                    &controller,
301                    drain_timeout,
302                    function_ctx.as_ref(),
303                )
304                .await;
305                for err in &errors {
306                    tracing::warn!(
307                        "hot-reload: error on route '{}' ({}): {}",
308                        err.route_id,
309                        err.action,
310                        err.error
311                    );
312                }
313                Ok(PassOutcome {
314                    rebuilt: derive_rebuilt_route_ids(&actions_for_derivation, &errors),
315                    removed: derive_removed_route_ids(&actions_for_derivation, &errors),
316                    aborted: false,
317                })
318            })
319        }
320    };
321
322    // Per-route template reload dispatch, bounded by the registry deadline plus
323    // the route-drain timeout.
324    let dispatch_reload = {
325        let controller = controller.clone();
326        let shutdown = shutdown.clone();
327        move |route_id: &str| -> BoxFuture<'static, Result<(), CamelError>> {
328            let controller = controller.clone();
329            let shutdown = shutdown.clone();
330            let route_id = route_id.to_string();
331            Box::pin(async move {
332                let bound = reload_dispatch_bound(&route_id, drain_timeout);
333                let command = RuntimeCommand::ReloadTemplates {
334                    route_id: route_id.clone(),
335                    command_id: next_reload_command_id(&route_id),
336                    causation_id: None,
337                };
338                bounded_dispatch(
339                    async move {
340                        controller
341                            .execute_runtime_command(command)
342                            .await
343                            .map(|_result| ())
344                    },
345                    bound,
346                    shutdown.as_ref(),
347                )
348                .await
349            })
350        }
351    };
352
353    // Re-derive the dev-target map from the registry on every batch.
354    let dev_map_provider = move || DevTargetMap::from_sources(&dev_provider());
355
356    let reload_loop = run_reload_loop(
357        rx,
358        watch_dirs,
359        controller,
360        &dev_map_provider,
361        &reload_pass,
362        &publish_script_sources,
363        &dispatch_reload,
364        parents_tx,
365        shutdown.clone(),
366        debounce,
367    );
368    let reconciliation = run_subscription_reconciliation(
369        watcher,
370        subscribed,
371        parents_rx,
372        reconciliation_tx,
373        shutdown,
374    );
375    tokio::try_join!(reload_loop, reconciliation)?;
376    Ok(())
377}
378
379/// Parent directories the watcher must subscribe for a dev-target snapshot.
380///
381/// Paths are normalized and sorted (deterministic output), and directories
382/// already covered by a recursive route-root watch are removed.
383fn wanted_dev_parents(map: &DevTargetMap, route_roots: &[PathBuf]) -> Vec<PathBuf> {
384    let roots: Vec<PathBuf> = route_roots
385        .iter()
386        .map(|root| normalize_path(root))
387        .collect();
388    let mut parents: Vec<PathBuf> = map
389        .parent_dirs()
390        .into_iter()
391        .map(|parent| normalize_path(&parent))
392        .filter(|parent| !roots.iter().any(|root| parent.starts_with(root)))
393        .collect::<HashSet<_>>()
394        .into_iter()
395        .collect();
396    parents.sort();
397    parents
398}
399
400/// Publish a parent-dir snapshot after every re-derivation.
401///
402/// Unchanged snapshots are published too: reconciliation is where failed
403/// best-effort subscriptions get retried, so suppressing a snapshot would also
404/// suppress those retries.
405fn publish_parents(tx: &watch::Sender<Vec<PathBuf>>, map: &DevTargetMap, route_roots: &[PathBuf]) {
406    let _ = tx.send(wanted_dev_parents(map, route_roots));
407}
408
409/// Add missing dev-target parent subscriptions and (best-effort) drop stale
410/// ones. Subscription errors are logged, not fatal: the watcher keeps running
411/// with whatever subscriptions it has.
412///
413/// The `subscribed` set records only *successful* operations, so a failed add
414/// is retried on the next reconciliation (the dir is not in the set) and a
415/// failed drop is retried too (the dir stays in the set). Successful operations
416/// are skipped, which keeps repeated reconciliation cheap.
417fn reconcile_subscriptions(
418    watcher: &mut RecommendedWatcher,
419    subscribed: &mut HashSet<PathBuf>,
420    wanted: Vec<PathBuf>,
421) {
422    let wanted_set: HashSet<&Path> = wanted.iter().map(PathBuf::as_path).collect();
423
424    for dir in &wanted {
425        if subscribed.contains(dir) {
426            continue;
427        }
428        match watcher.watch(dir, RecursiveMode::NonRecursive) {
429            Ok(()) => {
430                subscribed.insert(dir.clone());
431                tracing::info!("hot-reload: watching dev-target dir {:?}", dir);
432            }
433            Err(e) => {
434                tracing::warn!("hot-reload: failed to watch dev-target dir {dir:?}: {e}")
435            }
436        }
437    }
438
439    let stale: Vec<PathBuf> = subscribed
440        .iter()
441        .filter(|dir| !wanted_set.contains(dir.as_path()))
442        .cloned()
443        .collect();
444    for dir in stale {
445        match watcher.unwatch(&dir) {
446            Ok(()) => {
447                subscribed.remove(&dir);
448                tracing::debug!("hot-reload: dropped dev-target subscription {:?}", dir);
449            }
450            Err(e) => {
451                tracing::warn!("hot-reload: failed to drop dev-target dir {dir:?}: {e}")
452            }
453        }
454    }
455}
456
457/// Apply every parent-dir snapshot published by [`run_reload_loop`].
458async fn run_subscription_reconciliation(
459    mut watcher: RecommendedWatcher,
460    mut subscribed: HashSet<PathBuf>,
461    mut parents_rx: watch::Receiver<Vec<PathBuf>>,
462    reconciliation_tx: Option<watch::Sender<u64>>,
463    shutdown: Option<CancellationToken>,
464) -> Result<(), CamelError> {
465    loop {
466        let changed = if let Some(token) = shutdown.as_ref() {
467            tokio::select! {
468                biased;
469                _ = token.cancelled() => return Ok(()),
470                changed = parents_rx.changed() => changed,
471            }
472        } else {
473            parents_rx.changed().await
474        };
475
476        if changed.is_err() {
477            return Ok(());
478        }
479
480        let wanted = parents_rx.borrow_and_update().clone();
481        reconcile_subscriptions(&mut watcher, &mut subscribed, wanted);
482        if let Some(tx) = &reconciliation_tx {
483            let next = *tx.borrow() + 1;
484            let _ = tx.send(next);
485        }
486    }
487}
488
489/// Sequence for template-reload command ids, mirroring the context lifecycle
490/// command-id pattern (`context:{op}:{route_id}:{boot_nonce}:{seq}`).
491static RELOAD_COMMAND_SEQ: AtomicU64 = AtomicU64::new(0);
492
493fn next_reload_command_id(route_id: &str) -> String {
494    let seq = RELOAD_COMMAND_SEQ.fetch_add(1, Ordering::Relaxed);
495    format!("hot-reload:reload-templates:{route_id}:{seq}")
496}
497
498/// Dispatch bound for a template reload: the tightest registry deadline for
499/// `route_id` plus the route-drain timeout.
500fn reload_dispatch_bound(route_id: &str, drain_timeout: Duration) -> Duration {
501    let registry_deadline = TemplateReloadRegistry::global()
502        .find_all(route_id)
503        .iter()
504        .map(|target| target.reload_timeout())
505        .min()
506        .unwrap_or_else(|| Duration::from_millis(5000));
507    registry_deadline + drain_timeout
508}
509
510/// Run a dispatch future under a hard time bound, biased against shutdown.
511///
512/// On timeout or cancellation the future is dropped, so a slow reload can
513/// never commit late. A cancelled shutdown is reported with the same
514/// `TemplateReload("dispatch bound elapsed")` error as a timeout — the caller
515/// logs and continues; the outer loop observes the cancel on its next
516/// iteration and stops.
517pub(crate) async fn bounded_dispatch<F>(
518    fut: F,
519    bound: Duration,
520    shutdown: Option<&CancellationToken>,
521) -> Result<(), CamelError>
522where
523    F: std::future::Future<Output = Result<(), CamelError>>,
524{
525    let timed = tokio::time::timeout(bound, fut);
526    match shutdown {
527        Some(token) => {
528            tokio::select! {
529                biased;
530                _ = token.cancelled() => {
531                    Err(CamelError::TemplateReload("dispatch bound elapsed".to_string()))
532                }
533                result = timed => match result {
534                    Ok(inner) => inner,
535                    Err(_elapsed) => {
536                        Err(CamelError::TemplateReload("dispatch bound elapsed".to_string()))
537                    }
538                },
539            }
540        }
541        None => match timed.await {
542            Ok(inner) => inner,
543            Err(_elapsed) => Err(CamelError::TemplateReload(
544                "dispatch bound elapsed".to_string(),
545            )),
546        },
547    }
548}
549
550/// Outcome of one route-file reload pass.
551///
552/// `rebuilt` drives template dispatch suppression: a rebuilt route's assets are
553/// covered by the pass. `removed` lists routes whose `Remove` action executed
554/// without error, so the script watch registry can drop them. `aborted` marks a
555/// pass that ended before computing a diff (discovery or runtime snapshot
556/// failure); an aborted pass must not be published, because it says nothing
557/// about which routes still run.
558#[derive(Debug, Default, Clone, PartialEq, Eq)]
559pub(crate) struct PassOutcome {
560    /// Route ids successfully rebuilt by this pass.
561    pub(crate) rebuilt: Vec<String>,
562    /// Route ids removed by this pass (successful `Remove` actions only).
563    pub(crate) removed: Vec<String>,
564    /// `true` when the pass ended early without a diff.
565    pub(crate) aborted: bool,
566}
567
568impl PassOutcome {
569    /// An aborted pass: no diff was computed, so nothing may be published.
570    fn aborted_pass() -> Self {
571        Self {
572            rebuilt: Vec::new(),
573            removed: Vec::new(),
574            aborted: true,
575        }
576    }
577}
578
579/// Route ids successfully rebuilt by one reload pass.
580///
581/// `Add`, `Swap` and `Restart` rebuild the route, so their ids are candidates.
582/// `Skip` and `Remove` do not rebuild anything. A candidate whose action
583/// reported an error is excluded because the failed action left the prior
584/// generation in place — its assets still need a template dispatch.
585pub(crate) fn derive_rebuilt_route_ids(
586    actions: &[ReloadAction],
587    errors: &[ReloadError],
588) -> Vec<String> {
589    let failed: HashSet<&str> = errors.iter().map(|err| err.route_id.as_str()).collect();
590    actions
591        .iter()
592        .filter_map(|action| match action {
593            ReloadAction::Swap { route_id }
594            | ReloadAction::Restart { route_id }
595            | ReloadAction::Add { route_id } => Some(route_id),
596            ReloadAction::Skip { .. } | ReloadAction::Remove { .. } => None,
597        })
598        .filter(|route_id| !failed.contains(route_id.as_str()))
599        .cloned()
600        .collect()
601}
602
603/// Route ids removed by one reload pass.
604///
605/// Only `Remove` actions count. A `Remove` that reported an error did not stop
606/// the route, so it keeps running and its script targets must be retained.
607pub(crate) fn derive_removed_route_ids(
608    actions: &[ReloadAction],
609    errors: &[ReloadError],
610) -> Vec<String> {
611    let failed: HashSet<&str> = errors.iter().map(|err| err.route_id.as_str()).collect();
612    actions
613        .iter()
614        .filter_map(|action| match action {
615            ReloadAction::Remove { route_id } => Some(route_id),
616            ReloadAction::Swap { .. }
617            | ReloadAction::Restart { .. }
618            | ReloadAction::Add { .. }
619            | ReloadAction::Skip { .. } => None,
620        })
621        .filter(|route_id| !failed.contains(route_id.as_str()))
622        .cloned()
623        .collect()
624}
625
626/// Debounced watch loop extracted from [`watch_and_reload`] so tests can drive
627/// it with a synthetic event source.
628///
629/// The loop classifies each debounced batch: route files and script sources run
630/// `reload_pass` once, template edits dispatch a per-route template reload, and
631/// unrelated events are ignored. A successful, non-aborted pass publishes its
632/// [`PassOutcome`] through `publish_script_sources` so the script watch
633/// registry can promote or drop per-route script dependencies.
634#[allow(clippy::too_many_arguments)]
635pub(crate) async fn run_reload_loop(
636    mut event_rx: mpsc::Receiver<notify::Result<Event>>,
637    route_roots: Vec<PathBuf>,
638    _controller: RuntimeExecutionHandle,
639    dev_provider: &(dyn Fn() -> DevTargetMap + Send + Sync),
640    reload_pass: &(dyn Fn() -> BoxFuture<'static, Result<PassOutcome, CamelError>> + Send + Sync),
641    publish_script_sources: &(dyn Fn(&[String], &[String]) + Send + Sync),
642    dispatch_reload: &(dyn Fn(&str) -> BoxFuture<'static, Result<(), CamelError>> + Send + Sync),
643    parents_tx: watch::Sender<Vec<PathBuf>>,
644    shutdown: Option<CancellationToken>,
645    debounce: Duration,
646) -> Result<(), CamelError> {
647    let is_cancelled = || shutdown.as_ref().map(|t| t.is_cancelled()).unwrap_or(false);
648    let mut dev_map = dev_provider();
649
650    loop {
651        if is_cancelled() {
652            tracing::debug!("hot-reload: shutdown requested — stopping watcher");
653            return Ok(());
654        }
655
656        // Wait for the first classified event. The select only produces the
657        // next message; loop control stays outside so `break`/`continue` are
658        // never captured by the select macro.
659        let mut batch: Vec<(EventClass, Event)> = loop {
660            let msg = if let Some(token) = shutdown.as_ref() {
661                tokio::select! {
662                    biased;
663                    _ = token.cancelled() => {
664                        tracing::debug!("hot-reload: shutdown requested — stopping watcher");
665                        return Ok(());
666                    }
667                    msg = event_rx.recv() => msg,
668                }
669            } else {
670                event_rx.recv().await
671            };
672
673            match msg {
674                None => return Ok(()), // channel closed — watcher dropped
675                Some(Err(e)) => {
676                    tracing::warn!("hot-reload: watcher error: {e}");
677                }
678                Some(Ok(event)) => {
679                    if let Some(class) = classify_event(&event, &dev_map, &route_roots) {
680                        break vec![(class, event)];
681                    }
682                }
683            }
684        };
685
686        // Drain further events within the debounce window.
687        let deadline = tokio::time::Instant::now() + debounce;
688        loop {
689            let received = if let Some(token) = shutdown.as_ref() {
690                tokio::select! {
691                    biased;
692                    _ = token.cancelled() => {
693                        tracing::debug!("hot-reload: shutdown requested — stopping watcher");
694                        return Ok(());
695                    }
696                    result = tokio::time::timeout_at(deadline, event_rx.recv()) => result,
697                }
698            } else {
699                tokio::time::timeout_at(deadline, event_rx.recv()).await
700            };
701
702            match received {
703                Ok(Some(Ok(event))) => {
704                    if let Some(class) = classify_event(&event, &dev_map, &route_roots) {
705                        batch.push((class, event));
706                    }
707                }
708                Ok(Some(Err(e))) => tracing::warn!("hot-reload: watcher error: {e}"),
709                Ok(None) => return Ok(()), // channel closed
710                Err(_elapsed) => break,    // debounce window expired
711            }
712        }
713
714        let has_full_pass_trigger = batch
715            .iter()
716            .any(|(class, _)| matches!(*class, EventClass::RouteFile | EventClass::ScriptSource));
717        let mut pending: BTreeSet<String> = BTreeSet::new();
718        for (class, event) in &batch {
719            if *class == EventClass::DevTarget {
720                for path in &event.paths {
721                    pending.extend(dev_map.routes_for(path));
722                }
723            }
724        }
725
726        let mut rebuilt: HashSet<String> = HashSet::new();
727        if has_full_pass_trigger {
728            tracing::info!("hot-reload: file change detected — reloading routes");
729            match reload_pass().await {
730                Ok(outcome) => {
731                    rebuilt = outcome.rebuilt.iter().cloned().collect();
732                    // An aborted pass computed no diff, so it says nothing
733                    // about which routes still run: publishing it would let the
734                    // registry react to a phantom empty outcome.
735                    if !outcome.aborted {
736                        publish_script_sources(&outcome.rebuilt, &outcome.removed);
737                    }
738                }
739                Err(err) => tracing::warn!("hot-reload: reload pass failed: {err}"),
740            }
741            // Re-derive after the route pass: a rebuilt route's assets are
742            // covered by the pass; surviving target routes still dispatch.
743            dev_map = dev_provider();
744            publish_parents(&parents_tx, &dev_map, &route_roots);
745        } else {
746            tracing::info!(
747                "hot-reload: dev target change detected — dispatching {} target route(s)",
748                pending.len()
749            );
750            dev_map = dev_provider();
751            publish_parents(&parents_tx, &dev_map, &route_roots);
752        }
753
754        // Dispatch only pending routes that were not successfully rebuilt and
755        // still declare a target in the refreshed map.
756        pending.retain(|route_id| !rebuilt.contains(route_id) && dev_map.has_targets_for(route_id));
757
758        for route_id in pending {
759            match dispatch_reload(route_id.as_str()).await {
760                Ok(()) => {
761                    // A committed reload may change the route's dependency
762                    // closure (for example a template now includes a file from
763                    // a new directory), so re-derive and let the wrapper
764                    // reconcile subscriptions right away. Publishing per
765                    // commit means a later pending route that stalls can no
766                    // longer delay an earlier route's new parents.
767                    dev_map = dev_provider();
768                    publish_parents(&parents_tx, &dev_map, &route_roots);
769                }
770                Err(err) => {
771                    tracing::warn!(
772                        "hot-reload: reload dispatch failed for route '{route_id}': {err}"
773                    );
774                }
775            }
776        }
777    }
778}
779
780/// Classification outcome for a single notify event.
781///
782/// `None` (no class) is the ignore outcome: the event matches neither a
783/// dev-target source nor a route file.
784#[cfg_attr(not(test), allow(dead_code))]
785#[derive(Debug, Clone, Copy, PartialEq, Eq)]
786pub(crate) enum EventClass {
787    /// YAML/JSON route definition under a configured route root.
788    RouteFile,
789    /// Any template asset (template, proto, include, …) declared by a reload
790    /// target. Dispatched per route as `ReloadTemplates`.
791    DevTarget,
792    /// Script file (`.rhai`, `.js`, …) declared as a route script source.
793    /// Triggers a full reload pass so the DSL can re-read the file.
794    ScriptSource,
795}
796
797/// Kind of a watched dev source.
798///
799/// Templates are reloaded per route (`ReloadTemplates`); scripts feed the
800/// script watch registry and trigger a full route reload pass so discovery
801/// re-reads the file.
802#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
803pub enum DevSourceKind {
804    /// Template/proto/include asset owned by a template reload target.
805    Template,
806    /// Script file read by a route's `script:` step (and friends).
807    Script,
808}
809
810/// Path → route-id edges for one snapshot of committed dev-target sources,
811/// split by [`DevSourceKind`].
812///
813/// Paths are normalized on insert and lookup (see [`normalize_path`]) so a
814/// relative source and an absolute event path for the same file compare equal.
815/// Template accessors (`contains_path`, `routes_for`, `has_targets_for`) only
816/// see template entries; `script_routes_for` only sees script entries.
817#[cfg_attr(not(test), allow(dead_code))]
818#[derive(Debug, Default, Clone)]
819pub(crate) struct DevTargetMap {
820    template_path_to_routes: HashMap<PathBuf, HashSet<String>>,
821    script_path_to_routes: HashMap<PathBuf, HashSet<String>>,
822}
823
824#[cfg_attr(not(test), allow(dead_code))]
825impl DevTargetMap {
826    /// Build the map from `(route_id, (path, kind))` pairs.
827    pub(crate) fn from_sources(sources: &[(String, Vec<(PathBuf, DevSourceKind)>)]) -> Self {
828        let mut map = Self::default();
829        for (route_id, paths) in sources {
830            for (path, kind) in paths {
831                let by_path = match kind {
832                    DevSourceKind::Template => &mut map.template_path_to_routes,
833                    DevSourceKind::Script => &mut map.script_path_to_routes,
834                };
835                by_path
836                    .entry(normalize_path(path))
837                    .or_default()
838                    .insert(route_id.clone());
839            }
840        }
841        map
842    }
843
844    /// Returns `true` when `path` is a tracked template source.
845    pub(crate) fn contains_path(&self, path: &Path) -> bool {
846        self.template_path_to_routes
847            .contains_key(&normalize_path(path))
848    }
849
850    /// Route ids that declare `path` as a template source; empty when the path
851    /// is not tracked.
852    pub(crate) fn routes_for(&self, path: &Path) -> HashSet<String> {
853        self.template_path_to_routes
854            .get(&normalize_path(path))
855            .cloned()
856            .unwrap_or_default()
857    }
858
859    /// Returns `true` when `path` is a tracked script source.
860    pub(crate) fn contains_script_path(&self, path: &Path) -> bool {
861        self.script_path_to_routes
862            .contains_key(&normalize_path(path))
863    }
864
865    /// Route ids that declare `path` as a script source; empty when the path is
866    /// not tracked.
867    pub(crate) fn script_routes_for(&self, path: &Path) -> HashSet<String> {
868        self.script_path_to_routes
869            .get(&normalize_path(path))
870            .cloned()
871            .unwrap_or_default()
872    }
873
874    /// Returns `true` when `route_id` still declares at least one tracked
875    /// template source.
876    pub(crate) fn has_targets_for(&self, route_id: &str) -> bool {
877        self.template_path_to_routes
878            .values()
879            .any(|routes| routes.contains(route_id))
880    }
881
882    /// Unique parent directories of every tracked source, template or script.
883    ///
884    /// Directories already subscribed as route roots are NOT removed here;
885    /// that subtraction belongs to the watcher wrapper.
886    pub(crate) fn parent_dirs(&self) -> Vec<PathBuf> {
887        self.template_path_to_routes
888            .keys()
889            .chain(self.script_path_to_routes.keys())
890            .filter_map(|path| path.parent().map(Path::to_path_buf))
891            .collect::<HashSet<_>>()
892            .into_iter()
893            .collect()
894    }
895
896    /// Returns `true` when no sources of either kind are tracked.
897    pub(crate) fn is_empty(&self) -> bool {
898        self.template_path_to_routes.is_empty() && self.script_path_to_routes.is_empty()
899    }
900}
901
902/// Normalize a path to an absolute, canonical path when possible.
903///
904/// Relative paths are first joined onto the current directory. Existing
905/// paths are canonicalized so watcher events and registered sources compare
906/// equal across symlinked roots (notably macOS `/var` vs `/private/var`,
907/// where `tempfile` and notify disagree). For paths that no longer exist,
908/// including notify `Remove` events, canonicalization fails; in that case
909/// `.`/`..` are resolved textually as a deterministic fallback. Task 2.2
910/// must pass `watch_dirs` through the same normalization (here) rather than
911/// mixing raw and canonical roots.
912#[cfg_attr(not(test), allow(dead_code))] // consumed by the extracted loop (Task 2.2)
913fn normalize_path(path: &Path) -> PathBuf {
914    let absolute = if path.is_absolute() {
915        path.to_path_buf()
916    } else {
917        match std::env::current_dir() {
918            Ok(cwd) => cwd.join(path),
919            Err(_) => path.to_path_buf(),
920        }
921    };
922
923    if let Ok(canonical) = std::fs::canonicalize(&absolute) {
924        return canonical;
925    }
926
927    let mut normalized = PathBuf::new();
928    for component in absolute.components() {
929        match component {
930            Component::CurDir => {}
931            Component::ParentDir => {
932                normalized.pop();
933            }
934            other => normalized.push(other.as_os_str()),
935        }
936    }
937    normalized
938}
939
940/// Returns `true` for create/modify/remove event kinds.
941fn is_reload_kind(event: &Event) -> bool {
942    matches!(
943        event.kind,
944        EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_)
945    )
946}
947
948/// Returns `true` when `path` is a YAML/JSON file under one of `route_roots`.
949fn is_route_file_path(path: &Path, route_roots: &[PathBuf]) -> bool {
950    let is_route_extension = path
951        .extension()
952        .and_then(|ext| ext.to_str())
953        .map(|ext| matches!(ext, "yaml" | "yml" | "json"))
954        .unwrap_or(false);
955    if !is_route_extension {
956        return false;
957    }
958
959    let normalized = normalize_path(path);
960    route_roots
961        .iter()
962        .any(|root| normalized.starts_with(normalize_path(root)))
963}
964
965/// Classify a notify event against the dev-target map and route roots.
966///
967/// Dev-target paths take precedence over the route-file extension check, so a
968/// tracked `.yaml` template source is treated as a dev target. A tracked
969/// script source yields [`EventClass::ScriptSource`]; scripts are checked after
970/// templates because a path cannot be both kinds of target for the same route,
971/// and before the route-file extension check because a script source may itself
972/// be a `.yaml`/`.yml`/`.json` file under a route root.
973/// Events in asset-only directories (outside every route root) return `None`
974/// and must be ignored.
975#[cfg_attr(not(test), allow(dead_code))]
976fn classify_event(
977    event: &Event,
978    dev_map: &DevTargetMap,
979    route_roots: &[PathBuf],
980) -> Option<EventClass> {
981    if !is_reload_kind(event) {
982        return None;
983    }
984
985    if event.paths.iter().any(|path| dev_map.contains_path(path)) {
986        return Some(EventClass::DevTarget);
987    }
988
989    if event
990        .paths
991        .iter()
992        .any(|path| dev_map.contains_script_path(path))
993    {
994        return Some(EventClass::ScriptSource);
995    }
996
997    if event
998        .paths
999        .iter()
1000        .any(|path| is_route_file_path(path, route_roots))
1001    {
1002        return Some(EventClass::RouteFile);
1003    }
1004
1005    None
1006}
1007
1008/// Extract unique existing parent directories from glob patterns.
1009///
1010/// Given patterns like `"routes/*.yaml"` or `"/abs/**/*.yaml"`, walks up
1011/// from each path until the first non-glob segment and collects the
1012/// resulting existing directories.
1013pub fn resolve_watch_dirs(patterns: &[String]) -> Vec<PathBuf> {
1014    let mut dirs: HashSet<PathBuf> = HashSet::new();
1015
1016    for pattern in patterns {
1017        let path = Path::new(pattern.as_str());
1018
1019        let dir = if path.is_dir() {
1020            path.to_path_buf()
1021        } else {
1022            // Walk toward root until no glob characters remain.
1023            let mut candidate = path;
1024            loop {
1025                let s = candidate.to_string_lossy();
1026                if s.contains('*') || s.contains('?') || s.contains('[') {
1027                    match candidate.parent() {
1028                        Some(p) => candidate = p,
1029                        None => break,
1030                    }
1031                } else {
1032                    break;
1033                }
1034            }
1035            candidate.to_path_buf()
1036        };
1037
1038        if dir.as_os_str().is_empty() {
1039            // Relative pattern with no parent — watch current dir
1040            dirs.insert(PathBuf::from("."));
1041        } else if dir.exists() {
1042            dirs.insert(dir);
1043        }
1044    }
1045
1046    dirs.into_iter().collect()
1047}
1048
1049#[cfg(test)]
1050mod tests {
1051    use std::any::Any;
1052    use std::fs;
1053    use std::path::PathBuf;
1054    use std::sync::atomic::{AtomicBool, AtomicU64, AtomicUsize, Ordering};
1055    use std::sync::{Arc, Mutex};
1056    use std::time::{Duration, SystemTime, UNIX_EPOCH};
1057
1058    use async_trait::async_trait;
1059    use camel_component_api::template_reload::{
1060        TemplateReloadRegistry, TemplateReloadStaged, TemplateReloadTarget,
1061    };
1062    use futures::future::BoxFuture;
1063    use notify::{Event, EventKind};
1064    use tokio::sync::{mpsc, watch};
1065    use tokio_util::sync::CancellationToken;
1066
1067    use crate::CamelContext;
1068    use crate::context::RuntimeExecutionHandle;
1069    use crate::hot_reload::application::execute_reload_actions;
1070    use crate::hot_reload::domain::ReloadAction;
1071    use crate::lifecycle::application::route_definition::RouteDefinition;
1072    use camel_api::CamelError;
1073
1074    use super::{
1075        DevSourceKind, DevTargetMap, EventClass, PassOutcome, ReloadWatcher, bounded_dispatch,
1076        classify_event, derive_rebuilt_route_ids, derive_removed_route_ids, is_reload_kind,
1077        is_route_file_path, normalize_path, publish_parents, reload_dispatch_bound,
1078        resolve_watch_dirs, run_reload_loop, watch_and_reload, watch_and_reload_with_barriers,
1079    };
1080
1081    type ReloadPass =
1082        Box<dyn Fn() -> BoxFuture<'static, Result<PassOutcome, CamelError>> + Send + Sync>;
1083    type DispatchReload =
1084        Box<dyn Fn(&str) -> BoxFuture<'static, Result<(), CamelError>> + Send + Sync>;
1085
1086    /// Concrete staged marker for the test target.
1087    struct FakeStaged;
1088
1089    impl TemplateReloadStaged for FakeStaged {
1090        fn into_any(self: Box<Self>) -> Box<dyn Any> {
1091            self
1092        }
1093    }
1094
1095    /// Test reload target with a committed source list that may grow on commit.
1096    ///
1097    /// `watch_sources` reports only the committed list. A commit installs the
1098    /// pending list, mirroring real targets that re-resolve their dependency
1099    /// closure and report the new one afterwards.
1100    struct FakeReloadTarget {
1101        route: String,
1102        sources: Mutex<Vec<PathBuf>>,
1103        pending: Mutex<Vec<PathBuf>>,
1104        generation: AtomicU64,
1105        commits: Arc<AtomicUsize>,
1106    }
1107
1108    impl FakeReloadTarget {
1109        fn new(route: &str, sources: Vec<PathBuf>) -> Arc<Self> {
1110            Arc::new(Self {
1111                route: route.to_string(),
1112                sources: Mutex::new(sources.clone()),
1113                pending: Mutex::new(sources),
1114                generation: AtomicU64::new(0),
1115                commits: Arc::new(AtomicUsize::new(0)),
1116            })
1117        }
1118
1119        fn as_dyn(self: &Arc<Self>) -> Arc<dyn TemplateReloadTarget> {
1120            let concrete: Arc<Self> = Arc::clone(self);
1121            concrete
1122        }
1123
1124        /// Install the pending list without a commit (simulates a route pass
1125        /// re-deriving from a freshly committed closure).
1126        fn install_pending(&self) {
1127            let pending = self.pending.lock().expect("pending poisoned").clone();
1128            *self.sources.lock().expect("sources poisoned") = pending;
1129            self.generation.fetch_add(1, Ordering::SeqCst);
1130        }
1131
1132        fn set_pending(&self, sources: Vec<PathBuf>) {
1133            *self.pending.lock().expect("pending poisoned") = sources;
1134        }
1135    }
1136
1137    #[async_trait]
1138    impl TemplateReloadTarget for FakeReloadTarget {
1139        fn route_id(&self) -> &str {
1140            &self.route
1141        }
1142        fn reload_timeout(&self) -> Duration {
1143            Duration::from_secs(5)
1144        }
1145        fn current_generation(&self) -> u64 {
1146            self.generation.load(Ordering::SeqCst)
1147        }
1148        async fn build(&self) -> Result<(Box<dyn TemplateReloadStaged>, u64), CamelError> {
1149            Ok((Box::new(FakeStaged), self.generation.load(Ordering::SeqCst)))
1150        }
1151        fn commit(&self, _staged: Box<dyn TemplateReloadStaged>) {
1152            let pending = self.pending.lock().expect("pending poisoned").clone();
1153            *self.sources.lock().expect("sources poisoned") = pending;
1154            self.generation.fetch_add(1, Ordering::SeqCst);
1155            self.commits.fetch_add(1, Ordering::SeqCst);
1156        }
1157        fn watch_sources(&self) -> Vec<PathBuf> {
1158            self.sources.lock().expect("sources poisoned").clone()
1159        }
1160    }
1161
1162    /// Yield-spin until `cond` holds or `bound` elapses. No sleeps (lint).
1163    async fn wait_for_condition<F>(mut cond: F, bound: Duration)
1164    where
1165        F: FnMut() -> bool,
1166    {
1167        let start = std::time::Instant::now();
1168        loop {
1169            if cond() {
1170                return;
1171            }
1172            assert!(
1173                std::time::Instant::now() < start + bound,
1174                "condition not met within {bound:?}"
1175            );
1176            let _ = tokio::time::timeout(Duration::from_millis(1), tokio::task::yield_now()).await;
1177        }
1178    }
1179
1180    async fn await_ready(mut ready_rx: watch::Receiver<bool>) {
1181        let ready = tokio::time::timeout(Duration::from_secs(2), ready_rx.wait_for(|v| *v))
1182            .await
1183            .expect("watcher-ready barrier did not fire");
1184        assert!(ready.is_ok(), "watcher-ready sender dropped");
1185    }
1186
1187    async fn await_version_after(version_rx: &mut watch::Receiver<u64>, base: u64) {
1188        let bumped = tokio::time::timeout(
1189            Duration::from_secs(2),
1190            version_rx.wait_for(|version| *version > base),
1191        )
1192        .await
1193        .expect("reconciliation version bump did not arrive");
1194        assert!(bumped.is_ok(), "reconciliation sender dropped");
1195    }
1196
1197    #[allow(clippy::type_complexity)]
1198    fn spawn_watcher<F>(
1199        controller: RuntimeExecutionHandle,
1200        watch_dirs: Vec<PathBuf>,
1201        route_id: String,
1202        discover_fn: F,
1203    ) -> (
1204        CancellationToken,
1205        watch::Receiver<bool>,
1206        watch::Receiver<u64>,
1207        tokio::task::JoinHandle<Result<(), CamelError>>,
1208    )
1209    where
1210        F: Fn() -> Result<Vec<RouteDefinition>, CamelError> + Send + Sync + 'static,
1211    {
1212        let (ready_tx, ready_rx) = watch::channel(false);
1213        let (version_tx, version_rx) = watch::channel(0u64);
1214        let shutdown = CancellationToken::new();
1215        let provider = move || {
1216            template_kind_sources(
1217                TemplateReloadRegistry::global()
1218                    .route_watch_sources()
1219                    .into_iter()
1220                    .filter(|(route, _)| route.as_str() == route_id.as_str())
1221                    .collect::<Vec<(String, Vec<PathBuf>)>>(),
1222            )
1223        };
1224        let handle = tokio::spawn(watch_and_reload_with_barriers(
1225            watch_dirs,
1226            controller,
1227            discover_fn,
1228            provider,
1229            noop_publish,
1230            Some(shutdown.clone()),
1231            Duration::from_millis(50),
1232            Duration::from_millis(20),
1233            ready_tx,
1234            version_tx,
1235        ));
1236        (shutdown, ready_rx, version_rx, handle)
1237    }
1238
1239    async fn stop_watcher(
1240        shutdown: CancellationToken,
1241        handle: tokio::task::JoinHandle<Result<(), CamelError>>,
1242    ) {
1243        shutdown.cancel();
1244        let result = tokio::time::timeout(Duration::from_secs(2), handle)
1245            .await
1246            .expect("watcher did not stop")
1247            .expect("watcher task panicked");
1248        assert!(result.is_ok(), "watcher returned an error: {result:?}");
1249    }
1250
1251    fn fresh_registry() -> &'static TemplateReloadRegistry {
1252        Box::leak(Box::new(TemplateReloadRegistry::default()))
1253    }
1254
1255    /// Sets a flag when dropped, proving a parked dispatch future was dropped.
1256    struct DropFlag(Arc<AtomicBool>);
1257
1258    impl Drop for DropFlag {
1259        fn drop(&mut self) {
1260            self.0.store(true, Ordering::SeqCst);
1261        }
1262    }
1263
1264    fn modify_event(path: &str) -> Event {
1265        make_event(&[path], modify_content())
1266    }
1267
1268    /// Let the spawned-side loop future run to its next await point under a
1269    /// paused clock. `yield_now` is a finite scheduler yield, not a sleep.
1270    async fn settle() {
1271        for _ in 0..8 {
1272            tokio::task::yield_now().await;
1273        }
1274    }
1275
1276    fn reload_pass_counter(calls: Arc<AtomicUsize>, rebuilt: Vec<String>) -> ReloadPass {
1277        Box::new(move || {
1278            let calls = Arc::clone(&calls);
1279            let rebuilt = rebuilt.clone();
1280            Box::pin(async move {
1281                calls.fetch_add(1, Ordering::SeqCst);
1282                Ok(PassOutcome {
1283                    rebuilt,
1284                    removed: Vec::new(),
1285                    aborted: false,
1286                })
1287            })
1288        })
1289    }
1290
1291    /// Publish hook that ignores every outcome. Integration scenarios that do
1292    /// not exercise script sources pass this.
1293    fn noop_publish(_rebuilt: &[String], _removed: &[String]) {}
1294
1295    /// Recorded `(rebuilt, removed)` pairs from a publish hook.
1296    type PublishLog = Arc<Mutex<Vec<(Vec<String>, Vec<String>)>>>;
1297    /// Publish hook accepting one pass outcome.
1298    type PublishHook = Box<dyn Fn(&[String], &[String]) + Send + Sync>;
1299
1300    /// Publish hook that records every `(rebuilt, removed)` pair it receives.
1301    fn publish_logger(calls: PublishLog) -> PublishHook {
1302        Box::new(move |rebuilt: &[String], removed: &[String]| {
1303            calls
1304                .lock()
1305                .expect("publish log poisoned")
1306                .push((rebuilt.to_vec(), removed.to_vec()));
1307        })
1308    }
1309
1310    /// Dispatch bound the loop tests exercise: the production bound helper
1311    /// applied to the injected route id (registry deadline plus drain), so the
1312    /// loggers below run through `bounded_dispatch` under the same bound the
1313    /// watcher uses instead of an unbounded test-local future.
1314    fn test_dispatch_bound(route_id: &str) -> Duration {
1315        reload_dispatch_bound(route_id, Duration::ZERO)
1316    }
1317
1318    fn dispatch_logger(
1319        calls: Arc<Mutex<Vec<String>>>,
1320        shutdown: CancellationToken,
1321    ) -> DispatchReload {
1322        Box::new(move |route_id: &str| {
1323            let calls = Arc::clone(&calls);
1324            let route_id = route_id.to_string();
1325            let shutdown = shutdown.clone();
1326            Box::pin(async move {
1327                let bound = test_dispatch_bound(&route_id);
1328                bounded_dispatch(
1329                    async move {
1330                        calls.lock().expect("dispatch log poisoned").push(route_id);
1331                        Ok(())
1332                    },
1333                    bound,
1334                    Some(&shutdown),
1335                )
1336                .await
1337            })
1338        })
1339    }
1340
1341    fn make_event(paths: &[&str], kind: EventKind) -> Event {
1342        Event {
1343            kind,
1344            paths: paths.iter().map(PathBuf::from).collect(),
1345            attrs: Default::default(),
1346        }
1347    }
1348
1349    #[cfg(unix)]
1350    #[test]
1351    fn normalize_path_resolves_symlinked_existing_paths() {
1352        use std::os::unix::fs::symlink;
1353
1354        let tmp = tempfile::tempdir().expect("temp dir");
1355        let real = tmp.path().join("real");
1356        let link = tmp.path().join("link");
1357        fs::create_dir(&real).expect("create real dir");
1358        symlink(&real, &link).expect("create symlink");
1359
1360        assert_eq!(normalize_path(&link), normalize_path(&real));
1361    }
1362
1363    #[test]
1364    fn resolve_watch_dirs_returns_existing_dir_pattern_and_ignores_missing() {
1365        let root = std::env::temp_dir().join(format!(
1366            "camel-reload-watch-{}",
1367            SystemTime::now()
1368                .duration_since(UNIX_EPOCH)
1369                .expect("system clock before unix epoch")
1370                .as_nanos()
1371        ));
1372        let existing = root.join("routes");
1373        fs::create_dir_all(&existing).expect("create temp dir");
1374
1375        let patterns = vec![
1376            existing.to_string_lossy().to_string(),
1377            root.join("missing").to_string_lossy().to_string(),
1378        ];
1379
1380        let dirs = resolve_watch_dirs(&patterns);
1381
1382        assert!(dirs.contains(&existing));
1383        assert_eq!(dirs.len(), 1);
1384
1385        fs::remove_dir_all(&root).expect("cleanup temp dir");
1386    }
1387
1388    #[test]
1389    fn resolve_watch_dirs_walks_up_glob_segments() {
1390        let root = std::env::temp_dir().join(format!(
1391            "camel-reload-watch-glob-{}",
1392            SystemTime::now()
1393                .duration_since(UNIX_EPOCH)
1394                .expect("system clock before unix epoch")
1395                .as_nanos()
1396        ));
1397        let nested = root.join("a").join("b");
1398        fs::create_dir_all(&nested).expect("create nested temp dir");
1399
1400        let pattern = nested
1401            .join("**")
1402            .join("*.yaml")
1403            .to_string_lossy()
1404            .to_string();
1405
1406        let dirs = resolve_watch_dirs(&[pattern]);
1407
1408        assert!(dirs.contains(&nested));
1409
1410        fs::remove_dir_all(&root).expect("cleanup temp dir");
1411    }
1412
1413    #[test]
1414    fn resolve_watch_dirs_uses_current_dir_for_relative_no_parent_pattern() {
1415        let dirs = resolve_watch_dirs(&["*.yaml".to_string()]);
1416        assert_eq!(dirs, vec![PathBuf::from(".")]);
1417    }
1418
1419    #[tokio::test]
1420    async fn watch_and_reload_returns_immediately_when_shutdown_is_cancelled() {
1421        let token = CancellationToken::new();
1422        token.cancel();
1423
1424        let ctx = CamelContext::builder().build().await.unwrap();
1425        let result = watch_and_reload(
1426            vec![],
1427            ctx.runtime_execution_handle(),
1428            || Ok(vec![]),
1429            Vec::<(String, Vec<(PathBuf, DevSourceKind)>)>::new,
1430            noop_publish,
1431            Some(token),
1432            Duration::from_millis(1),
1433            Duration::from_millis(1),
1434        )
1435        .await;
1436
1437        assert!(result.is_ok());
1438    }
1439
1440    #[test]
1441    fn is_route_file_path_rejects_non_reload_extension() {
1442        let roots = vec![PathBuf::from("routes")];
1443        let ev = make_event(
1444            &["routes/test.toml"],
1445            EventKind::Create(notify::event::CreateKind::File),
1446        );
1447        assert!(!is_route_file_path(&ev.paths[0], &roots));
1448    }
1449
1450    #[test]
1451    fn is_route_file_path_rejects_editor_swap_file() {
1452        let roots = vec![PathBuf::from("routes")];
1453        let ev = make_event(
1454            &["routes/route.yaml.swp"],
1455            EventKind::Create(notify::event::CreateKind::File),
1456        );
1457        assert!(!is_route_file_path(&ev.paths[0], &roots));
1458    }
1459
1460    #[test]
1461    fn is_route_file_path_rejects_path_without_extension() {
1462        let roots = vec![PathBuf::from("routes")];
1463        let ev = make_event(
1464            &["routes/Makefile"],
1465            EventKind::Create(notify::event::CreateKind::File),
1466        );
1467        assert!(!is_route_file_path(&ev.paths[0], &roots));
1468    }
1469
1470    #[test]
1471    fn is_route_file_path_accepts_yml_and_json_under_route_root() {
1472        let roots = vec![PathBuf::from("routes")];
1473        for path in ["routes/route.yml", "routes/route.json"] {
1474            let ev = make_event(&[path], EventKind::Create(notify::event::CreateKind::File));
1475            assert!(
1476                is_route_file_path(&ev.paths[0], &roots),
1477                "{path} should be a route file"
1478            );
1479        }
1480    }
1481
1482    #[test]
1483    fn resolve_watch_dirs_deduplicates_same_directory() {
1484        let root = std::env::temp_dir().join(format!(
1485            "camel-reload-watch-dedup-{}",
1486            SystemTime::now()
1487                .duration_since(UNIX_EPOCH)
1488                .expect("system clock before unix epoch")
1489                .as_nanos()
1490        ));
1491        fs::create_dir_all(&root).expect("create temp dir");
1492
1493        let patterns = vec![
1494            root.join("*.yaml").to_string_lossy().to_string(),
1495            root.join("*.yml").to_string_lossy().to_string(),
1496        ];
1497
1498        let dirs = resolve_watch_dirs(&patterns);
1499        assert_eq!(dirs.len(), 1);
1500        assert!(dirs.contains(&root));
1501
1502        fs::remove_dir_all(&root).expect("cleanup temp dir");
1503    }
1504
1505    #[test]
1506    fn resolve_watch_dirs_handles_absolute_glob_pattern() {
1507        let root = std::env::temp_dir().join(format!(
1508            "camel-reload-watch-abs-{}",
1509            SystemTime::now()
1510                .duration_since(UNIX_EPOCH)
1511                .expect("system clock before unix epoch")
1512                .as_nanos()
1513        ));
1514        let nested = root.join("routes").join("sub");
1515        fs::create_dir_all(&nested).expect("create nested temp dir");
1516
1517        let pattern = root
1518            .join("routes")
1519            .join("**")
1520            .join("*.yaml")
1521            .to_string_lossy()
1522            .to_string();
1523
1524        let dirs = resolve_watch_dirs(&[pattern]);
1525        assert!(dirs.iter().any(|d| d.starts_with(root.join("routes"))));
1526
1527        fs::remove_dir_all(&root).expect("cleanup temp dir");
1528    }
1529
1530    #[test]
1531    fn resolve_watch_dirs_empty_patterns_returns_empty() {
1532        let dirs = resolve_watch_dirs(&[]);
1533        assert!(dirs.is_empty());
1534    }
1535
1536    #[test]
1537    fn resolve_watch_dirs_ignores_nonexistent_parent_of_glob() {
1538        let dirs = resolve_watch_dirs(&["/nonexistent/path/**/*.yaml".to_string()]);
1539        assert!(dirs.is_empty());
1540    }
1541
1542    #[test]
1543    fn reload_watcher_struct_is_unit() {
1544        let _ = ReloadWatcher;
1545    }
1546
1547    fn make_dev_map(sources: &[(&str, &[&str])]) -> DevTargetMap {
1548        let owned: Vec<(String, Vec<(PathBuf, DevSourceKind)>)> = sources
1549            .iter()
1550            .map(|(route, paths)| {
1551                (
1552                    (*route).to_string(),
1553                    paths
1554                        .iter()
1555                        .map(|path| (PathBuf::from(path), DevSourceKind::Template))
1556                        .collect(),
1557                )
1558            })
1559            .collect();
1560        DevTargetMap::from_sources(&owned)
1561    }
1562
1563    /// Build a dev map from `(route, path, kind)` triples.
1564    fn make_kinded_dev_map(sources: &[(&str, &str, DevSourceKind)]) -> DevTargetMap {
1565        let owned: Vec<(String, Vec<(PathBuf, DevSourceKind)>)> = sources
1566            .iter()
1567            .map(|(route, path, kind)| ((*route).to_string(), vec![(PathBuf::from(path), *kind)]))
1568            .collect();
1569        DevTargetMap::from_sources(&owned)
1570    }
1571
1572    /// Wrap a plain template watch snapshot as kind-tagged sources.
1573    fn template_kind_sources(
1574        sources: Vec<(String, Vec<PathBuf>)>,
1575    ) -> Vec<(String, Vec<(PathBuf, DevSourceKind)>)> {
1576        sources
1577            .into_iter()
1578            .map(|(route, paths)| {
1579                (
1580                    route,
1581                    paths
1582                        .into_iter()
1583                        .map(|path| (path, DevSourceKind::Template))
1584                        .collect(),
1585                )
1586            })
1587            .collect()
1588    }
1589
1590    fn modify_content() -> EventKind {
1591        EventKind::Modify(notify::event::ModifyKind::Data(
1592            notify::event::DataChange::Content,
1593        ))
1594    }
1595
1596    #[test]
1597    fn is_reload_kind_accepts_mutations_and_rejects_access() {
1598        assert!(is_reload_kind(&make_event(
1599            &["routes/route.yaml"],
1600            EventKind::Remove(notify::event::RemoveKind::File),
1601        )));
1602        assert!(is_reload_kind(&make_event(
1603            &["routes/route.yaml"],
1604            modify_content(),
1605        )));
1606        assert!(is_reload_kind(&make_event(
1607            &["routes/route.yaml"],
1608            EventKind::Create(notify::event::CreateKind::File),
1609        )));
1610        assert!(!is_reload_kind(&make_event(
1611            &["routes/route.yaml"],
1612            EventKind::Access(notify::event::AccessKind::Read),
1613        )));
1614    }
1615
1616    #[test]
1617    fn classify_dev_target_path_takes_precedence_over_extension() {
1618        let dev_map = make_dev_map(&[("t1", &["routes/defs.yaml"])]);
1619        let ev = make_event(&["routes/defs.yaml"], modify_content());
1620        let roots = vec![PathBuf::from("routes")];
1621
1622        assert_eq!(
1623            classify_event(&ev, &dev_map, &roots),
1624            Some(EventClass::DevTarget)
1625        );
1626    }
1627
1628    #[test]
1629    fn classify_route_file_when_not_tracked() {
1630        let dev_map = DevTargetMap::default();
1631        let ev = make_event(
1632            &["routes/other.yaml"],
1633            EventKind::Create(notify::event::CreateKind::File),
1634        );
1635        let roots = vec![PathBuf::from("routes")];
1636
1637        assert_eq!(
1638            classify_event(&ev, &dev_map, &roots),
1639            Some(EventClass::RouteFile)
1640        );
1641    }
1642
1643    #[test]
1644    fn unrelated_yaml_outside_route_roots_is_ignored() {
1645        let dev_map = DevTargetMap::default();
1646        let ev = make_event(
1647            &["assets/data.yaml"],
1648            EventKind::Create(notify::event::CreateKind::File),
1649        );
1650        let roots = vec![PathBuf::from("routes")];
1651
1652        let class = classify_event(&ev, &dev_map, &roots);
1653        assert_ne!(class, Some(EventClass::RouteFile));
1654        assert_ne!(class, Some(EventClass::DevTarget));
1655        assert_eq!(class, None);
1656    }
1657
1658    #[test]
1659    fn dev_map_limited_to_declared_sources() {
1660        let a = PathBuf::from("/work/site/a.jinja");
1661        let b = PathBuf::from("/work/site/b.jinja");
1662        let c = PathBuf::from("/work/site/part/c.jinja");
1663        let schema = PathBuf::from("/work/proto/schema.proto");
1664        let import = PathBuf::from("/work/proto/import.proto");
1665        let undeclared = PathBuf::from("/work/proto/never_declared.proto");
1666
1667        let sources = vec![
1668            (
1669                "t1".to_string(),
1670                vec![
1671                    (a.clone(), DevSourceKind::Template),
1672                    (b.clone(), DevSourceKind::Template),
1673                    (c.clone(), DevSourceKind::Template),
1674                ],
1675            ),
1676            (
1677                "v1".to_string(),
1678                vec![
1679                    (schema.clone(), DevSourceKind::Template),
1680                    (import.clone(), DevSourceKind::Template),
1681                ],
1682            ),
1683        ];
1684        let map = DevTargetMap::from_sources(&sources);
1685
1686        assert!(DevTargetMap::default().is_empty());
1687        assert!(!map.is_empty());
1688        for path in [&a, &b, &c, &schema, &import] {
1689            assert!(map.contains_path(path), "expected tracked path {path:?}");
1690        }
1691        assert!(!map.contains_path(&undeclared));
1692
1693        let routes = map.routes_for(&schema);
1694        assert_eq!(routes.len(), 1);
1695        assert!(routes.contains("v1"));
1696    }
1697
1698    #[test]
1699    fn dev_map_parent_dirs_unique() {
1700        let sources = vec![
1701            (
1702                "t1".to_string(),
1703                vec![
1704                    (
1705                        PathBuf::from("/work/site/page.jinja"),
1706                        DevSourceKind::Template,
1707                    ),
1708                    (
1709                        PathBuf::from("/work/site/other.jinja"),
1710                        DevSourceKind::Template,
1711                    ),
1712                ],
1713            ),
1714            (
1715                "v1".to_string(),
1716                vec![(
1717                    PathBuf::from("/work/proto/schema.proto"),
1718                    DevSourceKind::Template,
1719                )],
1720            ),
1721        ];
1722
1723        let dirs = DevTargetMap::from_sources(&sources).parent_dirs();
1724
1725        assert_eq!(dirs.len(), 2, "expected unique parent dirs, got {dirs:?}");
1726        assert!(dirs.contains(&PathBuf::from("/work/site")));
1727        assert!(dirs.contains(&PathBuf::from("/work/proto")));
1728    }
1729
1730    // ── run_reload_loop (synthetic event source) ────────────────────────────
1731
1732    #[tokio::test(start_paused = true)]
1733    async fn dev_target_event_dispatches_per_route() {
1734        let ctx = CamelContext::builder()
1735            .build()
1736            .await
1737            .expect("context build");
1738
1739        let debounce = Duration::from_millis(50);
1740        let dev_map = make_dev_map(&[("t1", &["templates/page.jinja"])]);
1741        let provider = move || dev_map.clone();
1742        let reload_calls = Arc::new(AtomicUsize::new(0));
1743        let reload_pass = reload_pass_counter(Arc::clone(&reload_calls), Vec::new());
1744        let dispatched = Arc::new(Mutex::new(Vec::new()));
1745        let token = CancellationToken::new();
1746        let dispatch = dispatch_logger(Arc::clone(&dispatched), token.clone());
1747
1748        let (tx, rx) = mpsc::channel(64);
1749        let (parents_tx, _parents_rx) = watch::channel(Vec::new());
1750        let loop_fut = run_reload_loop(
1751            rx,
1752            vec![PathBuf::from("routes")],
1753            ctx.runtime_execution_handle(),
1754            &provider,
1755            &reload_pass,
1756            &noop_publish,
1757            &dispatch,
1758            parents_tx,
1759            Some(token.clone()),
1760            debounce,
1761        );
1762
1763        let driver = async {
1764            tx.send(Ok(modify_event("templates/page.jinja")))
1765                .await
1766                .expect("send event");
1767            settle().await;
1768            tokio::time::advance(debounce).await;
1769            settle().await;
1770            token.cancel();
1771        };
1772
1773        let (loop_result, ()) = futures::future::join(loop_fut, driver).await;
1774        assert!(loop_result.is_ok());
1775        assert_eq!(
1776            reload_calls.load(Ordering::SeqCst),
1777            0,
1778            "dev-target batch must not run the route pass"
1779        );
1780        assert_eq!(
1781            *dispatched.lock().expect("dispatch log poisoned"),
1782            vec!["t1".to_string()]
1783        );
1784    }
1785
1786    #[tokio::test(start_paused = true)]
1787    async fn debounce_coalesces_rapid_edits() {
1788        let ctx = CamelContext::builder()
1789            .build()
1790            .await
1791            .expect("context build");
1792
1793        let debounce = Duration::from_millis(50);
1794        let dev_map = make_dev_map(&[("t1", &["templates/page.jinja"])]);
1795        let provider = move || dev_map.clone();
1796        let reload_calls = Arc::new(AtomicUsize::new(0));
1797        let reload_pass = reload_pass_counter(Arc::clone(&reload_calls), Vec::new());
1798        let dispatched = Arc::new(Mutex::new(Vec::new()));
1799        let token = CancellationToken::new();
1800        let dispatch = dispatch_logger(Arc::clone(&dispatched), token.clone());
1801
1802        let (tx, rx) = mpsc::channel(64);
1803        let (parents_tx, _parents_rx) = watch::channel(Vec::new());
1804        let loop_fut = run_reload_loop(
1805            rx,
1806            vec![PathBuf::from("routes")],
1807            ctx.runtime_execution_handle(),
1808            &provider,
1809            &reload_pass,
1810            &noop_publish,
1811            &dispatch,
1812            parents_tx,
1813            Some(token.clone()),
1814            debounce,
1815        );
1816
1817        let driver = async {
1818            for _ in 0..3 {
1819                tx.send(Ok(modify_event("templates/page.jinja")))
1820                    .await
1821                    .expect("send event");
1822            }
1823            settle().await;
1824            tokio::time::advance(debounce).await;
1825            settle().await;
1826            token.cancel();
1827        };
1828
1829        let (loop_result, ()) = futures::future::join(loop_fut, driver).await;
1830        assert!(loop_result.is_ok());
1831        assert_eq!(
1832            *dispatched.lock().expect("dispatch log poisoned"),
1833            vec!["t1".to_string()],
1834            "rapid edits within one debounce window must yield one dispatch"
1835        );
1836    }
1837
1838    #[tokio::test(start_paused = true)]
1839    async fn route_without_targets_skipped_and_loop_continues() {
1840        let ctx = CamelContext::builder()
1841            .build()
1842            .await
1843            .expect("context build");
1844
1845        let debounce = Duration::from_millis(50);
1846        let dev_map = make_dev_map(&[("t1", &["templates/page.jinja"])]);
1847        let provider = move || dev_map.clone();
1848        let reload_calls = Arc::new(AtomicUsize::new(0));
1849        let reload_pass = reload_pass_counter(Arc::clone(&reload_calls), Vec::new());
1850        let dispatched = Arc::new(Mutex::new(Vec::new()));
1851        let token = CancellationToken::new();
1852        let dispatch = dispatch_logger(Arc::clone(&dispatched), token.clone());
1853
1854        let (tx, rx) = mpsc::channel(64);
1855        let (parents_tx, _parents_rx) = watch::channel(Vec::new());
1856        let loop_fut = run_reload_loop(
1857            rx,
1858            vec![PathBuf::from("routes")],
1859            ctx.runtime_execution_handle(),
1860            &provider,
1861            &reload_pass,
1862            &noop_publish,
1863            &dispatch,
1864            parents_tx,
1865            Some(token.clone()),
1866            debounce,
1867        );
1868
1869        let driver = async {
1870            // Untracked, non-route file: classified as neither, so it must be
1871            // ignored without starting a debounce window or dispatching.
1872            tx.send(Ok(modify_event("assets/unrelated.jinja")))
1873                .await
1874                .expect("send unrelated event");
1875            settle().await;
1876            tx.send(Ok(modify_event("templates/page.jinja")))
1877                .await
1878                .expect("send tracked event");
1879            settle().await;
1880            tokio::time::advance(debounce).await;
1881            settle().await;
1882            token.cancel();
1883        };
1884
1885        let (loop_result, ()) = futures::future::join(loop_fut, driver).await;
1886        assert!(loop_result.is_ok());
1887        assert_eq!(
1888            reload_calls.load(Ordering::SeqCst),
1889            0,
1890            "target-less events must not run the route pass"
1891        );
1892        assert_eq!(
1893            *dispatched.lock().expect("dispatch log poisoned"),
1894            vec!["t1".to_string()],
1895            "the loop must keep processing after an unmatched event"
1896        );
1897    }
1898
1899    #[tokio::test(start_paused = true)]
1900    async fn dispatch_timeout_drops_without_late_commit() {
1901        let ctx = CamelContext::builder()
1902            .build()
1903            .await
1904            .expect("context build");
1905
1906        let debounce = Duration::from_millis(50);
1907        let bound = Duration::from_millis(100);
1908        let dev_map = make_dev_map(&[("t1", &["templates/page.jinja"])]);
1909        let provider = move || dev_map.clone();
1910        let reload_pass = reload_pass_counter(Arc::new(AtomicUsize::new(0)), Vec::new());
1911
1912        let token = CancellationToken::new();
1913        let calls = Arc::new(AtomicUsize::new(0));
1914        let dropped = Arc::new(AtomicBool::new(false));
1915        let dispatch: DispatchReload = {
1916            let calls = Arc::clone(&calls);
1917            let dropped = Arc::clone(&dropped);
1918            let token = token.clone();
1919            Box::new(move |_route_id: &str| {
1920                let call_index = calls.fetch_add(1, Ordering::SeqCst);
1921                let dropped = Arc::clone(&dropped);
1922                let token = token.clone();
1923                Box::pin(async move {
1924                    if call_index == 0 {
1925                        let guard = DropFlag(dropped);
1926                        bounded_dispatch(
1927                            async move {
1928                                let _guard = guard;
1929                                futures::future::pending::<Result<(), CamelError>>().await
1930                            },
1931                            bound,
1932                            Some(&token),
1933                        )
1934                        .await
1935                    } else {
1936                        Ok(())
1937                    }
1938                }) as BoxFuture<'static, Result<(), CamelError>>
1939            })
1940        };
1941
1942        let (tx, rx) = mpsc::channel(64);
1943        let (parents_tx, _parents_rx) = watch::channel(Vec::new());
1944        let loop_fut = run_reload_loop(
1945            rx,
1946            vec![PathBuf::from("routes")],
1947            ctx.runtime_execution_handle(),
1948            &provider,
1949            &reload_pass,
1950            &noop_publish,
1951            &dispatch,
1952            parents_tx,
1953            Some(token.clone()),
1954            debounce,
1955        );
1956
1957        let driver = async {
1958            tx.send(Ok(modify_event("templates/page.jinja")))
1959                .await
1960                .expect("send first event");
1961            settle().await;
1962            tokio::time::advance(debounce).await;
1963            settle().await;
1964            // First dispatch is parked; advance past the production bound.
1965            tokio::time::advance(bound).await;
1966            settle().await;
1967            // The loop must still process a subsequent event.
1968            tx.send(Ok(modify_event("templates/page.jinja")))
1969                .await
1970                .expect("send second event");
1971            settle().await;
1972            tokio::time::advance(debounce).await;
1973            settle().await;
1974            token.cancel();
1975        };
1976
1977        let (loop_result, ()) = futures::future::join(loop_fut, driver).await;
1978        assert!(loop_result.is_ok());
1979        assert!(
1980            dropped.load(Ordering::SeqCst),
1981            "timed-out dispatch future must be dropped, not left to commit later"
1982        );
1983        assert_eq!(
1984            calls.load(Ordering::SeqCst),
1985            2,
1986            "the loop must continue after a dispatch timeout"
1987        );
1988    }
1989
1990    #[tokio::test(start_paused = true)]
1991    async fn shutdown_responsive_during_dispatch() {
1992        let ctx = CamelContext::builder()
1993            .build()
1994            .await
1995            .expect("context build");
1996
1997        let debounce = Duration::from_millis(50);
1998        let dev_map = make_dev_map(&[("t1", &["templates/page.jinja"])]);
1999        let provider = move || dev_map.clone();
2000        let reload_pass = reload_pass_counter(Arc::new(AtomicUsize::new(0)), Vec::new());
2001
2002        let token = CancellationToken::new();
2003        let calls = Arc::new(AtomicUsize::new(0));
2004        let dropped = Arc::new(AtomicBool::new(false));
2005        let dispatch: DispatchReload = {
2006            let calls = Arc::clone(&calls);
2007            let dropped = Arc::clone(&dropped);
2008            let token = token.clone();
2009            Box::new(move |_route_id: &str| {
2010                calls.fetch_add(1, Ordering::SeqCst);
2011                let guard = DropFlag(Arc::clone(&dropped));
2012                let token = token.clone();
2013                Box::pin(async move {
2014                    bounded_dispatch(
2015                        async move {
2016                            let _guard = guard;
2017                            futures::future::pending::<Result<(), CamelError>>().await
2018                        },
2019                        Duration::from_secs(60),
2020                        Some(&token),
2021                    )
2022                    .await
2023                }) as BoxFuture<'static, Result<(), CamelError>>
2024            })
2025        };
2026
2027        let (tx, rx) = mpsc::channel(64);
2028        let (parents_tx, _parents_rx) = watch::channel(Vec::new());
2029        let loop_fut = run_reload_loop(
2030            rx,
2031            vec![PathBuf::from("routes")],
2032            ctx.runtime_execution_handle(),
2033            &provider,
2034            &reload_pass,
2035            &noop_publish,
2036            &dispatch,
2037            parents_tx,
2038            Some(token.clone()),
2039            debounce,
2040        );
2041
2042        let driver = async {
2043            tx.send(Ok(modify_event("templates/page.jinja")))
2044                .await
2045                .expect("send event");
2046            settle().await;
2047            tokio::time::advance(debounce).await;
2048            settle().await;
2049            // Dispatch is parked on a 60 s bound; cancellation must win long
2050            // before that bound elapses in virtual time. Return the instant
2051            // the cancel fired so the assertion below can prove the loop
2052            // stopped via the cancellation path, not the timeout path.
2053            token.cancel();
2054            tokio::time::Instant::now()
2055        };
2056
2057        let (loop_result, cancelled_at) = futures::future::join(loop_fut, driver).await;
2058        let cancel_latency = tokio::time::Instant::now() - cancelled_at;
2059        assert!(loop_result.is_ok());
2060        assert_eq!(calls.load(Ordering::SeqCst), 1);
2061        assert!(
2062            dropped.load(Ordering::SeqCst),
2063            "cancellation must drop the in-flight dispatch future"
2064        );
2065        assert!(
2066            cancel_latency < Duration::from_secs(30),
2067            "loop must stop via cancellation, not the 60 s dispatch timeout (took {cancel_latency:?})"
2068        );
2069    }
2070
2071    /// Drive one debounced batch through the extracted loop and return the
2072    /// route ids it dispatched, in dispatch order.
2073    async fn drive_one_batch(
2074        dev_map: DevTargetMap,
2075        reload_pass: ReloadPass,
2076        events: Vec<Event>,
2077    ) -> Vec<String> {
2078        drive_one_batch_with_provider(move || dev_map.clone(), reload_pass, events).await
2079    }
2080
2081    async fn drive_one_batch_with_provider<P>(
2082        provider: P,
2083        reload_pass: ReloadPass,
2084        events: Vec<Event>,
2085    ) -> Vec<String>
2086    where
2087        P: Fn() -> DevTargetMap + Send + Sync + 'static,
2088    {
2089        drive_one_batch_with_hook(provider, reload_pass, &noop_publish, events).await
2090    }
2091
2092    async fn drive_one_batch_with_hook<P>(
2093        provider: P,
2094        reload_pass: ReloadPass,
2095        publish_script_sources: &(dyn Fn(&[String], &[String]) + Send + Sync),
2096        events: Vec<Event>,
2097    ) -> Vec<String>
2098    where
2099        P: Fn() -> DevTargetMap + Send + Sync + 'static,
2100    {
2101        let ctx = CamelContext::builder()
2102            .build()
2103            .await
2104            .expect("context build");
2105
2106        let debounce = Duration::from_millis(50);
2107        let dispatched = Arc::new(Mutex::new(Vec::new()));
2108        let token = CancellationToken::new();
2109        let dispatch = dispatch_logger(Arc::clone(&dispatched), token.clone());
2110
2111        let (tx, rx) = mpsc::channel(64);
2112        let (parents_tx, _parents_rx) = watch::channel(Vec::new());
2113        let loop_fut = run_reload_loop(
2114            rx,
2115            vec![PathBuf::from("routes")],
2116            ctx.runtime_execution_handle(),
2117            &provider,
2118            &reload_pass,
2119            publish_script_sources,
2120            &dispatch,
2121            parents_tx,
2122            Some(token.clone()),
2123            debounce,
2124        );
2125
2126        let driver = async {
2127            for event in events {
2128                tx.send(Ok(event)).await.expect("send event");
2129            }
2130            settle().await;
2131            tokio::time::advance(debounce).await;
2132            settle().await;
2133            token.cancel();
2134        };
2135
2136        let (loop_result, ()) = futures::future::join(loop_fut, driver).await;
2137        assert!(loop_result.is_ok());
2138        dispatched.lock().expect("dispatch log poisoned").clone()
2139    }
2140
2141    fn route_file_event(path: &str) -> Event {
2142        make_event(&[path], EventKind::Create(notify::event::CreateKind::File))
2143    }
2144
2145    #[tokio::test(start_paused = true)]
2146    async fn mixed_batch_dispatches_for_surviving_unrebuilt_route() {
2147        let dev_map = make_dev_map(&[("A", &["templates/a.jinja"]), ("B", &["templates/b.jinja"])]);
2148        let reload_pass = reload_pass_counter(Arc::new(AtomicUsize::new(0)), vec!["B".to_string()]);
2149
2150        let dispatched = drive_one_batch(
2151            dev_map,
2152            reload_pass,
2153            vec![
2154                modify_event("templates/a.jinja"),
2155                route_file_event("routes/b.yaml"),
2156            ],
2157        )
2158        .await;
2159
2160        assert_eq!(dispatched, vec!["A".to_string()]);
2161    }
2162
2163    #[tokio::test(start_paused = true)]
2164    async fn mixed_batch_same_route_no_double_dispatch() {
2165        let dev_map = make_dev_map(&[("B", &["templates/b.jinja"])]);
2166        let reload_pass = reload_pass_counter(Arc::new(AtomicUsize::new(0)), vec!["B".to_string()]);
2167
2168        let dispatched = drive_one_batch(
2169            dev_map,
2170            reload_pass,
2171            vec![
2172                modify_event("templates/b.jinja"),
2173                route_file_event("routes/b.yaml"),
2174            ],
2175        )
2176        .await;
2177
2178        assert!(
2179            dispatched.is_empty(),
2180            "rebuilt route B must not receive a second dispatch, got {dispatched:?}"
2181        );
2182    }
2183
2184    #[tokio::test(start_paused = true)]
2185    async fn partial_survival_skipped_and_failed_still_dispatch() {
2186        let dev_map = make_dev_map(&[
2187            ("A", &["templates/a.jinja"]),
2188            ("B", &["templates/b.jinja"]),
2189            ("C", &["templates/c.jinja"]),
2190        ]);
2191        // A was skipped and B failed to rebuild; only C was rebuilt.
2192        let reload_pass = reload_pass_counter(Arc::new(AtomicUsize::new(0)), vec!["C".to_string()]);
2193
2194        let dispatched = drive_one_batch(
2195            dev_map,
2196            reload_pass,
2197            vec![
2198                modify_event("templates/a.jinja"),
2199                modify_event("templates/b.jinja"),
2200                modify_event("templates/c.jinja"),
2201                route_file_event("routes/c.yaml"),
2202            ],
2203        )
2204        .await;
2205
2206        assert_eq!(dispatched, vec!["A".to_string(), "B".to_string()]);
2207    }
2208
2209    #[tokio::test(start_paused = true)]
2210    async fn failed_discovery_still_dispatches_pending() {
2211        let dev_map = make_dev_map(&[("A", &["templates/a.jinja"]), ("B", &["templates/b.jinja"])]);
2212        let reload_pass: ReloadPass = Box::new(|| {
2213            Box::pin(async { Err(CamelError::Config("discovery failed".to_string())) })
2214        });
2215
2216        let dispatched = drive_one_batch(
2217            dev_map,
2218            reload_pass,
2219            vec![
2220                modify_event("templates/a.jinja"),
2221                modify_event("templates/b.jinja"),
2222                route_file_event("routes/b.yaml"),
2223            ],
2224        )
2225        .await;
2226
2227        assert_eq!(dispatched, vec!["A".to_string(), "B".to_string()]);
2228    }
2229
2230    #[tokio::test(start_paused = true)]
2231    async fn no_action_pass_still_dispatches() {
2232        let dev_map = make_dev_map(&[("A", &["templates/a.jinja"])]);
2233        let reload_pass = reload_pass_counter(Arc::new(AtomicUsize::new(0)), Vec::new());
2234
2235        let dispatched = drive_one_batch(
2236            dev_map,
2237            reload_pass,
2238            vec![
2239                modify_event("templates/a.jinja"),
2240                route_file_event("routes/a.yaml"),
2241            ],
2242        )
2243        .await;
2244
2245        assert_eq!(dispatched, vec!["A".to_string()]);
2246    }
2247
2248    // ── script sources (Task 3.1) ───────────────────────────────────────────
2249
2250    #[test]
2251    fn classify_script_path_yields_script_source_class() {
2252        let dev_map = make_kinded_dev_map(&[("s1", "scripts/enrich.rhai", DevSourceKind::Script)]);
2253        let script_path = PathBuf::from("scripts/enrich.rhai");
2254        assert!(
2255            dev_map.script_routes_for(&script_path).contains("s1"),
2256            "the script source must map back to its route"
2257        );
2258        assert!(
2259            dev_map.routes_for(&script_path).is_empty(),
2260            "script sources must not appear as template targets"
2261        );
2262
2263        let ev = make_event(&["scripts/enrich.rhai"], modify_content());
2264        let roots = vec![PathBuf::from("routes")];
2265
2266        assert_eq!(
2267            classify_event(&ev, &dev_map, &roots),
2268            Some(EventClass::ScriptSource)
2269        );
2270    }
2271
2272    #[test]
2273    fn classify_yaml_script_path_yields_script_source_not_route_file() {
2274        // A `.yaml` script source under a route root matches both the script
2275        // registry and the route-file extension check; the registry must win.
2276        let dev_map =
2277            make_kinded_dev_map(&[("s1", "routes/scripts/render.yaml", DevSourceKind::Script)]);
2278        let script_path = PathBuf::from("routes/scripts/render.yaml");
2279        assert!(
2280            dev_map.script_routes_for(&script_path).contains("s1"),
2281            "the script source must map back to its route"
2282        );
2283        assert!(
2284            dev_map.routes_for(&script_path).is_empty(),
2285            "script sources must not appear as template targets"
2286        );
2287
2288        let ev = make_event(&["routes/scripts/render.yaml"], modify_content());
2289        let roots = vec![PathBuf::from("routes")];
2290
2291        assert_eq!(
2292            classify_event(&ev, &dev_map, &roots),
2293            Some(EventClass::ScriptSource),
2294            "a tracked .yaml script source must not classify as RouteFile or DevTarget"
2295        );
2296    }
2297
2298    #[tokio::test(start_paused = true)]
2299    async fn script_event_triggers_full_reload_pass() {
2300        let dev_map = make_kinded_dev_map(&[("s1", "scripts/enrich.rhai", DevSourceKind::Script)]);
2301        let reload_calls = Arc::new(AtomicUsize::new(0));
2302        let reload_pass = reload_pass_counter(Arc::clone(&reload_calls), Vec::new());
2303
2304        let dispatched = drive_one_batch(
2305            dev_map,
2306            reload_pass,
2307            vec![modify_event("scripts/enrich.rhai")],
2308        )
2309        .await;
2310
2311        assert_eq!(
2312            reload_calls.load(Ordering::SeqCst),
2313            1,
2314            "a script-only batch must run the full reload pass once"
2315        );
2316        assert!(
2317            dispatched.is_empty(),
2318            "a script source must not dispatch ReloadTemplates, got {dispatched:?}"
2319        );
2320    }
2321
2322    #[tokio::test(start_paused = true)]
2323    async fn template_event_still_dispatches_reload_templates() {
2324        let dev_map = make_dev_map(&[("t1", &["templates/page.jinja"])]);
2325        let reload_calls = Arc::new(AtomicUsize::new(0));
2326        let reload_pass = reload_pass_counter(Arc::clone(&reload_calls), Vec::new());
2327
2328        let dispatched = drive_one_batch(
2329            dev_map,
2330            reload_pass,
2331            vec![modify_event("templates/page.jinja")],
2332        )
2333        .await;
2334
2335        assert_eq!(
2336            reload_calls.load(Ordering::SeqCst),
2337            0,
2338            "a template-only batch must keep the per-route dispatch path"
2339        );
2340        assert_eq!(dispatched, vec!["t1".to_string()]);
2341    }
2342
2343    #[tokio::test(start_paused = true)]
2344    async fn script_and_route_edit_in_one_batch_single_pass() {
2345        let dev_map = make_kinded_dev_map(&[("s1", "scripts/enrich.rhai", DevSourceKind::Script)]);
2346        let reload_calls = Arc::new(AtomicUsize::new(0));
2347        let reload_pass = reload_pass_counter(Arc::clone(&reload_calls), Vec::new());
2348
2349        drive_one_batch(
2350            dev_map,
2351            reload_pass,
2352            vec![
2353                modify_event("scripts/enrich.rhai"),
2354                route_file_event("routes/a.yaml"),
2355            ],
2356        )
2357        .await;
2358
2359        assert_eq!(
2360            reload_calls.load(Ordering::SeqCst),
2361            1,
2362            "a mixed script+route batch must run exactly one reload pass"
2363        );
2364    }
2365
2366    #[tokio::test(start_paused = true)]
2367    async fn publish_hook_called_with_outcome_after_pass() {
2368        // A successful Remove appears in `removed`; a failed one does not,
2369        // because the route keeps running and keeps its script targets.
2370        let actions = vec![
2371            ReloadAction::Remove {
2372                route_id: "removed-ok".into(),
2373            },
2374            ReloadAction::Remove {
2375                route_id: "removed-failed".into(),
2376            },
2377        ];
2378        let errors = vec![super::ReloadError {
2379            route_id: "removed-failed".into(),
2380            action: "remove".into(),
2381            error: CamelError::RouteError("removal failed".to_string()),
2382        }];
2383        assert_eq!(
2384            derive_removed_route_ids(&actions, &errors),
2385            vec!["removed-ok".to_string()],
2386            "a failed removal must stay out of the removed set"
2387        );
2388
2389        // Non-aborted pass: the hook sees exactly one (rebuilt, removed) pair.
2390        let published = Arc::new(Mutex::new(Vec::new()));
2391        let hook = publish_logger(Arc::clone(&published));
2392        let outcome = PassOutcome {
2393            rebuilt: vec!["rebuilt-1".to_string()],
2394            removed: vec!["removed-ok".to_string()],
2395            aborted: false,
2396        };
2397        let reload_pass: ReloadPass = Box::new(move || {
2398            let outcome = outcome.clone();
2399            Box::pin(async move { Ok(outcome) })
2400        });
2401        let dev_map = make_kinded_dev_map(&[("s1", "scripts/enrich.rhai", DevSourceKind::Script)]);
2402        let _ = drive_one_batch_with_hook(
2403            move || dev_map.clone(),
2404            reload_pass,
2405            &*hook,
2406            vec![modify_event("scripts/enrich.rhai")],
2407        )
2408        .await;
2409        assert_eq!(
2410            *published.lock().expect("publish log poisoned"),
2411            vec![(
2412                vec!["rebuilt-1".to_string()],
2413                vec!["removed-ok".to_string()]
2414            )],
2415            "a non-aborted pass must publish its outcome exactly once"
2416        );
2417
2418        // Aborted pass: never publishes. A discovery failure says nothing
2419        // about which routes still run.
2420        let aborted_published = Arc::new(Mutex::new(Vec::new()));
2421        let aborted_hook = publish_logger(Arc::clone(&aborted_published));
2422        let aborted_pass: ReloadPass = Box::new(|| {
2423            Box::pin(async {
2424                Ok(PassOutcome {
2425                    rebuilt: Vec::new(),
2426                    removed: Vec::new(),
2427                    aborted: true,
2428                })
2429            })
2430        });
2431        let dev_map = make_kinded_dev_map(&[("s1", "scripts/enrich.rhai", DevSourceKind::Script)]);
2432        let _ = drive_one_batch_with_hook(
2433            move || dev_map.clone(),
2434            aborted_pass,
2435            &*aborted_hook,
2436            vec![modify_event("scripts/enrich.rhai")],
2437        )
2438        .await;
2439        assert!(
2440            aborted_published
2441                .lock()
2442                .expect("publish log poisoned")
2443                .is_empty(),
2444            "an aborted pass must never publish"
2445        );
2446    }
2447
2448    /// Covers the production rebuilt-id derivation end-to-end against the real
2449    /// reload executor: only Add, Swap and Restart routes that did not error
2450    /// survive; Skip, Remove and the failed Swap are filtered out.
2451    #[tokio::test]
2452    async fn production_derivation_keeps_only_successful_rebuilds() {
2453        use camel_component_timer::TimerComponent;
2454
2455        let mut ctx = CamelContext::builder()
2456            .build()
2457            .await
2458            .expect("context build");
2459        ctx.register_component(TimerComponent::new());
2460        ctx.start().await.expect("context start");
2461
2462        // Seed the routes that Swap, Restart, Skip and Remove act on.
2463        for route_id in ["swapped", "restarted", "skipped", "removed"] {
2464            ctx.add_route_definition(
2465                RouteDefinition::new("timer:tick?period=50", Vec::new()).with_route_id(route_id),
2466            )
2467            .await
2468            .expect("seed route");
2469        }
2470
2471        let actions = vec![
2472            ReloadAction::Add {
2473                route_id: "added".into(),
2474            },
2475            ReloadAction::Swap {
2476                route_id: "swapped".into(),
2477            },
2478            ReloadAction::Restart {
2479                route_id: "restarted".into(),
2480            },
2481            ReloadAction::Skip {
2482                route_id: "skipped".into(),
2483            },
2484            ReloadAction::Remove {
2485                route_id: "removed".into(),
2486            },
2487            // No matching definition: the executor reports an error, so this
2488            // candidate must not count as rebuilt.
2489            ReloadAction::Swap {
2490                route_id: "failed".into(),
2491            },
2492        ];
2493        let new_defs = vec![
2494            RouteDefinition::new("timer:tick?period=50", Vec::new()).with_route_id("added"),
2495            RouteDefinition::new("timer:tick?period=50", Vec::new()).with_route_id("swapped"),
2496            RouteDefinition::new("timer:tick?period=60", Vec::new()).with_route_id("restarted"),
2497        ];
2498
2499        let errors = execute_reload_actions(
2500            actions.clone(),
2501            new_defs,
2502            &ctx.runtime_execution_handle(),
2503            Duration::from_secs(5),
2504            None,
2505        )
2506        .await;
2507        assert_eq!(
2508            errors.len(),
2509            1,
2510            "only the definition-less Swap may fail, got {errors:?}"
2511        );
2512        assert_eq!(errors[0].route_id, "failed");
2513
2514        let mut rebuilt = derive_rebuilt_route_ids(&actions, &errors);
2515        rebuilt.sort();
2516
2517        assert_eq!(
2518            rebuilt,
2519            vec![
2520                "added".to_string(),
2521                "restarted".to_string(),
2522                "swapped".to_string()
2523            ],
2524            "Skip, Remove and the errored rebuild must be excluded"
2525        );
2526
2527        ctx.stop().await.expect("context stop");
2528    }
2529
2530    #[tokio::test(start_paused = true)]
2531    async fn route_file_event_keeps_existing_behavior() {
2532        let ctx = CamelContext::builder()
2533            .build()
2534            .await
2535            .expect("context build");
2536
2537        let debounce = Duration::from_millis(50);
2538        let dev_map = DevTargetMap::default();
2539        let provider = move || dev_map.clone();
2540        let reload_calls = Arc::new(AtomicUsize::new(0));
2541        let reload_pass = reload_pass_counter(Arc::clone(&reload_calls), Vec::new());
2542        let dispatched = Arc::new(Mutex::new(Vec::new()));
2543        let token = CancellationToken::new();
2544        let dispatch = dispatch_logger(Arc::clone(&dispatched), token.clone());
2545
2546        let (tx, rx) = mpsc::channel(64);
2547        let (parents_tx, _parents_rx) = watch::channel(Vec::new());
2548        let loop_fut = run_reload_loop(
2549            rx,
2550            vec![PathBuf::from("routes")],
2551            ctx.runtime_execution_handle(),
2552            &provider,
2553            &reload_pass,
2554            &noop_publish,
2555            &dispatch,
2556            parents_tx,
2557            Some(token.clone()),
2558            debounce,
2559        );
2560
2561        let driver = async {
2562            tx.send(Ok(make_event(
2563                &["routes/x.yaml"],
2564                EventKind::Create(notify::event::CreateKind::File),
2565            )))
2566            .await
2567            .expect("send route-file event");
2568            settle().await;
2569            tokio::time::advance(debounce).await;
2570            settle().await;
2571            token.cancel();
2572        };
2573
2574        let (loop_result, ()) = futures::future::join(loop_fut, driver).await;
2575        assert!(loop_result.is_ok());
2576        assert_eq!(
2577            reload_calls.load(Ordering::SeqCst),
2578            1,
2579            "a route-file event must run the route pass exactly once"
2580        );
2581        assert!(
2582            dispatched.lock().expect("dispatch log poisoned").is_empty(),
2583            "no dev-target dispatch without a target map entry"
2584        );
2585    }
2586
2587    // ── Task 2.4: re-derivation + subscription reconciliation ───────────────
2588
2589    #[test]
2590    fn publish_parents_repeats_unchanged_snapshot() {
2591        let map = make_dev_map(&[("A", &["templates/a.jinja"])]);
2592        let route_roots: Vec<PathBuf> = Vec::new();
2593        let (tx, mut rx) = watch::channel(Vec::new());
2594
2595        publish_parents(&tx, &map, &route_roots);
2596        let first = rx.borrow_and_update().clone();
2597        assert!(!first.is_empty(), "first publish must carry the parent dir");
2598
2599        publish_parents(&tx, &map, &route_roots);
2600        assert!(
2601            rx.has_changed().expect("parents sender alive"),
2602            "an unchanged snapshot must still be published so failed \
2603             subscriptions retry"
2604        );
2605    }
2606
2607    #[tokio::test]
2608    async fn watcher_ready_barrier() {
2609        let ctx = CamelContext::builder()
2610            .build()
2611            .await
2612            .expect("context build");
2613        let (shutdown, ready_rx, version_rx, handle) = spawn_watcher(
2614            ctx.runtime_execution_handle(),
2615            Vec::new(),
2616            "ready-barrier-route".to_string(),
2617            || Ok(vec![]),
2618        );
2619
2620        await_ready(ready_rx).await;
2621        assert!(
2622            *version_rx.borrow() >= 1,
2623            "initial reconciliation must be applied before the readiness signal"
2624        );
2625
2626        stop_watcher(shutdown, handle).await;
2627    }
2628
2629    #[tokio::test(start_paused = true)]
2630    async fn failed_route_pass_retains_surviving_targets() {
2631        let reg = fresh_registry();
2632        let good = FakeReloadTarget::new(
2633            "failed-pass-good",
2634            vec![PathBuf::from("templates/good.jinja")],
2635        );
2636        let bad = FakeReloadTarget::new(
2637            "failed-pass-bad",
2638            vec![PathBuf::from("templates/bad.jinja")],
2639        );
2640        let _good = reg.register(good.as_dyn());
2641        let _bad = reg.register(bad.as_dyn());
2642
2643        let provider =
2644            move || DevTargetMap::from_sources(&template_kind_sources(reg.route_watch_sources()));
2645        let reload_pass: ReloadPass = Box::new(|| {
2646            Box::pin(async { Err(CamelError::Config("discovery failed".to_string())) })
2647        });
2648
2649        let dispatched = drive_one_batch_with_provider(
2650            provider,
2651            reload_pass,
2652            vec![
2653                modify_event("templates/good.jinja"),
2654                route_file_event("routes/x.yaml"),
2655            ],
2656        )
2657        .await;
2658
2659        assert_eq!(
2660            dispatched,
2661            vec!["failed-pass-good".to_string()],
2662            "the surviving target must dispatch even after a failed route pass"
2663        );
2664        let map = DevTargetMap::from_sources(&template_kind_sources(reg.route_watch_sources()));
2665        assert!(
2666            !map.routes_for(&PathBuf::from("templates/good.jinja"))
2667                .is_empty(),
2668            "good route source must survive re-derivation"
2669        );
2670        assert!(
2671            !map.routes_for(&PathBuf::from("templates/bad.jinja"))
2672                .is_empty(),
2673            "bad route source must survive re-derivation"
2674        );
2675    }
2676
2677    #[tokio::test]
2678    async fn rederive_after_committed_reload_picks_up_new_closure_file() {
2679        let reg = fresh_registry();
2680        let old = PathBuf::from("templates/page.jinja");
2681        let new = PathBuf::from("templates/part/head.jinja");
2682        let target = FakeReloadTarget::new("rederive-route", vec![old.clone()]);
2683        target.set_pending(vec![old.clone(), new.clone()]);
2684        let _guard = reg.register(target.as_dyn());
2685
2686        let provider =
2687            move || DevTargetMap::from_sources(&template_kind_sources(reg.route_watch_sources()));
2688        let reload_pass = reload_pass_counter(Arc::new(AtomicUsize::new(0)), Vec::new());
2689        let dispatch: DispatchReload = Box::new(move |_route_id: &str| {
2690            Box::pin(async move { reg.reload_route("rederive-route").await })
2691        });
2692
2693        let ctx = CamelContext::builder()
2694            .build()
2695            .await
2696            .expect("context build");
2697        let token = CancellationToken::new();
2698        let shutdown = token.clone();
2699        let (tx, rx) = mpsc::channel(64);
2700        let (parents_tx, mut parents_rx) = watch::channel(Vec::new());
2701        let handle = tokio::spawn(async move {
2702            run_reload_loop(
2703                rx,
2704                vec![PathBuf::from("routes")],
2705                ctx.runtime_execution_handle(),
2706                &provider,
2707                &reload_pass,
2708                &noop_publish,
2709                &dispatch,
2710                parents_tx,
2711                Some(shutdown),
2712                Duration::from_millis(20),
2713            )
2714            .await
2715        });
2716
2717        tx.send(Ok(modify_event("templates/page.jinja")))
2718            .await
2719            .expect("send tracked event");
2720
2721        let published = tokio::time::timeout(
2722            Duration::from_secs(2),
2723            parents_rx.wait_for(|dirs| dirs.iter().any(|dir| dir.ends_with("templates/part"))),
2724        )
2725        .await
2726        .expect("post-commit re-derivation must publish the new parent dir");
2727        assert!(published.is_ok(), "parents channel closed");
2728
2729        let map = DevTargetMap::from_sources(&template_kind_sources(reg.route_watch_sources()));
2730        assert!(
2731            !map.routes_for(&new).is_empty(),
2732            "re-derived map must route the newly committed closure file"
2733        );
2734
2735        token.cancel();
2736        let result = tokio::time::timeout(Duration::from_secs(2), handle)
2737            .await
2738            .expect("loop did not stop")
2739            .expect("loop task panicked");
2740        assert!(result.is_ok());
2741    }
2742
2743    #[tokio::test(start_paused = true)]
2744    async fn per_commit_rederivation_publishes_before_later_route_stalls() {
2745        let reg = fresh_registry();
2746        let tmp = tempfile::tempdir().expect("temp dir");
2747        let a_old = tmp.path().join("awatch/page.jinja");
2748        let a_new = tmp.path().join("awatch/grown/part.jinja");
2749        let a_new_parent = tmp.path().join("awatch/grown");
2750        let b_source = tmp.path().join("bwatch/page.jinja");
2751
2752        let route_a = "a-growth-route";
2753        let route_b = "b-stall-route";
2754
2755        // Route A grows its closure into a new parent dir when it commits.
2756        let target_a = FakeReloadTarget::new(route_a, vec![a_old.clone()]);
2757        target_a.set_pending(vec![a_old.clone(), a_new.clone()]);
2758        let _guard_a = reg.register(target_a.as_dyn());
2759
2760        // Route B never changes its closure; it only stalls on dispatch.
2761        let target_b = FakeReloadTarget::new(route_b, vec![b_source.clone()]);
2762        let _guard_b = reg.register(target_b.as_dyn());
2763
2764        let provider =
2765            move || DevTargetMap::from_sources(&template_kind_sources(reg.route_watch_sources()));
2766        let reload_pass = reload_pass_counter(Arc::new(AtomicUsize::new(0)), Vec::new());
2767
2768        let token = CancellationToken::new();
2769        let (started_tx, mut started_rx) = watch::channel(false);
2770        let (release_tx, release_rx) = watch::channel(false);
2771        let b_completed = Arc::new(AtomicBool::new(false));
2772
2773        let dispatch: DispatchReload = {
2774            let b_completed = Arc::clone(&b_completed);
2775            let shutdown = token.clone();
2776            Box::new(move |route_id: &str| {
2777                if route_id == route_b {
2778                    let _ = started_tx.send(true);
2779                    let mut released = release_rx.clone();
2780                    let b_completed = Arc::clone(&b_completed);
2781                    let shutdown = shutdown.clone();
2782                    Box::pin(async move {
2783                        // Park under the production dispatch bound; the test
2784                        // releases B only after asserting A's publication.
2785                        let result = bounded_dispatch(
2786                            async move {
2787                                let _ = released.wait_for(|released| *released).await;
2788                                Ok(())
2789                            },
2790                            test_dispatch_bound(route_b),
2791                            Some(&shutdown),
2792                        )
2793                        .await;
2794                        b_completed.store(true, Ordering::SeqCst);
2795                        result
2796                    })
2797                } else {
2798                    let route_id = route_id.to_string();
2799                    Box::pin(async move { reg.reload_route(&route_id).await })
2800                }
2801            })
2802        };
2803
2804        let ctx = CamelContext::builder()
2805            .build()
2806            .await
2807            .expect("context build");
2808        let (tx, rx) = mpsc::channel(64);
2809        let (parents_tx, parents_rx) = watch::channel(Vec::new());
2810        let debounce = Duration::from_millis(20);
2811        let loop_fut = run_reload_loop(
2812            rx,
2813            Vec::new(),
2814            ctx.runtime_execution_handle(),
2815            &provider,
2816            &reload_pass,
2817            &noop_publish,
2818            &dispatch,
2819            parents_tx,
2820            Some(token.clone()),
2821            debounce,
2822        );
2823
2824        let driver = async {
2825            tx.send(Ok(modify_event(a_old.to_str().expect("utf-8 test path"))))
2826                .await
2827                .expect("send A event");
2828            tx.send(Ok(modify_event(
2829                b_source.to_str().expect("utf-8 test path"),
2830            )))
2831            .await
2832            .expect("send B event");
2833            settle().await;
2834            tokio::time::advance(debounce).await;
2835            settle().await;
2836
2837            // A is dispatched first (BTreeSet order) and B is now parked in
2838            // its bounded dispatch. Waiting for B to start proves the loop
2839            // reached it without advancing past A's commit.
2840            let started = started_rx.wait_for(|started| *started).await;
2841            assert!(started.is_ok(), "route B dispatch never started");
2842
2843            let published = parents_rx.borrow().clone();
2844            assert!(
2845                published.iter().any(|dir| dir == &a_new_parent),
2846                "A's new parent must be published before B completes, got {published:?}"
2847            );
2848            assert!(
2849                !b_completed.load(Ordering::SeqCst),
2850                "B must still be parked when A's growth is published"
2851            );
2852
2853            release_tx.send(true).expect("release B");
2854            settle().await;
2855            token.cancel();
2856        };
2857
2858        let (loop_result, ()) = futures::future::join(loop_fut, driver).await;
2859        assert!(loop_result.is_ok());
2860        assert!(
2861            b_completed.load(Ordering::SeqCst),
2862            "released B dispatch must complete"
2863        );
2864    }
2865
2866    #[tokio::test]
2867    async fn replace_then_edit_still_dispatches() {
2868        let tmp = tempfile::tempdir().expect("temp dir");
2869        let source = tmp.path().join("page.jinja");
2870        fs::write(&source, "v1").expect("seed source");
2871
2872        let route = "replace-then-edit-route";
2873        let target = FakeReloadTarget::new(route, vec![source.clone()]);
2874        let commits = Arc::clone(&target.commits);
2875        let _guard = TemplateReloadRegistry::global().register(target.as_dyn());
2876
2877        let ctx = CamelContext::builder()
2878            .build()
2879            .await
2880            .expect("context build");
2881        let (shutdown, ready_rx, _version_rx, handle) = spawn_watcher(
2882            ctx.runtime_execution_handle(),
2883            Vec::new(),
2884            route.to_string(),
2885            || Ok(vec![]),
2886        );
2887        await_ready(ready_rx).await;
2888
2889        // Atomic replace: write a sibling then rename it over the target.
2890        let sibling = tmp.path().join("page.jinja.replacement");
2891        fs::write(&sibling, "v2").expect("write sibling");
2892        fs::rename(&sibling, &source).expect("rename over target");
2893        wait_for_condition(
2894            || commits.load(Ordering::SeqCst) >= 1,
2895            Duration::from_secs(3),
2896        )
2897        .await;
2898
2899        fs::write(&source, "v3").expect("edit target");
2900        wait_for_condition(
2901            || commits.load(Ordering::SeqCst) >= 2,
2902            Duration::from_secs(3),
2903        )
2904        .await;
2905        assert_eq!(
2906            commits.load(Ordering::SeqCst),
2907            2,
2908            "replace then edit must yield exactly two dispatches"
2909        );
2910
2911        stop_watcher(shutdown, handle).await;
2912    }
2913
2914    #[tokio::test]
2915    async fn new_parent_subscribed_after_closure_growth() {
2916        let tmp = tempfile::tempdir().expect("temp dir");
2917        let watch_a = tmp.path().join("watch_a");
2918        let watch_b = tmp.path().join("watch_b");
2919        fs::create_dir_all(&watch_a).expect("create watch_a");
2920        fs::create_dir_all(&watch_b).expect("create watch_b");
2921        let a_source = watch_a.join("page.jinja");
2922        let b_source = watch_b.join("new.jinja");
2923        fs::write(&a_source, "a1").expect("seed a");
2924        fs::write(&b_source, "b1").expect("seed b");
2925
2926        let route = "growth-target-route";
2927        let target = FakeReloadTarget::new(route, vec![a_source.clone()]);
2928        target.set_pending(vec![a_source.clone(), b_source.clone()]);
2929        let commits = Arc::clone(&target.commits);
2930        let _guard = TemplateReloadRegistry::global().register(target.as_dyn());
2931
2932        let ctx = CamelContext::builder()
2933            .build()
2934            .await
2935            .expect("context build");
2936        let (shutdown, ready_rx, mut version_rx, handle) = spawn_watcher(
2937            ctx.runtime_execution_handle(),
2938            Vec::new(),
2939            route.to_string(),
2940            || Ok(vec![]),
2941        );
2942        await_ready(ready_rx).await;
2943        let base_version = *version_rx.borrow();
2944
2945        fs::write(&a_source, "a2").expect("edit tracked source");
2946        wait_for_condition(
2947            || commits.load(Ordering::SeqCst) >= 1,
2948            Duration::from_secs(3),
2949        )
2950        .await;
2951        assert_eq!(
2952            commits.load(Ordering::SeqCst),
2953            1,
2954            "first edit must dispatch exactly once"
2955        );
2956
2957        // The commit grew the closure into watch_b/, so the wrapper must have
2958        // reconciled a subscription there before we write.
2959        await_version_after(&mut version_rx, base_version).await;
2960
2961        fs::write(&b_source, "b2").expect("edit newly watched source");
2962        wait_for_condition(
2963            || commits.load(Ordering::SeqCst) >= 2,
2964            Duration::from_secs(3),
2965        )
2966        .await;
2967
2968        stop_watcher(shutdown, handle).await;
2969    }
2970
2971    #[tokio::test]
2972    async fn route_pass_growth_subscribes_new_parent() {
2973        let tmp = tempfile::tempdir().expect("temp dir");
2974        let watch_a = tmp.path().join("watch_a");
2975        let watch_b = tmp.path().join("watch_b");
2976        let routes = tmp.path().join("routes");
2977        fs::create_dir_all(&watch_a).expect("create watch_a");
2978        fs::create_dir_all(&watch_b).expect("create watch_b");
2979        fs::create_dir_all(&routes).expect("create routes");
2980        let a_source = watch_a.join("page.jinja");
2981        let b_source = watch_b.join("new.jinja");
2982        fs::write(&a_source, "a1").expect("seed a");
2983        fs::write(&b_source, "b1").expect("seed b");
2984
2985        let route = "route-pass-growth-route";
2986        let target = FakeReloadTarget::new(route, vec![a_source.clone()]);
2987        target.set_pending(vec![a_source.clone(), b_source.clone()]);
2988        let commits = Arc::clone(&target.commits);
2989        let _guard = TemplateReloadRegistry::global().register(target.as_dyn());
2990
2991        // The fake's committed closure grows when the route pass runs.
2992        let discover_target = Arc::clone(&target);
2993        let discover = move || {
2994            discover_target.install_pending();
2995            Ok(vec![])
2996        };
2997
2998        let ctx = CamelContext::builder()
2999            .build()
3000            .await
3001            .expect("context build");
3002        let (shutdown, ready_rx, mut version_rx, handle) = spawn_watcher(
3003            ctx.runtime_execution_handle(),
3004            vec![routes.clone()],
3005            route.to_string(),
3006            discover,
3007        );
3008        await_ready(ready_rx).await;
3009        let base_version = *version_rx.borrow();
3010
3011        fs::write(routes.join("r.yaml"), "routes: []").expect("write route file");
3012        await_version_after(&mut version_rx, base_version).await;
3013
3014        // The route-pass re-derivation must have reconciled watch_b/.
3015        fs::write(&b_source, "b2").expect("edit newly watched source");
3016        wait_for_condition(
3017            || commits.load(Ordering::SeqCst) >= 1,
3018            Duration::from_secs(3),
3019        )
3020        .await;
3021
3022        stop_watcher(shutdown, handle).await;
3023    }
3024}