claviron-cache 0.2.7

Named cache stores, typed values, and fleet-shared caching for Claviron
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
use std::any::Any;
use std::borrow::Cow;
use std::num::NonZeroUsize;
use std::sync::Arc;
use std::time::Duration;

use async_trait::async_trait;
use bytes::Bytes;
use claviron_orbit::cache::{
    BackingEntry, BackingExpiry, CacheBacking, CacheMode, CacheRuntime,
    CacheService, DEFAULT_L1_CAPACITY,
};
use serde::Deserialize;

use crate::config::CacheStoreConfig;
use crate::drivers::memory::MemoryCacheStore;
use crate::error::{Error, Result};
use crate::{
    CacheDriver, CacheExpiry, CacheStore, CacheStoreResolver, CacheValue, Fill,
    FillToken, TaggedCacheStore,
};

/// Configured Orbit driver factory.
///
/// All stores created by this driver register with one `CacheService`, which
/// owns the physical rings and inbound lifecycle task in `claviron-orbit`.
pub struct OrbitCacheDriver {
    service: Arc<CacheService>,
}

impl OrbitCacheDriver {
    pub fn new() -> Self {
        Self { service: Arc::new(CacheService::new()) }
    }

    pub fn service(&self) -> Arc<CacheService> {
        self.service.clone()
    }

    pub fn has_stores(&self) -> bool {
        self.service.has_stores()
    }
}

impl Default for OrbitCacheDriver {
    fn default() -> Self {
        Self::new()
    }
}

struct CacheStoreBacking {
    store: Arc<dyn CacheStore>,
}

impl CacheStoreBacking {
    fn new(store: Arc<dyn CacheStore>) -> Self {
        Self { store }
    }
}

#[async_trait]
impl CacheBacking for CacheStoreBacking {
    fn store_name(&self) -> &str {
        self.store.store_name()
    }

    fn supports_ttl(&self) -> bool {
        self.store.supports_ttl()
    }

    async fn get(
        &self,
        key: &str,
    ) -> std::result::Result<Option<Bytes>, String> {
        self.store.get(key).await.map_err(|error| error.to_string())
    }

    async fn get_entry(
        &self,
        key: &str,
    ) -> std::result::Result<Option<BackingEntry>, String> {
        let entry = self
            .store
            .get_entry(key)
            .await
            .map_err(|error| error.to_string())?;
        Ok(entry.map(|entry| BackingEntry {
            bytes: entry.bytes,
            expiry: match entry.expiry {
                CacheExpiry::Unknown => BackingExpiry::Unknown,
                CacheExpiry::Never => BackingExpiry::Never,
                CacheExpiry::At(at) => unix_ms(at)
                    .map_or(BackingExpiry::Unknown, BackingExpiry::AtUnixMs),
            },
        }))
    }

    async fn put(
        &self,
        key: &str,
        value: &[u8],
        ttl: Option<Duration>,
    ) -> std::result::Result<(), String> {
        self.store
            .put(key, Cow::Borrowed(value), ttl)
            .await
            .map_err(|error| error.to_string())
    }

    async fn forget(
        &self,
        key: &str,
    ) -> std::result::Result<(), String> {
        self.store.forget(key).await.map_err(|error| error.to_string())
    }

    async fn clear(&self) -> std::result::Result<(), String> {
        self.store.clear().await.map_err(|error| error.to_string())
    }
}

/// Driver-neutral facade adapter for one logical Orbit cache store.
///
/// Named-store configuration and concrete L2 adaptation live here. The
/// physical connection, this store's L1/L2 ordering, resynchronization, and
/// notification mechanics live in `claviron-orbit`.
#[derive(Clone)]
pub struct OrbitCacheStore {
    store_name: String,
    l2_name: Option<String>,
    cache: CacheRuntime,
}

impl OrbitCacheStore {
    pub fn new(
        store_name: impl Into<String>,
        service: Arc<CacheService>,
        l1_capacity: usize,
        l2_name: Option<String>,
    ) -> Result<Self> {
        Self::with_config(
            store_name,
            service,
            OrbitCacheStoreConfig {
                mode: OrbitCacheMode::Replicated,
                l1_capacity: Some(l1_capacity),
                l2: l2_name,
            },
        )
    }

    fn with_config(
        store_name: impl Into<String>,
        service: Arc<CacheService>,
        config: OrbitCacheStoreConfig,
    ) -> Result<Self> {
        let store_name = store_name.into();
        let mode = match config.mode {
            OrbitCacheMode::Replicated => {
                let capacity =
                    config.l1_capacity.unwrap_or(DEFAULT_L1_CAPACITY);
                let l1_capacity =
                    NonZeroUsize::new(capacity).ok_or_else(|| {
                        Error::Rejected(
                            "orbit cache l1_capacity must be greater than zero"
                                .to_string(),
                        )
                    })?;
                CacheMode::Replicated { l1_capacity }
            }
            OrbitCacheMode::Shm => {
                if config.l1_capacity.is_some() {
                    return Err(Error::Rejected(
                        "orbit cache mode shm does not accept l1_capacity"
                            .to_string(),
                    ));
                }
                CacheMode::Shm
            }
        };
        let l2_name = config.l2;
        let cache = service
            .open_store_with_mode(store_name.clone(), mode)
            .map_err(Error::from)?;
        if l2_name.is_none() && cache.has_backing() {
            return Err(Error::Rejected(format!(
                "Orbit cache store '{store_name}' already has an L2; removing it requires restart"
            )));
        }
        Ok(Self { store_name, l2_name, cache })
    }

    pub fn l2_name(&self) -> Option<&str> {
        self.l2_name.as_deref()
    }

    pub fn cache(&self) -> &CacheRuntime {
        &self.cache
    }

    pub(crate) fn attach_l2(
        &self,
        store: Arc<dyn CacheStore>,
    ) -> Result<()> {
        if store.store_name() == self.store_name
            || store.driver_name() == "orbit"
        {
            return Err(Error::Rejected(format!(
                "orbit cache store '{}' cannot use another Orbit store as L2",
                self.store_name
            )));
        }
        if store.as_any().is::<MemoryCacheStore>() {
            return Err(Error::Rejected(format!(
                "orbit cache store '{}' requires a backing shared by its workers",
                self.store_name
            )));
        }
        self.cache
            .attach_backing(Arc::new(CacheStoreBacking::new(store)))
            .map_err(Error::from)
    }

    pub fn get_sync(
        &self,
        key: &str,
    ) -> Result<Option<Bytes>> {
        self.cache.get_sync(key).map_err(Error::from)
    }

    pub fn put_sync(
        &self,
        key: &str,
        value: &[u8],
        ttl: Option<Duration>,
    ) -> Result<()> {
        self.cache.put_sync(key, value, ttl).map_err(Error::from)
    }

    pub fn get_value_sync(
        &self,
        key: &str,
    ) -> Result<Option<CacheValue>> {
        self.get_sync(key)?
            .map(|bytes| CacheValue::decode(&bytes).map_err(Error::from))
            .transpose()
    }

    pub fn put_value_sync(
        &self,
        key: &str,
        value: CacheValue,
        ttl: Option<Duration>,
    ) -> Result<()> {
        self.put_sync(key, &value.encode().map_err(Error::from)?, ttl)
    }

    pub fn put_tagged_sync(
        &self,
        key: &str,
        value: &[u8],
        ttl: Option<Duration>,
        tags: &[&str],
    ) -> Result<()> {
        self.cache.put_tagged_sync(key, value, ttl, tags).map_err(Error::from)
    }

    pub fn invalidate_tags_sync(
        &self,
        tags: &[&str],
    ) -> Result<()> {
        self.cache.invalidate_tags_sync(tags).map_err(Error::from)
    }

    pub fn forget_sync(
        &self,
        key: &str,
    ) -> Result<()> {
        self.cache.forget_sync(key).map_err(Error::from)
    }

    pub fn reset_sync(&self) -> Result<()> {
        self.cache.clear_sync().map_err(Error::from)
    }
}

#[async_trait]
impl CacheStore for OrbitCacheStore {
    fn store_name(&self) -> &str {
        &self.store_name
    }

    fn driver_name(&self) -> &str {
        "orbit"
    }

    fn as_any(&self) -> &dyn Any {
        self
    }

    fn supports_ttl(&self) -> bool {
        self.cache.supports_ttl()
    }

    async fn get(
        &self,
        key: &str,
    ) -> Result<Option<Bytes>> {
        self.cache.get(key).await.map_err(Error::from)
    }

    async fn put(
        &self,
        key: &str,
        value: Cow<'_, [u8]>,
        ttl: Option<Duration>,
    ) -> Result<()> {
        self.cache.put(key, &value, ttl).await.map_err(Error::from)
    }

    async fn forget(
        &self,
        key: &str,
    ) -> Result<()> {
        self.cache.forget(key).await.map_err(Error::from)
    }

    async fn clear(&self) -> Result<()> {
        self.cache.clear().await.map_err(Error::from)
    }

    /// Both modes keep tags. A store configured with `l2` does not: its
    /// backing store would return a value after its tag was invalidated.
    fn tagged(&self) -> Option<&dyn TaggedCacheStore> {
        (self.l2_name.is_none() && self.cache.supports_tags())
            .then_some(self as &dyn TaggedCacheStore)
    }
}

#[async_trait]
impl TaggedCacheStore for OrbitCacheStore {
    async fn put_tagged(
        &self,
        key: &str,
        value: Cow<'_, [u8]>,
        ttl: Option<Duration>,
        tags: &[&str],
    ) -> Result<()> {
        self.cache.put_tagged(key, &value, ttl, tags).await.map_err(Error::from)
    }

    async fn fill_token(&self) -> Result<FillToken> {
        let token = self.cache.fill_token().map_err(Error::from)?;
        Ok(FillToken::new(token.source(), token.clock()))
    }

    async fn fill_tagged(
        &self,
        token: FillToken,
        key: &str,
        value: Cow<'_, [u8]>,
        ttl: Option<Duration>,
        tags: &[&str],
    ) -> Result<Fill> {
        use claviron_orbit::cache::Fill as Orbit;
        let token = claviron_orbit::cache::FillToken::from_parts(
            token.source(),
            token.clock(),
        );
        let fill = self
            .cache
            .fill_tagged(token, key, &value, ttl, tags)
            .map_err(Error::from)?;
        Ok(match fill {
            Orbit::Kept => Fill::Kept,
            Orbit::Invalidated => Fill::Invalidated,
            Orbit::Superseded => Fill::Superseded,
            Orbit::Skipped => Fill::Skipped,
        })
    }

    async fn invalidate_tags(
        &self,
        tags: &[&str],
    ) -> Result<()> {
        self.cache.invalidate_tags(tags).await.map_err(Error::from)
    }
}

impl CacheDriver for OrbitCacheDriver {
    fn driver_name(&self) -> &'static str {
        "orbit"
    }

    fn create_store(
        self: Arc<Self>,
        store_name: &str,
        store: &CacheStoreConfig,
    ) -> Result<Arc<dyn CacheStore>> {
        let config: OrbitCacheStoreConfig = store.deserialize_options()?;
        Ok(Arc::new(OrbitCacheStore::with_config(
            store_name,
            self.service.clone(),
            config,
        )?))
    }

    fn create_reload_store(
        self: Arc<Self>,
        store_name: &str,
        store: &CacheStoreConfig,
    ) -> Result<Arc<dyn CacheStore>> {
        if !self.service.is_booted() {
            return Err(Error::Rejected(format!(
                "Orbit cache store '{store_name}' cannot be enabled because OrbitCacheService was not active at boot; restart is required"
            )));
        }
        self.create_store(store_name, store)
    }

    fn finish_store(
        &self,
        store: &Arc<dyn CacheStore>,
        stores: &dyn CacheStoreResolver,
    ) -> Result<()> {
        let Some(orbit) = store.as_any().downcast_ref::<OrbitCacheStore>()
        else {
            return Err(Error::Rejected(format!(
                "orbit driver built incompatible cache store '{}'",
                store.store_name()
            )));
        };
        let Some(l2_name) = orbit.l2_name() else {
            return Ok(());
        };
        let l2 = stores.store(l2_name).map_err(|_| {
            Error::Missing(format!(
                "orbit cache store '{}' references unknown L2 store '{l2_name}'",
                orbit.store_name()
            ))
        })?;
        orbit.attach_l2(l2)
    }
}

#[derive(Clone, Copy, Debug, Default, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum OrbitCacheMode {
    #[default]
    Replicated,
    Shm,
}

#[derive(Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct OrbitCacheStoreConfig {
    #[serde(default)]
    pub mode: OrbitCacheMode,
    pub l1_capacity: Option<usize>,
    #[serde(default)]
    pub l2: Option<String>,
}

/// An `Instant` deadline on the wall clock Orbit's expiry uses. `None` when
/// the clock cannot express it, which leaves the expiry unknown.
fn unix_ms(at: std::time::Instant) -> Option<u64> {
    let remaining = at.saturating_duration_since(std::time::Instant::now());
    let deadline = std::time::SystemTime::now().checked_add(remaining)?;
    let since_epoch = deadline.duration_since(std::time::UNIX_EPOCH).ok()?;
    u64::try_from(since_epoch.as_millis()).ok()
}

#[cfg(test)]
#[path = "../../tests/drivers/orbit.rs"]
mod tests;