use std::error::Error;
use std::future::{Future, ready};
use ruststream::memory::prelude::*;
use ruststream::runtime::{BlanketLayer, Handler, Identity, Layer, Stack};
use serde::Deserialize;
#[derive(Debug, Deserialize, schemars::JsonSchema)]
struct Order {
id: u64,
}
struct Orders;
impl Handle<Order> for Orders {
fn handle(
&self,
order: &Order,
_outs: &(),
_ctx: &mut Context<'_>,
) -> impl Future<Output = Result<(), HandlerOutcome>> {
println!("got order {}", order.id);
ready(Ok(()))
}
}
struct Shipments;
impl Handle<Order> for Shipments {
fn handle(
&self,
order: &Order,
_outs: &(),
_ctx: &mut Context<'_>,
) -> impl Future<Output = Result<(), HandlerOutcome>> {
println!("got shipment for order {}", order.id);
ready(Ok(()))
}
}
struct Audit;
impl Handle<Order> for Audit {
fn handle(
&self,
order: &Order,
_outs: &(),
_ctx: &mut Context<'_>,
) -> impl Future<Output = Result<(), HandlerOutcome>> {
println!("audited order {}", order.id);
ready(Ok(()))
}
}
#[derive(Clone)]
struct LogLayer;
struct Logged<H>(H);
impl<H> Layer<H> for LogLayer {
type Handler = Logged<H>;
fn layer(&self, inner: H) -> Logged<H> {
Logged(inner)
}
}
impl<M: Send + Sync, C: Send, S: Send + Sync, H: Handler<M, C, S>> Handler<M, C, S> for Logged<H> {
async fn handle(&self, msg: &M, ctx: &mut Context<'_, C, S>) -> HandlerOutcome {
println!("app layer -> {}", ctx.name());
self.0.handle(msg, ctx).await
}
}
impl BlanketLayer for LogLayer {
fn apply<M, C, S, H>(&self, handler: H) -> impl Handler<M, C, S> + 'static
where
M: Send + Sync + 'static,
C: Send + 'static,
S: Send + Sync + 'static,
H: Handler<M, C, S> + 'static,
{
Logged(handler)
}
}
fn app() -> RustStream<Stack<LogLayer, Identity>> {
RustStream::new(AppInfo::new("app-scope", "0.1.0"))
.layer(LogLayer)
.with_broker(MemoryBroker::new(), |b| {
b.include(subscriber("orders", Orders).build());
b.include(subscriber("shipments", Shipments).build());
b.include_router(Router::new().include(subscriber("audit", Audit).build()));
})
}
#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
app().run().await?;
Ok(())
}