1
use std::{
2
    borrow::Cow,
3
    collections::{btree_map, BTreeMap, VecDeque},
4
    sync::Arc,
5
    time::Duration,
6
};
7

            
8
use async_lock::Mutex;
9
use async_trait::async_trait;
10
use bonsaidb_core::{
11
    keyvalue::{
12
        Command, KeyCheck, KeyOperation, KeyStatus, KeyValue, Numeric, Output, SetCommand,
13
        Timestamp, Value,
14
    },
15
    transaction::{ChangedKey, Changes},
16
};
17
use bonsaidb_utils::fast_async_lock;
18
use nebari::{
19
    io::any::AnyFile,
20
    tree::{CompareSwap, KeyEvaluation, Operation, Root, Unversioned},
21
    AbortError, ArcBytes, Roots,
22
};
23
use serde::{Deserialize, Serialize};
24
use tokio::{
25
    runtime::Handle,
26
    sync::{oneshot, watch},
27
};
28

            
29
use crate::{
30
    config::KeyValuePersistence,
31
    jobs::{Job, Keyed},
32
    tasks::Task,
33
    Database, Error,
34
};
35

            
36
640932
#[derive(Serialize, Deserialize, Debug, Clone)]
37
pub struct Entry {
38
    pub value: Value,
39
    pub expiration: Option<Timestamp>,
40
    #[serde(default)]
41
    pub last_updated: Timestamp,
42
}
43

            
44
impl Entry {
45
3
    pub(crate) async fn restore(
46
3
        self,
47
3
        namespace: Option<String>,
48
3
        key: String,
49
3
        database: &Database,
50
3
    ) -> Result<(), bonsaidb_core::Error> {
51
3
        database
52
3
            .execute_key_operation(KeyOperation {
53
3
                namespace,
54
3
                key,
55
3
                command: Command::Set(SetCommand {
56
3
                    value: self.value,
57
3
                    expiration: self.expiration,
58
3
                    keep_existing_expiration: false,
59
3
                    check: None,
60
3
                    return_previous_value: false,
61
3
                }),
62
3
            })
63
            .await?;
64
3
        Ok(())
65
3
    }
66
}
67

            
68
#[async_trait]
69
impl KeyValue for Database {
70
748418
    async fn execute_key_operation(
71
748418
        &self,
72
748418
        op: KeyOperation,
73
748418
    ) -> Result<Output, bonsaidb_core::Error> {
74
748418
        self.data.context.perform_kv_operation(op).await
75
1496835
    }
76
}
77

            
78
impl Database {
79
7691
    pub(crate) async fn all_key_value_entries(
80
7691
        &self,
81
7691
    ) -> Result<BTreeMap<(Option<String>, String), Entry>, Error> {
82
        // Lock the state so that new new modifications can be made while we gather this snapshot.
83
7691
        let state = fast_async_lock!(self.data.context.key_value_state);
84
7691
        let database = self.clone();
85
7691
        // Initialize our entries with any dirty keys and any keys that are about to be persisted.
86
7691
        let mut all_entries = BTreeMap::new();
87
7691
        let mut all_entries = tokio::task::spawn_blocking(move || {
88
7690
            database
89
7690
                .roots()
90
7690
                .tree(Unversioned::tree(KEY_TREE))?
91
7690
                .scan::<Error, _, _, _, _>(
92
7690
                    &(..),
93
7690
                    true,
94
7690
                    |_, _, _| true,
95
7690
                    |_, _| KeyEvaluation::ReadData,
96
7690
                    |key, _, entry: ArcBytes<'static>| {
97
219
                        let entry = bincode::deserialize::<Entry>(&entry)
98
219
                            .map_err(|err| AbortError::Other(Error::from(err)))?;
99
219
                        let full_key = std::str::from_utf8(&key)
100
219
                            .map_err(|err| AbortError::Other(Error::from(err)))?;
101

            
102
219
                        if let Some(split_key) = split_key(full_key) {
103
219
                            // Do not overwrite the existing key
104
219
                            all_entries.entry(split_key).or_insert(entry);
105
219
                        }
106

            
107
219
                        Ok(())
108
7690
                    },
109
7690
                )?;
110
7690
            Result::<_, Error>::Ok(all_entries)
111
7691
        })
112
6858
        .await??;
113

            
114
        // Apply the pending writes first
115
7613
        if let Some(pending_keys) = &state.keys_being_persisted {
116
510
            for (key, possible_entry) in pending_keys.iter() {
117
510
                let (namespace, key) = split_key(key).unwrap();
118
510
                if let Some(updated_entry) = possible_entry {
119
411
                    all_entries.insert((namespace, key), updated_entry.clone());
120
411
                } else {
121
99
                    all_entries.remove(&(namespace, key));
122
99
                }
123
            }
124
7223
        }
125

            
126
7613
        for (key, possible_entry) in &state.dirty_keys {
127
150
            let (namespace, key) = split_key(key).unwrap();
128
150
            if let Some(updated_entry) = possible_entry {
129
150
                all_entries.insert((namespace, key), updated_entry.clone());
130
150
            } else {
131
                all_entries.remove(&(namespace, key));
132
            }
133
        }
134

            
135
7613
        Ok(all_entries)
136
7613
    }
137
}
138

            
139
pub(crate) const KEY_TREE: &str = "kv";
140

            
141
748359
fn full_key(namespace: Option<&str>, key: &str) -> String {
142
748359
    let full_length = namespace.map_or_else(|| 0, str::len) + key.len() + 1;
143
748359
    let mut full_key = String::with_capacity(full_length);
144
748359
    if let Some(ns) = namespace {
145
5954
        full_key.push_str(ns);
146
742405
    }
147
748359
    full_key.push('\0');
148
748359
    full_key.push_str(key);
149
748359
    full_key
150
748359
}
151

            
152
fn split_key(full_key: &str) -> Option<(Option<String>, String)> {
153
175267
    if let Some((namespace, key)) = full_key.split_once('\0') {
154
175267
        let namespace = if namespace.is_empty() {
155
172106
            None
156
        } else {
157
3161
            Some(namespace.to_string())
158
        };
159
175267
        Some((namespace, key.to_string()))
160
    } else {
161
        None
162
    }
163
175267
}
164

            
165
740860
fn increment(existing: &Numeric, amount: &Numeric, saturating: bool) -> Numeric {
166
740860
    match amount {
167
222
        Numeric::Integer(amount) => {
168
222
            let existing_value = existing.as_i64_lossy(saturating);
169
222
            let new_value = if saturating {
170
148
                existing_value.saturating_add(*amount)
171
            } else {
172
74
                existing_value.wrapping_add(*amount)
173
            };
174
222
            Numeric::Integer(new_value)
175
        }
176
740416
        Numeric::UnsignedInteger(amount) => {
177
740416
            let existing_value = existing.as_u64_lossy(saturating);
178
740416
            let new_value = if saturating {
179
740342
                existing_value.saturating_add(*amount)
180
            } else {
181
74
                existing_value.wrapping_add(*amount)
182
            };
183
740416
            Numeric::UnsignedInteger(new_value)
184
        }
185
222
        Numeric::Float(amount) => {
186
222
            let existing_value = existing.as_f64_lossy();
187
222
            let new_value = existing_value + *amount;
188
222
            Numeric::Float(new_value)
189
        }
190
    }
191
740860
}
192

            
193
666
fn decrement(existing: &Numeric, amount: &Numeric, saturating: bool) -> Numeric {
194
666
    match amount {
195
222
        Numeric::Integer(amount) => {
196
222
            let existing_value = existing.as_i64_lossy(saturating);
197
222
            let new_value = if saturating {
198
148
                existing_value.saturating_sub(*amount)
199
            } else {
200
74
                existing_value.wrapping_sub(*amount)
201
            };
202
222
            Numeric::Integer(new_value)
203
        }
204
296
        Numeric::UnsignedInteger(amount) => {
205
296
            let existing_value = existing.as_u64_lossy(saturating);
206
296
            let new_value = if saturating {
207
148
                existing_value.saturating_sub(*amount)
208
            } else {
209
148
                existing_value.wrapping_sub(*amount)
210
            };
211
296
            Numeric::UnsignedInteger(new_value)
212
        }
213
148
        Numeric::Float(amount) => {
214
148
            let existing_value = existing.as_f64_lossy();
215
148
            let new_value = existing_value - *amount;
216
148
            Numeric::Float(new_value)
217
        }
218
    }
219
666
}
220

            
221
#[derive(Debug)]
222
pub struct KeyValueState {
223
    roots: Roots<AnyFile>,
224
    persistence: KeyValuePersistence,
225
    last_commit: Timestamp,
226
    background_worker_target: watch::Sender<Option<Timestamp>>,
227
    expiring_keys: BTreeMap<String, Timestamp>,
228
    expiration_order: VecDeque<String>,
229
    dirty_keys: BTreeMap<String, Option<Entry>>,
230
    keys_being_persisted: Option<Arc<BTreeMap<String, Option<Entry>>>>,
231
    shutdown: Option<oneshot::Sender<()>>,
232
}
233

            
234
impl KeyValueState {
235
19441
    pub fn new(
236
19441
        persistence: KeyValuePersistence,
237
19441
        roots: Roots<AnyFile>,
238
19441
        background_worker_target: watch::Sender<Option<Timestamp>>,
239
19441
    ) -> Self {
240
19441
        Self {
241
19441
            roots,
242
19441
            persistence,
243
19441
            last_commit: Timestamp::now(),
244
19441
            expiring_keys: BTreeMap::new(),
245
19441
            background_worker_target,
246
19441
            expiration_order: VecDeque::new(),
247
19441
            dirty_keys: BTreeMap::new(),
248
19441
            keys_being_persisted: None,
249
19441
            shutdown: None,
250
19441
        }
251
19441
    }
252

            
253
13543
    pub async fn shutdown(
254
13543
        &mut self,
255
13543
        state: &Arc<Mutex<KeyValueState>>,
256
13543
    ) -> Result<(), oneshot::error::RecvError> {
257
13543
        let (shutdown_sender, shutdown_receiver) = oneshot::channel();
258
13543
        self.shutdown = Some(shutdown_sender);
259
13543
        if self.keys_being_persisted.is_none() {
260
13543
            self.commit_dirty_keys(state);
261
13543
        }
262
13543
        shutdown_receiver.await
263
    }
264

            
265
748421
    pub async fn perform_kv_operation(
266
748421
        &mut self,
267
748421
        op: KeyOperation,
268
748421
        state: &Arc<Mutex<KeyValueState>>,
269
748421
    ) -> Result<Output, bonsaidb_core::Error> {
270
748421
        let now = Timestamp::now();
271
748421
        // If there are any keys that have expired, clear them before executing any operations.
272
748421
        self.remove_expired_keys(now);
273
748421
        let result = match op.command {
274
3250
            Command::Set(command) => {
275
3250
                self.execute_set_operation(op.namespace.as_deref(), &op.key, command, now)
276
            }
277
2905
            Command::Get { delete } => {
278
2905
                self.execute_get_operation(op.namespace.as_deref(), &op.key, delete)
279
            }
280
592
            Command::Delete => self.execute_delete_operation(op.namespace.as_deref(), &op.key),
281
740934
            Command::Increment { amount, saturating } => self.execute_increment_operation(
282
740934
                op.namespace.as_deref(),
283
740934
                &op.key,
284
740934
                &amount,
285
740934
                saturating,
286
740934
                now,
287
740934
            ),
288
740
            Command::Decrement { amount, saturating } => self.execute_decrement_operation(
289
740
                op.namespace.as_deref(),
290
740
                &op.key,
291
740
                &amount,
292
740
                saturating,
293
740
                now,
294
740
            ),
295
        };
296
748421
        if result.is_ok() {
297
748126
            if self.needs_commit(now) {
298
161389
                self.commit_dirty_keys(state);
299
586737
            }
300
748126
            self.update_background_worker_target();
301
295
        }
302
748421
        result
303
748421
    }
304

            
305
3251
    fn execute_set_operation(
306
3251
        &mut self,
307
3251
        namespace: Option<&str>,
308
3251
        key: &str,
309
3251
        set: SetCommand,
310
3251
        now: Timestamp,
311
3251
    ) -> Result<Output, bonsaidb_core::Error> {
312
3177
        let mut entry = Entry {
313
3251
            value: set.value.validate()?,
314
3177
            expiration: set.expiration,
315
3177
            last_updated: now,
316
3177
        };
317
3177
        let full_key = full_key(namespace, key);
318
3177
        let possible_existing_value =
319
3177
            if set.check.is_some() || set.return_previous_value || set.keep_existing_expiration {
320
664
                Some(self.get(&full_key).map_err(Error::from)?)
321
            } else {
322
2513
                None
323
            };
324
3177
        let existing_value_ref = possible_existing_value.as_ref().and_then(Option::as_ref);
325

            
326
3177
        let updating = match set.check {
327
172
            Some(KeyCheck::OnlyIfPresent) => existing_value_ref.is_some(),
328
196
            Some(KeyCheck::OnlyIfVacant) => existing_value_ref.is_none(),
329
2809
            None => true,
330
        };
331
3177
        if updating {
332
3005
            if set.keep_existing_expiration {
333
74
                if let Some(existing_value) = existing_value_ref {
334
74
                    entry.expiration = existing_value.expiration;
335
74
                }
336
2931
            }
337
3005
            self.update_key_expiration(&full_key, entry.expiration);
338

            
339
3005
            let previous_value = if let Some(existing_value) = possible_existing_value {
340
                // we already fetched, no need to ask for the existing value back
341
492
                self.set(full_key, entry);
342
492
                existing_value
343
            } else {
344
2513
                self.replace(full_key, entry).map_err(Error::from)?
345
            };
346
3005
            if set.return_previous_value {
347
246
                Ok(Output::Value(previous_value.map(|entry| entry.value)))
348
2759
            } else if previous_value.is_none() {
349
1257
                Ok(Output::Status(KeyStatus::Inserted))
350
            } else {
351
1502
                Ok(Output::Status(KeyStatus::Updated))
352
            }
353
        } else {
354
172
            Ok(Output::Status(KeyStatus::NotChanged))
355
        }
356
3251
    }
357

            
358
3756
    pub fn update_key_expiration<'key>(
359
3756
        &mut self,
360
3756
        tree_key: impl Into<Cow<'key, str>>,
361
3756
        expiration: Option<Timestamp>,
362
3756
    ) {
363
3756
        let tree_key = tree_key.into();
364
3756
        let mut changed_first_expiration = false;
365
3756
        if let Some(expiration) = expiration {
366
479
            let key = if self.expiring_keys.contains_key(tree_key.as_ref()) {
367
                // Update the existing entry.
368
149
                let existing_entry_index = self
369
149
                    .expiration_order
370
149
                    .iter()
371
149
                    .enumerate()
372
149
                    .find_map(
373
173
                        |(index, key)| {
374
173
                            if &tree_key == key {
375
149
                                Some(index)
376
                            } else {
377
24
                                None
378
                            }
379
173
                        },
380
149
                    )
381
149
                    .unwrap();
382
149
                changed_first_expiration = existing_entry_index == 0;
383
149
                self.expiration_order.remove(existing_entry_index).unwrap()
384
            } else {
385
330
                tree_key.into_owned()
386
            };
387

            
388
            // Insert the key into the expiration_order queue
389
479
            let mut insert_at = None;
390
479
            for (index, expiring_key) in self.expiration_order.iter().enumerate() {
391
226
                if self.expiring_keys.get(expiring_key).unwrap() > &expiration {
392
76
                    insert_at = Some(index);
393
76
                    break;
394
150
                }
395
            }
396
479
            if let Some(insert_at) = insert_at {
397
76
                changed_first_expiration |= insert_at == 0;
398
76

            
399
76
                self.expiration_order.insert(insert_at, key.clone());
400
403
            } else {
401
403
                changed_first_expiration |= self.expiration_order.is_empty();
402
403
                self.expiration_order.push_back(key.clone());
403
403
            }
404
479
            self.expiring_keys.insert(key, expiration);
405
3277
        } else if self.expiring_keys.remove(tree_key.as_ref()).is_some() {
406
75
            let index = self
407
75
                .expiration_order
408
75
                .iter()
409
75
                .enumerate()
410
75
                .find_map(|(index, key)| {
411
75
                    if tree_key.as_ref() == key {
412
75
                        Some(index)
413
                    } else {
414
                        None
415
                    }
416
75
                })
417
75
                .unwrap();
418
75

            
419
75
            changed_first_expiration |= index == 0;
420
75
            self.expiration_order.remove(index);
421
3202
        }
422

            
423
3756
        if changed_first_expiration {
424
478
            self.update_background_worker_target();
425
3278
        }
426
3756
    }
427

            
428
2905
    fn execute_get_operation(
429
2905
        &mut self,
430
2905
        namespace: Option<&str>,
431
2905
        key: &str,
432
2905
        delete: bool,
433
2905
    ) -> Result<Output, bonsaidb_core::Error> {
434
2905
        let full_key = full_key(namespace, key);
435
2905
        let entry = if delete {
436
148
            self.remove(full_key).map_err(Error::from)?
437
        } else {
438
2757
            self.get(&full_key).map_err(Error::from)?
439
        };
440

            
441
2905
        Ok(Output::Value(entry.map(|e| e.value)))
442
2905
    }
443

            
444
592
    fn execute_delete_operation(
445
592
        &mut self,
446
592
        namespace: Option<&str>,
447
592
        key: &str,
448
592
    ) -> Result<Output, bonsaidb_core::Error> {
449
592
        let full_key = full_key(namespace, key);
450
592
        let value = self.remove(full_key).map_err(Error::from)?;
451
592
        if value.is_some() {
452
222
            Ok(Output::Status(KeyStatus::Deleted))
453
        } else {
454
370
            Ok(Output::Status(KeyStatus::NotChanged))
455
        }
456
592
    }
457

            
458
740934
    fn execute_increment_operation(
459
740934
        &mut self,
460
740934
        namespace: Option<&str>,
461
740934
        key: &str,
462
740934
        amount: &Numeric,
463
740934
        saturating: bool,
464
740934
        now: Timestamp,
465
740934
    ) -> Result<Output, bonsaidb_core::Error> {
466
740934
        self.execute_numeric_operation(namespace, key, amount, saturating, now, increment)
467
740934
    }
468

            
469
740
    fn execute_decrement_operation(
470
740
        &mut self,
471
740
        namespace: Option<&str>,
472
740
        key: &str,
473
740
        amount: &Numeric,
474
740
        saturating: bool,
475
740
        now: Timestamp,
476
740
    ) -> Result<Output, bonsaidb_core::Error> {
477
740
        self.execute_numeric_operation(namespace, key, amount, saturating, now, decrement)
478
740
    }
479

            
480
741674
    fn execute_numeric_operation<F: Fn(&Numeric, &Numeric, bool) -> Numeric>(
481
741674
        &mut self,
482
741674
        namespace: Option<&str>,
483
741674
        key: &str,
484
741674
        amount: &Numeric,
485
741674
        saturating: bool,
486
741674
        now: Timestamp,
487
741674
        op: F,
488
741674
    ) -> Result<Output, bonsaidb_core::Error> {
489
741674
        let full_key = full_key(namespace, key);
490
741674
        let current = self.get(&full_key).map_err(Error::from)?;
491
741674
        let mut entry = current.unwrap_or(Entry {
492
741674
            value: Value::Numeric(Numeric::UnsignedInteger(0)),
493
741674
            expiration: None,
494
741674
            last_updated: now,
495
741674
        });
496
741674

            
497
741674
        match entry.value {
498
741526
            Value::Numeric(existing) => {
499
741526
                let value = Value::Numeric(op(&existing, amount, saturating).validate()?);
500
741452
                entry.value = value.clone();
501
741452

            
502
741452
                self.set(full_key, entry);
503
741452
                Ok(Output::Value(Some(value)))
504
            }
505
148
            Value::Bytes(_) => Err(bonsaidb_core::Error::Database(String::from(
506
148
                "type of stored `Value` is not `Numeric`",
507
148
            ))),
508
        }
509
741674
    }
510

            
511
740
    fn remove(&mut self, key: String) -> Result<Option<Entry>, nebari::Error> {
512
740
        self.update_key_expiration(&key, None);
513

            
514
740
        if let Some(dirty_entry) = self.dirty_keys.get_mut(&key) {
515
176
            Ok(dirty_entry.take())
516
564
        } else if let Some(persisting_entry) = self
517
564
            .keys_being_persisted
518
564
            .as_ref()
519
564
            .and_then(|keys| keys.get(&key))
520
        {
521
72
            self.dirty_keys.insert(key, None);
522
72
            Ok(persisting_entry.clone())
523
        } else {
524
            // There might be a value on-disk we need to remove.
525
492
            let previous_value = Self::retrieve_key_from_disk(&self.roots, &key)?;
526
492
            self.dirty_keys.insert(key, None);
527
492
            Ok(previous_value)
528
        }
529
740
    }
530

            
531
    fn get(&self, key: &str) -> Result<Option<Entry>, nebari::Error> {
532
745095
        if let Some(entry) = self.dirty_keys.get(key) {
533
570847
            Ok(entry.clone())
534
174248
        } else if let Some(persisting_entry) = self
535
174248
            .keys_being_persisted
536
174248
            .as_ref()
537
174248
            .and_then(|keys| keys.get(key))
538
        {
539
69478
            Ok(persisting_entry.clone())
540
        } else {
541
104770
            Self::retrieve_key_from_disk(&self.roots, key)
542
        }
543
745095
    }
544

            
545
741944
    fn set(&mut self, key: String, value: Entry) {
546
741944
        self.dirty_keys.insert(key, Some(value));
547
741944
    }
548

            
549
2513
    fn replace(&mut self, key: String, value: Entry) -> Result<Option<Entry>, nebari::Error> {
550
2513
        let mut value = Some(value);
551
2513
        let map_entry = self.dirty_keys.entry(key);
552
2513
        if matches!(map_entry, btree_map::Entry::Vacant(_)) {
553
            // This key is clean, and the caller is expecting the previous
554
            // value.
555
1998
            let stored_value = if let Some(persisting_entry) = self
556
1998
                .keys_being_persisted
557
1998
                .as_ref()
558
1998
                .and_then(|keys| keys.get(map_entry.key()))
559
            {
560
150
                persisting_entry.clone()
561
            } else {
562
1848
                Self::retrieve_key_from_disk(&self.roots, map_entry.key())?
563
            };
564
1998
            map_entry.or_insert(value);
565
1998
            Ok(stored_value)
566
        } else {
567
            // This key is already dirty, we can just replace the value and
568
            // return the old value.
569
515
            map_entry.and_modify(|map_entry| {
570
515
                std::mem::swap(&mut value, map_entry);
571
515
            });
572
515
            Ok(value)
573
        }
574
2513
    }
575

            
576
107110
    fn retrieve_key_from_disk(
577
107110
        roots: &Roots<AnyFile>,
578
107110
        key: &str,
579
107110
    ) -> Result<Option<Entry>, nebari::Error> {
580
107110
        roots
581
107110
            .tree(Unversioned::tree(KEY_TREE))?
582
107110
            .get(key.as_bytes())
583
107110
            .map(|current| current.and_then(|current| bincode::deserialize::<Entry>(&current).ok()))
584
107110
    }
585

            
586
943577
    fn update_background_worker_target(&mut self) {
587
943577
        let key_expiration_target =
588
943577
            self.expiration_order
589
943577
                .get(0)
590
943577
                .map_or_else(Timestamp::max, |key| {
591
2503
                    let expiration_timeout = self.expiring_keys.get(key).unwrap();
592
2503
                    *expiration_timeout
593
943577
                });
594
943577
        let now = Timestamp::now();
595
943577
        let duration_until_commit = if self.keys_being_persisted.is_some() {
596
767011
            Duration::MAX
597
        } else {
598
176566
            self.persistence.duration_until_next_commit(
599
176566
                self.dirty_keys.len(),
600
176566
                (now - self.last_commit).unwrap_or_default(),
601
176566
            )
602
        };
603
943577
        let commit_target = now + duration_until_commit;
604
943577
        let closest_target = key_expiration_target.min(commit_target);
605
943577
        if *self.background_worker_target.borrow() != Some(closest_target) {
606
941724
            drop(self.background_worker_target.send(Some(closest_target)));
607
941724
        }
608
943577
    }
609

            
610
769401
    fn remove_expired_keys(&mut self, now: Timestamp) {
611
769631
        while !self.expiration_order.is_empty()
612
1293
            && self.expiring_keys.get(&self.expiration_order[0]).unwrap() <= &now
613
230
        {
614
230
            let key = self.expiration_order.pop_front().unwrap();
615
230
            self.expiring_keys.remove(&key);
616
230
            self.dirty_keys.insert(key, None);
617
230
        }
618
769401
    }
619

            
620
769105
    fn needs_commit(&mut self, now: Timestamp) -> bool {
621
769105
        if self.keys_being_persisted.is_some() {
622
592889
            false
623
        } else {
624
176216
            let since_last_commit = (now - self.last_commit).unwrap_or_default();
625
176216
            self.persistence
626
176216
                .should_commit(self.dirty_keys.len(), since_last_commit)
627
        }
628
769105
    }
629

            
630
187537
    fn stage_dirty_keys(&mut self) -> Option<Arc<BTreeMap<String, Option<Entry>>>> {
631
187537
        if !self.dirty_keys.is_empty() && self.keys_being_persisted.is_none() {
632
173994
            let keys = Arc::new(std::mem::take(&mut self.dirty_keys));
633
173994
            self.keys_being_persisted = Some(keys.clone());
634
173994
            Some(keys)
635
        } else {
636
13543
            None
637
        }
638
187537
    }
639

            
640
    fn commit_dirty_keys(&mut self, state: &Arc<Mutex<KeyValueState>>) {
641
187439
        if let Some(keys) = self.stage_dirty_keys() {
642
173994
            let roots = self.roots.clone();
643
173994
            let state = state.clone();
644
173994
            let tokio = Handle::current();
645
173994
            tokio::task::spawn_blocking(move || Self::persist_keys(&state, &roots, &keys, &tokio));
646
173994
            self.last_commit = Timestamp::now();
647
173994
        }
648
187439
    }
649

            
650
173994
    fn persist_keys(
651
173994
        key_value_state: &Arc<Mutex<KeyValueState>>,
652
173994
        roots: &Roots<AnyFile>,
653
173994
        keys: &BTreeMap<String, Option<Entry>>,
654
173994
        runtime: &Handle,
655
173994
    ) -> Result<(), bonsaidb_core::Error> {
656
173994
        let mut transaction = roots
657
173994
            .transaction(&[Unversioned::tree(KEY_TREE)])
658
173994
            .map_err(Error::from)?;
659
173994
        let all_keys = keys
660
173994
            .keys()
661
174388
            .map(|key| ArcBytes::from(key.as_bytes().to_vec()))
662
173994
            .collect();
663
173994
        let mut changed_keys = Vec::new();
664
173994
        transaction
665
173994
            .tree::<Unversioned>(0)
666
173994
            .unwrap()
667
173994
            .modify(
668
173994
                all_keys,
669
174388
                Operation::CompareSwap(CompareSwap::new(&mut |key, existing_value| {
670
174388
                    let full_key = std::str::from_utf8(key).unwrap();
671
174388
                    let (namespace, key) = split_key(full_key).unwrap();
672

            
673
174388
                    if let Some(new_value) = keys.get(full_key).unwrap() {
674
173620
                        changed_keys.push(ChangedKey {
675
173620
                            namespace,
676
173620
                            key,
677
173620
                            deleted: false,
678
173620
                        });
679
173620
                        let bytes = bincode::serialize(new_value).unwrap();
680
173620
                        nebari::tree::KeyOperation::Set(ArcBytes::from(bytes))
681
768
                    } else if existing_value.is_some() {
682
450
                        changed_keys.push(ChangedKey {
683
450
                            namespace,
684
450
                            key,
685
450
                            deleted: existing_value.is_some(),
686
450
                        });
687
450
                        nebari::tree::KeyOperation::Remove
688
                    } else {
689
318
                        nebari::tree::KeyOperation::Skip
690
                    }
691
174388
                })),
692
173994
            )
693
173994
            .map_err(Error::from)?;
694

            
695
173994
        if !changed_keys.is_empty() {
696
173700
            transaction
697
173700
                .entry_mut()
698
173700
                .set_data(pot::to_vec(&Changes::Keys(changed_keys))?)
699
173700
                .map_err(Error::from)?;
700
173700
            transaction.commit().map_err(Error::from)?;
701
294
        }
702

            
703
        // If we are shutting down, check if we still have dirty keys.
704
173994
        if let Some(final_keys) = runtime.block_on(async {
705
173994
            let mut state = fast_async_lock!(key_value_state);
706
173994
            state.keys_being_persisted = None;
707
173994
            state.update_background_worker_target();
708
173994
            // This block is a little ugly to avoid having to acquire the lock
709
173994
            // twice. If we're shutting down and have no dirty keys, we notify
710
173994
            // the waiting shutdown task. If we have any dirty keys, we wait do
711
173994
            // to that step because we're going to recurse and reach this spot
712
173994
            // again.
713
173994
            if state.shutdown.is_some() {
714
98
                let staged_keys = state.stage_dirty_keys();
715
98
                if staged_keys.is_none() {
716
98
                    let shutdown = state.shutdown.take().unwrap();
717
98
                    let _ = shutdown.send(());
718
98
                }
719
98
                staged_keys
720
            } else {
721
173896
                None
722
            }
723
173994
        }) {
724
            Self::persist_keys(key_value_state, roots, &final_keys, runtime)?;
725
173994
        }
726
173994
        Ok(())
727
173994
    }
728
}
729

            
730
19441
pub async fn background_worker(
731
19441
    key_value_state: Arc<Mutex<KeyValueState>>,
732
19441
    mut timestamp_receiver: watch::Receiver<Option<Timestamp>>,
733
19441
) -> Result<(), Error> {
734
221154
    loop {
735
221154
        let mut perform_operations = false;
736
221154
        let current_timestamp = *timestamp_receiver.borrow_and_update();
737
221154
        let changed_result = match current_timestamp {
738
202315
            Some(target) => {
739
202315
                let remaining = target - Timestamp::now();
740
202315
                if let Some(remaining) = remaining {
741
181567
                    tokio::select! {
742
180404
                        changed = timestamp_receiver.changed() => changed,
743
                        _ = tokio::time::sleep(remaining) => {
744
                            perform_operations = true;
745
                            Ok(())
746
                        },
747
                    }
748
                } else {
749
20748
                    perform_operations = true;
750
20748
                    Ok(())
751
                }
752
            }
753
18839
            None => timestamp_receiver.changed().await,
754
        };
755

            
756
201869
        if changed_result.is_err() {
757
            break;
758
201869
        }
759
201869

            
760
201869
        if perform_operations {
761
30267
            let mut state = fast_async_lock!(key_value_state);
762
20979
            let now = Timestamp::now();
763
20979
            state.remove_expired_keys(now);
764
20979
            if state.needs_commit(now) {
765
12507
                state.commit_dirty_keys(&key_value_state);
766
12507
            }
767
20979
            state.update_background_worker_target();
768
180890
        }
769
    }
770

            
771
    Ok(())
772
}
773

            
774
#[derive(Debug)]
775
pub struct ExpirationLoader {
776
    pub database: Database,
777
    pub launched_at: Timestamp,
778
}
779

            
780
impl Keyed<Task> for ExpirationLoader {
781
10241
    fn key(&self) -> Task {
782
10241
        Task::ExpirationLoader(self.database.data.name.clone())
783
10241
    }
784
}
785

            
786
#[async_trait]
787
impl Job for ExpirationLoader {
788
    type Output = ();
789
    type Error = Error;
790

            
791
22554
    #[cfg_attr(feature = "tracing", tracing::instrument)]
792
7518
    async fn execute(&mut self) -> Result<Self::Output, Self::Error> {
793
7518
        let database = self.database.clone();
794
7518
        let launched_at = self.launched_at;
795

            
796
7518
        for ((namespace, key), entry) in database.all_key_value_entries().await? {
797
609
            if entry.last_updated < launched_at && entry.expiration.is_some() {
798
1
                self.database
799
1
                    .update_key_expiration_async(
800
1
                        full_key(namespace.as_deref(), &key),
801
1
                        entry.expiration,
802
1
                    )
803
                    .await;
804
608
            }
805
        }
806

            
807
7440
        self.database
808
7440
            .storage()
809
7440
            .tasks()
810
7440
            .mark_key_value_expiration_loaded(self.database.data.name.clone())
811
            .await;
812

            
813
7440
        Ok(())
814
14958
    }
815
}
816

            
817
#[cfg(test)]
818
mod tests {
819
    use std::time::Duration;
820

            
821
    use bonsaidb_core::{
822
        arc_bytes::serde::Bytes,
823
        test_util::{TestDirectory, TimingTest},
824
    };
825
    use futures::Future;
826
    use nebari::io::any::{AnyFile, AnyFileManager};
827

            
828
    use super::*;
829
    use crate::{config::PersistenceThreshold, database::Context};
830

            
831
6
    async fn run_test_with_persistence<
832
6
        F: Fn(Context, nebari::Roots<AnyFile>) -> R + Send,
833
6
        R: Future<Output = anyhow::Result<()>> + Send,
834
6
    >(
835
6
        name: &str,
836
6
        persistence: KeyValuePersistence,
837
6
        test_contents: &F,
838
6
    ) -> anyhow::Result<()> {
839
6
        let dir = TestDirectory::new(name);
840
6
        let sled = nebari::Config::new(&dir)
841
6
            .file_manager(AnyFileManager::std())
842
6
            .open()?;
843

            
844
6
        let context = Context::new(sled.clone(), persistence);
845
6

            
846
11
        test_contents(context, sled).await?;
847

            
848
6
        Ok(())
849
6
    }
850

            
851
5
    async fn run_test<
852
5
        F: Fn(Context, nebari::Roots<AnyFile>) -> R + Send,
853
5
        R: Future<Output = anyhow::Result<()>> + Send,
854
5
    >(
855
5
        name: &str,
856
5
        test_contents: F,
857
5
    ) -> anyhow::Result<()> {
858
9
        run_test_with_persistence(name, KeyValuePersistence::default(), &test_contents).await
859
5
    }
860

            
861
1
    #[tokio::test]
862
1
    async fn basic_expiration() -> anyhow::Result<()> {
863
1
        run_test("kv-basic-expiration", |sender, sled| async move {
864
            loop {
865
1
                sled.delete_tree(KEY_TREE)?;
866
1
                let tree = sled.tree(Unversioned::tree(KEY_TREE))?;
867
1
                tree.set(b"atree\0akey", b"somevalue")?;
868
1
                let timing = TimingTest::new(Duration::from_millis(100));
869
1
                sender
870
1
                    .update_key_expiration_async(
871
1
                        full_key(Some("atree"), "akey"),
872
1
                        Some(Timestamp::now() + Duration::from_millis(100)),
873
1
                    )
874
                    .await;
875
1
                if !timing.wait_until(Duration::from_secs(1)).await {
876
                    println!("basic_expiration restarting due to timing discrepency");
877
                    continue;
878
1
                }
879
1
                assert!(tree.get(b"akey")?.is_none());
880
1
                break;
881
1
            }
882
1

            
883
1
            Ok(())
884
1
        })
885
1
        .await
886
1
    }
887

            
888
1
    #[tokio::test]
889
1
    async fn updating_expiration() -> anyhow::Result<()> {
890
1
        run_test("kv-updating-expiration", |sender, sled| async move {
891
            loop {
892
1
                sled.delete_tree(KEY_TREE)?;
893
1
                let tree = sled.tree(Unversioned::tree(KEY_TREE))?;
894
1
                tree.set(b"atree\0akey", b"somevalue")?;
895
1
                let timing = TimingTest::new(Duration::from_millis(100));
896
1
                sender
897
1
                    .update_key_expiration_async(
898
1
                        full_key(Some("atree"), "akey"),
899
1
                        Some(Timestamp::now() + Duration::from_millis(100)),
900
1
                    )
901
                    .await;
902
1
                sender
903
1
                    .update_key_expiration_async(
904
1
                        full_key(Some("atree"), "akey"),
905
1
                        Some(Timestamp::now() + Duration::from_secs(1)),
906
1
                    )
907
                    .await;
908
1
                if timing.elapsed() > Duration::from_millis(100)
909
1
                    || !timing.wait_until(Duration::from_millis(500)).await
910
                {
911
                    continue;
912
1
                }
913
1
                assert!(tree.get(b"atree\0akey")?.is_some());
914

            
915
1
                timing.wait_until(Duration::from_secs_f32(1.5)).await;
916
1
                assert_eq!(tree.get(b"atree\0akey")?, None);
917
1
                break;
918
1
            }
919
1

            
920
1
            Ok(())
921
2
        })
922
2
        .await
923
1
    }
924

            
925
1
    #[tokio::test]
926
1
    async fn multiple_keys_expiration() -> anyhow::Result<()> {
927
1
        run_test("kv-multiple-keys-expiration", |sender, sled| async move {
928
            loop {
929
1
                sled.delete_tree(KEY_TREE)?;
930
1
                let tree = sled.tree(Unversioned::tree(KEY_TREE))?;
931
1
                tree.set(b"atree\0akey", b"somevalue")?;
932
1
                tree.set(b"atree\0bkey", b"somevalue")?;
933

            
934
1
                let timing = TimingTest::new(Duration::from_millis(100));
935
1
                sender
936
1
                    .update_key_expiration_async(
937
1
                        full_key(Some("atree"), "akey"),
938
1
                        Some(Timestamp::now() + Duration::from_millis(100)),
939
1
                    )
940
                    .await;
941
1
                sender
942
1
                    .update_key_expiration_async(
943
1
                        full_key(Some("atree"), "bkey"),
944
1
                        Some(Timestamp::now() + Duration::from_secs(1)),
945
1
                    )
946
                    .await;
947

            
948
1
                if !timing.wait_until(Duration::from_millis(200)).await {
949
                    continue;
950
1
                }
951

            
952
1
                assert!(tree.get(b"atree\0akey")?.is_none());
953
1
                assert!(tree.get(b"atree\0bkey")?.is_some());
954
1
                timing.wait_until(Duration::from_millis(1100)).await;
955
1
                assert!(tree.get(b"atree\0bkey")?.is_none());
956

            
957
1
                break;
958
1
            }
959
1

            
960
1
            Ok(())
961
2
        })
962
2
        .await
963
1
    }
964

            
965
1
    #[tokio::test]
966
1
    async fn clearing_expiration() -> anyhow::Result<()> {
967
1
        run_test("kv-clearing-expiration", |sender, sled| async move {
968
            loop {
969
1
                sled.delete_tree(KEY_TREE)?;
970
1
                let tree = sled.tree(Unversioned::tree(KEY_TREE))?;
971
1
                tree.set(b"atree\0akey", b"somevalue")?;
972
1
                let timing = TimingTest::new(Duration::from_millis(100));
973
1
                sender
974
1
                    .update_key_expiration_async(
975
1
                        full_key(Some("atree"), "akey"),
976
1
                        Some(Timestamp::now() + Duration::from_millis(100)),
977
1
                    )
978
                    .await;
979
1
                sender
980
1
                    .update_key_expiration_async(full_key(Some("atree"), "akey"), None)
981
                    .await;
982
1
                if timing.elapsed() > Duration::from_millis(100) {
983
                    // Restart, took too long.
984
                    continue;
985
1
                }
986
1
                timing.wait_until(Duration::from_millis(150)).await;
987
1
                assert!(tree.get(b"atree\0akey")?.is_some());
988
1
                break;
989
1
            }
990
1

            
991
1
            Ok(())
992
1
        })
993
1
        .await
994
1
    }
995

            
996
1
    #[tokio::test]
997
1
    async fn out_of_order_expiration() -> anyhow::Result<()> {
998
1
        run_test("kv-out-of-order-expiration", |sender, sled| async move {
999
1
            let tree = sled.tree(Unversioned::tree(KEY_TREE))?;
1
            tree.set(b"atree\0akey", b"somevalue")?;
1
            tree.set(b"atree\0bkey", b"somevalue")?;
1
            tree.set(b"atree\0ckey", b"somevalue")?;
1
            sender
1
                .update_key_expiration_async(
1
                    full_key(Some("atree"), "akey"),
1
                    Some(Timestamp::now() + Duration::from_secs(3)),
1
                )
                .await;
1
            sender
1
                .update_key_expiration_async(
1
                    full_key(Some("atree"), "ckey"),
1
                    Some(Timestamp::now() + Duration::from_secs(1)),
1
                )
                .await;
1
            sender
1
                .update_key_expiration_async(
1
                    full_key(Some("atree"), "bkey"),
1
                    Some(Timestamp::now() + Duration::from_secs(2)),
1
                )
                .await;
1
            tokio::time::sleep(Duration::from_millis(1200)).await;
1
            assert!(tree.get(b"atree\0akey")?.is_some());
1
            assert!(tree.get(b"atree\0bkey")?.is_some());
1
            assert!(tree.get(b"atree\0ckey")?.is_none());
1
            tokio::time::sleep(Duration::from_secs(1)).await;
1
            assert!(tree.get(b"atree\0akey")?.is_some());
1
            assert!(tree.get(b"atree\0bkey")?.is_none());
1
            tokio::time::sleep(Duration::from_secs(1)).await;
1
            assert!(tree.get(b"atree\0akey")?.is_none());

            
1
            Ok(())
3
        })
3
        .await
1
    }

            
1
    #[tokio::test]
1
    async fn basic_persistence() -> anyhow::Result<()> {
1
        run_test_with_persistence(
1
            "kv-basic-persistence",
1
            KeyValuePersistence::lazy([
1
                PersistenceThreshold::after_changes(2),
1
                PersistenceThreshold::after_changes(1).and_duration(Duration::from_secs(2)),
1
            ]),
1
            &|sender, sled| async move {
1
                loop {
1
                    let timing = TimingTest::new(Duration::from_millis(100));
1
                    let tree = sled.tree(Unversioned::tree(KEY_TREE))?;
1
                    // Set three keys in quick succession. The first two should
1
                    // persist immediately, and the third should show up after 2
1
                    // seconds.
1
                    sender
1
                        .perform_kv_operation(KeyOperation {
1
                            namespace: None,
1
                            key: String::from("key1"),
1
                            command: Command::Set(SetCommand {
1
                                value: Value::Bytes(Bytes::default()),
1
                                expiration: None,
1
                                keep_existing_expiration: false,
1
                                check: None,
1
                                return_previous_value: false,
1
                            }),
1
                        })
                        .await
1
                        .unwrap();
1
                    sender
1
                        .perform_kv_operation(KeyOperation {
1
                            namespace: None,
1
                            key: String::from("key2"),
1
                            command: Command::Set(SetCommand {
1
                                value: Value::Bytes(Bytes::default()),
1
                                expiration: None,
1
                                keep_existing_expiration: false,
1
                                check: None,
1
                                return_previous_value: false,
1
                            }),
1
                        })
                        .await
1
                        .unwrap();
1
                    sender
1
                        .perform_kv_operation(KeyOperation {
1
                            namespace: None,
1
                            key: String::from("key3"),
1
                            command: Command::Set(SetCommand {
1
                                value: Value::Bytes(Bytes::default()),
1
                                expiration: None,
1
                                keep_existing_expiration: false,
1
                                check: None,
1
                                return_previous_value: false,
1
                            }),
1
                        })
                        .await
1
                        .unwrap();
1
                    // Persisting is handled in the background. Sleep for a bit
1
                    // to give it a chance to happen, but not long enough to
1
                    // trigger the longer time-based rule.
1
                    if timing.elapsed() > Duration::from_millis(500)
1
                        || !timing.wait_until(Duration::from_secs(1)).await
1
                    {
1
                        println!("basic_persistence restarting due to timing discrepency");
                        continue;
1
                    }
1
                    assert!(tree.get(b"\0key1").unwrap().is_some());
1
                    assert!(tree.get(b"\0key2").unwrap().is_some());
1
                    assert!(tree.get(b"\0key3").unwrap().is_none());
1
                    if !timing.wait_until(Duration::from_secs(3)).await {
1
                        println!("basic_persistence restarting due to timing discrepency");
                        continue;
1
                    }
1
                    assert!(tree.get(b"\0key3").unwrap().is_some());
1
                    break;
1
                }
1

            
1
                Ok(())
1
            },
2
        )
2
        .await
1
    }

            
1
    #[tokio::test]
1
    async fn saves_on_drop() -> anyhow::Result<()> {
1
        let dir = TestDirectory::new("saves-on-drop.bonsaidb");
1
        let sled = nebari::Config::new(&dir)
1
            .file_manager(AnyFileManager::std())
1
            .open()?;
1
        let tree = sled.tree(Unversioned::tree(KEY_TREE))?;

            
1
        let context = Context::new(
1
            sled.clone(),
1
            KeyValuePersistence::lazy([PersistenceThreshold::after_changes(2)]),
1
        );
1
        context
1
            .perform_kv_operation(KeyOperation {
1
                namespace: None,
1
                key: String::from("key1"),
1
                command: Command::Set(SetCommand {
1
                    value: Value::Bytes(Bytes::default()),
1
                    expiration: None,
1
                    keep_existing_expiration: false,
1
                    check: None,
1
                    return_previous_value: false,
1
                }),
1
            })
            .await
1
            .unwrap();
1
        assert!(tree.get(b"\0key1").unwrap().is_none());
1
        drop(context);
1
        // Dropping spawns a task that should persist the keys. Give a moment
1
        // for the runtime to execute the task.
1
        tokio::time::sleep(Duration::from_millis(100)).await;
1
        assert!(tree.get(b"\0key1").unwrap().is_some());

            
1
        Ok(())
1
    }
}