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
#![doc = include_str!("../README.md")]

use std::{collections::VecDeque, io, pin::Pin};

use crate::{
    offset_store::{self},
    Handler, HandlerError, Handlers, PendingHandler, SourceProvider,
};
use akka_persistence_rs::{
    Offset, Source, TimestampOffset, WithOffset, WithPersistenceId, WithSeqNr, WithSource,
};
use futures::{self, future, stream, Future, Stream};
use log::{debug, warn};
use serde::{Deserialize, Serialize};
use tokio::sync::{mpsc, oneshot};
use tokio_stream::StreamExt;

#[derive(Default, Deserialize, Serialize)]
struct StorableState {
    last_offset: Option<Offset>,
}

/// Provides an asynchronous task and a kill switch that can run and stop a projection.
///
/// An at-least-once projection is returned with storage for projection offsets,
/// meaning, for multiple runs of a projection, it is possible for events to repeat
/// from previous runs.
pub fn task<A, B, Envelope, EE, IH, SP>(
    offset_store: (
        impl Future<Output = io::Result<()>>,
        mpsc::Sender<offset_store::Command>,
    ),
    source_provider: SP,
    handler: IH,
) -> (impl Future<Output = io::Result<()>>, oneshot::Sender<()>)
where
    A: Handler<Envelope = EE> + Send,
    B: PendingHandler<Envelope = EE> + Send,
    EE: TryFrom<Envelope>,
    Envelope: WithPersistenceId + WithOffset + WithSeqNr + WithSource + Send,
    IH: Into<Handlers<A, B>>,
    SP: SourceProvider<Envelope = Envelope>,
{
    let (kill_switch, mut kill_switch_receiver) = oneshot::channel();

    let (offset_store_task, offset_store) = offset_store;

    let projection_task = async move {
        let mut handler = handler.into();

        let mut always_pending_handler: Pin<
            Box<dyn Future<Output = Result<(), HandlerError>> + Send>,
        > = Box::pin(future::pending());

        'outer: loop {
            let mut source = source_provider
                .source(|| async {
                    let (reply_to, reply_to_receiver) = oneshot::channel();
                    offset_store
                        .send(offset_store::Command::GetLastOffset { reply_to })
                        .await
                        .ok()?;
                    reply_to_receiver.await.ok()?
                })
                .await;

            let mut always_pending_source: Pin<Box<dyn Stream<Item = Envelope> + Send>> =
                Box::pin(stream::pending());

            let mut active_source = &mut source;

            let mut handler_futures = VecDeque::with_capacity(B::MAX_PENDING);

            loop {
                tokio::select! {
                    envelope = active_source.next() => {
                        if let Some(envelope) = envelope {
                            let persistence_id = envelope.persistence_id().clone();
                            let offset = envelope.offset();

                            // Validate timestamp offsets if we have one.
                            let envelope = if matches!(offset, Offset::Timestamp(_)) {
                                // Process the sequence number. If it isn't what we expect then we go round again.

                                let seq_nr = envelope.seq_nr();

                                let (reply_to, reply_to_receiver) = oneshot::channel();
                                if offset_store
                                    .send(offset_store::Command::GetOffset { persistence_id: persistence_id.clone(), reply_to })
                                    .await
                                    .is_err()
                                {
                                    warn!("Cannot send to the offset store: {}. Aborting stream.", persistence_id);
                                    break;
                                }

                                let next_seq_nr = if let Ok(offset) = reply_to_receiver.await {
                                    if let Some(Offset::Timestamp(TimestampOffset { seq_nr, .. })) = offset {
                                        seq_nr.wrapping_add(1)
                                    } else {
                                        1
                                    }
                                } else {
                                    warn!("Cannot receive from the offset store: {}. Aborting stream.", persistence_id);
                                    break
                                };

                                let source = envelope.source();

                                if seq_nr > next_seq_nr && envelope.source() == Source::Backtrack {
                                    // This shouldn't happen, if so then abort.
                                    warn!("Back track received for a future event: {}. Aborting stream.", persistence_id);
                                    break;
                                } else if seq_nr != next_seq_nr {
                                    // Duplicate or gap
                                    continue;
                                }

                                // If the sequence number is what we expect and the producer is backtracking, then
                                // request its payload. If we can't get its payload then we abort as it is an error.

                                let resolved_envelope = if source == Source::Backtrack {
                                    if let Some(event) = source_provider.load_envelope(persistence_id.clone(), seq_nr)
                                        .await
                                    {
                                        Some(event)
                                    } else {
                                        warn!("Cannot obtain an backtrack envelope: {}. Aborting stream.", persistence_id);
                                        None
                                    }
                                } else {
                                    Some(envelope)
                                };

                                let Some(envelope) = resolved_envelope else { break; };
                                envelope
                            } else {
                                envelope
                            };

                            // We now have an event correctly sequenced. Process it.

                            match &mut handler {
                                Handlers::Ready(handler, _) => {
                                    if let Ok(event_envelope) = envelope.try_into() {
                                        if handler.process(event_envelope).await.is_err() {
                                            break;
                                        }
                                    }
                                    if offset_store
                                        .send(offset_store::Command::SaveOffset { persistence_id, offset })
                                        .await
                                        .is_err()
                                    {
                                        break;
                                    }
                                }
                                Handlers::Pending(handler, _) => {
                                    let pending = if let Ok(event_envelope) = envelope.try_into() {
                                        let Ok(pending) = handler.process_pending(event_envelope).await else {
                                            break;
                                        };
                                        pending
                                    } else {
                                        Box::pin(future::ready(Ok(())))
                                    };
                                    handler_futures.push_back((pending, persistence_id, offset));
                                    // If we've reached the limit on the pending futures in-flight
                                    // then back off sourcing more.
                                    if handler_futures.len() == B::MAX_PENDING {
                                        active_source = &mut always_pending_source;
                                    }
                            }
                            }
                        } else {
                            break;
                        }
                    }

                    pending = handler_futures.get_mut(0).map_or_else(|| &mut always_pending_handler, |(f, _, _)| f) => {
                        // A pending future will never complete so this MUST mean that we have a element in our queue.
                        let (_, persistence_id, offset) = handler_futures.pop_front().unwrap();

                        // We've freed up a slot on the pending futures in-flight, so allow more events to be received.
                        active_source = &mut source;

                        // If all is well with our pending future so we can finally cause the offset to be persisted.
                        if pending.is_err()
                            || offset_store
                                .send(offset_store::Command::SaveOffset { persistence_id, offset })
                                .await
                                .is_err()
                        {
                            break;
                        }
                    }

                    _ = &mut kill_switch_receiver => {
                        debug!("storage killed.");
                        break 'outer;
                    }

                    else => {
                        break 'outer;
                    }
                }
            }
        }
    };

    let combined_task = async {
        let (_, r) = tokio::join!(projection_task, offset_store_task);
        r
    };

    (combined_task, kill_switch)
}

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

    use super::*;
    use crate::{offset_store::LastOffset, HandlerError};
    use akka_persistence_rs::{EntityId, EntityType, PersistenceId};
    use async_stream::stream;
    use async_trait::async_trait;
    use chrono::{DateTime, Utc};
    use serde::Deserialize;
    use test_log::test;
    use tokio_stream::Stream;

    // Scaffolding

    struct TestEnvelope {
        persistence_id: PersistenceId,
        timestamp: DateTime<Utc>,
        seq_nr: u64,
        source: Source,
        event: MyEvent,
    }

    impl WithPersistenceId for TestEnvelope {
        fn persistence_id(&self) -> &PersistenceId {
            &self.persistence_id
        }
    }

    impl WithOffset for TestEnvelope {
        fn offset(&self) -> Offset {
            Offset::Timestamp(TimestampOffset {
                timestamp: self.timestamp,
                seq_nr: self.seq_nr,
            })
        }
    }

    impl WithSource for TestEnvelope {
        fn source(&self) -> akka_persistence_rs::Source {
            self.source
        }
    }

    impl WithSeqNr for TestEnvelope {
        fn seq_nr(&self) -> u64 {
            self.seq_nr
        }
    }

    #[derive(Clone, Debug, Deserialize, Serialize, PartialEq)]
    struct MyEvent {
        value: String,
    }

    // Developers are expected to provide a marshaller of events.
    // The marshaller is responsible for more than just the serialization
    // of an envelope. Extracting/saving an entity id and determining other
    // metadata is also important. We would also expect to see any encryption
    // and decyption being performed by the marshaller.
    // The example here overrides the default methods of the marshaller and
    // effectively ignores the use of a secret key; just to prove that you really
    // can lay out an envelope any way that you would like to. Note that secret keys
    // are important though.

    struct MySourceProvider {
        persistence_id: PersistenceId,
        event_value: String,
    }

    #[async_trait]
    impl SourceProvider for MySourceProvider {
        type Envelope = TestEnvelope;

        async fn source<F, FR>(
            &self,
            offset: F,
        ) -> Pin<Box<dyn Stream<Item = Self::Envelope> + Send + 'async_trait>>
        where
            F: Fn() -> FR + Send + Sync,
            FR: Future<Output = Option<LastOffset>> + Send,
        {
            Box::pin(
                stream! {
                    if offset().await.is_none() {
                        yield TestEnvelope {
                            persistence_id: self.persistence_id.clone(),
                            timestamp: Utc::now(),
                            seq_nr: 1,
                            event: MyEvent {
                                value: self.event_value.clone(),
                            },
                            source: Source::Backtrack,
                        };

                        yield TestEnvelope {
                            persistence_id: self.persistence_id.clone(),
                            timestamp: Utc::now(),
                            seq_nr: 2,
                            event: MyEvent {
                                value: self.event_value.clone(),
                            },
                            source: Source::Regular,
                        };
                    }
                }
                .chain(stream::pending()),
            )
        }
        async fn load_envelope(
            &self,
            persistence_id: PersistenceId,
            seq_nr: u64,
        ) -> Option<Self::Envelope> {
            if persistence_id == self.persistence_id && seq_nr == 1 {
                Some(TestEnvelope {
                    persistence_id: self.persistence_id.clone(),
                    timestamp: Utc::now(),
                    seq_nr: 1,
                    event: MyEvent {
                        value: self.event_value.clone(),
                    },
                    source: Source::Regular,
                })
            } else {
                None
            }
        }
    }

    struct MyHandler {
        persistence_id: PersistenceId,
        event_value: String,
    }

    #[async_trait]
    impl Handler for MyHandler {
        type Envelope = TestEnvelope;

        /// Process an envelope.
        async fn process(&mut self, envelope: Self::Envelope) -> Result<(), HandlerError> {
            assert_eq!(envelope.persistence_id, self.persistence_id);
            assert_eq!(
                envelope.event,
                MyEvent {
                    value: self.event_value.clone()
                }
            );
            Ok(())
        }
    }

    struct MyHandlerPending {
        persistence_id: PersistenceId,
        event_value: String,
    }

    #[async_trait]
    impl PendingHandler for MyHandlerPending {
        type Envelope = TestEnvelope;

        const MAX_PENDING: usize = 1;

        /// Process an envelope.
        async fn process_pending(
            &mut self,
            envelope: Self::Envelope,
        ) -> Result<Pin<Box<dyn Future<Output = Result<(), HandlerError>> + Send>>, HandlerError>
        {
            assert_eq!(envelope.persistence_id, self.persistence_id);
            assert_eq!(
                envelope.event,
                MyEvent {
                    value: self.event_value.clone()
                }
            );
            Ok(Box::pin(future::ready(Ok(()))))
        }
    }

    async fn test_projection<A, B, IH>(
        persistence_id: PersistenceId,
        event_value: String,
        handler: IH,
    ) where
        A: Handler<Envelope = TestEnvelope> + Send + 'static,
        B: PendingHandler<Envelope = TestEnvelope> + Send + 'static,
        IH: Into<Handlers<A, B>> + Send + 'static,
    {
        // Process an event.

        let (offset_store, mut offset_store_receiver) = mpsc::channel(1);
        let task_persistence_id = persistence_id.clone();
        let (projection_task, _kill_switch) = task(
            (future::pending(), offset_store),
            MySourceProvider {
                persistence_id: task_persistence_id.clone(),
                event_value: event_value.clone(),
            },
            handler,
        );
        tokio::spawn(projection_task);

        if let Some(offset_store::Command::GetLastOffset { reply_to }) =
            offset_store_receiver.recv().await
        {
            assert!(reply_to.send(None).is_ok());
        } else {
            panic!("Unexpected offset command");
        }

        if let Some(offset_store::Command::GetOffset {
            persistence_id: pid,
            reply_to,
        }) = offset_store_receiver.recv().await
        {
            if pid == persistence_id {
                assert!(reply_to.send(None).is_ok());
            } else {
                panic!("Unexpected pid");
            }
        } else {
            panic!("Unexpected offset command");
        }

        assert!(matches!(
            offset_store_receiver.recv().await,
            Some(offset_store::Command::SaveOffset {
                persistence_id: pid,
                offset: Offset::Timestamp(TimestampOffset { seq_nr: 1, .. })
            }) if pid == persistence_id
        ));

        if let Some(offset_store::Command::GetOffset {
            persistence_id: pid,
            reply_to,
        }) = offset_store_receiver.recv().await
        {
            if pid == persistence_id {
                assert!(reply_to
                    .send(Some(Offset::Timestamp(TimestampOffset {
                        timestamp: Utc::now(),
                        seq_nr: 1
                    })))
                    .is_ok());
            } else {
                panic!("Unexpected pid");
            }
        } else {
            panic!("Unexpected offset command");
        }

        assert!(matches!(
            offset_store_receiver.recv().await,
            Some(offset_store::Command::SaveOffset {
                persistence_id: pid,
                offset: Offset::Timestamp(TimestampOffset { seq_nr: 2, .. })
            }) if pid == persistence_id
        ));
    }

    #[test(tokio::test)]
    async fn can_run_ready() {
        let entity_type = EntityType::from("some-entity-type");
        let entity_id = EntityId::from("some-entity");
        let persistence_id = PersistenceId::new(entity_type, entity_id);
        let event_value = "some value".to_string();

        test_projection(
            persistence_id.clone(),
            event_value.clone(),
            MyHandler {
                persistence_id,
                event_value,
            },
        )
        .await;
    }

    #[test(tokio::test)]
    async fn can_run_pending() {
        let entity_type = EntityType::from("some-entity-type");
        let entity_id = EntityId::from("some-entity");
        let persistence_id = PersistenceId::new(entity_type, entity_id);
        let event_value = "some value".to_string();

        test_projection(
            persistence_id.clone(),
            event_value.clone(),
            MyHandlerPending {
                persistence_id,
                event_value,
            },
        )
        .await;
    }
}