Skip to main content

datum_persistence/projection/
mod.rs

1//! Managed read-side projection runtime, configuration, and storage contracts.
2//!
3//! A [`Projection`] is an inert blueprint. Constructing or configuring one
4//! starts no source, actor, task, or handler; execution begins only at
5//! [`Projection::spawn`] or [`Projection::run_on`].
6
7#[cfg(feature = "cassandra")]
8mod cassandra;
9mod cursor;
10mod error;
11mod group;
12mod handler;
13mod offset_store;
14#[cfg(feature = "postgres")]
15mod postgres;
16mod runtime;
17mod source;
18pub mod testkit;
19
20use std::{fmt, sync::Arc, time::Duration};
21
22use crate::query::QueryMode;
23
24#[cfg(feature = "cassandra")]
25pub use cassandra::{
26    CassandraProjectionOffsetStore, CassandraProjectionOffsetStoreConfig,
27    CassandraProjectionTableNames,
28};
29pub use cursor::{
30    BoundaryEvent, CursorPosition, DeduplicationBoundary, ProjectionCursor, ProviderManifest,
31};
32pub use error::{ProjectionError, ProjectionErrorKind, ProjectionResult};
33pub use group::{ProjectionGroup, ProjectionGroupHandle};
34#[cfg(feature = "postgres")]
35pub use handler::{
36    ExactlyOncePostgresHandler, GroupedExactlyOncePostgresHandler, PostgresProjectionTx,
37};
38pub use handler::{GroupedHandler, Handler};
39pub use offset_store::{MemoryProjectionOffsetStore, ProjectionGeneration, ProjectionOffsetStore};
40#[cfg(feature = "postgres")]
41pub use postgres::{
42    PostgresProjectionOffsetStore, PostgresProjectionOffsetStoreConfig,
43    PostgresProjectionTableNames,
44};
45pub use runtime::{
46    BackoffRng, ProjectionHandle, ProjectionRuntime, ProjectionStatus, StatusObserver,
47    restart_delay,
48};
49pub use source::{
50    EventsBySlicesSourceProvider, ProjectionSource, SliceRangeCursor, SourceProvider,
51    seed_resharded_slice_range, slice_projection_key,
52};
53pub use testkit::{
54    CrashSaveRequest, DurableProjectionOffsetStoreHarness, ManualPaceProbe, ProjectionTestKit,
55    SaveCrashOutcome, SaveCrashPoint, TestEnvelope, TestSourceProvider,
56    assert_cursor_codec_conformance, assert_projection_offset_store_durable_conformance,
57    assert_projection_offset_store_semantic_conformance,
58};
59
60const DEFAULT_SAVE_AFTER_ENVELOPES: usize = 100;
61const DEFAULT_SAVE_AFTER_DURATION: Duration = Duration::from_millis(500);
62const DEFAULT_GROUP_AFTER_ENVELOPES: usize = 20;
63const DEFAULT_GROUP_AFTER_DURATION: Duration = Duration::from_millis(500);
64const DEFAULT_RECOVERY_RETRIES: usize = 5;
65const DEFAULT_RECOVERY_DELAY: Duration = Duration::from_secs(1);
66const DEFAULT_MIN_BACKOFF: Duration = Duration::from_secs(3);
67const DEFAULT_MAX_BACKOFF: Duration = Duration::from_secs(30);
68const DEFAULT_RANDOM_FACTOR: f64 = 0.2;
69const DEFAULT_MAX_RESTARTS_WITHIN: Duration = DEFAULT_MIN_BACKOFF;
70
71type SingleHandlerFactory<Envelope> =
72    dyn Fn() -> Box<dyn Handler<Envelope>> + Send + Sync + 'static;
73type GroupedHandlerFactory<Envelope> =
74    dyn Fn() -> Box<dyn GroupedHandler<Envelope>> + Send + Sync + 'static;
75#[cfg(feature = "postgres")]
76type ExactlyOncePostgresHandlerFactory<Envelope> =
77    dyn Fn() -> Box<dyn ExactlyOncePostgresHandler<Envelope>> + Send + Sync + 'static;
78#[cfg(feature = "postgres")]
79type GroupedExactlyOncePostgresHandlerFactory<Envelope> =
80    dyn Fn() -> Box<dyn GroupedExactlyOncePostgresHandler<Envelope>> + Send + Sync + 'static;
81
82pub(crate) enum ProjectionHandlerFactory<Envelope> {
83    Single(Arc<SingleHandlerFactory<Envelope>>),
84    Grouped(Arc<GroupedHandlerFactory<Envelope>>),
85    #[cfg(feature = "postgres")]
86    ExactlyOncePostgres(Arc<ExactlyOncePostgresHandlerFactory<Envelope>>),
87    #[cfg(feature = "postgres")]
88    GroupedExactlyOncePostgres(Arc<GroupedExactlyOncePostgresHandlerFactory<Envelope>>),
89}
90
91/// Delivery ordering implemented by the single-envelope runtime.
92#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
93pub enum DeliverySemantics {
94    /// Invoke the handler before saving, with count/time cursor batching.
95    AtLeastOnce,
96    /// Save each cursor before invoking its handler.
97    AtMostOnce,
98}
99
100/// Immutable, side-effect-free projection blueprint.
101pub struct Projection<Envelope> {
102    pub(crate) projection_id: ProjectionId,
103    pub(crate) source_provider: Arc<dyn SourceProvider<Envelope>>,
104    pub(crate) handler_factory: ProjectionHandlerFactory<Envelope>,
105    pub(crate) delivery: DeliverySemantics,
106    pub(crate) query_mode: QueryMode,
107    pub(crate) save_offset: SaveOffsetConfig,
108    pub(crate) group: GroupConfig,
109    pub(crate) recovery_strategy: RecoveryStrategy,
110    pub(crate) restart_backoff: RestartBackoff,
111    pub(crate) status_observer: Arc<dyn StatusObserver<Envelope>>,
112}
113
114impl<Envelope> Projection<Envelope>
115where
116    Envelope: Send + Sync + 'static,
117{
118    /// Builds an inert at-least-once projection.
119    ///
120    /// A fresh handler is constructed from `handler_factory` for every source
121    /// incarnation. The provider is not queried until [`Self::spawn`].
122    #[must_use]
123    pub fn at_least_once<P, F, H>(
124        projection_id: ProjectionId,
125        source_provider: P,
126        handler_factory: F,
127    ) -> Self
128    where
129        P: SourceProvider<Envelope>,
130        F: Fn() -> H + Send + Sync + 'static,
131        H: Handler<Envelope>,
132    {
133        Self::new(
134            projection_id,
135            source_provider,
136            handler_factory,
137            DeliverySemantics::AtLeastOnce,
138        )
139    }
140
141    /// Builds an inert grouped at-least-once projection.
142    ///
143    /// Envelopes are delivered to one grouped-handler invocation after either
144    /// [`GroupConfig::group_after_envelopes`] or
145    /// [`GroupConfig::group_after_duration`] is reached, whichever happens
146    /// first. The cursor is saved after every successful whole-group
147    /// invocation; [`SaveOffsetConfig`] does not apply to grouped delivery.
148    /// A fresh handler is constructed for every source incarnation.
149    #[must_use]
150    pub fn grouped_at_least_once<P, F, H>(
151        projection_id: ProjectionId,
152        source_provider: P,
153        handler_factory: F,
154    ) -> Self
155    where
156        P: SourceProvider<Envelope>,
157        F: Fn() -> H + Send + Sync + 'static,
158        H: GroupedHandler<Envelope>,
159    {
160        Self {
161            projection_id,
162            source_provider: Arc::new(source_provider),
163            handler_factory: ProjectionHandlerFactory::Grouped(Arc::new(move || {
164                Box::new(handler_factory()) as Box<dyn GroupedHandler<Envelope>>
165            })),
166            delivery: DeliverySemantics::AtLeastOnce,
167            query_mode: QueryMode::Live,
168            save_offset: SaveOffsetConfig::default(),
169            group: GroupConfig::default(),
170            recovery_strategy: RecoveryStrategy::default(),
171            restart_backoff: RestartBackoff::default(),
172            status_observer: Arc::new(runtime::NoopStatusObserver),
173        }
174    }
175
176    /// Builds an inert PostgreSQL exactly-once projection.
177    ///
178    /// The runtime must use [`PostgresProjectionOffsetStore`]. For each
179    /// invocation it locks the offset row and validates the current owner
180    /// generation and expected position before calling the handler. User
181    /// writes and the provider-complete cursor then commit in the same
182    /// transaction.
183    ///
184    /// A skipped invocation is the documented exception: the failed handler
185    /// transaction rolls back and a separate cursor-only transaction advances
186    /// past it.
187    #[cfg(feature = "postgres")]
188    #[must_use]
189    pub fn exactly_once_postgres<P, F, H>(
190        projection_id: ProjectionId,
191        source_provider: P,
192        handler_factory: F,
193    ) -> Self
194    where
195        P: SourceProvider<Envelope>,
196        F: Fn() -> H + Send + Sync + 'static,
197        H: ExactlyOncePostgresHandler<Envelope>,
198    {
199        Self {
200            projection_id,
201            source_provider: Arc::new(source_provider),
202            handler_factory: ProjectionHandlerFactory::ExactlyOncePostgres(Arc::new(move || {
203                Box::new(handler_factory()) as Box<dyn ExactlyOncePostgresHandler<Envelope>>
204            })),
205            delivery: DeliverySemantics::AtLeastOnce,
206            query_mode: QueryMode::Live,
207            save_offset: SaveOffsetConfig::default(),
208            group: GroupConfig::default(),
209            recovery_strategy: RecoveryStrategy::default(),
210            restart_backoff: RestartBackoff::default(),
211            status_observer: Arc::new(runtime::NoopStatusObserver),
212        }
213    }
214
215    /// Builds an inert grouped PostgreSQL exactly-once projection.
216    ///
217    /// One transaction contains every write made for the complete group and
218    /// the cursor at its final envelope. Retry and skip operate on that whole
219    /// group. A skipped group rolls back its handler transaction and advances
220    /// only the cursor in a separate transaction.
221    #[cfg(feature = "postgres")]
222    #[must_use]
223    pub fn grouped_exactly_once_postgres<P, F, H>(
224        projection_id: ProjectionId,
225        source_provider: P,
226        handler_factory: F,
227    ) -> Self
228    where
229        P: SourceProvider<Envelope>,
230        F: Fn() -> H + Send + Sync + 'static,
231        H: GroupedExactlyOncePostgresHandler<Envelope>,
232    {
233        Self {
234            projection_id,
235            source_provider: Arc::new(source_provider),
236            handler_factory: ProjectionHandlerFactory::GroupedExactlyOncePostgres(Arc::new(
237                move || {
238                    Box::new(handler_factory())
239                        as Box<dyn GroupedExactlyOncePostgresHandler<Envelope>>
240                },
241            )),
242            delivery: DeliverySemantics::AtLeastOnce,
243            query_mode: QueryMode::Live,
244            save_offset: SaveOffsetConfig::default(),
245            group: GroupConfig::default(),
246            recovery_strategy: RecoveryStrategy::default(),
247            restart_backoff: RestartBackoff::default(),
248            status_observer: Arc::new(runtime::NoopStatusObserver),
249        }
250    }
251
252    /// Builds an inert at-most-once projection.
253    ///
254    /// The runtime performs one fenced cursor save before every handler
255    /// invocation; [`SaveOffsetConfig`] does not apply to this mode.
256    #[must_use]
257    pub fn at_most_once<P, F, H>(
258        projection_id: ProjectionId,
259        source_provider: P,
260        handler_factory: F,
261    ) -> Self
262    where
263        P: SourceProvider<Envelope>,
264        F: Fn() -> H + Send + Sync + 'static,
265        H: Handler<Envelope>,
266    {
267        Self::new(
268            projection_id,
269            source_provider,
270            handler_factory,
271            DeliverySemantics::AtMostOnce,
272        )
273    }
274
275    fn new<P, F, H>(
276        projection_id: ProjectionId,
277        source_provider: P,
278        handler_factory: F,
279        delivery: DeliverySemantics,
280    ) -> Self
281    where
282        P: SourceProvider<Envelope>,
283        F: Fn() -> H + Send + Sync + 'static,
284        H: Handler<Envelope>,
285    {
286        Self {
287            projection_id,
288            source_provider: Arc::new(source_provider),
289            handler_factory: ProjectionHandlerFactory::Single(Arc::new(move || {
290                Box::new(handler_factory()) as Box<dyn Handler<Envelope>>
291            })),
292            delivery,
293            query_mode: QueryMode::Live,
294            save_offset: SaveOffsetConfig::default(),
295            group: GroupConfig::default(),
296            recovery_strategy: RecoveryStrategy::default(),
297            restart_backoff: RestartBackoff::default(),
298            status_observer: Arc::new(runtime::NoopStatusObserver),
299        }
300    }
301
302    /// Returns this projection's durable identity.
303    #[must_use]
304    pub fn projection_id(&self) -> &ProjectionId {
305        &self.projection_id
306    }
307
308    /// Selects a live or current query materialization.
309    #[must_use]
310    pub fn with_query_mode(mut self, mode: QueryMode) -> Self {
311        self.query_mode = mode;
312        self
313    }
314
315    /// Selects the single-envelope at-least-once count/time save cadence.
316    ///
317    /// This setting is ignored by at-most-once and grouped projections.
318    #[must_use]
319    pub fn with_save_offset(mut self, config: SaveOffsetConfig) -> Self {
320        self.save_offset = config;
321        self
322    }
323
324    /// Selects the count/time grouping cadence for grouped delivery.
325    ///
326    /// This setting is ignored by single-envelope projections.
327    #[must_use]
328    pub fn with_group(mut self, config: GroupConfig) -> Self {
329        self.group = config;
330        self
331    }
332
333    /// Selects per-envelope handler recovery.
334    #[must_use]
335    pub fn with_recovery_strategy(mut self, strategy: RecoveryStrategy) -> Self {
336        self.recovery_strategy = strategy;
337        self
338    }
339
340    /// Selects complete-incarnation restart backoff.
341    #[must_use]
342    pub fn with_restart_backoff(mut self, backoff: RestartBackoff) -> Self {
343        self.restart_backoff = backoff;
344        self
345    }
346
347    /// Installs a progress and lifecycle observer.
348    #[must_use]
349    pub fn with_status_observer<O>(mut self, observer: O) -> Self
350    where
351        O: StatusObserver<Envelope>,
352    {
353        self.status_observer = Arc::new(observer);
354        self
355    }
356
357    /// Spawns the Ractor shell and begins projection execution.
358    pub async fn spawn(self, runtime: ProjectionRuntime) -> ProjectionResult<ProjectionHandle> {
359        runtime::spawn(self, runtime).await
360    }
361
362    /// Alias for [`Self::spawn`] emphasizing execution on the Tokio runtime.
363    pub async fn run_on(self, runtime: ProjectionRuntime) -> ProjectionResult<ProjectionHandle> {
364        self.spawn(runtime).await
365    }
366
367    pub(crate) fn validate(&self) -> ProjectionResult<()> {
368        self.projection_id.validate()?;
369        self.source_provider
370            .validate_projection_id(&self.projection_id)?;
371        if self.is_grouped() {
372            self.group.validate()?;
373        } else if self.delivery == DeliverySemantics::AtLeastOnce {
374            self.save_offset.validate()?;
375        }
376        self.restart_backoff.validate()
377    }
378
379    pub(crate) const fn is_grouped(&self) -> bool {
380        match &self.handler_factory {
381            ProjectionHandlerFactory::Grouped(_) => true,
382            #[cfg(feature = "postgres")]
383            ProjectionHandlerFactory::GroupedExactlyOncePostgres(_) => true,
384            _ => false,
385        }
386    }
387
388    #[cfg(feature = "postgres")]
389    pub(crate) const fn is_exactly_once_postgres(&self) -> bool {
390        matches!(
391            &self.handler_factory,
392            ProjectionHandlerFactory::ExactlyOncePostgres(_)
393                | ProjectionHandlerFactory::GroupedExactlyOncePostgres(_)
394        )
395    }
396}
397
398/// Stable identity of one projection instance.
399///
400/// A projection name identifies a logical projection, while its key identifies
401/// one independently owned instance of that projection. The pair is the offset
402/// store key and must be unique among concurrently running instances.
403#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
404pub struct ProjectionId {
405    name: String,
406    key: String,
407}
408
409impl ProjectionId {
410    /// Creates a projection identity.
411    ///
412    /// Construction is side-effect-free. Call [`Self::validate`] before using
413    /// an identity to spawn a projection or claim an offset-store generation.
414    #[must_use]
415    pub fn new(name: impl Into<String>, key: impl Into<String>) -> Self {
416        Self {
417            name: name.into(),
418            key: key.into(),
419        }
420    }
421
422    /// Returns the logical projection name.
423    #[must_use]
424    pub fn name(&self) -> &str {
425        &self.name
426    }
427
428    /// Returns the independently owned projection-instance key.
429    #[must_use]
430    pub fn key(&self) -> &str {
431        &self.key
432    }
433
434    /// Validates that both durable identity components are non-blank.
435    pub fn validate(&self) -> ProjectionResult<()> {
436        if self.name.trim().is_empty() {
437            return Err(ProjectionError::invalid_config(
438                "projection_id.name",
439                "projection name must not be blank",
440            ));
441        }
442        if self.key.trim().is_empty() {
443            return Err(ProjectionError::invalid_config(
444                "projection_id.key",
445                "projection key must not be blank",
446            ));
447        }
448        Ok(())
449    }
450}
451
452impl fmt::Display for ProjectionId {
453    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
454        write!(formatter, "{}:{}", self.name, self.key)
455    }
456}
457
458/// At-least-once cursor-save cadence.
459///
460/// A running projection saves after either threshold is reached, whichever
461/// happens first. The defaults mirror Akka Projection: 100 envelopes or
462/// 500 milliseconds.
463#[derive(Debug, Clone, Copy, PartialEq, Eq)]
464pub struct SaveOffsetConfig {
465    /// Number of successfully handled envelopes between cursor saves.
466    pub after_envelopes: usize,
467    /// Maximum elapsed time between cursor saves while envelopes are flowing.
468    pub after_duration: Duration,
469}
470
471impl SaveOffsetConfig {
472    /// Validates that both cadence thresholds are greater than zero.
473    pub fn validate(&self) -> ProjectionResult<()> {
474        validate_positive_count("save_offset.after_envelopes", self.after_envelopes)?;
475        validate_positive_duration("save_offset.after_duration", self.after_duration)
476    }
477}
478
479impl Default for SaveOffsetConfig {
480    fn default() -> Self {
481        Self {
482            after_envelopes: DEFAULT_SAVE_AFTER_ENVELOPES,
483            after_duration: DEFAULT_SAVE_AFTER_DURATION,
484        }
485    }
486}
487
488/// Grouped-handler batching cadence.
489///
490/// A group closes after either threshold is reached, whichever happens first.
491/// The defaults mirror Akka Projection: 20 envelopes or 500 milliseconds.
492#[derive(Debug, Clone, Copy, PartialEq, Eq)]
493pub struct GroupConfig {
494    /// Maximum envelopes in one handler invocation.
495    pub group_after_envelopes: usize,
496    /// Maximum time an incomplete group remains open while envelopes flow.
497    pub group_after_duration: Duration,
498}
499
500impl GroupConfig {
501    /// Validates that both grouping thresholds are greater than zero.
502    pub fn validate(&self) -> ProjectionResult<()> {
503        validate_positive_count("group.group_after_envelopes", self.group_after_envelopes)?;
504        validate_positive_duration("group.group_after_duration", self.group_after_duration)
505    }
506}
507
508impl Default for GroupConfig {
509    fn default() -> Self {
510        Self {
511            group_after_envelopes: DEFAULT_GROUP_AFTER_ENVELOPES,
512            group_after_duration: DEFAULT_GROUP_AFTER_DURATION,
513        }
514    }
515}
516
517/// Per-handler-invocation recovery policy.
518///
519/// For single-envelope handlers the invocation unit is one envelope; for
520/// grouped handlers it is the complete group. Handler failures are governed by
521/// this policy and are intentionally separate from [`ProjectionError`]'s
522/// fatal-versus-restartable infrastructure taxonomy.
523#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
524pub enum RecoveryStrategy {
525    /// Do not retry; escalate immediately to projection restart.
526    #[default]
527    Fail,
528    /// Discard the failed invocation and continue.
529    Skip,
530    /// Retry in order, then escalate to projection restart on exhaustion.
531    RetryAndFail {
532        /// Number of retry attempts after the initial failed invocation.
533        retries: usize,
534        /// Delay between retry attempts.
535        delay: Duration,
536    },
537    /// Retry in order, then discard the invocation on exhaustion.
538    RetryAndSkip {
539        /// Number of retry attempts after the initial failed invocation.
540        retries: usize,
541        /// Delay between retry attempts.
542        delay: Duration,
543    },
544}
545
546impl RecoveryStrategy {
547    /// Creates retry-then-fail recovery with the Akka defaults: five retries,
548    /// one second apart.
549    #[must_use]
550    pub const fn retry_and_fail() -> Self {
551        Self::RetryAndFail {
552            retries: DEFAULT_RECOVERY_RETRIES,
553            delay: DEFAULT_RECOVERY_DELAY,
554        }
555    }
556
557    /// Creates retry-then-skip recovery with the Akka defaults: five retries,
558    /// one second apart.
559    #[must_use]
560    pub const fn retry_and_skip() -> Self {
561        Self::RetryAndSkip {
562            retries: DEFAULT_RECOVERY_RETRIES,
563            delay: DEFAULT_RECOVERY_DELAY,
564        }
565    }
566}
567
568/// Projection-level restart backoff.
569///
570/// The runtime applies jitter after capping the exponential base delay:
571/// `min(min_backoff * 2^failures, max_backoff) *
572/// (1 + U(0, random_factor))`. `None` for [`Self::max_restarts`] means
573/// unlimited restarts. The restart count is reset after
574/// [`Self::max_restarts_within`], matching Akka's `maxRestartsWithin`
575/// tracking-window semantics.
576#[derive(Debug, Clone, Copy, PartialEq)]
577pub struct RestartBackoff {
578    /// Initial exponential backoff.
579    pub min_backoff: Duration,
580    /// Cap applied before jitter.
581    pub max_backoff: Duration,
582    /// Non-negative jitter fraction. Values above one are rejected.
583    pub random_factor: f64,
584    /// Maximum restarts within [`Self::max_restarts_within`], or `None` for
585    /// unlimited restarts.
586    pub max_restarts: Option<usize>,
587    /// Window that bounds [`Self::max_restarts`].
588    ///
589    /// The Akka-parity default is the initial backoff, three seconds.
590    pub max_restarts_within: Duration,
591}
592
593impl RestartBackoff {
594    /// Validates backoff ordering and the finite `0.0..=1.0` jitter range.
595    ///
596    /// Zero delays and `Some(0)` restarts are valid, which permits
597    /// deterministic tests and explicitly disables restarting respectively.
598    pub fn validate(&self) -> ProjectionResult<()> {
599        if self.min_backoff > self.max_backoff {
600            return Err(ProjectionError::invalid_config(
601                "restart_backoff",
602                "min_backoff must not exceed max_backoff",
603            ));
604        }
605        if !self.random_factor.is_finite() || !(0.0..=1.0).contains(&self.random_factor) {
606            return Err(ProjectionError::invalid_config(
607                "restart_backoff.random_factor",
608                "random_factor must be finite and between 0.0 and 1.0",
609            ));
610        }
611        Ok(())
612    }
613}
614
615impl Default for RestartBackoff {
616    fn default() -> Self {
617        Self {
618            min_backoff: DEFAULT_MIN_BACKOFF,
619            max_backoff: DEFAULT_MAX_BACKOFF,
620            random_factor: DEFAULT_RANDOM_FACTOR,
621            max_restarts: None,
622            max_restarts_within: DEFAULT_MAX_RESTARTS_WITHIN,
623        }
624    }
625}
626
627fn validate_positive_count(setting: &'static str, count: usize) -> ProjectionResult<()> {
628    if count == 0 {
629        return Err(ProjectionError::invalid_config(
630            setting,
631            "value must be greater than zero",
632        ));
633    }
634    Ok(())
635}
636
637fn validate_positive_duration(setting: &'static str, duration: Duration) -> ProjectionResult<()> {
638    if duration.is_zero() {
639        return Err(ProjectionError::invalid_config(
640            setting,
641            "duration must be greater than zero",
642        ));
643    }
644    Ok(())
645}
646
647#[cfg(test)]
648mod tests {
649    use super::*;
650
651    #[test]
652    fn configuration_defaults_match_akka_projection() {
653        assert_eq!(
654            SaveOffsetConfig::default(),
655            SaveOffsetConfig {
656                after_envelopes: 100,
657                after_duration: Duration::from_millis(500),
658            }
659        );
660        assert_eq!(
661            GroupConfig::default(),
662            GroupConfig {
663                group_after_envelopes: 20,
664                group_after_duration: Duration::from_millis(500),
665            }
666        );
667        assert_eq!(RecoveryStrategy::default(), RecoveryStrategy::Fail);
668        assert_eq!(
669            RecoveryStrategy::retry_and_fail(),
670            RecoveryStrategy::RetryAndFail {
671                retries: 5,
672                delay: Duration::from_secs(1),
673            }
674        );
675        assert_eq!(
676            RecoveryStrategy::retry_and_skip(),
677            RecoveryStrategy::RetryAndSkip {
678                retries: 5,
679                delay: Duration::from_secs(1),
680            }
681        );
682        assert_eq!(
683            RestartBackoff::default(),
684            RestartBackoff {
685                min_backoff: Duration::from_secs(3),
686                max_backoff: Duration::from_secs(30),
687                random_factor: 0.2,
688                max_restarts: None,
689                max_restarts_within: Duration::from_secs(3),
690            }
691        );
692    }
693
694    #[test]
695    fn invalid_configuration_is_fatal() {
696        let error = ProjectionId::new("", "key")
697            .validate()
698            .expect_err("blank projection names must fail validation");
699        assert_eq!(error.kind(), ProjectionErrorKind::Fatal);
700
701        let error = RestartBackoff {
702            random_factor: f64::NAN,
703            ..RestartBackoff::default()
704        }
705        .validate()
706        .expect_err("NaN jitter must fail validation");
707        assert!(error.is_fatal());
708    }
709}