datum-persistence 0.11.3

Event sourcing, durable state, and CQRS persistence for Datum
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
706
707
708
709
//! Managed read-side projection runtime, configuration, and storage contracts.
//!
//! A [`Projection`] is an inert blueprint. Constructing or configuring one
//! starts no source, actor, task, or handler; execution begins only at
//! [`Projection::spawn`] or [`Projection::run_on`].

#[cfg(feature = "cassandra")]
mod cassandra;
mod cursor;
mod error;
mod group;
mod handler;
mod offset_store;
#[cfg(feature = "postgres")]
mod postgres;
mod runtime;
mod source;
pub mod testkit;

use std::{fmt, sync::Arc, time::Duration};

use crate::query::QueryMode;

#[cfg(feature = "cassandra")]
pub use cassandra::{
    CassandraProjectionOffsetStore, CassandraProjectionOffsetStoreConfig,
    CassandraProjectionTableNames,
};
pub use cursor::{
    BoundaryEvent, CursorPosition, DeduplicationBoundary, ProjectionCursor, ProviderManifest,
};
pub use error::{ProjectionError, ProjectionErrorKind, ProjectionResult};
pub use group::{ProjectionGroup, ProjectionGroupHandle};
#[cfg(feature = "postgres")]
pub use handler::{
    ExactlyOncePostgresHandler, GroupedExactlyOncePostgresHandler, PostgresProjectionTx,
};
pub use handler::{GroupedHandler, Handler};
pub use offset_store::{MemoryProjectionOffsetStore, ProjectionGeneration, ProjectionOffsetStore};
#[cfg(feature = "postgres")]
pub use postgres::{
    PostgresProjectionOffsetStore, PostgresProjectionOffsetStoreConfig,
    PostgresProjectionTableNames,
};
pub use runtime::{
    BackoffRng, ProjectionHandle, ProjectionRuntime, ProjectionStatus, StatusObserver,
    restart_delay,
};
pub use source::{
    EventsBySlicesSourceProvider, ProjectionSource, SliceRangeCursor, SourceProvider,
    seed_resharded_slice_range, slice_projection_key,
};
pub use testkit::{
    CrashSaveRequest, DurableProjectionOffsetStoreHarness, ManualPaceProbe, ProjectionTestKit,
    SaveCrashOutcome, SaveCrashPoint, TestEnvelope, TestSourceProvider,
    assert_cursor_codec_conformance, assert_projection_offset_store_durable_conformance,
    assert_projection_offset_store_semantic_conformance,
};

const DEFAULT_SAVE_AFTER_ENVELOPES: usize = 100;
const DEFAULT_SAVE_AFTER_DURATION: Duration = Duration::from_millis(500);
const DEFAULT_GROUP_AFTER_ENVELOPES: usize = 20;
const DEFAULT_GROUP_AFTER_DURATION: Duration = Duration::from_millis(500);
const DEFAULT_RECOVERY_RETRIES: usize = 5;
const DEFAULT_RECOVERY_DELAY: Duration = Duration::from_secs(1);
const DEFAULT_MIN_BACKOFF: Duration = Duration::from_secs(3);
const DEFAULT_MAX_BACKOFF: Duration = Duration::from_secs(30);
const DEFAULT_RANDOM_FACTOR: f64 = 0.2;
const DEFAULT_MAX_RESTARTS_WITHIN: Duration = DEFAULT_MIN_BACKOFF;

type SingleHandlerFactory<Envelope> =
    dyn Fn() -> Box<dyn Handler<Envelope>> + Send + Sync + 'static;
type GroupedHandlerFactory<Envelope> =
    dyn Fn() -> Box<dyn GroupedHandler<Envelope>> + Send + Sync + 'static;
#[cfg(feature = "postgres")]
type ExactlyOncePostgresHandlerFactory<Envelope> =
    dyn Fn() -> Box<dyn ExactlyOncePostgresHandler<Envelope>> + Send + Sync + 'static;
#[cfg(feature = "postgres")]
type GroupedExactlyOncePostgresHandlerFactory<Envelope> =
    dyn Fn() -> Box<dyn GroupedExactlyOncePostgresHandler<Envelope>> + Send + Sync + 'static;

pub(crate) enum ProjectionHandlerFactory<Envelope> {
    Single(Arc<SingleHandlerFactory<Envelope>>),
    Grouped(Arc<GroupedHandlerFactory<Envelope>>),
    #[cfg(feature = "postgres")]
    ExactlyOncePostgres(Arc<ExactlyOncePostgresHandlerFactory<Envelope>>),
    #[cfg(feature = "postgres")]
    GroupedExactlyOncePostgres(Arc<GroupedExactlyOncePostgresHandlerFactory<Envelope>>),
}

/// Delivery ordering implemented by the single-envelope runtime.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum DeliverySemantics {
    /// Invoke the handler before saving, with count/time cursor batching.
    AtLeastOnce,
    /// Save each cursor before invoking its handler.
    AtMostOnce,
}

/// Immutable, side-effect-free projection blueprint.
pub struct Projection<Envelope> {
    pub(crate) projection_id: ProjectionId,
    pub(crate) source_provider: Arc<dyn SourceProvider<Envelope>>,
    pub(crate) handler_factory: ProjectionHandlerFactory<Envelope>,
    pub(crate) delivery: DeliverySemantics,
    pub(crate) query_mode: QueryMode,
    pub(crate) save_offset: SaveOffsetConfig,
    pub(crate) group: GroupConfig,
    pub(crate) recovery_strategy: RecoveryStrategy,
    pub(crate) restart_backoff: RestartBackoff,
    pub(crate) status_observer: Arc<dyn StatusObserver<Envelope>>,
}

impl<Envelope> Projection<Envelope>
where
    Envelope: Send + Sync + 'static,
{
    /// Builds an inert at-least-once projection.
    ///
    /// A fresh handler is constructed from `handler_factory` for every source
    /// incarnation. The provider is not queried until [`Self::spawn`].
    #[must_use]
    pub fn at_least_once<P, F, H>(
        projection_id: ProjectionId,
        source_provider: P,
        handler_factory: F,
    ) -> Self
    where
        P: SourceProvider<Envelope>,
        F: Fn() -> H + Send + Sync + 'static,
        H: Handler<Envelope>,
    {
        Self::new(
            projection_id,
            source_provider,
            handler_factory,
            DeliverySemantics::AtLeastOnce,
        )
    }

    /// Builds an inert grouped at-least-once projection.
    ///
    /// Envelopes are delivered to one grouped-handler invocation after either
    /// [`GroupConfig::group_after_envelopes`] or
    /// [`GroupConfig::group_after_duration`] is reached, whichever happens
    /// first. The cursor is saved after every successful whole-group
    /// invocation; [`SaveOffsetConfig`] does not apply to grouped delivery.
    /// A fresh handler is constructed for every source incarnation.
    #[must_use]
    pub fn grouped_at_least_once<P, F, H>(
        projection_id: ProjectionId,
        source_provider: P,
        handler_factory: F,
    ) -> Self
    where
        P: SourceProvider<Envelope>,
        F: Fn() -> H + Send + Sync + 'static,
        H: GroupedHandler<Envelope>,
    {
        Self {
            projection_id,
            source_provider: Arc::new(source_provider),
            handler_factory: ProjectionHandlerFactory::Grouped(Arc::new(move || {
                Box::new(handler_factory()) as Box<dyn GroupedHandler<Envelope>>
            })),
            delivery: DeliverySemantics::AtLeastOnce,
            query_mode: QueryMode::Live,
            save_offset: SaveOffsetConfig::default(),
            group: GroupConfig::default(),
            recovery_strategy: RecoveryStrategy::default(),
            restart_backoff: RestartBackoff::default(),
            status_observer: Arc::new(runtime::NoopStatusObserver),
        }
    }

    /// Builds an inert PostgreSQL exactly-once projection.
    ///
    /// The runtime must use [`PostgresProjectionOffsetStore`]. For each
    /// invocation it locks the offset row and validates the current owner
    /// generation and expected position before calling the handler. User
    /// writes and the provider-complete cursor then commit in the same
    /// transaction.
    ///
    /// A skipped invocation is the documented exception: the failed handler
    /// transaction rolls back and a separate cursor-only transaction advances
    /// past it.
    #[cfg(feature = "postgres")]
    #[must_use]
    pub fn exactly_once_postgres<P, F, H>(
        projection_id: ProjectionId,
        source_provider: P,
        handler_factory: F,
    ) -> Self
    where
        P: SourceProvider<Envelope>,
        F: Fn() -> H + Send + Sync + 'static,
        H: ExactlyOncePostgresHandler<Envelope>,
    {
        Self {
            projection_id,
            source_provider: Arc::new(source_provider),
            handler_factory: ProjectionHandlerFactory::ExactlyOncePostgres(Arc::new(move || {
                Box::new(handler_factory()) as Box<dyn ExactlyOncePostgresHandler<Envelope>>
            })),
            delivery: DeliverySemantics::AtLeastOnce,
            query_mode: QueryMode::Live,
            save_offset: SaveOffsetConfig::default(),
            group: GroupConfig::default(),
            recovery_strategy: RecoveryStrategy::default(),
            restart_backoff: RestartBackoff::default(),
            status_observer: Arc::new(runtime::NoopStatusObserver),
        }
    }

    /// Builds an inert grouped PostgreSQL exactly-once projection.
    ///
    /// One transaction contains every write made for the complete group and
    /// the cursor at its final envelope. Retry and skip operate on that whole
    /// group. A skipped group rolls back its handler transaction and advances
    /// only the cursor in a separate transaction.
    #[cfg(feature = "postgres")]
    #[must_use]
    pub fn grouped_exactly_once_postgres<P, F, H>(
        projection_id: ProjectionId,
        source_provider: P,
        handler_factory: F,
    ) -> Self
    where
        P: SourceProvider<Envelope>,
        F: Fn() -> H + Send + Sync + 'static,
        H: GroupedExactlyOncePostgresHandler<Envelope>,
    {
        Self {
            projection_id,
            source_provider: Arc::new(source_provider),
            handler_factory: ProjectionHandlerFactory::GroupedExactlyOncePostgres(Arc::new(
                move || {
                    Box::new(handler_factory())
                        as Box<dyn GroupedExactlyOncePostgresHandler<Envelope>>
                },
            )),
            delivery: DeliverySemantics::AtLeastOnce,
            query_mode: QueryMode::Live,
            save_offset: SaveOffsetConfig::default(),
            group: GroupConfig::default(),
            recovery_strategy: RecoveryStrategy::default(),
            restart_backoff: RestartBackoff::default(),
            status_observer: Arc::new(runtime::NoopStatusObserver),
        }
    }

    /// Builds an inert at-most-once projection.
    ///
    /// The runtime performs one fenced cursor save before every handler
    /// invocation; [`SaveOffsetConfig`] does not apply to this mode.
    #[must_use]
    pub fn at_most_once<P, F, H>(
        projection_id: ProjectionId,
        source_provider: P,
        handler_factory: F,
    ) -> Self
    where
        P: SourceProvider<Envelope>,
        F: Fn() -> H + Send + Sync + 'static,
        H: Handler<Envelope>,
    {
        Self::new(
            projection_id,
            source_provider,
            handler_factory,
            DeliverySemantics::AtMostOnce,
        )
    }

    fn new<P, F, H>(
        projection_id: ProjectionId,
        source_provider: P,
        handler_factory: F,
        delivery: DeliverySemantics,
    ) -> Self
    where
        P: SourceProvider<Envelope>,
        F: Fn() -> H + Send + Sync + 'static,
        H: Handler<Envelope>,
    {
        Self {
            projection_id,
            source_provider: Arc::new(source_provider),
            handler_factory: ProjectionHandlerFactory::Single(Arc::new(move || {
                Box::new(handler_factory()) as Box<dyn Handler<Envelope>>
            })),
            delivery,
            query_mode: QueryMode::Live,
            save_offset: SaveOffsetConfig::default(),
            group: GroupConfig::default(),
            recovery_strategy: RecoveryStrategy::default(),
            restart_backoff: RestartBackoff::default(),
            status_observer: Arc::new(runtime::NoopStatusObserver),
        }
    }

    /// Returns this projection's durable identity.
    #[must_use]
    pub fn projection_id(&self) -> &ProjectionId {
        &self.projection_id
    }

    /// Selects a live or current query materialization.
    #[must_use]
    pub fn with_query_mode(mut self, mode: QueryMode) -> Self {
        self.query_mode = mode;
        self
    }

    /// Selects the single-envelope at-least-once count/time save cadence.
    ///
    /// This setting is ignored by at-most-once and grouped projections.
    #[must_use]
    pub fn with_save_offset(mut self, config: SaveOffsetConfig) -> Self {
        self.save_offset = config;
        self
    }

    /// Selects the count/time grouping cadence for grouped delivery.
    ///
    /// This setting is ignored by single-envelope projections.
    #[must_use]
    pub fn with_group(mut self, config: GroupConfig) -> Self {
        self.group = config;
        self
    }

    /// Selects per-envelope handler recovery.
    #[must_use]
    pub fn with_recovery_strategy(mut self, strategy: RecoveryStrategy) -> Self {
        self.recovery_strategy = strategy;
        self
    }

    /// Selects complete-incarnation restart backoff.
    #[must_use]
    pub fn with_restart_backoff(mut self, backoff: RestartBackoff) -> Self {
        self.restart_backoff = backoff;
        self
    }

    /// Installs a progress and lifecycle observer.
    #[must_use]
    pub fn with_status_observer<O>(mut self, observer: O) -> Self
    where
        O: StatusObserver<Envelope>,
    {
        self.status_observer = Arc::new(observer);
        self
    }

    /// Spawns the Ractor shell and begins projection execution.
    pub async fn spawn(self, runtime: ProjectionRuntime) -> ProjectionResult<ProjectionHandle> {
        runtime::spawn(self, runtime).await
    }

    /// Alias for [`Self::spawn`] emphasizing execution on the Tokio runtime.
    pub async fn run_on(self, runtime: ProjectionRuntime) -> ProjectionResult<ProjectionHandle> {
        self.spawn(runtime).await
    }

    pub(crate) fn validate(&self) -> ProjectionResult<()> {
        self.projection_id.validate()?;
        self.source_provider
            .validate_projection_id(&self.projection_id)?;
        if self.is_grouped() {
            self.group.validate()?;
        } else if self.delivery == DeliverySemantics::AtLeastOnce {
            self.save_offset.validate()?;
        }
        self.restart_backoff.validate()
    }

    pub(crate) const fn is_grouped(&self) -> bool {
        match &self.handler_factory {
            ProjectionHandlerFactory::Grouped(_) => true,
            #[cfg(feature = "postgres")]
            ProjectionHandlerFactory::GroupedExactlyOncePostgres(_) => true,
            _ => false,
        }
    }

    #[cfg(feature = "postgres")]
    pub(crate) const fn is_exactly_once_postgres(&self) -> bool {
        matches!(
            &self.handler_factory,
            ProjectionHandlerFactory::ExactlyOncePostgres(_)
                | ProjectionHandlerFactory::GroupedExactlyOncePostgres(_)
        )
    }
}

/// Stable identity of one projection instance.
///
/// A projection name identifies a logical projection, while its key identifies
/// one independently owned instance of that projection. The pair is the offset
/// store key and must be unique among concurrently running instances.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ProjectionId {
    name: String,
    key: String,
}

impl ProjectionId {
    /// Creates a projection identity.
    ///
    /// Construction is side-effect-free. Call [`Self::validate`] before using
    /// an identity to spawn a projection or claim an offset-store generation.
    #[must_use]
    pub fn new(name: impl Into<String>, key: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            key: key.into(),
        }
    }

    /// Returns the logical projection name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the independently owned projection-instance key.
    #[must_use]
    pub fn key(&self) -> &str {
        &self.key
    }

    /// Validates that both durable identity components are non-blank.
    pub fn validate(&self) -> ProjectionResult<()> {
        if self.name.trim().is_empty() {
            return Err(ProjectionError::invalid_config(
                "projection_id.name",
                "projection name must not be blank",
            ));
        }
        if self.key.trim().is_empty() {
            return Err(ProjectionError::invalid_config(
                "projection_id.key",
                "projection key must not be blank",
            ));
        }
        Ok(())
    }
}

impl fmt::Display for ProjectionId {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "{}:{}", self.name, self.key)
    }
}

/// At-least-once cursor-save cadence.
///
/// A running projection saves after either threshold is reached, whichever
/// happens first. The defaults mirror Akka Projection: 100 envelopes or
/// 500 milliseconds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SaveOffsetConfig {
    /// Number of successfully handled envelopes between cursor saves.
    pub after_envelopes: usize,
    /// Maximum elapsed time between cursor saves while envelopes are flowing.
    pub after_duration: Duration,
}

impl SaveOffsetConfig {
    /// Validates that both cadence thresholds are greater than zero.
    pub fn validate(&self) -> ProjectionResult<()> {
        validate_positive_count("save_offset.after_envelopes", self.after_envelopes)?;
        validate_positive_duration("save_offset.after_duration", self.after_duration)
    }
}

impl Default for SaveOffsetConfig {
    fn default() -> Self {
        Self {
            after_envelopes: DEFAULT_SAVE_AFTER_ENVELOPES,
            after_duration: DEFAULT_SAVE_AFTER_DURATION,
        }
    }
}

/// Grouped-handler batching cadence.
///
/// A group closes after either threshold is reached, whichever happens first.
/// The defaults mirror Akka Projection: 20 envelopes or 500 milliseconds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GroupConfig {
    /// Maximum envelopes in one handler invocation.
    pub group_after_envelopes: usize,
    /// Maximum time an incomplete group remains open while envelopes flow.
    pub group_after_duration: Duration,
}

impl GroupConfig {
    /// Validates that both grouping thresholds are greater than zero.
    pub fn validate(&self) -> ProjectionResult<()> {
        validate_positive_count("group.group_after_envelopes", self.group_after_envelopes)?;
        validate_positive_duration("group.group_after_duration", self.group_after_duration)
    }
}

impl Default for GroupConfig {
    fn default() -> Self {
        Self {
            group_after_envelopes: DEFAULT_GROUP_AFTER_ENVELOPES,
            group_after_duration: DEFAULT_GROUP_AFTER_DURATION,
        }
    }
}

/// Per-handler-invocation recovery policy.
///
/// For single-envelope handlers the invocation unit is one envelope; for
/// grouped handlers it is the complete group. Handler failures are governed by
/// this policy and are intentionally separate from [`ProjectionError`]'s
/// fatal-versus-restartable infrastructure taxonomy.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum RecoveryStrategy {
    /// Do not retry; escalate immediately to projection restart.
    #[default]
    Fail,
    /// Discard the failed invocation and continue.
    Skip,
    /// Retry in order, then escalate to projection restart on exhaustion.
    RetryAndFail {
        /// Number of retry attempts after the initial failed invocation.
        retries: usize,
        /// Delay between retry attempts.
        delay: Duration,
    },
    /// Retry in order, then discard the invocation on exhaustion.
    RetryAndSkip {
        /// Number of retry attempts after the initial failed invocation.
        retries: usize,
        /// Delay between retry attempts.
        delay: Duration,
    },
}

impl RecoveryStrategy {
    /// Creates retry-then-fail recovery with the Akka defaults: five retries,
    /// one second apart.
    #[must_use]
    pub const fn retry_and_fail() -> Self {
        Self::RetryAndFail {
            retries: DEFAULT_RECOVERY_RETRIES,
            delay: DEFAULT_RECOVERY_DELAY,
        }
    }

    /// Creates retry-then-skip recovery with the Akka defaults: five retries,
    /// one second apart.
    #[must_use]
    pub const fn retry_and_skip() -> Self {
        Self::RetryAndSkip {
            retries: DEFAULT_RECOVERY_RETRIES,
            delay: DEFAULT_RECOVERY_DELAY,
        }
    }
}

/// Projection-level restart backoff.
///
/// The runtime applies jitter after capping the exponential base delay:
/// `min(min_backoff * 2^failures, max_backoff) *
/// (1 + U(0, random_factor))`. `None` for [`Self::max_restarts`] means
/// unlimited restarts. The restart count is reset after
/// [`Self::max_restarts_within`], matching Akka's `maxRestartsWithin`
/// tracking-window semantics.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RestartBackoff {
    /// Initial exponential backoff.
    pub min_backoff: Duration,
    /// Cap applied before jitter.
    pub max_backoff: Duration,
    /// Non-negative jitter fraction. Values above one are rejected.
    pub random_factor: f64,
    /// Maximum restarts within [`Self::max_restarts_within`], or `None` for
    /// unlimited restarts.
    pub max_restarts: Option<usize>,
    /// Window that bounds [`Self::max_restarts`].
    ///
    /// The Akka-parity default is the initial backoff, three seconds.
    pub max_restarts_within: Duration,
}

impl RestartBackoff {
    /// Validates backoff ordering and the finite `0.0..=1.0` jitter range.
    ///
    /// Zero delays and `Some(0)` restarts are valid, which permits
    /// deterministic tests and explicitly disables restarting respectively.
    pub fn validate(&self) -> ProjectionResult<()> {
        if self.min_backoff > self.max_backoff {
            return Err(ProjectionError::invalid_config(
                "restart_backoff",
                "min_backoff must not exceed max_backoff",
            ));
        }
        if !self.random_factor.is_finite() || !(0.0..=1.0).contains(&self.random_factor) {
            return Err(ProjectionError::invalid_config(
                "restart_backoff.random_factor",
                "random_factor must be finite and between 0.0 and 1.0",
            ));
        }
        Ok(())
    }
}

impl Default for RestartBackoff {
    fn default() -> Self {
        Self {
            min_backoff: DEFAULT_MIN_BACKOFF,
            max_backoff: DEFAULT_MAX_BACKOFF,
            random_factor: DEFAULT_RANDOM_FACTOR,
            max_restarts: None,
            max_restarts_within: DEFAULT_MAX_RESTARTS_WITHIN,
        }
    }
}

fn validate_positive_count(setting: &'static str, count: usize) -> ProjectionResult<()> {
    if count == 0 {
        return Err(ProjectionError::invalid_config(
            setting,
            "value must be greater than zero",
        ));
    }
    Ok(())
}

fn validate_positive_duration(setting: &'static str, duration: Duration) -> ProjectionResult<()> {
    if duration.is_zero() {
        return Err(ProjectionError::invalid_config(
            setting,
            "duration must be greater than zero",
        ));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn configuration_defaults_match_akka_projection() {
        assert_eq!(
            SaveOffsetConfig::default(),
            SaveOffsetConfig {
                after_envelopes: 100,
                after_duration: Duration::from_millis(500),
            }
        );
        assert_eq!(
            GroupConfig::default(),
            GroupConfig {
                group_after_envelopes: 20,
                group_after_duration: Duration::from_millis(500),
            }
        );
        assert_eq!(RecoveryStrategy::default(), RecoveryStrategy::Fail);
        assert_eq!(
            RecoveryStrategy::retry_and_fail(),
            RecoveryStrategy::RetryAndFail {
                retries: 5,
                delay: Duration::from_secs(1),
            }
        );
        assert_eq!(
            RecoveryStrategy::retry_and_skip(),
            RecoveryStrategy::RetryAndSkip {
                retries: 5,
                delay: Duration::from_secs(1),
            }
        );
        assert_eq!(
            RestartBackoff::default(),
            RestartBackoff {
                min_backoff: Duration::from_secs(3),
                max_backoff: Duration::from_secs(30),
                random_factor: 0.2,
                max_restarts: None,
                max_restarts_within: Duration::from_secs(3),
            }
        );
    }

    #[test]
    fn invalid_configuration_is_fatal() {
        let error = ProjectionId::new("", "key")
            .validate()
            .expect_err("blank projection names must fail validation");
        assert_eq!(error.kind(), ProjectionErrorKind::Fatal);

        let error = RestartBackoff {
            random_factor: f64::NAN,
            ..RestartBackoff::default()
        }
        .validate()
        .expect_err("NaN jitter must fail validation");
        assert!(error.is_fatal());
    }
}