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
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
#[cfg(feature = "handler")]
use backon::{ExponentialBuilder, Retryable};
#[cfg(feature = "stream")]
use futures_util::stream::{self, Stream};
#[cfg(any(feature = "stream", feature = "handler"))]
use tokio::time::{interval_at, Instant};
use ulid::Ulid;
use std::{
collections::{HashMap, HashSet},
fmt::Debug,
marker::PhantomData,
sync::{Arc, Mutex},
time::Duration,
};
use thiserror::Error;
use crate::{
context,
cursor::{Args, Value},
Aggregator, AggregatorName, Event, Executor,
};
#[derive(Debug, Error)]
pub enum SubscribeError {
#[error("duplicate handler {0:?}")]
DuplicateHandler(HashSet<String>),
#[error("read >> {0}")]
ReadError(#[from] super::ReadError),
#[error("{0}")]
Unknown(#[from] anyhow::Error),
#[error("ulid.decode >> {0}")]
UlidDecode(#[from] ulid::DecodeError),
#[error("ulid.decode >> {0}")]
Acknowledge(#[from] AcknowledgeError),
}
#[derive(Debug, Error)]
pub enum AcknowledgeError {
#[error("{0}")]
Unknown(#[from] anyhow::Error),
}
#[derive(Clone)]
pub enum RoutingKey {
All,
Value(Option<String>),
}
/// Handle for managing a running subscription
///
/// This handle allows you to gracefully shutdown the subscription and wait for it to complete.
/// Useful for implementing graceful shutdown in web servers and other applications.
#[cfg(feature = "handler")]
#[derive(Debug)]
pub struct SubscriptionHandle {
/// Handle to the spawned subscription task
task_handle: tokio::task::JoinHandle<()>,
/// Shutdown signal sender
shutdown_tx: tokio::sync::oneshot::Sender<()>,
}
#[cfg(feature = "handler")]
impl SubscriptionHandle {
/// Signal the subscription to shutdown gracefully
///
/// This sends a shutdown signal to the subscription. The subscription will finish
/// processing the current event and then stop.
pub fn shutdown(self) -> Result<tokio::task::JoinHandle<()>, String> {
// Send shutdown signal (ignore error if receiver is already dropped)
let _ = self.shutdown_tx.send(());
Ok(self.task_handle)
}
/// Wait for the subscription to complete
///
/// This waits for the subscription task to finish execution.
pub async fn wait(self) -> Result<(), tokio::task::JoinError> {
self.task_handle.await
}
/// Signal shutdown and wait for completion
///
/// This is a convenience method that calls shutdown() and then wait().
pub async fn shutdown_and_wait(self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
let handle = self
.shutdown()
.map_err(|_| "Failed to send shutdown signal")?;
handle
.await
.map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)
}
}
#[derive(Clone)]
pub struct Context<'a, E: Executor> {
inner: Arc<Mutex<context::Context>>,
key: String,
cursor: Value,
lag: u64,
pub event: Event,
pub executor: &'a E,
}
impl<'a, E: Executor> Context<'a, E> {
pub fn extract<T: Clone + 'static>(&self) -> T {
let context = self.inner.lock().expect("Unable to lock Context.inner");
context.extract::<T>().clone()
}
pub async fn acknowledge(&self) -> Result<(), AcknowledgeError> {
self.executor
.acknowledge(self.key.to_owned(), self.cursor.to_owned(), self.lag)
.await
}
}
pub trait SubscribeHandler<E: Executor>: Send + Sync {
fn handle<'async_trait>(
&'async_trait self,
context: &'async_trait Context<'_, E>,
) -> std::pin::Pin<
Box<dyn std::future::Future<Output = anyhow::Result<()>> + Send + 'async_trait>,
>
where
Self: Sync + 'async_trait;
fn aggregator_type(&self) -> &'static str;
fn event_name(&self) -> &'static str;
}
pub struct SubscribeBuilder<E: Executor> {
id: Ulid,
key: String,
routing_key: RoutingKey,
#[allow(dead_code)]
delay: Option<Duration>,
#[allow(dead_code)]
handlers: HashMap<String, Box<dyn SubscribeHandler<E>>>,
duplicate_handlers: HashSet<String>,
aggregator_types: HashSet<String>,
chunk_size: u16,
backon: bool,
#[cfg(feature = "handler")]
enforce_handler: bool,
context: Arc<Mutex<context::Context>>,
}
/// Create a new event subscription builder
///
/// Creates a builder for setting up continuous event processing. Subscriptions
/// listen to events from specified aggregates and process them with registered handlers.
///
/// # Parameters
///
/// - `key`: A unique identifier for this subscription (used for tracking progress)
///
/// # Examples
///
/// ```no_run
/// use evento::subscribe;
/// # use evento::*;
/// # use bincode::{Encode, Decode};
/// # #[derive(AggregatorName, Encode, Decode)]
/// # struct UserCreated { name: String }
/// # #[derive(Default, Encode, Decode, Clone, Debug)]
/// # struct User;
/// # #[evento::aggregator]
/// # impl User {}
/// # #[evento::handler(User)]
/// # async fn on_user_created<E: Executor>(
/// # context: &Context<'_, E>,
/// # event: EventDetails<UserCreated>,
/// # ) -> anyhow::Result<()> { Ok(()) }
///
/// async fn setup_subscription(executor: evento::Sqlite) -> anyhow::Result<()> {
/// subscribe("user-handlers")
/// .aggregator::<User>()
/// .handler(on_user_created())
/// .run(&executor)
/// .await?;
///
/// Ok(())
/// }
/// ```
pub fn subscribe<E: Executor>(key: impl Into<String>) -> SubscribeBuilder<E> {
SubscribeBuilder {
id: Ulid::new(),
key: key.into(),
delay: None,
routing_key: RoutingKey::Value(None),
handlers: HashMap::new(),
duplicate_handlers: HashSet::new(),
aggregator_types: HashSet::new(),
chunk_size: 300,
context: Arc::default(),
backon: true,
#[cfg(feature = "handler")]
enforce_handler: true,
}
}
impl<E: Executor + Clone> SubscribeBuilder<E> {
pub fn chunk_size(mut self, v: u16) -> Self {
self.chunk_size = v;
self
}
pub fn data<D: Send + Sync + 'static>(self, v: D) -> Self {
let mut context = self
.context
.lock()
.expect("Unable to lock SubscribeBuilder.context");
context.insert(v);
drop(context);
self
}
#[cfg(feature = "handler")]
pub fn delay(mut self, v: Duration) -> Self {
self.delay = Some(v);
self
}
pub fn routing_key(mut self, v: impl Into<String>) -> Self {
self.routing_key = RoutingKey::Value(Some(v.into()));
self
}
fn backoff(mut self) -> Self {
self.backon = false;
self
}
#[cfg(feature = "handler")]
pub fn handler_check_off(mut self) -> Self {
self.enforce_handler = false;
self
}
pub fn all(mut self) -> Self {
self.routing_key = RoutingKey::All;
self
}
/// Subscribe to events for a specific aggregator type
///
/// This method allows subscribing to all events for a given aggregator without
/// specifying individual handlers. Requires the `stream` feature to be enabled.
///
/// # Examples
///
/// ```no_run
/// # use evento::{subscribe, EventDetails, AggregatorName};
/// # use serde::{Serialize, Deserialize};
/// # use bincode::{Encode, Decode};
/// #
/// # #[derive(Default, Serialize, Deserialize, Encode, Decode, Clone, Debug)]
/// # struct User {
/// # name: String,
/// # }
/// #
/// # #[derive(AggregatorName, Encode, Decode)]
/// # struct UserCreated {
/// # name: String,
/// # }
/// #
/// # #[evento::aggregator]
/// # impl User {
/// # async fn user_created(&mut self, event: EventDetails<UserCreated>) -> anyhow::Result<()> {
/// # self.name = event.data.name;
/// # Ok(())
/// # }
/// # }
/// #
/// # async fn example(executor: &evento::Sqlite) -> anyhow::Result<()> {
/// subscribe("user-stream")
/// .aggregator::<User>()
/// .run(executor)
/// .await?;
/// # Ok(())
/// # }
/// ```
#[cfg(feature = "stream")]
pub fn aggregator<A: Aggregator>(mut self) -> Self {
self.aggregator_types.insert(A::name().to_owned());
self
}
#[cfg(feature = "handler")]
pub fn handler<H: SubscribeHandler<E> + 'static>(mut self, handler: H) -> Self {
self.aggregator_types
.insert(handler.aggregator_type().to_owned());
let key = format!("{}-{}", handler.aggregator_type(), handler.event_name());
if self
.handlers
.insert(key.to_owned(), Box::new(handler))
.is_some()
{
self.duplicate_handlers.insert(key);
};
self
}
#[cfg(feature = "handler")]
pub fn skip<A: Aggregator + 'static, N: AggregatorName + Send + Sync + 'static>(self) -> Self {
self.handler(SkipHandler::<A, N>(PhantomData, PhantomData))
}
pub async fn init(&self, executor: &E) -> Result<(), SubscribeError> {
if !self.duplicate_handlers.is_empty() {
let values = self.duplicate_handlers.iter().cloned().collect();
return Err(SubscribeError::DuplicateHandler(values));
}
executor
.upsert_subscriber(self.key.to_owned(), self.id)
.await?;
Ok(())
}
pub async fn is_subscriber_running(&self, executor: &E) -> Result<bool, SubscribeError> {
executor
.is_subscriber_running(self.key.to_owned(), self.id)
.await
}
pub async fn read<'a>(&self, executor: &'a E) -> Result<Vec<Context<'a, E>>, SubscribeError> {
let cursor = executor.get_subscriber_cursor(self.key.to_owned()).await?;
let timestamp = executor
.read(
self.aggregator_types.to_owned(),
self.routing_key.clone(),
Args::backward(1, None),
)
.await?
.edges
.last()
.map(|e| e.node.timestamp)
.unwrap_or_default();
let res = executor
.read(
self.aggregator_types.to_owned(),
self.routing_key.clone(),
Args::forward(self.chunk_size, cursor),
)
.await?;
Ok(res
.edges
.iter()
.map(|edge| Context {
inner: self.context.clone(),
key: self.key.to_owned(),
executor,
lag: (timestamp - edge.node.timestamp),
cursor: edge.cursor.to_owned(),
event: edge.node.clone(),
})
.collect())
}
#[cfg(feature = "handler")]
pub async fn run(self, executor: &E) -> Result<SubscriptionHandle, SubscribeError> {
self.init(executor).await?;
let executor = executor.clone();
let start = self
.delay
.map(|d| Instant::now() + d)
.unwrap_or_else(Instant::now);
let (shutdown_tx, mut shutdown_rx) = tokio::sync::oneshot::channel();
let task_handle = tokio::spawn(async move {
let mut interval = interval_at(
start - Duration::from_millis(400),
Duration::from_millis(300),
);
loop {
if shutdown_rx.try_recv().is_ok() {
tracing::info!(
key = self.key,
"Subscription received shutdown signal, stopping gracefull"
);
break;
}
interval.tick().await;
let data = (|| async { self.read(&executor).await })
.retry(ExponentialBuilder::default())
.when(|_| self.backon)
.sleep(tokio::time::sleep)
.notify(|err, dur| {
tracing::error!(
error_message = %err,
duration = ?dur,
"Failed to read events"
);
})
.await;
let data = match data {
Ok(data) => data,
Err(e) => {
tracing::error!(
error_message = %e,
"Failed to read events"
);
return;
}
};
for item in data {
let running = (|| async { self.is_subscriber_running(&executor).await })
.retry(ExponentialBuilder::default())
.sleep(tokio::time::sleep)
.when(|_| self.backon)
.notify(|err, dur| {
tracing::error!(
error_message = %err,
duration = ?dur,
"Failed to check if subscriber is running"
)
})
.await;
let running = match running {
Ok(data) => data,
Err(e) => {
tracing::error!(
error_message = %e,
"Failed to check if subscriber is running"
);
return;
}
};
if !running {
break;
}
let key = format!("{}-{}", item.event.aggregator_type, item.event.name);
match self.handlers.get(&key) {
Some(handler) => {
if let Err(e) = (|| async { handler.handle(&item).await })
.retry(ExponentialBuilder::default())
.sleep(tokio::time::sleep)
.when(|_| self.backon)
.notify(|err, dur| {
tracing::error!(
key = item.key,
aggregator = item.event.aggregator_type,
event = item.event.name,
error_message = %err,
duration = ?dur,
"Failed to handle event"
);
})
.await
{
tracing::error!(error_message = %e, "Failed to handle event");
return;
}
}
_ => {
if self.enforce_handler {
tracing::error!(
key = item.key,
aggregator = item.event.aggregator_type,
event = item.event.name,
"No event handler define, stop subscriber",
);
return;
}
tracing::debug!(
key = item.key,
aggregator = item.event.aggregator_type,
event = item.event.name,
"No event handler define",
);
}
};
if let Err(err) = (async || item.acknowledge().await)
.retry(ExponentialBuilder::default())
.when(|_| self.backon)
.sleep(tokio::time::sleep)
.notify(|err, dur| {
tracing::error!(error_message = %err, duration = ?dur, "Failed to acknowledge event");
})
.await
{
tracing::error!(error_message = %err, "Failed to acknowledge event");
break;
}
tracing::info!(
key = item.key,
aggregator = item.event.aggregator_type,
event = item.event.name,
"Event is handled"
);
}
}
});
Ok(SubscriptionHandle {
task_handle,
shutdown_tx,
})
}
#[cfg(feature = "handler")]
pub async fn unretry_run(self, executor: &E) -> Result<SubscriptionHandle, SubscribeError> {
self.backoff().run(executor).await
}
#[cfg(feature = "handler")]
pub async fn unretry_oneshot(self, executor: &E) -> Result<(), SubscribeError> {
self.backoff().oneshot(executor).await
}
#[cfg(feature = "handler")]
#[deprecated(since = "1.7.0", note = "use unretry_oneshot instead")]
pub async fn unsafe_oneshot(self, executor: &E) -> Result<(), SubscribeError> {
self.backoff().oneshot(executor).await
}
#[cfg(feature = "handler")]
#[deprecated(since = "1.4.0", note = "use oneshot instead")]
pub async fn run_once(self, executor: &E) -> Result<(), SubscribeError> {
self.oneshot(executor).await
}
#[cfg(feature = "handler")]
pub async fn oneshot(self, executor: &E) -> Result<(), SubscribeError> {
self.init(executor).await?;
let executor = executor.clone();
let mut interval = interval_at(
Instant::now() - Duration::from_millis(400),
Duration::from_millis(300),
);
loop {
interval.tick().await;
let data = (|| async { self.read(&executor).await })
.retry(ExponentialBuilder::default())
.sleep(tokio::time::sleep)
.when(|_| self.backon)
.notify(|err, dur| {
tracing::error!(
error_message = %err,
duration = ?dur,
"Failed to read events"
);
})
.await?;
if data.is_empty() {
break;
}
for item in data {
let running = (|| async { self.is_subscriber_running(&executor).await })
.retry(ExponentialBuilder::default())
.sleep(tokio::time::sleep)
.when(|_| self.backon)
.notify(|err, dur| {
tracing::error!(
error_message = %err,
duration = ?dur,
"Failed to check if subscriber running");
})
.await?;
if !running {
break;
}
let key = format!("{}-{}", item.event.aggregator_type, item.event.name);
match self.handlers.get(&key) {
Some(handler) => {
(|| async { handler.handle(&item).await })
.retry(ExponentialBuilder::default())
.sleep(tokio::time::sleep)
.when(|_| self.backon)
.notify(|err, dur| {
tracing::error!(
key = item.key,
aggregator = item.event.aggregator_type,
event = item.event.name,
error_message = %err,
duration = ?dur,
"Failed to handle event",
);
})
.await?;
}
_ => {
if self.enforce_handler {
return Err(SubscribeError::Unknown(anyhow::anyhow!(
"No event handler define for {} {}",
item.event.aggregator_type,
item.event.name
)));
}
tracing::debug!(
key = item.key,
aggregator = item.event.aggregator_type,
event = item.event.name,
"No event handler define",
);
}
};
(async || item.acknowledge().await)
.retry(ExponentialBuilder::default())
.sleep(tokio::time::sleep)
.when(|_| self.backon)
.notify(|err, dur| {
tracing::error!(
error_message = %err,
duration = ?dur,
"Failed to acknowledge event");
})
.await?;
tracing::info!(
key = item.key,
aggregator = item.event.aggregator_type,
event = item.event.name,
"Event is handled"
);
}
}
Ok(())
}
#[cfg(feature = "stream")]
pub async fn stream<'a>(
&self,
executor: &'a E,
) -> Result<impl Stream<Item = Context<'a, E>> + use<'a, '_, E>, SubscribeError> {
self.init(executor).await?;
Ok(stream::unfold(
(self, executor, Vec::<Context<'a, E>>::new().into_iter()),
move |(sub, executor, mut data)| async move {
let start = sub
.delay
.map(|d| Instant::now() + d)
.unwrap_or_else(Instant::now);
let mut interval = interval_at(
start - Duration::from_millis(400),
Duration::from_millis(300),
);
loop {
if let Some(item) = data.next() {
return Some((item, (sub, executor, data)));
}
interval.tick().await;
let Ok(r_data) = (|| async { self.read(executor).await })
.retry(ExponentialBuilder::default())
.sleep(tokio::time::sleep)
.when(|_| self.backon)
.notify(|err, dur| {
tracing::error!(error_message = %err, duration = ?dur, "Failed to read events");
})
.await
else {
return None;
};
data = r_data.into_iter();
}
},
))
}
}
pub struct SkipHandler<A: Aggregator, N: AggregatorName>(PhantomData<A>, PhantomData<N>);
impl<E: Executor, A: Aggregator, N: AggregatorName + Send + Sync> SubscribeHandler<E>
for SkipHandler<A, N>
{
fn handle<'async_trait>(
&'async_trait self,
_context: &'async_trait Context<'_, E>,
) -> std::pin::Pin<
Box<dyn std::future::Future<Output = anyhow::Result<()>> + Send + 'async_trait>,
>
where
Self: Sync + 'async_trait,
{
Box::pin(async { Ok(()) })
}
fn aggregator_type(&self) -> &'static str {
A::name()
}
fn event_name(&self) -> &'static str {
N::name()
}
}