1use std::marker::PhantomData;
37
38use serde::{Deserialize, Deserializer, Serialize, de::DeserializeOwned};
39
40use crate::Domain;
41
42pub trait Message: Serialize + DeserializeOwned + Send + Sync + 'static {
44 const DOMAIN: &'static str;
46 const TYPE: &'static str;
48 fn declare(domain: &Domain);
51}
52
53pub trait EventType: Message {}
55
56pub trait CommandType: Message {
58 const AGGREGATE: &'static str;
60}
61
62pub trait QueryType: Message {
69 type Answer: Serialize + DeserializeOwned;
71}
72
73pub struct Of<M>(PhantomData<fn() -> M>);
76
77impl<M> Of<M> {
78 #[doc(hidden)]
79 pub const fn new() -> Self {
80 Of(PhantomData)
81 }
82}
83
84impl<M> Clone for Of<M> {
85 fn clone(&self) -> Self {
86 *self
87 }
88}
89
90impl<M> Copy for Of<M> {}
91
92#[doc(hidden)]
94pub struct Key {
95 pub(crate) domain: Option<&'static str>,
97 pub(crate) name: String,
98 pub(crate) declare: Option<fn(&Domain)>,
99}
100
101pub trait TypeKey<D> {
105 #[doc(hidden)]
106 fn key(self) -> Key;
107}
108
109impl<D> TypeKey<D> for &str {
110 fn key(self) -> Key {
111 Key {
112 domain: None,
113 name: self.to_owned(),
114 declare: None,
115 }
116 }
117}
118
119impl<M: Message> TypeKey<M> for Of<M> {
120 fn key(self) -> Key {
121 Key {
122 domain: Some(M::DOMAIN),
123 name: M::TYPE.to_owned(),
124 declare: Some(M::declare),
125 }
126 }
127}
128
129impl Key {
130 pub(crate) fn within(self, domain: &Domain, what: &str) -> String {
132 if let Some(own) = self.domain {
133 assert!(
134 own == domain.name(),
135 "{own}.{} belongs to {own}; {what} of {} takes the types of its own domain",
136 self.name,
137 domain.name()
138 );
139 if let Some(declare) = self.declare {
140 domain.declare_once(&self.name, declare);
141 }
142 }
143 self.name
144 }
145
146 pub(crate) fn qualified_for(&self, domain: &Domain) -> String {
148 match self.domain {
149 Some(own) if own != domain.name() => format!("{own}.{}", self.name),
150 _ => self.name.clone(),
151 }
152 }
153}
154
155pub(crate) fn domain_of<M: Message>() -> Domain {
157 let d = crate::domain(M::DOMAIN);
158 d.declare_once(M::TYPE, M::declare);
159 d
160}
161
162#[doc(hidden)]
163pub mod __private {
164 pub use serde;
165 pub use serde_json;
166
167 use super::{Deserialize, Deserializer};
168
169 pub fn null_as_default<'de, D: Deserializer<'de>, T: Deserialize<'de> + Default>(
171 d: D,
172 ) -> Result<T, D::Error> {
173 Ok(Option::<T>::deserialize(d)?.unwrap_or_default())
174 }
175}
176
177#[cfg(test)]
178mod tests {
179 use serde::{Deserialize, Serialize};
180 use serde_json::{Value, json};
181
182 use crate::{
183 CommandContext, FoldEvent, NewEvent, Query, RequestContext, Submit, Timestamp, command,
184 domain, event, query,
185 };
186
187 fn own(_d: &Value, id: &str) -> String {
188 format!("account:{id}")
189 }
190
191 #[event("shopt", version = 2, upcasts = add_note, personal(fields = [email_address], subject = own))]
192 #[derive(Clone, Debug, PartialEq)]
193 pub struct Placed {
194 pub customer_id: String,
195 pub email_address: String,
196 pub note: Option<String>,
197 pub r#type: String,
198 }
199
200 fn add_note(schema: crate::EventSchema) -> crate::EventSchema {
201 schema.upcast(1, |mut d| {
202 d["type"] = json!("v1");
203 d
204 })
205 }
206
207 #[event("shopt")]
208 pub struct Cancelled {}
209
210 #[command("shopt", aggregate = "order", secret = [password])]
211 pub struct Place {
212 pub customer_id: String,
213 pub password: String,
214 }
215
216 #[query("shopt", answer = Vec<String>)]
217 pub struct ListOrders {
218 pub status: Option<String>,
219 }
220
221 #[query("shopt", answer = Vec<String>, target(aggregate = "order", field = order_id))]
222 pub struct GetOrder {
223 pub order_id: String,
224 }
225
226 #[derive(Clone, Default, Serialize, Deserialize)]
227 struct Order {
228 customer: String,
229 cancelled: bool,
230 }
231
232 #[test]
233 fn fields_are_camel_case_and_an_event_writes_none_as_null() {
234 let p = Placed {
235 customer_id: "c1".into(),
236 email_address: "a@b".into(),
237 note: None,
238 r#type: "x".into(),
239 };
240 assert_eq!(
241 serde_json::to_value(&p).unwrap(),
242 json!({ "customerId": "c1", "emailAddress": "a@b", "note": null, "type": "x" })
243 );
244 assert_eq!(
246 serde_json::to_value(ListOrders { status: None }).unwrap(),
247 json!({})
248 );
249 let back: Placed = serde_json::from_value(
251 json!({ "customerId": "c1", "emailAddress": null, "type": "x" }),
252 )
253 .unwrap();
254 assert_eq!(back.email_address, "");
255 assert_eq!(back.note, None);
256 }
257
258 #[test]
259 fn apply_and_command_take_the_type_and_declare_its_schema() {
260 let shop = domain("shopt");
261 let order = shop.aggregate("order", Order::default());
262 order.apply(Placed, |s, d, _, _| s.customer = d.customer_id);
263 order.apply(Cancelled, |s, _d, _, _| s.cancelled = true);
264 order.command(Place, |_s, d, _, _| {
265 Ok(vec![
266 Placed {
267 customer_id: d.customer_id,
268 email_address: "a@b".into(),
269 note: None,
270 r#type: "t".into(),
271 }
272 .into(),
273 ])
274 });
275 assert_eq!(shop.schema_of("Placed"), 2);
277 let v1 = FoldEvent {
278 schema: 1,
279 ..FoldEvent::new(
280 "Placed",
281 json!({ "customerId": "c1", "emailAddress": "a@b" }),
282 )
283 };
284 let state = order.fold([v1], None).unwrap();
285 assert_eq!(state.customer, "c1");
286 let mut ctx = CommandContext::new("cmd-1", RequestContext::default(), Timestamp(0));
287 let events = order
288 .handle(
289 &state,
290 "Place",
291 json!({ "customerId": "c2", "password": "p" }),
292 &mut ctx,
293 )
294 .unwrap();
295 assert_eq!(
296 events,
297 vec![NewEvent::new(
298 "Placed",
299 json!({ "customerId": "c2", "emailAddress": "a@b", "note": null, "type": "t" })
300 )]
301 );
302 assert_eq!(
304 shop.command_vault("Place").unwrap().secret,
305 vec!["password"]
306 );
307 assert_eq!(
308 shop.event_def("Placed").unwrap().vault.personal[0].0,
309 vec!["emailAddress"]
310 );
311 }
312
313 #[test]
314 #[should_panic(expected = "belongs to shopt")]
315 fn another_domain_s_message_type_is_refused() {
316 domain("other")
317 .aggregate("order", Order::default())
318 .apply(Placed, |_, _, _, _| {});
319 }
320
321 #[test]
322 fn a_listener_learns_another_domain_s_event_schema() {
323 let billing = domain("billingt");
324 let listener = billing
325 .read_model("orders")
326 .on(Placed, |d, _evt, _ctx| async move {
327 assert!(!d.customer_id.is_empty());
328 Ok(())
329 });
330 assert_eq!(
331 listener.domain_of("shopt").map(|d| d.schema_of("Placed")),
332 Some(2)
333 );
334 listener.query(ListOrders, |_d, _q, _ctx| async move {
335 Ok(vec!["o1".to_owned()])
336 });
337 }
338
339 #[test]
340 fn submit_and_query_carry_the_type() {
341 let s = Submit::command(
342 Place {
343 customer_id: "c".into(),
344 password: "p".into(),
345 },
346 "o1",
347 );
348 let shown = format!("{s:?}");
349 assert!(
350 shown.contains("domain: \"shopt\"")
351 && shown.contains("aggregate_type: \"order\"")
352 && shown.contains("command_type: \"Place\""),
353 "{shown}"
354 );
355 assert!(shown.contains("secret: [\"password\"]"), "{shown}");
356 let q = format!("{:?}", Query::of(ListOrders { status: None }));
357 assert!(
358 q.contains("query_type: \"ListOrders\"") && q.contains("data: Object {}"),
359 "{q}"
360 );
361 assert!(q.contains("target: None"), "{q}");
362 }
363
364 #[test]
365 fn a_query_declares_its_target_and_sends_it_qualified_with_the_id_from_its_data() {
366 let target = crate::messages::domain_of::<GetOrder>()
367 .query_target("GetOrder")
368 .unwrap();
369 assert_eq!(
370 target,
371 crate::QueryTarget {
372 aggregate_type: "order".into(),
373 field: "orderId".into(),
374 }
375 );
376 let q = format!(
377 "{:?}",
378 Query::of(GetOrder {
379 order_id: "o1".into()
380 })
381 );
382 assert!(q.contains("field: \"orderId\""), "{q}");
383 let wire = target.wire("shopt", &json!({ "orderId": "o1" })).unwrap();
384 assert_eq!(
385 (wire.aggregate_type.as_str(), wire.aggregate_id.as_str()),
386 ("shopt.order", "o1")
387 );
388 for data in [json!({}), json!({ "orderId": "" }), json!({ "orderId": 7 })] {
390 assert!(target.wire("shopt", &data).is_none());
391 }
392 let shop = domain("shopt2");
394 shop.query("GetCustomer")
395 .target("crm.customer", "customerId");
396 let wire = shop
397 .query_target("GetCustomer")
398 .unwrap()
399 .wire("shopt2", &json!({ "customerId": "c1" }))
400 .unwrap();
401 assert_eq!(wire.aggregate_type, "crm.customer");
402 assert_eq!(shop.query_target("Other"), None);
403 }
404
405 #[test]
406 fn a_read_model_answering_a_query_type_declares_its_target_on_its_domain() {
407 let shop = domain("shopt");
409 shop.read_model("orders")
410 .query(GetOrder, |_d, _q, _ctx| async move { Ok(()) });
411 assert_eq!(
412 shop.query_target("GetOrder").map(|t| t.field),
413 Some("orderId".to_owned())
414 );
415 let other = domain("shopt");
417 other.query("GetOrder").target("customer", "customerId");
418 other
419 .read_model("orders")
420 .query(GetOrder, |_d, _q, _ctx| async move { Ok(()) });
421 assert_eq!(
422 other.query_target("GetOrder").map(|t| t.aggregate_type),
423 Some("customer".to_owned())
424 );
425 }
426}