Skip to main content

crate_plugin_kit/
error.rs

1//! Error types.
2//!
3//! `anyhow::Error` is deliberately kept out of the public API: this crate is used
4//! by hosts right at the `dlopen` boundary, where an enumerable, matchable error
5//! type is far easier to diagnose than a type-erased one. The internals (the
6//! `install` module) use anyhow for convenience and convert at the exit points.
7
8use std::path::PathBuf;
9
10/// Errors produced by the kit.
11///
12/// The variants fall into two groups:
13///
14/// - Caller-actionable: [`KitError::NotInstalled`] / [`KitError::AlreadyInstalled`] /
15///   [`KitError::PluginInUse`] / [`KitError::CargoNotFound`] — the caller usually
16///   takes another route or prompts the user;
17/// - Broken environment or data: everything else. These can only be reported.
18#[derive(Debug, thiserror::Error)]
19pub enum KitError {
20    /// The plugin to uninstall or update is not installed.
21    #[error("plugin {name} is not installed")]
22    NotInstalled {
23        /// Full crate name.
24        name: String,
25    },
26
27    /// The plugin to install is already present.
28    ///
29    /// `install` never overwrites an existing installation; use `update` to replace it.
30    #[error("directory for plugin {name} already exists: {path}")]
31    AlreadyInstalled {
32        /// Full crate name.
33        name: String,
34        /// The existing directory.
35        path: PathBuf,
36    },
37
38    /// The plugin's dynamic library is still loaded in this process, so it cannot be deleted.
39    ///
40    /// A `.dll` that is currently `dlopen`ed cannot be removed on Windows; on
41    /// Linux/macOS the removal succeeds but the disk space is not reclaimed. Rather
42    /// than gamble on it, ask the user to retry from a clean process.
43    #[error(
44        "the dynamic library of plugin {name} is still loaded in this process and cannot be \
45         deleted. Retry in a new terminal (a new process does not load it), or exit the \
46         current session and try again"
47    )]
48    PluginInUse {
49        /// Full crate name.
50        name: String,
51    },
52
53    /// Reading the manifest file failed.
54    #[error("failed to read manifest ({path}): {source}")]
55    ManifestRead {
56        /// Manifest path.
57        path: PathBuf,
58        /// Underlying IO error.
59        #[source]
60        source: std::io::Error,
61    },
62
63    /// The manifest is not valid TOML, or a field has the wrong type.
64    #[error("failed to parse manifest ({path}): {source}")]
65    ManifestParse {
66        /// Manifest path.
67        path: PathBuf,
68        /// Underlying TOML error.
69        #[source]
70        source: Box<toml::de::Error>,
71    },
72
73    /// A required field in the manifest is missing or empty.
74    #[error("manifest is missing field `{field}` ({path})")]
75    ManifestMissingField {
76        /// Field name, e.g. `plugin.name`.
77        field: String,
78        /// Manifest path.
79        path: PathBuf,
80    },
81
82    /// No dynamic library matching the naming rules was found in the install dir.
83    #[error("could not find the dynamic library of plugin {name}; tried: {tried}")]
84    LibraryNotFound {
85        /// File name stem.
86        name: String,
87        /// The file names that were tried, comma-separated.
88        tried: String,
89    },
90
91    /// `dlopen` itself failed (corrupt file, wrong architecture, missing dependencies).
92    #[error("failed to load the dynamic library ({path}): {source}")]
93    LibraryLoad {
94        /// Dynamic library path.
95        path: PathBuf,
96        /// Underlying libloading error.
97        #[source]
98        source: Box<libloading::Error>,
99    },
100
101    /// The library loaded, but it does not export the symbol we look for.
102    ///
103    /// Usually means the wrong thing was installed — e.g. a plain library placed in
104    /// the plugin directory.
105    #[error("the dynamic library does not export symbol `{symbol}`")]
106    SymbolMissing {
107        /// The missing symbol name.
108        symbol: String,
109    },
110
111    /// The plugin's entry function returned a null pointer.
112    #[error("the plugin's entry function returned a null pointer")]
113    NullEntry,
114
115    /// Timed out waiting for the install lock.
116    #[error("timed out waiting for the file lock ({path}, waited {secs}s)")]
117    LockTimeout {
118        /// Lock file path.
119        path: PathBuf,
120        /// How many seconds were spent waiting.
121        secs: u64,
122    },
123
124    /// An operation on the lock file itself failed.
125    #[error("file lock operation failed ({path}): {source}")]
126    LockIo {
127        /// Lock file path.
128        path: PathBuf,
129        /// Underlying IO error.
130        #[source]
131        source: std::io::Error,
132    },
133
134    /// No `cargo` on `PATH`, so build-host installation is unavailable.
135    ///
136    /// The caller can use this to tell the user to install a Rust toolchain, or to
137    /// fall back to prebuilt.
138    #[error("could not find `cargo` on PATH; build-host installation needs a Rust toolchain")]
139    CargoNotFound,
140
141    /// `cargo build` failed. stderr has already been passed through to the user
142    /// (stdio is inherited).
143    #[error("build-host compilation failed ({})", describe_code(.code))]
144    BuildFailed {
145        /// Process exit code. `None` when the process was killed by a signal.
146        code: Option<i32>,
147    },
148
149    /// The build succeeded, but there is no cdylib among its artifacts.
150    #[error("no cdylib among the build artifacts (looked for {stem} in {dir})")]
151    BuildArtifactMissing {
152        /// Expected file name stem.
153        stem: String,
154        /// Directories that were searched.
155        dir: String,
156    },
157
158    /// No `Cargo.toml` where one was expected.
159    #[error("no Cargo.toml in {dir}")]
160    NoManifest {
161        /// The directory that was looked in.
162        dir: PathBuf,
163    },
164
165    /// `cargo metadata` did not describe the crate whose manifest was given.
166    ///
167    /// Either the manifest is not part of the reported workspace, or the output could
168    /// not be matched to it.
169    #[error("cargo metadata does not describe the package at {manifest}")]
170    NoPackage {
171        /// Manifest path that was asked about.
172        manifest: PathBuf,
173    },
174
175    /// The plugin manifest's `[plugin] version` disagrees with the crate's own version.
176    ///
177    /// Release assets carry both, and they have to be the same number: the manifest is
178    /// what a host reads before it downloads anything, and the asset file name is built
179    /// from the crate version.
180    #[error(
181        "the plugin manifest {path} declares version {declared}, but the crate version is \
182         {crate_version}"
183    )]
184    VersionMismatch {
185        /// Manifest path.
186        path: PathBuf,
187        /// Version declared inside the manifest.
188        declared: String,
189        /// Version declared by `Cargo.toml`.
190        crate_version: String,
191    },
192
193    /// The network request failed. The message carries the URL and status code.
194    #[error("network request failed: {0}")]
195    Http(String),
196
197    /// The registry returned content we could fetch but that is not what we expect.
198    #[error("registry returned an unexpected response: {0}")]
199    Registry(String),
200
201    /// A plugin panicked during a cross-boundary call (caught by `catch_unwind` on
202    /// the host side).
203    #[error("plugin panicked in {what} (caught by catch_unwind)")]
204    PluginPanicked {
205        /// Which call site, e.g. `"entry()"`.
206        what: String,
207    },
208
209    /// Neither HOME nor an equivalent system directory is available, so the data
210    /// dir cannot be determined.
211    #[error("cannot determine the host application's data dir (no HOME and no system equivalent)")]
212    NoDataDir,
213
214    /// IO error.
215    #[error(transparent)]
216    Io(#[from] std::io::Error),
217}
218
219/// This crate's `Result` alias.
220pub type KitResult<T> = std::result::Result<T, KitError>;
221
222/// Say what happened to the build process, rather than printing `Option`'s `Debug` output at
223/// the user -- `Some(101)` and `None` are implementation details, not an explanation.
224fn describe_code(code: &Option<i32>) -> String {
225    match code {
226        Some(code) => format!("exit code {code}"),
227        None => "killed by a signal".to_string(),
228    }
229}