Skip to main content

crate_plugin_kit/store/
mod.rs

1//! [`CratePluginKit`]: the facade of this crate.
2//!
3//! # The generic parameter `T`
4//!
5//! `T` is the host's own `#[repr(C)]` entry struct. This crate does not use any of
6//! its fields — it only appears in the return type of [`CratePluginKit::load`], to
7//! turn the symbol `dlopen` produced into a thin pointer `*const T`.
8//!
9//! That removes the "type erasure → restore" layer: there is no conversion of a fat
10//! pointer between two vtables, and therefore no UB of that kind.
11//!
12//! # Thread safety
13//!
14//! [`CratePluginKit`] holds a `RefCell` recording which plugins this process has
15//! loaded (used by [`CratePluginKit::uninstall`] to refuse deleting a library that
16//! is in use). It is therefore not `Sync` — build one per process and use it
17//! serially (which is what a CLI does). To go concurrent, give each thread its own
18//! kit in its own scope.
19//!
20//! # Layout
21//!
22//! The struct, its construction and its accessors are here. The methods that make up
23//! the API surface are split by concern into the private `install` submodule (install /
24//! update / uninstall), `list` (queries) and `load` (`dlopen`), which build the same
25//! `impl` block.
26
27use std::cell::RefCell;
28use std::collections::BTreeSet;
29use std::marker::PhantomData;
30use std::path::PathBuf;
31
32use crate::cache::{now_unix, Index, IndexEntry, InstallSource};
33use crate::config::{KitConfig, KitPaths};
34use crate::error::{KitError, KitResult};
35use crate::install::Installed;
36use crate::lock::FileLock;
37use crate::manifest::PluginManifest;
38use crate::registry::Registry;
39
40pub(super) mod install;
41pub(super) mod list;
42pub(super) mod load;
43
44/// An overview of one installed plugin.
45///
46/// This is what the kit read from the manifest while listing the plugin directory. It
47/// carries the fields the kit itself understands, plus [`PluginInfo::extra`] — every
48/// other section, exactly as written — so a host can read its own sections from the
49/// same read instead of opening the manifest a second time.
50#[derive(Debug, Clone)]
51pub struct PluginInfo {
52    /// Plugin's self-declared name (the manifest's `plugin.name`).
53    pub name: String,
54    /// Full crate name, such as `bmux-plugin-cargo`.
55    pub crate_name: String,
56    /// Version.
57    pub version: String,
58    /// Ecosystem family (a host field; may be empty).
59    pub family: Option<String>,
60    /// ABI version (a host field; may be empty).
61    pub abi: Option<u32>,
62    /// Install dir.
63    pub dir: PathBuf,
64    /// How it got installed.
65    pub source: InstallSource,
66
67    /// Every top-level section the kit does not interpret, verbatim.
68    ///
69    /// A host's own sections live here: `[detect]`, `[context]`, and anything else it
70    /// defines. The kit neither reads nor validates them — it only carries them through,
71    /// which is what lets a host keep its manifest vocabulary while the kit stays
72    /// host-agnostic.
73    pub extra: toml::Table,
74}
75
76/// Generic plugin management library.
77///
78/// Build one and use it serially.
79pub struct CratePluginKit<T> {
80    cfg: KitConfig,
81    paths: KitPaths,
82    registry: Registry,
83    /// Crate names this process has `dlopen`ed. `uninstall` uses it to refuse
84    /// deleting a library that is in use.
85    loaded: RefCell<BTreeSet<String>>,
86    /// `fn() -> T` rather than `T`: does not pretend to own a `T`, and does not
87    /// require `T: Send/Sync`.
88    _host: PhantomData<fn() -> T>,
89}
90
91impl<T> CratePluginKit<T> {
92    /// Builds a kit instance from the config. Creates the data directories.
93    pub fn new(cfg: KitConfig) -> KitResult<Self> {
94        let paths = cfg.paths()?;
95        std::fs::create_dir_all(&paths.plugins)?;
96        std::fs::create_dir_all(&paths.build)?;
97
98        let registry = Registry::new(&cfg);
99
100        Ok(Self {
101            cfg,
102            paths,
103            registry,
104            loaded: RefCell::new(BTreeSet::new()),
105            _host: PhantomData,
106        })
107    }
108
109    /// Config.
110    pub fn config(&self) -> &KitConfig {
111        &self.cfg
112    }
113
114    /// The various paths.
115    pub fn paths(&self) -> &KitPaths {
116        &self.paths
117    }
118
119    /// Registry client.
120    pub fn registry(&self) -> &Registry {
121        &self.registry
122    }
123
124    // ---- internals -------------------------------------------------------
125
126    /// Takes the install lock. Only `install`, `update` and `uninstall` need it, which
127    /// is why it lives next to the record rather than on the public surface.
128    pub(super) fn lock(&self) -> KitResult<FileLock> {
129        FileLock::acquire(&self.paths.lock_file, self.cfg.lock_timeout)
130    }
131
132    /// Looks up the latest version when none was given.
133    ///
134    /// Shared with the `install` submodule, which is why it is not private.
135    pub(super) fn resolve_version(
136        &self,
137        crate_name: &str,
138        version: Option<&str>,
139    ) -> KitResult<String> {
140        if let Some(v) = version {
141            return Ok(v.to_string());
142        }
143        match self.registry.view(crate_name)? {
144            Some(info) if !info.version.is_empty() => Ok(info.version),
145            Some(_) => Err(KitError::Registry(format!(
146                "no usable version of {crate_name} in the registry"
147            ))),
148            None => Err(KitError::Registry(format!(
149                "{crate_name} was not found in the registry"
150            ))),
151        }
152    }
153
154    /// Writes one install into the record cache.
155    pub(super) fn record(&self, installed: &Installed) -> KitResult<()> {
156        let mut idx = Index::load(&self.paths.index_file);
157
158        let abi = PluginManifest::read(
159            &self
160                .paths
161                .manifest_path(&installed.crate_name, &self.cfg.manifest_name),
162        )
163        .ok()
164        .and_then(|m| m.plugin.abi);
165
166        idx.insert(
167            &installed.crate_name,
168            IndexEntry {
169                version: installed.version.clone(),
170                abi,
171                root: installed.dir.clone(),
172                source: installed.source.clone(),
173                installed_at: now_unix(),
174            },
175        );
176        idx.save(&self.paths.index_file)
177    }
178}
179
180#[cfg(test)]
181mod tests {
182    use super::*;
183    use std::path::Path;
184    use std::time::Duration;
185
186    /// A host ABI struct for tests.
187    ///
188    /// Its contents are arbitrary — this crate never reads a field of `T`, it only
189    /// casts the symbol to `*const T`.
190    #[repr(C)]
191    pub(super) struct FakeEntry {
192        abi_version: u32,
193    }
194
195    pub(super) const MANIFEST: &str = r#"
196[plugin]
197name    = "foo"
198version = "0.1.0"
199abi     = 1
200family  = "node"
201
202[detect]
203strong = ["fake.lock"]
204"#;
205
206    pub(super) fn kit(root: &Path) -> CratePluginKit<FakeEntry> {
207        let cfg = KitConfig::new("myapp")
208            .with_data_dir(root)
209            .with_lock_timeout(Duration::from_millis(500));
210        CratePluginKit::new(cfg).expect("should build")
211    }
212
213    /// Lays out an "installed" plugin directory by hand, skipping the compile step.
214    pub(super) fn place_plugin(root: &Path, crate_name: &str) -> PathBuf {
215        let dir = root.join("plugins").join(crate_name);
216        std::fs::create_dir_all(&dir).unwrap();
217        std::fs::write(dir.join("myapp-plugin.toml"), MANIFEST).unwrap();
218        dir
219    }
220
221    #[test]
222    fn new_creates_the_data_directories() {
223        let tmp = tempfile::tempdir().unwrap();
224        let root = tmp.path().join("store");
225
226        let k = kit(&root);
227        assert!(
228            k.paths().plugins.is_dir(),
229            "the plugins dir should have been created"
230        );
231        assert!(
232            k.paths().build.is_dir(),
233            "the build dir should have been created"
234        );
235    }
236
237    #[test]
238    fn config_is_exposed() {
239        let tmp = tempfile::tempdir().unwrap();
240        let k = kit(&tmp.path().join("store"));
241        assert_eq!(k.config().id, "myapp");
242        assert_eq!(k.config().crate_prefix, "myapp-plugin-");
243    }
244}