#![cfg_attr(not(test), allow(dead_code, unused_imports))]
use std::error::Error;
use std::future::{Future, ready};
use ruststream::memory::prelude::*;
use ruststream::testing::TestApp;
use serde::{Deserialize, Serialize};
#[derive(Debug, PartialEq, Deserialize, Serialize, Outgoing)]
struct Order {
id: u64,
}
struct Tenant(String);
impl<C: Send, S: Sync> FromContext<C, S> for Tenant {
type Rejection = HandlerOutcome;
fn from_context(
ctx: &mut Context<'_, C, S>,
) -> impl Future<Output = Result<Self, HandlerOutcome>> + Send {
let tenant = ctx.headers().get("x-tenant");
let tenant = tenant.map(|tenant| Self(String::from_utf8_lossy(tenant).into_owned()));
ready(tenant.ok_or_else(HandlerOutcome::drop))
}
}
#[derive(Debug, PartialEq, Deserialize, Serialize, Outgoing)]
#[outgoing(name = "accepted")]
struct Accepted {
order: u64,
tenant: String,
}
#[subscriber("orders", reply)]
async fn accept(order: &Order, Tenant(tenant): Tenant) -> Accepted {
Accepted {
order: order.id,
tenant,
}
}
fn app() -> impl App {
RustStream::new(AppInfo::new("orders", "0.1.0")).with_broker(MemoryBroker::new(), |b| {
b.include(accept);
})
}
#[tokio::test]
async fn an_order_without_a_tenant_is_dropped() -> Result<(), Box<dyn Error>> {
let tb = TestApp::start(app()).await?;
let broker = tb.broker::<MemoryBroker>();
let mut headers = HeaderMap::new();
headers.insert("x-tenant", "acme");
broker
.message(&Order { id: 7 })
.to("orders")
.with_headers(headers)
.publish()
.await?;
broker
.message(&Order { id: 8 })
.to("orders")
.publish()
.await?;
broker
.subscriber("orders")
.assert_called(2)
.settled(HandlerOutcome::drop());
broker
.published::<Accepted>("accepted")
.assert_called_once()
.with(&Accepted {
order: 7,
tenant: "acme".to_owned(),
});
Ok(())
}
fn main() {}