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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
//! An entity manager task handles the lifecycle and routing of messages for
//! an entity type. One EntityManager per entity type.
//! The EntityManager will generally instantiate the entities on demand, i.e. when first
//! message is sent to a specific entity. It will passivate least used
//! entities to have a bounded number of entities in memory.
//! The entities will recover their state from a stream of events.

use async_trait::async_trait;
use chrono::DateTime;
use chrono::Utc;
use log::debug;
use log::warn;
use lru::LruCache;
use std::future::Future;
use std::hash::BuildHasher;
use std::io;
use std::num::NonZeroUsize;
use std::pin::Pin;
use tokio::sync::mpsc;
use tokio::sync::mpsc::Receiver;
use tokio_stream::{Stream, StreamExt};

use crate::entity::Context;
use crate::entity::EventSourcedBehavior;
use crate::{EntityId, Message};

/// An envelope wraps an event associated with a specific entity.
#[derive(Clone, Debug, PartialEq)]
pub struct EventEnvelope<E> {
    /// Flags whether the associated event is to be considered
    /// as one that represents an entity instance being deleted.
    pub deletion_event: bool,
    pub entity_id: EntityId,
    pub seq_nr: u64,
    pub event: E,
    pub timestamp: DateTime<Utc>,
}

impl<E> EventEnvelope<E> {
    pub fn new<EI>(entity_id: EI, seq_nr: u64, timestamp: DateTime<Utc>, event: E) -> Self
    where
        EI: Into<EntityId>,
    {
        Self {
            deletion_event: false,
            entity_id: entity_id.into(),
            event,
            seq_nr,
            timestamp,
        }
    }
}

/// Sources events, in form of event envelopes, to another type of envelope e.g. those
/// that can be sourced using a storage technology.
#[async_trait]
pub trait SourceProvider<E> {
    /// Produce an initial source of events, which is called upon an entity
    /// manager task starting up. Any error from this method is considered fatal
    /// and will terminate the entity manager.
    async fn source_initial(
        &mut self,
    ) -> io::Result<Pin<Box<dyn Stream<Item = EventEnvelope<E>> + Send + 'async_trait>>>;

    /// Produce a source of events. An entity id
    /// is passed to the source method so that the source is
    /// discriminate regarding the entity events to supply.
    async fn source(
        &mut self,
        entity_id: &EntityId,
    ) -> io::Result<Pin<Box<dyn Stream<Item = EventEnvelope<E>> + Send + 'async_trait>>>;
}

/// Handles events, in form of event envelopes, to another type of envelope e.g. those
/// that can be persisted using a storage technology.
#[async_trait]
pub trait Handler<E> {
    /// Consume an envelope, performing some processing
    /// e.g. persisting an envelope, and then returning the same envelope
    /// if all went well.
    async fn process(&mut self, envelope: EventEnvelope<E>) -> io::Result<EventEnvelope<E>>;
}

// An opaque type internal to the library. The type records the public and private
// state of an entity in the context of the entity manager and friends.
#[derive(Default)]
struct EntityStatus<S> {
    pub(crate) state: S,
    pub(crate) last_seq_nr: u64,
}

/// An internal structure for the purposes of operating on the cache of entities.
pub trait EntityOps<B>
where
    B: EventSourcedBehavior,
{
    fn get(&mut self, entity_id: &EntityId) -> Option<&B::State>;
    fn update(&mut self, envelope: EventEnvelope<B::Event>) -> u64;
}

struct EntityLruCache<A, S>
where
    S: BuildHasher,
{
    cache: LruCache<EntityId, EntityStatus<A>, S>,
}

impl<B, S> EntityOps<B> for EntityLruCache<B::State, S>
where
    B: EventSourcedBehavior + Send + Sync + 'static,
    B::State: Default,
    S: BuildHasher,
{
    fn get(&mut self, entity_id: &EntityId) -> Option<&<B as EventSourcedBehavior>::State> {
        self.cache.get(entity_id).map(|status| &status.state)
    }

    fn update(&mut self, envelope: EventEnvelope<<B as EventSourcedBehavior>::Event>) -> u64 {
        update_entity::<B, S>(&mut self.cache, envelope)
    }
}

/// Provides an asynchronous task and a command channel that can run and drive an entity manager.
///
/// Entity managers manage the lifecycle of entities given a specific behavior.
/// They are established given an adapter of persistent events associated
/// with an entity type. That source is consumed by subsequently telling
/// the entity manager to run, generally on its own task. Events are persisted by
/// calling on the adapter's handler.
///
/// Commands are sent to a channel established for the entity manager.
/// Effects may be produced as a result of performing a command, which may,
/// in turn, perform side effects and yield events.
///
/// * `command_capacity` declares size of the command channel and will panic at runtime if zero.
/// * `entity_capacity` declares size of the number of entities to cache in memory at one time,
/// and will panic at runtime if zero.
pub fn task<A, B>(
    behavior: B,
    adapter: A,
    command_capacity: usize,
    entity_capacity: usize,
) -> (
    impl Future<Output = io::Result<()>>,
    mpsc::Sender<Message<B::Command>>,
)
where
    B: EventSourcedBehavior + Send + Sync + 'static,
    B::Command: Send,
    B::State: Send + Sync,
    A: SourceProvider<B::Event> + Handler<B::Event> + Send + 'static,
{
    let (sender, receiver) = mpsc::channel(command_capacity);
    (
        task_with_hasher(
            behavior,
            adapter,
            receiver,
            entity_capacity,
            lru::DefaultHasher::default(),
        ),
        sender,
    )
}

/// Provides an asynchronous task and a command channel that can run and drive an entity manager.
///
/// Entity managers manage the lifecycle of entities given a specific behavior.
/// They are established given an adapter of persistent events associated
/// with an entity type. That source is consumed by subsequently telling
/// the entity manager to run, generally on its own task. Events are persisted by
/// calling on the adapter's handler.
///
/// Commands are sent to a channel established for the entity manager.
/// Effects may be produced as a result of performing a command, which may,
/// in turn, perform side effects and yield events.
///
/// A hasher for entity ids can also be supplied which will be used to control the
/// internal caching of entities.
///
/// * `entity_capacity` declares size of the number of entities to cache in memory at one time,
/// and will panic at runtime if zero.
pub async fn task_with_hasher<A, B, S>(
    behavior: B,
    mut adapter: A,
    mut receiver: Receiver<Message<B::Command>>,
    entity_capacity: usize,
    hash_builder: S,
) -> io::Result<()>
where
    B: EventSourcedBehavior + Send + Sync + 'static,
    B::Command: Send,
    B::State: Send + Sync,
    A: SourceProvider<B::Event> + Handler<B::Event> + Send + 'static,
    S: BuildHasher + Send + Sync,
{
    // Source our initial events and populate our internal entities map.

    let mut entities = EntityLruCache {
        cache: LruCache::with_hasher(NonZeroUsize::new(entity_capacity).unwrap(), hash_builder),
    };

    let envelopes = adapter.source_initial().await?;

    {
        tokio::pin!(envelopes);
        while let Some(envelope) = envelopes.next().await {
            update_entity::<B, S>(&mut entities.cache, envelope);
        }
        for (entity_id, entity_status) in entities.cache.iter() {
            let context = Context { entity_id };
            behavior
                .on_recovery_completed(&context, &entity_status.state)
                .await;
        }
        behavior.on_initial_recovery_completed().await;
    }

    // Receive commands for the entities and process them.

    while let Some(message) = receiver.recv().await {
        // Source entity if we don't have it.

        let mut entity_status = entities.cache.get(&message.entity_id);

        if entity_status.is_none() {
            let envelopes = adapter.source(&message.entity_id).await?;

            tokio::pin!(envelopes);
            while let Some(envelope) = envelopes.next().await {
                update_entity::<B, S>(&mut entities.cache, envelope);
            }
            entity_status = entities.cache.get(&message.entity_id);
            let context = Context {
                entity_id: &message.entity_id,
            };
            behavior
                .on_recovery_completed(
                    &context,
                    &entity_status
                        .unwrap_or(&EntityStatus::<B::State>::default())
                        .state,
                )
                .await;
        }

        // Given an entity, send it the command, possibly producing an effect.
        // Effects may persist events that will update state on success.

        let context = Context {
            entity_id: &message.entity_id,
        };
        let (mut effect, mut last_seq_nr) = if let Some(entity_status) = entity_status {
            let effect = B::for_command(&context, &entity_status.state, message.command);
            let last_seq_nr = entity_status.last_seq_nr;
            (effect, last_seq_nr)
        } else {
            let entity_status = EntityStatus::<B::State>::default();
            let effect = B::for_command(&context, &entity_status.state, message.command);
            let last_seq_nr = entity_status.last_seq_nr;
            (effect, last_seq_nr)
        };
        let result = effect
            .process(
                &behavior,
                &mut adapter,
                &mut entities,
                context.entity_id,
                &mut last_seq_nr,
                Ok(()),
            )
            .await;
        if result.is_err() {
            warn!(
                "An error occurred when processing an effect for {}. Result: {result:?} Evicting it.",
                context.entity_id
            );
            entities.cache.pop(context.entity_id);
        }
    }

    Ok(())
}

fn update_entity<B, S>(
    entities: &mut LruCache<EntityId, EntityStatus<B::State>, S>,
    envelope: EventEnvelope<B::Event>,
) -> u64
where
    B: EventSourcedBehavior + Send + Sync + 'static,
    B::State: Default,
    S: BuildHasher,
{
    if !envelope.deletion_event {
        // Apply an event to state, creating the entity entry if necessary.
        let context = Context {
            entity_id: &envelope.entity_id,
        };
        let entity_state = if let Some(entity_state) = entities.get_mut(&envelope.entity_id) {
            entity_state.last_seq_nr = envelope.seq_nr;
            entity_state
        } else {
            debug!("Inserting new entity: {}", envelope.entity_id);

            // We're avoiding the use of get_or_insert so that we can avoid
            // cloning the entity id unless necessary.
            entities.push(
                envelope.entity_id.clone(),
                EntityStatus::<B::State> {
                    state: B::State::default(),
                    last_seq_nr: envelope.seq_nr,
                },
            );
            entities.get_mut(&envelope.entity_id).unwrap()
        };
        B::on_event(&context, &mut entity_state.state, envelope.event);
    } else {
        debug!("Removing entity: {}", envelope.entity_id);

        entities.pop(&envelope.entity_id);
    }
    envelope.seq_nr
}

#[cfg(test)]
mod tests {
    use std::{future, io, pin::Pin, sync::Arc};

    use super::*;
    use crate::{
        effect::{persist_deletion_event, persist_event, reply, unhandled, Effect, EffectExt},
        entity::Context,
    };
    use async_trait::async_trait;
    use test_log::test;
    use tokio::sync::{mpsc, oneshot, Notify};
    use tokio_stream::Stream;

    // Declare an entity behavior. We do this by declaring state, commands, events and then the
    // behavior itself. For our example, we are going to share a notifier object with our
    // behavior so that we can illustrate how things from outside can be passed in. This becomes
    // useful when needing to perform side-effects e.g. communicating with a sensor via a
    // connection over MODBUS, or sending something on a socket etc.

    #[derive(Default)]
    struct TempState {
        registered: bool,
        temp: u32,
    }

    enum TempCommand {
        Deregister,
        GetTemperature { reply_to: oneshot::Sender<u32> },
        Register,
        UpdateTemperature { temp: u32 },
    }

    #[derive(Clone, Debug, PartialEq)]
    enum TempEvent {
        Deregistered,
        Registered,
        TemperatureUpdated { temp: u32 },
    }

    struct TempSensorBehavior {
        recovered_1: Arc<Notify>,
        recovered_2: Arc<Notify>,
        updated: Arc<Notify>,
    }

    #[async_trait]
    impl EventSourcedBehavior for TempSensorBehavior {
        type State = TempState;

        type Command = TempCommand;

        type Event = TempEvent;

        fn for_command(
            _context: &Context,
            state: &Self::State,
            command: Self::Command,
        ) -> Box<dyn Effect<Self>> {
            match command {
                TempCommand::Register if !state.registered => {
                    persist_event(TempEvent::Registered).boxed()
                }

                TempCommand::Deregister if state.registered => {
                    persist_deletion_event(TempEvent::Deregistered).boxed()
                }

                TempCommand::GetTemperature { reply_to } if state.registered => {
                    reply(reply_to, state.temp).boxed()
                }

                TempCommand::UpdateTemperature { temp } if state.registered => {
                    persist_event(TempEvent::TemperatureUpdated { temp })
                        .and_then(|behavior: &Self, new_state, prev_result| {
                            let updated = behavior.updated.clone();
                            let temp = new_state.map_or(0, |s| s.temp);
                            if prev_result.is_ok() {
                                updated.notify_one();
                                println!("Updated with {}!", temp);
                            }
                            future::ready(prev_result)
                        })
                        .boxed()
                }

                _ => unhandled(),
            }
        }

        fn on_event(_context: &Context, state: &mut Self::State, event: Self::Event) {
            match event {
                TempEvent::Deregistered => state.registered = false,
                TempEvent::Registered => state.registered = true,
                TempEvent::TemperatureUpdated { temp } => state.temp = temp,
            }
        }

        async fn on_recovery_completed(&self, context: &Context, state: &Self::State) {
            if context.entity_id == "id-1" {
                self.recovered_1.notify_one();
            } else {
                self.recovered_2.notify_one();
            };
            println!("Recovered {} with {}!", context.entity_id, state.temp);
        }
    }

    // The following adapter is not normally created by a developer, but we
    // declare one here so that we can provide a source of events and capture
    // ones persisted by the entity manager.
    struct VecEventEnvelopeAdapter {
        initial_events: Option<Vec<EventEnvelope<TempEvent>>>,
        captured_events: mpsc::Sender<EventEnvelope<TempEvent>>,
    }

    #[async_trait]
    impl SourceProvider<TempEvent> for VecEventEnvelopeAdapter {
        async fn source_initial(
            &mut self,
        ) -> io::Result<Pin<Box<dyn Stream<Item = EventEnvelope<TempEvent>> + Send + 'async_trait>>>
        {
            if let Some(events) = self.initial_events.take() {
                Ok(Box::pin(tokio_stream::iter(events)))
            } else {
                Ok(Box::pin(tokio_stream::empty()))
            }
        }

        async fn source(
            &mut self,
            _entity_id: &EntityId,
        ) -> io::Result<Pin<Box<dyn Stream<Item = EventEnvelope<TempEvent>> + Send + 'async_trait>>>
        {
            Ok(Box::pin(tokio_stream::empty()))
        }
    }

    #[async_trait]
    impl Handler<TempEvent> for VecEventEnvelopeAdapter {
        async fn process(
            &mut self,
            envelope: EventEnvelope<TempEvent>,
        ) -> io::Result<EventEnvelope<TempEvent>> {
            self.captured_events
                .send(envelope.clone())
                .await
                .map(|_| envelope)
                .map_err(|e| {
                    io::Error::new(
                        io::ErrorKind::Other,
                        format!("A problem occurred processing an envelope: {e:?}"),
                    )
                })
        }
    }

    // We now set up and run the entity manager, send a few commands, and consume a
    // few events.

    #[test(tokio::test)]
    async fn new_manager_with_one_update_and_a_message_reply() {
        // Set up the behavior and entity manager.

        let temp_sensor_recovered_id_1 = Arc::new(Notify::new());
        let temp_sensor_recovered_id_2 = Arc::new(Notify::new());
        let temp_sensor_updated = Arc::new(Notify::new());

        let temp_sensor_behavior = TempSensorBehavior {
            recovered_1: temp_sensor_recovered_id_1.clone(),
            recovered_2: temp_sensor_recovered_id_2.clone(),
            updated: temp_sensor_updated.clone(),
        };

        let (temp_sensor_events, mut temp_sensor_events_captured) = mpsc::channel(4);
        let temp_sensor_event_adapter = VecEventEnvelopeAdapter {
            initial_events: Some(vec![
                EventEnvelope::new("id-1", 1, Utc::now(), TempEvent::Registered),
                EventEnvelope::new(
                    "id-1",
                    2,
                    Utc::now(),
                    TempEvent::TemperatureUpdated { temp: 10 },
                ),
            ]),
            captured_events: temp_sensor_events,
        };

        let (entity_manager_task, temp_sensor) =
            task(temp_sensor_behavior, temp_sensor_event_adapter, 10, 1);
        let entity_manager_task = tokio::spawn(entity_manager_task);

        // Send a command to update the temperature and wait until it is done. We then wait
        // on a noification from within our entity that the update has occurred. Waiting on
        // this notification demonstrates side-effect behavior. Side-effects can be anything
        // e.g. updating something on a sensor using the MODBUS protocol...

        assert!(temp_sensor
            .send(Message::new(
                "id-1",
                TempCommand::UpdateTemperature { temp: 32 },
            ))
            .await
            .is_ok());

        temp_sensor_recovered_id_1.notified().await;
        temp_sensor_updated.notified().await;

        let (reply_to, reply) = oneshot::channel();
        assert!(temp_sensor
            .send(Message::new(
                "id-1",
                TempCommand::GetTemperature { reply_to }
            ))
            .await
            .is_ok());
        assert_eq!(reply.await.unwrap(), 32);

        // Update the temperature again so we will be able to see a couple of events
        // when we come to consume the entity manager's source.

        assert!(temp_sensor
            .send(Message::new(
                "id-1",
                TempCommand::UpdateTemperature { temp: 64 },
            ))
            .await
            .is_ok());

        temp_sensor_updated.notified().await;

        // Delete the entity

        assert!(temp_sensor
            .send(Message::new("id-1", TempCommand::Deregister,))
            .await
            .is_ok());

        // Create another entity. This should cause cache eviction as the cache is
        // size for a capacity of 1 when we created the entity manager.

        assert!(temp_sensor
            .send(Message::new("id-2", TempCommand::Register,))
            .await
            .is_ok());

        temp_sensor_recovered_id_2.notified().await;

        // We test eviction by querying for id-1 again. This should
        // fail as we have an empty produce method in our adapter.

        let (reply_to, reply) = oneshot::channel();
        assert!(temp_sensor
            .send(Message::new(
                "id-1",
                TempCommand::GetTemperature { reply_to }
            ))
            .await
            .is_ok());
        assert!(reply.await.is_err());

        temp_sensor_recovered_id_1.notified().await;

        // Drop our command sender so that the entity manager stops.

        drop(temp_sensor);

        assert!(entity_manager_task.await.is_ok());

        // We now consume our entity manager as a source of events.

        let envelope = temp_sensor_events_captured.recv().await.unwrap();
        assert_eq!(envelope.entity_id, EntityId::from("id-1"));
        assert_eq!(envelope.seq_nr, 3);
        assert_eq!(envelope.event, TempEvent::TemperatureUpdated { temp: 32 });

        let envelope = temp_sensor_events_captured.recv().await.unwrap();
        assert_eq!(envelope.event, TempEvent::TemperatureUpdated { temp: 64 });

        let envelope = temp_sensor_events_captured.recv().await.unwrap();
        assert!(envelope.deletion_event,);
        assert_eq!(envelope.event, TempEvent::Deregistered,);

        let envelope = temp_sensor_events_captured.recv().await.unwrap();
        assert_eq!(envelope.entity_id, EntityId::from("id-2"));
        assert_eq!(envelope.seq_nr, 1);
        assert_eq!(envelope.event, TempEvent::Registered);

        assert!(temp_sensor_events_captured.recv().await.is_none());
    }
}