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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! HTTP server configuration.
/// CORS (Cross-Origin Resource Sharing) configuration.
#[derive(Debug, Clone)]
pub struct CorsConfig {
/// Allowed origins. Empty means allow any origin (development mode only).
allowed_origins: Vec<String>,
/// Allowed HTTP methods.
allowed_methods: Vec<String>,
/// Allowed HTTP headers.
allowed_headers: Vec<String>,
/// Max age for preflight cache in seconds.
max_age: u32,
}
impl CorsConfig {
/// Create a permissive CORS config for development.
///
/// # Security Warning
///
/// This allows any origin and should NOT be used in production.
/// Use [`CorsConfig::restrictive`] or configure specific origins instead.
pub fn permissive() -> Self {
Self {
allowed_origins: vec![],
allowed_methods: vec![
"GET".to_string(),
"POST".to_string(),
"PUT".to_string(),
"DELETE".to_string(),
"OPTIONS".to_string(),
],
allowed_headers: vec!["Content-Type".to_string(), "Authorization".to_string()],
max_age: 3600,
}
}
/// Create a restrictive CORS config with no allowed origins.
///
/// You must explicitly add allowed origins using [`CorsConfig::allow_origin`].
pub fn restrictive() -> Self {
Self {
allowed_origins: vec!["http://localhost:3000".to_string()],
allowed_methods: vec!["GET".to_string(), "POST".to_string(), "OPTIONS".to_string()],
allowed_headers: vec!["Content-Type".to_string()],
max_age: 3600,
}
}
/// Add an allowed origin.
pub fn allow_origin(mut self, origin: impl Into<String>) -> Self {
self.allowed_origins.push(origin.into());
self
}
/// Set allowed HTTP methods.
pub fn allowed_methods(mut self, methods: Vec<String>) -> Self {
self.allowed_methods = methods;
self
}
/// Set allowed HTTP headers.
pub fn allowed_headers(mut self, headers: Vec<String>) -> Self {
self.allowed_headers = headers;
self
}
/// Set max age for preflight cache.
pub fn max_age(mut self, seconds: u32) -> Self {
self.max_age = seconds;
self
}
/// Check if any origin is allowed (permissive mode).
pub fn is_permissive(&self) -> bool {
self.allowed_origins.is_empty()
}
/// Get allowed origins.
pub fn allowed_origins(&self) -> &[String] {
&self.allowed_origins
}
/// Get allowed methods.
pub fn get_allowed_methods(&self) -> &[String] {
&self.allowed_methods
}
/// Get allowed headers.
pub fn get_allowed_headers(&self) -> &[String] {
&self.allowed_headers
}
/// Get max age in seconds.
pub fn get_max_age(&self) -> u32 {
self.max_age
}
}
impl Default for CorsConfig {
fn default() -> Self {
Self::restrictive()
}
}
/// Rate limiting configuration.
#[derive(Debug, Clone)]
pub struct RateLimitConfig {
/// Number of requests allowed per second per IP.
requests_per_second: u32,
/// Maximum burst size (concurrent requests) per IP.
burst_size: u32,
}
impl RateLimitConfig {
/// Create a new rate limit configuration.
pub fn new(requests_per_second: u32, burst_size: u32) -> Self {
Self {
requests_per_second,
burst_size,
}
}
/// Get requests per second.
pub fn requests_per_second(&self) -> u32 {
self.requests_per_second
}
/// Get burst size.
pub fn burst_size(&self) -> u32 {
self.burst_size
}
/// Validate the configuration.
pub fn validate(&self) -> Result<(), String> {
if self.requests_per_second == 0 {
return Err("requests_per_second must be > 0".to_string());
}
if self.burst_size == 0 {
return Err("burst_size must be > 0".to_string());
}
Ok(())
}
}
impl Default for RateLimitConfig {
fn default() -> Self {
Self {
requests_per_second: 10,
burst_size: 20,
}
}
}
/// Configuration for the HTTP server.
#[derive(Debug, Clone)]
pub struct ServerConfig {
port: u16,
host: String,
cors: CorsConfig,
rate_limit: RateLimitConfig,
/// When `Some`, WAL + index persistence are written under this directory
/// so restarts preserve state. When `None`, the server runs on an in-memory
/// `AletheiaDB::new()` (useful for tests and ephemeral demos).
data_dir: Option<std::path::PathBuf>,
}
impl ServerConfig {
/// Create a new server config with the specified port.
///
/// Uses default host of "0.0.0.0" (all interfaces), restrictive CORS,
/// default rate limiting (10 req/s, 20 burst), and **no** data directory
/// (database is in-memory).
pub fn new(port: u16) -> Self {
Self {
port,
host: "0.0.0.0".to_string(),
cors: CorsConfig::default(),
rate_limit: RateLimitConfig::default(),
data_dir: None,
}
}
/// Get the configured port.
pub fn port(&self) -> u16 {
self.port
}
/// Get the configured host.
pub fn host(&self) -> &str {
&self.host
}
/// Get the CORS configuration.
pub fn cors(&self) -> &CorsConfig {
&self.cors
}
/// Get the rate limit configuration.
pub fn rate_limit(&self) -> &RateLimitConfig {
&self.rate_limit
}
/// Get the configured data directory, if any.
///
/// When `Some(path)`, the server will create `{path}/wal` and
/// `{path}/indexes` for durable storage. When `None`, the server runs
/// on an in-memory database.
pub fn data_dir(&self) -> Option<&std::path::Path> {
self.data_dir.as_deref()
}
/// Materialize the [`AletheiaDBConfig`] this server config implies.
///
/// Returns `None` when no [`data_dir`](Self::data_dir) is set — that
/// signals in-memory mode, and the caller should construct the DB via
/// [`AletheiaDB::new`](crate::AletheiaDB::new) instead.
///
/// Returns `Some(cfg)` with WAL (GroupCommit durability, 10ms /
/// 200-op batching) under `{data_dir}/wal` and index persistence
/// under `{data_dir}/indexes` when a data directory is configured.
/// Both subdirectories are created on startup by
/// [`AletheiaDB::with_unified_config`](crate::AletheiaDB::with_unified_config).
///
/// The durability parameters are intentionally not exposed as
/// per-server-binary env vars: library consumers that need to tune
/// them build their own [`AletheiaDBConfig`] directly via
/// [`AletheiaDBConfig::builder`](crate::AletheiaDBConfig::builder).
/// The server binary uses conservative production-safe defaults.
#[must_use]
pub fn to_unified_config(&self) -> Option<crate::AletheiaDBConfig> {
use crate::config::{AletheiaDBConfig, WalConfigBuilder};
use crate::storage::index_persistence::PersistenceConfig;
use crate::storage::wal::DurabilityMode;
let data_dir = self.data_dir.as_deref()?;
Some(
AletheiaDBConfig::builder()
.wal(
WalConfigBuilder::new()
.wal_dir(data_dir.join("wal"))
.durability_mode(DurabilityMode::GroupCommit {
max_delay_ms: 10,
max_batch_size: 200,
})
.build(),
)
.persistence(PersistenceConfig {
enabled: true,
data_dir: data_dir.join("indexes"),
load_on_startup: true,
..Default::default()
})
.build(),
)
}
/// Get the bind address as "host:port".
pub fn bind_address(&self) -> String {
format!("{}:{}", self.host, self.port)
}
/// Create a builder for more complex configuration.
pub fn builder() -> ServerConfigBuilder {
ServerConfigBuilder::default()
}
}
impl Default for ServerConfig {
fn default() -> Self {
Self {
port: 1963,
host: "0.0.0.0".to_string(),
cors: CorsConfig::default(),
rate_limit: RateLimitConfig::default(),
data_dir: None,
}
}
}
/// Builder for [`ServerConfig`].
#[derive(Debug, Clone, Default)]
pub struct ServerConfigBuilder {
port: Option<u16>,
host: Option<String>,
cors: Option<CorsConfig>,
rate_limit: Option<RateLimitConfig>,
data_dir: Option<std::path::PathBuf>,
}
impl ServerConfigBuilder {
/// Set the port to bind to.
pub fn port(mut self, port: u16) -> Self {
self.port = Some(port);
self
}
/// Set the host to bind to.
///
/// # Valid Values
///
/// - IPv4 addresses: "0.0.0.0", "127.0.0.1", etc.
/// - IPv6 addresses: "::", "::1", etc.
/// - Hostnames: "localhost", etc.
///
/// The host is validated at bind time by the underlying server.
pub fn host(mut self, host: impl Into<String>) -> Self {
self.host = Some(host.into());
self
}
/// Set the CORS configuration.
///
/// # Example
///
/// ```ignore
/// use aletheiadb::http::{ServerConfig, CorsConfig};
///
/// let config = ServerConfig::builder()
/// .port(1963)
/// .cors(CorsConfig::restrictive().allow_origin("https://myapp.com"))
/// .build();
/// ```
pub fn cors(mut self, cors: CorsConfig) -> Self {
self.cors = Some(cors);
self
}
/// Set the rate limit configuration.
pub fn rate_limit(mut self, rate_limit: RateLimitConfig) -> Self {
self.rate_limit = Some(rate_limit);
self
}
/// Set a data directory for durable WAL + index persistence.
///
/// The server will create `{path}/wal` and `{path}/indexes` on startup.
/// If `None` (the default), the database is in-memory and everything is
/// lost on shutdown.
pub fn data_dir(mut self, path: impl Into<std::path::PathBuf>) -> Self {
self.data_dir = Some(path.into());
self
}
/// Build the server configuration.
pub fn build(self) -> ServerConfig {
ServerConfig {
port: self.port.unwrap_or(1963),
host: self.host.unwrap_or_else(|| "0.0.0.0".to_string()),
cors: self.cors.unwrap_or_default(),
rate_limit: self.rate_limit.unwrap_or_default(),
data_dir: self.data_dir,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default_config() {
let config = ServerConfig::default();
assert_eq!(config.port(), 1963);
assert_eq!(config.host(), "0.0.0.0");
assert!(!config.cors().is_permissive());
}
#[test]
fn test_new_with_port() {
let config = ServerConfig::new(3000);
assert_eq!(config.port(), 3000);
assert_eq!(config.host(), "0.0.0.0");
}
#[test]
fn test_builder() {
let config = ServerConfig::builder().port(9000).host("127.0.0.1").build();
assert_eq!(config.port(), 9000);
assert_eq!(config.host(), "127.0.0.1");
}
#[test]
fn test_bind_address() {
let config = ServerConfig::builder().port(1963).host("localhost").build();
assert_eq!(config.bind_address(), "localhost:1963");
}
#[test]
fn test_cors_permissive() {
let cors = CorsConfig::permissive();
assert!(cors.is_permissive());
assert!(cors.allowed_origins().is_empty());
}
#[test]
fn test_cors_restrictive() {
let cors = CorsConfig::restrictive();
assert!(!cors.is_permissive());
assert!(!cors.allowed_origins().is_empty());
}
#[test]
fn test_cors_allow_origin() {
let cors = CorsConfig::restrictive().allow_origin("https://example.com");
assert!(
cors.allowed_origins()
.contains(&"https://example.com".to_string())
);
}
#[test]
fn test_builder_with_cors() {
let config = ServerConfig::builder()
.port(1963)
.cors(CorsConfig::permissive())
.build();
assert!(config.cors().is_permissive());
}
#[test]
fn test_default_rate_limit() {
let config = ServerConfig::default();
assert_eq!(config.rate_limit().requests_per_second(), 10);
assert_eq!(config.rate_limit().burst_size(), 20);
}
#[test]
fn test_custom_rate_limit() {
let rate_limit = RateLimitConfig::new(100, 200);
let config = ServerConfig::builder().rate_limit(rate_limit).build();
assert_eq!(config.rate_limit().requests_per_second(), 100);
assert_eq!(config.rate_limit().burst_size(), 200);
}
#[test]
fn test_rate_limit_validation() {
let valid = RateLimitConfig::new(10, 20);
assert!(valid.validate().is_ok());
let invalid_rps = RateLimitConfig::new(0, 20);
assert!(invalid_rps.validate().is_err());
let invalid_burst = RateLimitConfig::new(10, 0);
assert!(invalid_burst.validate().is_err());
}
}