happenstance_sync_testkit/ingest_fixture.rs
1//! What a store adapter hands the ingest family, and the reference
2//! implementation of it.
3
4use alloc::format;
5use alloc::sync::Arc;
6use alloc::vec::Vec;
7use core::future::Future;
8use core::num::NonZeroUsize;
9
10use happenstance_testkit::Capability;
11
12use crate::violation::{Violation, ensure};
13
14use happenstance_core::futures_core::Stream;
15use happenstance_core::{
16 AppendCondition, AppendError, Event, EventId, MemoryStoreError, Query, ReadOptions,
17 SendEventStore, SequencePosition, SequencedEvent, StoreId,
18};
19use happenstance_sync::{
20 GroupPage, IngestError, IngestGroup, Ingested, MemoryIngestStore, SendIngestStore,
21 SendWriteGroupStore, Watermark,
22};
23
24/// One isolated backing store that both appends and ingests, and a way to
25/// reach it.
26///
27/// One fixture instance is one isolated backing store, and each
28/// [`connect`](Self::connect) is one handle onto it: the event-store family's
29/// contract, one port over. A rule calls the opener it is given for a fresh
30/// instance, so no rule sees another's events.
31///
32/// # No `Send`, on purpose
33///
34/// Not `trait_variant`-derived, and bounded on the bare `EventStore` and
35/// `IngestStore`, so a `!Send` store, the Durable Object's, is a valid fixture.
36/// This crate's `tests/local_ingest_conformance.rs` mounts one.
37///
38/// # Capabilities are defaulted items
39///
40/// Every item past [`connect`](Self::connect) has a default, so each one
41/// added is additive to every implementation written before it, as
42/// `happenstance_testkit::Fixture`'s capabilities are:
43///
44/// * [`MID_GROUP_FAULT`](Self::MID_GROUP_FAULT) and
45/// [`arm_mid_group_fault`](Self::arm_mid_group_fault), which SY-30's rule
46/// needs. Declined by default, in this crate's words, and
47/// [`ingest_declensions_are_stated`] rejects a fixture that keeps them.
48/// * Three per-event ceilings, which SY-18's ingest rule holds to every event
49/// an ingest writes. `None` by default: facts, not trades.
50/// * One per-call ceiling, [`MAX_TAGS_PER_BATCH`](Self::MAX_TAGS_PER_BATCH),
51/// which VT-36's ingest rule holds to the whole call, compensation
52/// included. `None` by default, for the same reason.
53pub trait IngestFixture {
54 /// The store under test: an event store that also ingests.
55 type Store: happenstance_core::EventStore + happenstance_sync::IngestStore;
56
57 /// Whether this fixture can make its store fail between two rows of one
58 /// ingest group.
59 ///
60 /// SY-30 says a group lands whole, and a conformant store decides every
61 /// refusal before it writes, so the case left is a fault inside the write.
62 /// Nothing in the port reaches between two rows of one `ingest`, so the
63 /// injection is the adapter's: a trigger, a constraint armed for one write.
64 ///
65 /// A store that can absorb every fault its fixture could arm, and commit
66 /// the group anyway, declines: the rule requires an armed ingest to fail,
67 /// or it has not shown that a failure leaves nothing behind.
68 const MID_GROUP_FAULT: Capability = Capability::declined(UNSTATED_MID_GROUP_FAULT);
69
70 /// The largest `data` payload, in bytes, the store accepts in one event,
71 /// or `None` for no ceiling.
72 ///
73 /// A fact about the store rather than a trade, so an `Option` rather than
74 /// a [`Capability`]. It must mirror the adapter's own constant, never a
75 /// literal restated here, or the rule checks the fixture and not the store.
76 const MAX_EVENT_DATA_LEN: Option<usize> = None;
77
78 /// The most tags the store accepts on one event, or `None` for no
79 /// ceiling. Mirrored, as [`MAX_EVENT_DATA_LEN`](Self::MAX_EVENT_DATA_LEN)
80 /// is.
81 const MAX_TAGS_PER_EVENT: Option<usize> = None;
82
83 /// The largest `metadata`, in bytes, the store accepts on one event, or
84 /// `None` for no ceiling. Mirrored, as
85 /// [`MAX_EVENT_DATA_LEN`](Self::MAX_EVENT_DATA_LEN) is. Zero is a legal
86 /// declaration, because the contract guarantees no metadata capacity.
87 const MAX_METADATA_LEN: Option<usize> = None;
88
89 /// The most tags, summed over every foreign event and every compensation
90 /// event of one `ingest` call, the store accepts, or `None` for no ceiling
91 /// beyond what its per-event ceiling and its call length already imply.
92 ///
93 /// Mirrored from the adapter's own constant, as
94 /// [`MAX_EVENT_DATA_LEN`](Self::MAX_EVENT_DATA_LEN) is. Stating a number
95 /// commits the store to landing a call that carries exactly that many and
96 /// to refusing one more as `IngestError::ExceedsStoreLimit { limit:
97 /// StoreLimit::TagsPerBatch, .. }`, class `Split`, with nothing written.
98 /// The call is the batch: its groups and their compensation count
99 /// together (VT-36, ADR-0100). It must be at least
100 /// [`MAX_TAGS_PER_EVENT`](Self::MAX_TAGS_PER_EVENT), or a call of one
101 /// event within its own ceiling is refused as a batch with nothing left
102 /// to split.
103 const MAX_TAGS_PER_BATCH: Option<usize> = None;
104
105 /// A handle onto this fixture's one backing store.
106 ///
107 /// An implementation in test code may panic when the environment cannot
108 /// connect, as the event-store family's fixtures do: the suite has nothing
109 /// to report about a store it never reached.
110 fn connect(&self) -> impl Future<Output = Self::Store>;
111
112 /// Arms the store so that its next `ingest` fails while writing the
113 /// `after + 1`-th row it writes in that call.
114 ///
115 /// Foreign rows and compensation rows both count, in the store's own write
116 /// order; a row it skips is not written and is not counted. Arming reaches
117 /// handles already connected. The fault may stay armed for the fixture's
118 /// life: no rule writes to an armed fixture except with the one ingest it
119 /// armed for.
120 ///
121 /// # Errors
122 ///
123 /// The provided body returns a [`Violation`] of SY-30, naming the two ways
124 /// to reach it: a fixture that declares
125 /// [`MID_GROUP_FAULT`](Self::MID_GROUP_FAULT) supported and does not
126 /// override this, or a rule that did not check the capability first. An
127 /// override returns one when its environment cannot arm the fault.
128 fn arm_mid_group_fault(&self, after: usize) -> impl Future<Output = Result<(), Violation>> {
129 core::future::ready(Err(Violation::new(
130 "SY-30",
131 format!(
132 "`IngestFixture::arm_mid_group_fault({after})` was called and not overridden: \
133 either this fixture declares MID_GROUP_FAULT supported and does not arm the \
134 fault, or a rule armed it without checking the capability"
135 ),
136 )))
137 }
138}
139
140/// What [`IngestFixture::MID_GROUP_FAULT`] says when a fixture says nothing.
141///
142/// `pub` so an adapter author can read what their silence says. A fixture
143/// cannot agree with it by naming it: [`ingest_declensions_are_stated`]
144/// compares the text, so the constant named is the constant inherited.
145pub const UNSTATED_MID_GROUP_FAULT: &str = "this fixture cannot make its store fail between two rows of one ingest \
146 group; nothing in the port reaches inside an `ingest`, so the injection has \
147 to come from the adapter and this one has none to offer";
148
149/// CF-18's machine-checked half for the ingest family: no capability `F`
150/// declines carries the reason it would inherit by saying nothing.
151///
152/// A declined capability's reason is printed on every run as the adapter's
153/// account of its own store, and a default written by this crate says the same
154/// thing about every store. `happenstance_testkit::assert_declensions_are_stated`
155/// is the event-store family's copy. Emitted once per mounted suite by
156/// [`ingest_store_conformance!`](crate::ingest_store_conformance), not by the
157/// emitter, so a third-party emitter cannot drop it. It cannot see a reason
158/// that is merely bad.
159///
160/// The opener is taken, and never called, so `F` is inferred from the
161/// macro's hoisted fixture function.
162///
163/// # Errors
164///
165/// A [`Violation`] of CF-18 naming each capability `F` declines with the
166/// inherited reason.
167pub fn ingest_declensions_are_stated<F: IngestFixture>(
168 _opener: impl AsyncFn() -> F,
169) -> Result<(), Violation> {
170 let declared = [(
171 "MID_GROUP_FAULT",
172 F::MID_GROUP_FAULT,
173 UNSTATED_MID_GROUP_FAULT,
174 )];
175 let unstated: Vec<&str> = declared
176 .iter()
177 .filter(|(_, capability, default)| capability.reason() == Some(*default))
178 .map(|(name, _, _)| *name)
179 .collect();
180 ensure(unstated.is_empty(), "CF-18", || {
181 format!(
182 "this fixture declines {} without saying why: the reason printed on every run is \
183 this crate's words, not the adapter's account of its store. Write the constant on \
184 the `impl`, with the reason this store cannot co-operate, in your own words",
185 unstated.join(", ")
186 )
187 })
188}
189
190/// The reference [`IngestFixture`], over [`MemoryIngestStore`].
191///
192/// Every ingest rule is proven against this before it is allowed to fail an
193/// adapter: a rule red here is a wrong rule, not a wrong store. Each instance
194/// owns one fresh store, with an incarnation of its own, and each
195/// [`connect`](IngestFixture::connect) is a new handle onto it.
196#[derive(Debug, Clone, Default)]
197pub struct MemoryIngestFixture {
198 /// Shared by every handle, so two handles see one log.
199 store: Arc<MemoryIngestStore>,
200}
201
202impl MemoryIngestFixture {
203 /// A fixture over a fresh in-memory store.
204 #[must_use]
205 pub fn new() -> Self {
206 Self::default()
207 }
208}
209
210impl IngestFixture for MemoryIngestFixture {
211 type Store = MemoryIngestHandle;
212
213 /// Declined, by incapacity. The oracle's store error is uninhabited and
214 /// its ingest stages every row before one `extend`, so there is no write
215 /// between two rows for a fault to land in, and adding one would put a
216 /// mistake switch in the reference (TST-09).
217 const MID_GROUP_FAULT: Capability = Capability::declined(
218 "the in-memory oracle stages every row of a call and then extends its log once, and its \
219 store error cannot be constructed, so no fault can land between two rows of a group; \
220 SY-30's rule is proven against the faithful wrong store and the SQLite spike instead",
221 );
222
223 fn connect(&self) -> impl Future<Output = Self::Store> {
224 // Ready rather than `async`: a handle is a refcount bump, and this
225 // says so where a real fixture's `connect` does I/O.
226 core::future::ready(MemoryIngestHandle {
227 store: Arc::clone(&self.store),
228 })
229 }
230}
231
232/// One handle onto a [`MemoryIngestFixture`]'s store.
233///
234/// A type of its own because the orphan rule refuses `impl EventStore for
235/// Arc<MemoryIngestStore>` in this crate: both the trait and `Arc` are
236/// foreign, and `Arc` is not `#[fundamental]`. `Arc` because the store is
237/// `Send + Sync` and the handle keeps it so, which is what lets it run under
238/// the tokio emitter.
239#[derive(Debug, Clone)]
240pub struct MemoryIngestHandle {
241 store: Arc<MemoryIngestStore>,
242}
243
244impl SendEventStore for MemoryIngestHandle {
245 type Error = MemoryStoreError;
246
247 fn read(
248 &self,
249 query: &Query,
250 options: ReadOptions,
251 ) -> impl Stream<Item = Result<SequencedEvent, Self::Error>> + Send {
252 SendEventStore::read(&*self.store, query, options)
253 }
254
255 async fn append(
256 &self,
257 events: &[Event],
258 condition: Option<&AppendCondition>,
259 ) -> Result<SequencePosition, AppendError<Self::Error>> {
260 SendEventStore::append(&*self.store, events, condition).await
261 }
262
263 async fn head(&self) -> Result<Option<SequencePosition>, Self::Error> {
264 SendEventStore::head(&*self.store).await
265 }
266
267 async fn contains_event_id(&self, id: EventId) -> Result<bool, Self::Error> {
268 SendEventStore::contains_event_id(&*self.store, id).await
269 }
270}
271
272impl SendIngestStore for MemoryIngestHandle {
273 type Error = MemoryStoreError;
274
275 async fn store_id(&self) -> Result<StoreId, Self::Error> {
276 SendIngestStore::store_id(&*self.store).await
277 }
278
279 async fn ingest(
280 &self,
281 groups: &[IngestGroup<'_>],
282 ) -> Result<Ingested, IngestError<Self::Error>> {
283 SendIngestStore::ingest(&*self.store, groups).await
284 }
285
286 async fn watermark(&self) -> Result<Watermark, Self::Error> {
287 SendIngestStore::watermark(&*self.store).await
288 }
289}
290
291impl SendWriteGroupStore for MemoryIngestHandle {
292 type Error = happenstance_sync::write_group::GroupOrderError;
293
294 async fn read_groups(
295 &self,
296 after: Option<SequencePosition>,
297 max_events: NonZeroUsize,
298 ) -> Result<GroupPage, Self::Error> {
299 SendWriteGroupStore::read_groups(&*self.store, after, max_events).await
300 }
301}
302
303// Declared below the impls so their lines do not move.
304impl MemoryIngestHandle {
305 /// A handle onto `store`, for a fixture that swaps the store its handles
306 /// reach: [`MemoryRestoreFixture`](crate::MemoryRestoreFixture)'s restore.
307 pub(crate) const fn over(store: Arc<MemoryIngestStore>) -> Self {
308 Self { store }
309 }
310}
311
312#[cfg(test)]
313mod tests {
314 use core::future::Future;
315
316 use happenstance_testkit::Capability;
317
318 use super::{IngestFixture, MemoryIngestHandle, ingest_declensions_are_stated};
319 use crate::MemoryIngestFixture;
320
321 /// A fixture that declares nothing, so every item is the trait's default.
322 struct Silent(MemoryIngestFixture);
323
324 impl IngestFixture for Silent {
325 type Store = MemoryIngestHandle;
326
327 fn connect(&self) -> impl Future<Output = Self::Store> {
328 self.0.connect()
329 }
330 }
331
332 #[test]
333 fn the_default_arm_reports_a_violation_of_sy_30() {
334 let armed = happenstance_testkit::block_on(
335 Silent(MemoryIngestFixture::new()).arm_mid_group_fault(2),
336 );
337
338 assert_eq!(armed.map_err(|violation| violation.clause()), Err("SY-30"));
339 }
340
341 #[test]
342 fn a_fixture_that_inherits_the_default_declension_is_rejected() {
343 let checked = ingest_declensions_are_stated(async || Silent(MemoryIngestFixture::new()));
344
345 assert_eq!(
346 checked.map_err(|violation| violation.clause()),
347 Err("CF-18")
348 );
349 }
350
351 /// One that supports the fault, and one that declines it in its own words.
352 struct Supports(MemoryIngestFixture);
353 struct States(MemoryIngestFixture);
354
355 impl IngestFixture for Supports {
356 type Store = MemoryIngestHandle;
357 const MID_GROUP_FAULT: Capability = Capability::SUPPORTED;
358
359 fn connect(&self) -> impl Future<Output = Self::Store> {
360 self.0.connect()
361 }
362 }
363
364 impl IngestFixture for States {
365 type Store = MemoryIngestHandle;
366 const MID_GROUP_FAULT: Capability =
367 Capability::declined("a test fixture over the oracle, which has no fault seam");
368
369 fn connect(&self) -> impl Future<Output = Self::Store> {
370 self.0.connect()
371 }
372 }
373
374 #[test]
375 fn a_supported_or_stated_capability_passes() {
376 assert_eq!(
377 ingest_declensions_are_stated(async || Supports(MemoryIngestFixture::new())),
378 Ok(())
379 );
380 assert_eq!(
381 ingest_declensions_are_stated(async || States(MemoryIngestFixture::new())),
382 Ok(())
383 );
384 }
385}