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
use crate::Dispatcher;

/// Represents a side effect that can be executed.
///
/// `Effect` is used to encapsulate actions that should be performed as a result of a state change.
/// an effect can be either simple function or more complex thunk that require a dispatcher.
pub enum Effect<Action> {
    /// An action that should be dispatched.
    Action(Action),
    /// A task which will be executed asynchronously.
    Task(Box<dyn FnOnce() + Send>),
    /// A task that takes the dispatcher as an argument.
    Thunk(Box<dyn FnOnce(Box<dyn Dispatcher<Action>>) + Send>),
    /// A function which has a result.
    /// The result is an Any type which can be downcasted to the expected type,
    /// It is useful when you want to produce an effect without any dependency of 'store'
    ///
    /// ### Caution
    /// The result default ignored, if you want to get the result of the function,
    /// you can use a middleware like `TestEffectMiddleware`
    Function(String, EffectFunction),
}

pub type EffectResult = Result<Box<dyn std::any::Any>, Box<dyn std::error::Error>>;
pub type EffectFunction = Box<dyn FnOnce() -> EffectResult + Send>;

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        DispatchOp, MiddlewareFn, MiddlewareFnFactory, Reducer, StoreBuilder, StoreError,
        Subscriber,
    };
    use std::sync::{Arc, Mutex};
    use std::thread;
    use std::time::Duration;

    // Test state and actions for Effect tests
    #[derive(Debug, Clone, PartialEq)]
    struct TestState {
        value: i32,
        messages: Vec<String>,
    }

    impl Default for TestState {
        fn default() -> Self {
            TestState {
                value: 0,
                messages: Vec::new(),
            }
        }
    }

    #[derive(Debug, Clone)]
    enum TestAction {
        SetValue(i32),
        AddValue(i32),
        AddMessage(String),
        AsyncTask,
        ThunkTask(i32),
        FunctionTask,
    }

    // Test reducer that produces different types of effects
    struct TestReducer;

    impl Reducer<TestState, TestAction> for TestReducer {
        fn reduce(
            &self,
            state: &TestState,
            action: &TestAction,
        ) -> crate::DispatchOp<TestState, TestAction> {
            match action {
                TestAction::SetValue(value) => {
                    let new_state = TestState {
                        value: *value,
                        messages: state.messages.clone(),
                    };
                    // Effect::Action - dispatch another action
                    let effect =
                        Effect::Action(TestAction::AddMessage(format!("Set to {}", value)));
                    crate::DispatchOp::Dispatch(new_state, vec![effect])
                }
                TestAction::AddValue(value) => {
                    let new_state = TestState {
                        value: state.value + value,
                        messages: state.messages.clone(),
                    };
                    crate::DispatchOp::Dispatch(new_state, vec![])
                }
                TestAction::AddMessage(msg) => {
                    let mut new_messages = state.messages.clone();
                    new_messages.push(msg.clone());
                    let new_state = TestState {
                        value: state.value,
                        messages: new_messages,
                    };
                    crate::DispatchOp::Dispatch(new_state, vec![])
                }
                TestAction::AsyncTask => {
                    let new_state = TestState {
                        value: state.value,
                        messages: state.messages.clone(),
                    };
                    // Effect::Task - simple async task
                    let effect = Effect::Task(Box::new(|| {
                        thread::sleep(Duration::from_millis(10));
                    }));
                    crate::DispatchOp::Dispatch(new_state, vec![effect])
                }
                TestAction::ThunkTask(value) => {
                    let new_state = TestState {
                        value: state.value,
                        messages: state.messages.clone(),
                    };
                    // Effect::Thunk - task that uses dispatcher
                    let value_clone = *value; // Clone the value to avoid lifetime issues
                    let effect = Effect::Thunk(Box::new(move |dispatcher| {
                        thread::sleep(Duration::from_millis(10));
                        let _ = dispatcher.dispatch(TestAction::AddValue(value_clone));
                    }));
                    crate::DispatchOp::Dispatch(new_state, vec![effect])
                }
                TestAction::FunctionTask => {
                    let new_state = TestState {
                        value: state.value,
                        messages: state.messages.clone(),
                    };
                    // Effect::Function - function that returns a result
                    // key == test-key
                    let key = "test-key".to_string();
                    let effect = Effect::Function(
                        key.clone(),
                        Box::new(move || {
                            thread::sleep(Duration::from_millis(10));
                            Ok(Box::new(format!("Result for {}", key)) as Box<dyn std::any::Any>)
                        }),
                    );
                    crate::DispatchOp::Dispatch(new_state, vec![effect])
                }
            }
        }
    }

    // Test subscriber to track state changes
    #[derive(Default)]
    struct TestSubscriber {
        states: Arc<Mutex<Vec<TestState>>>,
        actions: Arc<Mutex<Vec<TestAction>>>,
    }

    impl Subscriber<TestState, TestAction> for TestSubscriber {
        fn on_notify(&self, state: &TestState, action: &TestAction) {
            self.states.lock().unwrap().push(state.clone());
            self.actions.lock().unwrap().push(action.clone());
        }
    }

    impl TestSubscriber {
        fn get_states(&self) -> Vec<TestState> {
            self.states.lock().unwrap().clone()
        }

        fn get_actions(&self) -> Vec<TestAction> {
            self.actions.lock().unwrap().clone()
        }
    }

    #[test]
    fn test_effect_action() {
        // Test Effect::Action - simple action dispatch
        println!("Testing Effect::Action");

        let store = StoreBuilder::new_with_reducer(TestState::default(), Box::new(TestReducer))
            .with_name("test-action-effect".into())
            .build()
            .unwrap();

        let subscriber = Arc::new(TestSubscriber::default());
        store.add_subscriber(subscriber.clone()).unwrap();

        // Dispatch action that produces Effect::Action
        store.dispatch(TestAction::SetValue(42)).unwrap();

        // Wait for effect to be processed
        thread::sleep(Duration::from_millis(100));

        // Stop store to ensure all effects are processed
        store.stop().unwrap();

        let states = subscriber.get_states();
        let actions = subscriber.get_actions();

        // Should have received the initial state and the SetValue action
        assert!(states.len() >= 1);
        assert!(actions.len() >= 1);

        // The last state should have value 42
        assert_eq!(states.last().unwrap().value, 42);

        // Should have received both SetValue and AddMessage actions
        assert!(actions.iter().any(|a| matches!(a, TestAction::SetValue(42))));
        assert!(actions.iter().any(|a| matches!(a, TestAction::AddMessage(_))));

        println!("Effect::Action test passed");
    }

    #[test]
    fn test_effect_task() {
        // Test Effect::Task - async task execution
        println!("Testing Effect::Task");

        let store = StoreBuilder::new_with_reducer(TestState::default(), Box::new(TestReducer))
            .with_name("test-task-effect".into())
            .build()
            .unwrap();

        let subscriber = Arc::new(TestSubscriber::default());
        store.add_subscriber(subscriber.clone()).unwrap();

        // Dispatch action that produces Effect::Task
        store.dispatch(TestAction::AsyncTask).unwrap();

        // Wait for effect to be processed
        thread::sleep(Duration::from_millis(100));

        // Stop store to ensure all effects are processed
        store.stop().unwrap();

        let actions = subscriber.get_actions();

        // Should have received the AsyncTask action
        assert!(actions.iter().any(|a| matches!(a, TestAction::AsyncTask)));

        println!("Effect::Task test passed");
    }

    #[test]
    fn test_effect_thunk() {
        // Test Effect::Thunk - task that uses dispatcher
        println!("Testing Effect::Thunk");

        let store = StoreBuilder::new_with_reducer(TestState::default(), Box::new(TestReducer))
            .with_name("test-thunk-effect".into())
            .build()
            .unwrap();

        let subscriber = Arc::new(TestSubscriber::default());
        store.add_subscriber(subscriber.clone()).unwrap();

        // Dispatch action that produces Effect::Thunk
        store.dispatch(TestAction::ThunkTask(10)).unwrap();

        // Wait for effect to be processed
        thread::sleep(Duration::from_millis(100));

        // Stop store to ensure all effects are processed
        store.stop().unwrap();

        let states = subscriber.get_states();
        let actions = subscriber.get_actions();

        // Should have received the ThunkTask action
        assert!(actions.iter().any(|a| matches!(a, TestAction::ThunkTask(10))));

        // The thunk should have dispatched AddValue action
        assert!(actions.iter().any(|a| matches!(a, TestAction::AddValue(10))));

        // Final state should have value 10
        assert_eq!(states.last().unwrap().value, 10);

        println!("Effect::Thunk test passed");
    }

    struct TestEffectMiddleware;
    impl TestEffectMiddleware {
        fn new() -> Self {
            Self {}
        }
    }
    impl MiddlewareFnFactory<TestState, TestAction> for TestEffectMiddleware {
        fn create(
            &self,
            inner: MiddlewareFn<TestState, TestAction>,
        ) -> MiddlewareFn<TestState, TestAction> {
            Arc::new(move |state: &TestState, action: &TestAction| {
                // inner
                let result: Result<DispatchOp<TestState, TestAction>, StoreError> =
                    inner(state, action);

                // effects 를 순회하면서 function 을 변환
                let (need_to_dispatch, state, effects) = match result {
                    Ok(DispatchOp::Dispatch(state, effects)) => (true, state, effects),
                    Ok(DispatchOp::Keep(state, effects)) => (false, state, effects),
                    Err(e) => {
                        return Err(e);
                    }
                };

                // convert function effect to task effect if key is "test-key"
                let new_effects: Vec<Effect<TestAction>> = effects
                    .into_iter()
                    .map(|effect| match effect {
                        Effect::Function(key, function) => {
                            if key == "test-key" {
                                // convert the function to task or thunk as you want, here we use task
                                return Effect::Task(Box::new(move || {
                                    let result = function();
                                    // result for 'test-key'should be Box<String>
                                    match result {
                                        Ok(result) => {
                                            let result_string: Box<String> =
                                                result.downcast().unwrap();
                                            println!("result_string: {:?}", result_string);
                                            assert_eq!(
                                                result_string.to_string(),
                                                "Result for test-key".to_string()
                                            );
                                        }
                                        Err(e) => {
                                            assert!(false, "result should be Ok: {:?}", e);
                                        }
                                    }
                                }));
                            } else {
                                return Effect::Function(key, function);
                            }
                        }
                        Effect::Action(action) => {
                            return Effect::Action(action);
                        }
                        Effect::Task(task) => {
                            return Effect::Task(task);
                        }
                        Effect::Thunk(thunk) => {
                            return Effect::Thunk(thunk);
                        }
                    })
                    .collect();

                if need_to_dispatch {
                    Ok(DispatchOp::Dispatch(state, new_effects))
                } else {
                    Ok(DispatchOp::Keep(state, new_effects))
                }
            })
        }
    }

    #[test]
    fn test_effect_function() {
        // Test Effect::Function - function that returns a result
        println!("Testing Effect::Function");

        let store = StoreBuilder::new_with_reducer(TestState::default(), Box::new(TestReducer))
            .with_name("test-function-effect".into())
            .with_middleware(Arc::new(TestEffectMiddleware::new()))
            .build()
            .unwrap();

        let subscriber = Arc::new(TestSubscriber::default());
        store.add_subscriber(subscriber.clone()).unwrap();

        // Dispatch action that produces Effect::Function
        store.dispatch(TestAction::FunctionTask).unwrap();

        // Wait for effect to be processed
        thread::sleep(Duration::from_millis(100));

        // Stop store to ensure all effects are processed
        store.stop().unwrap();

        let actions = subscriber.get_actions();

        // Should have received the FunctionTask action
        assert!(actions.iter().any(|a| matches!(a, TestAction::FunctionTask)));

        println!("Effect::Function test passed");
    }

    #[test]
    fn test_effect_chain() {
        // Test chaining multiple effects
        println!("Testing Effect chaining");

        let store = StoreBuilder::new_with_reducer(TestState::default(), Box::new(TestReducer))
            .with_name("test-effect-chain".into())
            .build()
            .unwrap();

        let subscriber = Arc::new(TestSubscriber::default());
        store.add_subscriber(subscriber.clone()).unwrap();

        // Dispatch multiple actions with effects
        store.dispatch(TestAction::SetValue(5)).unwrap();
        store.dispatch(TestAction::ThunkTask(3)).unwrap();
        store.dispatch(TestAction::AsyncTask).unwrap();

        // Wait for all effects to be processed
        thread::sleep(Duration::from_millis(200));

        // Stop store to ensure all effects are processed
        store.stop().unwrap();

        let actions = subscriber.get_actions();

        // Should have multiple actions
        assert!(actions.len() >= 3);

        // Should have SetValue, ThunkTask, and AsyncTask
        assert!(actions.iter().any(|a| matches!(a, TestAction::SetValue(5))));
        assert!(actions.iter().any(|a| matches!(a, TestAction::ThunkTask(3))));
        assert!(actions.iter().any(|a| matches!(a, TestAction::AsyncTask)));

        // Should have AddValue from thunk
        assert!(actions.iter().any(|a| matches!(a, TestAction::AddValue(3))));

        // Should have AddMessage from SetValue effect
        assert!(actions.iter().any(|a| matches!(a, TestAction::AddMessage(_))));

        println!("Effect chaining test passed");
    }
}