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
/*
Copyright (C) 2021-2023 Kunal Mehta <legoktm@debian.org>

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */

use serde::Deserialize;
use serde_json::Value;
use std::fmt::{Display, Formatter};
use std::io;
use thiserror::Error as ThisError;

/// Represents a raw MediaWiki API error, with a error code and error message
/// (text). This is also used for warnings since they use the same format.
#[derive(Clone, Debug, Deserialize)]
pub struct ApiError {
    /// Error code
    pub code: String,
    /// Error message
    pub text: String,
    /// Extra data
    pub data: Option<Value>,
}

impl Display for ApiError {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "(code: {}): {}", self.code, self.text)
    }
}

/// Possible errors
#[non_exhaustive]
#[derive(ThisError, Debug)]
pub enum Error {
    /* Request related errors */
    /// A HTTP error like a 4XX or 5XX status code
    #[error("HTTP error: {0}")]
    HttpError(#[from] reqwest::Error),
    /// Invalid header value, likely if the provided OAuth2 token
    /// or User-agent are invalid
    #[error("Invalid header value: {0}")]
    InvalidHeaderValue(#[from] reqwest::header::InvalidHeaderValue),
    /// Error when decoding the JSON response from the API
    #[error("JSON error: {0}")]
    InvalidJson(#[from] serde_json::Error),
    /// Error if unable to get request concurrency lock
    #[error("Unable to get request lock: {0}")]
    LockFailure(#[from] tokio::sync::AcquireError),
    #[error("I/O error: {0}")]
    IoError(#[from] io::Error),
    /// A HTTP error with 429 status code
    #[error("HTTP 429 Too Many Requests")]
    TooManyRequests { retry_after: Option<u64> },

    /* Token issues */
    /// Token invalid or expired
    #[error("Invalid CSRF token")]
    BadToken,
    /// Unable to fetch a CSRF token
    #[error("Unable to get token `{0}`")]
    TokenFailure(String),

    /* User-related issues */
    /// When expected to be logged in but aren't
    #[error("You're not logged in")]
    NotLoggedIn,
    /// When expected to be logged in but aren't
    #[error("You're not logged in as a bot account")]
    NotLoggedInAsBot,

    /* File-related issues */
    #[error("Upload warnings: {0:?}")]
    UploadWarning(Vec<String>),

    /* MediaWiki-side issues */
    #[error("maxlag tripped: {info}")]
    Maxlag {
        info: String,
        retry_after: Option<u64>,
    },
    /// When MediaWiki is in readonly mode
    #[error("MediaWiki is readonly: {info}")]
    Readonly {
        info: String,
        retry_after: Option<u64>,
    },
    /// An internal MediaWiki exception
    #[error("Internal MediaWiki exception: {0}")]
    InternalException(ApiError),

    /* Catchall/generic issues */
    /// Any arbitrary error returned by the MediaWiki API
    #[error("API error: {0}")]
    ApiError(ApiError),
    /// An error where we don't know what to do nor have
    /// information to report back
    #[error("Unknown error: {0}")]
    Unknown(String),
}

impl Error {
    /// Store the value of the retry-after header, if one was present, for
    /// error types that are safe to retry
    pub fn with_retry_after(self, value: u64) -> Self {
        match self {
            Error::TooManyRequests { .. } => Error::TooManyRequests {
                retry_after: Some(value),
            },
            Error::Maxlag { info, .. } => Error::Maxlag {
                info,
                retry_after: Some(value),
            },
            Error::Readonly { info, .. } => Error::Readonly {
                info,
                retry_after: Some(value),
            },
            err => err,
        }
    }

    /// If the error merits a retry, how long should we wait?
    pub fn retry_after(&self) -> Option<u64> {
        match self {
            Error::TooManyRequests { retry_after, .. } => {
                Some((*retry_after).unwrap_or(1))
            }
            Error::Maxlag { retry_after, .. } => {
                Some((*retry_after).unwrap_or(1))
            }
            Error::Readonly { retry_after, .. } => {
                Some((*retry_after).unwrap_or(1))
            }
            _ => None,
        }
    }
}

impl From<ApiError> for Error {
    fn from(apierr: ApiError) -> Self {
        match apierr.code.as_str() {
            "assertuserfailed" => Self::NotLoggedIn,
            "assertbotfailed" => Self::NotLoggedInAsBot,
            "badtoken" => Self::BadToken,
            "maxlag" => Self::Maxlag {
                info: apierr.text,
                retry_after: None,
            },
            "readonly" => Self::Readonly {
                info: apierr.text,
                retry_after: None,
            },
            code => {
                if code.starts_with("internal_api_error_") {
                    Self::InternalException(apierr)
                } else {
                    Self::ApiError(apierr)
                }
            }
        }
    }
}

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

    #[test]
    fn test_from_apierror() {
        let apierr = ApiError {
            code: "assertbotfailed".to_string(),
            text: "Something something".to_string(),
            data: None,
        };
        let err = Error::from(apierr);
        assert!(matches!(err, Error::NotLoggedInAsBot));
    }

    #[test]
    fn test_to_string() {
        let apierr = ApiError {
            code: "errorcode".to_string(),
            text: "Some description".to_string(),
            data: None,
        };
        assert_eq!(&apierr.to_string(), "(code: errorcode): Some description");
    }
}