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
669587
#[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
1496836
    }
76
}
77

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

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

            
107
75
                        Ok(())
108
7666
                    },
109
7666
                )?;
110
7666
            Result::<_, Error>::Ok(all_entries)
111
7667
        })
112
6733
        .await??;
113

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

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

            
135
7635
        Ok(all_entries)
136
7635
    }
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
133215
    if let Some((namespace, key)) = full_key.split_once('\0') {
154
133215
        let namespace = if namespace.is_empty() {
155
130510
            None
156
        } else {
157
2705
            Some(namespace.to_string())
158
        };
159
133215
        Some((namespace, key.to_string()))
160
    } else {
161
        None
162
    }
163
133215
}
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<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
19441
    pub fn new(
236
19441
        persistence: KeyValuePersistence,
237
19441
        roots: Roots<AnyFile>,
238
19441
        background_worker_target: watch::Sender<BackgroundWorkerProcessTarget>,
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
13353
    pub async fn shutdown(
254
13353
        &mut self,
255
13353
        state: &Arc<Mutex<KeyValueState>>,
256
13353
    ) -> Result<(), oneshot::error::RecvError> {
257
13353
        let (shutdown_sender, shutdown_receiver) = oneshot::channel();
258
13353
        self.shutdown = Some(shutdown_sender);
259
13353
        if self.keys_being_persisted.is_none() {
260
13329
            self.commit_dirty_keys(state);
261
13329
        }
262
13353
        shutdown_receiver.await
263
    }
264

            
265
748422
    pub async fn perform_kv_operation(
266
748422
        &mut self,
267
748422
        op: KeyOperation,
268
748422
        state: &Arc<Mutex<KeyValueState>>,
269
748422
    ) -> Result<Output, bonsaidb_core::Error> {
270
748422
        let now = Timestamp::now();
271
748422
        // If there are any keys that have expired, clear them before executing any operations.
272
748422
        self.remove_expired_keys(now);
273
748422
        let result = match op.command {
274
3251
            Command::Set(command) => {
275
3251
                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
748422
        if result.is_ok() {
297
748126
            if self.needs_commit(now) {
298
119368
                self.commit_dirty_keys(state);
299
628758
            }
300
748126
            self.update_background_worker_target();
301
296
        }
302
748422
        result
303
748422
    }
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
128
            Ok(dirty_entry.take())
516
612
        } else if let Some(persisting_entry) = self
517
612
            .keys_being_persisted
518
612
            .as_ref()
519
612
            .and_then(|keys| keys.get(&key))
520
        {
521
24
            self.dirty_keys.insert(key, None);
522
24
            Ok(persisting_entry.clone())
523
        } else {
524
            // There might be a value on-disk we need to remove.
525
588
            let previous_value = Self::retrieve_key_from_disk(&self.roots, &key)?;
526
588
            self.dirty_keys.insert(key, None);
527
588
            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
612464
            Ok(entry.clone())
534
132631
        } else if let Some(persisting_entry) = self
535
132631
            .keys_being_persisted
536
132631
            .as_ref()
537
132631
            .and_then(|keys| keys.get(key))
538
        {
539
56683
            Ok(persisting_entry.clone())
540
        } else {
541
75948
            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
1926
            let stored_value = if let Some(persisting_entry) = self
556
1926
                .keys_being_persisted
557
1926
                .as_ref()
558
1926
                .and_then(|keys| keys.get(map_entry.key()))
559
            {
560
78
                persisting_entry.clone()
561
            } else {
562
1848
                Self::retrieve_key_from_disk(&self.roots, map_entry.key())?
563
            };
564
1926
            map_entry.or_insert(value);
565
1926
            Ok(stored_value)
566
        } else {
567
            // This key is already dirty, we can just replace the value and
568
            // return the old value.
569
587
            map_entry.and_modify(|map_entry| {
570
587
                std::mem::swap(&mut value, map_entry);
571
587
            });
572
587
            Ok(value)
573
        }
574
2513
    }
575

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

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

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

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

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

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

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

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

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

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

            
745
19441
pub async fn background_worker(
746
19441
    key_value_state: Arc<Mutex<KeyValueState>>,
747
19441
    mut timestamp_receiver: watch::Receiver<BackgroundWorkerProcessTarget>,
748
19441
) -> Result<(), Error> {
749
200336
    loop {
750
200336
        let mut perform_operations = false;
751
200336
        let current_timestamp = *timestamp_receiver.borrow_and_update();
752
200336
        let changed_result = match current_timestamp {
753
128665
            BackgroundWorkerProcessTarget::Never => timestamp_receiver.changed().await,
754
47185
            BackgroundWorkerProcessTarget::Timestamp(target) => {
755
47185
                let remaining = target - Timestamp::now();
756
47185
                if let Some(remaining) = remaining {
757
47185
                    tokio::select! {
758
46095
                        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
24486
                perform_operations = true;
771
24486
                Ok(())
772
            }
773
        };
774

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

            
779
181075
        if perform_operations {
780
38015
            let mut state = fast_async_lock!(key_value_state);
781
24717
            let now = Timestamp::now();
782
24717
            state.remove_expired_keys(now);
783
24717
            if state.needs_commit(now) {
784
13029
                state.commit_dirty_keys(&key_value_state);
785
13029
            }
786
24717
            state.update_background_worker_target();
787
156358
        }
788
    }
789

            
790
    Ok(())
791
}
792

            
793
78914
#[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
10042
    fn key(&self) -> Task {
808
10042
        Task::ExpirationLoader(self.database.data.name.clone())
809
10042
    }
810
}
811

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

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

            
822
7494
        for ((namespace, key), entry) in database.all_key_value_entries().await? {
823
513
            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
512
            }
831
        }
832

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

            
839
7462
        Ok(())
840
14956
    }
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
    }
}