spatio 0.2.7

A high-performance, embedded spatio-temporal database for modern applications
Documentation
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
//! Configuration and database settings for Spatio
//!
//! This module provides configuration types and re-exports spatial types
//! from the `spatio-types` crate for convenience.
use bytes::Bytes;
use serde::de::Error;
use std::time::{Duration, SystemTime};

pub use spatio_types::bbox::{
    BoundingBox2D, BoundingBox3D, TemporalBoundingBox2D, TemporalBoundingBox3D,
};
pub use spatio_types::point::{Point3d, TemporalPoint, TemporalPoint3D};
pub use spatio_types::polygon::{Polygon3D, PolygonDynamic, PolygonDynamic3D};

pub use spatio_types::config::{SyncMode, SyncPolicy};

/// Database configuration
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    #[serde(default = "Config::default_sync_policy")]
    pub sync_policy: SyncPolicy,

    #[serde(default)]
    pub default_ttl_seconds: Option<f64>,

    #[serde(default)]
    pub sync_mode: SyncMode,

    #[serde(default = "Config::default_sync_batch_size")]
    pub sync_batch_size: usize,

    #[cfg(feature = "time-index")]
    #[serde(default)]
    pub history_capacity: Option<usize>,

    /// Buffer capacity per object for recent history in ColdState
    #[serde(default = "Config::default_buffer_capacity")]
    pub buffer_capacity: usize,

    /// Persistence configuration
    #[serde(default)]
    pub persistence: PersistenceConfig,
}

/// Configuration for data persistence and durability
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(deny_unknown_fields)]
pub struct PersistenceConfig {
    /// Number of writes to buffer in memory before flushing to disk
    #[serde(default = "PersistenceConfig::default_buffer_size")]
    pub buffer_size: usize,
}

impl PersistenceConfig {
    const fn default_buffer_size() -> usize {
        512
    }
}

impl Default for PersistenceConfig {
    fn default() -> Self {
        Self {
            buffer_size: Self::default_buffer_size(),
        }
    }
}

impl Config {
    const fn default_sync_batch_size() -> usize {
        1
    }

    const fn default_sync_policy() -> SyncPolicy {
        SyncPolicy::EverySecond
    }

    pub fn with_default_ttl(mut self, ttl: Duration) -> Self {
        let ttl_secs = ttl.as_secs();

        if ttl_secs > 365 * 24 * 3600 {
            log::warn!(
                "TTL of {} days is very large. This may indicate a misconfiguration.",
                ttl_secs / (24 * 3600)
            );
        } else if ttl_secs < 60 {
            log::warn!(
                "TTL of {} seconds is very short. Consider if this is intentional.",
                ttl_secs
            );
        }

        self.default_ttl_seconds = Some(ttl.as_secs_f64());
        self
    }

    pub fn with_sync_policy(mut self, policy: SyncPolicy) -> Self {
        self.sync_policy = policy;
        self
    }

    pub fn with_sync_mode(mut self, mode: SyncMode) -> Self {
        self.sync_mode = mode;
        self
    }

    pub fn with_sync_batch_size(mut self, batch_size: usize) -> Self {
        assert!(batch_size > 0, "Sync batch size must be greater than zero");
        self.sync_batch_size = batch_size;
        self
    }

    #[cfg(feature = "time-index")]
    pub fn with_history_capacity(mut self, capacity: usize) -> Self {
        assert!(capacity > 0, "History capacity must be greater than zero");

        if capacity > 100_000 {
            log::warn!(
                "History capacity of {} is very large and may consume significant memory. \
                Each entry stores key + value + timestamp.",
                capacity
            );
        }

        self.history_capacity = Some(capacity);
        self
    }

    const fn default_buffer_capacity() -> usize {
        100
    }

    pub fn with_buffer_capacity(mut self, capacity: usize) -> Self {
        assert!(capacity > 0, "Buffer capacity must be greater than zero");
        self.buffer_capacity = capacity;
        self
    }

    pub fn with_persistence(mut self, config: PersistenceConfig) -> Self {
        self.persistence = config;
        self
    }

    pub fn default_ttl(&self) -> Option<Duration> {
        self.default_ttl_seconds.and_then(|ttl| {
            if ttl.is_finite() && ttl > 0.0 && ttl <= u64::MAX as f64 {
                Some(Duration::from_secs_f64(ttl))
            } else {
                None
            }
        })
    }

    pub fn validate(&self) -> Result<(), String> {
        if let Some(ttl) = self.default_ttl_seconds {
            if !ttl.is_finite() {
                return Err("Default TTL must be finite (not NaN or infinity)".to_string());
            }
            if ttl <= 0.0 {
                return Err("Default TTL must be positive".to_string());
            }
            if ttl > u64::MAX as f64 {
                return Err("Default TTL is too large".to_string());
            }
        }

        #[cfg(feature = "time-index")]
        if let Some(capacity) = self.history_capacity
            && capacity == 0
        {
            return Err("History capacity must be greater than zero".to_string());
        }

        if self.sync_batch_size == 0 {
            return Err("Sync batch size must be greater than zero".to_string());
        }

        Ok(())
    }

    pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
        let config: Config = serde_json::from_str(json)?;
        if let Err(e) = config.validate() {
            return Err(Error::custom(e));
        }
        Ok(config)
    }

    pub fn to_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }

    #[cfg(feature = "toml")]
    pub fn from_toml(toml_str: &str) -> Result<Self, toml::de::Error> {
        let config: Config = toml::from_str(toml_str)?;
        if let Err(e) = config.validate() {
            return Err(toml::de::Error::custom(e));
        }
        Ok(config)
    }

    #[cfg(feature = "toml")]
    pub fn to_toml(&self) -> Result<String, toml::ser::Error> {
        toml::to_string_pretty(self)
    }
}

impl Default for Config {
    fn default() -> Self {
        Self {
            sync_policy: SyncPolicy::default(),
            default_ttl_seconds: None,
            sync_mode: SyncMode::default(),
            sync_batch_size: Self::default_sync_batch_size(),
            #[cfg(feature = "time-index")]
            history_capacity: None,

            buffer_capacity: Self::default_buffer_capacity(),
            persistence: PersistenceConfig::default(),
        }
    }
}

pub use spatio_types::config::SetOptions;

/// Internal representation of a database item.
///
/// Note: Items with expired `expires_at` are not automatically deleted.
/// They are filtered out during reads and can be removed with `cleanup_expired()`.
#[derive(Debug, Clone)]
pub struct DbItem {
    /// The value bytes
    pub value: Bytes,
    pub created_at: SystemTime,
    /// Expiration time (if any). Item is considered expired when SystemTime::now() >= expires_at.
    pub expires_at: Option<SystemTime>,
}

/// Operation types captured in history tracking.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HistoryEventKind {
    Set,
    Delete,
}

/// Historical record for key mutations.
#[derive(Debug, Clone)]
pub struct HistoryEntry {
    pub timestamp: SystemTime,
    pub kind: HistoryEventKind,
    pub value: Option<Bytes>,
    pub expires_at: Option<SystemTime>,
}

impl DbItem {
    /// Create a new item without expiration
    pub fn new(value: impl Into<Bytes>) -> Self {
        Self {
            value: value.into(),
            created_at: SystemTime::now(),
            expires_at: None,
        }
    }

    /// Create an item with absolute expiration
    pub fn with_expiration(value: impl Into<Bytes>, expires_at: SystemTime) -> Self {
        Self {
            value: value.into(),
            created_at: SystemTime::now(),
            expires_at: Some(expires_at),
        }
    }

    /// Create an item with TTL
    pub fn with_ttl(value: impl Into<Bytes>, ttl: Duration) -> Self {
        let expires_at = SystemTime::now() + ttl;
        Self::with_expiration(value, expires_at)
    }

    /// Create from SetOptions
    pub fn from_options(value: impl Into<Bytes>, options: Option<&SetOptions>) -> Self {
        let value = value.into();

        match options {
            Some(opts) => {
                let expires_at = opts.effective_expires_at();
                Self {
                    value,
                    created_at: SystemTime::now(),
                    expires_at,
                }
            }
            None => Self::new(value),
        }
    }

    pub fn is_expired(&self) -> bool {
        self.is_expired_at(SystemTime::now())
    }

    /// Check if this item has expired at a specific time
    pub fn is_expired_at(&self, now: SystemTime) -> bool {
        match self.expires_at {
            Some(expires_at) => now >= expires_at,
            None => false,
        }
    }

    /// Get remaining TTL
    pub fn remaining_ttl(&self) -> Option<Duration> {
        self.remaining_ttl_at(SystemTime::now())
    }

    /// Get remaining TTL at a specific time
    pub fn remaining_ttl_at(&self, now: SystemTime) -> Option<Duration> {
        match self.expires_at {
            Some(expires_at) => {
                if now < expires_at {
                    expires_at.duration_since(now).ok()
                } else {
                    Some(Duration::ZERO)
                }
            }
            None => None,
        }
    }
}

pub use spatio_types::stats::DbStats;

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::Duration;

    #[test]
    fn test_config_default() {
        let config = Config::default();
        assert_eq!(config.sync_policy, SyncPolicy::EverySecond);
        assert_eq!(config.sync_mode, SyncMode::All);
        assert_eq!(config.sync_batch_size, 1);
        assert!(config.default_ttl_seconds.is_none());
        #[cfg(feature = "time-index")]
        assert!(config.history_capacity.is_none());
    }

    #[test]
    fn test_config_serialization() {
        let config = Config::default()
            .with_default_ttl(Duration::from_secs(3600))
            .with_sync_policy(SyncPolicy::Always)
            .with_sync_mode(SyncMode::Data)
            .with_sync_batch_size(8);

        let json = config.to_json().unwrap();
        let deserialized: Config = Config::from_json(&json).unwrap();

        assert_eq!(deserialized.sync_policy, SyncPolicy::Always);
        assert_eq!(deserialized.sync_mode, SyncMode::Data);
        assert_eq!(deserialized.sync_batch_size, 8);
        assert_eq!(
            deserialized.default_ttl().unwrap(),
            Duration::from_secs(3600)
        );
    }

    #[cfg(feature = "time-index")]
    #[test]
    fn test_config_history_capacity() {
        let config = Config::default().with_history_capacity(5);
        assert_eq!(config.history_capacity, Some(5));
    }

    #[test]
    fn test_set_options() {
        let ttl_opts = SetOptions::with_ttl(Duration::from_secs(60));
        assert!(ttl_opts.ttl.is_some());
        assert!(ttl_opts.expires_at.is_none());

        let exp_opts = SetOptions::with_expiration(SystemTime::now());
        assert!(exp_opts.ttl.is_none());
        assert!(exp_opts.expires_at.is_some());
    }

    #[test]
    fn test_db_item_expiration() {
        let item = DbItem::new("test");
        assert!(!item.is_expired());

        let past = SystemTime::now() - Duration::from_secs(60);
        let expired_item = DbItem::with_expiration("test", past);
        assert!(expired_item.is_expired());

        let future = SystemTime::now() + Duration::from_secs(60);
        let future_item = DbItem::with_expiration("test", future);
        assert!(!future_item.is_expired());
    }

    #[test]
    fn test_db_item_ttl() {
        let item = DbItem::with_ttl("test", Duration::from_secs(60));
        let remaining = item.remaining_ttl().unwrap();

        // Should be close to 60 seconds (allowing for small timing differences)
        assert!(remaining.as_secs() >= 59 && remaining.as_secs() <= 60);
    }

    #[test]
    fn test_db_item_from_options() {
        let opts = SetOptions::with_ttl(Duration::from_secs(300));
        let item = DbItem::from_options("test", Some(&opts));

        assert!(item.expires_at.is_some());
        assert!(!item.is_expired());
    }

    #[test]
    fn test_db_stats() {
        let mut stats = DbStats::new();
        assert_eq!(stats.operations_count, 0);

        stats.record_operation();
        assert_eq!(stats.operations_count, 1);

        stats.record_expired(5);
        assert_eq!(stats.expired_count, 5);
    }

    #[test]
    fn test_config_validation() {
        let config = Config::default();
        assert!(config.validate().is_ok());

        let config = Config {
            default_ttl_seconds: Some(-1.0),
            ..Default::default()
        };
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_config_ttl_validation() {
        let mut config = Config::default();
        assert!(config.validate().is_ok());

        // Valid TTL
        config = Config {
            default_ttl_seconds: Some(60.0),
            ..Default::default()
        };
        assert!(config.validate().is_ok());

        // Negative TTL
        config.default_ttl_seconds = Some(-1.0);
        assert!(config.validate().is_err());

        // Zero TTL
        config.default_ttl_seconds = Some(0.0);
        assert!(config.validate().is_err());

        // NaN TTL
        config.default_ttl_seconds = Some(f64::NAN);
        assert!(config.validate().is_err());

        // Positive infinity TTL
        config.default_ttl_seconds = Some(f64::INFINITY);
        assert!(config.validate().is_err());

        // Negative infinity TTL
        config.default_ttl_seconds = Some(f64::NEG_INFINITY);
        assert!(config.validate().is_err());

        // Too large TTL (use 1e20 which is definitely larger than u64::MAX as f64)
        config.default_ttl_seconds = Some(1e20);
        assert!(config.validate().is_err());
    }

    #[test]
    fn test_config_default_ttl_safe_conversion() {
        let mut config = Config {
            default_ttl_seconds: Some(60.0),
            ..Default::default()
        };

        // Valid TTL should convert successfully
        assert!(config.default_ttl().is_some());

        // NaN should return None (safe fallback)
        config.default_ttl_seconds = Some(f64::NAN);
        assert!(config.default_ttl().is_none());

        // Infinity should return None (safe fallback)
        config.default_ttl_seconds = Some(f64::INFINITY);
        assert!(config.default_ttl().is_none());

        // Negative values should return None (safe fallback)
        config.default_ttl_seconds = Some(-1.0);
        assert!(config.default_ttl().is_none());

        // Too large values should return None (safe fallback)
        config.default_ttl_seconds = Some(1e20);
        assert!(config.default_ttl().is_none());

        // Zero should return None (safe fallback)
        config.default_ttl_seconds = Some(0.0);
        assert!(config.default_ttl().is_none());
    }
}