use std::marker::PhantomData;
use serde::{Deserialize, Deserializer, Serialize, de::DeserializeOwned};
use crate::Domain;
pub trait Message: Serialize + DeserializeOwned + Send + Sync + 'static {
const DOMAIN: &'static str;
const TYPE: &'static str;
fn declare(domain: &Domain);
}
pub trait EventType: Message {}
pub trait CommandType: Message {
const AGGREGATE: &'static str;
}
pub trait QueryType: Message {
type Answer: Serialize + DeserializeOwned;
}
pub struct Of<M>(PhantomData<fn() -> M>);
impl<M> Of<M> {
#[doc(hidden)]
pub const fn new() -> Self {
Of(PhantomData)
}
}
impl<M> Clone for Of<M> {
fn clone(&self) -> Self {
*self
}
}
impl<M> Copy for Of<M> {}
#[doc(hidden)]
pub struct Key {
pub(crate) domain: Option<&'static str>,
pub(crate) name: String,
pub(crate) declare: Option<fn(&Domain)>,
}
pub trait TypeKey<D> {
#[doc(hidden)]
fn key(self) -> Key;
}
impl<D> TypeKey<D> for &str {
fn key(self) -> Key {
Key {
domain: None,
name: self.to_owned(),
declare: None,
}
}
}
impl<M: Message> TypeKey<M> for Of<M> {
fn key(self) -> Key {
Key {
domain: Some(M::DOMAIN),
name: M::TYPE.to_owned(),
declare: Some(M::declare),
}
}
}
impl Key {
pub(crate) fn within(self, domain: &Domain, what: &str) -> String {
if let Some(own) = self.domain {
assert!(
own == domain.name(),
"{own}.{} belongs to {own}; {what} of {} takes the types of its own domain",
self.name,
domain.name()
);
if let Some(declare) = self.declare {
domain.declare_once(&self.name, declare);
}
}
self.name
}
pub(crate) fn qualified_for(&self, domain: &Domain) -> String {
match self.domain {
Some(own) if own != domain.name() => format!("{own}.{}", self.name),
_ => self.name.clone(),
}
}
}
pub(crate) fn domain_of<M: Message>() -> Domain {
let d = crate::domain(M::DOMAIN);
d.declare_once(M::TYPE, M::declare);
d
}
#[doc(hidden)]
pub mod __private {
pub use serde;
pub use serde_json;
use super::{Deserialize, Deserializer};
pub fn null_as_default<'de, D: Deserializer<'de>, T: Deserialize<'de> + Default>(
d: D,
) -> Result<T, D::Error> {
Ok(Option::<T>::deserialize(d)?.unwrap_or_default())
}
}
#[cfg(test)]
mod tests {
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::{
CommandContext, FoldEvent, NewEvent, Query, RequestContext, Submit, Timestamp, command,
domain, event, query,
};
fn own(_d: &Value, id: &str) -> String {
format!("account:{id}")
}
#[event("shopt", version = 2, upcasts = add_note, personal(fields = [email_address], subject = own))]
#[derive(Clone, Debug, PartialEq)]
pub struct Placed {
pub customer_id: String,
pub email_address: String,
pub note: Option<String>,
pub r#type: String,
}
fn add_note(schema: crate::EventSchema) -> crate::EventSchema {
schema.upcast(1, |mut d| {
d["type"] = json!("v1");
d
})
}
#[event("shopt")]
pub struct Cancelled {}
#[command("shopt", aggregate = "order", secret = [password])]
pub struct Place {
pub customer_id: String,
pub password: String,
}
#[query("shopt", answer = Vec<String>)]
pub struct ListOrders {
pub status: Option<String>,
}
#[query("shopt", answer = Vec<String>, target(aggregate = "order", field = order_id))]
pub struct GetOrder {
pub order_id: String,
}
#[derive(Clone, Default, Serialize, Deserialize)]
struct Order {
customer: String,
cancelled: bool,
}
#[test]
fn fields_are_camel_case_and_an_event_writes_none_as_null() {
let p = Placed {
customer_id: "c1".into(),
email_address: "a@b".into(),
note: None,
r#type: "x".into(),
};
assert_eq!(
serde_json::to_value(&p).unwrap(),
json!({ "customerId": "c1", "emailAddress": "a@b", "note": null, "type": "x" })
);
assert_eq!(
serde_json::to_value(ListOrders { status: None }).unwrap(),
json!({})
);
let back: Placed = serde_json::from_value(
json!({ "customerId": "c1", "emailAddress": null, "type": "x" }),
)
.unwrap();
assert_eq!(back.email_address, "");
assert_eq!(back.note, None);
}
#[test]
fn apply_and_command_take_the_type_and_declare_its_schema() {
let shop = domain("shopt");
let order = shop.aggregate("order", Order::default());
order.apply(Placed, |s, d, _, _| s.customer = d.customer_id);
order.apply(Cancelled, |s, _d, _, _| s.cancelled = true);
order.command(Place, |_s, d, _, _| {
Ok(vec![
Placed {
customer_id: d.customer_id,
email_address: "a@b".into(),
note: None,
r#type: "t".into(),
}
.into(),
])
});
assert_eq!(shop.schema_of("Placed"), 2);
let v1 = FoldEvent {
schema: 1,
..FoldEvent::new(
"Placed",
json!({ "customerId": "c1", "emailAddress": "a@b" }),
)
};
let state = order.fold([v1], None).unwrap();
assert_eq!(state.customer, "c1");
let mut ctx = CommandContext::new("cmd-1", RequestContext::default(), Timestamp(0));
let events = order
.handle(
&state,
"Place",
json!({ "customerId": "c2", "password": "p" }),
&mut ctx,
)
.unwrap();
assert_eq!(
events,
vec![NewEvent::new(
"Placed",
json!({ "customerId": "c2", "emailAddress": "a@b", "note": null, "type": "t" })
)]
);
assert_eq!(
shop.command_vault("Place").unwrap().secret,
vec!["password"]
);
assert_eq!(
shop.event_def("Placed").unwrap().vault.personal[0].0,
vec!["emailAddress"]
);
}
#[test]
#[should_panic(expected = "belongs to shopt")]
fn another_domain_s_message_type_is_refused() {
domain("other")
.aggregate("order", Order::default())
.apply(Placed, |_, _, _, _| {});
}
#[test]
fn a_listener_learns_another_domain_s_event_schema() {
let billing = domain("billingt");
let listener = billing
.read_model("orders")
.on(Placed, |d, _evt, _ctx| async move {
assert!(!d.customer_id.is_empty());
Ok(())
});
assert_eq!(
listener.domain_of("shopt").map(|d| d.schema_of("Placed")),
Some(2)
);
listener.query(ListOrders, |_d, _q, _ctx| async move {
Ok(vec!["o1".to_owned()])
});
}
#[test]
fn submit_and_query_carry_the_type() {
let s = Submit::command(
Place {
customer_id: "c".into(),
password: "p".into(),
},
"o1",
);
let shown = format!("{s:?}");
assert!(
shown.contains("domain: \"shopt\"")
&& shown.contains("aggregate_type: \"order\"")
&& shown.contains("command_type: \"Place\""),
"{shown}"
);
assert!(shown.contains("secret: [\"password\"]"), "{shown}");
let q = format!("{:?}", Query::of(ListOrders { status: None }));
assert!(
q.contains("query_type: \"ListOrders\"") && q.contains("data: Object {}"),
"{q}"
);
assert!(q.contains("target: None"), "{q}");
}
#[test]
fn a_query_declares_its_target_and_sends_it_qualified_with_the_id_from_its_data() {
let target = crate::messages::domain_of::<GetOrder>()
.query_target("GetOrder")
.unwrap();
assert_eq!(
target,
crate::QueryTarget {
aggregate_type: "order".into(),
field: "orderId".into(),
}
);
let q = format!(
"{:?}",
Query::of(GetOrder {
order_id: "o1".into()
})
);
assert!(q.contains("field: \"orderId\""), "{q}");
let wire = target.wire("shopt", &json!({ "orderId": "o1" })).unwrap();
assert_eq!(
(wire.aggregate_type.as_str(), wire.aggregate_id.as_str()),
("shopt.order", "o1")
);
for data in [json!({}), json!({ "orderId": "" }), json!({ "orderId": 7 })] {
assert!(target.wire("shopt", &data).is_none());
}
let shop = domain("shopt2");
shop.query("GetCustomer")
.target("crm.customer", "customerId");
let wire = shop
.query_target("GetCustomer")
.unwrap()
.wire("shopt2", &json!({ "customerId": "c1" }))
.unwrap();
assert_eq!(wire.aggregate_type, "crm.customer");
assert_eq!(shop.query_target("Other"), None);
}
#[test]
fn a_read_model_answering_a_query_type_declares_its_target_on_its_domain() {
let shop = domain("shopt");
shop.read_model("orders")
.query(GetOrder, |_d, _q, _ctx| async move { Ok(()) });
assert_eq!(
shop.query_target("GetOrder").map(|t| t.field),
Some("orderId".to_owned())
);
let other = domain("shopt");
other.query("GetOrder").target("customer", "customerId");
other
.read_model("orders")
.query(GetOrder, |_d, _q, _ctx| async move { Ok(()) });
assert_eq!(
other.query_target("GetOrder").map(|t| t.aggregate_type),
Some("customer".to_owned())
);
}
}