rs-store 3.0.0

Redux Store for Rust
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
use crate::effect::Effect;
use std::sync::Arc;

/// determine if the action should be dispatched or not
pub enum DispatchOp<State, Action> {
    /// Dispatch new state with effects
    /// since 3.0.0
    Dispatch(State, Vec<Effect<Action>>),
    /// Keep new state but do not dispatch
    Keep(State, Vec<Effect<Action>>),
}

/// Reducer reduces the state based on the action.
///
/// ## Parameters
/// - `state`: Current state (reference)
/// - `action`: Action to process (reference)
///
/// ## Returns
/// - [`DispatchOp<State, Action>`]: result that contains the next state and any effects to run.
pub trait Reducer<State, Action>
where
    State: Send + Sync + Clone,
    Action: Send + Sync + Clone + 'static,
{
    fn reduce(&self, state: &State, action: &Action) -> DispatchOp<State, Action>;
}

/// ReducerChain chains reducers together sequentially.
/// The first reducer in the vector becomes the first reducer in the chain.
/// Execution order: first reducer -> second reducer -> ... -> last reducer
pub struct ReducerChain<State, Action>
where
    State: Send + Sync + Clone,
    Action: Send + Sync + 'static,
{
    reducer: Arc<dyn Reducer<State, Action> + Send + Sync>,
    next: Option<Box<ReducerChain<State, Action>>>,
}

impl<State, Action> ReducerChain<State, Action>
where
    State: Send + Sync + Clone,
    Action: Send + Sync + 'static,
{
    /// Create a new reducer chain with a single reducer
    pub fn new(reducer: Arc<dyn Reducer<State, Action> + Send + Sync>) -> Self {
        Self {
            reducer,
            next: None,
        }
    }

    /// Chain another reducer to this chain
    pub fn chain(mut self, reducer: Arc<dyn Reducer<State, Action> + Send + Sync>) -> Self {
        if let Some(ref mut next) = self.next {
            // Recursively chain to the end
            *next = Box::new(next.as_ref().clone().chain(reducer));
        } else {
            // add at tail of the chain
            self.next = Some(Box::new(ReducerChain::new(reducer)));
        }
        self
    }

    /// Create a reducer chain from a vector of reducers
    /// The first reducer in the vector becomes the first reducer in the chain.
    pub fn from_vec(reducers: Vec<Box<dyn Reducer<State, Action> + Send + Sync>>) -> Option<Self> {
        if reducers.is_empty() {
            return None;
        }

        let mut iter = reducers.into_iter();
        let mut tail = ReducerChain::new(Arc::from(iter.next()?));

        for reducer in iter {
            tail = tail.chain(Arc::from(reducer));
        }

        Some(tail)
    }
}

// Implement Clone for ReducerChain to support recursive chaining
impl<State, Action> Clone for ReducerChain<State, Action>
where
    State: Send + Sync + Clone,
    Action: Send + Sync + 'static,
{
    fn clone(&self) -> Self {
        Self {
            reducer: self.reducer.clone(),
            next: self.next.as_ref().map(|n| Box::new(n.as_ref().clone())),
        }
    }
}

impl<State, Action> Reducer<State, Action> for ReducerChain<State, Action>
where
    State: Send + Sync + Clone,
    Action: Send + Sync + Clone + 'static,
{
    fn reduce(&self, state: &State, action: &Action) -> DispatchOp<State, Action> {
        // Execute current reducer
        let mut result = self.reducer.reduce(state, action);

        // Continue with next reducer if exists
        if let Some(ref next) = self.next {
            match result {
                DispatchOp::Dispatch(current_state, current_effects) => {
                    result = next.reduce(&current_state, action);
                    // Merge effects from both reducers
                    match result {
                        DispatchOp::Dispatch(next_state, mut next_effects) => {
                            next_effects.extend(current_effects);
                            DispatchOp::Dispatch(next_state, next_effects)
                        }
                        DispatchOp::Keep(next_state, mut next_effects) => {
                            next_effects.extend(current_effects);
                            DispatchOp::Keep(next_state, next_effects)
                        }
                    }
                }
                DispatchOp::Keep(current_state, current_effects) => {
                    result = next.reduce(&current_state, action);
                    // Merge effects from both reducers
                    match result {
                        DispatchOp::Dispatch(next_state, mut next_effects) => {
                            next_effects.extend(current_effects);
                            DispatchOp::Dispatch(next_state, next_effects)
                        }
                        DispatchOp::Keep(next_state, mut next_effects) => {
                            next_effects.extend(current_effects);
                            DispatchOp::Keep(next_state, next_effects)
                        }
                    }
                }
            }
        } else {
            result
        }
    }
}

/// FnReducer is a reducer that is created from a function.
///
/// The function signature should match: `Fn(&State, &Action) -> DispatchOp<State, Action>`
pub struct FnReducer<F, State, Action>
where
    F: Fn(&State, &Action) -> DispatchOp<State, Action>,
    State: Send + Sync + Clone,
    Action: Send + Sync + Clone + 'static,
{
    func: F,
    _marker: std::marker::PhantomData<(State, Action)>,
}

impl<F, State, Action> Reducer<State, Action> for FnReducer<F, State, Action>
where
    F: Fn(&State, &Action) -> DispatchOp<State, Action>,
    State: Send + Sync + Clone,
    Action: Send + Sync + Clone + 'static,
{
    fn reduce(&self, state: &State, action: &Action) -> DispatchOp<State, Action> {
        (self.func)(state, action)
    }
}

impl<F, State, Action> From<F> for FnReducer<F, State, Action>
where
    F: Fn(&State, &Action) -> DispatchOp<State, Action>,
    State: Send + Sync + Clone,
    Action: Send + Sync + Clone + 'static,
{
    fn from(func: F) -> Self {
        Self {
            func,
            _marker: std::marker::PhantomData,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::subscriber::Subscriber;
    use crate::StoreBuilder;
    use std::sync::{Arc, Mutex};
    use std::thread;

    struct TestSubscriber {
        state_changes: Arc<Mutex<Vec<i32>>>,
    }

    impl Subscriber<i32, i32> for TestSubscriber {
        fn on_notify(&self, state: &i32, _action: &i32) {
            self.state_changes.lock().unwrap().push(*state);
        }
    }

    #[test]
    fn test_store_continues_after_reducer_panic() {
        // given

        // A reducer that panics on specific action value
        struct PanicOnValueReducer {
            panic_on: i32,
        }

        impl Reducer<i32, i32> for PanicOnValueReducer {
            fn reduce(&self, state: &i32, action: &i32) -> DispatchOp<i32, i32> {
                if *action == self.panic_on {
                    // Catch the panic and return current state
                    let result = std::panic::catch_unwind(|| {
                        panic!("Intentional panic on action {}", action);
                    });
                    // keep state if panic
                    if result.is_err() {
                        return DispatchOp::Keep(state.clone(), vec![]);
                    }
                }
                // Normal operation for other actions
                DispatchOp::Dispatch(state + action, vec![])
            }
        }

        // Create store with our test reducer
        let reducer = Box::new(PanicOnValueReducer { panic_on: 42 });
        let store = StoreBuilder::new_with_reducer(0, reducer).build().unwrap();

        // Track state changes
        let state_changes = Arc::new(Mutex::new(Vec::new()));
        let state_changes_clone = state_changes.clone();

        let subscriber = Arc::new(TestSubscriber {
            state_changes: state_changes_clone,
        });
        store.add_subscriber(subscriber).unwrap();

        // then
        // Test sequence of actions
        store.dispatch(1).unwrap(); // Should work: 0 -> 1
        store.dispatch(42).unwrap(); // Should panic but be caught: stays at 1
        store.dispatch(2).unwrap(); // Should work: 1 -> 3

        // Give time for all actions to be processed
        match store.stop() {
            Ok(_) => println!("store stopped"),
            Err(e) => {
                panic!("store stop failed  : {:?}", e);
            }
        }

        // then
        // Verify final state
        assert_eq!(store.get_state(), 3);
        // Verify state change history
        let changes = state_changes.lock().unwrap();
        assert_eq!(&*changes, &vec![1, 3]); // Should only have non-panic state changes
    }

    #[test]
    fn test_multiple_reducers_continue_after_panic() {
        // given
        struct PanicReducer;
        struct NormalReducer;

        impl Reducer<i32, i32> for PanicReducer {
            fn reduce(&self, state: &i32, action: &i32) -> DispatchOp<i32, i32> {
                let result = std::panic::catch_unwind(|| {
                    panic!("Always panic!");
                });
                // keep state if panic
                if result.is_err() {
                    return DispatchOp::Keep(state.clone(), vec![]);
                }
                DispatchOp::Dispatch(state + action, vec![])
            }
        }

        impl Reducer<i32, i32> for NormalReducer {
            fn reduce(&self, state: &i32, action: &i32) -> DispatchOp<i32, i32> {
                DispatchOp::Dispatch(state + action, vec![])
            }
        }

        // Create store with both reducers
        let store = StoreBuilder::new(0)
            .with_reducer(Box::new(PanicReducer))
            .add_reducer(Box::new(NormalReducer))
            .build()
            .unwrap();

        // when
        // Dispatch actions
        store.dispatch(1).unwrap();
        store.dispatch(2).unwrap();

        match store.stop() {
            Ok(_) => println!("store stopped"),
            Err(e) => {
                panic!("store stop failed  : {:?}", e);
            }
        }

        // then
        // Even though PanicReducer panics, NormalReducer should still process actions
        assert_eq!(store.get_state(), 3);
    }

    #[test]
    fn test_fn_reducer_basic() {
        // given
        let reducer = FnReducer::from(|state: &i32, action: &i32| {
            DispatchOp::Dispatch(state + action, vec![])
        });
        let store = StoreBuilder::new_with_reducer(0, Box::new(reducer)).build().unwrap();

        // when
        store.dispatch(5).unwrap();
        store.dispatch(3).unwrap();
        match store.stop() {
            Ok(_) => println!("store stopped"),
            Err(e) => {
                panic!("store stop failed  : {:?}", e);
            }
        }

        // then
        assert_eq!(store.get_state(), 8); // 0 + 5 + 3 = 8
    }

    #[test]
    fn test_fn_reducer_with_effect() {
        // given
        #[derive(Clone, Debug)]
        enum Action {
            AddWithEffect(i32),
            Add(i32),
        }

        let reducer = FnReducer::from(|state: &i32, action: &Action| {
            match action {
                Action::AddWithEffect(i) => {
                    let new_state = state + i;
                    let effect = Effect::Action(Action::Add(40)); // Effect that adds 40 more
                    DispatchOp::Dispatch(new_state, vec![effect])
                }
                Action::Add(i) => {
                    let new_state = state + i;
                    DispatchOp::Dispatch(new_state, vec![])
                }
            }
        });
        let store = StoreBuilder::new_with_reducer(0, Box::new(reducer)).build().unwrap();

        // when
        store.dispatch(Action::AddWithEffect(2)).unwrap();
        thread::sleep(std::time::Duration::from_millis(1000)); // Wait for effect to be processed
        match store.stop() {
            Ok(_) => println!("store stopped"),
            Err(e) => {
                panic!("store stop failed  : {:?}", e);
            }
        }

        // then
        // Initial state(0) + action(2) + effect(40) = 42
        assert_eq!(store.get_state(), 42);
    }

    #[test]
    fn test_fn_reducer_keep_state() {
        // given
        let reducer = FnReducer::from(|state: &i32, action: &i32| {
            if *action < 0 {
                // Keep current state for negative actions
                DispatchOp::Keep(state.clone(), vec![])
            } else {
                DispatchOp::Dispatch(state + action, vec![])
            }
        });
        let store = StoreBuilder::new_with_reducer(0, Box::new(reducer)).build().unwrap();

        // Track state changes
        let state_changes = Arc::new(Mutex::new(Vec::new()));
        let state_changes_clone = state_changes.clone();

        let subscriber = Arc::new(TestSubscriber {
            state_changes: state_changes_clone,
        });
        store.add_subscriber(subscriber).unwrap();

        // when
        store.dispatch(5).unwrap(); // Should change state
        store.dispatch(-3).unwrap(); // Should keep state
        store.dispatch(2).unwrap(); // Should change state
        match store.stop() {
            Ok(_) => println!("store stopped"),
            Err(e) => {
                panic!("store stop failed  : {:?}", e);
            }
        }

        // then
        assert_eq!(store.get_state(), 7); // 0 + 5 + 2 = 7
        let changes = state_changes.lock().unwrap();
        assert_eq!(&*changes, &vec![5, 7]); // Only two state changes should be recorded
    }

    #[test]
    fn test_multiple_fn_reducers() {
        // given
        let add_reducer = FnReducer::from(|state: &i32, action: &i32| {
            DispatchOp::Dispatch(state + action, vec![])
        });
        let double_reducer =
            FnReducer::from(|state: &i32, _action: &i32| DispatchOp::Dispatch(state * 2, vec![]));

        let store = StoreBuilder::new(0)
            .with_reducer(Box::new(add_reducer))
            .add_reducer(Box::new(double_reducer))
            .build()
            .unwrap();

        // when
        store.dispatch(3).unwrap(); // (((0)  +3) *2) = 6
        store.dispatch(15).unwrap(); // (((6) +15) *2) = 42
        match store.stop() {
            Ok(_) => println!("store stopped"),
            Err(e) => {
                panic!("store stop failed  : {:?}", e);
            }
        }

        // then
        assert_eq!(store.get_state(), 42);
    }
}