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
#[doc(hidden)] pub use ::tokio;
#[doc(hidden)] pub use ::futures;
#[doc(hidden)] pub use ::log;
#[doc(hidden)] pub use ::crossbeam;
#[doc(hidden)] pub use ::async_trait;
#[doc(hidden)] pub use ::async_channel;
#[doc(hidden)] pub use ::anyhow;
#[doc(hidden)] pub use ::downcast_rs;

// only visible to other vin crates
pub mod detail;
use detail::*;

use downcast_rs::{Downcast, DowncastSync};
use async_trait::async_trait;
use std::{
    sync::atomic::Ordering,
    time::Duration
};
use tokio::sync::{
    RwLockReadGuard, 
    RwLockWriteGuard, 
    futures::Notified,
};

/// Actor lifecycle states.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum State {
    Pending,
    Starting,
    Running,
    Closing,
    Closed,
}

impl Default for State {
    fn default() -> Self {
        Self::Pending
    }
}

/// Trait indicating that the type is a message.
pub trait Message: Downcast + Send {
    type Result: std::fmt::Debug + Send;
    type Error: std::fmt::Debug + Send;
}
downcast_rs::impl_downcast!(Message assoc Result, Error);

/// Handler for specifying message handling logic.
#[async_trait]
pub trait Handler<M: Message> {
    async fn handle(&self, msg: M) -> Result<M::Result, M::Error>;
}

/// A restricted interface of `Actor` that provides send mechanics and state reads.
#[async_trait]
pub trait Addr: DowncastSync + Sync {

    /// Sends a typed message to the actor.
    async fn send<M: Message>(&self, msg: M)
        where
            Self: Sized + Forwarder<M>;

    /// Sends a typed message to the actor and awaits the result.
    #[must_use]
    async fn send_and_wait<M: Message>(&self, msg: M) -> Result<M::Result, M::Error>
        where
            Self: Sized + Forwarder<M>;

    /// Returns the current state of the actor.
    /// 
    /// # Warning
    /// Beware of potential races, given that the state can be changed after you fetched it.
    fn state(&self) -> State;

    /// Closes the actor and gives the actor time to process the already-queued up 
    /// messages.
    fn close(&self);
    
    /// Returns this actor's close future.
    fn close_future(&self) -> Notified<'_>;

    /// Returns the id of the actor.
    fn id(&self) -> String;

    /// Checks if the actor has been started.
    fn is_started(&self) -> bool {
        self.state() != State::Pending && self.state() != State::Closed
    }

    /// Checks if the actor is closed.
    fn is_closed(&self) -> bool {
        self.state() == State::Closed
    }
}
downcast_rs::impl_downcast!(sync Addr);

/// Actor trait that all generic (non-specialized) actors must implement.
/// 
/// # Usage
/// Implementation is generated by the [`vin::actor`] proc macro.
/// 
/// # Behind the scenes
/// The way actors work in [`vin`] is that they live in their own [`tokio`] task, polling messages sent 
/// and starting handler tasks for each message received. Shutdown is also synchronized and actors 
/// will be given time to gracefully shutdown before being forcibly closed.
#[async_trait]
pub trait Actor: Addr {
    type Context;

    /// Returns a read lock to the underlying actor context.
    #[must_use]
    async fn ctx(&self) -> RwLockReadGuard<Self::Context>;

    /// Returns a write lock to the underlying actor context.
    #[must_use]
    async fn ctx_mut(&self) -> RwLockWriteGuard<Self::Context>;

    /// Creates and starts an actor with the given id (if available) and context.
    #[must_use]
    async fn start<Id: Into<ActorId> + Send>(id: Id, ctx: Self::Context) -> Result<StrongAddr<Self>, ActorStartError>;
}

/// Actor id type for the actor registry.
pub type ActorId = std::borrow::Cow<'static, str>;

/// A strong typed reference to the spawned actor.
pub type StrongAddr<A> = std::sync::Arc<A>;

/// A weak typed reference to the spawned actor.
pub type WeakAddr<A> = std::sync::Weak<A>;

/// A strong erased reference to the spawned actor.
pub type StrongErasedAddr = std::sync::Arc<dyn Addr>;

/// A weak erased reference to the spawned actor.
pub type WeakErasedAddr = std::sync::Weak<dyn Addr>;

/// Sends a shutdown signal to all actors.
pub fn shutdown() {
    SHUTDOWN_SIGNAL.notify_waiters();
}

/// Registers a shutdown future.
/// 
/// Useful in loops aside from the main actor loops to cancel activities.
/// 
/// # Example
/// Pseudo Rust code to get the point across.
/// 
/// ```ignore
/// let shutdown = vin::shutdown_future();
/// tokio::pin!(shutdown);
/// 
/// loop {
///     tokio::select! {
///         msg = tcp_stream.read() => {
///             ...
///         },
///         ...
///         _ = &mut shutdown => {
///             info!("Received shutdown signal.");
///             break;
///         },
///     }
/// }
/// ```
pub fn shutdown_future<'a>() -> Notified<'a> {
    SHUTDOWN_SIGNAL.notified()
}

/// Registers an actor in the actor counter.
pub fn add_actor() {
    ACTORS_ALIVE.fetch_add(1, Ordering::Release);
}

/// Unregisters an actor in the actor counter.
pub fn remove_actor() {
    ACTORS_ALIVE.fetch_sub(1, Ordering::Release);
}

/// Waits for all actors to shutdown gracefully.
pub async fn wait_for_shutdowns() {
    while ACTORS_ALIVE.load(Ordering::Acquire) != 0 {
        tokio::time::sleep(Duration::from_millis(500)).await;
    }
}

/// Error returned by the actor query functions.
#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
pub enum ActorQueryError {
    #[error("actor has expired and is either closing or closed")]
    Expired,

    #[error("actor is not found in the registry")]
    NotFound,

    #[error("invalid type of actor queried")]
    InvalidType,
}

/// Error returned by `start()`.
#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
#[error("actor id already taken")]
pub struct ActorStartError;

/// Queries a typed actor from the registry.
pub async fn query_actor<A: Addr, Id: Into<ActorId>>(id: Id) -> Result<StrongAddr<A>, ActorQueryError> {
    let id = id.into();
    let addr = query_actor_erased(id).await?;
    let addr = if let Ok(addr) = addr.downcast_arc::<A>() {
        addr
    } else {
        return Err(ActorQueryError::InvalidType);
    };

    Ok(addr)
}

/// Queries an erased actor from the registry.
pub async fn query_actor_erased<Id: Into<ActorId>>(id: Id) -> Result<StrongErasedAddr, ActorQueryError> {
    let id = id.into();
    let reg = REGISTRY.lock().await;
    let addr = reg.get(id.as_ref());
    let addr = match addr {
        Some(addr) => if let Some(addr) = addr.upgrade() {
            if addr.is_closed() {
                return Err(ActorQueryError::Expired);
            } else {
                addr
            }
        } else {
            return Err(ActorQueryError::Expired);
        },
        None => {
            return Err(ActorQueryError::NotFound);
        },
    };

    Ok(addr)
}

/// Sends a typed message to an actor with the corresponding id.
pub async fn send<A, Id, M>(actor_id: Id, msg: M) -> Result<(), ActorQueryError>
where
    Id: Into<ActorId>,
    M: Message,
    A: Addr + Forwarder<M>
{
    let id = actor_id.into();
    let addr = query_actor::<A, _>(id).await?;
    addr.send(msg).await;

    Ok(())
}

/// Sends a typed message to an actor with the corresponding id.
#[must_use]
pub async fn send_and_wait<A, Id, M>(actor_id: Id, msg: M) -> Result<Result<M::Result, M::Error>, ActorQueryError>
where
    Id: Into<ActorId>,
    M: Message,
    A: Addr + Forwarder<M>
{
    let id = actor_id.into();
    let addr = query_actor::<A, _>(id).await?;
    Ok(addr.send_and_wait(msg).await)
}

/// Used to call arbitrary code on state changes.
/// 
/// ## Example
/// ```rust
/// #[derive(Debug, Clone)]
/// enum Message {
///     Foo,
///     Bar,
/// }
/// 
/// #[vin::actor]
/// #[vin::handles(Message)]
/// struct MyActor;
/// 
/// #[async_trait]
/// impl vin::Hooks for MyActor {
///     async fn on_started(&self) {
///         println!("Started!");
///     }
/// }
/// ```
#[async_trait]
pub trait Hooks {
    async fn on_started(&self) {}
    async fn on_closed(&self) {}
}

/// Actor trait that all generic (non-specialized) actors must implement.
#[async_trait]
pub trait TaskActor: Task + TaskAddr {
    /// Creates and starts a task actor with the given id (if available) and context.
    async fn start<Id: Into<ActorId> + Send>(id: Id, ctx: Self::Context) -> StrongAddr<Self>;
}

/// A restricted interface of `TaskActor` that provides closing and state reads.
pub trait TaskAddr {
    /// Sends a close signal to the task actor.
    fn close(&self);
    
    /// Returns this task actor's close future.
    fn close_future(&self) -> Notified<'_>;

    /// Returns the state of the task actor.
    fn state(&self) -> State;

    /// Returns the id of the task actor.
    fn id(&self) -> String;

    /// Returns if the task actor is closed.
    fn is_closed(&self) -> bool {
        self.state() == State::Closed
    }
}

/// Used to call arbitrary code on a task actor.
#[async_trait]
pub trait Task: TaskContextTrait {
    /// Task function being executed.
    async fn task(&self, ctx: Self::Context) -> anyhow::Result<()>;
}

/// Private trait used by [`Task`] implementations to have access 
/// to the context associated type.
pub trait TaskContextTrait {
    /// The task's context type.
    type Context;
}