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
//! **Cached process lookups with [lunatic](https://crates.io/crates/lunatic).**
//!
//! When a process is lookup, it is cached in the local process to avoid unnecessery future lookups.
//! This is useful for globally registered processes and abstract processes.
//!
//! # Example
//!
//! ```
//! use lunatic::{spawn_link, test};
//! use lunatic_cached_process::{cached_process, CachedLookup};
//!
//! cached_process! {
//!     static COUNTER_PROCESS: Process<()> = "counter-process";
//! }
//!
//! let process = spawn_link!(|mailbox: Mailbox<()>| { loop { } });
//! process.register("counter-process");
//!
//! let lookup: Option<Process<T>> = COUNTER_PROCESS.get(); // First call will lookup process from lunatic runtime
//! assert!(lookup.is_some());
//!
//! let lookup: Option<Process<T>> = COUNTER_PROCESS.get(); // Subsequent calls will use cached lookup
//! assert!(lookup.is_some());
//! ```

use std::cell::RefCell;

use lunatic::{process::ProcessRef, serializer::Bincode, Process, ProcessLocal};
use serde::{Deserialize, Serialize};

/// This is used internally for the cached_process! macro.
#[doc(hidden)]
pub use paste::paste;

pub type ProcessCached<'a, T, S = Bincode> = CachedProcess<'a, Process<T, S>>;
pub type ProcessRefCached<'a, T> = CachedProcess<'a, ProcessRef<T>>;

/// Cached process to avoid looking up a global process multiple times.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct CachedProcess<'a, T> {
    // TODO: Replace with `Cell` when lunatic gets a new version where `ProcessRef` is `Copy`.
    lookup_state: RefCell<LookupState<T>>,
    process_name: &'a str,
}

impl<'a, T> CachedProcess<'a, T> {
    /// Construct a new process cache with a registered process name.
    pub fn new(name: &'a str) -> Self {
        CachedProcess {
            lookup_state: RefCell::new(LookupState::NotLookedUp),
            process_name: name,
        }
    }

    /// Returns the process name.
    pub fn process_name(&'a self) -> &'a str {
        self.process_name
    }

    /// Returns true if the process has been looked up and exists.
    ///
    /// # Example
    ///
    /// ```
    /// use lunatic::Process;
    ///
    /// let process: CachedProcess<'static, Process<()>> = CachedProcess::new("foo");
    /// assert!(!process.is_present()); // Initially not present
    ///
    /// process.get();
    /// assert!(!process.is_present()); // Not present, even after lookup
    ///
    /// spawn!(|| { loop { /* ... */ } }).register("foo"); // Start a process called "foo"
    ///
    /// process.reset();
    /// process.get();
    /// assert!(process.is_present()); // Is present
    /// ```
    pub fn is_present(&'a self) -> bool {
        matches!(&*self.lookup_state.borrow(), LookupState::Present(_))
    }

    /// Returns true if the process has been looked up, regardless if the process was found.
    ///
    /// # Example
    ///
    /// ```
    /// use lunatic::Process;
    ///
    /// let process: CachedProcess<'static, Process<()>> = CachedProcess::new("");
    /// assert!(!process.is_looked_up());
    ///
    /// process.get();
    /// assert!(process.is_looked_up());
    /// ```
    pub fn is_looked_up(&'a self) -> bool {
        matches!(&*self.lookup_state.borrow(), LookupState::NotLookedUp)
    }
}

/// Trait for accessing a static process local cache.
pub trait CachedLookup<'a, T> {
    /// Looks up a process by its name, and caches the result.
    /// Subsequent calls will used the cached value.
    fn get(&'a self) -> Option<T>;

    /// Sets the cached lookup. This will prevent any lookups from being made,
    /// since subsequent calls to [`CachedLookup::get`] will return this cached value.
    fn set(&'a self, value: T);

    /// Resets the cache, causing the next call to [`CachedLookup::get`] to lookup the process again.
    fn reset(&'a self);
}

impl<T, S> CachedLookup<'static, Process<T, S>> for ProcessLocal<ProcessCached<'_, T, S>> {
    #[inline]
    fn get(&'static self) -> Option<Process<T, S>> {
        self.with(|proc| lookup(proc, |name| Process::lookup(name)))
    }

    #[inline]
    fn set(&'static self, value: Process<T, S>) {
        self.with(|proc| CachedLookup::set(proc, value))
    }

    #[inline]
    fn reset(&'static self) {
        self.with(CachedLookup::reset)
    }
}

impl<T, S> CachedLookup<'static, Process<T, S>> for ProcessCached<'_, T, S> {
    #[inline]
    fn get(&'static self) -> Option<Process<T, S>> {
        lookup(self, |name| Process::lookup(name))
    }

    #[inline]
    fn set(&'static self, value: Process<T, S>) {
        *self.lookup_state.borrow_mut() = LookupState::Present(value);
    }

    #[inline]
    fn reset(&'static self) {
        *self.lookup_state.borrow_mut() = LookupState::NotLookedUp;
    }
}

impl<T> CachedLookup<'static, ProcessRef<T>> for ProcessLocal<ProcessRefCached<'_, T>> {
    #[inline]
    fn get(&'static self) -> Option<ProcessRef<T>> {
        self.with(|proc| lookup(proc, |name| ProcessRef::lookup(name)))
    }

    #[inline]
    fn set(&'static self, value: ProcessRef<T>) {
        self.with(|proc| CachedLookup::set(proc, value))
    }

    #[inline]
    fn reset(&'static self) {
        self.with(CachedLookup::reset)
    }
}

impl<T> CachedLookup<'static, ProcessRef<T>> for ProcessRefCached<'_, T> {
    #[inline]
    fn get(&'static self) -> Option<ProcessRef<T>> {
        lookup(self, |name| ProcessRef::lookup(name))
    }

    #[inline]
    fn set(&'static self, value: ProcessRef<T>) {
        *self.lookup_state.borrow_mut() = LookupState::Present(value);
    }

    #[inline]
    fn reset(&'static self) {
        *self.lookup_state.borrow_mut() = LookupState::NotLookedUp;
    }
}

/// Macro for defining a process local lookup cache for processes.
///
/// The structure is as follows:
///
/// ```
/// static <ident>: <process_type> = <process_name>;
/// ```
///
/// Where
///
/// - `<ident>`: Static variable name.
/// - `<process_type>`: Either `Process<T>`, `ProcessRef<T>`, or `Process<T, S>` where `T` is the message type, and `S` is the serializer.
/// - `<process_name>`: The string literal of the process name.
///
/// # Examples
///
/// Cached [`lunatic::Process`].
///
/// ```
/// use lunatic_cached_process::cached_process;
/// use serde::{Serialize, Deserialize};
///
/// cached_process! {
///     static COUNTER: Process<CountMessage> = "global-counter-process";
/// }
///
/// #[derive(Serialize, Deserialize)]
/// enum CountMessage {
///     Inc,
///     Dec,
/// }
/// ```
///
/// Cached [`lunatic::process::ProcessRef`].
///
/// ```
/// use lunatic_cached_process::cached_process;
///
/// cached_process! {
///     static COUNTER: ProcessRef<CounterProcess> = "global-counter-process-ref";
/// }
///
/// struct CounterProcess;
///
/// impl lunatic::process::AbstractProcess for CounterProcess {
///     type Arg = ();
///     type State = Self;
/// }
/// ```
#[macro_export]
macro_rules! cached_process {
    (
        $(
            $(#[$attr:meta])* $vis:vis static $ident:ident : $process_type:ident <$ty:ty $( , $s:ty )?> = $name:tt ;
        )+
    ) => {
        $crate::paste! {
            $(
                lunatic::process_local! {
                    $(#[$attr])* $vis static $ident: $crate:: [<$process_type Cached>] <'static, $ty $( , $s )?> = $crate::CachedProcess::new($name);
                }
            )+
        }
    };
}

#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, Serialize, Deserialize)]
enum LookupState<T> {
    NotLookedUp,
    NotPresent,
    Present(T),
}

impl<T> Default for LookupState<T> {
    fn default() -> Self {
        LookupState::NotLookedUp
    }
}

#[inline]
fn lookup<'a, F, T>(proc: &'a CachedProcess<T>, f: F) -> Option<T>
where
    F: Fn(&'a str) -> Option<T>,
    T: Clone,
{
    let proc_ref = proc.lookup_state.borrow();
    match &*proc_ref {
        LookupState::NotLookedUp => {
            std::mem::drop(proc_ref);
            match f(proc.process_name) {
                Some(process) => {
                    *proc.lookup_state.borrow_mut() = LookupState::Present(process.clone()); // TODO: Replace clone with copy
                    Some(process)
                }
                None => {
                    *proc.lookup_state.borrow_mut() = LookupState::NotPresent;
                    None
                }
            }
        }
        LookupState::NotPresent => None,
        LookupState::Present(process) => {
            Some(process.clone()) // TODO: Replace clone with copy
        }
    }
}