Skip to main content

kernable/
index.rs

1//! Unique keys, facts and requirements: what the kernel checks across aggregates at commit.
2
3use std::sync::Arc;
4
5use kernable_core::proto;
6use sha2::{Digest, Sha256};
7
8use crate::{Error, Kernable, Outcome, Submit, Wait};
9
10/// The type of the command every aggregate that declares unique keys or facts runs without a
11/// handler of its own: `_reindex_<aggregate_type>`, e.g. `reindex_type("customer")` is
12/// `_reindex_customer` (command types are unique within a domain). It produces no events, so
13/// the worker sends the keys and facts of the current state; [`Kernable::reindex`] submits it.
14/// Command types starting with `_reindex_` are reserved for it.
15pub fn reindex_type(aggregate_type: &str) -> String {
16    format!("_reindex_{aggregate_type}")
17}
18
19/// Whose personal data a key's value is: from the state.
20pub(crate) type KeySubject<S> = Arc<dyn Fn(&S) -> Option<String> + Send + Sync>;
21
22/// How a unique key is unique, for [`crate::Aggregate::unique`]: within the command's tenant
23/// ([`Unique::tenant`], also `Unique::default()`) or across tenants ([`Unique::global`]), and
24/// optionally personal: `Unique::global().personal(|s: &Customer| Some(s.id.clone()))`.
25pub struct Unique<S> {
26    pub(crate) global: bool,
27    pub(crate) personal: Option<KeySubject<S>>,
28}
29
30impl<S> Default for Unique<S> {
31    fn default() -> Self {
32        Unique::tenant()
33    }
34}
35
36impl<S> Unique<S> {
37    /// Unique within the command's tenant: another tenant may hold the same value.
38    pub fn tenant() -> Self {
39        Unique {
40            global: false,
41            personal: None,
42        }
43    }
44
45    /// Unique across tenants. The key's identity has no tenant, so a command that is rejected
46    /// with `unique_taken` learns that some tenant holds the value.
47    pub fn global() -> Self {
48        Unique {
49            global: true,
50            personal: None,
51        }
52    }
53
54    /// Makes the value personal data of the subject `subject` returns from the state: the
55    /// kernel keeps the key in its vault, and erasing the subject frees it. `None` or an empty
56    /// subject: the aggregate holds no value of this key.
57    #[must_use]
58    pub fn personal(
59        mut self,
60        subject: impl Fn(&S) -> Option<String> + Send + Sync + 'static,
61    ) -> Self {
62        self.personal = Some(Arc::new(subject));
63        self
64    }
65}
66
67/// The unique keys and facts an aggregate holds in some state, as
68/// [`crate::Aggregate::index`] computes them for a test, in the order they are declared.
69#[derive(Clone, Debug, Default, PartialEq, Eq)]
70pub struct Index {
71    pub keys: Vec<UniqueKey>,
72    /// The names of the facts that are true.
73    pub facts: Vec<String>,
74}
75
76/// A value of a unique key: no other aggregate holds the same value of the same key (of the
77/// same domain and aggregate type, in the same tenant unless global) at the same time.
78#[derive(Clone, Debug, PartialEq, Eq)]
79pub struct UniqueKey {
80    /// The key's name, as declared.
81    pub name: String,
82    /// The value. The kernel gets only its SHA-256, never the value.
83    pub value: String,
84    /// Unique across tenants.
85    pub global: bool,
86    /// The person the value belongs to, for a personal key.
87    pub subject: Option<String>,
88}
89
90impl UniqueKey {
91    pub(crate) fn to_wire(&self) -> proto::UniqueKey {
92        proto::UniqueKey {
93            name: self.name.clone(),
94            global: self.global,
95            value_hash: Sha256::digest(self.value.as_bytes()).to_vec(),
96            subject: self.subject.clone().unwrap_or_default(),
97        }
98    }
99}
100
101/// A fact that another aggregate of the command's tenant must hold (or, [`Requirement::absent`],
102/// must not hold) when a command commits, returned by the function given to
103/// [`crate::Aggregate::requires`]: `Requirement::new("shop", "vehicle", &data.vehicle_id, "open")`.
104/// The aggregate is named by its ID, or by a unique key of its type and the key's value
105/// ([`Requirement::by_key`]), which the kernel resolves at commit: no aggregate holds the key,
106/// none holds the fact. An empty domain is the command's own ([`Requirement::of`]).
107#[derive(Clone, Debug, PartialEq, Eq)]
108pub struct Requirement {
109    /// Empty: the domain of the command's aggregate.
110    pub domain: String,
111    /// Unqualified, e.g. `vehicle`.
112    pub aggregate_type: String,
113    /// Empty when the aggregate is named by a key.
114    pub aggregate_id: String,
115    /// The unique key that names the aggregate instead of its ID, as the aggregate type
116    /// declares it.
117    pub key: Option<String>,
118    /// The key's value, normalised as the aggregate type's key function does: the kernel
119    /// gets only its SHA-256. `None` in a rejection, which never carries the value.
120    pub value: Option<String>,
121    /// The name of a fact that aggregate declares.
122    pub fact: String,
123    /// The aggregate must not hold the fact.
124    pub absent: bool,
125}
126
127impl Requirement {
128    /// The fact `fact` of the `domain.aggregate_type` aggregate with ID `aggregate_id`.
129    pub fn new(domain: &str, aggregate_type: &str, aggregate_id: &str, fact: &str) -> Requirement {
130        Requirement {
131            domain: domain.to_owned(),
132            aggregate_type: aggregate_type.to_owned(),
133            aggregate_id: aggregate_id.to_owned(),
134            key: None,
135            value: None,
136            fact: fact.to_owned(),
137            absent: false,
138        }
139    }
140
141    /// As [`Requirement::new`], of an aggregate type of the command's own domain:
142    /// `Requirement::of("vehicle", &data.vehicle_id, "open")`.
143    pub fn of(aggregate_type: &str, aggregate_id: &str, fact: &str) -> Requirement {
144        Requirement::new("", aggregate_type, aggregate_id, fact)
145    }
146
147    /// The fact `fact` of the `domain.aggregate_type` aggregate that holds the unique key `key`
148    /// with `value` (not a personal key): `Requirement::by_key("funds", "vehicle", "isin",
149    /// &data.vehicle, "open")`. Normalise `value` as the aggregate type's key does.
150    pub fn by_key(
151        domain: &str,
152        aggregate_type: &str,
153        key: &str,
154        value: &str,
155        fact: &str,
156    ) -> Requirement {
157        Requirement {
158            key: Some(key.to_owned()),
159            value: Some(value.to_owned()),
160            ..Requirement::new(domain, aggregate_type, "", fact)
161        }
162    }
163
164    /// This requirement turned around: the aggregate must not hold the fact. One without
165    /// events, or no holder of the key, holds none: `Requirement::of("vehicle", id,
166    /// "woundUp").absent()`.
167    #[must_use]
168    pub fn absent(mut self) -> Requirement {
169        self.absent = true;
170        self
171    }
172
173    /// On the wire, with an empty domain filled in with `own`.
174    pub(crate) fn to_wire(&self, own: &str) -> proto::Requirement {
175        proto::Requirement {
176            domain: if self.domain.is_empty() {
177                own.to_owned()
178            } else {
179                self.domain.clone()
180            },
181            aggregate_type: self.aggregate_type.clone(),
182            aggregate_id: self.aggregate_id.clone(),
183            fact: self.fact.clone(),
184            key: self.key.clone().unwrap_or_default(),
185            value_hash: self
186                .value
187                .as_ref()
188                .map(|v| Sha256::digest(v.as_bytes()).to_vec())
189                .unwrap_or_default(),
190            absent: self.absent,
191        }
192    }
193
194    /// As the kernel names it in a rejection: without the key's value.
195    pub(crate) fn from_wire(q: proto::Requirement) -> Requirement {
196        Requirement {
197            domain: q.domain,
198            aggregate_type: q.aggregate_type,
199            aggregate_id: q.aggregate_id,
200            key: Some(q.key).filter(|k| !k.is_empty()),
201            value: None,
202            fact: q.fact,
203            absent: q.absent,
204        }
205    }
206}
207
208/// Aggregates to reindex with [`Kernable::reindex`], built with methods that each return the
209/// changed request: `Reindex::new("shop", "customer", ["k1", "k2"]).tenant("t1")`.
210#[derive(Clone, Debug)]
211pub struct Reindex {
212    domain: String,
213    aggregate_type: String,
214    aggregate_ids: Vec<String>,
215    tenant: Option<String>,
216}
217
218impl Reindex {
219    /// The `domain.aggregate_type` aggregates with these IDs.
220    pub fn new(
221        domain: &str,
222        aggregate_type: &str,
223        aggregate_ids: impl IntoIterator<Item = impl Into<String>>,
224    ) -> Reindex {
225        Reindex {
226            domain: domain.to_owned(),
227            aggregate_type: aggregate_type.to_owned(),
228            aggregate_ids: aggregate_ids.into_iter().map(Into::into).collect(),
229            tenant: None,
230        }
231    }
232
233    /// The tenant they belong to. Default: the connection's ([`crate::Options::tenant`]).
234    pub fn tenant(mut self, tenant: impl Into<String>) -> Reindex {
235        self.tenant = Some(tenant.into());
236        self
237    }
238}
239
240impl Kernable {
241    /// Stores the unique keys and facts of aggregates as their current state yields them:
242    /// submits the built-in `_reindex_<aggregate_type>` command ([`reindex_type`]; no events)
243    /// to each ID in turn and returns each ID with its outcome. Run it after declaring a key or fact on an aggregate that has events
244    /// already: until an aggregate runs a command, it holds what its last command left. An ID
245    /// without events holds nothing and commits. A rejection is an outcome, e.g.
246    /// `unique_taken` if another aggregate holds one of its keys (a duplicate from before the
247    /// key was declared). [`Error`] as for [`Kernable::submit`], for the first ID that fails;
248    /// the ones before it are done. Needs the `submit` grant for
249    /// `<domain>._reindex_<aggregate_type>`. Example:
250    /// `kernable.reindex(Reindex::new("shop", "customer", ["k1", "k2"])).await?`.
251    pub async fn reindex(&self, reindex: Reindex) -> Result<Vec<(String, Outcome)>, Error> {
252        let mut outcomes = Vec::with_capacity(reindex.aggregate_ids.len());
253        let command = reindex_type(&reindex.aggregate_type);
254        for id in reindex.aggregate_ids {
255            let mut submit = Submit::new(&reindex.domain, &reindex.aggregate_type, &id, &command)
256                .wait(Wait::Committed);
257            if let Some(tenant) = &reindex.tenant {
258                submit = submit.tenant(tenant.clone());
259            }
260            let outcome = self.submit(submit).await?;
261            outcomes.push((id, outcome));
262        }
263        Ok(outcomes)
264    }
265}