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
use HashMap;
use Arc;
use Event;
use crate;
/// ResolveMapping is a trait that defines the mapping of event types to their respective handlers.
///
/// ## Example
/// ```rust
/// # use async_trait::async_trait;
/// # use serde::{Deserialize, Serialize};
/// # use nitinol_core::errors::{DeserializeError, SerializeError};
/// # use nitinol_core::event::Event;
/// # use nitinol_resolver::resolver::ResolveHandler;
/// #
/// # pub struct Entity;
/// #
/// # #[derive(Debug, Deserialize, Serialize)]
/// # pub enum EntityEvent {}
/// #
/// # impl Event for EntityEvent {
/// # const EVENT_TYPE: &'static str = "entity-event";
/// #
/// # fn as_bytes(&self) -> Result<Vec<u8>, SerializeError> {
/// # Ok(serde_json::to_vec(self)?)
/// # }
/// # fn from_bytes(bytes: &[u8]) -> Result<Self, DeserializeError> {
/// # Ok(serde_json::from_slice(bytes)?)
/// # }
/// # }
/// #
/// # pub struct Subscribe;
/// #
/// # #[async_trait]
/// # pub trait SubscribeHandler<E: Event>: 'static + Sync + Send + Sized {
/// # type Rejection: std::fmt::Debug + Sync + Send + 'static;
/// # async fn on(&mut self, event: E) -> Result<(), Self::Rejection>;
/// # }
/// #
/// # #[async_trait]
/// # impl<E: Event, T> ResolveHandler<E, T> for Subscribe
/// # where
/// # T: SubscribeHandler<E>,
/// # {
/// # const HANDLER_TYPE: &'static str = "subscribe";
/// # type Error = T::Rejection;
/// #
/// # async fn apply(entity: &mut Option<T>, event: E) -> Result<(), Self::Error> {
/// # let Some(entity) = entity else {
/// # panic!("Entity must exist in this process.");
/// # };
/// #
/// # entity.on(event).await?;
/// #
/// # Ok(())
/// # }
/// # }
/// #
/// use nitinol_resolver::mapping::{Mapper, ResolveMapping};
///
/// #[async_trait]
/// impl SubscribeHandler<EntityEvent> for Entity {
/// type Rejection = String;
/// async fn on(&mut self, event: EntityEvent) -> Result<(), Self::Rejection> {
/// // something process...
/// Ok(())
/// }
/// }
///
/// impl ResolveMapping for Entity {
/// fn mapping(mapper: &mut Mapper<Self>) {
/// // Register the event type and its handler
/// // This `Subscribe` shown as an example points out a compile error,
/// // if the above `SubscribeHandler` is not implemented for the Entity type.
/// mapper.register::<EntityEvent, Subscribe>();
/// }
/// }
/// ```