1
use std::{
2
    collections::HashMap,
3
    path::{Path, PathBuf},
4
    sync::Arc,
5
    time::Duration,
6
};
7

            
8
#[cfg(feature = "encryption")]
9
use bonsaidb_core::document::KeyId;
10
use bonsaidb_core::schema::{Schema, SchemaName};
11
use sysinfo::{RefreshKind, System, SystemExt};
12

            
13
#[cfg(feature = "encryption")]
14
use crate::vault::AnyVaultKeyStorage;
15
use crate::{
16
    storage::{DatabaseOpener, StorageSchemaOpener},
17
    Error,
18
};
19

            
20
#[cfg(feature = "password-hashing")]
21
mod argon;
22
#[cfg(feature = "password-hashing")]
23
pub use argon::*;
24

            
25
/// Configuration options for [`Storage`](crate::storage::Storage).
26
10
#[derive(Debug, Clone)]
27
#[non_exhaustive]
28
pub struct StorageConfiguration {
29
    /// The path to the database. Defaults to `db.bonsaidb` if not specified.
30
    pub path: Option<PathBuf>,
31

            
32
    /// Prevents storing data on the disk. This is intended for testing purposes
33
    /// primarily. Keep in mind that the underlying storage format is
34
    /// append-only.
35
    pub memory_only: bool,
36

            
37
    /// The unique id of the server. If not specified, the server will randomly
38
    /// generate a unique id on startup. If the server generated an id and this
39
    /// value is subsequently set, the generated id will be overridden by the
40
    /// one specified here.
41
    pub unique_id: Option<u64>,
42

            
43
    /// The vault key storage to use. If not specified,
44
    /// [`LocalVaultKeyStorage`](crate::vault::LocalVaultKeyStorage) will be
45
    /// used with the server's data folder as the path. This is **incredibly
46
    /// insecure and should not be used outside of testing**.
47
    ///
48
    /// For secure encryption, it is important to store the vault keys in a
49
    /// location that is separate from the database. If the keys are on the same
50
    /// hardware as the encrypted content, anyone with access to the disk will
51
    /// be able to decrypt the stored data.
52
    #[cfg(feature = "encryption")]
53
    pub vault_key_storage: Option<Arc<dyn AnyVaultKeyStorage>>,
54

            
55
    /// The default encryption key for the database. If specified, all documents
56
    /// will be stored encrypted at-rest using the key specified. Having this
57
    /// key specified will also encrypt views. Without this, views will be
58
    /// stored unencrypted.
59
    #[cfg(feature = "encryption")]
60
    pub default_encryption_key: Option<KeyId>,
61

            
62
    /// Configuration options related to background tasks.
63
    pub workers: Tasks,
64

            
65
    /// Configuration options related to views.
66
    pub views: Views,
67

            
68
    /// Controls how the key-value store persists keys, on a per-database basis.
69
    pub key_value_persistence: KeyValuePersistence,
70

            
71
    /// Sets the default compression algorithm.
72
    #[cfg(feature = "compression")]
73
    pub default_compression: Option<Compression>,
74

            
75
    /// Password hashing configuration.
76
    #[cfg(feature = "password-hashing")]
77
    pub argon: ArgonConfiguration,
78

            
79
    pub(crate) initial_schemas: HashMap<SchemaName, Arc<dyn DatabaseOpener>>,
80
}
81

            
82
impl Default for StorageConfiguration {
83
2619
    fn default() -> Self {
84
2619
        let system_specs = RefreshKind::new().with_cpu().with_memory();
85
2619
        let mut system = System::new_with_specifics(system_specs);
86
2619
        system.refresh_specifics(system_specs);
87
2619
        Self {
88
2619
            path: None,
89
2619
            memory_only: false,
90
2619
            unique_id: None,
91
2619
            #[cfg(feature = "encryption")]
92
2619
            vault_key_storage: None,
93
2619
            #[cfg(feature = "encryption")]
94
2619
            default_encryption_key: None,
95
2619
            #[cfg(feature = "compression")]
96
2619
            default_compression: None,
97
2619
            workers: Tasks::default_for(&system),
98
2619
            views: Views::default(),
99
2619
            key_value_persistence: KeyValuePersistence::default(),
100
2619
            #[cfg(feature = "password-hashing")]
101
2619
            argon: ArgonConfiguration::default_for(&system),
102
2619
            initial_schemas: HashMap::default(),
103
2619
        }
104
2619
    }
105
}
106

            
107
impl StorageConfiguration {
108
    /// Registers the schema provided.
109
    pub fn register_schema<S: Schema>(&mut self) -> Result<(), Error> {
110
        self.initial_schemas
111
249
            .insert(S::schema_name(), Arc::new(StorageSchemaOpener::<S>::new()?));
112
249
        Ok(())
113
249
    }
114
}
115

            
116
/// Configuration options for background tasks.
117
10
#[derive(Debug, Clone)]
118
pub struct Tasks {
119
    /// Defines how many workers should be spawned to process tasks. This
120
    /// defaults to the 2x the number of cpu cores available to the system or 4, whichever is larger.
121
    pub worker_count: usize,
122
}
123

            
124
impl SystemDefault for Tasks {
125
2619
    fn default_for(system: &System) -> Self {
126
2619
        Self {
127
2619
            worker_count: system
128
2619
                .physical_core_count()
129
2619
                .unwrap_or_else(|| system.processors().len())
130
2619
                * 2,
131
2619
        }
132
2619
    }
133
}
134

            
135
/// Configuration options for views.
136
2619
#[derive(Clone, Debug, Default)]
137
pub struct Views {
138
    /// If true, the database will scan all views during the call to
139
    /// `open_local`. This will cause database opening to take longer, but once
140
    /// the database is open, no request will need to wait for the integrity to
141
    /// be checked. However, for faster startup time, you may wish to delay the
142
    /// integrity scan. Default value is `false`.
143
    pub check_integrity_on_open: bool,
144
}
145

            
146
/// Rules for persisting key-value changes. Default persistence is to
147
/// immediately persist all changes. While this ensures data integrity, the
148
/// overhead of the key-value store can be significantly reduced by utilizing
149
/// lazy persistence strategies that delay writing changes until certain
150
/// thresholds have been met.
151
///
152
/// ## Immediate persistence
153
///
154
/// The default persistence mode will trigger commits always:
155
///
156
/// ```rust
157
/// # use bonsaidb_local::config::KeyValuePersistence;
158
/// # use std::time::Duration;
159
/// assert!(!KeyValuePersistence::default().should_commit(0, Duration::ZERO));
160
/// assert!(KeyValuePersistence::default().should_commit(1, Duration::ZERO));
161
/// ```
162
///
163
/// ## Lazy persistence
164
///
165
/// Lazy persistence allows setting multiple thresholds, allowing for customized
166
/// behavior that can help tune performance, especially under write-heavy loads.
167
///
168
/// It is good practice to include one [`PersistenceThreshold`] that has no
169
/// duration, as it will ensure that the in-memory cache cannot exceed a certain
170
/// size. This number is counted for each database indepenently.
171
///
172
/// ```rust
173
/// # use bonsaidb_local::config::{KeyValuePersistence, PersistenceThreshold};
174
/// # use std::time::Duration;
175
/// #
176
/// let persistence = KeyValuePersistence::lazy([
177
///     PersistenceThreshold::after_changes(1).and_duration(Duration::from_secs(120)),
178
///     PersistenceThreshold::after_changes(10).and_duration(Duration::from_secs(10)),
179
///     PersistenceThreshold::after_changes(100),
180
/// ]);
181
///
182
/// // After 1 change and 60 seconds, no changes would be committed:
183
/// assert!(!persistence.should_commit(1, Duration::from_secs(60)));
184
/// // But on or after 120 seconds, that change will be committed:
185
/// assert!(persistence.should_commit(1, Duration::from_secs(120)));
186
///
187
/// // After 10 changes and 10 seconds, changes will be committed:
188
/// assert!(persistence.should_commit(10, Duration::from_secs(10)));
189
///
190
/// // Once 100 changes have been accumulated, this ruleset will always commit
191
/// // regardless of duration.
192
/// assert!(persistence.should_commit(100, Duration::ZERO));
193
/// ```
194
20848
#[derive(Debug, Clone)]
195
#[must_use]
196
pub struct KeyValuePersistence(KeyValuePersistenceInner);
197

            
198
20848
#[derive(Debug, Clone)]
199
enum KeyValuePersistenceInner {
200
    Immediate,
201
    Lazy(Vec<PersistenceThreshold>),
202
}
203

            
204
impl Default for KeyValuePersistence {
205
    /// Returns [`KeyValuePersistence::immediate()`].
206
2624
    fn default() -> Self {
207
2624
        Self::immediate()
208
2624
    }
209
}
210

            
211
impl KeyValuePersistence {
212
    /// Returns a ruleset that commits all changes immediately.
213
2824
    pub const fn immediate() -> Self {
214
2824
        Self(KeyValuePersistenceInner::Immediate)
215
2824
    }
216

            
217
    /// Returns a ruleset that lazily commits data based on a list of thresholds.
218
13
    pub fn lazy<II>(rules: II) -> Self
219
13
    where
220
13
        II: IntoIterator<Item = PersistenceThreshold>,
221
13
    {
222
13
        let mut rules = rules.into_iter().collect::<Vec<_>>();
223
13
        rules.sort_by(|a, b| a.number_of_changes.cmp(&b.number_of_changes));
224
13
        Self(KeyValuePersistenceInner::Lazy(rules))
225
13
    }
226

            
227
    /// Returns true if these rules determine that the outstanding changes should be persisted.
228
    #[must_use]
229
157202
    pub fn should_commit(
230
157202
        &self,
231
157202
        number_of_changes: usize,
232
157202
        elapsed_since_last_commit: Duration,
233
157202
    ) -> bool {
234
157202
        self.duration_until_next_commit(number_of_changes, elapsed_since_last_commit)
235
157202
            == Duration::ZERO
236
157202
    }
237

            
238
314793
    pub(crate) fn duration_until_next_commit(
239
314793
        &self,
240
314793
        number_of_changes: usize,
241
314793
        elapsed_since_last_commit: Duration,
242
314793
    ) -> Duration {
243
314793
        if number_of_changes == 0 {
244
110554
            Duration::MAX
245
        } else {
246
204239
            match &self.0 {
247
203478
                KeyValuePersistenceInner::Immediate => Duration::ZERO,
248
761
                KeyValuePersistenceInner::Lazy(rules) => {
249
761
                    let mut shortest_duration = Duration::MAX;
250
761
                    for rule in rules
251
761
                        .iter()
252
765
                        .take_while(|rule| rule.number_of_changes <= number_of_changes)
253
                    {
254
7
                        let remaining_time =
255
7
                            rule.duration.saturating_sub(elapsed_since_last_commit);
256
7
                        shortest_duration = shortest_duration.min(remaining_time);
257
7

            
258
7
                        if shortest_duration == Duration::ZERO {
259
3
                            break;
260
4
                        }
261
                    }
262
761
                    shortest_duration
263
                }
264
            }
265
        }
266
314793
    }
267
}
268

            
269
/// A threshold controlling lazy commits. For a threshold to apply, both
270
/// `number_of_changes` must be met or surpassed and `duration` must have
271
/// elpased since the last commit.
272
///
273
/// A threshold with a duration of zero will not wait any time to persist
274
/// changes once the specified `number_of_changes` has been met or surpassed.
275
#[derive(Debug, Copy, Clone)]
276
#[must_use]
277
pub struct PersistenceThreshold {
278
    /// The minimum number of changes that must have occurred for this threshold to apply.
279
    pub number_of_changes: usize,
280
    /// The amount of time that must elapse since the last write for this threshold to apply.
281
    pub duration: Duration,
282
}
283

            
284
impl PersistenceThreshold {
285
    /// Returns a threshold that applies after a number of changes have elapsed.
286
254
    pub const fn after_changes(number_of_changes: usize) -> Self {
287
254
        Self {
288
254
            number_of_changes,
289
254
            duration: Duration::ZERO,
290
254
        }
291
254
    }
292

            
293
    /// Sets the duration of this threshold to `duration` and returns self.
294
1
    pub const fn and_duration(mut self, duration: Duration) -> Self {
295
1
        self.duration = duration;
296
1
        self
297
1
    }
298
}
299

            
300
/// Storage configuration builder methods.
301
pub trait Builder: Default {
302
    /// Creates a default configuration with `path` set.
303
171
    fn new<P: AsRef<Path>>(path: P) -> Self {
304
171
        Self::default().path(path)
305
171
    }
306

            
307
    /// Sets [`StorageConfiguration::path`](StorageConfiguration#structfield.memory_only) to true and returns self.
308
    fn memory_only(self) -> Self;
309

            
310
    /// Registers the schema and returns self.
311
    fn with_schema<S: Schema>(self) -> Result<Self, Error>;
312

            
313
    /// Sets [`StorageConfiguration::path`](StorageConfiguration#structfield.path) to `path` and returns self.
314
    fn path<P: AsRef<Path>>(self, path: P) -> Self;
315
    /// Sets [`StorageConfiguration::unique_id`](StorageConfiguration#structfield.unique_id) to `unique_id` and returns self.
316
    fn unique_id(self, unique_id: u64) -> Self;
317
    /// Sets [`StorageConfiguration::vault_key_storage`](StorageConfiguration#structfield.vault_key_storage) to `key_storage` and returns self.
318
    #[cfg(feature = "encryption")]
319
    fn vault_key_storage<VaultKeyStorage: AnyVaultKeyStorage>(
320
        self,
321
        key_storage: VaultKeyStorage,
322
    ) -> Self;
323
    /// Sets [`StorageConfiguration::default_encryption_key`](StorageConfiguration#structfield.default_encryption_key) to `path` and returns self.
324
    #[cfg(feature = "encryption")]
325
    fn default_encryption_key(self, key: KeyId) -> Self;
326
    /// Sets [`Tasks::worker_count`] to `worker_count` and returns self.
327
    fn tasks_worker_count(self, worker_count: usize) -> Self;
328
    /// Sets [`Views::check_integrity_on_open`] to `check` and returns self.
329
    fn check_view_integrity_on_open(self, check: bool) -> Self;
330
    /// Sets [`StorageConfiguration::default_compression`](StorageConfiguration#structfield.default_compression) to `path` and returns self.
331
    #[cfg(feature = "compression")]
332
    fn default_compression(self, compression: Compression) -> Self;
333

            
334
    /// Sets [`StorageConfiguration::key_value_persistence`](StorageConfiguration#structfield.key_value_persistence) to `persistence` and returns self.
335
    fn key_value_persistence(self, persistence: KeyValuePersistence) -> Self;
336
}
337

            
338
impl Builder for StorageConfiguration {
339
    fn with_schema<S: Schema>(mut self) -> Result<Self, Error> {
340
171
        self.register_schema::<S>()?;
341
171
        Ok(self)
342
171
    }
343

            
344
30
    fn memory_only(mut self) -> Self {
345
30
        self.memory_only = true;
346
30
        self
347
30
    }
348

            
349
91
    fn path<P: AsRef<Path>>(mut self, path: P) -> Self {
350
91
        self.path = Some(path.as_ref().to_owned());
351
91
        self
352
91
    }
353

            
354
    fn unique_id(mut self, unique_id: u64) -> Self {
355
        self.unique_id = Some(unique_id);
356
        self
357
    }
358

            
359
    #[cfg(feature = "encryption")]
360
3
    fn vault_key_storage<VaultKeyStorage: AnyVaultKeyStorage>(
361
3
        mut self,
362
3
        key_storage: VaultKeyStorage,
363
3
    ) -> Self {
364
3
        self.vault_key_storage = Some(Arc::new(key_storage));
365
3
        self
366
3
    }
367

            
368
    #[cfg(feature = "encryption")]
369
75
    fn default_encryption_key(mut self, key: KeyId) -> Self {
370
75
        self.default_encryption_key = Some(key);
371
75
        self
372
75
    }
373

            
374
    #[cfg(feature = "compression")]
375
185
    fn default_compression(mut self, compression: Compression) -> Self {
376
185
        self.default_compression = Some(compression);
377
185
        self
378
185
    }
379

            
380
    fn tasks_worker_count(mut self, worker_count: usize) -> Self {
381
        self.workers.worker_count = worker_count;
382
        self
383
    }
384

            
385
1
    fn check_view_integrity_on_open(mut self, check: bool) -> Self {
386
1
        self.views.check_integrity_on_open = check;
387
1
        self
388
1
    }
389

            
390
1
    fn key_value_persistence(mut self, persistence: KeyValuePersistence) -> Self {
391
1
        self.key_value_persistence = persistence;
392
1
        self
393
1
    }
394
}
395

            
396
pub(crate) trait SystemDefault: Sized {
397
    fn default_for(system: &System) -> Self;
398
1
    fn default() -> Self {
399
1
        let system_specs = RefreshKind::new().with_cpu().with_memory();
400
1
        let mut system = System::new_with_specifics(system_specs);
401
1
        system.refresh_specifics(system_specs);
402
1
        Self::default_for(&system)
403
1
    }
404
}
405

            
406
/// All available compression algorithms.
407
1188977
#[derive(Debug, Clone, Copy)]
408
pub enum Compression {
409
    /// Compress data using the
410
    /// [lz4](https://en.wikipedia.org/wiki/LZ4_(compression_algorithm))
411
    /// algorithm. This is powered by
412
    /// [lz4_flex](https://crates.io/crates/lz4_flex).
413
    Lz4 = 1,
414
}
415

            
416
impl Compression {
417
    #[must_use]
418
    #[cfg(feature = "compression")]
419
79841
    pub(crate) fn from_u8(value: u8) -> Option<Self> {
420
79841
        match value {
421
73932
            1 => Some(Self::Lz4),
422
5909
            _ => None,
423
        }
424
79841
    }
425
}