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
670551
#[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
778760
    async fn execute_key_operation(
71
778760
        &self,
72
778760
        op: KeyOperation,
73
778760
    ) -> Result<Output, bonsaidb_core::Error> {
74
778760
        self.data.context.perform_kv_operation(op).await
75
1557520
    }
76
}
77

            
78
impl Database {
79
8606
    pub(crate) async fn all_key_value_entries(
80
8606
        &self,
81
8606
    ) -> 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
8606
        let state = fast_async_lock!(self.data.context.key_value_state);
84
8606
        let database = self.clone();
85
8606
        // Initialize our entries with any dirty keys and any keys that are about to be persisted.
86
8606
        let mut all_entries = BTreeMap::new();
87
8606
        let mut all_entries = tokio::task::spawn_blocking(move || {
88
8605
            database
89
8605
                .roots()
90
8605
                .tree(Unversioned::tree(KEY_TREE))?
91
8605
                .scan::<Error, _, _, _, _>(
92
8605
                    &(..),
93
8605
                    true,
94
8605
                    |_, _, _| true,
95
8605
                    |_, _| KeyEvaluation::ReadData,
96
8605
                    |key, _, entry: ArcBytes<'static>| {
97
104
                        let entry = bincode::deserialize::<Entry>(&entry)
98
104
                            .map_err(|err| AbortError::Other(Error::from(err)))?;
99
104
                        let full_key = std::str::from_utf8(&key)
100
104
                            .map_err(|err| AbortError::Other(Error::from(err)))?;
101

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

            
107
104
                        Ok(())
108
8605
                    },
109
8605
                )?;
110
8605
            Result::<_, Error>::Ok(all_entries)
111
8606
        })
112
7763
        .await??;
113

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

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

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

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

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

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

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

            
193
693
fn decrement(existing: &Numeric, amount: &Numeric, saturating: bool) -> Numeric {
194
693
    match amount {
195
231
        Numeric::Integer(amount) => {
196
231
            let existing_value = existing.as_i64_lossy(saturating);
197
231
            let new_value = if saturating {
198
154
                existing_value.saturating_sub(*amount)
199
            } else {
200
77
                existing_value.wrapping_sub(*amount)
201
            };
202
231
            Numeric::Integer(new_value)
203
        }
204
308
        Numeric::UnsignedInteger(amount) => {
205
308
            let existing_value = existing.as_u64_lossy(saturating);
206
308
            let new_value = if saturating {
207
154
                existing_value.saturating_sub(*amount)
208
            } else {
209
154
                existing_value.wrapping_sub(*amount)
210
            };
211
308
            Numeric::UnsignedInteger(new_value)
212
        }
213
154
        Numeric::Float(amount) => {
214
154
            let existing_value = existing.as_f64_lossy();
215
154
            let new_value = existing_value - *amount;
216
154
            Numeric::Float(new_value)
217
        }
218
    }
219
693
}
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<BackgroundWorkerProcessTarget>,
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
20845
    pub fn new(
236
20845
        persistence: KeyValuePersistence,
237
20845
        roots: Roots<AnyFile>,
238
20845
        background_worker_target: watch::Sender<BackgroundWorkerProcessTarget>,
239
20845
    ) -> Self {
240
20845
        Self {
241
20845
            roots,
242
20845
            persistence,
243
20845
            last_commit: Timestamp::now(),
244
20845
            expiring_keys: BTreeMap::new(),
245
20845
            background_worker_target,
246
20845
            expiration_order: VecDeque::new(),
247
20845
            dirty_keys: BTreeMap::new(),
248
20845
            keys_being_persisted: None,
249
20845
            shutdown: None,
250
20845
        }
251
20845
    }
252

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

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

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

            
326
3306
        let updating = match set.check {
327
179
            Some(KeyCheck::OnlyIfPresent) => existing_value_ref.is_some(),
328
204
            Some(KeyCheck::OnlyIfVacant) => existing_value_ref.is_none(),
329
2923
            None => true,
330
        };
331
3306
        if updating {
332
3127
            if set.keep_existing_expiration {
333
77
                if let Some(existing_value) = existing_value_ref {
334
77
                    entry.expiration = existing_value.expiration;
335
77
                }
336
3050
            }
337
3127
            self.update_key_expiration(&full_key, entry.expiration);
338

            
339
3127
            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
512
                self.set(full_key, entry);
342
512
                existing_value
343
            } else {
344
2615
                self.replace(full_key, entry).map_err(Error::from)?
345
            };
346
3127
            if set.return_previous_value {
347
256
                Ok(Output::Value(previous_value.map(|entry| entry.value)))
348
2871
            } else if previous_value.is_none() {
349
1308
                Ok(Output::Status(KeyStatus::Inserted))
350
            } else {
351
1563
                Ok(Output::Status(KeyStatus::Updated))
352
            }
353
        } else {
354
179
            Ok(Output::Status(KeyStatus::NotChanged))
355
        }
356
3383
    }
357

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

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

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

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

            
423
3908
        if changed_first_expiration {
424
472
            self.update_background_worker_target();
425
3436
        }
426
3908
    }
427

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
586
956815
    fn update_background_worker_target(&mut self) {
587
956815
        let key_expiration_target =
588
956815
            self.expiration_order
589
956815
                .get(0)
590
956815
                .map_or_else(Timestamp::max, |key| {
591
2579
                    let expiration_timeout = self.expiring_keys.get(key).unwrap();
592
2579
                    *expiration_timeout
593
956815
                });
594
956815
        let now = Timestamp::now();
595
956815
        if self.keys_being_persisted.is_some() {
596
799225
            drop(
597
799225
                self.background_worker_target
598
799225
                    .send(BackgroundWorkerProcessTarget::Never),
599
799225
            );
600
799225
            return;
601
157590
        }
602
157590
        let duration_until_commit = self.persistence.duration_until_next_commit(
603
157590
            self.dirty_keys.len(),
604
157590
            (now - self.last_commit).unwrap_or_default(),
605
157590
        );
606
157590
        if duration_until_commit == Duration::ZERO {
607
49145
            drop(
608
49145
                self.background_worker_target
609
49145
                    .send(BackgroundWorkerProcessTarget::Now),
610
49145
            );
611
49145
        } else {
612
108445
            let commit_target = now + duration_until_commit;
613
108445
            let closest_target = key_expiration_target.min(commit_target);
614
108445
            if *self.background_worker_target.borrow()
615
108445
                != BackgroundWorkerProcessTarget::Timestamp(closest_target)
616
108269
            {
617
108269
                drop(
618
108269
                    self.background_worker_target
619
108269
                        .send(BackgroundWorkerProcessTarget::Timestamp(closest_target)),
620
108269
                );
621
108269
            }
622
        }
623
956816
    }
624

            
625
802239
    fn remove_expired_keys(&mut self, now: Timestamp) {
626
802478
        while !self.expiration_order.is_empty()
627
1295
            && self.expiring_keys.get(&self.expiration_order[0]).unwrap() <= &now
628
239
        {
629
239
            let key = self.expiration_order.pop_front().unwrap();
630
239
            self.expiring_keys.remove(&key);
631
239
            self.dirty_keys.insert(key, None);
632
239
        }
633
802239
    }
634

            
635
801930
    fn needs_commit(&mut self, now: Timestamp) -> bool {
636
801930
        if self.keys_being_persisted.is_some() {
637
644728
            false
638
        } else {
639
157202
            let since_last_commit = (now - self.last_commit).unwrap_or_default();
640
157202
            self.persistence
641
157202
                .should_commit(self.dirty_keys.len(), since_last_commit)
642
        }
643
801930
    }
644

            
645
168822
    fn stage_dirty_keys(&mut self) -> Option<Arc<BTreeMap<String, Option<Entry>>>> {
646
168822
        if !self.dirty_keys.is_empty() && self.keys_being_persisted.is_none() {
647
154413
            let keys = Arc::new(std::mem::take(&mut self.dirty_keys));
648
154413
            self.keys_being_persisted = Some(keys.clone());
649
154413
            Some(keys)
650
        } else {
651
14409
            None
652
        }
653
168822
    }
654

            
655
    fn commit_dirty_keys(&mut self, state: &Arc<Mutex<KeyValueState>>) {
656
168695
        if let Some(keys) = self.stage_dirty_keys() {
657
154413
            let roots = self.roots.clone();
658
154413
            let state = state.clone();
659
154413
            let tokio = Handle::current();
660
154413
            tokio::task::spawn_blocking(move || Self::persist_keys(&state, &roots, &keys, &tokio));
661
154413
            self.last_commit = Timestamp::now();
662
154413
        }
663
168695
    }
664

            
665
154413
    fn persist_keys(
666
154413
        key_value_state: &Arc<Mutex<KeyValueState>>,
667
154413
        roots: &Roots<AnyFile>,
668
154413
        keys: &BTreeMap<String, Option<Entry>>,
669
154413
        runtime: &Handle,
670
154413
    ) -> Result<(), bonsaidb_core::Error> {
671
154413
        let mut transaction = roots
672
154413
            .transaction(&[Unversioned::tree(KEY_TREE)])
673
154413
            .map_err(Error::from)?;
674
154413
        let all_keys = keys
675
154413
            .keys()
676
154748
            .map(|key| ArcBytes::from(key.as_bytes().to_vec()))
677
154413
            .collect();
678
154413
        let mut changed_keys = Vec::new();
679
154413
        transaction
680
154413
            .tree::<Unversioned>(0)
681
154413
            .unwrap()
682
154413
            .modify(
683
154413
                all_keys,
684
154748
                Operation::CompareSwap(CompareSwap::new(&mut |key, existing_value| {
685
154748
                    let full_key = std::str::from_utf8(key).unwrap();
686
154748
                    let (namespace, key) = split_key(full_key).unwrap();
687

            
688
154748
                    if let Some(new_value) = keys.get(full_key).unwrap() {
689
153899
                        changed_keys.push(ChangedKey {
690
153899
                            namespace,
691
153899
                            key,
692
153899
                            deleted: false,
693
153899
                        });
694
153899
                        let bytes = bincode::serialize(new_value).unwrap();
695
153899
                        nebari::tree::KeyOperation::Set(ArcBytes::from(bytes))
696
849
                    } else if existing_value.is_some() {
697
518
                        changed_keys.push(ChangedKey {
698
518
                            namespace,
699
518
                            key,
700
518
                            deleted: existing_value.is_some(),
701
518
                        });
702
518
                        nebari::tree::KeyOperation::Remove
703
                    } else {
704
331
                        nebari::tree::KeyOperation::Skip
705
                    }
706
154748
                })),
707
154413
            )
708
154413
            .map_err(Error::from)?;
709

            
710
154413
        if !changed_keys.is_empty() {
711
154082
            transaction
712
154082
                .entry_mut()
713
154082
                .set_data(pot::to_vec(&Changes::Keys(changed_keys))?)
714
154082
                .map_err(Error::from)?;
715
154082
            transaction.commit().map_err(Error::from)?;
716
331
        }
717

            
718
        // If we are shutting down, check if we still have dirty keys.
719
154413
        if let Some(final_keys) = runtime.block_on(async {
720
154413
            let mut state = fast_async_lock!(key_value_state);
721
154413
            state.keys_being_persisted = None;
722
154413
            state.update_background_worker_target();
723
154413
            // This block is a little ugly to avoid having to acquire the lock
724
154413
            // twice. If we're shutting down and have no dirty keys, we notify
725
154413
            // the waiting shutdown task. If we have any dirty keys, we wait do
726
154413
            // to that step because we're going to recurse and reach this spot
727
154413
            // again.
728
154413
            if state.shutdown.is_some() {
729
127
                let staged_keys = state.stage_dirty_keys();
730
127
                if staged_keys.is_none() {
731
127
                    let shutdown = state.shutdown.take().unwrap();
732
127
                    let _ = shutdown.send(());
733
127
                }
734
127
                staged_keys
735
            } else {
736
154286
                None
737
            }
738
154413
        }) {
739
            Self::persist_keys(key_value_state, roots, &final_keys, runtime)?;
740
154413
        }
741
154413
        Ok(())
742
154413
    }
743
}
744

            
745
20845
pub async fn background_worker(
746
20845
    key_value_state: Arc<Mutex<KeyValueState>>,
747
20845
    mut timestamp_receiver: watch::Receiver<BackgroundWorkerProcessTarget>,
748
20845
) -> Result<(), Error> {
749
239274
    loop {
750
239274
        let mut perform_operations = false;
751
239274
        let current_timestamp = *timestamp_receiver.borrow_and_update();
752
239274
        let changed_result = match current_timestamp {
753
149463
            BackgroundWorkerProcessTarget::Never => timestamp_receiver.changed().await,
754
66576
            BackgroundWorkerProcessTarget::Timestamp(target) => {
755
66576
                let remaining = target - Timestamp::now();
756
66576
                if let Some(remaining) = remaining {
757
66576
                    tokio::select! {
758
65467
                        changed = timestamp_receiver.changed() => changed,
759
                        _ = tokio::time::sleep(remaining) => {
760
                            perform_operations = true;
761
                            Ok(())
762
                        },
763
                    }
764
                } else {
765
                    perform_operations = true;
766
                    Ok(())
767
                }
768
            }
769
            BackgroundWorkerProcessTarget::Now => {
770
23235
                perform_operations = true;
771
23235
                Ok(())
772
            }
773
        };
774

            
775
218591
        if changed_result.is_err() {
776
            break;
777
218591
        }
778
218591

            
779
218591
        if perform_operations {
780
36752
            let mut state = fast_async_lock!(key_value_state);
781
23475
            let now = Timestamp::now();
782
23475
            state.remove_expired_keys(now);
783
23475
            if state.needs_commit(now) {
784
11874
                state.commit_dirty_keys(&key_value_state);
785
11874
            }
786
23475
            state.update_background_worker_target();
787
195116
        }
788
    }
789

            
790
    Ok(())
791
}
792

            
793
108446
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
794
pub enum BackgroundWorkerProcessTarget {
795
    Now,
796
    Timestamp(Timestamp),
797
    Never,
798
}
799

            
800
#[derive(Debug)]
801
pub struct ExpirationLoader {
802
    pub database: Database,
803
    pub launched_at: Timestamp,
804
}
805

            
806
impl Keyed<Task> for ExpirationLoader {
807
9689
    fn key(&self) -> Task {
808
9689
        Task::ExpirationLoader(self.database.data.name.clone())
809
9689
    }
810
}
811

            
812
#[async_trait]
813
impl Job for ExpirationLoader {
814
    type Output = ();
815
    type Error = Error;
816

            
817
25278
    #[cfg_attr(feature = "tracing", tracing::instrument)]
818
8401
    async fn execute(&mut self) -> Result<Self::Output, Self::Error> {
819
8401
        let database = self.database.clone();
820
8401
        let launched_at = self.launched_at;
821

            
822
8401
        for ((namespace, key), entry) in database.all_key_value_entries().await? {
823
534
            if entry.last_updated < launched_at && entry.expiration.is_some() {
824
1
                self.database
825
1
                    .update_key_expiration_async(
826
1
                        full_key(namespace.as_deref(), &key),
827
1
                        entry.expiration,
828
1
                    )
829
                    .await;
830
533
            }
831
        }
832

            
833
8321
        self.database
834
8321
            .storage()
835
8321
            .tasks()
836
8321
            .mark_key_value_expiration_loaded(self.database.data.name.clone())
837
            .await;
838

            
839
8321
        Ok(())
840
16722
    }
841
}
842

            
843
#[cfg(test)]
844
mod tests {
845
    use std::time::Duration;
846

            
847
    use bonsaidb_core::{
848
        arc_bytes::serde::Bytes,
849
        test_util::{TestDirectory, TimingTest},
850
    };
851
    use futures::Future;
852
    use nebari::io::any::{AnyFile, AnyFileManager};
853

            
854
    use super::*;
855
    use crate::{config::PersistenceThreshold, database::Context};
856

            
857
6
    async fn run_test_with_persistence<
858
6
        F: Fn(Context, nebari::Roots<AnyFile>) -> R + Send,
859
6
        R: Future<Output = anyhow::Result<()>> + Send,
860
6
    >(
861
6
        name: &str,
862
6
        persistence: KeyValuePersistence,
863
6
        test_contents: &F,
864
6
    ) -> anyhow::Result<()> {
865
6
        let dir = TestDirectory::new(name);
866
6
        let sled = nebari::Config::new(&dir)
867
6
            .file_manager(AnyFileManager::std())
868
6
            .open()?;
869

            
870
6
        let context = Context::new(sled.clone(), persistence);
871
6

            
872
11
        test_contents(context, sled).await?;
873

            
874
6
        Ok(())
875
6
    }
876

            
877
5
    async fn run_test<
878
5
        F: Fn(Context, nebari::Roots<AnyFile>) -> R + Send,
879
5
        R: Future<Output = anyhow::Result<()>> + Send,
880
5
    >(
881
5
        name: &str,
882
5
        test_contents: F,
883
5
    ) -> anyhow::Result<()> {
884
9
        run_test_with_persistence(name, KeyValuePersistence::default(), &test_contents).await
885
5
    }
886

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

            
909
1
            Ok(())
910
1
        })
911
1
        .await
912
1
    }
913

            
914
1
    #[tokio::test]
915
1
    async fn updating_expiration() -> anyhow::Result<()> {
916
1
        run_test("kv-updating-expiration", |sender, sled| async move {
917
            loop {
918
1
                sled.delete_tree(KEY_TREE)?;
919
1
                let tree = sled.tree(Unversioned::tree(KEY_TREE))?;
920
1
                tree.set(b"atree\0akey", b"somevalue")?;
921
1
                let timing = TimingTest::new(Duration::from_millis(100));
922
1
                sender
923
1
                    .update_key_expiration_async(
924
1
                        full_key(Some("atree"), "akey"),
925
1
                        Some(Timestamp::now() + Duration::from_millis(100)),
926
1
                    )
927
                    .await;
928
1
                sender
929
1
                    .update_key_expiration_async(
930
1
                        full_key(Some("atree"), "akey"),
931
1
                        Some(Timestamp::now() + Duration::from_secs(1)),
932
1
                    )
933
                    .await;
934
1
                if timing.elapsed() > Duration::from_millis(100)
935
1
                    || !timing.wait_until(Duration::from_millis(500)).await
936
                {
937
                    continue;
938
1
                }
939
1
                assert!(tree.get(b"atree\0akey")?.is_some());
940

            
941
1
                timing.wait_until(Duration::from_secs_f32(1.5)).await;
942
1
                assert_eq!(tree.get(b"atree\0akey")?, None);
943
1
                break;
944
1
            }
945
1

            
946
1
            Ok(())
947
2
        })
948
2
        .await
949
1
    }
950

            
951
1
    #[tokio::test]
952
1
    async fn multiple_keys_expiration() -> anyhow::Result<()> {
953
1
        run_test("kv-multiple-keys-expiration", |sender, sled| async move {
954
            loop {
955
1
                sled.delete_tree(KEY_TREE)?;
956
1
                let tree = sled.tree(Unversioned::tree(KEY_TREE))?;
957
1
                tree.set(b"atree\0akey", b"somevalue")?;
958
1
                tree.set(b"atree\0bkey", b"somevalue")?;
959

            
960
1
                let timing = TimingTest::new(Duration::from_millis(100));
961
1
                sender
962
1
                    .update_key_expiration_async(
963
1
                        full_key(Some("atree"), "akey"),
964
1
                        Some(Timestamp::now() + Duration::from_millis(100)),
965
1
                    )
966
                    .await;
967
1
                sender
968
1
                    .update_key_expiration_async(
969
1
                        full_key(Some("atree"), "bkey"),
970
1
                        Some(Timestamp::now() + Duration::from_secs(1)),
971
1
                    )
972
                    .await;
973

            
974
1
                if !timing.wait_until(Duration::from_millis(200)).await {
975
                    continue;
976
1
                }
977

            
978
1
                assert!(tree.get(b"atree\0akey")?.is_none());
979
1
                assert!(tree.get(b"atree\0bkey")?.is_some());
980
1
                timing.wait_until(Duration::from_millis(1100)).await;
981
1
                assert!(tree.get(b"atree\0bkey")?.is_none());
982

            
983
1
                break;
984
1
            }
985
1

            
986
1
            Ok(())
987
2
        })
988
2
        .await
989
1
    }
990

            
991
1
    #[tokio::test]
992
1
    async fn clearing_expiration() -> anyhow::Result<()> {
993
1
        run_test("kv-clearing-expiration", |sender, sled| async move {
994
            loop {
995
1
                sled.delete_tree(KEY_TREE)?;
996
1
                let tree = sled.tree(Unversioned::tree(KEY_TREE))?;
997
1
                tree.set(b"atree\0akey", b"somevalue")?;
998
1
                let timing = TimingTest::new(Duration::from_millis(100));
999
1
                sender
1
                    .update_key_expiration_async(
1
                        full_key(Some("atree"), "akey"),
1
                        Some(Timestamp::now() + Duration::from_millis(100)),
1
                    )
                    .await;
1
                sender
1
                    .update_key_expiration_async(full_key(Some("atree"), "akey"), None)
                    .await;
1
                if timing.elapsed() > Duration::from_millis(100) {
                    // Restart, took too long.
                    continue;
1
                }
1
                timing.wait_until(Duration::from_millis(150)).await;
1
                assert!(tree.get(b"atree\0akey")?.is_some());
1
                break;
1
            }
1

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

            
1
    #[tokio::test]
1
    async fn out_of_order_expiration() -> anyhow::Result<()> {
1
        run_test("kv-out-of-order-expiration", |sender, sled| async move {
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
    }
}