s3-wire 0.3.1

An async, streaming S3-compatible client for Rust
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
//! Structured client errors.

use std::error::Error;
use std::fmt;

use http::StatusCode;
use time::OffsetDateTime;

/// Broad category suitable for programmatic error handling.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum ErrorCategory {
    /// Client configuration is invalid.
    Configuration,
    /// Credentials or a signature were rejected.
    Authentication,
    /// The authenticated principal is not permitted to perform the operation.
    Authorization,
    /// The requested bucket, object, or upload does not exist.
    NotFound,
    /// The request conflicts with existing S3 state.
    Conflict,
    /// A conditional request precondition failed.
    Precondition,
    /// S3 asked the caller to reduce its request rate.
    Throttling,
    /// S3 returned a server-side failure.
    Server,
    /// The HTTP transport failed.
    Transport,
    /// TLS negotiation or validation failed.
    Tls,
    /// A configured timeout expired.
    Timeout,
    /// The operation was cancelled.
    Cancellation,
    /// The service response was malformed or internally inconsistent.
    InvalidResponse,
    /// A bounded response exceeded its configured limit.
    OversizedResponse,
    /// The requested behavior is intentionally unsupported.
    UnsupportedOperation,
    /// A checksum, length, or other integrity check failed.
    Integrity,
}

/// Whether an operation may be retried after an error.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RetryClassification {
    /// Retrying is not expected to succeed.
    Never,
    /// The failure is transient, subject to operation replayability.
    Retryable,
    /// The service throttled the request, subject to operation replayability.
    Throttled,
}

/// The phase in which a timeout occurred.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum TimeoutPhase {
    /// Establishing the network connection.
    Connect,
    /// Sending the request or waiting for response headers.
    Request,
    /// Waiting for progress while streaming a response body.
    ResponseBody,
    /// The overall operation deadline.
    Operation,
}

/// Why a retryable request stopped without another attempt.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum RetryStopReason {
    /// The final error is not retryable.
    NonRetryable,
    /// The request body or operation cannot be safely replayed.
    NonReplayable,
    /// The configured attempt limit was reached.
    AttemptsExhausted,
    /// The configured retry elapsed-time limit was reached.
    ElapsedLimit,
    /// The operation deadline cannot accommodate another retry.
    Deadline,
    /// The client-wide retry quota was depleted.
    RetryQuota,
}

#[derive(Debug)]
struct RedactedSource {
    error_type: &'static str,
}

impl fmt::Display for RedactedSource {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "underlying {} error (details redacted)",
            self.error_type
        )
    }
}

impl Error for RedactedSource {}

/// A structured S3 client error.
///
/// Formatting an error never prints its underlying source or cleanup error. Source
/// errors are retained only as redacted type markers, preventing URLs, headers, or
/// response data from escaping through an otherwise innocent log statement.
pub struct S3Error {
    details: Box<S3ErrorDetails>,
}

struct S3ErrorDetails {
    category: ErrorCategory,
    code: Option<String>,
    status: Option<StatusCode>,
    message: String,
    request_id: Option<String>,
    host_id: Option<String>,
    retry: RetryClassification,
    timeout_phase: Option<TimeoutPhase>,
    server_time: Option<OffsetDateTime>,
    clock_skew: Option<time::Duration>,
    source: Option<RedactedSource>,
    cleanup_failure: Option<S3Error>,
    attempts: u32,
    retry_stop_reason: Option<RetryStopReason>,
}

impl S3Error {
    /// Creates an error with a category, safe message, and retry classification.
    pub fn new(
        category: ErrorCategory,
        message: impl Into<String>,
        retry: RetryClassification,
    ) -> Self {
        Self {
            details: Box::new(S3ErrorDetails {
                category,
                code: None,
                status: None,
                message: message.into(),
                request_id: None,
                host_id: None,
                retry,
                timeout_phase: None,
                server_time: None,
                clock_skew: None,
                source: None,
                cleanup_failure: None,
                attempts: 0,
                retry_stop_reason: None,
            }),
        }
    }

    /// Creates a configuration error.
    pub fn configuration(message: impl Into<String>) -> Self {
        Self::new(
            ErrorCategory::Configuration,
            message,
            RetryClassification::Never,
        )
    }

    /// Creates an unsupported-operation error.
    pub fn unsupported(message: impl Into<String>) -> Self {
        Self::new(
            ErrorCategory::UnsupportedOperation,
            message,
            RetryClassification::Never,
        )
    }

    /// Creates a transport error while retaining only a redacted source marker.
    pub fn transport<E>(source: E) -> Self
    where
        E: Error + Send + Sync + 'static,
    {
        Self::new(
            ErrorCategory::Transport,
            "HTTP transport failed",
            RetryClassification::Retryable,
        )
        .with_source(source)
    }

    /// Creates a timeout error.
    pub fn timeout(phase: TimeoutPhase, message: impl Into<String>) -> Self {
        let mut error = Self::new(
            ErrorCategory::Timeout,
            message,
            RetryClassification::Retryable,
        );
        error.details.timeout_phase = Some(phase);
        error
    }

    /// Creates an invalid-response error.
    pub fn invalid_response(message: impl Into<String>) -> Self {
        Self::new(
            ErrorCategory::InvalidResponse,
            message,
            RetryClassification::Never,
        )
    }

    /// Creates an integrity error.
    pub fn integrity(message: impl Into<String>) -> Self {
        Self::new(
            ErrorCategory::Integrity,
            message,
            RetryClassification::Never,
        )
    }

    /// Creates a cancellation error.
    pub fn cancellation(message: impl Into<String>) -> Self {
        Self::new(
            ErrorCategory::Cancellation,
            message,
            RetryClassification::Never,
        )
    }

    /// Attaches parsed S3 response metadata.
    pub(crate) fn with_service_details(
        mut self,
        code: Option<String>,
        status: StatusCode,
        request_id: Option<String>,
        host_id: Option<String>,
    ) -> Self {
        self.details.code = code;
        self.details.status = Some(status);
        self.details.request_id = request_id;
        self.details.host_id = host_id;
        self
    }

    /// Retains the source error's type while discarding potentially sensitive text.
    pub fn with_source<E>(mut self, _source: E) -> Self
    where
        E: Error + Send + Sync + 'static,
    {
        self.details.source = Some(RedactedSource {
            error_type: std::any::type_name::<E>(),
        });
        self
    }

    /// Attaches a cleanup error without replacing the primary failure.
    pub(crate) fn with_cleanup_failure(mut self, cleanup_failure: Self) -> Self {
        self.details.cleanup_failure = Some(cleanup_failure);
        self
    }

    /// Attaches the server time and measured local clock offset.
    pub(crate) fn with_clock_skew(
        mut self,
        server_time: OffsetDateTime,
        local_time: OffsetDateTime,
    ) -> Self {
        self.details.server_time = Some(server_time);
        self.details.clock_skew = Some(server_time - local_time);
        self
    }

    /// Returns the broad error category.
    pub fn category(&self) -> ErrorCategory {
        self.details.category
    }

    /// Returns the S3 error code, when supplied by the service.
    pub fn code(&self) -> Option<&str> {
        self.details.code.as_deref()
    }

    /// Returns the numeric HTTP response status, when a response was received.
    pub fn status(&self) -> Option<u16> {
        self.details.status.map(|status| status.as_u16())
    }

    /// Returns the safe, caller-facing error message.
    pub fn message(&self) -> &str {
        &self.details.message
    }

    /// Returns the S3 request identifier, when supplied by the service.
    pub fn request_id(&self) -> Option<&str> {
        self.details.request_id.as_deref()
    }

    /// Returns the S3 host identifier, when supplied by the service.
    pub fn host_id(&self) -> Option<&str> {
        self.details.host_id.as_deref()
    }

    /// Returns the retry classification.
    pub fn retry_classification(&self) -> RetryClassification {
        self.details.retry
    }

    /// Returns the timeout phase, when this is a timeout error.
    pub fn timeout_phase(&self) -> Option<TimeoutPhase> {
        self.details.timeout_phase
    }

    /// Returns the server's reported time for a clock-skew failure.
    pub fn server_time(&self) -> Option<OffsetDateTime> {
        self.details.server_time
    }

    /// Returns `server_time - local_time` for a clock-skew failure.
    pub fn clock_skew(&self) -> Option<time::Duration> {
        self.details.clock_skew
    }

    /// Returns the cleanup error attached to a primary failure.
    pub fn cleanup_failure(&self) -> Option<&Self> {
        self.details.cleanup_failure.as_ref()
    }

    /// Returns the number of completed request attempts represented by this error.
    pub fn attempts(&self) -> u32 {
        self.details.attempts
    }

    /// Returns why the client did not make another retry attempt.
    pub fn retry_stop_reason(&self) -> Option<RetryStopReason> {
        self.details.retry_stop_reason
    }

    pub(crate) fn with_retry_context(mut self, attempts: u32, reason: RetryStopReason) -> Self {
        self.details.attempts = attempts;
        self.details.retry_stop_reason = Some(reason);
        self
    }
}

impl fmt::Display for S3Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "{:?}: {}",
            self.details.category, self.details.message
        )?;
        if self.details.cleanup_failure.is_some() {
            formatter.write_str(" (cleanup also failed)")?;
        }
        Ok(())
    }
}

impl fmt::Debug for S3Error {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("S3Error")
            .field("category", &self.details.category)
            .field("code", &self.details.code)
            .field("status", &self.details.status)
            .field("message", &self.details.message)
            .field("request_id", &self.details.request_id)
            .field("host_id", &self.details.host_id)
            .field("retry", &self.details.retry)
            .field("attempts", &self.details.attempts)
            .field("retry_stop_reason", &self.details.retry_stop_reason)
            .field("timeout_phase", &self.details.timeout_phase)
            .field("server_time", &self.details.server_time)
            .field("clock_skew", &self.details.clock_skew)
            .field(
                "source",
                &self.details.source.as_ref().map(|_| "[REDACTED]"),
            )
            .field(
                "cleanup_failure",
                &self.details.cleanup_failure.as_ref().map(|_| "[REDACTED]"),
            )
            .finish()
    }
}

impl Error for S3Error {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        self.details
            .source
            .as_ref()
            .map(|source| source as &(dyn Error + 'static))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[derive(Debug)]
    struct SensitiveSource;

    impl fmt::Display for SensitiveSource {
        fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
            formatter.write_str("secret=do-not-print")
        }
    }

    impl Error for SensitiveSource {}

    #[test]
    fn public_error_is_pointer_sized() {
        assert_eq!(std::mem::size_of::<S3Error>(), std::mem::size_of::<usize>());
    }

    #[test]
    fn service_status_is_exposed_without_an_http_type() {
        let error = S3Error::invalid_response("service error").with_service_details(
            Some("NoSuchKey".to_owned()),
            StatusCode::NOT_FOUND,
            None,
            None,
        );
        assert_eq!(error.status(), Some(404));
    }

    #[test]
    fn source_and_cleanup_details_are_redacted() {
        let error = S3Error::transport(SensitiveSource).with_cleanup_failure(
            S3Error::invalid_response("cleanup detail must remain nested"),
        );

        let rendered = format!("{error:?} {error} {}", error.source().unwrap());
        assert!(!rendered.contains("do-not-print"));
        assert!(!rendered.contains("cleanup detail"));
        assert!(rendered.contains("cleanup also failed"));
    }
}