use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use crossbeam_channel::{select, unbounded, Receiver, Sender};
use notify::{Config, RecommendedWatcher, RecursiveMode, Watcher};
use nativeview_engine::HotPatchMsg;
use crate::pair::PairControlMsg;
use crate::hot_diff;
use crate::hot_diff::cache::WatchSnapshot;
use super::control::{DevCoordinator, WatchTrigger};
use super::session::DevSessionFiles;
use super::watch::{classify_watch_changes, collect_relevant_paths, drain_notify_events};
use super::ws::DevWsHub;
pub(crate) struct WatchLoopState {
pub workspace_root: PathBuf,
pub watch_roots: Vec<PathBuf>,
pub web_asset_paths: Vec<PathBuf>,
pub excluded_dirs: Vec<PathBuf>,
pub force_tier2_for_web: bool,
pub sync_standalone_web_on_tier1: bool,
pub initial_ok: bool,
pub initial_snapshot: WatchSnapshot,
pub ws_hub: Arc<DevWsHub>,
pub pair_tx_slot: Arc<Mutex<Option<Sender<PairControlMsg>>>>,
pub coord: Arc<DevCoordinator>,
pub trigger_rx: Receiver<WatchTrigger>,
pub skia_ready_tx: Sender<()>,
}
pub(crate) fn run_watch_loop<FBuild, FPair, FWebSync>(
state: WatchLoopState,
build_once: FBuild,
start_pair_server: FPair,
sync_standalone_web: FWebSync,
) where
FBuild: Fn(u64, &[PathBuf], &str, Option<&str>) -> bool,
FPair: Fn(),
FWebSync: Fn(),
{
let WatchLoopState {
workspace_root,
watch_roots,
web_asset_paths,
excluded_dirs,
force_tier2_for_web,
sync_standalone_web_on_tier1,
initial_ok,
initial_snapshot,
ws_hub,
pair_tx_slot,
coord,
trigger_rx,
skia_ready_tx,
} = state;
let mut has_built_once = initial_ok;
let mut watch_cache = hot_diff::WatchCache::with_workspace_root(workspace_root);
if has_built_once {
watch_cache.adopt_snapshot(initial_snapshot);
} else {
watch_cache.record_attempted_snapshot(&initial_snapshot, &[]);
}
let (notify_tx, notify_rx) = unbounded();
let mut watcher = RecommendedWatcher::new(
move |res| {
let _ = notify_tx.send(res);
},
Config::default(),
)
.expect("create file watcher");
for root in &watch_roots {
if root.exists() {
let _ = watcher.watch(root, RecursiveMode::Recursive);
}
}
let mut generation = 1u64;
println!(
"Watching {} root(s) ({} cached .rs file(s) for Tier-1 hot-patch; Ctrl-C to stop)...",
watch_roots.len(),
watch_cache.len()
);
loop {
let mut changed_paths: Vec<PathBuf> = Vec::new();
let mut force_scan_epoch: Option<u64> = None;
select! {
recv(notify_rx) -> ev => {
if let Ok(Ok(event)) = ev {
collect_relevant_paths(&event, &watch_roots, &excluded_dirs, &mut changed_paths);
if changed_paths.is_empty() {
continue;
}
std::thread::sleep(Duration::from_millis(40));
drain_notify_events(¬ify_rx, &watch_roots, &excluded_dirs, &mut changed_paths);
}
}
recv(trigger_rx) -> trig => {
if let Ok(WatchTrigger::ForceScan { paths, target_scan_epoch }) = trig {
force_scan_epoch = Some(target_scan_epoch);
drain_notify_events(¬ify_rx, &watch_roots, &excluded_dirs, &mut changed_paths);
for p in watch_cache.disk_changed_paths_with_assets(
&watch_roots,
&web_asset_paths,
&excluded_dirs,
&paths,
) {
if !changed_paths.contains(&p) {
changed_paths.push(p);
}
}
}
}
}
if !changed_paths.is_empty() {
let next_gen = generation + 1;
let t_diff = Instant::now();
let (tier1_patches, fallback_reason) = if force_tier2_for_web {
(Vec::new(), Some("standalone web PWA requires WASM rebuild".to_owned()))
} else {
classify_watch_changes(has_built_once, &changed_paths, &mut watch_cache, next_gen)
};
if let Some(reason) = fallback_reason {
if let Some(first) = changed_paths.first() {
println!("[tier-2] {} ({reason}) — rebuilding...", first.display());
}
let pre_build_snap = hot_diff::WatchCache::snapshot_roots_with_assets(
&watch_roots,
&web_asset_paths,
&excluded_dirs,
);
generation = next_gen;
if build_once(generation, &changed_paths, "tier2", Some(&reason)) {
let first_success = !has_built_once;
has_built_once = true;
watch_cache.adopt_snapshot(pre_build_snap);
if first_success {
start_pair_server();
let _ = skia_ready_tx.try_send(());
}
} else {
watch_cache.record_attempted_snapshot(&pre_build_snap, &changed_paths);
}
} else if tier1_patches.is_empty() {
if let Some(first) = changed_paths.first() {
println!(
"[watch] {} — comment/whitespace-only edit (no-op)",
first.display()
);
}
coord.record_noop(generation, &changed_paths);
} else {
let mut stamped_ws: Vec<HotPatchMsg> = Vec::new();
let mut pair_batch: Vec<Vec<u8>> = Vec::new();
let mut patched_paths: Vec<PathBuf> = Vec::new();
for (path, messages) in tier1_patches {
patched_paths.push(path);
for mut msg in messages {
generation += 1;
if let HotPatchMsg::TemplatePatch { generation: ref mut g, .. } = msg {
*g = generation;
}
if let Ok(bytes) = msg.to_bytes() {
pair_batch.push(bytes);
}
stamped_ws.push(msg);
}
}
let last_gen = generation;
let seq = coord.begin_cycle(last_gen, "tier1", &changed_paths, None);
let elapsed_ms = t_diff.elapsed().as_millis() as u64;
let pair_tx = pair_tx_slot
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone();
let has_pair = pair_tx.is_some() && !pair_batch.is_empty();
coord.record_built(
seq,
last_gen,
"tier1",
&changed_paths,
elapsed_ms,
None,
None,
0,
has_pair,
);
for msg in &stamped_ws {
let _ = ws_hub.broadcast(msg);
}
if let Some(tx) = pair_tx
&& !pair_batch.is_empty()
&& tx
.send(PairControlMsg::Tier1Batch {
generation: last_gen,
patches: pair_batch,
})
.is_err()
{
coord.mark_pair_send_failed(
last_gen,
"pairing session thread exited".to_owned(),
);
}
for path in patched_paths {
let status = HotPatchMsg::DevStatus {
message: format!(
"[tier-1] patched {} in {}ms (0 cargo build)",
path.display(),
elapsed_ms
),
latency_ms: elapsed_ms,
};
let _ = ws_hub.broadcast(&status);
println!(
"[tier-1] patched {} in {elapsed_ms}ms (0 cargo build)",
path.display()
);
}
if sync_standalone_web_on_tier1 {
sync_standalone_web();
}
}
}
if let Some(epoch) = force_scan_epoch {
coord.mark_scan_completed(epoch);
}
}
}
pub(crate) fn spawn_shutdown_signal_cleaner(session_files: Arc<DevSessionFiles>) {
let _ = std::thread::Builder::new()
.name("nv-dev-signal".to_owned())
.spawn(move || {
let Ok(rt) = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
else {
return;
};
rt.block_on(async move {
#[cfg(unix)]
{
let mut sigterm =
tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())
.ok();
tokio::select! {
_ = tokio::signal::ctrl_c() => {
session_files.cleanup_session_file();
std::process::exit(130);
}
_ = async {
if let Some(ref mut s) = sigterm {
let _ = s.recv().await;
} else {
std::future::pending::<()>().await;
}
} => {
session_files.cleanup_session_file();
std::process::exit(143);
}
}
}
#[cfg(not(unix))]
{
let _ = tokio::signal::ctrl_c().await;
session_files.cleanup_session_file();
std::process::exit(130);
}
});
});
}