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
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
//! Fresh projection source factories and resume-boundary filtering.

use std::{cmp::Ordering, pin::Pin, sync::Arc};

use futures_core::Stream;
use futures_util::StreamExt;

use crate::query::{EventEnvelope, EventsBySlicesQuery, Offset, QueryMode, SliceRange, slice_for};

use super::{
    BoundaryEvent, CursorPosition, DeduplicationBoundary, ProjectionCursor, ProjectionError,
    ProjectionId, ProjectionOffsetStore, ProjectionResult, ProviderManifest,
};

const SLICE_PROVIDER_MANIFEST_VERSION: &str = "datum-postgres-events-by-slices-v1";
const TIMESTAMP_POSITION_VERSION: &str = "pg-timestamp-v1";

/// Owned asynchronous stream materialized for one projection incarnation.
///
/// A source may fail after emitting envelopes by yielding an error item. The
/// runtime consumes this stream only from its dedicated source worker.
pub type ProjectionSource<Envelope> =
    Pin<Box<dyn Stream<Item = ProjectionResult<Envelope>> + Send + 'static>>;

/// Factory for provider-complete, restartable projection sources.
///
/// [`Self::source_from`] must materialize a **new** source every time it is
/// invoked. Returning a reused stream or a clone sharing one underlying query
/// cursor violates the projection restart contract.
///
/// Delivery guarantees apply only to envelopes emitted by the provider. They
/// cannot repair source-side omissions: PostgreSQL live tag/slice queries can
/// permanently skip events committed by transactions open longer than their
/// configured visibility lag, Cassandra can commit a journal row while losing
/// its non-atomic tag-index row until external repair, and durable-state change
/// sources may coalesce rapid revisions to the latest revision per id.
#[async_trait::async_trait]
pub trait SourceProvider<Envelope>: Send + Sync + 'static {
    /// Returns the stable durable identity of this provider and cursor format.
    fn manifest(&self) -> &ProviderManifest;

    /// Validates that this provider may run under `projection_id`.
    ///
    /// The projection runtime invokes this side-effect-free hook during spawn
    /// validation, before the provider is materialized or an offset-store
    /// generation is claimed. Most providers accept any valid projection id,
    /// so the default preserves that behavior. Providers whose durable source
    /// identity requires a particular instance key can override the hook and
    /// return a fatal [`ProjectionError::InvalidConfig`].
    fn validate_projection_id(&self, _projection_id: &ProjectionId) -> ProjectionResult<()> {
        Ok(())
    }

    /// Materializes a fresh source beginning at `cursor`.
    ///
    /// Inclusive-resume implementations should begin at the cursor position;
    /// the runtime's demand-side resume filter removes already
    /// consumed boundary events before they reach the handler.
    async fn source_from(
        &self,
        cursor: Option<&ProjectionCursor>,
        mode: QueryMode,
    ) -> ProjectionResult<ProjectionSource<Envelope>>;

    /// Extracts the complete durable cursor after processing `envelope`.
    ///
    /// For an inclusive position shared by multiple persistence ids, the
    /// returned boundary should contain the identity represented by this
    /// envelope. The runtime merges identities at equal positions.
    fn extract_cursor(&self, envelope: &Envelope) -> ProjectionResult<ProjectionCursor>;

    /// Compares two opaque provider positions in source order.
    ///
    /// Implementations must not use lexical ordering unless their stable
    /// position codec is explicitly lexicographically sortable.
    fn compare_positions(
        &self,
        left: &super::CursorPosition,
        right: &super::CursorPosition,
    ) -> ProjectionResult<Ordering>;

    /// Decides whether `envelope` is after the already-consumed resume cursor.
    ///
    /// Providers may override this for backend-specific inclusive-resume
    /// rules. The default drops earlier positions, accepts later positions,
    /// and at an equal position checks the emitted envelope's own boundary
    /// identity. A scalar cursor with no boundary identity treats equality as
    /// consumed. An equal-position cursor containing multiple identities is
    /// rejected as ambiguous: [`Self::extract_cursor`] must identify the one
    /// `(persistence_id, sequence_nr)` represented by this envelope, rather
    /// than returning a cumulative boundary set.
    fn resume_allows(
        &self,
        cursor: &ProjectionCursor,
        envelope: &Envelope,
    ) -> ProjectionResult<bool> {
        cursor.ensure_manifest(self.manifest())?;
        let candidate = self.extract_cursor(envelope)?;
        candidate.ensure_manifest(self.manifest())?;
        match self.compare_positions(candidate.position(), cursor.position())? {
            Ordering::Less => Ok(false),
            Ordering::Greater => Ok(true),
            Ordering::Equal => {
                let mut candidate_events = candidate.boundary().consumed();
                let Some(event) = candidate_events.next() else {
                    return Ok(false);
                };
                if candidate_events.next().is_some() {
                    return Err(ProjectionError::invalid_config(
                        "source_provider.resume_boundary",
                        "extract_cursor must identify exactly one boundary event per envelope",
                    ));
                }
                Ok(!cursor
                    .boundary()
                    .contains(event.persistence_id(), event.sequence_nr()))
            }
        }
    }
}

/// PostgreSQL timestamp-cursor provider over [`EventsBySlicesQuery`].
///
/// The provider manifest durably includes the caller-supplied query identity,
/// entity type, inclusive slice range, and range version. A cursor written for
/// any different range or version therefore fails with
/// [`ProjectionError::ProviderManifestMismatch`] instead of being silently
/// reused. `query_identity` should be a stable, non-secret identifier for the
/// PostgreSQL journal/database (for example, a deployment database id plus
/// schema), so cursors are not accidentally moved across databases.
///
/// PostgreSQL resumes timestamp offsets inclusively. The provider stores every
/// consumed `(persistence_id, sequence_nr)` at the exact boundary in
/// [`DeduplicationBoundary`]. PostgreSQL's projection offset store normalizes
/// those identities into PJ4's timestamp-boundary table; no second dedup row
/// shape is introduced here.
///
/// Delivery guarantees cover only emitted rows. A live PostgreSQL slice query
/// can permanently skip an event committed by a transaction open longer than
/// the configured visibility lag.
#[derive(Clone)]
pub struct EventsBySlicesSourceProvider {
    query: Arc<dyn EventsBySlicesQuery>,
    query_identity: String,
    entity_type: String,
    range: SliceRange,
    version: u32,
    projection_key: String,
    manifest: ProviderManifest,
}

impl EventsBySlicesSourceProvider {
    /// Creates an inert, restartable provider for one versioned slice range.
    pub fn new(
        query: Arc<dyn EventsBySlicesQuery>,
        query_identity: impl Into<String>,
        entity_type: impl Into<String>,
        range: SliceRange,
        version: u32,
    ) -> ProjectionResult<Self> {
        let query_identity = query_identity.into();
        if query_identity.trim().is_empty() {
            return Err(ProjectionError::invalid_config(
                "events_by_slices.query_identity",
                "query identity must not be blank",
            ));
        }
        let entity_type = entity_type.into();
        if entity_type.trim().is_empty() {
            return Err(ProjectionError::invalid_config(
                "events_by_slices.entity_type",
                "entity type must not be blank",
            ));
        }
        if version == 0 {
            return Err(ProjectionError::invalid_config(
                "events_by_slices.range_version",
                "range version must be greater than zero",
            ));
        }
        let projection_key = slice_projection_key(range, version);
        let manifest = slice_provider_manifest(
            &query_identity,
            &entity_type,
            range,
            version,
            &projection_key,
        )?;
        Ok(Self {
            query,
            query_identity,
            entity_type,
            range,
            version,
            projection_key,
            manifest,
        })
    }

    /// Returns the stable query/database identity included in the manifest.
    #[must_use]
    pub fn query_identity(&self) -> &str {
        &self.query_identity
    }

    /// Returns the queried persistence entity type.
    #[must_use]
    pub fn entity_type(&self) -> &str {
        &self.entity_type
    }

    /// Returns the inclusive slice range owned by this provider.
    #[must_use]
    pub const fn range(&self) -> SliceRange {
        self.range
    }

    /// Returns the explicit range version.
    #[must_use]
    pub const fn version(&self) -> u32 {
        self.version
    }

    /// Returns the range-derived projection key, such as `slices-256-511@v1`.
    #[must_use]
    pub fn projection_key(&self) -> &str {
        &self.projection_key
    }

    fn manifest_for(&self, range: SliceRange, version: u32) -> ProjectionResult<ProviderManifest> {
        let projection_key = slice_projection_key(range, version);
        slice_provider_manifest(
            &self.query_identity,
            &self.entity_type,
            range,
            version,
            &projection_key,
        )
    }
}

/// One stopped old-range cursor supplied to an explicit reshard seed.
///
/// `None` means the old range had not committed a cursor, so any new range it
/// covers must start from the beginning.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SliceRangeCursor {
    range: SliceRange,
    version: u32,
    cursor: Option<ProjectionCursor>,
}

impl SliceRangeCursor {
    /// Associates a stopped range/version with its final flushed cursor.
    pub fn new(
        range: SliceRange,
        version: u32,
        cursor: Option<ProjectionCursor>,
    ) -> ProjectionResult<Self> {
        if version == 0 {
            return Err(ProjectionError::invalid_config(
                "events_by_slices.old_range_version",
                "range version must be greater than zero",
            ));
        }
        Ok(Self {
            range,
            version,
            cursor,
        })
    }

    /// Returns the stopped range.
    #[must_use]
    pub const fn range(&self) -> SliceRange {
        self.range
    }

    /// Returns the stopped range's version.
    #[must_use]
    pub const fn version(&self) -> u32 {
        self.version
    }

    /// Returns the final flushed cursor, if that range had one.
    #[must_use]
    pub fn cursor(&self) -> Option<&ProjectionCursor> {
        self.cursor.as_ref()
    }
}

/// Explicitly seeds one new slice-range key during resharding.
///
/// The required procedure is:
///
/// 1. stop every old range and wait for its final cursor flush;
/// 2. construct the new range/version provider and gather the stopped old
///    ranges whose intersections cover it exactly;
/// 3. call this function for the new range-derived [`ProjectionId`];
/// 4. only after every new key is seeded, start the new projection instances.
///
/// This function never remaps or overwrites a live/previously seeded key. It
/// claims the new key, validates old range/version manifests, verifies exact
/// contiguous coverage, and persists the minimum cursor position among the
/// covering old cursors. Equal-minimum PJ4 boundary identities are merged and
/// filtered to the new range. If any covering old range has no cursor, the new
/// key intentionally remains at no cursor. Starting from the minimum may
/// replay work already processed by covering ranges with later positions, but
/// that replay is bounded by their position spread and cannot lose events.
///
/// `projection_id.key()` must equal [`EventsBySlicesSourceProvider::projection_key`],
/// making an instance-count change an explicit new-key operation.
pub async fn seed_resharded_slice_range(
    store: &dyn ProjectionOffsetStore,
    projection_id: &ProjectionId,
    provider: &EventsBySlicesSourceProvider,
    covering_old_ranges: &[SliceRangeCursor],
) -> ProjectionResult<Option<ProjectionCursor>> {
    projection_id.validate()?;
    if projection_id.key() != provider.projection_key() {
        return Err(ProjectionError::invalid_config(
            "events_by_slices.reshard_projection_key",
            format!(
                "new projection key {:?} must equal range-derived key {:?}",
                projection_id.key(),
                provider.projection_key()
            ),
        ));
    }

    let seed = resharding_seed_cursor(provider, covering_old_ranges)?;
    if store.load(projection_id).await?.is_some() {
        return Err(ProjectionError::invalid_config(
            "events_by_slices.reshard_existing_cursor",
            format!(
                "new range key {projection_id} already has a cursor; reshard seeding never overwrites"
            ),
        ));
    }
    let generation = store.claim(projection_id).await?;
    if store.load(projection_id).await?.is_some() {
        return Err(ProjectionError::invalid_config(
            "events_by_slices.reshard_existing_cursor",
            format!(
                "new range key {projection_id} already has a cursor; reshard seeding never overwrites"
            ),
        ));
    }
    if let Some(cursor) = seed.clone() {
        store.save(projection_id, generation, None, cursor).await?;
    }
    Ok(seed)
}

fn resharding_seed_cursor(
    provider: &EventsBySlicesSourceProvider,
    covering_old_ranges: &[SliceRangeCursor],
) -> ProjectionResult<Option<ProjectionCursor>> {
    validate_reshard_coverage(provider.range, covering_old_ranges)?;
    let mut cursors = Vec::with_capacity(covering_old_ranges.len());
    let mut any_absent = false;
    for old in covering_old_ranges {
        let expected_manifest = provider.manifest_for(old.range, old.version)?;
        if let Some(cursor) = &old.cursor {
            cursor.ensure_manifest(&expected_manifest)?;
            provider.compare_positions(cursor.position(), cursor.position())?;
            cursors.push(cursor);
        } else {
            any_absent = true;
        }
    }
    if any_absent {
        return Ok(None);
    }

    let mut minimum = cursors
        .first()
        .expect("coverage validation requires at least one old range")
        .position();
    for cursor in cursors.iter().skip(1) {
        if provider.compare_positions(cursor.position(), minimum)? == Ordering::Less {
            minimum = cursor.position();
        }
    }

    let mut consumed = Vec::new();
    for cursor in cursors {
        if provider.compare_positions(cursor.position(), minimum)? == Ordering::Equal {
            consumed.extend(
                cursor
                    .boundary()
                    .consumed()
                    .filter(|event| {
                        provider
                            .range
                            .contains(slice_for(event.persistence_id().id()))
                    })
                    .cloned(),
            );
        }
    }
    Ok(Some(ProjectionCursor::new(
        provider.manifest.clone(),
        DeduplicationBoundary::with_consumed(minimum.clone(), consumed),
    )))
}

fn validate_reshard_coverage(
    new_range: SliceRange,
    covering_old_ranges: &[SliceRangeCursor],
) -> ProjectionResult<()> {
    let mut intersections = covering_old_ranges
        .iter()
        .map(|old| {
            let min = old.range.min().max(new_range.min());
            let max = old.range.max().min(new_range.max());
            if min > max {
                return Err(ProjectionError::invalid_config(
                    "events_by_slices.reshard_coverage",
                    format!(
                        "old range {} does not intersect new range {}",
                        slice_projection_key(old.range, old.version),
                        slice_projection_key(new_range, 1)
                    ),
                ));
            }
            Ok((min, max))
        })
        .collect::<ProjectionResult<Vec<_>>>()?;
    intersections.sort_unstable();

    let mut expected = new_range.min();
    for (min, max) in intersections {
        if min != expected {
            let reason = if min < expected {
                format!("old range intersections overlap at slice {min}")
            } else {
                format!("old range intersections leave a gap beginning at slice {expected}")
            };
            return Err(ProjectionError::invalid_config(
                "events_by_slices.reshard_coverage",
                reason,
            ));
        }
        expected = max + 1;
    }
    if expected != new_range.max() + 1 {
        return Err(ProjectionError::invalid_config(
            "events_by_slices.reshard_coverage",
            format!(
                "old range intersections stop before slice {}",
                new_range.max()
            ),
        ));
    }
    Ok(())
}

#[async_trait::async_trait]
impl SourceProvider<EventEnvelope> for EventsBySlicesSourceProvider {
    fn manifest(&self) -> &ProviderManifest {
        &self.manifest
    }

    fn validate_projection_id(&self, projection_id: &ProjectionId) -> ProjectionResult<()> {
        if projection_id.key() != self.projection_key {
            return Err(ProjectionError::invalid_config(
                "events_by_slices.projection_key",
                format!(
                    "projection key {:?} must equal range-derived key {:?}",
                    projection_id.key(),
                    self.projection_key
                ),
            ));
        }
        Ok(())
    }

    async fn source_from(
        &self,
        cursor: Option<&ProjectionCursor>,
        mode: QueryMode,
    ) -> ProjectionResult<ProjectionSource<EventEnvelope>> {
        let offset = cursor.map_or(Ok(Offset::NoOffset), |cursor| {
            cursor.ensure_manifest(&self.manifest)?;
            decode_timestamp_position(cursor.position())
        })?;
        let stream = self
            .query
            .events_by_slices(
                &self.entity_type,
                self.range.min(),
                self.range.max(),
                offset,
                mode,
            )
            .await
            .map_err(|error| ProjectionError::Source(error.to_string()))?;
        Ok(Box::pin(stream.map(|item| {
            item.map_err(|error| ProjectionError::Source(error.to_string()))
        })))
    }

    fn extract_cursor(&self, envelope: &EventEnvelope) -> ProjectionResult<ProjectionCursor> {
        let Offset::Timestamp {
            epoch_micros,
            seq_nr,
        } = envelope.offset
        else {
            return Err(ProjectionError::Source(format!(
                "PostgreSQL events-by-slices emitted non-timestamp offset {:?}",
                envelope.offset
            )));
        };
        if envelope.persistence_id.entity_type() != self.entity_type {
            return Err(ProjectionError::Source(format!(
                "events-by-slices provider for entity type {:?} received persistence id {}",
                self.entity_type, envelope.persistence_id
            )));
        }
        let actual_slice = slice_for(envelope.persistence_id.id());
        if !self.range.contains(actual_slice) {
            return Err(ProjectionError::Source(format!(
                "events-by-slices provider for {} received persistence id {} in slice {actual_slice}",
                self.projection_key, envelope.persistence_id
            )));
        }
        Ok(ProjectionCursor::new(
            self.manifest.clone(),
            DeduplicationBoundary::with_consumed(
                encode_timestamp_position(epoch_micros, seq_nr),
                [BoundaryEvent::new(
                    envelope.persistence_id.clone(),
                    envelope.sequence_nr,
                )],
            ),
        ))
    }

    fn compare_positions(
        &self,
        left: &CursorPosition,
        right: &CursorPosition,
    ) -> ProjectionResult<Ordering> {
        Ok(decode_timestamp_position_value(left)?.cmp(&decode_timestamp_position_value(right)?))
    }
}

/// Returns the mandatory range-derived, versioned projection key.
#[must_use]
pub fn slice_projection_key(range: SliceRange, version: u32) -> String {
    format!("slices-{}-{}@v{version}", range.min(), range.max())
}

fn slice_provider_manifest(
    query_identity: &str,
    entity_type: &str,
    range: SliceRange,
    version: u32,
    projection_key: &str,
) -> ProjectionResult<ProviderManifest> {
    ProviderManifest::new(format!(
        "{SLICE_PROVIDER_MANIFEST_VERSION}|query={}|entity={}|range={}-{}|version={version}|key={projection_key}",
        encode_utf8_hex(query_identity),
        encode_utf8_hex(entity_type),
        range.min(),
        range.max(),
    ))
}

fn encode_timestamp_position(epoch_micros: i64, sequence_nr: u64) -> CursorPosition {
    CursorPosition::new(format!(
        "{TIMESTAMP_POSITION_VERSION}|{epoch_micros}|{sequence_nr}"
    ))
}

fn decode_timestamp_position(position: &CursorPosition) -> ProjectionResult<Offset> {
    let (epoch_micros, seq_nr) = decode_timestamp_position_value(position)?;
    Ok(Offset::Timestamp {
        epoch_micros,
        seq_nr,
    })
}

fn decode_timestamp_position_value(position: &CursorPosition) -> ProjectionResult<(i64, u64)> {
    let mut fields = position.as_str().split('|');
    let version = fields.next();
    let epoch_micros = fields.next();
    let sequence_nr = fields.next();
    if version != Some(TIMESTAMP_POSITION_VERSION)
        || epoch_micros.is_none()
        || sequence_nr.is_none()
        || fields.next().is_some()
    {
        return Err(ProjectionError::CursorCodec(format!(
            "invalid PostgreSQL timestamp cursor position {:?}",
            position.as_str()
        )));
    }
    let epoch_micros = epoch_micros
        .expect("presence was checked")
        .parse::<i64>()
        .map_err(|_| {
            ProjectionError::CursorCodec(format!(
                "invalid PostgreSQL timestamp micros in position {:?}",
                position.as_str()
            ))
        })?;
    let sequence_nr = sequence_nr
        .expect("presence was checked")
        .parse::<u64>()
        .map_err(|_| {
            ProjectionError::CursorCodec(format!(
                "invalid PostgreSQL timestamp sequence in position {:?}",
                position.as_str()
            ))
        })?;
    Ok((epoch_micros, sequence_nr))
}

fn encode_utf8_hex(value: &str) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut encoded = String::with_capacity(value.len().saturating_mul(2));
    for byte in value.bytes() {
        encoded.push(char::from(HEX[usize::from(byte >> 4)]));
        encoded.push(char::from(HEX[usize::from(byte & 0x0f)]));
    }
    encoded
}

/// Returns whether an envelope is after the already-consumed resume boundary.
///
/// Positions before the cursor are always dropped. At an equal position,
/// provider-complete boundary identities are checked individually so unseen
/// persistence ids sharing that exact position remain eligible.
pub(crate) fn resume_allows<Envelope: 'static>(
    provider: &dyn SourceProvider<Envelope>,
    cursor: Option<&ProjectionCursor>,
    envelope: &Envelope,
) -> ProjectionResult<bool> {
    let Some(cursor) = cursor else {
        return Ok(true);
    };
    provider.resume_allows(cursor, envelope)
}

/// Advances a logical cursor and merges dedup identities at one exact position.
pub(crate) fn advance_cursor<Envelope: 'static>(
    provider: &dyn SourceProvider<Envelope>,
    current: Option<&ProjectionCursor>,
    envelope: &Envelope,
) -> ProjectionResult<ProjectionCursor> {
    let next = provider.extract_cursor(envelope)?;
    next.ensure_manifest(provider.manifest())?;
    let Some(current) = current else {
        return Ok(next);
    };
    current.ensure_manifest(provider.manifest())?;

    match provider.compare_positions(next.position(), current.position())? {
        Ordering::Less => Err(ProjectionError::Source(format!(
            "provider {} emitted cursor position {} after later position {}",
            provider.manifest(),
            next.position(),
            current.position()
        ))),
        Ordering::Greater => Ok(next),
        Ordering::Equal => {
            let consumed = current
                .boundary()
                .consumed()
                .chain(next.boundary().consumed())
                .cloned();
            Ok(ProjectionCursor::new(
                provider.manifest().clone(),
                DeduplicationBoundary::with_consumed(current.position().clone(), consumed),
            ))
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Mutex;

    use futures_util::stream;

    use crate::projection::{
        GroupedHandler, Handler, MemoryProjectionOffsetStore, Projection, ProjectionRuntime,
        ProjectionStatus, TestEnvelope, TestSourceProvider,
    };
    use crate::query::QueryStream;
    use crate::{PersistenceId, SequenceNr, SerializedPayload, SerializerId};

    use super::*;

    type RecordedCall = (String, u16, u16, Offset, QueryMode);

    struct RecordingSliceQuery {
        calls: Mutex<Vec<RecordedCall>>,
    }

    #[async_trait::async_trait]
    impl EventsBySlicesQuery for RecordingSliceQuery {
        async fn events_by_slices(
            &self,
            entity_type: &str,
            min_slice: u16,
            max_slice: u16,
            offset: Offset,
            mode: QueryMode,
        ) -> crate::PersistenceResult<QueryStream<EventEnvelope>> {
            self.calls.lock().unwrap().push((
                entity_type.to_owned(),
                min_slice,
                max_slice,
                offset,
                mode,
            ));
            Ok(Box::pin(stream::empty()))
        }
    }

    struct NoopHandler;

    #[async_trait::async_trait]
    impl Handler<EventEnvelope> for NoopHandler {
        async fn process(&mut self, _envelope: &EventEnvelope) -> ProjectionResult<()> {
            Ok(())
        }
    }

    struct NoopGroupedHandler;

    #[async_trait::async_trait]
    impl GroupedHandler<EventEnvelope> for NoopGroupedHandler {
        async fn process(&mut self, _envelopes: &[EventEnvelope]) -> ProjectionResult<()> {
            Ok(())
        }
    }

    struct NoopTestHandler;

    #[async_trait::async_trait]
    impl Handler<TestEnvelope<usize>> for NoopTestHandler {
        async fn process(&mut self, _envelope: &TestEnvelope<usize>) -> ProjectionResult<()> {
            Ok(())
        }
    }

    fn envelope(persistence_id: PersistenceId, epoch_micros: i64) -> EventEnvelope {
        EventEnvelope {
            offset: Offset::Timestamp {
                epoch_micros,
                seq_nr: 7,
            },
            persistence_id,
            sequence_nr: SequenceNr::new(7),
            timestamp_ms: 1,
            adapter_manifest: "adapter-v1".into(),
            payload: SerializedPayload::new(SerializerId::new(1), "event-v1", vec![]),
            metadata: None,
            tags: Vec::new(),
        }
    }

    fn id_in(range: SliceRange) -> PersistenceId {
        (0..10_000)
            .map(|suffix| PersistenceId::new("account", suffix.to_string()).unwrap())
            .find(|persistence_id| range.contains(slice_for(persistence_id.id())))
            .expect("fixture search finds an id in the range")
    }

    fn id_in_but_not(in_range: SliceRange, excluded: SliceRange) -> PersistenceId {
        (0..10_000)
            .map(|suffix| PersistenceId::new("account", format!("outside-{suffix}")).unwrap())
            .find(|persistence_id| {
                let slice = slice_for(persistence_id.id());
                in_range.contains(slice) && !excluded.contains(slice)
            })
            .expect("fixture search finds an id in only the old range")
    }

    #[tokio::test]
    async fn range_version_is_in_key_manifest_and_query_resume() {
        let query = Arc::new(RecordingSliceQuery {
            calls: Mutex::new(Vec::new()),
        });
        let range = SliceRange::new(256, 511).unwrap();
        let provider = EventsBySlicesSourceProvider::new(
            query.clone(),
            "postgres:test-db/public",
            "account",
            range,
            1,
        )
        .unwrap();
        assert_eq!(provider.projection_key(), "slices-256-511@v1");
        assert_eq!(
            provider.manifest().as_str(),
            "datum-postgres-events-by-slices-v1|query=706f7374677265733a746573742d64622f7075626c6963|entity=6163636f756e74|range=256-511|version=1|key=slices-256-511@v1"
        );

        let persistence_id = PersistenceId::new("account", "0").unwrap();
        assert_eq!(slice_for(persistence_id.id()), 336);
        let event = envelope(persistence_id, 123);
        let cursor = provider.extract_cursor(&event).unwrap();
        assert_eq!(cursor.boundary().consumed().len(), 1);
        assert_eq!(cursor.position().as_str(), "pg-timestamp-v1|123|7");
        assert_eq!(
            cursor.encode(),
            "datum-projection-cursor-v1|646174756d2d706f7374677265732d6576656e74732d62792d736c696365732d76317c71756572793d373036663733373436373732363537333361373436353733373432643634363232663730373536323663363936337c656e746974793d36313633363336663735366537347c72616e67653d3235362d3531317c76657273696f6e3d317c6b65793d736c696365732d3235362d353131407631|70672d74696d657374616d702d76317c3132337c37|1|6163636f756e747c30:7"
        );
        let _source = provider
            .source_from(Some(&cursor), QueryMode::Current)
            .await
            .unwrap();
        assert_eq!(
            query.calls.lock().unwrap().as_slice(),
            [(
                "account".to_owned(),
                256,
                511,
                Offset::Timestamp {
                    epoch_micros: 123,
                    seq_nr: 7,
                },
                QueryMode::Current,
            )]
        );
    }

    #[tokio::test]
    async fn normal_spawn_enforces_slice_key_for_every_builder_before_materialization() {
        let query = Arc::new(RecordingSliceQuery {
            calls: Mutex::new(Vec::new()),
        });
        let range = SliceRange::new(256, 511).unwrap();
        let provider =
            EventsBySlicesSourceProvider::new(query.clone(), "postgres:test", "account", range, 3)
                .unwrap();
        let store = Arc::new(MemoryProjectionOffsetStore::new());
        let runtime = ProjectionRuntime::new(Arc::clone(&store) as Arc<dyn ProjectionOffsetStore>);
        let wrong_key = "manual";
        let projections = [
            Projection::at_least_once(
                ProjectionId::new("slice-key-alo", wrong_key),
                provider.clone(),
                || NoopHandler,
            ),
            Projection::at_most_once(
                ProjectionId::new("slice-key-amo", wrong_key),
                provider.clone(),
                || NoopHandler,
            ),
            Projection::grouped_at_least_once(
                ProjectionId::new("slice-key-grouped", wrong_key),
                provider.clone(),
                || NoopGroupedHandler,
            ),
        ];

        for projection in projections {
            let error = match projection.spawn(runtime.clone()).await {
                Ok(_) => panic!("wrong range-derived key must fail normal spawn"),
                Err(error) => error,
            };
            assert!(matches!(
                error,
                ProjectionError::InvalidConfig {
                    setting: "events_by_slices.projection_key",
                    ..
                }
            ));
            assert!(error.is_fatal());
        }
        assert!(
            query.calls.lock().unwrap().is_empty(),
            "projection-id validation must run before source materialization"
        );

        let correct_provider =
            EventsBySlicesSourceProvider::new(query.clone(), "postgres:test", "account", range, 3)
                .unwrap();
        let correct_id = ProjectionId::new("slice-key-correct", correct_provider.projection_key());
        let correct = Projection::at_least_once(correct_id, correct_provider, || NoopHandler)
            .with_query_mode(QueryMode::Current)
            .spawn(runtime.clone())
            .await
            .expect("range-derived key is accepted");
        assert_eq!(correct.wait().await.unwrap(), ProjectionStatus::Completed);
        assert_eq!(query.calls.lock().unwrap().len(), 1);

        let unrestricted = Projection::at_least_once(
            ProjectionId::new("non-slice-provider", "manual-key"),
            TestSourceProvider::new(Vec::<TestEnvelope<usize>>::new()),
            || NoopTestHandler,
        )
        .with_query_mode(QueryMode::Current)
        .spawn(runtime)
        .await
        .expect("the default provider hook preserves arbitrary valid keys");
        assert_eq!(
            unrestricted.wait().await.unwrap(),
            ProjectionStatus::Completed
        );
    }

    #[tokio::test]
    async fn range_or_version_change_is_a_fatal_manifest_mismatch() {
        let query = Arc::new(RecordingSliceQuery {
            calls: Mutex::new(Vec::new()),
        });
        let old_range = SliceRange::new(0, 511).unwrap();
        let old = EventsBySlicesSourceProvider::new(
            query.clone(),
            "postgres:test-db/public",
            "account",
            old_range,
            1,
        )
        .unwrap();
        let cursor = old
            .extract_cursor(&envelope(id_in(old_range), 123))
            .unwrap();

        for (range, version) in [(SliceRange::new(0, 255).unwrap(), 1), (old_range, 2)] {
            let changed = EventsBySlicesSourceProvider::new(
                query.clone(),
                "postgres:test-db/public",
                "account",
                range,
                version,
            )
            .unwrap();
            let error = match changed.source_from(Some(&cursor), QueryMode::Live).await {
                Ok(_) => panic!("changed provider must reject the old cursor"),
                Err(error) => error,
            };
            assert!(matches!(
                error,
                ProjectionError::ProviderManifestMismatch { .. }
            ));
            assert!(error.is_fatal());
        }
    }

    #[test]
    fn provider_rejects_invalid_identity_version_and_envelopes() {
        let query: Arc<dyn EventsBySlicesQuery> = Arc::new(RecordingSliceQuery {
            calls: Mutex::new(Vec::new()),
        });
        let range = SliceRange::new(0, 127).unwrap();
        assert!(EventsBySlicesSourceProvider::new(query.clone(), "", "account", range, 1).is_err());
        assert!(
            EventsBySlicesSourceProvider::new(query.clone(), "postgres:test", "", range, 1)
                .is_err()
        );
        assert!(
            EventsBySlicesSourceProvider::new(query.clone(), "postgres:test", "account", range, 0)
                .is_err()
        );

        let provider =
            EventsBySlicesSourceProvider::new(query, "postgres:test", "account", range, 1).unwrap();
        let wrong = PersistenceId::new("other", "id").unwrap();
        let error = provider
            .extract_cursor(&envelope(wrong, 1))
            .expect_err("wrong entity type is a source failure");
        assert!(matches!(error, ProjectionError::Source(_)));

        let malformed = ProjectionCursor::from_position(
            provider.manifest().clone(),
            "not-a-timestamp-position",
        );
        let error = provider
            .compare_positions(malformed.position(), &CursorPosition::new("also-invalid"))
            .expect_err("malformed position is fatal");
        assert!(matches!(error, ProjectionError::CursorCodec(_)));
    }

    #[tokio::test]
    async fn four_to_eight_seed_persists_new_manifest_and_filters_boundary() {
        let query: Arc<dyn EventsBySlicesQuery> = Arc::new(RecordingSliceQuery {
            calls: Mutex::new(Vec::new()),
        });
        let old_range = SliceRange::new(0, 255).unwrap();
        let new_range = SliceRange::new(0, 127).unwrap();
        let old = EventsBySlicesSourceProvider::new(
            query.clone(),
            "postgres:test",
            "account",
            old_range,
            1,
        )
        .unwrap();
        let new =
            EventsBySlicesSourceProvider::new(query, "postgres:test", "account", new_range, 2)
                .unwrap();
        let included = id_in(new_range);
        let excluded = id_in_but_not(old_range, new_range);
        let base = old
            .extract_cursor(&envelope(included.clone(), 100))
            .unwrap();
        let old_cursor = ProjectionCursor::new(
            old.manifest().clone(),
            DeduplicationBoundary::with_consumed(
                base.position().clone(),
                [
                    BoundaryEvent::new(included.clone(), SequenceNr::new(7)),
                    BoundaryEvent::new(excluded, SequenceNr::new(7)),
                ],
            ),
        );
        let covering = [SliceRangeCursor::new(old_range, 1, Some(old_cursor)).unwrap()];
        let projection_id = ProjectionId::new("accounts", new.projection_key());
        let store = MemoryProjectionOffsetStore::new();

        let seeded = seed_resharded_slice_range(&store, &projection_id, &new, &covering)
            .await
            .unwrap()
            .expect("old range had a cursor");
        assert_eq!(seeded.provider_manifest(), new.manifest());
        assert_eq!(seeded.boundary().consumed().len(), 1);
        assert!(seeded.boundary().contains(&included, SequenceNr::new(7)));
        assert_eq!(store.load(&projection_id).await.unwrap(), Some(seeded));

        let error = seed_resharded_slice_range(&store, &projection_id, &new, &covering)
            .await
            .expect_err("seed never overwrites an existing new-range cursor");
        assert!(matches!(error, ProjectionError::InvalidConfig { .. }));
    }

    #[test]
    fn seed_takes_minimum_covering_position_and_validates_coverage() {
        let query: Arc<dyn EventsBySlicesQuery> = Arc::new(RecordingSliceQuery {
            calls: Mutex::new(Vec::new()),
        });
        let left_range = SliceRange::new(0, 127).unwrap();
        let right_range = SliceRange::new(128, 255).unwrap();
        let new_range = SliceRange::new(0, 255).unwrap();
        let left = EventsBySlicesSourceProvider::new(
            query.clone(),
            "postgres:test",
            "account",
            left_range,
            1,
        )
        .unwrap();
        let right = EventsBySlicesSourceProvider::new(
            query.clone(),
            "postgres:test",
            "account",
            right_range,
            1,
        )
        .unwrap();
        let new =
            EventsBySlicesSourceProvider::new(query, "postgres:test", "account", new_range, 2)
                .unwrap();
        let covering = [
            SliceRangeCursor::new(
                left_range,
                1,
                Some(
                    left.extract_cursor(&envelope(id_in(left_range), 120))
                        .unwrap(),
                ),
            )
            .unwrap(),
            SliceRangeCursor::new(
                right_range,
                1,
                Some(
                    right
                        .extract_cursor(&envelope(id_in(right_range), 100))
                        .unwrap(),
                ),
            )
            .unwrap(),
        ];
        let seed = resharding_seed_cursor(&new, &covering)
            .unwrap()
            .expect("both old ranges had cursors");
        assert_eq!(
            decode_timestamp_position_value(seed.position()).unwrap(),
            (100, 7)
        );

        let all_absent = [
            SliceRangeCursor::new(left_range, 1, None).unwrap(),
            SliceRangeCursor::new(right_range, 1, None).unwrap(),
        ];
        assert_eq!(
            resharding_seed_cursor(&new, &all_absent).unwrap(),
            None,
            "all unstarted covering ranges seed from the beginning"
        );
        let gap = resharding_seed_cursor(&new, &covering[..1])
            .expect_err("partial coverage must be rejected");
        assert!(matches!(gap, ProjectionError::InvalidConfig { .. }));
    }

    #[test]
    fn absent_reshard_cursor_never_hides_a_wrong_range_cursor_in_either_order() {
        let query: Arc<dyn EventsBySlicesQuery> = Arc::new(RecordingSliceQuery {
            calls: Mutex::new(Vec::new()),
        });
        let left_range = SliceRange::new(0, 127).unwrap();
        let right_range = SliceRange::new(128, 255).unwrap();
        let new_range = SliceRange::new(0, 255).unwrap();
        let left = EventsBySlicesSourceProvider::new(
            query.clone(),
            "postgres:test",
            "account",
            left_range,
            1,
        )
        .unwrap();
        let new =
            EventsBySlicesSourceProvider::new(query, "postgres:test", "account", new_range, 2)
                .unwrap();
        let cursor_for_left = left
            .extract_cursor(&envelope(id_in(left_range), 100))
            .unwrap();
        let absent_left = SliceRangeCursor::new(left_range, 1, None).unwrap();
        let wrong_right = SliceRangeCursor::new(right_range, 1, Some(cursor_for_left)).unwrap();

        for covering in [
            vec![absent_left.clone(), wrong_right.clone()],
            vec![wrong_right.clone(), absent_left.clone()],
        ] {
            let error = resharding_seed_cursor(&new, &covering)
                .expect_err("every present old cursor must be validated before absence wins");
            assert!(matches!(
                error,
                ProjectionError::ProviderManifestMismatch { .. }
            ));
            assert!(error.is_fatal());
        }
    }
}