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#[derive(Debug, Clone)]
46pub struct PluginInfo {
47    /// Plugin's self-declared name (the manifest's `plugin.name`).
48    pub name: String,
49    /// Full crate name, such as `bmux-plugin-cargo`.
50    pub crate_name: String,
51    /// Version.
52    pub version: String,
53    /// Ecosystem family (a host field; may be empty).
54    pub family: Option<String>,
55    /// ABI version (a host field; may be empty).
56    pub abi: Option<u32>,
57    /// Install dir.
58    pub dir: PathBuf,
59    /// How it got installed.
60    pub source: InstallSource,
61}
62
63/// Generic plugin management library.
64///
65/// Build one and use it serially.
66pub struct CratePluginKit<T> {
67    cfg: KitConfig,
68    paths: KitPaths,
69    registry: Registry,
70    /// Crate names this process has `dlopen`ed. `uninstall` uses it to refuse
71    /// deleting a library that is in use.
72    loaded: RefCell<BTreeSet<String>>,
73    /// `fn() -> T` rather than `T`: does not pretend to own a `T`, and does not
74    /// require `T: Send/Sync`.
75    _host: PhantomData<fn() -> T>,
76}
77
78impl<T> CratePluginKit<T> {
79    /// Builds a kit instance from the config. Creates the data directories.
80    pub fn new(cfg: KitConfig) -> KitResult<Self> {
81        let paths = cfg.paths()?;
82        std::fs::create_dir_all(&paths.plugins)?;
83        std::fs::create_dir_all(&paths.build)?;
84
85        let registry = Registry::new(&cfg);
86
87        Ok(Self {
88            cfg,
89            paths,
90            registry,
91            loaded: RefCell::new(BTreeSet::new()),
92            _host: PhantomData,
93        })
94    }
95
96    /// Config.
97    pub fn config(&self) -> &KitConfig {
98        &self.cfg
99    }
100
101    /// The various paths.
102    pub fn paths(&self) -> &KitPaths {
103        &self.paths
104    }
105
106    /// Registry client.
107    pub fn registry(&self) -> &Registry {
108        &self.registry
109    }
110
111    // ---- internals -------------------------------------------------------
112
113    /// Takes the install lock. Only `install`, `update` and `uninstall` need it, which
114    /// is why it lives next to the record rather than on the public surface.
115    pub(super) fn lock(&self) -> KitResult<FileLock> {
116        FileLock::acquire(&self.paths.lock_file, self.cfg.lock_timeout)
117    }
118
119    /// Looks up the latest version when none was given.
120    ///
121    /// Shared with the `install` submodule, which is why it is not private.
122    pub(super) fn resolve_version(
123        &self,
124        crate_name: &str,
125        version: Option<&str>,
126    ) -> KitResult<String> {
127        if let Some(v) = version {
128            return Ok(v.to_string());
129        }
130        match self.registry.view(crate_name)? {
131            Some(info) if !info.version.is_empty() => Ok(info.version),
132            Some(_) => Err(KitError::Registry(format!(
133                "no usable version of {crate_name} in the registry"
134            ))),
135            None => Err(KitError::Registry(format!(
136                "{crate_name} was not found in the registry"
137            ))),
138        }
139    }
140
141    /// Writes one install into the record cache.
142    pub(super) fn record(&self, installed: &Installed) -> KitResult<()> {
143        let mut idx = Index::load(&self.paths.index_file);
144
145        let abi = PluginManifest::read(
146            &self
147                .paths
148                .manifest_path(&installed.crate_name, &self.cfg.manifest_name),
149        )
150        .ok()
151        .and_then(|m| m.plugin.abi);
152
153        idx.insert(
154            &installed.crate_name,
155            IndexEntry {
156                version: installed.version.clone(),
157                abi,
158                root: installed.dir.clone(),
159                source: installed.source,
160                installed_at: now_unix(),
161            },
162        );
163        idx.save(&self.paths.index_file)
164    }
165}
166
167#[cfg(test)]
168mod tests {
169    use super::*;
170    use std::path::Path;
171    use std::time::Duration;
172
173    /// A host ABI struct for tests.
174    ///
175    /// Its contents are arbitrary — this crate never reads a field of `T`, it only
176    /// casts the symbol to `*const T`.
177    #[repr(C)]
178    pub(super) struct FakeEntry {
179        abi_version: u32,
180    }
181
182    pub(super) const MANIFEST: &str = r#"
183[plugin]
184name    = "foo"
185version = "0.1.0"
186abi     = 1
187family  = "node"
188
189[detect]
190strong = ["fake.lock"]
191"#;
192
193    pub(super) fn kit(root: &Path) -> CratePluginKit<FakeEntry> {
194        let cfg = KitConfig::new("myapp")
195            .with_data_dir(root)
196            .with_lock_timeout(Duration::from_millis(500));
197        CratePluginKit::new(cfg).expect("should build")
198    }
199
200    /// Lays out an "installed" plugin directory by hand, skipping the compile step.
201    pub(super) fn place_plugin(root: &Path, crate_name: &str) -> PathBuf {
202        let dir = root.join("plugins").join(crate_name);
203        std::fs::create_dir_all(&dir).unwrap();
204        std::fs::write(dir.join("myapp-plugin.toml"), MANIFEST).unwrap();
205        dir
206    }
207
208    #[test]
209    fn new_creates_the_data_directories() {
210        let tmp = tempfile::tempdir().unwrap();
211        let root = tmp.path().join("store");
212
213        let k = kit(&root);
214        assert!(
215            k.paths().plugins.is_dir(),
216            "the plugins dir should have been created"
217        );
218        assert!(
219            k.paths().build.is_dir(),
220            "the build dir should have been created"
221        );
222    }
223
224    #[test]
225    fn config_is_exposed() {
226        let tmp = tempfile::tempdir().unwrap();
227        let k = kit(&tmp.path().join("store"));
228        assert_eq!(k.config().id, "myapp");
229        assert_eq!(k.config().crate_prefix, "myapp-plugin-");
230    }
231}