Skip to main content

two_devices_one_seat/
scenario.rs

1//! Three files, two sync edges, and the steps the story is told in.
2//!
3//! [`Scenario`] owns every handle the story opens, so dropping it closes them
4//! all at once, and the read-back after it can only see what reached disk.
5
6use std::path::{Path, PathBuf};
7
8use happenstance::{
9    Boundary, Chunk, CommandOutcome, EventStore, Json, Query, ReadOptions, Retry, SequencedEvent,
10    collect, commit, read_decision_model, run_projection,
11};
12use happenstance_sqlite::connection::open_configured;
13use happenstance_sqlite::event_store::SqliteEventStore;
14use happenstance_sqlite::projection_store::SqliteProjectionStore;
15use happenstance_sync::runner::{Adjudicate, Edge, SyncStatus};
16use happenstance_sync::wire::ResumeToken;
17use happenstance_sync::{EventGroup, RemoteSyncPeer, ReplicatedEvent, StoreSyncPeer, SyncPeer};
18use rusqlite::Connection;
19
20use crate::domain::{BoxOffice, Device, Place, SaleId, ShowId, ShowLedger, schedule, sell_seat};
21use crate::error::StoryError;
22use crate::rule::{CentralRule, RuleError};
23use crate::timeline::{DDL, Timeline, TimelineView};
24use crate::uplink::{Central, Link, Uplink};
25
26/// The show the story sells.
27pub const SHOW: &str = "premiere";
28
29/// Its seats.
30pub const CAPACITY: u32 = 3;
31
32/// How many times a decision may be attempted before it gives up: three.
33/// Every writer here is alone on its file, so the bound is never spent.
34/// `MIN.saturating_add` is a `const` way to name a non-zero number without an
35/// `unwrap` that could only fail at compile time anyway.
36const ATTEMPTS: Retry = Retry::attempts(core::num::NonZeroU32::MIN.saturating_add(2));
37
38/// How many events one projection chunk commits: sixteen.
39const CHUNK: core::num::NonZeroUsize = core::num::NonZeroUsize::MIN.saturating_add(15);
40
41/// The most steps one sync takes before it is reported as stuck. A step
42/// against an in-process far side either answers or fails, so this is a
43/// bound on a loop, not a wait: no sleep, no backoff.
44const MAX_STEPS: usize = 4;
45
46/// One place's file, opened in its three roles: the event log, the read
47/// model's checkpoint, and the application's own connection for the read
48/// model's table. All three share one file, as `transfers-on-sqlite` does.
49#[derive(Debug)]
50pub(crate) struct Site {
51    pub(crate) events: SqliteEventStore,
52    models: SqliteProjectionStore,
53    app: Connection,
54    file: PathBuf,
55}
56
57impl Site {
58    /// Opens, or reopens, `at`'s file under `dir`.
59    pub(crate) fn open(dir: &Path, at: Place) -> Result<Self, StoryError> {
60        let file = dir.join(format!("{at}.db"));
61        let events = SqliteEventStore::open(&file).map_err(|source| StoryError::Open {
62            file: file.clone(),
63            source,
64        })?;
65        let models =
66            SqliteProjectionStore::open(&file).map_err(|source| StoryError::OpenModel {
67                file: file.clone(),
68                source,
69            })?;
70        let app = open_configured(&file)
71            .and_then(|app| app.execute_batch(DDL).map(|()| app))
72            .map_err(|source| StoryError::ReadModel {
73                file: file.clone(),
74                source,
75            })?;
76        Ok(Self {
77            events,
78            models,
79            app,
80            file,
81        })
82    }
83
84    /// `show`'s read model as this file holds it.
85    pub(crate) fn view(&self, show: &ShowId) -> Result<TimelineView, StoryError> {
86        TimelineView::read(&self.app, show).map_err(|source| StoryError::ReadModel {
87            file: self.file.clone(),
88            source,
89        })
90    }
91
92    /// Brings this file's read model of `show` up to date, and says how many
93    /// events that applied. `at` names the place in an error.
94    pub(crate) async fn project(&self, at: Place, show: &ShowId) -> Result<usize, StoryError> {
95        let mut timeline = Timeline::new(show);
96        let progressed = run_projection(
97            &self.events,
98            &self.models,
99            &mut timeline,
100            &Json,
101            Chunk::of(CHUNK),
102        )
103        .await
104        .map_err(|source| StoryError::Project {
105            place: at,
106            source: Box::new(source),
107        })?;
108        Ok(progressed.applied)
109    }
110
111    /// Every event in this file's log, in its own order.
112    pub(crate) async fn log(&self, at: Place) -> Result<Vec<SequencedEvent>, StoryError> {
113        collect(self.events.read(&Query::all(), ReadOptions::new()))
114            .await
115            .map_err(|source| StoryError::Read { place: at, source })
116    }
117}
118
119/// A device's side of its one sync relationship: the peer it talks to and
120/// the edge that remembers how far they got.
121///
122/// The edge judges nothing it pulls (its rule is the default `Accept`):
123/// central is the one place that writes a refund (SY-7), so the rule sits on
124/// central's side of the link, on what the device pushes.
125#[derive(Debug)]
126struct Handset<A> {
127    peer: RemoteSyncPeer<Uplink<A>>,
128    edge: Edge<ResumeToken>,
129}
130
131impl<A: Adjudicate<Error = RuleError>> Handset<A> {
132    /// A device linked to `central`, through its own endpoint, whose peer
133    /// judges each push by `rule` before it lands.
134    fn linked_to(central: &Central, rule: A) -> Self {
135        // Two handles onto one store: central's read half and ingest half
136        // must be the same store, and a `SqliteEventStore` clone is a second
137        // handle onto the same connection, not a copy of the log.
138        let far = StoreSyncPeer::new(central.clone(), central.clone()).with_adjudicator(rule);
139        let limits = far.limits();
140        Self {
141            peer: RemoteSyncPeer::new(Uplink::new(far), limits),
142            edge: Edge::new(),
143        }
144    }
145}
146
147/// What one sync moved, counted where it landed.
148///
149/// Counted at the destination rather than on the wire, because a device
150/// pushes its whole log, the events it pulled from central included (SY-27),
151/// and central skips what it already holds. "Sent three" would be true and
152/// would say nothing.
153#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
154pub struct Synced {
155    /// Events new to the device's log.
156    pub pulled: usize,
157    /// Events new to central's log.
158    pub landed: usize,
159}
160
161/// The story's world: central, the tablet and the phone, each on its own file,
162/// one sync edge per device, and the rule central judges every push by.
163///
164/// Generic over the rule, defaulting to central's own, for one reason: the
165/// test that shows the oversell left unanswered mounts a rule that answers
166/// nothing, through [`judged_by`](Self::judged_by). The story and the binary
167/// only ever call [`open`](Self::open).
168#[derive(Debug)]
169pub struct Scenario<A = CentralRule> {
170    show: ShowId,
171    central: Site,
172    tablet: Site,
173    phone: Site,
174    tablet_link: Handset<A>,
175    phone_link: Handset<A>,
176    rule: A,
177}
178
179impl Scenario {
180    /// Opens the three files under `dir`, creating them if they are new, with
181    /// central judging every push by its own rule.
182    ///
183    /// # Errors
184    ///
185    /// [`StoryError::Open`], [`StoryError::OpenModel`] or
186    /// [`StoryError::ReadModel`] naming the file that would not open.
187    pub fn open(dir: &Path) -> Result<Self, StoryError> {
188        Self::judged_by(dir, CentralRule::new)
189    }
190}
191
192impl<A: Adjudicate<Error = RuleError> + Clone> Scenario<A> {
193    /// Opens the three files under `dir`, with central judging every push by
194    /// the rule `rule` builds from central's store and the show.
195    ///
196    /// The rule is cloned once per device, because each device's link holds
197    /// a peer of its own, and kept once more for
198    /// [`judge_again`](Self::judge_again). Central's rule is two handles, so
199    /// a clone is a handle onto the same file and a copy of the show's name.
200    ///
201    /// # Errors
202    ///
203    /// As [`open`](Scenario::open).
204    pub fn judged_by(
205        dir: &Path,
206        rule: impl FnOnce(Central, ShowId) -> A,
207    ) -> Result<Self, StoryError> {
208        let show = ShowId::new(SHOW).map_err(StoryError::Show)?;
209        let central = Site::open(dir, Place::Central)?;
210        let rule = rule(central.events.clone(), show.clone());
211        let tablet_link = Handset::linked_to(&central.events, rule.clone());
212        let phone_link = Handset::linked_to(&central.events, rule.clone());
213        Ok(Self {
214            show,
215            tablet: Site::open(dir, Place::Tablet)?,
216            phone: Site::open(dir, Place::Phone)?,
217            central,
218            tablet_link,
219            phone_link,
220            rule,
221        })
222    }
223
224    const fn site(&self, at: Place) -> &Site {
225        match at {
226            Place::Central => &self.central,
227            Place::Tablet => &self.tablet,
228            Place::Phone => &self.phone,
229        }
230    }
231
232    const fn handset(&self, device: Device) -> &Handset<A> {
233        match device {
234            Device::Tablet => &self.tablet_link,
235            Device::Phone => &self.phone_link,
236        }
237    }
238
239    /// Schedules the show on central.
240    ///
241    /// # Errors
242    ///
243    /// [`StoryError::Schedule`] if the store fails the append.
244    pub async fn schedule(&self, capacity: u32) -> Result<(), StoryError> {
245        commit(
246            &self.central.events,
247            ShowLedger::new(&self.show),
248            ATTEMPTS,
249            |ledger: &ShowLedger| schedule(ledger, capacity),
250        )
251        .await
252        .map(|_| ())
253        .map_err(|source| StoryError::Schedule(Box::new(source)))
254    }
255
256    /// Sells a seat at `at` to `buyer`, deciding against the history `at`
257    /// holds and nothing else: no round trip, with or without signal.
258    ///
259    /// # Errors
260    ///
261    /// [`StoryError::Sell`], carrying the [`Refusal`](crate::Refusal) if the
262    /// decision said no, or [`StoryError::NothingSold`] if it decided nothing.
263    pub async fn sell(&self, at: Place, buyer: &str) -> Result<SaleId, StoryError> {
264        let mut minted = None;
265        let outcome = commit(
266            &self.site(at).events,
267            ShowLedger::new(&self.show),
268            ATTEMPTS,
269            |ledger: &ShowLedger| {
270                let events = sell_seat(ledger, at, buyer)?;
271                // The event moves into the append; the caller is handed a
272                // copy of its id.
273                minted = events.iter().find_map(BoxOffice::sale).cloned();
274                Ok(events)
275            },
276        )
277        .await
278        .map_err(|source| StoryError::Sell {
279            place: at,
280            source: Box::new(source),
281        })?;
282        match (outcome, minted) {
283            (CommandOutcome::Committed(_), Some(sale)) => Ok(sale),
284            _ => Err(StoryError::NothingSold { place: at }),
285        }
286    }
287
288    /// Turns a device's signal on or off, or leaves it able to pull only.
289    pub fn set_link(&self, device: Device, link: Link) {
290        self.handset(device).peer.exchange().set(link);
291    }
292
293    /// Syncs a device with central: pull and ingest, then push, step by step
294    /// until the edge says both sides hold the same history.
295    ///
296    /// A failure is returned, not retried: the story wants to show it.
297    ///
298    /// # Errors
299    ///
300    /// [`StoryError::Sync`] carrying the step's failure and its class, or
301    /// [`StoryError::NotSynced`] if the bound ran out first, or
302    /// [`StoryError::Read`] if central's log cannot be counted.
303    pub async fn sync(&mut self, device: Device) -> Result<Synced, StoryError> {
304        // What landed is counted on central's log before and after: two whole
305        // reads, which a log of six events can afford and a real one would
306        // replace with a count query.
307        let before = self.central.log(Place::Central).await?.len();
308        let (site, handset) = match device {
309            Device::Tablet => (&self.tablet, &mut self.tablet_link),
310            Device::Phone => (&self.phone, &mut self.phone_link),
311        };
312        let mut synced = Synced::default();
313        for _ in 0..MAX_STEPS {
314            let stepped = handset
315                .edge
316                .step(&handset.peer, &site.events)
317                .await
318                .map_err(|source| StoryError::Sync {
319                    device,
320                    source: Box::new(source),
321                })?;
322            synced.pulled = synced.pulled.saturating_add(stepped.ingested.appended);
323            if handset.edge.status().is_synced() {
324                let after = self.central.log(Place::Central).await?.len();
325                synced.landed = after.saturating_sub(before);
326                return Ok(synced);
327            }
328        }
329        Err(StoryError::NotSynced {
330            device,
331            steps: MAX_STEPS,
332        })
333    }
334
335    /// A device's edge, as of its last step.
336    #[must_use]
337    pub const fn status(&self, device: Device) -> &SyncStatus {
338        self.handset(device).edge.status()
339    }
340
341    /// Asks central's rule about everything central holds, as though it were
342    /// all pushed again in one group, and says how many events it answered.
343    ///
344    /// Nothing is written: the rule decides and never writes, and the answer
345    /// is only counted. Central's rule answers a history it has already
346    /// judged with nothing, so a push delivered twice could not earn a second
347    /// refund even if the runner did not skip it (SY-11).
348    ///
349    /// # Errors
350    ///
351    /// [`StoryError::Read`] if central's log cannot be read, and
352    /// [`StoryError::Adjudicate`] if the rule cannot judge it.
353    pub async fn judge_again(&self) -> Result<usize, StoryError> {
354        let held = self
355            .central
356            .log(Place::Central)
357            .await?
358            .into_iter()
359            .map(|event| ReplicatedEvent::new(event.id, event.recorded_at, event.event))
360            .collect();
361        let answered = self
362            .rule
363            .compensation(&EventGroup::new(None, held), &[])
364            .await
365            .map_err(StoryError::Adjudicate)?;
366        Ok(answered.len())
367    }
368
369    /// Brings the read model up to date on all three files, and says how many
370    /// events that applied in all.
371    ///
372    /// # Errors
373    ///
374    /// [`StoryError::Project`] naming the place that failed.
375    pub async fn project(&self) -> Result<usize, StoryError> {
376        let mut applied = 0usize;
377        for at in Place::ALL {
378            let progressed = self.site(at).project(at, &self.show).await?;
379            applied = applied.saturating_add(progressed);
380        }
381        Ok(applied)
382    }
383
384    /// The read model as `at` holds it.
385    ///
386    /// # Errors
387    ///
388    /// [`StoryError::ReadModel`] if the table cannot be read.
389    pub fn view(&self, at: Place) -> Result<TimelineView, StoryError> {
390        self.site(at).view(&self.show)
391    }
392
393    /// The show, folded from the history `at` holds.
394    ///
395    /// # Errors
396    ///
397    /// [`StoryError::Read`] or [`StoryError::Decode`] naming the place.
398    pub async fn ledger(&self, at: Place) -> Result<ShowLedger, StoryError> {
399        let mut ledger = ShowLedger::new(&self.show);
400        let query = ledger.query()?;
401        let (found, _) = read_decision_model(&self.site(at).events, &query)
402            .await
403            .map_err(|source| StoryError::Read { place: at, source })?;
404        for event in &found {
405            ledger
406                .absorb(event, &Json)
407                .map_err(|source| StoryError::Decode { place: at, source })?;
408        }
409        Ok(ledger)
410    }
411
412    /// Every event in `at`'s log.
413    ///
414    /// # Errors
415    ///
416    /// [`StoryError::Read`] naming the place.
417    pub async fn log(&self, at: Place) -> Result<Vec<SequencedEvent>, StoryError> {
418        self.site(at).log(at).await
419    }
420}