happenstance_core/lib.rs
1// The README's code blocks are compiled as doctests. `cfg(doctest)` keeps the
2// prose out of the rendered documentation — it would otherwise appear twice, once
3// here and once in the module docs below — while still type-checking every
4// example. A README example that does not compile is worse than no example: it
5// is the first thing a reader tries, and the first impression the crate makes.
6// (D10)
7#![cfg_attr(doctest, doc = include_str!("../README.md"))]
8//! The happenstance contract: DCB-compliant event sourcing types and storage ports.
9//!
10//! This crate defines *what* an event store is and nothing about *how* one is
11//! built. It holds no I/O, opens no connections, and takes no opinion on
12//! serialisation. Everything else in the happenstance ecosystem — SQLite, Postgres,
13//! replication — depends on it, so it is deliberately the smallest and most
14//! stable crate in the workspace.
15//!
16//! It implements the [Dynamic Consistency Boundary specification][spec].
17//!
18//! [spec]: https://dcb.events/specification/
19//!
20//! # DCB in a paragraph
21//!
22//! Classical event sourcing draws consistency boundaries ahead of time, as
23//! aggregates, and every decision must fit inside one. DCB draws them per
24//! decision instead. A command handler reads whatever events it needs — across
25//! any number of entities — and then appends conditioned on *nothing matching
26//! that same query having appeared since*. The boundary is whatever the handler
27//! actually looked at, so invariants that span entities stop requiring either an
28//! oversized aggregate or a saga.
29//!
30//! # The shape of the API
31//!
32//! | Concern | Type |
33//! |---|---|
34//! | What happened | [`Event`], [`EventType`], [`Tag`], [`Tags`] |
35//! | Where it sits in the log | [`SequencePosition`], [`SequencedEvent`] |
36//! | What to read | [`Query`], [`QueryItem`], [`ReadOptions`] |
37//! | What must not have changed | [`AppendCondition`] |
38//! | Storage seams | [`EventStore`], [`ProjectionStore`] |
39//!
40//! # Design notes
41//!
42//! **Illegal states are unrepresentable.** [`Query`] is an enum rather than a
43//! vector because the specification permits "at least one item" or "match
44//! everything" and nothing else. [`SequencePosition`] wraps a [`NonZeroU64`],
45//! so position zero cannot exist and `Option<SequencePosition>` costs no extra
46//! space. [`Tags`] is canonically sorted at construction, so it can never be
47//! observed out of order.
48//!
49//! [`NonZeroU64`]: core::num::NonZeroU64
50//!
51//! **Payloads are opaque.** [`Event::data`] is [`Bytes`](bytes::Bytes) with no
52//! `serde` bound in sight. Adapters stay free of domain knowledge, and
53//! replication can forward an event byte-for-byte without deserialising it.
54//! Encoding is a job for the layer above.
55//!
56//! **The concurrency signal is in the type system.** An append returns
57//! [`AppendError`], which separates [`ConditionViolated`] — routine under
58//! contention, and a cue to retry — from adapter-specific failures. No caller
59//! has to match on a string to tell them apart.
60//!
61//! **There are two flavours of each port.** [`EventStore`] carries no `Send`
62//! bound so it can be implemented on `wasm32`; [`SendEventStore`] is derived
63//! from it for native use. Implementing the latter gives you the former. See
64//! the [`store`] module documentation for the full rationale.
65//!
66//! # Getting started
67//!
68//! Enable the `memory` feature (on by default) and use `MemoryEventStore` — see
69//! its documentation for a runnable walkthrough of the read-decide-append loop.
70//! `MemoryProjectionStore` is its projection-side twin, and its page carries a
71//! runnable `begin` → write → `commit` → read-back walkthrough of its own.
72//!
73//! Neither name is a link here. It would be a broken one whenever `memory` is
74//! off, and `cargo doc --no-default-features` treats a broken intra-doc link as a
75//! hard error rather than a warning (D13).
76//!
77//! # Feature flags
78//!
79//! * **`std`** *(default)* — standard library support.
80//! * **`memory`** *(default)* — the `MemoryEventStore` and
81//! `MemoryProjectionStore` reference implementations. Implies `std`.
82//! * **`serde`** — `Serialize`/`Deserialize` for the wire types. Off by
83//! default so the contract crate carries no serialisation opinion; enabled by
84//! replication adapters that need one.
85//! * **`unstable-projection`** — **removed in `0.4.0`.** From `0.2.0` to
86//! ADR-0063 it held the `ProjectionStore` port out of the semver promise, for
87//! the reason the [`projection`] module header records; from ADR-0063 to
88//! `0.4.0` it was declared empty, so a `0.2.0` manifest kept resolving. The
89//! port is unconditional and frozen, and a manifest that still names the
90//! feature fails to resolve — the break `0.4.0` was the release to make.
91//! * **`conformance`** — `ProjectionProbe`, the write seam the projection
92//! conformance suite drives an adapter's read model through. For adapter
93//! authors running that suite against their own store; nothing in the runtime
94//! path needs it. Off by default, pulls in no dependency, and implies no other
95//! feature — not `std` and not `memory`. It implied `unstable-projection`
96//! until ADR-0063, because the module it lives in was gated then; it is
97//! not gated now, and that feature is gone.
98//!
99//! The name is deliberately not a link here: a link into a `cfg`-gated item is
100//! a hard error when the feature is off, and `cargo doc --no-default-features`
101//! is a gate step.
102#![doc(/* one line: rustfmt keeps a commented list whole, and the lines below are cited by number */ html_logo_url = "https://raw.githubusercontent.com/Wet-Ink-Corporation/happenstance/main/assets/brand/favicon.svg", html_favicon_url = "https://raw.githubusercontent.com/Wet-Ink-Corporation/happenstance/main/assets/brand/favicon.svg")]
103#![cfg_attr(not(feature = "std"), no_std)]
104#![cfg_attr(docsrs, feature(doc_cfg))]
105
106extern crate alloc;
107
108mod append;
109mod derivation;
110mod error;
111mod event;
112mod identity;
113mod limits;
114mod query;
115mod tag;
116mod validate;
117
118pub mod store;
119
120// Unconditional since ADR-0063. It sat behind `unstable-projection` from
121// phase 6 to the lift, and the `xtask` tests that held it there now hold the
122// opposite: no `cfg` on this line, none on the re-exports below, no feature.
123pub mod projection;
124
125#[cfg(feature = "memory")]
126#[cfg_attr(docsrs, doc(cfg(feature = "memory")))]
127mod memory;
128
129// `memory` alone, like its event-store twin: the port it implements is
130// unconditional.
131#[cfg(feature = "memory")]
132#[cfg_attr(docsrs, doc(cfg(feature = "memory")))]
133mod projection_memory;
134
135pub use append::{AppendCondition, Guard};
136pub use error::{AppendError, ConditionViolated, InvalidEventType, InvalidQuery, InvalidTag};
137pub use event::{
138 Event, EventParts, EventType, MAX_EVENT_TYPE_LEN, SequencePosition, SequencedEvent,
139};
140pub use identity::{EventId, RecordedAt, StoreId};
141pub use limits::{
142 MIN_SUPPORTED_EVENT_DATA_LEN, MIN_SUPPORTED_EVENTS_PER_BATCH, MIN_SUPPORTED_QUERY_ITEMS,
143 MIN_SUPPORTED_TAGS_PER_BATCH, MIN_SUPPORTED_TAGS_PER_EVENT, StoreLimit,
144};
145pub use query::{Query, QueryItem, ReadOptions};
146pub use store::{EventStore, SendEventStore, collect, read_decision_model};
147pub use tag::{MAX_TAG_LEN, Tag, Tags};
148
149pub use projection::{
150 Authority, Checkpoint, CommitError, InvalidProjectionId, MAX_PROJECTION_ID_LEN, ProjectionId,
151 ProjectionStore, ResetError, SendProjectionStore,
152};
153
154#[cfg(feature = "conformance")]
155#[cfg_attr(docsrs, doc(cfg(feature = "conformance")))]
156pub use projection::ProjectionProbe;
157
158#[cfg(feature = "memory")]
159#[cfg_attr(docsrs, doc(cfg(feature = "memory")))]
160pub use memory::{MemoryEventStore, MemoryStoreError};
161
162#[cfg(feature = "memory")]
163#[cfg_attr(docsrs, doc(cfg(feature = "memory")))]
164pub use projection_memory::{
165 MemoryProjectionBatch, MemoryProjectionStore, MemoryProjectionStoreError,
166};
167
168/// Re-exported so adapters and callers can name payload types without adding a
169/// direct dependency on a specific `bytes` version.
170pub use bytes;
171
172/// Re-exported for the reason [`bytes`] is, one trait over: `Stream` appears at
173/// the *top level* of [`EventStore::read`]'s signature, so every adapter and
174/// every generic caller is forced to name it, and two `Stream` traits that print
175/// identically fail as `error[E0277]` naming a trait the author can see is
176/// implemented.
177pub use futures_core;
178
179/// Compiled proof that every path this crate promises a caller actually
180/// resolves from outside it — and the statement of what that promise is not.
181///
182/// A re-export is a **type-identity and discoverability** guarantee: one
183/// `Bytes` and one `Stream` in a build rather than two that print identically,
184/// and reachable without a second manifest line for a caller to get wrong. It
185/// is **not** a substitute for a consumer's own dependency — features a caller
186/// did not enable do not arrive through it — and it is not a statement about
187/// which versions of which crates travel together.
188///
189/// `#[cfg(doctest)]` because the module carries no items. It exists to be
190/// compiled by `cargo test -p happenstance-core --doc`, which is the only place
191/// in this workspace where a `happenstance_core::…` path is resolved the way a
192/// consumer resolves it: from outside.
193///
194/// ```
195/// fn payload(b: happenstance_core::bytes::Bytes) -> usize { b.len() }
196/// # fn main() { assert_eq!(payload(happenstance_core::bytes::Bytes::from_static(b"{}")), 2); }
197/// ```
198///
199/// `Stream` sits at the *top level* of `EventStore::read`'s signature rather
200/// than inside a future (ADR-0008), so no adapter and no generic caller can
201/// avoid naming it:
202///
203/// ```
204/// fn readable<S: happenstance_core::futures_core::Stream>(_s: S) {}
205/// # fn main() {}
206/// ```
207#[cfg(doctest)]
208mod reexported_paths {}