Skip to main content

happenstance_sync_testkit/
convergence_fixture.rs

1//! What the convergence family is handed: a projection, its store, and a set
2//! of events from two origins — and the two reference cases over one domain.
3
4use alloc::collections::VecDeque;
5use alloc::format;
6use alloc::vec;
7use alloc::vec::Vec;
8use core::future::Future;
9
10use happenstance::bytes::Bytes;
11use happenstance::{
12    Codec, CodecError, Delivered, DomainEvent, EventType, Postcard, Projection, ProjectionId, Tags,
13};
14use happenstance_core::{MemoryProjectionBatch, MemoryProjectionStore, MemoryProjectionStoreError};
15
16use crate::Violation;
17
18/// The store a fixture's projection commits into.
19pub type StoreOf<F> = <<F as ConvergenceFixture>::Projection as Projection>::Store;
20
21/// The domain event a fixture's projection folds.
22pub type EventOf<F> = <<F as ConvergenceFixture>::Projection as Projection>::Event;
23
24/// One projection, the events two origins authored, and a way to read what it
25/// committed.
26///
27/// The convergence family's fixture, and a different shape from the peer and
28/// ingest families' because its subject is different: not an adapter but a
29/// typed fold. The rule replays the two origins' events in two interleavings
30/// and runs a fresh [`projection`](Self::projection) over each into a fresh
31/// [`store`](Self::store), so every method that builds something is called
32/// once per interleaving and must build it anew.
33///
34/// # No convergence bound here, on purpose (SY-22)
35///
36/// `Projection` is bounded on [`Projection`] alone. The declaration is
37/// required by the rule,
38/// [`convergent_projection_is_interleaving_independent`](crate::convergence_rules::convergent_projection_is_interleaving_independent),
39/// in its own where-clause, so a fixture over an undeclared projection can be
40/// written and cannot be handed to it. That where-clause is the exclusion
41/// SY-22 asks for, and [`CostLayersFixture`] is the honest case it excludes.
42///
43/// # The events are the check's strength
44///
45/// The rule reorders what it is given and nothing else, so a fold that
46/// depends on arrival order is caught only by events whose order it depends
47/// on. Hand it two origins that disagree about something the fold keeps — the
48/// same key written from both sides, a quantity one consumes from the other —
49/// or the rule passes a fold it should not.
50pub trait ConvergenceFixture {
51    /// The projection under test, in either flavour.
52    type Projection: Projection;
53
54    /// The codec its events are written with.
55    type Codec: Codec;
56
57    /// A fresh projection, in the state it starts a rebuild in.
58    fn projection(&self) -> Self::Projection;
59
60    /// The codec the rule encodes the events with and the runner decodes
61    /// them with.
62    fn codec(&self) -> &Self::Codec;
63
64    /// The events each origin authored, in authorship order: origin one's,
65    /// then origin two's.
66    ///
67    /// Neither may be empty. An origin with nothing to interleave makes the
68    /// two interleavings the same log, and a check over one log is decorative,
69    /// so the rule refuses that case rather than passing it.
70    fn authored(&self) -> [Vec<EventOf<Self>>; 2];
71
72    /// A fresh, empty store that shares nothing with any other it returned.
73    ///
74    /// # Errors
75    ///
76    /// A [`Violation`] if the store cannot be opened: the fixture's own
77    /// failure, reported under the clause of the rule that asked.
78    fn store(&self) -> impl Future<Output = Result<StoreOf<Self>, Violation>>;
79
80    /// The read model `store` holds, as bytes the rule compares.
81    ///
82    /// Everything the projection wrote and nothing else: not the checkpoint,
83    /// which is a position in the replica's own log.
84    ///
85    /// # Errors
86    ///
87    /// A [`Violation`] if the store cannot be read, as for
88    /// [`store`](Self::store).
89    fn read_model(&self, store: &StoreOf<Self>)
90    -> impl Future<Output = Result<Vec<u8>, Violation>>;
91}
92
93// ---------------------------------------------------------------------------
94// The reference cases: one stock domain, two folds over it
95// ---------------------------------------------------------------------------
96
97const RECEIVED: EventType = EventType::from_static("StockReceived");
98const ISSUED: EventType = EventType::from_static("StockIssued");
99
100/// A stock movement at one site: the reference cases' domain event.
101///
102/// Encoded as a `(units, unit_cost)` pair under the fixture's codec, which is
103/// why this crate needs no `serde` of its own. An issue carries no cost; what
104/// it cost is what the fold says it cost.
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub enum Stock {
107    /// `units` arrived, each bought at `unit_cost`.
108    Received {
109        /// How many units arrived.
110        units: u64,
111        /// What each one cost.
112        unit_cost: u64,
113    },
114    /// `units` left.
115    Issued {
116        /// How many units left.
117        units: u64,
118    },
119}
120
121impl DomainEvent for Stock {
122    const EVENT_TYPES: &'static [EventType] = &[RECEIVED, ISSUED];
123
124    fn event_type(&self) -> EventType {
125        match self {
126            Self::Received { .. } => RECEIVED,
127            Self::Issued { .. } => ISSUED,
128        }
129    }
130
131    fn tags(&self) -> Tags {
132        Tags::empty()
133    }
134
135    fn encode<C: Codec>(&self, codec: &C) -> Result<Bytes, CodecError> {
136        match *self {
137            Self::Received { units, unit_cost } => codec.encode(&(units, unit_cost)),
138            Self::Issued { units } => codec.encode(&(units, 0_u64)),
139        }
140    }
141
142    fn decode<C: Codec>(
143        codec: &C,
144        event_type: &EventType,
145        data: &Bytes,
146    ) -> Result<Self, CodecError> {
147        if event_type != &RECEIVED && event_type != &ISSUED {
148            return Err(CodecError::UnknownEventType {
149                event_type: event_type.clone(),
150            });
151        }
152        let (units, unit_cost): (u64, u64) = codec.decode(data)?;
153        if event_type == &RECEIVED {
154            Ok(Self::Received { units, unit_cost })
155        } else {
156            Ok(Self::Issued { units })
157        }
158    }
159}
160
161/// The two sites both reference cases replay: each receives ten units at its
162/// own price and issues four. The prices differ, so which layer an issue
163/// consumes is visible in what it cost.
164fn two_sites() -> [Vec<Stock>; 2] {
165    [
166        vec![
167            Stock::Received {
168                units: 10,
169                unit_cost: 3,
170            },
171            Stock::Issued { units: 4 },
172        ],
173        vec![
174            Stock::Received {
175                units: 10,
176                unit_cost: 7,
177            },
178            Stock::Issued { units: 4 },
179        ],
180    ]
181}
182
183/// The bytes a memory store's read model is compared as: every key and value,
184/// in key order, one per line.
185pub(crate) fn memory_read_model(store: &MemoryProjectionStore) -> Vec<u8> {
186    store
187        .snapshot()
188        .iter()
189        .flat_map(|(key, value)| format!("{key}={value}\n").into_bytes())
190        .collect()
191}
192
193/// Units received and units issued, as two sums.
194///
195/// `stock-on-hand`: it converges because addition does not care about order,
196/// and the declaration below is what makes that a checked property rather than
197/// luck (SY-20). The sums saturate, and saturating addition of unsigned values
198/// is still commutative and associative, so even an overflow cannot make the
199/// answer depend on arrival.
200#[derive(Debug)]
201pub struct StockOnHand {
202    id: ProjectionId,
203    scope: Tags,
204    received: u64,
205    issued: u64,
206}
207
208impl Projection for StockOnHand {
209    type Event = Stock;
210    type Store = MemoryProjectionStore;
211    type Error = MemoryProjectionStoreError;
212
213    fn id(&self) -> &ProjectionId {
214        &self.id
215    }
216
217    fn scope(&self) -> &Tags {
218        &self.scope
219    }
220
221    async fn apply(
222        &mut self,
223        event: Delivered<Stock>,
224        batch: &mut MemoryProjectionBatch,
225    ) -> Result<(), MemoryProjectionStoreError> {
226        match *event.event() {
227            Stock::Received { units, .. } => self.received = self.received.saturating_add(units),
228            Stock::Issued { units } => self.issued = self.issued.saturating_add(units),
229        }
230        batch.write("received", self.received);
231        batch.write("issued", self.issued);
232        Ok(())
233    }
234}
235
236impl happenstance::ConvergentProjection for StockOnHand {}
237
238/// The cost of every issue, consuming the oldest units received first.
239///
240/// `cost-layers`: FIFO consumption order **is** the fold, so what an issue
241/// cost depends on which receipt arrived first, and no order exists that two
242/// peers both hold. It is correct and it is not convergent, so it does not
243/// implement [`ConvergentProjection`](happenstance::ConvergentProjection), and
244/// that absence is its SY-22 declaration.
245#[derive(Debug)]
246pub struct CostLayers {
247    id: ProjectionId,
248    scope: Tags,
249    /// Unconsumed receipts, oldest first: `(units, unit_cost)`.
250    layers: VecDeque<(u64, u64)>,
251    cost_of_goods_issued: u64,
252}
253
254impl CostLayers {
255    /// Consumes `units` from the oldest layers, adding what they cost. Units
256    /// issued beyond what is held cost nothing: the fold records what was
257    /// consumed, and there was nothing to consume.
258    fn issue(&mut self, mut units: u64) {
259        while units > 0 {
260            let Some(layer) = self.layers.front_mut() else {
261                return;
262            };
263            let taken = units.min(layer.0);
264            self.cost_of_goods_issued = self
265                .cost_of_goods_issued
266                .saturating_add(taken.saturating_mul(layer.1));
267            // `taken` is the smaller of the two, so neither subtraction can
268            // reach below zero; saturating says so without a second proof.
269            layer.0 = layer.0.saturating_sub(taken);
270            units = units.saturating_sub(taken);
271            if layer.0 == 0 {
272                self.layers.pop_front();
273            }
274        }
275    }
276}
277
278impl Projection for CostLayers {
279    type Event = Stock;
280    type Store = MemoryProjectionStore;
281    type Error = MemoryProjectionStoreError;
282
283    fn id(&self) -> &ProjectionId {
284        &self.id
285    }
286
287    fn scope(&self) -> &Tags {
288        &self.scope
289    }
290
291    async fn apply(
292        &mut self,
293        event: Delivered<Stock>,
294        batch: &mut MemoryProjectionBatch,
295    ) -> Result<(), MemoryProjectionStoreError> {
296        match *event.event() {
297            Stock::Received { units, unit_cost } => self.layers.push_back((units, unit_cost)),
298            Stock::Issued { units } => self.issue(units),
299        }
300        batch.write("cost_of_goods_issued", self.cost_of_goods_issued);
301        Ok(())
302    }
303}
304
305/// [`StockOnHand`] over two sites: the declared case SY-20's rule is proven
306/// against before it may fail anyone's projection.
307#[derive(Debug, Default)]
308pub struct StockOnHandFixture;
309
310impl StockOnHandFixture {
311    /// The fixture. It holds nothing; every projection and store it builds
312    /// is fresh.
313    #[must_use]
314    pub const fn new() -> Self {
315        Self
316    }
317}
318
319impl ConvergenceFixture for StockOnHandFixture {
320    type Projection = StockOnHand;
321    type Codec = Postcard;
322
323    fn projection(&self) -> StockOnHand {
324        StockOnHand {
325            id: ProjectionId::from_static("stock_on_hand"),
326            scope: Tags::empty(),
327            received: 0,
328            issued: 0,
329        }
330    }
331
332    fn codec(&self) -> &Postcard {
333        &Postcard
334    }
335
336    fn authored(&self) -> [Vec<Stock>; 2] {
337        two_sites()
338    }
339
340    async fn store(&self) -> Result<MemoryProjectionStore, Violation> {
341        Ok(MemoryProjectionStore::new())
342    }
343
344    async fn read_model(&self, store: &MemoryProjectionStore) -> Result<Vec<u8>, Violation> {
345        Ok(memory_read_model(store))
346    }
347}
348
349/// [`CostLayers`] over the same two sites: the honest non-convergent case
350/// SY-22 excludes.
351///
352/// A [`ConvergenceFixture`], so the machinery the rule uses can run it, and
353/// not one the rule accepts: its projection makes no convergence declaration.
354/// [`non_convergent_projections_are_excluded_not_failed`](crate::convergence_rules::non_convergent_projections_are_excluded_not_failed)
355/// is where both facts are held.
356#[derive(Debug, Default)]
357pub struct CostLayersFixture;
358
359impl CostLayersFixture {
360    /// The fixture. It holds nothing; every projection and store it builds
361    /// is fresh.
362    #[must_use]
363    pub const fn new() -> Self {
364        Self
365    }
366}
367
368impl ConvergenceFixture for CostLayersFixture {
369    type Projection = CostLayers;
370    type Codec = Postcard;
371
372    fn projection(&self) -> CostLayers {
373        CostLayers {
374            id: ProjectionId::from_static("cost_layers"),
375            scope: Tags::empty(),
376            layers: VecDeque::new(),
377            cost_of_goods_issued: 0,
378        }
379    }
380
381    fn codec(&self) -> &Postcard {
382        &Postcard
383    }
384
385    fn authored(&self) -> [Vec<Stock>; 2] {
386        two_sites()
387    }
388
389    async fn store(&self) -> Result<MemoryProjectionStore, Violation> {
390        Ok(MemoryProjectionStore::new())
391    }
392
393    async fn read_model(&self, store: &MemoryProjectionStore) -> Result<Vec<u8>, Violation> {
394        Ok(memory_read_model(store))
395    }
396}