1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
use std::collections::HashMap;
use std::marker::PhantomData;
use std::net::{Ipv6Addr, SocketAddr, SocketAddrV6};
use std::path::Path;
use std::sync::Arc;

use bonsaidb_core::api;
use bonsaidb_core::api::ApiName;
#[cfg(feature = "encryption")]
use bonsaidb_core::document::KeyId;
use bonsaidb_core::permissions::{Permissions, Statement};
use bonsaidb_core::schema::Schema;
#[cfg(feature = "compression")]
use bonsaidb_local::config::Compression;
use bonsaidb_local::config::{Builder, KeyValuePersistence, StorageConfiguration};
#[cfg(feature = "encryption")]
use bonsaidb_local::vault::AnyVaultKeyStorage;

use crate::api::{AnyHandler, AnyWrapper, Handler};
use crate::{Backend, Error, NoBackend};

/// Configuration options for [`Server`](crate::Server)
#[derive(Debug, Clone)]
#[must_use]
#[non_exhaustive]
pub struct ServerConfiguration<B: Backend = NoBackend> {
    /// The [`Backend`] for the server.
    pub backend: B,
    /// The DNS name of the server.
    pub server_name: String,
    /// Number of sumultaneous requests a single client can have in flight at a
    /// time. Default value is 16. It is important to have this number be tuned
    /// relative to `request_workers` such that one client cannot overwhelm the
    /// entire queue.
    pub client_simultaneous_request_limit: usize,
    /// Number of simultaneous requests to be processed. Default value is 16.
    pub request_workers: usize,
    /// Configuration options for individual databases.
    pub storage: StorageConfiguration,
    /// The permissions granted to all connections to this server.
    pub default_permissions: DefaultPermissions,
    /// The ACME settings for automatic TLS certificate management.
    #[cfg(feature = "acme")]
    pub acme: AcmeConfiguration,

    pub(crate) custom_apis: HashMap<ApiName, Arc<dyn AnyHandler<B>>>,
}

impl<B: Backend> ServerConfiguration<B> {
    /// Returns a default configuration for the given backend.
    pub fn default_for(backend: B) -> Self {
        Self {
            backend,
            server_name: String::from("bonsaidb"),
            client_simultaneous_request_limit: 16,
            // TODO this was arbitrarily picked, it probably should be higher,
            // but it also should probably be based on the cpu's capabilities
            request_workers: 16,
            storage: bonsaidb_local::config::StorageConfiguration::default(),
            default_permissions: DefaultPermissions::Permissions(Permissions::default()),
            custom_apis: HashMap::default(),
            #[cfg(feature = "acme")]
            acme: AcmeConfiguration::default(),
        }
    }

    /// Returns a default configuration for the given backend and path.
    pub fn new_with_backend<P: AsRef<Path>>(path: P, backend: B) -> Self {
        Self::default_for(backend).path(path)
    }

    /// Sets [`Self::server_name`](Self#structfield.server_name) to `server_name` and returns self.
    pub fn server_name(mut self, server_name: impl Into<String>) -> Self {
        self.server_name = server_name.into();
        self
    }

    /// Sets [`Self::client_simultaneous_request_limit`](Self#structfield.client_simultaneous_request_limit) to `request_limit` and returns self.
    pub const fn client_simultaneous_request_limit(mut self, request_limit: usize) -> Self {
        self.client_simultaneous_request_limit = request_limit;
        self
    }

    /// Sets [`Self::request_workers`](Self#structfield.request_workers) to `workers` and returns self.
    pub const fn request_workers(mut self, workers: usize) -> Self {
        self.request_workers = workers;
        self
    }

    /// Sets [`Self::default_permissions`](Self#structfield.default_permissions) to `default_permissions` and returns self.
    pub fn default_permissions<P: Into<DefaultPermissions>>(
        mut self,
        default_permissions: P,
    ) -> Self {
        self.default_permissions = default_permissions.into();
        self
    }

    /// Sets [`AcmeConfiguration::contact_email`] to `contact_email` and returns self.
    #[cfg(feature = "acme")]
    pub fn acme_contact_email(mut self, contact_email: impl Into<String>) -> Self {
        self.acme.contact_email = Some(contact_email.into());
        self
    }

    /// Sets [`AcmeConfiguration::directory`] to `directory` and returns self.
    #[cfg(feature = "acme")]
    pub fn acme_directory(mut self, directory: impl Into<String>) -> Self {
        self.acme.directory = directory.into();
        self
    }

    /// Registers a `handler` for a [`Api`][api::Api]. When an [`Api`][api::Api] is
    /// received by the server, the handler will be invoked
    pub fn register_custom_api<Dispatcher: Handler<Api, B> + 'static, Api: api::Api>(
        &mut self,
    ) -> Result<(), Error> {
        // TODO this should error on duplicate registration.
        self.custom_apis.insert(
            Api::name(),
            Arc::new(AnyWrapper::<Dispatcher, B, Api>(PhantomData)),
        );
        Ok(())
    }

    /// Registers the custom api dispatcher and returns self.
    pub fn with_api<Dispatcher: Handler<Api, B> + 'static, Api: api::Api>(
        mut self,
    ) -> Result<Self, Error> {
        self.register_custom_api::<Dispatcher, Api>()?;
        Ok(self)
    }
}

impl<B> Default for ServerConfiguration<B>
where
    B: Backend + Default,
{
    fn default() -> Self {
        Self::default_for(B::default())
    }
}

#[cfg(feature = "acme")]
mod acme {
    /// The Automated Certificate Management Environment (ACME) configuration.
    #[derive(Debug, Clone)]
    pub struct AcmeConfiguration {
        /// The contact email to register with the ACME directory for the account.
        pub contact_email: Option<String>,
        /// The ACME directory to use for registration. The default is
        /// [`LETS_ENCRYPT_PRODUCTION_DIRECTORY`].
        pub directory: String,
    }

    impl Default for AcmeConfiguration {
        fn default() -> Self {
            Self {
                contact_email: None,
                directory: LETS_ENCRYPT_PRODUCTION_DIRECTORY.to_string(),
            }
        }
    }

    pub use async_acme::acme::{LETS_ENCRYPT_PRODUCTION_DIRECTORY, LETS_ENCRYPT_STAGING_DIRECTORY};
}

#[cfg(feature = "acme")]
pub use acme::*;

/// The default permissions to use for all connections to the server.
#[derive(Debug, Clone)]
pub enum DefaultPermissions {
    /// Allow all permissions. Do not use outside of completely trusted environments.
    AllowAll,
    /// A defined set of permissions.
    Permissions(Permissions),
}

impl From<DefaultPermissions> for Permissions {
    fn from(permissions: DefaultPermissions) -> Self {
        match permissions {
            DefaultPermissions::Permissions(permissions) => permissions,
            DefaultPermissions::AllowAll => Self::allow_all(),
        }
    }
}

impl From<Permissions> for DefaultPermissions {
    fn from(permissions: Permissions) -> Self {
        Self::Permissions(permissions)
    }
}

impl From<Vec<Statement>> for DefaultPermissions {
    fn from(permissions: Vec<Statement>) -> Self {
        Self::from(Permissions::from(permissions))
    }
}

impl From<Statement> for DefaultPermissions {
    fn from(permissions: Statement) -> Self {
        Self::from(Permissions::from(permissions))
    }
}

impl<B: Backend> Builder for ServerConfiguration<B> {
    fn with_schema<S: Schema>(mut self) -> Result<Self, bonsaidb_local::Error> {
        self.storage.register_schema::<S>()?;
        Ok(self)
    }

    fn memory_only(mut self) -> Self {
        self.storage.memory_only = true;
        self
    }

    fn path<P: AsRef<Path>>(mut self, path: P) -> Self {
        self.storage.path = Some(path.as_ref().to_owned());
        self
    }

    fn unique_id(mut self, unique_id: u64) -> Self {
        self.storage.unique_id = Some(unique_id);
        self
    }

    #[cfg(feature = "encryption")]
    fn vault_key_storage<VaultKeyStorage: AnyVaultKeyStorage>(
        mut self,
        key_storage: VaultKeyStorage,
    ) -> Self {
        self.storage.vault_key_storage = Some(std::sync::Arc::new(key_storage));
        self
    }

    #[cfg(feature = "encryption")]
    fn default_encryption_key(mut self, key: KeyId) -> Self {
        self.storage.default_encryption_key = Some(key);
        self
    }

    fn tasks_worker_count(mut self, worker_count: usize) -> Self {
        self.storage.workers.worker_count = worker_count;
        self
    }

    fn tasks_parallelization(mut self, parallelization: usize) -> Self {
        self.storage.workers.parallelization = parallelization;
        self
    }

    fn check_view_integrity_on_open(mut self, check: bool) -> Self {
        self.storage.views.check_integrity_on_open = check;
        self
    }

    #[cfg(feature = "compression")]
    fn default_compression(mut self, compression: Compression) -> Self {
        self.storage.default_compression = Some(compression);
        self
    }

    fn key_value_persistence(mut self, persistence: KeyValuePersistence) -> Self {
        self.storage.key_value_persistence = persistence;
        self
    }

    fn authenticated_permissions<P: Into<Permissions>>(
        mut self,
        authenticated_permissions: P,
    ) -> Self {
        self.storage.authenticated_permissions = authenticated_permissions.into();
        self
    }

    #[cfg(feature = "password-hashing")]
    fn argon(mut self, argon: bonsaidb_local::config::ArgonConfiguration) -> Self {
        self.storage.argon = argon;
        self
    }
}

/// Configuration for the BonsaiDb network protocol.
///
/// The BonsaiDb network protocol is built using QUIC, which uses UDP instead of
/// TCP.
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct BonsaiListenConfig {
    /// The socket port to listen for connections on.
    ///
    /// By default, this is `[::]:5645`.
    pub address: SocketAddr,

    /// If this is set to true, the `SO_REUSEADDR` flag will be set on the
    /// listening socket.
    ///
    /// This informs the operating system that it should allow reusing the exact
    /// same address/port combination in the future, which enables restarting a
    /// BonsaiDb network protocol listener without restarting the process
    /// itself. In general, this is not needed for users in regular deployments,
    /// and is more useful for specific kinds of testing.
    pub reuse_address: bool,
}

impl Default for BonsaiListenConfig {
    fn default() -> Self {
        Self {
            address: SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, 5645, 0, 0)),
            reuse_address: false,
        }
    }
}

impl BonsaiListenConfig {
    /// Sets the port for the socket address, and returns the updated config.
    #[must_use]
    pub fn port(mut self, port: u16) -> Self {
        self.address.set_port(port);
        self
    }

    /// Sets the [`reuse_address`](Self::reuse_address) flag.
    #[must_use]
    pub const fn reuse_address(mut self, reuse_address: bool) -> Self {
        self.reuse_address = reuse_address;
        self
    }
}

impl From<u16> for BonsaiListenConfig {
    fn from(value: u16) -> Self {
        Self::default().port(value)
    }
}