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
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// SPDX-License-Identifier: Apache-2.0

use std::any;
use std::error::Error;

use thiserror::Error;

use crate::api::PaginationError;
use crate::types::ServiceType;

/// Errors which may occur when creating form data.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum BodyError {
    /// Body data could not be serialized from form parameters.
    #[error("failed to URL encode form parameters: {}", source)]
    UrlEncoded {
        /// The source of the error.
        #[from]
        source: serde_urlencoded::ser::Error,
    },
    #[error("failed to serialize request body: {}", source)]
    Serialize {
        /// The source of the error.
        #[from]
        source: serde_json::Error,
    },
}

/// Errors which may occur when using API endpoints.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum ApiError<E>
where
    E: Error + Send + Sync + 'static,
{
    /// The client encountered an error.
    #[error("client error: {}", source)]
    Client {
        /// The client error.
        source: E,
    },
    /// The URL failed to parse.
    #[error("failed to parse url: {}", source)]
    UrlParse {
        /// The source of the error.
        #[from]
        source: url::ParseError,
    },
    /// Body data could not be created.
    #[error("failed to create form data: {}", source)]
    Body {
        /// The source of the error.
        #[from]
        source: BodyError,
    },
    /// JSON deserialization from OpenStack failed.
    #[error("could not parse JSON response: {}", source)]
    Json {
        /// The source of the error.
        #[from]
        source: serde_json::Error,
    },
    /// Server returned 404.
    #[error("resource not found")]
    ResourceNotFound,
    /// Too many candidates to identitfy resource by identifier
    #[error("cannot uniqly find resource by identifier")]
    IdNotUnique,
    /// OpenStack session error.
    #[error("openstack session error: {}", msg)]
    Session {
        /// The error message from OpenStack.
        msg: String,
    },
    /// OpenStack returned understandable error message
    #[error("openstack server error: {}", msg)]
    OpenStack {
        /// The status code for the return.
        status: http::StatusCode,
        /// The error message from OpenStack.
        msg: String,
    },
    /// OpenStack returned an error without JSON information.
    #[error("openstack internal server error {}", status)]
    OpenStackService {
        /// The status code for the return.
        status: http::StatusCode,
        /// The error data from OpenStack.
        data: String,
    },
    /// OpenStack returned an HTTP error with JSON we did not recognize.
    #[error("openstack server error: {:?}", obj)]
    OpenStackUnrecognized {
        /// The status code for the return.
        status: http::StatusCode,
        /// The full object from OpenStack.
        obj: serde_json::Value,
    },
    /// Failed to parse an expected data type from JSON.
    #[error("could not parse {} data from JSON: {}", typename, source)]
    DataType {
        /// The source of the error.
        source: serde_json::Error,
        /// The name of the type that could not be deserialized.
        typename: &'static str,
    },
    /// An error with pagination occurred.
    #[error("failed to handle for pagination: {}", source)]
    Pagination {
        /// The source of the error.
        #[from]
        source: PaginationError,
    },
    //    #[error("failed to handle for catalog: {}", source)]
    //    Catalog {
    //        /// The source of the error.
    //        #[from]
    //        source: CaralogError,
    //    },
}

impl<E> ApiError<E>
where
    E: Error + Send + Sync + 'static,
{
    /// Create an API error in a client error.
    pub fn client(source: E) -> Self {
        ApiError::Client { source }
    }

    /// Wrap a client error in another wrapper.
    pub fn map_client<F, W>(self, f: F) -> ApiError<W>
    where
        F: FnOnce(E) -> W,
        W: Error + Send + Sync + 'static,
    {
        match self {
            Self::Client { source } => ApiError::client(f(source)),
            Self::UrlParse { source } => ApiError::UrlParse { source },
            Self::Body { source } => ApiError::Body { source },
            Self::Json { source } => ApiError::Json { source },
            Self::OpenStack { status, msg } => ApiError::OpenStack { status, msg },
            Self::Session { msg } => ApiError::Session { msg },
            Self::OpenStackService { status, data } => ApiError::OpenStackService { status, data },
            Self::ResourceNotFound => ApiError::ResourceNotFound,
            Self::IdNotUnique => ApiError::IdNotUnique,
            Self::OpenStackUnrecognized { status, obj } => {
                ApiError::OpenStackUnrecognized { status, obj }
            }
            Self::DataType { source, typename } => ApiError::DataType { source, typename },
            Self::Pagination { source } => ApiError::Pagination { source },
        }
    }

    /// Process server response with no Json body
    pub(crate) fn server_error(status: http::StatusCode, body: &bytes::Bytes) -> Self {
        // Non Json body response ends in this function
        if http::StatusCode::NOT_FOUND.as_u16() == status {
            return ApiError::ResourceNotFound;
        };

        Self::OpenStackService {
            status,
            data: String::from_utf8_lossy(body).into(),
        }
    }

    /// Process server error response with Json body
    pub(crate) fn from_openstack(status: http::StatusCode, value: serde_json::Value) -> Self {
        if http::StatusCode::NOT_FOUND.as_u16() == status {
            return ApiError::ResourceNotFound;
        };

        let error_value = value
            .pointer("/message")
            .or_else(|| value.pointer("/error"));

        if let Some(error_value) = error_value {
            if let Some(msg) = error_value.as_str() {
                // Error we know how to parse
                ApiError::OpenStack {
                    status,
                    msg: msg.into(),
                }
            } else {
                // Error we do not know how to parse
                ApiError::OpenStackUnrecognized {
                    status,
                    obj: error_value.clone(),
                }
            }
        } else {
            ApiError::OpenStackUnrecognized { status, obj: value }
        }
    }

    pub(crate) fn data_type<T>(source: serde_json::Error) -> Self {
        ApiError::DataType {
            source,
            typename: any::type_name::<T>(),
        }
    }

    pub(crate) fn endpoint(service_type: &ServiceType) -> Self {
        ApiError::Session {
            msg: format!("No Endpoint for service `{}`", service_type),
        }
    }
}

#[cfg(test)]
mod tests {
    use serde_json::json;
    use thiserror::Error;

    use crate::api::ApiError;

    #[derive(Debug, Error)]
    #[error("my error")]
    enum MyError {}

    #[test]
    fn openstack_error_error() {
        let obj = json!({
            "error": "error contents",
        });

        let err: ApiError<MyError> =
            ApiError::from_openstack(http::StatusCode::CONFLICT, obj.clone());
        if let ApiError::OpenStack { status, msg } = err {
            assert_eq!(msg, "error contents");
            assert_eq!(status, http::StatusCode::CONFLICT);
        } else {
            panic!("unexpected error: {}", err);
        }
    }

    #[test]
    fn openstack_error_message_string() {
        let obj = json!({
            "message": "error contents",
        });

        let err: ApiError<MyError> =
            ApiError::from_openstack(http::StatusCode::CONFLICT, obj.clone());
        if let ApiError::OpenStack { status, msg } = err {
            assert_eq!(msg, "error contents");
            assert_eq!(status, http::StatusCode::CONFLICT);
        } else {
            panic!("unexpected error: {}", err);
        }
    }

    #[test]
    fn openstack_error_message_object() {
        let err_obj = json!({
            "blah": "foo",
        });
        let obj = json!({
            "message": err_obj,
        });

        let err: ApiError<MyError> =
            ApiError::from_openstack(http::StatusCode::CONFLICT, obj.clone());
        if let ApiError::OpenStackUnrecognized { status, obj } = err {
            assert_eq!(obj, err_obj);
            assert_eq!(status, http::StatusCode::CONFLICT);
        } else {
            panic!("unexpected error: {}", err);
        }
    }

    #[test]
    fn openstack_error_message_unrecognized() {
        let err_obj = json!({
            "some_weird_key": "an even weirder value",
        });

        let err: ApiError<MyError> =
            ApiError::from_openstack(http::StatusCode::CONFLICT, err_obj.clone());
        if let ApiError::OpenStackUnrecognized { status, obj } = err {
            assert_eq!(obj, err_obj);
            assert_eq!(status, http::StatusCode::CONFLICT);
        } else {
            panic!("unexpected error: {}", err);
        }
    }

    #[test]
    fn openstack_error_not_found() {
        let err_obj = json!({
            "some_weird_key": "an even weirder value",
        });

        let err: ApiError<MyError> =
            ApiError::from_openstack(http::StatusCode::NOT_FOUND, err_obj.clone());
        if !matches!(err, ApiError::ResourceNotFound) {
            panic!("unexpected error: {}", err);
        }
    }
}