wb_cache/
entry.rs

1use crate::cache::Cache;
2use crate::cache::ValueState;
3use crate::traits::DataController;
4use fieldx_plus::child_build;
5use fieldx_plus::fx_plus;
6use moka::Entry as MokaEntry;
7use std::fmt::Debug;
8use std::sync::Arc;
9use tracing::instrument;
10
11/// This is a snapshot of a single entry in the cache. Note that as a snapshot, it doesn't refer to the value in the
12/// cache, but holds a copy of it.
13#[fx_plus(child(Cache<DC>, rc_strong), sync, default(off))]
14pub struct Entry<DC>
15where
16    DC: DataController,
17{
18    key:   DC::Key,
19    value: DC::Value,
20}
21
22impl<DC> Entry<DC>
23where
24    DC: DataController,
25{
26    pub(crate) fn new(parent: &Cache<DC>, key: DC::Key, value: DC::Value) -> Self {
27        child_build!(
28            parent,
29            Entry<DC> {
30                key:   key,
31                value: value,
32            }
33        )
34        .unwrap()
35    }
36
37    // Only valid for primaries
38    #[instrument(level = "trace")]
39    pub(crate) fn from_primary_entry(
40        parent: &Cache<DC>,
41        entry: MokaEntry<DC::Key, ValueState<DC::Key, DC::Value>>,
42    ) -> Self {
43        child_build!(
44            parent,
45            Entry<DC> {
46                key: entry.key().clone(),
47                value: entry.into_value().into_value(),
48            }
49        )
50        .unwrap()
51    }
52
53    /// The snapshot value.
54    #[instrument(level = "trace")]
55    pub async fn value(&self) -> Result<&DC::Value, Arc<DC::Error>> {
56        self.parent().on_access(&self.key, Arc::new(self.value.clone())).await?;
57        Ok(&self.value)
58    }
59
60    /// The key of the entry.
61    pub fn key(&self) -> &DC::Key {
62        &self.key
63    }
64
65    /// Consumes the entry and returns its stored value.
66    pub fn into_value(self) -> DC::Value {
67        self.value
68    }
69}
70
71impl<DC> Debug for Entry<DC>
72where
73    DC: DataController,
74{
75    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
76        f.debug_struct("Entry")
77            .field("key", &self.key)
78            .field("value", &self.value)
79            .finish()
80    }
81}