use std::sync::Arc;
use ruststream::conformance::harness;
use ruststream::runtime::{AppInfo, HandlerResult, RustStream};
use ruststream::subscriber;
use ruststream::testing::TestApp;
use ruststream_fred::{RedisList, RedisPubSub, RedisStream, testing::RedisTestBroker};
use serde::{Deserialize, Serialize};
use tokio::sync::Mutex;
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq)]
struct Payment {
id: u64,
user_id: u64,
amount: u64,
}
#[derive(Clone, Default)]
struct PaymentRepository {
payments: Arc<Mutex<Vec<Payment>>>,
}
impl PaymentRepository {
async fn save(&self, payment: Payment) {
self.payments.lock().await.push(payment);
}
async fn count(&self) -> usize {
self.payments.lock().await.len()
}
async fn contains(&self, id: u64) -> bool {
self.payments.lock().await.iter().any(|p| p.id == id)
}
}
#[subscriber(
RedisStream::new("payments")
.group("workers")
)]
async fn process_payment(
payment: &Payment,
ctx: &mut Context<'_, (), PaymentRepository>,
) -> HandlerResult {
if payment.amount == 0 {
return HandlerResult::drop();
}
ctx.state().save(payment.clone()).await;
HandlerResult::ack()
}
#[subscriber(
RedisStream::new("events")
.group("workers")
)]
async fn handle_stream_event(payment: &Payment) -> HandlerResult {
println!("stream event {}", payment.id);
HandlerResult::Ack
}
#[subscriber(
RedisList::new("jobs")
.reliable()
)]
async fn handle_list_job(payment: &Payment) -> HandlerResult {
println!("list job {}", payment.id);
HandlerResult::Ack
}
#[subscriber(RedisPubSub::new("notifications"))]
async fn handle_pubsub_notification(payment: &Payment) -> HandlerResult {
println!("pubsub notification {}", payment.id);
HandlerResult::Ack
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
test_payment_processing().await?;
test_stream_delivery().await?;
test_list_delivery().await?;
test_pubsub_delivery().await?;
test_conformance_suite().await?;
Ok(())
}
fn payment(id: u64, amount: u64) -> Payment {
Payment {
id,
user_id: 42,
amount,
}
}
async fn test_payment_processing() -> Result<(), Box<dyn std::error::Error>> {
let repository = PaymentRepository::default();
let repository_for_app = repository.clone();
let app = RustStream::new(AppInfo::new("test", "0.1.0"))
.on_startup(move |()| async move { Ok::<_, std::convert::Infallible>(repository_for_app) })
.with_broker(RedisTestBroker::new(), |b| {
b.include(process_payment);
});
let tb = TestApp::start(app).await?;
tb.broker::<RedisTestBroker>()
.publish("payments", &payment(1, 100))
.await?;
tb.broker::<RedisTestBroker>()
.publish("payments", &payment(2, 0))
.await?;
assert!(repository.contains(1).await, "valid payment was not saved");
assert!(
!repository.contains(2).await,
"invalid payment should have been dropped"
);
assert_eq!(repository.count().await, 1);
tb.shutdown().await?;
Ok(())
}
async fn test_stream_delivery() -> Result<(), Box<dyn std::error::Error>> {
let app =
RustStream::new(AppInfo::new("test", "0.1.0")).with_broker(RedisTestBroker::new(), |b| {
b.include(handle_stream_event);
});
let tb = TestApp::start(app).await?;
tb.broker::<RedisTestBroker>()
.publish("events", &payment(1, 100))
.await?;
tb.broker::<RedisTestBroker>()
.subscriber("events")
.assert_called_once()
.settled(HandlerResult::Ack);
tb.shutdown().await?;
Ok(())
}
async fn test_list_delivery() -> Result<(), Box<dyn std::error::Error>> {
let app =
RustStream::new(AppInfo::new("test", "0.1.0")).with_broker(RedisTestBroker::new(), |b| {
b.include(handle_list_job);
});
let tb = TestApp::start(app).await?;
tb.broker::<RedisTestBroker>()
.publish("jobs", &payment(1, 100))
.await?;
tb.broker::<RedisTestBroker>()
.subscriber("jobs")
.assert_called_once()
.settled(HandlerResult::Ack);
tb.shutdown().await?;
Ok(())
}
async fn test_pubsub_delivery() -> Result<(), Box<dyn std::error::Error>> {
let app =
RustStream::new(AppInfo::new("test", "0.1.0")).with_broker(RedisTestBroker::new(), |b| {
b.include(handle_pubsub_notification);
});
let tb = TestApp::start(app).await?;
tb.broker::<RedisTestBroker>()
.publish("notifications", &payment(1, 100))
.await?;
tb.broker::<RedisTestBroker>()
.subscriber("notifications")
.assert_called_once()
.settled(HandlerResult::Ack);
tb.shutdown().await?;
Ok(())
}
async fn test_conformance_suite() -> Result<(), Box<dyn std::error::Error>> {
harness::run_suite(RedisTestBroker::new).await;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn valid_payment_is_saved_and_invalid_is_dropped() {
let repository = PaymentRepository::default();
let repository_for_app = repository.clone();
let app = RustStream::new(AppInfo::new("test", "0.1.0"))
.on_startup(
move |()| async move { Ok::<_, std::convert::Infallible>(repository_for_app) },
)
.with_broker(RedisTestBroker::new(), |b| {
b.include(process_payment);
});
let tb = TestApp::start(app).await.expect("startup failed");
tb.broker::<RedisTestBroker>()
.publish("payments", &payment(1, 100))
.await
.expect("publish valid");
tb.broker::<RedisTestBroker>()
.publish("payments", &payment(2, 0))
.await
.expect("publish invalid");
assert!(repository.contains(1).await);
assert!(!repository.contains(2).await);
assert_eq!(repository.count().await, 1);
tb.shutdown().await.expect("graceful shutdown failed");
}
}