Skip to main content

two_devices_one_seat/
domain.rs

1//! The box office: who sells, what happens to a show, and the one rule.
2//!
3//! Nothing in this module knows about SQLite or sync. The same decision model
4//! runs on a device, offline, and on central, over the whole history; that it
5//! is one model is the point (the pillar *true to your rules*).
6
7use core::fmt;
8use std::collections::BTreeMap;
9
10use happenstance::bytes::Bytes;
11use happenstance::{
12    Codec, CodecError, DecisionModel, DomainEvent, EventType, InvalidTag, Tag, Tags,
13};
14use serde::{Deserialize, Serialize};
15
16/// Every place that holds a copy of the log and can sell a seat.
17///
18/// A closed set, so every `match` on it names all three.
19#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
20#[serde(rename_all = "lowercase")]
21pub enum Place {
22    /// The central store: the box office's own till, and the one place that
23    /// sees every device's history once they sync.
24    Central,
25    /// The box-office tablet, a store of its own on its own file.
26    Tablet,
27    /// A phone, likewise.
28    Phone,
29}
30
31impl Place {
32    /// All three, central first, in the order the story prints them.
33    pub const ALL: [Self; 3] = [Self::Central, Self::Tablet, Self::Phone];
34
35    /// The name a sale id and the transcript use.
36    #[must_use]
37    pub const fn as_str(self) -> &'static str {
38        match self {
39            Self::Central => "central",
40            Self::Tablet => "tablet",
41            Self::Phone => "phone",
42        }
43    }
44}
45
46impl fmt::Display for Place {
47    /// `pad` rather than `write_str`, so `{:<8}` aligns a column.
48    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49        f.pad(self.as_str())
50    }
51}
52
53impl core::str::FromStr for Place {
54    type Err = UnknownPlace;
55
56    fn from_str(name: &str) -> Result<Self, UnknownPlace> {
57        Self::ALL
58            .into_iter()
59            .find(|place| place.as_str() == name)
60            .ok_or(UnknownPlace)
61    }
62}
63
64/// A place name that is none of the three.
65#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
66#[error("not a place: expected central, tablet or phone")]
67pub struct UnknownPlace;
68
69/// The two places that sync with central. Central does not sync with itself,
70/// so a function taking a `Device` cannot be asked to.
71#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
72pub enum Device {
73    /// The box-office tablet.
74    Tablet,
75    /// The phone.
76    Phone,
77}
78
79impl Device {
80    /// The device that is not this one.
81    #[must_use]
82    pub const fn other(self) -> Self {
83        match self {
84            Self::Tablet => Self::Phone,
85            Self::Phone => Self::Tablet,
86        }
87    }
88}
89
90impl From<Device> for Place {
91    fn from(device: Device) -> Self {
92        match device {
93            Device::Tablet => Self::Tablet,
94            Device::Phone => Self::Phone,
95        }
96    }
97}
98
99impl fmt::Display for Device {
100    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
101        fmt::Display::fmt(&Place::from(*self), f)
102    }
103}
104
105/// A show, validated once into the tag every one of its events carries.
106///
107/// The shape `transfers-on-sqlite` reaches for its accounts: `DomainEvent::tags`
108/// cannot fail and `Tag::key_value` can, so the type holds the validated tag
109/// rather than rebuilding it on every call.
110#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
111#[serde(try_from = "String", into = "String")]
112pub struct ShowId {
113    name: String,
114    tag: Tag,
115}
116
117impl ShowId {
118    /// Validates `name` into the show's tag.
119    ///
120    /// # Errors
121    ///
122    /// [`InvalidTag`] if `name` cannot be a tag value.
123    pub fn new(name: &str) -> Result<Self, InvalidTag> {
124        Ok(Self {
125            name: name.to_owned(),
126            tag: Tag::key_value("show", name)?,
127        })
128    }
129
130    /// The name as the application wrote it.
131    #[must_use]
132    pub fn as_str(&self) -> &str {
133        &self.name
134    }
135
136    /// The scope every model and view of this show reads: its one tag.
137    #[must_use]
138    pub fn scope(&self) -> Tags {
139        [self.tag.clone()].into_iter().collect()
140    }
141}
142
143impl TryFrom<String> for ShowId {
144    type Error = InvalidTag;
145
146    fn try_from(name: String) -> Result<Self, InvalidTag> {
147        Self::new(&name)
148    }
149}
150
151impl From<ShowId> for String {
152    fn from(show: ShowId) -> Self {
153        show.name
154    }
155}
156
157impl fmt::Display for ShowId {
158    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159        f.write_str(&self.name)
160    }
161}
162
163/// One sale, named by the place that made it and its count there:
164/// `central-1`, `tablet-1`, `phone-1`.
165///
166/// Minted by the decision from the history it folded, so a run's ids are the
167/// same every time and the transcript can be quoted. Not a tag: nothing queries
168/// by sale, and a field that is never queried does not need to be indexed.
169#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
170#[serde(transparent)]
171pub struct SaleId(String);
172
173impl SaleId {
174    /// The `n`th sale made at `at`.
175    fn mint(at: Place, n: usize) -> Self {
176        Self(format!("{at}-{n}"))
177    }
178
179    /// The id as the transcript prints it.
180    #[must_use]
181    pub fn as_str(&self) -> &str {
182        &self.0
183    }
184
185    /// The id, given up as the string it is.
186    #[must_use]
187    pub fn into_string(self) -> String {
188        self.0
189    }
190}
191
192impl fmt::Display for SaleId {
193    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194        f.write_str(&self.0)
195    }
196}
197
198/// Everything that can happen at the box office.
199///
200/// One enum, so a query and a fold cannot name different sets, and no `_ =>`
201/// arm anywhere in this crate: a fourth variant is a compile error in every
202/// fold that has not been taught it.
203///
204/// # The payload's shape is pinned
205///
206/// Every payload is an object that names itself, `{"type": "seat_sold",
207/// "show": ..., ...}`. The attribute says so instead of leaving it to serde's
208/// default, which keys the object by the Rust variant's name: under that
209/// default, renaming a variant would silently change what goes into the log,
210/// while here it changes nothing on disk.
211///
212/// A v2 of an event keeps every v1 already in a log readable, and the log is
213/// never rewritten. The changed event takes a new event type, and
214/// [`decode`](DomainEvent::decode) starts reading the event-type argument it
215/// ignores today: the old type decodes into a private DTO of the v1 shape,
216/// mapped by a total `upcast` into this enum, so no fold ever sees two shapes.
217/// Dispatching on the type rather than trying one shape and then the other
218/// means a payload that fits neither is reported, not guessed at.
219/// `telemetry-across-codecs` upcasts a v1 shape in exactly this place.
220#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
221#[serde(tag = "type", rename_all = "snake_case")]
222pub enum BoxOffice {
223    /// A show exists and has this many seats.
224    ShowScheduled {
225        /// The show.
226        show: ShowId,
227        /// How many seats it has.
228        capacity: u32,
229    },
230    /// A seat was sold. Holding the seat is the sale's until a refund says
231    /// otherwise.
232    SeatSold {
233        /// The show.
234        show: ShowId,
235        /// Which sale this is.
236        sale: SaleId,
237        /// Who bought it.
238        buyer: String,
239        /// Where it was sold.
240        sold_by: Place,
241    },
242    /// A sale was refunded, and why. The compensation SY-2 describes: an
243    /// ordinary append, which says what happened instead of rewriting it.
244    SaleRefunded {
245        /// The show.
246        show: ShowId,
247        /// The sale refunded.
248        sale: SaleId,
249        /// Why, as data, so every replica prints the same audit line.
250        reason: RefundReason,
251    },
252}
253
254impl BoxOffice {
255    /// The sale this event is about, if it is about one.
256    #[must_use]
257    pub const fn sale(&self) -> Option<&SaleId> {
258        match self {
259            Self::ShowScheduled { .. } => None,
260            Self::SeatSold { sale, .. } | Self::SaleRefunded { sale, .. } => Some(sale),
261        }
262    }
263}
264
265const SHOW_SCHEDULED: EventType = EventType::from_static("ShowScheduled");
266const SEAT_SOLD: EventType = EventType::from_static("SeatSold");
267/// The refund's event type, which the read-back counts by.
268pub(crate) const SALE_REFUNDED: EventType = EventType::from_static("SaleRefunded");
269
270impl DomainEvent for BoxOffice {
271    const EVENT_TYPES: &'static [EventType] = &[SHOW_SCHEDULED, SEAT_SOLD, SALE_REFUNDED];
272
273    fn event_type(&self) -> EventType {
274        match self {
275            Self::ShowScheduled { .. } => SHOW_SCHEDULED,
276            Self::SeatSold { .. } => SEAT_SOLD,
277            Self::SaleRefunded { .. } => SALE_REFUNDED,
278        }
279    }
280
281    fn tags(&self) -> Tags {
282        match self {
283            Self::ShowScheduled { show, .. }
284            | Self::SeatSold { show, .. }
285            | Self::SaleRefunded { show, .. } => show.scope(),
286        }
287    }
288
289    fn encode<C: Codec>(&self, codec: &C) -> Result<Bytes, CodecError> {
290        codec.encode(self)
291    }
292
293    fn decode<C: Codec>(
294        codec: &C,
295        _event_type: &EventType,
296        data: &Bytes,
297    ) -> Result<Self, CodecError> {
298        codec.decode(data)
299    }
300}
301
302/// Why central refunded a sale: what it saw, and which rule it applied.
303#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
304pub struct RefundReason {
305    /// The show's capacity.
306    pub capacity: u32,
307    /// How many sales were holding a seat when central decided.
308    pub sales_seen: u32,
309    /// The rule that chose this sale.
310    pub rule: Rule,
311}
312
313impl fmt::Display for RefundReason {
314    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
315        write!(
316            f,
317            "{} sales reached central for {} seats; rule: {}",
318            self.sales_seen, self.capacity, self.rule
319        )
320    }
321}
322
323/// The rules central can refund by. One today, and an enum rather than a
324/// string so the audit line is data a fold can match on.
325#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
326pub enum Rule {
327    /// The sales that reached central first keep their seats, by central's
328    /// own log order; the ones past capacity are refunded.
329    FirstToReachCentralKeepsTheSeat,
330}
331
332impl fmt::Display for Rule {
333    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
334        f.write_str(match self {
335            Self::FirstToReachCentralKeepsTheSeat => {
336                "the first sale to reach central keeps the seat"
337            }
338        })
339    }
340}
341
342/// Why a sale was refused.
343#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
344pub enum Refusal {
345    /// The show has not reached this store yet.
346    #[error("show {show} is not scheduled here yet")]
347    NotScheduled {
348        /// The show asked for.
349        show: String,
350    },
351    /// Every seat is held.
352    #[error("sold out: {held} of {capacity} seats are held")]
353    SoldOut {
354        /// The show's capacity.
355        capacity: u32,
356        /// Seats held, as this store knows them.
357        held: u32,
358    },
359}
360
361/// One sale as a ledger keeps it.
362#[derive(Debug, Clone, PartialEq, Eq)]
363pub struct Sale {
364    /// Which sale.
365    pub sale: SaleId,
366    /// Who bought it.
367    pub buyer: String,
368    /// Where it was sold.
369    pub sold_by: Place,
370}
371
372/// One show, as the history a store holds tells it.
373///
374/// A decision model over **one** log, folded in that log's own order. On
375/// central that order is the order sales arrived in, which is what the rule
376/// refunds by. It is not a convergent fold, and does not need to be: the
377/// decision it informs is written down as an event, and that event is what
378/// replicates.
379#[derive(Debug, Clone)]
380pub struct ShowLedger {
381    show: ShowId,
382    scope: Tags,
383    capacity: Option<u32>,
384    sales: Vec<Sale>,
385    refunds: BTreeMap<SaleId, RefundReason>,
386}
387
388impl ShowLedger {
389    /// An empty ledger for `show`.
390    #[must_use]
391    pub fn new(show: &ShowId) -> Self {
392        Self {
393            show: show.clone(),
394            scope: show.scope(),
395            capacity: None,
396            sales: Vec::new(),
397            refunds: BTreeMap::new(),
398        }
399    }
400
401    /// The show's capacity, once it is scheduled here.
402    #[must_use]
403    pub const fn capacity(&self) -> Option<u32> {
404        self.capacity
405    }
406
407    /// Every sale, in this log's order, refunded ones included.
408    pub fn sales(&self) -> impl Iterator<Item = &Sale> + '_ {
409        self.sales.iter()
410    }
411
412    /// The sales still holding a seat, in this log's order.
413    pub fn holding(&self) -> impl Iterator<Item = &Sale> + '_ {
414        self.sales
415            .iter()
416            .filter(|sale| !self.refunds.contains_key(&sale.sale))
417    }
418
419    /// The sales refunded, by id.
420    pub fn refunded(&self) -> impl Iterator<Item = &SaleId> + '_ {
421        self.refunds.keys()
422    }
423
424    /// Why `sale` was refunded, if it was.
425    #[must_use]
426    pub fn refund_reason(&self, sale: &SaleId) -> Option<&RefundReason> {
427        self.refunds.get(sale)
428    }
429
430    /// How many seats are held. Saturates at `u32::MAX`, which a show's
431    /// capacity can never reach past.
432    #[must_use]
433    pub fn held(&self) -> u32 {
434        u32::try_from(self.holding().count()).unwrap_or(u32::MAX)
435    }
436}
437
438impl DecisionModel for ShowLedger {
439    type Event = BoxOffice;
440
441    fn scope(&self) -> &Tags {
442        &self.scope
443    }
444
445    fn apply(&mut self, event: BoxOffice) {
446        match event {
447            BoxOffice::ShowScheduled { capacity, .. } => self.capacity = Some(capacity),
448            BoxOffice::SeatSold {
449                sale,
450                buyer,
451                sold_by,
452                ..
453            } => self.sales.push(Sale {
454                sale,
455                buyer,
456                sold_by,
457            }),
458            BoxOffice::SaleRefunded { sale, reason, .. } => {
459                self.refunds.insert(sale, reason);
460            }
461        }
462    }
463}
464
465mod decide;
466pub use decide::{adjudicate, schedule, sell_seat};
467
468#[cfg(test)]
469mod tests;