inferadb 0.1.5

Official Rust SDK for InferaDB
Documentation
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
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
//! Main error type for the InferaDB SDK.

use std::borrow::Cow;
use std::error::Error as StdError;
use std::fmt;
use std::time::Duration;

use super::ErrorKind;

/// The primary error type for InferaDB SDK operations.
///
/// `Error` provides rich context for debugging and error handling:
/// - [`kind()`](Error::kind): Categorization for `match` statements
/// - [`request_id()`](Error::request_id): Correlation ID for support
/// - [`retry_after()`](Error::retry_after): Delay hint for rate limits
/// - [`is_retriable()`](Error::is_retriable): Quick retry decision
///
/// ## Error Hierarchy
///
/// ```text
/// Error
/// ├── kind: ErrorKind          (category for matching)
/// ├── message: String          (human-readable description)
/// ├── request_id: Option       (server-assigned correlation ID)
/// ├── retry_after: Option      (rate limit delay hint)
/// └── source: Option           (underlying cause)
/// ```
///
/// ## Example
///
/// ```rust
/// use inferadb::{Error, ErrorKind};
///
/// fn handle_error(err: Error) {
///     match err.kind() {
///         ErrorKind::RateLimited => {
///             if let Some(delay) = err.retry_after() {
///                 println!("Rate limited, retry after {:?}", delay);
///             }
///         }
///         ErrorKind::Unauthorized => {
///             println!("Invalid credentials");
///         }
///         kind if kind.is_retriable() => {
///             println!("Transient error, will retry");
///         }
///         _ => {
///             println!("Permanent error: {}", err);
///         }
///     }
///
///     // Always log request_id for support
///     if let Some(id) = err.request_id() {
///         eprintln!("Request ID: {}", id);
///     }
/// }
/// ```
#[derive(Debug)]
pub struct Error {
    /// The error category.
    kind: ErrorKind,

    /// Human-readable error message.
    message: Cow<'static, str>,

    /// Server-assigned request ID for correlation.
    request_id: Option<String>,

    /// Recommended delay before retrying (for rate limits).
    retry_after: Option<Duration>,

    /// The underlying error, if any.
    source: Option<Box<dyn StdError + Send + Sync + 'static>>,
}

impl Error {
    /// Creates a new error with the given kind and message.
    ///
    /// # Example
    ///
    /// ```rust
    /// use inferadb::{Error, ErrorKind};
    ///
    /// let err = Error::new(ErrorKind::InvalidArgument, "subject cannot be empty");
    /// assert_eq!(err.kind(), ErrorKind::InvalidArgument);
    /// ```
    pub fn new(kind: ErrorKind, message: impl Into<Cow<'static, str>>) -> Self {
        Self {
            kind,
            message: message.into(),
            request_id: None,
            retry_after: None,
            source: None,
        }
    }

    /// Creates an error from a kind with a default message.
    pub fn from_kind(kind: ErrorKind) -> Self {
        let message = match kind {
            ErrorKind::Unauthorized => "authentication failed",
            ErrorKind::Forbidden => "permission denied",
            ErrorKind::NotFound => "resource not found",
            ErrorKind::InvalidArgument => "invalid argument",
            ErrorKind::SchemaViolation => "schema violation",
            ErrorKind::RateLimited => "rate limit exceeded",
            ErrorKind::Unavailable => "service unavailable",
            ErrorKind::Timeout => "request timed out",
            ErrorKind::Internal => "internal server error",
            ErrorKind::Cancelled => "request cancelled",
            ErrorKind::CircuitOpen => "circuit breaker open",
            ErrorKind::Connection => "connection failed",
            ErrorKind::Protocol => "protocol error",
            ErrorKind::Configuration => "configuration error",
            ErrorKind::Unknown => "unknown error",
            ErrorKind::Conflict => "resource conflict",
            ErrorKind::Transport => "transport error",
            ErrorKind::InvalidResponse => "invalid response",
        };
        Self::new(kind, message)
    }

    /// Returns the error kind for categorization.
    ///
    /// Use this for `match` expressions to handle different error types:
    ///
    /// ```rust
    /// use inferadb::{Error, ErrorKind};
    ///
    /// fn should_retry(err: &Error) -> bool {
    ///     err.kind().is_retriable()
    /// }
    /// ```
    #[inline]
    pub fn kind(&self) -> ErrorKind {
        self.kind
    }

    /// Returns the server-assigned request ID, if available.
    ///
    /// Always include this in error logs for support correlation:
    ///
    /// ```rust
    /// use inferadb::Error;
    ///
    /// fn log_error(err: &Error) {
    ///     if let Some(request_id) = err.request_id() {
    ///         eprintln!("Error (request_id: {}): {}", request_id, err);
    ///     } else {
    ///         eprintln!("Error: {}", err);
    ///     }
    /// }
    /// ```
    #[inline]
    pub fn request_id(&self) -> Option<&str> {
        self.request_id.as_deref()
    }

    /// Returns the recommended retry delay for rate limit errors.
    ///
    /// This is populated from the `Retry-After` header or equivalent.
    /// Always prefer this value over a fixed delay for rate limit handling.
    ///
    /// ```rust
    /// use inferadb::{Error, ErrorKind};
    /// use std::time::Duration;
    ///
    /// async fn with_rate_limit_handling<T, F, Fut>(f: F) -> Result<T, Error>
    /// where
    ///     F: Fn() -> Fut,
    ///     Fut: std::future::Future<Output = Result<T, Error>>,
    /// {
    ///     loop {
    ///         match f().await {
    ///             Ok(v) => return Ok(v),
    ///             Err(e) if e.kind() == ErrorKind::RateLimited => {
    ///                 let delay = e.retry_after().unwrap_or(Duration::from_secs(1));
    ///                 tokio::time::sleep(delay).await;
    ///             }
    ///             Err(e) => return Err(e),
    ///         }
    ///     }
    /// }
    /// ```
    #[inline]
    pub fn retry_after(&self) -> Option<Duration> {
        self.retry_after
    }

    /// Returns `true` if this error is generally safe to retry.
    ///
    /// This is a convenience method equivalent to `self.kind().is_retriable()`.
    ///
    /// Retriable errors include:
    /// - `Unavailable` - service temporarily down
    /// - `Timeout` - request timed out
    /// - `RateLimited` - rate limit exceeded (use `retry_after()`)
    /// - `CircuitOpen` - circuit breaker tripped
    /// - `Connection` - network connectivity issues
    #[inline]
    pub fn is_retriable(&self) -> bool {
        self.kind.is_retriable()
    }

    /// Sets the request ID for this error.
    #[must_use]
    pub fn with_request_id(mut self, request_id: impl Into<String>) -> Self {
        self.request_id = Some(request_id.into());
        self
    }

    /// Sets the retry-after duration for this error.
    #[must_use]
    pub fn with_retry_after(mut self, duration: Duration) -> Self {
        self.retry_after = Some(duration);
        self
    }

    /// Sets the source error for this error.
    #[must_use]
    pub fn with_source<E>(mut self, source: E) -> Self
    where
        E: StdError + Send + Sync + 'static,
    {
        self.source = Some(Box::new(source));
        self
    }

    // Convenience constructors for common error types

    /// Creates an unauthorized error.
    pub fn unauthorized(message: impl Into<Cow<'static, str>>) -> Self {
        Self::new(ErrorKind::Unauthorized, message)
    }

    /// Creates a forbidden error.
    pub fn forbidden(message: impl Into<Cow<'static, str>>) -> Self {
        Self::new(ErrorKind::Forbidden, message)
    }

    /// Creates a not found error.
    pub fn not_found(message: impl Into<Cow<'static, str>>) -> Self {
        Self::new(ErrorKind::NotFound, message)
    }

    /// Creates an invalid argument error.
    pub fn invalid_argument(message: impl Into<Cow<'static, str>>) -> Self {
        Self::new(ErrorKind::InvalidArgument, message)
    }

    /// Creates a schema violation error.
    pub fn schema_violation(message: impl Into<Cow<'static, str>>) -> Self {
        Self::new(ErrorKind::SchemaViolation, message)
    }

    /// Creates a rate limited error.
    pub fn rate_limited(retry_after: Option<Duration>) -> Self {
        let mut err = Self::from_kind(ErrorKind::RateLimited);
        if let Some(duration) = retry_after {
            err.retry_after = Some(duration);
        }
        err
    }

    /// Creates an unavailable error.
    pub fn unavailable(message: impl Into<Cow<'static, str>>) -> Self {
        Self::new(ErrorKind::Unavailable, message)
    }

    /// Creates a timeout error.
    pub fn timeout(message: impl Into<Cow<'static, str>>) -> Self {
        Self::new(ErrorKind::Timeout, message)
    }

    /// Creates an internal error.
    pub fn internal(message: impl Into<Cow<'static, str>>) -> Self {
        Self::new(ErrorKind::Internal, message)
    }

    /// Creates a cancelled error.
    pub fn cancelled() -> Self {
        Self::from_kind(ErrorKind::Cancelled)
    }

    /// Creates a circuit open error.
    pub fn circuit_open() -> Self {
        Self::from_kind(ErrorKind::CircuitOpen)
    }

    /// Creates a connection error.
    pub fn connection(message: impl Into<Cow<'static, str>>) -> Self {
        Self::new(ErrorKind::Connection, message)
    }

    /// Creates a protocol error.
    pub fn protocol(message: impl Into<Cow<'static, str>>) -> Self {
        Self::new(ErrorKind::Protocol, message)
    }

    /// Creates a configuration error.
    pub fn configuration(message: impl Into<Cow<'static, str>>) -> Self {
        Self::new(ErrorKind::Configuration, message)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.kind, self.message)?;

        if let Some(ref request_id) = self.request_id {
            write!(f, " (request_id: {})", request_id)?;
        }

        Ok(())
    }
}

impl StdError for Error {
    fn source(&self) -> Option<&(dyn StdError + 'static)> {
        self.source
            .as_ref()
            .map(|e| e.as_ref() as &(dyn StdError + 'static))
    }
}

// Implement From for common error types

impl From<ErrorKind> for Error {
    fn from(kind: ErrorKind) -> Self {
        Self::from_kind(kind)
    }
}

impl From<std::io::Error> for Error {
    fn from(err: std::io::Error) -> Self {
        let kind = match err.kind() {
            std::io::ErrorKind::NotFound => ErrorKind::NotFound,
            std::io::ErrorKind::PermissionDenied => ErrorKind::Forbidden,
            std::io::ErrorKind::ConnectionRefused
            | std::io::ErrorKind::ConnectionReset
            | std::io::ErrorKind::ConnectionAborted
            | std::io::ErrorKind::NotConnected => ErrorKind::Connection,
            std::io::ErrorKind::TimedOut => ErrorKind::Timeout,
            _ => ErrorKind::Internal,
        };
        Error::new(kind, err.to_string()).with_source(err)
    }
}

impl From<url::ParseError> for Error {
    fn from(err: url::ParseError) -> Self {
        Error::configuration(format!("invalid URL: {}", err)).with_source(err)
    }
}

impl From<serde_json::Error> for Error {
    fn from(err: serde_json::Error) -> Self {
        Error::protocol(format!("JSON error: {}", err)).with_source(err)
    }
}

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

    #[test]
    fn test_error_new() {
        let err = Error::new(ErrorKind::InvalidArgument, "test message");
        assert_eq!(err.kind(), ErrorKind::InvalidArgument);
        assert!(err.to_string().contains("test message"));
        assert!(err.request_id().is_none());
        assert!(err.retry_after().is_none());
    }

    #[test]
    fn test_error_from_kind() {
        let err = Error::from_kind(ErrorKind::Unauthorized);
        assert_eq!(err.kind(), ErrorKind::Unauthorized);
        assert!(err.to_string().contains("authentication failed"));
    }

    #[test]
    fn test_error_with_request_id() {
        let err = Error::new(ErrorKind::Internal, "server error").with_request_id("req_abc123");
        assert_eq!(err.request_id(), Some("req_abc123"));
        assert!(err.to_string().contains("req_abc123"));
    }

    #[test]
    fn test_error_with_retry_after() {
        let err = Error::rate_limited(Some(Duration::from_secs(30)));
        assert_eq!(err.kind(), ErrorKind::RateLimited);
        assert_eq!(err.retry_after(), Some(Duration::from_secs(30)));
    }

    #[test]
    fn test_error_is_retriable() {
        assert!(Error::from_kind(ErrorKind::Timeout).is_retriable());
        assert!(Error::from_kind(ErrorKind::Unavailable).is_retriable());
        assert!(Error::from_kind(ErrorKind::RateLimited).is_retriable());
        assert!(!Error::from_kind(ErrorKind::Unauthorized).is_retriable());
        assert!(!Error::from_kind(ErrorKind::NotFound).is_retriable());
    }

    #[test]
    fn test_error_with_source() {
        let io_err = std::io::Error::other("underlying error");
        let err = Error::new(ErrorKind::Connection, "connection failed").with_source(io_err);
        assert!(err.source().is_some());
    }

    #[test]
    fn test_convenience_constructors() {
        assert_eq!(Error::unauthorized("test").kind(), ErrorKind::Unauthorized);
        assert_eq!(Error::forbidden("test").kind(), ErrorKind::Forbidden);
        assert_eq!(Error::not_found("test").kind(), ErrorKind::NotFound);
        assert_eq!(
            Error::invalid_argument("test").kind(),
            ErrorKind::InvalidArgument
        );
        assert_eq!(
            Error::schema_violation("test").kind(),
            ErrorKind::SchemaViolation
        );
        assert_eq!(Error::unavailable("test").kind(), ErrorKind::Unavailable);
        assert_eq!(Error::timeout("test").kind(), ErrorKind::Timeout);
        assert_eq!(Error::internal("test").kind(), ErrorKind::Internal);
        assert_eq!(Error::cancelled().kind(), ErrorKind::Cancelled);
        assert_eq!(Error::circuit_open().kind(), ErrorKind::CircuitOpen);
        assert_eq!(Error::connection("test").kind(), ErrorKind::Connection);
        assert_eq!(Error::protocol("test").kind(), ErrorKind::Protocol);
        assert_eq!(
            Error::configuration("test").kind(),
            ErrorKind::Configuration
        );
    }

    #[test]
    fn test_from_error_kind() {
        let err: Error = ErrorKind::Timeout.into();
        assert_eq!(err.kind(), ErrorKind::Timeout);
    }

    #[test]
    fn test_from_io_error() {
        let io_err = std::io::Error::new(std::io::ErrorKind::TimedOut, "timed out");
        let err: Error = io_err.into();
        assert_eq!(err.kind(), ErrorKind::Timeout);
    }

    #[test]
    fn test_display_format() {
        let err = Error::new(ErrorKind::NotFound, "vault not found").with_request_id("req_xyz789");
        let display = err.to_string();
        assert!(display.contains("not found"));
        assert!(display.contains("vault not found"));
        assert!(display.contains("req_xyz789"));
    }

    #[test]
    fn test_from_kind_all_variants() {
        // Test all ErrorKind variants to cover the match arms
        let _ = Error::from_kind(ErrorKind::Forbidden);
        let _ = Error::from_kind(ErrorKind::NotFound);
        let _ = Error::from_kind(ErrorKind::InvalidArgument);
        let _ = Error::from_kind(ErrorKind::SchemaViolation);
        let _ = Error::from_kind(ErrorKind::RateLimited);
        let _ = Error::from_kind(ErrorKind::Unavailable);
        let _ = Error::from_kind(ErrorKind::Timeout);
        let _ = Error::from_kind(ErrorKind::Internal);
        let _ = Error::from_kind(ErrorKind::Cancelled);
        let _ = Error::from_kind(ErrorKind::CircuitOpen);
        let _ = Error::from_kind(ErrorKind::Connection);
        let _ = Error::from_kind(ErrorKind::Protocol);
        let _ = Error::from_kind(ErrorKind::Configuration);
        let _ = Error::from_kind(ErrorKind::Unknown);
    }

    #[test]
    fn test_from_io_error_not_found() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
        let err: Error = io_err.into();
        assert_eq!(err.kind(), ErrorKind::NotFound);
    }

    #[test]
    fn test_from_io_error_permission_denied() {
        let io_err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "permission denied");
        let err: Error = io_err.into();
        assert_eq!(err.kind(), ErrorKind::Forbidden);
    }

    #[test]
    fn test_from_io_error_connection_refused() {
        let io_err =
            std::io::Error::new(std::io::ErrorKind::ConnectionRefused, "connection refused");
        let err: Error = io_err.into();
        assert_eq!(err.kind(), ErrorKind::Connection);
    }

    #[test]
    fn test_from_io_error_connection_reset() {
        let io_err = std::io::Error::new(std::io::ErrorKind::ConnectionReset, "connection reset");
        let err: Error = io_err.into();
        assert_eq!(err.kind(), ErrorKind::Connection);
    }

    #[test]
    fn test_from_io_error_connection_aborted() {
        let io_err =
            std::io::Error::new(std::io::ErrorKind::ConnectionAborted, "connection aborted");
        let err: Error = io_err.into();
        assert_eq!(err.kind(), ErrorKind::Connection);
    }

    #[test]
    fn test_from_io_error_not_connected() {
        let io_err = std::io::Error::new(std::io::ErrorKind::NotConnected, "not connected");
        let err: Error = io_err.into();
        assert_eq!(err.kind(), ErrorKind::Connection);
    }

    #[test]
    fn test_from_io_error_other() {
        let io_err = std::io::Error::other("other error");
        let err: Error = io_err.into();
        assert_eq!(err.kind(), ErrorKind::Internal);
    }

    #[test]
    fn test_from_url_parse_error() {
        let url_err = url::Url::parse("not a valid url").unwrap_err();
        let err: Error = url_err.into();
        assert_eq!(err.kind(), ErrorKind::Configuration);
        assert!(err.to_string().contains("invalid URL"));
    }

    #[test]
    fn test_from_serde_json_error() {
        let json_err: serde_json::Error =
            serde_json::from_str::<serde_json::Value>("{invalid}").unwrap_err();
        let err: Error = json_err.into();
        assert_eq!(err.kind(), ErrorKind::Protocol);
        assert!(err.to_string().contains("JSON error"));
    }

    #[test]
    fn test_error_display_without_request_id() {
        let err = Error::new(ErrorKind::NotFound, "vault not found");
        let display = err.to_string();
        assert!(!display.contains("request_id"));
    }

    #[test]
    fn test_error_source_none() {
        let err = Error::new(ErrorKind::Internal, "test");
        assert!(err.source().is_none());
    }

    #[test]
    fn test_error_debug() {
        let err = Error::new(ErrorKind::Internal, "test error");
        let debug = format!("{:?}", err);
        assert!(debug.contains("Error"));
    }

    #[test]
    fn test_from_kind_remaining_variants() {
        // Cover remaining from_kind match arms
        let _ = Error::from_kind(ErrorKind::Conflict);
        let _ = Error::from_kind(ErrorKind::Transport);
        let _ = Error::from_kind(ErrorKind::InvalidResponse);
    }

    #[test]
    fn test_rate_limited_without_retry_after() {
        let err = Error::rate_limited(None);
        assert_eq!(err.kind(), ErrorKind::RateLimited);
        assert!(err.retry_after().is_none());
    }

    #[test]
    fn test_error_with_retry_after_builder() {
        let err = Error::new(ErrorKind::RateLimited, "rate limited")
            .with_retry_after(Duration::from_secs(60));
        assert_eq!(err.retry_after(), Some(Duration::from_secs(60)));
    }

    #[test]
    fn test_error_from_kind_message_content() {
        // Verify the default messages are sensible
        let err = Error::from_kind(ErrorKind::Unauthorized);
        assert!(err.to_string().contains("authentication"));

        let err = Error::from_kind(ErrorKind::NotFound);
        assert!(err.to_string().contains("not found"));

        let err = Error::from_kind(ErrorKind::Conflict);
        assert!(err.to_string().contains("conflict"));
    }
}