quilt-rs 0.34.0

Rust library for accessing Quilt data packages.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
use std::path::PathBuf;
use std::path::StripPrefixError;
use std::str::Utf8Error;

use aws_smithy_types::byte_stream;
use reqwest::header::ToStrError;
use thiserror::Error;

use crate::io::remote::HostChecksums;
use crate::object_hash::Error as ObjectHashError;
use crate::workflow::WorkflowValidationError;
use quilt_uri::Host;
use quilt_uri::Namespace;
use quilt_uri::UriError;

#[derive(Error, Debug)]
#[error("S3 error{}: {kind}", .host.as_ref().map_or(String::new(), |h| format!(" for {h}")))]
pub struct S3Error {
    pub host: Option<Host>,
    #[source]
    pub kind: S3ErrorKind,
}

impl S3Error {
    #[must_use]
    pub fn new(kind: S3ErrorKind) -> Self {
        Self { host: None, kind }
    }

    #[must_use]
    pub fn is_not_found(&self) -> bool {
        matches!(self.kind, S3ErrorKind::NotFound(_))
    }

    /// True when S3 refused the call with the `AccessDenied` code — under a
    /// vended credential that proves the session is healthy, this means the
    /// active role cannot reach the object, not that the user is logged out.
    #[must_use]
    pub fn is_access_denied(&self) -> bool {
        matches!(self.kind, S3ErrorKind::AccessDenied(_))
    }
}

#[derive(Error, Debug, PartialEq)]
pub enum S3ErrorKind {
    #[error("Failed to check object existence: {0}")]
    Exists(String),

    #[error("Failed to get object: {0}")]
    GetObject(String),

    #[error("Failed to get object attributes: {0}")]
    GetObjectAttributes(String),

    #[error("Failed to get object stream: {0}")]
    GetObjectStream(String),

    #[error("Failed to initialize S3 client: {0}")]
    Client(String),

    #[error("Failed to list objects: {0}")]
    ListObjects(String),

    #[error("Failed to put object: {0}")]
    PutObject(String),

    #[error("Failed to resolve object URL: {0}")]
    ResolveUrl(String),

    #[error("Failed to upload object: {0}")]
    UploadFile(String),

    #[error("S3 not found: {0}")]
    NotFound(String),

    #[error("S3 access denied: {0}")]
    AccessDenied(String),

    #[error("S3 error: {0}")]
    Raw(String),

    #[error("Failed to initialize S3 Remote")]
    RemoteInit,

    #[error("Object key expected to be present")]
    ObjectKey,

    #[error("Error with upload id: {0}")]
    UploadId(String),

    #[error("Failed to read RwLock: {0}")]
    PoisonLock(String),
}

#[derive(Error, Debug, PartialEq)]
pub enum AuthError {
    #[error("Failed to read credentials: {0}")]
    CredentialsRead(String),

    #[error("Failed to refresh credentials: {0}")]
    CredentialsRefresh(String),

    #[error("Failed to read tokens: {0}")]
    TokensRead(String),

    #[error("Failed to refresh tokens: {0}")]
    TokensRefresh(String),

    #[error("Failed to exchange authorization code for tokens: {0}")]
    TokensExchange(String),
}

#[derive(Error, Debug, PartialEq)]
pub enum RoleError {
    #[error("Not authenticated with {0}")]
    NotAuthenticated(Host),

    #[error("Registry rejected the request: {0}")]
    GraphQl(String),

    #[error("Role switch rejected: {0}")]
    SwitchRejected(String),
}

#[derive(Error, Debug, PartialEq)]
pub enum InstallPackageError {
    #[error("The package {0} is already installed")]
    AlreadyInstalled(Namespace),

    #[error("The given package is not installed: {0}")]
    NotInstalled(Namespace),
}

#[derive(Error, Debug, PartialEq)]
pub enum InstallPathError {
    #[error("Failed to install path: {}", .0.display())]
    Install(PathBuf),

    #[error("Some paths are already installed")]
    AlreadyInstalled,

    #[error("Failed to uninstall path: {}", .0.display())]
    Uninstall(PathBuf),
}

#[derive(Error, Debug)]
pub enum ChecksumError {
    #[error("Checksum error: {0}")]
    Mismatch(String),

    #[error("Missing checksum: {0:?}")]
    Missing(HostChecksums),

    #[error("Malformed checksum: {0}")]
    Malformed(String),

    #[error("Failed to get checksum from S3: {0}")]
    NoS3Checksum(String),
}

#[derive(Error, Debug)]
pub enum ManifestError {
    #[error("Manifest header: {0}")]
    Header(String),

    #[error("Failed to load manifest from {path}: {source}")]
    Load {
        path: PathBuf,
        source: Box<crate::Error>,
    },

    #[error("Table error: {0}")]
    Table(String),
}

#[derive(Error, Debug)]
pub enum LineageError {
    #[error("Domain lineage missing, including missing Home directory")]
    Missing,

    #[error("Domain lineage missing Home directory")]
    MissingHome,

    #[error("Failed to parse lineage file: {0}")]
    Parse(serde_json::Error),

    #[error("Operation requires a remote origin, but this is a local-only package")]
    NoRemote,
}

#[derive(Error, Debug, PartialEq)]
pub enum RemoteCatalogError {
    #[error("Workflow error: {0}")]
    Workflow(String),

    /// The bucket's `.quilt/workflows/config.yml` is malformed — it violates the
    /// vendored quilt3 config schema, or its YAML could not be converted for
    /// validation. Distinct from [`RemoteCatalogError::Workflow`] (a workflow
    /// that resolved against a *valid* config could not be found/applied): an
    /// invalid config means every commit to the bucket will fail until it is
    /// fixed, so callers can present that honestly instead of "couldn't load".
    #[error("Invalid workflows config: {0}")]
    InvalidWorkflowsConfig(String),

    #[error("Failed to fetch host config: {0}")]
    HostConfig(String),

    #[error("S3 bucket '{0}' is not reachable — verify the bucket name")]
    BucketUnreachable(String),
}

#[derive(Error, Debug, PartialEq)]
pub enum LoginError {
    #[error("Login required{}", .0.as_ref().map_or(String::new(), |h| format!(": {h}")))]
    Required(Option<Host>),

    #[error("Failed to get registry URL from {0}. Does {0}/config.json have it?")]
    RequiredRegistryUrl(Host),
}

#[derive(Error, Debug)]
pub enum FsError {
    #[error("Failed to read file {path}: {source}")]
    Read {
        path: PathBuf,
        source: std::io::Error,
    },

    #[error("Failed to write file {path}: {source}")]
    Write {
        path: PathBuf,
        source: std::io::Error,
    },

    #[error("Failed to copy file from {from} to {to}: {source}")]
    Copy {
        from: PathBuf,
        to: PathBuf,
        source: std::io::Error,
    },

    #[error("Failed to create directory {path}: {source}")]
    DirectoryCreate {
        path: PathBuf,
        source: std::io::Error,
    },

    #[error("File not found: {path}")]
    NotFound { path: PathBuf },

    #[error("Path prefix not found: {0}")]
    PathPrefixNotFound(StripPrefixError),

    #[error("ByteStream error: {0}")]
    ByteStream(#[from] byte_stream::error::Error),
}

#[derive(Error, Debug, PartialEq)]
pub enum PackageOpError {
    #[error("Commit error: {0}")]
    Commit(String),

    #[error("Push error: {0}")]
    Push(String),

    #[error("Publish error: {0}")]
    Publish(String),

    #[error("General error regarding package: {0}")]
    Package(String),

    #[error("Pull blocked by conflicting local changes: {0:?}")]
    PullConflict(Vec<PathBuf>),

    #[error("package is already up-to-date")]
    AlreadyUpToDate,
}

/// The error type for this library
#[derive(Error, Debug)]
pub enum Error {
    #[error("Authentication failed for {0}: {1}")]
    Auth(Host, AuthError),

    #[error(transparent)]
    Checksum(#[from] ChecksumError),

    #[error(transparent)]
    Fs(#[from] FsError),

    #[error(transparent)]
    InstallPackage(InstallPackageError),

    #[error(transparent)]
    InstallPath(InstallPathError),

    #[error("IO error: {0}")]
    Io(#[from] std::io::Error),

    #[error("JSON error: {0}")]
    Json(#[from] serde_json::Error),

    #[error(transparent)]
    Lineage(#[from] LineageError),

    #[error(transparent)]
    Login(#[from] LoginError),

    #[error(transparent)]
    Manifest(#[from] ManifestError),

    #[error(transparent)]
    ObjectHash(#[from] ObjectHashError),

    #[error(transparent)]
    PackageOp(#[from] PackageOpError),

    #[error("Reqwest error: {0}")]
    Reqwest(#[from] reqwest::Error),

    #[error(transparent)]
    Role(#[from] RoleError),

    #[error(transparent)]
    RemoteCatalog(#[from] RemoteCatalogError),

    #[error(transparent)]
    S3(#[from] S3Error),

    #[error("Cannot convert to string: {0}")]
    ToString(#[from] ToStrError),

    #[error("Integer conversion error: {0}")]
    TryFromIntError(#[from] std::num::TryFromIntError),

    #[error("Unimplemented")]
    Unimplemented,

    #[error(transparent)]
    Uri(#[from] UriError),

    #[error("Error parsing URL: {0}")]
    UrlParse(#[from] url::ParseError),

    #[error("UTF-8 error: {0}")]
    Utf8(#[from] Utf8Error),

    #[error(transparent)]
    WorkflowValidation(#[from] WorkflowValidationError),

    #[error("YAML error: {0}")]
    Yaml(#[from] serde_yaml::Error),
}

/// Map a workflow config error onto the existing `Error` variants so the
/// consumer-visible `Display` and variant matching are byte-identical to before
/// the crate extraction. The mapping is cross-variant (a single `ConfigError`
/// splits across `RemoteCatalog` and `Uri`), so it cannot be a `#[from]` field
/// attribute.
impl From<crate::workflow::ConfigError> for Error {
    fn from(err: crate::workflow::ConfigError) -> Self {
        use crate::workflow::ConfigError;
        match err {
            ConfigError::Workflow(msg) => Error::RemoteCatalog(RemoteCatalogError::Workflow(msg)),
            ConfigError::InvalidWorkflowsConfig(msg) => {
                Error::RemoteCatalog(RemoteCatalogError::InvalidWorkflowsConfig(msg))
            }
            ConfigError::Uri(err) => Error::Uri(err),
        }
    }
}

impl Error {
    /// Returns `true` if this error represents a "not found" — an S3
    /// `NoSuchKey` response, or a local filesystem miss (a working-tree file
    /// that was deleted). Lets callers tell an absent object/file apart from a
    /// genuine I/O failure (permission denied, transient storage error).
    #[must_use]
    pub fn is_not_found(&self) -> bool {
        match self {
            Error::S3(s3) => s3.is_not_found(),
            Error::Fs(FsError::NotFound { .. }) => true,
            Error::Fs(FsError::Read { source, .. }) => {
                source.kind() == std::io::ErrorKind::NotFound
            }
            Error::Io(e) => e.kind() == std::io::ErrorKind::NotFound,
            _ => false,
        }
    }

    /// Returns `true` if S3 refused the call with the `AccessDenied` code.
    ///
    /// The mirror of [`Error::is_not_found`] for the role dimension: callers
    /// that only ever see an [`enum@Error`] need this to tell "the active role
    /// cannot reach this object" apart from a generic storage failure, so
    /// every layer that re-wraps an S3 error must let this variant through
    /// unchanged.
    #[must_use]
    pub fn is_access_denied(&self) -> bool {
        matches!(self, Error::S3(s3) if s3.is_access_denied())
    }
}

// Compose `?` across two From hops: external error → focused enum → Error.
// Rust's `?` only runs one `From::from`, so these bridges make call sites
// keep working without `.map_err(..)`.

impl From<multihash::Error> for Error {
    fn from(err: multihash::Error) -> Self {
        Error::ObjectHash(err.into())
    }
}

impl From<multibase::Error> for Error {
    fn from(err: multibase::Error) -> Self {
        Error::ObjectHash(err.into())
    }
}

impl From<byte_stream::error::Error> for Error {
    fn from(err: byte_stream::error::Error) -> Self {
        FsError::ByteStream(err).into()
    }
}

impl From<StripPrefixError> for Error {
    fn from(err: StripPrefixError) -> Self {
        Error::Fs(FsError::PathPrefixNotFound(err))
    }
}