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
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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
//! The outbox feature's settings, with an opt-in environment loader (ADR 0019).
//!
//! **The library never reads the environment implicitly.** No constructor, `Default` or builder
//! method touches [`std::env`] — only [`OutboxSettings::from_env`] does, and only when called.

use std::env::VarError;
use std::time::Duration;

use reliar_core::SettingsError;

use crate::ordering::Ordering;
use crate::retry::ExponentialBackoff;
use crate::worker::WorkerId;

/// The one settings struct for the outbox feature. Env prefix `RELIAR_OUTBOX_` by convention;
/// [`OutboxSettings::from_env`] takes whatever prefix the caller passes.
///
/// ```
/// use reliar_outbox::{DispatcherSettings, OutboxSettings};
///
/// let settings = OutboxSettings::default()
///     .dispatcher(DispatcherSettings::default().batch_size(50));
/// assert_eq!(settings.dispatcher.batch_size, 50);
/// ```
#[derive(Clone, Debug, Default)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(default, deny_unknown_fields))]
#[non_exhaustive]
pub struct OutboxSettings {
    /// Worker-loop tunables.
    pub dispatcher: DispatcherSettings,

    /// Purge tunables.
    pub retention: RetentionSettings,
}

impl OutboxSettings {
    /// Sets [`Self::dispatcher`].
    ///
    /// ```
    /// use reliar_outbox::{DispatcherSettings, OutboxSettings};
    /// let settings = OutboxSettings::default().dispatcher(DispatcherSettings::default());
    /// assert_eq!(settings.dispatcher.batch_size, 100);
    /// ```
    #[must_use]
    pub fn dispatcher(mut self, dispatcher: DispatcherSettings) -> Self {
        self.dispatcher = dispatcher;

        self
    }

    /// Sets [`Self::retention`].
    ///
    /// ```
    /// use reliar_outbox::{OutboxSettings, RetentionSettings};
    /// let settings = OutboxSettings::default()
    ///     .retention(RetentionSettings::default().purge_batch_size(500));
    /// assert_eq!(settings.retention.purge_batch_size, 500);
    /// ```
    #[must_use]
    pub fn retention(mut self, retention: RetentionSettings) -> Self {
        self.retention = retention;

        self
    }
}

/// Worker-loop tunables — the struct the outbox defaults table and the drain rule refer to.
///
/// ```
/// use reliar_outbox::DispatcherSettings;
/// use std::time::Duration;
///
/// let settings = DispatcherSettings::default().batch_size(50).lease(Duration::from_secs(60));
/// assert_eq!(settings.batch_size, 50);
/// assert_eq!(settings.lease, Duration::from_secs(60));
/// ```
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(default, deny_unknown_fields))]
#[non_exhaustive]
pub struct DispatcherSettings {
    /// The maximum number of rows one `acquire` **statement** claims. `BATCH_SIZE`. Default
    /// 100.
    ///
    /// **`max_in_flight` is the real ceiling on rows this worker holds leased at once —
    /// `batch_size` only caps a single claim.** The dispatcher claims only while
    /// `outstanding < max_in_flight`, asking for `min(batch_size, max_in_flight - outstanding)`,
    /// so the largest claim this dispatcher will ever issue is `min(batch_size, max_in_flight)`
    /// — the **effective batch**. With the accepted defaults (100 / 16) that is 16, so
    /// `batch_size` does not bind. Raise it only alongside `max_in_flight` if a single worker is
    /// meant to hold more rows leased at once.
    pub batch_size: u32,

    /// How long a claim holds the lease before it may be reclaimed. `LEASE_MS`. Default 30 s.
    #[cfg_attr(
        feature = "serde",
        serde(rename = "lease_ms", with = "crate::duration_serde::millis")
    )]
    pub lease: Duration,

    /// The maximum number of publishes running concurrently — **the ceiling that actually
    /// binds**: every claim asks for at most this many rows, and every startup check that
    /// reasons about a claim's size (see [`Self::batch_size`]) is computed against it, not
    /// against `batch_size` alone. `MAX_IN_FLIGHT`. Default 16.
    pub max_in_flight: usize,

    /// How long one publish is allowed to run before it counts as a timeout (classified
    /// [`crate::FailureKind::Transient`]). `PUBLISH_TIMEOUT_MS`. Default 10 s.
    #[cfg_attr(
        feature = "serde",
        serde(rename = "publish_timeout_ms", with = "crate::duration_serde::millis")
    )]
    pub publish_timeout: Duration,

    /// How long the loop waits after a claim that came back **partially filled** — the store
    /// had work, but less than this worker asked for (ADR 0039). A claim that fills its request
    /// (`records.len() == want`) is followed **immediately** by the next one, with no wait at
    /// all; an empty claim — including one made entirely of poisoned rows — waits
    /// [`Self::idle_poll_interval`] instead. `POLL_INTERVAL_MS`. Default 500 ms. **Must be
    /// greater than zero** ([`crate::ConfigError::ZeroPollInterval`]) — it also seeds the
    /// outcome-write retry pacing (`outcome_retry_interval`), so a zero value would re-enable a
    /// CPU-speed spin on both paths.
    #[cfg_attr(
        feature = "serde",
        serde(rename = "poll_interval_ms", with = "crate::duration_serde::millis")
    )]
    pub poll_interval: Duration,

    /// How often the loop polls once it has seen an empty claim (ADR 0039) — the only pacing
    /// left once a busy dispatcher no longer waits `poll_interval` between full claims. This
    /// bounds the worst-case pickup latency for a row enqueued while the worker is idle;
    /// lowering it is the supported way to cut that latency (this release has no
    /// `LISTEN/NOTIFY`). `IDLE_POLL_INTERVAL_MS`. Default 5 s. **Must be greater than zero**
    /// ([`crate::ConfigError::ZeroPollInterval`]) — a zero value would poll an idle store at CPU
    /// speed instead of backing off.
    #[cfg_attr(
        feature = "serde",
        serde(
            rename = "idle_poll_interval_ms",
            with = "crate::duration_serde::millis"
        )
    )]
    pub idle_poll_interval: Duration,

    /// The maximum time `run()` spends draining in-flight publishes after cancellation.
    /// `DRAIN_TIMEOUT_MS`. Default 30 s.
    ///
    /// With the defaults, worst-case shutdown is roughly **`drain_timeout + store_timeout`**,
    /// not just `drain_timeout`: the drain loop itself is bounded by `drain_timeout`, and the one
    /// best-effort outcome-write attempt made right after it is separately bounded by
    /// `store_timeout` — the two budgets are not nested, they are sequential.
    #[cfg_attr(
        feature = "serde",
        serde(rename = "drain_timeout_ms", with = "crate::duration_serde::millis")
    )]
    pub drain_timeout: Duration,

    /// A client-side bound on **every** `OutboxStore` call `run` makes — without it a hung
    /// statement (a lost connection with no server-side `statement_timeout`, a saturated pool)
    /// makes `drain_timeout` unenforceable. A timeout is treated as a transient store error.
    ///
    /// **Must be shorter than half the lease** (`store_timeout < lease / 2`,
    /// [`crate::ConfigError::StoreTimeoutTooLong`]): `run`'s outcome-write retry races the
    /// lease-renewal tick inside the same `select!`, so a `store_timeout` any longer could let
    /// one hung `complete`/`fail` attempt occupy an entire tick gap and starve renewal.
    /// `STORE_TIMEOUT_MS`. Default 10 s (comfortably under half the default 30 s lease's 15 s).
    #[cfg_attr(
        feature = "serde",
        serde(rename = "store_timeout_ms", with = "crate::duration_serde::millis")
    )]
    pub store_timeout: Duration,

    /// How often `stats()` is polled for the lag/dead-count gauges. `STATS_INTERVAL_MS`.
    /// Default 15 s.
    ///
    /// # Cost
    ///
    /// The poll is `O(claimable backlog)`, not `O(table)` — a host that lets the backlog reach
    /// millions of rows should raise this interval, or set it to [`Duration::ZERO`] to disable
    /// the tick entirely (opt-in gauges) and call [`crate::OutboxStore::stats`] on its own
    /// schedule instead.
    #[cfg_attr(
        feature = "serde",
        serde(rename = "stats_interval_ms", with = "crate::duration_serde::millis")
    )]
    pub stats_interval: Duration,

    /// The publication ordering strategy. `ORDERING`. Default [`Ordering::Unordered`].
    pub ordering: Ordering,

    /// The retry/backoff policy. `RETRY_BASE_MS`, `RETRY_MAX_DELAY_MS`,
    /// `RETRY_MAX_ATTEMPTS`, `RETRY_JITTER`.
    pub retry: ExponentialBackoff,

    /// Overrides the generated [`WorkerId`]. `WORKER_ID`. Default: generated.
    pub worker_id: Option<WorkerId>,
}

impl Default for DispatcherSettings {
    fn default() -> Self {
        Self {
            batch_size: 100,
            lease: Duration::from_secs(30),
            max_in_flight: 16,
            publish_timeout: Duration::from_secs(10),
            poll_interval: Duration::from_millis(500),
            idle_poll_interval: Duration::from_secs(5),
            drain_timeout: Duration::from_secs(30),
            store_timeout: Duration::from_secs(10),
            stats_interval: Duration::from_secs(15),
            ordering: Ordering::default(),
            retry: ExponentialBackoff::default(),
            worker_id: None,
        }
    }
}

impl DispatcherSettings {
    /// Sets [`Self::batch_size`].
    ///
    /// ```
    /// use reliar_outbox::DispatcherSettings;
    /// assert_eq!(DispatcherSettings::default().batch_size(50).batch_size, 50);
    /// ```
    #[must_use]
    pub const fn batch_size(mut self, batch_size: u32) -> Self {
        self.batch_size = batch_size;

        self
    }

    /// Sets [`Self::lease`].
    ///
    /// ```
    /// use reliar_outbox::DispatcherSettings;
    /// use std::time::Duration;
    /// let lease = Duration::from_secs(60);
    /// assert_eq!(DispatcherSettings::default().lease(lease).lease, lease);
    /// ```
    #[must_use]
    pub const fn lease(mut self, lease: Duration) -> Self {
        self.lease = lease;

        self
    }

    /// Sets [`Self::max_in_flight`].
    ///
    /// ```
    /// use reliar_outbox::DispatcherSettings;
    /// assert_eq!(DispatcherSettings::default().max_in_flight(32).max_in_flight, 32);
    /// ```
    #[must_use]
    pub const fn max_in_flight(mut self, max_in_flight: usize) -> Self {
        self.max_in_flight = max_in_flight;

        self
    }

    /// Sets [`Self::publish_timeout`].
    ///
    /// ```
    /// use reliar_outbox::DispatcherSettings;
    /// use std::time::Duration;
    /// let timeout = Duration::from_secs(5);
    /// assert_eq!(DispatcherSettings::default().publish_timeout(timeout).publish_timeout, timeout);
    /// ```
    #[must_use]
    pub const fn publish_timeout(mut self, publish_timeout: Duration) -> Self {
        self.publish_timeout = publish_timeout;

        self
    }

    /// Sets [`Self::poll_interval`].
    ///
    /// ```
    /// use reliar_outbox::DispatcherSettings;
    /// use std::time::Duration;
    /// let interval = Duration::from_millis(200);
    /// assert_eq!(DispatcherSettings::default().poll_interval(interval).poll_interval, interval);
    /// ```
    #[must_use]
    pub const fn poll_interval(mut self, poll_interval: Duration) -> Self {
        self.poll_interval = poll_interval;

        self
    }

    /// Sets [`Self::idle_poll_interval`].
    ///
    /// ```
    /// use reliar_outbox::DispatcherSettings;
    /// use std::time::Duration;
    /// let interval = Duration::from_secs(2);
    /// assert_eq!(
    ///     DispatcherSettings::default().idle_poll_interval(interval).idle_poll_interval,
    ///     interval
    /// );
    /// ```
    #[must_use]
    pub const fn idle_poll_interval(mut self, idle_poll_interval: Duration) -> Self {
        self.idle_poll_interval = idle_poll_interval;

        self
    }

    /// Sets [`Self::drain_timeout`].
    ///
    /// ```
    /// use reliar_outbox::DispatcherSettings;
    /// use std::time::Duration;
    /// let timeout = Duration::from_secs(15);
    /// assert_eq!(DispatcherSettings::default().drain_timeout(timeout).drain_timeout, timeout);
    /// ```
    #[must_use]
    pub const fn drain_timeout(mut self, drain_timeout: Duration) -> Self {
        self.drain_timeout = drain_timeout;

        self
    }

    /// Sets [`Self::store_timeout`].
    ///
    /// ```
    /// use reliar_outbox::DispatcherSettings;
    /// use std::time::Duration;
    /// let timeout = Duration::from_secs(3);
    /// assert_eq!(DispatcherSettings::default().store_timeout(timeout).store_timeout, timeout);
    /// ```
    #[must_use]
    pub const fn store_timeout(mut self, store_timeout: Duration) -> Self {
        self.store_timeout = store_timeout;

        self
    }

    /// Sets [`Self::stats_interval`].
    ///
    /// ```
    /// use reliar_outbox::DispatcherSettings;
    /// use std::time::Duration;
    /// assert_eq!(
    ///     DispatcherSettings::default().stats_interval(Duration::ZERO).stats_interval,
    ///     Duration::ZERO
    /// );
    /// ```
    #[must_use]
    pub const fn stats_interval(mut self, stats_interval: Duration) -> Self {
        self.stats_interval = stats_interval;

        self
    }

    /// Sets [`Self::ordering`].
    ///
    /// ```
    /// use reliar_outbox::{DispatcherSettings, Ordering};
    /// let settings = DispatcherSettings::default().ordering(Ordering::Unordered);
    /// assert_eq!(settings.ordering, Ordering::Unordered);
    /// ```
    #[must_use]
    pub const fn ordering(mut self, ordering: Ordering) -> Self {
        self.ordering = ordering;

        self
    }

    /// Sets [`Self::retry`].
    ///
    /// ```
    /// use reliar_outbox::{DispatcherSettings, ExponentialBackoff};
    /// let retry = ExponentialBackoff::default().max_attempts(3);
    /// let settings = DispatcherSettings::default().retry(retry);
    /// assert_eq!(settings.retry.max_attempts, 3);
    /// ```
    #[must_use]
    pub const fn retry(mut self, retry: ExponentialBackoff) -> Self {
        self.retry = retry;

        self
    }

    /// Sets [`Self::worker_id`].
    ///
    /// ```
    /// use reliar_outbox::{DispatcherSettings, WorkerId};
    /// let worker = WorkerId::parse("worker-1").unwrap();
    /// let settings = DispatcherSettings::default().worker_id(worker.clone());
    /// assert_eq!(settings.worker_id, Some(worker));
    /// ```
    #[must_use]
    pub fn worker_id(mut self, worker_id: WorkerId) -> Self {
        self.worker_id = Some(worker_id);

        self
    }
}

/// Purge tunables.
///
/// ```
/// use reliar_outbox::RetentionSettings;
/// use std::time::Duration;
///
/// let settings = RetentionSettings::default().dead_retention(Some(Duration::from_secs(30 * 24 * 60 * 60)));
/// assert_eq!(settings.dead_retention, Some(Duration::from_secs(30 * 24 * 60 * 60)));
/// ```
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(default, deny_unknown_fields))]
#[non_exhaustive]
pub struct RetentionSettings {
    /// How long a published row is kept before `purge` deletes it. `PUBLISHED_RETENTION_MS`.
    /// Default 7 days.
    #[cfg_attr(
        feature = "serde",
        serde(
            rename = "published_retention_ms",
            with = "crate::duration_serde::millis"
        )
    )]
    pub published_retention: Duration,

    /// How long a dead row is kept before `purge` deletes it. `None` keeps dead rows until an
    /// explicit purge. `DEAD_RETENTION_MS`. Default `None`.
    ///
    /// # Warning
    ///
    /// The default `None` means [`crate::PurgeRequest::from`] (built from these settings) also
    /// leaves `dead_retention` at `None` — a host that wants dead rows collected must set a
    /// value explicitly; deleting one is always a deliberate act.
    #[cfg_attr(
        feature = "serde",
        serde(
            rename = "dead_retention_ms",
            with = "crate::duration_serde::optional_millis"
        )
    )]
    pub dead_retention: Option<Duration>,

    /// The maximum number of rows one purge pass deletes, per pass. `PURGE_BATCH_SIZE`.
    /// Default 1000.
    pub purge_batch_size: u32,
}

impl Default for RetentionSettings {
    fn default() -> Self {
        Self {
            published_retention: Duration::from_secs(7 * 24 * 60 * 60),
            dead_retention: None,
            purge_batch_size: 1_000,
        }
    }
}

impl RetentionSettings {
    /// Sets [`Self::published_retention`].
    ///
    /// ```
    /// use reliar_outbox::RetentionSettings;
    /// use std::time::Duration;
    /// let retention = Duration::from_secs(24 * 60 * 60);
    /// let settings = RetentionSettings::default().published_retention(retention);
    /// assert_eq!(settings.published_retention, retention);
    /// ```
    #[must_use]
    pub const fn published_retention(mut self, retention: Duration) -> Self {
        self.published_retention = retention;

        self
    }

    /// Sets [`Self::dead_retention`].
    ///
    /// ```
    /// use reliar_outbox::RetentionSettings;
    /// use std::time::Duration;
    /// let settings = RetentionSettings::default().dead_retention(Some(Duration::from_secs(60)));
    /// assert_eq!(settings.dead_retention, Some(Duration::from_secs(60)));
    /// ```
    #[must_use]
    pub const fn dead_retention(mut self, retention: Option<Duration>) -> Self {
        self.dead_retention = retention;

        self
    }

    /// Sets [`Self::purge_batch_size`].
    ///
    /// ```
    /// use reliar_outbox::RetentionSettings;
    /// assert_eq!(RetentionSettings::default().purge_batch_size(200).purge_batch_size, 200);
    /// ```
    #[must_use]
    pub const fn purge_batch_size(mut self, purge_batch_size: u32) -> Self {
        self.purge_batch_size = purge_batch_size;

        self
    }
}

impl OutboxSettings {
    /// Opt-in. Starts from [`Self::default`], overrides **only** the variables present under
    /// `prefix`, and returns `Err` for a present-but-unparseable or out-of-range value — never
    /// a silent fallback to the default. Env variable names are flat under `prefix` (e.g.
    /// `{prefix}LEASE_MS`), regardless of which nested settings struct they populate.
    ///
    /// # Errors
    ///
    /// Returns [`SettingsError::Parse`] for a present variable that cannot be parsed as its
    /// declared type (a bad UTF-8 value counts as unparseable), or
    /// [`SettingsError::OutOfRange`] for one that parses but violates a documented bound (a
    /// `RETRY_JITTER` outside `[0.0, 1.0)`, a `WORKER_ID` over its maximum length).
    ///
    /// ```
    /// use reliar_outbox::OutboxSettings;
    ///
    /// // A prefix with nothing set in the environment falls back to every documented default —
    /// // `from_env` never invents a value, it only overrides what is present.
    /// let settings = OutboxSettings::from_env("RELIAR_OUTBOX_DOCTEST_UNSET_").unwrap();
    /// assert_eq!(settings.dispatcher.batch_size, 100);
    /// ```
    pub fn from_env(prefix: &str) -> Result<Self, SettingsError> {
        let mut dispatcher = DispatcherSettings::default();
        let mut retention = RetentionSettings::default();

        if let Some(v) = env_u32(prefix, "BATCH_SIZE")? {
            dispatcher.batch_size = v;
        }

        if let Some(v) = env_duration_ms(prefix, "LEASE_MS")? {
            dispatcher.lease = v;
        }

        if let Some(v) = env_usize(prefix, "MAX_IN_FLIGHT")? {
            dispatcher.max_in_flight = v;
        }

        if let Some(v) = env_duration_ms(prefix, "PUBLISH_TIMEOUT_MS")? {
            dispatcher.publish_timeout = v;
        }

        if let Some(v) = env_duration_ms(prefix, "POLL_INTERVAL_MS")? {
            dispatcher.poll_interval = v;
        }

        if let Some(v) = env_duration_ms(prefix, "IDLE_POLL_INTERVAL_MS")? {
            dispatcher.idle_poll_interval = v;
        }

        if let Some(v) = env_duration_ms(prefix, "DRAIN_TIMEOUT_MS")? {
            dispatcher.drain_timeout = v;
        }

        if let Some(v) = env_duration_ms(prefix, "STORE_TIMEOUT_MS")? {
            dispatcher.store_timeout = v;
        }

        if let Some(v) = env_duration_ms(prefix, "STATS_INTERVAL_MS")? {
            dispatcher.stats_interval = v;
        }

        if let Some(v) = env_ordering(prefix, "ORDERING")? {
            dispatcher.ordering = v;
        }

        if let Some(v) = env_duration_ms(prefix, "RETRY_BASE_MS")? {
            dispatcher.retry.base = v;
        }

        if let Some(v) = env_duration_ms(prefix, "RETRY_MAX_DELAY_MS")? {
            dispatcher.retry.max_delay = v;
        }

        if let Some(v) = env_u32(prefix, "RETRY_MAX_ATTEMPTS")? {
            dispatcher.retry.max_attempts = v;
        }

        if let Some(v) = env_jitter(prefix, "RETRY_JITTER")? {
            dispatcher.retry.jitter = v;
        }

        if let Some(v) = env_worker_id(prefix, "WORKER_ID")? {
            dispatcher.worker_id = Some(v);
        }

        if let Some(v) = env_duration_ms(prefix, "PUBLISHED_RETENTION_MS")? {
            retention.published_retention = v;
        }

        if let Some(v) = env_duration_ms(prefix, "DEAD_RETENTION_MS")? {
            retention.dead_retention = Some(v);
        }

        if let Some(v) = env_u32(prefix, "PURGE_BATCH_SIZE")? {
            retention.purge_batch_size = v;
        }

        // The retired `{prefix}ENABLED` / `_ALLOWED_TYPES` / `_DISALLOWED_TYPES` keys are neither
        // read nor rejected here: an environment is an open namespace, so a retired-key deny-list
        // would be a permanent tax that could collide with a host's own variable (ADR 0036 §7).

        Ok(Self {
            dispatcher,
            retention,
        })
    }
}

/// Reads one raw environment variable under `prefix`. `Ok(None)` when absent; a present but
/// non-UTF-8 value is treated as unparseable rather than panicking or silently skipping it.
fn env_raw(prefix: &str, suffix: &str) -> Result<Option<String>, SettingsError> {
    let key = format!("{prefix}{suffix}");

    match std::env::var(&key) {
        Ok(value) => Ok(Some(value)),
        Err(VarError::NotPresent) => Ok(None),
        Err(VarError::NotUnicode(_)) => Err(SettingsError::parse(key, "a UTF-8 string")),
    }
}

fn env_u32(prefix: &str, suffix: &str) -> Result<Option<u32>, SettingsError> {
    let Some(raw) = env_raw(prefix, suffix)? else {
        return Ok(None);
    };

    raw.trim()
        .parse::<u32>()
        .map(Some)
        .map_err(|_| SettingsError::parse(format!("{prefix}{suffix}"), "u32"))
}

fn env_usize(prefix: &str, suffix: &str) -> Result<Option<usize>, SettingsError> {
    let Some(raw) = env_raw(prefix, suffix)? else {
        return Ok(None);
    };

    raw.trim()
        .parse::<usize>()
        .map(Some)
        .map_err(|_| SettingsError::parse(format!("{prefix}{suffix}"), "usize"))
}

fn env_duration_ms(prefix: &str, suffix: &str) -> Result<Option<Duration>, SettingsError> {
    let Some(raw) = env_raw(prefix, suffix)? else {
        return Ok(None);
    };
    let ms = raw
        .trim()
        .parse::<u64>()
        .map_err(|_| SettingsError::parse(format!("{prefix}{suffix}"), "milliseconds"))?;

    Ok(Some(Duration::from_millis(ms)))
}

fn env_jitter(prefix: &str, suffix: &str) -> Result<Option<f64>, SettingsError> {
    let Some(raw) = env_raw(prefix, suffix)? else {
        return Ok(None);
    };
    let key = format!("{prefix}{suffix}");
    let value = raw
        .trim()
        .parse::<f64>()
        .map_err(|_| SettingsError::parse(key.clone(), "f64"))?;

    if !(0.0..1.0).contains(&value) {
        return Err(SettingsError::out_of_range(
            key,
            "jitter must be in the range [0.0, 1.0)",
        ));
    }

    Ok(Some(value))
}

fn env_ordering(prefix: &str, suffix: &str) -> Result<Option<Ordering>, SettingsError> {
    let Some(raw) = env_raw(prefix, suffix)? else {
        return Ok(None);
    };

    match raw.trim().to_ascii_lowercase().as_str() {
        "unordered" => Ok(Some(Ordering::Unordered)),
        "per_key" | "perkey" | "per-key" => Ok(Some(Ordering::PerKey)),
        _ => Err(SettingsError::parse(
            format!("{prefix}{suffix}"),
            "ordering (\"unordered\" or \"per_key\")",
        )),
    }
}

fn env_worker_id(prefix: &str, suffix: &str) -> Result<Option<WorkerId>, SettingsError> {
    let Some(raw) = env_raw(prefix, suffix)? else {
        return Ok(None);
    };
    let key = format!("{prefix}{suffix}");

    WorkerId::parse(raw).map(Some).map_err(|err| match err {
        reliar_core::IdError::TooLong { .. } => {
            SettingsError::out_of_range(key, "worker id exceeds the maximum length")
        }
        _ => SettingsError::parse(key, "worker id"),
    })
}