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
//! Ditto Error Types
//!
//! Modeled after std::io::error::Error;

use std::{convert::Infallible, error::Error as ErrorTrait, fmt};

use crate::{
    auth::authenticator::AuthenticationClientFeedback,
    ffi_sdk::{self, ffi_utils::repr_c},
};

/// Custom result type for Ditto
pub type Result<Ok, Err = DittoError> = ::core::result::Result<Ok, Err>;

/// Custom error for Ditto
pub struct DittoError {
    repr: Repr,
}

enum Repr {
    Simple(ErrorKind),
    Authentication(AuthenticationClientFeedback),
    FfiLegacy(legacy::FfiError),
    Rust(RustError),
    License(LicenseError),
}

/// Error related to License
pub enum LicenseError {
    LicenseTokenVerificationFailed { message: String },
    LicenseTokenExpired { message: String },
    LicenseTokenUnsupportedFutureVersion { message: String },
}

impl LicenseError {
    /// Returns the internal error message for more details
    pub fn message(&self) -> &String {
        match self {
            LicenseError::LicenseTokenVerificationFailed { message } => message,
            LicenseError::LicenseTokenExpired { message } => message,
            LicenseError::LicenseTokenUnsupportedFutureVersion { message } => message,
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
/// General kind of an error
pub enum ErrorKind {
    /// Configured Authentication provider was not found or failed to authenticate
    Authentication,

    /// Required configuration was missing or invalid
    Config, // use to distinguish misconfigured from invalid query/document/etc.

    /// Error originated in the FFI layer
    FfiLegacy, // use this when you can't re-map into a Rust Error

    /// An error occurred in Ditto's internals
    Internal,

    /// Provided parameters or data are not valid
    InvalidInput, // use when user input fails validation

    /// Error with the local file system or networking
    IO, // re-maps std::io::error types (Filesystem and Network), including missing local files

    /// The Ditto license is missing, expired, or otherwise invalid
    License, // specifically when the License is not valid

    /// Ditto sync was started without a valid license
    NotActivated, // When Sync started before license validation

    /// The requested resource *no longer* exists (i.e. lost or destroyed)
    /// Used typically for empty query results
    NonExtant, // when a requested resource doesn't exist

    /// The requested Ditto instance has already been dropped
    ReleasedDittoInstance,
}

impl ErrorKind {
    // TODO(Daniel): see how to replace this with the current `FfiErrorCode`.
    #[allow(nonstandard_style)]
    #[deprecated]
    pub const Ffi: Self = Self::FfiLegacy;
}

// FIXME(Daniel): remove this from the Rust SDK's public API.
#[deprecated]
pub use legacy::FfiError;

/// A datastructure representing an error from the FFI using the legacy mechanisms
/// (thread-local storage and integer error code).
mod legacy {
    // TODO(pub_check): If this is public then it should probably be named in a more
    // customer-friendly way
    /// Errors originating in FFI code.
    ///
    /// Shadows the FFI's CError type which doesn't have a C Repr.
    pub struct FfiError {
        pub code: i32,
        pub msg: String,
    }
}

/// Errors originating in Rust Code
pub struct RustError {
    pub kind: ErrorKind,
    pub error: Box<dyn ErrorTrait + Send + Sync>,
}

impl fmt::Debug for RustError {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        // Display both the ErrorKind Varriend but also the message text
        let msg = format!("{:?} - {}", &self.kind, self.kind.as_str());
        fmt.debug_struct("RustError")
            .field("kind", &msg)
            .field("error", &self.error) // Then also display underlying cause info
            .finish()
    }
}

impl ErrorKind {
    pub fn as_str(&self) -> &'static str {
        match *self {
            ErrorKind::Authentication => "Unable to authenticate Ditto",
            ErrorKind::Config => "Required configuration values are missing or invalid",
            ErrorKind::FfiLegacy => "Unmapped Ditto Error",
            ErrorKind::IO => "There is a problem with the underlying file, directory, or network socket",
            ErrorKind::Internal => "Ditto encountered an internal error",
            ErrorKind::InvalidInput => "Invalid client input provided",
            ErrorKind::License => "License token error",
            ErrorKind::NotActivated => "Sync could not be started because Ditto has not yet been activated. This can be achieved with a successful call to `set_license_token`. If you need to obtain a license token then please visit https://portal.ditto.live.",
            ErrorKind::NonExtant => "The target entity can no longer be found",
            ErrorKind::ReleasedDittoInstance => "The related Ditto instance has been closed",
        }
    }
}

impl From<ErrorKind> for DittoError {
    fn from(kind: ErrorKind) -> DittoError {
        DittoError {
            repr: Repr::Simple(kind),
        }
    }
}

impl fmt::Debug for DittoError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.repr, f)
    }
}

impl ErrorTrait for DittoError {}

impl DittoError {
    /// Construct an error from an existing Error creating an error chain
    pub(crate) fn new<E>(kind: ErrorKind, rust_err: E) -> DittoError
    where
        E: Into<Box<dyn ErrorTrait + Send + Sync>>,
    {
        DittoError {
            repr: Repr::Rust(RustError {
                kind,
                error: rust_err.into(),
            }),
        }
    }

    /// Construct an error with a specific message from a string
    pub(crate) fn from_str(kind: ErrorKind, msg: impl Into<String>) -> DittoError {
        let msg: String = msg.into();
        DittoError {
            repr: Repr::Rust(RustError {
                kind,
                error: msg.into(),
            }),
        }
    }

    /// Construct an error from a small peer info error code
    pub(crate) fn from_small_peer_info_error_code(error_code: i32) -> DittoError {
        match error_code {
            -1 => Self::from_str(
                ErrorKind::InvalidInput,
                "The observability subsystem is unavailable",
            ),
            1 => Self::from_str(
                ErrorKind::InvalidInput,
                "The amount of data is too large according to our self-imposed limits.",
            ),
            2 => Self::from_str(
                ErrorKind::InvalidInput,
                "The amount of JSON data is too nested acccording to out self-imposed limits, or \
                 if the data cannot be parsed to determine the depth.",
            ),
            3 => Self::from_str(
                ErrorKind::InvalidInput,
                "The data cannot be parsed as a Map<String, Value>.",
            ),
            _ => Self::from_str(ErrorKind::FfiLegacy, "Unmapped error"),
        }
    }

    /// Construct an error from a LicenseError
    pub(crate) fn license(err: LicenseError) -> DittoError {
        DittoError {
            repr: Repr::License(err),
        }
    }

    /// Manually specify the Error Kind, but fetch the message from the FFI.
    ///
    /// The result is returned as a Rust style error with the cause of `<String as ErrorTrait>`
    pub(crate) fn from_ffi(kind: ErrorKind) -> DittoError {
        let msg = match ffi_sdk::ditto_error_message() {
            Some(c_msg) => c_msg.into_string(),
            None => "no message".into(),
        };
        DittoError::new(kind, msg)
    }

    /// Return the kind of the Error
    pub fn kind(&self) -> ErrorKind {
        match &self.repr {
            Repr::Simple(kind) => *kind,
            Repr::Rust(e) => e.kind,
            Repr::FfiLegacy(_c) => ErrorKind::FfiLegacy, // could implement uniform code to kind
            // mapping in future
            Repr::License(_) => ErrorKind::License,
            Repr::Authentication(_) => ErrorKind::Authentication,
        }
    }

    // TODO(pub_check)
    pub fn get_authentication_client_feedback(&self) -> Option<AuthenticationClientFeedback> {
        if let Repr::Authentication(ref feedback) = self.repr {
            Some(feedback.clone())
        } else {
            None
        }
    }

    // We may want to evolve how this is constructed, so let's not expose it to customers yet
    pub(crate) fn from_authentication_feedback(feedback: AuthenticationClientFeedback) -> Self {
        DittoError {
            repr: Repr::Authentication(feedback),
        }
    }
}

impl fmt::Debug for Repr {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        match *self {
            Repr::Simple(kind) => fmt.debug_tuple("Kind").field(&kind).finish(),
            Repr::Rust(ref e) => fmt::Debug::fmt(&e, fmt),
            Repr::FfiLegacy(ref c) => fmt
                .debug_struct("FFILegacyError")
                .field("code", &c.code)
                .field("message", &c.msg)
                .field("kind", &ErrorKind::FfiLegacy)
                .finish(),
            Repr::License(ref e) => fmt
                .debug_struct("LicenseTokenError")
                .field("message", e.message())
                .field("kind", &ErrorKind::License)
                .finish(),
            Repr::Authentication(ref feedback) => fmt
                .debug_struct("AuthenticationError")
                .field("Feedback", &feedback.feedback)
                .finish(),
        }
    }
}

impl fmt::Display for DittoError {
    fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.repr {
            Repr::Simple(kind) => write!(fmt, "{}", kind.as_str()),
            Repr::Rust(ref e) => e.error.fmt(fmt), // forward to cause error
            Repr::FfiLegacy(ref c) => write!(fmt, "{} (code {})", c.msg, c.code),
            Repr::License(ref e) => write!(fmt, "{}", e.message()),
            Repr::Authentication(ref feedback) => match feedback.feedback {
                Some(ref feedback) => {
                    write!(fmt, "Authentication Error with feedback: {}", feedback)
                }
                None => {
                    write!(fmt, "Authentication Error")
                }
            },
        }
    }
}

error_from_i32! {
    i32, ::core::num::NonZeroI32
}
#[rustfmt::skip]
macro_rules! error_from_i32 {(
    $( $i32:ty ),* $(,)?
) => (
    $(
        impl From<$i32> for FfiError {
            fn from(code: $i32) -> FfiError {
                let code: i32 = code.into();
                debug_assert_ne!(code, 0);
                match ffi_sdk::ditto_error_message() {
                    Some(c_msg) => {
                        let msg = c_msg.into_string();
                        FfiError { code, msg }
                    }
                    None => FfiError {
                        msg: "No Message".to_owned(),
                        code,
                    },
                }
            }
        }

        impl From<$i32> for DittoError {
            fn from(code: $i32) -> DittoError {
                DittoError { repr: Repr::FfiLegacy(code.into()) }
            }
        }
    )*
)}
use error_from_i32;

impl From<::serde_cbor::Error> for DittoError {
    fn from(err: ::serde_cbor::Error) -> Self {
        DittoError::new(ErrorKind::InvalidInput, err)
    }
}

impl From<::serde_json::Error> for DittoError {
    fn from(err: ::serde_json::Error) -> Self {
        DittoError::new(ErrorKind::InvalidInput, err)
    }
}

impl From<::std::io::Error> for DittoError {
    fn from(err: ::std::io::Error) -> Self {
        DittoError::new(ErrorKind::IO, err)
    }
}

impl From<Infallible> for DittoError {
    fn from(err: Infallible) -> Self {
        DittoError::new(ErrorKind::Internal, err)
    }
}

impl From<repr_c::Box_<ffi_sdk::FfiError>> for DittoError {
    fn from(err: repr_c::Box<ffi_sdk::FfiError>) -> Self {
        let err_code = ffi_sdk::dittoffi_error_code(&*err);
        let raw_description = ffi_sdk::dittoffi_error_description(&*err);

        DittoError {
            repr: Repr::FfiLegacy(legacy::FfiError {
                code: err_code as i32,
                msg: raw_description.to_string(),
            }),
        }
    }
}