Skip to main content

handles_and_quotas/
main.rs

1// The module documentation is `src/overview.md`, included rather than written
2// here so the reader who is sent to it and the reader who runs `cargo doc` meet
3// the same bytes by construction. Same mechanism, and the same argument, as
4// `examples/course-subscriptions/src/main.rs`.
5#![doc = include_str!("overview.md")]
6#![allow(clippy::print_stdout, reason = "the transcript is the point")]
7
8use std::path::{Path, PathBuf};
9
10use anyhow::{Result, bail};
11use happenstance::bytes::Bytes;
12use happenstance::{
13    Boundary, Codec, CodecError, CommandError, CommandOutcome, DecisionModel, DomainEvent,
14    EventStore, EventType, InvalidTag, Query, ReadOptions, Retry, SequencePosition, Tag, Tags,
15    collect, commit,
16};
17use happenstance_sqlite::event_store::{SqliteEventStore, SqliteEventStoreError};
18use serde::{Deserialize, Serialize};
19
20/// How many times a command may be attempted before it gives up.
21///
22/// Spelled at every call site for the reason `course-subscriptions` gives: a
23/// loop whose only exit is success is a hang with better manners. This run is
24/// single-writer, so the bound is never spent and every commit below reports
25/// one attempt — a visible bound on an unexercised path.
26const ATTEMPTS: u32 = 3;
27
28/// How many handles an owner may hold before anybody has said otherwise.
29///
30/// A fold's starting value and not a row in a table, which is the whole reason
31/// the quota needs no aggregate: an owner who has never been heard of has a
32/// plan, because the fold gives them one.
33const DEFAULT_PLAN: u32 = 2;
34
35#[tokio::main(flavor = "current_thread")]
36async fn main() -> Result<()> {
37    let path = database_path();
38    remove_database(&path);
39
40    println!("== the database this run writes to ==");
41    println!("   {}", path.display());
42
43    // The run is a function so every store and connection it builds is dropped
44    // before the file is removed — on Windows an open handle is what makes the
45    // cleanup silently fail and the next run start on the tail of this one.
46    let outcome = run(&path).await;
47    remove_database(&path);
48    outcome
49}
50
51/// Everything this program does, against one file.
52async fn run(path: &Path) -> Result<()> {
53    let events = SqliteEventStore::open(path)?;
54
55    the_boundary_is_a_query()?;
56    a_name_is_held_by_one_owner(&events).await?;
57    a_released_name_is_claimable_again(&events).await?;
58    a_plan_caps_what_an_owner_holds(&events).await?;
59    one_command_delivered_twice(&events).await?;
60
61    println!("\n== what the log actually says ==");
62    print_log(&events).await?;
63
64    Ok(())
65}
66
67// ---------------------------------------------------------------------------
68// The five things this program shows
69// ---------------------------------------------------------------------------
70
71/// Prints the query a claim derives, before any of them is taken.
72///
73/// The point the rest of the program is evidence for, made once and in the
74/// open: the consistency boundary is a **value**. It can be bound, printed and
75/// asserted on, and it is derived from the event set crossed with each model's
76/// scope — so the query and the folds that consume it cannot name different
77/// sets. Nothing here is hidden inside a read.
78fn the_boundary_is_a_query() -> Result<()> {
79    println!("\n== the boundary is a query, not an entity ==");
80
81    let owner = OwnerId::new("u-1")?;
82    let handle = HandleName::new("alice")?;
83    let request = RequestId::new("r-1")?;
84    let boundary = (
85        Handle::new(&handle)?,
86        Holdings::new(&owner)?,
87        Request::new(&request)?,
88    );
89
90    println!("   claiming `alice` for u-1 reads three things at once:");
91    print_boundary(&boundary)?;
92    println!(
93        "   one event set, three scopes, three query items. There is no Handle\n   \
94         object, no Owner row and no Request table — each rule is the set of\n   \
95         events that could contradict it, and the append is conditioned on all\n   \
96         three of them at once."
97    );
98
99    Ok(())
100}
101
102/// Claims a name, and shows the second claimant refused.
103async fn a_name_is_held_by_one_owner(events: &SqliteEventStore) -> Result<()> {
104    println!("\n== a name is held by one owner ==");
105
106    println!(
107        "   u-1 claims alice: {}",
108        claim(events, "u-1", "alice", "r-1").await?
109    );
110
111    match claim(events, "u-2", "alice", "r-2").await {
112        Ok(outcome) => bail!("a claim on a held name should have been refused, got: {outcome}"),
113        Err(err) => println!("   u-2 claims alice: refused: {err}"),
114    }
115
116    Ok(())
117}
118
119/// Releases the name and lets somebody else have it.
120///
121/// The half of rule 1 that a unique index cannot state without a delete: the
122/// boundary is not "names that are taken", it is "everything that has happened
123/// to this name", and a release is one of the things that can have happened.
124async fn a_released_name_is_claimable_again(events: &SqliteEventStore) -> Result<()> {
125    println!("\n== a released name is claimable again ==");
126
127    println!(
128        "   u-1 releases alice: {}",
129        release(events, "u-1", "alice", "r-3").await?
130    );
131    println!(
132        "   u-2 claims alice:   {}",
133        claim(events, "u-2", "alice", "r-4").await?
134    );
135    println!(
136        "   the log still holds u-1's claim; what changed is what the fold of\n   \
137         that name now says, which is the only thing the condition consults"
138    );
139
140    Ok(())
141}
142
143/// Fills an owner's plan, is refused, raises the plan, and is not.
144///
145/// The second boundary, composed with the first in every one of these
146/// commands. It spans a set nobody can enumerate in advance — the handles this
147/// owner holds — and it is enforced by the same append condition that enforces
148/// the name.
149async fn a_plan_caps_what_an_owner_holds(events: &SqliteEventStore) -> Result<()> {
150    println!("\n== a plan caps what an owner holds ==");
151
152    println!(
153        "   u-2 claims bob:   {}",
154        claim(events, "u-2", "bob", "r-5").await?
155    );
156
157    match claim(events, "u-2", "carol", "r-6").await {
158        Ok(outcome) => bail!("a claim over the plan should have been refused, got: {outcome}"),
159        Err(err) => println!("   u-2 claims carol: refused: {err}"),
160    }
161
162    println!(
163        "   u-2 moves to a plan of 3: {}",
164        change_plan(events, "u-2", 3, "r-7").await?
165    );
166    println!(
167        "   u-2 claims carol: {}",
168        claim(events, "u-2", "carol", "r-8").await?
169    );
170
171    Ok(())
172}
173
174/// Sends one command twice under one request id, and appends once.
175///
176/// The third boundary. It is not domain state at all — it is whether *this
177/// delivery* has already been applied — and it is enforced the same way as the
178/// other two, which is the point: an idempotency key does not need a table, a
179/// lock or a separate transaction when it can be a scope.
180async fn one_command_delivered_twice(events: &SqliteEventStore) -> Result<()> {
181    println!("\n== one command, delivered twice ==");
182
183    let before = head(events).await?;
184    println!(
185        "   first delivery:  {}",
186        claim(events, "u-1", "dave", "r-9").await?
187    );
188    println!(
189        "   second delivery: {}",
190        claim(events, "u-1", "dave", "r-9").await?
191    );
192    let after = head(events).await?;
193
194    let grew = after.saturating_sub(before);
195    if grew != 1 {
196        bail!("a command delivered twice appended {grew} event(s), not 1");
197    }
198    println!("   the log grew by {grew} event, not 2");
199    println!(
200        "   and the second delivery is not an error: it restates what the first\n   \
201         one did, which is what a client that timed out and retried needs"
202    );
203
204    Ok(())
205}
206
207// ---------------------------------------------------------------------------
208// Identity, validated once at the edge
209// ---------------------------------------------------------------------------
210
211/// An owner, validated once into the tag their events carry.
212///
213/// The resolution the other examples reach, and for the same reason:
214/// `DomainEvent::tags` is infallible while `Tag::key_value` can refuse, so a
215/// domain type whose tags come from runtime values holds the validated form
216/// instead of rebuilding it on every call.
217#[derive(Debug, Clone, Serialize, Deserialize)]
218#[serde(try_from = "String", into = "String")]
219struct OwnerId {
220    /// The identifier as the application wrote it.
221    id: String,
222    /// The same value, validated into a tag.
223    tag: Tag,
224}
225
226impl OwnerId {
227    /// Validates `id` into the tag every event for this owner is written with.
228    fn new(id: &str) -> Result<Self, InvalidTag> {
229        Ok(Self {
230            id: id.to_owned(),
231            tag: Tag::key_value("owner", id)?,
232        })
233    }
234
235    /// The identifier as the application wrote it.
236    fn as_str(&self) -> &str {
237        &self.id
238    }
239}
240
241impl TryFrom<String> for OwnerId {
242    type Error = InvalidTag;
243
244    fn try_from(id: String) -> Result<Self, InvalidTag> {
245        Self::new(&id)
246    }
247}
248
249impl From<OwnerId> for String {
250    fn from(owner: OwnerId) -> Self {
251        owner.id
252    }
253}
254
255/// A handle, validated once into the tag its events carry.
256///
257/// **This is the type with no entity behind it.** A handle nobody has claimed
258/// is not an object in an unclaimed state; it is a string drawn from a set
259/// nobody can enumerate. What makes it a consistency boundary is not that it
260/// exists, but that a query can be written for it.
261#[derive(Debug, Clone, Serialize, Deserialize)]
262#[serde(try_from = "String", into = "String")]
263struct HandleName {
264    /// The handle as the application wrote it.
265    id: String,
266    /// The same value, validated into a tag.
267    tag: Tag,
268}
269
270impl HandleName {
271    /// Validates `id` into the tag every event for this handle is written with.
272    fn new(id: &str) -> Result<Self, InvalidTag> {
273        Ok(Self {
274            id: id.to_owned(),
275            tag: Tag::key_value("handle", id)?,
276        })
277    }
278
279    /// The handle as the application wrote it.
280    fn as_str(&self) -> &str {
281        &self.id
282    }
283}
284
285impl TryFrom<String> for HandleName {
286    type Error = InvalidTag;
287
288    fn try_from(id: String) -> Result<Self, InvalidTag> {
289        Self::new(&id)
290    }
291}
292
293impl From<HandleName> for String {
294    fn from(handle: HandleName) -> Self {
295        handle.id
296    }
297}
298
299/// One delivery of one command, validated once into the tag its events carry.
300///
301/// Supplied by the caller, not minted here. That is what makes it an
302/// idempotency key rather than an event id: two deliveries of one command
303/// carry the same value precisely because the client, not the server, decided
304/// what it was.
305#[derive(Debug, Clone, Serialize, Deserialize)]
306#[serde(try_from = "String", into = "String")]
307struct RequestId {
308    /// The request as the client wrote it.
309    id: String,
310    /// The same value, validated into a tag.
311    tag: Tag,
312}
313
314impl RequestId {
315    /// Validates `id` into the tag every event this delivery writes carries.
316    fn new(id: &str) -> Result<Self, InvalidTag> {
317        Ok(Self {
318            id: id.to_owned(),
319            tag: Tag::key_value("request", id)?,
320        })
321    }
322
323    /// The request as the client wrote it.
324    fn as_str(&self) -> &str {
325        &self.id
326    }
327}
328
329impl TryFrom<String> for RequestId {
330    type Error = InvalidTag;
331
332    fn try_from(id: String) -> Result<Self, InvalidTag> {
333        Self::new(&id)
334    }
335}
336
337impl From<RequestId> for String {
338    fn from(request: RequestId) -> Self {
339        request.id
340    }
341}
342
343// ---------------------------------------------------------------------------
344// The domain: one enum, named once
345// ---------------------------------------------------------------------------
346
347/// Everything that can happen in the registry.
348///
349/// Every variant carries the `request` that wrote it, and that is not
350/// bookkeeping — it is what puts a delivery inside the same tag space as the
351/// domain, so the same query vocabulary reaches it and the same append
352/// condition covers it.
353///
354/// One enum, so a query and a fold cannot name different sets. There is no
355/// `_ =>` arm anywhere in this file.
356#[derive(Debug, Serialize, Deserialize)]
357enum Registry {
358    /// An owner took a handle.
359    HandleClaimed {
360        /// The handle now held.
361        handle: HandleName,
362        /// Who holds it.
363        owner: OwnerId,
364        /// The delivery that wrote this.
365        request: RequestId,
366    },
367    /// An owner gave a handle back.
368    HandleReleased {
369        /// The handle now free.
370        handle: HandleName,
371        /// Who was holding it.
372        owner: OwnerId,
373        /// The delivery that wrote this.
374        request: RequestId,
375    },
376    /// An owner's plan changed how many handles they may hold.
377    PlanChanged {
378        /// Whose plan.
379        owner: OwnerId,
380        /// How many handles it now allows.
381        handles: u32,
382        /// The delivery that wrote this.
383        request: RequestId,
384    },
385}
386
387const HANDLE_CLAIMED: EventType = EventType::from_static("HandleClaimed");
388const HANDLE_RELEASED: EventType = EventType::from_static("HandleReleased");
389const PLAN_CHANGED: EventType = EventType::from_static("PlanChanged");
390
391impl DomainEvent for Registry {
392    const EVENT_TYPES: &'static [EventType] = &[HANDLE_CLAIMED, HANDLE_RELEASED, PLAN_CHANGED];
393
394    fn event_type(&self) -> EventType {
395        match self {
396            Self::HandleClaimed { .. } => HANDLE_CLAIMED,
397            Self::HandleReleased { .. } => HANDLE_RELEASED,
398            Self::PlanChanged { .. } => PLAN_CHANGED,
399        }
400    }
401
402    fn tags(&self) -> Tags {
403        match self {
404            Self::HandleClaimed {
405                handle,
406                owner,
407                request,
408            }
409            | Self::HandleReleased {
410                handle,
411                owner,
412                request,
413            } => [handle.tag.clone(), owner.tag.clone(), request.tag.clone()]
414                .into_iter()
415                .collect(),
416            // No handle tag, so a claim's boundary never nominates a plan
417            // change — which is correct: what an owner is allowed to hold has
418            // nothing to say about who holds one particular name.
419            Self::PlanChanged { owner, request, .. } => [owner.tag.clone(), request.tag.clone()]
420                .into_iter()
421                .collect(),
422        }
423    }
424
425    fn encode<C: Codec>(&self, codec: &C) -> Result<Bytes, CodecError> {
426        codec.encode(self)
427    }
428
429    fn decode<C: Codec>(
430        codec: &C,
431        _event_type: &EventType,
432        data: &Bytes,
433    ) -> Result<Self, CodecError> {
434        codec.decode(data)
435    }
436}
437
438// ---------------------------------------------------------------------------
439// What a command did, and why one refused
440// ---------------------------------------------------------------------------
441
442/// What a delivery turned out to have done.
443///
444/// Folded out of the log rather than remembered, which is what makes it
445/// survive a restart: a replay learns what the first delivery did by reading
446/// the event that delivery wrote.
447#[derive(Debug, Clone)]
448enum Landed {
449    /// It claimed a handle.
450    Claimed {
451        /// The handle it claimed.
452        handle: String,
453    },
454    /// It released one.
455    Released {
456        /// The handle it released.
457        handle: String,
458    },
459    /// It set a plan.
460    PlanSet {
461        /// How many handles the plan now allows.
462        handles: u32,
463    },
464}
465
466impl core::fmt::Display for Landed {
467    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
468        match self {
469            Self::Claimed { handle } => write!(formatter, "claimed {handle}"),
470            Self::Released { handle } => write!(formatter, "released {handle}"),
471            Self::PlanSet { handles } => write!(formatter, "set the plan to {handles}"),
472        }
473    }
474}
475
476/// What a command call returned.
477///
478/// Two arms rather than a `Result<(), _>` with a special error, because a
479/// replay is a **success**: the client asked for a thing to be true and it is
480/// true. Modelling it as a failure is how retries turn into user-visible
481/// errors that nobody can act on.
482#[derive(Debug)]
483enum Outcome {
484    /// The decision was taken and its events were appended.
485    Applied {
486        /// Where the last appended event landed.
487        position: u64,
488        /// How many attempts the command loop spent, the successful one
489        /// included.
490        attempts: u32,
491    },
492    /// This delivery had already been applied, and nothing was appended.
493    Replayed {
494        /// What the first delivery did.
495        landed: Landed,
496    },
497}
498
499impl core::fmt::Display for Outcome {
500    fn fmt(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
501        match self {
502            Self::Applied { position, attempts } => write!(
503                formatter,
504                "applied at position {position}, in {attempts} attempt(s)"
505            ),
506            Self::Replayed { landed } => {
507                write!(formatter, "already applied — {landed}; nothing appended")
508            }
509        }
510    }
511}
512
513/// Why a decision refused.
514///
515/// Every variant carries the value the transcript prints — `alice is held by
516/// u-1` and never `conflict` — so a reader can act on the refusal where it is
517/// printed instead of opening a second document to learn what happened.
518#[derive(Debug, thiserror::Error)]
519enum Refusal {
520    /// Rule 1: a handle is held by at most one owner.
521    #[error("{handle} is held by {owner}")]
522    HandleTaken {
523        /// The handle somebody else has.
524        handle: String,
525        /// Who has it.
526        owner: String,
527    },
528    /// A handle cannot be released by somebody who is not holding it.
529    #[error("{handle} is not held by {owner}")]
530    NotHeld {
531        /// The handle in question.
532        handle: String,
533        /// Who tried to give it back.
534        owner: String,
535    },
536    /// Rule 2: an owner may not exceed their plan.
537    #[error("{owner} holds {held} of {cap}")]
538    PlanFull {
539        /// The owner at their limit.
540        owner: String,
541        /// How many they hold.
542        held: u32,
543        /// How many they may hold.
544        cap: u32,
545    },
546    /// Rule 3: this delivery has already been applied.
547    ///
548    /// **Not a failure**, and the only variant here that is matched on by
549    /// value rather than printed: `settle` turns it into
550    /// [`Outcome::Replayed`]. It is spelled as a refusal because that is what
551    /// it is to the decision — there is nothing left to append — and the
552    /// translation into a success belongs one layer out, where the client is.
553    #[error("already applied — {landed}")]
554    AlreadyApplied {
555        /// What the first delivery did.
556        landed: Landed,
557    },
558}
559
560// ---------------------------------------------------------------------------
561// The decision models: one per rule
562// ---------------------------------------------------------------------------
563
564/// Who holds one handle, if anybody.
565///
566/// Scoped to a single `handle` tag, so its query nominates every event ever
567/// written about that name — including the releases, which is what makes the
568/// boundary dynamic.
569#[derive(Debug, Clone)]
570struct Handle {
571    /// The tags every event inside this boundary carries.
572    scope: Tags,
573    /// Who holds it now, or `None` if nobody does.
574    held_by: Option<String>,
575}
576
577impl Handle {
578    /// Validates the scope once, here, where the caller already writes a `?`.
579    fn new(handle: &HandleName) -> Result<Self, InvalidTag> {
580        Ok(Self {
581            scope: Tags::from_pairs([("handle", handle.as_str())])?,
582            held_by: None,
583        })
584    }
585}
586
587impl DecisionModel for Handle {
588    type Event = Registry;
589
590    fn scope(&self) -> &Tags {
591        &self.scope
592    }
593
594    fn apply(&mut self, event: Self::Event) {
595        match event {
596            Registry::HandleClaimed { owner, .. } => self.held_by = Some(owner.id),
597            Registry::HandleReleased { .. } => self.held_by = None,
598            // A plan change carries no `handle` tag, so this model's query
599            // never nominates one. The arm exists because the fold is
600            // exhaustive over the enum, and that exhaustiveness is the whole
601            // guarantee.
602            Registry::PlanChanged { .. } => {}
603        }
604    }
605}
606
607/// How many handles one owner holds, and how many they may.
608///
609/// Scoped to a single `owner` tag. The count is a fold over a set nobody
610/// enumerated — every handle this owner has ever taken or given back — which
611/// is the shape a quota actually has and the shape an aggregate cannot hold
612/// without owning every handle in the system.
613#[derive(Debug, Clone)]
614struct Holdings {
615    /// The tags every event inside this boundary carries.
616    scope: Tags,
617    /// How many handles are currently held.
618    held: u32,
619    /// How many may be held.
620    cap: u32,
621}
622
623impl Holdings {
624    /// Validates the scope once, here, where the caller already writes a `?`.
625    fn new(owner: &OwnerId) -> Result<Self, InvalidTag> {
626        Ok(Self {
627            scope: Tags::from_pairs([("owner", owner.as_str())])?,
628            held: 0,
629            cap: DEFAULT_PLAN,
630        })
631    }
632}
633
634impl DecisionModel for Holdings {
635    type Event = Registry;
636
637    fn scope(&self) -> &Tags {
638        &self.scope
639    }
640
641    fn apply(&mut self, event: Self::Event) {
642        match event {
643            Registry::HandleClaimed { .. } => self.held = self.held.saturating_add(1),
644            Registry::HandleReleased { .. } => self.held = self.held.saturating_sub(1),
645            Registry::PlanChanged { handles, .. } => self.cap = handles,
646        }
647    }
648}
649
650/// Whether one delivery has already been applied, and what it did.
651///
652/// Scoped to a single `request` tag. It is the smallest useful decision model
653/// in this file and the one that does the most: because it is part of the same
654/// boundary as the other two, the check and the write are one conditional
655/// append, and two concurrent deliveries of a command cannot both land.
656#[derive(Debug, Clone)]
657struct Request {
658    /// The tags every event inside this boundary carries.
659    scope: Tags,
660    /// What this delivery already did, if it has run.
661    landed: Option<Landed>,
662}
663
664impl Request {
665    /// Validates the scope once, here, where the caller already writes a `?`.
666    fn new(request: &RequestId) -> Result<Self, InvalidTag> {
667        Ok(Self {
668            scope: Tags::from_pairs([("request", request.as_str())])?,
669            landed: None,
670        })
671    }
672}
673
674impl DecisionModel for Request {
675    type Event = Registry;
676
677    fn scope(&self) -> &Tags {
678        &self.scope
679    }
680
681    fn apply(&mut self, event: Self::Event) {
682        self.landed = Some(match event {
683            Registry::HandleClaimed { handle, .. } => Landed::Claimed { handle: handle.id },
684            Registry::HandleReleased { handle, .. } => Landed::Released { handle: handle.id },
685            Registry::PlanChanged { handles, .. } => Landed::PlanSet { handles },
686        });
687    }
688}
689
690// ---------------------------------------------------------------------------
691// The three command handlers
692// ---------------------------------------------------------------------------
693
694/// Claims a handle for an owner, under one delivery.
695///
696/// The three-tuple is the boundary, and there is no macro invocation and no
697/// builder in the way: a tuple of decision models is a `Boundary`, its query
698/// is the union of theirs, and one append condition carries all three.
699async fn claim(
700    events: &SqliteEventStore,
701    owner: &str,
702    handle: &str,
703    request: &str,
704) -> Result<Outcome> {
705    let owner = OwnerId::new(owner)?;
706    let handle = HandleName::new(handle)?;
707    let request = RequestId::new(request)?;
708    let boundary = (
709        Handle::new(&handle)?,
710        Holdings::new(&owner)?,
711        Request::new(&request)?,
712    );
713
714    let result = commit(
715        events,
716        boundary,
717        Retry::attempts(ATTEMPTS.try_into()?),
718        |(name, holdings, delivery): &(Handle, Holdings, Request)| {
719            // Rule 3 first. A replayed delivery must not be re-judged against
720            // rules 1 and 2 — the world has moved on since it was applied, and
721            // re-judging it would report a conflict for work that succeeded.
722            if let Some(landed) = delivery.landed.clone() {
723                return Err(Refusal::AlreadyApplied { landed });
724            }
725            if let Some(holder) = name.held_by.clone() {
726                return Err(Refusal::HandleTaken {
727                    handle: handle.id.clone(),
728                    owner: holder,
729                });
730            }
731            if holdings.held >= holdings.cap {
732                return Err(Refusal::PlanFull {
733                    owner: owner.id.clone(),
734                    held: holdings.held,
735                    cap: holdings.cap,
736                });
737            }
738            Ok(vec![Registry::HandleClaimed {
739                handle: handle.clone(),
740                owner: owner.clone(),
741                request: request.clone(),
742            }])
743        },
744    )
745    .await;
746
747    settle(result)
748}
749
750/// Gives a handle back, under one delivery.
751async fn release(
752    events: &SqliteEventStore,
753    owner: &str,
754    handle: &str,
755    request: &str,
756) -> Result<Outcome> {
757    let owner = OwnerId::new(owner)?;
758    let handle = HandleName::new(handle)?;
759    let request = RequestId::new(request)?;
760    let boundary = (Handle::new(&handle)?, Request::new(&request)?);
761
762    let result = commit(
763        events,
764        boundary,
765        Retry::attempts(ATTEMPTS.try_into()?),
766        |(name, delivery): &(Handle, Request)| {
767            if let Some(landed) = delivery.landed.clone() {
768                return Err(Refusal::AlreadyApplied { landed });
769            }
770            if name.held_by.as_deref() != Some(owner.as_str()) {
771                return Err(Refusal::NotHeld {
772                    handle: handle.id.clone(),
773                    owner: owner.id.clone(),
774                });
775            }
776            Ok(vec![Registry::HandleReleased {
777                handle: handle.clone(),
778                owner: owner.clone(),
779                request: request.clone(),
780            }])
781        },
782    )
783    .await;
784
785    settle(result)
786}
787
788/// Sets how many handles an owner may hold, under one delivery.
789///
790/// Two models here rather than three: a plan has nothing to say about any
791/// particular name, so the handle boundary is not part of this decision and is
792/// not in its condition. Composing it in anyway would widen the condition to
793/// events that cannot contradict it, and every unrelated claim would then be a
794/// spurious retry.
795async fn change_plan(
796    events: &SqliteEventStore,
797    owner: &str,
798    handles: u32,
799    request: &str,
800) -> Result<Outcome> {
801    let owner = OwnerId::new(owner)?;
802    let request = RequestId::new(request)?;
803    let boundary = (Holdings::new(&owner)?, Request::new(&request)?);
804
805    let result = commit(
806        events,
807        boundary,
808        Retry::attempts(ATTEMPTS.try_into()?),
809        |(_holdings, delivery): &(Holdings, Request)| {
810            if let Some(landed) = delivery.landed.clone() {
811                return Err(Refusal::AlreadyApplied { landed });
812            }
813            Ok(vec![Registry::PlanChanged {
814                owner: owner.clone(),
815                handles,
816                request: request.clone(),
817            }])
818        },
819    )
820    .await;
821
822    settle(result)
823}
824
825// ---------------------------------------------------------------------------
826// Turning a command's result into what a client is told
827// ---------------------------------------------------------------------------
828
829/// Renders a command's result as an outcome, or as the error to print.
830///
831/// The one place `Refusal::AlreadyApplied` becomes a success. Everything else
832/// travels out with its source chain intact: `CommandError::Refused` carries
833/// the handler's own refusal, and that is what a reader must see, because
834/// `CommandError`'s own `Display` says "the decision refused", which is a
835/// category rather than a value.
836fn settle(
837    result: core::result::Result<CommandOutcome, CommandError<SqliteEventStoreError, Refusal>>,
838) -> Result<Outcome> {
839    match result {
840        Ok(CommandOutcome::Committed(committed)) => Ok(Outcome::Applied {
841            position: committed.position.get(),
842            attempts: committed.attempts,
843        }),
844
845        // **This example refuses instead of deciding nothing, and the arm is
846        // here to say that is a choice.** `CommandOutcome::Nothing` and
847        // `Refusal::AlreadyApplied` both mean *this delivery was already
848        // handled*; they differ in what they can carry. `Nothing` carries no
849        // payload, and the whole point of the idempotent path below is
850        // reporting `landed` — what the *first* delivery did — which a handler
851        // that returned an empty `Vec` would have thrown away before this
852        // function saw it.
853        //
854        // So reaching this arm means a handler returned no events on a path
855        // that was supposed to refuse, and it is reported rather than folded
856        // into `Applied` with a fabricated position. Deciding nothing is the
857        // right shape when there is nothing to say; here there is.
858        Ok(CommandOutcome::Nothing) => bail!(
859            "a handler decided no events: this example's idempotent path              refuses with `AlreadyApplied` so that it can report what the              first delivery landed, and an empty decision has nowhere to put it"
860        ),
861
862        Err(CommandError::Refused(Refusal::AlreadyApplied { landed })) => {
863            Ok(Outcome::Replayed { landed })
864        }
865        Err(CommandError::Refused(refusal)) => Err(refusal.into()),
866        Err(other) => Err(other.into()),
867    }
868}
869
870// ---------------------------------------------------------------------------
871// Reading
872// ---------------------------------------------------------------------------
873
874/// Prints the query items a boundary derives, one per line.
875///
876/// Generic over `Boundary`, which is what a tuple of decision models becomes.
877/// The trait is sealed, so this signature can consume one and no crate outside
878/// `happenstance` can add a third kind of implementor to surprise it.
879fn print_boundary<B: Boundary>(boundary: &B) -> Result<()> {
880    let query = boundary.query()?;
881
882    match query.items() {
883        Some(items) => {
884            for item in items {
885                let types: Vec<&str> = item.types().iter().map(EventType::as_str).collect();
886                println!("      {} where {:?}", types.join(" | "), item.tags());
887            }
888        }
889        // Unreachable for a well-formed model, and spelled rather than
890        // `unwrap`ped: `Query::All` is what a boundary constraining neither
891        // types nor tags would produce, and an empty `EVENT_TYPES` is already
892        // a compile error.
893        None => println!("      the whole log"),
894    }
895
896    Ok(())
897}
898
899/// The position of the last event in the store, or 0 if there is none.
900async fn head(events: &SqliteEventStore) -> Result<u64> {
901    Ok(events.head().await?.map_or(0, SequencePosition::get))
902}
903
904/// Prints every event in the store, in the order the store assigned.
905async fn print_log(events: &SqliteEventStore) -> Result<()> {
906    let log = collect(events.read(&Query::all(), ReadOptions::new())).await?;
907
908    for event in log {
909        println!(
910            "   {:>3}  {:<15} {:?}",
911            event.position.get(),
912            event.event_type().as_str(),
913            event.tags()
914        );
915    }
916
917    Ok(())
918}
919
920// ---------------------------------------------------------------------------
921// The file this run owns
922// ---------------------------------------------------------------------------
923
924/// Where this run's database lives.
925///
926/// Under the process id, so a `cargo run` and the test that spawns the binary
927/// never meet on one file.
928fn database_path() -> PathBuf {
929    std::env::temp_dir().join(format!("happenstance-handles-{}.db", std::process::id()))
930}
931
932/// Removes the database and the two files WAL mode keeps beside it.
933///
934/// Deleting only the `.db` and leaving `-wal` behind is how a "fresh" run
935/// starts on the tail of the last one.
936fn remove_database(path: &Path) {
937    for suffix in ["", "-wal", "-shm"] {
938        let mut name = path.as_os_str().to_owned();
939        name.push(suffix);
940        drop(std::fs::remove_file(PathBuf::from(name)));
941    }
942}