two_devices_one_seat/rule.rs
1//! Central's rule, mounted where central ingests what a device pushes.
2//!
3//! [`CentralRule`] is a [`happenstance_sync::runner::Adjudicate`]: central's
4//! [`StoreSyncPeer`](happenstance_sync::StoreSyncPeer) asks it about each
5//! group a device pushes, before the push lands, and lands the group and the
6//! refunds it answers in one write (SY-2). Only central's peer mounts it, so
7//! only central writes a refund (SY-7); a device's edge keeps the default,
8//! which judges nothing. The decision itself is the domain's
9//! [`adjudicate`]; this module reads what central holds,
10//! decodes the push, and encodes the answer.
11//!
12//! # Why the bare `Adjudicate`
13//!
14//! For the reason [`Uplink`](crate::Uplink) implements the bare `Exchange`:
15//! the story runs on one thread, the runner takes `!Send` rules as it takes
16//! `!Send` peers, and the `Send` flavour would buy thread safety nobody uses.
17//!
18//! # What the refund carries
19//!
20//! The rule hands back plain [`Event`]s, built from the domain event's type,
21//! tags and JSON bytes. An event `commit` writes also carries the typed
22//! layer's codec tag in its metadata, and the typed layer has no public way to
23//! build one outside `commit` (tracked in #492). A payload without the tag
24//! decodes under the reader's own codec, which is JSON in every place here,
25//! so the refund reads back the same everywhere.
26
27use happenstance::{
28 Boundary, CodecError, DomainEvent, Event, InvalidEventType, InvalidQuery, Json, Query,
29 read_decision_model,
30};
31use happenstance_sync::runner::Adjudicate;
32use happenstance_sync::{Classify, EventGroup, FailureClass, ReplicatedEvent};
33
34use crate::domain::{BoxOffice, ShowId, ShowLedger, adjudicate};
35use crate::uplink::{Central, CentralError};
36
37/// Central's rule over one show: the first sales to reach central keep their
38/// seats, and each later sale lands with its refund.
39///
40/// Holds its own read handle onto central, as the hook asks: a rule reads
41/// what it judges from, and writes nothing.
42#[derive(Debug, Clone)]
43pub struct CentralRule {
44 central: Central,
45 show: ShowId,
46}
47
48impl CentralRule {
49 /// The rule for `show`, reading what `central` holds.
50 ///
51 /// Takes both by value because the rule keeps them: a `SqliteEventStore`
52 /// is a handle onto the same file, not a copy of the log.
53 #[must_use]
54 pub const fn new(central: Central, show: ShowId) -> Self {
55 Self { central, show }
56 }
57
58 /// The show as central holds it now.
59 async fn held(&self) -> Result<(ShowLedger, Query), RuleError> {
60 let mut ledger = ShowLedger::new(&self.show);
61 let query = ledger.query().map_err(RuleError::Query)?;
62 let (found, _) = read_decision_model(&self.central, &query)
63 .await
64 .map_err(RuleError::Read)?;
65 for event in &found {
66 ledger.absorb(event, &Json).map_err(RuleError::Decode)?;
67 }
68 Ok((ledger, query))
69 }
70}
71
72impl Adjudicate for CentralRule {
73 type Error = RuleError;
74
75 /// The refunds `group` lands with: one for each sale in it that lands
76 /// past capacity, after what central holds and what lands before it in
77 /// the same push.
78 ///
79 /// # Errors
80 ///
81 /// [`RuleError`] if central's history cannot be read or an event cannot
82 /// be decoded or encoded. Nothing in the push is written.
83 async fn compensation(
84 &self,
85 group: &EventGroup,
86 earlier: &[EventGroup],
87 ) -> Result<Vec<Event>, RuleError> {
88 let (ledger, query) = self.held().await?;
89 let before = earlier
90 .iter()
91 .map(|group| decode(&query, &group.events))
92 .collect::<Result<Vec<_>, _>>()?;
93 let arriving = decode(&query, &group.events)?;
94 adjudicate(ledger, before, arriving)
95 .iter()
96 .map(encode)
97 .collect()
98 }
99}
100
101/// The show's events among `events`, decoded. An event outside the show's
102/// query is not this rule's to judge, and is passed over.
103fn decode<'a>(
104 query: &Query,
105 events: impl IntoIterator<Item = &'a ReplicatedEvent>,
106) -> Result<Vec<BoxOffice>, RuleError> {
107 events
108 .into_iter()
109 .map(|replicated| &replicated.event)
110 .filter(|event| query.matches(event.event_type(), event.tags()))
111 .map(|event| {
112 BoxOffice::decode(&Json, event.event_type(), event.data()).map_err(RuleError::Decode)
113 })
114 .collect()
115}
116
117/// A decided event as the store takes it: its type, its tags, its JSON bytes.
118fn encode(event: &BoxOffice) -> Result<Event, RuleError> {
119 let data = event.encode(&Json).map_err(RuleError::Encode)?;
120 Ok(Event::new(event.event_type(), data)
121 .map_err(RuleError::EventType)?
122 .with_tags(event.tags()))
123}
124
125/// Why central's rule could not judge a push. Every case writes nothing.
126#[derive(Debug, thiserror::Error)]
127pub enum RuleError {
128 /// The show's query could not be derived.
129 #[error("the show's query")]
130 Query(#[source] InvalidQuery),
131 /// Central's history could not be read.
132 #[error("reading central's history")]
133 Read(#[source] CentralError),
134 /// An event central holds, or one in the push, did not decode.
135 #[error("decoding an event to judge")]
136 Decode(#[source] CodecError),
137 /// A refund did not encode.
138 #[error("encoding a refund")]
139 Encode(#[source] CodecError),
140 /// A refund's event type was refused. The type is a declared constant,
141 /// so this is a broken declaration, reported rather than assumed away.
142 #[error("a refund's event type")]
143 EventType(#[source] InvalidEventType),
144}
145
146impl Classify for RuleError {
147 /// A failed read keeps the class the store stated (SY-36). Everything
148 /// else fails the same way on every retry, so it stops the edge.
149 fn class(&self) -> FailureClass {
150 match self {
151 Self::Read(error) => error.class(),
152 Self::Query(_) | Self::Decode(_) | Self::Encode(_) | Self::EventType(_) => {
153 FailureClass::Stop
154 }
155 }
156 }
157}