s3 0.1.36

A lean, modern, unofficial 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
use std::{error::Error as StdError, fmt, time::Duration};

use http::StatusCode;

/// Library result type.
pub type Result<T> = std::result::Result<T, Error>;

/// Error type for request building, transport, and API responses.
#[non_exhaustive]
pub enum Error {
    /// Invalid configuration or parameters.
    InvalidConfig {
        /// Human-readable validation failure message.
        message: String,
    },

    /// Request signing failed.
    Signing {
        /// Human-readable signing failure message.
        message: String,
    },

    /// Request was throttled by the service.
    RateLimited {
        /// HTTP status returned by the service.
        status: StatusCode,
        /// Suggested delay before retrying, usually derived from `Retry-After`.
        retry_after: Option<Duration>,
        /// Service request id, when present in headers or the error payload.
        request_id: Option<String>,
        /// Service-specific error code, when present.
        code: Option<String>,
        /// Service-provided error message, when present.
        message: Option<String>,
        /// Service host id, when present.
        host_id: Option<String>,
        /// Truncated response body captured for debugging.
        body_snippet: Option<String>,
    },

    /// Service returned an error response.
    Api {
        /// HTTP status returned by the service.
        status: StatusCode,
        /// Service-specific error code, when present.
        code: Option<String>,
        /// Service-provided error message, when present.
        message: Option<String>,
        /// Service request id, when present in headers or the error payload.
        request_id: Option<String>,
        /// Service host id, when present.
        host_id: Option<String>,
        /// Truncated response body captured for debugging.
        body_snippet: Option<String>,
    },

    /// Transport-level failure (HTTP client, IO, TLS).
    Transport {
        /// Human-readable transport failure message.
        message: String,
        /// Underlying transport error, if preserved.
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    },

    /// Response decode or parse failure.
    Decode {
        /// Human-readable decode failure message.
        message: String,
        /// Underlying decode error, if preserved.
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    },
}

impl fmt::Debug for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidConfig { message } => f
                .debug_struct("InvalidConfig")
                .field("message", message)
                .finish(),
            Self::Signing { message } => {
                f.debug_struct("Signing").field("message", message).finish()
            }
            Self::RateLimited {
                status,
                retry_after,
                request_id,
                code,
                message,
                host_id,
                body_snippet,
            } => f
                .debug_struct("RateLimited")
                .field("status", status)
                .field("retry_after", retry_after)
                .field("request_id", request_id)
                .field("code", code)
                .field("message", message)
                .field("host_id", host_id)
                .field("body_snippet", body_snippet)
                .finish(),
            Self::Api {
                status,
                code,
                message,
                request_id,
                host_id,
                body_snippet,
            } => f
                .debug_struct("Api")
                .field("status", status)
                .field("code", code)
                .field("message", message)
                .field("request_id", request_id)
                .field("host_id", host_id)
                .field("body_snippet", body_snippet)
                .finish(),
            Self::Transport { message, source } => f
                .debug_struct("Transport")
                .field("message", message)
                .field("source", source)
                .finish(),
            Self::Decode { message, source } => f
                .debug_struct("Decode")
                .field("message", message)
                .field("source", source)
                .finish(),
        }
    }
}

impl Error {
    /// Creates an invalid configuration error.
    pub fn invalid_config(message: impl Into<String>) -> Self {
        Self::InvalidConfig {
            message: message.into(),
        }
    }

    /// Creates a signing error.
    pub fn signing(message: impl Into<String>) -> Self {
        Self::Signing {
            message: message.into(),
        }
    }

    /// Creates a transport error with optional source.
    pub fn transport(
        message: impl Into<String>,
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    ) -> Self {
        Self::Transport {
            message: message.into(),
            source,
        }
    }

    /// Creates a decode error with optional source.
    pub fn decode(
        message: impl Into<String>,
        source: Option<Box<dyn StdError + Send + Sync + 'static>>,
    ) -> Self {
        Self::Decode {
            message: message.into(),
            source,
        }
    }

    /// Returns an HTTP status when available.
    pub fn status(&self) -> Option<StatusCode> {
        match self {
            Self::Api { status, .. } => Some(*status),
            Self::RateLimited { status, .. } => Some(*status),
            Self::InvalidConfig { .. }
            | Self::Signing { .. }
            | Self::Transport { .. }
            | Self::Decode { .. } => None,
        }
    }

    /// Returns the request id if reported by the service.
    pub fn request_id(&self) -> Option<&str> {
        match self {
            Self::Api { request_id, .. } | Self::RateLimited { request_id, .. } => {
                request_id.as_deref()
            }
            Self::InvalidConfig { .. }
            | Self::Signing { .. }
            | Self::Transport { .. }
            | Self::Decode { .. } => None,
        }
    }

    /// Returns the service error code when available.
    pub fn code(&self) -> Option<&str> {
        match self {
            Self::Api { code, .. } | Self::RateLimited { code, .. } => code.as_deref(),
            Self::InvalidConfig { .. }
            | Self::Signing { .. }
            | Self::Transport { .. }
            | Self::Decode { .. } => None,
        }
    }

    /// Returns the service error message when available.
    pub fn message(&self) -> Option<&str> {
        match self {
            Self::Api { message, .. } | Self::RateLimited { message, .. } => message.as_deref(),
            Self::InvalidConfig { .. }
            | Self::Signing { .. }
            | Self::Transport { .. }
            | Self::Decode { .. } => None,
        }
    }

    /// Returns the service host id when available.
    pub fn host_id(&self) -> Option<&str> {
        match self {
            Self::Api { host_id, .. } | Self::RateLimited { host_id, .. } => host_id.as_deref(),
            Self::InvalidConfig { .. }
            | Self::Signing { .. }
            | Self::Transport { .. }
            | Self::Decode { .. } => None,
        }
    }

    /// Returns a truncated response body snippet when available.
    pub fn body_snippet(&self) -> Option<&str> {
        match self {
            Self::Api { body_snippet, .. } | Self::RateLimited { body_snippet, .. } => {
                body_snippet.as_deref()
            }
            Self::InvalidConfig { .. }
            | Self::Signing { .. }
            | Self::Transport { .. }
            | Self::Decode { .. } => None,
        }
    }

    /// Returns true if the error is safe to retry.
    pub fn is_retryable(&self) -> bool {
        match self {
            Self::RateLimited { .. } => true,
            Self::Api { status, code, .. } => {
                status.is_server_error()
                    || code.as_deref().is_some_and(is_retryable_service_error_code)
            }
            Self::Transport { .. } => true,
            Self::InvalidConfig { .. } | Self::Signing { .. } | Self::Decode { .. } => false,
        }
    }
}

fn is_retryable_service_error_code(code: &str) -> bool {
    matches!(
        code,
        "RequestTimeout"
            | "RequestTimeoutException"
            | "Throttling"
            | "ThrottlingException"
            | "ThrottledException"
            | "TooManyRequestsException"
            | "RequestLimitExceeded"
            | "SlowDown"
            | "InternalError"
            | "InternalFailure"
            | "ServiceUnavailable"
    )
}

#[cfg(any(feature = "async", feature = "blocking"))]
pub(crate) fn is_rate_limited_service_error_code(code: &str) -> bool {
    matches!(
        code,
        "Throttling"
            | "ThrottlingException"
            | "ThrottledException"
            | "TooManyRequestsException"
            | "RequestLimitExceeded"
            | "SlowDown"
    )
}

fn format_optional_field(label: &str, value: &Option<String>) -> String {
    match value.as_deref() {
        Some(v) if !v.is_empty() => format!(" {label}={v}"),
        _ => String::new(),
    }
}

fn format_optional_message(value: &Option<String>) -> String {
    match value.as_deref() {
        Some(v) if !v.is_empty() => format!(" ({v})"),
        _ => String::new(),
    }
}

impl Error {
    fn format_rate_limited_retry_after(retry_after: &Option<Duration>) -> String {
        match retry_after {
            Some(d) => format!(" (retry after {}s)", d.as_secs()),
            None => String::new(),
        }
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidConfig { message } => write!(f, "invalid config: {message}"),
            Self::Signing { message } => write!(f, "signing error: {message}"),
            Self::RateLimited {
                status,
                retry_after,
                code,
                message,
                request_id,
                host_id,
                ..
            } => {
                let retry_after = Self::format_rate_limited_retry_after(retry_after);
                let code = format_optional_field("code", code);
                let request_id = format_optional_field("request_id", request_id);
                let host_id = format_optional_field("host_id", host_id);
                let msg = format_optional_message(message);
                write!(
                    f,
                    "rate limited: {status}{retry_after}{code}{request_id}{host_id}{msg}"
                )
            }
            Self::Api {
                status,
                code,
                message,
                request_id,
                host_id,
                ..
            } => {
                let code = format_optional_field("code", code);
                let request_id = format_optional_field("request_id", request_id);
                let host_id = format_optional_field("host_id", host_id);
                let msg = format_optional_message(message);
                write!(f, "api error: {status}{code}{request_id}{host_id}{msg}")
            }
            Self::Transport { message, .. } => write!(f, "transport error: {message}"),
            Self::Decode { message, .. } => write!(f, "decode error: {message}"),
        }
    }
}

impl StdError for Error {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        match self {
            Self::Transport { source, .. } | Self::Decode { source, .. } => {
                source.as_deref().map(|e| e as &(dyn StdError + 'static))
            }
            Self::InvalidConfig { .. }
            | Self::Signing { .. }
            | Self::RateLimited { .. }
            | Self::Api { .. } => None,
        }
    }
}

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

    #[test]
    fn api_error_retryability_can_be_driven_by_service_code() {
        let err = Error::Api {
            status: StatusCode::OK,
            code: Some("InternalError".to_string()),
            message: Some("backend failure".to_string()),
            request_id: None,
            host_id: None,
            body_snippet: None,
        };
        assert!(err.is_retryable());
    }

    #[test]
    fn api_error_with_non_retryable_code_and_2xx_status_is_not_retryable() {
        let err = Error::Api {
            status: StatusCode::OK,
            code: Some("AccessDenied".to_string()),
            message: Some("denied".to_string()),
            request_id: None,
            host_id: None,
            body_snippet: None,
        };
        assert!(!err.is_retryable());
    }

    #[test]
    fn api_error_display_includes_host_id_when_available() {
        let err = Error::Api {
            status: StatusCode::FORBIDDEN,
            code: Some("AccessDenied".to_string()),
            message: Some("denied".to_string()),
            request_id: Some("req-1".to_string()),
            host_id: Some("host-1".to_string()),
            body_snippet: None,
        };

        let text = err.to_string();
        assert!(text.contains("request_id=req-1"));
        assert!(text.contains("host_id=host-1"));
    }
}