Skip to main content

fedimint_client/
meta.rs

1use std::collections::BTreeMap;
2use std::pin::pin;
3use std::sync::Arc;
4
5use async_stream::stream;
6use fedimint_client_module::meta::{FetchKind, MetaSource, MetaValue, MetaValues};
7use fedimint_core::db::{Database, DatabaseTransaction, IDatabaseTransactionOpsCoreTyped};
8use fedimint_core::task::waiter::Waiter;
9use fedimint_core::util::FmtCompact as _;
10use fedimint_logging::LOG_CLIENT;
11use futures::StreamExt as _;
12use serde::de::DeserializeOwned;
13use tokio::sync::Notify;
14use tokio_stream::Stream;
15use tracing::warn;
16
17use crate::Client;
18use crate::db::{
19    MetaFieldKey, MetaFieldPrefix, MetaFieldValue, MetaServiceInfo, MetaServiceInfoKey,
20};
21
22/// Service for managing the caching of meta fields.
23// a fancy DST to save one allocation.
24pub struct MetaService<S: ?Sized = dyn MetaSource> {
25    initial_fetch_waiter: Waiter,
26    meta_update_notify: Notify,
27    source: S,
28}
29
30pub type MetaEntries = BTreeMap<String, serde_json::Value>;
31
32impl<S: MetaSource + ?Sized> MetaService<S> {
33    pub fn new(source: S) -> Arc<MetaService>
34    where
35        S: Sized,
36    {
37        // implicit cast `Arc<MetaService<S>>` to `Arc<MetaService<dyn MetaSource>>`
38        Arc::new(MetaService {
39            initial_fetch_waiter: Waiter::new(),
40            meta_update_notify: Notify::new(),
41            source,
42        })
43    }
44
45    /// Get the value for the meta field.
46    ///
47    /// This may wait for significant time on first run.
48    pub async fn get_field<V: DeserializeOwned + 'static>(
49        &self,
50        db: &Database,
51        field: &str,
52    ) -> Option<MetaValue<V>> {
53        match self.get_cached_field(db, field).await {
54            Some(value) => {
55                // might be from in old cache.
56                // TODO: maybe old cache should have a ttl?
57                Some(value)
58            }
59            _ => {
60                // wait for initial value
61                self.initial_fetch_waiter.wait().await;
62                self.get_cached_field(db, field).await
63            }
64        }
65    }
66
67    /// Read a cached field without waiting for the initial metadata fetch.
68    ///
69    /// Returns `None` if the cache has not been initialized. Cached values may
70    /// be stale; the background task refreshes them independently.
71    pub async fn get_cached_field<V: DeserializeOwned + 'static>(
72        &self,
73        db: &Database,
74        field: &str,
75    ) -> Option<MetaValue<V>> {
76        let dbtx = &mut db.begin_transaction_nc().await;
77        let info = dbtx.get_value(&MetaServiceInfoKey).await?;
78        let value = dbtx
79            .get_value(&MetaFieldKey(fedimint_client_module::meta::MetaFieldKey(
80                field.to_string(),
81            )))
82            .await
83            .and_then(|value| {
84                serde_json::from_value(value.0.0)
85                    .inspect_err(|err| {
86                        warn!(target: LOG_CLIENT,
87                        %field,
88                        type = std::any::type_name::<V>(),
89                        err = %err.fmt_compact(),
90                        "Failed to deserialize meta value as the requested type")
91                    })
92                    .ok()
93            });
94
95        Some(MetaValue {
96            fetch_time: info.last_updated,
97            value,
98        })
99    }
100
101    /// Get all meta entries.
102    ///
103    /// This may wait for significant time on first run when there is no cached
104    /// data.
105    pub async fn entries(&self, db: &Database) -> Option<MetaEntries> {
106        if let Some(value) = self.entries_from_db(db).await {
107            // might be from in old cache.
108            // TODO: maybe old cache should have a ttl?
109            Some(value)
110        } else {
111            // wait for initial value
112            self.wait_initialization().await;
113            self.entries_from_db(db).await
114        }
115    }
116
117    async fn entries_from_db(&self, db: &Database) -> Option<MetaEntries> {
118        let dbtx = &mut db.begin_transaction_nc().await;
119        let info = dbtx.get_value(&MetaServiceInfoKey).await;
120        #[allow(clippy::question_mark)] // more readable
121        if info.is_none() {
122            return None;
123        }
124        let entries: MetaEntries = dbtx
125            .find_by_prefix(&MetaFieldPrefix)
126            .await
127            .map(|(k, v)| (k.0.0, v.0.0))
128            .collect()
129            .await;
130        Some(entries)
131    }
132
133    async fn current_revision(&self, dbtx: &mut DatabaseTransaction<'_>) -> Option<u64> {
134        dbtx.get_value(&MetaServiceInfoKey)
135            .await
136            .map(|x| x.revision)
137    }
138
139    /// Wait until Meta Service is initialized, after this `get_field` will not
140    /// block.
141    pub async fn wait_initialization(&self) {
142        self.initial_fetch_waiter.wait().await;
143    }
144
145    /// NOTE: this subscription never ends even after update task is shutdown.
146    /// You should consume this stream in a spawn_cancellable.
147    pub fn subscribe_to_updates(&self) -> impl Stream<Item = ()> + '_ {
148        stream! {
149            let mut notify = pin!(self.meta_update_notify.notified());
150            loop {
151                notify.as_mut().await;
152                notify.set(self.meta_update_notify.notified());
153                // enable waiting for next notification before yield so don't miss
154                // any notifications.
155                notify.as_mut().enable();
156                yield ();
157            }
158        }
159    }
160
161    /// NOTE: this subscription never ends even after update task is shutdown.
162    /// You should consume this stream in a spawn_cancellable.
163    ///
164    /// Stream will yield the first element immediately without blocking.
165    /// The first element will be initial value of the field.
166    ///
167    /// This may yield an outdated initial value if you didn't call
168    /// [`Self::wait_initialization`].
169    pub fn subscribe_to_field<'a, V: DeserializeOwned + 'static>(
170        &'a self,
171        db: &'a Database,
172        name: &'a str,
173    ) -> impl Stream<Item = Option<MetaValue<V>>> + 'a {
174        stream! {
175            let mut update_stream = pin!(self.subscribe_to_updates());
176            loop {
177                let value = self.get_cached_field(db, name).await;
178                yield value;
179                if update_stream.next().await.is_none() {
180                    break;
181                }
182            }
183        }
184    }
185
186    /// Update all source in background.
187    ///
188    /// Caller should run this method in a task.
189    pub(crate) async fn update_continuously(&self, client: &Client) -> ! {
190        let mut current_revision = self
191            .current_revision(&mut client.db().begin_transaction_nc().await)
192            .await;
193        let client_config = client.config().await;
194        let meta_values = self
195            .source
196            .fetch(
197                &client_config,
198                &client.api,
199                FetchKind::Initial,
200                current_revision,
201            )
202            .await;
203        let failed_initial = meta_values.is_err();
204        match meta_values {
205            Ok(meta_values) => self.save_meta_values(client, &meta_values).await,
206            Err(error) => {
207                warn!(target: LOG_CLIENT, err = %error.fmt_compact(), "failed to fetch source");
208            }
209        };
210        self.initial_fetch_waiter.done();
211
212        // don't wait if we failed first item
213        if !failed_initial {
214            self.source.wait_for_update().await;
215        }
216
217        // now keep updating slowly
218        loop {
219            if let Ok(meta_values) = self
220                .source
221                .fetch(
222                    &client_config,
223                    &client.api,
224                    FetchKind::Background,
225                    current_revision,
226                )
227                .await
228            {
229                current_revision = Some(meta_values.revision);
230                self.save_meta_values(client, &meta_values).await;
231            }
232            self.source.wait_for_update().await;
233        }
234    }
235
236    async fn save_meta_values(&self, client: &Client, meta_values: &MetaValues) {
237        let mut dbtx = client.db().begin_transaction().await;
238        dbtx.remove_by_prefix(&MetaFieldPrefix).await;
239        dbtx.insert_entry(
240            &MetaServiceInfoKey,
241            &MetaServiceInfo {
242                last_updated: fedimint_core::time::now(),
243                revision: meta_values.revision,
244            },
245        )
246        .await;
247        for (key, value) in &meta_values.values {
248            dbtx.insert_entry(&MetaFieldKey(key.clone()), &MetaFieldValue(value.clone()))
249                .await;
250        }
251        dbtx.commit_tx().await;
252        // notify everyone about changes
253        self.meta_update_notify.notify_waiters();
254    }
255}
256
257#[cfg(test)]
258mod tests;