dioxus-provider 0.2.1

Data fetching and caching library for Dioxus applications with intelligent caching strategies and global providers.
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
//! # Mutation System for Dioxus Provider
//!
//! This module provides mutation capabilities for modifying data and keeping caches in sync.
//! It integrates seamlessly with the provider system for automatic cache invalidation and
//! optimistic updates.
//!
//! ## Features
//!
//! - **Mutation Providers**: Define mutations with the `#[mutation]` macro
//! - **Optimistic Updates**: Immediate UI updates with rollback on failure
//! - **Automatic Cache Invalidation**: Invalidate related providers automatically
//! - **Mutation State**: Track loading, success, and error states
//! - **Rollback Support**: Automatic rollback of optimistic updates on failure

use dioxus::prelude::*;
use futures::channel::oneshot;
use std::{collections::HashSet, future::Future};

use crate::{
    global::{get_global_cache, get_global_refresh_registry},
    hooks::Provider,
    types::ProviderParamBounds,
};

/// Represents the state of a mutation operation
#[derive(Clone, PartialEq)]
pub enum MutationState<T, E> {
    /// The mutation is idle (not running)
    Idle,
    /// The mutation is currently loading
    Loading,
    /// The mutation completed successfully
    Success(T),
    /// The mutation failed with an error
    Error(E),
}

impl<T, E> crate::state::AsyncState for MutationState<T, E> {
    type Data = T;
    type Error = E;

    fn is_loading(&self) -> bool {
        matches!(self, MutationState::Loading)
    }

    fn is_success(&self) -> bool {
        matches!(self, MutationState::Success(_))
    }

    fn is_error(&self) -> bool {
        matches!(self, MutationState::Error(_))
    }

    fn data(&self) -> Option<&T> {
        match self {
            MutationState::Success(data) => Some(data),
            _ => None,
        }
    }

    fn error(&self) -> Option<&E> {
        match self {
            MutationState::Error(error) => Some(error),
            _ => None,
        }
    }
}

impl<T, E> MutationState<T, E> {
    /// Returns true if the mutation is idle
    pub fn is_idle(&self) -> bool {
        matches!(self, MutationState::Idle)
    }

    /// Returns true if the mutation is currently loading
    pub fn is_loading(&self) -> bool {
        <Self as crate::state::AsyncState>::is_loading(self)
    }

    /// Returns true if the mutation completed successfully
    pub fn is_success(&self) -> bool {
        <Self as crate::state::AsyncState>::is_success(self)
    }

    /// Returns true if the mutation failed
    pub fn is_error(&self) -> bool {
        <Self as crate::state::AsyncState>::is_error(self)
    }

    /// Returns the success data if available
    pub fn data(&self) -> Option<&T> {
        <Self as crate::state::AsyncState>::data(self)
    }

    /// Returns the error if available
    pub fn error(&self) -> Option<&E> {
        <Self as crate::state::AsyncState>::error(self)
    }
}

/// Provides access to cached mutation data for implementations generated by the macro.
pub struct MutationContext<'a, Data, Error> {
    current: Option<&'a Result<Data, Error>>,
}

impl<'a, Data, Error> MutationContext<'a, Data, Error> {
    /// Create a new mutation context from the current cached result.
    pub fn new(current: Option<&'a Result<Data, Error>>) -> Self {
        Self { current }
    }

    /// Returns the current cached result, including the error if the cache failed previously.
    pub fn current(&self) -> Option<&Result<Data, Error>> {
        self.current
    }

    /// Returns a reference to the current successful cached data, if available.
    pub fn current_success(&self) -> Option<&Data> {
        match self.current? {
            Ok(data) => Some(data),
            Err(_) => None,
        }
    }

    /// Clones the current successful cached data, if available.
    pub fn cloned_success(&self) -> Option<Data>
    where
        Data: Clone,
    {
        self.current()?.as_ref().ok().cloned()
    }

    /// Applies a transformation to the cloned cached data and returns the updated value.
    pub fn map_current<F>(&self, f: F) -> Option<Data>
    where
        Data: Clone,
        F: FnOnce(&mut Data),
    {
        let mut cloned = self.cloned_success()?;
        f(&mut cloned);
        Some(cloned)
    }

    /// Applies a transformation to the cloned cached data, or returns a default value if no data is available.
    ///
    /// This is useful when you need to ensure a value is always returned, even if the cache is empty.
    ///
    /// ## Example
    ///
    /// ```rust,no_run
    /// use dioxus_provider::prelude::*;
    ///
    /// #[mutation(invalidates = [fetch_items])]
    /// async fn add_item(
    ///     item: String,
    ///     ctx: MutationContext<Vec<String>, String>,
    /// ) -> Result<Vec<String>, String> {
    ///     Ok(ctx.map_or_else(
    ///         || vec![item.clone()],  // default if no cached data
    ///         |items| {
    ///             items.push(item.clone());
    ///         }
    ///     ))
    /// }
    /// ```
    pub fn map_or_else<F, D>(&self, default: D, f: F) -> Data
    where
        Data: Clone,
        F: FnOnce(&mut Data),
        D: FnOnce() -> Data,
    {
        self.map_current(f).unwrap_or_else(default)
    }

    /// Updates the cached data in place, returning the modified data or None if no data exists.
    ///
    /// This is similar to `map_current` but provides a more explicit name for mutations
    /// that modify existing data.
    ///
    /// ## Example
    ///
    /// ```rust,no_run
    /// use dioxus_provider::prelude::*;
    ///
    /// #[mutation(invalidates = [fetch_counter])]
    /// async fn increment_counter(
    ///     ctx: MutationContext<i32, String>,
    /// ) -> Result<i32, String> {
    ///     ctx.update_in_place(|count| *count += 1)
    ///         .ok_or_else(|| "No counter data available".to_string())
    /// }
    /// ```
    pub fn update_in_place<F>(&self, f: F) -> Option<Data>
    where
        Data: Clone,
        F: FnOnce(&mut Data),
    {
        self.map_current(f)
    }

    /// Returns true if there is currently cached data available.
    pub fn has_data(&self) -> bool {
        self.current_success().is_some()
    }

    /// Returns true if the current cache contains an error.
    pub fn has_error(&self) -> bool {
        matches!(self.current, Some(Err(_)))
    }
}

/// Trait for defining mutations - operations that modify data
///
/// Mutations are similar to providers but are designed for data modification operations.
/// They typically involve server requests to create, update, or delete data.
///
/// ## Usage
/// Prefer using the `#[mutation]` macro to define mutations. Manual trait implementations are for advanced use only.
///
/// ## Example
///
/// ```rust,no_run
/// use dioxus_provider::prelude::*;
///
/// #[mutation(invalidates = [fetch_user, fetch_users])]
/// async fn update_user(user_id: u32, data: UserData) -> Result<User, String> {
///     // Make API call to update user
///     api_client.update_user(user_id, data).await
/// }
/// ```
pub trait Mutation<Input = ()>: Clone + PartialEq + 'static
where
    Input: Clone + PartialEq + 'static,
{
    /// The type of data returned on successful mutation
    type Output: Clone + PartialEq + Send + Sync + 'static;
    /// The type of error returned on mutation failure
    type Error: Clone + PartialEq + Send + Sync + 'static;

    /// Execute the mutation with the given input
    fn mutate(&self, input: Input) -> impl Future<Output = Result<Self::Output, Self::Error>>;

    /// Execute the mutation with access to current cached data
    /// This allows mutations to work with existing state instead of redefining data
    /// If not implemented, falls back to the simple mutate method
    fn mutate_with_current(
        &self,
        input: Input,
        _current_data: Option<&Result<Self::Output, Self::Error>>,
    ) -> impl Future<Output = Result<Self::Output, Self::Error>> {
        // Default implementation falls back to simple mutate
        self.mutate(input)
    }

    /// Get a unique identifier for this mutation type
    fn id(&self) -> String {
        std::any::type_name::<Self>().to_string()
    }

    /// Get list of provider cache keys that should be invalidated after successful mutation
    /// Override this to specify which providers should be refreshed after mutation
    fn invalidates(&self) -> Vec<String> {
        Vec::new()
    }

    /// Returns true if this mutation has optimistic updates configured
    /// Used by `use_mutation` to automatically detect and enable optimistic behavior
    fn has_optimistic(&self) -> bool {
        false
    }

    /// Provide optimistic cache updates for immediate UI feedback
    /// Returns a list of (cache_key, optimistic_result) pairs to update the cache with
    /// This allows the UI to update immediately with the expected result
    /// The Result should contain the optimistic success value
    fn optimistic_updates(
        &self,
        _input: &Input,
    ) -> Vec<(String, Result<Self::Output, Self::Error>)> {
        Vec::new()
    }

    /// Compute optimistic updates with access to current cached data
    /// This is more efficient as it allows mutations to work with existing data
    /// instead of duplicating data structures
    ///
    /// ## Return Value Usage
    /// The mutation's return value is used to update the cache directly on success,
    /// avoiding unnecessary provider refetches when using optimistic updates.
    /// When optimistic updates are defined, the actual server response replaces
    /// the optimistic value in the cache, keeping the UI in sync with the backend.
    fn optimistic_updates_with_current(
        &self,
        _input: &Input,
        _current_data: Option<&Result<Self::Output, Self::Error>>,
    ) -> Vec<(String, Result<Self::Output, Self::Error>)> {
        // Fallback to the simple method if not overridden
        self.optimistic_updates(_input)
    }
}

/// Type alias for the return type of mutation hooks
pub type MutationHookResult<M, Input, F> = (
    Signal<MutationState<<M as Mutation<Input>>::Output, <M as Mutation<Input>>::Error>>,
    F,
);

/// Configuration for mutation behavior
#[derive(Clone, Debug)]
struct MutationConfig {
    /// Whether to apply optimistic updates
    optimistic: bool,
}

impl MutationConfig {
    /// Create a default mutation configuration (no optimistic updates)
    fn default() -> Self {
        Self { optimistic: false }
    }

    /// Create a mutation configuration with optimistic updates enabled
    fn optimistic() -> Self {
        Self { optimistic: true }
    }
}

/// Core mutation logic shared between use_mutation and use_optimistic_mutation
fn mutation_core<M, Input>(
    mutation: M,
    config: MutationConfig,
) -> MutationHookResult<M, Input, impl Fn(Input) + Clone>
where
    M: Mutation<Input> + Send + Sync + 'static,
    Input: Clone + PartialEq + Send + Sync + 'static,
{
    let state = use_signal(|| MutationState::Idle);
    let cache = get_global_cache();
    let refresh_registry = get_global_refresh_registry();

    let mutate_fn = {
        let mutation = mutation.clone();
        let cache = cache
            .unwrap_or_else(|_| {
                panic!("Global providers not initialized. Call dioxus_provider::init() before using mutations.")
            })
            .clone();
        let refresh_registry = refresh_registry
            .unwrap_or_else(|_| {
                panic!("Global providers not initialized. Call dioxus_provider::init() before using mutations.")
            })
            .clone();
        let is_optimistic = config.optimistic;

        move |input: Input| {
            // Prevent concurrent optimistic mutations
            if is_optimistic && matches!(*state.read(), MutationState::Loading) {
                crate::debug_log!(
                    "⏸️ [MUTATION] Skipping mutation - already in progress for: {}",
                    mutation.id()
                );
                return;
            }

            let mutation = mutation.clone();
            let cache = cache.clone();
            let refresh_registry = refresh_registry.clone();
            let input = input.clone();
            let mut ui_state = state;

            // Set loading state
            ui_state.set(MutationState::Loading);

            // Collect optimistic updates if enabled
            let cache_keys_to_check: Vec<String> = mutation.invalidates();
            let mut optimistic_updates = Vec::new();

            if is_optimistic {
                // First, try to get optimistic updates from providers that have cached data
                for cache_key in &cache_keys_to_check {
                    let current_data = cache.get::<Result<M::Output, M::Error>>(cache_key);
                    let updates =
                        mutation.optimistic_updates_with_current(&input, current_data.as_ref());
                    optimistic_updates.extend(updates);
                }

                // If we don't have any optimistic updates yet, try the fallback method
                if optimistic_updates.is_empty() {
                    optimistic_updates = mutation.optimistic_updates(&input);
                }

                // If we still don't have optimistic updates, but we have cache keys to invalidate,
                // we need to handle the case where some providers don't have cached data
                if optimistic_updates.is_empty() && !cache_keys_to_check.is_empty() {
                    // For providers without cached data, we'll use SWR behavior:
                    // - Don't show loading state immediately
                    // - Let them fetch in the background while showing stale data (if any)
                    // - This prevents jitters for providers that don't have optimistic updates
                    crate::debug_log!(
                        "⚡ [OPTIMISTIC] No optimistic updates available, using SWR for {} cache keys",
                        cache_keys_to_check.len()
                    );
                }

                if !optimistic_updates.is_empty() {
                    crate::debug_log!(
                        "⚡ [OPTIMISTIC] Optimistically updating {} cache entries",
                        optimistic_updates.len()
                    );
                    for (cache_key, optimistic_result) in &optimistic_updates {
                        cache.set(cache_key.clone(), optimistic_result.clone());
                        refresh_registry.trigger_refresh(cache_key);
                    }
                }
            }

            let optimistic_updates_for_rollback = optimistic_updates.clone();
            let (result_tx, result_rx) = oneshot::channel::<Result<M::Output, M::Error>>();

            spawn({
                let mut state = ui_state;
                async move {
                    if let Ok(outcome) = result_rx.await {
                        match outcome {
                            Ok(result) => state.set(MutationState::Success(result)),
                            Err(error) => state.set(MutationState::Error(error)),
                        }
                    }
                }
            });

            dioxus_core::spawn_forever(async move {
                #[cfg(feature = "tracing")]
                let mutation_type = if is_optimistic {
                    "optimistic mutation"
                } else {
                    "mutation"
                };
                crate::debug_log!(
                    "🔄 [MUTATION] Starting {}: {}",
                    mutation_type,
                    mutation.id()
                );

                // Get current data for the mutation
                let mutation_current_data = cache_keys_to_check
                    .first()
                    .and_then(|first_key| cache.get::<Result<M::Output, M::Error>>(first_key));

                let mutation_result = mutation
                    .mutate_with_current(input, mutation_current_data.as_ref())
                    .await;

                crate::debug_log!(
                    "📡 [MUTATION] Mutation completed for: {}, result: {}",
                    mutation.id(),
                    match &mutation_result {
                        Ok(_) => "Success",
                        Err(_) => "Error",
                    }
                );

                match &mutation_result {
                    Ok(result) => {
                        crate::debug_log!("✅ [MUTATION] Mutation succeeded: {}", mutation.id());

                        if is_optimistic && !optimistic_updates_for_rollback.is_empty() {
                            // Update optimistic caches with real result
                            let optimistic_keys: HashSet<String> = optimistic_updates_for_rollback
                                .iter()
                                .map(|(key, _)| key.clone())
                                .collect();

                            crate::debug_log!(
                                "📦 [MUTATION] Updating {} optimistic cache entries with mutation result",
                                optimistic_keys.len()
                            );

                            for cache_key in &optimistic_keys {
                                cache.set(cache_key.clone(), Ok::<_, M::Error>(result.clone()));
                                refresh_registry.trigger_refresh(cache_key);
                            }

                            let invalidation_keys: Vec<_> = cache_keys_to_check
                                .iter()
                                .filter(|key| !optimistic_keys.contains(*key))
                                .cloned()
                                .collect();

                            if !invalidation_keys.is_empty() {
                                crate::debug_log!(
                                    "🔄 [MUTATION] Invalidating {} cache keys: {:?}",
                                    invalidation_keys.len(),
                                    invalidation_keys
                                );

                                for cache_key in invalidation_keys {
                                    cache.invalidate(&cache_key);
                                    refresh_registry.trigger_refresh(&cache_key);
                                }
                            }
                        } else {
                            // Standard cache invalidation
                            crate::debug_log!(
                                "🔄 [MUTATION] Invalidating {} cache keys: {:?}",
                                cache_keys_to_check.len(),
                                cache_keys_to_check
                            );

                            for cache_key in &cache_keys_to_check {
                                crate::debug_log!(
                                    "🗑️ [MUTATION] Invalidating cache key: {}",
                                    cache_key
                                );
                                cache.invalidate(cache_key);
                                refresh_registry.trigger_refresh(cache_key);
                            }
                        }
                    }
                    Err(_) => {
                        crate::debug_log!("❌ [MUTATION] Mutation failed: {}", mutation.id());

                        if is_optimistic && !optimistic_updates_for_rollback.is_empty() {
                            crate::debug_log!(
                                "🔄 [ROLLBACK] Rolling back {} optimistic updates",
                                optimistic_updates_for_rollback.len()
                            );

                            for (cache_key, _) in &optimistic_updates_for_rollback {
                                crate::debug_log!(
                                    "🔄 [ROLLBACK] Rolling back optimistic update for cache key: {}",
                                    cache_key
                                );
                                cache.invalidate(cache_key);
                                refresh_registry.trigger_refresh(cache_key);
                            }
                        }
                    }
                }

                if result_tx.send(mutation_result).is_err() {
                    crate::debug_log!(
                        "⚠️ [MUTATION] Result receiver dropped before completion for: {}",
                        mutation.id()
                    );
                }
            });
        }
    };

    (state, mutate_fn)
}

/// Hook to create a mutation that can be triggered manually
///
/// This hook automatically detects whether optimistic updates are configured
/// in the `#[mutation]` macro and enables them accordingly. You no longer need
/// to choose between `use_mutation` and `use_optimistic_mutation` - this hook
/// handles both cases automatically.
///
/// Returns a tuple containing:
/// 1. A signal with the current mutation state
/// 2. A function to trigger the mutation
///
/// ## Example
///
/// ```rust,no_run
/// use dioxus::prelude::*;
/// use dioxus_provider::prelude::*;
///
/// #[component]
/// fn UpdateUserForm(user_id: u32) -> Element {
///     let (mutation_state, mutate) = use_mutation(update_user());
///     
///     let handle_submit = move |data: UserData| {
///         mutate(user_id, data);
///     };
///     
///     rsx! {
///         form {
///             button {
///                 disabled: mutation_state.read().is_loading(),
///                 onclick: move |_| handle_submit(get_form_data()),
///                 "Update User"
///             }
///             match &*mutation_state.read() {
///                 MutationState::Loading => rsx! { div { "Updating..." } },
///                 MutationState::Success(_) => rsx! { div { "Updated successfully!" } },
///                 MutationState::Error(err) => rsx! { div { "Error: {err}" } },
///                 MutationState::Idle => rsx! { div {} },
///             }
///         }
///     }
/// }
/// ```
pub fn use_mutation<M, Input>(mutation: M) -> MutationHookResult<M, Input, impl Fn(Input) + Clone>
where
    M: Mutation<Input> + Send + Sync + 'static,
    Input: Clone + PartialEq + Send + Sync + 'static,
{
    let config = if mutation.has_optimistic() {
        MutationConfig::optimistic()
    } else {
        MutationConfig::default()
    };
    mutation_core(mutation, config)
}

/// Hook to create a mutation with optimistic updates
///
/// **Note:** This hook is now an alias for `use_mutation`, which automatically detects
/// whether optimistic updates are configured. You can use `use_mutation` directly instead.
/// This function is maintained for backward compatibility.
///
/// The optimistic behavior is automatically detected from the `#[mutation]` macro's
/// `optimistic` parameter. If an optimistic closure is provided in the macro,
/// the mutation will automatically use optimistic updates.
///
/// ## Example
///
/// ```rust,no_run
/// use dioxus::prelude::*;
/// use dioxus_provider::prelude::*;
///
/// #[component]
/// fn TodoItem(todo_id: u32) -> Element {
///     // Both of these are equivalent:
///     let (mutation_state, mutate) = use_mutation(toggle_todo());
///     // let (mutation_state, mutate) = use_optimistic_mutation(toggle_todo());
///     
///     rsx! {
///         div {
///             button {
///                 onclick: move |_| mutate(todo_id),
///                 "Toggle Todo"
///             }
///             match &*mutation_state.read() {
///                 MutationState::Loading => rsx! { span { "Saving..." } },
///                 MutationState::Error(err) => rsx! { span { "Error: {err}" } },
///                 _ => rsx! { span {} },
///             }
///         }
///     }
/// }
/// ```
pub fn use_optimistic_mutation<M, Input>(
    mutation: M,
) -> MutationHookResult<M, Input, impl Fn(Input) + Clone>
where
    M: Mutation<Input> + Send + Sync + 'static,
    Input: Clone + PartialEq + Send + Sync + 'static,
{
    // Simply delegate to use_mutation, which auto-detects optimistic updates
    use_mutation(mutation)
}

/// Helper function to create cache keys for providers with parameters
pub fn provider_cache_key<P, Param>(provider: P, param: Param) -> String
where
    P: Provider<Param>,
    Param: ProviderParamBounds,
{
    provider.id(&param)
}

/// Helper function to create cache keys for providers without parameters
pub fn provider_cache_key_simple<P>(provider: P) -> String
where
    P: Provider<()>,
{
    provider.id(&())
}