quilt-rs 0.40.0

Rust library for versioning data packages: content-addressed manifests, local domains, and S3 remotes.
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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
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(_))
    }

    /// True when the S3 service rejected the credentials themselves rather
    /// than the active role's access to an object.
    #[must_use]
    pub fn is_invalid_credentials(&self) -> bool {
        matches!(self.kind, S3ErrorKind::InvalidCredentials(_))
    }
}

#[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("Invalid AWS credentials: {0}")]
    InvalidCredentials(String),

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

    #[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,

    /// The path has no row in the revision being installed. Reachable when a
    /// download waited out a pull that moved the package to a revision
    /// without it.
    #[error("{} is not in the package's current revision", .0.display())]
    NotInRevision(PathBuf),

    #[error(
        "A local file is already at {}",
        .0.iter().map(|p| p.display().to_string()).collect::<Vec<_>>().join(", ")
    )]
    LocalFileExists(Vec<PathBuf>),

    /// The remote returned bytes that do not hash to the row being installed.
    /// The usual cause is a row whose `physical_key` carries no `versionId`:
    /// it names whatever the object is now, and a later revision has replaced
    /// it, so this revision's content is no longer on the remote.
    ///
    /// Raised only where a partial apply would be wrong, the pull's reconcile.
    /// `install_paths` skips such a row and reports it instead.
    #[error(
        "The remote no longer holds this revision's content for {}: the object it points to has been replaced",
        .0.display()
    )]
    ContentMismatch(PathBuf),

    #[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 {
    /// No usable session for this deployment; `None` when the call carried no
    /// deployment — a bare bucket on ambient AWS credentials.
    ///
    /// Names the state, not a remedy: each surface answers it differently.
    #[error("No session{}", .0.as_ref().map_or(String::new(), |h| format!(" for {h}")))]
    NoSession(Option<Host>),

    /// The deployment answered but its `config.json` names no registry. A
    /// misconfiguration, not a missing session: signing in cannot change it.
    #[error("{0} does not advertise a registry URL in its config.json")]
    NoRegistryUrl(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("Undo error: {0}")]
    Undo(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())
    }

    /// Returns `true` if S3 rejected the credentials themselves.
    ///
    /// Distinct from [`Error::is_access_denied`]: that one means the session is
    /// healthy and the active role cannot reach the object, this one means the
    /// session is not healthy. Callers that back off on storage failures must
    /// check this first — retrying a rejected credential never succeeds.
    #[must_use]
    pub fn is_invalid_credentials(&self) -> bool {
        matches!(self, Error::S3(s3) if s3.is_invalid_credentials())
    }

    /// No usable session, by either route — refused before issue
    /// ([`LoginError::NoSession`]) or issued and rejected
    /// ([`S3ErrorKind::InvalidCredentials`]). One predicate because callers act
    /// on the state; which route it took is where the failure was noticed.
    #[must_use]
    pub fn is_session_absent(&self) -> bool {
        self.is_invalid_credentials() || matches!(self, Error::Login(LoginError::NoSession(_)))
    }

    /// The deployment this request was for, if any.
    ///
    /// `None` for a bare S3 bucket reached with ambient credentials, and for
    /// errors that are not S3 errors. What that absence *means* is the
    /// caller's to decide: paired with [`Error::is_invalid_credentials`] it
    /// says there is no stack to sign back in to.
    #[must_use]
    pub fn s3_host(&self) -> Option<&quilt_uri::Host> {
        match self {
            Error::S3(s3) => s3.host.as_ref(),
            _ => None,
        }
    }
}

// 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))
    }
}