cordis_loader/lib.rs
1//! Config-file driven plugin loader for
2//! [cordis-rs](https://crates.io/crates/cordis-rs).
3//!
4//! This crate is the assembly half of porting upstream Cordis' loader: it
5//! connects `cordis-include`'s entry trees to cordis fibers. Everything a
6//! config-driven cordis application needs is re-exported here — depend on
7//! `cordis-loader` alone.
8//!
9//! # How it works
10//!
11//! - **Static registry** ([`PluginRegistry`]) replaces upstream's dynamic
12//! `import(name)`: register plugins at startup, entries resolve by name.
13//! The `group` builtin is pre-registered. With the `dynamic` feature,
14//! names can also resolve to plugins compiled as dynamic libraries (see
15//! the [`dynamic`] module).
16//! - **Startup**: [`Loader::open`] reads the entry file (writing
17//! `initial` when missing), builds the [`EntryTree`], and starts every
18//! enabled entry — group entries as `cordis_group::Group` fibers, children
19//! beneath their parent group's context, so disposing a group cascades.
20//! - **Config**: entries carry a `cordis_include::Node` config (never `()`);
21//! loader plugins read it via `config.downcast::<Node>()`. `${{ env.X }}`
22//! templates expand at hand-off time; the file keeps the raw text.
23//! - **Reload** ([`Loader::reload`], wired to the `watch` feature):
24//! re-read the file, diff the tree, and reconcile fibers — created entries
25//! start, removed subtrees stop, moved entries restart under their new
26//! parent, entries whose plugin name / inject declaration / enabled flag
27//! changed stop and restart with their new options, and config-only
28//! changes patch in place via `Fiber::update_value`. A corrupt or
29//! unreadable main file fails the operation instead of silently booting
30//! an empty tree (import files keep a tolerant record-and-skip path).
31//! - **Inject**: an entry's `inject` list is merged into the plugin's own
32//! declaration, so the core fiber machinery reconciles entries when
33//! services come and go — "hot-swapped service restarts its dependents"
34//! for free.
35//! - **Self-kill vs. removal**: a fiber that reaches `Disposed` outside
36//! loader operation was killed by its own plugin; the loader persists
37//! `disabled: true` for that entry shortly after, deferred off the dying
38//! fiber's transition lock. Removing an entry from the file just stops
39//! it.
40//! - **Write-back**: [`Loader::update_config`] is the runtime entry point —
41//! it updates the fiber *and* persists the config. Reloads apply their
42//! patches without writing them back; only newly generated ids are
43//! persisted. `reload`, `update_config`, and `dispose` serialize through
44//! one operation lock (reentrant from event listeners), so a
45//! watch-thread reload cannot interleave with a plugin-thread
46//! `update_config`.
47//!
48//! # Example
49//!
50//! ```
51//! use cordis_loader::{Loader, LoaderConfig, PluginRegistry};
52//!
53//! let root = cordis::Context::new();
54//! let mut registry = PluginRegistry::new();
55//! // registry.register_plugin(my_plugin); // your plugins, by name
56//! let config = LoaderConfig::new("cordis.yml").with_registry(registry);
57//! let loader = Loader::open(&root, config)?;
58//! # assert!(loader.tree().entries().is_empty());
59//! # Ok::<(), cordis_loader::LoaderError>(())
60//! ```
61//!
62//! Register the plugins first (the `group` builtin is pre-registered), then
63//! open; plugins registered later via [`Loader::register_plugin`] are picked
64//! up by the next [`Loader::reload`].
65//!
66//! # Imports
67//!
68//! An entry with `name: import` and `config: { url: "…" }` mounts another
69//! config file as its subtree. Reloads compose every involved file into
70//! one tree (so diffs and id reuse work across files), while write-back
71//! decomposes: mounted children are persisted to the file they came from,
72//! never to the importing file. Import cycles are reported through
73//! [`Loader::last_error`] instead of recursing. With the `watch` feature,
74//! import files are watched like the main file.
75//!
76//! # Events and write coalescing
77//!
78//! Lifecycle transitions are observable through the [`events`] module's
79//! event names on the root context's bus; listener failures are recorded,
80//! never propagated. Write-backs can be debounced via
81//! [`LoaderConfig::with_write_debounce`] or
82//! [`Loader::set_write_debounce`]: rapid successive writes coalesce into
83//! one physical write after the quiet window.
84//!
85//! # Dynamic library plugins
86//!
87//! With the `dynamic` feature, plugins can be compiled as `cdylib`
88//! libraries and resolved from a directory instead of being registered
89//! statically:
90//!
91//! ```rust,ignore
92//! let registry = PluginRegistry::new().with_dynamic_dirs(["./plugins"]);
93//! ```
94//!
95//! A plugin library exports its implementation through
96//! [`dynamic::export_plugin!`] and must be built by the exact same
97//! toolchain, target, panic strategy, and cordis-rs version as the loading
98//! process — the loader verifies a build fingerprint before accepting the
99//! library. Libraries are never unloaded within a process; reloading a
100//! changed library is the worker-restart HMR flow implemented by
101//! `cordis-cli`.
102//!
103//! # Not in scope yet
104//!
105//! Isolate/service migration is future work.
106
107// `deny` instead of `forbid` because the `dynamic` feature wraps
108// libloading's unsafe primitives; every unsafe operation lives in that one
109// module, item-scoped behind `#[allow(unsafe_code)]` with SAFETY notes
110// (the same pattern cordis-cli uses for dotenv).
111#![deny(unsafe_code)]
112#![warn(missing_docs)]
113
114#[cfg(feature = "dynamic")]
115pub mod dynamic;
116pub mod error;
117pub mod events;
118pub mod loader;
119pub mod registry;
120
121pub use cordis_group::Group;
122pub use cordis_include::{Document, Entry, EntryOptions, EntryTree, LoaderFile, Node};
123pub use error::{LoaderError, Result};
124pub use loader::{Loader, LoaderConfig, LoaderHandle};
125pub use registry::PluginRegistry;
126
127/// Lock a mutex tolerantly, treating a poisoned lock as unlocked.
128pub(crate) fn lock<T>(mutex: &std::sync::Mutex<T>) -> std::sync::MutexGuard<'_, T> {
129 mutex.lock().unwrap_or_else(|error| error.into_inner())
130}