use std::time::Duration;
use ruststream::codec::JsonCodec;
use ruststream::memory::prelude::*;
use ruststream::runtime::{Names, Outgoing, PublishContext, Router, RouterDef};
use ruststream::{NamedCopies, Subscribe, SubscriptionSource};
use serde::Deserialize;
#[derive(Debug, Deserialize)]
struct Payment {
id: u64,
settled: bool,
}
#[subscriber("payments")]
async fn reconcile(payment: &Payment) -> HandlerOutcome {
if !payment.settled {
return HandlerOutcome::retry_after(Duration::from_secs(5));
}
println!("payment {} settled", payment.id);
HandlerOutcome::ack()
}
#[subscriber("payments")]
async fn reconcile_batch(payments: &[Payment]) -> Vec<HandlerOutcome> {
payments
.iter()
.map(|payment| {
if payment.settled {
HandlerOutcome::ack()
} else {
HandlerOutcome::retry_after(Duration::from_secs(30))
}
})
.collect()
}
#[derive(Debug, Clone)]
struct PaymentFilter;
impl<C: Subscribe> SubscriptionSource<C> for PaymentFilter {
type Subscriber = C::Subscriber;
type Copies = NamedCopies;
#[allow(clippy::unnecessary_literal_bound)]
fn name(&self) -> &str {
"payments.*"
}
async fn subscribe(self, connected: &C) -> Result<Self::Subscriber, C::Error> {
connected.subscribe("payments.*").await
}
}
#[subscriber(PaymentFilter {})]
async fn reconcile_filtered(payment: &Payment) -> HandlerOutcome {
if !payment.settled {
return HandlerOutcome::retry_after(Duration::from_secs(5));
}
HandlerOutcome::ack()
}
struct ToDeliveryTopic;
impl<C, Options> PublishTransform<ForReply<C>, Options> for ToDeliveryTopic {
type Destination = Names;
fn apply(
&self,
out: &mut Outgoing<'_>,
_options: &mut Option<Options>,
cx: &PublishContext<'_, C>,
) {
let topic = cx
.headers()
.get_str("x-topic")
.unwrap_or_else(|| cx.name())
.to_owned();
out.set_name(topic);
}
}
struct DeferredStamp;
impl<C, Options> PublishTransform<ForReply<C>, Options> for DeferredStamp {
type Destination = Reads;
fn apply(
&self,
out: &mut Outgoing<'_>,
_options: &mut Option<Options>,
cx: &PublishContext<'_, C>,
) {
out.headers_mut()
.insert("x-retried-from", cx.name().to_owned());
}
}
#[ruststream::app]
fn app() -> RustStream {
RustStream::new(AppInfo::new("retry", "0.1.0")).with_broker(MemoryBroker::new(), |b| {
b.include(reconcile)
.max_attempts(nonzero!(5u32))
.dead_letter("payments.dead");
b.include(reconcile_filtered)
.max_attempts(nonzero!(5u32))
.dead_letter("payments.dead")
.out_retry(Publish)
.to("payments.retry");
b.include(reconcile_batch.batch(nonzero!(64)))
.max_attempts(nonzero!(5u32))
.dead_letter("payments.dead")
.out_retry(Publish)
.codec(JsonCodec)
.transform(DeferredStamp);
b.include_router(routed());
})
}
fn routed() -> impl RouterDef<MemoryBroker> {
Router::<MemoryBroker>::new()
.include(reconcile_filtered)
.out_retry(Publish)
.transform(ToDeliveryTopic)
.build()
}