1#![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
18const 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#[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 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 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#[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 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 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#[derive(Debug, Serialize, Deserialize)]
173enum Enrolment {
174 CourseDefined { course: CourseId, capacity: u32 },
176 StudentSubscribed {
178 course: CourseId,
179 student: StudentId,
180 },
181 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#[derive(Debug, thiserror::Error)]
235enum Refusal {
236 #[error("course {course} is already defined")]
238 AlreadyDefined {
239 course: String,
241 },
242 #[error("course {course} does not exist")]
244 NotDefined {
245 course: String,
247 },
248 #[error("student {student} is already subscribed to {course}")]
250 AlreadySubscribed {
251 student: String,
253 course: String,
255 },
256 #[error("course {course} is full ({taken}/{capacity})")]
258 Full {
259 course: String,
261 taken: u32,
263 capacity: u32,
265 },
266 #[error("student {student} is not subscribed to {course}")]
268 NotSubscribed {
269 student: String,
271 course: String,
273 },
274}
275
276#[derive(Debug, Clone)]
285struct CourseDefinition {
286 scope: Tags,
287 defined: bool,
288}
289
290impl CourseDefinition {
291 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#[derive(Debug, Clone)]
321struct Seats {
322 scope: Tags,
323 capacity: Option<u32>,
324 taken: u32,
325}
326
327impl Seats {
328 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#[derive(Debug, Clone)]
361struct StudentSeat {
362 scope: Tags,
363 subscribed: bool,
364}
365
366impl StudentSeat {
367 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 Enrolment::CourseDefined { .. } => {}
392 }
393 }
394}
395
396async 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
426async 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
473async 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
501fn rejected(err: CommandError<MemoryStoreError, Refusal>) -> anyhow::Error {
508 match err {
509 CommandError::Refused(refusal) => refusal.into(),
510 other => other.into(),
511 }
512}