crb_agent/message/
event.rs

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
use crate::address::{Address, MessageFor};
use crate::agent::Agent;
use crate::context::Context;
use anyhow::{Error, Result};
use async_trait::async_trait;
use crb_send::Recipient;

impl<A: Agent> Address<A> {
    pub fn event<E>(&self, event: E) -> Result<()>
    where
        A: OnEvent<E>,
        E: Send + 'static,
    {
        self.send(Event::new(event))
    }

    pub fn recipient<E>(&self) -> Recipient<E>
    where
        A: OnEvent<E>,
        E: Send + 'static,
    {
        Recipient::new(self.clone()).reform(Event::new)
    }
}

impl<A: Agent> Context<A> {
    pub fn event<E>(&self, event: E) -> Result<()>
    where
        A: OnEvent<E>,
        E: Send + 'static,
    {
        self.address().event(event)
    }

    pub fn recipient<E>(&self) -> Recipient<E>
    where
        A: OnEvent<E>,
        E: Send + 'static,
    {
        self.address().recipient()
    }
}

/// Do not introduce tags: use event wrapper instead.
#[async_trait]
pub trait OnEvent<E>: Agent {
    // TODO: Add when RFC 192 will be implemented (associated types defaults)
    // type Error: Into<Error> + Send + 'static;

    async fn handle(&mut self, event: E, ctx: &mut Context<Self>) -> Result<()>;

    async fn fallback(&mut self, err: Error, _ctx: &mut Context<Self>) -> Result<()> {
        Err(err)
    }
}

pub struct Event<E> {
    event: E,
}

impl<E> Event<E> {
    pub fn new(event: E) -> Self {
        Self { event }
    }
}

#[async_trait]
impl<A, E> MessageFor<A> for Event<E>
where
    A: OnEvent<E>,
    E: Send + 'static,
{
    async fn handle(self: Box<Self>, agent: &mut A, ctx: &mut Context<A>) -> Result<()> {
        if let Err(err) = agent.handle(self.event, ctx).await {
            agent.fallback(err, ctx).await
        } else {
            Ok(())
        }
    }
}