limbo_core 0.0.19

The Limbo database library
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
use std::cell::{Cell, UnsafeCell};

use crate::OwnedValue;

use super::jsonb::Jsonb;

const JSON_CACHE_SIZE: usize = 4;

#[derive(Debug)]
pub struct JsonCache {
    entries: [Option<(OwnedValue, Jsonb)>; JSON_CACHE_SIZE],
    age: [usize; JSON_CACHE_SIZE],
    used: usize,
    counter: usize,
}

impl JsonCache {
    pub fn new() -> Self {
        Self {
            entries: [None, None, None, None],
            age: [0, 0, 0, 0],
            used: 0,
            counter: 0,
        }
    }

    fn find_oldest_entry(&self) -> usize {
        let mut oldest_idx = 0;
        let mut oldest_age = self.age[0];

        for i in 1..self.used {
            if self.age[i] < oldest_age {
                oldest_idx = i;
                oldest_age = self.age[i];
            }
        }

        oldest_idx
    }

    pub fn insert(&mut self, key: &OwnedValue, value: &Jsonb) {
        if self.used < JSON_CACHE_SIZE {
            self.entries[self.used] = Some((key.clone(), value.clone()));
            self.age[self.used] = self.counter;
            self.counter += 1;
            self.used += 1
        } else {
            let id = self.find_oldest_entry();

            self.entries[id] = Some((key.clone(), value.clone()));
            self.age[id] = self.counter;
            self.counter += 1;
        }
    }

    pub fn lookup(&mut self, key: &OwnedValue) -> Option<Jsonb> {
        for i in (0..self.used).rev() {
            if let Some((stored_key, value)) = &self.entries[i] {
                if key == stored_key {
                    self.age[i] = self.counter;
                    self.counter += 1;
                    let json = value.clone();

                    return Some(json);
                }
            }
        }
        None
    }

    pub fn clear(&mut self) {
        self.counter = 0;
        self.used = 0;
    }
}

#[derive(Debug)]
pub struct JsonCacheCell {
    inner: UnsafeCell<Option<JsonCache>>,
    accessed: Cell<bool>,
}

impl JsonCacheCell {
    pub fn new() -> Self {
        Self {
            inner: UnsafeCell::new(None),
            accessed: Cell::new(false),
        }
    }

    #[cfg(test)]
    pub fn lookup(&self, key: &OwnedValue) -> Option<Jsonb> {
        assert_eq!(self.accessed.get(), false);

        self.accessed.set(true);

        let result = unsafe {
            let cache_ptr = self.inner.get();
            if (*cache_ptr).is_none() {
                *cache_ptr = Some(JsonCache::new());
            }

            if let Some(cache) = &mut (*cache_ptr) {
                cache.lookup(key)
            } else {
                None
            }
        };

        self.accessed.set(false);
        result
    }

    pub fn get_or_insert_with(
        &self,
        key: &OwnedValue,
        value: impl Fn(&OwnedValue) -> crate::Result<Jsonb>,
    ) -> crate::Result<Jsonb> {
        assert_eq!(self.accessed.get(), false);

        self.accessed.set(true);
        let result = unsafe {
            let cache_ptr = self.inner.get();
            if (*cache_ptr).is_none() {
                *cache_ptr = Some(JsonCache::new());
            }

            if let Some(cache) = &mut (*cache_ptr) {
                if let Some(jsonb) = cache.lookup(key) {
                    Ok(jsonb)
                } else {
                    let result = value(key);
                    match result {
                        Ok(json) => {
                            cache.insert(key, &json);
                            Ok(json)
                        }
                        Err(e) => Err(e),
                    }
                }
            } else {
                let result = value(key);
                result
            }
        };
        self.accessed.set(false);

        result
    }

    pub fn clear(&mut self) {
        assert_eq!(self.accessed.get(), false);
        self.accessed.set(true);
        unsafe {
            let cache_ptr = self.inner.get();
            if (*cache_ptr).is_none() {
                self.accessed.set(false);
                return;
            }

            if let Some(cache) = &mut (*cache_ptr) {
                cache.clear()
            }
        }
        self.accessed.set(false);
    }
}

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

    // Helper function to create test OwnedValue and Jsonb from JSON string
    fn create_test_pair(json_str: &str) -> (OwnedValue, Jsonb) {
        // Create OwnedValue as text representation of JSON
        let key = OwnedValue::build_text(json_str);

        // Create Jsonb from the same JSON string
        let value = Jsonb::from_str(json_str).unwrap();

        (key, value)
    }

    #[test]
    fn test_json_cache_new() {
        let cache = JsonCache::new();
        assert_eq!(cache.used, 0);
        assert_eq!(cache.counter, 0);
        assert_eq!(cache.age, [0, 0, 0, 0]);
        assert!(cache.entries.iter().all(|entry| entry.is_none()));
    }

    #[test]
    fn test_json_cache_insert_and_lookup() {
        let mut cache = JsonCache::new();
        let json_str = "{\"test\": \"value\"}";
        let (key, value) = create_test_pair(json_str);

        // Insert a value
        cache.insert(&key, &value);

        // Verify it was inserted
        assert_eq!(cache.used, 1);
        assert_eq!(cache.counter, 1);

        // Look it up
        let result = cache.lookup(&key);
        assert!(result.is_some());
        assert_eq!(result.unwrap(), value);

        // Counter should be incremented after lookup
        assert_eq!(cache.counter, 2);
    }

    #[test]
    fn test_json_cache_lookup_nonexistent() {
        let mut cache = JsonCache::new();
        let (key, _) = create_test_pair("{\"id\": 123}");

        // Look up a non-existent key
        let result = cache.lookup(&key);
        assert!(result.is_none());

        // Counter should remain unchanged
        assert_eq!(cache.counter, 0);
    }

    #[test]
    fn test_json_cache_multiple_entries() {
        let mut cache = JsonCache::new();

        // Insert multiple entries
        let (key1, value1) = create_test_pair("{\"id\": 1}");
        let (key2, value2) = create_test_pair("{\"id\": 2}");
        let (key3, value3) = create_test_pair("{\"id\": 3}");

        cache.insert(&key1, &value1);
        cache.insert(&key2, &value2);
        cache.insert(&key3, &value3);

        // Verify they were all inserted
        assert_eq!(cache.used, 3);
        assert_eq!(cache.counter, 3);

        // Look them up in reverse order
        let result3 = cache.lookup(&key3);
        let result2 = cache.lookup(&key2);
        let result1 = cache.lookup(&key1);

        assert_eq!(result3.unwrap(), value3);
        assert_eq!(result2.unwrap(), value2);
        assert_eq!(result1.unwrap(), value1);

        // Counter should be incremented for each lookup
        assert_eq!(cache.counter, 6);
    }

    #[test]
    fn test_json_cache_eviction() {
        let mut cache = JsonCache::new();

        // Insert more than JSON_CACHE_SIZE entries
        let (key1, value1) = create_test_pair("{\"id\": 1}");
        let (key2, value2) = create_test_pair("{\"id\": 2}");
        let (key3, value3) = create_test_pair("{\"id\": 3}");
        let (key4, value4) = create_test_pair("{\"id\": 4}");
        let (key5, value5) = create_test_pair("{\"id\": 5}");

        cache.insert(&key1, &value1);
        cache.insert(&key2, &value2);
        cache.insert(&key3, &value3);
        cache.insert(&key4, &value4);

        // Cache is now full
        assert_eq!(cache.used, 4);

        // Look up key1 to make it the most recently used
        let _ = cache.lookup(&key1);

        // Insert one more entry - should evict the oldest (key2)
        cache.insert(&key5, &value5);

        // Cache size should still be JSON_CACHE_SIZE
        assert_eq!(cache.used, 4);

        // key2 should have been evicted
        let result2 = cache.lookup(&key2);
        assert!(result2.is_none());

        // Other entries should still be present
        assert!(cache.lookup(&key1).is_some());
        assert!(cache.lookup(&key3).is_some());
        assert!(cache.lookup(&key4).is_some());
        assert!(cache.lookup(&key5).is_some());
    }

    #[test]
    fn test_json_cache_find_oldest_entry() {
        let mut cache = JsonCache::new();

        // Insert entries
        let (key1, value1) = create_test_pair("{\"id\": 1}");
        let (key2, value2) = create_test_pair("{\"id\": 2}");
        let (key3, value3) = create_test_pair("{\"id\": 3}");

        cache.insert(&key1, &value1);
        cache.insert(&key2, &value2);
        cache.insert(&key3, &value3);

        // key1 should be the oldest
        assert_eq!(cache.find_oldest_entry(), 0);

        // Access key1 to make it the newest
        let _ = cache.lookup(&key1);

        // Now key2 should be the oldest
        assert_eq!(cache.find_oldest_entry(), 1);
    }

    // Tests for JsonCacheCell

    #[test]
    fn test_json_cache_cell_new() {
        let cache_cell = JsonCacheCell::new();

        // Access flag should be false initially
        assert_eq!(cache_cell.accessed.get(), false);

        // Inner cache should be None initially
        unsafe {
            let inner = &*cache_cell.inner.get();
            assert!(inner.is_none());
        }
    }

    #[test]
    fn test_json_cache_cell_lookup() {
        let cache_cell = JsonCacheCell::new();
        let (key, value) = create_test_pair("{\"test\": \"value\"}");

        // First lookup should return None since cache is empty
        let result = cache_cell.lookup(&key);
        assert!(result.is_none());

        // Cache should be initialized after first lookup
        unsafe {
            let inner = &*cache_cell.inner.get();
            assert!(inner.is_some());
        }

        // Access flag should be reset to false
        assert_eq!(cache_cell.accessed.get(), false);

        // Insert the value using get_or_insert_with
        let insert_result = cache_cell.get_or_insert_with(&key, |k| {
            // Verify that k is the same as our key
            assert_eq!(k, &key);
            Ok(value.clone())
        });

        assert!(insert_result.is_ok());
        assert_eq!(insert_result.unwrap(), value);

        // Access flag should be reset to false
        assert_eq!(cache_cell.accessed.get(), false);

        // Lookup should now return the value
        let lookup_result = cache_cell.lookup(&key);
        assert!(lookup_result.is_some());
        assert_eq!(lookup_result.unwrap(), value);
    }

    #[test]
    fn test_json_cache_cell_get_or_insert_with_existing() {
        let cache_cell = JsonCacheCell::new();
        let (key, value) = create_test_pair("{\"test\": \"value\"}");

        // Insert a value
        let _ = cache_cell.get_or_insert_with(&key, |_| Ok(value.clone()));

        // Counter indicating if the closure was called
        let closure_called = Cell::new(false);

        // Try to insert again with the same key
        let result = cache_cell.get_or_insert_with(&key, |_| {
            closure_called.set(true);
            Ok(Jsonb::from_str("{\"test\": \"value\"}").unwrap())
        });

        // The closure should not have been called
        assert!(!closure_called.get());

        // Should return the original value
        assert_eq!(result.unwrap(), value);
    }

    #[test]
    #[should_panic]
    fn test_json_cache_cell_double_access() {
        let cache_cell = JsonCacheCell::new();
        let (key, _) = create_test_pair("{\"test\": \"value\"}");

        // Access the cache

        // Set accessed flag to true manually
        cache_cell.accessed.set(true);

        // This should panic due to double access

        let _ = cache_cell.lookup(&key);
    }

    #[test]
    fn test_json_cache_cell_get_or_insert_error_handling() {
        let cache_cell = JsonCacheCell::new();
        let (key, _) = create_test_pair("{\"test\": \"value\"}");

        // Test error handling
        let error_result = cache_cell.get_or_insert_with(&key, |_| {
            // Return an error
            Err(crate::LimboError::Constraint("Test error".to_string()))
        });

        // Should propagate the error
        assert!(error_result.is_err());

        // Access flag should be reset to false
        assert_eq!(cache_cell.accessed.get(), false);

        // The entry should not be cached
        let lookup_result = cache_cell.lookup(&key);
        assert!(lookup_result.is_none());
    }
}