Skip to main content

course_subscriptions/
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// `crates/happenstance/src/lib.rs:10`.
5#![doc = include_str!("overview.md")]
6#![allow(clippy::print_stdout)]
7
8use core::num::NonZeroU32;
9
10use anyhow::{Result, bail};
11use happenstance::bytes::Bytes;
12use happenstance::{
13    Codec, CodecError, CommandError, DecisionModel, DomainEvent, EventType, InvalidTag,
14    MemoryEventStore, MemoryStoreError, Retry, Tag, Tags, commit,
15};
16use serde::{Deserialize, Serialize};
17
18/// How many times a command may be attempted before it gives up.
19///
20/// Spelled at every call site rather than defaulted inside the loop, because a
21/// loop whose only exit is success is a hang with better manners. This run is
22/// uncontended — one process, one writer — so every commit reports a single
23/// attempt and the bound is never spent: a visible bound on an unexercised
24/// path. Built at compile time: `attempts` is `const fn`, so there is no
25/// fallible conversion to spell at the call site.
26const ATTEMPTS: NonZeroU32 = NonZeroU32::new(3).unwrap();
27
28#[tokio::main(flavor = "current_thread")]
29async fn main() -> Result<()> {
30    let store = MemoryEventStore::new();
31
32    println!("== defining course c1 with capacity 2 ==");
33    define_course(&store, "c1", 2).await?;
34    println!("   defined");
35
36    println!("\n== defining course c1 again ==");
37    match define_course(&store, "c1", 5).await {
38        Ok(()) => bail!("a duplicate course definition should have been rejected"),
39        Err(err) => println!("   rejected: {err}"),
40    }
41
42    println!("\n== subscribing s1 and s2 ==");
43    subscribe(&store, "c1", "s1").await?;
44    subscribe(&store, "c1", "s2").await?;
45    println!("   both subscribed");
46
47    println!("\n== subscribing s1 again ==");
48    match subscribe(&store, "c1", "s1").await {
49        Ok(()) => bail!("a duplicate subscription should have been rejected"),
50        Err(err) => println!("   rejected: {err}"),
51    }
52
53    println!("\n== subscribing s3, which would exceed capacity ==");
54    match subscribe(&store, "c1", "s3").await {
55        Ok(()) => bail!("exceeding capacity should have been rejected"),
56        Err(err) => println!("   rejected: {err}"),
57    }
58
59    println!("\n== s1 unsubscribes, freeing a seat ==");
60    unsubscribe(&store, "c1", "s1").await?;
61    subscribe(&store, "c1", "s3").await?;
62    println!("   s3 subscribed into the freed seat");
63
64    println!("\n== final log ==");
65    for event in store.snapshot() {
66        println!(
67            "   {:>3}  {:<22} {:?}",
68            event.position.get(),
69            event.event_type().as_str(),
70            event.tags()
71        );
72    }
73
74    Ok(())
75}
76
77// ---------------------------------------------------------------------------
78// Identity, validated once at the edge
79// ---------------------------------------------------------------------------
80
81/// A course identifier, validated once into the tag its events carry.
82///
83/// `DomainEvent::tags` is infallible and `Tags` has no infallible constructor —
84/// `Tag::key_value` is the only way in and it can refuse. So a domain type
85/// whose tags come from runtime values has to *hold* the validated form rather
86/// than rebuild it on every call, and the `?` is paid here, at the edge, where
87/// the handler is already writing one. That is the resolution `DecisionModel`
88/// makes for a model's own scope, applied to the event.
89#[derive(Debug, Clone, Serialize, Deserialize)]
90#[serde(try_from = "String", into = "String")]
91struct CourseId {
92    id: String,
93    tag: Tag,
94}
95
96impl CourseId {
97    /// Validates `id` into the tag every event for this course is written with.
98    fn new(id: &str) -> Result<Self, InvalidTag> {
99        Ok(Self {
100            id: id.to_owned(),
101            tag: Tag::key_value("course", id)?,
102        })
103    }
104
105    /// The identifier as the application wrote it.
106    fn as_str(&self) -> &str {
107        &self.id
108    }
109}
110
111impl TryFrom<String> for CourseId {
112    type Error = InvalidTag;
113
114    fn try_from(id: String) -> Result<Self, InvalidTag> {
115        Self::new(&id)
116    }
117}
118
119impl From<CourseId> for String {
120    fn from(course: CourseId) -> Self {
121        course.id
122    }
123}
124
125/// A student identifier, validated the same way and for the same reason.
126#[derive(Debug, Clone, Serialize, Deserialize)]
127#[serde(try_from = "String", into = "String")]
128struct StudentId {
129    id: String,
130    tag: Tag,
131}
132
133impl StudentId {
134    /// Validates `id` into the tag every event for this student carries.
135    fn new(id: &str) -> Result<Self, InvalidTag> {
136        Ok(Self {
137            id: id.to_owned(),
138            tag: Tag::key_value("student", id)?,
139        })
140    }
141
142    /// The identifier as the application wrote it.
143    fn as_str(&self) -> &str {
144        &self.id
145    }
146}
147
148impl TryFrom<String> for StudentId {
149    type Error = InvalidTag;
150
151    fn try_from(id: String) -> Result<Self, InvalidTag> {
152        Self::new(&id)
153    }
154}
155
156impl From<StudentId> for String {
157    fn from(student: StudentId) -> Self {
158        student.id
159    }
160}
161
162// ---------------------------------------------------------------------------
163// The domain: one enum, named once
164// ---------------------------------------------------------------------------
165
166/// Everything that can happen to an enrolment.
167///
168/// One enum, so a query and a fold cannot name different sets: the query is
169/// derived from `EVENT_TYPES` below plus the model's scope, and every fold is a
170/// `match` over these variants with no wildcard arm. A fourth variant is a
171/// compile error in every decision model that has not said what it means.
172#[derive(Debug, Serialize, Deserialize)]
173enum Enrolment {
174    /// A course exists, and how many seats it has.
175    CourseDefined { course: CourseId, capacity: u32 },
176    /// A student holds one of those seats.
177    StudentSubscribed {
178        course: CourseId,
179        student: StudentId,
180    },
181    /// A student gave one back.
182    StudentUnsubscribed {
183        course: CourseId,
184        student: StudentId,
185    },
186}
187
188const COURSE_DEFINED: EventType = EventType::from_static("CourseDefined");
189const STUDENT_SUBSCRIBED: EventType = EventType::from_static("StudentSubscribed");
190const STUDENT_UNSUBSCRIBED: EventType = EventType::from_static("StudentUnsubscribed");
191
192impl DomainEvent for Enrolment {
193    const EVENT_TYPES: &'static [EventType] =
194        &[COURSE_DEFINED, STUDENT_SUBSCRIBED, STUDENT_UNSUBSCRIBED];
195
196    fn event_type(&self) -> EventType {
197        match self {
198            Self::CourseDefined { .. } => COURSE_DEFINED,
199            Self::StudentSubscribed { .. } => STUDENT_SUBSCRIBED,
200            Self::StudentUnsubscribed { .. } => STUDENT_UNSUBSCRIBED,
201        }
202    }
203
204    fn tags(&self) -> Tags {
205        match self {
206            Self::CourseDefined { course, .. } => [course.tag.clone()].into_iter().collect(),
207            Self::StudentSubscribed { course, student }
208            | Self::StudentUnsubscribed { course, student } => {
209                [course.tag.clone(), student.tag.clone()]
210                    .into_iter()
211                    .collect()
212            }
213        }
214    }
215
216    fn encode<C: Codec>(&self, codec: &C) -> Result<Bytes, CodecError> {
217        codec.encode(self)
218    }
219
220    fn decode<C: Codec>(
221        codec: &C,
222        _event_type: &EventType,
223        data: &Bytes,
224    ) -> Result<Self, CodecError> {
225        codec.decode(data)
226    }
227}
228
229/// Why a decision refused.
230///
231/// Every variant carries the value the transcript prints — `course c1 is full
232/// (2/2)`, never `capacity exceeded` — so a reader can act on the refusal where
233/// it is printed instead of opening a second document to learn what happened.
234#[derive(Debug, thiserror::Error)]
235enum Refusal {
236    /// Invariant 1: a course may not be defined twice.
237    #[error("course {course} is already defined")]
238    AlreadyDefined {
239        /// The course that already exists.
240        course: String,
241    },
242    /// A course has to exist before anyone can hold a seat in it.
243    #[error("course {course} does not exist")]
244    NotDefined {
245        /// The course nobody has defined.
246        course: String,
247    },
248    /// Invariant 3: a student may not subscribe to the same course twice.
249    #[error("student {student} is already subscribed to {course}")]
250    AlreadySubscribed {
251        /// The student already holding a seat.
252        student: String,
253        /// The course they hold it in.
254        course: String,
255    },
256    /// Invariant 2: a course may not exceed its capacity.
257    #[error("course {course} is full ({taken}/{capacity})")]
258    Full {
259        /// The full course.
260        course: String,
261        /// Seats currently held.
262        taken: u32,
263        /// Seats the course was defined with.
264        capacity: u32,
265    },
266    /// A seat cannot be released by someone who is not holding one.
267    #[error("student {student} is not subscribed to {course}")]
268    NotSubscribed {
269        /// The student who holds no seat.
270        student: String,
271        /// The course they are not in.
272        course: String,
273    },
274}
275
276// ---------------------------------------------------------------------------
277// The decision models: one per consistency concern
278// ---------------------------------------------------------------------------
279
280/// Whether this course has been defined.
281///
282/// `define_course`'s whole boundary. The query it derives is every event tagged
283/// with this course — the smallest set that could invalidate the decision.
284#[derive(Debug, Clone)]
285struct CourseDefinition {
286    scope: Tags,
287    defined: bool,
288}
289
290impl CourseDefinition {
291    /// Validates the scope once, here, where the caller already writes a `?`.
292    fn new(course: &CourseId) -> Result<Self, InvalidTag> {
293        Ok(Self {
294            scope: Tags::from_pairs([("course", course.as_str())])?,
295            defined: false,
296        })
297    }
298}
299
300impl DecisionModel for CourseDefinition {
301    type Event = Enrolment;
302
303    fn scope(&self) -> &Tags {
304        &self.scope
305    }
306
307    fn apply(&mut self, event: Self::Event) {
308        match event {
309            Enrolment::CourseDefined { .. } => self.defined = true,
310            Enrolment::StudentSubscribed { .. } | Enrolment::StudentUnsubscribed { .. } => {}
311        }
312    }
313}
314
315/// The course's capacity, and everyone currently holding a seat.
316///
317/// The capacity arrives by *decoding* the `CourseDefined` variant, not by
318/// scraping the payload's bytes: a course with no capacity is a decode failure
319/// naming its position, never a course with capacity zero.
320#[derive(Debug, Clone)]
321struct Seats {
322    scope: Tags,
323    capacity: Option<u32>,
324    taken: u32,
325}
326
327impl Seats {
328    /// Validates the scope once, here, where the caller already writes a `?`.
329    fn new(course: &CourseId) -> Result<Self, InvalidTag> {
330        Ok(Self {
331            scope: Tags::from_pairs([("course", course.as_str())])?,
332            capacity: None,
333            taken: 0,
334        })
335    }
336}
337
338impl DecisionModel for Seats {
339    type Event = Enrolment;
340
341    fn scope(&self) -> &Tags {
342        &self.scope
343    }
344
345    fn apply(&mut self, event: Self::Event) {
346        match event {
347            Enrolment::CourseDefined { capacity, .. } => self.capacity = Some(capacity),
348            Enrolment::StudentSubscribed { .. } => self.taken += 1,
349            Enrolment::StudentUnsubscribed { .. } => self.taken = self.taken.saturating_sub(1),
350        }
351    }
352}
353
354/// One student's own history with one course.
355///
356/// The second consistency concern in `subscribe`, and the whole of
357/// `unsubscribe` — which is the demonstration that a decision model is a
358/// reusable value rather than a per-handler blob. Its scope carries both tags,
359/// so the query it derives nominates this student's events and nobody else's.
360#[derive(Debug, Clone)]
361struct StudentSeat {
362    scope: Tags,
363    subscribed: bool,
364}
365
366impl StudentSeat {
367    /// Validates the scope once, here, where the caller already writes a `?`.
368    fn new(course: &CourseId, student: &StudentId) -> Result<Self, InvalidTag> {
369        Ok(Self {
370            scope: Tags::from_pairs([("course", course.as_str()), ("student", student.as_str())])?,
371            subscribed: false,
372        })
373    }
374}
375
376impl DecisionModel for StudentSeat {
377    type Event = Enrolment;
378
379    fn scope(&self) -> &Tags {
380        &self.scope
381    }
382
383    fn apply(&mut self, event: Self::Event) {
384        match event {
385            Enrolment::StudentSubscribed { .. } => self.subscribed = true,
386            Enrolment::StudentUnsubscribed { .. } => self.subscribed = false,
387            // A course definition carries no `student` tag, so this model's
388            // query never nominates one. The arm exists because the fold is
389            // exhaustive over the enum, and that exhaustiveness is the whole
390            // guarantee.
391            Enrolment::CourseDefined { .. } => {}
392        }
393    }
394}
395
396// ---------------------------------------------------------------------------
397// The three command handlers
398// ---------------------------------------------------------------------------
399
400/// Defines a course, rejecting a second definition of the same one.
401async fn define_course(store: &MemoryEventStore, course: &str, capacity: u32) -> Result<()> {
402    let course = CourseId::new(course)?;
403    let boundary = CourseDefinition::new(&course)?;
404
405    commit(
406        store,
407        boundary,
408        Retry::attempts(ATTEMPTS),
409        |defined: &CourseDefinition| {
410            if defined.defined {
411                return Err(Refusal::AlreadyDefined {
412                    course: course.id.clone(),
413                });
414            }
415            Ok(vec![Enrolment::CourseDefined {
416                course: course.clone(),
417                capacity,
418            }])
419        },
420    )
421    .await
422    .map(|_| ())
423    .map_err(rejected)
424}
425
426/// Subscribes a student, enforcing capacity and no-double-subscription together.
427///
428/// This is the case that motivates DCB, and it is the case that motivates
429/// composition. *The course's capacity and everyone holding a seat* is one
430/// consistency concern; *this student's own history* is another. The tuple
431/// below is both of them, OR'd into one query and checked by one append
432/// condition — with no macro invocation and no builder in the way. A tuple of
433/// decision models is a boundary.
434async fn subscribe(store: &MemoryEventStore, course: &str, student: &str) -> Result<()> {
435    let course = CourseId::new(course)?;
436    let student = StudentId::new(student)?;
437    let boundary = (Seats::new(&course)?, StudentSeat::new(&course, &student)?);
438
439    commit(
440        store,
441        boundary,
442        Retry::attempts(ATTEMPTS),
443        |(seats, seat): &(Seats, StudentSeat)| {
444            let Some(capacity) = seats.capacity else {
445                return Err(Refusal::NotDefined {
446                    course: course.id.clone(),
447                });
448            };
449            if seat.subscribed {
450                return Err(Refusal::AlreadySubscribed {
451                    student: student.id.clone(),
452                    course: course.id.clone(),
453                });
454            }
455            if seats.taken >= capacity {
456                return Err(Refusal::Full {
457                    course: course.id.clone(),
458                    taken: seats.taken,
459                    capacity,
460                });
461            }
462            Ok(vec![Enrolment::StudentSubscribed {
463                course: course.clone(),
464                student: student.clone(),
465            }])
466        },
467    )
468    .await
469    .map(|_| ())
470    .map_err(rejected)
471}
472
473/// Releases a student's seat.
474async fn unsubscribe(store: &MemoryEventStore, course: &str, student: &str) -> Result<()> {
475    let course = CourseId::new(course)?;
476    let student = StudentId::new(student)?;
477    let boundary = StudentSeat::new(&course, &student)?;
478
479    commit(
480        store,
481        boundary,
482        Retry::attempts(ATTEMPTS),
483        |seat: &StudentSeat| {
484            if !seat.subscribed {
485                return Err(Refusal::NotSubscribed {
486                    student: student.id.clone(),
487                    course: course.id.clone(),
488                });
489            }
490            Ok(vec![Enrolment::StudentUnsubscribed {
491                course: course.clone(),
492                student: student.clone(),
493            }])
494        },
495    )
496    .await
497    .map(|_| ())
498    .map_err(rejected)
499}
500
501/// Renders a command failure as the message the transcript prints.
502///
503/// `CommandError::Refused` carries the handler's *own* refusal, and that is
504/// what a reader must see: `CommandError`'s own `Display` says "the decision
505/// refused", which is a category rather than a value. Every other variant is a
506/// real failure and travels out with its source chain intact.
507fn rejected(err: CommandError<MemoryStoreError, Refusal>) -> anyhow::Error {
508    match err {
509        CommandError::Refused(refusal) => refusal.into(),
510        other => other.into(),
511    }
512}