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
impl Tag
Sourcepub fn new(value: impl Into<String>) -> Result<Self, InvalidTag>
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.
Sourcepub const fn from_static(value: &'static str) -> Self
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.
Sourcepub fn key_value(key: &str, value: &str) -> Result<Self, InvalidTag>
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?
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
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 }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 }Trait Implementations§
Source§impl<'de> Deserialize<'de> for Tag
Available on crate feature serde only.
impl<'de> Deserialize<'de> for Tag
serde only.Source§fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>
fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error>
impl Eq for Tag
Source§impl Extend<Tag> for Tags
impl Extend<Tag> for Tags
Source§fn extend<I: IntoIterator<Item = Tag>>(&mut self, iter: I)
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)
fn extend_one(&mut self, item: T)
extend_one)Source§fn extend_reserve(&mut self, additional: usize)
fn extend_reserve(&mut self, additional: usize)
extend_one)Source§impl FromIterator<Tag> for Tags
impl FromIterator<Tag> for Tags
Source§fn from_iter<I: IntoIterator<Item = Tag>>(iter: I) -> Self
fn from_iter<I: IntoIterator<Item = Tag>>(iter: I) -> Self
Sorts and deduplicates, producing the canonical form.