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
//! Cassandra-backed projection cursor and management storage.
//!
//! Construction with [`CassandraProjectionOffsetStore::new`] is inert. Use
//! [`CassandraProjectionOffsetStore::connect`] to connect, create the
//! keyspace/tables when absent, and prepare the runtime statements, or call
//! [`CassandraProjectionOffsetStore::initialize`] later on a blueprint.
//!
//! The offset and management tables mirror Akka Projection's Cassandra row
//! distribution: a stable synthetic `partition` in `0..5`, derived from the
//! projection key with Java's `String.hashCode`, is part of each partition
//! key. With the default names the schema is:
//!
//! ```sql
//! CREATE TABLE IF NOT EXISTS datum_projection_offset_store (
//!   projection_name text,
//!   partition int,
//!   projection_key text,
//!   generation bigint,
//!   has_cursor boolean,
//!   cursor_position text,
//!   offset text,
//!   manifest text,
//!   last_updated timestamp,
//!   PRIMARY KEY ((projection_name, partition), projection_key)
//! );
//!
//! CREATE TABLE IF NOT EXISTS datum_projection_management (
//!   projection_name text,
//!   partition int,
//!   projection_key text,
//!   paused boolean,
//!   last_updated timestamp,
//!   PRIMARY KEY ((projection_name, partition), projection_key)
//! );
//! ```
//!
//! `offset` contains [`ProjectionCursor::encode`], including the complete
//! [`super::DeduplicationBoundary`]. `cursor_position` is duplicated only as
//! the LWT comparison value; `manifest` makes provider identity inspectable
//! and is checked against the encoded cursor when loading.
//!
//! Claiming uses an LWT to insert generation one or conditionally advance the
//! current generation. Every save is an LWT conditioned on both generation
//! and expected cursor position. At-least-once therefore pays this Paxos cost
//! at its configured save cadence, and grouped at-least-once pays it once per
//! successful group. **At-most-once saves before every envelope, so choosing
//! at-most-once on Cassandra pays one LWT per envelope.** That is the price of
//! choosing AMO on Cassandra; WP-PJ9 must report a dedicated microbenchmark
//! row rather than weakening the fence.
//!
//! Cassandra has no cross-table transaction that can atomically include user
//! handler writes and this offset row. Exactly-once is therefore unsupported,
//! matching Akka Projection. [`ProjectionOffsetStore::validate_exactly_once`]
//! fails with a fatal [`ProjectionError::InvalidConfig`] before execution.

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

use scylla::{
    client::{session::Session, session_builder::SessionBuilder},
    response::query_result::QueryResult,
    statement::{Consistency, SerialConsistency, prepared::PreparedStatement},
    value::{CqlValue, Row},
};
use tokio::sync::OnceCell;

use super::{
    CursorPosition, ProjectionCursor, ProjectionError, ProjectionGeneration, ProjectionId,
    ProjectionOffsetStore, ProjectionResult,
};

const DEFAULT_REPLICATION_FACTOR: u32 = 1;
const CASSANDRA_PARTITIONS: i32 = 5;
const MAX_CQL_IDENTIFIER_BYTES: usize = 48;
const MAX_CLAIM_ATTEMPTS: usize = 64;

/// Cassandra table names used by the projection offset store.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CassandraProjectionTableNames {
    /// Generation-fenced, partition-distributed cursor table.
    pub offset_store: String,
    /// Independent persistent pause-management table.
    pub management: String,
}

impl Default for CassandraProjectionTableNames {
    fn default() -> Self {
        Self {
            offset_store: "datum_projection_offset_store".into(),
            management: "datum_projection_management".into(),
        }
    }
}

/// Side-effect-free Cassandra projection offset-store configuration.
#[derive(Clone, PartialEq, Eq)]
pub struct CassandraProjectionOffsetStoreConfig {
    /// Seed nodes used by the driver to discover the cluster.
    pub contact_points: Vec<String>,
    /// Keyspace created on initialization when it does not already exist.
    pub keyspace: String,
    /// SimpleStrategy replication factor used only when creating the keyspace.
    pub replication_factor: u32,
    /// Projection offset and management table names.
    pub tables: CassandraProjectionTableNames,
    /// Consistency applied to cursor and management writes.
    ///
    /// [`Consistency::Any`] is rejected because an acknowledged hint does not
    /// establish durable cursor visibility.
    pub write_consistency: Consistency,
    /// Consistency applied to cursor and management reads.
    pub read_consistency: Consistency,
    /// Serial consistency applied to claim, save, and clear LWTs.
    pub serial_consistency: SerialConsistency,
}

impl fmt::Debug for CassandraProjectionOffsetStoreConfig {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CassandraProjectionOffsetStoreConfig")
            .field("contact_points", &self.contact_points)
            .field("keyspace", &self.keyspace)
            .field("replication_factor", &self.replication_factor)
            .field("tables", &self.tables)
            .field("write_consistency", &self.write_consistency)
            .field("read_consistency", &self.read_consistency)
            .field("serial_consistency", &self.serial_consistency)
            .finish()
    }
}

impl CassandraProjectionOffsetStoreConfig {
    /// Creates a single-seed configuration with Cassandra-safe defaults.
    #[must_use]
    pub fn new(contact_point: impl Into<String>, keyspace: impl Into<String>) -> Self {
        Self {
            contact_points: vec![contact_point.into()],
            keyspace: keyspace.into(),
            replication_factor: DEFAULT_REPLICATION_FACTOR,
            tables: CassandraProjectionTableNames::default(),
            write_consistency: Consistency::LocalQuorum,
            read_consistency: Consistency::LocalQuorum,
            serial_consistency: SerialConsistency::LocalSerial,
        }
    }
}

/// Cassandra projection offset store with LWT generation and position fencing.
///
/// Values are normally shared behind an [`Arc`]. Complete close/reopen is
/// obtained by dropping every handle and connecting a new value with the same
/// configuration.
pub struct CassandraProjectionOffsetStore {
    config: CassandraProjectionOffsetStoreConfig,
    schema: CassandraProjectionSchema,
    connected: OnceCell<Arc<ConnectedCassandraProjection>>,
}

impl fmt::Debug for CassandraProjectionOffsetStore {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("CassandraProjectionOffsetStore")
            .field("config", &self.config)
            .field("connected", &self.connected.get().is_some())
            .finish_non_exhaustive()
    }
}

impl CassandraProjectionOffsetStore {
    /// Validates and creates an inert Cassandra offset-store blueprint.
    pub fn new(config: CassandraProjectionOffsetStoreConfig) -> ProjectionResult<Self> {
        validate_config(&config)?;
        let schema = CassandraProjectionSchema::new(&config);
        Ok(Self {
            config,
            schema,
            connected: OnceCell::new(),
        })
    }

    /// Connects to Cassandra, creates missing schema, and prepares statements.
    pub async fn connect(config: CassandraProjectionOffsetStoreConfig) -> ProjectionResult<Self> {
        let store = Self::new(config)?;
        store.initialize().await?;
        Ok(store)
    }

    /// Initializes a blueprint created with [`Self::new`].
    ///
    /// Concurrent callers share an initialization attempt. A failed attempt is
    /// not cached and can be retried.
    pub async fn initialize(&self) -> ProjectionResult<()> {
        self.connected
            .get_or_try_init(|| connect_cassandra(&self.config, &self.schema))
            .await
            .map(|_| ())
    }

    /// Returns the immutable store configuration.
    #[must_use]
    pub fn config(&self) -> &CassandraProjectionOffsetStoreConfig {
        &self.config
    }

    /// Returns the exact idempotent CQL emitted during schema bootstrap.
    #[must_use]
    pub fn schema_ddl(&self) -> String {
        let mut ddl = self.schema.ddl.join(";\n");
        ddl.push(';');
        ddl
    }

    /// Returns the Akka-compatible synthetic partition for a projection id.
    ///
    /// Akka's Cassandra offset store uses five partitions and Java
    /// `String.hashCode` over the projection key. Keeping that algorithm
    /// stable makes table placement independent of Rust process hash seeds.
    #[must_use]
    pub fn partition_for(projection_id: &ProjectionId) -> i32 {
        let hash = projection_id
            .key()
            .encode_utf16()
            .fold(0_i32, |hash, unit| {
                hash.wrapping_mul(31).wrapping_add(i32::from(unit))
            });
        (hash % CASSANDRA_PARTITIONS).abs()
    }

    async fn ready(&self) -> ProjectionResult<Arc<ConnectedCassandraProjection>> {
        self.initialize().await?;
        self.connected.get().cloned().ok_or_else(|| {
            ProjectionError::OffsetStore(
                "Cassandra projection session unavailable after initialization".into(),
            )
        })
    }

    async fn read_state(
        &self,
        projection_id: &ProjectionId,
    ) -> ProjectionResult<Option<StoredOffsetState>> {
        let connected = self.ready().await?;
        let result = connected
            .session
            .execute_unpaged(&connected.statements.select_offset, row_key(projection_id))
            .await
            .map_err(|error| offset_store_error("load Cassandra projection offset", error))?;
        let rows = result.into_rows_result().map_err(|error| {
            offset_store_error("decode Cassandra projection offset result", error)
        })?;
        let row = rows
            .maybe_first_row::<CassandraOffsetRow>()
            .map_err(|error| offset_store_error("decode Cassandra projection offset row", error))?;
        row.map(StoredOffsetState::decode).transpose()
    }

    async fn classify_save_rejection(
        &self,
        projection_id: &ProjectionId,
        attempted: ProjectionGeneration,
        expected_position: Option<&CursorPosition>,
    ) -> ProjectionResult<()> {
        let state = self.read_state(projection_id).await?;
        let current = state
            .as_ref()
            .map_or(ProjectionGeneration::default(), |state| state.generation);
        if attempted != current || attempted == ProjectionGeneration::default() {
            return Err(ProjectionError::Fenced {
                projection_id: projection_id.clone(),
                attempted_generation: attempted.as_u64(),
                current_generation: current.as_u64(),
            });
        }
        let actual_position = state
            .as_ref()
            .expect("a current non-zero generation has a row")
            .position()?;
        if actual_position.as_ref() != expected_position {
            return Err(ProjectionError::UnexpectedPosition {
                projection_id: projection_id.clone(),
                expected: expected_position.map(ToString::to_string),
                actual: actual_position.map(|position| position.to_string()),
            });
        }
        Err(ProjectionError::OffsetStore(format!(
            "Cassandra projection save LWT for {projection_id} was not applied even though a \
             follow-up read matched generation and expected position; commit outcome is uncertain"
        )))
    }

    async fn classify_generation_rejection(
        &self,
        projection_id: &ProjectionId,
        attempted: ProjectionGeneration,
        operation: &str,
    ) -> ProjectionResult<()> {
        let current = self
            .read_state(projection_id)
            .await?
            .map_or(ProjectionGeneration::default(), |state| state.generation);
        if attempted != current || attempted == ProjectionGeneration::default() {
            return Err(ProjectionError::Fenced {
                projection_id: projection_id.clone(),
                attempted_generation: attempted.as_u64(),
                current_generation: current.as_u64(),
            });
        }
        Err(ProjectionError::OffsetStore(format!(
            "Cassandra projection {operation} LWT for {projection_id} was not applied even though \
             a follow-up read matched generation; commit outcome is uncertain"
        )))
    }
}

#[async_trait::async_trait]
impl ProjectionOffsetStore for CassandraProjectionOffsetStore {
    fn validate_exactly_once(&self) -> ProjectionResult<()> {
        Err(ProjectionError::invalid_config(
            "delivery_semantics",
            "Cassandra projection offset stores do not support exactly-once because Cassandra \
             cannot atomically commit handler writes and the offset row across tables",
        ))
    }

    async fn claim(&self, projection_id: &ProjectionId) -> ProjectionResult<ProjectionGeneration> {
        projection_id.validate()?;
        let connected = self.ready().await?;
        for _ in 0..MAX_CLAIM_ATTEMPTS {
            let current = self.read_state(projection_id).await?;
            match current {
                None => {
                    let result = connected
                        .session
                        .execute_unpaged(
                            &connected.statements.insert_initial_generation,
                            row_key(projection_id),
                        )
                        .await
                        .map_err(|error| {
                            offset_store_error(
                                "claim initial Cassandra projection generation",
                                error,
                            )
                        })?;
                    if lwt_applied(result)? {
                        return Ok(ProjectionGeneration::new(1));
                    }
                }
                Some(current) => {
                    let current_i64 = generation_i64(current.generation, projection_id)?;
                    let Some(next_i64) = current_i64.checked_add(1) else {
                        return Err(ProjectionError::GenerationExhausted {
                            projection_id: projection_id.clone(),
                        });
                    };
                    let result = connected
                        .session
                        .execute_unpaged(
                            &connected.statements.advance_generation,
                            (
                                next_i64,
                                projection_id.name(),
                                Self::partition_for(projection_id),
                                projection_id.key(),
                                current_i64,
                            ),
                        )
                        .await
                        .map_err(|error| {
                            offset_store_error("advance Cassandra projection generation", error)
                        })?;
                    if lwt_applied(result)? {
                        return Ok(ProjectionGeneration::new(
                            u64::try_from(next_i64).expect("positive i64 generation fits u64"),
                        ));
                    }
                }
            }
        }
        Err(ProjectionError::OffsetStore(format!(
            "Cassandra projection claim for {projection_id} exceeded \
             {MAX_CLAIM_ATTEMPTS} LWT contention retries"
        )))
    }

    async fn load(
        &self,
        projection_id: &ProjectionId,
    ) -> ProjectionResult<Option<ProjectionCursor>> {
        projection_id.validate()?;
        self.read_state(projection_id)
            .await?
            .map(StoredOffsetState::cursor)
            .transpose()
            .map(Option::flatten)
    }

    async fn save(
        &self,
        projection_id: &ProjectionId,
        generation: ProjectionGeneration,
        expected_position: Option<&CursorPosition>,
        cursor: ProjectionCursor,
    ) -> ProjectionResult<()> {
        projection_id.validate()?;
        let generation_i64 = match i64::try_from(generation.as_u64()) {
            Ok(generation) => generation,
            Err(_) => {
                return self
                    .classify_save_rejection(projection_id, generation, expected_position)
                    .await;
            }
        };
        let connected = self.ready().await?;
        let position = cursor.position().as_str().to_owned();
        let manifest = cursor.provider_manifest().as_str().to_owned();
        let offset = cursor.encode();
        let result = match expected_position {
            None => {
                connected
                    .session
                    .execute_unpaged(
                        &connected.statements.save_without_cursor,
                        (
                            position,
                            offset,
                            manifest,
                            projection_id.name(),
                            Self::partition_for(projection_id),
                            projection_id.key(),
                            generation_i64,
                            false,
                        ),
                    )
                    .await
            }
            Some(expected_position) => {
                connected
                    .session
                    .execute_unpaged(
                        &connected.statements.save_with_cursor,
                        (
                            position,
                            offset,
                            manifest,
                            projection_id.name(),
                            Self::partition_for(projection_id),
                            projection_id.key(),
                            generation_i64,
                            true,
                            expected_position.as_str(),
                        ),
                    )
                    .await
            }
        }
        .map_err(|error| offset_store_error("save Cassandra projection offset LWT", error))?;
        if lwt_applied(result)? {
            return Ok(());
        }
        self.classify_save_rejection(projection_id, generation, expected_position)
            .await
    }

    async fn clear(
        &self,
        projection_id: &ProjectionId,
        generation: ProjectionGeneration,
    ) -> ProjectionResult<()> {
        projection_id.validate()?;
        let generation_i64 = match i64::try_from(generation.as_u64()) {
            Ok(generation) => generation,
            Err(_) => {
                return self
                    .classify_generation_rejection(projection_id, generation, "clear")
                    .await;
            }
        };
        let connected = self.ready().await?;
        let result = connected
            .session
            .execute_unpaged(
                &connected.statements.clear_cursor,
                (
                    projection_id.name(),
                    Self::partition_for(projection_id),
                    projection_id.key(),
                    generation_i64,
                ),
            )
            .await
            .map_err(|error| offset_store_error("clear Cassandra projection offset LWT", error))?;
        if lwt_applied(result)? {
            return Ok(());
        }
        self.classify_generation_rejection(projection_id, generation, "clear")
            .await
    }

    async fn load_paused(&self, projection_id: &ProjectionId) -> ProjectionResult<bool> {
        projection_id.validate()?;
        let connected = self.ready().await?;
        let result = connected
            .session
            .execute_unpaged(&connected.statements.select_paused, row_key(projection_id))
            .await
            .map_err(|error| {
                offset_store_error("load Cassandra projection management row", error)
            })?;
        let rows = result.into_rows_result().map_err(|error| {
            offset_store_error("decode Cassandra projection management result", error)
        })?;
        let row = rows
            .maybe_first_row::<CassandraPausedRow>()
            .map_err(|error| {
                offset_store_error("decode Cassandra projection management row", error)
            })?;
        Ok(row.is_some_and(|row| row.paused))
    }

    async fn set_paused(&self, projection_id: &ProjectionId, paused: bool) -> ProjectionResult<()> {
        projection_id.validate()?;
        let connected = self.ready().await?;
        connected
            .session
            .execute_unpaged(
                &connected.statements.upsert_paused,
                (
                    projection_id.name(),
                    Self::partition_for(projection_id),
                    projection_id.key(),
                    paused,
                ),
            )
            .await
            .map_err(|error| {
                offset_store_error("save Cassandra projection management row", error)
            })?;
        Ok(())
    }
}

fn row_key(projection_id: &ProjectionId) -> (&str, i32, &str) {
    (
        projection_id.name(),
        CassandraProjectionOffsetStore::partition_for(projection_id),
        projection_id.key(),
    )
}

#[derive(Debug)]
struct ConnectedCassandraProjection {
    session: Arc<Session>,
    statements: CassandraProjectionStatements,
}

#[derive(Debug)]
struct CassandraProjectionStatements {
    select_offset: PreparedStatement,
    insert_initial_generation: PreparedStatement,
    advance_generation: PreparedStatement,
    save_without_cursor: PreparedStatement,
    save_with_cursor: PreparedStatement,
    clear_cursor: PreparedStatement,
    select_paused: PreparedStatement,
    upsert_paused: PreparedStatement,
}

#[derive(Debug)]
struct CassandraProjectionSchema {
    offset_store: String,
    management: String,
    ddl: Vec<String>,
}

impl CassandraProjectionSchema {
    fn new(config: &CassandraProjectionOffsetStoreConfig) -> Self {
        let offset_store = qualified(&config.keyspace, &config.tables.offset_store);
        let management = qualified(&config.keyspace, &config.tables.management);
        let ddl = vec![
            format!(
                "CREATE KEYSPACE IF NOT EXISTS {} WITH replication = {{'class': \
                 'SimpleStrategy', 'replication_factor': {}}} AND durable_writes = true",
                config.keyspace, config.replication_factor
            ),
            format!(
                "CREATE TABLE IF NOT EXISTS {offset_store} (\
                 projection_name text, partition int, projection_key text, generation bigint, \
                 has_cursor boolean, cursor_position text, offset text, manifest text, \
                 last_updated timestamp, \
                 PRIMARY KEY ((projection_name, partition), projection_key))"
            ),
            format!(
                "CREATE TABLE IF NOT EXISTS {management} (\
                 projection_name text, partition int, projection_key text, paused boolean, \
                 last_updated timestamp, \
                 PRIMARY KEY ((projection_name, partition), projection_key))"
            ),
        ];
        Self {
            offset_store,
            management,
            ddl,
        }
    }
}

async fn connect_cassandra(
    config: &CassandraProjectionOffsetStoreConfig,
    schema: &CassandraProjectionSchema,
) -> ProjectionResult<Arc<ConnectedCassandraProjection>> {
    let session = SessionBuilder::new()
        .known_nodes(config.contact_points.iter().map(String::as_str))
        .build()
        .await
        .map_err(|error| offset_store_error("connect Cassandra projection session", error))?;
    let session = Arc::new(session);
    for ddl in &schema.ddl {
        session
            .query_unpaged(ddl.as_str(), ())
            .await
            .map_err(|error| {
                offset_store_error("execute Cassandra projection schema bootstrap", error)
            })?;
    }
    let statements = prepare_statements(&session, config, schema).await?;
    Ok(Arc::new(ConnectedCassandraProjection {
        session,
        statements,
    }))
}

async fn prepare_statements(
    session: &Session,
    config: &CassandraProjectionOffsetStoreConfig,
    schema: &CassandraProjectionSchema,
) -> ProjectionResult<CassandraProjectionStatements> {
    let select_offset = prepare(
        session,
        format!(
            "SELECT generation, has_cursor, cursor_position, offset, manifest FROM {} \
             WHERE projection_name = ? AND partition = ? AND projection_key = ?",
            schema.offset_store
        ),
        config.read_consistency,
        None,
    )
    .await?;
    let insert_initial_generation = prepare(
        session,
        format!(
            "INSERT INTO {} (projection_name, partition, projection_key, generation, \
             has_cursor, last_updated) VALUES (?, ?, ?, 1, false, toTimestamp(now())) \
             IF NOT EXISTS",
            schema.offset_store
        ),
        config.write_consistency,
        Some(config.serial_consistency),
    )
    .await?;
    let advance_generation = prepare(
        session,
        format!(
            "UPDATE {} SET generation = ?, last_updated = toTimestamp(now()) \
             WHERE projection_name = ? AND partition = ? AND projection_key = ? \
             IF generation = ?",
            schema.offset_store
        ),
        config.write_consistency,
        Some(config.serial_consistency),
    )
    .await?;
    let save_without_cursor = prepare(
        session,
        format!(
            "UPDATE {} SET has_cursor = true, cursor_position = ?, offset = ?, manifest = ?, \
             last_updated = toTimestamp(now()) \
             WHERE projection_name = ? AND partition = ? AND projection_key = ? \
             IF generation = ? AND has_cursor = ?",
            schema.offset_store
        ),
        config.write_consistency,
        Some(config.serial_consistency),
    )
    .await?;
    let save_with_cursor = prepare(
        session,
        format!(
            "UPDATE {} SET has_cursor = true, cursor_position = ?, offset = ?, manifest = ?, \
             last_updated = toTimestamp(now()) \
             WHERE projection_name = ? AND partition = ? AND projection_key = ? \
             IF generation = ? AND has_cursor = ? AND cursor_position = ?",
            schema.offset_store
        ),
        config.write_consistency,
        Some(config.serial_consistency),
    )
    .await?;
    let clear_cursor = prepare(
        session,
        format!(
            "UPDATE {} SET has_cursor = false, cursor_position = null, offset = null, \
             manifest = null, last_updated = toTimestamp(now()) \
             WHERE projection_name = ? AND partition = ? AND projection_key = ? \
             IF generation = ?",
            schema.offset_store
        ),
        config.write_consistency,
        Some(config.serial_consistency),
    )
    .await?;
    let select_paused = prepare(
        session,
        format!(
            "SELECT paused FROM {} WHERE projection_name = ? AND partition = ? \
             AND projection_key = ?",
            schema.management
        ),
        config.read_consistency,
        None,
    )
    .await?;
    let upsert_paused = prepare(
        session,
        format!(
            "INSERT INTO {} (projection_name, partition, projection_key, paused, last_updated) \
             VALUES (?, ?, ?, ?, toTimestamp(now()))",
            schema.management
        ),
        config.write_consistency,
        None,
    )
    .await?;
    Ok(CassandraProjectionStatements {
        select_offset,
        insert_initial_generation,
        advance_generation,
        save_without_cursor,
        save_with_cursor,
        clear_cursor,
        select_paused,
        upsert_paused,
    })
}

async fn prepare(
    session: &Session,
    cql: String,
    consistency: Consistency,
    serial_consistency: Option<SerialConsistency>,
) -> ProjectionResult<PreparedStatement> {
    let mut statement = session
        .prepare(cql)
        .await
        .map_err(|error| offset_store_error("prepare Cassandra projection statement", error))?;
    statement.set_consistency(consistency);
    if let Some(serial_consistency) = serial_consistency {
        statement.set_serial_consistency(Some(serial_consistency));
    }
    Ok(statement)
}

#[derive(Debug, scylla::DeserializeRow)]
#[scylla(flavor = "enforce_order", skip_name_checks)]
struct CassandraOffsetRow {
    generation: Option<i64>,
    has_cursor: Option<bool>,
    cursor_position: Option<String>,
    offset: Option<String>,
    manifest: Option<String>,
}

#[derive(Debug, scylla::DeserializeRow)]
#[scylla(flavor = "enforce_order", skip_name_checks)]
struct CassandraPausedRow {
    paused: bool,
}

#[derive(Debug)]
struct StoredOffsetState {
    generation: ProjectionGeneration,
    has_cursor: bool,
    cursor_position: Option<String>,
    offset: Option<String>,
    manifest: Option<String>,
}

impl StoredOffsetState {
    fn decode(row: CassandraOffsetRow) -> ProjectionResult<Self> {
        let generation = row.generation.ok_or_else(|| {
            ProjectionError::CursorCodec(
                "Cassandra projection offset row is missing generation".into(),
            )
        })?;
        let generation = u64::try_from(generation).map_err(|_| {
            ProjectionError::CursorCodec(format!(
                "Cassandra projection offset row has negative generation {generation}"
            ))
        })?;
        let has_cursor = row.has_cursor.ok_or_else(|| {
            ProjectionError::CursorCodec(
                "Cassandra projection offset row is missing has_cursor".into(),
            )
        })?;
        Ok(Self {
            generation: ProjectionGeneration::new(generation),
            has_cursor,
            cursor_position: row.cursor_position,
            offset: row.offset,
            manifest: row.manifest,
        })
    }

    fn position(&self) -> ProjectionResult<Option<CursorPosition>> {
        if !self.has_cursor {
            if self.cursor_position.is_some() || self.offset.is_some() || self.manifest.is_some() {
                return Err(ProjectionError::CursorCodec(
                    "cleared Cassandra projection offset row retains cursor fields".into(),
                ));
            }
            return Ok(None);
        }
        self.cursor_position
            .as_ref()
            .map(|position| CursorPosition::new(position.clone()))
            .map(Some)
            .ok_or_else(|| {
                ProjectionError::CursorCodec(
                    "Cassandra projection offset row is missing cursor_position".into(),
                )
            })
    }

    fn cursor(self) -> ProjectionResult<Option<ProjectionCursor>> {
        if self.position()?.is_none() {
            return Ok(None);
        }
        let offset = self.offset.ok_or_else(|| {
            ProjectionError::CursorCodec(
                "Cassandra projection offset row is missing encoded offset".into(),
            )
        })?;
        let manifest = self.manifest.ok_or_else(|| {
            ProjectionError::CursorCodec(
                "Cassandra projection offset row is missing provider manifest".into(),
            )
        })?;
        let cursor = ProjectionCursor::decode(&offset)?;
        if cursor.provider_manifest().as_str() != manifest {
            return Err(ProjectionError::CursorCodec(format!(
                "Cassandra projection offset manifest {manifest:?} does not match encoded cursor \
                 manifest {:?}",
                cursor.provider_manifest().as_str()
            )));
        }
        if self.cursor_position.as_deref() != Some(cursor.position().as_str()) {
            return Err(ProjectionError::CursorCodec(format!(
                "Cassandra projection cursor position {:?} does not match encoded position {:?}",
                self.cursor_position,
                cursor.position().as_str()
            )));
        }
        Ok(Some(cursor))
    }
}

fn lwt_applied(result: QueryResult) -> ProjectionResult<bool> {
    let rows = result
        .into_rows_result()
        .map_err(|error| offset_store_error("decode Cassandra projection LWT result", error))?;
    let row = rows
        .first_row::<Row>()
        .map_err(|error| offset_store_error("decode Cassandra projection LWT row", error))?;
    match row.columns.first().and_then(Option::as_ref) {
        Some(CqlValue::Boolean(applied)) => Ok(*applied),
        other => Err(ProjectionError::OffsetStore(format!(
            "Cassandra projection LWT result did not contain boolean [applied], got {other:?}"
        ))),
    }
}

fn generation_i64(
    generation: ProjectionGeneration,
    projection_id: &ProjectionId,
) -> ProjectionResult<i64> {
    i64::try_from(generation.as_u64()).map_err(|_| ProjectionError::GenerationExhausted {
        projection_id: projection_id.clone(),
    })
}

fn validate_config(config: &CassandraProjectionOffsetStoreConfig) -> ProjectionResult<()> {
    if config.contact_points.is_empty()
        || config
            .contact_points
            .iter()
            .any(|contact_point| contact_point.trim().is_empty())
    {
        return Err(ProjectionError::invalid_config(
            "cassandra.contact_points",
            "contact_points must contain at least one non-empty seed",
        ));
    }
    validate_identifier("cassandra.keyspace", &config.keyspace)?;
    validate_identifier("cassandra.tables.offset_store", &config.tables.offset_store)?;
    validate_identifier("cassandra.tables.management", &config.tables.management)?;
    if config.tables.offset_store == config.tables.management {
        return Err(ProjectionError::invalid_config(
            "cassandra.tables",
            "offset_store and management must use different table names",
        ));
    }
    if config.replication_factor == 0 {
        return Err(ProjectionError::invalid_config(
            "cassandra.replication_factor",
            "replication_factor must be greater than zero",
        ));
    }
    if matches!(
        config.write_consistency,
        Consistency::Any | Consistency::Serial | Consistency::LocalSerial
    ) {
        return Err(ProjectionError::invalid_config(
            "cassandra.write_consistency",
            "write_consistency cannot be ANY, SERIAL, or LOCAL_SERIAL",
        ));
    }
    if matches!(
        config.read_consistency,
        Consistency::Any | Consistency::Serial | Consistency::LocalSerial
    ) {
        return Err(ProjectionError::invalid_config(
            "cassandra.read_consistency",
            "read_consistency must be non-serial",
        ));
    }
    Ok(())
}

fn validate_identifier(setting: &'static str, value: &str) -> ProjectionResult<()> {
    let mut characters = value.chars();
    let valid_first = characters
        .next()
        .is_some_and(|character| character == '_' || character.is_ascii_lowercase());
    if !valid_first
        || !characters.all(|character| {
            character == '_' || character.is_ascii_lowercase() || character.is_ascii_digit()
        })
        || value.len() > MAX_CQL_IDENTIFIER_BYTES
    {
        return Err(ProjectionError::invalid_config(
            setting,
            format!(
                "expected a lowercase ASCII CQL identifier of at most \
                 {MAX_CQL_IDENTIFIER_BYTES} bytes, got {value:?}"
            ),
        ));
    }
    Ok(())
}

fn qualified(keyspace: &str, table: &str) -> String {
    format!("{keyspace}.{table}")
}

fn offset_store_error(context: &str, error: impl fmt::Display) -> ProjectionError {
    ProjectionError::OffsetStore(format!("{context}: {error}"))
}

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

    #[test]
    fn schema_is_partition_distributed_and_contains_fencing_columns() {
        let store = CassandraProjectionOffsetStore::new(CassandraProjectionOffsetStoreConfig::new(
            "127.0.0.1:9042",
            "datum_projection_test",
        ))
        .expect("configuration is valid");
        let ddl = store.schema_ddl();
        assert!(ddl.contains("PRIMARY KEY ((projection_name, partition), projection_key)"));
        assert!(ddl.contains("generation bigint"));
        assert!(ddl.contains("has_cursor boolean"));
        assert!(ddl.contains("cursor_position text"));
        assert!(ddl.contains("datum_projection_management"));
    }

    #[test]
    fn partition_mapping_matches_akka_java_hash_fixtures() {
        let fixtures = [
            ("carts-1", 4),
            ("slices-0-255@v1", 3),
            ("λ-projection", 2),
            ("", 0),
        ];
        for (key, expected) in fixtures {
            let id = ProjectionId::new("projection", key);
            assert_eq!(
                CassandraProjectionOffsetStore::partition_for(&id),
                expected,
                "unexpected partition for key {key:?}"
            );
        }
    }

    #[test]
    fn exactly_once_is_rejected_with_typed_fatal_error() {
        let store = CassandraProjectionOffsetStore::new(CassandraProjectionOffsetStoreConfig::new(
            "127.0.0.1:9042",
            "datum_projection_test",
        ))
        .expect("configuration is valid");
        let error = store
            .validate_exactly_once()
            .expect_err("Cassandra must reject exactly-once");
        assert!(matches!(
            error,
            ProjectionError::InvalidConfig {
                setting: "delivery_semantics",
                ..
            }
        ));
        assert!(error.is_fatal());
    }

    #[test]
    fn constructor_rejects_unsafe_cql_configuration_without_connecting() {
        let mut config =
            CassandraProjectionOffsetStoreConfig::new("127.0.0.1:9042", "datum_projection_test");
        config.tables.offset_store = "offset-store".into();
        let error = CassandraProjectionOffsetStore::new(config)
            .expect_err("invalid identifiers must fail before I/O");
        assert!(matches!(error, ProjectionError::InvalidConfig { .. }));
    }
}