opendal/services/d1/
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;
20use http::StatusCode;
21use serde_json::de;
22
23use super::model::*;
24use crate::raw::*;
25use crate::*;
26
27/// Parse error response into Error.
28pub(super) fn parse_error(resp: Response<Buffer>) -> Error {
29    let (parts, body) = resp.into_parts();
30    let bs = body.to_bytes();
31
32    let (mut kind, mut retryable) = match parts.status {
33        StatusCode::NOT_FOUND => (ErrorKind::NotFound, false),
34        // Some services (like owncloud) return 403 while file locked.
35        StatusCode::FORBIDDEN => (ErrorKind::PermissionDenied, true),
36        // Allowing retry for resource locked.
37        StatusCode::LOCKED => (ErrorKind::Unexpected, true),
38        StatusCode::INTERNAL_SERVER_ERROR
39        | StatusCode::BAD_GATEWAY
40        | StatusCode::SERVICE_UNAVAILABLE
41        | StatusCode::GATEWAY_TIMEOUT => (ErrorKind::Unexpected, true),
42        _ => (ErrorKind::Unexpected, false),
43    };
44
45    let (message, d1_err) = de::from_reader::<_, D1Response>(bs.clone().reader())
46        .map(|d1_err| (format!("{d1_err:?}"), Some(d1_err)))
47        .unwrap_or_else(|_| (String::from_utf8_lossy(&bs).into_owned(), None));
48
49    if let Some(d1_err) = d1_err {
50        (kind, retryable) = parse_d1_error_code(d1_err.errors).unwrap_or((kind, retryable));
51    }
52
53    let mut err = Error::new(kind, message);
54
55    err = with_error_response_context(err, parts);
56
57    if retryable {
58        err = err.set_temporary();
59    }
60
61    err
62}
63
64pub fn parse_d1_error_code(errors: Vec<D1Error>) -> Option<(ErrorKind, bool)> {
65    if errors.is_empty() {
66        return None;
67    }
68
69    match errors[0].code {
70        // The request is malformed: failed to decode id.
71        7400 => Some((ErrorKind::Unexpected, false)),
72        // no such column: Xxxx.
73        7500 => Some((ErrorKind::NotFound, false)),
74        // Authentication error.
75        10000 => Some((ErrorKind::PermissionDenied, false)),
76        _ => None,
77    }
78}