freya-query 0.5.0-beta.12

Fully-typed, async, reusable cached data management for Freya 🧬
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
use core::fmt;
use std::{
    cell::{
        Ref,
        RefCell,
    },
    collections::HashMap,
    future::Future,
    hash::Hash,
    mem,
    rc::Rc,
    time::{
        Duration,
        Instant,
    },
};

use freya_core::{
    integration::FxHashSet,
    prelude::*,
};

pub trait MutationCapability
where
    Self: 'static + Clone + PartialEq + Hash + Eq,
{
    type Ok;
    type Err;
    type Keys: Hash + PartialEq + Clone;

    /// Mutation logic.
    fn run(&self, keys: &Self::Keys) -> impl Future<Output = Result<Self::Ok, Self::Err>>;

    /// Implement a custom logic to check if this mutation should be invalidated or not given a [MutationCapability::Keys].
    fn matches(&self, _keys: &Self::Keys) -> bool {
        true
    }

    /// Runs after [MutationCapability::run].
    /// You may use this method to invalidate [crate::query::Query]s.
    fn on_settled(
        &self,
        _keys: &Self::Keys,
        _result: &Result<Self::Ok, Self::Err>,
    ) -> impl Future<Output = ()> {
        async {}
    }
}

pub enum MutationStateData<Q: MutationCapability> {
    /// Has not loaded yet.
    Pending,
    /// Is loading and may not have a previous settled value.
    Loading { res: Option<Result<Q::Ok, Q::Err>> },
    /// Is not loading and has a settled value.
    Settled {
        res: Result<Q::Ok, Q::Err>,
        settlement_instant: Instant,
    },
}

impl<Q> fmt::Debug for MutationStateData<Q>
where
    Q: MutationCapability,
    Q::Ok: fmt::Debug,
    Q::Err: fmt::Debug,
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Pending => f.write_str("Pending"),
            Self::Loading { res } => write!(f, "Loading {{ {res:?} }}"),
            Self::Settled { res, .. } => write!(f, "Settled {{ {res:?} }}"),
        }
    }
}

impl<Q: MutationCapability> MutationStateData<Q> {
    /// Check if the state is [MutationStateData::Settled] and [Result::Ok].
    pub fn is_ok(&self) -> bool {
        matches!(self, MutationStateData::Settled { res: Ok(_), .. })
    }

    /// Check if the state is [MutationStateData::Settled] and [Result::Err].
    pub fn is_err(&self) -> bool {
        matches!(self, MutationStateData::Settled { res: Err(_), .. })
    }

    /// Check if the state is [MutationStateData::Loading].
    pub fn is_loading(&self) -> bool {
        matches!(self, MutationStateData::Loading { .. })
    }

    /// Check if the state is [MutationStateData::Pending].
    pub fn is_pending(&self) -> bool {
        matches!(self, MutationStateData::Pending)
    }

    /// Get the value as an [Option].
    pub fn ok(&self) -> Option<&Q::Ok> {
        match self {
            Self::Settled { res: Ok(res), .. } => Some(res),
            Self::Loading { res: Some(Ok(res)) } => Some(res),
            _ => None,
        }
    }

    /// Get the error as an [Option].
    pub fn err(&self) -> Option<&Q::Err> {
        match self {
            Self::Settled { res: Err(err), .. } => Some(err),
            Self::Loading {
                res: Some(Err(err)),
            } => Some(err),
            _ => None,
        }
    }

    /// Get the value as an [Result] if possible, otherwise it will panic.
    pub fn unwrap(&self) -> &Result<Q::Ok, Q::Err> {
        match self {
            Self::Loading { res: Some(v) } => v,
            Self::Settled { res, .. } => res,
            _ => unreachable!(),
        }
    }

    fn into_loading(self) -> MutationStateData<Q> {
        match self {
            MutationStateData::Pending => MutationStateData::Loading { res: None },
            MutationStateData::Loading { res } => MutationStateData::Loading { res },
            MutationStateData::Settled { res, .. } => MutationStateData::Loading { res: Some(res) },
        }
    }
}
#[cfg(debug_assertions)]
type MutationMock<Q> = Rc<
    dyn Fn(
        <Q as MutationCapability>::Keys,
    ) -> std::pin::Pin<
        Box<
            dyn Future<
                Output = Result<<Q as MutationCapability>::Ok, <Q as MutationCapability>::Err>,
            >,
        >,
    >,
>;

pub struct MutationsStorage<Q: MutationCapability> {
    storage: State<HashMap<Mutation<Q>, MutationData<Q>>>,

    #[cfg(debug_assertions)]
    mock: State<Option<MutationMock<Q>>>,
}

impl<Q: MutationCapability> Copy for MutationsStorage<Q> {}

impl<Q: MutationCapability> Clone for MutationsStorage<Q> {
    fn clone(&self) -> Self {
        *self
    }
}

pub struct MutationData<Q: MutationCapability> {
    state: Rc<RefCell<MutationStateData<Q>>>,
    reactive_contexts: Rc<RefCell<FxHashSet<ReactiveContext>>>,

    clean_task: Rc<RefCell<Option<TaskHandle>>>,
}

impl<Q: MutationCapability> Clone for MutationData<Q> {
    fn clone(&self) -> Self {
        Self {
            state: self.state.clone(),
            reactive_contexts: self.reactive_contexts.clone(),
            clean_task: self.clean_task.clone(),
        }
    }
}

impl<Q: MutationCapability> MutationsStorage<Q> {
    fn create_global() -> Self {
        Self {
            storage: State::create_global(HashMap::default()),
            #[cfg(debug_assertions)]
            mock: State::create_global(None),
        }
    }

    /// Create a storage whose mutations resolve with `mock` instead of [MutationCapability::run].
    ///
    /// [MutationCapability::on_settled] still runs.
    ///
    /// Insert it into the [GlobalContexts] before the app runs any mutation.
    #[cfg(debug_assertions)]
    pub fn mocked(mock: impl Fn(Q::Keys) -> Result<Q::Ok, Q::Err> + 'static) -> Self {
        Self::mocked_async(move |keys| {
            let res = mock(keys);
            async move { res }
        })
    }

    /// Like [MutationsStorage::mocked] but with an async mock.
    #[cfg(debug_assertions)]
    pub fn mocked_async<F>(mock: impl Fn(Q::Keys) -> F + 'static) -> Self
    where
        F: Future<Output = Result<Q::Ok, Q::Err>> + 'static,
    {
        let mock: MutationMock<Q> = Rc::new(move |keys| Box::pin(mock(keys)));

        Self {
            storage: State::create_global(HashMap::default()),
            mock: State::create_global(Some(mock)),
        }
    }

    fn insert_or_get_mutation(&mut self, mutation: Mutation<Q>) -> MutationData<Q> {
        let mut storage = self.storage.write_unchecked();

        let mutation_data = storage.entry(mutation).or_insert_with(|| MutationData {
            state: Rc::new(RefCell::new(MutationStateData::Pending)),
            reactive_contexts: Rc::new(RefCell::new(FxHashSet::default())),
            clean_task: Rc::default(),
        });

        // Cancel clean task
        if let Some(clean_task) = mutation_data.clean_task.take() {
            clean_task.cancel();
        }

        mutation_data.clone()
    }

    fn update_tasks(&mut self, mutation: Mutation<Q>) {
        let storage_clone = self.storage;
        let mut storage = self.storage.write_unchecked();

        let mutation_data = storage.get_mut(&mutation).unwrap();

        // Spawn clean up task if there no more reactive contexts
        if mutation_data.reactive_contexts.borrow().len() == 1 {
            *mutation_data.clean_task.borrow_mut() = Some(spawn_in_window(async move {
                // Wait as long as the stale time is configured
                timer(mutation.clean_time).await;

                // Finally clear the mutation
                let mut storage = storage_clone.write_unchecked();
                storage.remove(&mutation);
            }));
        }
    }

    async fn run(mutation: &Mutation<Q>, data: &MutationData<Q>, keys: Q::Keys) {
        // Set to Loading
        let res =
            mem::replace(&mut *data.state.borrow_mut(), MutationStateData::Pending).into_loading();
        *data.state.borrow_mut() = res;
        for reactive_context in data.reactive_contexts.borrow().iter() {
            reactive_context.notify();
        }

        // Run
        let res = mutation.run(&keys).await;

        // Set to Settled
        mutation.mutation.on_settled(&keys, &res).await;
        *data.state.borrow_mut() = MutationStateData::Settled {
            res,
            settlement_instant: Instant::now(),
        };
        for reactive_context in data.reactive_contexts.borrow().iter() {
            reactive_context.notify();
        }
    }
}

#[derive(PartialEq, Clone)]
pub struct Mutation<Q: MutationCapability> {
    mutation: Q,

    clean_time: Duration,
}

impl<Q: MutationCapability> Eq for Mutation<Q> {}
impl<Q: MutationCapability> Hash for Mutation<Q> {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.mutation.hash(state);
    }
}

impl<Q: MutationCapability> From<Q> for Mutation<Q> {
    fn from(mutation: Q) -> Self {
        Self::new(mutation)
    }
}

impl<Q: MutationCapability> Mutation<Q> {
    /// Run the mutation, using its mock if there is one.
    async fn run(&self, keys: &Q::Keys) -> Result<Q::Ok, Q::Err> {
        #[cfg(debug_assertions)]
        {
            let mock = GlobalContexts::get()
                .try_get_context::<MutationsStorage<Q>>()
                .and_then(|storage| storage.mock.peek().clone());

            if let Some(mock) = mock {
                return mock(keys.clone()).await;
            }
        }

        self.mutation.run(keys).await
    }

    pub fn new(mutation: Q) -> Self {
        Self {
            mutation,
            clean_time: Duration::ZERO,
        }
    }

    /// For how long the data is kept cached after there are no more mutation subscribers.
    ///
    /// Defaults to [Duration::ZERO], meaning it clears automatically.
    pub fn clean_time(self, clean_time: Duration) -> Self {
        Self { clean_time, ..self }
    }
}

pub struct MutationReader<Q: MutationCapability> {
    state: Rc<RefCell<MutationStateData<Q>>>,
}

impl<Q: MutationCapability> MutationReader<Q> {
    pub fn state(&'_ self) -> Ref<'_, MutationStateData<Q>> {
        self.state.borrow()
    }
}

pub struct UseMutation<Q: MutationCapability> {
    mutation: State<Mutation<Q>>,
}

impl<Q: MutationCapability> Clone for UseMutation<Q> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<Q: MutationCapability> Copy for UseMutation<Q> {}

impl<Q: MutationCapability> UseMutation<Q> {
    /// Read the [Mutation].
    ///
    /// This **will** automatically subscribe.
    /// If you want a **subscribing** method have a look at [UseMutation::peek].
    pub fn read(&self) -> MutationReader<Q> {
        let storage = GlobalContexts::get().get_context::<MutationsStorage<Q>>();
        let mutation_data = storage
            .storage
            .peek()
            .get(&self.mutation.read())
            .cloned()
            .unwrap();

        // Subscribe if possible
        if let Some(mut reactive_context) = ReactiveContext::try_current() {
            reactive_context.subscribe(&mutation_data.reactive_contexts);
        }

        MutationReader {
            state: mutation_data.state,
        }
    }

    /// Read the [Mutation].
    ///
    /// This **will not** automatically subscribe.
    /// If you want a **subscribing** method have a look at [UseMutation::read].
    pub fn peek(&self) -> MutationReader<Q> {
        let storage = GlobalContexts::get().get_context::<MutationsStorage<Q>>();
        let mutation_data = storage
            .storage
            .peek()
            .get(&self.mutation.peek())
            .cloned()
            .unwrap();

        MutationReader {
            state: mutation_data.state,
        }
    }

    /// Run this mutation await its result.
    ///
    /// For a `sync` version use [UseMutation::mutate].
    pub async fn mutate_async(&self, keys: Q::Keys) -> MutationReader<Q> {
        let storage = GlobalContexts::get().get_context::<MutationsStorage<Q>>();

        let mutation = self.mutation.peek().clone();
        let mutation_data = storage.storage.peek().get(&mutation).cloned().unwrap();

        // Run the mutation
        MutationsStorage::run(&mutation, &mutation_data, keys).await;

        MutationReader {
            state: mutation_data.state,
        }
    }

    // Run this mutation and await its result.
    ///
    /// For an `async` version use [UseMutation::mutate_async].
    pub fn mutate(&self, keys: Q::Keys) {
        let storage = GlobalContexts::get().get_context::<MutationsStorage<Q>>();

        let mutation = self.mutation.peek().clone();
        let mutation_data = storage.storage.peek().get(&mutation).cloned().unwrap();

        // Run the mutation
        spawn_in_window(
            async move { MutationsStorage::run(&mutation, &mutation_data, keys).await },
        );
    }
}

/// Mutations are used to update data asynchronously of an e.g external resources such as HTTP APIs.
///
/// ### Clean time
/// This is how long will the mutation result be kept cached after there are no more subscribers of that mutation.
///
/// See [Mutation::clean_time].
pub fn use_mutation<Q: MutationCapability>(mutation: impl Into<Mutation<Q>>) -> UseMutation<Q> {
    let mutation = mutation.into();
    let mut storage =
        GlobalContexts::get().get_context_or_insert(MutationsStorage::<Q>::create_global);

    let mut make_mutation = |mutation: &Mutation<Q>, mut prev_mutation: Option<Mutation<Q>>| {
        let _data = storage.insert_or_get_mutation(mutation.clone());

        // Update the mutation tasks if there has been a change in the mutation
        if let Some(prev_mutation) = prev_mutation.take() {
            storage.update_tasks(prev_mutation);
        }
    };

    let mut current_mutation = use_hook(|| {
        make_mutation(&mutation, None);
        State::create(mutation.clone())
    });

    if *current_mutation.read() != mutation {
        let prev = mem::replace(&mut *current_mutation.write(), mutation.clone());
        make_mutation(&mutation, Some(prev));
    }

    // Update the mutation tasks when the scope is dropped
    use_drop({
        move || {
            storage.update_tasks(current_mutation.peek().clone());
        }
    });

    let mutation = UseMutation {
        mutation: current_mutation,
    };

    // Used to consider this use_mutation call as a subscriber without rerunning the component
    use_side_effect(move || {
        let _ = mutation.read();
    });

    mutation
}