b2-client 0.1.3

HTTP client-agnostic Backblaze B2 client library
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
/* This Source Code Form is subject to the terms of the Mozilla Public
   License, v. 2.0. If a copy of the MPL was not distributed with this
   file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

//! Error types for b2-client
//!
//! Errors are divided into two types:
//!
//! * [ValidationError] for data validation errors prior to sending a request to
//!   the B2 API. This is currently being split into multiple errors as
//!   appropriate:
//!     * [BadHeaderName]
//!     * [BucketValidationError]
//!     * [CorsRuleValidationError]
//!     * [FileNameValidationError]
//!     * [LifecycleRuleValidationError]
//!     * [MissingData]
//! * [Error] for errors returned by the Backblaze B2 API or the HTTP client.

use std::{
    collections::HashMap,
    fmt,
};

use crate::bucket::LifecycleRule;

use serde::{Serialize, Deserialize};


// TODO: Splitting these up will provide nicer error handling when the user
// actually wants to handle them, rather than merely print them. As part of
// this, we need data-oriented errors rather than string-oriented errors.
/// Errors from validating B2 requests prior to making the request.
#[derive(Debug)]
pub enum ValidationError {
    /// Failure to parse a URL.
    ///
    /// The string the problematic URL.
    BadUrl(String),
    /// The data is an invalid format or contains invalid information.
    ///
    /// The string is a short description of the failure.
    BadFormat(String),
    /// Required information was not provided.
    ///
    /// The string is a short description of the failure.
    MissingData(String),
    /// The data is outside its valid range.
    ///
    /// The string is a short description of the failure.
    OutOfBounds(String),
    /// Two pieces of data are incompatible together.
    ///
    /// The string is a short description of the failure.
    Incompatible(String),
}

impl std::error::Error for ValidationError {}

impl fmt::Display for ValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::BadUrl(s) => write!(f, "Error parsing URL: {}", s),
            Self::BadFormat(s) => write!(f, "{}", s),
            Self::MissingData(s) => write!(f, "{}", s),
            Self::OutOfBounds(s) => write!(f, "{}", s),
            Self::Incompatible(s) => write!(f, "{}", s),
        }
    }
}

impl From<url::ParseError> for ValidationError {
    fn from(e: url::ParseError) -> Self {
        Self::BadUrl(format!("{}", e))
    }
}

#[cfg(feature = "with_surf")]
impl From<http_types::Error> for ValidationError {
    fn from(e: http_types::Error) -> Self {
        Self::BadFormat(format!("{}", e))
    }
}

#[cfg(feature = "with_hyper")]
impl From<hyper::header::InvalidHeaderName> for ValidationError {
    fn from(e: hyper::header::InvalidHeaderName) -> Self {
        Self::BadFormat(format!("{}", e))
    }
}

#[cfg(feature = "with_hyper")]
impl From<hyper::header::InvalidHeaderValue> for ValidationError {
    fn from(e: hyper::header::InvalidHeaderValue) -> Self {
        Self::BadFormat(format!("{}", e))
    }
}

#[cfg(feature = "with_isahc")]
impl From<isahc::http::header::InvalidHeaderName> for ValidationError {
    fn from(e: isahc::http::header::InvalidHeaderName) -> Self {
        Self::BadFormat(format!("{}", e))
    }
}

#[cfg(feature = "with_isahc")]
impl From<isahc::http::header::InvalidHeaderValue> for ValidationError {
    fn from(e: isahc::http::header::InvalidHeaderValue) -> Self {
        Self::BadFormat(format!("{}", e))
    }
}

/// Generic invalid data error.
#[derive(Debug)]
pub struct BadData<T>
    where T: std::fmt::Debug + std::fmt::Display,
{
    pub value: T,
    pub(crate) msg: String,
}

impl<T> std::error::Error for BadData<T>
    where T: std::fmt::Debug + std::fmt::Display,
{}

impl<T> fmt::Display for BadData<T>
    where T: std::fmt::Debug + std::fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.msg)
    }
}

/// Error type with information on invalid HTTP header name.
#[derive(Debug)]
pub struct BadHeaderName {
    /// The name of the bad header.
    pub header: String,
    /// The illegal character in the header name.
    pub invalid_char: char,
}

impl std::error::Error for BadHeaderName {}

impl fmt::Display for BadHeaderName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "Invalid character in header {}: {}",
            self.header,
            self.invalid_char
        )
    }
}

/// Error type for invalid bucket names.
#[derive(Debug)]
pub enum BucketValidationError {
    /// The name of the bucket must be between 8 and 50 characters, inclusive.
    // TODO: find full B2 requirement - bytes? ASCII-only characters? I think it
    // will be the latter since only ASCII control characters were explicitly
    // prohibited.
    BadNameLength(usize),
    /// Illegal character in filename.
    InvalidChar(char),
}

impl std::error::Error for BucketValidationError {}

impl fmt::Display for BucketValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::BadNameLength(sz) => write!(f,
                "Name must be between 6 and 50 characters, inclusive. Was {}",
                sz
            ),
            Self::InvalidChar(ch) => write!(f, "Unexpected character: {}", ch),
        }
    }
}

// TODO: Likely need to copy-paste this since the compiler won't reliably use
// the new name (same for `use as`).
/// Error type for invalid CORS rule names.
///
/// The requirements for CORS rules are the same as for bucket names.
pub type CorsRuleValidationError = BucketValidationError;

/// Error type for bad filenames.
#[derive(Debug)]
pub enum FileNameValidationError {
    /// A filename length cannot exceed 1024 bytes.
    BadLength(usize),
    /// An invalid character was in the filename string.
    InvalidChar(char),
}

impl std::error::Error for FileNameValidationError {}

impl fmt::Display for FileNameValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::BadLength(sz) => write!(f,
                "Name must be no more than 1024 bytes. Was {}", sz
            ),
            Self::InvalidChar(ch) => write!(f, "Illegal character: {}", ch),
        }
    }
}

/// Error type from failure to validate a set of [LifecycleRule]s.
#[derive(Debug)]
pub enum LifecycleRuleValidationError {
    /// The maximum number of rules (100) was exceeded for the bucket.
    TooManyRules(usize),
    /// Multiple [LifecycleRule]s exist for the same file.
    ///
    /// Returns a map of conflicting filename prefixes; the most broad prefix
    /// (the base path) for each group of conflicts is the key and the
    /// conflicting rules are in the value.
    ///
    /// There can be duplicate entries in the map when rules involving
    /// subfolders exist.
    ConflictingRules(HashMap<String, Vec<LifecycleRule>>),
}

impl std::error::Error for LifecycleRuleValidationError {}

impl fmt::Display for LifecycleRuleValidationError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::TooManyRules(i) => write!(f, concat!(
                "A bucket can have no more than 100 rules;",
                "you have provided {}"), i
            ),
            Self::ConflictingRules(_) => (write!(f,
                "Only one lifecycle rule can apply to any given set of files"
            )),
        }
    }
}

#[derive(Debug)]
pub struct MissingData {
    pub field: &'static str,
    msg: Option<String>,
}

impl MissingData {
    pub fn new(missing_field: &'static str) -> Self {
        Self {
            field: missing_field,
            msg: None,
        }
    }

    pub fn with_message(mut self, message: impl Into<String>) -> Self {
        self.msg = Some(message.into());
        self
    }
}

impl std::error::Error for MissingData {}

impl fmt::Display for MissingData {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.msg {
            Some(msg) => write!(f, "{}", msg),
            None => write!(f, "Missing data: {} is required", self.field),
        }
    }
}

/// Errors related to making B2 API calls.
#[derive(Debug)]
pub enum Error<E>
    // Surf's Error doesn't implement StdError.
    where E: fmt::Debug + fmt::Display,
{
    /// An error from the underlying HTTP client.
    Client(E),
    /// An I/O error from the local filesystem.
    IO(std::io::Error),
    /// An error from the Backblaze B2 API.
    B2(B2Error),
    /// An error deserializing the HTTP client's response.
    Format(serde_json::Error),
    /// The [Authorization](crate::account::Authorization) lacks a required
    /// capability to perform a task. The provided capability is required.
    ///
    /// This error is typically used when the B2 API returns `null` rather than
    /// returning an error or to return what we know will be an authorization
    /// error prior to sending a request to the API.
    Unauthorized(crate::account::Capability),
    /// An error validating data prior to making a Backblaze B2 API call.
    Validation(ValidationError),
    /// Attempted to send a request without a valid
    /// [Authorization](crate::account::Authorization).
    MissingAuthorization,
    /// Attempted to send a non-existent request.
    NoRequest,
}

impl<E> std::error::Error for Error<E>
    where E: fmt::Debug + fmt::Display,
{}

impl<E> fmt::Display for Error<E>
    where E: fmt::Debug + fmt::Display,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use fmt::Display;

        match self {
            Self::Client(e) => Display::fmt(&e, f),
            Self::IO(e) => e.fmt(f),
            Self::B2(e) => Display::fmt(&e, f),
            Self::Format(e) => e.fmt(f),
            Self::Unauthorized(c) => write!(f, "Missing capability: {:?}", c),
            Self::Validation(e) => e.fmt(f),
            Self::MissingAuthorization =>
                write!(f, "An Authorization is required for that operation"),
            Self::NoRequest => write!(f, "No request was created"),
        }
    }
}

impl<E> From<B2Error> for Error<E>
    where E: fmt::Debug + fmt::Display,
{
    fn from(e: B2Error) -> Self {
        Self::B2(e)
    }
}

impl<E> From<std::io::Error> for Error<E>
    where E: fmt::Debug + fmt::Display,
{
    fn from(e: std::io::Error) -> Self {
        Self::IO(e)
    }
}

impl<E> From<serde_json::Error> for Error<E>
    where E: fmt::Debug + fmt::Display,
{
    fn from(e: serde_json::Error) -> Self {
        Self::Format(e)
    }
}

#[cfg(feature = "with_surf")]
impl From<surf::Error> for Error<surf::Error> {
    fn from(e: surf::Error) -> Self {
        Self::Client(e)
    }
}

#[cfg(feature = "with_hyper")]
impl From<hyper::Error> for Error<hyper::Error> {
    fn from(e: hyper::Error) -> Self {
        Self::Client(e)
    }
}

#[cfg(feature = "with_isahc")]
impl From<isahc::Error> for Error<isahc::Error> {
    fn from(e: isahc::Error) -> Self {
        Self::Client(e)
    }
}

#[cfg(feature = "with_isahc")]
impl From<isahc::http::Error> for Error<isahc::Error> {
    fn from(e: isahc::http::Error) -> Self {
        Self::Client(e.into())
    }
}

impl<E> From<ValidationError> for Error<E>
    where E: fmt::Debug + fmt::Display,
{
    fn from(e: ValidationError) -> Self {
        Self::Validation(e)
    }
}

/// An error code from the B2 API.
///
/// The HTTP status code is not necessarily constant for any given error code.
/// See the B2 documentation for the relevant API call to match HTTP status
/// codes and B2 error codes.
#[derive(Debug, Eq, PartialEq, Serialize, Deserialize)]
pub enum ErrorCode {
    // 400
    BadBucketId,
    BadRequest, // Also 503
    BucketMissingFileLock,
    DuplicateBucketName,
    FileNotPresent,
    InvalidBucketId,
    InvalidFileId,
    NoSuchFile,
    // The only documented receiving of this isn't possible for us unless B2
    // modifies the range because we clamp the user's value to the valid range.
    OutOfRange,
    TooManyBuckets,

    // 401
    AccessDenied, // Also 403
    BadAuthToken,
    ExpiredAuthToken,
    Unauthorized,
    Unsupported,

    // 403
    CapExceeded,
    StorageCapExceeded,
    TransactionCapExceeded,

    // 404
    NotFound,

    // 405
    MethodNotAllowed,

    // 408
    RequestTimeout,

    // 409
    Conflict,

    // 416
    RangeNotSatisfiable,

    // 500
    InternalError,

    // 503
    ServiceUnavailable,

    /// The B2 service returned an unknown error code.
    ///
    /// If you receive this in practice, please file an issue or submit a patch
    /// to support the error code.
    Unknown(String),
}

impl ErrorCode {
    /// Convert the error code received from the B2 service to an [ErrorCode].
    fn from_api_code<S: AsRef<str>>(code: S) -> Self {
        match code.as_ref() {
            "bad_bucket_id" => Self::BadBucketId,
            "bad_request" => Self::BadRequest,
            "bucket_missing_file_lock" => Self::BucketMissingFileLock,
            "duplicate_bucket_name" => Self::DuplicateBucketName,
            "file_not_present" => Self::FileNotPresent,
            "invalid_bucket_id" => Self::InvalidBucketId,
            "invalid_file_id" => Self::InvalidFileId,
            "no_such_file" => Self::NoSuchFile,
            "out_of_range" => Self::OutOfRange,
            "too_many_buckets" => Self::TooManyBuckets,

            "bad_auth_token" => Self::BadAuthToken,
            "expired_auth_token" => Self::ExpiredAuthToken,
            "unauthorized" => Self::Unauthorized,
            "unsupported" => Self::Unsupported,

            "access_denied" => Self::AccessDenied,
            "cap_exceeded" => Self::CapExceeded,
            "storage_cap_exceeded" => Self::StorageCapExceeded,
            "transaction_cap_exceeded" => Self::TransactionCapExceeded,

            "not_found" => Self::NotFound,

            "method_not_allowed" => Self::MethodNotAllowed,

            "request_timeout" => Self::RequestTimeout,

            "range_not_satisfiable" => Self::RangeNotSatisfiable,

            "conflict" => Self::Conflict,

            "internal_error" => Self::InternalError,

            "service_unavailable" => Self::ServiceUnavailable,

            s => Self::Unknown(s.to_owned()),
        }
    }
}

/// An error response from the Backblaze B2 API.
///
/// See <https://www.backblaze.com/b2/docs/calling.html#error_handling> for
/// information on B2 error handling.
#[derive(Debug, Deserialize)]
pub struct B2Error {
    /// The HTTP status code accompanying the error.
    status: u16,
    /// A code that identifies the error.
    #[serde(rename = "code")]
    code_str: String,
    /// A description of what went wrong.
    message: String,
}

impl B2Error {
    /// Get the HTTP status code for the error.
    pub fn http_status(&self) -> u16 { self.status }

    pub fn code(&self) -> ErrorCode {
        ErrorCode::from_api_code(&self.code_str)
    }
}

impl std::error::Error for B2Error {}

impl fmt::Display for B2Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.code_str, self.message)
    }
}