1use std::{
4 collections::{HashMap, HashSet},
5 panic::{AssertUnwindSafe, catch_unwind},
6 sync::{Arc, Mutex, RwLock},
7};
8
9use kernable_core::{proto, signing};
10use serde::{Serialize, de::DeserializeOwned};
11use serde_json::{Map, Value};
12
13use crate::{
14 BoxError, Error, Listener, Rejected, RequestContext,
15 context::Timestamp,
16 index::{Index, KeySubject, Requirement, Unique, UniqueKey, reindex_type},
17 messages::{EventType, TypeKey},
18 vault::{self, VaultFields},
19};
20
21type Upcast = Arc<dyn Fn(Value) -> Value + Send + Sync>;
22pub(crate) type Subject = Arc<dyn Fn(&Value, &str) -> String + Send + Sync>;
24
25#[derive(Clone, Default)]
26pub(crate) struct EventDef {
27 pub schema: u32,
28 pub steps: HashMap<u32, Upcast>,
29 pub vault: VaultFields,
30 pub eraser: Option<Subject>,
31}
32
33struct DomainInner {
34 name: String,
35 events: RwLock<HashMap<String, EventDef>>,
36 commands: RwLock<HashMap<String, VaultFields>>,
37 queries: RwLock<HashMap<String, Option<QueryTarget>>>,
39 aggregates: RwLock<Vec<Arc<dyn Runnable>>>,
41 listeners: RwLock<Vec<Listener>>,
43 processes: RwLock<Vec<crate::process::Process>>,
45 declared: RwLock<HashSet<String>>,
47}
48
49#[derive(Clone)]
58pub struct Domain {
59 inner: Arc<DomainInner>,
60}
61
62pub fn domain(name: &str) -> Domain {
70 let valid = name.starts_with(|c: char| c.is_ascii_alphabetic())
71 && name
72 .chars()
73 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
74 assert!(valid, "invalid domain name {name:?}");
75 Domain {
76 inner: Arc::new(DomainInner {
77 name: name.to_owned(),
78 events: RwLock::default(),
79 commands: RwLock::default(),
80 queries: RwLock::default(),
81 aggregates: RwLock::default(),
82 listeners: RwLock::default(),
83 processes: RwLock::default(),
84 declared: RwLock::default(),
85 }),
86 }
87}
88
89impl Domain {
90 pub fn name(&self) -> &str {
92 &self.inner.name
93 }
94
95 pub fn event(&self, event_type: &str, schema: u32) -> EventSchema {
104 assert!(
105 unqualified(event_type),
106 "event types are unqualified within their domain, not {event_type:?}"
107 );
108 assert!(schema >= 1, "a schema is a version from 1, not {schema}");
109 self.inner.events.write().unwrap().insert(
110 event_type.to_owned(),
111 EventDef {
112 schema,
113 ..EventDef::default()
114 },
115 );
116 EventSchema {
117 domain: self.clone(),
118 event_type: event_type.to_owned(),
119 }
120 }
121
122 pub fn command(&self, command_type: &str) -> CommandSchema {
130 assert!(
131 unqualified(command_type),
132 "command types are unqualified within their domain, not {command_type:?}"
133 );
134 self.inner
135 .commands
136 .write()
137 .unwrap()
138 .insert(command_type.to_owned(), VaultFields::default());
139 CommandSchema {
140 domain: self.clone(),
141 command_type: command_type.to_owned(),
142 }
143 }
144
145 pub fn query(&self, query_type: &str) -> QuerySchema {
154 assert!(
155 unqualified(query_type),
156 "query types are unqualified within their domain, not {query_type:?}"
157 );
158 self.inner
159 .queries
160 .write()
161 .unwrap()
162 .insert(query_type.to_owned(), None);
163 QuerySchema {
164 domain: self.clone(),
165 query_type: query_type.to_owned(),
166 }
167 }
168
169 pub fn process(&self, name: &str) -> crate::process::Process {
179 let valid = !name.is_empty()
180 && name
181 .chars()
182 .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
183 assert!(valid, "invalid process name {name:?}");
184 let process = crate::process::Process::new(self.name(), name);
185 let mut processes = self.inner.processes.write().unwrap();
186 let qualified = process.name();
187 assert!(
188 !processes.iter().any(|p| p.name() == qualified),
189 "{} has a process {name} already",
190 self.inner.name
191 );
192 processes.push(process.clone());
193 process
194 }
195
196 pub(crate) fn processes(&self) -> Vec<crate::process::Process> {
198 self.inner.processes.read().unwrap().clone()
199 }
200
201 pub fn aggregate<S: State>(&self, name: &str, initial: S) -> Aggregate<S> {
209 let taken = self.aggregates().iter().any(|a| a.name() == name);
210 assert!(
211 !taken,
212 "{} has an aggregate {name} already",
213 self.inner.name
214 );
215 let aggregate = Aggregate {
216 inner: Arc::new(AggregateInner {
217 domain: self.clone(),
218 name: name.to_owned(),
219 initial,
220 settings: Mutex::new((100, "1".to_owned())),
221 appliers: RwLock::default(),
222 handlers: RwLock::default(),
223 keys: RwLock::default(),
224 facts: RwLock::default(),
225 requires: RwLock::default(),
226 }),
227 };
228 self.inner
229 .aggregates
230 .write()
231 .unwrap()
232 .push(Arc::new(aggregate.clone()));
233 aggregate
234 }
235
236 pub fn read_model(&self, name: &str) -> Listener {
246 self.remember(Listener::new(self, name, 0, Some(0), 0, false))
247 }
248
249 pub fn reactor(&self, name: &str) -> Listener {
261 self.remember(Listener::new(
262 self,
263 name,
264 10,
265 None,
266 crate::listener::PARK_AFTER,
267 true,
268 ))
269 }
270
271 fn remember(&self, listener: Listener) -> Listener {
272 let taken = self.listeners().iter().any(|l| l.name() == listener.name());
273 assert!(
274 !taken,
275 "{} has a listener {} already",
276 self.inner.name,
277 listener.name()
278 );
279 self.inner.listeners.write().unwrap().push(listener.clone());
280 listener
281 }
282
283 pub(crate) fn aggregates(&self) -> Vec<Arc<dyn Runnable>> {
285 self.inner.aggregates.read().unwrap().clone()
286 }
287
288 pub(crate) fn listeners(&self) -> Vec<Listener> {
290 self.inner.listeners.read().unwrap().clone()
291 }
292
293 pub(crate) fn event_def(&self, event_type: &str) -> Option<EventDef> {
294 self.inner.events.read().unwrap().get(event_type).cloned()
295 }
296
297 pub(crate) fn event_types(&self) -> Vec<String> {
298 self.inner.events.read().unwrap().keys().cloned().collect()
299 }
300
301 pub(crate) fn command_vault(&self, command_type: &str) -> Option<VaultFields> {
302 self.inner
303 .commands
304 .read()
305 .unwrap()
306 .get(command_type)
307 .cloned()
308 }
309
310 pub(crate) fn query_target(&self, query_type: &str) -> Option<QueryTarget> {
312 self.inner
313 .queries
314 .read()
315 .unwrap()
316 .get(query_type)
317 .cloned()
318 .flatten()
319 }
320
321 pub(crate) fn declare_once(&self, message_type: &str, declare: fn(&Domain)) {
324 let by_name = self.event_def(message_type).is_some()
325 || self.command_vault(message_type).is_some()
326 || self
327 .inner
328 .queries
329 .read()
330 .unwrap()
331 .contains_key(message_type);
332 if self
333 .inner
334 .declared
335 .write()
336 .unwrap()
337 .insert(message_type.to_owned())
338 && !by_name
339 {
340 declare(self);
341 }
342 }
343
344 pub fn schema_of(&self, event_type: &str) -> u32 {
346 self.event_def(event_type).map_or(1, |d| d.schema)
347 }
348
349 pub(crate) fn upcast(
352 &self,
353 event_type: &str,
354 schema: u32,
355 data: Value,
356 ) -> Result<Value, SchemaError> {
357 upcast(Some(self), &self.inner.name, event_type, schema, data)
358 }
359}
360
361fn unqualified(t: &str) -> bool {
362 !t.is_empty() && !t.contains(['.', '*'])
363}
364
365pub struct EventSchema {
374 domain: Domain,
375 event_type: String,
376}
377
378impl EventSchema {
379 fn update(&self, f: impl FnOnce(&mut EventDef)) {
380 let mut events = self.domain.inner.events.write().unwrap();
381 f(events
382 .get_mut(&self.event_type)
383 .expect("declared by Domain::event"));
384 }
385
386 pub fn personal(
391 self,
392 fields: &[&str],
393 subject: impl Fn(&Value, &str) -> String + Send + Sync + 'static,
394 ) -> Self {
395 let fields = fields.iter().map(|f| (*f).to_owned()).collect();
396 self.update(|d| d.vault.personal.push((fields, Arc::new(subject))));
397 self
398 }
399
400 pub fn erases(self, subject: impl Fn(&Value, &str) -> String + Send + Sync + 'static) -> Self {
404 self.update(|d| d.eraser = Some(Arc::new(subject)));
405 self
406 }
407
408 pub fn upcast(self, from: u32, step: impl Fn(Value) -> Value + Send + Sync + 'static) -> Self {
415 self.update(|d| {
416 assert!(
417 from >= 1 && from < d.schema,
418 "upcast {} from a version between 1 and {}, not {from}",
419 self.event_type,
420 d.schema - 1
421 );
422 d.steps.insert(from, Arc::new(step));
423 });
424 self
425 }
426}
427
428pub struct CommandSchema {
433 domain: Domain,
434 command_type: String,
435}
436
437impl CommandSchema {
438 fn update(&self, f: impl FnOnce(&mut VaultFields)) {
439 let mut commands = self.domain.inner.commands.write().unwrap();
440 f(commands
441 .get_mut(&self.command_type)
442 .expect("declared by Domain::command"));
443 }
444
445 pub fn personal(
448 self,
449 fields: &[&str],
450 subject: impl Fn(&Value, &str) -> String + Send + Sync + 'static,
451 ) -> Self {
452 let fields = fields.iter().map(|f| (*f).to_owned()).collect();
453 self.update(|v| v.personal.push((fields, Arc::new(subject))));
454 self
455 }
456
457 pub fn secret(self, fields: &[&str]) -> Self {
460 self.update(|v| v.secret.extend(fields.iter().map(|f| (*f).to_owned())));
461 self
462 }
463}
464
465pub struct QuerySchema {
470 domain: Domain,
471 query_type: String,
472}
473
474impl QuerySchema {
475 pub fn target(self, aggregate_type: &str, field: &str) -> Self {
481 self.domain.inner.queries.write().unwrap().insert(
482 self.query_type.clone(),
483 Some(QueryTarget {
484 aggregate_type: aggregate_type.to_owned(),
485 field: field.to_owned(),
486 }),
487 );
488 self
489 }
490}
491
492#[derive(Clone, Debug, PartialEq, Eq)]
494pub struct QueryTarget {
495 pub aggregate_type: String,
497 pub field: String,
499}
500
501impl QueryTarget {
502 pub(crate) fn wire(&self, domain: &str, data: &Value) -> Option<proto::Target> {
505 let id = data
506 .get(&self.field)?
507 .as_str()
508 .filter(|id| !id.is_empty())?;
509 let aggregate_type = if self.aggregate_type.contains('.') {
510 self.aggregate_type.clone()
511 } else {
512 format!("{domain}.{}", self.aggregate_type)
513 };
514 Some(proto::Target {
515 aggregate_type,
516 aggregate_id: id.to_owned(),
517 })
518 }
519}
520
521#[derive(Debug)]
523pub(crate) struct SchemaError(pub String);
524
525impl std::fmt::Display for SchemaError {
526 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
527 f.write_str(&self.0)
528 }
529}
530
531impl std::error::Error for SchemaError {}
532
533pub(crate) fn known_schema(known: Option<&Domain>, event_type: &str) -> u32 {
536 known.map_or(1, |d| d.schema_of(event_type))
537}
538
539pub(crate) fn upcast(
542 known: Option<&Domain>,
543 domain: &str,
544 event_type: &str,
545 schema: u32,
546 mut data: Value,
547) -> Result<Value, SchemaError> {
548 let def = known.and_then(|d| d.event_def(event_type));
549 let current = def.as_ref().map_or(1, |d| d.schema);
550 if schema > current {
551 return Err(SchemaError(format!(
552 "{domain}.{event_type} has schema {schema}, but this process knows it only up to {current}: update it"
553 )));
554 }
555 for v in schema..current {
556 let step = def.as_ref().and_then(|d| d.steps.get(&v)).ok_or_else(|| {
557 SchemaError(format!(
558 "no upcast for {domain}.{event_type} from schema {v}"
559 ))
560 })?;
561 data = step(data);
562 }
563 Ok(data)
564}
565
566#[derive(Clone, Debug, PartialEq)]
569pub struct NewEvent {
570 pub event_type: String,
572 pub data: Value,
574}
575
576impl NewEvent {
577 pub fn new(event_type: &str, data: impl Serialize) -> NewEvent {
583 NewEvent {
584 event_type: event_type.to_owned(),
585 data: serde_json::to_value(data).expect("event data is JSON"),
586 }
587 }
588}
589
590impl<E: EventType> From<E> for NewEvent {
591 fn from(event: E) -> NewEvent {
593 NewEvent::new(E::TYPE, event)
594 }
595}
596
597#[derive(Clone, Debug, Default, PartialEq, Eq)]
601pub struct EventMeta {
602 pub event_type: String,
603 pub version: u64,
605 pub tenant: String,
606 pub domain: String,
607 pub aggregate_type: String,
608 pub aggregate_id: String,
609 pub command_id: String,
611}
612
613#[derive(Clone, Debug, Default, PartialEq, Eq)]
616pub struct ApplyContext {
617 pub request: RequestContext,
619}
620
621#[derive(Clone, Debug, Default, PartialEq, Eq)]
623pub struct CommandMeta {
624 pub command_id: String,
626 pub command_type: String,
628 pub domain: String,
629 pub aggregate_type: String,
630 pub aggregate_id: String,
631 pub tenant: String,
632}
633
634#[derive(Clone, Debug)]
637pub struct CommandContext {
638 pub request: RequestContext,
640 command_id: String,
641 received_at: Timestamp,
642 deadline: Timestamp,
643 ids: u64,
644 target: (String, String),
646}
647
648impl CommandContext {
649 pub fn new(
652 command_id: &str,
653 request: RequestContext,
654 received_at: Timestamp,
655 ) -> CommandContext {
656 CommandContext {
657 command_id: command_id.to_owned(),
658 request,
659 received_at,
660 deadline: Timestamp(received_at.0 + 30_000),
661 ids: 0,
662 target: (String::new(), String::new()),
663 }
664 }
665
666 pub fn on(mut self, aggregate_id: &str, tenant: &str) -> CommandContext {
669 self.target = (aggregate_id.to_owned(), tenant.to_owned());
670 self
671 }
672
673 pub fn now(&self) -> Timestamp {
676 self.received_at
677 }
678
679 pub fn id(&mut self) -> String {
682 self.ids += 1;
683 signing::derived_id(&self.command_id, self.ids - 1)
684 }
685
686 pub fn deadline(&self) -> Timestamp {
688 self.deadline
689 }
690}
691
692#[derive(Clone, Debug, Default)]
696pub struct FoldEvent {
697 pub event_type: String,
698 pub schema: u32,
699 pub data: Value,
700 pub meta: EventMeta,
701 pub request: RequestContext,
704}
705
706impl FoldEvent {
707 pub fn new(event_type: &str, data: impl Serialize) -> FoldEvent {
709 FoldEvent {
710 event_type: event_type.to_owned(),
711 schema: 1,
712 data: serde_json::to_value(data).expect("event data is JSON"),
713 meta: EventMeta::default(),
714 request: RequestContext::default(),
715 }
716 }
717}
718
719pub trait State: Clone + Serialize + DeserializeOwned + Send + Sync + 'static {}
723
724impl<S: Clone + Serialize + DeserializeOwned + Send + Sync + 'static> State for S {}
725
726type Apply<S> =
727 Arc<dyn Fn(&mut S, Value, &EventMeta, &ApplyContext) -> Result<(), BoxError> + Send + Sync>;
728type Handle<S> = Arc<
729 dyn Fn(&S, Value, &CommandMeta, &mut CommandContext) -> Result<Vec<NewEvent>, Failure>
730 + Send
731 + Sync,
732>;
733
734type Fact<S> = Arc<dyn Fn(&S) -> bool + Send + Sync>;
735type KeyValues<S> = Arc<dyn Fn(&S) -> Vec<String> + Send + Sync>;
736type Requires<S> = Arc<dyn Fn(&S, Value) -> Result<Vec<Requirement>, Failure> + Send + Sync>;
737
738struct KeyDef<S> {
740 name: String,
741 values: KeyValues<S>,
742 global: bool,
743 personal: Option<KeySubject<S>>,
744}
745
746impl<S> Clone for KeyDef<S> {
747 fn clone(&self) -> Self {
748 KeyDef {
749 name: self.name.clone(),
750 values: Arc::clone(&self.values),
751 global: self.global,
752 personal: self.personal.clone(),
753 }
754 }
755}
756
757struct AggregateInner<S> {
758 domain: Domain,
759 name: String,
760 initial: S,
761 settings: Mutex<(u64, String)>,
763 appliers: RwLock<HashMap<String, Apply<S>>>,
764 handlers: RwLock<HashMap<String, Handle<S>>>,
765 keys: RwLock<Vec<KeyDef<S>>>,
767 facts: RwLock<Vec<(String, Fact<S>)>>,
768 requires: RwLock<HashMap<String, Requires<S>>>,
770}
771
772pub struct Aggregate<S> {
802 inner: Arc<AggregateInner<S>>,
803}
804
805impl<S> Clone for Aggregate<S> {
806 fn clone(&self) -> Self {
807 Aggregate {
808 inner: Arc::clone(&self.inner),
809 }
810 }
811}
812
813#[derive(Debug)]
815pub(crate) enum Failure {
816 Rejected(Rejected),
817 Error(String),
818 Schema(String),
820}
821
822impl Failure {
823 fn into_error(self) -> Error {
825 match self {
826 Failure::Rejected(r) => Error::Rejected(r),
827 Failure::Error(m) | Failure::Schema(m) => Error::Config(m),
828 }
829 }
830}
831
832impl From<SchemaError> for Failure {
833 fn from(e: SchemaError) -> Failure {
834 Failure::Schema(e.0)
835 }
836}
837
838impl<S: State> Aggregate<S> {
839 pub fn domain(&self) -> &Domain {
841 &self.inner.domain
842 }
843
844 pub fn name(&self) -> &str {
846 &self.inner.name
847 }
848
849 pub fn initial(&self) -> &S {
851 &self.inner.initial
852 }
853
854 pub fn snapshot_every(&self, events: u64) -> Self {
856 self.inner.settings.lock().unwrap().0 = events;
857 self.clone()
858 }
859
860 pub fn schema(&self, schema: &str) -> Self {
863 self.inner.settings.lock().unwrap().1 = schema.to_owned();
864 self.clone()
865 }
866
867 pub fn apply<D: DeserializeOwned>(
874 &self,
875 event_type: impl TypeKey<D>,
876 f: impl Fn(&mut S, D, &EventMeta, &ApplyContext) + Send + Sync + 'static,
877 ) -> Self {
878 let event_type = event_type.key().within(&self.inner.domain, "apply");
879 let event_type = event_type.as_str();
880 let apply: Apply<S> = Arc::new(move |state, data, meta, ctx| {
881 let data = serde_json::from_value(data)
882 .map_err(|e| format!("{} data: {e}", meta.event_type))?;
883 f(state, data, meta, ctx);
884 Ok(())
885 });
886 self.inner
887 .appliers
888 .write()
889 .unwrap()
890 .insert(event_type.to_owned(), apply);
891 self.clone()
892 }
893
894 pub fn command<D: DeserializeOwned>(
906 &self,
907 command_type: impl TypeKey<D>,
908 f: impl Fn(&S, D, &CommandMeta, &mut CommandContext) -> Result<Vec<NewEvent>, Rejected>
909 + Send
910 + Sync
911 + 'static,
912 ) -> Self {
913 let command_type = command_type.key().within(&self.inner.domain, "command");
914 let command_type = command_type.as_str();
915 assert!(
916 !command_type.starts_with("_reindex_"),
917 "{command_type}: command types starting with _reindex_ are reserved for the built-in \
918 command of aggregates with unique keys or facts; name yours otherwise"
919 );
920 let name = command_type.to_owned();
921 let handle: Handle<S> = Arc::new(move |state, data, cmd, ctx| {
922 let data = serde_json::from_value(data)
923 .map_err(|e| Failure::Error(format!("{name} data: {e}")))?;
924 f(state, data, cmd, ctx).map_err(Failure::Rejected)
925 });
926 self.inner
927 .handlers
928 .write()
929 .unwrap()
930 .insert(command_type.to_owned(), handle);
931 self.clone()
932 }
933
934 pub fn unique<I: IntoIterator<Item = String>>(
956 &self,
957 name: &str,
958 values: impl Fn(&S) -> I + Send + Sync + 'static,
959 options: Unique<S>,
960 ) -> Self {
961 let taken = self
962 .inner
963 .keys
964 .read()
965 .unwrap()
966 .iter()
967 .any(|k| k.name == name);
968 self.declarable("key", name, taken);
969 self.inner.keys.write().unwrap().push(KeyDef {
970 name: name.to_owned(),
971 values: Arc::new(move |state| values(state).into_iter().collect()),
972 global: options.global,
973 personal: options.personal,
974 });
975 self.clone()
976 }
977
978 pub fn fact(&self, name: &str, holds: impl Fn(&S) -> bool + Send + Sync + 'static) -> Self {
988 let taken = self
989 .inner
990 .facts
991 .read()
992 .unwrap()
993 .iter()
994 .any(|(f, _)| f == name);
995 self.declarable("fact", name, taken);
996 self.inner
997 .facts
998 .write()
999 .unwrap()
1000 .push((name.to_owned(), Arc::new(holds)));
1001 self.clone()
1002 }
1003
1004 pub fn requires<D: DeserializeOwned, I: IntoIterator<Item = Requirement>>(
1018 &self,
1019 command_type: impl TypeKey<D>,
1020 f: impl Fn(&S, D) -> I + Send + Sync + 'static,
1021 ) -> Self {
1022 let command_type = command_type.key().within(&self.inner.domain, "requires");
1023 let command_type = command_type.as_str();
1024 assert!(
1025 self.handler(command_type).is_some(),
1026 "{} has no command {command_type} to require facts for: declare it first",
1027 self.inner.name
1028 );
1029 let name = command_type.to_owned();
1030 let requires: Requires<S> = Arc::new(move |state, data| {
1031 let data = serde_json::from_value(data)
1032 .map_err(|e| Failure::Error(format!("{name} data: {e}")))?;
1033 Ok(f(state, data).into_iter().collect())
1034 });
1035 self.inner
1036 .requires
1037 .write()
1038 .unwrap()
1039 .insert(command_type.to_owned(), requires);
1040 self.clone()
1041 }
1042
1043 fn declarable(&self, kind: &str, name: &str, taken: bool) {
1046 let aggregate = format!("{}.{}", self.inner.domain.name(), self.inner.name);
1047 assert!(
1048 unqualified(name) && name.len() <= 128,
1049 "{aggregate}: a {kind} name is 1 to 128 bytes without `.` or `*`, not {name:?}"
1050 );
1051 assert!(!taken, "{aggregate} declares a {kind} {name} already");
1052 }
1053
1054 fn indexed(&self) -> bool {
1056 !self.inner.keys.read().unwrap().is_empty() || !self.inner.facts.read().unwrap().is_empty()
1057 }
1058
1059 pub fn index(&self, state: &S) -> Result<Index, Error> {
1063 self.index_of(state).map_err(Failure::into_error)
1064 }
1065
1066 pub fn requirements(
1070 &self,
1071 state: &S,
1072 command_type: &str,
1073 data: impl Serialize,
1074 ) -> Result<Vec<Requirement>, Error> {
1075 let data = serde_json::to_value(data)?;
1076 self.requirements_of(state, command_type, data)
1077 .map_err(Failure::into_error)
1078 }
1079
1080 fn index_of(&self, state: &S) -> Result<Index, Failure> {
1081 let keys = self.inner.keys.read().unwrap().clone();
1082 let facts = self.inner.facts.read().unwrap().clone();
1083 caught(|| {
1084 let mut index = Index::default();
1085 for key in &keys {
1086 let subject = match &key.personal {
1087 None => None,
1088 Some(subject) => match subject(state) {
1089 Some(s) if !s.is_empty() => Some(s),
1090 _ => continue,
1091 },
1092 };
1093 let mut values: Vec<String> = Vec::new();
1094 for value in (key.values)(state) {
1095 if !values.contains(&value) {
1096 values.push(value);
1097 }
1098 }
1099 index.keys.extend(values.into_iter().map(|value| UniqueKey {
1100 name: key.name.clone(),
1101 value,
1102 global: key.global,
1103 subject: subject.clone(),
1104 }));
1105 }
1106 index.facts = facts
1107 .iter()
1108 .filter(|(_, holds)| holds(state))
1109 .map(|(name, _)| name.clone())
1110 .collect();
1111 index
1112 })
1113 }
1114
1115 fn requirements_of(
1116 &self,
1117 state: &S,
1118 command_type: &str,
1119 data: Value,
1120 ) -> Result<Vec<Requirement>, Failure> {
1121 let requires = self
1122 .inner
1123 .requires
1124 .read()
1125 .unwrap()
1126 .get(command_type)
1127 .cloned();
1128 match requires {
1129 Some(requires) => caught(|| requires(state, data))?,
1130 None => Ok(Vec::new()),
1131 }
1132 }
1133
1134 pub fn fold(
1139 &self,
1140 history: impl IntoIterator<Item = FoldEvent>,
1141 from: Option<S>,
1142 ) -> Result<S, Error> {
1143 self.fold_inner(history, from).map_err(|f| match f {
1144 Failure::Rejected(r) => Error::Rejected(r),
1145 Failure::Error(m) | Failure::Schema(m) => Error::Config(m),
1146 })
1147 }
1148
1149 fn fold_inner(
1150 &self,
1151 history: impl IntoIterator<Item = FoldEvent>,
1152 from: Option<S>,
1153 ) -> Result<S, Failure> {
1154 let mut state = from.unwrap_or_else(|| self.inner.initial.clone());
1155 let appliers = self.inner.appliers.read().unwrap();
1156 for e in history {
1157 let Some(apply) = appliers.get(&e.event_type) else {
1158 continue;
1159 };
1160 let data = self.inner.domain.upcast(&e.event_type, e.schema, e.data)?;
1161 let meta = EventMeta {
1162 event_type: e.event_type,
1163 domain: if e.meta.domain.is_empty() {
1164 self.inner.domain.name().to_owned()
1165 } else {
1166 e.meta.domain
1167 },
1168 aggregate_type: if e.meta.aggregate_type.is_empty() {
1169 self.inner.name.clone()
1170 } else {
1171 e.meta.aggregate_type
1172 },
1173 ..e.meta
1174 };
1175 let ctx = ApplyContext { request: e.request };
1176 caught(|| apply(&mut state, data, &meta, &ctx))?
1177 .map_err(|e| Failure::Error(e.to_string()))?;
1178 }
1179 Ok(state)
1180 }
1181
1182 pub fn handle(
1187 &self,
1188 state: &S,
1189 command_type: &str,
1190 data: impl Serialize,
1191 ctx: &mut CommandContext,
1192 ) -> Result<Vec<NewEvent>, Error> {
1193 let handler = self.handler(command_type).ok_or_else(|| {
1194 Error::Config(format!(
1195 "no handler for {command_type} on {}",
1196 self.inner.name
1197 ))
1198 })?;
1199 let data = serde_json::to_value(data)?;
1200 let cmd = CommandMeta {
1201 command_id: ctx.command_id.clone(),
1202 command_type: command_type.to_owned(),
1203 domain: self.inner.domain.name().to_owned(),
1204 aggregate_type: self.inner.name.clone(),
1205 aggregate_id: ctx.target.0.clone(),
1206 tenant: ctx.target.1.clone(),
1207 };
1208 match caught(|| handler(state, data, &cmd, ctx)).and_then(|r| r) {
1209 Ok(events) => Ok(events),
1210 Err(Failure::Rejected(r)) => Err(Error::Rejected(r)),
1211 Err(Failure::Error(m) | Failure::Schema(m)) => Err(Error::Config(m)),
1212 }
1213 }
1214
1215 fn handler(&self, command_type: &str) -> Option<Handle<S>> {
1216 self.inner
1217 .handlers
1218 .read()
1219 .unwrap()
1220 .get(command_type)
1221 .cloned()
1222 }
1223
1224 fn personal_in_clear(&self, command_type: &str, events: &[NewEvent]) -> Result<(), Failure> {
1228 let domain = &self.inner.domain;
1229 let Some(command) = domain.command_vault(command_type) else {
1230 return Ok(());
1231 };
1232 for e in events {
1233 let def = domain.event_def(&e.event_type);
1234 let declared = |field: &String| {
1235 def.as_ref()
1236 .is_some_and(|d| d.vault.personal.iter().any(|(f, _)| f.contains(field)))
1237 };
1238 for field in command.personal.iter().flat_map(|(fields, _)| fields) {
1239 let held = e.data.get(field).is_some_and(|v| !v.is_null());
1240 if held && !declared(field) {
1241 return Err(Failure::Rejected(
1242 Rejected::new(format!(
1243 "{command_type} declares {field} personal, but {event} does not: it \
1244 would be stored in clear (declare it with Domain.event({event:?}, \
1245 …).personal)",
1246 event = e.event_type,
1247 ))
1248 .code("personal_in_clear"),
1249 ));
1250 }
1251 }
1252 }
1253 Ok(())
1254 }
1255}
1256
1257fn caught<T>(f: impl FnOnce() -> T) -> Result<T, Failure> {
1259 catch_unwind(AssertUnwindSafe(f)).map_err(|panic| Failure::Error(panic_text(panic.as_ref())))
1260}
1261
1262pub(crate) fn panic_text(panic: &(dyn std::any::Any + Send)) -> String {
1264 panic
1265 .downcast_ref::<&str>()
1266 .map(|s| (*s).to_owned())
1267 .or_else(|| panic.downcast_ref::<String>().cloned())
1268 .unwrap_or_else(|| "handler panicked".into())
1269}
1270
1271pub(crate) struct Executed {
1273 pub events: Vec<proto::NewEvent>,
1274 pub vault: Vec<proto::VaultValue>,
1275 pub snapshot: Option<(u64, String, Vec<u8>)>,
1277 pub keys: Vec<proto::UniqueKey>,
1280 pub facts: Vec<String>,
1281 pub requires: Vec<proto::Requirement>,
1282}
1283
1284pub(crate) trait Runnable: Send + Sync {
1286 fn domain(&self) -> &Domain;
1287 fn name(&self) -> &str;
1288 fn command_types(&self) -> Vec<String>;
1289 fn event_types(&self) -> Vec<String>;
1291 fn execute(&self, x: &proto::Execute) -> Result<Executed, Failure>;
1292}
1293
1294impl<S: State> Runnable for Aggregate<S> {
1295 fn domain(&self) -> &Domain {
1296 &self.inner.domain
1297 }
1298
1299 fn name(&self) -> &str {
1300 &self.inner.name
1301 }
1302
1303 fn command_types(&self) -> Vec<String> {
1304 let mut types: Vec<String> = self
1305 .inner
1306 .handlers
1307 .read()
1308 .unwrap()
1309 .keys()
1310 .cloned()
1311 .collect();
1312 if self.indexed() {
1313 types.push(reindex_type(&self.inner.name));
1314 }
1315 types
1316 }
1317
1318 fn event_types(&self) -> Vec<String> {
1319 let mut types: Vec<String> = self
1320 .inner
1321 .appliers
1322 .read()
1323 .unwrap()
1324 .keys()
1325 .cloned()
1326 .collect();
1327 types.extend(self.inner.domain.event_types());
1328 types.sort();
1329 types.dedup();
1330 types
1331 }
1332
1333 fn execute(&self, x: &proto::Execute) -> Result<Executed, Failure> {
1334 let cmd = x.command.clone().unwrap_or_default();
1335 let (snapshot_every, schema) = self.inner.settings.lock().unwrap().clone();
1336 let from = match &x.snapshot {
1337 Some(s) if s.schema != schema => {
1338 return Err(Failure::Rejected(
1339 Rejected::new(format!("snapshot schema {} is not {schema}", s.schema))
1340 .code("snapshot_stale"),
1341 ));
1342 }
1343 Some(s) => Some(
1344 serde_json::from_slice(&s.state)
1345 .map_err(|e| Failure::Error(format!("snapshot of {}: {e}", self.inner.name)))?,
1346 ),
1347 None => None,
1348 };
1349 let history = x.history.iter().map(|e| FoldEvent {
1350 event_type: e.event_type.clone(),
1351 schema: e.schema,
1352 data: vault::unseal(decode(&e.payload), &x.vault).0,
1353 meta: meta_of(&e.event_type, e.version, &cmd, &e.command_id),
1354 request: RequestContext::from_wire(e.context.as_ref()),
1355 });
1356 let state = self.fold_inner(history.collect::<Vec<_>>(), from)?;
1357 let request = RequestContext::from_wire(cmd.context.as_ref());
1358 let meta = CommandMeta {
1359 command_id: cmd.command_id.clone(),
1360 command_type: cmd.command_type.clone(),
1361 domain: cmd.domain.clone(),
1362 aggregate_type: cmd.aggregate_type.clone(),
1363 aggregate_id: cmd.aggregate_id.clone(),
1364 tenant: cmd.tenant_id.clone(),
1365 };
1366 let mut ctx = CommandContext {
1367 command_id: cmd.command_id.clone(),
1368 request: request.clone(),
1369 received_at: Timestamp(x.received_at),
1370 deadline: Timestamp(x.deadline),
1371 ids: 0,
1372 target: (cmd.aggregate_id.clone(), cmd.tenant_id.clone()),
1373 };
1374 let indexed = self.indexed();
1375 let handler = self.handler(&cmd.command_type);
1376 let data = vault::unseal(decode(&cmd.payload), &x.vault).0;
1377 let produced = match handler {
1378 Some(handler) => caught(|| handler(&state, data.clone(), &meta, &mut ctx))??,
1379 None if indexed && cmd.command_type == reindex_type(&self.inner.name) => Vec::new(),
1381 None => {
1382 return Err(Failure::Rejected(
1383 Rejected::new(format!(
1384 "no handler for {} on {}.{}",
1385 cmd.command_type, cmd.domain, cmd.aggregate_type
1386 ))
1387 .code("unknown_command"),
1388 ));
1389 }
1390 };
1391 self.personal_in_clear(&cmd.command_type, &produced)?;
1392 let requires = self.requirements_of(&state, &cmd.command_type, data)?;
1393
1394 let mut events = Vec::with_capacity(produced.len());
1395 let mut values = Vec::new();
1396 for e in &produced {
1397 let def = self.inner.domain.event_def(&e.event_type);
1398 let sealed = vault::seal(&e.data, def.as_ref().map(|d| &d.vault), &cmd.aggregate_id)
1399 .map_err(Failure::Error)?;
1400 values.extend(sealed.values);
1401 let erases = def
1402 .as_ref()
1403 .and_then(|d| d.eraser.as_ref())
1404 .map(|subject| subject(&e.data, &cmd.aggregate_id))
1405 .unwrap_or_default();
1406 events.push(proto::NewEvent {
1407 event_type: e.event_type.clone(),
1408 schema: def.as_ref().map_or(1, |d| d.schema),
1409 payload: sealed.payload,
1410 vault_refs: sealed.refs,
1411 erases,
1412 origin_partition: String::new(),
1413 origin_position: 0,
1414 deployment: String::new(),
1416 });
1417 }
1418
1419 let before = x.expected_version;
1420 let version = before + produced.len() as u64;
1421 let snapshot_due = snapshot_every != 0
1422 && !produced.is_empty()
1423 && version / snapshot_every != before / snapshot_every;
1424 let after = if produced.is_empty() || !(snapshot_due || indexed) {
1425 state
1426 } else {
1427 let read = produced.iter().enumerate().map(|(i, e)| FoldEvent {
1430 event_type: e.event_type.clone(),
1431 schema: self.inner.domain.schema_of(&e.event_type),
1432 data: decode(&encode(&e.data)),
1433 meta: meta_of(&e.event_type, before + i as u64 + 1, &cmd, &cmd.command_id),
1434 request: request.clone(),
1435 });
1436 self.fold_inner(read.collect::<Vec<_>>(), Some(state))?
1437 };
1438 let snapshot = if snapshot_due {
1439 let state = serde_json::to_vec(&after).map_err(|e| Failure::Error(e.to_string()))?;
1440 Some((version, schema, state))
1441 } else {
1442 None
1443 };
1444 let index = if indexed {
1445 self.index_of(&after)?
1446 } else {
1447 Index::default()
1448 };
1449 Ok(Executed {
1450 events,
1451 vault: values,
1452 snapshot,
1453 keys: index.keys.iter().map(UniqueKey::to_wire).collect(),
1454 facts: index.facts,
1455 requires: requires.iter().map(|q| q.to_wire(&cmd.domain)).collect(),
1456 })
1457 }
1458}
1459
1460fn meta_of(event_type: &str, version: u64, cmd: &proto::Command, command_id: &str) -> EventMeta {
1462 EventMeta {
1463 event_type: event_type.to_owned(),
1464 version,
1465 tenant: cmd.tenant_id.clone(),
1466 domain: cmd.domain.clone(),
1467 aggregate_type: cmd.aggregate_type.clone(),
1468 aggregate_id: cmd.aggregate_id.clone(),
1469 command_id: command_id.to_owned(),
1470 }
1471}
1472
1473pub(crate) fn encode(data: &Value) -> Vec<u8> {
1475 if data.is_null() {
1476 return b"{}".to_vec();
1477 }
1478 serde_json::to_vec(data).expect("a JSON value encodes")
1479}
1480
1481pub(crate) fn decode(payload: &[u8]) -> Value {
1483 if payload.is_empty() {
1484 return Value::Object(Map::new());
1485 }
1486 serde_json::from_slice(payload).unwrap_or(Value::Null)
1487}
1488
1489#[cfg(test)]
1490mod tests {
1491 use super::*;
1492
1493 #[test]
1494 fn a_panic_says_what_it_said_as_far_as_it_can() {
1495 let text = |f: fn()| panic_text(catch_unwind(f).unwrap_err().as_ref());
1496 std::panic::set_hook(Box::new(|_| {}));
1497 assert_eq!(text(|| panic!("plain")), "plain");
1498 assert_eq!(text(|| panic!("formatted {}", 7)), "formatted 7");
1499 assert_eq!(text(|| std::panic::panic_any(7)), "handler panicked");
1500 let _ = std::panic::take_hook();
1501 assert_eq!(SchemaError("too new".into()).to_string(), "too new");
1502 }
1503}