happenstance_core/projection.rs
1//! The projection store port.
2//!
3//! # Status: frozen, and how that was earned
4//!
5//! Like [`EventStore`](crate::EventStore), this port is **frozen** and inside
6//! the crate's semver promise, since ADR-0063. It was not, from `0.2.0` until
7//! that decision: it shipped behind an off-by-default `unstable-projection`
8//! feature with a written exemption, and the reason it did is worth keeping
9//! here because it is the reason the freeze means something now.
10//!
11//! The bar the specification set (PS-2) was not a count of adapters but a
12//! **spread**: the suite green against two adapters at opposite ends of the
13//! batch-shape axis — one whose batch is an owned write set replayed at commit,
14//! and one whose batch *is* a live transaction. Every implementation there had
15//! ever been sat at the first end, and ADR-0060 found the second was not merely
16//! unbuilt but unreachable through this port's own signatures: `begin` was
17//! total, synchronous and infallible while every route to a real driver's
18//! transaction is `async` and fallible; and the probe seam the suite drives a
19//! read model through was synchronous, infallible and took `&Self::Batch`,
20//! while a driver borrows its connection mutably to issue a statement. A
21//! live-transaction store could implement the port only by declaring
22//! `READS_THROUGH_BATCH = false` — a false statement about itself — so the
23//! suite could not tell the two ends apart. A skeleton did not report any of
24//! this because `todo!()` has type `!` and coerces to anything.
25//!
26//! ADR-0062 moved those signatures: `begin` is `async` and fallible, and the
27//! three batch-touching probe members take `&mut Self::Batch` and return a
28//! future of a `Result`. `happenstance-postgres` then built the far end — a
29//! store whose batch is a `sqlx::Transaction`, declaring `READS_THROUGH_BATCH =
30//! true` truthfully — and it passed all seventeen rules against a live server,
31//! with PS-12's read-through rule reported as a run rather than a skip for the
32//! first time on any adapter over a real database. The two ends disagreed about
33//! nothing the port had to move for. That is the measurement PS-2 asked for,
34//! and ADR-0063 is the freeze taken on it.
35//!
36//! **What is frozen is this port.** The runner over it has its own axis: the
37//! typed layer's `Projection::apply` is `async` since ADR-0074 was built, so it
38//! can issue a statement into a live batch, and the runner sat behind
39//! `happenstance`'s own `unstable-projection` until `0.5.0` removed it. Neither
40//! fact moved this port.
41//!
42//! Changing a signature here is now a breaking change with a decision record
43//! behind it, which is what *frozen* means in this workspace.
44//!
45//! # The invariant that drives the design
46//!
47//! A read model and its checkpoint must move together. If the read-model write
48//! commits and the checkpoint write does not, a restart replays events that
49//! were already applied; if the checkpoint commits first, a crash silently
50//! skips events. Neither is acceptable, and no amount of ordering or retrying
51//! fixes it — the two writes must be **one** transaction.
52//!
53//! So the port cannot offer `apply()` and `set_checkpoint()` as independent
54//! calls. It hands out an adapter-owned batch and takes it back at commit time
55//! together with the position.
56//!
57//! # What is out of scope at 0.1: a projection that writes back into the log
58//!
59//! A projection that emits events into the event store as a side effect of
60//! applying one is **out of scope for this port at 0.1**, and this paragraph is
61//! the port saying so rather than leaving it to be discovered
62//! (`spec/SPECIFICATION.md` §4's PS-31).
63//!
64//! It is a consequence of a decision already taken, not a question still open.
65//! An `EventId` is a store-assigned `(StoreId, SequencePosition)` pair minted at
66//! append (VT-5), and [`EventStore::append`](crate::EventStore::append) refuses a
67//! caller-supplied one (VT-10). An outward-writing projection needs exactly what
68//! VT-10 refuses: a write whose identity the *caller* chooses, so that a rebuild
69//! re-emitting the same event is a no-op rather than a second fact. Without that,
70//! every rebuild duplicates every emitted event, which is the wrong
71//! implementation silence here produces. Revisiting it means a deliberate
72//! idempotent-emission seam, and VT-5 is what would make one expressible.
73//!
74//! # The batch is owned, and is not required to be a live transaction
75//!
76//! [`ProjectionStore::Batch`] is a plain associated type with **no lifetime
77//! parameter**. It used to be a generic associated type borrowing from the
78//! store, on the reasoning that a transaction cannot outlive its connection.
79//! Two compiled results retired that shape and neither is about `Send`: the
80//! `error[E0195]` every impl hit, written out once beside the doctest that
81//! disposes of it in [`# Implementing it`](ProjectionStore#implementing-it),
82//! and a store carrying a lifetime of its own, which made rustc 1.97.1 *ICE*
83//! while reporting the region error the GAT's `where Self: 'a` produced. A
84//! batch may still *be* a live transaction — the port stops requiring one,
85//! which is what lets an adapter with no connection at all implement it.
86//!
87//! # The `Send` flavour's extra requirement is documented, not declared
88//!
89//! [`SendProjectionStore`] transitively requires `Batch: Send`, because the
90//! batch crosses an await between [`begin`](ProjectionStore::begin) and
91//! [`commit`](ProjectionStore::commit). That bound cannot be written on the
92//! associated type: `trait_variant` copies associated-type bounds **verbatim**
93//! into the bare flavour, so `type Batch: Send;` would impose `Send` on the
94//! flavour that exists precisely for `wasm32`, where nothing is. A caller who
95//! needs a spawnable runner writes `S::Batch: Send` in their own `where`
96//! clause.
97//!
98//! Projections that cannot be made transactional with their checkpoint must
99//! instead be made **idempotent**, so that replaying an event is harmless. That
100//! is a property of the projection, not of this port.
101//!
102//! # Naming what the port hands back
103//!
104//! ```
105//! use happenstance_core::{
106//! Authority, Checkpoint, CommitError, ProjectionId, ResetError, SequencePosition,
107//! };
108//!
109//! // Every state the port can report is one a caller can name.
110//! let checkpoint = Checkpoint::Live {
111//! through: SequencePosition::FIRST,
112//! };
113//! assert!(matches!(checkpoint, Checkpoint::Live { .. }));
114//!
115//! // `commit` and `reset` fail differently, so a caller matching one is never
116//! // offered the other's arms.
117//! let refused: ResetError<core::convert::Infallible> = ResetError::Refused;
118//! let foreign: CommitError<core::convert::Infallible> = CommitError::ForeignBatch;
119//! assert!(matches!(refused, ResetError::Refused));
120//! assert!(matches!(foreign, CommitError::ForeignBatch));
121//!
122//! let _rebuild = (ProjectionId::from_static("van_stock"), Authority::Rebuilding);
123//! ```
124
125use alloc::borrow::Cow;
126use alloc::string::String;
127#[cfg(feature = "conformance")]
128use core::future::Future;
129
130use crate::event::SequencePosition;
131use crate::identity::StoreId;
132use crate::validate;
133
134/// Longest permitted projection identifier, in bytes.
135///
136/// The same bound as [`MAX_EVENT_TYPE_LEN`](crate::MAX_EVENT_TYPE_LEN) and
137/// [`MAX_TAG_LEN`](crate::MAX_TAG_LEN), and it applies to every
138/// [`ProjectionId`], including one a runner derives from a projection's name
139/// (ADR-0082 §D5).
140pub const MAX_PROJECTION_ID_LEN: usize = 255;
141
142/// The prefix [`ProjectionId::sync_watermark`] renders, and one of the two
143/// [`RESERVED`] entries.
144const SYNC_PREFIX: &str = "sync/";
145
146/// Prefixes no caller-supplied id may begin with, matched as exact bytes.
147///
148/// Private: the list is documented on [`ProjectionId::new`] and in VT-35, and
149/// widening it later refuses ids that are valid today, which is a behaviour
150/// break whatever this constant's visibility.
151const RESERVED: [&str; 2] = ["happenstance/", SYNC_PREFIX];
152
153/// Names a read model within a projection store.
154///
155/// Distinct projections advance independently, so each needs its own
156/// checkpoint, and the id is that checkpoint's key: a store keeps it byte for
157/// byte (PS-39).
158///
159/// Validated, like its siblings [`EventType`](crate::EventType) and
160/// [`Tag`](crate::Tag), by the same rules plus one (VT-35, ADR-0082). There
161/// is no infallible way in, because two constructors enforcing different rules
162/// is the defect that makes an invalid value reachable through the weaker one.
163///
164/// # Examples
165///
166/// ```
167/// use happenstance_core::ProjectionId;
168///
169/// let id = ProjectionId::new("van_stock")?;
170/// assert_eq!(id.as_str(), "van_stock");
171/// # Ok::<(), happenstance_core::InvalidProjectionId>(())
172/// ```
173///
174/// A string does not become an id by conversion alone. There is no
175/// `From<&str>`, because an infallible door would bypass the rules:
176///
177/// ```compile_fail
178/// use happenstance_core::ProjectionId;
179///
180/// let id: ProjectionId = "van_stock".into();
181/// # let _ = id;
182/// ```
183///
184/// Backed by `Cow<'static, str>` rather than `Box<str>` so that
185/// [`from_static`](Self::from_static) can build one in a `const` without
186/// allocating, the trade VT-32 records for [`EventType`](crate::EventType).
187#[derive(Debug, Clone)]
188pub struct ProjectionId(Cow<'static, str>);
189
190impl ProjectionId {
191 /// Creates a projection identifier.
192 ///
193 /// The value is kept exactly as given: nothing is trimmed, folded or
194 /// normalised, so an accepted id's [`as_str`](Self::as_str) is byte for
195 /// byte its input.
196 ///
197 /// # Errors
198 ///
199 /// Returns [`InvalidProjectionId`], checking in this order, if the value is
200 /// empty; longer than [`MAX_PROJECTION_ID_LEN`] bytes; contains a character
201 /// in Unicode general category `Cc` or one of the explicit bidirectional
202 /// formatting controls U+202A–U+202E or U+2066–U+2069, reporting whichever
203 /// comes first; or begins with one of the reserved prefixes `happenstance/`
204 /// and `sync/`, compared as exact bytes. `Cf` in general is accepted, so the
205 /// joiners U+200C and U+200D that Persian, Hindi and emoji sequences need
206 /// are kept.
207 ///
208 /// A `sync/` id is built only by [`sync_watermark`](Self::sync_watermark).
209 pub fn new(value: impl Into<String>) -> Result<Self, InvalidProjectionId> {
210 let value = value.into();
211 match refusal(&value) {
212 None => Ok(Self(Cow::Owned(value))),
213 Some(refused) => Err(refused),
214 }
215 }
216
217 /// Creates a projection identifier from a string literal, validating at
218 /// compile time.
219 ///
220 /// Enforces exactly the rules [`new`](Self::new) enforces — one function
221 /// checks both — so a `ProjectionId` is always a validated value, with some
222 /// of that validation having happened before the program ran.
223 ///
224 /// # Panics
225 ///
226 /// Panics if the value would be rejected by [`new`](Self::new). **Where
227 /// that panic surfaces depends on the call site, and the difference is
228 /// sharp enough to be worth stating:**
229 ///
230 /// | Call site | When the invalid value is caught |
231 /// |---|---|
232 /// | a free `const` | `cargo check`, as `error[E0080]` |
233 /// | an associated `const` that is read somewhere | `cargo build` |
234 /// | an associated `const` that is never read | **never** |
235 /// | a `let` binding | at run time, as a panic |
236 ///
237 /// The third row is the one to design around: an associated const is
238 /// evaluated lazily, so an invalid one that nothing reads survives `check`,
239 /// `clippy`, `build` and `test`. Prefer a free `const` for anything whose
240 /// validity you want the compiler to guarantee:
241 ///
242 /// ```
243 /// use happenstance_core::ProjectionId;
244 ///
245 /// const VAN_STOCK: ProjectionId = ProjectionId::from_static("van_stock");
246 /// # let _ = VAN_STOCK;
247 /// ```
248 ///
249 /// An invalid value at the same free `const` site is a compile error, and
250 /// a reserved prefix is invalid:
251 ///
252 /// ```compile_fail
253 /// use happenstance_core::ProjectionId;
254 ///
255 /// const X: ProjectionId = ProjectionId::from_static("sync/x");
256 /// # let _ = X;
257 /// ```
258 ///
259 /// Spelled bare `compile_fail` rather than `compile_fail,E0080`: rustdoc on
260 /// 1.97.1 silently ignores an error-code annotation it cannot match, so the
261 /// stricter-looking spelling is the weaker check. It is also deliberately
262 /// weaker than a `trybuild` snapshot — it does not pin the diagnostic — and
263 /// ADR-0015 records that phase 6 owns the `trybuild` dependency decision.
264 /// The passing example above it is the control: the two differ only in the
265 /// literal, so the failure is the validator's and nothing else's.
266 #[must_use]
267 pub const fn from_static(value: &'static str) -> Self {
268 match refusal(value) {
269 None => Self(Cow::Borrowed(value)),
270 #[expect(
271 clippy::panic,
272 reason = "the sanctioned const construction path (VT-35, as VT-32's \
273 `EventType::from_static`): at a free `const` this panic is a \
274 compile error, and `new` is the fallible door"
275 )]
276 Some(refused) => panic!("{}", refused.const_message()),
277 }
278 }
279
280 /// The replication watermark for `peer`: `sync/` followed by the peer's
281 /// [`StoreId`] as 32 lowercase hex digits, 37 bytes in all.
282 ///
283 /// The **only** constructor of a `sync/` id (SY-31, VT-35). Every other one
284 /// refuses the prefix, so no application projection can collide with a
285 /// watermark, and the reservation is enforced rather than advised: there is
286 /// no unchecked constructor behind it.
287 ///
288 /// The rendered format is part of VT-35 and frozen, because changing it
289 /// orphans every persisted watermark. A peer restored from a backup
290 /// re-mints its `StoreId` and so gets a new watermark, which is correct: a
291 /// new incarnation is new history.
292 ///
293 /// ```
294 /// use happenstance_core::{ProjectionId, StoreId};
295 ///
296 /// let peer = StoreId::from_bytes([0xab; 16]);
297 /// let watermark = ProjectionId::sync_watermark(peer);
298 /// assert_eq!(watermark.as_str(), "sync/abababababababababababababababab");
299 /// assert!(ProjectionId::new(watermark.as_str()).is_err());
300 /// ```
301 #[must_use]
302 pub fn sync_watermark(peer: StoreId) -> Self {
303 Self(Cow::Owned(alloc::format!("{SYNC_PREFIX}{peer}")))
304 }
305
306 /// The identifier as a string slice.
307 #[must_use]
308 pub fn as_str(&self) -> &str {
309 &self.0
310 }
311}
312
313/// The one validator both of [`ProjectionId`]'s checking doors call (RS-11-1):
314/// VT-14's rules through [`validate::check`], then the reserved prefixes.
315const fn refusal(value: &str) -> Option<InvalidProjectionId> {
316 match validate::check(value, MAX_PROJECTION_ID_LEN) {
317 validate::Refusal::Accepted => match reserved_prefix(value) {
318 Some(prefix) => Some(InvalidProjectionId::Reserved { prefix }),
319 None => None,
320 },
321 validate::Refusal::Empty => Some(InvalidProjectionId::Empty),
322 validate::Refusal::TooLong => Some(InvalidProjectionId::TooLong { len: value.len() }),
323 validate::Refusal::ControlCharacter => Some(InvalidProjectionId::ControlCharacter),
324 validate::Refusal::BidirectionalControl => Some(InvalidProjectionId::BidirectionalControl),
325 }
326}
327
328/// The [`RESERVED`] entry `value` begins with, compared as exact bytes.
329///
330/// `while` loops rather than `starts_with`, which is not `const` (RS-11-3).
331/// Every index is below a length checked first, the shape `validate.rs` uses.
332const fn reserved_prefix(value: &str) -> Option<&'static str> {
333 let bytes = value.as_bytes();
334 let mut k = 0;
335 while k < RESERVED.len() {
336 let prefix = RESERVED[k].as_bytes();
337 if prefix.len() <= bytes.len() {
338 let mut i = 0;
339 let mut matched = true;
340 while i < prefix.len() {
341 if bytes[i] != prefix[i] {
342 matched = false;
343 break;
344 }
345 i += 1;
346 }
347 if matched {
348 return Some(RESERVED[k]);
349 }
350 }
351 k += 1;
352 }
353 None
354}
355
356// `Eq`, `Ord` and `Hash` are written out rather than derived, for the reason
357// `EventType`'s are: `Borrow<str>` promises the borrowed form hashes and
358// compares identically to the owner, and these bodies are where that promise
359// is discharged.
360impl PartialEq for ProjectionId {
361 fn eq(&self, other: &Self) -> bool {
362 self.as_str() == other.as_str()
363 }
364}
365
366impl Eq for ProjectionId {}
367
368impl PartialOrd for ProjectionId {
369 fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
370 Some(self.cmp(other))
371 }
372}
373
374impl Ord for ProjectionId {
375 fn cmp(&self, other: &Self) -> core::cmp::Ordering {
376 self.as_str().cmp(other.as_str())
377 }
378}
379
380impl core::hash::Hash for ProjectionId {
381 fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
382 self.as_str().hash(state);
383 }
384}
385
386impl core::borrow::Borrow<str> for ProjectionId {
387 fn borrow(&self) -> &str {
388 self.as_str()
389 }
390}
391
392impl AsRef<str> for ProjectionId {
393 fn as_ref(&self) -> &str {
394 self.as_str()
395 }
396}
397
398impl core::fmt::Display for ProjectionId {
399 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
400 f.write_str(self.as_str())
401 }
402}
403
404impl TryFrom<&str> for ProjectionId {
405 type Error = InvalidProjectionId;
406
407 fn try_from(value: &str) -> Result<Self, Self::Error> {
408 Self::new(value)
409 }
410}
411
412impl TryFrom<String> for ProjectionId {
413 type Error = InvalidProjectionId;
414
415 fn try_from(value: String) -> Result<Self, Self::Error> {
416 Self::new(value)
417 }
418}
419
420impl core::str::FromStr for ProjectionId {
421 type Err = InvalidProjectionId;
422
423 fn from_str(value: &str) -> Result<Self, Self::Err> {
424 Self::new(value)
425 }
426}
427
428/// A [`ProjectionId`] failed validation (VT-35).
429#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
430#[non_exhaustive]
431pub enum InvalidProjectionId {
432 /// The id was empty. It is the primary key of a checkpoint row, and an
433 /// empty key names nothing.
434 #[error("a projection id must not be empty")]
435 Empty,
436 /// The id exceeded [`MAX_PROJECTION_ID_LEN`] bytes.
437 #[error("a projection id must be at most {max} bytes, got {len}", max = MAX_PROJECTION_ID_LEN)]
438 TooLong {
439 /// The rejected length, in bytes.
440 len: usize,
441 },
442 /// The id contained a control character (Unicode `Cc`), NUL among them,
443 /// which a Postgres `text` column refuses at `commit`.
444 #[error("a projection id must not contain control characters")]
445 ControlCharacter,
446 /// The id contained one of the explicit bidirectional formatting controls:
447 /// U+202A–U+202E or U+2066–U+2069.
448 ///
449 /// Separate from [`ControlCharacter`](Self::ControlCharacter) for the reason
450 /// [`InvalidTag::BidirectionalControl`](crate::InvalidTag::BidirectionalControl)
451 /// gives.
452 #[error("a projection id must not contain bidirectional formatting controls")]
453 BidirectionalControl,
454 /// The id began with a reserved prefix, compared as exact bytes.
455 ///
456 /// `sync/` belongs to SY-31's replication watermark and is minted only by
457 /// [`ProjectionId::sync_watermark`]. `happenstance/` is held for ids this
458 /// library may mint later, so that minting one is not a breaking change.
459 #[error("a projection id must not begin with the reserved prefix `{prefix}`")]
460 Reserved {
461 /// The reserved prefix the value began with, verbatim.
462 prefix: &'static str,
463 },
464}
465
466impl InvalidProjectionId {
467 /// The message [`ProjectionId::from_static`] panics with: a literal per
468 /// variant, because a `const` panic cannot format a field.
469 const fn const_message(&self) -> &'static str {
470 match self {
471 Self::Empty => "a projection id must not be empty",
472 Self::TooLong { .. } => "a projection id must be at most MAX_PROJECTION_ID_LEN bytes",
473 Self::ControlCharacter => "a projection id must not contain control characters",
474 Self::BidirectionalControl => {
475 "a projection id must not contain bidirectional formatting controls"
476 }
477 Self::Reserved { .. } => {
478 "a projection id must not begin with a reserved prefix (`happenstance/` or `sync/`)"
479 }
480 }
481 }
482}
483
484impl From<core::convert::Infallible> for InvalidProjectionId {
485 /// Lets a caller accept `impl TryInto<ProjectionId, Error: Into<InvalidProjectionId>>`
486 /// and so take both a `&str`, which converts fallibly, and an already-built
487 /// [`ProjectionId`], whose conversion cannot fail, with no second error
488 /// type.
489 ///
490 /// The match has no arms because [`Infallible`](core::convert::Infallible)
491 /// has no values, which the compiler accepts as exhaustive.
492 fn from(never: core::convert::Infallible) -> Self {
493 match never {}
494 }
495}
496
497/// Where a projection has been brought to, and whether its rows can be trusted.
498///
499/// An enum rather than `(Option<SequencePosition>, bool)` because the tuple can
500/// spell `(None, true)` — authoritative, never run — which means nothing. That
501/// is this crate's "illegal states are unrepresentable" line, applied where a
502/// reader would otherwise write `if let Some(p) = checkpoint` and get it wrong.
503/// A bare `Option<SequencePosition>`, the weaker alternative, cannot distinguish
504/// a rebuild in flight from an authoritative read model at all.
505#[derive(Debug, Clone, Copy, PartialEq, Eq)]
506#[non_exhaustive]
507pub enum Checkpoint {
508 /// Never run, or reset, or rebuilding with nothing committed yet.
509 ///
510 /// Distinct from a checkpoint at the first position: an operator who
511 /// substitutes `commit(empty_batch, id, FIRST, _)` for "never run" makes a
512 /// runner resume *after* event 1, which is then skipped permanently and
513 /// silently.
514 NeverRun,
515
516 /// Considered through `through`, and the read model is authoritative.
517 Live {
518 /// The position this projection has considered up to. A runner resumes
519 /// strictly after it.
520 through: SequencePosition,
521 },
522
523 /// A rebuild is in flight, considered through `through`. Rows are **not**
524 /// authoritative.
525 Rebuilding {
526 /// The position the rebuild has considered up to.
527 through: SequencePosition,
528 },
529}
530
531/// What a commit claims about the rows it leaves behind.
532///
533/// Taken by value at [`commit`](ProjectionStore::commit) so the claim is made at
534/// write time and [`checkpoint`](ProjectionStore::checkpoint) can report it
535/// without inferring it. A rebuild in place therefore cannot be spelled as an
536/// ordinary commit.
537#[derive(Debug, Clone, Copy, PartialEq, Eq)]
538#[non_exhaustive]
539pub enum Authority {
540 /// The rows this commit leaves behind are authoritative.
541 Live,
542 /// A rebuild is in flight; the rows are not yet authoritative.
543 Rebuilding,
544}
545
546/// Why a [`commit`](ProjectionStore::commit) failed.
547///
548/// Generic over the adapter's own error rather than carrying a `String`, for the
549/// same reason [`AppendError`](crate::AppendError) is: a caller must be able to
550/// tell a port-level outcome from an adapter failure without pattern-matching on
551/// text. `#[non_exhaustive]`, so a match needs a wildcard arm.
552#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
553#[non_exhaustive]
554pub enum CommitError<E> {
555 /// The batch was begun on a different store instance.
556 ///
557 /// Rejected at run time rather than at compile time, and deliberately.
558 /// Tying the batch to the receiver's lifetime was compiled and refuted: a
559 /// lifetime names a *region*, not an *instance*, so two `&Store` references
560 /// unify to a common region and `b.commit(a.begin(), …)` still type-checks.
561 /// The only type-level fix is a generative brand, which forbids the batch
562 /// escaping the closure that begins it — defeating the caller the hazard is
563 /// about. So an adapter stamps an identity minted per store instance at
564 /// [`begin`](ProjectionStore::begin) and compares it here; with an owned
565 /// batch the stamp is a field and the check is an integer comparison.
566 #[error("the batch was begun on a different store instance")]
567 ForeignBatch,
568
569 /// `position` is below the checkpoint already recorded.
570 ///
571 /// Both values are carried so a caller can log the gap rather than re-derive
572 /// it with a second round trip.
573 #[error("checkpoint regression: {current} is recorded, {attempted} was attempted")]
574 CheckpointRegression {
575 /// The checkpoint the store already holds.
576 current: SequencePosition,
577 /// The position the caller tried to move it to.
578 attempted: SequencePosition,
579 },
580
581 /// The adapter failed for its own reasons.
582 #[error(transparent)]
583 Store(E),
584}
585
586/// Why a [`reset`](ProjectionStore::reset) failed.
587///
588/// Separate from [`CommitError`] so a caller matching `commit`'s result never
589/// has to consider [`Refused`](Self::Refused), which `commit` cannot produce.
590/// One merged `ProjectionError<E>` was the alternative and it lost:
591/// `#[non_exhaustive]` already forces a wildcard arm without also forcing dead
592/// ones.
593#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
594#[non_exhaustive]
595pub enum ResetError<E> {
596 /// The batch was begun on a different store instance.
597 ///
598 /// See [`CommitError::ForeignBatch`] for why this is a run-time rejection.
599 #[error("the batch was begun on a different store instance")]
600 ForeignBatch,
601
602 /// This store declines to reset this projection.
603 ///
604 /// The variant is bare on purpose. The port supplies the mechanism and the
605 /// domain decides what to protect, so a `&'static str` here would push a
606 /// domain sentence through a port type that cannot validate it, cannot
607 /// localise it and cannot keep it in step with the policy that produced it.
608 /// An operator learns *that* the reset was declined from this variant, and
609 /// *which policy* declined it from the store that holds the policy. A
610 /// refusal is not success: it leaves the rows and the checkpoint unchanged.
611 #[error("this store declines to reset this projection")]
612 Refused,
613
614 /// The adapter failed for its own reasons.
615 #[error(transparent)]
616 Store(E),
617}
618
619/// A store that holds read models and their replay checkpoints.
620///
621/// See the [module documentation](self) for the transactional invariant this
622/// shape exists to enforce, for why the batch is owned, and for how its freeze
623/// was earned.
624///
625/// Two traits, one set of doc attributes. `trait_variant` derives
626/// [`SendProjectionStore`] from [`ProjectionStore`] and copies this block onto
627/// it, so every sentence here is written to hold on whichever of the two pages
628/// you opened. [`ProjectionStore`] states no `Send` requirement and is what
629/// generic code binds; [`SendProjectionStore`] adds it and hands back
630/// [`ProjectionStore`] free. The same split as
631/// [`EventStore`](crate::EventStore), for the same reason.
632///
633/// # Implementing it
634///
635/// The whole port, on a store small enough to read at a glance. Note what is
636/// *absent*: there is no `Self::Batch<'_>` anywhere, because there is no
637/// lifetime to spell. An implementer writes `type Batch = MyBatch;` and then
638/// `async fn commit(&self, batch: MyBatch, …)`, and it compiles.
639///
640/// That used to be the trap that explained why this port had no adapters. While
641/// `Batch` was a generic associated type, the trait declared
642/// `batch: Self::Batch<'_>`, so naming the concrete type in the impl declared a
643/// different set of lifetime generics and rustc answered
644/// `error[E0195]: lifetime parameters or bounds on method 'commit' do not match
645/// the trait declaration` — with nothing in the workspace saying the literal
646/// `Self::Batch<'_>` was required, and nothing to copy. This example is the
647/// disposition of that trap: it compiles on every CI run, so it cannot rot back.
648///
649/// ```
650/// use happenstance_core::{
651/// Authority, Checkpoint, CommitError, ProjectionId, ProjectionStore, ResetError,
652/// SequencePosition,
653/// };
654///
655/// /// The adapter's own batch. Owned, and not a live transaction.
656/// #[derive(Debug, Default)]
657/// struct ToyBatch {
658/// rows: Vec<(String, u64)>,
659/// }
660///
661/// #[derive(Debug, Default)]
662/// struct ToyStore {
663/// committed: std::cell::RefCell<Vec<(String, u64)>>,
664/// checkpoint: std::cell::Cell<Option<SequencePosition>>,
665/// }
666///
667/// impl ProjectionStore for ToyStore {
668/// type Error = ToyError;
669///
670/// // No lifetime, and no `where Self: 'a`.
671/// type Batch = ToyBatch;
672///
673/// // `async` and fallible on the port because a batch that is a live
674/// // transaction has a round trip and a failure here. A buffer has neither:
675/// // this body never yields and never fails, and costs what it looks like.
676/// async fn begin(&self) -> Result<ToyBatch, ToyError> {
677/// Ok(ToyBatch::default())
678/// }
679///
680/// async fn checkpoint(&self, _id: &ProjectionId) -> Result<Checkpoint, ToyError> {
681/// Ok(match self.checkpoint.get() {
682/// None => Checkpoint::NeverRun,
683/// Some(through) => Checkpoint::Live { through },
684/// })
685/// }
686///
687/// // The concrete type, spelled straight out. This is the line that used
688/// // to be `error[E0195]`.
689/// async fn commit(
690/// &self,
691/// batch: ToyBatch,
692/// _id: &ProjectionId,
693/// position: SequencePosition,
694/// _authority: Authority,
695/// ) -> Result<(), CommitError<ToyError>> {
696/// // The rows and the checkpoint, or neither.
697/// self.committed.borrow_mut().extend(batch.rows);
698/// self.checkpoint.set(Some(position));
699/// Ok(())
700/// }
701///
702/// async fn reset(
703/// &self,
704/// batch: ToyBatch,
705/// _id: &ProjectionId,
706/// ) -> Result<(), ResetError<ToyError>> {
707/// // The caller's batch carries the deletes; this store's whole read
708/// // model is the vector, so clearing it is the same unit of work.
709/// drop(batch);
710/// self.committed.borrow_mut().clear();
711/// self.checkpoint.set(None);
712/// Ok(())
713/// }
714///
715/// async fn rollback(&self, batch: ToyBatch) -> Result<(), ToyError> {
716/// drop(batch);
717/// Ok(())
718/// }
719/// }
720///
721/// #[derive(Debug)]
722/// struct ToyError;
723/// impl core::fmt::Display for ToyError {
724/// fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
725/// f.write_str("the toy store failed")
726/// }
727/// }
728/// impl core::error::Error for ToyError {}
729///
730/// # #[tokio::main(flavor = "current_thread")]
731/// # async fn main() -> Result<(), Box<dyn core::error::Error>> {
732/// let store = ToyStore::default();
733/// let id = ProjectionId::new("toy")?;
734///
735/// let mut batch = store.begin().await?;
736/// batch.rows.push(("depot-7".to_owned(), 12));
737/// store
738/// .commit(batch, &id, SequencePosition::FIRST, Authority::Live)
739/// .await?;
740///
741/// assert_eq!(
742/// store.checkpoint(&id).await?,
743/// Checkpoint::Live { through: SequencePosition::FIRST },
744/// );
745/// # Ok(())
746/// # }
747/// ```
748#[trait_variant::make(SendProjectionStore: Send)]
749pub trait ProjectionStore {
750 /// How this adapter fails.
751 type Error: core::error::Error + 'static;
752
753 /// The adapter's write set.
754 ///
755 /// **Owned, and not required to be a live transaction.** Only the adapter
756 /// knows what it is: a SQL transaction, a buffered statement list, a graph
757 /// write set. Applying an event mutates it; it becomes durable only when
758 /// handed to [`commit`](ProjectionStore::commit) or
759 /// [`reset`](ProjectionStore::reset).
760 ///
761 /// No `Send` bound is written here, and it is not an oversight.
762 /// [`SendProjectionStore`] transitively requires `Batch: Send`, but
763 /// `trait_variant` copies associated-type bounds verbatim into the bare
764 /// flavour — so `type Batch: Send;` would impose `Send` on the flavour that
765 /// exists for `wasm32`, where nothing is. The requirement is documented
766 /// here and written by the caller as `S::Batch: Send` when they need it.
767 type Batch;
768
769 /// Opens a write set.
770 ///
771 /// `async` and fallible, and it was neither until ADR-0062. The old shape
772 /// argued that an `async fn begin() -> Result<…>` *implies a round trip*,
773 /// which an adapter on a one-shot HTTP transport cannot afford. It does
774 /// not imply one: an `async fn` whose body never awaits is a future that
775 /// is ready at its first poll, and `Ok(Vec::new())` is what every buffering
776 /// adapter in this workspace writes here. What the old shape *forbade* was
777 /// a batch that is a live transaction, because every route to a real
778 /// driver's transaction is `async` and fallible — `sqlx`'s
779 /// `Pool::begin().await?` has no synchronous spelling and private fields —
780 /// and PS-6's own falsifier, *an adapter that must reserve something from
781 /// the server before the first write*, is exactly that `BEGIN`.
782 ///
783 /// The discipline the old signature enforced is now the implementer's:
784 /// **an adapter with nothing to reserve MUST NOT spend a round trip here.**
785 /// A transport that can count its requests can assert it, and
786 /// `happenstance-neon` does.
787 ///
788 /// # Errors
789 ///
790 /// Returns the adapter's error if a write set could not be opened — a
791 /// connection that could not be acquired, a `BEGIN` that was refused. A
792 /// buffering adapter has no failing path and returns `Ok` unconditionally.
793 async fn begin(&self) -> Result<Self::Batch, Self::Error>;
794
795 /// How far this projection has been brought, and whether its rows are
796 /// authoritative.
797 ///
798 /// Returns a [`Checkpoint`], never an `Option<SequencePosition>`; the
799 /// reason the tuple form lost is recorded on that type. Resume a replay by
800 /// feeding `through` to [`ReadOptions::from`](crate::ReadOptions::from)
801 /// after advancing past it.
802 ///
803 /// PS-38, frozen: the answer reflects every commit this store has
804 /// acknowledged, through any handle onto it, and an adapter over replicated
805 /// storage answers from the primary, never from a replica that may lag it —
806 /// a runner that resumes from a stale checkpoint applies again what it
807 /// already committed. No conformance rule can observe a lagging replica in
808 /// process, so this is documented rather than checked, and if PS-38's
809 /// falsifier fires the obligation narrows to reads through the same handle.
810 ///
811 /// # Errors
812 ///
813 /// Returns the adapter's error if the checkpoint cannot be read.
814 async fn checkpoint(&self, id: &ProjectionId) -> Result<Checkpoint, Self::Error>;
815
816 /// Applies `batch` and moves `id`'s checkpoint to `position`, as one unit.
817 ///
818 /// `position` is the position *considered*, not the position applied, so a
819 /// batch that wrote nothing still advances the checkpoint. `authority` is
820 /// the claim this commit makes about the rows it leaves behind.
821 ///
822 /// # Errors
823 ///
824 /// Returns [`CommitError::ForeignBatch`] if `batch` was begun on a different
825 /// store instance, [`CommitError::CheckpointRegression`] if `position` is
826 /// below the checkpoint already recorded, and [`CommitError::Store`] if the
827 /// adapter itself failed. The batch is consumed either way, and a failed
828 /// commit leaves both the read model and the checkpoint unchanged.
829 async fn commit(
830 &self,
831 batch: Self::Batch,
832 id: &ProjectionId,
833 position: SequencePosition,
834 authority: Authority,
835 ) -> Result<(), CommitError<Self::Error>>;
836
837 /// Applies `batch` and returns `id` to [`Checkpoint::NeverRun`], as one
838 /// unit.
839 ///
840 /// The dual of [`commit`](ProjectionStore::commit): the caller's own batch
841 /// carries the deletes, because **the port has no idea what the read model
842 /// is**. The alternative — a `reset` that clears the rows itself — would
843 /// oblige the adapter to know which tables belong to a [`ProjectionId`],
844 /// which is exactly the knowledge this port keeps out.
845 ///
846 /// # Errors
847 ///
848 /// Returns [`ResetError::ForeignBatch`] if `batch` was begun on a different
849 /// store instance, [`ResetError::Refused`] if this store declines to reset
850 /// this projection, and [`ResetError::Store`] if the adapter itself failed.
851 /// A refusal, like a failure, leaves both halves unchanged.
852 async fn reset(
853 &self,
854 batch: Self::Batch,
855 id: &ProjectionId,
856 ) -> Result<(), ResetError<Self::Error>>;
857
858 /// Discards the batch without committing.
859 ///
860 /// Exists because `Drop` cannot await: an adapter holding a real resource
861 /// needs somewhere to release it. Dropping a batch bare must also roll back
862 /// and leave the store usable.
863 ///
864 /// # Errors
865 ///
866 /// Returns the adapter's error if the rollback fails.
867 async fn rollback(&self, batch: Self::Batch) -> Result<(), Self::Error>;
868}
869
870/// The write seam the projection conformance suite runs through.
871///
872/// Without it, generic code holding an adapter's batch can do exactly two things
873/// with it — commit it or roll it back. There is no way to put a row *into* the
874/// batch and no way to look at the read model afterwards, so the rule carrying
875/// this port's entire reason for existing — the read-model write and the
876/// checkpoint write become durable together or not at all — cannot be written,
877/// and a suite built on [`ProjectionStore`] alone degenerates into a checkpoint
878/// test that a store writing *only* checkpoints passes.
879///
880/// An adapter that wants to be certified implements this beside its
881/// [`ProjectionStore`] impl. It is not part of the runtime surface: it exists so
882/// a suite that has never heard of the adapter can drive its read model.
883///
884/// # Why this lives in the contract crate rather than the testkit
885///
886/// It looks like a testing utility and belongs beside the port anyway, and the
887/// reason is coherence rather than taste. An adapter crate implementing a
888/// *testkit* trait for its own type is legal — the type is local, so the orphan
889/// rule is satisfied. But the natural place to write such an impl is the
890/// adapter's own `tests/` directory, and **that is a different crate**. There,
891/// neither the trait nor the type is local, `impl ProjectionProbe for MyStore`
892/// is rejected by the orphan rule, and the only way out is a **non-dev**
893/// dependency on the testkit, feature-gated. Putting the trait here keeps the
894/// impl in the adapter's own `src/`, beside the store and behind the adapter's
895/// own feature, and costs one flag on a dependency it already has rather than a
896/// new edge in its graph:
897///
898/// ```toml
899/// [dependencies]
900/// # No feature: the port and every item the `impl ProjectionStore` below
901/// # names are unconditional since ADR-0063. (From `0.2.0` until then this
902/// # line had to carry `unstable-projection`, because the port impl in an
903/// # adapter's `src/` cannot be made optional and the port was gated.)
904/// happenstance-core = "…"
905///
906/// [features]
907/// # Forwards to the contract crate. The `impl ProjectionProbe` lives in `src/`
908/// # under `#[cfg(feature = "conformance")]`, because a crate cannot `cfg` on a
909/// # dependency's feature — which is also why a `[dev-dependencies]` entry
910/// # would not work: it does not exist for the lib build the impl compiles in.
911/// conformance = ["happenstance-core/conformance"]
912///
913/// [dev-dependencies]
914/// happenstance-testkit = "…"
915/// ```
916///
917/// **Nothing inside this workspace can fail the wrong version of that
918/// decision.** Every fixture here already lives in a crate that depends on the
919/// testkit, so the trait would be local, the impls local, the orphan rule
920/// silent, and the whole gate green. The falsifier is
921/// `documented-extension-surface` (HS-S0015), which builds an outside author's
922/// fixture from this documentation alone — named here so the placement is not
923/// "simplified" into the testkit on grounds of diff size before it runs.
924///
925/// # Both flavours, one trait
926///
927/// The bound is bare [`ProjectionStore`], and there is deliberately no
928/// `SendProjectionProbe`. `trait_variant` emits a blanket impl, so
929/// [`SendProjectionStore`] implies [`ProjectionStore`] and a `Send` adapter
930/// already satisfies this supertrait bound. A second trait would collide with
931/// that blanket impl — `error[E0275]` — which is the shape ADR-0008 records.
932#[cfg(feature = "conformance")]
933pub trait ProjectionProbe: ProjectionStore {
934 /// Whether this adapter offers any read path on an open batch.
935 ///
936 /// Declaring `false` is a conformant answer, not a failure: many adapters
937 /// buffer their writes and cannot read them back before commit. A store
938 /// declaring `false` still has the read-through rule **emitted as a
939 /// reported skip carrying its reason** — never omitted — because a rule
940 /// absent from the binary is indistinguishable in CI output from a rule
941 /// that passed.
942 const READS_THROUGH_BATCH: bool;
943
944 /// Writes one probe row into an open batch.
945 ///
946 /// A future of a `Result`, because the batch may be a live transaction and
947 /// then this is a statement: I/O that yields and can fail. A buffering
948 /// adapter pushes onto a vector, never awaits and never fails, and its
949 /// body reads `async move { batch.push(…); Ok(()) }`. Nothing becomes
950 /// durable until the batch reaches [`commit`](ProjectionStore::commit)
951 /// either way.
952 ///
953 /// Spelled `-> impl Future<…>` with **no `+ Send`**, for the reason
954 /// [`probe_read`](Self::probe_read) gives.
955 ///
956 /// # Errors
957 ///
958 /// Returns the adapter's error if the statement was refused. A refused
959 /// statement on a live transaction may poison it; the suite treats any
960 /// error here as the batch being unusable and does not commit it.
961 fn probe_write(
962 &self,
963 batch: &mut Self::Batch,
964 key: &str,
965 value: u64,
966 ) -> impl Future<Output = Result<(), Self::Error>>;
967
968 /// Queues deletion of every probe row into an open batch.
969 ///
970 /// Exists so [`reset`](ProjectionStore::reset) is checkable *without the
971 /// suite knowing what a read model is*. `reset` takes the caller's own
972 /// deletes, so a suite with no way to express "delete everything" cannot
973 /// exercise it at all. Shaped like [`probe_write`](Self::probe_write) for
974 /// the same reason.
975 ///
976 /// # Errors
977 ///
978 /// Returns the adapter's error if the statement was refused.
979 fn probe_delete_all(
980 &self,
981 batch: &mut Self::Batch,
982 ) -> impl Future<Output = Result<(), Self::Error>>;
983
984 /// Reads one probe row from the **committed** read model.
985 ///
986 /// The one asynchronous member, and not arbitrarily so: the other three
987 /// mutate a batch the caller already holds, while this is real I/O against
988 /// the store.
989 ///
990 /// Spelled `-> impl Future<…>` rather than `async fn`, and with **no
991 /// `+ Send`**. This trait is not under `#[trait_variant::make]`, so `async
992 /// fn` here would fire `async_fn_in_trait` under the gate's `-D warnings`;
993 /// writing the desugaring by hand also puts the *absence* of the `Send`
994 /// bound at the declaration, where a reader can see it. A `Send` bound
995 /// would break `wasm32` and could not be relaxed later without a breaking
996 /// change — and it is not needed, because suite code binds the weaker
997 /// flavour and takes its per-test wrapper as a parameter.
998 ///
999 /// # Errors
1000 ///
1001 /// Returns the adapter's error if the read model cannot be read.
1002 fn probe_read(&self, key: &str) -> impl Future<Output = Result<Option<u64>, Self::Error>>;
1003
1004 /// Reads one probe row through an **open** batch, committed state included.
1005 ///
1006 /// Only called when [`READS_THROUGH_BATCH`](Self::READS_THROUGH_BATCH) is
1007 /// `true`; may be `unimplemented!()` otherwise.
1008 ///
1009 /// # This signature is the one a live transaction can meet
1010 ///
1011 /// `&mut Self::Batch` because a driver borrows its connection mutably to
1012 /// issue a statement — `sqlx`'s `Executor for &mut Transaction`,
1013 /// `rusqlite`'s `&mut Transaction`; a future because the statement is I/O
1014 /// and yields; a `Result` because a statement on a live transaction can
1015 /// fail. Until ADR-0062 it was `fn(&self, &Self::Batch, &str) -> Option<u64>`,
1016 /// and `tests/probe_live_transaction_shape.rs` recorded what that cost: a
1017 /// store whose batch *is* a transaction could satisfy it only by declaring
1018 /// `READS_THROUGH_BATCH = false`, a false statement about itself, so the
1019 /// suite could not tell a live-transaction adapter from a buffering one.
1020 /// That file now runs the honest body instead.
1021 ///
1022 /// A buffering adapter that can read its own pending set — a map layered
1023 /// over committed state — answers from the map without awaiting. One that
1024 /// cannot declares `false` and leaves this `unimplemented!()`, which is a
1025 /// conformant answer and the reported-skip path.
1026 ///
1027 /// # Errors
1028 ///
1029 /// Returns the adapter's error if the read could not be issued.
1030 fn probe_read_through(
1031 &self,
1032 batch: &mut Self::Batch,
1033 key: &str,
1034 ) -> impl Future<Output = Result<Option<u64>, Self::Error>>;
1035}
1036
1037#[cfg(test)]
1038mod tests {
1039 // Local override of the workspace `unwrap_used = "deny"`, as the house style
1040 // permits for test modules.
1041 #![allow(clippy::unwrap_used)]
1042
1043 use alloc::rc::Rc;
1044
1045 use alloc::string::{String, ToString};
1046
1047 use super::{Authority, Checkpoint, CommitError, ProjectionId, ProjectionStore, ResetError};
1048 use super::{InvalidProjectionId, MAX_PROJECTION_ID_LEN};
1049 use crate::event::SequencePosition;
1050 use crate::identity::StoreId;
1051
1052 /// The witness store's error. Real, so `Self::Error`'s bound is discharged
1053 /// by something other than `!`.
1054 #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1055 #[error("the witness store failed")]
1056 struct WitnessError;
1057
1058 /// An owned batch that is deliberately **not** `Send`.
1059 ///
1060 /// The `Rc` is the assertion. `trait_variant` copies associated-type bounds
1061 /// verbatim into the bare flavour, so writing `type Batch: Send;` on the
1062 /// trait would make this struct an illegal `Batch` — and would break the
1063 /// `wasm32` target the bare flavour exists for (PS-36).
1064 #[derive(Debug, Default)]
1065 struct WitnessBatch {
1066 writes: usize,
1067 not_send: Rc<()>,
1068 }
1069
1070 /// A zero-sized witness that the port is *implementable*.
1071 ///
1072 /// Not a store worth shipping and not a step towards one:
1073 /// `MemoryProjectionStore` is a separate deliverable, behind the `memory`
1074 /// feature, with a doctest and real state. This is the smallest thing that
1075 /// makes AC-001, AC-004 and AC-005 tests rather than assertions about text.
1076 #[derive(Debug, Default)]
1077 struct Witness;
1078
1079 impl ProjectionStore for Witness {
1080 type Error = WitnessError;
1081
1082 type Batch = WitnessBatch;
1083
1084 async fn begin(&self) -> Result<Self::Batch, Self::Error> {
1085 Ok(WitnessBatch::default())
1086 }
1087
1088 async fn checkpoint(&self, _id: &ProjectionId) -> Result<Checkpoint, Self::Error> {
1089 Ok(Checkpoint::NeverRun)
1090 }
1091
1092 async fn commit(
1093 &self,
1094 batch: Self::Batch,
1095 _id: &ProjectionId,
1096 _position: SequencePosition,
1097 _authority: Authority,
1098 ) -> Result<(), CommitError<Self::Error>> {
1099 drop(batch);
1100 Ok(())
1101 }
1102
1103 async fn reset(
1104 &self,
1105 batch: Self::Batch,
1106 _id: &ProjectionId,
1107 ) -> Result<(), ResetError<Self::Error>> {
1108 drop(batch);
1109 Ok(())
1110 }
1111
1112 async fn rollback(&self, batch: Self::Batch) -> Result<(), Self::Error> {
1113 drop(batch);
1114 Ok(())
1115 }
1116 }
1117
1118 /// AC-001. All six items, implemented and driven.
1119 #[tokio::test]
1120 async fn the_port_is_implementable_with_an_owned_batch() {
1121 let store = Witness;
1122 let id = ProjectionId::from_static("witness");
1123
1124 assert_eq!(store.checkpoint(&id).await.unwrap(), Checkpoint::NeverRun);
1125
1126 let mut batch = store.begin().await.unwrap();
1127 batch.writes += 1;
1128 store
1129 .commit(batch, &id, SequencePosition::FIRST, Authority::Live)
1130 .await
1131 .unwrap();
1132
1133 store
1134 .reset(store.begin().await.unwrap(), &id)
1135 .await
1136 .unwrap();
1137 store.rollback(store.begin().await.unwrap()).await.unwrap();
1138 }
1139
1140 /// AC-002. No `_` arm: a fourth state fails this test rather than widening
1141 /// it silently.
1142 #[test]
1143 fn checkpoint_names_every_state_and_no_others() {
1144 fn considered_through(checkpoint: Checkpoint) -> Option<SequencePosition> {
1145 match checkpoint {
1146 Checkpoint::NeverRun => None,
1147 Checkpoint::Live { through } | Checkpoint::Rebuilding { through } => Some(through),
1148 }
1149 }
1150
1151 fn is_authoritative(checkpoint: Checkpoint) -> bool {
1152 match checkpoint {
1153 Checkpoint::Live { .. } => true,
1154 Checkpoint::NeverRun | Checkpoint::Rebuilding { .. } => false,
1155 }
1156 }
1157
1158 assert_eq!(considered_through(Checkpoint::NeverRun), None);
1159 assert_eq!(
1160 considered_through(Checkpoint::Live {
1161 through: SequencePosition::FIRST
1162 }),
1163 Some(SequencePosition::FIRST)
1164 );
1165 assert_eq!(
1166 considered_through(Checkpoint::Rebuilding {
1167 through: SequencePosition::FIRST
1168 }),
1169 Some(SequencePosition::FIRST)
1170 );
1171
1172 // The pair `(None, true)` the tuple could spell has no counterpart
1173 // here: every variant that is authoritative also carries a position.
1174 assert!(!is_authoritative(Checkpoint::NeverRun));
1175 assert!(is_authoritative(Checkpoint::Live {
1176 through: SequencePosition::FIRST
1177 }));
1178 assert!(!is_authoritative(Checkpoint::Rebuilding {
1179 through: SequencePosition::FIRST
1180 }));
1181 }
1182
1183 /// AC-003. Two enums, each exhaustively matchable inside this crate over
1184 /// exactly the arms its own operation can produce.
1185 #[test]
1186 fn commit_and_reset_errors_stay_separate() {
1187 fn commit_arm(error: &CommitError<WitnessError>) -> &'static str {
1188 match error {
1189 CommitError::ForeignBatch => "foreign",
1190 CommitError::CheckpointRegression { .. } => "regression",
1191 CommitError::Store(_) => "store",
1192 }
1193 }
1194
1195 fn reset_arm(error: &ResetError<WitnessError>) -> &'static str {
1196 match error {
1197 ResetError::ForeignBatch => "foreign",
1198 ResetError::Refused => "refused",
1199 ResetError::Store(_) => "store",
1200 }
1201 }
1202
1203 assert_eq!(commit_arm(&CommitError::ForeignBatch), "foreign");
1204 assert_eq!(
1205 commit_arm(&CommitError::CheckpointRegression {
1206 current: SequencePosition::FIRST,
1207 attempted: SequencePosition::FIRST,
1208 }),
1209 "regression"
1210 );
1211 assert_eq!(reset_arm(&ResetError::ForeignBatch), "foreign");
1212 assert_eq!(reset_arm(&ResetError::Refused), "refused");
1213
1214 // The payload is the adapter's own error, recovered by value — not a
1215 // `String`, and not a `Box<dyn Error>` that has lost its type.
1216 let recovered = match CommitError::Store(WitnessError) {
1217 CommitError::Store(error) => error,
1218 other => panic!("expected Store, got {other:?}"),
1219 };
1220 assert_eq!(recovered, WitnessError);
1221 }
1222
1223 /// ADR-0062 inverted AC-004. `begin` is a future of a `Result`, and a
1224 /// buffering store's future is ready at its first poll: no executor is
1225 /// needed to drive it, which is the compiled form of "costs no round trip".
1226 #[test]
1227 fn begin_is_async_and_fallible_and_a_buffer_resolves_at_first_poll() {
1228 use core::task::{Context, Poll, Waker};
1229
1230 let store = Witness;
1231 let mut pending = core::pin::pin!(store.begin());
1232 let batch = match pending
1233 .as_mut()
1234 .poll(&mut Context::from_waker(Waker::noop()))
1235 {
1236 Poll::Ready(Ok(batch)) => batch,
1237 Poll::Ready(Err(error)) => panic!("a buffer cannot fail to open: {error}"),
1238 Poll::Pending => panic!("a buffer's `begin` yielded, which is a round trip"),
1239 };
1240 assert_eq!(batch.writes, 0);
1241 assert_eq!(Rc::strong_count(&batch.not_send), 1);
1242 }
1243
1244 /// AC-005. The bare flavour accepts a `!Send` batch, which is what
1245 /// `type Batch: Send;` would forbid.
1246 #[test]
1247 fn a_non_send_batch_still_implements_the_bare_flavour() {
1248 fn accepts_the_bare_flavour<P: ProjectionStore>() {}
1249 accepts_the_bare_flavour::<Witness>();
1250 }
1251
1252 /// VT-35. Every refusal VT-14 makes for the sibling identifiers, made here
1253 /// too, each with its own variant.
1254 ///
1255 /// Rejects a `new` that checks only ASCII C0 (`char::is_ascii_control`) and
1256 /// so misses U+0085; one that skips the bidirectional arm; one that
1257 /// truncates to the bound instead of refusing; and one whose `TooLong`
1258 /// reports the bound rather than the length. The NUL case is the one
1259 /// Postgres and Neon used to report at `commit`, far from the constructor
1260 /// that accepted it.
1261 #[test]
1262 fn projection_id_refuses_what_vt_14_refuses() {
1263 assert_eq!(ProjectionId::new(""), Err(InvalidProjectionId::Empty));
1264 assert_eq!(
1265 ProjectionId::new("a\nb"),
1266 Err(InvalidProjectionId::ControlCharacter)
1267 );
1268 assert_eq!(
1269 ProjectionId::new("a\0b"),
1270 Err(InvalidProjectionId::ControlCharacter)
1271 );
1272 assert_eq!(
1273 ProjectionId::new("a\u{85}b"),
1274 Err(InvalidProjectionId::ControlCharacter)
1275 );
1276 assert_eq!(
1277 ProjectionId::new("a\u{202E}b"),
1278 Err(InvalidProjectionId::BidirectionalControl)
1279 );
1280 assert_eq!(
1281 ProjectionId::new("x".repeat(MAX_PROJECTION_ID_LEN + 1)),
1282 Err(InvalidProjectionId::TooLong {
1283 len: MAX_PROJECTION_ID_LEN + 1
1284 })
1285 );
1286
1287 let longest = ProjectionId::new("x".repeat(MAX_PROJECTION_ID_LEN)).unwrap();
1288 assert_eq!(longest.as_str().len(), MAX_PROJECTION_ID_LEN);
1289 }
1290
1291 /// VT-35 keeps VT-14's refusal of a blanket `Cf` ban: the joiners scripts
1292 /// need are accepted, and so are the four neighbours of the two closed
1293 /// bidirectional runs.
1294 ///
1295 /// Rejects a blanket `Cf` ban, and a bidirectional range one codepoint too
1296 /// wide either way.
1297 #[test]
1298 fn projection_id_accepts_the_format_characters_scripts_need() {
1299 for value in [
1300 "a\u{200C}b",
1301 "a\u{200D}b",
1302 "a\u{200B}b",
1303 "a\u{2029}b",
1304 "a\u{202F}b",
1305 "a\u{2065}b",
1306 "a\u{206A}b",
1307 ] {
1308 assert_eq!(ProjectionId::new(value).unwrap().as_str(), value);
1309 }
1310 }
1311
1312 /// The two reserved prefixes are refused, bare and followed by more.
1313 ///
1314 /// Rejects a `contains` test, and a test that refuses only the bare prefix
1315 /// or only a longer value.
1316 #[test]
1317 fn projection_id_refuses_the_reserved_prefixes_by_exact_bytes() {
1318 for value in ["sync/", "sync/peer"] {
1319 assert_eq!(
1320 ProjectionId::new(value),
1321 Err(InvalidProjectionId::Reserved { prefix: "sync/" })
1322 );
1323 }
1324 for value in ["happenstance/", "happenstance/x"] {
1325 assert_eq!(
1326 ProjectionId::new(value),
1327 Err(InvalidProjectionId::Reserved {
1328 prefix: "happenstance/"
1329 })
1330 );
1331 }
1332 }
1333
1334 /// The reservation is an exact byte prefix: nothing near it is refused,
1335 /// and nothing accepted is altered.
1336 ///
1337 /// Rejects `starts_with("sync")` without the slash; case folding before the
1338 /// compare; a trim before the check; and a `contains`.
1339 #[test]
1340 fn projection_id_accepts_the_neighbours_of_the_reserved_prefixes() {
1341 for value in [
1342 "sync",
1343 "syncope",
1344 "sync_jobs",
1345 "sync-x",
1346 "Sync/x",
1347 "SYNC/x",
1348 " sync/x",
1349 "x/sync/y",
1350 "happenstance",
1351 "happenstance-x",
1352 "Happenstance/x",
1353 ] {
1354 assert_eq!(ProjectionId::new(value).unwrap().as_str(), value);
1355 }
1356 }
1357
1358 /// VT-35's MUST that the `const` door is exactly as strong as the runtime
1359 /// one, asserted on the accepting side. The refusing side is the
1360 /// `should_panic` tests below.
1361 ///
1362 /// Rejects a `const` path with a second, simplified copy of the rules
1363 /// (RS-11-1).
1364 #[test]
1365 fn projection_id_from_static_and_new_agree() {
1366 const LONGEST: &str = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\
1367 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\
1368 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\
1369 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
1370 assert_eq!(LONGEST.len(), MAX_PROJECTION_ID_LEN);
1371
1372 for value in [
1373 "van_stock",
1374 LONGEST,
1375 "a\u{200C}b",
1376 "a\u{200D}b",
1377 "a\u{200B}b",
1378 "a\u{2029}b",
1379 "a\u{202F}b",
1380 "a\u{2065}b",
1381 "a\u{206A}b",
1382 "sync",
1383 "syncope",
1384 "sync_jobs",
1385 "sync-x",
1386 "Sync/x",
1387 "SYNC/x",
1388 " sync/x",
1389 "x/sync/y",
1390 "happenstance",
1391 "happenstance-x",
1392 "Happenstance/x",
1393 ] {
1394 let runtime = ProjectionId::new(value).unwrap();
1395 assert_eq!(ProjectionId::from_static(value).as_str(), runtime.as_str());
1396 }
1397 }
1398
1399 /// `from_static` refuses a reserved prefix, which is the refusal VT-35 adds
1400 /// on top of VT-14 and so the one a copied `const` path would lack.
1401 #[test]
1402 #[should_panic(expected = "reserved prefix")]
1403 fn projection_id_from_static_rejects_a_reserved_prefix() {
1404 let _ = ProjectionId::from_static("sync/x");
1405 }
1406
1407 #[test]
1408 #[should_panic(expected = "bidirectional formatting controls")]
1409 fn projection_id_from_static_rejects_a_bidirectional_control() {
1410 let _ = ProjectionId::from_static("a\u{202E}b");
1411 }
1412
1413 #[test]
1414 #[should_panic(expected = "control characters")]
1415 fn projection_id_from_static_rejects_a_c1_control() {
1416 let _ = ProjectionId::from_static("a\u{85}b");
1417 }
1418
1419 /// `from_static` is a `const fn`, which is what makes a free `const` the
1420 /// compile-time-validated spelling the examples teach.
1421 ///
1422 /// Rejects dropping `const` from `from_static`: nothing else notices
1423 /// (RS-11-3).
1424 #[test]
1425 fn projection_id_is_const_constructible() {
1426 const VAN_STOCK: ProjectionId = ProjectionId::from_static("van_stock");
1427
1428 assert_eq!(VAN_STOCK.as_str(), "van_stock");
1429 assert_eq!(VAN_STOCK, ProjectionId::new("van_stock").unwrap());
1430 }
1431
1432 /// The watermark is `sync/` and the peer's 32 lowercase hex digits, and it
1433 /// passes every VT-14 rule: `new` refuses it **only** for its prefix, and
1434 /// the reservation is checked last.
1435 ///
1436 /// Rejects a watermark rendered with `Debug` (`StoreId([..])`), with UUID
1437 /// dashes, or in uppercase hex (a second spelling of one peer); and one
1438 /// built by a path that `new` would also accept, which would make the
1439 /// reservation advisory.
1440 #[test]
1441 fn sync_watermark_is_reserved_and_otherwise_valid() {
1442 let zero = ProjectionId::sync_watermark(StoreId::from_bytes([0x00; 16]));
1443 let ones = ProjectionId::sync_watermark(StoreId::from_bytes([0xff; 16]));
1444 let mixed = ProjectionId::sync_watermark(StoreId::from_bytes([
1445 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab,
1446 0xcd, 0xef,
1447 ]));
1448
1449 assert_eq!(zero.as_str(), "sync/00000000000000000000000000000000");
1450 assert_eq!(ones.as_str(), "sync/ffffffffffffffffffffffffffffffff");
1451 assert_eq!(mixed.as_str(), "sync/0123456789abcdef0123456789abcdef");
1452
1453 for watermark in [&zero, &ones, &mixed] {
1454 assert_eq!(watermark.as_str().len(), 37);
1455 assert_eq!(
1456 ProjectionId::new(watermark.as_str()),
1457 Err(InvalidProjectionId::Reserved { prefix: "sync/" })
1458 );
1459 }
1460 }
1461
1462 /// Two peers never share a watermark.
1463 ///
1464 /// Rejects a rendering of a truncated `StoreId`, such as its first eight
1465 /// bytes.
1466 #[test]
1467 fn sync_watermarks_of_distinct_peers_are_distinct() {
1468 let ids = [
1469 ProjectionId::sync_watermark(StoreId::from_bytes([0x00; 16])),
1470 ProjectionId::sync_watermark(StoreId::from_bytes([0xff; 16])),
1471 ProjectionId::sync_watermark(StoreId::from_bytes([
1472 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67, 0x89, 0xab,
1473 0xcd, 0xef,
1474 ])),
1475 ];
1476 for (i, left) in ids.iter().enumerate() {
1477 for right in ids.iter().skip(i + 1) {
1478 assert_ne!(left, right);
1479 }
1480 }
1481
1482 let mut last = [0x5a; 16];
1483 let before = ProjectionId::sync_watermark(StoreId::from_bytes(last));
1484 last[15] = 0x5b;
1485 let after = ProjectionId::sync_watermark(StoreId::from_bytes(last));
1486 assert_ne!(before, after);
1487 }
1488
1489 /// `Borrow<str>` hashes, compares and orders as the owner does, so both map
1490 /// kinds can be probed by `&str`.
1491 ///
1492 /// Rejects a `Borrow<str>` whose `Hash`, `Eq` or `Ord` disagrees with
1493 /// `str`'s (RS-12-1). Gated on `std` because `HashMap` is `std`'s.
1494 #[cfg(feature = "std")]
1495 #[test]
1496 fn a_map_keyed_by_projection_id_is_probed_by_str() {
1497 let mut hashed = std::collections::HashMap::new();
1498 hashed.insert(ProjectionId::from_static("van_stock"), 1);
1499 assert_eq!(hashed.get("van_stock"), Some(&1));
1500 assert!(hashed.contains_key(&ProjectionId::new("van_stock").unwrap()));
1501
1502 let mut ordered = alloc::collections::BTreeMap::new();
1503 ordered.insert(ProjectionId::from_static("van_stock"), 2);
1504 ordered.insert(ProjectionId::from_static("order_status"), 3);
1505 assert_eq!(ordered.get("van_stock"), Some(&2));
1506 assert_eq!(ordered.get("order_status"), Some(&3));
1507 assert!(ordered.contains_key(&ProjectionId::new("van_stock").unwrap()));
1508 }
1509
1510 /// Every conversion from a string validates, with the verdict `new` gives.
1511 ///
1512 /// Rejects a conversion that forwards to an unchecked path.
1513 #[test]
1514 fn projection_id_conversions_all_validate() {
1515 for (value, refusal) in [
1516 ("", InvalidProjectionId::Empty),
1517 ("sync/x", InvalidProjectionId::Reserved { prefix: "sync/" }),
1518 ] {
1519 assert_eq!(ProjectionId::try_from(value), Err(refusal.clone()));
1520 assert_eq!(
1521 ProjectionId::try_from(String::from(value)),
1522 Err(refusal.clone())
1523 );
1524 assert_eq!(value.parse::<ProjectionId>(), Err(refusal));
1525 }
1526
1527 let expected = ProjectionId::from_static("van_stock");
1528 assert_eq!(ProjectionId::try_from("van_stock"), Ok(expected.clone()));
1529 assert_eq!(
1530 ProjectionId::try_from(String::from("van_stock")),
1531 Ok(expected.clone())
1532 );
1533 assert_eq!("van_stock".parse::<ProjectionId>(), Ok(expected));
1534 }
1535
1536 /// The messages carry the bound, the length and the prefix.
1537 ///
1538 /// Rejects a message that drops any of them.
1539 #[test]
1540 fn invalid_projection_id_messages_carry_their_context() {
1541 let too_long = InvalidProjectionId::TooLong { len: 256 }.to_string();
1542 assert!(too_long.contains("255"), "{too_long}");
1543 assert!(too_long.contains("256"), "{too_long}");
1544
1545 let reserved = InvalidProjectionId::Reserved { prefix: "sync/" }.to_string();
1546 assert!(reserved.contains("`sync/`"), "{reserved}");
1547 }
1548}
1549
1550/// The trait-level doc block, read as text because it is published on **two**
1551/// pages.
1552///
1553/// The same mechanism as `store.rs`'s module of this name, and the same defect:
1554/// `#[trait_variant::make(SendProjectionStore: Send)]` rebuilds the derived trait
1555/// with `..tr.clone()`, so every `///` line above the derivation is rendered
1556/// verbatim on `SendProjectionStore`'s page too. `SendProjectionStore` has no doc
1557/// comment of its own, so the copying is load-bearing — `missing_docs` is what
1558/// would notice it stopping — and the sentences therefore have to be true on
1559/// whichever page a reader opened.
1560///
1561/// The extractor is duplicated from `store.rs` rather than shared: sharing it
1562/// would put a test-only module in the crate root, which is the file
1563/// `happenstance`'s `contract_surface.rs` derives every gate from.
1564#[cfg(test)]
1565mod derived_flavour_doc {
1566 #![allow(clippy::unwrap_used, reason = "test code, per the house style")]
1567
1568 use alloc::string::String;
1569 use alloc::vec::Vec;
1570
1571 /// This file's own source. The doc block is the deliverable, so it is read
1572 /// rather than trusted.
1573 const SOURCE: &str = include_str!("projection.rs");
1574
1575 /// The derivation whose expansion copies the block above it onto a second page.
1576 const DERIVATION: &str = "#[trait_variant::make(SendProjectionStore: Send)]";
1577
1578 /// The two flavours, in the link form a reader can click from either page.
1579 const FLAVOURS: [&str; 2] = ["[`ProjectionStore`]", "[`SendProjectionStore`]"];
1580
1581 /// The `///` lines the derivation copies, marker removed and fences dropped.
1582 fn copied_prose() -> Vec<&'static str> {
1583 let lines: Vec<&str> = SOURCE.lines().collect();
1584 let make = lines
1585 .iter()
1586 .position(|line| line.trim_end() == DERIVATION)
1587 .expect("the derivation that copies this block onto the second page");
1588 let start = lines[..make]
1589 .iter()
1590 .rposition(|line| {
1591 !(line.starts_with("///") || line.starts_with("//") || line.starts_with("#["))
1592 })
1593 .map_or(0, |index| index + 1);
1594 let mut fenced = false;
1595 lines[start..make]
1596 .iter()
1597 .filter_map(|line| {
1598 let text = line.strip_prefix("///")?;
1599 let text = text.strip_prefix(' ').unwrap_or(text);
1600 if text.trim_start().starts_with("```") {
1601 fenced = !fenced;
1602 return None;
1603 }
1604 if fenced { None } else { Some(text) }
1605 })
1606 .collect()
1607 }
1608
1609 /// The copied prose in blank-line-separated paragraphs.
1610 fn paragraphs() -> Vec<String> {
1611 copied_prose()
1612 .split(|line| line.is_empty())
1613 .filter(|block| !block.is_empty())
1614 .map(|block| block.join(" "))
1615 .collect()
1616 }
1617
1618 /// A paragraph that distinguishes the flavours names them; it does not point.
1619 #[test]
1620 fn no_paragraph_tells_the_flavours_apart_by_deixis() {
1621 /// Pointers that resolve against the page rather than against a name.
1622 const DEIXIS: [&str; 6] = [
1623 "this trait",
1624 "this is",
1625 "this flavour",
1626 "this one",
1627 "the one to use",
1628 "instead",
1629 ];
1630 for paragraph in paragraphs() {
1631 let lower = paragraph.to_lowercase();
1632 if !lower.contains("send") {
1633 continue;
1634 }
1635 for pointer in DEIXIS {
1636 assert!(
1637 !lower.contains(pointer),
1638 "{DERIVATION} copies this paragraph verbatim onto \
1639 `SendProjectionStore`, where {pointer:?} points at the wrong \
1640 trait. Name the flavour: {paragraph}"
1641 );
1642 }
1643 }
1644 }
1645
1646 /// Both flavours are named, in link form, in the prose a reader lands on.
1647 #[test]
1648 fn the_block_names_both_flavours_in_link_form() {
1649 let prose = copied_prose().join("\n");
1650 for flavour in FLAVOURS {
1651 assert!(
1652 prose.contains(flavour),
1653 "the block is rendered on both pages, so it must name {flavour} \
1654 rather than leave a reader to infer which trait they are on. \
1655 Prose as read:\n{prose}"
1656 );
1657 }
1658 }
1659}