1#![doc(html_favicon_url = "https://zng-ui.github.io/res/zng-logo-icon.png")]
2#![doc(html_logo_url = "https://zng-ui.github.io/res/zng-logo.png")]
3#![doc = include_str!(concat!("../", std::env!("CARGO_PKG_README")))]
9#![warn(unused_extern_crates)]
10#![warn(missing_docs)]
11
12mod cargo;
13mod node;
14mod util;
15use std::{
16 collections::{HashMap, HashSet},
17 fmt, io, mem,
18 path::PathBuf,
19 sync::Arc,
20 time::Duration,
21};
22
23pub use cargo::BuildError;
24use node::*;
25
26use zng_app::{
27 APP, AppExtension, DInstant, INSTANT,
28 event::{event, event_args},
29 handler::async_clmv,
30 update::UPDATES,
31};
32use zng_app_context::{LocalContext, app_local};
33use zng_ext_fs_watcher::WATCHER;
34pub use zng_ext_hot_reload_proc_macros::hot_node;
35use zng_task::{SignalOnce, parking_lot::Mutex};
36use zng_txt::Txt;
37use zng_unique_id::hot_reload::HOT_STATICS;
38use zng_unit::TimeUnits as _;
39use zng_var::{ResponseVar, Var};
40
41#[doc(inline)]
42pub use zng_unique_id::{hot_static, hot_static_ref, lazy_static};
43
44#[macro_export]
52macro_rules! zng_hot_entry {
53 () => {
54 #[doc(hidden)] pub use $crate::zng_hot_entry;
56
57 #[unsafe(no_mangle)] #[doc(hidden)] pub extern "C" fn zng_hot_entry(
60 manifest_dir: &&str,
61 node_name: &&'static str,
62 ctx: &mut $crate::zng_hot_entry::LocalContext,
63 exchange: &mut $crate::HotEntryExchange,
64 ) {
65 $crate::zng_hot_entry::entry(manifest_dir, node_name, ctx, exchange)
66 }
67
68 #[unsafe(no_mangle)] #[doc(hidden)]
70 pub extern "C" fn zng_hot_entry_init(patch: &$crate::StaticPatch) {
71 $crate::zng_hot_entry::init(patch)
72 }
73 };
74}
75
76#[doc(hidden)]
77pub mod zng_hot_entry {
78 pub use crate::node::{HotNode, HotNodeArgs, HotNodeHost};
79 use crate::{HotEntryExchange, StaticPatch};
80 pub use zng_app_context::LocalContext;
81
82 pub struct HotNodeEntry {
83 pub manifest_dir: &'static str,
84 pub hot_node_name: &'static str,
85 pub hot_node_fn: fn(HotNodeArgs) -> HotNode,
86 }
87
88 #[linkme::distributed_slice]
89 pub static HOT_NODES: [HotNodeEntry];
90
91 pub fn entry(manifest_dir: &str, node_name: &'static str, ctx: &mut LocalContext, exchange: &mut HotEntryExchange) {
92 for entry in HOT_NODES.iter() {
93 if node_name == entry.hot_node_name && manifest_dir == entry.manifest_dir {
94 let args = match std::mem::replace(exchange, HotEntryExchange::Responding) {
95 HotEntryExchange::Request(args) => args,
96 _ => panic!("bad request"),
97 };
98 let node = ctx.with_context(|| (entry.hot_node_fn)(args));
99 *exchange = HotEntryExchange::Response(Some(node));
100 return;
101 }
102 }
103 *exchange = HotEntryExchange::Response(None);
104 }
105
106 pub fn init(statics: &StaticPatch) {
107 std::panic::set_hook(Box::new(|args| {
108 eprintln!("PANIC IN HOT LOADED LIBRARY, ABORTING");
109 crate::util::crash_handler(args);
110 zng_env::exit(101);
111 }));
112
113 unsafe { statics.apply() }
115 }
116}
117
118type StaticPatchersMap = HashMap<&'static dyn zng_unique_id::hot_reload::PatchKey, unsafe fn(*const ()) -> *const ()>;
119
120#[doc(hidden)]
121#[derive(Clone)]
122#[repr(C)]
123pub struct StaticPatch {
124 tracing: tracing_shared::SharedLogger,
125 entries: Arc<StaticPatchersMap>,
126}
127impl StaticPatch {
128 pub fn capture() -> Self {
130 let mut entries = StaticPatchersMap::with_capacity(HOT_STATICS.len());
131 for (key, val) in HOT_STATICS.iter() {
132 match entries.entry(*key) {
133 std::collections::hash_map::Entry::Vacant(e) => {
134 e.insert(*val);
135 }
136 std::collections::hash_map::Entry::Occupied(_) => {
137 panic!("repeated hot static key `{key:?}`");
138 }
139 }
140 }
141
142 Self {
143 entries: Arc::new(entries),
144 tracing: tracing_shared::SharedLogger::new(),
145 }
146 }
147
148 unsafe fn apply(&self) {
150 self.tracing.install();
151
152 for (key, patch) in HOT_STATICS.iter() {
153 if let Some(val) = self.entries.get(key) {
154 unsafe {
157 patch(val(std::ptr::null()));
158 }
159 } else {
160 eprintln!("did not find `{key:?}` to patch, static references may fail");
161 }
162 }
163 }
164}
165
166#[derive(Clone, PartialEq, Debug)]
168#[non_exhaustive]
169pub struct HotStatus {
170 pub manifest_dir: Txt,
174
175 pub building: Option<DInstant>,
177
178 pub last_build: Result<Duration, BuildError>,
182
183 pub rebuild_count: usize,
185}
186impl HotStatus {
187 pub fn ok(&self) -> Option<Duration> {
189 self.last_build.as_ref().ok().copied()
190 }
191
192 pub fn is_cancelled(&self) -> bool {
194 matches!(&self.last_build, Err(BuildError::Cancelled))
195 }
196
197 pub fn err(&self) -> Option<&BuildError> {
199 self.last_build.as_ref().err().filter(|e| !matches!(e, BuildError::Cancelled))
200 }
201}
202
203#[derive(Default)]
217pub struct HotReloadManager {
218 libs: HashMap<&'static str, WatchedLib>,
219 static_patch: Option<StaticPatch>,
220}
221impl AppExtension for HotReloadManager {
222 fn init(&mut self) {
223 let mut status = vec![];
225 for entry in crate::zng_hot_entry::HOT_NODES.iter() {
226 if let std::collections::hash_map::Entry::Vacant(e) = self.libs.entry(entry.manifest_dir) {
227 e.insert(WatchedLib::default());
228 WATCHER.watch_dir(entry.manifest_dir, true).perm();
229
230 status.push(HotStatus {
231 manifest_dir: entry.manifest_dir.into(),
232 building: None,
233 last_build: Ok(Duration::MAX),
234 rebuild_count: 0,
235 });
236 }
237 }
238 HOT_RELOAD_SV.read().status.set(status);
239 }
240
241 fn event_preview(&mut self, update: &mut zng_app::update::EventUpdate) {
242 if let Some(args) = zng_ext_fs_watcher::FS_CHANGES_EVENT.on(update) {
243 for (manifest_dir, watched) in self.libs.iter_mut() {
244 if args.changes_for_path(manifest_dir.as_ref()).next().is_some() {
245 watched.rebuild((*manifest_dir).into(), self.static_patch.get_or_insert_with(StaticPatch::capture));
246 }
247 }
248 }
249 }
250
251 fn update_preview(&mut self) {
252 for (manifest_dir, watched) in self.libs.iter_mut() {
253 if let Some(b) = &watched.building
254 && let Some(r) = b.rebuild_load.rsp()
255 {
256 let build_time = b.start_time.elapsed();
257 let mut lib = None;
258 let status_r = match r {
259 Ok(l) => {
260 lib = Some(l);
261 Ok(build_time)
262 }
263 Err(e) => {
264 if matches!(&e, BuildError::Cancelled) {
265 tracing::warn!("cancelled rebuild `{manifest_dir}`");
266 } else {
267 tracing::error!("failed rebuild `{manifest_dir}`, {e}");
268 }
269 Err(e)
270 }
271 };
272 if let Some(lib) = lib {
273 tracing::info!("rebuilt and reloaded `{manifest_dir}` in {build_time:?}");
274 HOT_RELOAD.set(lib.clone());
275 HOT_RELOAD_EVENT.notify(HotReloadArgs::now(lib));
276 }
277
278 watched.building = None;
279
280 let manifest_dir = *manifest_dir;
281 HOT_RELOAD_SV.read().status.modify(move |s| {
282 let s = s.iter_mut().find(|s| s.manifest_dir == manifest_dir).unwrap();
283 s.building = None;
284 s.last_build = status_r;
285 s.rebuild_count += 1;
286 });
287
288 if mem::take(&mut watched.rebuild_again) {
289 HOT_RELOAD_SV.write().rebuild_requests.push(manifest_dir.into());
290 }
291 }
292 }
293
294 let mut sv = HOT_RELOAD_SV.write();
295 let requests: HashSet<Txt> = sv.cancel_requests.drain(..).collect();
296 for r in requests {
297 if let Some(watched) = self.libs.get_mut(r.as_str())
298 && let Some(b) = &watched.building
299 {
300 b.cancel_build.set();
301 }
302 }
303
304 let requests: HashSet<Txt> = sv.rebuild_requests.drain(..).collect();
305 drop(sv);
306 for r in requests {
307 if let Some(watched) = self.libs.get_mut(r.as_str()) {
308 watched.rebuild(r, self.static_patch.get_or_insert_with(StaticPatch::capture));
309 } else {
310 tracing::error!("cannot rebuild `{r}`, unknown");
311 }
312 }
313 }
314}
315
316type RebuildVar = ResponseVar<Result<PathBuf, BuildError>>;
317
318type RebuildLoadVar = ResponseVar<Result<HotLib, BuildError>>;
319
320#[derive(Clone, Debug, PartialEq)]
326#[non_exhaustive]
327pub struct BuildArgs {
328 pub manifest_dir: Txt,
330 pub cancel_build: SignalOnce,
335}
336impl BuildArgs {
337 pub fn build(&self, package: Option<&str>) -> Option<RebuildVar> {
341 Some(cargo::build(
342 &self.manifest_dir,
343 "--package",
344 package.unwrap_or(""),
345 "",
346 "",
347 self.cancel_build.clone(),
348 ))
349 }
350
351 pub fn build_example(&self, package: Option<&str>, example: &str) -> Option<RebuildVar> {
356 Some(cargo::build(
357 &self.manifest_dir,
358 "--package",
359 package.unwrap_or(""),
360 "--example",
361 example,
362 self.cancel_build.clone(),
363 ))
364 }
365
366 pub fn build_bin(&self, package: Option<&str>, bin: &str) -> Option<RebuildVar> {
371 Some(cargo::build(
372 &self.manifest_dir,
373 "--package",
374 package.unwrap_or(""),
375 "--bin",
376 bin,
377 self.cancel_build.clone(),
378 ))
379 }
380
381 pub fn build_manifest(&self, path: &str) -> Option<RebuildVar> {
385 Some(cargo::build(
386 &self.manifest_dir,
387 "--manifest-path",
388 path,
389 "",
390 "",
391 self.cancel_build.clone(),
392 ))
393 }
394
395 pub fn custom(&self, cmd: std::process::Command) -> Option<RebuildVar> {
402 Some(cargo::build_custom(&self.manifest_dir, cmd, self.cancel_build.clone()))
403 }
404
405 pub fn custom_env(&self, mut var_key: &str) -> Option<RebuildVar> {
417 if var_key.is_empty() {
418 var_key = "ZNG_HOT_RELOAD_REBUILDER";
419 }
420
421 let custom = std::env::var(var_key).ok()?;
422 let mut custom = custom.split(' ');
423
424 let subcommand = custom.next()?;
425
426 let mut cmd = std::process::Command::new("cargo");
427 cmd.arg(subcommand);
428 cmd.args(custom);
429
430 self.custom(cmd)
431 }
432
433 pub fn default_build(&self) -> Option<RebuildVar> {
439 self.custom_env("").or_else(|| self.build(None))
440 }
441}
442
443#[expect(non_camel_case_types)]
449pub struct HOT_RELOAD;
450impl HOT_RELOAD {
451 pub fn status(&self) -> Var<Vec<HotStatus>> {
453 HOT_RELOAD_SV.read().status.read_only()
454 }
455
456 pub fn rebuilder(&self, rebuilder: impl FnMut(BuildArgs) -> Option<RebuildVar> + Send + 'static) {
467 HOT_RELOAD_SV.write().rebuilders.get_mut().push(Box::new(rebuilder));
468 }
469
470 pub fn rebuild(&self, manifest_dir: impl Into<Txt>) {
474 HOT_RELOAD_SV.write().rebuild_requests.push(manifest_dir.into());
475 UPDATES.update(None);
476 }
477
478 pub fn cancel(&self, manifest_dir: impl Into<Txt>) {
480 HOT_RELOAD_SV.write().cancel_requests.push(manifest_dir.into());
481 UPDATES.update(None);
482 }
483
484 pub(crate) fn lib(&self, manifest_dir: &'static str) -> Option<HotLib> {
485 HOT_RELOAD_SV
486 .read()
487 .libs
488 .iter()
489 .rev()
490 .find(|l| l.manifest_dir() == manifest_dir)
491 .cloned()
492 }
493
494 fn set(&self, lib: HotLib) {
495 HOT_RELOAD_SV.write().libs.push(lib);
498 }
499}
500app_local! {
501 static HOT_RELOAD_SV: HotReloadService = {
502 APP.extensions().require::<HotReloadManager>();
503 HotReloadService {
504 libs: vec![],
505 rebuilders: Mutex::new(vec![]),
506 status: zng_var::var(vec![]),
507 rebuild_requests: vec![],
508 cancel_requests: vec![],
509 }
510 };
511}
512struct HotReloadService {
513 libs: Vec<HotLib>,
514 #[expect(clippy::type_complexity)]
516 rebuilders: Mutex<Vec<Box<dyn FnMut(BuildArgs) -> Option<RebuildVar> + Send + 'static>>>,
517
518 status: Var<Vec<HotStatus>>,
519 rebuild_requests: Vec<Txt>,
520 cancel_requests: Vec<Txt>,
521}
522impl HotReloadService {
523 fn rebuild_reload(&mut self, manifest_dir: Txt, static_patch: &StaticPatch) -> (RebuildLoadVar, SignalOnce) {
524 let (rebuild, cancel) = self.rebuild(manifest_dir.clone());
525 let rebuild_load = zng_task::respond(async_clmv!(static_patch, {
526 let build_path = rebuild.wait_rsp().await?;
527
528 let file_name = match build_path.file_name() {
530 Some(f) => f.to_string_lossy(),
531 None => return Err(std::io::Error::new(std::io::ErrorKind::NotFound, "dylib path does not have a file name").into()),
532 };
533
534 for p in glob::glob(&format!("{}/zng-hot-{file_name}-*", build_path.parent().unwrap().display()))
536 .unwrap()
537 .flatten()
538 {
539 let _ = std::fs::remove_file(p);
540 }
541
542 let mut unique_path = build_path.clone();
543 let ts = std::time::SystemTime::now()
544 .duration_since(std::time::UNIX_EPOCH)
545 .unwrap()
546 .as_millis();
547 unique_path.set_file_name(format!("zng-hot-{file_name}-{ts:x}"));
548 std::fs::copy(&build_path, &unique_path)?;
549
550 let dylib = zng_task::wait(move || HotLib::new(&static_patch, manifest_dir, unique_path));
551 match zng_task::with_deadline(dylib, 10.secs()).await {
552 Ok(r) => r.map_err(Into::into),
553 Err(_) => Err(BuildError::Io(Arc::new(io::Error::new(
554 io::ErrorKind::TimedOut,
555 "hot dylib did not init after 10s",
556 )))),
557 }
558 }));
559 (rebuild_load, cancel)
560 }
561
562 fn rebuild(&mut self, manifest_dir: Txt) -> (RebuildVar, SignalOnce) {
563 for r in self.rebuilders.get_mut() {
564 let cancel = SignalOnce::new();
565 let args = BuildArgs {
566 manifest_dir: manifest_dir.clone(),
567 cancel_build: cancel.clone(),
568 };
569 if let Some(r) = r(args.clone()) {
570 return (r, cancel);
571 }
572 }
573 let cancel = SignalOnce::new();
574 let args = BuildArgs {
575 manifest_dir: manifest_dir.clone(),
576 cancel_build: cancel.clone(),
577 };
578 (args.default_build().unwrap(), cancel)
579 }
580}
581
582event_args! {
583 pub struct HotReloadArgs {
585 pub(crate) lib: HotLib,
587
588 ..
589
590 fn delivery_list(&self, list: &mut UpdateDeliveryList) {
591 list.search_all();
592 }
593 }
594}
595impl HotReloadArgs {
596 pub fn manifest_dir(&self) -> &Txt {
598 self.lib.manifest_dir()
599 }
600}
601
602event! {
603 pub static HOT_RELOAD_EVENT: HotReloadArgs;
607}
608
609#[derive(Default)]
610struct WatchedLib {
611 building: Option<BuildingLib>,
612 rebuild_again: bool,
613}
614impl WatchedLib {
615 fn rebuild(&mut self, manifest_dir: Txt, static_path: &StaticPatch) {
616 if let Some(b) = &self.building {
617 if b.start_time.elapsed() > WATCHER.debounce().get() + 34.ms() {
618 b.cancel_build.set();
625 self.rebuild_again = true;
626 }
627 } else {
628 let start_time = INSTANT.now();
629 tracing::info!("rebuilding `{manifest_dir}`");
630
631 let mut sv = HOT_RELOAD_SV.write();
632
633 let (rebuild_load, cancel_build) = sv.rebuild_reload(manifest_dir.clone(), static_path);
634 self.building = Some(BuildingLib {
635 start_time,
636 rebuild_load,
637 cancel_build,
638 });
639
640 sv.status.modify(move |s| {
641 s.iter_mut().find(|s| s.manifest_dir == manifest_dir).unwrap().building = Some(start_time);
642 });
643 }
644 }
645}
646
647struct BuildingLib {
648 start_time: DInstant,
649 rebuild_load: RebuildLoadVar,
650 cancel_build: SignalOnce,
651}
652
653#[doc(hidden)]
654pub enum HotEntryExchange {
655 Request(HotNodeArgs),
656 Responding,
657 Response(Option<HotNode>),
658}
659
660#[derive(Clone)]
662pub(crate) struct HotLib {
663 manifest_dir: Txt,
664 lib: Arc<libloading::Library>,
665 hot_entry: unsafe extern "C" fn(&&str, &&'static str, &mut LocalContext, &mut HotEntryExchange),
666}
667impl PartialEq for HotLib {
668 fn eq(&self, other: &Self) -> bool {
669 Arc::ptr_eq(&self.lib, &other.lib)
670 }
671}
672impl fmt::Debug for HotLib {
673 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
674 f.debug_struct("HotLib")
675 .field("manifest_dir", &self.manifest_dir)
676 .finish_non_exhaustive()
677 }
678}
679impl HotLib {
680 pub fn new(patch: &StaticPatch, manifest_dir: Txt, lib: impl AsRef<std::ffi::OsStr>) -> Result<Self, libloading::Error> {
681 unsafe {
682 let lib = libloading::Library::new(lib)?;
688
689 let init: unsafe extern "C" fn(&StaticPatch) = *lib.get(b"zng_hot_entry_init")?;
691 init(patch);
692
693 Ok(Self {
694 manifest_dir,
695 hot_entry: *lib.get(b"zng_hot_entry")?,
696 lib: Arc::new(lib),
697 })
698 }
699 }
700
701 pub fn manifest_dir(&self) -> &Txt {
703 &self.manifest_dir
704 }
705
706 pub fn instantiate(&self, hot_node_name: &'static str, ctx: &mut LocalContext, args: HotNodeArgs) -> Option<HotNode> {
707 let mut exchange = HotEntryExchange::Request(args);
708 unsafe { (self.hot_entry)(&self.manifest_dir.as_str(), &hot_node_name, ctx, &mut exchange) };
710 let mut node = match exchange {
711 HotEntryExchange::Response(n) => n,
712 _ => None,
713 };
714 if let Some(n) = &mut node {
715 n._lib = Some(self.lib.clone());
716 }
717 node
718 }
719}