zng_ext_hot_reload/
lib.rs

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//!
4//! Hot reload service.
5//!
6//! # Crate
7//!
8#![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/// Declare hot reload entry.
45///
46/// Must be called at the root of the crate.
47///
48/// # Safety
49///
50/// Must be called only once at the hot-reload crate.
51#[macro_export]
52macro_rules! zng_hot_entry {
53    () => {
54        #[doc(hidden)] // used by proc-macro
55        pub use $crate::zng_hot_entry;
56
57        #[unsafe(no_mangle)] // SAFETY: docs instruct users to call the macro only once, name is unlikely to have collisions.
58        #[doc(hidden)] // used by lib loader
59        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)] // SAFETY: docs instruct users to call the macro only once, name is unlikely to have collisions.
69        #[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        // SAFETY: hot reload rebuilds in the same environment, so this is safe if the keys are strong enough.
114        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    /// Called on the static code (host).
129    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    /// Called on the dynamic code (dylib).
149    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                // println!("patched `{key:?}`");
155                // SAFETY: HOT_STATICS is defined using linkme, so all entries are defined by the hot_static! macro
156                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/// Status of a monitored dynamic library crate.
167#[derive(Clone, PartialEq, Debug)]
168#[non_exhaustive]
169pub struct HotStatus {
170    /// Dynamic library crate directory.
171    ///
172    /// Any file changes inside this directory triggers a rebuild.
173    pub manifest_dir: Txt,
174
175    /// Build start time if is rebuilding.
176    pub building: Option<DInstant>,
177
178    /// Last rebuild and reload result.
179    ///
180    /// is `Ok(build_duration)` or `Err(build_error)`.
181    pub last_build: Result<Duration, BuildError>,
182
183    /// Number of times the dynamically library was rebuilt (successfully or with error).
184    pub rebuild_count: usize,
185}
186impl HotStatus {
187    /// Gets the build time if the last build succeeded.
188    pub fn ok(&self) -> Option<Duration> {
189        self.last_build.as_ref().ok().copied()
190    }
191
192    /// If the last build was cancelled.
193    pub fn is_cancelled(&self) -> bool {
194        matches!(&self.last_build, Err(BuildError::Cancelled))
195    }
196
197    /// Gets the last build error if it failed and was not cancelled.
198    pub fn err(&self) -> Option<&BuildError> {
199        self.last_build.as_ref().err().filter(|e| !matches!(e, BuildError::Cancelled))
200    }
201}
202
203/// Hot reload app extension.
204///
205/// # Events
206///
207/// Events this extension provides.
208///
209/// * [`HOT_RELOAD_EVENT`]
210///
211/// # Services
212///
213/// Services this extension provides.
214///
215/// * [`HOT_RELOAD`]
216#[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        // watch all hot libraries.
224        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/// Arguments for custom rebuild runners.
321///
322/// See [`HOT_RELOAD.rebuilder`] for more details.
323///
324/// [`HOT_RELOAD.rebuilder`]: HOT_RELOAD::rebuilder
325#[derive(Clone, Debug, PartialEq)]
326#[non_exhaustive]
327pub struct BuildArgs {
328    /// Crate that changed.
329    pub manifest_dir: Txt,
330    /// Cancel signal.
331    ///
332    /// If the build cannot be cancelled or has already finished this signal must be ignored and
333    /// the normal result returned.
334    pub cancel_build: SignalOnce,
335}
336impl BuildArgs {
337    /// Calls `cargo build [--package {package}] --message-format json` and cancels it as soon as the dylib is rebuilt.
338    ///
339    /// Always returns `Some(_)`.
340    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    /// Calls `cargo build [--package {package}] --example {example} --message-format json` and cancels
352    /// it as soon as the dylib is rebuilt.
353    ///
354    /// Always returns `Some(_)`.
355    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    /// Calls `cargo build [--package {package}] --bin {bin}  --message-format json` and cancels it as
367    /// soon as the dylib is rebuilt.
368    ///
369    /// Always returns `Some(_)`.
370    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    /// Calls `cargo build --manifest-path {path} --message-format json` and cancels it as soon as the dylib is rebuilt.
382    ///
383    /// Always returns `Some(_)`.
384    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    /// Calls a custom command that must write to stdout the same way `cargo build --message-format json` does.
396    ///
397    /// The command will run until it writes the `"compiler-artifact"` for the `manifest_dir/Cargo.toml` to stdout, it will
398    /// then be killed.
399    ///
400    /// Always returns `Some(_)`.
401    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    /// Call a custom command defined in an environment var.
406    ///
407    /// The variable value must be arguments for `cargo`, that is `cargo $VAR`.
408    ///
409    /// See [`custom`] for other requirements of the command.
410    ///
411    /// If `var_key` is empty the default key `"ZNG_HOT_RELOAD_REBUILDER"` is used.
412    ///
413    /// Returns `None` if the var is not found or is set empty.
414    ///
415    /// [`custom`]: Self::custom
416    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    /// The default action.
434    ///
435    /// Tries `custom_env`, if env is not set, does `build(None)`.
436    ///
437    /// Always returns `Some(_)`.
438    pub fn default_build(&self) -> Option<RebuildVar> {
439        self.custom_env("").or_else(|| self.build(None))
440    }
441}
442
443/// Hot reload service.
444///
445/// # Provider
446///
447/// This service is provided by the [`HotReloadManager`] extension, it will panic if used in an app not extended.
448#[expect(non_camel_case_types)]
449pub struct HOT_RELOAD;
450impl HOT_RELOAD {
451    /// Hot reload status, libs that are rebuilding, errors.
452    pub fn status(&self) -> Var<Vec<HotStatus>> {
453        HOT_RELOAD_SV.read().status.read_only()
454    }
455
456    /// Register a handler that can override the hot library rebuild.
457    ///
458    /// The command should rebuild using the same features used to run the program (not just rebuild the dylib).
459    /// By default it is just `cargo build`, that works if the program was started using only `cargo run`, but
460    /// an example program needs a custom runner.
461    ///
462    /// If `rebuilder` wants to handle the rebuild it must return a response var that updates when the rebuild is finished with
463    /// the path to the rebuilt dylib. The [`BuildArgs`] also provides helper methods to rebuild common workspace setups.
464    ///
465    /// Note that unlike most services the `rebuilder` is registered immediately, not after an update cycle.
466    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    /// Request a rebuild, if `manifest_dir` is a hot library.
471    ///
472    /// Note that changes inside the directory already trigger a rebuild automatically.
473    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    /// Request a rebuild cancel for the current building `manifest_dir`.
479    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        // we never unload HotLib because hot nodes can pass &'static references (usually inside `Txt`) to the
496        // program that will remain being used after.
497        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    // mutex for Sync only
515    #[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            // copy dylib to not block the next rebuild
529            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            // cleanup previous session
535            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    /// Args for [`HOT_RELOAD_EVENT`].
584    pub struct HotReloadArgs {
585        /// Reloaded library.
586        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    /// Crate directory that changed and caused the rebuild.
597    pub fn manifest_dir(&self) -> &Txt {
598        self.lib.manifest_dir()
599    }
600}
601
602event! {
603    /// Event notifies when a new version of a hot reload dynamic library has finished rebuild and has loaded.
604    ///
605    /// This event is used internally by hot nodes to reinit.
606    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                // WATCHER debounce notifies immediately, then debounces. Some
619                // IDEs (VsCode) touch the saving file multiple times within
620                // the debounce interval, this causes two rebuild requests.
621                //
622                // So we only cancel rebuild if the second event (current) is not
623                // within debounce + a generous 34ms for the notification delay.
624                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/// Dynamically loaded library.
661#[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            // SAFETY: assuming the hot lib was setup as the docs instruct, this works,
683            // even the `linkme` stuff does not require any special care.
684            //
685            // If the hot lib developer add some "ctor/dtor" stuff and that fails they will probably
686            // know why, hot reloading should only run in dev machines.
687            let lib = libloading::Library::new(lib)?;
688
689            // SAFETY: thats the signature.
690            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    /// Lib identifier.
702    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        // SAFETY: lib is still loaded and will remain until all HotNodes are dropped.
709        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}