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
//! This module contains `Address` to interact with an `Actor`.

use crate::{
    Action, ActionHandler, ActionPerformer, ActionRecipient, Actor, Controller, Envelope, Id,
    Interaction, InteractionHandler, InteractionRecipient,
};
use anyhow::Error;
use derive_more::{Deref, DerefMut};
use futures::channel::mpsc;
use futures::{SinkExt, Stream, StreamExt};
use std::fmt;
use std::hash::{Hash, Hasher};
use tokio::task::JoinHandle;

/// `Address` to send messages to `Actor`.
///
/// Can be compared each other to identify senders to
/// the same `Actor`.
#[derive(Deref, DerefMut)]
pub struct Address<A: Actor> {
    #[deref]
    #[deref_mut]
    controller: Controller,
    msg_tx: mpsc::Sender<Envelope<A>>,
}

impl<A: Actor> Into<Controller> for Address<A> {
    fn into(self) -> Controller {
        self.controller
    }
}

impl<A: Actor> Clone for Address<A> {
    fn clone(&self) -> Self {
        Self {
            controller: self.controller.clone(),
            msg_tx: self.msg_tx.clone(),
        }
    }
}

impl<A: Actor> fmt::Debug for Address<A> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        // TODO: Id cloned here. Fix!
        f.debug_tuple("Address")
            .field(&self.controller.id())
            .finish()
    }
}

impl<A: Actor> PartialEq for Address<A> {
    fn eq(&self, other: &Self) -> bool {
        self.controller.eq(&other.controller)
    }
}

impl<A: Actor> Eq for Address<A> {}

impl<A: Actor> Hash for Address<A> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.controller.hash(state);
    }
}

impl<A: Actor> Address<A> {
    pub(crate) fn new(controller: Controller, msg_tx: mpsc::Sender<Envelope<A>>) -> Self {
        Self { controller, msg_tx }
    }

    /// **Internal method.** Use `action` or `interaction` instead.
    /// It sends `Message` wrapped with `Envelope` to `Actor`.
    pub(crate) async fn send(&mut self, msg: Envelope<A>) -> Result<(), Error> {
        self.msg_tx.send(msg).await.map_err(Error::from)
    }

    /// Forwards the stream into a flow of events to an `Actor`.
    async fn forward<S>(id: Id, mut stream: S, mut recipient: ActionRecipient<S::Item>)
    where
        A: ActionHandler<S::Item>,
        S: Stream + Unpin,
        S::Item: Action,
    {
        while let Some(action) = stream.next().await {
            if let Err(err) = recipient.act(action).await {
                log::error!(
                    "Can't send an event to {:?} form a background stream: {}. Breaking...",
                    id,
                    err
                );
                break;
            }
        }
    }

    /// Attaches a `Stream` of event to an `Actor`.
    pub fn attach<S>(&mut self, stream: S) -> JoinHandle<()>
    where
        A: ActionHandler<S::Item>,
        S: Stream + Send + Unpin + 'static,
        S::Item: Action,
    {
        let recipient = self.action_recipient();
        let id = self.controller.id();
        let fut = Self::forward(id, stream, recipient);
        tokio::spawn(fut)
    }

    /// Generates `ActionRecipient`.
    pub fn action_recipient<I>(&self) -> ActionRecipient<I>
    where
        A: ActionHandler<I>,
        I: Action,
    {
        ActionRecipient::from(self.clone())
    }

    /// Generates `InteractionRecipient`.
    pub fn interaction_recipient<I>(&self) -> InteractionRecipient<I>
    where
        A: InteractionHandler<I>,
        I: Interaction,
    {
        InteractionRecipient::from(self.clone())
    }

    /// Gives a `Controller` of that entity.
    pub fn controller(&self) -> Controller {
        self.controller.clone()
    }
}