Skip to main content

thunderstore_engine/
error.rs

1#![deny(missing_docs)]
2
3use std::fmt;
4use std::io;
5use std::num::ParseIntError;
6use std::sync::Arc;
7use thiserror::Error;
8
9/// A type alias for `Result<T, Error>` used throughout the engine.
10pub type Result<T> = std::result::Result<T, Error>;
11
12/// Represents all possible errors that can occur within the Thunderstore engine.
13///
14/// This enum is `#[non_exhaustive]`: new variants may be added in future
15/// releases without a breaking change, so downstream `match`es must include a
16/// wildcard arm.
17///
18/// `Error` is `Clone`, so a client can keep one in its state or hand it to
19/// several listeners. Sources that are not `Clone` themselves are held in a
20/// [`Shared`]; `?` still converts them directly, and
21/// [`source`](std::error::Error::source) still downcasts to them.
22#[derive(Error, Debug, Clone)]
23#[non_exhaustive]
24pub enum Error {
25  /// Error from the IO system.
26  #[error("IO error: {0}")]
27  Io(#[source] Shared<io::Error>),
28
29  /// Error from HTTP operations.
30  #[cfg(feature = "io")]
31  #[error("HTTP error: {0}")]
32  Http(#[source] Shared<reqwest::Error>),
33
34  /// Error from JSON parsing.
35  #[error("JSON error: {0}")]
36  Json(#[source] Shared<serde_json::Error>),
37
38  /// Error from ZIP operations.
39  #[cfg(feature = "io")]
40  #[error("ZIP error: {0}")]
41  Zip(#[source] Shared<zip::result::ZipError>),
42
43  /// Error from header parsing.
44  #[cfg(feature = "io")]
45  #[error("Header error: {0}")]
46  Header(#[source] Shared<reqwest::header::ToStrError>),
47
48  /// Error from parsing integers.
49  #[error("Parse integer error: {0}")]
50  ParseInt(#[from] ParseIntError),
51
52  /// Missing header in response.
53  #[error("Missing header: {0}")]
54  MissingHeader(String),
55
56  /// Error from builder or configuration validation.
57  #[error("Configuration error: {0}")]
58  Config(String),
59
60  /// Error parsing a per-mod `manifest.json`.
61  #[error("manifest parse error: {0}")]
62  ManifestParse(String),
63
64  /// Error reading, writing, or validating the on-disk package-index cache.
65  ///
66  /// Covers cache load/decode/encode, a missing cache, an incompatible or
67  /// corrupt cache layout, and the integrity checks in
68  /// [`PackageIndex::validate`](crate::models::PackageIndex) — which run at the
69  /// cache boundary.
70  #[error("cache error: {0}")]
71  Cache(String),
72
73  /// A network body, manifest file, or decompressed payload exceeded a
74  /// configured size limit.
75  ///
76  /// `actual` is a structured field for programmatic inspection; it is
77  /// deliberately not rendered in `Display` because `thiserror` cannot
78  /// conditionally format an `Option`.
79  #[error("{context} exceeds size limit of {limit} bytes")]
80  SizeLimitExceeded {
81    /// A short label for what was being read (e.g. `"download body"`).
82    context: String,
83    /// The configured byte ceiling.
84    limit: u64,
85    /// The observed size, when known.
86    actual: Option<u64>,
87  },
88
89  /// A download ended before the declared number of bytes arrived.
90  #[error("incomplete download: expected {expected} bytes, received {actual}")]
91  IncompleteDownload {
92    /// The number of bytes the server declared.
93    expected: u64,
94    /// The number of bytes actually received.
95    actual: u64,
96  },
97
98  /// A download filename was unsafe (empty, absolute, or path-traversing).
99  #[error("unsafe name: {0}")]
100  UnsafeName(String),
101
102  /// The on-disk cache was written by an incompatible version of the cache
103  /// format. The client treats this as a cache miss and re-fetches.
104  #[error("unsupported cache format version {found} (expected {expected})")]
105  UnsupportedCacheVersion {
106    /// The format version read from the cache file.
107    found: u32,
108    /// The format version this build understands.
109    expected: u32,
110  },
111
112  /// Error from ecosystem-schema parsing.
113  #[error("Ecosystem error: {0}")]
114  Ecosystem(String),
115
116  /// Error from install routing, e.g. a package that would escape the install root.
117  #[error("Install error: {0}")]
118  Install(String),
119
120  /// Error from the profile layer: an invalid profile name, a malformed
121  /// `mods.yml`/state file, or a profile operation that could not complete.
122  #[error("Profile error: {0}")]
123  Profile(String),
124
125  /// A profile name that could not be used, from any operation that gates on
126  /// [`layout::require_profile`](crate::profile::layout::require_profile).
127  ///
128  /// Carries the reason rather than a sentence so an operation with other
129  /// failure modes, such as
130  /// [`layout::use_profile`](crate::profile::layout::use_profile), can still
131  /// return one `Error` without a caller losing the ability to word the refusal
132  /// itself. Renders exactly as [`Error::Profile`] did for the same refusal.
133  #[error("Profile error: {0}")]
134  BadProfile(#[from] crate::profile::layout::BadProfile),
135
136  /// The package is not recorded in the target's `mods.yml`.
137  #[error("Profile error: {package} is not installed")]
138  NotInstalled {
139    /// The `Owner-Name` identifier as given.
140    package: String,
141  },
142
143  /// A requested package, or a package in its dependency closure, is not in
144  /// the package index, so nothing was installed.
145  #[error("Profile error: cannot install {package}: could not resolve {}", .unresolved.join(", "))]
146  UnresolvedDependency {
147    /// The identifier whose install was requested.
148    package: String,
149    /// Every identifier that could not be resolved, sorted.
150    unresolved: Vec<String>,
151  },
152
153  /// The index has the package, but not the version the request names.
154  #[error("Profile error: cannot install {package}-{version}: {package} has no version {version}")]
155  MissingVersion {
156    /// The `Owner-Name` identifier.
157    package: String,
158    /// The requested version.
159    version: String,
160  },
161
162  /// The ecosystem has no game with this slug.
163  #[error("Profile error: unknown game {game:?}")]
164  UnknownGame {
165    /// The game slug as given.
166    game: String,
167  },
168
169  /// The game is known, but the ecosystem gives it no profile, so there are no
170  /// install rules to route its packages with.
171  #[error("Profile error: no ecosystem profile for game {game:?}")]
172  NoGameProfile {
173    /// The game slug as given.
174    game: String,
175  },
176
177  /// A modded launch found no mod loader installed in the target, so its mods
178  /// would not load.
179  #[error("Profile error: no {loader:?} mod loader is installed")]
180  NoModLoader {
181    /// The loader the game's mods need.
182    loader: crate::ecosystem::LoaderKind,
183  },
184
185  /// The game folder a launch needs does not exist.
186  #[error("Profile error: the game folder {} does not exist", .path.display())]
187  MissingGameDir {
188    /// The game folder as given.
189    path: std::path::PathBuf,
190  },
191
192  /// One or more files in a batch download failed.
193  #[error("{} of {total} downloads failed: {}", .failures.len(), list_failures(.failures))]
194  Download {
195    /// How many files were attempted.
196    total: usize,
197    /// Each file that failed, with the reason, sorted by file name.
198    failures: Vec<(String, Error)>,
199  },
200
201  /// An import stopped because one or more of its mods failed to install, so
202  /// its config files were not restored. Importing again once the causes are
203  /// fixed skips the mods already installed and completes it.
204  #[error(
205    "Profile error: {}; the import is unfinished (its config files were not restored)",
206    list_import_failures(.failures)
207  )]
208  ImportUnfinished {
209    /// Each exported identifier that failed, with the reason.
210    failures: Vec<(String, Error)>,
211  },
212
213  /// A response header was present but could not be parsed, e.g. an
214  /// unparseable `Last-Modified` value.
215  #[error("invalid header: {0}")]
216  InvalidHeader(String),
217
218  /// An archive exceeded a configured extraction limit (entry count or
219  /// uncompressed size), e.g. a zip bomb.
220  #[error("Archive extraction limit exceeded: {0}")]
221  ExtractLimitExceeded(String),
222
223  /// CRC32 verification failed while extracting an archive entry.
224  #[error("CRC32 verification failed for {path}: expected {expected:08x}, got {actual:08x}")]
225  ChecksumMismatch {
226    /// The archive-relative path of the entry that failed verification.
227    path: String,
228    /// The CRC32 the archive recorded for the entry.
229    expected: u32,
230    /// The CRC32 computed over the bytes actually read.
231    actual: u32,
232  },
233}
234
235/// Renders `name: reason` pairs as one line, separated by `; `.
236fn list_failures(failures: &[(String, Error)]) -> String {
237  failures
238    .iter()
239    .map(|(name, error)| format!("{name}: {error}"))
240    .collect::<Vec<_>>()
241    .join("; ")
242}
243
244/// An error that is not `Clone`, shared behind an [`Arc`] so [`Error`] can be.
245///
246/// It derefs to the error it holds, and that error, not the `Shared`, is what
247/// [`Error`]'s [`source`](std::error::Error::source) returns, so a caller can
248/// downcast it:
249///
250/// ```
251/// use std::error::Error as _;
252/// use thunderstore_engine::Error;
253///
254/// let err = Error::from(std::io::Error::other("gone"));
255///
256/// assert!(err.source().unwrap().downcast_ref::<std::io::Error>().is_some());
257/// ```
258#[derive(Debug)]
259pub struct Shared<T>(Arc<T>);
260
261impl<T> Clone for Shared<T> {
262  fn clone(&self) -> Self {
263    Self(Arc::clone(&self.0))
264  }
265}
266
267impl<T> std::ops::Deref for Shared<T> {
268  type Target = T;
269
270  fn deref(&self) -> &T {
271    &self.0
272  }
273}
274
275impl<T: fmt::Display> fmt::Display for Shared<T> {
276  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
277    self.0.fmt(f)
278  }
279}
280
281/// Renders import failures as `importing name: reason`, separated by `; `.
282fn list_import_failures(failures: &[(String, Error)]) -> String {
283  failures
284    .iter()
285    .map(|(name, error)| format!("importing {name}: {error}"))
286    .collect::<Vec<_>>()
287    .join("; ")
288}
289
290impl From<io::Error> for Error {
291  fn from(error: io::Error) -> Self {
292    Self::Io(Shared(Arc::new(error)))
293  }
294}
295
296#[cfg(feature = "io")]
297impl From<reqwest::Error> for Error {
298  fn from(error: reqwest::Error) -> Self {
299    Self::Http(Shared(Arc::new(error)))
300  }
301}
302
303impl From<serde_json::Error> for Error {
304  fn from(error: serde_json::Error) -> Self {
305    Self::Json(Shared(Arc::new(error)))
306  }
307}
308
309#[cfg(feature = "io")]
310impl From<zip::result::ZipError> for Error {
311  fn from(error: zip::result::ZipError) -> Self {
312    Self::Zip(Shared(Arc::new(error)))
313  }
314}
315
316#[cfg(feature = "io")]
317impl From<reqwest::header::ToStrError> for Error {
318  fn from(error: reqwest::header::ToStrError) -> Self {
319    Self::Header(Shared(Arc::new(error)))
320  }
321}
322
323#[cfg(test)]
324mod tests {
325  use super::*;
326
327  #[test]
328  fn profile_error_displays_message() {
329    let err = Error::Profile("bad profile".to_string());
330
331    assert_eq!(err.to_string(), "Profile error: bad profile");
332  }
333
334  #[test]
335  fn a_cloned_error_keeps_its_message_and_source() {
336    let err = Error::from(io::Error::new(io::ErrorKind::NotFound, "gone"));
337
338    let kept = err.clone();
339
340    assert_eq!(kept.to_string(), "IO error: gone");
341    assert_eq!(
342      std::error::Error::source(&kept).map(|source| source.to_string()),
343      Some("gone".to_string())
344    );
345  }
346
347  #[test]
348  fn a_wrapped_source_downcasts_to_the_original_error() {
349    let io = Error::from(io::Error::new(io::ErrorKind::NotFound, "gone"));
350    let json = Error::from(serde_json::from_str::<u8>("x").unwrap_err());
351
352    let io_source =
353      std::error::Error::source(&io).and_then(|source| source.downcast_ref::<io::Error>());
354    let json_source = std::error::Error::source(&json)
355      .and_then(|source| source.downcast_ref::<serde_json::Error>());
356
357    assert_eq!(
358      io_source.map(io::Error::kind),
359      Some(io::ErrorKind::NotFound)
360    );
361    assert!(json_source.is_some());
362  }
363}