Skip to main content

two_devices_one_seat/
story.rs

1//! The story, told beat by beat into any writer.
2//!
3//! Written against `io::Write` rather than to stdout, so the binary hands it a
4//! locked stdout and a test hands it a `Vec<u8>`. Nothing printed depends on
5//! the run: no store id, no path, no time, so the transcript can be quoted.
6
7use std::io::Write;
8use std::path::Path;
9
10use happenstance_sync::FailureClass;
11
12use crate::domain::{Device, Place, ShowLedger};
13use crate::error::StoryError;
14use crate::readback::Converged;
15use crate::scenario::{CAPACITY, SHOW, Scenario, Synced};
16use crate::timeline::{Row, Status, TimelineView};
17use crate::uplink::Link;
18
19/// Tells the whole story into `out` over three files under `dir`, and returns
20/// what the files held when they were read back with every handle dropped.
21///
22/// # Errors
23///
24/// Any [`StoryError`]: a file that will not open, a decision or sync that
25/// fails in a way the story did not expect, or a write to `out` that fails.
26pub async fn tell<W: Write>(dir: &Path, out: &mut W) -> Result<Converged, StoryError> {
27    // One scope owns every handle, so all of them are closed before the
28    // read-back opens the files again.
29    {
30        let mut scenario = Scenario::open(dir)?;
31        the_show(&mut scenario, out).await?;
32        offline(&mut scenario, out).await?;
33        back_online(&mut scenario, out).await?;
34        converge(&mut scenario, out).await?;
35    }
36    let converged = Converged::read(dir).await?;
37    read_back(&converged, out)?;
38    try_again(dir, out).await?;
39    Ok(converged)
40}
41
42/// Central schedules the show and sells two seats; both devices sync down.
43async fn the_show<W: Write>(scenario: &mut Scenario, out: &mut W) -> Result<(), StoryError> {
44    writeln!(out, "== the show ==")?;
45    scenario.schedule(CAPACITY).await?;
46    writeln!(out, "   central schedules {SHOW:?} with {CAPACITY} seats")?;
47    for buyer in ["Ada", "Brian"] {
48        let sale = scenario.sell(Place::Central, buyer).await?;
49        writeln!(out, "   central sells {sale} to {buyer}")?;
50    }
51    for device in [Device::Tablet, Device::Phone] {
52        let synced = scenario.sync(device).await?;
53        synced_line(out, device, synced)?;
54    }
55    for at in Place::ALL {
56        if scenario.ledger(at).await?.held() != 2 {
57            return Err(StoryError::Contradicted {
58                claim: "every place holds two sales",
59            });
60        }
61    }
62    writeln!(
63        out,
64        "   every place holds 2 of {CAPACITY} seats sold; one is left"
65    )?;
66    Ok(())
67}
68
69/// The signal drops, both devices sell the last seat, and a sync fails
70/// without losing anything.
71async fn offline<W: Write>(scenario: &mut Scenario, out: &mut W) -> Result<(), StoryError> {
72    writeln!(out, "\n== the signal drops ==")?;
73    for device in [Device::Tablet, Device::Phone] {
74        scenario.set_link(device, Link::Down);
75        writeln!(out, "   {device}: no signal")?;
76    }
77
78    writeln!(out, "\n== both devices sell the last seat ==")?;
79    for (device, buyer) in [(Device::Tablet, "Grace"), (Device::Phone, "Linus")] {
80        let at = Place::from(device);
81        let sale = scenario.sell(at, buyer).await?;
82        let held = scenario.ledger(at).await?.held();
83        writeln!(
84            out,
85            "   {device} sells {sale} to {buyer}: accepted, {held} of {CAPACITY} held as the {device} knows it"
86        )?;
87    }
88    match scenario.sync(Device::Tablet).await {
89        Err(error) => match error.failure() {
90            Some(failure) if failure.class == FailureClass::Transient => writeln!(
91                out,
92                "   the tablet tries to sync: no signal, {failure};\n   \
93                 the edge keeps its place, and the sale waits on the tablet"
94            )?,
95            _ => return Err(error),
96        },
97        Ok(_) => {
98            return Err(StoryError::Contradicted {
99                claim: "a sync with no signal fails",
100            });
101        }
102    }
103    Ok(())
104}
105
106/// The signal returns: both devices push, central holds four sales for three
107/// seats, and the push that oversold the show landed with central's refund.
108async fn back_online<W: Write>(scenario: &mut Scenario, out: &mut W) -> Result<(), StoryError> {
109    writeln!(out, "\n== the signal returns ==")?;
110    for device in [Device::Tablet, Device::Phone] {
111        scenario.set_link(device, Link::Up);
112        let synced = scenario.sync(device).await?;
113        synced_line(out, device, synced)?;
114    }
115
116    writeln!(out, "\n== central sees the whole history ==")?;
117    let ledger = scenario.ledger(Place::Central).await?;
118    history(out, &ledger)?;
119    writeln!(
120        out,
121        "   {} sales for {CAPACITY} seats: each device was right about what it knew,",
122        ledger.sales().count()
123    )?;
124    writeln!(out, "   and ingest refused neither (SY-1)")?;
125
126    writeln!(out, "\n== central keeps its rule ==")?;
127    if ledger.refunded().count() != 1 {
128        return Err(StoryError::Contradicted {
129            claim: "central refunds the seat sold twice",
130        });
131    }
132    writeln!(
133        out,
134        "   central judged each push as it landed: the sale past capacity\n   \
135         landed with its refund, in one write (SY-2)"
136    )?;
137    for sale in ledger.sales() {
138        if let Some(reason) = ledger.refund_reason(&sale.sale) {
139            writeln!(
140                out,
141                "   refunded {} ({}, sold at {}): {reason}",
142                sale.sale, sale.buyer, sale.sold_by
143            )?;
144        }
145    }
146    if scenario.judge_again().await? != 0 {
147        return Err(StoryError::Contradicted {
148            claim: "central's rule, applied twice, refunds once",
149        });
150    }
151    writeln!(out, "   central applies its rule again: nothing to do")?;
152    writeln!(
153        out,
154        "   {} of {CAPACITY} seats held, as central knows it",
155        ledger.held()
156    )?;
157    Ok(())
158}
159
160/// Both devices pull the refund, and every place projects the same view.
161async fn converge<W: Write>(scenario: &mut Scenario, out: &mut W) -> Result<(), StoryError> {
162    writeln!(out, "\n== everyone converges ==")?;
163    for device in [Device::Tablet, Device::Phone] {
164        let synced = scenario.sync(device).await?;
165        synced_line(out, device, synced)?;
166    }
167
168    writeln!(out, "\n== the same view, three places ==")?;
169    scenario.project().await?;
170    for at in Place::ALL {
171        let view = scenario.view(at)?;
172        view_line(out, at, &view)?;
173    }
174    let view = scenario.view(Place::Central)?;
175    for row in view
176        .rows
177        .iter()
178        .filter(|row| row.status == Status::Refunded)
179    {
180        writeln!(out, "   audit: {}", audit(row))?;
181    }
182    Ok(())
183}
184
185/// What the three files hold, read back with every handle dropped.
186fn read_back<W: Write>(converged: &Converged, out: &mut W) -> Result<(), StoryError> {
187    writeln!(out, "\n== every handle dropped; reading the files back ==")?;
188    for (at, replica) in converged.replicas() {
189        if replica
190            .refunds
191            .iter()
192            .any(|id| id.store() != converged.central.store)
193        {
194            return Err(StoryError::Contradicted {
195                claim: "central wrote every refund (SY-7)",
196            });
197        }
198        let refunds = u32::try_from(replica.refunds.len()).unwrap_or(u32::MAX);
199        writeln!(
200            out,
201            "   {at:<8} {} events, {}, written by central",
202            replica.ids.len(),
203            plural(refunds, "refund", "refunds")
204        )?;
205    }
206    if !converged.agrees() {
207        return Err(StoryError::Contradicted {
208            claim: "the three files agree",
209        });
210    }
211    writeln!(
212        out,
213        "   the three logs hold the same {} events; the three read models are identical",
214        converged.central.ids.len()
215    )?;
216    Ok(())
217}
218
219/// The phone, reopened and offline, decides against the complete history.
220async fn try_again<W: Write>(dir: &Path, out: &mut W) -> Result<(), StoryError> {
221    writeln!(out, "\n== the phone tries again ==")?;
222    let scenario = Scenario::open(dir)?;
223    scenario.set_link(Device::Phone, Link::Down);
224    match scenario.sell(Place::Phone, "Margaret").await {
225        Err(error) => match error.refusal() {
226            Some(refusal) => writeln!(
227                out,
228                "   the phone, offline, sells to Margaret: refused, {refusal}"
229            )?,
230            None => return Err(error),
231        },
232        Ok(_) => {
233            return Err(StoryError::Contradicted {
234                claim: "the phone refuses a seat central has kept",
235            });
236        }
237    }
238    writeln!(
239        out,
240        "   no round trip: the history it holds is the complete one"
241    )?;
242    Ok(())
243}
244
245fn synced_line<W: Write>(out: &mut W, device: Device, synced: Synced) -> Result<(), StoryError> {
246    writeln!(
247        out,
248        "   {device} syncs: {} in, {} out",
249        events(synced.pulled),
250        events(synced.landed)
251    )?;
252    Ok(())
253}
254
255fn history<W: Write>(out: &mut W, ledger: &ShowLedger) -> Result<(), StoryError> {
256    for sale in ledger.sales() {
257        writeln!(
258            out,
259            "   {:<10} {:<6} sold at {}",
260            sale.sale.as_str(),
261            sale.buyer,
262            sale.sold_by
263        )?;
264    }
265    Ok(())
266}
267
268fn view_line<W: Write>(out: &mut W, at: Place, view: &TimelineView) -> Result<(), StoryError> {
269    let Some(capacity) = view.capacity else {
270        writeln!(out, "   {at:<8} the show is not scheduled here")?;
271        return Ok(());
272    };
273    writeln!(
274        out,
275        "   {at:<8} {} of {capacity} seats held, {} sales, {}",
276        view.held(),
277        view.sales(),
278        plural(view.refunds(), "refund", "refunds")
279    )?;
280    Ok(())
281}
282
283/// The audit line, from the row's own data: the reason travelled with the
284/// refund, so every replica prints the same words. A refund whose sale has not
285/// arrived yet has no buyer or place, and says so.
286fn audit(row: &Row) -> String {
287    let sold = match (&row.buyer, row.sold_by) {
288        (Some(buyer), Some(at)) => format!("{buyer}, sold at {at}"),
289        _ => "its sale not yet here".to_owned(),
290    };
291    let reason = row.reason.as_deref().unwrap_or("no reason recorded");
292    format!("{} ({sold}): {reason}", row.sale)
293}
294
295fn events(n: usize) -> String {
296    if n == 1 {
297        "1 event".to_owned()
298    } else {
299        format!("{n} events")
300    }
301}
302
303fn plural(n: u32, one: &str, many: &str) -> String {
304    if n == 1 {
305        format!("1 {one}")
306    } else {
307        format!("{n} {many}")
308    }
309}