leptos-fetch 0.4.2

Async query manager for Leptos
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
use std::{
    collections::{HashMap, HashSet},
    fmt::Debug,
    sync::Arc,
    time::Duration,
};

use leptos::prelude::{ArcRwSignal, Set};
use parking_lot::Mutex;
use send_wrapper::SendWrapper;

use crate::{
    QueryOptions, SYNC_TRACK_UPDATE_MARKER,
    cache::ScopeLookup,
    debug_if_devtools_enabled::DebugIfDevtoolsEnabled,
    maybe_local::MaybeLocal,
    options_combine,
    query_scope::{QueryScopeInfo, ScopeCacheKey},
    safe_dt_dur_add,
    utils::{KeyHash, new_buster_id},
    value_with_callbacks::{GcHandle, GcValue, RefetchHandle},
};

pub(crate) struct Query<K, V: 'static> {
    key: MaybeLocal<K>,
    value_maybe_stale: GcValue<V>,
    pub combined_options: QueryOptions,
    pub updated_at: chrono::DateTime<chrono::Utc>,
    invalidation_prefix: Option<Vec<String>>,
    invalidated: bool,
    /// Will always be None on the server, hence the SendWrapper is fine:
    gc_cb: Option<Arc<SendWrapper<Box<dyn Fn() -> bool>>>>,
    /// Will always be None on the server, hence the SendWrapper is fine:
    refetch_cb: Option<Arc<SendWrapper<Box<dyn Fn()>>>>,
    active_resources: Arc<Mutex<HashSet<u64>>>,
    pub buster: ArcRwSignal<u64>,
    scope_lookup: ScopeLookup,
    cache_key: ScopeCacheKey,
    key_hash: KeyHash,
    #[cfg(any(
        all(debug_assertions, feature = "devtools"),
        feature = "devtools-always"
    ))]
    pub events: crate::events::Events,
}

impl<K, V> Drop for Query<K, V> {
    fn drop(&mut self) {
        self.scope_lookup
            .scope_subscriptions_mut()
            .notify_value_set_updated_or_removed(self.cache_key, self.key_hash);
        #[cfg(any(
            all(debug_assertions, feature = "devtools"),
            feature = "devtools-always"
        ))]
        self.scope_lookup
            .scope_subscriptions_mut()
            .notify_active_resource_change(self.cache_key, self.key_hash, 0);
    }
}

#[cfg(any(
    all(debug_assertions, feature = "devtools"),
    feature = "devtools-always"
))]
pub(crate) trait DynQuery {
    fn key_hash(&self) -> &KeyHash;

    fn debug_key(&self) -> crate::utils::DebugValue;

    fn debug_value_may_panic(&self) -> crate::utils::DebugValue;

    fn combined_options(&self) -> QueryOptions;

    fn updated_at(&self) -> chrono::DateTime<chrono::Utc>;

    fn events(&self) -> &[crate::events::Event];

    /// Option when already stale.
    fn till_stale(&self) -> Option<Duration>;

    fn is_invalidated(&self) -> bool;

    fn active_resources_len(&self) -> usize;
}

#[cfg(any(
    all(debug_assertions, feature = "devtools"),
    feature = "devtools-always"
))]
impl<K, V> DynQuery for Query<K, V>
where
    K: DebugIfDevtoolsEnabled + 'static,
    V: DebugIfDevtoolsEnabled + 'static,
{
    fn key_hash(&self) -> &KeyHash {
        &self.key_hash
    }

    fn debug_key(&self) -> crate::utils::DebugValue {
        // SAFETY: should only be called from single threaded frontend (devtools)
        crate::utils::DebugValue::new(self.key.value_may_panic())
    }

    fn debug_value_may_panic(&self) -> crate::utils::DebugValue {
        // SAFETY: should only be called from single threaded frontend (devtools)
        crate::utils::DebugValue::new(self.value_maybe_stale.value().value_may_panic())
    }

    fn combined_options(&self) -> QueryOptions {
        self.combined_options
    }

    fn updated_at(&self) -> chrono::DateTime<chrono::Utc> {
        self.updated_at
    }

    fn events(&self) -> &[crate::events::Event] {
        &self.events
    }

    /// Option when already stale.
    fn till_stale(&self) -> Option<Duration> {
        if self.stale() {
            None
        } else {
            let stale_after = safe_dt_dur_add(self.updated_at, self.combined_options.stale_time());
            let now = chrono::Utc::now();
            let till_stale = stale_after - now;
            if till_stale < chrono::TimeDelta::zero() {
                return None;
            }
            Some(
                till_stale
                    .to_std()
                    .expect("Could not convert to std duration"),
            )
        }
    }

    fn is_invalidated(&self) -> bool {
        self.invalidated
    }

    fn active_resources_len(&self) -> usize {
        self.active_resources.lock().len()
    }
}

impl<K, V> Debug for Query<K, V> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Query").finish()
    }
}

impl<K, V> Query<K, V> {
    pub fn new(
        client_options: QueryOptions,
        scope_lookup: ScopeLookup,
        query_scope_info: &QueryScopeInfo,
        invalidation_prefix: Option<Vec<String>>,
        key_hash: KeyHash,
        key: MaybeLocal<K>,
        value: MaybeLocal<V>,
        buster: ArcRwSignal<u64>,
        scope_options: Option<QueryOptions>,
        active_resources: Option<Arc<Mutex<HashSet<u64>>>>,
        #[cfg(any(
            all(debug_assertions, feature = "devtools"),
            feature = "devtools-always"
        ))]
        event: crate::events::Event,
    ) -> Self
    where
        K: DebugIfDevtoolsEnabled + Clone + 'static,
        V: DebugIfDevtoolsEnabled + Clone + 'static,
    {
        let cache_key = query_scope_info.cache_key;
        let combined_options = options_combine(client_options, scope_options);
        let active_resources =
            active_resources.unwrap_or_else(|| Arc::new(Mutex::new(HashSet::new())));

        // Add to the invalidation prefix trie/hierarchy on creation:
        if let Some(invalidation_prefix) = &invalidation_prefix {
            scope_lookup
                .invalidation_trie()
                .insert(invalidation_prefix, (cache_key, key_hash));
        }

        let gc_cb = if cfg!(any(test, not(feature = "ssr")))
            && combined_options.gc_time() < Duration::from_secs(60 * 60 * 24 * 365)
        {
            let active_resources = active_resources.clone();
            // GC is client only (non-ssr) hence can wrap in a SendWrapper:
            let invalidation_prefix = invalidation_prefix.clone();
            Some(Arc::new(SendWrapper::new(Box::new(move || {
                if active_resources.lock().is_empty() {
                    scope_lookup.gc_query::<K, V>(&cache_key, &key_hash);

                    // Remove from the invalidation prefix trie/hierarchy on gc:
                    if let Some(invalidation_prefix) = &invalidation_prefix {
                        scope_lookup
                            .invalidation_trie()
                            .remove(invalidation_prefix, &(cache_key, key_hash));
                    }

                    true
                } else {
                    false
                }
            })
                as Box<dyn Fn() -> bool>)))
        } else {
            None
        };

        let refetch_cb = if cfg!(any(test, not(feature = "ssr")))
            && combined_options.refetch_interval().is_some()
        {
            // Refetching is client only (non-ssr) hence can wrap in a SendWrapper:
            let query_scope_info = query_scope_info.clone();
            Some(Arc::new(SendWrapper::new(Box::new(move || {
                scope_lookup.with_cached_scope_mut::<K, V, _>(
                    &query_scope_info,
                    false,
                    |maybe_scope| {
                        // Invalidation will only trigger a refetch if there are active resources, hence fine to always call:
                        if let Some(scope) = maybe_scope {
                            if let Some(cached) = scope.get_mut(&key_hash) {
                                cached.invalidate();
                                #[cfg(any(
                                    all(debug_assertions, feature = "devtools"),
                                    feature = "devtools-always"
                                ))]
                                {
                                    cached.events.push(crate::events::Event::new(
                                    crate::events::EventVariant::RefetchTriggeredViaInvalidation,
                                ));
                                }
                            }
                        }
                    },
                );
            }) as Box<dyn Fn()>)))
        } else {
            None
        };

        let created_at = chrono::Utc::now();
        Self {
            #[cfg(any(
                all(debug_assertions, feature = "devtools"),
                feature = "devtools-always"
            ))]
            events: crate::events::Events::new(&scope_lookup, cache_key, key_hash, vec![event]),
            key,
            value_maybe_stale: GcValue::new(
                value,
                GcHandle::new(gc_cb.clone(), combined_options.gc_time()),
                RefetchHandle::new(refetch_cb.clone(), combined_options.refetch_interval()),
            ),
            combined_options,
            updated_at: created_at,
            invalidation_prefix,
            invalidated: false,
            gc_cb,
            refetch_cb,
            active_resources,
            buster,
            scope_lookup,
            cache_key,
            key_hash,
        }
    }

    #[cfg(test)]
    pub fn is_invalidated(&self) -> bool {
        self.invalidated
    }

    pub fn mark_resource_active(&self, resource_id: u64) {
        let total_active = {
            let mut guard = self.active_resources.lock();
            guard.insert(resource_id);
            guard.len()
        };
        #[cfg(any(
            all(debug_assertions, feature = "devtools"),
            feature = "devtools-always"
        ))]
        {
            self.scope_lookup
                .scope_subscriptions_mut()
                .notify_active_resource_change(self.cache_key, self.key_hash, total_active);
        }
        let _ = total_active;
    }

    pub fn mark_resource_dropped(&self, resource_id: u64) {
        let total_active = {
            let mut guard = self.active_resources.lock();
            guard.remove(&resource_id);
            guard.len()
        };
        #[cfg(any(
            all(debug_assertions, feature = "devtools"),
            feature = "devtools-always"
        ))]
        {
            self.scope_lookup
                .scope_subscriptions_mut()
                .notify_active_resource_change(self.cache_key, self.key_hash, total_active);
        }
        let _ = total_active;
    }

    pub fn invalidate(&mut self) {
        if !self.invalidated {
            self.invalidated = true;
            // To re-trigger all active resources automatically on manual invalidation:
            self.buster.set(new_buster_id());

            // Invalidate any linked children through the invalidation prefix trie/hierarchy on creation:
            if let Some(invalidation_prefix) = &self.invalidation_prefix {
                let trie = self.scope_lookup.invalidation_trie();
                let mut invalidation_map = HashMap::new();
                for (cache_key, key_hash) in trie.find_with_prefix(invalidation_prefix) {
                    if cache_key == &self.cache_key && *key_hash == self.key_hash {
                        continue;
                    }

                    invalidation_map
                        .entry(*cache_key)
                        .or_insert_with(Vec::new)
                        .push(*key_hash);
                }
                if !invalidation_map.is_empty() {
                    // Not ideal having to spawn, but need to get access to the global lock we'll already be holding in this .invalidate() fn:
                    let scope_lookup = self.scope_lookup;
                    leptos::task::spawn(async move {
                        let mut scopes = scope_lookup.scopes_mut();
                        for (cache_key, key_hashes) in invalidation_map {
                            if let Some(scope) = scopes.get_mut(&cache_key) {
                                scope.invalidate_queries(key_hashes);
                            }
                        }
                    });
                }
            }

            #[cfg(any(
                all(debug_assertions, feature = "devtools"),
                feature = "devtools-always"
            ))]
            {
                self.events.push(crate::events::Event::new(
                    crate::events::EventVariant::Invalidated,
                ));
            }
        }
    }

    pub fn stale(&self) -> bool {
        if self.invalidated {
            true
        } else {
            chrono::Utc::now()
                > safe_dt_dur_add(self.updated_at, self.combined_options.stale_time())
        }
    }

    pub fn key(&self) -> &MaybeLocal<K> {
        &self.key
    }

    pub fn value_maybe_stale(&self) -> &MaybeLocal<V> {
        self.value_maybe_stale.value()
    }

    pub fn set_value(
        &mut self,
        new_value: MaybeLocal<V>,
        track: bool,
        #[cfg(any(
            all(debug_assertions, feature = "devtools"),
            feature = "devtools-always"
        ))]
        event: crate::events::Event,
    ) where
        V: DebugIfDevtoolsEnabled + 'static,
    {
        self.update_value(
            |value| {
                // Only need to update on false, always defaults to true:
                if !track {
                    SYNC_TRACK_UPDATE_MARKER
                        .with(|marker| marker.store(false, std::sync::atomic::Ordering::Relaxed));
                }
                *value = new_value;
            },
            #[cfg(any(
                all(debug_assertions, feature = "devtools"),
                feature = "devtools-always"
            ))]
            event,
        );
    }

    /// Respects SYNC_TRACK_UPDATE_MARKER if set to false during the modifier:
    pub fn update_value<T>(
        &mut self,
        cb: impl FnOnce(&mut MaybeLocal<V>) -> T,
        #[cfg(any(
            all(debug_assertions, feature = "devtools"),
            feature = "devtools-always"
        ))]
        event: crate::events::Event,
    ) -> T
    where
        V: DebugIfDevtoolsEnabled + 'static,
    {
        // Default to true instead overriden during the modifier:
        SYNC_TRACK_UPDATE_MARKER
            .with(|marker| marker.store(true, std::sync::atomic::Ordering::Relaxed));

        let result = cb(self.value_maybe_stale.value_mut());

        let should_track = SYNC_TRACK_UPDATE_MARKER
            .with(|marker| marker.load(std::sync::atomic::Ordering::Relaxed));

        self.value_maybe_stale.reset_callbacks(
            GcHandle::new(self.gc_cb.clone(), self.combined_options.gc_time()),
            RefetchHandle::new(
                self.refetch_cb.clone(),
                self.combined_options.refetch_interval(),
            ),
        );

        #[cfg(any(
            all(debug_assertions, feature = "devtools"),
            feature = "devtools-always"
        ))]
        {
            self.events.push(event);
        }

        self.invalidated = false;
        self.updated_at = chrono::Utc::now();

        if should_track {
            // To update all existing resources:
            self.buster.set(new_buster_id());

            self.scope_lookup
                .scope_subscriptions_mut()
                .notify_value_set_updated_or_removed(self.cache_key, self.key_hash);
        }

        result
    }
}