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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
use serde::{Deserialize, Serialize};
use thiserror::Error;

/// An enum representing the errors that can occur.

#[derive(Debug, Error)]
#[non_exhaustive]
pub enum Error {
    /// The exhaustive list of Meilisearch errors: <https://github.com/meilisearch/specifications/blob/main/text/0061-error-format-and-definitions.md>
    ///
    /// Also check out: <https://github.com/meilisearch/Meilisearch/blob/main/meilisearch-error/src/lib.rs>
    #[error(transparent)]
    Meilisearch(#[from] MeilisearchError),
    #[error(transparent)]
    MeilisearchCommunication(#[from] MeilisearchCommunicationError),
    /// There is no Meilisearch server listening on the [specified host]
    /// (../client/struct.Client.html#method.new).
    #[error("The Meilisearch server can't be reached.")]
    UnreachableServer,
    /// The Meilisearch server returned an invalid JSON for a request.
    #[error("Error parsing response JSON: {}", .0)]
    ParseError(#[from] serde_json::Error),
    /// A timeout happened while waiting for an update to complete.
    #[error("A task did not succeed in time.")]
    Timeout,
    /// This Meilisearch SDK generated an invalid request (which was not sent).
    ///
    /// It probably comes from an invalid API key resulting in an invalid HTTP header.
    #[error("Unable to generate a valid HTTP request. It probably comes from an invalid API key.")]
    InvalidRequest,

    /// Can't call this method without setting an api key in the client.
    #[error("You need to provide an api key to use the `{0}` method.")]
    CantUseWithoutApiKey(String),
    /// It is not possible to generate a tenant token with a invalid api key.
    ///
    /// Empty strings or with less than 8 characters are considered invalid.
    #[error("The provided api_key is invalid.")]
    TenantTokensInvalidApiKey,
    /// It is not possible to generate an already expired tenant token.
    #[error("The provided expires_at is already expired.")]
    TenantTokensExpiredSignature,

    /// When jsonwebtoken cannot generate the token successfully.
    #[error("Impossible to generate the token, jsonwebtoken encountered an error: {}", .0)]
    InvalidTenantToken(#[from] jsonwebtoken::errors::Error),

    /// The http client encountered an error.
    #[cfg(not(target_arch = "wasm32"))]
    #[error("HTTP request failed: {}", .0)]
    HttpError(isahc::Error),

    /// The http client encountered an error.
    #[cfg(target_arch = "wasm32")]
    #[error("HTTP request failed: {}", .0)]
    HttpError(String),

    // The library formating the query parameters encountered an error.
    #[error("Internal Error: could not parse the query parameters: {}", .0)]
    Yaup(#[from] yaup::Error),
    // The library validating the format of an uuid.
    #[cfg(not(target_arch = "wasm32"))]
    #[error("The uid of the token has bit an uuid4 format: {}", .0)]
    Uuid(#[from] uuid::Error),
    // Error thrown in case the version of the Uuid is not v4.
    #[error("The uid provided to the token is not of version uuidv4")]
    InvalidUuid4Version,
}

#[derive(Debug, Clone, Deserialize, Error)]
#[serde(rename_all = "camelCase")]

pub struct MeilisearchCommunicationError {
    pub status_code: u16,
    pub message: Option<String>,
    pub url: String,
}

impl std::fmt::Display for MeilisearchCommunicationError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "MeilisearchCommunicationError: The server responded with a {}.",
            self.status_code
        )?;
        if let Some(message) = &self.message {
            write!(f, " {}", message)?;
        }
        write!(f, "\nurl: {}", self.url)?;
        Ok(())
    }
}

#[derive(Debug, Clone, Deserialize, Error)]
#[serde(rename_all = "camelCase")]
#[error("Meilisearch {}: {}: {}. {}", .error_type, .error_code, .error_message, .error_link)]
pub struct MeilisearchError {
    /// The human readable error message
    #[serde(rename = "message")]
    pub error_message: String,
    /// The error code of the error.  Officially documented at
    /// <https://www.meilisearch.com/docs/reference/errors/error_codes>.
    #[serde(rename = "code")]
    pub error_code: ErrorCode,
    /// The type of error (invalid request, internal error, or authentication error)
    #[serde(rename = "type")]
    pub error_type: ErrorType,
    /// A link to the Meilisearch documentation for an error.
    #[serde(rename = "link")]
    pub error_link: String,
}

/// The type of error that was encountered.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ErrorType {
    /// The submitted request was invalid.
    InvalidRequest,
    /// The Meilisearch instance encountered an internal error.
    Internal,
    /// Authentication was either incorrect or missing.
    Auth,

    /// That's unexpected. Please open a GitHub issue after ensuring you are
    /// using the supported version of the Meilisearch server.
    #[serde(other)]
    Unknown,
}

impl std::fmt::Display for ErrorType {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        write!(
            fmt,
            "{}",
            // this can't fail
            serde_json::to_value(self).unwrap().as_str().unwrap()
        )
    }
}

/// The error code.
///
/// Officially documented at <https://www.meilisearch.com/docs/reference/errors/error_codes>.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ErrorCode {
    IndexCreationFailed,
    IndexAlreadyExists,
    IndexNotFound,
    InvalidIndexUid,
    InvalidState,
    PrimaryKeyInferenceFailed,
    IndexPrimaryKeyAlreadyPresent,
    InvalidStoreFile,
    MaxFieldsLimitExceeded,
    MissingDocumentId,
    InvalidDocumentId,
    BadParameter,
    BadRequest,
    DatabaseSizeLimitReached,
    DocumentNotFound,
    InternalError,
    InvalidApiKey,
    MissingAuthorizationHeader,
    TaskNotFound,
    DumpNotFound,
    MssingMasterKey,
    NoSpaceLeftOnDevice,
    PayloadTooLarge,
    UnretrievableDocument,
    SearchError,
    UnsupportedMediaType,
    DumpAlreadyProcessing,
    DumpProcessFailed,
    MissingContentType,
    MalformedPayload,
    InvalidContentType,
    MissingPayload,
    InvalidApiKeyDescription,
    InvalidApiKeyActions,
    InvalidApiKeyIndexes,
    InvalidApiKeyExpiresAt,
    ApiKeyNotFound,
    MissingTaskFilters,
    MissingIndexUid,
    InvalidIndexOffset,
    InvalidIndexLimit,
    InvalidIndexPrimaryKey,
    InvalidDocumentFilter,
    MissingDocumentFilter,
    InvalidDocumentFields,
    InvalidDocumentLimit,
    InvalidDocumentOffset,
    InvalidDocumentGeoField,
    InvalidSearchQ,
    InvalidSearchOffset,
    InvalidSearchLimit,
    InvalidSearchPage,
    InvalidSearchHitsPerPage,
    InvalidSearchAttributesToRetrieve,
    InvalidSearchAttributesToCrop,
    InvalidSearchCropLength,
    InvalidSearchAttributesToHighlight,
    InvalidSearchShowMatchesPosition,
    InvalidSearchFilter,
    InvalidSearchSort,
    InvalidSearchFacets,
    InvalidSearchHighlightPreTag,
    InvalidSearchHighlightPostTag,
    InvalidSearchCropMarker,
    InvalidSearchMatchingStrategy,
    ImmutableApiKeyUid,
    ImmutableApiKeyActions,
    ImmutableApiKeyIndexes,
    ImmutableExpiresAt,
    ImmutableCreatedAt,
    ImmutableUpdatedAt,
    InvalidSwapDuplicateIndexFound,
    InvalidSwapIndexes,
    MissingSwapIndexes,
    InvalidTaskTypes,
    InvalidTaskUids,
    InvalidTaskStatuses,
    InvalidTaskLimit,
    InvalidTaskFrom,
    InvalidTaskCanceledBy,
    InvalidTaskFilters,
    TooManyOpenFiles,
    IoError,
    InvalidTaskIndexUids,
    ImmutableIndexUid,
    ImmutableIndexCreatedAt,
    ImmutableIndexUpdatedAt,
    InvalidSettingsDisplayedAttributes,
    InvalidSettingsSearchableAttributes,
    InvalidSettingsFilterableAttributes,
    InvalidSettingsSortableAttributes,
    InvalidSettingsRankingRules,
    InvalidSettingsStopWords,
    InvalidSettingsSynonyms,
    InvalidSettingsDistinctAttributes,
    InvalidSettingsTypoTolerance,
    InvalidSettingsFaceting,
    InvalidSettingsPagination,
    InvalidTaskBeforeEnqueuedAt,
    InvalidTaskAfterEnqueuedAt,
    InvalidTaskBeforeStartedAt,
    InvalidTaskAfterStartedAt,
    InvalidTaskBeforeFinishedAt,
    InvalidTaskAfterFinishedAt,
    MissingApiKeyActions,
    MissingApiKeyIndexes,
    MissingApiKeyExpiresAt,
    InvalidApiKeyLimit,
    InvalidApiKeyOffset,

    /// That's unexpected. Please open a GitHub issue after ensuring you are
    /// using the supported version of the Meilisearch server.
    #[serde(other)]
    Unknown,
}

pub const MEILISEARCH_VERSION_HINT: &str = "Hint: It might not be working because you're not up to date with the Meilisearch version that updated the get_documents_with method";

impl std::fmt::Display for ErrorCode {
    fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::result::Result<(), std::fmt::Error> {
        write!(
            fmt,
            "{}",
            // this can't fail
            serde_json::to_value(self).unwrap().as_str().unwrap()
        )
    }
}

#[cfg(not(target_arch = "wasm32"))]
impl From<isahc::Error> for Error {
    fn from(error: isahc::Error) -> Error {
        if error.kind() == isahc::error::ErrorKind::ConnectionFailed {
            Error::UnreachableServer
        } else {
            Error::HttpError(error)
        }
    }
}

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

    use jsonwebtoken::errors::ErrorKind::InvalidToken;
    use uuid::Uuid;

    #[test]
    fn test_meilisearch_error() {
        let error: MeilisearchError = serde_json::from_str(
            r#"
{
  "message": "The cool error message.",
  "code": "index_creation_failed",
  "type": "internal",
  "link": "https://the best link eveer"
}"#,
        )
        .unwrap();

        assert_eq!(error.error_message, "The cool error message.");
        assert_eq!(error.error_code, ErrorCode::IndexCreationFailed);
        assert_eq!(error.error_type, ErrorType::Internal);
        assert_eq!(error.error_link, "https://the best link eveer");

        let error: MeilisearchError = serde_json::from_str(
            r#"
{
  "message": "",
  "code": "An unknown error",
  "type": "An unknown type",
  "link": ""
}"#,
        )
        .unwrap();

        assert_eq!(error.error_code, ErrorCode::Unknown);
        assert_eq!(error.error_type, ErrorType::Unknown);
    }

    #[test]
    fn test_error_message_parsing() {
        let error: MeilisearchError = serde_json::from_str(
            r#"
{
  "message": "The cool error message.",
  "code": "index_creation_failed",
  "type": "internal",
  "link": "https://the best link eveer"
}"#,
        )
        .unwrap();

        assert_eq!(error.to_string(), ("Meilisearch internal: index_creation_failed: The cool error message.. https://the best link eveer"));

        let error: MeilisearchCommunicationError = MeilisearchCommunicationError {
            status_code: 404,
            message: Some("Hint: something.".to_string()),
            url: "http://localhost:7700/something".to_string(),
        };

        assert_eq!(
            error.to_string(),
            ("MeilisearchCommunicationError: The server responded with a 404. Hint: something.\nurl: http://localhost:7700/something")
        );

        let error: MeilisearchCommunicationError = MeilisearchCommunicationError {
            status_code: 404,
            message: None,
            url: "http://localhost:7700/something".to_string(),
        };

        assert_eq!(
            error.to_string(),
            ("MeilisearchCommunicationError: The server responded with a 404.\nurl: http://localhost:7700/something")
        );

        let error = Error::UnreachableServer;
        assert_eq!(
            error.to_string(),
            "The Meilisearch server can't be reached."
        );

        let error = Error::Timeout;
        assert_eq!(error.to_string(), "A task did not succeed in time.");

        let error = Error::InvalidRequest;
        assert_eq!(
            error.to_string(),
            "Unable to generate a valid HTTP request. It probably comes from an invalid API key."
        );

        let error = Error::TenantTokensInvalidApiKey;
        assert_eq!(error.to_string(), "The provided api_key is invalid.");

        let error = Error::TenantTokensExpiredSignature;
        assert_eq!(
            error.to_string(),
            "The provided expires_at is already expired."
        );

        let error = Error::InvalidUuid4Version;
        assert_eq!(
            error.to_string(),
            "The uid provided to the token is not of version uuidv4"
        );

        let error = Error::Uuid(Uuid::parse_str("67e55044").unwrap_err());
        assert_eq!(error.to_string(), "The uid of the token has bit an uuid4 format: invalid length: expected length 32 for simple format, found 8");

        let data = r#"
        {
            "name": "John Doe"
            "age": 43,
        }"#;

        let error = Error::ParseError(serde_json::from_str::<String>(data).unwrap_err());
        assert_eq!(
            error.to_string(),
            "Error parsing response JSON: invalid type: map, expected a string at line 2 column 8"
        );

        let error = Error::HttpError(isahc::post("test_url", "test_body").unwrap_err());
        assert_eq!(
            error.to_string(),
            "HTTP request failed: failed to resolve host name"
        );

        let error = Error::InvalidTenantToken(jsonwebtoken::errors::Error::from(InvalidToken));
        assert_eq!(
            error.to_string(),
            "Impossible to generate the token, jsonwebtoken encountered an error: InvalidToken"
        );

        let error = Error::Yaup(yaup::error::Error::Custom("Test yaup error".to_string()));
        assert_eq!(
            error.to_string(),
            "Internal Error: could not parse the query parameters: Test yaup error"
        );
    }
}