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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
use tokio::sync::mpsc::{channel, Receiver, Sender};
use log::*;

use crate::event_handler::{EventHandler, OutputEvent, Completion};
use crate::event_retriever::PayloadRetriever;
use crate::completion_handler::CompletionHandler;
use crate::consumer::Consumer;
use std::fmt::Debug;

use std::marker::PhantomData;
use aktors::actor::Actor;
use async_trait::async_trait;

#[derive(Copy, Clone, Debug)]
pub enum ProcessorState {
    Started,
    Waiting,
    Complete,
}

#[derive(Clone)]
pub struct EventProcessor<M, C, EH, Input, Output, ER, CH>
    where
        M: Send + Clone + Sync + 'static,
        C: Consumer<M> + Clone + Send + Sync + 'static,
        EH: EventHandler<InputEvent=Input, OutputEvent=Output> + Send + Sync + Clone + 'static,
        Input: Send + Clone + 'static,
        Output: Send + Sync + Clone + 'static,
        ER: PayloadRetriever<Input, Message=M> + Send + Sync + Clone + 'static,
        CH: CompletionHandler<Message=M, CompletedEvent=OutputEvent<Output, <EH as EventHandler>::Error>> + Send + Sync + Clone + 'static,
{
    consumer: C,
    completion_handler: CH,
    event_retriever: ER,
    event_handler: EH,
    state: ProcessorState,
    self_actor: Option<EventProcessorActor<M>>,
}

impl<M, C, EH, Input, Output, ER, CH> EventProcessor<M, C, EH, Input, Output, ER, CH>
    where
        M: Send + Clone + Sync + 'static,
        C: Consumer<M> + Clone + Send + Sync + 'static,
        EH: EventHandler<InputEvent=Input, OutputEvent=Output> + Send + Sync + Clone + 'static,
        Input: Send + Clone + 'static,
        Output: Send + Sync + Clone + 'static,
        ER: PayloadRetriever<Input, Message=M> + Send + Sync + Clone + 'static,
        CH: CompletionHandler<Message=M, CompletedEvent=OutputEvent<Output, <EH as EventHandler>::Error>> + Send + Sync + Clone + 'static,
{
    pub fn new(
        consumer: C,
        completion_handler: CH,
        event_handler: EH,
        event_retriever: ER,
    ) -> Self {
        Self {
            consumer,
            completion_handler,
            event_handler,
            event_retriever,
            state: ProcessorState::Waiting,
            self_actor: None,
        }
    }
}

impl<M, C, EH, Input, Output, ER, CH> EventProcessor<M, C, EH, Input, Output, ER, CH>
    where
        M: Send + Clone + Sync + 'static,
        C: Consumer<M> + Clone + Send + Sync + 'static,
        EH: EventHandler<InputEvent=Input, OutputEvent=Output> + Send + Sync + Clone + 'static,
        Input: Send + Clone + 'static,
        Output: Send + Sync + Clone + 'static,
        ER: PayloadRetriever<Input, Message=M> + Send + Sync + Clone + 'static,
        CH: CompletionHandler<Message=M, CompletedEvent=OutputEvent<Output, <EH as EventHandler>::Error>> + Send + Sync + Clone + 'static,

{
    pub async fn process_event(&mut self, event: M) {
        // TODO: Handle errors
        info!("Processing event");
        let retrieved_event = match self.event_retriever.retrieve_event(&event).await {
            Ok(retrieved_event) => {
                info!("Retrieved event");
                Some(retrieved_event)
            },
            Err(e) => {
                warn!("Failed to retrieve event with: {:?}", e);
                None
                // TODO: Retry
                // TODO: We could reset the message visibility to 0 so it gets picked up again?
            }
        };

        if let Some(retrieved_event) = retrieved_event {
            info!("Handling retrieved event");
            let output_event = self.event_handler.handle_event(retrieved_event).await;
            self.completion_handler.mark_complete(event, output_event).await;
        }

        info!("self.processor_state {:?}", self.state);
        if let ProcessorState::Started = self.state {
            info!("Getting next event");
            self.consumer
                .get_next_event(self.self_actor.clone().expect("event_processor, self_actor")).await;
        }
    }

    pub async fn start_processing(&mut self) {
        self.state = ProcessorState::Started;

        info!("Getting next event from consumer");
        self.consumer
            .get_next_event(self.self_actor.clone().unwrap()).await;
    }

    pub fn stop_processing(&mut self) {
        info!("stop_processing");
        self.state = ProcessorState::Complete;
    }
}

#[allow(non_camel_case_types)]
pub enum EventProcessorMessage<M>
    where
        M: Send + Clone + Sync + 'static,
{
    process_event { event: M },
    start_processing {},
    stop_processing {},
    release
}

impl<M> aktors::actor::Message for EventProcessorMessage<M>
    where
        M: Send + Clone + Sync + 'static,
{
    fn is_release(&self) -> bool {
        if let Self::release = self {
            true
        } else {
            false
        }
    }
}

#[async_trait]
impl<M, C, EH, Input, Output, ER, CH> Actor<EventProcessorMessage<M>> for EventProcessor<M, C, EH, Input, Output, ER, CH>
    where
        M: Send + Clone + Sync + 'static,
        C: Consumer<M> + Clone + Send + Sync + 'static,
        EH: EventHandler<InputEvent=Input, OutputEvent=Output> + Send + Sync + Clone + 'static,
        Input: Send + Clone + 'static,
        Output: Send + Sync + Clone + 'static,
        ER: PayloadRetriever<Input, Message=M> + Send + Sync + Clone + 'static,
        CH: CompletionHandler<Message=M, CompletedEvent=OutputEvent<Output, <EH as EventHandler>::Error>> + Send + Sync + Clone + 'static,
{
    async fn route_message(&mut self, msg: EventProcessorMessage<M>) {
        match msg {
            EventProcessorMessage::process_event { event } => self.process_event(event).await,
            EventProcessorMessage::start_processing {} => self.start_processing().await,
            EventProcessorMessage::stop_processing {} => self.stop_processing(),
            EventProcessorMessage::release => ()
        };
    }

    fn get_actor_name(&self) -> &str {
        &self.self_actor.as_ref().unwrap().actor_name
    }

    fn close(&mut self) {
        self.self_actor = None;
    }
}

pub struct EventProcessorActor<M>
    where
        M: Send + Clone + Sync + 'static,
{
    sender: Sender<EventProcessorMessage<M>>,
    inner_rc: std::sync::Arc<std::sync::atomic::AtomicUsize>,
    queue_len: std::sync::Arc<std::sync::atomic::AtomicUsize>,
    actor_name: String,
    actor_uuid: uuid::Uuid,
    actor_num: usize,
}

impl<M> Clone for EventProcessorActor<M>
    where
        M: Send + Clone + Sync + 'static,
{
    fn clone(&self) -> Self {
        self.inner_rc.clone().fetch_add(1, std::sync::atomic::Ordering::SeqCst);

        Self {
            sender: self.sender.clone(),
            inner_rc: self.inner_rc.clone(),
            queue_len: self.queue_len.clone(),
            actor_name: format!(
                "{} {} {}",
                stringify!(EventProcessorActor),
                self.actor_uuid,
                self.actor_num + 1,
            ),
            actor_uuid: self.actor_uuid,
            actor_num: self.actor_num + 1,
        }
    }
}

impl<M> EventProcessorActor<M>
    where
        M: Send + Clone + Sync + 'static,
{
    pub fn new<C, EH, Input, Output, ER, CH>(mut actor_impl: EventProcessor<M, C, EH, Input, Output, ER, CH>) -> (Self, tokio::task::JoinHandle<()>)
        where
            C: Consumer<M> + Clone + Send + Sync + 'static,
            EH: EventHandler<InputEvent=Input, OutputEvent=Output> + Send + Sync + Clone + 'static,
            Input: Send + Clone + 'static,
            Output: Send + Sync + Clone + 'static,
            ER: PayloadRetriever<Input, Message=M> + Send + Sync + Clone + 'static,
            CH: CompletionHandler<Message=M, CompletedEvent=OutputEvent<Output, <EH as EventHandler>::Error>> + Send + Sync + Clone + 'static,
    {
        let (sender, receiver) = channel(1);
        let inner_rc = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(1));
        let queue_len = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));

        let actor_uuid = uuid::Uuid::new_v4();
        let actor_name = format!(
            "{} {} {}",
            stringify!(EventProcessor),
            actor_uuid,
            0,
        );
        let inner_actor = Self {
            sender,
            inner_rc: inner_rc.clone(),
            queue_len: queue_len.clone(),
            actor_name,
            actor_uuid,
            actor_num: 0,
        };

        let self_actor = inner_actor.clone();

        actor_impl.self_actor = Some(inner_actor);

        let handle = tokio::task::spawn(
            aktors::actor::route_wrapper(
                aktors::actor::Router::new(
                    actor_impl,
                    receiver,
                    inner_rc,
                    queue_len
                )
            )
        );

        (self_actor, handle)
    }

    pub async fn release(self) {
        let msg = EventProcessorMessage::release;

        let mut sender = self.sender.clone();

        let queue_len = self.queue_len.clone();
        queue_len.fetch_add(1, std::sync::atomic::Ordering::SeqCst);

        tokio::task::spawn(
            async move {
                sender.send(msg).await;
            }
        );
    }

    pub async fn process_event(&self, event: M) {
        let msg = EventProcessorMessage::process_event { event };

        let mut sender = self.sender.clone();

        let queue_len = self.queue_len.clone();
        queue_len.fetch_add(1, std::sync::atomic::Ordering::SeqCst);

        tokio::task::spawn(
            async move {
                if let Err(e) = sender.send(msg).await {
                    panic!(
                        concat!(
                            "Receiver has failed with {}, propagating error. ",
                            "EventProcessorActor.process_event"
                        ),
                        e
                    )
                }
            }
        );
    }

    pub async fn start_processing(&self) {
        let msg = EventProcessorMessage::start_processing {};

        let mut sender = self.sender.clone();

        let queue_len = self.queue_len.clone();
        queue_len.fetch_add(1, std::sync::atomic::Ordering::SeqCst);

        tokio::task::spawn(
            async move {
                if let Err(e) = sender.send(msg).await {
                    panic!(
                        concat!(
                            "Receiver has failed with {}, propagating error. ",
                            "EventProcessorActor.start_processing"
                        ),
                        e
                    )
                }
            }
        );
    }

    pub async fn stop_processing(&self) {
        let msg = EventProcessorMessage::stop_processing {};

        let mut sender = self.sender.clone();

        let queue_len = self.queue_len.clone();

        queue_len.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
        tokio::task::spawn(
            async move {
                if let Err(e) = sender.send(msg).await {
                    panic!(
                        concat!(
                            "Receiver has failed with {}, propagating error. ",
                            "EventProcessorActor.stop_processing"
                        ),
                        e
                    )
                }
            }
        );
    }
}

impl<M> Drop for EventProcessorActor<M>
    where
        M: Send + Clone + Sync + 'static,
{
    fn drop(&mut self) {
        self.inner_rc.clone().fetch_sub(1, std::sync::atomic::Ordering::SeqCst);
    }
}