Skip to main content

Tag

Struct Tag 

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

A single domain-specific label attached to an Event.

The DCB specification treats a tag as an opaque string. By convention tags take a key:value shape such as course:c1, and Tag::key and Tag::value expose that convention without enforcing it — a tag with no colon is perfectly legal.

Like EventType, backed by Cow<'static, str> so that a tag written in the source costs no allocation and a tag arriving from a peer at run time is still representable.

§Equality is byte equality, and nothing is normalised

Two tags are equal exactly when their UTF-8 bytes are equal. The contract applies no Unicode normalisation, no case folding and no trimming, and no adapter may apply any either: a store that rewrites a caller’s tag makes the value read back differ from the value written, which breaks byte-faithful replication and puts the store’s index out of step with every external system holding the original string.

Whitespace is therefore significant, including leading and trailing whitespace — "turbine:HW2-A14 " and "turbine:HW2-A14" are two tags and so two consistency boundaries. "café" written NFC (caf + U+00E9) and NFD (cafe + U+0301) is the same failure with no visible cue at all: the two render identically and index separately.

Choosing a normal form is the application’s job, done before the tag is built. The contract’s job is to say loudly that it does not choose one — the DCB specification treats a tag as an opaque string, and a contract that normalised would be deciding what a caller’s identifier means.

use happenstance_core::Tag;

// "café" twice: one code point, then `e` plus a combining acute.
assert_ne!(Tag::new("city:caf\u{e9}")?, Tag::new("city:cafe\u{301}")?);

// A trailing space is part of the tag.
assert_ne!(Tag::new("turbine:HW2-A14 ")?, Tag::new("turbine:HW2-A14")?);

// As is case.
assert_ne!(Tag::new("course:C1")?, Tag::new("course:c1")?);

§Examples

use happenstance_core::Tag;

let tag = Tag::key_value("course", "c1")?;
assert_eq!(tag.as_str(), "course:c1");
assert_eq!(tag.key(), Some("course"));
assert_eq!(tag.value(), Some("c1"));

// Opaque tags are legal too.
let opaque = Tag::new("archived")?;
assert_eq!(opaque.key(), None);

Implementations§

Source§

impl Tag

Source

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

Creates a tag from an arbitrary string.

§Errors

Returns InvalidTag if the value is empty, longer than MAX_TAG_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 a tag from a string literal, validating at compile time.

Enforces exactly the rules new enforces.

§Panics

Panics if the value would be rejected by new. See EventType::from_static for where that panic surfaces, which depends on the kind of call site and is not uniform.

Source

pub fn key_value(key: &str, value: &str) -> Result<Self, InvalidTag>

Creates a key:value tag, the conventional DCB shape.

§Errors

Returns InvalidTag if either part is empty, if key itself contains a colon (which would make Tag::key ambiguous), or if the joined value fails Tag::new’s validation.

Examples found in repository?
examples/rebuilding-read-models/src/main.rs (line 536)
533    fn new(id: &str) -> Result<Self, InvalidTag> {
534        Ok(Self {
535            id: id.to_owned(),
536            tag: Tag::key_value("sku", id)?,
537        })
538    }
539
540    /// The identifier as the application wrote it.
541    fn as_str(&self) -> &str {
542        &self.id
543    }
544}
545
546impl TryFrom<String> for Sku {
547    type Error = InvalidTag;
548
549    fn try_from(id: String) -> Result<Self, InvalidTag> {
550        Self::new(&id)
551    }
552}
553
554impl From<Sku> for String {
555    fn from(sku: Sku) -> Self {
556        sku.id
557    }
558}
559
560/// An order reference, validated once into the tag its events carry.
561#[derive(Debug, Clone, Serialize, Deserialize)]
562#[serde(try_from = "String", into = "String")]
563struct OrderId {
564    /// The reference as the application wrote it.
565    id: String,
566    /// The same value, validated into the tag every event for it carries.
567    tag: Tag,
568}
569
570impl OrderId {
571    /// Validates `id` into the tag every event for this order is written with.
572    fn new(id: &str) -> Result<Self, InvalidTag> {
573        Ok(Self {
574            id: id.to_owned(),
575            tag: Tag::key_value("order", id)?,
576        })
577    }
More examples
Hide additional examples
examples/handles-and-quotas/src/main.rs (line 231)
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    }
examples/course-subscriptions/src/main.rs (line 101)
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    }
examples/telemetry-across-codecs/src/main.rs (line 271)
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    }
examples/transfers-on-sqlite/src/main.rs (line 227)
224    fn new(id: &str) -> Result<Self, InvalidTag> {
225        Ok(Self {
226            id: id.to_owned(),
227            tag: Tag::key_value("account", id)?,
228        })
229    }
examples/two-devices-one-seat/src/domain.rs (line 126)
123    pub fn new(name: &str) -> Result<Self, InvalidTag> {
124        Ok(Self {
125            name: name.to_owned(),
126            tag: Tag::key_value("show", name)?,
127        })
128    }
Source

pub fn as_str(&self) -> &str

The tag as a string slice.

Source

pub fn key(&self) -> Option<&str>

The portion before the first :, if the tag follows the key:value convention.

Source

pub fn value(&self) -> Option<&str>

The portion after the first :, if the tag follows the key:value convention.

Trait Implementations§

Source§

impl AsRef<str> for Tag

Source§

fn as_ref(&self) -> &str

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

impl Borrow<str> for Tag

Source§

fn borrow(&self) -> &str

Immutably borrows from an owned value. Read more
Source§

impl Clone for Tag

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 Tag

Source§

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

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

impl<'de> Deserialize<'de> for Tag

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 Tag

Source§

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

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

impl Eq for Tag

Source§

impl Extend<Tag> for Tags

Source§

fn extend<I: IntoIterator<Item = Tag>>(&mut self, iter: I)

Adds tags and re-canonicalises.

Not the amortised O(1) Extend usually implies. Each call sorts and deduplicates the whole set, so extending n times costs n sorts; build the tags first and collect once where you can.

Source§

fn extend_one(&mut self, item: T)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl FromIterator<Tag> for Tags

Source§

fn from_iter<I: IntoIterator<Item = Tag>>(iter: I) -> Self

Sorts and deduplicates, producing the canonical form.

Source§

impl FromStr for Tag

Source§

type Err = InvalidTag

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 Tag

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 Tag

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 Tag

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 Tag

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 Tag

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 Tag

Source§

type Error = InvalidTag

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 Tag

Source§

type Error = InvalidTag

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§

§

impl Freeze for Tag

§

impl RefUnwindSafe for Tag

§

impl Send for Tag

§

impl Sync for Tag

§

impl Unpin for Tag

§

impl UnsafeUnpin for Tag

§

impl UnwindSafe for Tag

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.