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;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CassandraProjectionTableNames {
pub offset_store: String,
pub management: String,
}
impl Default for CassandraProjectionTableNames {
fn default() -> Self {
Self {
offset_store: "datum_projection_offset_store".into(),
management: "datum_projection_management".into(),
}
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct CassandraProjectionOffsetStoreConfig {
pub contact_points: Vec<String>,
pub keyspace: String,
pub replication_factor: u32,
pub tables: CassandraProjectionTableNames,
pub write_consistency: Consistency,
pub read_consistency: Consistency,
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 {
#[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,
}
}
}
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 {
pub fn new(config: CassandraProjectionOffsetStoreConfig) -> ProjectionResult<Self> {
validate_config(&config)?;
let schema = CassandraProjectionSchema::new(&config);
Ok(Self {
config,
schema,
connected: OnceCell::new(),
})
}
pub async fn connect(config: CassandraProjectionOffsetStoreConfig) -> ProjectionResult<Self> {
let store = Self::new(config)?;
store.initialize().await?;
Ok(store)
}
pub async fn initialize(&self) -> ProjectionResult<()> {
self.connected
.get_or_try_init(|| connect_cassandra(&self.config, &self.schema))
.await
.map(|_| ())
}
#[must_use]
pub fn config(&self) -> &CassandraProjectionOffsetStoreConfig {
&self.config
}
#[must_use]
pub fn schema_ddl(&self) -> String {
let mut ddl = self.schema.ddl.join(";\n");
ddl.push(';');
ddl
}
#[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 { .. }));
}
}