Skip to main content

Event

Struct Event 

Source
pub struct Event { /* private fields */ }
Expand description

An event on its way into the store.

The payload is opaque: the contract layer never parses it. That keeps adapters free of domain knowledge and lets replication forward events byte-for-byte without deserialising them. Encoding and decoding are the typed layer’s job.

§Examples

use happenstance_core::{Event, Tags};

let event = Event::new("StudentSubscribed", &b"{\"student\":\"s1\"}"[..])?
    .with_tags(Tags::from_pairs([("course", "c1"), ("student", "s1")])?);

assert_eq!(event.event_type().as_str(), "StudentSubscribed");
assert_eq!(event.tags().len(), 2);
assert!(event.metadata().is_none());

Implementations§

Source§

impl Event

Source

pub fn new<T>( event_type: T, data: impl Into<Bytes>, ) -> Result<Self, InvalidEventType>

Creates an untagged event.

§Errors

Returns InvalidEventType if event_type fails EventType::new’s validation.

§Examples

The bound accepts a &str, which is validated here, and an already-built EventType, which is not validated twice:

use happenstance_core::{Event, EventType};

const COURSE_DEFINED: EventType = EventType::from_static("CourseDefined");

let from_str = Event::new("CourseDefined", &b"{}"[..])?;
let from_const = Event::new(COURSE_DEFINED, &b"{}"[..])?;
assert_eq!(from_str.event_type(), from_const.event_type());
Examples found in repository?
examples/two-devices-one-seat/src/rule.rs (line 120)
118fn encode(event: &BoxOffice) -> Result<Event, RuleError> {
119    let data = event.encode(&Json).map_err(RuleError::Encode)?;
120    Ok(Event::new(event.event_type(), data)
121        .map_err(RuleError::EventType)?
122        .with_tags(event.tags()))
123}
Source

pub fn with_tags(self, tags: Tags) -> Self

Attaches tags, replacing any already set.

Examples found in repository?
examples/two-devices-one-seat/src/rule.rs (line 122)
118fn encode(event: &BoxOffice) -> Result<Event, RuleError> {
119    let data = event.encode(&Json).map_err(RuleError::Encode)?;
120    Ok(Event::new(event.event_type(), data)
121        .map_err(RuleError::EventType)?
122        .with_tags(event.tags()))
123}
Source

pub fn with_metadata(self, metadata: impl Into<Bytes>) -> Self

Attaches opaque client metadata, replacing any already set.

Source

pub fn event_type(&self) -> &EventType

The event’s type.

Examples found in repository?
examples/two-devices-one-seat/src/rule.rs (line 110)
103fn decode<'a>(
104    query: &Query,
105    events: impl IntoIterator<Item = &'a ReplicatedEvent>,
106) -> Result<Vec<BoxOffice>, RuleError> {
107    events
108        .into_iter()
109        .map(|replicated| &replicated.event)
110        .filter(|event| query.matches(event.event_type(), event.tags()))
111        .map(|event| {
112            BoxOffice::decode(&Json, event.event_type(), event.data()).map_err(RuleError::Decode)
113        })
114        .collect()
115}
Source

pub fn data(&self) -> &Bytes

The opaque payload.

Examples found in repository?
examples/telemetry-across-codecs/src/main.rs (line 184)
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}
More examples
Hide additional examples
examples/two-devices-one-seat/src/rule.rs (line 112)
103fn decode<'a>(
104    query: &Query,
105    events: impl IntoIterator<Item = &'a ReplicatedEvent>,
106) -> Result<Vec<BoxOffice>, RuleError> {
107    events
108        .into_iter()
109        .map(|replicated| &replicated.event)
110        .filter(|event| query.matches(event.event_type(), event.tags()))
111        .map(|event| {
112            BoxOffice::decode(&Json, event.event_type(), event.data()).map_err(RuleError::Decode)
113        })
114        .collect()
115}
Source

pub fn tags(&self) -> &Tags

The event’s tags, in canonical order.

Examples found in repository?
examples/two-devices-one-seat/src/rule.rs (line 110)
103fn decode<'a>(
104    query: &Query,
105    events: impl IntoIterator<Item = &'a ReplicatedEvent>,
106) -> Result<Vec<BoxOffice>, RuleError> {
107    events
108        .into_iter()
109        .map(|replicated| &replicated.event)
110        .filter(|event| query.matches(event.event_type(), event.tags()))
111        .map(|event| {
112            BoxOffice::decode(&Json, event.event_type(), event.data()).map_err(RuleError::Decode)
113        })
114        .collect()
115}
Source

pub fn metadata(&self) -> Option<&Bytes>

The opaque client metadata, if any.

Examples found in repository?
examples/telemetry-across-codecs/src/main.rs (line 751)
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}
Source

pub fn into_parts(self) -> EventParts

Decomposes the event into its owned parts.

Not a clone-avoidance route for adapters, which is what this line used to claim. EventStore::append takes &[Event], so no store implementation ever owns an Event and none can reach this method at all; an owning adapter clones instead. That clone bumps the payload’s refcount rather than copying it, then allocates once for the EventType, once for the boxed tag slice and once per Tag — t + 2 heap operations, so 66 at VT-22’s 64-tag floor, measured at experiments/event-clone-allocations. It exists for code that owns one.

Returns a struct rather than a tuple so that the number of an event’s parts is not public API. Every let (ty, data, tags, meta) = … would break the day a fifth part existed; reading fields by name, or destructuring with .., survives it.

Trait Implementations§

Source§

impl Clone for Event

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 Event

Source§

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

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

impl<'de> Deserialize<'de> for Event

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 Eq for Event

Source§

impl PartialEq for Event

Source§

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

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

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

Inequality operator !=. Read more
Source§

impl Serialize for Event

Available on crate feature serde only.
Source§

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

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

impl StructuralPartialEq for Event

Auto Trait Implementations§

§

impl !Freeze for Event

§

impl RefUnwindSafe for Event

§

impl Send for Event

§

impl Sync for Event

§

impl Unpin for Event

§

impl UnsafeUnpin for Event

§

impl UnwindSafe for Event

Blanket Implementations§

Source§

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

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

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

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

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

Source§

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

Mutably borrows from an owned value. Read more
Source§

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

Source§

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

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

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

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

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

Source§

fn into(self) -> U

Calls U::from(self).

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

Source§

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

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

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

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

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

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

Source§

type Error = !

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

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

Performs the conversion.
Source§

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

Source§

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

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

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

Performs the conversion.