reliar-core 0.3.0

Pure envelope/message model shared by every Reliar crate — no storage or transport dependency.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! `Envelope<T>` / `SerializedEnvelope` and their builder (ADR 0003, ADR 0011).

use core::fmt;

use bytes::Bytes;

use crate::{
    ConversationId, CorrelationId, CorrelationMetadata, HeaderError, Headers, Message, MessageId,
    MessageType, Metadata,
};

/// An envelope: a typed or serialized body plus the metadata Reliar understands and the custom
/// headers it does not. `Envelope != OutboxRecord != InboxRecord` — nothing here
/// carries delivery state (attempts, leases, dead-letter bookkeeping).
///
/// ```
/// use reliar_core::Envelope;
///
/// #[derive(serde::Serialize, serde::Deserialize)]
/// struct Ping;
/// impl reliar_core::Message for Ping {
///     const TYPE: &'static str = "ping";
///     const VERSION: u16 = 1;
/// }
///
/// let envelope = Envelope::builder(Ping).build();
/// assert_eq!(envelope.message_type.to_string(), "ping.v1");
/// ```
#[non_exhaustive]
pub struct Envelope<T> {
    /// The envelope's own identity.
    pub id: MessageId,

    /// The message's stable contract identity — `T::TYPE`/`T::VERSION`, never chosen ad hoc.
    pub message_type: MessageType,

    /// The message body: typed on the application side, `bytes::Bytes` once serialized.
    pub body: T,

    /// Canonical, typed framework metadata — the single source of truth (ADR 0004).
    pub metadata: Metadata,

    /// Private: preserves [`Headers`]' validation invariants — mutate only through
    /// [`Self::headers_mut`]/[`Self::set_headers`].
    pub(crate) headers: Option<Headers>,
}

/// The persistence/transport form: an envelope whose body has already been serialized to bytes.
///
/// ```
/// use bytes::Bytes;
/// use reliar_core::{Envelope, SerializedEnvelope};
/// # #[derive(serde::Serialize, serde::Deserialize)]
/// # struct Ping;
/// # impl reliar_core::Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
///
/// let typed = Envelope::builder(Ping).build();
/// let wire: SerializedEnvelope = typed.map_body(|_| Bytes::from_static(b"{}"));
/// assert_eq!(wire.body.as_ref(), b"{}");
/// ```
pub type SerializedEnvelope = Envelope<Bytes>;

impl<T> Envelope<T> {
    /// The envelope's custom headers, if any were set.
    ///
    /// ```
    /// use reliar_core::Envelope;
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl reliar_core::Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// let envelope = Envelope::builder(Ping).build();
    /// assert!(envelope.headers().is_none());
    /// ```
    #[must_use]
    pub fn headers(&self) -> Option<&Headers> {
        self.headers.as_ref()
    }

    /// Mutably accesses the envelope's custom headers, lazily allocating an empty [`Headers`]
    /// the first time this is called.
    ///
    /// ```
    /// use reliar_core::Envelope;
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl reliar_core::Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// let mut envelope = Envelope::builder(Ping).build();
    /// envelope.headers_mut().insert("x-a", "1")?;
    /// assert_eq!(envelope.headers().unwrap().get("x-a"), Some("1"));
    /// # Ok::<(), reliar_core::HeaderError>(())
    /// ```
    pub fn headers_mut(&mut self) -> &mut Headers {
        self.headers.get_or_insert_with(Headers::default)
    }

    /// Replaces the whole header map. The rehydration path for providers and transport mappers,
    /// which read back an already-validated map rather than inserting key by key.
    ///
    /// ```
    /// use reliar_core::{Envelope, Headers};
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl reliar_core::Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// let mut envelope = Envelope::builder(Ping).build();
    /// let mut headers = Headers::default();
    /// headers.insert("x-a", "1")?;
    /// envelope.set_headers(Some(headers));
    /// assert_eq!(envelope.headers().unwrap().get("x-a"), Some("1"));
    /// # Ok::<(), reliar_core::HeaderError>(())
    /// ```
    pub fn set_headers(&mut self, headers: Option<Headers>) {
        self.headers = headers;
    }

    /// Converts the body, keeping every other field. The only conversion between typed and
    /// serialized envelopes — no field is ever re-declared, so none can be dropped in the
    /// process (ADR 0003).
    ///
    /// ```
    /// use bytes::Bytes;
    /// use reliar_core::Envelope;
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl reliar_core::Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// let envelope = Envelope::builder(Ping).build();
    /// let serialized: Envelope<Bytes> = envelope.map_body(|_| Bytes::from_static(b"{}"));
    /// assert_eq!(serialized.body.as_ref(), b"{}");
    /// ```
    #[must_use]
    pub fn map_body<U>(self, f: impl FnOnce(T) -> U) -> Envelope<U> {
        Envelope {
            id: self.id,
            message_type: self.message_type,
            body: f(self.body),
            metadata: self.metadata,
            headers: self.headers,
        }
    }

    /// Fallible variant of [`Self::map_body`], for `SerializedEnvelope -> Envelope<T>` via a
    /// [`Serializer`](crate::Serializer).
    ///
    /// # Errors
    ///
    /// Returns whatever error `f` returns, unchanged.
    ///
    /// ```
    /// use bytes::Bytes;
    /// use reliar_core::Envelope;
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl reliar_core::Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// let wire = Envelope::builder(Ping)
    ///     .build()
    ///     .map_body(|_| Bytes::from_static(b"{}"));
    ///
    /// let typed: Envelope<Ping> = wire.try_map_body(|_body| Ok::<_, std::convert::Infallible>(Ping))?;
    /// assert_eq!(typed.message_type.to_string(), "ping.v1");
    /// # Ok::<(), std::convert::Infallible>(())
    /// ```
    pub fn try_map_body<U, E>(self, f: impl FnOnce(T) -> Result<U, E>) -> Result<Envelope<U>, E> {
        Ok(Envelope {
            id: self.id,
            message_type: self.message_type,
            body: f(self.body)?,
            metadata: self.metadata,
            headers: self.headers,
        })
    }
}

impl<T: Message> Envelope<T> {
    /// Starts building an envelope for `body`. `message_type` is derived from `T::TYPE`/
    /// `T::VERSION` and cannot be passed in (ADR 0010).
    ///
    /// ```
    /// use reliar_core::Envelope;
    ///
    /// #[derive(serde::Serialize, serde::Deserialize)]
    /// struct OrderCreated { order_id: u64 }
    ///
    /// impl reliar_core::Message for OrderCreated {
    ///     const TYPE: &'static str = "orders.created";
    ///     const VERSION: u16 = 1;
    /// }
    ///
    /// let envelope = Envelope::builder(OrderCreated { order_id: 42 })
    ///     .tenant("acme")
    ///     .header("x-import-batch", "2026-09-04")?
    ///     .build();
    ///
    /// assert_eq!(envelope.message_type.to_string(), "orders.created.v1");
    /// assert_eq!(envelope.metadata.tenant_id.as_deref(), Some("acme"));
    /// # Ok::<(), reliar_core::HeaderError>(())
    /// ```
    pub fn builder(body: T) -> EnvelopeBuilder<T> {
        EnvelopeBuilder::new(body)
    }
}

impl SerializedEnvelope {
    /// Rehydration entry point for providers and transport mappers, which have a `MessageType`
    /// read from storage or the wire rather than from a Rust type (ADR 0011).
    ///
    /// ```
    /// use bytes::Bytes;
    /// use reliar_core::{Metadata, MessageId, MessageType, SerializedEnvelope};
    ///
    /// let envelope = SerializedEnvelope::from_parts(
    ///     MessageId::new(),
    ///     MessageType::from_parts("orders.created".to_string(), 1),
    ///     Bytes::from_static(b"{}"),
    ///     Metadata::default(),
    ///     None,
    /// );
    /// assert_eq!(envelope.message_type.name(), "orders.created");
    /// ```
    #[must_use]
    pub fn from_parts(
        id: MessageId,
        message_type: MessageType,
        body: Bytes,
        metadata: Metadata,
        headers: Option<Headers>,
    ) -> Self {
        Self {
            id,
            message_type,
            body,
            metadata,
            headers,
        }
    }
}

/// Elides the body unconditionally: a typed body may be arbitrary application data and a
/// serialized one is raw payload bytes, and neither belongs in a log line (ADR 0003).
impl<T> fmt::Debug for Envelope<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Envelope")
            .field("id", &self.id)
            .field("message_type", &self.message_type)
            .field("body", &"<elided>")
            .field("metadata", &self.metadata)
            .field("headers", &self.headers)
            .finish()
    }
}

impl<T: PartialEq> PartialEq for Envelope<T> {
    fn eq(&self, other: &Self) -> bool {
        self.id == other.id
            && self.message_type == other.message_type
            && self.body == other.body
            && self.metadata == other.metadata
            && self.headers == other.headers
    }
}

/// `Clone` only where `T: Clone` — nothing in Reliar requires it, since a dispatcher moves owned
/// records into publish tasks rather than cloning them; the impl exists for tests and host code.
impl<T: Clone> Clone for Envelope<T> {
    fn clone(&self) -> Self {
        Self {
            id: self.id,
            message_type: self.message_type.clone(),
            body: self.body.clone(),
            metadata: self.metadata.clone(),
            headers: self.headers.clone(),
        }
    }
}

/// Builds an [`Envelope<T>`]. Obtained from [`Envelope::builder`].
///
/// ```
/// use reliar_core::Envelope;
///
/// #[derive(serde::Serialize, serde::Deserialize)]
/// struct OrderCreated { order_id: u64 }
/// impl reliar_core::Message for OrderCreated {
///     const TYPE: &'static str = "orders.created";
///     const VERSION: u16 = 1;
/// }
///
/// let envelope = Envelope::builder(OrderCreated { order_id: 42 })
///     .tenant("acme")
///     .build();
/// assert_eq!(envelope.metadata.tenant_id.as_deref(), Some("acme"));
/// ```
#[must_use]
pub struct EnvelopeBuilder<T> {
    id: Option<MessageId>,

    body: T,

    metadata: Metadata,

    headers: Option<Headers>,
}

/// Elides the body: an in-progress envelope's body is arbitrary application data.
impl<T> fmt::Debug for EnvelopeBuilder<T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EnvelopeBuilder")
            .field("id", &self.id)
            .field("body", &"<elided>")
            .field("metadata", &self.metadata)
            .field("headers", &self.headers)
            .finish()
    }
}

impl<T: Message> EnvelopeBuilder<T> {
    fn new(body: T) -> Self {
        Self {
            id: None,
            body,
            metadata: Metadata::default(),
            headers: None,
        }
    }

    /// Overrides the generated id. Defaults to a fresh `UUIDv7`.
    ///
    /// ```
    /// use reliar_core::{Envelope, MessageId};
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl reliar_core::Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// let id = MessageId::new();
    /// let envelope = Envelope::builder(Ping).id(id).build();
    /// assert_eq!(envelope.id, id);
    /// ```
    pub fn id(mut self, id: MessageId) -> Self {
        self.id = Some(id);

        self
    }

    /// Replaces the whole metadata struct, including its correlation metadata. Conversation
    /// rooting is decided by *value*, not by call order: if the replacement's `conversation_id`
    /// is still [`crate::ConversationId::UNSET`], [`Self::build`] roots it at the envelope's own
    /// id regardless of an earlier [`Self::conversation`] call; a non-`UNSET` value (including
    /// one copied from a causing message) is kept.
    ///
    /// ```
    /// use reliar_core::{Envelope, Metadata};
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl reliar_core::Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// let mut metadata = Metadata::default();
    /// metadata.tenant_id = Some("acme".to_string());
    /// let envelope = Envelope::builder(Ping).metadata(metadata).build();
    /// assert_eq!(envelope.metadata.tenant_id.as_deref(), Some("acme"));
    /// ```
    pub fn metadata(mut self, metadata: Metadata) -> Self {
        self.metadata = metadata;

        self
    }

    /// Replaces the correlation metadata (correlation id, conversation id, causation, request
    /// id) as a group. Same value-decides-rooting rule as [`Self::metadata`].
    ///
    /// ```
    /// use reliar_core::{CorrelationMetadata, Envelope};
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl reliar_core::Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// let mut correlation = CorrelationMetadata::default();
    /// correlation.causation_id = Some(reliar_core::MessageId::new());
    /// let envelope = Envelope::builder(Ping).correlation(correlation).build();
    /// assert!(envelope.metadata.correlation.causation_id.is_some());
    /// ```
    pub fn correlation(mut self, correlation: CorrelationMetadata) -> Self {
        self.metadata.correlation = correlation;

        self
    }

    /// Sets the business correlation id.
    ///
    /// ```
    /// use reliar_core::{CorrelationId, Envelope};
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl reliar_core::Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// let envelope = Envelope::builder(Ping)
    ///     .correlation_id(CorrelationId::parse("checkout-42")?)
    ///     .build();
    /// assert_eq!(envelope.metadata.correlation.correlation_id.unwrap().as_str(), "checkout-42");
    /// # Ok::<(), reliar_core::IdError>(())
    /// ```
    pub fn correlation_id(mut self, id: CorrelationId) -> Self {
        self.metadata.correlation.correlation_id = Some(id);

        self
    }

    /// Joins an existing conversation — typically the causing message's own `conversation_id`.
    /// [`Self::build`] keeps this value as long as nothing later replaces it with
    /// [`Self::metadata`] or [`Self::correlation`] (setter order matters only in that sense: the
    /// last write to `conversation_id` wins, same as any other field).
    ///
    /// ```
    /// use reliar_core::{ConversationId, Envelope};
    /// use uuid::Uuid;
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl reliar_core::Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// let parent_conversation = ConversationId::from_uuid(Uuid::now_v7());
    /// let envelope = Envelope::builder(Ping).conversation(parent_conversation).build();
    /// assert_eq!(envelope.metadata.correlation.conversation_id, parent_conversation);
    /// ```
    pub fn conversation(mut self, id: ConversationId) -> Self {
        self.metadata.correlation.conversation_id = id;

        self
    }

    /// Records the message that caused this one.
    ///
    /// ```
    /// use reliar_core::{Envelope, MessageId};
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl reliar_core::Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// let parent = MessageId::new();
    /// let envelope = Envelope::builder(Ping).causation(parent).build();
    /// assert_eq!(envelope.metadata.correlation.causation_id, Some(parent));
    /// ```
    pub fn causation(mut self, parent: MessageId) -> Self {
        self.metadata.correlation.causation_id = Some(parent);

        self
    }

    /// Sets the owning tenant.
    ///
    /// ```
    /// use reliar_core::Envelope;
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl reliar_core::Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// let envelope = Envelope::builder(Ping).tenant("acme").build();
    /// assert_eq!(envelope.metadata.tenant_id.as_deref(), Some("acme"));
    /// ```
    pub fn tenant(mut self, tenant_id: impl Into<String>) -> Self {
        self.metadata.tenant_id = Some(tenant_id.into());

        self
    }

    /// Sets the time after which the message must not be published.
    ///
    /// ```
    /// use reliar_core::Envelope;
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl reliar_core::Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// let one_day = time::Duration::days(1);
    /// let envelope = Envelope::builder(Ping)
    ///     .expires_at(time::OffsetDateTime::now_utc() + one_day)
    ///     .build();
    /// assert!(envelope.metadata.delivery.expires_at.is_some());
    /// ```
    pub fn expires_at(mut self, at: time::OffsetDateTime) -> Self {
        self.metadata.delivery.expires_at = Some(at);

        self
    }

    /// Sets the W3C Trace Context to carry verbatim. Reliar never invents or re-derives it
    /// (ADR 0004, ADR 0020).
    ///
    /// ```
    /// use reliar_core::Envelope;
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl reliar_core::Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// let envelope = Envelope::builder(Ping)
    ///     .trace("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01", None)
    ///     .build();
    /// assert!(envelope.metadata.trace.traceparent.is_some());
    /// ```
    pub fn trace(mut self, traceparent: impl Into<String>, tracestate: Option<String>) -> Self {
        self.metadata.trace.traceparent = Some(traceparent.into());
        self.metadata.trace.tracestate = tracestate;

        self
    }

    /// Sets one custom header. Returns `Err` if `k` uses the reserved `reliar-` prefix or
    /// breaches a cap (see [`Headers::insert`]).
    ///
    /// # Errors
    ///
    /// Returns [`HeaderError`] under the same conditions as [`Headers::insert`].
    ///
    /// ```
    /// use reliar_core::Envelope;
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl reliar_core::Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// let envelope = Envelope::builder(Ping).header("x-import-batch", "2026-09-04")?.build();
    /// assert_eq!(envelope.headers().unwrap().get("x-import-batch"), Some("2026-09-04"));
    /// # Ok::<(), reliar_core::HeaderError>(())
    /// ```
    pub fn header(
        mut self,
        k: impl Into<String>,
        v: impl Into<String>,
    ) -> Result<Self, HeaderError> {
        self.headers
            .get_or_insert_with(Headers::default)
            .insert(k, v)?;

        Ok(self)
    }

    /// Builds the envelope. `message_type` is `MessageType::of::<T>()`. `conversation_id`:
    /// **iff** it is still [`crate::ConversationId::UNSET`], it becomes this envelope's own id
    /// (an un-correlated message roots its own conversation); any other value — set via
    /// [`Self::conversation`], [`Self::correlation`], or [`Self::metadata`] — is kept verbatim.
    /// Rooting is decided by the value alone, never by which setter was called or in what order
    /// (ADR 0011).
    ///
    /// ```
    /// use reliar_core::Envelope;
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl reliar_core::Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// let envelope = Envelope::builder(Ping).build();
    /// // An un-correlated message roots its own conversation.
    /// assert_eq!(envelope.metadata.correlation.conversation_id.as_uuid(), envelope.id.as_uuid());
    /// ```
    #[must_use]
    pub fn build(mut self) -> Envelope<T> {
        let id = self.id.unwrap_or_default();

        if self.metadata.correlation.conversation_id.is_unset() {
            self.metadata.correlation.conversation_id = ConversationId::from_uuid(id.as_uuid());
        }

        Envelope {
            id,
            message_type: MessageType::of::<T>(),
            body: self.body,
            metadata: self.metadata,
            headers: self.headers,
        }
    }
}