opendal/services/s3/
error.rs

1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements.  See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership.  The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with the License.  You may obtain a copy of the License at
8//
9//   http://www.apache.org/licenses/LICENSE-2.0
10//
11// Unless required by applicable law or agreed to in writing,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied.  See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use bytes::Buf;
19use http::response::Parts;
20use http::Response;
21use quick_xml::de;
22use serde::Deserialize;
23
24use crate::raw::*;
25use crate::*;
26
27/// S3Error is the error returned by s3 service.
28#[derive(Default, Debug, Deserialize, PartialEq, Eq)]
29#[serde(default, rename_all = "PascalCase")]
30pub(crate) struct S3Error {
31    pub code: String,
32    pub message: String,
33    pub resource: String,
34    pub request_id: String,
35}
36
37/// Parse error response into Error.
38pub(super) fn parse_error(resp: Response<Buffer>) -> Error {
39    let (parts, body) = resp.into_parts();
40    let bs = body.to_bytes();
41
42    let (mut kind, mut retryable) = match parts.status.as_u16() {
43        403 => (ErrorKind::PermissionDenied, false),
44        404 => (ErrorKind::NotFound, false),
45        304 | 412 => (ErrorKind::ConditionNotMatch, false),
46        // Service like R2 could return 499 error with a message like:
47        // Client Disconnect, we should retry it.
48        499 => (ErrorKind::Unexpected, true),
49        500 | 502 | 503 | 504 => (ErrorKind::Unexpected, true),
50        429 => (ErrorKind::RateLimited, true),
51        _ => (ErrorKind::Unexpected, false),
52    };
53
54    let body_content = bs.chunk();
55    let (message, s3_err) = de::from_reader::<_, S3Error>(body_content.reader())
56        .map(|s3_err| (format!("{s3_err:?}"), Some(s3_err)))
57        .unwrap_or_else(|_| (String::from_utf8_lossy(&bs).into_owned(), None));
58
59    if let Some(s3_err) = s3_err {
60        (kind, retryable) = parse_s3_error_code(s3_err.code.as_str()).unwrap_or((kind, retryable));
61    }
62
63    let mut err = Error::new(kind, message);
64
65    err = with_error_response_context(err, parts);
66
67    if retryable {
68        err = err.set_temporary();
69    }
70
71    err
72}
73
74/// Util function to build [`Error`] from a [`S3Error`] object.
75pub(crate) fn from_s3_error(s3_error: S3Error, parts: Parts) -> Error {
76    let (kind, retryable) =
77        parse_s3_error_code(s3_error.code.as_str()).unwrap_or((ErrorKind::Unexpected, false));
78    let mut err = Error::new(kind, format!("{s3_error:?}"));
79
80    err = with_error_response_context(err, parts);
81
82    if retryable {
83        err = err.set_temporary();
84    }
85
86    err
87}
88
89/// Returns the `Error kind` of this code and whether the error is retryable.
90/// All possible error code: <https://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html#ErrorCodeList>
91pub fn parse_s3_error_code(code: &str) -> Option<(ErrorKind, bool)> {
92    match code {
93        // > The specified bucket does not exist.
94        //
95        // Although the status code is 404, NoSuchBucket is
96        // a config invalid error, and it's not retryable from OpenDAL.
97        "NoSuchBucket" => Some((ErrorKind::ConfigInvalid, false)),
98        // > Your socket connection to the server was not read from
99        // > or written to within the timeout period."
100        //
101        // It's Ok for us to retry it again.
102        "RequestTimeout" => Some((ErrorKind::Unexpected, true)),
103        // > An internal error occurred. Try again.
104        "InternalError" => Some((ErrorKind::Unexpected, true)),
105        // > A conflicting conditional operation is currently in progress
106        // > against this resource. Try again.
107        "OperationAborted" => Some((ErrorKind::Unexpected, true)),
108        // > Please reduce your request rate.
109        //
110        // It's Ok to retry since later on the request rate may get reduced.
111        "SlowDown" => Some((ErrorKind::RateLimited, true)),
112        // > Service is unable to handle request.
113        //
114        // ServiceUnavailable is considered a retryable error because it typically
115        // indicates a temporary issue with the service or server, such as high load,
116        // maintenance, or an internal problem.
117        "ServiceUnavailable" => Some((ErrorKind::Unexpected, true)),
118        // > Too Many Requests - rate limit exceeded.
119        //
120        // It's Ok to retry since later on the request rate may get reduced.
121        "TooManyRequests" => Some((ErrorKind::RateLimited, true)),
122        _ => None,
123    }
124}
125
126#[cfg(test)]
127mod tests {
128    use super::*;
129
130    /// Error response example is from https://docs.aws.amazon.com/AmazonS3/latest/API/ErrorResponses.html
131    #[test]
132    fn test_parse_error() {
133        let bs = bytes::Bytes::from(
134            r#"
135<?xml version="1.0" encoding="UTF-8"?>
136<Error>
137  <Code>NoSuchKey</Code>
138  <Message>The resource you requested does not exist</Message>
139  <Resource>/mybucket/myfoto.jpg</Resource>
140  <RequestId>4442587FB7D0A2F9</RequestId>
141</Error>
142"#,
143        );
144
145        let out: S3Error = de::from_reader(bs.reader()).expect("must success");
146        println!("{out:?}");
147
148        assert_eq!(out.code, "NoSuchKey");
149        assert_eq!(out.message, "The resource you requested does not exist");
150        assert_eq!(out.resource, "/mybucket/myfoto.jpg");
151        assert_eq!(out.request_id, "4442587FB7D0A2F9");
152    }
153
154    #[test]
155    fn test_parse_error_from_unrelated_input() {
156        let bs = bytes::Bytes::from(
157            r#"
158<?xml version="1.0" encoding="UTF-8"?>
159<CompleteMultipartUploadResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
160  <Location>http://Example-Bucket.s3.ap-southeast-1.amazonaws.com/Example-Object</Location>
161  <Bucket>Example-Bucket</Bucket>
162  <Key>Example-Object</Key>
163  <ETag>"3858f62230ac3c915f300c664312c11f-9"</ETag>
164</CompleteMultipartUploadResult>
165"#,
166        );
167
168        let out: S3Error = de::from_reader(bs.reader()).expect("must success");
169        assert_eq!(out, S3Error::default());
170    }
171}