reliar-outbox 0.6.0

Storage-agnostic transactional outbox: OutboxStore/Publisher contracts, retry policy, settings and dispatcher (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
//! The outbox row: [`OutboxRecord`] and its builder.

use reliar_core::SerializedEnvelope;

use crate::store::{DeadReason, MessageRef};
use crate::worker::WorkerId;

/// The maximum length, in bytes, [`OutboxRecord::last_error`] and [`crate::PoisonedRow::error`]
/// are truncated to before being persisted.
const MAX_ERROR_LEN: usize = 2048;
const TRUNCATION_MARKER: &str = "…[truncated]";

/// Truncates `error` to [`MAX_ERROR_LEN`] bytes at a char boundary, appending
/// [`TRUNCATION_MARKER`] when it was cut. Shared by [`OutboxRecordBuilder::last_error`] and
/// [`crate::PoisonedRow::new`] so both truncate identically.
pub(crate) fn truncate_error(error: impl Into<String>) -> String {
    let error = error.into();

    if error.len() <= MAX_ERROR_LEN {
        return error;
    }

    let budget = MAX_ERROR_LEN.saturating_sub(TRUNCATION_MARKER.len());
    let mut end = budget.min(error.len());

    while end > 0 && !error.is_char_boundary(end) {
        end -= 1;
    }

    tracing::debug!(
        original_len = error.len(),
        truncated_len = end,
        "outbox error truncated before persisting"
    );

    let mut truncated = String::with_capacity(end + TRUNCATION_MARKER.len());
    truncated.push_str(&error[..end]);
    truncated.push_str(TRUNCATION_MARKER);

    truncated
}

/// An envelope **plus** its outbound delivery state. Distinct from [`reliar_core::Envelope`]:
/// nothing here reaches the wire.
///
/// `Clone` and `PartialEq` are required: the `test-support` fakes hand records out by value and
/// the acceptance tests compare them. `Debug` is derived and is payload-safe — it delegates to
/// `Envelope`'s manual `Debug`, which elides the body for every `T`; `last_error` is already
/// truncated and redacted, so it is safe to print in full.
///
/// ```
/// use bytes::Bytes;
/// use reliar_core::{Envelope, Message};
/// use reliar_outbox::OutboxRecord;
/// use time::OffsetDateTime;
///
/// # #[derive(serde::Serialize, serde::Deserialize)]
/// # struct Ping;
/// # impl Message for Ping {
/// #     const TYPE: &'static str = "ping";
/// #     const VERSION: u16 = 1;
/// # }
/// let envelope = Envelope::builder(Ping).build().map_body(|_| Bytes::from_static(b"{}"));
/// let now = OffsetDateTime::now_utc();
/// let record = OutboxRecord::builder(envelope, 1, now).build();
/// assert_eq!(record.attempts, 0);
/// assert_eq!(record.available_at, now);
/// assert!(record.locked_by.is_none());
/// ```
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct OutboxRecord {
    /// The envelope this row carries.
    pub envelope: SerializedEnvelope,

    /// Monotonic, store-assigned. Not gap-free.
    pub sequence: i64,

    /// Immutable once written (ADR 0016).
    pub created_at: time::OffsetDateTime,

    /// `None` means unordered.
    pub ordering_key: Option<String>,

    /// Publish outcomes observed, **not** claims (ADR 0009). A claimed-then-crashed row
    /// reports 0 here even though it was claimed once.
    pub attempts: u32,

    /// The time before which this row is not claimable. On a record just returned by
    /// [`crate::OutboxStore::acquire`] this is the **lease end**, not the enqueue time — a claim
    /// (and a lease renewal) moves it forward to `now() + lease` so the row is invisible to the
    /// claim scan for exactly its lease (ADR 0040). Use [`Self::created_at`] for the enqueue
    /// time.
    pub available_at: time::OffsetDateTime,

    /// The worker currently holding this row's lease, if any.
    pub locked_by: Option<WorkerId>,

    /// When the current lease expires, if any.
    pub locked_until: Option<time::OffsetDateTime>,

    /// When this row was marked published, if it was.
    pub published_at: Option<time::OffsetDateTime>,

    /// When this row was marked dead, if it was.
    pub dead_at: Option<time::OffsetDateTime>,

    /// Why this row is dead, if it is.
    pub dead_reason: Option<DeadReason>,

    /// The last failure's `Display` output, truncated to 2 KiB at a char boundary with a
    /// `"…[truncated]"` marker. Never payload bytes, header values, or credentials.
    pub last_error: Option<String>,
}

impl OutboxRecord {
    /// The value the dead-letter API and by-id operations take.
    ///
    /// ```
    /// use bytes::Bytes;
    /// use reliar_core::{Envelope, Message};
    /// use reliar_outbox::OutboxRecord;
    /// use time::OffsetDateTime;
    ///
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl Message for Ping {
    /// #     const TYPE: &'static str = "ping";
    /// #     const VERSION: u16 = 1;
    /// # }
    /// let envelope = Envelope::builder(Ping).build().map_body(|_| Bytes::from_static(b"{}"));
    /// let id = envelope.id;
    /// let now = OffsetDateTime::now_utc();
    /// let record = OutboxRecord::builder(envelope, 1, now).build();
    /// let message_ref = record.message_ref();
    /// assert_eq!(message_ref.id, id);
    /// assert_eq!(message_ref.created_at, now);
    /// ```
    #[must_use]
    pub fn message_ref(&self) -> MessageRef {
        MessageRef::new(self.envelope.id, self.created_at)
    }

    /// **Provider entry point.** `OutboxRecord` is `#[non_exhaustive]`, so a crate other than
    /// `reliar-outbox` cannot build one with struct-literal syntax — every provider rehydrating
    /// a row goes through this builder.
    ///
    /// Defaults: `attempts = 0`, `available_at = created_at`, no lease, not published, not dead,
    /// no error, no ordering key.
    ///
    /// ```
    /// use bytes::Bytes;
    /// use reliar_core::{Envelope, Message};
    /// use reliar_outbox::OutboxRecord;
    /// use time::OffsetDateTime;
    ///
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl Message for Ping {
    /// #     const TYPE: &'static str = "ping";
    /// #     const VERSION: u16 = 1;
    /// # }
    /// let envelope = Envelope::builder(Ping).build().map_body(|_| Bytes::from_static(b"{}"));
    /// let record = OutboxRecord::builder(envelope, 1, OffsetDateTime::now_utc()).build();
    /// assert_eq!(record.sequence, 1);
    /// assert_eq!(record.attempts, 0);
    /// ```
    pub fn builder(
        envelope: SerializedEnvelope,
        sequence: i64,
        created_at: time::OffsetDateTime,
    ) -> OutboxRecordBuilder {
        OutboxRecordBuilder::new(envelope, sequence, created_at)
    }
}

/// Builds an [`OutboxRecord`]. Obtained from [`OutboxRecord::builder`].
///
/// ```
/// use bytes::Bytes;
/// use reliar_core::{Envelope, Message};
/// use reliar_outbox::OutboxRecord;
/// # #[derive(serde::Serialize, serde::Deserialize)]
/// # struct Ping;
/// # impl Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
/// let envelope = Envelope::builder(Ping).build().map_body(|_| Bytes::from_static(b"{}"));
/// let builder = OutboxRecord::builder(envelope, 1, time::OffsetDateTime::now_utc());
/// assert_eq!(builder.build().sequence, 1);
/// ```
#[must_use]
#[derive(Debug)]
pub struct OutboxRecordBuilder {
    envelope: SerializedEnvelope,

    sequence: i64,

    created_at: time::OffsetDateTime,

    ordering_key: Option<String>,

    attempts: u32,

    available_at: time::OffsetDateTime,

    locked_by: Option<WorkerId>,

    locked_until: Option<time::OffsetDateTime>,

    published_at: Option<time::OffsetDateTime>,

    dead_at: Option<time::OffsetDateTime>,

    dead_reason: Option<DeadReason>,

    last_error: Option<String>,
}

impl OutboxRecordBuilder {
    fn new(envelope: SerializedEnvelope, sequence: i64, created_at: time::OffsetDateTime) -> Self {
        Self {
            envelope,
            sequence,
            available_at: created_at,
            created_at,
            ordering_key: None,
            attempts: 0,
            locked_by: None,
            locked_until: None,
            published_at: None,
            dead_at: None,
            dead_reason: None,
            last_error: None,
        }
    }

    /// Sets [`OutboxRecord::ordering_key`].
    ///
    /// ```
    /// # use bytes::Bytes;
    /// # use reliar_core::{Envelope, Message};
    /// # use reliar_outbox::OutboxRecord;
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// # let envelope = Envelope::builder(Ping).build().map_body(|_| Bytes::from_static(b"{}"));
    /// let record = OutboxRecord::builder(envelope, 1, time::OffsetDateTime::now_utc())
    ///     .ordering_key(Some("order-1".to_string()))
    ///     .build();
    /// assert_eq!(record.ordering_key.as_deref(), Some("order-1"));
    /// ```
    pub fn ordering_key(mut self, key: Option<String>) -> Self {
        self.ordering_key = key;

        self
    }

    /// Sets [`OutboxRecord::attempts`].
    ///
    /// ```
    /// # use bytes::Bytes;
    /// # use reliar_core::{Envelope, Message};
    /// # use reliar_outbox::OutboxRecord;
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// # let envelope = Envelope::builder(Ping).build().map_body(|_| Bytes::from_static(b"{}"));
    /// let record = OutboxRecord::builder(envelope, 1, time::OffsetDateTime::now_utc())
    ///     .attempts(2)
    ///     .build();
    /// assert_eq!(record.attempts, 2);
    /// ```
    pub const fn attempts(mut self, attempts: u32) -> Self {
        self.attempts = attempts;

        self
    }

    /// Sets [`OutboxRecord::available_at`].
    ///
    /// ```
    /// # use bytes::Bytes;
    /// # use reliar_core::{Envelope, Message};
    /// # use reliar_outbox::OutboxRecord;
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// # let envelope = Envelope::builder(Ping).build().map_body(|_| Bytes::from_static(b"{}"));
    /// let created_at = time::OffsetDateTime::now_utc();
    /// let available_at = created_at + time::Duration::seconds(30);
    /// let record = OutboxRecord::builder(envelope, 1, created_at)
    ///     .available_at(available_at)
    ///     .build();
    /// assert_eq!(record.available_at, available_at);
    /// ```
    pub const fn available_at(mut self, at: time::OffsetDateTime) -> Self {
        self.available_at = at;

        self
    }

    /// Sets [`OutboxRecord::locked_by`] and [`OutboxRecord::locked_until`] together — a lease is
    /// either held by a worker until a time, or not held at all.
    ///
    /// ```
    /// # use bytes::Bytes;
    /// # use reliar_core::{Envelope, Message};
    /// # use reliar_outbox::{OutboxRecord, WorkerId};
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// # let envelope = Envelope::builder(Ping).build().map_body(|_| Bytes::from_static(b"{}"));
    /// let worker = WorkerId::parse("worker-1").unwrap();
    /// let until = time::OffsetDateTime::now_utc() + time::Duration::seconds(30);
    /// let record = OutboxRecord::builder(envelope, 1, time::OffsetDateTime::now_utc())
    ///     .lease(Some(worker.clone()), Some(until))
    ///     .build();
    /// assert_eq!(record.locked_by, Some(worker));
    /// assert_eq!(record.locked_until, Some(until));
    /// ```
    pub fn lease(mut self, by: Option<WorkerId>, until: Option<time::OffsetDateTime>) -> Self {
        self.locked_by = by;
        self.locked_until = until;

        self
    }

    /// Sets [`OutboxRecord::published_at`].
    ///
    /// ```
    /// # use bytes::Bytes;
    /// # use reliar_core::{Envelope, Message};
    /// # use reliar_outbox::OutboxRecord;
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// # let envelope = Envelope::builder(Ping).build().map_body(|_| Bytes::from_static(b"{}"));
    /// let now = time::OffsetDateTime::now_utc();
    /// let record = OutboxRecord::builder(envelope, 1, now)
    ///     .published_at(Some(now))
    ///     .build();
    /// assert_eq!(record.published_at, Some(now));
    /// ```
    pub const fn published_at(mut self, at: Option<time::OffsetDateTime>) -> Self {
        self.published_at = at;

        self
    }

    /// Sets [`OutboxRecord::dead_at`] and [`OutboxRecord::dead_reason`] together.
    ///
    /// ```
    /// # use bytes::Bytes;
    /// # use reliar_core::{Envelope, Message};
    /// # use reliar_outbox::{DeadReason, OutboxRecord};
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// # let envelope = Envelope::builder(Ping).build().map_body(|_| Bytes::from_static(b"{}"));
    /// let now = time::OffsetDateTime::now_utc();
    /// let record = OutboxRecord::builder(envelope, 1, now)
    ///     .dead(Some(now), Some(DeadReason::AttemptsExhausted))
    ///     .build();
    /// assert_eq!(record.dead_reason, Some(DeadReason::AttemptsExhausted));
    /// ```
    pub const fn dead(
        mut self,
        at: Option<time::OffsetDateTime>,
        reason: Option<DeadReason>,
    ) -> Self {
        self.dead_at = at;
        self.dead_reason = reason;

        self
    }

    /// Sets [`OutboxRecord::last_error`], truncating to 2 KiB at a char boundary with a
    /// `"…[truncated]"` marker.
    ///
    /// ```
    /// # use bytes::Bytes;
    /// # use reliar_core::{Envelope, Message};
    /// # use reliar_outbox::OutboxRecord;
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// # let envelope = Envelope::builder(Ping).build().map_body(|_| Bytes::from_static(b"{}"));
    /// let record = OutboxRecord::builder(envelope, 1, time::OffsetDateTime::now_utc())
    ///     .last_error(Some("connection refused".to_string()))
    ///     .build();
    /// assert_eq!(record.last_error.as_deref(), Some("connection refused"));
    /// ```
    pub fn last_error(mut self, error: Option<String>) -> Self {
        self.last_error = error.map(truncate_error);

        self
    }

    /// Builds the record.
    ///
    /// ```
    /// # use bytes::Bytes;
    /// # use reliar_core::{Envelope, Message};
    /// # use reliar_outbox::OutboxRecord;
    /// # #[derive(serde::Serialize, serde::Deserialize)]
    /// # struct Ping;
    /// # impl Message for Ping { const TYPE: &'static str = "ping"; const VERSION: u16 = 1; }
    /// # let envelope = Envelope::builder(Ping).build().map_body(|_| Bytes::from_static(b"{}"));
    /// let record = OutboxRecord::builder(envelope, 1, time::OffsetDateTime::now_utc()).build();
    /// assert!(record.published_at.is_none());
    /// ```
    #[must_use]
    pub fn build(self) -> OutboxRecord {
        OutboxRecord {
            envelope: self.envelope,
            sequence: self.sequence,
            created_at: self.created_at,
            ordering_key: self.ordering_key,
            attempts: self.attempts,
            available_at: self.available_at,
            locked_by: self.locked_by,
            locked_until: self.locked_until,
            published_at: self.published_at,
            dead_at: self.dead_at,
            dead_reason: self.dead_reason,
            last_error: self.last_error,
        }
    }
}