Skip to main content

crate_plugin_kit/
store.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
20use std::cell::RefCell;
21use std::collections::BTreeSet;
22use std::marker::PhantomData;
23use std::path::{Path, PathBuf};
24
25use crate::cache::{now_unix, Index, IndexEntry, InstallSource};
26use crate::config::{KitConfig, KitPaths};
27use crate::error::{KitError, KitResult};
28use crate::install::{self, build_host, prebuilt, Installed};
29use crate::loader::{self, LoadedPlugin};
30use crate::lock::FileLock;
31use crate::manifest::PluginManifest;
32use crate::registry::{CrateInfo, CrateSummary, Registry};
33
34/// An overview of one installed plugin.
35#[derive(Debug, Clone)]
36pub struct PluginInfo {
37    /// Plugin's self-declared name (the manifest's `plugin.name`).
38    pub name: String,
39    /// Full crate name, such as `bmux-plugin-cargo`.
40    pub crate_name: String,
41    /// Version.
42    pub version: String,
43    /// Ecosystem family (a host field; may be empty).
44    pub family: Option<String>,
45    /// ABI version (a host field; may be empty).
46    pub abi: Option<u32>,
47    /// Install dir.
48    pub dir: PathBuf,
49    /// How it got installed.
50    pub source: InstallSource,
51}
52
53/// Generic plugin management library.
54///
55/// Build one and use it serially.
56pub struct CratePluginKit<T> {
57    cfg: KitConfig,
58    paths: KitPaths,
59    registry: Registry,
60    /// Crate names this process has `dlopen`ed. `uninstall` uses it to refuse
61    /// deleting a library that is in use.
62    loaded: RefCell<BTreeSet<String>>,
63    /// `fn() -> T` rather than `T`: does not pretend to own a `T`, and does not
64    /// require `T: Send/Sync`.
65    _host: PhantomData<fn() -> T>,
66}
67
68impl<T> CratePluginKit<T> {
69    /// Builds a kit instance from the config. Creates the data directories.
70    pub fn new(cfg: KitConfig) -> KitResult<Self> {
71        let paths = cfg.paths()?;
72        std::fs::create_dir_all(&paths.plugins)?;
73        std::fs::create_dir_all(&paths.build)?;
74
75        let registry = Registry::new(&cfg);
76
77        Ok(Self {
78            cfg,
79            paths,
80            registry,
81            loaded: RefCell::new(BTreeSet::new()),
82            _host: PhantomData,
83        })
84    }
85
86    /// Config.
87    pub fn config(&self) -> &KitConfig {
88        &self.cfg
89    }
90
91    /// The various paths.
92    pub fn paths(&self) -> &KitPaths {
93        &self.paths
94    }
95
96    /// Registry client.
97    pub fn registry(&self) -> &Registry {
98        &self.registry
99    }
100
101    // ---- install / uninstall ----------------------------------------------
102
103    /// Installs a plugin.
104    ///
105    /// `name` may be a short name (`"cargo"`, to which [`KitConfig::crate_prefix`]
106    /// is prepended) or a full crate name. With `version` set to `None`, the latest
107    /// version is looked up on crates.io.
108    ///
109    /// # Errors
110    ///
111    /// - [`KitError::AlreadyInstalled`]: it is already installed. Use [`Self::update`]
112    ///   to replace it.
113    pub fn install(&self, name: &str, version: Option<&str>) -> KitResult<Installed> {
114        let crate_name = self.cfg.normalize_crate_name(name);
115
116        let _lock = self.lock()?;
117
118        let dir = self.paths.plugin_dir(&crate_name);
119        if dir.is_dir() {
120            return Err(KitError::AlreadyInstalled {
121                name: crate_name,
122                path: dir,
123            });
124        }
125
126        let version = self.resolve_version(&crate_name, version)?;
127        let installed = self.install_locked(&crate_name, &version)?;
128        self.record(&installed)?;
129        Ok(installed)
130    }
131
132    /// Updates (or reinstalls) a plugin. Replaces it if present, installs it if not.
133    pub fn update(&self, name: &str, version: Option<&str>) -> KitResult<Installed> {
134        let crate_name = self.cfg.normalize_crate_name(name);
135
136        let _lock = self.lock()?;
137
138        let version = self.resolve_version(&crate_name, version)?;
139        let installed = self.install_locked(&crate_name, &version)?;
140        self.record(&installed)?;
141        Ok(installed)
142    }
143
144    /// Uninstalls a plugin.
145    ///
146    /// # Errors
147    ///
148    /// - [`KitError::NotInstalled`]: it was not installed in the first place.
149    /// - [`KitError::PluginInUse`]: this process has loaded its library. A `.dll`
150    ///   that is currently `dlopen`ed cannot be deleted on Windows; on Linux the
151    ///   removal succeeds but the disk space is not reclaimed. Rather than gamble on
152    ///   it, ask the user to retry from a clean process.
153    pub fn uninstall(&self, name: &str) -> KitResult<()> {
154        let crate_name = self.cfg.normalize_crate_name(name);
155
156        let _lock = self.lock()?;
157
158        let dir = self.paths.plugin_dir(&crate_name);
159        if !dir.is_dir() {
160            return Err(KitError::NotInstalled { name: crate_name });
161        }
162
163        if self.loaded.borrow().contains(&crate_name) {
164            return Err(KitError::PluginInUse {
165                name: crate_name.clone(),
166            });
167        }
168
169        std::fs::remove_dir_all(&dir)?;
170
171        let mut idx = Index::load(&self.paths.index_file);
172        idx.remove(&crate_name);
173        idx.save(&self.paths.index_file)?;
174
175        Ok(())
176    }
177
178    // ---- queries ----------------------------------------------------------
179
180    /// Lists the installed plugins.
181    ///
182    /// The manifests on disk are authoritative; `.plugins.json` only supplies
183    /// information the manifest does not carry, such as the source and install time.
184    /// A lost cache therefore never hides a plugin.
185    pub fn list(&self) -> KitResult<Vec<PluginInfo>> {
186        let idx = Index::load(&self.paths.index_file);
187        let mut out = Vec::new();
188
189        let entries = match std::fs::read_dir(&self.paths.plugins) {
190            Ok(e) => e,
191            Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(out),
192            Err(e) => return Err(e.into()),
193        };
194
195        for entry in entries {
196            let entry = entry?;
197            if !entry.file_type()?.is_dir() {
198                continue;
199            }
200            let crate_name = entry.file_name().to_string_lossy().into_owned();
201
202            // The directory is there but the manifest is missing or broken: skip it,
203            // so one bad plugin cannot make the whole list fail
204            let manifest_path = entry.path().join(&self.cfg.manifest_name);
205            let Ok(manifest) = PluginManifest::read(&manifest_path) else {
206                continue;
207            };
208
209            let source = idx.get(&crate_name).map(|e| e.source).unwrap_or_default();
210
211            out.push(PluginInfo {
212                name: manifest.plugin.name.clone(),
213                crate_name,
214                version: manifest.plugin.version.clone(),
215                family: manifest.plugin.family.clone(),
216                abi: manifest.plugin.abi,
217                dir: entry.path(),
218                source,
219            });
220        }
221
222        out.sort_by(|a, b| a.crate_name.cmp(&b.crate_name));
223        Ok(out)
224    }
225
226    /// Reads the manifest of one plugin.
227    pub fn manifest_of(&self, name: &str) -> KitResult<PluginManifest> {
228        let crate_name = self.cfg.normalize_crate_name(name);
229        let path = self
230            .paths
231            .manifest_path(&crate_name, &self.cfg.manifest_name);
232        PluginManifest::read(&path)
233    }
234
235    /// Resolves a path relative to `name` into an absolute path.
236    pub fn resolve(&self, name: &str, relative: impl AsRef<Path>) -> PathBuf {
237        let crate_name = self.cfg.normalize_crate_name(name);
238        self.paths.plugin_dir(&crate_name).join(relative)
239    }
240
241    // ---- loading ----------------------------------------------------------
242
243    /// Loads a plugin and returns a `*const T`.
244    ///
245    /// Once loaded, [`Self::uninstall`] refuses to delete it until the process exits.
246    pub fn load(&self, name: &str) -> KitResult<LoadedPlugin<T>> {
247        let crate_name = self.cfg.normalize_crate_name(name);
248
249        let manifest = self.manifest_of(&crate_name)?;
250        let dir = self.paths.plugin_dir(&crate_name);
251        let stem = manifest.effective_lib_stem(&self.cfg, &crate_name);
252        let lib_path = loader::find_library(&dir, &stem)?;
253
254        // SAFETY: `lib_path` was installed by this kit; whether the layout of `T`
255        // matches the struct it exports is covered by the host's abi_version field —
256        // that is the host contract crate's job, not this crate's.
257        let plugin = unsafe { loader::open::<T>(&lib_path, &self.cfg.entry_symbol)? };
258
259        self.loaded.borrow_mut().insert(crate_name);
260        Ok(plugin)
261    }
262
263    // ---- registry --------------------------------------------------------
264
265    /// Searches for crates.
266    pub fn search(&self, keyword: &str, limit: usize) -> KitResult<Vec<CrateSummary>> {
267        self.registry.search(keyword, limit)
268    }
269
270    /// Looks up a crate by exact name.
271    pub fn view(&self, name: &str) -> KitResult<Option<CrateInfo>> {
272        let crate_name = self.cfg.normalize_crate_name(name);
273        self.registry.view(&crate_name)
274    }
275
276    // ---- internals -------------------------------------------------------
277
278    fn lock(&self) -> KitResult<FileLock> {
279        FileLock::acquire(&self.paths.lock_file, self.cfg.lock_timeout)
280    }
281
282    /// Looks up the latest version when none was given.
283    fn resolve_version(&self, crate_name: &str, version: Option<&str>) -> KitResult<String> {
284        if let Some(v) = version {
285            return Ok(v.to_string());
286        }
287        match self.registry.view(crate_name)? {
288            Some(info) if !info.version.is_empty() => Ok(info.version),
289            Some(_) => Err(KitError::Registry(format!(
290                "no usable version of {crate_name} in the registry"
291            ))),
292            None => Err(KitError::Registry(format!(
293                "{crate_name} was not found in the registry"
294            ))),
295        }
296    }
297
298    /// The actual install. The caller must already hold the lock.
299    fn install_locked(&self, crate_name: &str, version: &str) -> KitResult<Installed> {
300        // Clear the old directory first (the update path)
301        install::remove_dir_if_exists(&self.paths.plugin_dir(crate_name))?;
302
303        if self.cfg.prefer_prebuilt {
304            match prebuilt::try_install(&self.cfg, &self.paths, &self.registry, crate_name, version)
305            {
306                Ok(Some(installed)) => return Ok(installed),
307                // No prebuilt asset — this is exactly the signal to fall back to
308                // build-host
309                Ok(None) => {}
310                // Broken network or a corrupt asset: fall back as well. build-host
311                // goes through cargo, which is a different route from GitHub and may
312                // well work.
313                Err(_) => {}
314            }
315        }
316
317        build_host::install(&self.cfg, &self.paths, crate_name, version)
318    }
319
320    fn record(&self, installed: &Installed) -> KitResult<()> {
321        let mut idx = Index::load(&self.paths.index_file);
322
323        let abi = PluginManifest::read(
324            &self
325                .paths
326                .manifest_path(&installed.crate_name, &self.cfg.manifest_name),
327        )
328        .ok()
329        .and_then(|m| m.plugin.abi);
330
331        idx.insert(
332            &installed.crate_name,
333            IndexEntry {
334                version: installed.version.clone(),
335                abi,
336                root: installed.dir.clone(),
337                source: installed.source,
338                installed_at: now_unix(),
339            },
340        );
341        idx.save(&self.paths.index_file)
342    }
343}
344
345#[cfg(test)]
346mod tests {
347    use super::*;
348    use std::time::Duration;
349
350    /// A host ABI struct for tests.
351    ///
352    /// Its contents are arbitrary — this crate never reads a field of `T`, it only
353    /// casts the symbol to `*const T`.
354    #[repr(C)]
355    struct FakeEntry {
356        abi_version: u32,
357    }
358
359    const MANIFEST: &str = r#"
360[plugin]
361name    = "foo"
362version = "0.1.0"
363abi     = 1
364family  = "node"
365
366[detect]
367strong = ["fake.lock"]
368"#;
369
370    fn kit(root: &Path) -> CratePluginKit<FakeEntry> {
371        let cfg = KitConfig::new("myapp")
372            .with_data_dir(root)
373            .with_lock_timeout(Duration::from_millis(500));
374        CratePluginKit::new(cfg).expect("should build")
375    }
376
377    /// Lays out an "installed" plugin directory by hand, skipping the compile step.
378    fn place_plugin(root: &Path, crate_name: &str) -> PathBuf {
379        let dir = root.join("plugins").join(crate_name);
380        std::fs::create_dir_all(&dir).unwrap();
381        std::fs::write(dir.join("myapp-plugin.toml"), MANIFEST).unwrap();
382        dir
383    }
384
385    #[test]
386    fn new_creates_the_data_directories() {
387        let tmp = tempfile::tempdir().unwrap();
388        let root = tmp.path().join("store");
389
390        let k = kit(&root);
391        assert!(
392            k.paths().plugins.is_dir(),
393            "the plugins dir should have been created"
394        );
395        assert!(
396            k.paths().build.is_dir(),
397            "the build dir should have been created"
398        );
399    }
400
401    #[test]
402    fn a_fresh_store_lists_nothing() {
403        let tmp = tempfile::tempdir().unwrap();
404        let k = kit(&tmp.path().join("store"));
405        assert!(k.list().unwrap().is_empty());
406    }
407
408    /// When the directory does not exist at all, `list` still returns an empty list
409    /// instead of an error.
410    #[test]
411    fn list_tolerates_a_missing_plugins_directory() {
412        let tmp = tempfile::tempdir().unwrap();
413        let root = tmp.path().join("store");
414        let k = kit(&root);
415
416        std::fs::remove_dir_all(&root).unwrap();
417        assert!(k.list().unwrap().is_empty());
418    }
419
420    /// Key behavior: the manifest on disk is the source of truth, not
421    /// `.plugins.json`. A plugin placed by hand (with no cache entry) must still be
422    /// listed.
423    #[test]
424    fn list_reads_manifests_from_disk_not_the_cache() {
425        let tmp = tempfile::tempdir().unwrap();
426        let root = tmp.path().join("store");
427        let k = kit(&root);
428
429        place_plugin(&root, "myapp-plugin-foo");
430
431        let all = k.list().unwrap();
432        assert_eq!(all.len(), 1, "the cache is empty but the disk has a plugin");
433        let info = &all[0];
434        assert_eq!(info.name, "foo");
435        assert_eq!(info.crate_name, "myapp-plugin-foo");
436        assert_eq!(info.version, "0.1.0");
437        assert_eq!(info.abi, Some(1));
438        assert_eq!(info.family.as_deref(), Some("node"));
439        // No cache entry → falls back to the default source
440        assert_eq!(info.source, InstallSource::BuildHost);
441    }
442
443    /// A broken manifest must not fail the whole `list()` — skipping it is enough.
444    #[test]
445    fn list_skips_a_directory_with_a_broken_manifest() {
446        let tmp = tempfile::tempdir().unwrap();
447        let root = tmp.path().join("store");
448        let k = kit(&root);
449
450        place_plugin(&root, "myapp-plugin-good");
451        let bad = root.join("plugins").join("myapp-plugin-bad");
452        std::fs::create_dir_all(&bad).unwrap();
453        std::fs::write(bad.join("myapp-plugin.toml"), "this is not toml").unwrap();
454
455        // A directory that does not even have a manifest
456        let empty = root.join("plugins").join("myapp-plugin-empty");
457        std::fs::create_dir_all(&empty).unwrap();
458
459        let all = k.list().unwrap();
460        assert_eq!(all.len(), 1, "only the good one should be listed: {all:?}");
461        assert_eq!(all[0].crate_name, "myapp-plugin-good");
462    }
463
464    #[test]
465    fn list_is_sorted_by_crate_name() {
466        let tmp = tempfile::tempdir().unwrap();
467        let root = tmp.path().join("store");
468        let k = kit(&root);
469
470        for name in ["myapp-plugin-c", "myapp-plugin-a", "myapp-plugin-b"] {
471            place_plugin(&root, name);
472        }
473
474        let names: Vec<_> = k
475            .list()
476            .unwrap()
477            .into_iter()
478            .map(|i| i.crate_name)
479            .collect();
480        assert_eq!(
481            names,
482            vec!["myapp-plugin-a", "myapp-plugin-b", "myapp-plugin-c"]
483        );
484    }
485
486    #[test]
487    fn manifest_of_reads_the_plugin() {
488        let tmp = tempfile::tempdir().unwrap();
489        let root = tmp.path().join("store");
490        let k = kit(&root);
491        place_plugin(&root, "myapp-plugin-foo");
492
493        let m = k
494            .manifest_of("foo")
495            .expect("the short name should work too");
496        assert_eq!(m.plugin.name, "foo");
497        assert!(m.extra.contains_key("detect"), "the host's section is kept");
498    }
499
500    #[test]
501    fn manifest_of_reports_a_missing_plugin() {
502        let tmp = tempfile::tempdir().unwrap();
503        let k = kit(&tmp.path().join("store"));
504        assert!(matches!(
505            k.manifest_of("nope"),
506            Err(KitError::ManifestRead { .. })
507        ));
508    }
509
510    #[test]
511    fn uninstall_reports_a_plugin_that_is_not_installed() {
512        let tmp = tempfile::tempdir().unwrap();
513        let k = kit(&tmp.path().join("store"));
514
515        assert!(matches!(
516            k.uninstall("nope"),
517            Err(KitError::NotInstalled { .. })
518        ));
519    }
520
521    #[test]
522    fn uninstall_removes_the_directory() {
523        let tmp = tempfile::tempdir().unwrap();
524        let root = tmp.path().join("store");
525        let k = kit(&root);
526        let dir = place_plugin(&root, "myapp-plugin-foo");
527
528        assert!(dir.is_dir());
529        k.uninstall("foo").expect("should uninstall");
530        assert!(!dir.exists(), "the directory should have been deleted");
531        assert!(k.list().unwrap().is_empty());
532    }
533
534    /// `install` does not overwrite an existing installation — use `update` to
535    /// replace it.
536    ///
537    /// The check happens after the lock is taken and before any network or compile
538    /// work, so the test needs no network access.
539    #[test]
540    fn install_refuses_when_already_installed() {
541        let tmp = tempfile::tempdir().unwrap();
542        let root = tmp.path().join("store");
543        let k = kit(&root);
544        place_plugin(&root, "myapp-plugin-foo");
545
546        match k.install("foo", Some("0.1.0")) {
547            Err(KitError::AlreadyInstalled { name, .. }) => {
548                assert_eq!(name, "myapp-plugin-foo")
549            }
550            other => panic!("expected AlreadyInstalled, got {other:?}"),
551        }
552    }
553
554    #[test]
555    fn resolve_points_into_the_plugin_directory() {
556        let tmp = tempfile::tempdir().unwrap();
557        let root = tmp.path().join("store");
558        let k = kit(&root);
559
560        assert_eq!(
561            k.resolve("foo", "extra.txt"),
562            root.join("plugins")
563                .join("myapp-plugin-foo")
564                .join("extra.txt")
565        );
566        // The short and the full name must land in the same place
567        assert_eq!(k.resolve("foo", "x"), k.resolve("myapp-plugin-foo", "x"));
568    }
569
570    #[test]
571    fn config_is_exposed() {
572        let tmp = tempfile::tempdir().unwrap();
573        let k = kit(&tmp.path().join("store"));
574        assert_eq!(k.config().id, "myapp");
575        assert_eq!(k.config().crate_prefix, "myapp-plugin-");
576    }
577}