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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
//! Context type for ABAC (Attribute-Based Access Control).

use std::collections::HashMap;
use std::fmt;

use serde::{Deserialize, Serialize};

/// A value that can be passed in an ABAC context.
///
/// Context values are used to evaluate attribute-based conditions in
/// permission checks. They support the common JSON-compatible types.
///
/// # Example
///
/// ```rust
/// use inferadb::ContextValue;
///
/// let string_val: ContextValue = "production".into();
/// let number_val: ContextValue = 42.into();
/// let bool_val: ContextValue = true.into();
/// let null_val = ContextValue::Null;
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(untagged)]
pub enum ContextValue {
    /// Null value.
    #[default]
    Null,

    /// Boolean value.
    Bool(bool),

    /// Integer value (64-bit signed).
    Integer(i64),

    /// Floating-point value (64-bit).
    Float(f64),

    /// String value.
    String(String),

    /// Array of values.
    Array(Vec<ContextValue>),

    /// Nested object.
    Object(HashMap<String, ContextValue>),
}

impl ContextValue {
    /// Returns `true` if this is a null value.
    #[inline]
    pub fn is_null(&self) -> bool {
        matches!(self, ContextValue::Null)
    }

    /// Returns the boolean value if this is a Bool variant.
    #[inline]
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            ContextValue::Bool(b) => Some(*b),
            _ => None,
        }
    }

    /// Returns the integer value if this is an Integer variant.
    #[inline]
    pub fn as_i64(&self) -> Option<i64> {
        match self {
            ContextValue::Integer(i) => Some(*i),
            _ => None,
        }
    }

    /// Returns the float value if this is a Float variant.
    #[inline]
    pub fn as_f64(&self) -> Option<f64> {
        match self {
            ContextValue::Float(f) => Some(*f),
            ContextValue::Integer(i) => Some(*i as f64),
            _ => None,
        }
    }

    /// Returns the string value if this is a String variant.
    #[inline]
    pub fn as_str(&self) -> Option<&str> {
        match self {
            ContextValue::String(s) => Some(s),
            _ => None,
        }
    }

    /// Returns the array if this is an Array variant.
    #[inline]
    pub fn as_array(&self) -> Option<&[ContextValue]> {
        match self {
            ContextValue::Array(arr) => Some(arr),
            _ => None,
        }
    }

    /// Returns the object if this is an Object variant.
    #[inline]
    pub fn as_object(&self) -> Option<&HashMap<String, ContextValue>> {
        match self {
            ContextValue::Object(obj) => Some(obj),
            _ => None,
        }
    }
}

impl From<bool> for ContextValue {
    fn from(value: bool) -> Self {
        ContextValue::Bool(value)
    }
}

impl From<i32> for ContextValue {
    fn from(value: i32) -> Self {
        ContextValue::Integer(value as i64)
    }
}

impl From<i64> for ContextValue {
    fn from(value: i64) -> Self {
        ContextValue::Integer(value)
    }
}

impl From<f64> for ContextValue {
    fn from(value: f64) -> Self {
        ContextValue::Float(value)
    }
}

impl From<&str> for ContextValue {
    fn from(value: &str) -> Self {
        ContextValue::String(value.to_owned())
    }
}

impl From<String> for ContextValue {
    fn from(value: String) -> Self {
        ContextValue::String(value)
    }
}

impl<T: Into<ContextValue>> From<Vec<T>> for ContextValue {
    fn from(value: Vec<T>) -> Self {
        ContextValue::Array(value.into_iter().map(Into::into).collect())
    }
}

impl<T: Into<ContextValue>> From<Option<T>> for ContextValue {
    fn from(value: Option<T>) -> Self {
        match value {
            Some(v) => v.into(),
            None => ContextValue::Null,
        }
    }
}

impl fmt::Display for ContextValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ContextValue::Null => write!(f, "null"),
            ContextValue::Bool(b) => write!(f, "{}", b),
            ContextValue::Integer(i) => write!(f, "{}", i),
            ContextValue::Float(fl) => write!(f, "{}", fl),
            ContextValue::String(s) => write!(f, "\"{}\"", s),
            ContextValue::Array(arr) => {
                write!(f, "[")?;
                for (i, v) in arr.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "{}", v)?;
                }
                write!(f, "]")
            }
            ContextValue::Object(obj) => {
                write!(f, "{{")?;
                for (i, (k, v)) in obj.iter().enumerate() {
                    if i > 0 {
                        write!(f, ", ")?;
                    }
                    write!(f, "\"{}\": {}", k, v)?;
                }
                write!(f, "}}")
            }
        }
    }
}

/// ABAC context for attribute-based authorization conditions.
///
/// Context provides dynamic attributes that can be evaluated in permission
/// checks. These attributes are evaluated against conditions defined in
/// the authorization schema.
///
/// ## Common Use Cases
///
/// - **Time-based access**: Check if current time is within business hours
/// - **Location-based access**: Verify user's IP is in allowed range
/// - **Environment checks**: Production vs. development access rules
/// - **Dynamic attributes**: User's current subscription tier
///
/// ## Example
///
/// ```rust
/// use inferadb::{Context, ContextValue};
///
/// // Build context for a permission check
/// let context = Context::new()
///     .with("environment", "production")
///     .with("user_tier", "premium")
///     .with("request_ip", "192.168.1.100")
///     .with("is_business_hours", true);
///
/// // Use with check
/// // vault.check("user:alice", "access", "resource:data")
/// //     .with_context(context)
/// //     .await?;
/// ```
///
/// ## Nested Values
///
/// Context supports nested structures:
///
/// ```rust
/// use inferadb::{Context, ContextValue};
/// use std::collections::HashMap;
///
/// let mut user_attrs = HashMap::new();
/// user_attrs.insert("department".to_string(), ContextValue::from("engineering"));
/// user_attrs.insert("level".to_string(), ContextValue::from(5));
///
/// let context = Context::new()
///     .with("user", ContextValue::Object(user_attrs));
/// ```
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Context {
    #[serde(flatten)]
    values: HashMap<String, ContextValue>,
}

impl Context {
    /// Creates an empty context.
    ///
    /// # Example
    ///
    /// ```rust
    /// use inferadb::Context;
    ///
    /// let context = Context::new();
    /// assert!(context.is_empty());
    /// ```
    pub fn new() -> Self {
        Self {
            values: HashMap::new(),
        }
    }

    /// Creates a context with the given capacity.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            values: HashMap::with_capacity(capacity),
        }
    }

    /// Adds a key-value pair to the context.
    ///
    /// # Example
    ///
    /// ```rust
    /// use inferadb::Context;
    ///
    /// let context = Context::new()
    ///     .with("environment", "production")
    ///     .with("debug", false)
    ///     .with("max_retries", 3);
    /// ```
    #[must_use]
    pub fn with(mut self, key: impl Into<String>, value: impl Into<ContextValue>) -> Self {
        self.values.insert(key.into(), value.into());
        self
    }

    /// Inserts a key-value pair, mutating the context.
    ///
    /// Returns the previous value if the key was present.
    pub fn insert(
        &mut self,
        key: impl Into<String>,
        value: impl Into<ContextValue>,
    ) -> Option<ContextValue> {
        self.values.insert(key.into(), value.into())
    }

    /// Gets a value by key.
    pub fn get(&self, key: &str) -> Option<&ContextValue> {
        self.values.get(key)
    }

    /// Removes a value by key.
    pub fn remove(&mut self, key: &str) -> Option<ContextValue> {
        self.values.remove(key)
    }

    /// Returns `true` if the context contains the given key.
    pub fn contains_key(&self, key: &str) -> bool {
        self.values.contains_key(key)
    }

    /// Returns `true` if the context is empty.
    pub fn is_empty(&self) -> bool {
        self.values.is_empty()
    }

    /// Returns the number of entries in the context.
    pub fn len(&self) -> usize {
        self.values.len()
    }

    /// Returns an iterator over the context entries.
    pub fn iter(&self) -> impl Iterator<Item = (&String, &ContextValue)> {
        self.values.iter()
    }

    /// Extends this context with entries from another context.
    ///
    /// Existing keys are overwritten.
    pub fn extend(&mut self, other: Context) {
        self.values.extend(other.values);
    }

    /// Merges another context into this one, returning a new context.
    ///
    /// Entries from `other` overwrite entries from `self`.
    #[must_use]
    pub fn merge(mut self, other: Context) -> Self {
        self.extend(other);
        self
    }

    /// Converts this context into a JSON value.
    ///
    /// This is useful for serializing the context for API requests.
    pub fn into_value(self) -> serde_json::Value {
        serde_json::to_value(self).unwrap_or(serde_json::Value::Null)
    }
}

impl FromIterator<(String, ContextValue)> for Context {
    fn from_iter<T: IntoIterator<Item = (String, ContextValue)>>(iter: T) -> Self {
        Self {
            values: iter.into_iter().collect(),
        }
    }
}

impl IntoIterator for Context {
    type Item = (String, ContextValue);
    type IntoIter = std::collections::hash_map::IntoIter<String, ContextValue>;

    fn into_iter(self) -> Self::IntoIter {
        self.values.into_iter()
    }
}

impl<'a> IntoIterator for &'a Context {
    type Item = (&'a String, &'a ContextValue);
    type IntoIter = std::collections::hash_map::Iter<'a, String, ContextValue>;

    fn into_iter(self) -> Self::IntoIter {
        self.values.iter()
    }
}

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

    #[test]
    fn test_context_value_types() {
        assert!(ContextValue::Null.is_null());
        assert_eq!(ContextValue::Bool(true).as_bool(), Some(true));
        assert_eq!(ContextValue::Integer(42).as_i64(), Some(42));
        assert_eq!(ContextValue::Float(2.5).as_f64(), Some(2.5));
        assert_eq!(ContextValue::String("test".into()).as_str(), Some("test"));
    }

    #[test]
    fn test_context_value_conversions() {
        let b: ContextValue = true.into();
        assert_eq!(b.as_bool(), Some(true));

        let i: ContextValue = 42i32.into();
        assert_eq!(i.as_i64(), Some(42));

        let f: ContextValue = 2.5.into();
        assert_eq!(f.as_f64(), Some(2.5));

        let s: ContextValue = "hello".into();
        assert_eq!(s.as_str(), Some("hello"));

        let arr: ContextValue = vec![1i32, 2, 3].into();
        assert!(arr.as_array().is_some());
    }

    #[test]
    fn test_context_new() {
        let ctx = Context::new();
        assert!(ctx.is_empty());
        assert_eq!(ctx.len(), 0);
    }

    #[test]
    fn test_context_with_capacity() {
        let ctx = Context::with_capacity(10);
        assert!(ctx.is_empty());
        assert_eq!(ctx.len(), 0);
    }

    #[test]
    fn test_context_with() {
        let ctx = Context::new()
            .with("env", "prod")
            .with("debug", false)
            .with("count", 10);

        assert_eq!(ctx.len(), 3);
        assert_eq!(ctx.get("env").and_then(|v| v.as_str()), Some("prod"));
        assert_eq!(ctx.get("debug").and_then(|v| v.as_bool()), Some(false));
        assert_eq!(ctx.get("count").and_then(|v| v.as_i64()), Some(10));
    }

    #[test]
    fn test_context_insert() {
        let mut ctx = Context::new();
        assert!(ctx.insert("key", "value1").is_none());
        assert!(ctx.insert("key", "value2").is_some());
        assert_eq!(ctx.get("key").and_then(|v| v.as_str()), Some("value2"));
    }

    #[test]
    fn test_context_remove() {
        let mut ctx = Context::new().with("key", "value");
        assert!(ctx.remove("key").is_some());
        assert!(ctx.remove("key").is_none());
        assert!(!ctx.contains_key("key"));
    }

    #[test]
    fn test_context_merge() {
        let ctx1 = Context::new().with("a", 1).with("b", 2);
        let ctx2 = Context::new().with("b", 3).with("c", 4);

        let merged = ctx1.merge(ctx2);
        assert_eq!(merged.get("a").and_then(|v| v.as_i64()), Some(1));
        assert_eq!(merged.get("b").and_then(|v| v.as_i64()), Some(3)); // Overwritten
        assert_eq!(merged.get("c").and_then(|v| v.as_i64()), Some(4));
    }

    #[test]
    fn test_context_iteration() {
        let ctx = Context::new().with("a", 1).with("b", 2);

        let keys: Vec<_> = ctx.iter().map(|(k, _)| k.as_str()).collect();
        assert!(keys.contains(&"a"));
        assert!(keys.contains(&"b"));
    }

    #[test]
    fn test_context_serialization() {
        let ctx = Context::new()
            .with("string", "hello")
            .with("number", 42)
            .with("bool", true);

        let json = serde_json::to_string(&ctx).unwrap();
        let parsed: Context = serde_json::from_str(&json).unwrap();

        assert_eq!(ctx, parsed);
    }

    #[test]
    fn test_context_value_display() {
        assert_eq!(ContextValue::Null.to_string(), "null");
        assert_eq!(ContextValue::Bool(true).to_string(), "true");
        assert_eq!(ContextValue::Integer(42).to_string(), "42");
        assert_eq!(ContextValue::String("test".into()).to_string(), "\"test\"");
    }

    #[test]
    fn test_nested_context() {
        let mut inner = HashMap::new();
        inner.insert("nested_key".to_string(), ContextValue::from("nested_value"));

        let ctx = Context::new().with("outer", ContextValue::Object(inner));

        let obj = ctx.get("outer").and_then(|v| v.as_object()).unwrap();
        assert_eq!(
            obj.get("nested_key").and_then(|v| v.as_str()),
            Some("nested_value")
        );
    }

    #[test]
    fn test_array_context_value() {
        let arr = ContextValue::from(vec!["a", "b", "c"]);
        let values = arr.as_array().unwrap();
        assert_eq!(values.len(), 3);
        assert_eq!(values[0].as_str(), Some("a"));
    }

    #[test]
    fn test_option_conversion() {
        let some: ContextValue = Some("value").into();
        assert_eq!(some.as_str(), Some("value"));

        let none: ContextValue = Option::<String>::None.into();
        assert!(none.is_null());
    }

    #[test]
    fn test_from_iterator() {
        let pairs = vec![
            ("a".to_string(), ContextValue::from(1)),
            ("b".to_string(), ContextValue::from(2)),
        ];
        let ctx: Context = pairs.into_iter().collect();
        assert_eq!(ctx.len(), 2);
    }

    #[test]
    fn test_context_value_as_wrong_type() {
        // Test as_bool on non-Bool
        assert!(ContextValue::Integer(42).as_bool().is_none());
        assert!(ContextValue::Null.as_bool().is_none());

        // Test as_i64 on non-Integer
        assert!(ContextValue::Bool(true).as_i64().is_none());
        assert!(ContextValue::String("test".into()).as_i64().is_none());

        // Test as_f64 on non-numeric
        assert!(ContextValue::Bool(true).as_f64().is_none());
        assert!(ContextValue::Null.as_f64().is_none());

        // Test as_str on non-String
        assert!(ContextValue::Integer(42).as_str().is_none());
        assert!(ContextValue::Bool(true).as_str().is_none());

        // Test as_array on non-Array
        assert!(ContextValue::Integer(42).as_array().is_none());
        assert!(ContextValue::String("test".into()).as_array().is_none());

        // Test as_object on non-Object
        assert!(ContextValue::Integer(42).as_object().is_none());
        assert!(ContextValue::Array(vec![]).as_object().is_none());
    }

    #[test]
    fn test_context_value_as_f64_from_integer() {
        // Integer can be converted to f64
        let val = ContextValue::Integer(42);
        assert_eq!(val.as_f64(), Some(42.0));
    }

    #[test]
    fn test_context_value_from_i64() {
        let val: ContextValue = 100i64.into();
        assert_eq!(val.as_i64(), Some(100));
    }

    #[test]
    fn test_context_value_from_string_owned() {
        let val: ContextValue = String::from("hello").into();
        assert_eq!(val.as_str(), Some("hello"));
    }

    #[test]
    fn test_context_value_display_float() {
        let val = ContextValue::Float(1.23);
        assert_eq!(val.to_string(), "1.23");
    }

    #[test]
    fn test_context_value_display_array_multiple() {
        let arr = ContextValue::Array(vec![
            ContextValue::Integer(1),
            ContextValue::Integer(2),
            ContextValue::Integer(3),
        ]);
        assert_eq!(arr.to_string(), "[1, 2, 3]");
    }

    #[test]
    fn test_context_value_display_object() {
        let mut obj = HashMap::new();
        obj.insert("key".to_string(), ContextValue::String("value".into()));
        let val = ContextValue::Object(obj);
        let display = val.to_string();
        assert!(display.starts_with("{"));
        assert!(display.ends_with("}"));
        assert!(display.contains("\"key\""));
        assert!(display.contains("\"value\""));
    }

    #[test]
    fn test_context_value_display_object_multiple() {
        let mut obj = HashMap::new();
        obj.insert("a".to_string(), ContextValue::Integer(1));
        obj.insert("b".to_string(), ContextValue::Integer(2));
        let val = ContextValue::Object(obj);
        let display = val.to_string();
        // Contains comma separator
        assert!(display.contains(", "));
    }

    #[test]
    fn test_context_into_iterator() {
        let ctx = Context::new().with("a", 1).with("b", 2);

        let mut count = 0;
        for (key, _) in ctx {
            assert!(key == "a" || key == "b");
            count += 1;
        }
        assert_eq!(count, 2);
    }

    #[test]
    fn test_context_ref_into_iterator() {
        let ctx = Context::new().with("a", 1).with("b", 2);

        let mut count = 0;
        for (key, _) in &ctx {
            assert!(key == "a" || key == "b");
            count += 1;
        }
        assert_eq!(count, 2);
    }

    #[test]
    fn test_context_extend() {
        let mut ctx1 = Context::new().with("a", 1);
        let ctx2 = Context::new().with("b", 2).with("a", 3);

        ctx1.extend(ctx2);

        assert_eq!(ctx1.get("a").and_then(|v| v.as_i64()), Some(3));
        assert_eq!(ctx1.get("b").and_then(|v| v.as_i64()), Some(2));
    }

    #[test]
    fn test_context_value_debug() {
        let val = ContextValue::Integer(42);
        let debug = format!("{:?}", val);
        assert!(debug.contains("Integer"));
        assert!(debug.contains("42"));
    }

    #[test]
    fn test_context_value_clone() {
        let val = ContextValue::String("test".into());
        let cloned = val.clone();
        assert_eq!(val, cloned);
    }

    #[test]
    fn test_context_default() {
        let ctx = Context::default();
        assert!(ctx.is_empty());
    }

    #[test]
    fn test_context_debug() {
        let ctx = Context::new().with("key", "value");
        let debug = format!("{:?}", ctx);
        assert!(debug.contains("Context"));
    }

    #[test]
    fn test_context_clone() {
        let ctx = Context::new().with("key", "value");
        let cloned = ctx.clone();
        assert_eq!(ctx.get("key"), cloned.get("key"));
    }
}