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
use std::ops::{Deref, DerefMut};
use std::rc::Rc;
use std::sync::mpsc::{channel, Receiver, RecvError, SendError, Sender, TryRecvError};
use std::sync::{Mutex, PoisonError};
use std::thread::JoinHandle;

/// A store is a thing that manages mutations for a given state based on actions.
///
/// If you know redux: This is like redux but without middleware (yet).
///
/// # Types
/// A: The Action of the Store
/// S: The State of the Store
///
/// # Examples
/// ```rust
///
/// #[macro_use]
/// extern crate lazy_static;
///
///
/// use std::rc::Rc;
/// use std::sync::Mutex;
///
/// use gstore::store::{ combine_reducers, Store, LifecycleAction };
///
///
/// #[derive(Debug, Clone)]
/// struct State {
///    count: u32,
/// }
///
/// #[derive(Debug, Clone, Eq, PartialEq)]
/// enum Action {
///     Increment,
///     Decrement,
///     Startup,
///     Shutdown,
/// }
///
/// impl LifecycleAction for Action {
///     fn is_stop(&self) -> bool {
///         self == &Action::Shutdown
///     }
///     fn is_start(&self) -> bool {
///         self == &Action::Startup
///     }
/// }
///
/// lazy_static! {
///     static ref STATE: Mutex<State> = Mutex::new(State { count: 0 });
/// }
///
/// fn main() {
///     let mutex = Mutex::new(State { count: 0 });
///     let store: Rc<Store<Action, State>> = Rc::new(Store::new(&STATE));
///     let join = combine_reducers(store.clone(), &STATE, |action, state| match action {
///         Action::Increment => State {
///             count: state.count + 1,
///         },
///         Action::Decrement => State {
///          count: state.count - 1,
///         },
///         _ => state,
///     });
///     store.send(Action::Increment);
///     store.send(Action::Increment);
///     store.send(Action::Increment);
///     store.send(Action::Decrement);
///     store.send(Action::Shutdown);
///     join.join().unwrap().expect("Error during Store handling.");
///     assert_eq!(STATE.lock().unwrap().count, 2);
/// }
/// ```
///
pub struct Store<A, S>
where
    A: LifecycleAction + Send + Clone + Eq + PartialEq + 'static,
    S: Send + Clone + 'static,
{
    sender: Sender<A>,
    // Sender for ui actions
    receiver: Receiver<A>,
    // receiver of ui actions
    send_to_background: std::cell::Cell<Option<Sender<A>>>,
    // Sender for background actions
    state: &'static Mutex<S>,
    callbacks: Mutex<Vec<Box<dyn Fn(A, &S) + 'static>>>,
}

impl<A, S> Store<A, S>
where
    A: LifecycleAction + Send + Clone + Eq + PartialEq + 'static,
    S: Send + Clone + 'static,
{
    /// Creates a new state.
    ///
    /// Creates a new state with the reference to the static State mutex.
    pub fn new(state: &'static Mutex<S>) -> Self {
        let (sender, receiver) = channel();
        Store {
            sender,
            receiver,
            state,
            send_to_background: std::cell::Cell::new(None),
            callbacks: Mutex::new(Vec::new()),
        }
    }

    /// Sends the given `Action` to the store.
    ///
    /// This will trigger the reducers as well as notify all receivers (after the reducers) to
    /// handle the state change.
    pub fn send(&self, action: A) {
        if let Some(sender) = self.send_to_background.take() {
            match sender.send(action) {
                Ok(_) => self.send_to_background.set(Some(sender)),
                Err(e) => eprintln!("Could not send event: {:?}", e),
            }
        } else {
            eprintln!("Could not send event to background thread. No backgroun thread has been connected.")
        }
    }

    /// Registers the callback in the store.
    ///
    /// # Arguments
    /// callback: A closure which receives a sent `Action` and the `State` **after** the reducers
    /// were applied.
    pub fn receive(&self, callback: impl Fn(A, &S) + 'static) {
        match self.callbacks.lock() {
            Ok(mut cb) => {
                cb.deref_mut().push(Box::new(callback));
            }
            Err(_) => {}
        }
    }

    /// Send the given action from the ui thread.
    ///
    /// May only be used in the connected UI thread handler.
    pub fn ui_send(&self, action: A) {
        match self.callbacks.lock() {
            Ok(callbacks_lock) => match self.state.lock() {
                Ok(state) => {
                    for callback in callbacks_lock.deref() {
                        callback(action.clone(), state.deref());
                    }
                }
                Err(_) => {}
            },
            Err(_) => {}
        }
    }

    /// Tries to receive an Action from the Store.
    ///
    /// May only be used in the connected UI thread handler.
    pub fn ui_try_receive(&self) -> Result<A, TryRecvError> {
        self.receiver.try_recv()
    }

    // Returns a sender to the store (ui thread) and a receiver for the background thread.
    // Saves a sender to the background thread in self.connection
    fn connect(&self) -> (Sender<A>, Receiver<A>) {
        let (s, r) = channel();
        self.send_to_background.set(Some(s.clone()));
        (self.sender.clone(), r)
    }
}

/// Actions need to implement this trait so gstore can determine whether to notify, when the
/// application was started or stopped.
pub trait LifecycleAction {
    // return true for the action indicating that the application may be stopped.
    fn is_stop(&self) -> bool;
    // return true for the action indicating that the application was started.
    fn is_start(&self) -> bool;
}

/// Represents all possible runtime errors of the Store.
///
/// Those are either: RecvErrors or SendErrors of the internally used channel or PoisonErrors when
/// accessing the State mutex fails.
#[derive(Debug)]
pub struct StoreError {
    message: String,
    cause: String,
}

impl StoreError {
    pub fn message(&self) -> &str {
        &self.message
    }
    pub fn cause(&self) -> &str {
        &self.cause
    }
}

impl From<RecvError> for StoreError {
    fn from(re: RecvError) -> Self {
        StoreError {
            message: "Error in gstores channel communication.".to_string(),
            cause: format!("RecvError: {}", re),
        }
    }
}

impl<T> From<SendError<T>> for StoreError {
    fn from(re: SendError<T>) -> Self {
        StoreError {
            message: "Error in gstores channel communication.".to_string(),
            cause: format!("SendError: {}", re),
        }
    }
}

impl<T> From<PoisonError<T>> for StoreError {
    fn from(e: PoisonError<T>) -> Self {
        StoreError {
            message: "".to_string(),
            cause: format!("{:?}", e),
        }
    }
}

/// Applies the given reducer to the store.
pub fn combine_reducers<A, S>(
    store: Rc<Store<A, S>>,
    state: &'static Mutex<S>,
    reducer: impl Fn(A, S) -> S + Send + 'static,
) -> JoinHandle<Result<(), StoreError>>
where
    A: LifecycleAction + Send + Clone + Eq + PartialEq + 'static,
    S: Send + Clone + 'static,
{
    let (send_to_ui, receiver_in_background_thread) = store.connect();
    return std::thread::spawn(move || {
        loop {
            let action = receiver_in_background_thread.recv()?;
            let mut state = state.lock()?;
            *state = reducer(action.clone(), state.clone());
            send_to_ui.send(action.clone())?;
            if action.is_stop() {
                break;
            }
        }
        return Ok(());
    });
}

#[cfg(test)]
mod tests {
    use std::rc::Rc;
    use std::sync::Mutex;

    use crate::store::{combine_reducers, LifecycleAction, Store};

    #[derive(Debug, Clone)]
    struct State {
        count: u32,
    }

    #[derive(Debug, Clone, Eq, PartialEq)]
    enum Action {
        Increment,
        Decrement,
        Startup,
        Shutdown,
    }

    impl LifecycleAction for Action {
        fn is_stop(&self) -> bool {
            self == &Action::Shutdown
        }

        fn is_start(&self) -> bool {
            self == &Action::Shutdown
        }
    }

    lazy_static! {
        static ref STATE: Mutex<State> = Mutex::new(State { count: 0 });
    }

    #[test]
    fn test_counter() {
        let store: Rc<Store<Action, State>> = Rc::new(Store::new(&STATE));
        let handle = combine_reducers(store.clone(), &STATE, |action, state| match action {
            Action::Increment => State {
                count: state.count + 1,
            },
            Action::Decrement => State {
                count: state.count - 1,
            },
            Action::Shutdown => state,
            Action::Startup => state,
        });

        store.send(Action::Startup);
        store.send(Action::Increment);
        store.send(Action::Increment);
        store.send(Action::Increment);
        store.send(Action::Decrement);

        store.send(Action::Shutdown);
        handle.join().unwrap().expect("Could not join thread.");

        assert_eq!(STATE.lock().unwrap().count, 2);
    }
}