use std::{
collections::{HashMap, HashSet},
panic::{AssertUnwindSafe, catch_unwind},
sync::{Arc, Mutex, RwLock},
};
use kernable_core::{proto, signing};
use serde::{Serialize, de::DeserializeOwned};
use serde_json::{Map, Value};
use crate::{
BoxError, Error, Listener, Rejected, RequestContext,
context::Timestamp,
index::{Index, KeySubject, Requirement, Unique, UniqueKey, reindex_type},
messages::{EventType, TypeKey},
vault::{self, VaultFields},
};
type Upcast = Arc<dyn Fn(Value) -> Value + Send + Sync>;
pub(crate) type Subject = Arc<dyn Fn(&Value, &str) -> String + Send + Sync>;
#[derive(Clone, Default)]
pub(crate) struct EventDef {
pub schema: u32,
pub steps: HashMap<u32, Upcast>,
pub vault: VaultFields,
pub eraser: Option<Subject>,
}
struct DomainInner {
name: String,
events: RwLock<HashMap<String, EventDef>>,
commands: RwLock<HashMap<String, VaultFields>>,
queries: RwLock<HashMap<String, Option<QueryTarget>>>,
aggregates: RwLock<Vec<Arc<dyn Runnable>>>,
listeners: RwLock<Vec<Listener>>,
processes: RwLock<Vec<crate::process::Process>>,
declared: RwLock<HashSet<String>>,
}
#[derive(Clone)]
pub struct Domain {
inner: Arc<DomainInner>,
}
pub fn domain(name: &str) -> Domain {
let valid = name.starts_with(|c: char| c.is_ascii_alphabetic())
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
assert!(valid, "invalid domain name {name:?}");
Domain {
inner: Arc::new(DomainInner {
name: name.to_owned(),
events: RwLock::default(),
commands: RwLock::default(),
queries: RwLock::default(),
aggregates: RwLock::default(),
listeners: RwLock::default(),
processes: RwLock::default(),
declared: RwLock::default(),
}),
}
}
impl Domain {
pub fn name(&self) -> &str {
&self.inner.name
}
pub fn event(&self, event_type: &str, schema: u32) -> EventSchema {
assert!(
unqualified(event_type),
"event types are unqualified within their domain, not {event_type:?}"
);
assert!(schema >= 1, "a schema is a version from 1, not {schema}");
self.inner.events.write().unwrap().insert(
event_type.to_owned(),
EventDef {
schema,
..EventDef::default()
},
);
EventSchema {
domain: self.clone(),
event_type: event_type.to_owned(),
}
}
pub fn command(&self, command_type: &str) -> CommandSchema {
assert!(
unqualified(command_type),
"command types are unqualified within their domain, not {command_type:?}"
);
self.inner
.commands
.write()
.unwrap()
.insert(command_type.to_owned(), VaultFields::default());
CommandSchema {
domain: self.clone(),
command_type: command_type.to_owned(),
}
}
pub fn query(&self, query_type: &str) -> QuerySchema {
assert!(
unqualified(query_type),
"query types are unqualified within their domain, not {query_type:?}"
);
self.inner
.queries
.write()
.unwrap()
.insert(query_type.to_owned(), None);
QuerySchema {
domain: self.clone(),
query_type: query_type.to_owned(),
}
}
pub fn process(&self, name: &str) -> crate::process::Process {
let valid = !name.is_empty()
&& name
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
assert!(valid, "invalid process name {name:?}");
let process = crate::process::Process::new(self.name(), name);
let mut processes = self.inner.processes.write().unwrap();
let qualified = process.name();
assert!(
!processes.iter().any(|p| p.name() == qualified),
"{} has a process {name} already",
self.inner.name
);
processes.push(process.clone());
process
}
pub(crate) fn processes(&self) -> Vec<crate::process::Process> {
self.inner.processes.read().unwrap().clone()
}
pub fn aggregate<S: State>(&self, name: &str, initial: S) -> Aggregate<S> {
let taken = self.aggregates().iter().any(|a| a.name() == name);
assert!(
!taken,
"{} has an aggregate {name} already",
self.inner.name
);
let aggregate = Aggregate {
inner: Arc::new(AggregateInner {
domain: self.clone(),
name: name.to_owned(),
initial,
settings: Mutex::new((100, "1".to_owned())),
appliers: RwLock::default(),
handlers: RwLock::default(),
keys: RwLock::default(),
facts: RwLock::default(),
requires: RwLock::default(),
}),
};
self.inner
.aggregates
.write()
.unwrap()
.push(Arc::new(aggregate.clone()));
aggregate
}
pub fn read_model(&self, name: &str) -> Listener {
self.remember(Listener::new(self, name, 0, Some(0), 0, false))
}
pub fn reactor(&self, name: &str) -> Listener {
self.remember(Listener::new(
self,
name,
10,
None,
crate::listener::PARK_AFTER,
true,
))
}
fn remember(&self, listener: Listener) -> Listener {
let taken = self.listeners().iter().any(|l| l.name() == listener.name());
assert!(
!taken,
"{} has a listener {} already",
self.inner.name,
listener.name()
);
self.inner.listeners.write().unwrap().push(listener.clone());
listener
}
pub(crate) fn aggregates(&self) -> Vec<Arc<dyn Runnable>> {
self.inner.aggregates.read().unwrap().clone()
}
pub(crate) fn listeners(&self) -> Vec<Listener> {
self.inner.listeners.read().unwrap().clone()
}
pub(crate) fn event_def(&self, event_type: &str) -> Option<EventDef> {
self.inner.events.read().unwrap().get(event_type).cloned()
}
pub(crate) fn event_types(&self) -> Vec<String> {
self.inner.events.read().unwrap().keys().cloned().collect()
}
pub(crate) fn command_vault(&self, command_type: &str) -> Option<VaultFields> {
self.inner
.commands
.read()
.unwrap()
.get(command_type)
.cloned()
}
pub(crate) fn query_target(&self, query_type: &str) -> Option<QueryTarget> {
self.inner
.queries
.read()
.unwrap()
.get(query_type)
.cloned()
.flatten()
}
pub(crate) fn declare_once(&self, message_type: &str, declare: fn(&Domain)) {
let by_name = self.event_def(message_type).is_some()
|| self.command_vault(message_type).is_some()
|| self
.inner
.queries
.read()
.unwrap()
.contains_key(message_type);
if self
.inner
.declared
.write()
.unwrap()
.insert(message_type.to_owned())
&& !by_name
{
declare(self);
}
}
pub fn schema_of(&self, event_type: &str) -> u32 {
self.event_def(event_type).map_or(1, |d| d.schema)
}
pub(crate) fn upcast(
&self,
event_type: &str,
schema: u32,
data: Value,
) -> Result<Value, SchemaError> {
upcast(Some(self), &self.inner.name, event_type, schema, data)
}
}
fn unqualified(t: &str) -> bool {
!t.is_empty() && !t.contains(['.', '*'])
}
pub struct EventSchema {
domain: Domain,
event_type: String,
}
impl EventSchema {
fn update(&self, f: impl FnOnce(&mut EventDef)) {
let mut events = self.domain.inner.events.write().unwrap();
f(events
.get_mut(&self.event_type)
.expect("declared by Domain::event"));
}
pub fn personal(
self,
fields: &[&str],
subject: impl Fn(&Value, &str) -> String + Send + Sync + 'static,
) -> Self {
let fields = fields.iter().map(|f| (*f).to_owned()).collect();
self.update(|d| d.vault.personal.push((fields, Arc::new(subject))));
self
}
pub fn erases(self, subject: impl Fn(&Value, &str) -> String + Send + Sync + 'static) -> Self {
self.update(|d| d.eraser = Some(Arc::new(subject)));
self
}
pub fn upcast(self, from: u32, step: impl Fn(Value) -> Value + Send + Sync + 'static) -> Self {
self.update(|d| {
assert!(
from >= 1 && from < d.schema,
"upcast {} from a version between 1 and {}, not {from}",
self.event_type,
d.schema - 1
);
d.steps.insert(from, Arc::new(step));
});
self
}
}
pub struct CommandSchema {
domain: Domain,
command_type: String,
}
impl CommandSchema {
fn update(&self, f: impl FnOnce(&mut VaultFields)) {
let mut commands = self.domain.inner.commands.write().unwrap();
f(commands
.get_mut(&self.command_type)
.expect("declared by Domain::command"));
}
pub fn personal(
self,
fields: &[&str],
subject: impl Fn(&Value, &str) -> String + Send + Sync + 'static,
) -> Self {
let fields = fields.iter().map(|f| (*f).to_owned()).collect();
self.update(|v| v.personal.push((fields, Arc::new(subject))));
self
}
pub fn secret(self, fields: &[&str]) -> Self {
self.update(|v| v.secret.extend(fields.iter().map(|f| (*f).to_owned())));
self
}
}
pub struct QuerySchema {
domain: Domain,
query_type: String,
}
impl QuerySchema {
pub fn target(self, aggregate_type: &str, field: &str) -> Self {
self.domain.inner.queries.write().unwrap().insert(
self.query_type.clone(),
Some(QueryTarget {
aggregate_type: aggregate_type.to_owned(),
field: field.to_owned(),
}),
);
self
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct QueryTarget {
pub aggregate_type: String,
pub field: String,
}
impl QueryTarget {
pub(crate) fn wire(&self, domain: &str, data: &Value) -> Option<proto::Target> {
let id = data
.get(&self.field)?
.as_str()
.filter(|id| !id.is_empty())?;
let aggregate_type = if self.aggregate_type.contains('.') {
self.aggregate_type.clone()
} else {
format!("{domain}.{}", self.aggregate_type)
};
Some(proto::Target {
aggregate_type,
aggregate_id: id.to_owned(),
})
}
}
#[derive(Debug)]
pub(crate) struct SchemaError(pub String);
impl std::fmt::Display for SchemaError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(&self.0)
}
}
impl std::error::Error for SchemaError {}
pub(crate) fn known_schema(known: Option<&Domain>, event_type: &str) -> u32 {
known.map_or(1, |d| d.schema_of(event_type))
}
pub(crate) fn upcast(
known: Option<&Domain>,
domain: &str,
event_type: &str,
schema: u32,
mut data: Value,
) -> Result<Value, SchemaError> {
let def = known.and_then(|d| d.event_def(event_type));
let current = def.as_ref().map_or(1, |d| d.schema);
if schema > current {
return Err(SchemaError(format!(
"{domain}.{event_type} has schema {schema}, but this process knows it only up to {current}: update it"
)));
}
for v in schema..current {
let step = def.as_ref().and_then(|d| d.steps.get(&v)).ok_or_else(|| {
SchemaError(format!(
"no upcast for {domain}.{event_type} from schema {v}"
))
})?;
data = step(data);
}
Ok(data)
}
#[derive(Clone, Debug, PartialEq)]
pub struct NewEvent {
pub event_type: String,
pub data: Value,
}
impl NewEvent {
pub fn new(event_type: &str, data: impl Serialize) -> NewEvent {
NewEvent {
event_type: event_type.to_owned(),
data: serde_json::to_value(data).expect("event data is JSON"),
}
}
}
impl<E: EventType> From<E> for NewEvent {
fn from(event: E) -> NewEvent {
NewEvent::new(E::TYPE, event)
}
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct EventMeta {
pub event_type: String,
pub version: u64,
pub tenant: String,
pub domain: String,
pub aggregate_type: String,
pub aggregate_id: String,
pub command_id: String,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ApplyContext {
pub request: RequestContext,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct CommandMeta {
pub command_id: String,
pub command_type: String,
pub domain: String,
pub aggregate_type: String,
pub aggregate_id: String,
pub tenant: String,
}
#[derive(Clone, Debug)]
pub struct CommandContext {
pub request: RequestContext,
command_id: String,
received_at: Timestamp,
deadline: Timestamp,
ids: u64,
target: (String, String),
}
impl CommandContext {
pub fn new(
command_id: &str,
request: RequestContext,
received_at: Timestamp,
) -> CommandContext {
CommandContext {
command_id: command_id.to_owned(),
request,
received_at,
deadline: Timestamp(received_at.0 + 30_000),
ids: 0,
target: (String::new(), String::new()),
}
}
pub fn on(mut self, aggregate_id: &str, tenant: &str) -> CommandContext {
self.target = (aggregate_id.to_owned(), tenant.to_owned());
self
}
pub fn now(&self) -> Timestamp {
self.received_at
}
pub fn id(&mut self) -> String {
self.ids += 1;
signing::derived_id(&self.command_id, self.ids - 1)
}
pub fn deadline(&self) -> Timestamp {
self.deadline
}
}
#[derive(Clone, Debug, Default)]
pub struct FoldEvent {
pub event_type: String,
pub schema: u32,
pub data: Value,
pub meta: EventMeta,
pub request: RequestContext,
}
impl FoldEvent {
pub fn new(event_type: &str, data: impl Serialize) -> FoldEvent {
FoldEvent {
event_type: event_type.to_owned(),
schema: 1,
data: serde_json::to_value(data).expect("event data is JSON"),
meta: EventMeta::default(),
request: RequestContext::default(),
}
}
}
pub trait State: Clone + Serialize + DeserializeOwned + Send + Sync + 'static {}
impl<S: Clone + Serialize + DeserializeOwned + Send + Sync + 'static> State for S {}
type Apply<S> =
Arc<dyn Fn(&mut S, Value, &EventMeta, &ApplyContext) -> Result<(), BoxError> + Send + Sync>;
type Handle<S> = Arc<
dyn Fn(&S, Value, &CommandMeta, &mut CommandContext) -> Result<Vec<NewEvent>, Failure>
+ Send
+ Sync,
>;
type Fact<S> = Arc<dyn Fn(&S) -> bool + Send + Sync>;
type KeyValues<S> = Arc<dyn Fn(&S) -> Vec<String> + Send + Sync>;
type Requires<S> = Arc<dyn Fn(&S, Value) -> Result<Vec<Requirement>, Failure> + Send + Sync>;
struct KeyDef<S> {
name: String,
values: KeyValues<S>,
global: bool,
personal: Option<KeySubject<S>>,
}
impl<S> Clone for KeyDef<S> {
fn clone(&self) -> Self {
KeyDef {
name: self.name.clone(),
values: Arc::clone(&self.values),
global: self.global,
personal: self.personal.clone(),
}
}
}
struct AggregateInner<S> {
domain: Domain,
name: String,
initial: S,
settings: Mutex<(u64, String)>,
appliers: RwLock<HashMap<String, Apply<S>>>,
handlers: RwLock<HashMap<String, Handle<S>>>,
keys: RwLock<Vec<KeyDef<S>>>,
facts: RwLock<Vec<(String, Fact<S>)>>,
requires: RwLock<HashMap<String, Requires<S>>>,
}
pub struct Aggregate<S> {
inner: Arc<AggregateInner<S>>,
}
impl<S> Clone for Aggregate<S> {
fn clone(&self) -> Self {
Aggregate {
inner: Arc::clone(&self.inner),
}
}
}
#[derive(Debug)]
pub(crate) enum Failure {
Rejected(Rejected),
Error(String),
Schema(String),
}
impl Failure {
fn into_error(self) -> Error {
match self {
Failure::Rejected(r) => Error::Rejected(r),
Failure::Error(m) | Failure::Schema(m) => Error::Config(m),
}
}
}
impl From<SchemaError> for Failure {
fn from(e: SchemaError) -> Failure {
Failure::Schema(e.0)
}
}
impl<S: State> Aggregate<S> {
pub fn domain(&self) -> &Domain {
&self.inner.domain
}
pub fn name(&self) -> &str {
&self.inner.name
}
pub fn initial(&self) -> &S {
&self.inner.initial
}
pub fn snapshot_every(&self, events: u64) -> Self {
self.inner.settings.lock().unwrap().0 = events;
self.clone()
}
pub fn schema(&self, schema: &str) -> Self {
self.inner.settings.lock().unwrap().1 = schema.to_owned();
self.clone()
}
pub fn apply<D: DeserializeOwned>(
&self,
event_type: impl TypeKey<D>,
f: impl Fn(&mut S, D, &EventMeta, &ApplyContext) + Send + Sync + 'static,
) -> Self {
let event_type = event_type.key().within(&self.inner.domain, "apply");
let event_type = event_type.as_str();
let apply: Apply<S> = Arc::new(move |state, data, meta, ctx| {
let data = serde_json::from_value(data)
.map_err(|e| format!("{} data: {e}", meta.event_type))?;
f(state, data, meta, ctx);
Ok(())
});
self.inner
.appliers
.write()
.unwrap()
.insert(event_type.to_owned(), apply);
self.clone()
}
pub fn command<D: DeserializeOwned>(
&self,
command_type: impl TypeKey<D>,
f: impl Fn(&S, D, &CommandMeta, &mut CommandContext) -> Result<Vec<NewEvent>, Rejected>
+ Send
+ Sync
+ 'static,
) -> Self {
let command_type = command_type.key().within(&self.inner.domain, "command");
let command_type = command_type.as_str();
assert!(
!command_type.starts_with("_reindex_"),
"{command_type}: command types starting with _reindex_ are reserved for the built-in \
command of aggregates with unique keys or facts; name yours otherwise"
);
let name = command_type.to_owned();
let handle: Handle<S> = Arc::new(move |state, data, cmd, ctx| {
let data = serde_json::from_value(data)
.map_err(|e| Failure::Error(format!("{name} data: {e}")))?;
f(state, data, cmd, ctx).map_err(Failure::Rejected)
});
self.inner
.handlers
.write()
.unwrap()
.insert(command_type.to_owned(), handle);
self.clone()
}
pub fn unique<I: IntoIterator<Item = String>>(
&self,
name: &str,
values: impl Fn(&S) -> I + Send + Sync + 'static,
options: Unique<S>,
) -> Self {
let taken = self
.inner
.keys
.read()
.unwrap()
.iter()
.any(|k| k.name == name);
self.declarable("key", name, taken);
self.inner.keys.write().unwrap().push(KeyDef {
name: name.to_owned(),
values: Arc::new(move |state| values(state).into_iter().collect()),
global: options.global,
personal: options.personal,
});
self.clone()
}
pub fn fact(&self, name: &str, holds: impl Fn(&S) -> bool + Send + Sync + 'static) -> Self {
let taken = self
.inner
.facts
.read()
.unwrap()
.iter()
.any(|(f, _)| f == name);
self.declarable("fact", name, taken);
self.inner
.facts
.write()
.unwrap()
.push((name.to_owned(), Arc::new(holds)));
self.clone()
}
pub fn requires<D: DeserializeOwned, I: IntoIterator<Item = Requirement>>(
&self,
command_type: impl TypeKey<D>,
f: impl Fn(&S, D) -> I + Send + Sync + 'static,
) -> Self {
let command_type = command_type.key().within(&self.inner.domain, "requires");
let command_type = command_type.as_str();
assert!(
self.handler(command_type).is_some(),
"{} has no command {command_type} to require facts for: declare it first",
self.inner.name
);
let name = command_type.to_owned();
let requires: Requires<S> = Arc::new(move |state, data| {
let data = serde_json::from_value(data)
.map_err(|e| Failure::Error(format!("{name} data: {e}")))?;
Ok(f(state, data).into_iter().collect())
});
self.inner
.requires
.write()
.unwrap()
.insert(command_type.to_owned(), requires);
self.clone()
}
fn declarable(&self, kind: &str, name: &str, taken: bool) {
let aggregate = format!("{}.{}", self.inner.domain.name(), self.inner.name);
assert!(
unqualified(name) && name.len() <= 128,
"{aggregate}: a {kind} name is 1 to 128 bytes without `.` or `*`, not {name:?}"
);
assert!(!taken, "{aggregate} declares a {kind} {name} already");
}
fn indexed(&self) -> bool {
!self.inner.keys.read().unwrap().is_empty() || !self.inner.facts.read().unwrap().is_empty()
}
pub fn index(&self, state: &S) -> Result<Index, Error> {
self.index_of(state).map_err(Failure::into_error)
}
pub fn requirements(
&self,
state: &S,
command_type: &str,
data: impl Serialize,
) -> Result<Vec<Requirement>, Error> {
let data = serde_json::to_value(data)?;
self.requirements_of(state, command_type, data)
.map_err(Failure::into_error)
}
fn index_of(&self, state: &S) -> Result<Index, Failure> {
let keys = self.inner.keys.read().unwrap().clone();
let facts = self.inner.facts.read().unwrap().clone();
caught(|| {
let mut index = Index::default();
for key in &keys {
let subject = match &key.personal {
None => None,
Some(subject) => match subject(state) {
Some(s) if !s.is_empty() => Some(s),
_ => continue,
},
};
let mut values: Vec<String> = Vec::new();
for value in (key.values)(state) {
if !values.contains(&value) {
values.push(value);
}
}
index.keys.extend(values.into_iter().map(|value| UniqueKey {
name: key.name.clone(),
value,
global: key.global,
subject: subject.clone(),
}));
}
index.facts = facts
.iter()
.filter(|(_, holds)| holds(state))
.map(|(name, _)| name.clone())
.collect();
index
})
}
fn requirements_of(
&self,
state: &S,
command_type: &str,
data: Value,
) -> Result<Vec<Requirement>, Failure> {
let requires = self
.inner
.requires
.read()
.unwrap()
.get(command_type)
.cloned();
match requires {
Some(requires) => caught(|| requires(state, data))?,
None => Ok(Vec::new()),
}
}
pub fn fold(
&self,
history: impl IntoIterator<Item = FoldEvent>,
from: Option<S>,
) -> Result<S, Error> {
self.fold_inner(history, from).map_err(|f| match f {
Failure::Rejected(r) => Error::Rejected(r),
Failure::Error(m) | Failure::Schema(m) => Error::Config(m),
})
}
fn fold_inner(
&self,
history: impl IntoIterator<Item = FoldEvent>,
from: Option<S>,
) -> Result<S, Failure> {
let mut state = from.unwrap_or_else(|| self.inner.initial.clone());
let appliers = self.inner.appliers.read().unwrap();
for e in history {
let Some(apply) = appliers.get(&e.event_type) else {
continue;
};
let data = self.inner.domain.upcast(&e.event_type, e.schema, e.data)?;
let meta = EventMeta {
event_type: e.event_type,
domain: if e.meta.domain.is_empty() {
self.inner.domain.name().to_owned()
} else {
e.meta.domain
},
aggregate_type: if e.meta.aggregate_type.is_empty() {
self.inner.name.clone()
} else {
e.meta.aggregate_type
},
..e.meta
};
let ctx = ApplyContext { request: e.request };
caught(|| apply(&mut state, data, &meta, &ctx))?
.map_err(|e| Failure::Error(e.to_string()))?;
}
Ok(state)
}
pub fn handle(
&self,
state: &S,
command_type: &str,
data: impl Serialize,
ctx: &mut CommandContext,
) -> Result<Vec<NewEvent>, Error> {
let handler = self.handler(command_type).ok_or_else(|| {
Error::Config(format!(
"no handler for {command_type} on {}",
self.inner.name
))
})?;
let data = serde_json::to_value(data)?;
let cmd = CommandMeta {
command_id: ctx.command_id.clone(),
command_type: command_type.to_owned(),
domain: self.inner.domain.name().to_owned(),
aggregate_type: self.inner.name.clone(),
aggregate_id: ctx.target.0.clone(),
tenant: ctx.target.1.clone(),
};
match caught(|| handler(state, data, &cmd, ctx)).and_then(|r| r) {
Ok(events) => Ok(events),
Err(Failure::Rejected(r)) => Err(Error::Rejected(r)),
Err(Failure::Error(m) | Failure::Schema(m)) => Err(Error::Config(m)),
}
}
fn handler(&self, command_type: &str) -> Option<Handle<S>> {
self.inner
.handlers
.read()
.unwrap()
.get(command_type)
.cloned()
}
fn personal_in_clear(&self, command_type: &str, events: &[NewEvent]) -> Result<(), Failure> {
let domain = &self.inner.domain;
let Some(command) = domain.command_vault(command_type) else {
return Ok(());
};
for e in events {
let def = domain.event_def(&e.event_type);
let declared = |field: &String| {
def.as_ref()
.is_some_and(|d| d.vault.personal.iter().any(|(f, _)| f.contains(field)))
};
for field in command.personal.iter().flat_map(|(fields, _)| fields) {
let held = e.data.get(field).is_some_and(|v| !v.is_null());
if held && !declared(field) {
return Err(Failure::Rejected(
Rejected::new(format!(
"{command_type} declares {field} personal, but {event} does not: it \
would be stored in clear (declare it with Domain.event({event:?}, \
…).personal)",
event = e.event_type,
))
.code("personal_in_clear"),
));
}
}
}
Ok(())
}
}
fn caught<T>(f: impl FnOnce() -> T) -> Result<T, Failure> {
catch_unwind(AssertUnwindSafe(f)).map_err(|panic| Failure::Error(panic_text(panic.as_ref())))
}
pub(crate) fn panic_text(panic: &(dyn std::any::Any + Send)) -> String {
panic
.downcast_ref::<&str>()
.map(|s| (*s).to_owned())
.or_else(|| panic.downcast_ref::<String>().cloned())
.unwrap_or_else(|| "handler panicked".into())
}
pub(crate) struct Executed {
pub events: Vec<proto::NewEvent>,
pub vault: Vec<proto::VaultValue>,
pub snapshot: Option<(u64, String, Vec<u8>)>,
pub keys: Vec<proto::UniqueKey>,
pub facts: Vec<String>,
pub requires: Vec<proto::Requirement>,
}
pub(crate) trait Runnable: Send + Sync {
fn domain(&self) -> &Domain;
fn name(&self) -> &str;
fn command_types(&self) -> Vec<String>;
fn event_types(&self) -> Vec<String>;
fn execute(&self, x: &proto::Execute) -> Result<Executed, Failure>;
}
impl<S: State> Runnable for Aggregate<S> {
fn domain(&self) -> &Domain {
&self.inner.domain
}
fn name(&self) -> &str {
&self.inner.name
}
fn command_types(&self) -> Vec<String> {
let mut types: Vec<String> = self
.inner
.handlers
.read()
.unwrap()
.keys()
.cloned()
.collect();
if self.indexed() {
types.push(reindex_type(&self.inner.name));
}
types
}
fn event_types(&self) -> Vec<String> {
let mut types: Vec<String> = self
.inner
.appliers
.read()
.unwrap()
.keys()
.cloned()
.collect();
types.extend(self.inner.domain.event_types());
types.sort();
types.dedup();
types
}
fn execute(&self, x: &proto::Execute) -> Result<Executed, Failure> {
let cmd = x.command.clone().unwrap_or_default();
let (snapshot_every, schema) = self.inner.settings.lock().unwrap().clone();
let from = match &x.snapshot {
Some(s) if s.schema != schema => {
return Err(Failure::Rejected(
Rejected::new(format!("snapshot schema {} is not {schema}", s.schema))
.code("snapshot_stale"),
));
}
Some(s) => Some(
serde_json::from_slice(&s.state)
.map_err(|e| Failure::Error(format!("snapshot of {}: {e}", self.inner.name)))?,
),
None => None,
};
let history = x.history.iter().map(|e| FoldEvent {
event_type: e.event_type.clone(),
schema: e.schema,
data: vault::unseal(decode(&e.payload), &x.vault).0,
meta: meta_of(&e.event_type, e.version, &cmd, &e.command_id),
request: RequestContext::from_wire(e.context.as_ref()),
});
let state = self.fold_inner(history.collect::<Vec<_>>(), from)?;
let request = RequestContext::from_wire(cmd.context.as_ref());
let meta = CommandMeta {
command_id: cmd.command_id.clone(),
command_type: cmd.command_type.clone(),
domain: cmd.domain.clone(),
aggregate_type: cmd.aggregate_type.clone(),
aggregate_id: cmd.aggregate_id.clone(),
tenant: cmd.tenant_id.clone(),
};
let mut ctx = CommandContext {
command_id: cmd.command_id.clone(),
request: request.clone(),
received_at: Timestamp(x.received_at),
deadline: Timestamp(x.deadline),
ids: 0,
target: (cmd.aggregate_id.clone(), cmd.tenant_id.clone()),
};
let indexed = self.indexed();
let handler = self.handler(&cmd.command_type);
let data = vault::unseal(decode(&cmd.payload), &x.vault).0;
let produced = match handler {
Some(handler) => caught(|| handler(&state, data.clone(), &meta, &mut ctx))??,
None if indexed && cmd.command_type == reindex_type(&self.inner.name) => Vec::new(),
None => {
return Err(Failure::Rejected(
Rejected::new(format!(
"no handler for {} on {}.{}",
cmd.command_type, cmd.domain, cmd.aggregate_type
))
.code("unknown_command"),
));
}
};
self.personal_in_clear(&cmd.command_type, &produced)?;
let requires = self.requirements_of(&state, &cmd.command_type, data)?;
let mut events = Vec::with_capacity(produced.len());
let mut values = Vec::new();
for e in &produced {
let def = self.inner.domain.event_def(&e.event_type);
let sealed = vault::seal(&e.data, def.as_ref().map(|d| &d.vault), &cmd.aggregate_id)
.map_err(Failure::Error)?;
values.extend(sealed.values);
let erases = def
.as_ref()
.and_then(|d| d.eraser.as_ref())
.map(|subject| subject(&e.data, &cmd.aggregate_id))
.unwrap_or_default();
events.push(proto::NewEvent {
event_type: e.event_type.clone(),
schema: def.as_ref().map_or(1, |d| d.schema),
payload: sealed.payload,
vault_refs: sealed.refs,
erases,
origin_partition: String::new(),
origin_position: 0,
deployment: String::new(),
});
}
let before = x.expected_version;
let version = before + produced.len() as u64;
let snapshot_due = snapshot_every != 0
&& !produced.is_empty()
&& version / snapshot_every != before / snapshot_every;
let after = if produced.is_empty() || !(snapshot_due || indexed) {
state
} else {
let read = produced.iter().enumerate().map(|(i, e)| FoldEvent {
event_type: e.event_type.clone(),
schema: self.inner.domain.schema_of(&e.event_type),
data: decode(&encode(&e.data)),
meta: meta_of(&e.event_type, before + i as u64 + 1, &cmd, &cmd.command_id),
request: request.clone(),
});
self.fold_inner(read.collect::<Vec<_>>(), Some(state))?
};
let snapshot = if snapshot_due {
let state = serde_json::to_vec(&after).map_err(|e| Failure::Error(e.to_string()))?;
Some((version, schema, state))
} else {
None
};
let index = if indexed {
self.index_of(&after)?
} else {
Index::default()
};
Ok(Executed {
events,
vault: values,
snapshot,
keys: index.keys.iter().map(UniqueKey::to_wire).collect(),
facts: index.facts,
requires: requires.iter().map(|q| q.to_wire(&cmd.domain)).collect(),
})
}
}
fn meta_of(event_type: &str, version: u64, cmd: &proto::Command, command_id: &str) -> EventMeta {
EventMeta {
event_type: event_type.to_owned(),
version,
tenant: cmd.tenant_id.clone(),
domain: cmd.domain.clone(),
aggregate_type: cmd.aggregate_type.clone(),
aggregate_id: cmd.aggregate_id.clone(),
command_id: command_id.to_owned(),
}
}
pub(crate) fn encode(data: &Value) -> Vec<u8> {
if data.is_null() {
return b"{}".to_vec();
}
serde_json::to_vec(data).expect("a JSON value encodes")
}
pub(crate) fn decode(payload: &[u8]) -> Value {
if payload.is_empty() {
return Value::Object(Map::new());
}
serde_json::from_slice(payload).unwrap_or(Value::Null)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_panic_says_what_it_said_as_far_as_it_can() {
let text = |f: fn()| panic_text(catch_unwind(f).unwrap_err().as_ref());
std::panic::set_hook(Box::new(|_| {}));
assert_eq!(text(|| panic!("plain")), "plain");
assert_eq!(text(|| panic!("formatted {}", 7)), "formatted 7");
assert_eq!(text(|| std::panic::panic_any(7)), "handler panicked");
let _ = std::panic::take_hook();
assert_eq!(SchemaError("too new".into()).to_string(), "too new");
}
}