Skip to main content

AppendCondition

Struct AppendCondition 

Source
#[non_exhaustive]
pub struct AppendCondition { /* private fields */ }
Expand description

The consistency boundary an append is checked against.

This is the whole point of DCB. Rather than locking an aggregate, a command handler declares what it looked at when it made its decision. The store then refuses the append if anything matching that description has landed since — which is precisely the set of writes that could have changed the decision.

A condition is a non-empty sequence of Guards, each pairing a query with its own boundary. The store must reject the append if any guard is violated — that is, if the store holds an event matching that guard’s query at a position strictly greater than that guard’s after. A guard whose after is None is violated by any match at all.

Most conditions have exactly one guard, which is what new builds and what every example below shows. More than one is for a decision model assembled from fragments read separately: four reads produce four boundaries, and there is no single boundary that is correct for all four.

§A claim about one store’s log, not about the world

A condition is evaluated against the events the evaluating store still holds, and against nothing else. A conditional append is therefore sound only where that store holds every event the condition’s query ranges over, and the contract promises nothing beyond that.

Where matching history has been removed (pruned, archived, truncated, or never replicated here) the store MAY admit an append it would otherwise have rejected. That MAY is the caller’s reading: a caller must not rely on a refusal. A conformant store admits: the condition passes vacuously, because the information is missing from the store, not merely from the API, and a pruned store and a young one are the same value at every seam of this port. The testkit’s condition_over_removed_history_does_not_reject (ES-40) checks it, requiring the append once the condition’s only match is removed.

The sharp consequence is for replication: re-evaluating an origin’s condition against a partial local log answers “nothing matched” for history that exists elsewhere, and a decision taken on that answer may miss the events it names.

§The usual shape

A command handler reads with some query, notes the last position it saw, and appends with the same query and that position:

let query = Query::from_item(QueryItem::of_types(["StudentSubscribed"])?);

// ... read with `query`, ending at `last_seen` ...
let last_seen = None; // nothing matched

let condition = AppendCondition::new(query).after_every_guard_opt(last_seen);

§Examples

Asserting that a course has never been defined — the classic uniqueness check, expressed without an aggregate:

use happenstance_core::{AppendCondition, Query, QueryItem, Tags};

let condition = AppendCondition::new(Query::from_item(QueryItem::new(
    ["CourseDefined"],
    Tags::from_pairs([("course", "c1")])?,
)?));

assert_eq!(condition.guards().len(), 1);
assert!(condition.guards()[0].after.is_none());

Two fragments read separately, each carrying its own boundary — the shape a min(p₁, p₂) collapse gets wrong:

use happenstance_core::{AppendCondition, Query, QueryItem, SequencePosition};

let busy = Query::from_item(QueryItem::of_types(["MeterReadingTaken"])?);
let quiet = Query::from_item(QueryItem::of_types(["TariffPublished"])?);

let condition = AppendCondition::new(busy)
    .after_every_guard_opt(SequencePosition::new(9_000))
    .and_guard(quiet, SequencePosition::new(12));

assert_eq!(condition.guards().len(), 2);
// The quiet fragment's stale boundary does not govern the busy one.
assert_eq!(condition.guards()[0].after, SequencePosition::new(9_000));
assert_eq!(condition.guards()[1].after, SequencePosition::new(12));

Implementations§

Source§

impl AppendCondition

Source

pub fn new(fail_if_events_match: Query) -> Self

A condition with one unbounded guard, checking the whole log.

Source

pub fn and_guard(self, query: Query, after: Option<SequencePosition>) -> Self

Adds a guard with its own boundary.

This is what makes the specification’s advice to “issue one read per fragment” sound. Four reads produce four boundaries, and collapsing them to min(p₁…p₄) — the obvious application-side workaround — means the quietest fragment’s stale boundary governs the busiest one, so a busy consistency boundary rejects appends that never conflicted and the deployment reads the rejection rate as contention.

A later after_every_guard or after_every_guard_opt erases the after given here, because each rewrites every guard already present: call them before and_guard, never after.

Allocation note, since this is the trade a reader coming from a language with a growable list will not expect: guards is a boxed slice, which carries no spare capacity, so this unboxes, pushes and re-boxes. A chain of n calls is quadratic in allocation. For the counts this exists to serve — four in the worked case — that is the right side of the trade against carrying capacity in every cloned condition forever.

Source

pub fn guards(&self) -> &[Guard]

The guards, in the order they were added. Never empty.

Source

pub fn after_every_guard(self, position: SequencePosition) -> Self

Restricts every guard to events after position, exclusive, erasing any boundary and_guard set: after_every_guard_opt(Some(position)).

Source

pub fn after_every_guard_opt(self, position: Option<SequencePosition>) -> Self

Restricts every guard to events after position, exclusive, or checks the whole log when position is None.

The Option-taking form exists because callers usually hold the last position they read, which is None when their query matched nothing.

Applying to every guard is what keeps a single-guard condition — the shape every existing caller builds — behaving exactly as it always has. For per-guard boundaries, use and_guard. Called after and_guard, this erases the boundary it attached, so a quiet guard takes position and the condition tolerates more.

Source

pub fn is_violated_by( &self, position: SequencePosition, event_type: &EventType, tags: &Tags, ) -> bool

Whether an event at position with this type and these tags would violate the condition.

Violated if any guard is violated — the guards are a conjunction of constraints, so one broken clause rejects the append.

Adapters should push this down into storage; this is the reference definition the conformance suite holds them to. An adapter generating SQL must parenthesise each guard explicitly — (item AND position > p) OR … — because the precedence bug that already threatens the single-boundary form becomes n times more likely here.

Source§

impl AppendCondition

The two spellings ADR-0054 renamed, kept through 1.x.

A separate impl block, after everything else, so that adding them moved no line a citation names. Each forwards to the name that says its scope.

Source

pub fn after(self, position: SequencePosition) -> Self

👎Deprecated since 0.4.2:

use after_every_guard, which names its scope; after is kept through 1.x

Restricts every guard to events after position, exclusive.

Renamed after_every_guard, because the old name did not say that it overwrites the boundary of every guard already present. The behaviour is identical, and this spelling is kept through 1.x.

Source

pub fn after_opt(self, position: Option<SequencePosition>) -> Self

👎Deprecated since 0.4.2:

use after_every_guard_opt, which names its scope; after_opt is kept through 1.x

Restricts every guard to events after position, exclusive, or checks the whole log when position is None.

Renamed after_every_guard_opt, because the old name did not say its scope. Called after and_guard, it erases the boundary and_guard attached, moving a quiet guard’s boundary to position and widening what the condition tolerates. The behaviour is identical, and this spelling is kept through 1.x.

Trait Implementations§

Source§

impl Clone for AppendCondition

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for AppendCondition

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de> Deserialize<'de> for AppendCondition

Available on crate feature serde only.
Source§

fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>

Rejects an empty guard sequence.

Deserialisation is the other door into the private field, and a validity invariant that the constructor enforces and the decoder does not is not an invariant. An empty condition decoded from a peer would be a condition nothing can violate — the same silent lost update the private field exists to prevent, arriving over the wire instead of through an assignment.

Source§

impl Eq for AppendCondition

Source§

impl PartialEq for AppendCondition

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl Serialize for AppendCondition

Available on crate feature serde only.
Source§

fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error>

Serialize this value into the given Serde serializer. Read more
Source§

impl StructuralPartialEq for AppendCondition

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.