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