storage-kit 0.0.1

Portable database and transactional state-store Kit.
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
use std::{
    ffi::OsStr,
    fmt,
    path::{Path, PathBuf},
    time::Duration,
};

use serde::{
    Deserialize, Deserializer, Serialize, Serializer, de,
    ser::{SerializeMap, SerializeStruct},
};

use crate::StateStoreError;

const DEFAULT_OPERATION_TIMEOUT_MS: u64 = 5_000;
const DEFAULT_CACHE_SIZE_BYTES: usize = 64 * 1024 * 1024;

/// Local Redb StateStore location.
///
/// Redb is an opt-in embedded StateStore backend. Memory locations
/// are process-local. File locations persist embedded control-plane state to a
/// caller-selected local path.
///
/// # Examples
///
/// ```rust
/// let memory = storage_kit::state::config::RedbStateStoreLocation::Memory;
/// let file = storage_kit::state::config::RedbStateStoreLocation::File(
///     std::env::temp_dir().join("storage-kit-state.redb"),
/// );
/// let _ = (memory, file);
/// ```
pub enum RedbStateStoreLocation {
    /// Uses a process-local Redb in-memory backend.
    Memory,
    /// Uses a caller-selected local Redb database file.
    File(PathBuf),
}

impl RedbStateStoreLocation {
    /// Returns true for an in-memory Redb location.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let location = storage_kit::state::config::RedbStateStoreLocation::Memory;
    /// if !location.is_memory() {
    ///     return Err(storage_kit::StateStoreError::InvalidRequest(
    ///         "expected memory location".to_owned(),
    ///     ));
    /// }
    /// # Ok::<(), storage_kit::StateStoreError>(())
    /// ```
    #[must_use]
    pub fn is_memory(&self) -> bool {
        match self {
            Self::Memory => true,
            Self::File(_) => false,
        }
    }

    pub(crate) fn validate(&self) -> Result<(), StateStoreError> {
        match self {
            Self::Memory => Ok(()),
            Self::File(path) => RedbStateStorePath::new(path).validate(),
        }
    }

    fn from_json_value(value: &serde_json::Value) -> Result<Self, String> {
        if value.as_str() == Some("Memory") {
            return Ok(Self::Memory);
        }
        let object = value.as_object().ok_or_else(|| {
            "RedbStateStoreLocation must be `Memory` or `{ File: ... }`".to_owned()
        })?;
        if object.len() != 1 {
            return Err(
                "RedbStateStoreLocation object must contain exactly one variant".to_owned(),
            );
        }
        let file = object
            .get("File")
            .ok_or_else(|| "RedbStateStoreLocation object must contain `File`".to_owned())?;
        let path = file
            .as_str()
            .ok_or_else(|| "RedbStateStoreLocation.File must be a string".to_owned())?;
        Ok(Self::File(PathBuf::from(path)))
    }
}

impl Clone for RedbStateStoreLocation {
    fn clone(&self) -> Self {
        match self {
            Self::Memory => Self::Memory,
            Self::File(path) => Self::File(path.clone()),
        }
    }
}

impl fmt::Debug for RedbStateStoreLocation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Memory => f.write_str("Memory"),
            Self::File(path) => f.debug_tuple("File").field(path).finish(),
        }
    }
}

impl PartialEq for RedbStateStoreLocation {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Self::Memory, Self::Memory) => true,
            (Self::File(left), Self::File(right)) => left == right,
            _ => false,
        }
    }
}

impl Eq for RedbStateStoreLocation {}

impl Serialize for RedbStateStoreLocation {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Memory => serializer.serialize_str("Memory"),
            Self::File(path) => {
                let value = path.to_str().ok_or_else(|| {
                    serde::ser::Error::custom(
                        "RedbStateStoreLocation.File must be valid UTF-8 to serialize as JSON",
                    )
                })?;
                let mut map = serializer.serialize_map(Some(1))?;
                map.serialize_entry("File", value)?;
                map.end()
            }
        }
    }
}

impl<'de> Deserialize<'de> for RedbStateStoreLocation {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = serde_json::Value::deserialize(deserializer)?;
        Self::from_json_value(&value).map_err(de::Error::custom)
    }
}

/// Redb embedded StateStore configuration.
///
/// This always-available config selects the Redb StateStore backend, which
/// requires the `redb` feature. Use
/// [`Self::memory`] for process-local embedded state and
/// [`Self::file`] for persisted embedded state.
///
/// # Examples
///
/// ```rust
/// let config = storage_kit::state::config::RedbStateStoreConfig::memory();
/// let state_config = storage_kit::state::config::StateStoreConfig::redb(config);
/// let _ = state_config;
/// ```
pub struct RedbStateStoreConfig {
    location: RedbStateStoreLocation,
    operation_timeout_ms: u64,
    cache_size_bytes: usize,
}

impl RedbStateStoreConfig {
    /// Builds an in-memory Redb StateStore config.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let config = storage_kit::state::config::RedbStateStoreConfig::memory();
    /// if !config.location().is_memory() {
    ///     return Err(storage_kit::StateStoreError::InvalidRequest(
    ///         "expected memory location".to_owned(),
    ///     ));
    /// }
    /// # Ok::<(), storage_kit::StateStoreError>(())
    /// ```
    #[must_use]
    pub fn memory() -> Self {
        Self {
            location: RedbStateStoreLocation::Memory,
            operation_timeout_ms: DEFAULT_OPERATION_TIMEOUT_MS,
            cache_size_bytes: DEFAULT_CACHE_SIZE_BYTES,
        }
    }

    /// Builds a file-backed Redb StateStore config.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let path = std::env::temp_dir().join("storage-kit-state.redb");
    /// let config = storage_kit::state::config::RedbStateStoreConfig::file(path);
    /// let _ = config;
    /// ```
    #[must_use]
    pub fn file(path: impl Into<PathBuf>) -> Self {
        Self {
            location: RedbStateStoreLocation::File(path.into()),
            operation_timeout_ms: DEFAULT_OPERATION_TIMEOUT_MS,
            cache_size_bytes: DEFAULT_CACHE_SIZE_BYTES,
        }
    }

    /// Replaces the operation timeout.
    ///
    /// # Errors
    ///
    /// Returns an invalid-config error when the timeout is zero or cannot be
    /// represented as milliseconds.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let config = storage_kit::state::config::RedbStateStoreConfig::memory()
    ///     .with_operation_timeout(std::time::Duration::from_secs(2))?;
    /// let _ = config;
    /// # Ok::<(), storage_kit::StateStoreError>(())
    /// ```
    pub fn with_operation_timeout(mut self, timeout: Duration) -> Result<Self, StateStoreError> {
        let millis = u64::try_from(timeout.as_millis()).map_err(|err| {
            StateStoreError::invalid_config({
                let mut message = String::from("Redb state store operation_timeout overflow: ");
                message.push_str(&err.to_string());
                message
            })
        })?;
        if millis == 0 {
            return Err(StateStoreError::invalid_config(
                "Redb state store operation_timeout must be greater than zero",
            ));
        }
        self.operation_timeout_ms = millis;
        Ok(self)
    }

    /// Replaces the Redb cache size in bytes.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let config = storage_kit::state::config::RedbStateStoreConfig::memory()
    ///     .with_cache_size_bytes(64 * 1024 * 1024);
    /// let _ = config;
    /// ```
    #[must_use]
    pub fn with_cache_size_bytes(mut self, bytes: usize) -> Self {
        self.cache_size_bytes = bytes;
        self
    }

    /// Returns the configured operation timeout.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let timeout = storage_kit::state::config::RedbStateStoreConfig::memory().operation_timeout();
    /// let _ = timeout;
    /// ```
    #[must_use]
    pub fn operation_timeout(&self) -> Duration {
        Duration::from_millis(self.operation_timeout_ms)
    }

    /// Returns the configured Redb cache size in bytes.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let bytes = storage_kit::state::config::RedbStateStoreConfig::memory().cache_size_bytes();
    /// let _ = bytes;
    /// ```
    #[must_use]
    pub fn cache_size_bytes(&self) -> usize {
        self.cache_size_bytes
    }

    /// Returns the configured Redb location.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let config = storage_kit::state::config::RedbStateStoreConfig::memory();
    /// let location = config.location();
    /// let _ = location;
    /// ```
    #[must_use]
    pub fn location(&self) -> &RedbStateStoreLocation {
        &self.location
    }

    /// Validates Redb location, timeout, and cache settings.
    ///
    /// # Errors
    ///
    /// Returns an invalid-config error when a numeric setting is zero or a
    /// file path is not valid for Redb construction.
    ///
    /// # Examples
    ///
    /// ```rust
    /// storage_kit::state::config::RedbStateStoreConfig::memory().validate()?;
    /// # Ok::<(), storage_kit::StateStoreError>(())
    /// ```
    pub fn validate(&self) -> Result<(), StateStoreError> {
        if self.operation_timeout_ms == 0 {
            return Err(StateStoreError::invalid_config(
                "Redb state store operation_timeout must be greater than zero",
            ));
        }
        if self.cache_size_bytes == 0 {
            return Err(StateStoreError::invalid_config(
                "Redb state store cache_size_bytes must be greater than zero",
            ));
        }
        self.location.validate()
    }

    #[cfg(feature = "redb")]
    pub(crate) fn operation_timeout_ms(&self) -> u64 {
        self.operation_timeout_ms
    }

    pub(crate) fn from_json_value(value: &serde_json::Value) -> Result<Self, String> {
        let object = value
            .as_object()
            .ok_or_else(|| "RedbStateStoreConfig must be an object".to_owned())?;
        let location = object
            .get("location")
            .ok_or_else(|| "RedbStateStoreConfig.location is required".to_owned())
            .and_then(RedbStateStoreLocation::from_json_value)?;
        let operation_timeout_ms = object
            .get("operation_timeout_ms")
            .ok_or_else(|| "RedbStateStoreConfig.operation_timeout_ms is required".to_owned())?
            .as_u64()
            .ok_or_else(|| "RedbStateStoreConfig.operation_timeout_ms must be a u64".to_owned())?;
        let cache_size_u64 = object
            .get("cache_size_bytes")
            .ok_or_else(|| "RedbStateStoreConfig.cache_size_bytes is required".to_owned())?
            .as_u64()
            .ok_or_else(|| "RedbStateStoreConfig.cache_size_bytes must be a u64".to_owned())?;
        let cache_size_bytes = usize::try_from(cache_size_u64).map_err(|err| {
            let mut message = String::from("RedbStateStoreConfig.cache_size_bytes overflow: ");
            message.push_str(&err.to_string());
            message
        })?;
        Ok(Self {
            location,
            operation_timeout_ms,
            cache_size_bytes,
        })
    }
}

impl Clone for RedbStateStoreConfig {
    fn clone(&self) -> Self {
        Self {
            location: self.location.clone(),
            operation_timeout_ms: self.operation_timeout_ms,
            cache_size_bytes: self.cache_size_bytes,
        }
    }
}

impl fmt::Debug for RedbStateStoreConfig {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RedbStateStoreConfig")
            .field("location", &self.location)
            .field("operation_timeout_ms", &self.operation_timeout_ms)
            .field("cache_size_bytes", &self.cache_size_bytes)
            .finish()
    }
}

impl PartialEq for RedbStateStoreConfig {
    fn eq(&self, other: &Self) -> bool {
        self.location == other.location
            && self.operation_timeout_ms == other.operation_timeout_ms
            && self.cache_size_bytes == other.cache_size_bytes
    }
}

impl Eq for RedbStateStoreConfig {}

impl Serialize for RedbStateStoreConfig {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        let mut state = serializer.serialize_struct("RedbStateStoreConfig", 3)?;
        state.serialize_field("location", &self.location)?;
        state.serialize_field("operation_timeout_ms", &self.operation_timeout_ms)?;
        state.serialize_field("cache_size_bytes", &self.cache_size_bytes)?;
        state.end()
    }
}

impl<'de> Deserialize<'de> for RedbStateStoreConfig {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let value = serde_json::Value::deserialize(deserializer)?;
        Self::from_json_value(&value).map_err(de::Error::custom)
    }
}

struct RedbStateStorePath<'a> {
    path: &'a Path,
}

impl<'a> RedbStateStorePath<'a> {
    fn new(path: &'a Path) -> Self {
        Self { path }
    }

    fn validate(&self) -> Result<(), StateStoreError> {
        if self.path.as_os_str().is_empty() {
            return Err(StateStoreError::invalid_config(
                "Redb state store file path must not be empty",
            ));
        }
        if self.contains_nul(self.path.as_os_str()) {
            return Err(StateStoreError::invalid_config(
                "Redb state store file path must not contain NUL",
            ));
        }
        Ok(())
    }

    fn contains_nul(&self, value: &OsStr) -> bool {
        value.as_encoded_bytes().contains(&0)
    }
}