use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Condvar, Mutex};
use std::time::{Duration, Instant};
use crossbeam_channel::Sender;
use super::session::{now_unix_ms, CompilerDiagnostic, DevEvent, DevSessionFiles};
pub(crate) use super::settle::{ControlRequest, ControlResponse, WaitForMode};
use super::settle::{
build_status_response, build_timeout_response, evaluate_settled, make_error_resp,
};
use super::ws::WsHubEvent;
use crate::pair::PairDaemonEvent;
#[derive(Debug)]
pub(crate) enum WatchTrigger {
ForceScan {
paths: Vec<PathBuf>,
target_scan_epoch: u64,
},
}
#[derive(Debug, Clone)]
pub(crate) struct CycleSnapshot {
pub seq: u64,
pub generation: u64,
pub tier: String,
pub build_ms: u64,
pub ok: bool,
pub error: Option<String>,
pub diagnostics: Vec<CompilerDiagnostic>,
pub web_bundle_hash: Option<String>,
pub built_at: Instant,
pub pair_done: bool,
pub pair_target_wire_seq: Option<u32>,
pub pair_error: Option<String>,
}
#[derive(Debug, Clone)]
pub(crate) struct WsHostEntry {
pub client_kind: String,
pub bundle_hash: String,
pub last_acked_gen: u64,
pub last_ack_ok: bool,
pub last_ack_ms: u64,
pub last_ack_detail: Option<String>,
}
#[derive(Debug, Clone)]
pub(crate) struct PairHostEntry {
pub last_acked_seq: u32,
pub last_ack_status: u8,
pub last_acked_gen: u64,
pub last_ack_ms: u64,
}
pub(crate) struct CoordinatorState {
pub pid: u32,
pub package: String,
pub watched_roots: Vec<PathBuf>,
pub scan_epoch: u64,
pub next_scan_epoch: u64,
pub next_seq: u64,
pub in_flight: bool,
pub last_cycle: Option<CycleSnapshot>,
pub ws_hosts: HashMap<u64, WsHostEntry>,
pub pair_hosts: HashMap<u32, PairHostEntry>,
pub pending_web_reloads: HashMap<u64, (usize, Instant)>,
pub host_disconnect_err: Option<(u64, String)>,
}
pub(crate) struct DevCoordinator {
inner: Mutex<CoordinatorState>,
cv: Condvar,
files: Arc<DevSessionFiles>,
trigger_tx: Sender<WatchTrigger>,
}
impl DevCoordinator {
pub(crate) fn new(
package: String,
watched_roots: Vec<PathBuf>,
files: Arc<DevSessionFiles>,
trigger_tx: Sender<WatchTrigger>,
) -> Arc<Self> {
let canon_roots = watched_roots
.into_iter()
.map(|p| crate::hot_diff::cache::canonicalize_preserving_missing(&p))
.collect();
Arc::new(Self {
inner: Mutex::new(CoordinatorState {
pid: std::process::id(),
package,
watched_roots: canon_roots,
scan_epoch: 0,
next_scan_epoch: 0,
next_seq: 0,
in_flight: false,
last_cycle: None,
ws_hosts: HashMap::new(),
pair_hosts: HashMap::new(),
pending_web_reloads: HashMap::new(),
host_disconnect_err: None,
}),
cv: Condvar::new(),
files,
trigger_tx,
})
}
pub(crate) fn mark_pair_send_failed(&self, generation: u64, error: String) {
{
let mut st = self.inner.lock().unwrap_or_else(|e| e.into_inner());
if let Some(ref mut cycle) = st.last_cycle
&& cycle.generation == generation
{
cycle.pair_done = true;
cycle.pair_error = Some(error);
}
}
self.cv.notify_all();
}
pub(crate) fn mark_scan_completed(&self, epoch: u64) {
let mut st = self.inner.lock().unwrap_or_else(|e| e.into_inner());
if epoch > st.scan_epoch {
st.scan_epoch = epoch;
}
self.cv.notify_all();
}
pub(crate) fn begin_cycle(
&self,
generation: u64,
tier: &str,
files: &[PathBuf],
reason: Option<&str>,
) -> u64 {
let file_strs: Vec<String> = files.iter().map(|p| p.display().to_string()).collect();
let seq = {
let mut st = self.inner.lock().unwrap_or_else(|e| e.into_inner());
st.next_seq += 1;
st.in_flight = true;
st.host_disconnect_err = None;
st.next_seq
};
self.files.append_event(&DevEvent::CycleStarted {
ts_ms: now_unix_ms(),
seq,
generation,
tier: tier.to_owned(),
files: file_strs,
reason: reason.map(str::to_owned),
});
seq
}
pub(crate) fn record_noop(&self, generation: u64, files: &[PathBuf]) {
let file_strs: Vec<String> = files.iter().map(|p| p.display().to_string()).collect();
let seq = {
let mut st = self.inner.lock().unwrap_or_else(|e| e.into_inner());
st.next_seq += 1;
let seq = st.next_seq;
st.in_flight = false;
st.last_cycle = Some(CycleSnapshot {
seq,
generation,
tier: "noop".to_owned(),
build_ms: 0,
ok: true,
error: None,
diagnostics: Vec::new(),
web_bundle_hash: None,
built_at: Instant::now(),
pair_done: true,
pair_target_wire_seq: None,
pair_error: None,
});
seq
};
self.files.append_event(&DevEvent::NoOp {
ts_ms: now_unix_ms(),
seq,
generation,
files: file_strs,
});
self.cv.notify_all();
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn record_built(
&self,
seq: u64,
generation: u64,
tier: &str,
files: &[PathBuf],
build_ms: u64,
dylib_path: Option<&Path>,
web_bundle_hash: Option<String>,
clients_notified: usize,
sent_to_pair: bool,
) {
let file_strs: Vec<String> = files.iter().map(|p| p.display().to_string()).collect();
{
let mut st = self.inner.lock().unwrap_or_else(|e| e.into_inner());
st.in_flight = false;
st.last_cycle = Some(CycleSnapshot {
seq,
generation,
tier: tier.to_owned(),
build_ms,
ok: true,
error: None,
diagnostics: Vec::new(),
web_bundle_hash: web_bundle_hash.clone(),
built_at: Instant::now(),
pair_done: !sent_to_pair,
pair_target_wire_seq: None,
pair_error: None,
});
}
self.files.append_event(&DevEvent::Built {
ts_ms: now_unix_ms(),
seq,
generation,
tier: tier.to_owned(),
files: file_strs,
build_ms,
dylib_path: dylib_path.map(|p| p.display().to_string()),
web_bundle_hash,
clients_notified,
});
self.cv.notify_all();
}
#[allow(clippy::too_many_arguments)]
pub(crate) fn record_error(
&self,
seq: u64,
generation: u64,
tier: &str,
files: &[PathBuf],
build_ms: u64,
message: String,
diagnostics: Vec<CompilerDiagnostic>,
) {
let file_strs: Vec<String> = files.iter().map(|p| p.display().to_string()).collect();
{
let mut st = self.inner.lock().unwrap_or_else(|e| e.into_inner());
st.in_flight = false;
st.last_cycle = Some(CycleSnapshot {
seq,
generation,
tier: tier.to_owned(),
build_ms,
ok: false,
error: Some(message.clone()),
diagnostics: diagnostics.clone(),
web_bundle_hash: None,
built_at: Instant::now(),
pair_done: true,
pair_target_wire_seq: None,
pair_error: None,
});
}
self.files.append_event(&DevEvent::Error {
ts_ms: now_unix_ms(),
seq,
generation,
tier: tier.to_owned(),
files: file_strs,
build_ms,
message,
diagnostics,
});
self.cv.notify_all();
}
pub(crate) fn on_ws_event(&self, ev: WsHubEvent) {
let log_ev = {
let mut st = self.inner.lock().unwrap_or_else(|e| e.into_inner());
match ev {
WsHubEvent::Connected { peer_id } => {
let init_gen = st.last_cycle.as_ref().map_or(0, |c| c.generation);
st.ws_hosts.insert(
peer_id,
WsHostEntry {
client_kind: "ws".to_owned(),
bundle_hash: String::new(),
last_acked_gen: init_gen,
last_ack_ok: true,
last_ack_ms: 0,
last_ack_detail: None,
},
);
Some(DevEvent::HostConnection {
ts_ms: now_unix_ms(),
host_kind: "ws".to_owned(),
host_id: format!("ws-{peer_id}"),
connected: true,
})
}
WsHubEvent::Hello { peer_id, client_kind, bundle_hash, reloaded_generation } => {
let mut acked_gen = reloaded_generation;
let cycle_info = st.last_cycle.as_ref().map(|c| (c.seq, c.generation, c.web_bundle_hash.clone()));
if let Some((_, cur_gen, ref web_hash)) = cycle_info {
let hash_matches = !bundle_hash.is_empty() && web_hash.as_deref() == Some(bundle_hash.as_str());
if hash_matches && acked_gen < cur_gen {
acked_gen = cur_gen;
}
if client_kind == "web" {
let mut satisfied = Vec::new();
for (&g, (cnt, _)) in st.pending_web_reloads.iter_mut() {
if acked_gen >= g {
*cnt = cnt.saturating_sub(1);
if *cnt == 0 { satisfied.push(g); }
}
}
for g in satisfied { st.pending_web_reloads.remove(&g); }
if reloaded_generation == 0 && st.pending_web_reloads.is_empty() && (hash_matches || web_hash.is_none()) {
acked_gen = acked_gen.max(cur_gen);
}
} else if reloaded_generation == 0 {
acked_gen = acked_gen.max(cur_gen);
}
}
let entry = st.ws_hosts.entry(peer_id).or_insert_with(|| WsHostEntry {
client_kind: client_kind.clone(),
bundle_hash: bundle_hash.clone(),
last_acked_gen: acked_gen,
last_ack_ok: true,
last_ack_ms: 0,
last_ack_detail: None,
});
entry.client_kind = client_kind.clone();
entry.bundle_hash = bundle_hash;
if acked_gen >= entry.last_acked_gen {
entry.last_acked_gen = acked_gen;
entry.last_ack_ok = true;
entry.last_ack_detail = None;
}
(acked_gen > 0).then(|| DevEvent::HostAck {
ts_ms: now_unix_ms(),
seq: cycle_info.map_or(0, |(s, _, _)| s),
generation: acked_gen,
host_kind: client_kind,
host_id: format!("ws-{peer_id}"),
ok: true,
applied: true,
applied_ms: 0,
detail: None,
})
}
WsHubEvent::ReloadAck { peer_id, generation, ok, applied, applied_ms, detail } => {
let eff_gen = if generation == 0 {
st.last_cycle.as_ref().map_or(0, |c| c.generation)
} else {
generation
};
let host_kind = if let Some(entry) = st.ws_hosts.get_mut(&peer_id) {
if eff_gen >= entry.last_acked_gen {
entry.last_acked_gen = eff_gen;
entry.last_ack_ok = ok;
entry.last_ack_ms = applied_ms;
entry.last_ack_detail = (!detail.is_empty()).then_some(detail.clone());
}
entry.client_kind.clone()
} else {
"ws".to_owned()
};
Some(DevEvent::HostAck {
ts_ms: now_unix_ms(),
seq: st.last_cycle.as_ref().map_or(0, |c| c.seq),
generation: eff_gen,
host_kind,
host_id: format!("ws-{peer_id}"),
ok,
applied,
applied_ms,
detail: (!detail.is_empty()).then_some(detail),
})
}
WsHubEvent::Disconnected { peer_id } => {
st.ws_hosts.remove(&peer_id).map(|removed| {
let cycle_info = st.last_cycle.as_ref().map(|c| (c.ok, c.generation, c.tier == "tier2"));
if let Some((true, cur_gen, is_tier2)) = cycle_info
&& removed.last_acked_gen < cur_gen
{
if removed.client_kind == "web" && is_tier2 {
let entry = st.pending_web_reloads.entry(cur_gen).or_insert((0, Instant::now()));
entry.0 += 1;
} else {
st.host_disconnect_err = Some((
cur_gen,
format!("{} host (ws-{peer_id}) disconnected before acking generation {cur_gen}", removed.client_kind),
));
}
}
DevEvent::HostConnection {
ts_ms: now_unix_ms(),
host_kind: removed.client_kind,
host_id: format!("ws-{peer_id}"),
connected: false,
}
})
}
}
};
if let Some(ev) = log_ev {
self.files.append_event(&ev);
}
self.cv.notify_all();
}
pub(crate) fn on_pair_event(&self, ev: PairDaemonEvent) {
let log_ev = {
let mut st = self.inner.lock().unwrap_or_else(|e| e.into_inner());
match ev {
PairDaemonEvent::PeerConnected { session_id } => {
st.pair_hosts.insert(
session_id,
PairHostEntry { last_acked_seq: 0, last_ack_status: 0, last_acked_gen: 0, last_ack_ms: 0 },
);
Some(DevEvent::HostConnection {
ts_ms: now_unix_ms(),
host_kind: "pair".to_owned(),
host_id: format!("pair-{session_id}"),
connected: true,
})
}
PairDaemonEvent::PeerDisconnected { session_id } => {
st.pair_hosts.remove(&session_id).map(|removed| {
if let Some(ref cycle) = st.last_cycle
&& cycle.ok
&& (!cycle.pair_done
|| cycle.pair_target_wire_seq.is_some_and(|t| removed.last_acked_seq < t))
{
let detail = match cycle.pair_target_wire_seq {
Some(t) => format!("paired peer-{session_id} disconnected before acking wire seq {t}"),
None => format!("paired peer-{session_id} disconnected during generation {}", cycle.generation),
};
st.host_disconnect_err = Some((cycle.generation, detail));
}
DevEvent::HostConnection {
ts_ms: now_unix_ms(),
host_kind: "pair".to_owned(),
host_id: format!("pair-{session_id}"),
connected: false,
}
})
}
PairDaemonEvent::ReloadApplied { generation, wire_seq } => {
if let Some(ref mut cycle) = st.last_cycle
&& cycle.generation == generation
{
cycle.pair_done = true;
cycle.pair_target_wire_seq = wire_seq;
}
None
}
PairDaemonEvent::ReloadFailed { generation, error } => {
let seq = st.last_cycle.as_ref().map_or(0, |c| c.seq);
if let Some(ref mut cycle) = st.last_cycle
&& cycle.generation == generation
{
cycle.pair_done = true;
cycle.pair_error = Some(error.clone());
}
Some(DevEvent::HostAck {
ts_ms: now_unix_ms(),
seq,
generation,
host_kind: "pair".to_owned(),
host_id: "pair-server".to_owned(),
ok: false,
applied: false,
applied_ms: 0,
detail: Some(error),
})
}
PairDaemonEvent::PeerFrameAck { session_id, acked_seq, status } => {
let cycle_meta = st.last_cycle.as_ref().map(|c| {
(c.seq, c.generation, c.pair_target_wire_seq, c.built_at.elapsed().as_millis() as u64)
});
let entry = st.pair_hosts.entry(session_id).or_insert(PairHostEntry {
last_acked_seq: 0,
last_ack_status: 0,
last_acked_gen: 0,
last_ack_ms: 0,
});
let prev_seq = entry.last_acked_seq;
if acked_seq >= entry.last_acked_seq {
entry.last_acked_seq = acked_seq;
entry.last_ack_status = status;
}
let ok = status == nativeview_wire::FRAME_ACK_STATUS_APPLIED;
let (seq, generation, target_seq, applied_ms) = cycle_meta.unwrap_or((0, 0, None, 0));
let newly_satisfied = target_seq.is_some_and(|t| acked_seq >= t && prev_seq < t);
if newly_satisfied {
entry.last_acked_gen = generation;
entry.last_ack_ms = applied_ms;
}
(!ok || newly_satisfied).then(|| DevEvent::HostAck {
ts_ms: now_unix_ms(),
seq,
generation,
host_kind: "pair".to_owned(),
host_id: format!("pair-{session_id}"),
ok,
applied: ok,
applied_ms,
detail: (!ok).then(|| format!("paired client decode error on wire seq {acked_seq}")),
})
}
}
};
if let Some(ev) = log_ev {
self.files.append_event(&ev);
}
self.cv.notify_all();
}
pub(crate) fn handle_request(&self, req: ControlRequest) -> ControlResponse {
match req {
ControlRequest::Status => {
let st = self.inner.lock().unwrap_or_else(|e| e.into_inner());
build_status_response(&st)
}
ControlRequest::Settle { paths, timeout_ms, wait_for, require_host } => {
self.handle_settle(paths, timeout_ms, wait_for, require_host)
}
}
}
fn handle_settle(
&self,
paths: Vec<PathBuf>,
timeout_ms: u64,
wait_for: WaitForMode,
require_host: bool,
) -> ControlResponse {
let (target_scan_epoch, outside) = {
let mut st = self.inner.lock().unwrap_or_else(|e| e.into_inner());
let mut outside_path = None;
for p in &paths {
let canon = crate::hot_diff::cache::canonicalize_preserving_missing(p);
if !st.watched_roots.iter().any(|root| canon.starts_with(root)) {
outside_path = Some((p.clone(), st.watched_roots.clone()));
break;
}
}
if let Some((bad, roots)) = outside_path {
(0, Some((bad, roots)))
} else {
st.next_scan_epoch += 1;
(st.next_scan_epoch, None)
}
};
if let Some((bad, roots)) = outside {
let watched_roots: Vec<String> = roots.iter().map(|r| r.display().to_string()).collect();
return make_error_resp(
"outside_watch_roots",
"tier3",
0,
0,
0,
Vec::new(),
watched_roots,
format!("'{}' is outside watched Rust roots; hot reload will not trigger for this file", bad.display()),
Some("Tier-3 host/runtime/ABI changes require rebuilding the host shell, or restart `nv dev` with `--watch <dir>`.".to_owned()),
);
}
let _ = self.trigger_tx.send(WatchTrigger::ForceScan { paths, target_scan_epoch });
let deadline = Instant::now() + Duration::from_millis(timeout_ms.clamp(50, 600_000));
let mut st = self.inner.lock().unwrap_or_else(|e| e.into_inner());
loop {
if st.scan_epoch >= target_scan_epoch
&& !st.in_flight
&& let Some(resp) = evaluate_settled(&st, wait_for, require_host)
{
return resp;
}
let now = Instant::now();
if now >= deadline {
return build_timeout_response(&st);
}
let wait_dur = (deadline - now).min(Duration::from_millis(100));
let (guard, _) = self.cv.wait_timeout(st, wait_dur).unwrap_or_else(|e| e.into_inner());
st = guard;
}
}
}