Skip to main content

EventType

Struct EventType 

Source
pub struct EventType(/* private fields */);
Expand description

The identifier a store filters on: CourseDefined, StudentSubscribed, and so on.

Backed by Cow<'static, str> so that one type expresses both identifiers written in the source and baked into the binary, and identifiers that arrived from a peer at run time and had to be allocated. Ingest needs the second; a codec registry wants the first; a newtype over &'static str alone could only express the first, which is why it lost.

§Examples

use happenstance_core::EventType;

let ty = EventType::new("StudentSubscribed")?;
assert_eq!(ty.as_str(), "StudentSubscribed");

Constructed in a const, it is validated by the compiler and allocates nothing:

use happenstance_core::EventType;

const COURSE_DEFINED: EventType = EventType::from_static("CourseDefined");
assert_eq!(COURSE_DEFINED.as_str(), "CourseDefined");

Implementations§

Source§

impl EventType

Source

pub fn new(value: impl Into<String>) -> Result<Self, InvalidEventType>

Creates an event type.

§Errors

Returns InvalidEventType if the value is empty, longer than MAX_EVENT_TYPE_LEN bytes, contains a character in Unicode general category Cc, or contains one of the nine explicit bidirectional formatting controls.

Source

pub const fn from_static(value: &'static str) -> Self

Creates an event type from a string literal, validating at compile time.

Enforces exactly the rules new enforces — one function checks both — so an EventType is always a validated value, with some of that validation having happened before the program ran.

§Panics

Panics if the value would be rejected by new. Where that panic surfaces depends on the call site, and the difference is sharp enough to be worth stating:

Call siteWhen the invalid value is caught
a free constcargo check, as error[E0080]
an associated const that is read somewherecargo build
an associated const that is never readnever
a let bindingat run time, as a panic

The third row is the one to design around: an associated const is evaluated lazily, so an invalid one that nothing reads survives check, clippy, build and test. Prefer a free const for anything whose validity you want the compiler to guarantee.

An invalid value at a free const site is a compile error:

ⓘ
use happenstance_core::EventType;

const EMPTY: EventType = EventType::from_static("");

Spelled bare compile_fail rather than compile_fail,E0080: rustdoc on 1.97.1 silently ignores an error-code annotation it cannot match, so the stricter-looking spelling is the weaker check. It is also deliberately weaker than a trybuild snapshot — it does not pin the diagnostic — and ADR-0015 records that phase 6 owns the trybuild dependency decision.

Examples found in repository?
examples/course-subscriptions/src/main.rs (line 188)
188const COURSE_DEFINED: EventType = EventType::from_static("CourseDefined");
189const STUDENT_SUBSCRIBED: EventType = EventType::from_static("StudentSubscribed");
190const STUDENT_UNSUBSCRIBED: EventType = EventType::from_static("StudentUnsubscribed");
More examples
Hide additional examples
examples/handles-and-quotas/src/main.rs (line 387)
387const HANDLE_CLAIMED: EventType = EventType::from_static("HandleClaimed");
388const HANDLE_RELEASED: EventType = EventType::from_static("HandleReleased");
389const PLAN_CHANGED: EventType = EventType::from_static("PlanChanged");
examples/rebuilding-read-models/src/main.rs (line 653)
653const STOCK_RECEIVED: EventType = EventType::from_static("StockReceived");
654/// See [`STOCK_RECEIVED`].
655const ORDER_PLACED: EventType = EventType::from_static("OrderPlaced");
656/// See [`STOCK_RECEIVED`].
657const ORDER_DISPATCHED: EventType = EventType::from_static("OrderDispatched");
658/// See [`STOCK_RECEIVED`].
659const ORDER_CANCELLED: EventType = EventType::from_static("OrderCancelled");
examples/transfers-on-sqlite/src/main.rs (line 283)
283const ACCOUNT_OPENED: EventType = EventType::from_static("AccountOpened");
284const DEPOSITED: EventType = EventType::from_static("Deposited");
285const WITHDRAWN: EventType = EventType::from_static("Withdrawn");
examples/telemetry-across-codecs/src/main.rs (line 335)
335const DEVICE_REGISTERED: EventType = EventType::from_static("DeviceRegistered");
336/// See [`DEVICE_REGISTERED`].
337const FIRMWARE_UPGRADED: EventType = EventType::from_static("FirmwareUpgraded");
338/// The **v1** reading. Read-only: nothing writes this name any more.
339const TEMPERATURE_REPORTED: EventType = EventType::from_static("TemperatureReported");
340/// The **v2** reading, and what a reading written now carries.
341const TEMPERATURE_REPORTED_V2: EventType = EventType::from_static("TemperatureReportedV2");
examples/tickets-over-http/src/lib.rs (line 205)
205const SHOW_OPENED: EventType = EventType::from_static("ShowOpened");
206const SEAT_RESERVED: EventType = EventType::from_static("SeatReserved");
207const SEAT_RELEASED: EventType = EventType::from_static("SeatReleased");
Source

pub fn as_str(&self) -> &str

The event type as a string slice.

Examples found in repository?
examples/handles-and-quotas/src/main.rs (line 912)
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}
More examples
Hide additional examples
examples/transfers-on-sqlite/src/main.rs (line 627)
620async fn print_log(events: &SqliteEventStore) -> Result<()> {
621    let log = collect(events.read(&Query::all(), ReadOptions::new())).await?;
622
623    for event in log {
624        println!(
625            "   {:>3}  {:<15} {:?}",
626            event.position.get(),
627            event.event_type().as_str(),
628            event.tags()
629        );
630    }
631
632    Ok(())
633}
examples/rebuilding-read-models/src/main.rs (line 1603)
1595async fn print_log(events: &SqliteEventStore) -> Result<()> {
1596    let log = collect(events.read(&Query::all(), ReadOptions::new())).await?;
1597
1598    for event in log {
1599        writeln!(
1600            io::stdout().lock(),
1601            "   {:>3}  {:<16} {:?}",
1602            event.position.get(),
1603            event.event_type().as_str(),
1604            event.tags()
1605        )?;
1606    }
1607
1608    Ok(())
1609}
examples/telemetry-across-codecs/src/main.rs (line 182)
171async fn one_log_two_encodings(events: &SqliteEventStore) -> Result<()> {
172    println!("\n== one log, two encodings ==");
173
174    let log = collect(events.read(&Query::all(), ReadOptions::new())).await?;
175    let mut seen = Vec::new();
176
177    for event in &log {
178        let codec = framed_codec(event).unwrap_or_else(|| "unframed".to_owned());
179        println!(
180            "   {:>3}  {:<22} {:<8} {} bytes",
181            event.position.get(),
182            event.event_type().as_str(),
183            codec,
184            event.event.data().len()
185        );
186        if !seen.contains(&codec) {
187            seen.push(codec);
188        }
189    }
190
191    if seen.len() < 2 {
192        bail!("the log holds only {seen:?}, so there are no two encodings to read across");
193    }
194    println!("   two encodings and two temperature types, in one store, side by side");
195
196    Ok(())
197}
198
199/// Folds the whole device history with one codec in hand.
200///
201/// The section the other three exist for. `Json` is the only codec named at
202/// this call site; the postcard readings arrive decoded anyway, because the
203/// framing region says what they were written with. The v1 readings arrive
204/// *upcast*, because `Telemetry::decode` was handed their event type and knew
205/// what to do with it.
206async fn one_fold_reads_both(events: &SqliteEventStore) -> Result<()> {
207    println!("\n== one fold reads both ==");
208
209    let device = DeviceId::new(DEVICE)?;
210    let mut readings = Readings::new(&device)?;
211
212    let query = readings.query()?;
213    let (found, _) = read_decision_model(events, &query).await?;
214    for event in &found {
215        readings.absorb(event, &Json)?;
216    }
217
218    println!(
219        "   the derived query nominated {} event(s), and one codec was named here: Json",
220        found.len()
221    );
222    println!(
223        "   firmware:   {}",
224        readings.firmware.as_deref().unwrap_or("unknown")
225    );
226    println!("   readings:   {:?}", readings.millidegrees);
227
228    // The upcast is the assertion. 21 degrees was written by a binary that had
229    // never heard of a thousandth, and it is 21000 here without anything in
230    // this function converting it.
231    if !readings.millidegrees.contains(&(21 * PER_DEGREE)) {
232        bail!(
233            "the first JSON reading did not arrive upcast: {:?}",
234            readings.millidegrees
235        );
236    }
237    println!(
238        "   21 whole degrees, written by a binary with no concept of a\n   \
239         thousandth, arrives as {} — the upcast is in `decode`, and the fold\n   \
240         below it has one temperature variant and no idea there were ever two",
241        21 * PER_DEGREE
242    );
243
244    Ok(())
245}
246
247// ---------------------------------------------------------------------------
248// Identity, validated once at the edge
249// ---------------------------------------------------------------------------
250
251/// A device, validated once into the tag its events carry.
252///
253/// The resolution the other examples reach, and for the same reason:
254/// `DomainEvent::tags` is infallible while `Tag::key_value` can refuse, so a
255/// domain type whose tags come from runtime values holds the validated form
256/// instead of rebuilding it on every call.
257#[derive(Debug, Clone, Serialize, Deserialize)]
258#[serde(try_from = "String", into = "String")]
259struct DeviceId {
260    /// The identifier as the application wrote it.
261    id: String,
262    /// The same value, validated into a tag.
263    tag: Tag,
264}
265
266impl DeviceId {
267    /// Validates `id` into the tag every event for this device is written with.
268    fn new(id: &str) -> Result<Self, InvalidTag> {
269        Ok(Self {
270            id: id.to_owned(),
271            tag: Tag::key_value("device", id)?,
272        })
273    }
274
275    /// The identifier as the application wrote it.
276    fn as_str(&self) -> &str {
277        &self.id
278    }
279}
280
281impl TryFrom<String> for DeviceId {
282    type Error = InvalidTag;
283
284    fn try_from(id: String) -> Result<Self, InvalidTag> {
285        Self::new(&id)
286    }
287}
288
289impl From<DeviceId> for String {
290    fn from(device: DeviceId) -> Self {
291        device.id
292    }
293}
294
295// ---------------------------------------------------------------------------
296// The domain, in the shape the old binary had
297// ---------------------------------------------------------------------------
298
299/// The event set the previous version of this application shipped.
300///
301/// **Kept rather than deleted, and it is not dead code.** It is the wire
302/// format of every reading written before the upgrade, and `Telemetry::decode`
303/// still reaches for it — an upcast is "decode with the type that wrote these
304/// bytes, then map forward", and the type that wrote them has to still exist
305/// for that sentence to be executable.
306///
307/// It writes two event types. `Telemetry` declares four, because it must
308/// nominate these two as well as its own.
309#[derive(Debug, Serialize, Deserialize)]
310enum Legacy {
311    /// A device came online. The same shape the new version writes.
312    DeviceRegistered {
313        /// The device now known.
314        device: DeviceId,
315        /// What it was running.
316        firmware: String,
317    },
318    /// A reading, in whole degrees Celsius.
319    TemperatureReported {
320        /// Which device reported.
321        device: DeviceId,
322        /// The reading, in whole degrees.
323        celsius: i32,
324    },
325}
326
327/// The four names this log has ever carried, declared once.
328///
329/// Two of them mean the same *reading* at different schema versions, and that is
330/// the whole point of this example — so they are named rather than indexed.
331/// Indexing the declaration list gave two subscripts that differ by one
332/// character and mean "what is written now" and "what may still be read";
333/// `TEMPERATURE_REPORTED_V2` and `TEMPERATURE_REPORTED` cannot be confused by a
334/// reader, or reordered into a lie by an editor.
335const DEVICE_REGISTERED: EventType = EventType::from_static("DeviceRegistered");
336/// See [`DEVICE_REGISTERED`].
337const FIRMWARE_UPGRADED: EventType = EventType::from_static("FirmwareUpgraded");
338/// The **v1** reading. Read-only: nothing writes this name any more.
339const TEMPERATURE_REPORTED: EventType = EventType::from_static("TemperatureReported");
340/// The **v2** reading, and what a reading written now carries.
341const TEMPERATURE_REPORTED_V2: EventType = EventType::from_static("TemperatureReportedV2");
342
343impl DomainEvent for Legacy {
344    const EVENT_TYPES: &'static [EventType] = &[DEVICE_REGISTERED, TEMPERATURE_REPORTED];
345
346    fn event_type(&self) -> EventType {
347        match self {
348            Self::DeviceRegistered { .. } => DEVICE_REGISTERED,
349            Self::TemperatureReported { .. } => TEMPERATURE_REPORTED,
350        }
351    }
352
353    fn tags(&self) -> Tags {
354        match self {
355            Self::DeviceRegistered { device, .. } | Self::TemperatureReported { device, .. } => {
356                [device.tag.clone()].into_iter().collect()
357            }
358        }
359    }
360
361    fn encode<C: Codec>(&self, codec: &C) -> Result<Bytes, CodecError> {
362        codec.encode(self)
363    }
364
365    fn decode<C: Codec>(
366        codec: &C,
367        _event_type: &EventType,
368        data: &Bytes,
369    ) -> Result<Self, CodecError> {
370        codec.decode(data)
371    }
372}
373
374// ---------------------------------------------------------------------------
375// The domain, as it is now
376// ---------------------------------------------------------------------------
377
378/// Everything that can happen to a device, in this version's vocabulary.
379///
380/// One temperature variant, in thousandths. The fold does not know there were
381/// ever two shapes, and that is the whole reason the upcast lives in `decode`
382/// rather than in every `apply` that has to deal with a reading.
383#[derive(Debug, Serialize, Deserialize)]
384enum Telemetry {
385    /// A device came online.
386    DeviceRegistered {
387        /// The device now known.
388        device: DeviceId,
389        /// What it was running.
390        firmware: String,
391    },
392    /// A device's firmware changed.
393    FirmwareUpgraded {
394        /// The device upgraded.
395        device: DeviceId,
396        /// What it is running now.
397        firmware: String,
398    },
399    /// A reading, in thousandths of a degree.
400    TemperatureReported {
401        /// Which device reported.
402        device: DeviceId,
403        /// The reading, in thousandths of a degree.
404        millidegrees: i32,
405    },
406}
407
408impl DomainEvent for Telemetry {
409    /// Four names for three variants.
410    ///
411    /// `TemperatureReported` is the **old** name and nothing writes it any
412    /// more. It is declared because the query is derived from this list, so
413    /// removing it would stop every boundary nominating the readings written
414    /// before the upgrade — silently, and with no test, lint or conformance
415    /// rule that has an opinion. The list is where a log's past is kept alive.
416    const EVENT_TYPES: &'static [EventType] = &[
417        DEVICE_REGISTERED,
418        FIRMWARE_UPGRADED,
419        TEMPERATURE_REPORTED,
420        TEMPERATURE_REPORTED_V2,
421    ];
422
423    fn event_type(&self) -> EventType {
424        match self {
425            Self::DeviceRegistered { .. } => DEVICE_REGISTERED,
426            Self::FirmwareUpgraded { .. } => FIRMWARE_UPGRADED,
427            // The v2 name, never the v1 one. A reading written now is a v2
428            // reading; the v1 name is read-only. This used to be a subscript
429            // into the list above, carried by a comment saying "index 3, never
430            // index 2" — the comment a named constant makes unnecessary.
431            Self::TemperatureReported { .. } => TEMPERATURE_REPORTED_V2,
432        }
433    }
434
435    fn tags(&self) -> Tags {
436        match self {
437            Self::DeviceRegistered { device, .. }
438            | Self::FirmwareUpgraded { device, .. }
439            | Self::TemperatureReported { device, .. } => {
440                [device.tag.clone()].into_iter().collect()
441            }
442        }
443    }
444
445    fn encode<C: Codec>(&self, codec: &C) -> Result<Bytes, CodecError> {
446        codec.encode(self)
447    }
448
449    /// Decodes a payload written for `event_type`, upcasting the old shape.
450    ///
451    /// **The one place in this workspace where that parameter is used.** The
452    /// codec tag in the framing region has already decided *how* these bytes
453    /// were encoded; what it cannot decide is what they meant, because a v1
454    /// reading deserialises perfectly into a number that is a thousand times
455    /// too small. Only the event type distinguishes them.
456    fn decode<C: Codec>(
457        codec: &C,
458        event_type: &EventType,
459        data: &Bytes,
460    ) -> Result<Self, CodecError> {
461        // The named v1 constant, not the literal `"TemperatureReported"`: one
462        // declaration, so there is no second spelling to get wrong.
463        if *event_type == TEMPERATURE_REPORTED {
464            return Ok(upcast(codec.decode::<Legacy>(data)?));
465        }
466
467        codec.decode(data)
468    }
469}
470
471/// Maps an event written by the previous version into this one's vocabulary.
472///
473/// Total, and deliberately so: an upcast that can fail is a log that can stop
474/// being readable, and there is nothing a caller could do about it at the
475/// moment it happens. Whole degrees multiply into thousandths exactly, so the
476/// conversion loses nothing — `i32` covers the plausible range this
477/// application accepts several hundred times over.
478fn upcast(old: Legacy) -> Telemetry {
479    match old {
480        Legacy::DeviceRegistered { device, firmware } => {
481            Telemetry::DeviceRegistered { device, firmware }
482        }
483        Legacy::TemperatureReported { device, celsius } => Telemetry::TemperatureReported {
484            device,
485            millidegrees: celsius.saturating_mul(PER_DEGREE),
486        },
487    }
488}
489
490/// Why a decision refused.
491///
492/// Every variant carries the value the transcript prints — `900000 is outside
493/// -60000..=150000` and never `invalid reading` — so a reader can act on the
494/// refusal where it is printed.
495#[derive(Debug, thiserror::Error)]
496enum Refusal {
497    /// Nothing can be reported for a device nobody registered.
498    #[error("device {device} is not registered")]
499    NotRegistered {
500        /// The unknown device.
501        device: String,
502    },
503    /// A device registers once.
504    #[error("device {device} is already registered")]
505    AlreadyRegistered {
506        /// The device already known.
507        device: String,
508    },
509    /// A reading outside the range this application accepts.
510    #[error("{millidegrees} is outside {MIN_MILLIDEGREES}..={MAX_MILLIDEGREES}")]
511    Implausible {
512        /// The reading that was refused.
513        millidegrees: i32,
514    },
515}
516
517// ---------------------------------------------------------------------------
518// The decision models
519// ---------------------------------------------------------------------------
520
521/// One device's history, as the old binary saw it.
522///
523/// It exists to write the old log honestly. Its query is derived from
524/// `Legacy::EVENT_TYPES`, which is the two names that version knew — which is
525/// exactly the boundary the old binary had, and exactly why the new one has to
526/// declare four.
527#[derive(Debug, Clone)]
528struct LegacyDevice {
529    /// The tags every event inside this boundary carries.
530    scope: Tags,
531    /// Whether the device has been registered.
532    registered: bool,
533}
534
535impl LegacyDevice {
536    /// Validates the scope once, here, where the caller already writes a `?`.
537    fn new(device: &DeviceId) -> Result<Self, InvalidTag> {
538        Ok(Self {
539            scope: Tags::from_pairs([("device", device.as_str())])?,
540            registered: false,
541        })
542    }
543}
544
545impl DecisionModel for LegacyDevice {
546    type Event = Legacy;
547
548    fn scope(&self) -> &Tags {
549        &self.scope
550    }
551
552    fn apply(&mut self, event: Self::Event) {
553        match event {
554            Legacy::DeviceRegistered { .. } => self.registered = true,
555            // A reading changes nothing this model decides on. The arm exists
556            // because the fold is exhaustive over the enum, and that
557            // exhaustiveness is the whole guarantee.
558            Legacy::TemperatureReported { .. } => {}
559        }
560    }
561}
562
563/// One device's history, in this version's vocabulary.
564///
565/// Its `millidegrees` holds every reading the boundary nominated, from both
566/// eras, in one unit. There is no branch in `apply` that knows about the
567/// upgrade, because by the time an event reaches `apply` it has already been
568/// upcast.
569#[derive(Debug, Clone)]
570struct Readings {
571    /// The tags every event inside this boundary carries.
572    scope: Tags,
573    /// Whether the device has been registered.
574    registered: bool,
575    /// What it is running now, once anything has said.
576    firmware: Option<String>,
577    /// Every reading the boundary nominated, in thousandths of a degree.
578    millidegrees: Vec<i32>,
579}
580
581impl Readings {
582    /// Validates the scope once, here, where the caller already writes a `?`.
583    fn new(device: &DeviceId) -> Result<Self, InvalidTag> {
584        Ok(Self {
585            scope: Tags::from_pairs([("device", device.as_str())])?,
586            registered: false,
587            firmware: None,
588            millidegrees: Vec::new(),
589        })
590    }
591}
592
593impl DecisionModel for Readings {
594    type Event = Telemetry;
595
596    fn scope(&self) -> &Tags {
597        &self.scope
598    }
599
600    fn apply(&mut self, event: Self::Event) {
601        match event {
602            Telemetry::DeviceRegistered { firmware, .. } => {
603                self.registered = true;
604                self.firmware = Some(firmware);
605            }
606            Telemetry::FirmwareUpgraded { firmware, .. } => self.firmware = Some(firmware),
607            Telemetry::TemperatureReported { millidegrees, .. } => {
608                self.millidegrees.push(millidegrees);
609            }
610        }
611    }
612}
613
614// ---------------------------------------------------------------------------
615// The command handlers, in two generations
616// ---------------------------------------------------------------------------
617
618/// Registers a device, as the old binary did: `commit`, so JSON.
619async fn register(events: &SqliteEventStore, device: &str, firmware: &str) -> Result<()> {
620    let device = DeviceId::new(device)?;
621    let boundary = LegacyDevice::new(&device)?;
622
623    commit(
624        events,
625        boundary,
626        Retry::attempts(ATTEMPTS.try_into()?),
627        |known: &LegacyDevice| {
628            if known.registered {
629                return Err(Refusal::AlreadyRegistered {
630                    device: device.id.clone(),
631                });
632            }
633            Ok(vec![Legacy::DeviceRegistered {
634                device: device.clone(),
635                firmware: firmware.to_owned(),
636            }])
637        },
638    )
639    .await
640    .map(|_| ())
641    .map_err(rejected)
642}
643
644/// Reports a reading in whole degrees, as the old binary did: `commit`, so JSON.
645async fn report_celsius(events: &SqliteEventStore, device: &str, celsius: i32) -> Result<()> {
646    let device = DeviceId::new(device)?;
647    let boundary = LegacyDevice::new(&device)?;
648
649    commit(
650        events,
651        boundary,
652        Retry::attempts(ATTEMPTS.try_into()?),
653        |known: &LegacyDevice| {
654            if !known.registered {
655                return Err(Refusal::NotRegistered {
656                    device: device.id.clone(),
657                });
658            }
659            Ok(vec![Legacy::TemperatureReported {
660                device: device.clone(),
661                celsius,
662            }])
663        },
664    )
665    .await
666    .map(|_| ())
667    .map_err(rejected)
668}
669
670/// Records a firmware upgrade, in the new encoding.
671async fn upgrade_firmware(events: &SqliteEventStore, device: &str, firmware: &str) -> Result<()> {
672    let device = DeviceId::new(device)?;
673    let boundary = Readings::new(&device)?;
674
675    commit_with(
676        events,
677        boundary,
678        &Postcard,
679        Retry::attempts(ATTEMPTS.try_into()?),
680        |known: &Readings| {
681            if !known.registered {
682                return Err(Refusal::NotRegistered {
683                    device: device.id.clone(),
684                });
685            }
686            Ok(vec![Telemetry::FirmwareUpgraded {
687                device: device.clone(),
688                firmware: firmware.to_owned(),
689            }])
690        },
691    )
692    .await
693    .map(|_| ())
694    .map_err(rejected)
695}
696
697/// Reports a reading in thousandths, in the new encoding.
698///
699/// `commit_with` and an explicit `&Postcard`. It is the ungated entry point —
700/// `commit` is this function with `Json` already chosen — and naming the codec
701/// here is the only difference between this handler and the one above it that
702/// wrote JSON. The boundary it reads is a `Readings`, so this decision is taken
703/// against a fold that has already absorbed the *JSON* events written before
704/// the upgrade.
705async fn report_millidegrees(
706    events: &SqliteEventStore,
707    device: &str,
708    millidegrees: i32,
709) -> Result<()> {
710    let device = DeviceId::new(device)?;
711    let boundary = Readings::new(&device)?;
712
713    commit_with(
714        events,
715        boundary,
716        &Postcard,
717        Retry::attempts(ATTEMPTS.try_into()?),
718        |known: &Readings| {
719            if !known.registered {
720                return Err(Refusal::NotRegistered {
721                    device: device.id.clone(),
722                });
723            }
724            if !(MIN_MILLIDEGREES..=MAX_MILLIDEGREES).contains(&millidegrees) {
725                return Err(Refusal::Implausible { millidegrees });
726            }
727            Ok(vec![Telemetry::TemperatureReported {
728                device: device.clone(),
729                millidegrees,
730            }])
731        },
732    )
733    .await
734    .map(|_| ())
735    .map_err(rejected)
736}
737
738// ---------------------------------------------------------------------------
739// Reading
740// ---------------------------------------------------------------------------
741
742/// The codec tag an event was framed with, read out of its metadata.
743///
744/// **Nothing needs this.** The framing region is documented as opaque to
745/// stores and adapters, and the decode path resolves it without any caller
746/// looking; it is parsed here so the transcript can show that two encodings
747/// really are sitting in one log. Every step is fallible and none of it
748/// panics: an event written by something that does not frame its payloads at
749/// all is a legitimate thing to meet, and it renders as `unframed`.
750fn framed_codec(event: &SequencedEvent) -> Option<String> {
751    let metadata = event.event.metadata()?;
752    let after_magic = metadata.strip_prefix(b"hpst\x01")?;
753    let end = after_magic.iter().position(|byte| *byte == 0xFF)?;
754
755    core::str::from_utf8(&after_magic[..end])
756        .ok()
757        .map(str::to_owned)
758}
759
760/// Prints every event in the store, in the order the store assigned.
761async fn print_log(events: &SqliteEventStore) -> Result<()> {
762    let log = collect(events.read(&Query::all(), ReadOptions::new())).await?;
763
764    for event in log {
765        println!(
766            "   {:>3}  {:<22} {:?}",
767            event.position.get(),
768            event.event_type().as_str(),
769            event.tags()
770        );
771    }
772
773    Ok(())
774}
examples/course-subscriptions/src/main.rs (line 69)
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}

Trait Implementations§

Source§

impl AsRef<str> for EventType

Source§

fn as_ref(&self) -> &str

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Borrow<str> for EventType

Source§

fn borrow(&self) -> &str

Immutably borrows from an owned value. Read more
Source§

impl Clone for EventType

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 EventType

Source§

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

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

impl<'de> Deserialize<'de> for EventType

Available on crate feature serde only.
Source§

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

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for EventType

Source§

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

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

impl Eq for EventType

Source§

impl FromStr for EventType

Source§

type Err = InvalidEventType

The associated error which can be returned from parsing.
Source§

fn from_str(value: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
Source§

impl Hash for EventType

Source§

fn hash<H: Hasher>(&self, state: &mut H)

Feeds this value into the given Hasher. Read more
1.3.0 · Source§

fn hash_slice<H>(data: &[Self], state: &mut H)
where H: Hasher, Self: Sized,

Feeds a slice of this type into the given Hasher. Read more
Source§

impl Ord for EventType

Source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 (const: unstable) · Source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 (const: unstable) · Source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 (const: unstable) · Source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized,

Restrict a value to a certain interval. Read more
Source§

fn clamp_to<R>(self, range: R) -> Self
where Self: Sized, R: ClampBounds<Self>,

🔬This is a nightly-only experimental API. (clamp_to)
Restrict a value to a certain range. Read more
Source§

impl PartialEq for EventType

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 PartialOrd for EventType

Source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 (const: unstable) · Source§

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

Tests less than (for self and other) and is used by the < operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 (const: unstable) · Source§

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

Tests greater than or equal to (for self and other) and is used by the >= operator. Read more
Source§

impl Serialize for EventType

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 TryFrom<&str> for EventType

Source§

type Error = InvalidEventType

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

fn try_from(value: &str) -> Result<Self, Self::Error>

Performs the conversion.
Source§

impl TryFrom<String> for EventType

Source§

type Error = InvalidEventType

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

fn try_from(value: String) -> Result<Self, Self::Error>

Performs the conversion.

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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. 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.