diff --git a/crates/storage-cassandra/src/admin_store.rs b/crates/storage-cassandra/src/admin_store.rs index 2189233b9..ba73263f4 100755 --- a/crates/storage-cassandra/src/admin_store.rs +++ b/crates/storage-cassandra/src/admin_store.rs @@ -3,6 +3,8 @@ //! `AdminStore` implementation for `CassandraCatalogStore`. +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use cdrs_tokio::types::IntoRustByName; use extenddb_storage::management_store::{AdminEntry, OpError, OpResult}; use futures::future::BoxFuture; @@ -39,7 +41,8 @@ impl extenddb_storage::management_store::AdminStore for CassandraCatalogStore { ); let result = session - .query_with_values( + .run( + Stmt::Lwt, &query, cdrs_tokio::query_values!(admin_name.as_str(), password_hash.as_str()), ) @@ -119,7 +122,7 @@ impl extenddb_storage::management_store::AdminStore for CassandraCatalogStore { // Quorum, so the console's quorum session check sees the deletion. let query = format!("DELETE FROM {catalog_keyspace}.admin_users WHERE admin_name = ?"); - crate::cassandra_util::execute_quorum( + crate::cassandra_util::execute( &session, &query, cdrs_tokio::query_values!(admin_name.as_str()), @@ -147,7 +150,7 @@ impl extenddb_storage::management_store::AdminStore for CassandraCatalogStore { let query = format!( "UPDATE {catalog_keyspace}.admin_users SET password_hash = ? WHERE admin_name = ?" ); - crate::cassandra_util::execute_quorum( + crate::cassandra_util::execute( &session, &query, cdrs_tokio::query_values!(password_hash.as_str(), admin_name.as_str()), diff --git a/crates/storage-cassandra/src/authorization_store.rs b/crates/storage-cassandra/src/authorization_store.rs index 9cec84781..ae0a6ec01 100755 --- a/crates/storage-cassandra/src/authorization_store.rs +++ b/crates/storage-cassandra/src/authorization_store.rs @@ -3,6 +3,8 @@ //! `AuthorizationStore` implementation for `CassandraCatalogStore`. +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use cdrs_tokio::types::IntoRustByName; use extenddb_storage::authorization_store::{AuthorizationStore, SessionData}; use extenddb_storage::management_store::{OpError, OpResult}; @@ -26,7 +28,8 @@ impl AuthorizationStore for CassandraCatalogStore { WHERE account_id = ? AND principal_type = 'user' AND principal_name = ?" ); let result = session - .query_with_values( + .run( + Stmt::Read, &query, cdrs_tokio::query_values!(account_id.as_str(), user_name.as_str()), ) @@ -73,7 +76,8 @@ impl AuthorizationStore for CassandraCatalogStore { WHERE account_id = ? AND user_name = ? ALLOW FILTERING" ); let groups_result = session - .query_with_values( + .run( + Stmt::Read, &groups_query, cdrs_tokio::query_values!(account_id.as_str(), user_name.as_str()), ) @@ -103,7 +107,8 @@ impl AuthorizationStore for CassandraCatalogStore { WHERE account_id = ? AND principal_type = 'group' AND principal_name = ?" ); let policy_result = session - .query_with_values( + .run( + Stmt::Read, &policy_query, cdrs_tokio::query_values!(account_id.as_str(), group_name.as_str()), ) @@ -151,7 +156,8 @@ impl AuthorizationStore for CassandraCatalogStore { WHERE account_id = ? AND principal_type = 'user' AND principal_name = ?" ); let result = session - .query_with_values( + .run( + Stmt::Read, &query, cdrs_tokio::query_values!(account_id.as_str(), user_name.as_str()), ) @@ -266,7 +272,8 @@ impl AuthorizationStore for CassandraCatalogStore { ); let result = session - .query_with_values( + .run( + Stmt::Read, &query, cdrs_tokio::query_values!( account_id.as_str(), @@ -354,7 +361,8 @@ impl AuthorizationStore for CassandraCatalogStore { ); let result = session - .query_with_values( + .run( + Stmt::Read, &query, cdrs_tokio::query_values!(account_id.as_str(), user_name.as_str()), ) @@ -408,7 +416,8 @@ impl AuthorizationStore for CassandraCatalogStore { ); let result = session - .query_with_values( + .run( + Stmt::Read, &query, cdrs_tokio::query_values!(account_id.as_str(), role_name.as_str()), ) @@ -456,7 +465,7 @@ impl AuthorizationStore for CassandraCatalogStore { ); let result = session - .query_with_values(&query, cdrs_tokio::query_values!(arn.as_str())) + .run(Stmt::Read, &query, cdrs_tokio::query_values!(arn.as_str())) .await .map_err(|e| { tracing::error!("fetch_resource_tags query failed: {e}"); diff --git a/crates/storage-cassandra/src/backup_catalog.rs b/crates/storage-cassandra/src/backup_catalog.rs index 824864144..0ac0f6655 100644 --- a/crates/storage-cassandra/src/backup_catalog.rs +++ b/crates/storage-cassandra/src/backup_catalog.rs @@ -114,13 +114,13 @@ //! serial level is a local quorum with no Paxos read, so the scan reads at //! quorum and the coordinator clock after it. +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use std::time::Duration; -use cdrs_tokio::consistency::Consistency; use cdrs_tokio::error::Error as DriverError; use cdrs_tokio::frame::message_error::ErrorType; -use cdrs_tokio::query::{BatchQueryBuilder, QueryValues}; -use cdrs_tokio::statement::StatementParamsBuilder; +use cdrs_tokio::query::QueryValues; use cdrs_tokio::types::IntoRustByName; use cdrs_tokio::types::rows::Row; use cdrs_tokio::types::value::Value; @@ -184,7 +184,7 @@ fn seconds_to_millis(seconds: f64) -> i64 { /// The coordinator's clock, in epoch milliseconds: the clock every heartbeat /// is stamped with, so a stale window is measured on it. pub(crate) async fn coordinator_now_millis(engine: &CassandraEngine) -> Result { - let rows = crate::cassandra_util::query_rows::( + let rows = crate::cassandra_util::system_read::( &engine.session, "SELECT toTimestamp(now()) AS now FROM system.local", cdrs_tokio::query_values!(), @@ -242,12 +242,7 @@ pub(crate) async fn conditional_write( query: &str, values: QueryValues, ) -> Result { - let params = StatementParamsBuilder::new() - .with_consistency(Consistency::LocalQuorum) - .with_serial_consistency(Consistency::LocalSerial) - .with_values(values) - .build(); - match session.query_with_params(query, params).await { + match session.run(Stmt::Lwt, query, values).await { Ok(result) => Ok(if crate::cassandra_util::lwt_applied(&result)? { WriteOutcome::Matched } else { @@ -463,7 +458,7 @@ impl JobClaim for CassandraBackupClaim { FROM {}.backups_by_arn WHERE account_id = ? AND backup_arn = ?", self.engine.catalog_keyspace() ); - let rows = crate::cassandra_util::query_rows_quorum::( + let rows = crate::cassandra_util::query_rows::( &self.engine.session, &query, cdrs_tokio::query_values!( @@ -502,8 +497,7 @@ impl CassandraEngine { if let Some(error) = crate::test_hooks::index_entry_removal_error(&row.backup_arn) { return Err(error); } - let batch = BatchQueryBuilder::new() - .with_consistency(Consistency::LocalQuorum) + let batch = crate::cassandra_util::batch() .add_query( format!( "DELETE FROM {catalog}.backup_index_by_status \ @@ -539,7 +533,7 @@ impl CassandraEngine { ), ); self.session - .batch( + .run_batch( batch .build() .map_err(|e| StorageError::Internal(e.to_string()))?, @@ -564,8 +558,7 @@ impl CassandraEngine { if let Some(error) = crate::test_hooks::index_entry_batch_error(&row.backup_arn) { return Err(error); } - let batch = BatchQueryBuilder::new() - .with_consistency(Consistency::LocalQuorum) + let batch = crate::cassandra_util::batch() .add_query( format!( "INSERT INTO {catalog}.backups_by_account (account_id, created_at, \ @@ -616,7 +609,7 @@ impl CassandraEngine { ), ); self.session - .batch( + .run_batch( batch .build() .map_err(|e| StorageError::Internal(e.to_string()))?, @@ -659,7 +652,7 @@ impl CassandraEngine { "SELECT * FROM {}.backups_by_arn WHERE account_id = ? AND backup_arn = ?", self.catalog_keyspace() ); - let rows = crate::cassandra_util::query_rows_quorum::( + let rows = crate::cassandra_util::query_rows::( &self.session, &query, cdrs_tokio::query_values!(account_id, backup_arn), @@ -686,8 +679,7 @@ impl CassandraEngine { to: &str, ) { let catalog = self.catalog_keyspace(); - let batch = BatchQueryBuilder::new() - .with_consistency(Consistency::LocalQuorum) + let batch = crate::cassandra_util::batch() .add_query( format!( "DELETE FROM {catalog}.backup_index_by_status \ @@ -711,7 +703,7 @@ impl CassandraEngine { ), ); let sent = match batch.build() { - Ok(batch) => self.session.batch(batch).await.map(|_| ()), + Ok(batch) => self.session.run_batch(batch).await.map(|_| ()), Err(error) => Err(error), }; if let Err(error) = sent { @@ -907,7 +899,7 @@ impl CassandraEngine { WHERE store_root = ? AND backup_status = ?", self.catalog_keyspace() ); - let rows = crate::cassandra_util::query_rows_quorum::( + let rows = crate::cassandra_util::query_rows::( &self.session, &query, cdrs_tokio::query_values!(store_root, status.as_str()), @@ -943,7 +935,7 @@ impl CassandraEngine { ) -> Result<(), StorageError> { let catalog = self.catalog_keyspace(); if remove { - crate::cassandra_util::query_rows_quorum::( + crate::cassandra_util::execute::( &self.session, &format!( "DELETE FROM {catalog}.backup_index_by_status \ @@ -958,7 +950,7 @@ impl CassandraEngine { ) .await?; } else { - crate::cassandra_util::query_rows_quorum::( + crate::cassandra_util::execute::( &self.session, &format!( "INSERT INTO {catalog}.backup_index_by_status \ @@ -1236,7 +1228,7 @@ impl CassandraEngine { FROM {}.tables WHERE account_id = ? AND table_name = ?", self.catalog_keyspace() ); - let rows = crate::cassandra_util::query_rows_quorum::( + let rows = crate::cassandra_util::query_rows::( &self.session, &query, cdrs_tokio::query_values!(account_id, table_name), @@ -1429,7 +1421,7 @@ impl JobClaim for CassandraRestoreClaim { restore_failure_reason FROM {}.tables WHERE account_id = ? AND table_name = ?", self.engine.catalog_keyspace() ); - let rows = crate::cassandra_util::query_rows_quorum::( + let rows = crate::cassandra_util::query_rows::( &self.engine.session, &query, cdrs_tokio::query_values!( @@ -1472,7 +1464,7 @@ impl BackupCatalog for CassandraEngine { "SELECT value FROM {}.settings WHERE key = 'catalog_id'", self.catalog_keyspace() ); - let rows = crate::cassandra_util::query_rows_quorum::( + let rows = crate::cassandra_util::query_rows::( &self.session, &query, cdrs_tokio::query_values!(), @@ -1815,13 +1807,9 @@ impl BackupCatalog for CassandraEngine { query.push_str(" AND created_at < ?"); values.push(Value::from((upper * 1_000.0).ceil() as i64)); } - let params = StatementParamsBuilder::new() - .with_consistency(Consistency::LocalQuorum) - .with_values(QueryValues::SimpleValues(values)) - .build(); let listed = self .session - .query_with_params(&query, params) + .run(Stmt::Read, &query, QueryValues::SimpleValues(values)) .await .map_err(|e| StorageError::Internal(format!("List backup index: {e}")))? .response_body() @@ -2239,7 +2227,7 @@ impl BackupCatalog for CassandraEngine { let scan = format!( "SELECT account_id, backup_arn, active_restores FROM {catalog}.backups_by_arn" ); - let rows = crate::cassandra_util::query_rows_quorum::( + let rows = crate::cassandra_util::query_rows::( &self.session, &scan, cdrs_tokio::query_values!(), @@ -2418,7 +2406,7 @@ impl BackupCatalog for CassandraEngine { ALLOW FILTERING", self.catalog_keyspace() ); - let rows = crate::cassandra_util::query_rows_quorum::( + let rows = crate::cassandra_util::query_rows::( &self.session, &query, cdrs_tokio::query_values!(status), @@ -2502,7 +2490,7 @@ impl BackupCatalog for CassandraEngine { ALLOW FILTERING", self.catalog_keyspace() ); - let rows = crate::cassandra_util::query_rows_quorum::( + let rows = crate::cassandra_util::query_rows::( &self.session, &query, cdrs_tokio::query_values!(), @@ -2672,7 +2660,7 @@ impl BackupCatalog for CassandraEngine { WHERE account_id = ? AND table_name = ?", self.catalog_keyspace() ); - let rows = crate::cassandra_util::query_rows_quorum::( + let rows = crate::cassandra_util::query_rows::( &self.session, &query, cdrs_tokio::query_values!(key.account_id.as_str(), key.table_name.as_str()), @@ -2711,7 +2699,7 @@ impl BackupCatalog for CassandraEngine { ALLOW FILTERING", self.catalog_keyspace() ); - let rows = crate::cassandra_util::query_rows_quorum::( + let rows = crate::cassandra_util::query_rows::( &self.session, &query, cdrs_tokio::query_values!(status.as_str()), @@ -2788,7 +2776,7 @@ impl BackupCatalog for CassandraEngine { BackupStatus::Deleted, BackupStatus::Failed, ] { - let rows = crate::cassandra_util::query_rows_quorum::( + let rows = crate::cassandra_util::query_rows::( &self.session, &query, cdrs_tokio::query_values!(store_root, status.as_str()), @@ -2854,7 +2842,7 @@ impl BackupCatalog for CassandraEngine { } _ => sweep.removed += 1, } - crate::cassandra_util::query_rows_quorum::( + crate::cassandra_util::execute::( &self.session, &delete, cdrs_tokio::query_values!(store_root, status.as_str(), backup_arn.as_str()), @@ -2874,7 +2862,7 @@ impl BackupCatalog for CassandraEngine { // the kind and id they carry. Hints, not verified against the // rows (the trait doc). let catalog = self.catalog_keyspace(); - let partitions = crate::cassandra_util::query_rows_quorum::( + let partitions = crate::cassandra_util::query_rows::( &self.session, &format!("SELECT DISTINCT store_root, backup_status FROM {catalog}.backup_index_by_status"), cdrs_tokio::query_values!(), @@ -2892,7 +2880,7 @@ impl BackupCatalog for CassandraEngine { let status: String = crate::cassandra_util::get_column(&partition, "backup_status", "status index")?; let status = BackupStatus::parse(&status)?; - let rows = crate::cassandra_util::query_rows_quorum::( + let rows = crate::cassandra_util::query_rows::( &self.session, &entries_query, cdrs_tokio::query_values!(root.as_str(), status.as_str()), @@ -3431,6 +3419,7 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; + use cdrs_tokio::consistency::Consistency; use cdrs_tokio::frame::message_error::{ErrorBody, WriteTimeoutError, WriteType}; use super::*; diff --git a/crates/storage-cassandra/src/backup_engine.rs b/crates/storage-cassandra/src/backup_engine.rs index 82c83b9ef..ca470c31a 100755 --- a/crates/storage-cassandra/src/backup_engine.rs +++ b/crates/storage-cassandra/src/backup_engine.rs @@ -83,13 +83,13 @@ //! that read the in-catalog row before the conversion does not claim the //! index row after it. +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use std::collections::HashMap; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::time::Duration; -use cdrs_tokio::consistency::Consistency; -use cdrs_tokio::query::BatchQueryBuilder; use cdrs_tokio::types::map::Map; use cdrs_tokio::types::{AsRust, IntoRustByName, rows::Row}; use extenddb_core::types::{ @@ -512,7 +512,7 @@ impl CassandraEngine { "SELECT * FROM {}.backups_by_arn WHERE account_id = ? AND backup_arn = ?", self.catalog_keyspace() ); - let rows = crate::cassandra_util::query_rows_quorum::( + let rows = crate::cassandra_util::query_rows::( &self.session, &query, cdrs_tokio::query_values!(account_id, backup_arn), @@ -595,7 +595,7 @@ impl CassandraEngine { #[allow(clippy::cast_possible_truncation)] let bucket_i32 = bucket as i32; if bucket >= known { - let rows = crate::cassandra_util::query_rows_quorum::( + let rows = crate::cassandra_util::query_rows::( &self.session, &probe, cdrs_tokio::query_values!(backup_arn, bucket_i32), @@ -607,7 +607,11 @@ impl CassandraEngine { } } self.session - .query_with_values(&delete, cdrs_tokio::query_values!(backup_arn, bucket_i32)) + .run( + Stmt::Write, + &delete, + cdrs_tokio::query_values!(backup_arn, bucket_i32), + ) .await .map_err(|e| StorageError::Internal(format!("Delete backup payload: {e}")))?; bucket += 1; @@ -644,7 +648,8 @@ impl CassandraEngine { "DELETE FROM {catalog}.backups_by_account WHERE account_id = ? AND created_at = ? AND backup_arn = ?" ); self.session - .query_with_values( + .run( + Stmt::Write, &by_account, cdrs_tokio::query_values!( backup.account_id.as_str(), @@ -659,7 +664,8 @@ impl CassandraEngine { "DELETE FROM {catalog}.backups_by_table WHERE account_id = ? AND table_name = ? AND created_at = ? AND backup_arn = ?" ); self.session - .query_with_values( + .run( + Stmt::Write, &by_table, cdrs_tokio::query_values!( backup.account_id.as_str(), @@ -869,7 +875,7 @@ impl CassandraEngine { WHERE account_id = ? AND table_name = ?", self.catalog_keyspace() ); - let row = crate::cassandra_util::query_rows_quorum::( + let row = crate::cassandra_util::query_rows::( &self.session, &query, cdrs_tokio::query_values!(account_id, target_name), @@ -902,7 +908,7 @@ impl CassandraEngine { WHERE account_id = ? AND table_name = ?", self.catalog_keyspace() ); - let row = crate::cassandra_util::query_rows_quorum::( + let row = crate::cassandra_util::query_rows::( &self.session, &query, cdrs_tokio::query_values!(account_id, table_name), @@ -942,7 +948,7 @@ impl CassandraEngine { ALLOW FILTERING", self.catalog_keyspace() ); - let rows = crate::cassandra_util::query_rows_quorum::( + let rows = crate::cassandra_util::query_rows::( &self.session, &query, cdrs_tokio::query_values!(account_id, backup_arn), @@ -1251,7 +1257,8 @@ impl CassandraEngine { let bucket_i32 = bucket as i32; let rows = self .session - .query_with_values( + .run( + Stmt::Read, &query, cdrs_tokio::query_values!(job.backup_arn.as_str(), bucket_i32), ) @@ -1793,17 +1800,17 @@ impl CassandraEngine { let mut keys = Vec::new(); let mut paging_state = None; loop { - let mut params = cdrs_tokio::statement::StatementParamsBuilder::new() - .with_consistency(Consistency::LocalQuorum) - .with_page_size(page_size); - if let Some(state) = paging_state.take() { - params = params.with_paging_state(state); - } let failed = |e: cdrs_tokio::error::Error| StorageError::Internal(format!("{WHAT}: {e}")); let body = self .session - .query_with_params(&scan, params.build()) + .run_paged( + Stmt::Read, + &scan, + cdrs_tokio::query_values!(), + page_size, + paging_state.take(), + ) .await .map_err(failed)? .response_body() @@ -1998,7 +2005,8 @@ impl LegacyBackupReader for CassandraEngine { #[allow(clippy::cast_possible_truncation)] let bucket_i32 = bucket as i32; self.session - .query_with_values( + .run( + Stmt::Write, &insert_item, cdrs_tokio::query_values!( backup_arn.as_str(), @@ -2070,8 +2078,7 @@ impl LegacyBackupReader for CassandraEngine { // once its heartbeat is stale, rather than an AVAILABLE backup no // listing ever shows. let list_rows: Result<(), StorageError> = async { - let batch = BatchQueryBuilder::new() - .with_consistency(Consistency::LocalQuorum) + let batch = crate::cassandra_util::batch() .add_query( insert_by_account, cdrs_tokio::query_values!( @@ -2099,7 +2106,7 @@ impl LegacyBackupReader for CassandraEngine { ), ); self.session - .batch( + .run_batch( batch .build() .map_err(|e| StorageError::Internal(e.to_string()))?, @@ -2205,7 +2212,8 @@ impl LegacyBackupReader for CassandraEngine { "SELECT backup_arn FROM {catalog}.backups_by_table WHERE account_id = ? AND table_name = ?" ); self.session - .query_with_values( + .run( + Stmt::Read, &query, cdrs_tokio::query_values!(account_id.as_str(), table_name), ) @@ -2215,7 +2223,11 @@ impl LegacyBackupReader for CassandraEngine { "SELECT backup_arn FROM {catalog}.backups_by_account WHERE account_id = ?" ); self.session - .query_with_values(&query, cdrs_tokio::query_values!(account_id.as_str())) + .run( + Stmt::Read, + &query, + cdrs_tokio::query_values!(account_id.as_str()), + ) .await }; let rows = result @@ -2421,7 +2433,7 @@ impl LegacyBackupReader for CassandraEngine { heartbeat_at FROM {catalog}.backups_by_arn \ WHERE backup_status = ? ALLOW FILTERING" ); - let rows = crate::cassandra_util::query_rows_quorum::( + let rows = crate::cassandra_util::query_rows::( &self.session, &query, cdrs_tokio::query_values!(status), @@ -2605,19 +2617,18 @@ const LEGACY_KEYS_PAGE: i32 = 1000; /// Rows of one item bucket `items` reads per query. const LEGACY_ITEMS_PAGE: i32 = 8; -/// The parameters of one page of `items`: the values at consistency `ALL`. -/// The in-catalog create wrote each bucket row at `ONE`, so a read of fewer -/// than every replica can miss a row one replica alone holds and end short; -/// at `ALL` every live replica's rows are merged, and a replica that does -/// not answer fails the read rather than shortening it +/// One page of `items`, read at `ALL`. The in-catalog create of an older +/// version wrote each bucket row at `ONE`, so a read of fewer than every +/// replica can miss a row that one replica alone holds, and end short. At +/// `ALL`, every live replica's rows are merged, and a replica that does not +/// answer fails the read instead of shortening it /// ([`legacy_items_read_error`]). -fn legacy_items_page_params( +async fn read_items_page( + session: &S, + query: &str, values: cdrs_tokio::query::QueryValues, -) -> cdrs_tokio::statement::StatementParams { - cdrs_tokio::statement::StatementParamsBuilder::new() - .with_consistency(Consistency::All) - .with_values(values) - .build() +) -> Result { + session.run(Stmt::ReadAll, query, values).await } /// A failed page read of `items`: a replica that did not answer the read @@ -2678,24 +2689,22 @@ impl LegacyItemsCursor { async fn read_page(&mut self) -> Result<(), StorageError> { #[allow(clippy::cast_possible_truncation)] let bucket = self.bucket as i32; - let rows = self - .engine - .session - .query_with_params( - &self.query, - legacy_items_page_params(cdrs_tokio::query_values!( - self.backup_arn.as_str(), - bucket, - self.after, - LEGACY_ITEMS_PAGE - )), - ) - .await - .map_err(|e| legacy_items_read_error(&e))? - .response_body() - .map_err(|e| StorageError::Internal(format!("Parse backup payload: {e}")))? - .into_rows() - .unwrap_or_default(); + let rows = read_items_page( + &*self.engine.session, + &self.query, + cdrs_tokio::query_values!( + self.backup_arn.as_str(), + bucket, + self.after, + LEGACY_ITEMS_PAGE + ), + ) + .await + .map_err(|e| legacy_items_read_error(&e))? + .response_body() + .map_err(|e| StorageError::Internal(format!("Parse backup payload: {e}")))? + .into_rows() + .unwrap_or_default(); let full = rows.len() >= usize::try_from(LEGACY_ITEMS_PAGE).unwrap_or(usize::MAX); for row in rows { let item_index: i64 = row @@ -2760,14 +2769,74 @@ fn restore_source_of(backup: &StoredBackup) -> Result>); + + impl Recorder { + fn record( + &self, + kind: Stmt, + ) -> std::future::Ready> + { + self.0.lock().expect("the record").push(kind); + std::future::ready(Err(cdrs_tokio::error::Error::General( + "recorded, not sent".to_owned(), + ))) + } + } + + impl crate::cassandra_util::PolicySession for Recorder { + fn run>( + &self, + kind: Stmt, + _query: Q, + _values: cdrs_tokio::query::QueryValues, + ) -> impl std::future::Future< + Output = Result, + > + Send { + self.record(kind) + } + + fn run_paged>( + &self, + kind: Stmt, + _query: Q, + _values: cdrs_tokio::query::QueryValues, + _page_size: i32, + _paging_state: Option, + ) -> impl std::future::Future< + Output = Result, + > + Send { + self.record(kind) + } + + fn run_batch( + &self, + _batch: cdrs_tokio::query::QueryBatch, + ) -> impl std::future::Future< + Output = Result, + > + Send { + std::future::ready(Err(cdrs_tokio::error::Error::General( + "recorded, not sent".to_owned(), + ))) + } + } + + /// `items` reads every page as `Stmt::ReadAll`, which runs at `ALL`: the + /// one level at which a row written at `ONE` to one replica cannot be + /// missed by a live read. One node cannot show the level, so this test + /// checks the kind that the page read sends. + #[tokio::test] + async fn the_legacy_item_pages_are_read_at_all() { + let session = Recorder::default(); + let _ = read_items_page( + &session, + "SELECT item_index, item_data FROM ks.backup_items", + cdrs_tokio::query_values!(), + ) + .await; + assert_eq!(*session.0.lock().expect("the record"), [Stmt::ReadAll]); } /// A replica that does not answer the read at `ALL` is named, the diff --git a/crates/storage-cassandra/src/bootstrapper.rs b/crates/storage-cassandra/src/bootstrapper.rs index abecf44aa..0eef33130 100644 --- a/crates/storage-cassandra/src/bootstrapper.rs +++ b/crates/storage-cassandra/src/bootstrapper.rs @@ -3,6 +3,8 @@ //! Cassandra implementation of `Bootstrapper`. +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use async_trait::async_trait; use cdrs_tokio::TryFromRow; use cdrs_tokio::frame::TryFromRow as TryFromRowTrait; @@ -460,7 +462,7 @@ impl CassandraBootstrapper { .held .request( "Read the accounts", - crate::cassandra_util::query_rows_quorum::( + crate::cassandra_util::query_rows::( &self.engine.session_arc(), &format!("SELECT account_id FROM {keyspace}.accounts"), cdrs_tokio::query_values!(), @@ -551,7 +553,11 @@ impl Bootstrapper for CassandraBootstrapper { let exists = self .engine .session() - .query_with_values(check_cql, cdrs_tokio::query_values!(user.as_str())) + .run( + Stmt::Read, + check_cql, + cdrs_tokio::query_values!(user.as_str()), + ) .await .ok() .and_then(|frame| frame.response_body().ok()) @@ -588,7 +594,11 @@ impl Bootstrapper for CassandraBootstrapper { ); self.engine .session() - .query(create_cql) + .run( + Stmt::Ddl, + create_cql, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ) .await .map_err(|e| OpError::Internal(format!("Create user: {e}")))?; @@ -607,7 +617,8 @@ impl Bootstrapper for CassandraBootstrapper { let already_granted = self .engine .session() - .query_with_values( + .run( + Stmt::Read, check_cql, cdrs_tokio::query_values!( self.config.app_user.as_str(), @@ -628,12 +639,20 @@ impl Bootstrapper for CassandraBootstrapper { "GRANT '{}' TO '{}'", self.config.app_user, self.config.admin_user ); - self.engine.session().query(grant_cql).await.map_err(|e| { - OpError::Internal(format!( - "Cannot grant {} to {}: {}", - self.config.app_user, self.config.admin_user, e - )) - })?; + self.engine + .session() + .run( + Stmt::Ddl, + grant_cql, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ) + .await + .map_err(|e| { + OpError::Internal(format!( + "Cannot grant {} to {}: {}", + self.config.app_user, self.config.admin_user, e + )) + })?; Ok(()) } @@ -819,16 +838,15 @@ impl Bootstrapper for CassandraBootstrapper { }) } - /// Read at `LOCAL_QUORUM`, since `init` finishes a catalog this answers - /// `false` for: at `ONE` a replica that missed the admin user's write - /// would read as empty. + /// Read at `LOCAL_QUORUM`: `init` finishes a catalog this answers `false` + /// for, so a replica that missed the admin user's write must not answer. async fn has_admin_user(&self) -> OpResult { let keyspace = self.engine.catalog_keyspace(); let rows = self .held .request( "Read the admin users", - crate::cassandra_util::query_rows_quorum::( + crate::cassandra_util::query_rows::( &self.engine.session_arc(), &format!("SELECT admin_name FROM {keyspace}.admin_users LIMIT 1"), cdrs_tokio::query_values!(), @@ -843,7 +861,16 @@ impl Bootstrapper for CassandraBootstrapper { let keyspace = self.engine.catalog_keyspace(); let cql = format!("SELECT table_name FROM {keyspace}.tables ORDER BY table_name"); - let rows = match self.engine.session().query(cql).await { + let rows = match self + .engine + .session() + .run( + Stmt::Read, + cql, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ) + .await + { Ok(frame) => frame .response_body() .ok() @@ -882,7 +909,11 @@ impl Bootstrapper for CassandraBootstrapper { let rows = self .engine .session() - .query(cql) + .run( + Stmt::SystemRead, + cql, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ) .await .map_err(|e| OpError::Internal(format!("List keyspaces: {e}")))? .response_body() diff --git a/crates/storage-cassandra/src/cassandra_util.rs b/crates/storage-cassandra/src/cassandra_util.rs index 2b846cc79..1cf51f9e2 100644 --- a/crates/storage-cassandra/src/cassandra_util.rs +++ b/crates/storage-cassandra/src/cassandra_util.rs @@ -17,24 +17,410 @@ pub type CassandraSession = Session< RoundRobinLoadBalancingStrategy, >; -/// Execute a lightweight transaction with explicit regional quorum and serial -/// consistency. TTL claims and lifecycle metadata use this rather than the -/// driver's default consistency. -pub async fn query_lwt( - session: &CassandraSession, - query: &str, - values: QueryValues, -) -> Result { +// ══════════════════════════════════════════════════════════════════════════════ +// Consistency policy (#770) +// ══════════════════════════════════════════════════════════════════════════════ + +/// The kind of a statement. [`params`] gives each kind its consistency level, +/// so this enum and [`params`] are the only place that sets the level of a +/// statement. [`batch`] does the same for batches. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Stmt { + /// A read: `LOCAL_QUORUM`. + Read, + /// A write without a condition: `LOCAL_QUORUM`. + Write, + /// A conditional write (LWT): Paxos at `LOCAL_SERIAL`, commit at + /// `LOCAL_QUORUM`. + Lwt, + /// A read at `LOCAL_SERIAL`, which sees every committed Paxos round. + SerialRead, + /// A read at `ALL`. Use it only to read rows that an earlier version of + /// ExtendDB wrote at `ONE`: the in-catalog backup payload that + /// `backup migrate-legacy` reads. A quorum read can miss a row that only + /// one replica holds. At `ALL`, every replica answers, so a replica that + /// is down fails the read instead of shortening it. The restore of an + /// in-catalog backup reads the same rows as [`Stmt::Read`]: a row that + /// read misses fails the restore with an item count mismatch. Remove + /// this kind when `backup migrate-legacy` is removed. + ReadAll, + /// `CREATE`, `ALTER`, `DROP`, `GRANT` or `REVOKE`: `ONE`. Cassandra does + /// not use the client's consistency level for these statements. + Ddl, + /// A read of a node-local system table (`system.local`, `system.peers`, + /// `system_schema`): `ONE`. + SystemRead, +} + +impl Stmt { + /// Whether the kind is a `SELECT`: only these kinds may be paged. + #[must_use] + pub fn is_read(self) -> bool { + matches!( + self, + Stmt::Read | Stmt::SerialRead | Stmt::ReadAll | Stmt::SystemRead + ) + } +} + +/// The consistency level of a statement of `kind`, and its serial level +/// when it has one. [`params`] and [`params_paged`] both read it, so it is +/// the one place that maps a kind to its levels. +fn levels( + kind: Stmt, +) -> ( + cdrs_tokio::consistency::Consistency, + Option, +) { use cdrs_tokio::consistency::Consistency; + + match kind { + Stmt::Read | Stmt::Write => (Consistency::LocalQuorum, None), + Stmt::Lwt => (Consistency::LocalQuorum, Some(Consistency::LocalSerial)), + Stmt::SerialRead => (Consistency::LocalSerial, None), + Stmt::ReadAll => (Consistency::All, None), + Stmt::Ddl | Stmt::SystemRead => (Consistency::One, None), + } +} + +/// The statement parameters for a statement of `kind` with `values`. +#[must_use] +pub fn params(kind: Stmt, values: QueryValues) -> cdrs_tokio::statement::StatementParams { + use cdrs_tokio::statement::StatementParamsBuilder; + + let (level, serial) = levels(kind); + let builder = StatementParamsBuilder::new() + .with_values(values) + .with_consistency(level); + match serial { + Some(serial) => builder.with_serial_consistency(serial), + None => builder, + } + .build() +} + +/// The statement parameters for one page of a read of `kind`. `page_size` +/// is the number of rows in a page. `paging_state` is `None` for the first +/// page, and for each next page it is the paging state that the page before +/// returned. The level is the one [`params`] gives `kind`. +#[must_use] +pub fn params_paged( + kind: Stmt, + values: QueryValues, + page_size: i32, + paging_state: Option, +) -> cdrs_tokio::statement::StatementParams { use cdrs_tokio::statement::StatementParamsBuilder; - let params = StatementParamsBuilder::new() + let (level, _) = levels(kind); + let mut builder = StatementParamsBuilder::new() + .with_values(values) + .with_consistency(level) + .with_page_size(page_size); + if let Some(state) = paging_state { + builder = builder.with_paging_state(state); + } + builder.build() +} + +/// Run one statement at the consistency level of its kind. Every statement +/// outside this module and `migrations/` goes through [`PolicySession::run`] +/// or a helper that calls it. +pub trait PolicySession { + /// Run `query` with `values` as a statement of `kind`, with the + /// parameters [`params`] gives that kind. In a debug build, a statement + /// whose CQL does not match `kind` ([`shape_error`]) panics. + /// + /// # Errors + /// Returns the driver's error if the statement fails. + fn run>( + &self, + kind: Stmt, + query: Q, + values: QueryValues, + ) -> impl std::future::Future< + Output = Result, + > + Send; + + /// Run one page of a read: like [`PolicySession::run`], with `page_size` + /// rows in the page, starting at `paging_state` (`None` for the first + /// page). In a debug build, a `kind` that is not a read panics. The + /// next page starts at the paging state in the rows metadata of the + /// response. + /// + /// # Errors + /// Returns the driver's error if the statement fails. + fn run_paged>( + &self, + kind: Stmt, + query: Q, + values: QueryValues, + page_size: i32, + paging_state: Option, + ) -> impl std::future::Future< + Output = Result, + > + Send; + + /// Send `batch`. In a debug build, a batch whose levels are not the ones + /// [`batch`] sets ([`batch_level_error`]) panics. + /// + /// # Errors + /// Returns the driver's error if the batch fails. + fn run_batch( + &self, + batch: cdrs_tokio::query::QueryBatch, + ) -> impl std::future::Future< + Output = Result, + > + Send; +} + +impl PolicySession for CassandraSession { + fn run_batch( + &self, + batch: cdrs_tokio::query::QueryBatch, + ) -> impl std::future::Future< + Output = Result, + > + Send { + debug_assert!( + batch_level_error(&batch).is_none(), + "batch: {}", + batch_level_error(&batch).unwrap_or_default() + ); + self.batch(batch) + } + + fn run>( + &self, + kind: Stmt, + query: Q, + values: QueryValues, + ) -> impl std::future::Future< + Output = Result, + > + Send { + let query = query.as_ref().to_owned(); + debug_assert!( + shape_error(kind, &query).is_none(), + // The CQL text is not in the message: it can hold a password + // (CREATE ROLE) or account names. + "{kind:?} statement: {}", + shape_error(kind, &query).unwrap_or_default() + ); + async move { self.query_with_params(query, params(kind, values)).await } + } + + fn run_paged>( + &self, + kind: Stmt, + query: Q, + values: QueryValues, + page_size: i32, + paging_state: Option, + ) -> impl std::future::Future< + Output = Result, + > + Send { + let query = query.as_ref().to_owned(); + debug_assert!( + kind.is_read() && shape_error(kind, &query).is_none(), + "{kind:?} paged statement: {}", + if kind.is_read() { + shape_error(kind, &query).unwrap_or_default() + } else { + "a paged statement must be a read" + } + ); + async move { + self.query_with_params(query, params_paged(kind, values, page_size, paging_state)) + .await + } + } +} + +/// What is wrong with `query` as a statement of `kind`, or `None` when its +/// CQL matches `kind`: +/// +/// - [`Stmt::Read`], [`Stmt::SerialRead`] and [`Stmt::ReadAll`]: a `SELECT` that does not read +/// `system.*` or `system_schema.*`. +/// - [`Stmt::SystemRead`]: a `SELECT` from `system.*` or `system_schema.*`. +/// - [`Stmt::Write`]: an `INSERT`, `UPDATE`, `DELETE` or `BEGIN BATCH` with +/// no `IF` condition. +/// - [`Stmt::Lwt`]: an `INSERT`, `UPDATE` or `DELETE` with an `IF` condition. +/// - [`Stmt::Ddl`]: a `CREATE`, `ALTER`, `DROP`, `GRANT` or `REVOKE`. +/// +/// Quoted literals and identifiers are removed before the check, so an `IF` +/// inside a string does not count. +#[must_use] +pub fn shape_error(kind: Stmt, query: &str) -> Option<&'static str> { + let words = cql_words(query); + let first = words.first().map_or("", String::as_str); + let conditional = words.iter().any(|word| word == "IF"); + // Each node keeps its own copy of these keyspaces (LocalStrategy). + let system = words + .iter() + .skip_while(|word| *word != "FROM") + .nth(1) + .is_some_and(|table| table.starts_with("SYSTEM.") || table.starts_with("SYSTEM_SCHEMA.")); + match kind { + Stmt::Read | Stmt::SerialRead | Stmt::ReadAll => { + if first != "SELECT" { + Some("a read must be a SELECT") + } else if system { + Some("a read of system.* or system_schema.* must use Stmt::SystemRead") + } else { + None + } + } + Stmt::SystemRead => { + if first != "SELECT" { + Some("a system read must be a SELECT") + } else if system { + None + } else { + Some("a system read must read system.* or system_schema.*") + } + } + Stmt::Write => { + if !matches!(first, "INSERT" | "UPDATE" | "DELETE" | "BEGIN") { + Some("a write must be an INSERT, UPDATE, DELETE or BEGIN BATCH") + } else if conditional { + Some("a write with an IF condition must use Stmt::Lwt") + } else { + None + } + } + Stmt::Lwt => { + if !matches!(first, "INSERT" | "UPDATE" | "DELETE") { + Some("an LWT must be an INSERT, UPDATE or DELETE") + } else if conditional { + None + } else { + Some("an LWT must have an IF condition") + } + } + Stmt::Ddl => (!matches!(first, "CREATE" | "ALTER" | "DROP" | "GRANT" | "REVOKE")) + .then_some("DDL must be a CREATE, ALTER, DROP, GRANT or REVOKE"), + } +} + +/// What is wrong with the levels of `batch`, or `None` when they are the +/// ones [`batch`] sets: `LOCAL_QUORUM`, with `LOCAL_SERIAL` for a +/// conditional batch. +#[must_use] +pub fn batch_level_error(batch: &cdrs_tokio::query::QueryBatch) -> Option<&'static str> { + use cdrs_tokio::consistency::Consistency; + + if batch.request.consistency != Consistency::LocalQuorum { + Some("a batch must run at LOCAL_QUORUM; build it with cassandra_util::batch()") + } else if batch.request.serial_consistency != Some(Consistency::LocalSerial) { + Some("a batch must have LOCAL_SERIAL; build it with cassandra_util::batch()") + } else { + None + } +} + +/// The words of `query` in upper case, with quoted literals and quoted +/// identifiers removed. A word holds letters, digits, `_` and `.`. +fn cql_words(query: &str) -> Vec { + let mut words = Vec::new(); + let mut word = String::new(); + let mut quote: Option = None; + for c in query.chars() { + if let Some(open) = quote { + if c == open { + quote = None; + } + continue; + } + if c == '\'' || c == '"' { + quote = Some(c); + } else if c.is_ascii_alphanumeric() || c == '_' || c == '.' { + word.push(c.to_ascii_uppercase()); + continue; + } + if !word.is_empty() { + words.push(std::mem::take(&mut word)); + } + } + if !word.is_empty() { + words.push(word); + } + words +} + +/// A batch builder at `LOCAL_QUORUM`, with `LOCAL_SERIAL` for a conditional +/// batch. Use it in place of `BatchQueryBuilder::new()`. +#[must_use] +pub fn batch() -> cdrs_tokio::query::BatchQueryBuilder { + use cdrs_tokio::consistency::Consistency; + + cdrs_tokio::query::BatchQueryBuilder::new() .with_consistency(Consistency::LocalQuorum) .with_serial_consistency(Consistency::LocalSerial) - .with_values(values) - .build(); +} + +/// Run a `CREATE`, `ALTER` or `DROP` statement. +/// +/// # Errors +/// Returns an error if the Cassandra statement fails. +pub async fn ddl( + session: &Arc, + query: &str, + context: &str, +) -> Result<(), E> { session - .query_with_params(query, params) + .run(Stmt::Ddl, query, QueryValues::SimpleValues(vec![])) + .await + .map_err(|e| { + tracing::error!("{context} DDL failed: {e}"); + E::db_error(format!("{context}: {e}")) + })?; + Ok(()) +} + +/// Read rows from a node-local system table (`system.local`, +/// `system.peers`, `system_schema`). +/// +/// # Errors +/// Returns an error if the Cassandra query fails or the response cannot be parsed. +pub async fn system_read( + session: &Arc, + query: &str, + values: QueryValues, + context: &str, +) -> Result, E> { + rows_at(session, query, Stmt::SystemRead, values, context).await +} + +/// Run `query` with `values` as a statement of `kind` and return its rows. +async fn rows_at( + session: &Arc, + query: &str, + kind: Stmt, + values: QueryValues, + context: &str, +) -> Result, E> { + let result = session.run(kind, query, values).await.map_err(|e| { + tracing::error!("{context} query failed: {e}"); + E::db_error(format!("{context}: {e}")) + })?; + + let body = result.response_body().map_err(|e| { + tracing::error!("{context} response_body failed: {e}"); + E::db_error(format!("{context} response_body: {e}")) + })?; + + Ok(body.into_rows().unwrap_or_default()) +} + +/// Execute a lightweight transaction: Paxos at `LOCAL_SERIAL`, commit at +/// `LOCAL_QUORUM`. Returns the response, for callers that read more than +/// the `[applied]` flag. +pub async fn query_lwt( + session: &CassandraSession, + query: &str, + values: QueryValues, +) -> Result { + session + .run(Stmt::Lwt, query, values) .await .map_err(|error| { extenddb_storage::error::StorageError::Internal(format!("LWT query failed: {error}")) @@ -85,7 +471,7 @@ pub fn is_fk_violation(_err: &cdrs_tokio::error::Error) -> bool { // Phase 1: Core Query Helpers // ══════════════════════════════════════════════════════════════════════════════ -/// Execute a query and return all rows with standardized error handling. +/// Execute a query at `LOCAL_QUORUM` and return all rows. /// /// # Errors /// Returns an error if the Cassandra query fails or the response cannot be parsed. @@ -95,56 +481,7 @@ pub async fn query_rows( values: QueryValues, context: &str, ) -> Result, E> { - let result = session - .query_with_values(query, values) - .await - .map_err(|e| { - tracing::error!("{context} query failed: {e}"); - E::db_error(format!("{context}: {e}")) - })?; - - let body = result.response_body().map_err(|e| { - tracing::error!("{context} response_body failed: {e}"); - E::db_error(format!("{context} response_body: {e}")) - })?; - - Ok(body.into_rows().unwrap_or_default()) -} - -/// Execute a query at `LOCAL_QUORUM` and return all rows. -/// -/// [`query_rows`] uses the driver's default consistency, which is `ONE`. Use -/// this instead wherever an *empty* result is treated as authoritative and acted -/// on destructively: at `ONE` a replica that has not yet received a write reads -/// as empty, and a decision made on that read cannot be undone by a timestamp -/// guard, because the write it missed is older than the guard. -pub async fn query_rows_quorum( - session: &Arc, - query: &str, - values: QueryValues, - context: &str, -) -> Result, E> { - use cdrs_tokio::consistency::Consistency; - use cdrs_tokio::statement::StatementParamsBuilder; - - let params = StatementParamsBuilder::new() - .with_consistency(Consistency::LocalQuorum) - .with_values(values) - .build(); - let result = session - .query_with_params(query, params) - .await - .map_err(|e| { - tracing::error!("{context} quorum query failed: {e}"); - E::db_error(format!("{context}: {e}")) - })?; - - let body = result.response_body().map_err(|e| { - tracing::error!("{context} response_body failed: {e}"); - E::db_error(format!("{context} response_body: {e}")) - })?; - - Ok(body.into_rows().unwrap_or_default()) + rows_at(session, query, Stmt::Read, values, context).await } /// Execute a query at `LOCAL_SERIAL` and return all rows: the read sees @@ -157,27 +494,7 @@ pub async fn query_rows_serial( values: QueryValues, context: &str, ) -> Result, E> { - use cdrs_tokio::consistency::Consistency; - use cdrs_tokio::statement::StatementParamsBuilder; - - let params = StatementParamsBuilder::new() - .with_consistency(Consistency::LocalSerial) - .with_values(values) - .build(); - let result = session - .query_with_params(query, params) - .await - .map_err(|e| { - tracing::error!("{context} serial query failed: {e}"); - E::db_error(format!("{context}: {e}")) - })?; - - let body = result.response_body().map_err(|e| { - tracing::error!("{context} response_body failed: {e}"); - E::db_error(format!("{context} response_body: {e}")) - })?; - - Ok(body.into_rows().unwrap_or_default()) + rows_at(session, query, Stmt::SerialRead, values, context).await } /// Execute a query and return the first row, if any. @@ -196,7 +513,7 @@ pub async fn query_optional( Ok(rows.drain(..).next()) } -/// Execute a non-query statement (INSERT/UPDATE/DELETE). +/// Execute a non-query statement (INSERT/UPDATE/DELETE) at `LOCAL_QUORUM`. /// /// # Errors /// Returns an error if the Cassandra statement fails. @@ -206,44 +523,11 @@ pub async fn execute( values: QueryValues, context: &str, ) -> Result<(), E> { - session - .query_with_values(query, values) - .await - .map_err(|e| { - tracing::error!("{context} execute failed: {e}"); - E::db_error("Database error".to_owned()) - })?; - - Ok(()) -} - -/// Execute a non-query statement at `LOCAL_QUORUM`. -/// -/// Use this for writes that are prerequisites for a later quorum operation or -/// whose loss would make an absence decision unsafe. -/// -/// # Errors -/// Returns an error if Cassandra does not acknowledge the statement at quorum. -pub async fn execute_quorum( - session: &Arc, - query: &str, - values: QueryValues, - context: &str, -) -> Result<(), E> { - use cdrs_tokio::consistency::Consistency; - use cdrs_tokio::statement::StatementParamsBuilder; + session.run(Stmt::Write, query, values).await.map_err(|e| { + tracing::error!("{context} execute failed: {e}"); + E::db_error("Database error".to_owned()) + })?; - let params = StatementParamsBuilder::new() - .with_consistency(Consistency::LocalQuorum) - .with_values(values) - .build(); - session - .query_with_params(query, params) - .await - .map_err(|error| { - tracing::error!("{context} quorum execute failed: {error}"); - E::db_error(format!("{context}: {error}")) - })?; Ok(()) } @@ -376,6 +660,8 @@ pub fn lwt_applied( }) } +/// Execute a lightweight transaction (Paxos at `LOCAL_SERIAL`, commit at +/// `LOCAL_QUORUM`) and return whether it applied. /// /// Parses the `[applied]` column from the Cassandra LWT response. /// Use for `INSERT ... IF NOT EXISTS` and `UPDATE ... IF ...` statements. @@ -388,46 +674,10 @@ pub async fn apply_lwt( values: QueryValues, context: &str, ) -> Result { - let result = session - .query_with_values(query, values) - .await - .map_err(|e| { - tracing::error!("{context} lwt failed: {e}"); - E::db_error("Database error".to_owned()) - })?; - lwt_applied_flag(&result, context) -} - -/// [`apply_lwt`] with the commit phase at `LOCAL_QUORUM`. -/// -/// [`apply_lwt`] commits at the driver's default consistency, `ONE`, so a -/// `LOCAL_QUORUM` read issued after it returns can still miss the write. Use -/// this where a later quorum read must see the change. The serial phase keeps -/// the default, `SERIAL`, which every other LWT on these rows also uses. -/// -/// # Errors -/// Returns an error if Cassandra does not acknowledge the statement at quorum -/// or the response cannot be parsed. -pub async fn apply_lwt_quorum( - session: &Arc, - query: &str, - values: QueryValues, - context: &str, -) -> Result { - use cdrs_tokio::consistency::Consistency; - use cdrs_tokio::statement::StatementParamsBuilder; - - let params = StatementParamsBuilder::new() - .with_consistency(Consistency::LocalQuorum) - .with_values(values) - .build(); - let result = session - .query_with_params(query, params) - .await - .map_err(|e| { - tracing::error!("{context} quorum lwt failed: {e}"); - E::db_error("Database error".to_owned()) - })?; + let result = session.run(Stmt::Lwt, query, values).await.map_err(|e| { + tracing::error!("{context} lwt failed: {e}"); + E::db_error("Database error".to_owned()) + })?; lwt_applied_flag(&result, context) } @@ -449,3 +699,278 @@ fn lwt_applied_flag( .and_then(|row| row.get_r_by_name("[applied]").ok()) .unwrap_or(false)) } + +#[cfg(test)] +mod tests { + use super::{Stmt, batch, batch_level_error, params, params_paged, shape_error}; + + fn one_insert(builder: cdrs_tokio::query::BatchQueryBuilder) -> cdrs_tokio::query::QueryBatch { + builder + .add_query( + "INSERT INTO ks.t (id) VALUES (1)", + QueryValues::SimpleValues(vec![]), + ) + .build() + .expect("a batch") + } + + #[test] + fn only_a_batch_from_batch_has_the_policy_levels() { + assert_eq!(batch_level_error(&one_insert(batch())), None); + assert!( + batch_level_error(&one_insert(cdrs_tokio::query::BatchQueryBuilder::new())).is_some() + ); + assert!(batch_level_error(&one_insert(Default::default())).is_some()); + assert!( + batch_level_error(&one_insert( + cdrs_tokio::query::BatchQueryBuilder::new() + .with_consistency(Consistency::LocalQuorum) + )) + .is_some(), + "LOCAL_QUORUM without LOCAL_SERIAL" + ); + } + + #[test] + fn a_read_must_be_a_select() { + assert_eq!( + shape_error(Stmt::Read, "SELECT a FROM ks.t WHERE pk = ?"), + None + ); + assert_eq!(shape_error(Stmt::SerialRead, "select a from ks.t"), None); + assert_eq!( + shape_error( + Stmt::Read, + "SELECT role FROM system_auth.roles WHERE role = ?" + ), + None, + "system_auth is replicated, so it is not a SystemRead" + ); + assert!(shape_error(Stmt::Read, "SELECT token(?) AS t FROM system.local").is_some()); + assert!( + shape_error( + Stmt::SerialRead, + "SELECT table_name FROM system_schema.tables" + ) + .is_some() + ); + assert!(shape_error(Stmt::Read, "UPDATE ks.t SET a = 1 WHERE pk = ?").is_some()); + assert!(shape_error(Stmt::SerialRead, "DELETE FROM ks.t WHERE pk = ?").is_some()); + } + + #[test] + fn a_system_read_must_read_a_system_table() { + assert_eq!( + shape_error( + Stmt::SystemRead, + "SELECT keyspace_name FROM system_schema.keyspaces" + ), + None + ); + assert_eq!( + shape_error(Stmt::SystemRead, "SELECT data_center FROM system.local"), + None + ); + assert!(shape_error(Stmt::SystemRead, "SELECT role FROM system_auth.roles").is_some()); + assert!(shape_error(Stmt::SystemRead, "SELECT a FROM ks.t").is_some()); + assert!(shape_error(Stmt::SystemRead, "DELETE FROM system.local").is_some()); + } + + #[test] + fn a_write_has_no_condition() { + assert_eq!( + shape_error(Stmt::Write, "INSERT INTO ks.t (a) VALUES (?)"), + None + ); + assert_eq!( + shape_error(Stmt::Write, "UPDATE ks.t SET a = ? WHERE pk = ?"), + None + ); + assert_eq!( + shape_error(Stmt::Write, "DELETE FROM ks.t WHERE pk = ?"), + None + ); + assert_eq!( + shape_error( + Stmt::Write, + "BEGIN BATCH\nINSERT INTO ks.t (a) VALUES (1)\nAPPLY BATCH" + ), + None + ); + assert!( + shape_error(Stmt::Write, "INSERT INTO ks.t (a) VALUES (?) IF NOT EXISTS").is_some() + ); + assert!(shape_error(Stmt::Write, "UPDATE ks.t SET a = ? WHERE pk = ? IF a = ?").is_some()); + assert!(shape_error(Stmt::Write, "DELETE FROM ks.t WHERE pk = ? IF EXISTS").is_some()); + assert!(shape_error(Stmt::Write, "SELECT a FROM ks.t").is_some()); + } + + #[test] + fn an_lwt_has_a_condition() { + assert_eq!( + shape_error(Stmt::Lwt, "INSERT INTO ks.t (a) VALUES (?) IF NOT EXISTS"), + None + ); + assert_eq!( + shape_error(Stmt::Lwt, "UPDATE ks.t SET a = ? WHERE pk = ? IF a = null"), + None + ); + assert!(shape_error(Stmt::Lwt, "UPDATE ks.t SET a = ? WHERE pk = ?").is_some()); + assert!(shape_error(Stmt::Lwt, "SELECT a FROM ks.t").is_some()); + } + + #[test] + fn ddl_is_create_alter_drop_or_a_role_statement() { + for cql in [ + "CREATE TABLE IF NOT EXISTS ks.t (a int PRIMARY KEY)", + "ALTER TABLE ks.t ADD b int", + "DROP KEYSPACE IF EXISTS ks", + "CREATE ROLE IF NOT EXISTS 'app' WITH PASSWORD = 'x' AND LOGIN = true", + "GRANT 'app' TO 'admin'", + "REVOKE 'app' FROM 'admin'", + ] { + assert_eq!(shape_error(Stmt::Ddl, cql), None, "{cql}"); + } + assert!(shape_error(Stmt::Ddl, "INSERT INTO ks.t (a) VALUES (1)").is_some()); + } + + #[test] + fn a_quoted_if_is_not_a_condition() { + assert_eq!( + shape_error(Stmt::Write, "INSERT INTO ks.t (a) VALUES ('IF x = 1')"), + None + ); + assert_eq!( + shape_error( + Stmt::Write, + "UPDATE ks.t SET \"IF\" = 'it''s IF' WHERE pk = ?" + ), + None + ); + assert!(shape_error(Stmt::Lwt, "INSERT INTO ks.t (a) VALUES ('IF')").is_some()); + } + use cdrs_tokio::consistency::Consistency; + use cdrs_tokio::query::QueryValues; + + fn levels(kind: Stmt) -> (Consistency, Option) { + let built = params(kind, QueryValues::SimpleValues(vec![])); + ( + built.query_params.consistency, + built.query_params.serial_consistency, + ) + } + + #[test] + fn reads_and_writes_run_at_local_quorum() { + assert_eq!(levels(Stmt::Read), (Consistency::LocalQuorum, None)); + assert_eq!(levels(Stmt::Write), (Consistency::LocalQuorum, None)); + } + + #[test] + fn an_lwt_runs_paxos_at_local_serial_and_commits_at_local_quorum() { + assert_eq!( + levels(Stmt::Lwt), + (Consistency::LocalQuorum, Some(Consistency::LocalSerial)) + ); + } + + #[test] + fn a_serial_read_runs_at_local_serial() { + assert_eq!(levels(Stmt::SerialRead), (Consistency::LocalSerial, None)); + } + + #[test] + fn a_read_all_runs_at_all() { + assert_eq!(levels(Stmt::ReadAll), (Consistency::All, None)); + } + + #[test] + fn a_read_all_must_be_a_select_of_a_replicated_table() { + assert_eq!( + shape_error(Stmt::ReadAll, "SELECT a FROM ks.t WHERE pk = ?"), + None + ); + assert!(shape_error(Stmt::ReadAll, "SELECT a FROM system.local").is_some()); + assert!(shape_error(Stmt::ReadAll, "DELETE FROM ks.t WHERE pk = ?").is_some()); + } + + fn paged_levels(kind: Stmt) -> (Consistency, Option) { + let built = params_paged(kind, QueryValues::SimpleValues(vec![]), 10, None); + ( + built.query_params.consistency, + built.query_params.serial_consistency, + ) + } + + #[test] + fn a_page_of_a_read_has_the_level_of_its_kind() { + for kind in [ + Stmt::Read, + Stmt::SerialRead, + Stmt::ReadAll, + Stmt::SystemRead, + ] { + assert_eq!(paged_levels(kind), levels(kind), "{kind:?}"); + } + } + + #[test] + fn a_page_has_its_size_and_its_paging_state() { + let first = params_paged(Stmt::Read, QueryValues::SimpleValues(vec![]), 25, None); + assert_eq!(first.query_params.page_size, Some(25)); + assert_eq!(first.query_params.paging_state, None); + let state = cdrs_tokio::types::CBytes::new(vec![1, 2, 3]); + let next = params_paged( + Stmt::Read, + QueryValues::SimpleValues(vec![]), + 25, + Some(state.clone()), + ); + assert_eq!(next.query_params.page_size, Some(25)); + assert_eq!(next.query_params.paging_state, Some(state)); + } + + #[test] + fn only_a_read_can_be_paged() { + for kind in [ + Stmt::Read, + Stmt::SerialRead, + Stmt::ReadAll, + Stmt::SystemRead, + ] { + assert!(kind.is_read(), "{kind:?}"); + } + for kind in [Stmt::Write, Stmt::Lwt, Stmt::Ddl] { + assert!(!kind.is_read(), "{kind:?}"); + } + } + + #[test] + fn ddl_and_system_reads_run_at_one() { + assert_eq!(levels(Stmt::Ddl), (Consistency::One, None)); + assert_eq!(levels(Stmt::SystemRead), (Consistency::One, None)); + } + + #[test] + fn params_keep_the_values() { + let values = QueryValues::SimpleValues(vec![1_i32.into()]); + let built = params(Stmt::Write, values.clone()); + assert_eq!(built.query_params.values, Some(values)); + } + + #[test] + fn a_batch_runs_at_local_quorum_and_local_serial() { + let built = batch() + .add_query( + "INSERT INTO ks.t (id) VALUES (1)", + QueryValues::SimpleValues(vec![]), + ) + .build() + .expect("a batch"); + assert_eq!(built.request.consistency, Consistency::LocalQuorum); + assert_eq!( + built.request.serial_consistency, + Some(Consistency::LocalSerial) + ); + } +} diff --git a/crates/storage-cassandra/src/catalog_store.rs b/crates/storage-cassandra/src/catalog_store.rs index 15ffdf8db..542e6a26d 100644 --- a/crates/storage-cassandra/src/catalog_store.rs +++ b/crates/storage-cassandra/src/catalog_store.rs @@ -7,6 +7,8 @@ //! `CassandraCatalogStore` wraps a Cassandra session connected to the catalog //! keyspace and implements the operational traits defined in `extenddb_storage`. +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use std::sync::Arc; use cdrs_tokio::cluster::TcpConnectionManager; @@ -198,7 +200,14 @@ impl CassandraCatalogStore { let cql = format!( "CREATE KEYSPACE IF NOT EXISTS {keyspace_name} WITH replication = {replication}" ); - self.session.query(cql).await.map_err(|e| failed(&e))?; + self.session + .run( + Stmt::Ddl, + cql, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ) + .await + .map_err(|e| failed(&e))?; crate::migrations::migrate_account( self.session.clone(), &self.keyspace_prefix, @@ -215,10 +224,17 @@ impl CassandraCatalogStore { let keyspace_name = self.account_keyspace(account_id); let cql = format!("DROP KEYSPACE IF EXISTS {keyspace_name}"); - self.session.query(cql).await.map_err(|e| { - tracing::error!("Failed to drop account keyspace {}: {}", keyspace_name, e); - OpError::Internal("Failed to drop account storage".to_owned()) - })?; + self.session + .run( + Stmt::Ddl, + cql, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ) + .await + .map_err(|e| { + tracing::error!("Failed to drop account keyspace {}: {}", keyspace_name, e); + OpError::Internal("Failed to drop account storage".to_owned()) + })?; Ok(()) } @@ -251,7 +267,7 @@ impl CassandraCatalogStore { "SELECT account_id FROM {}.accounts WHERE account_id = ?", self.catalog_keyspace() ); - let rows = crate::cassandra_util::query_rows_quorum( + let rows = crate::cassandra_util::query_rows( &self.session, &query, cdrs_tokio::query_values!(account_id), @@ -378,9 +394,16 @@ impl extenddb_storage::diagnostics::DiagnosticsStore for CassandraCatalogStore { let catalog_keyspace = self.catalog_keyspace(); Box::pin(async move { let query = format!("SELECT COUNT(*) FROM {catalog_keyspace}.tables"); - let result = session.query(&query).await.map_err(|e| { - extenddb_storage::diagnostics::DiagError::QueryFailed(e.to_string()) - })?; + let result = session + .run( + Stmt::Read, + &query, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ) + .await + .map_err(|e| { + extenddb_storage::diagnostics::DiagError::QueryFailed(e.to_string()) + })?; let body = result.response_body().map_err(|e| { extenddb_storage::diagnostics::DiagError::QueryFailed(e.to_string()) @@ -404,9 +427,16 @@ impl extenddb_storage::diagnostics::DiagnosticsStore for CassandraCatalogStore { let catalog_keyspace = self.catalog_keyspace(); Box::pin(async move { let query = format!("SELECT COUNT(*) FROM {catalog_keyspace}.indexes"); - let result = session.query(&query).await.map_err(|e| { - extenddb_storage::diagnostics::DiagError::QueryFailed(e.to_string()) - })?; + let result = session + .run( + Stmt::Read, + &query, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ) + .await + .map_err(|e| { + extenddb_storage::diagnostics::DiagError::QueryFailed(e.to_string()) + })?; let body = result.response_body().map_err(|e| { extenddb_storage::diagnostics::DiagError::QueryFailed(e.to_string()) @@ -435,11 +465,18 @@ impl extenddb_storage::diagnostics::DiagnosticsStore for CassandraCatalogStore { // For Cassandra, we test connection to account keyspaces // Get a sample account keyspace name from accounts table let query = format!("SELECT account_id FROM {catalog_keyspace}.accounts LIMIT 1"); - let result = session.query(&query).await.map_err(|e| { - extenddb_storage::diagnostics::DiagError::QueryFailed(format!( - "Failed to query accounts: {e}" - )) - })?; + let result = session + .run( + Stmt::Read, + &query, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ) + .await + .map_err(|e| { + extenddb_storage::diagnostics::DiagError::QueryFailed(format!( + "Failed to query accounts: {e}" + )) + })?; let body = result.response_body().map_err(|e| { extenddb_storage::diagnostics::DiagError::QueryFailed(e.to_string()) @@ -456,11 +493,18 @@ impl extenddb_storage::diagnostics::DiagnosticsStore for CassandraCatalogStore { let account_keyspace = format!("{keyspace_prefix}_account_{account_id}"); let test_query = format!("SELECT COUNT(*) FROM {account_keyspace}.schema_history"); - session.query(&test_query).await.map_err(|e| { - extenddb_storage::diagnostics::DiagError::ConnectionFailed(format!( - "Failed to query account keyspace {account_keyspace}: {e}" - )) - })?; + session + .run( + Stmt::Read, + &test_query, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ) + .await + .map_err(|e| { + extenddb_storage::diagnostics::DiagError::ConnectionFailed(format!( + "Failed to query account keyspace {account_keyspace}: {e}" + )) + })?; return Ok(account_keyspace); } @@ -495,7 +539,8 @@ impl RateLimitStore for CassandraCatalogStore { AND source_ip = ? ALLOW FILTERING" ); let result = session - .query_with_values( + .run( + Stmt::Read, &query, cdrs_tokio::query_values!(principal.as_str(), cutoff_ms, source_ip.as_str()), ) @@ -534,7 +579,8 @@ impl RateLimitStore for CassandraCatalogStore { ALLOW FILTERING" ); let result = session - .query_with_values( + .run( + Stmt::Read, &query, cdrs_tokio::query_values!(source_ip.as_str(), cutoff_ms), ) @@ -566,7 +612,8 @@ impl RateLimitStore for CassandraCatalogStore { (principal, attempted_at, success, source_ip) VALUES (?, ?, false, ?)" ); if let Err(e) = session - .query_with_values( + .run( + Stmt::Write, &query, cdrs_tokio::query_values!(principal.as_str(), now_ms, source_ip.as_deref()), ) @@ -590,7 +637,11 @@ impl RateLimitStore for CassandraCatalogStore { let select = format!("SELECT DISTINCT principal FROM {catalog_keyspace}.login_attempts"); let principals = match session - .query(&select) + .run( + Stmt::Read, + &select, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ) .await .and_then(|r| r.response_body()) .map(|b| b.into_rows().unwrap_or_default()) @@ -610,7 +661,8 @@ impl RateLimitStore for CassandraCatalogStore { continue; }; if let Err(e) = session - .query_with_values( + .run( + Stmt::Write, &delete, cdrs_tokio::query_values!(principal.as_str(), cutoff_ms), ) @@ -643,7 +695,8 @@ impl MetricsStore for CassandraCatalogStore { #[allow(clippy::cast_possible_truncation)] let bucket_ms = (row.bucket.unix_timestamp_nanos() / 1_000_000) as i64; if let Err(e) = session - .query_with_values( + .run( + Stmt::Write, &query, cdrs_tokio::query_values!( bucket_ms, @@ -693,7 +746,11 @@ impl MetricsStore for CassandraCatalogStore { WHERE bucket >= ? AND bucket <= ? ALLOW FILTERING" ); let result = session - .query_with_values(&query, cdrs_tokio::query_values!(start_ms, end_ms)) + .run( + Stmt::Read, + &query, + cdrs_tokio::query_values!(start_ms, end_ms), + ) .await .map_err(|e| { tracing::warn!("query_metrics: {e}"); diff --git a/crates/storage-cassandra/src/create_table.rs b/crates/storage-cassandra/src/create_table.rs index 5a19975ce..e71c8d84e 100644 --- a/crates/storage-cassandra/src/create_table.rs +++ b/crates/storage-cassandra/src/create_table.rs @@ -3,6 +3,8 @@ //! `create_table` implementation for `CassandraEngine`. +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use cdrs_tokio::types::value::Value; use extenddb_core::types::{ BillingMode, BillingModeSummary, CreateTableInput, GsiDescription, LsiDescription, @@ -195,7 +197,8 @@ impl CassandraEngine { let delay_query = format!("SELECT value FROM {catalog_keyspace}.settings WHERE key = ?"); let delay_seconds: f64 = self .session - .query_with_values( + .run( + Stmt::Read, &delay_query, cdrs_tokio::query_values!("control_plane_delay_seconds"), ) @@ -331,7 +334,8 @@ impl CassandraEngine { let result = self .session - .query_with_values( + .run( + Stmt::Lwt, &insert_table_cql, cdrs_tokio::query::QueryValues::SimpleValues(values), ) @@ -444,7 +448,8 @@ impl CassandraEngine { ); self.session - .query_with_values( + .run( + Stmt::Write, &insert_index_cql, cdrs_tokio::query::QueryValues::SimpleValues(index_values), ) @@ -475,7 +480,8 @@ impl CassandraEngine { ); self.session - .query_with_values( + .run( + Stmt::Write, &insert_index_cql, cdrs_tokio::query::QueryValues::SimpleValues(vec![ Value::from(table_id.as_str()), @@ -504,7 +510,8 @@ impl CassandraEngine { ); self.session - .query_with_values( + .run( + Stmt::Write, &insert_tag_cql, cdrs_tokio::query_values!( table_arn.as_str(), diff --git a/crates/storage-cassandra/src/credential_store.rs b/crates/storage-cassandra/src/credential_store.rs index 4a10eb7a7..5468f844d 100644 --- a/crates/storage-cassandra/src/credential_store.rs +++ b/crates/storage-cassandra/src/credential_store.rs @@ -7,6 +7,8 @@ //! session credentials from Cassandra, decrypting secrets with AES-256-GCM //! through `extenddb_storage::secret_cipher`, with the access key id as the AAD. +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use std::sync::Arc; use async_trait::async_trait; @@ -103,7 +105,7 @@ impl CassandraCredentialStore { let result = self .session - .query_with_values(&query, cdrs_tokio::query_values!(access_key_id)) + .run(Stmt::Read, &query, cdrs_tokio::query_values!(access_key_id)) .await .map_err(|e| { tracing::error!("Credential lookup failed for access key {access_key_id}: {e}"); @@ -181,7 +183,7 @@ impl CassandraCredentialStore { let result = self .session - .query_with_values(&query, cdrs_tokio::query_values!(access_key_id)) + .run(Stmt::Read, &query, cdrs_tokio::query_values!(access_key_id)) .await .map_err(|e| { tracing::error!( diff --git a/crates/storage-cassandra/src/data/ddl.rs b/crates/storage-cassandra/src/data/ddl.rs index 74cc6fb7e..de2d9bf33 100644 --- a/crates/storage-cassandra/src/data/ddl.rs +++ b/crates/storage-cassandra/src/data/ddl.rs @@ -3,6 +3,7 @@ //! DDL helpers for creating and dropping per-DynamoDB-table data tables in Cassandra. +use crate::cassandra_util::PolicySession as _; use cdrs_tokio::types::IntoRustByName; use extenddb_core::types::{ AttributeDefinition, IndexInfo, IndexType, KeySchemaElement, ScalarAttributeType, @@ -12,6 +13,7 @@ use extenddb_storage::error::StorageError; use extenddb_storage::util::{sk_column, sk_column_n}; use crate::CassandraEngine; +use crate::cassandra_util::batch; /// CQL table name for a DynamoDB table in an account keyspace. pub(crate) fn data_table_name(table_id: &str) -> String { @@ -55,27 +57,6 @@ impl CassandraEngine { &self, account_id: &str, table_name: &str, - ) -> Result { - self.fetch_table_key_info_with_consistency(account_id, table_name, false) - .await - } - - /// Fetch table identity at `LOCAL_QUORUM` when absence or name reuse would - /// otherwise allow a durable repair obligation to be discarded. - pub(crate) async fn fetch_table_key_info_quorum( - &self, - account_id: &str, - table_name: &str, - ) -> Result { - self.fetch_table_key_info_with_consistency(account_id, table_name, true) - .await - } - - async fn fetch_table_key_info_with_consistency( - &self, - account_id: &str, - table_name: &str, - quorum: bool, ) -> Result { let catalog_keyspace = format!("{}_catalog", self.keyspace_prefix); @@ -84,18 +65,13 @@ impl CassandraEngine { FROM {catalog_keyspace}.tables WHERE account_id = ? AND table_name = ?" ); let values = cdrs_tokio::query_values!(account_id, table_name); - let rows = if quorum { - crate::cassandra_util::query_rows_quorum( - &self.session, - &query, - values, - "fetch_table_key_info", - ) - .await? - } else { - crate::cassandra_util::query_rows(&self.session, &query, values, "fetch_table_key_info") - .await? - }; + let rows = crate::cassandra_util::query_rows( + &self.session, + &query, + values, + "fetch_table_key_info", + ) + .await?; let row = rows .into_iter() @@ -270,10 +246,12 @@ impl CassandraEngine { ) }; - self.session - .query(&ddl) - .await - .map_err(|e| StorageError::Internal(format!("Failed to create data table: {e}")))?; + crate::cassandra_util::ddl::( + &self.session, + &ddl, + "Failed to create data table", + ) + .await?; Ok(()) } @@ -287,10 +265,12 @@ impl CassandraEngine { let ddb_table = data_table_name(table_id); let ddl = format!("DROP TABLE IF EXISTS {account_keyspace}.{ddb_table}"); - self.session - .query(&ddl) - .await - .map_err(|e| StorageError::Internal(format!("Failed to drop data table: {e}")))?; + crate::cassandra_util::ddl::( + &self.session, + &ddl, + "Failed to drop data table", + ) + .await?; Ok(()) } @@ -304,10 +284,12 @@ impl CassandraEngine { let idx_table = index_table_name(index_id); let ddl = format!("DROP TABLE IF EXISTS {account_keyspace}.{idx_table}"); - self.session - .query(&ddl) - .await - .map_err(|e| StorageError::Internal(format!("Failed to drop index data table: {e}")))?; + crate::cassandra_util::ddl::( + &self.session, + &ddl, + "Failed to drop index data table", + ) + .await?; Ok(()) } @@ -409,10 +391,12 @@ impl CassandraEngine { primary_key ); - self.session - .query(&ddl) - .await - .map_err(|e| StorageError::Internal(format!("Failed to create index table: {e}")))?; + crate::cassandra_util::ddl::( + &self.session, + &ddl, + "Failed to create index table", + ) + .await?; Ok(()) } @@ -443,8 +427,6 @@ pub(crate) async fn backfill_gsi( projection: &extenddb_core::types::Projection, ) -> Result<(), StorageError> { use crate::data::index::{insert_index_row_multi, item_has_index_keys, project_item_for_index}; - use cdrs_tokio::consistency::Consistency; - use cdrs_tokio::query::BatchQueryBuilder; use cdrs_tokio::types::IntoRustByName as _; const PAGE_SIZE: i64 = 500; @@ -495,7 +477,7 @@ pub(crate) async fn backfill_gsi( break; } - let mut batch = BatchQueryBuilder::new().with_consistency(Consistency::LocalQuorum); + let mut batch = batch(); let mut batch_has_rows = false; for row in &rows { @@ -536,7 +518,7 @@ pub(crate) async fn backfill_gsi( if batch_has_rows { session - .batch( + .run_batch( batch .build() .map_err(|e| StorageError::Internal(e.to_string()))?, diff --git a/crates/storage-cassandra/src/data/delete_item.rs b/crates/storage-cassandra/src/data/delete_item.rs index 301cbb696..bfe8e3297 100644 --- a/crates/storage-cassandra/src/data/delete_item.rs +++ b/crates/storage-cassandra/src/data/delete_item.rs @@ -3,8 +3,7 @@ //! `delete_item` implementation for the Cassandra backend. -use cdrs_tokio::consistency::Consistency; -use cdrs_tokio::query::BatchQueryBuilder; +use crate::cassandra_util::PolicySession as _; use cdrs_tokio::types::IntoRustByName; use extenddb_core::expression::{Expr, ExpressionMaps}; use extenddb_core::types::{Item, TableKeyInfo}; @@ -16,6 +15,7 @@ use super::ddl::data_table_name; use super::index::fetch_indexes_for_table; use super::{json_to_item, query_with_pk_sk}; use crate::CassandraEngine; +use crate::cassandra_util::{Stmt, batch}; use crate::stream_util::stream_record_statement; /// Lifetime of the base-row claim an ordinary request holds while it commits @@ -230,8 +230,14 @@ impl CassandraEngine { "SELECT item_data, version, prepared_txn_id FROM {data_keyspace}.{ddb_table} WHERE pk = ? AND {sk_col} = ?" ); - let old_result = - query_with_pk_sk(&self.session, &select_query, pk_text.as_ref(), &sk).await?; + let old_result = query_with_pk_sk( + &self.session, + &select_query, + Stmt::Read, + pk_text.as_ref(), + &sk, + ) + .await?; let body = old_result .response_body() @@ -299,9 +305,10 @@ impl CassandraEngine { // index rows written afterwards carry that order (`data::version`). // Deleting an absent item writes nothing. let Some(old_item) = old_item_opt else { - // The read above is at the driver's default consistency, - // and a replica that missed the latest write reads as - // absent. The fence catches a stale image but not a stale + // The read above is at LOCAL_QUORUM. It sees every write that + // was acknowledged before it, but not an LWT whose Paxos round + // is still in progress, so it can read as absent. The fence + // catches a stale image but not a stale // absence, so the absence is confirmed at LOCAL_SERIAL // before the delete answers without writing. An item found // there that a write stored before this delete began is @@ -406,7 +413,14 @@ impl CassandraEngine { && ttl_config.is_none() && ttl_claim.is_none() { - query_with_pk_sk(&self.session, &delete_cql, pk_text.as_ref(), &sk).await?; + query_with_pk_sk( + &self.session, + &delete_cql, + Stmt::Write, + pk_text.as_ref(), + &sk, + ) + .await?; } else { use super::index::sk_to_value; let delete_qv = cdrs_tokio::query::QueryValues::SimpleValues(vec![ @@ -426,9 +440,7 @@ impl CassandraEngine { return Err(error); } }; - let mut batch = BatchQueryBuilder::new() - .with_consistency(Consistency::LocalQuorum) - .with_timestamp(mutation_timestamp); + let mut batch = batch().with_timestamp(mutation_timestamp); batch = batch.add_query(delete_cql, delete_qv); if !indexes.is_empty() @@ -502,7 +514,7 @@ impl CassandraEngine { return Err(StorageError::Internal(error.to_string())); } }; - if let Err(error) = self.session.batch(built).await { + if let Err(error) = self.session.run_batch(built).await { self.release_ttl_mutation_claim(key_info, key, ttl_claim) .await; return Err(StorageError::Internal(format!("Batch execution: {error}"))); @@ -587,9 +599,10 @@ impl CassandraEngine { } else { // Ordinary delete without TTL: see the sort-key variant above. let Some(old_item) = old_item_opt else { - // The read above is at the driver's default consistency, - // and a replica that missed the latest write reads as - // absent. The fence catches a stale image but not a stale + // The read above is at LOCAL_QUORUM. It sees every write that + // was acknowledged before it, but not an LWT whose Paxos round + // is still in progress, so it can read as absent. The fence + // catches a stale image but not a stale // absence, so the absence is confirmed at LOCAL_SERIAL // before the delete answers without writing. An item found // there that a write stored before this delete began is @@ -687,7 +700,11 @@ impl CassandraEngine { && ttl_claim.is_none() { self.session - .query_with_values(&delete_cql, cdrs_tokio::query_values!(pk_text.as_str())) + .run( + Stmt::Write, + &delete_cql, + cdrs_tokio::query_values!(pk_text.as_str()), + ) .await .map_err(|e| StorageError::Internal(format!("Delete failed: {e}")))?; } else { @@ -707,9 +724,7 @@ impl CassandraEngine { return Err(error); } }; - let mut batch = BatchQueryBuilder::new() - .with_consistency(Consistency::LocalQuorum) - .with_timestamp(mutation_timestamp); + let mut batch = batch().with_timestamp(mutation_timestamp); batch = batch.add_query(delete_cql, delete_qv); if !indexes.is_empty() @@ -783,7 +798,7 @@ impl CassandraEngine { return Err(StorageError::Internal(error.to_string())); } }; - if let Err(error) = self.session.batch(built).await { + if let Err(error) = self.session.run_batch(built).await { self.release_ttl_mutation_claim(key_info, key, ttl_claim) .await; return Err(StorageError::Internal(format!("Batch execution: {error}"))); @@ -837,7 +852,7 @@ impl CassandraEngine { WHERE pk = ? AND {} = ?", sk_column(sk_type) ); - query_with_pk_sk(&self.session, &query, pk.as_str(), &sk) + query_with_pk_sk(&self.session, &query, Stmt::Read, pk.as_str(), &sk) .await? .response_body() .ok() @@ -971,13 +986,9 @@ impl CassandraEngine { ]), ) }; - let rows = crate::cassandra_util::query_rows_quorum( - &self.session, - &query, - values, - "base_row_owned_by", - ) - .await?; + let rows = + crate::cassandra_util::query_rows(&self.session, &query, values, "base_row_owned_by") + .await?; let owner: Option = rows .first() .and_then(|row| row.get_by_name("prepared_txn_id").ok().flatten()); @@ -999,10 +1010,10 @@ impl CassandraEngine { effects_timestamp_ms: i64, ) -> Result<(), StorageError> { let account_keyspace = self.account_keyspace(&key_info.account_id); - // Quorum: a stale replica omitting an index here would be read as - // "nothing to restore", and this is the last chance to restore it - // before the sealed owner is released. - let indexes = super::index::fetch_indexes_for_table_quorum( + // This is the last chance to restore an index before the sealed + // owner is released, so an index missing from this list is never + // restored. + let indexes = super::index::fetch_indexes_for_table( &key_info.table_id, &self.session, &self.catalog_keyspace(), @@ -1024,9 +1035,7 @@ impl CassandraEngine { // with now-derived micros keeps it also above any older write. let restore_timestamp = (effects_timestamp_ms * 1_000 + 1).max(chrono::Utc::now().timestamp_micros()); - let mut batch = BatchQueryBuilder::new() - .with_consistency(Consistency::LocalQuorum) - .with_timestamp(restore_timestamp); + let mut batch = batch().with_timestamp(restore_timestamp); // old = None: this is a pure re-upsert of the current image's rows. super::index::sync_indexes( &mut batch, @@ -1054,7 +1063,7 @@ impl CassandraEngine { .build() .map_err(|error| StorageError::Internal(error.to_string()))?; self.session - .batch(built) + .run_batch(built) .await .map_err(|error| StorageError::Internal(format!("Restore sync indexes: {error}")))?; self.gsi_queue.notify_workers(); @@ -1092,9 +1101,7 @@ impl CassandraEngine { // identical cells at an identical timestamp, and so restoration (which // stamps strictly above this) beats these tombstones by construction // rather than by cross-coordinator clock luck. - let mut batch = BatchQueryBuilder::new() - .with_consistency(Consistency::LocalQuorum) - .with_timestamp(delete_timestamp_ms * 1_000); + let mut batch = batch().with_timestamp(delete_timestamp_ms * 1_000); let mut has_effects = !indexes.is_empty(); if !indexes.is_empty() { super::index::sync_indexes( @@ -1158,7 +1165,7 @@ impl CassandraEngine { .build() .map_err(|error| StorageError::Internal(error.to_string()))?; self.session - .batch(built) + .run_batch(built) .await .map_err(|error| StorageError::Internal(format!("TTL side effects: {error}")))?; if !indexes.is_empty() { @@ -1488,7 +1495,11 @@ impl CassandraEngine { let result = self .session - .query_with_values(&query_null, cdrs_tokio::query_values!(now_ms, pk)) + .run( + Stmt::Lwt, + &query_null, + cdrs_tokio::query_values!(now_ms, pk), + ) .await .map_err(|e| { tracing::error!("update_partition_max_delete_timestamp (null): {e}"); @@ -1516,7 +1527,8 @@ impl CassandraEngine { ); self.session - .query_with_values( + .run( + Stmt::Lwt, &query_compare, cdrs_tokio::query_values!(now_ms, pk, now_ms), ) @@ -1553,7 +1565,7 @@ impl CassandraEngine { pk, sk.map(|(value, _)| value), sk.map(|(_, col)| col), - Some(Consistency::LocalSerial), + crate::cassandra_util::Stmt::SerialRead, ) .await?; Ok(row.is_some_and(|row| { @@ -1617,10 +1629,7 @@ impl CassandraEngine { sys_delay: u64, stamp: i64, ) -> Result<(), StorageError> { - use cdrs_tokio::consistency::Consistency; - use cdrs_tokio::query::BatchQueryBuilder; - - let mut batch = BatchQueryBuilder::new().with_consistency(Consistency::LocalQuorum); + let mut batch = batch(); if !indexes.is_empty() { super::index::sync_indexes_at( @@ -1667,7 +1676,7 @@ impl CassandraEngine { .build() .map_err(|e| StorageError::Internal(e.to_string()))?; self.session - .batch(built) + .run_batch(built) .await .map_err(|e| StorageError::Internal(format!("delete secondary effects: {e}")))?; diff --git a/crates/storage-cassandra/src/data/index.rs b/crates/storage-cassandra/src/data/index.rs index 2b2c0ef9f..803d02d81 100644 --- a/crates/storage-cassandra/src/data/index.rs +++ b/crates/storage-cassandra/src/data/index.rs @@ -54,52 +54,19 @@ pub async fn fetch_indexes_for_table( table_id: &str, session: &Arc, catalog_keyspace: &str, -) -> Result, StorageError> { - fetch_indexes_for_table_at(table_id, session, catalog_keyspace, false).await -} - -/// [`fetch_indexes_for_table`] at `LOCAL_QUORUM`. -/// -/// For paths where a stale-empty answer is acted on destructively or treated -/// as "nothing to restore": at the default consistency a lagging replica can -/// omit an index, and a must-complete restoration that trusts that omission -/// leaves a live item permanently missing an index row. -pub async fn fetch_indexes_for_table_quorum( - table_id: &str, - session: &Arc, - catalog_keyspace: &str, -) -> Result, StorageError> { - fetch_indexes_for_table_at(table_id, session, catalog_keyspace, true).await -} - -async fn fetch_indexes_for_table_at( - table_id: &str, - session: &Arc, - catalog_keyspace: &str, - quorum: bool, ) -> Result, StorageError> { let query = format!( "SELECT index_name, index_id, index_type, key_schema, projection, propagation_delay_ms \ FROM {catalog_keyspace}.indexes WHERE table_id = ?" ); - let rows = if quorum { - crate::cassandra_util::query_rows_quorum( - session, - &query, - query_values!(table_id), - "fetch_indexes_for_table", - ) - .await? - } else { - query_rows( - session, - &query, - query_values!(table_id), - "fetch_indexes_for_table", - ) - .await? - }; + let rows = query_rows( + session, + &query, + query_values!(table_id), + "fetch_indexes_for_table", + ) + .await?; rows.into_iter() .map(|row| { @@ -493,7 +460,7 @@ pub(crate) async fn enqueue_async_indexes( cdrs_tokio::types::value::Value::from(context_json.as_str()), ]); - let old = std::mem::replace(batch, BatchQueryBuilder::new()); + let old = std::mem::take(batch); *batch = old.add_query(insert_cql, insert_qv); enqueued += 1; @@ -577,7 +544,7 @@ pub(crate) fn delete_index_row_multi( where_cols.join(" AND ") ); let qv = cdrs_tokio::query::QueryValues::SimpleValues(values); - let old = std::mem::replace(batch, BatchQueryBuilder::new()); + let old = std::mem::take(batch); *batch = old.add_query(cql, qv); Ok(()) } @@ -656,7 +623,7 @@ pub(crate) fn insert_index_row_multi( using ); let qv = cdrs_tokio::query::QueryValues::SimpleValues(values); - let old = std::mem::replace(batch, BatchQueryBuilder::new()); + let old = std::mem::take(batch); *batch = old.add_query(cql, qv); Ok(()) } diff --git a/crates/storage-cassandra/src/data/mod.rs b/crates/storage-cassandra/src/data/mod.rs index 1c8817724..86806a120 100644 --- a/crates/storage-cassandra/src/data/mod.rs +++ b/crates/storage-cassandra/src/data/mod.rs @@ -3,15 +3,17 @@ //! Data table operations for Cassandra. +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use cdrs_tokio::cluster::TcpConnectionManager; use cdrs_tokio::cluster::session::Session; use cdrs_tokio::load_balancing::RoundRobinLoadBalancingStrategy; use cdrs_tokio::transport::TransportTcp; -use cdrs_tokio::types::blob::Blob; use extenddb_core::expression::ExpressionMaps; use extenddb_core::types::Item; use extenddb_storage::error::StorageError; use extenddb_storage::util::SortKeyValue; +use index::sk_to_value; mod condition; mod data_engine; @@ -87,35 +89,38 @@ pub(crate) fn decimal_to_value(n: &bigdecimal::BigDecimal) -> cdrs_tokio::types: cdrs_tokio::types::value::Value::from(bigdecimal_to_cql_decimal(n)) } -/// Execute a query with pk and sort key, returning the result. -/// -/// Helper to reduce repetitive match-on-sk-type pattern. +/// Run `query` with `values` as a statement of `kind`, at the level the +/// consistency policy gives that kind ([`crate::cassandra_util::params`]). +async fn run( + session: &CassandraSession, + query: &str, + kind: Stmt, + values: cdrs_tokio::query::QueryValues, +) -> Result { + session + .run(kind, query, values) + .await + .map_err(|e| StorageError::Internal(format!("Query failed: {e}"))) +} + +/// Execute a statement of `kind` with `(pk, sk)` bound parameters. pub(crate) async fn query_with_pk_sk( session: &CassandraSession, query: &str, + kind: Stmt, pk: &str, sk: &SortKeyValue, ) -> Result { - match sk { - SortKeyValue::S(s) => { - session - .query_with_values(query, cdrs_tokio::query_values!(pk, s.as_str())) - .await - } - SortKeyValue::N(n) => { - session - .query_with_values(query, cdrs_tokio::query_values!(pk, decimal_to_value(n))) - .await - } - SortKeyValue::B(b) => { - session - .query_with_values(query, cdrs_tokio::query_values!(pk, Blob::new(b.clone()))) - .await - } - } - .map_err(|e| StorageError::Internal(format!("Query failed: {e}"))) + run( + session, + query, + kind, + cdrs_tokio::query_values!(pk, sk_to_value(sk)), + ) + .await } -/// Execute a query with `(pk, sk, txn_id_bytes)` bound parameters. + +/// Execute an LWT with `(pk, sk, txn_id_bytes)` bound parameters. /// /// Used for: rollback DELETE, commit DELETE. pub(crate) async fn query_with_pk_sk_txnid( @@ -125,33 +130,16 @@ pub(crate) async fn query_with_pk_sk_txnid( sk: &SortKeyValue, txn_id: cdrs_tokio::types::value::Bytes, ) -> Result { - match sk { - SortKeyValue::S(s) => { - session - .query_with_values(query, cdrs_tokio::query_values!(pk, s.as_str(), txn_id)) - .await - } - SortKeyValue::N(n) => { - session - .query_with_values( - query, - cdrs_tokio::query_values!(pk, decimal_to_value(n), txn_id), - ) - .await - } - SortKeyValue::B(b) => { - session - .query_with_values( - query, - cdrs_tokio::query_values!(pk, Blob::new(b.clone()), txn_id), - ) - .await - } - } - .map_err(|e| StorageError::Internal(format!("Query failed: {e}"))) + run( + session, + query, + Stmt::Lwt, + cdrs_tokio::query_values!(pk, sk_to_value(sk), txn_id), + ) + .await } -/// Execute a query with `(txn_id_bytes, txn_timestamp, pk, sk)` bound parameters. +/// Execute an LWT with `(txn_id_bytes, txn_timestamp, pk, sk)` bound parameters. /// /// Used for: prepare UPDATE existing item. pub(crate) async fn query_with_txnid_ts_pk_sk( @@ -162,36 +150,17 @@ pub(crate) async fn query_with_txnid_ts_pk_sk( pk: &str, sk: &SortKeyValue, ) -> Result { - match sk { - SortKeyValue::S(s) => { - session - .query_with_values( - query, - cdrs_tokio::query_values!(txn_id, txn_timestamp, pk, s.as_str()), - ) - .await - } - SortKeyValue::N(n) => { - session - .query_with_values( - query, - cdrs_tokio::query_values!(txn_id, txn_timestamp, pk, decimal_to_value(n)), - ) - .await - } - SortKeyValue::B(b) => { - session - .query_with_values( - query, - cdrs_tokio::query_values!(txn_id, txn_timestamp, pk, Blob::new(b.clone())), - ) - .await - } - } - .map_err(|e| StorageError::Internal(format!("Query failed: {e}"))) + run( + session, + query, + Stmt::Lwt, + cdrs_tokio::query_values!(txn_id, txn_timestamp, pk, sk_to_value(sk)), + ) + .await } -/// Execute a query with `(pk, sk, item_text, txn_id_bytes, txn_timestamp)` bound parameters. +/// Execute an LWT with `(pk, sk, item_text, txn_id_bytes, txn_timestamp)` +/// bound parameters. /// /// Used for: prepare INSERT new item. pub(crate) async fn query_with_pk_sk_item_txnid_ts( @@ -203,51 +172,19 @@ pub(crate) async fn query_with_pk_sk_item_txnid_ts( txn_id: cdrs_tokio::types::value::Bytes, txn_timestamp: i64, ) -> Result { - match sk { - SortKeyValue::S(s) => { - session - .query_with_values( - query, - cdrs_tokio::query_values!(pk, s.as_str(), item_text, txn_id, txn_timestamp), - ) - .await - } - SortKeyValue::N(n) => { - session - .query_with_values( - query, - cdrs_tokio::query_values!( - pk, - decimal_to_value(n), - item_text, - txn_id, - txn_timestamp - ), - ) - .await - } - SortKeyValue::B(b) => { - session - .query_with_values( - query, - cdrs_tokio::query_values!( - pk, - Blob::new(b.clone()), - item_text, - txn_id, - txn_timestamp - ), - ) - .await - } - } - .map_err(|e| StorageError::Internal(format!("Query failed: {e}"))) + run( + session, + query, + Stmt::Lwt, + cdrs_tokio::query_values!(pk, sk_to_value(sk), item_text, txn_id, txn_timestamp), + ) + .await } /// Execute a SELECT query by primary key (pk only, or pk + sort key). /// /// Builds the appropriate query based on whether a sort key is present, -/// executes it, and returns the first row if any. +/// executes it at `LOCAL_QUORUM`, and returns the first row if any. pub(crate) async fn select_by_pk( session: &CassandraSession, keyspace: &str, @@ -257,12 +194,23 @@ pub(crate) async fn select_by_pk( sk: Option<&SortKeyValue>, sk_col: Option<&str>, ) -> Result, StorageError> { - select_by_pk_at(session, keyspace, table, columns, pk, sk, sk_col, None).await + select_by_pk_at( + session, + keyspace, + table, + columns, + pk, + sk, + sk_col, + Stmt::Read, + ) + .await } -/// [`select_by_pk`] at `consistency`, or at the driver's default (`ONE`) when -/// it is `None`. A read at `LOCAL_SERIAL` sees every LWT that has committed, -/// and completes one still in progress, before it answers. +/// [`select_by_pk`] as a read of `kind`: [`Stmt::Read`] (`LOCAL_QUORUM`) or +/// [`Stmt::SerialRead`] (`LOCAL_SERIAL`). A read at `LOCAL_SERIAL` sees every +/// LWT that has committed, and completes one still in progress, before it +/// answers. #[allow(clippy::too_many_arguments)] pub(crate) async fn select_by_pk_at( session: &CassandraSession, @@ -272,17 +220,12 @@ pub(crate) async fn select_by_pk_at( pk: &str, sk: Option<&SortKeyValue>, sk_col: Option<&str>, - consistency: Option, + kind: Stmt, ) -> Result, StorageError> { let (query, values) = if let (Some(sk), Some(sk_col)) = (sk, sk_col) { - let values = match sk { - SortKeyValue::S(s) => cdrs_tokio::query_values!(pk, s.as_str()), - SortKeyValue::N(n) => cdrs_tokio::query_values!(pk, decimal_to_value(n)), - SortKeyValue::B(b) => cdrs_tokio::query_values!(pk, Blob::new(b.clone())), - }; ( format!("SELECT {columns} FROM {keyspace}.{table} WHERE pk = ? AND {sk_col} = ?"), - values, + cdrs_tokio::query_values!(pk, sk_to_value(sk)), ) } else { ( @@ -290,14 +233,7 @@ pub(crate) async fn select_by_pk_at( cdrs_tokio::query_values!(pk), ) }; - let mut params = cdrs_tokio::statement::StatementParamsBuilder::new().with_values(values); - if let Some(consistency) = consistency { - params = params.with_consistency(consistency); - } - let result = session - .query_with_params(&query, params.build()) - .await - .map_err(|e| StorageError::Internal(format!("Query failed: {e}")))?; + let result = run(session, &query, kind, values).await?; let rows = result .response_body() diff --git a/crates/storage-cassandra/src/data/put_get_item.rs b/crates/storage-cassandra/src/data/put_get_item.rs index 3c95c6dca..255b36776 100644 --- a/crates/storage-cassandra/src/data/put_get_item.rs +++ b/crates/storage-cassandra/src/data/put_get_item.rs @@ -3,8 +3,7 @@ //! `put_item` and `get_item` implementations for the Cassandra backend. -use cdrs_tokio::consistency::Consistency; -use cdrs_tokio::query::BatchQueryBuilder; +use crate::cassandra_util::PolicySession as _; use cdrs_tokio::types::IntoRustByName; use extenddb_core::expression::{Expr, ExpressionMaps}; use extenddb_core::types::{Item, TableKeyInfo}; @@ -15,6 +14,7 @@ use extenddb_storage::util::{composite_pk_to_text, parse_sk, pk_to_text, sk_colu use super::ddl::data_table_name; use super::{json_to_item, query_with_pk_sk}; use crate::CassandraEngine; +use crate::cassandra_util::{Stmt, batch}; use crate::stream_util::stream_record_statement; /// How a put maintains GSIs. @@ -151,8 +151,7 @@ impl CassandraEngine { }; // The batch carries the timestamp, so the index statements pass none // of their own (Cassandra refuses a batch with both). - let mut batch = BatchQueryBuilder::new() - .with_consistency(Consistency::LocalQuorum) + let mut batch = batch() .with_timestamp(stamp) .add_query(cql, cdrs_tokio::query::QueryValues::SimpleValues(values)); if !indexes.is_empty() { @@ -171,7 +170,7 @@ impl CassandraEngine { let built = batch .build() .map_err(|error| StorageError::Internal(error.to_string()))?; - self.session.batch(built).await.map_err(|error| { + self.session.run_batch(built).await.map_err(|error| { StorageError::Internal(format!("put_restored_item_at batch: {error}")) })?; Ok(()) @@ -324,8 +323,14 @@ impl CassandraEngine { "SELECT item_data, version, prepared_txn_id FROM {data_keyspace}.{ddb_table} WHERE pk = ? AND {sk_col} = ?" ); - let old_result = - query_with_pk_sk(&self.session, &select_query, pk_text.as_ref(), &sk).await?; + let old_result = query_with_pk_sk( + &self.session, + &select_query, + Stmt::Read, + pk_text.as_ref(), + &sk, + ) + .await?; let body = old_result .response_body() @@ -607,7 +612,7 @@ impl CassandraEngine { let result = self .session - .query_with_values(&insert_cql, insert_qv) + .run(Stmt::Lwt, &insert_cql, insert_qv) .await .map_err(|e| StorageError::Internal(format!("put_item_if_not_exists: {e}")))?; @@ -654,7 +659,7 @@ impl CassandraEngine { } // The index statements carry the version; the queue rows and the // stream record keep Cassandra's timestamp (`data::version`). - let mut batch = BatchQueryBuilder::new().with_consistency(Consistency::LocalQuorum); + let mut batch = batch(); if !indexes.is_empty() { super::index::sync_indexes_at( @@ -694,7 +699,7 @@ impl CassandraEngine { let built = batch .build() .map_err(|error| StorageError::Internal(error.to_string()))?; - self.session.batch(built).await.map_err(|error| { + self.session.run_batch(built).await.map_err(|error| { StorageError::Internal(format!("put_item_if_not_exists batch: {error}")) })?; @@ -704,19 +709,12 @@ impl CassandraEngine { Ok(None) // return_old is always None — item didn't exist } - /// Implementation of `DataEngine::get_item`. - /// Read an item at `LOCAL_QUORUM`. + /// Read an item at `LOCAL_QUORUM` for a TTL decision. /// - /// [`Self::get_item_impl`] reads at the driver's default consistency, which is - /// correct for an eventually-consistent `GetItem` but not for a TTL decision: - /// the expiration worker and the reconciliation outbox both treat `None` as - /// authoritative and act on it destructively — retiring queue work, or - /// dropping an outbox row — and a lagging replica reads as `None` for an item - /// that exists. Acting on that would leave the item with no expiration entry - /// and therefore never expiring. - /// - /// All TTL writes commit at `LOCAL_QUORUM`, so a `LOCAL_QUORUM` read - /// intersects them and cannot miss a committed item. + /// The expiration worker and the reconciliation outbox both treat `None` + /// as authoritative and act on it destructively: they retire queue work, + /// or drop an outbox row. All TTL writes commit at `LOCAL_QUORUM`, so a + /// `LOCAL_QUORUM` read intersects them and cannot miss a committed item. pub(crate) async fn get_item_quorum( &self, key_info: &TableKeyInfo, @@ -753,13 +751,9 @@ impl CassandraEngine { ) }; - let rows = crate::cassandra_util::query_rows_quorum( - &self.session, - &query, - values, - "get_item_quorum", - ) - .await?; + let rows = + crate::cassandra_util::query_rows(&self.session, &query, values, "get_item_quorum") + .await?; let Some(row) = rows.into_iter().next() else { return Ok(None); }; @@ -767,6 +761,7 @@ impl CassandraEngine { item_data.map(json_to_item).transpose() } + /// Implementation of `DataEngine::get_item`, at `LOCAL_QUORUM`. pub(crate) async fn get_item_impl( &self, key_info: &TableKeyInfo, @@ -795,7 +790,8 @@ impl CassandraEngine { "SELECT item_data FROM {data_keyspace}.{ddb_table} WHERE pk = ? AND {sk_col} = ?" ); - let result = query_with_pk_sk(&self.session, &query, pk_text.as_ref(), &sk).await?; + let result = + query_with_pk_sk(&self.session, &query, Stmt::Read, pk_text.as_ref(), &sk).await?; let body = result .response_body() @@ -815,7 +811,11 @@ impl CassandraEngine { let result = self .session - .query_with_values(&query, cdrs_tokio::query_values!(pk_text.as_ref() as &str)) + .run( + Stmt::Read, + &query, + cdrs_tokio::query_values!(pk_text.as_ref() as &str), + ) .await .map_err(|e| StorageError::Internal(format!("Get item: {e}")))?; diff --git a/crates/storage-cassandra/src/data/scan.rs b/crates/storage-cassandra/src/data/scan.rs index 6e93d4a30..3c4c2d4f2 100644 --- a/crates/storage-cassandra/src/data/scan.rs +++ b/crates/storage-cassandra/src/data/scan.rs @@ -108,14 +108,13 @@ async fn rows_no_values( session: &Arc, query: &str, ) -> Result, StorageError> { - let result = session - .query(query) - .await - .map_err(|e| StorageError::Internal(format!("scan query failed: {e}")))?; - let body = result - .response_body() - .map_err(|e| StorageError::Internal(format!("scan parse failed: {e}")))?; - Ok(body.into_rows().unwrap_or_default()) + crate::cassandra_util::query_rows( + session, + query, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + "scan query failed", + ) + .await } impl crate::CassandraEngine { @@ -310,7 +309,7 @@ impl crate::CassandraEngine { // exactly one row, and `token()` is independent of the queried table's // schema, so this needs neither the data table to exist nor a matching // row in it. - let rows = cassandra_util::query_rows::( + let rows = cassandra_util::system_read::( &self.session_arc(), "SELECT token(?) AS t FROM system.local", QueryValues::SimpleValues(vec![Value::from(pk_text.as_str())]), diff --git a/crates/storage-cassandra/src/data/transact_stream.rs b/crates/storage-cassandra/src/data/transact_stream.rs index 4df80819a..54a2185fd 100644 --- a/crates/storage-cassandra/src/data/transact_stream.rs +++ b/crates/storage-cassandra/src/data/transact_stream.rs @@ -85,7 +85,9 @@ pub(super) fn secondary_effect_batches( } let request = &index_batch.request; + // consistency-policy-ok: the record batch copies the index batch's levels. let record_batch = QueryBatch::new( + // consistency-policy-ok: the levels below are the index batch's. BodyReqBatch::new( request.batch_type, vec![record], diff --git a/crates/storage-cassandra/src/data/transaction_ledger.rs b/crates/storage-cassandra/src/data/transaction_ledger.rs index 9068370f9..c2d513a23 100644 --- a/crates/storage-cassandra/src/data/transaction_ledger.rs +++ b/crates/storage-cassandra/src/data/transaction_ledger.rs @@ -3,13 +3,14 @@ //! Transaction ledger access functions for DynamoDB transactions. +use crate::cassandra_util::PolicySession as _; use cdrs_tokio::types::IntoRustByName; use cdrs_tokio::types::value::Bytes; use extenddb_storage::error::StorageError; use uuid::Uuid; use crate::CassandraEngine; -use crate::cassandra_util::{get_column, query_optional, query_rows}; +use crate::cassandra_util::{Stmt, get_column, query_optional, query_rows}; /// Transaction states (from DynamoDB paper). #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -120,7 +121,8 @@ impl CassandraEngine { let result = self .session - .query_with_values( + .run( + Stmt::Lwt, &query, cdrs_tokio::query_values!( Bytes::new(txn_id.as_bytes().to_vec()), @@ -167,7 +169,8 @@ impl CassandraEngine { let query = format!("UPDATE {keyspace}.transaction_ledger SET state = ? WHERE txn_id = ?"); self.session - .query_with_values( + .run( + Stmt::Write, &query, cdrs_tokio::query_values!( new_state.as_str(), @@ -198,7 +201,8 @@ impl CassandraEngine { let query = format!("UPDATE {keyspace}.transaction_ledger SET items_blob = ? WHERE txn_id = ?"); self.session - .query_with_values( + .run( + Stmt::Write, &query, cdrs_tokio::query_values!(blob, Bytes::new(txn_id.as_bytes().to_vec())), ) @@ -304,7 +308,8 @@ impl CassandraEngine { let query = format!("DELETE FROM {keyspace}.transaction_ledger WHERE txn_id = ?"); self.session - .query_with_values( + .run( + Stmt::Write, &query, cdrs_tokio::query_values!(Bytes::new(txn_id.as_bytes().to_vec())), ) diff --git a/crates/storage-cassandra/src/data/transactions.rs b/crates/storage-cassandra/src/data/transactions.rs index 891c62436..ad4f7aa5f 100644 --- a/crates/storage-cassandra/src/data/transactions.rs +++ b/crates/storage-cassandra/src/data/transactions.rs @@ -4,9 +4,8 @@ //! DynamoDB transaction implementations for Cassandra backend. use super::transact_stream::{commit_old_image, secondary_effect_batches}; -use cdrs_tokio::consistency::Consistency; +use crate::cassandra_util::PolicySession as _; use cdrs_tokio::frame::Envelope; -use cdrs_tokio::query::BatchQueryBuilder; use cdrs_tokio::types::IntoRustByName; use cdrs_tokio::types::value::Bytes; use extenddb_core::expression::{self, ExpressionMaps}; @@ -23,7 +22,7 @@ use std::time::Duration; use uuid::Uuid; use crate::CassandraEngine; -use crate::cassandra_util::{get_column, query_optional}; +use crate::cassandra_util::{Stmt, get_column, query_optional}; use crate::data::ddl::data_table_name; use crate::data::transaction_ledger::{LedgerOp, TransactionState}; use crate::data::{ @@ -1342,7 +1341,12 @@ impl CassandraEngine { skip_txn_id: Option, ) -> Result, StorageError> { Ok(self - .fetch_row_for_transaction(key_info, key, skip_txn_id, None) + .fetch_row_for_transaction( + key_info, + key, + skip_txn_id, + crate::cassandra_util::Stmt::Read, + ) .await? .item) } @@ -1358,8 +1362,9 @@ impl CassandraEngine { /// item and therefore a real old image. The version is `None` in that last /// case too: the row belongs to the other transaction until it finishes. /// - /// `consistency` is the read's consistency. COMMIT reads its own fenced - /// row at `LOCAL_SERIAL`: the read supplies the old image whose index rows + /// `read` is the kind of the read. COMMIT reads its own fenced row as a + /// [`Stmt::SerialRead`](crate::cassandra_util::Stmt::SerialRead), at + /// `LOCAL_SERIAL`: the read supplies the old image whose index rows /// the commit removes and the version it advances, and the commit's /// `IF prepared_txn_id = ?` checks neither, so a replica that missed the /// latest write must not answer it. @@ -1368,7 +1373,7 @@ impl CassandraEngine { key_info: &TableKeyInfo, key: &Item, skip_txn_id: Option, - consistency: Option, + read: crate::cassandra_util::Stmt, ) -> Result { let keyspace = self.account_keyspace(&key_info.account_id); let table = data_table_name(&key_info.table_id); @@ -1384,7 +1389,7 @@ impl CassandraEngine { pk_text.as_str(), sk.as_ref(), sk_col.as_deref(), - consistency, + read, ) .await? else { @@ -1542,7 +1547,11 @@ impl CassandraEngine { let result = self .session - .query_with_values(&query, cdrs_tokio::query_values!(pk_text.as_str())) + .run( + Stmt::Read, + &query, + cdrs_tokio::query_values!(pk_text.as_str()), + ) .await .map_err(|e| { tracing::error!("check_partition_max_delete_timestamp: {e}"); @@ -1624,7 +1633,7 @@ impl CassandraEngine { VALUES (?, ?, ?, ?, true) IF NOT EXISTS" ); self.session - .query_with_values(&query, cdrs_tokio::query_values!(pk_text.as_str(), item_text, txn_id_bytes, txn_timestamp)) + .run(Stmt::Lwt, &query, cdrs_tokio::query_values!(pk_text.as_str(), item_text, txn_id_bytes, txn_timestamp)) .await .map_err(|e| StorageError::Internal(e.to_string())) } else { @@ -1633,7 +1642,7 @@ impl CassandraEngine { WHERE pk = ? IF prepared_txn_id = null" ); self.session - .query_with_values(&query, cdrs_tokio::query_values!(txn_id_bytes, txn_timestamp, pk_text.as_str())) + .run(Stmt::Lwt, &query, cdrs_tokio::query_values!(txn_id_bytes, txn_timestamp, pk_text.as_str())) .await .map_err(|e| StorageError::Internal(e.to_string())) } @@ -1685,7 +1694,7 @@ impl CassandraEngine { key_info, item, Some(txn_id), - Some(Consistency::LocalSerial), + crate::cassandra_util::Stmt::SerialRead, ) .await?; let old_image = commit_old_image(row.item, row.created_to_prepare); @@ -1740,7 +1749,7 @@ impl CassandraEngine { key_info, key, Some(txn_id), - Some(Consistency::LocalSerial), + crate::cassandra_util::Stmt::SerialRead, ) .await?; let mut final_item = row.item.clone().unwrap_or_else(|| (*key).clone()); @@ -1791,7 +1800,7 @@ impl CassandraEngine { key_info, key, Some(txn_id), - Some(Consistency::LocalSerial), + crate::cassandra_util::Stmt::SerialRead, ) .await?; let old_image = commit_old_image(row.item, row.created_to_prepare); @@ -1817,7 +1826,8 @@ impl CassandraEngine { let result = self .session - .query_with_values( + .run( + Stmt::Lwt, &update_max_ts_null_query, cdrs_tokio::query_values!(txn_timestamp, pk_text.as_str()), ) @@ -1838,7 +1848,8 @@ impl CassandraEngine { let _result2 = self .session - .query_with_values( + .run( + Stmt::Lwt, &update_max_ts_query, cdrs_tokio::query_values!( txn_timestamp, @@ -1881,10 +1892,7 @@ impl CassandraEngine { "DELETE FROM {keyspace}.{ddb_table} WHERE pk = ? IF prepared_txn_id = ?" ); self.session - .query_with_values( - &delete_query, - cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes), - ) + .run(Stmt::Lwt, &delete_query, cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes)) .await .map_err(|e| StorageError::Internal(e.to_string())) } @@ -1962,7 +1970,8 @@ impl CassandraEngine { IF prepared_txn_id = ? AND created_to_prepare = true" ); self.session - .query_with_values( + .run( + Stmt::Lwt, &query, cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes), ) @@ -2029,17 +2038,14 @@ impl CassandraEngine { WHERE pk = ? AND {sk_col} = ? IF prepared_txn_id = ?" ); self.session - .query_with_values( - &query, - cdrs_tokio::query::QueryValues::SimpleValues(vec![ + .run(Stmt::Lwt, &query, cdrs_tokio::query::QueryValues::SimpleValues(vec![ item_text.as_str().into(), next_version.into(), txn_timestamp.into(), cdrs_tokio::types::value::Value::from(pk_text.as_str()), super::index::sk_to_value(&sk), txn_id_bytes.into(), - ]), - ) + ])) .await .map_err(|e| StorageError::Internal(e.to_string())) } else { @@ -2048,7 +2054,7 @@ impl CassandraEngine { WHERE pk = ? IF prepared_txn_id = ?" ); self.session - .query_with_values(&query, cdrs_tokio::query_values!(item_text, next_version, txn_timestamp, pk_text.as_str(), txn_id_bytes)) + .run(Stmt::Lwt, &query, cdrs_tokio::query_values!(item_text, next_version, txn_timestamp, pk_text.as_str(), txn_id_bytes)) .await .map_err(|e| StorageError::Internal(e.to_string())) } @@ -2159,7 +2165,7 @@ impl CassandraEngine { return Ok(()); } - let mut batch = BatchQueryBuilder::new().with_consistency(Consistency::LocalQuorum); + let mut batch = crate::cassandra_util::batch(); let mut async_enqueued = 0; if !indexes.is_empty() { @@ -2197,7 +2203,7 @@ impl CassandraEngine { .build() .map_err(|e| StorageError::Internal(e.to_string()))?; for batch in secondary_effect_batches(index_batch, stream_stmt) { - self.session.batch(batch).await.map_err(|e| { + self.session.run_batch(batch).await.map_err(|e| { StorageError::Internal(format!("commit_secondary_effects batch: {e}")) })?; } @@ -2285,7 +2291,7 @@ impl CassandraEngine { ); let dr = self.session - .query_with_values(&delete_query, cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes.clone())) + .run(Stmt::Lwt, &delete_query, cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes.clone())) .await .map_err(|e| StorageError::Internal(e.to_string())) .map_err(|e| { tracing::error!("rollback delete: {e}"); e })?; @@ -2293,7 +2299,7 @@ impl CassandraEngine { return Ok(()); } self.session - .query_with_values(&update_query, cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes)) + .run(Stmt::Lwt, &update_query, cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes)) .await .map_err(|e| StorageError::Internal(e.to_string())) } @@ -2431,7 +2437,7 @@ impl CassandraEngine { pk, sk.map(|(value, _)| value), sk.map(|(_, col)| col.as_str()), - Some(Consistency::LocalSerial), + crate::cassandra_util::Stmt::SerialRead, ) .await?; Ok(row.and_then(|row| row.get_by_name("version").ok().flatten())) @@ -2458,7 +2464,7 @@ impl CassandraEngine { pk, sk.map(|(value, _)| value), sk.map(|(_, col)| col.as_str()), - Some(Consistency::LocalSerial), + crate::cassandra_util::Stmt::SerialRead, ) .await? else { @@ -2604,7 +2610,11 @@ impl CassandraEngine { IF prepared_txn_id = ? AND created_to_prepare = true", ); self.session - .query_with_values(&dq, cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes)) + .run( + Stmt::Lwt, + &dq, + cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes), + ) .await .map_err(|e| StorageError::Internal(e.to_string())) } @@ -2646,7 +2656,8 @@ impl CassandraEngine { WHERE pk = ? AND {sk_col} = ? IF prepared_txn_id = ?", ); self.session - .query_with_values( + .run( + Stmt::Lwt, &query, cdrs_tokio::query::QueryValues::SimpleValues(vec![ item_data.into(), @@ -2667,7 +2678,8 @@ impl CassandraEngine { WHERE pk = ? IF prepared_txn_id = ?", ); self.session - .query_with_values( + .run( + Stmt::Lwt, &query, cdrs_tokio::query_values!( item_data, @@ -2719,7 +2731,8 @@ impl CassandraEngine { ); let r1 = self .session - .query_with_values( + .run( + Stmt::Lwt, &update_null, cdrs_tokio::query_values!(txn_timestamp, op.pk.as_str()), ) @@ -2737,7 +2750,8 @@ impl CassandraEngine { ); let _ = self .session - .query_with_values( + .run( + Stmt::Lwt, &update_cmp, cdrs_tokio::query_values!(txn_timestamp, op.pk.as_str(), txn_timestamp), ) @@ -2762,7 +2776,8 @@ impl CassandraEngine { "DELETE FROM {keyspace}.{table} WHERE pk = ? IF prepared_txn_id = ?", ); self.session - .query_with_values( + .run( + Stmt::Lwt, &query, cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes), ) @@ -2834,7 +2849,8 @@ impl CassandraEngine { ); let dr = self .session - .query_with_values( + .run( + Stmt::Lwt, &dq, cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes.clone()), ) @@ -2856,7 +2872,8 @@ impl CassandraEngine { query_with_pk_sk_txnid(&self.session, &update_query, &op.pk, sk_val, txn_id_bytes).await } else { self.session - .query_with_values( + .run( + Stmt::Lwt, &update_query, cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes), ) diff --git a/crates/storage-cassandra/src/data/ttl.rs b/crates/storage-cassandra/src/data/ttl.rs index e2b2b0fea..e2c189fc0 100644 --- a/crates/storage-cassandra/src/data/ttl.rs +++ b/crates/storage-cassandra/src/data/ttl.rs @@ -8,6 +8,8 @@ //! indexed into day-bucketed, 64-way sharded partitions and are deleted through //! the normal item mutation path. +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use cdrs_tokio::query::BatchQueryBuilder; use cdrs_tokio::types::IntoRustByName; use extenddb_core::types::{AttributeValue, Item, TableKeyInfo}; @@ -143,7 +145,7 @@ fn same_queue_key(left: &TtlEntry, right: &TtlEntry) -> bool { /// `&mut` needs a swap. Doing that inline at each call site buried the statements /// being built. fn push_query(batch: &mut BatchQueryBuilder, cql: String, values: cdrs_tokio::query::QueryValues) { - let previous = std::mem::replace(batch, BatchQueryBuilder::new()); + let previous = std::mem::take(batch); *batch = previous.add_query(cql, values); } @@ -319,8 +321,7 @@ pub(crate) async fn record_ttl_repair( // account deletion + same-id recreation safe in a multi-host fleet — a // process-lifetime "already registered" cache on any one host would go // stale the moment another host dropped and recreated the keyspace. - let batch = cdrs_tokio::query::BatchQueryBuilder::new() - .with_consistency(cdrs_tokio::consistency::Consistency::LocalQuorum) + let batch = crate::cassandra_util::batch() .add_query( format!( "INSERT INTO {account_keyspace}.ttl_repair_inflight_partitions \ @@ -349,7 +350,7 @@ pub(crate) async fn record_ttl_repair( .map_err(|error| StorageError::Internal(format!("Build TTL repair batch: {error}")))?; engine .session - .batch(built) + .run_batch(built) .await .map_err(|error| StorageError::Internal(format!("Record TTL repair inflight: {error}")))?; @@ -386,7 +387,7 @@ impl TtlRepairGuard { engine: &CassandraEngine, account_keyspace: &str, ) -> Result<(), StorageError> { - crate::cassandra_util::execute_quorum( + crate::cassandra_util::execute( &engine.session, &format!( "INSERT INTO {account_keyspace}.ttl_reconcile_pending \ @@ -404,7 +405,7 @@ impl TtlRepairGuard { ) .await?; - crate::cassandra_util::execute_quorum( + crate::cassandra_util::execute( &engine.session, &format!( "DELETE FROM {account_keyspace}.ttl_repair_inflight \ @@ -432,7 +433,7 @@ pub(crate) async fn ttl_entry_registered( generation: uuid::Uuid, entry: &TtlEntry, ) -> Result { - let rows = crate::cassandra_util::query_rows_quorum( + let rows = crate::cassandra_util::query_rows( &engine.session, &format!( "SELECT key_hash FROM {account_keyspace}.{TTL_QUEUE_TABLE} \ @@ -462,7 +463,7 @@ async fn ensure_ttl_bucket_registration( entry: &TtlEntry, ) -> Result<(), StorageError> { let generation_bytes = cdrs_tokio::types::value::Bytes::new(generation.as_bytes().to_vec()); - crate::cassandra_util::execute_quorum( + crate::cassandra_util::execute( &engine.session, &format!( "INSERT INTO {account_keyspace}.{TTL_BUCKET_TABLE} \ @@ -477,7 +478,7 @@ async fn ensure_ttl_bucket_registration( "restore TTL bucket registration", ) .await?; - let visible = crate::cassandra_util::query_rows_quorum( + let visible = crate::cassandra_util::query_rows( &engine.session, &format!( "SELECT shard FROM {account_keyspace}.{TTL_BUCKET_TABLE} \ @@ -512,7 +513,7 @@ pub(crate) async fn insert_ttl_entry( // Common case after restoring discoverability: the entry is already there // because the write's own logged batch inserted it. A plain quorum read // avoids Paxos when that row is still PENDING. - let existing = crate::cassandra_util::query_rows_quorum( + let existing = crate::cassandra_util::query_rows( &engine.session, &format!( "SELECT state FROM {account_keyspace}.{TTL_QUEUE_TABLE} \ @@ -945,7 +946,7 @@ async fn retire_bucket_registration( "DELETE FROM {account_keyspace}.{TTL_BUCKET_TABLE}{using} \ WHERE table_id = ? AND generation = ? AND bucket = ? AND shard = ?" ); - crate::cassandra_util::execute_quorum( + crate::cassandra_util::execute( &engine.session, &cql, cdrs_tokio::query_values!( @@ -1021,7 +1022,7 @@ pub(crate) async fn load_due_ttl_work( AND generation = ? AND bucket = ? AND shard = ? AND expires_at <= ? \ LIMIT {partition_limit}" ); - let rows = crate::cassandra_util::query_rows_quorum( + let rows = crate::cassandra_util::query_rows( &engine.session, &query, cdrs_tokio::query_values!(table_id, generation_bytes.clone(), *bucket, *shard, now), @@ -1105,7 +1106,7 @@ pub(crate) async fn load_generation_work( } // Quorum: work this read misses would be abandoned holding a base-row // claim, and the generation would be reported drained when it is not. - let rows = crate::cassandra_util::query_rows_quorum( + let rows = crate::cassandra_util::query_rows( &engine.session, &format!( "SELECT expires_at, key_hash, key_data, state, work_id, work_data \ @@ -1161,7 +1162,7 @@ async fn generation_partitions( table_id: &str, generation: uuid::Uuid, ) -> Result, StorageError> { - let rows = crate::cassandra_util::query_rows_quorum( + let rows = crate::cassandra_util::query_rows( &engine.session, &format!( "SELECT bucket, shard FROM {account_keyspace}.{TTL_BUCKET_TABLE} \ @@ -1206,7 +1207,7 @@ pub(crate) async fn clear_ttl_generation( { // Quorum: `partition_drained` below decides whether to delete the bucket // registration and whether the generation can be reported fully drained. - let rows = crate::cassandra_util::query_rows_quorum( + let rows = crate::cassandra_util::query_rows( &engine.session, &format!( "SELECT expires_at, key_hash, key_data, state \ @@ -1294,7 +1295,8 @@ pub(crate) async fn clear_ttl_entries( ); engine .session - .query_with_values( + .run( + Stmt::Write, &delete, cdrs_tokio::query_values!( table_id, @@ -1310,7 +1312,11 @@ pub(crate) async fn clear_ttl_entries( format!("DELETE FROM {account_keyspace}.{TTL_BUCKET_TABLE} WHERE table_id = ?"); engine .session - .query_with_values(&delete_buckets, cdrs_tokio::query_values!(table_id)) + .run( + Stmt::Write, + &delete_buckets, + cdrs_tokio::query_values!(table_id), + ) .await .map_err(|error| StorageError::Internal(format!("Clear TTL buckets: {error}")))?; Ok(()) diff --git a/crates/storage-cassandra/src/data/update_item.rs b/crates/storage-cassandra/src/data/update_item.rs index 1a76efa0e..b6784ac41 100644 --- a/crates/storage-cassandra/src/data/update_item.rs +++ b/crates/storage-cassandra/src/data/update_item.rs @@ -3,8 +3,7 @@ //! `update_item` implementation for the Cassandra backend. -use cdrs_tokio::consistency::Consistency; -use cdrs_tokio::query::BatchQueryBuilder; +use crate::cassandra_util::PolicySession as _; use extenddb_core::expression::{self, Expr, ExpressionMaps, UpdateAction}; use extenddb_core::types::{Item, KeyType, TableKeyInfo}; use extenddb_core::validation; @@ -15,6 +14,7 @@ use extenddb_storage::util::{parse_sk, pk_to_text, sk_column}; use super::ddl::data_table_name; use super::{json_to_item, query_with_pk_sk}; use crate::CassandraEngine; +use crate::cassandra_util::{Stmt, batch}; use crate::stream_util::stream_record_statement; // 400 KB limit from DynamoDB specification @@ -284,7 +284,7 @@ impl CassandraEngine { let q = format!( "SELECT item_data, version, prepared_txn_id FROM {data_keyspace}.{ddb_table} WHERE pk = ? AND {sk_col} = ?" ); - let result = query_with_pk_sk(&self.session, &q, pk_text, sk).await?; + let result = query_with_pk_sk(&self.session, &q, Stmt::Read, pk_text, sk).await?; result .response_body() .map_err(|e| StorageError::Internal(format!("occ_read response_body: {e}")))? @@ -427,7 +427,7 @@ impl CassandraEngine { // Preserve f997485's Paxos linearization for ordinary writes. let result = self .session - .query_with_values(&lwt_cql, lwt_qv) + .run(Stmt::Lwt, &lwt_cql, lwt_qv) .await .map_err(|e| StorageError::Internal(format!("occ_write lwt: {e}")))?; if !crate::cassandra_util::lwt_applied(&result)? { @@ -448,7 +448,7 @@ impl CassandraEngine { // index statements carry the version that LWT stored, so index rows // resolve in base-row commit order, and its queue rows and stream // record keep Cassandra's timestamp (`data::version`). - let mut batch = BatchQueryBuilder::new().with_consistency(Consistency::LocalQuorum); + let mut batch = batch(); if let Some(timestamp) = mutation_timestamp { batch = batch.with_timestamp(timestamp); } @@ -544,7 +544,7 @@ impl CassandraEngine { .build() .map_err(|error| StorageError::Internal(error.to_string()))?; self.session - .batch(built) + .run_batch(built) .await .map_err(|error| StorageError::Internal(format!("occ_write batch: {error}")))?; diff --git a/crates/storage-cassandra/src/delete_table.rs b/crates/storage-cassandra/src/delete_table.rs index 052bc4e92..b4b493d0e 100644 --- a/crates/storage-cassandra/src/delete_table.rs +++ b/crates/storage-cassandra/src/delete_table.rs @@ -3,6 +3,8 @@ //! `delete_table` implementation for `CassandraEngine`. +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use cdrs_tokio::types::IntoRustByName; use extenddb_core::types::{DeleteTableInput, TableDescription}; use extenddb_storage::error::StorageError; @@ -53,7 +55,8 @@ impl CassandraEngine { let table_result = self .session - .query_with_values( + .run( + Stmt::Read, &table_query, cdrs_tokio::query_values!(account_id, input.table_name.as_str()), ) @@ -114,7 +117,11 @@ impl CassandraEngine { let index_result = self .session - .query_with_values(&index_query, cdrs_tokio::query_values!(table_id.as_str())) + .run( + Stmt::Read, + &index_query, + cdrs_tokio::query_values!(table_id.as_str()), + ) .await .map_err(|e| StorageError::Internal(format!("Query indexes: {e}")))?; @@ -156,7 +163,8 @@ impl CassandraEngine { let delete_indexes_query = format!("DELETE FROM {catalog_keyspace}.indexes WHERE table_id = ?"); self.session - .query_with_values( + .run( + Stmt::Write, &delete_indexes_query, cdrs_tokio::query_values!(table_id.as_str()), ) @@ -167,7 +175,8 @@ impl CassandraEngine { let delete_tags_query = format!("DELETE FROM {catalog_keyspace}.tags WHERE resource_arn = ?"); self.session - .query_with_values( + .run( + Stmt::Write, &delete_tags_query, cdrs_tokio::query_values!(description.table_arn.as_str()), ) diff --git a/crates/storage-cassandra/src/engine.rs b/crates/storage-cassandra/src/engine.rs index 310773934..8c86b8c2d 100644 --- a/crates/storage-cassandra/src/engine.rs +++ b/crates/storage-cassandra/src/engine.rs @@ -3,6 +3,8 @@ //! Cassandra storage engine implementation. +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use std::sync::Arc; use cdrs_tokio::authenticators::{NoneAuthenticatorProvider, StaticPasswordAuthenticatorProvider}; @@ -296,11 +298,8 @@ impl CassandraEngine { use std::sync::atomic::Ordering; self.index_delay_reads.fetch_add(1, Ordering::Relaxed); - // Read at the driver default, ONE, and `settings set` writes at ONE - // too. With replication factor above 1, each read can reach a - // different replica, so until every replica has a new value, - // successive writes can see the old and the new value in any order. - // One consistency policy for every statement is #770. + // Read at LOCAL_QUORUM, and `settings set` writes at LOCAL_QUORUM + // too (#770), so a read sees a new value once its write has returned. let query = format!( "SELECT key, value FROM {}.settings \ WHERE key IN ('index_propagation_delay_ms', 'gsi_propagation_delay_ms')", @@ -393,7 +392,11 @@ impl CassandraEngine { ); self.session - .query(cql) + .run( + Stmt::Ddl, + cql, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ) .await .map_err(|e| StorageError::Internal(format!("Failed to create keyspace: {e}")))?; @@ -405,7 +408,11 @@ impl CassandraEngine { let cql = format!("DROP KEYSPACE IF EXISTS {keyspace_name}"); self.session - .query(cql) + .run( + Stmt::Ddl, + cql, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ) .await .map_err(|e| StorageError::Internal(format!("Failed to drop keyspace: {e}")))?; @@ -418,7 +425,7 @@ impl CassandraEngine { let rows = self .session - .query_with_values(cql, query_values!(keyspace_name)) + .run(Stmt::SystemRead, cql, query_values!(keyspace_name)) .await .map_err(|e| StorageError::Internal(format!("Failed to query keyspaces: {e}")))? .response_body() diff --git a/crates/storage-cassandra/src/lib.rs b/crates/storage-cassandra/src/lib.rs index 7ba272865..db416494b 100644 --- a/crates/storage-cassandra/src/lib.rs +++ b/crates/storage-cassandra/src/lib.rs @@ -61,6 +61,8 @@ pub use config::CassandraStorageConfig; pub use engine::{CassandraEngine, CassandraSession}; pub use metadata_engine::TtlBackfillCursor; +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use cdrs_tokio::types::IntoRustByName; use extenddb_storage::hooks::{ServerRuntimeHooks, ServingRegistrar, WorkerContext}; use extenddb_storage::server_components::{BackendError, ServerComponents}; @@ -473,9 +475,17 @@ fn server_components_factory( let catalog_keyspace = format!("{}_catalog", cassandra_config.keyspace_prefix); let enc_key_query = format!("SELECT value FROM {catalog_keyspace}.settings WHERE key = 'encryption_key'"); - let enc_key_result = engine.session.query(&enc_key_query).await.map_err(|e| { - BackendError::InitializationFailed(format!("Failed to load encryption key: {e}")) - })?; + let enc_key_result = engine + .session + .run( + Stmt::Read, + &enc_key_query, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ) + .await + .map_err(|e| { + BackendError::InitializationFailed(format!("Failed to load encryption key: {e}")) + })?; let enc_key_body = enc_key_result.response_body().map_err(|e| { BackendError::InitializationFailed(format!( "Failed to parse encryption key response: {e}" diff --git a/crates/storage-cassandra/src/management_store/access_keys.rs b/crates/storage-cassandra/src/management_store/access_keys.rs index 5e2f409ae..1f2fc29f3 100755 --- a/crates/storage-cassandra/src/management_store/access_keys.rs +++ b/crates/storage-cassandra/src/management_store/access_keys.rs @@ -3,6 +3,8 @@ //! Access key, session, and caller-tag operations for `CassandraCatalogStore`. +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use crate::catalog_store::CassandraCatalogStore; use cdrs_tokio::types::IntoRustByName; use cdrs_tokio::types::blob::Blob; @@ -98,7 +100,8 @@ impl CassandraCatalogStore { let result = self .session() - .query_with_values( + .run( + Stmt::Lwt, &delete_query, cdrs_tokio::query_values!(key_id, account_id, user_name), ) diff --git a/crates/storage-cassandra/src/management_store/accounts.rs b/crates/storage-cassandra/src/management_store/accounts.rs index f861ffa9c..84e118abc 100644 --- a/crates/storage-cassandra/src/management_store/accounts.rs +++ b/crates/storage-cassandra/src/management_store/accounts.rs @@ -3,6 +3,8 @@ //! Account management operations for `CassandraCatalogStore`. +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use cdrs_tokio::types::IntoRustByName; use extenddb_storage::management_store::{AccountDetail, OpError, OpResult}; @@ -32,7 +34,11 @@ impl CassandraCatalogStore { let result = self .session() - .query_with_values(&query, cdrs_tokio::query_values!(account_id, account_name)) + .run( + Stmt::Lwt, + &query, + cdrs_tokio::query_values!(account_id, account_name), + ) .await .map_err(|e| { tracing::error!("create_account query failed: {e}"); @@ -165,7 +171,7 @@ impl CassandraCatalogStore { .await?; // Quorum commit, so the console's quorum reads see the account gone. - crate::cassandra_util::apply_lwt_quorum( + crate::cassandra_util::apply_lwt( self.session(), &format!("DELETE FROM {catalog_keyspace}.accounts WHERE account_id = ? IF EXISTS"), cdrs_tokio::query_values!(account_id), diff --git a/crates/storage-cassandra/src/management_store/dependents.rs b/crates/storage-cassandra/src/management_store/dependents.rs index d89ba17c9..b0fe1fa5b 100644 --- a/crates/storage-cassandra/src/management_store/dependents.rs +++ b/crates/storage-cassandra/src/management_store/dependents.rs @@ -23,7 +23,7 @@ use cdrs_tokio::query::QueryValues; use cdrs_tokio::query_values; use extenddb_storage::management_store::{OpError, OpResult}; -use crate::cassandra_util::{apply_lwt, apply_lwt_quorum, execute, get_column, query_rows}; +use crate::cassandra_util::{apply_lwt, execute, get_column, query_rows}; use crate::catalog_store::CassandraCatalogStore; impl CassandraCatalogStore { @@ -232,7 +232,7 @@ impl CassandraCatalogStore { let ks = self.catalog_keyspace(); let what = format!("delete {principal_type} {principal_name}"); match principal_type { - "user" => apply_lwt_quorum::( + "user" => apply_lwt::( self.session(), &format!( "DELETE FROM {ks}.iam_users WHERE account_id = ? AND user_name = ? IF EXISTS" diff --git a/crates/storage-cassandra/src/management_store/users.rs b/crates/storage-cassandra/src/management_store/users.rs index 9cadb2542..4de04f447 100644 --- a/crates/storage-cassandra/src/management_store/users.rs +++ b/crates/storage-cassandra/src/management_store/users.rs @@ -3,6 +3,8 @@ //! User management operations for `CassandraCatalogStore`. +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use crate::catalog_store::CassandraCatalogStore; use cdrs_tokio::types::IntoRustByName; use extenddb_storage::management_store::{OpError, OpResult, UserDetail}; @@ -76,7 +78,8 @@ impl CassandraCatalogStore { ); session - .query_with_values( + .run( + Stmt::Write, &policy_query, cdrs_tokio::query_values!( account_id.as_str(), @@ -319,7 +322,7 @@ impl CassandraCatalogStore { ); // Quorum commit, so the console's quorum session check sees the new hash. - crate::cassandra_util::apply_lwt_quorum( + crate::cassandra_util::apply_lwt( self.session(), &update_query, cdrs_tokio::query_values!(password_hash, account_id, user_name), diff --git a/crates/storage-cassandra/src/metadata_engine.rs b/crates/storage-cassandra/src/metadata_engine.rs index dca76da15..412b9fcfa 100755 --- a/crates/storage-cassandra/src/metadata_engine.rs +++ b/crates/storage-cassandra/src/metadata_engine.rs @@ -3,6 +3,8 @@ //! `MetadataEngine` trait implementation for `CassandraEngine`. +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use cdrs_tokio::types::IntoRustByName; use extenddb_core::types::{Item, Tag, TimeToLiveDescription, TimeToLiveStatus}; use extenddb_storage::MetadataEngine; @@ -50,9 +52,7 @@ impl CassandraEngine { let epoch_before = self .ttl_config_cache_epoch .load(std::sync::atomic::Ordering::Acquire); - let config = self - .ttl_config_for_table_at(account_id, table_name, false) - .await?; + let config = self.read_ttl_config(account_id, table_name).await?; let mut cache = self .ttl_config_cache .lock() @@ -83,27 +83,26 @@ impl CassandraEngine { .remove(&(account_id.to_owned(), table_name.to_owned())); } - /// Read TTL configuration at `LOCAL_QUORUM` for an authoritative absence - /// decision. Durable repair records must not be discharged from a stale - /// replica that still reports TTL disabled or an old generation. + /// Read TTL configuration from the catalog, not from the cache that + /// [`Self::ttl_config_for_table`] serves, for an authoritative absence + /// decision. Durable repair records must not be discharged from a cached + /// value that still reports TTL disabled or an old generation. pub(crate) async fn ttl_config_for_table_quorum( &self, account_id: &str, table_name: &str, ) -> Result, StorageError> { - self.ttl_config_for_table_at(account_id, table_name, true) - .await + self.read_ttl_config(account_id, table_name).await } - /// One implementation for both consistencies, so the legacy null-generation - /// adoption cannot drift between them. An applied adoption LWT is already - /// authoritative (Paxos), so no re-read is needed in that arm at either - /// consistency; a lost adoption race re-reads to pick up the winner. - async fn ttl_config_for_table_at( + /// The catalog read behind both TTL configuration reads, so the legacy + /// null-generation adoption cannot drift between them. An applied + /// adoption LWT is already authoritative (Paxos), so no re-read is needed + /// in that arm; a lost adoption race re-reads to pick up the winner. + async fn read_ttl_config( &self, account_id: &str, table_name: &str, - quorum: bool, ) -> Result, StorageError> { let query = format!( "SELECT ttl_attribute, ttl_generation FROM {}.tables \ @@ -113,23 +112,13 @@ impl CassandraEngine { let read = |context: &'static str| { let query = query.clone(); async move { - let rows = if quorum { - crate::cassandra_util::query_rows_quorum( - &self.session, - &query, - cdrs_tokio::query_values!(account_id, table_name), - context, - ) - .await? - } else { - crate::cassandra_util::query_rows( - &self.session, - &query, - cdrs_tokio::query_values!(account_id, table_name), - context, - ) - .await? - }; + let rows = crate::cassandra_util::query_rows( + &self.session, + &query, + cdrs_tokio::query_values!(account_id, table_name), + context, + ) + .await?; Ok::<_, StorageError>(rows.into_iter().next()) } }; @@ -1107,7 +1096,8 @@ impl MetadataEngine for CassandraEngine { "INSERT INTO {catalog}.tags (resource_arn, tag_key, tag_value) VALUES (?, ?, ?)" ); self.session_arc() - .query_with_values( + .run( + Stmt::Write, &query, cdrs_tokio::query_values!( arn.as_str(), @@ -1138,7 +1128,8 @@ impl MetadataEngine for CassandraEngine { let query = format!("DELETE FROM {catalog}.tags WHERE resource_arn = ? AND tag_key = ?"); self.session_arc() - .query_with_values( + .run( + Stmt::Write, &query, cdrs_tokio::query_values!(arn.as_str(), key.as_str()), ) @@ -1160,7 +1151,7 @@ impl MetadataEngine for CassandraEngine { format!("SELECT tag_key, tag_value FROM {catalog}.tags WHERE resource_arn = ?"); let result = self .session_arc() - .query_with_values(&query, cdrs_tokio::query_values!(arn.as_str())) + .run(Stmt::Read, &query, cdrs_tokio::query_values!(arn.as_str())) .await .map_err(|e| { tracing::error!("list_tags: {e}"); diff --git a/crates/storage-cassandra/src/password_hash_store.rs b/crates/storage-cassandra/src/password_hash_store.rs index a3d5f9658..08716200d 100644 --- a/crates/storage-cassandra/src/password_hash_store.rs +++ b/crates/storage-cassandra/src/password_hash_store.rs @@ -24,7 +24,7 @@ impl PasswordHashStore for CassandraCatalogStore { let query = format!( "SELECT password_hash FROM {catalog_keyspace}.admin_users WHERE admin_name = ?" ); - let rows = crate::cassandra_util::query_rows_quorum( + let rows = crate::cassandra_util::query_rows( &session, &query, cdrs_tokio::query_values!(admin_name.as_str()), @@ -49,7 +49,7 @@ impl PasswordHashStore for CassandraCatalogStore { "SELECT password_hash FROM {catalog_keyspace}.iam_users \ WHERE account_id = ? AND user_name = ?" ); - let rows = crate::cassandra_util::query_rows_quorum( + let rows = crate::cassandra_util::query_rows( &session, &query, cdrs_tokio::query_values!(account_id.as_str(), user_name.as_str()), diff --git a/crates/storage-cassandra/src/restore_engine.rs b/crates/storage-cassandra/src/restore_engine.rs index e157f4356..0304e45aa 100644 --- a/crates/storage-cassandra/src/restore_engine.rs +++ b/crates/storage-cassandra/src/restore_engine.rs @@ -106,7 +106,7 @@ impl CassandraEngine { attribute_definitions FROM {}.tables WHERE account_id = ? AND table_name = ?", self.catalog_keyspace() ); - let rows = crate::cassandra_util::query_rows_quorum::( + let rows = crate::cassandra_util::query_rows::( &self.session, &query, cdrs_tokio::query_values!(key.account_id.as_str(), key.table_name.as_str()), @@ -538,7 +538,7 @@ impl RestoreEngine for CassandraEngine { let account_keyspace = self.account_keyspace(&key.account_id); let data_table = data_table_name(&key.table_id); let query = format!("SELECT COUNT(*) AS c FROM {account_keyspace}.{data_table}"); - let rows = crate::cassandra_util::query_rows_quorum::( + let rows = crate::cassandra_util::query_rows::( &self.session, &query, cdrs_tokio::query_values!(), @@ -581,7 +581,7 @@ impl RestoreEngine for CassandraEngine { .map(|index| index_table_name(&index.index_id).to_lowercase()), ); for table in tables { - let rows = crate::cassandra_util::query_rows::( + let rows = crate::cassandra_util::system_read::( &self.session, "SELECT table_name FROM system_schema.tables WHERE keyspace_name = ? AND \ table_name = ?", diff --git a/crates/storage-cassandra/src/stream_engine.rs b/crates/storage-cassandra/src/stream_engine.rs index 81e0ac8de..99b8055f0 100755 --- a/crates/storage-cassandra/src/stream_engine.rs +++ b/crates/storage-cassandra/src/stream_engine.rs @@ -3,6 +3,8 @@ //! `StreamEngine` trait implementation for `CassandraEngine`. +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use cdrs_tokio::types::IntoRustByName; use extenddb_core::types::{StreamDescription, StreamRecord, StreamSummary}; use extenddb_storage::StreamEngine; @@ -39,7 +41,7 @@ impl CassandraEngine { let query = format!("SELECT account_id FROM {catalog_keyspace}.tables WHERE table_id = ?"); let result = self .session - .query_with_values(&query, cdrs_tokio::query_values!(table_id)) + .run(Stmt::Read, &query, cdrs_tokio::query_values!(table_id)) .await .map_err(|e| StorageError::Internal(e.to_string()))?; @@ -79,7 +81,7 @@ impl StreamEngine for CassandraEngine { }) } - #[allow(unused_variables)] // `after` is used in query_with_values below + #[allow(unused_variables)] // `after` is used in the records read below fn get_stream_records( &self, account_id: &str, @@ -123,9 +125,11 @@ impl StreamEngine for CassandraEngine { "SELECT table_id, starting_sequence_number, ending_sequence_number \ FROM {keyspace}.stream_shards WHERE shard_id = ?" ); - let shard_read = self - .session - .query_with_values(&shard_query, cdrs_tokio::query_values!(shard_id.as_str())); + let shard_read = self.session.run( + Stmt::Read, + &shard_query, + cdrs_tokio::query_values!(shard_id.as_str()), + ); let query = if after_sequence.is_some() { format!( @@ -143,14 +147,19 @@ impl StreamEngine for CassandraEngine { let records_read = async { if let Some(ref after) = after_sequence { self.session - .query_with_values( + .run( + Stmt::Read, &query, cdrs_tokio::query_values!(physical.as_str(), after.as_str()), ) .await } else { self.session - .query_with_values(&query, cdrs_tokio::query_values!(physical.as_str())) + .run( + Stmt::Read, + &query, + cdrs_tokio::query_values!(physical.as_str()), + ) .await } }; diff --git a/crates/storage-cassandra/src/stream_lifecycle.rs b/crates/storage-cassandra/src/stream_lifecycle.rs index fbb5dfdc1..017b7d124 100644 --- a/crates/storage-cassandra/src/stream_lifecycle.rs +++ b/crates/storage-cassandra/src/stream_lifecycle.rs @@ -44,6 +44,8 @@ use extenddb_storage::stream_lineage::{ }; use crate::CassandraEngine; +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use crate::cassandra_util::query_rows; use crate::stream_util::ZERO_SEQUENCE; @@ -352,10 +354,17 @@ impl CassandraEngine { )); } let batch = format!("BEGIN BATCH\n{}\nAPPLY BATCH", statements.join(";\n")); - self.session.query(&batch).await.map_err(|e| { - tracing::error!("insert_stream_shards batch: {e}"); - StorageError::Internal(format!("Failed to initialize stream shards: {e}")) - })?; + self.session + .run( + Stmt::Write, + &batch, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ) + .await + .map_err(|e| { + tracing::error!("insert_stream_shards batch: {e}"); + StorageError::Internal(format!("Failed to initialize stream shards: {e}")) + })?; Ok(()) } @@ -430,7 +439,9 @@ impl CassandraEngine { .last_sequence_in(account_ks, &range) .await? .unwrap_or(row.starting_sequence_number); - crate::cassandra_util::execute::( + // Not applied when an earlier close already set the ending number; + // that close's number stays. + let _closed_now = crate::cassandra_util::apply_lwt::( &self.session, &format!( "UPDATE {account_ks}.stream_shards SET ending_sequence_number = ? \ diff --git a/crates/storage-cassandra/src/table_engine.rs b/crates/storage-cassandra/src/table_engine.rs index d2ffdb56f..c256d28d1 100644 --- a/crates/storage-cassandra/src/table_engine.rs +++ b/crates/storage-cassandra/src/table_engine.rs @@ -3,6 +3,8 @@ //! `TableEngine` trait implementation for `CassandraEngine`. +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use cdrs_tokio::types::IntoRustByName; use futures::future::BoxFuture; @@ -69,14 +71,16 @@ impl TableEngine for CassandraEngine { let result = if let Some(ref start) = input.exclusive_start_table_name { self.session - .query_with_values( + .run( + Stmt::Read, &query, cdrs_tokio::query_values!(account_id.as_str(), start.as_str(), limit + 1), ) .await } else { self.session - .query_with_values( + .run( + Stmt::Read, &query, cdrs_tokio::query_values!(account_id.as_str(), limit + 1), ) diff --git a/crates/storage-cassandra/src/table_helpers.rs b/crates/storage-cassandra/src/table_helpers.rs index eb2745999..5f2a8d1c8 100644 --- a/crates/storage-cassandra/src/table_helpers.rs +++ b/crates/storage-cassandra/src/table_helpers.rs @@ -3,6 +3,8 @@ //! Helper methods for `TableEngine` operations. +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use cdrs_tokio::types::{IntoRustByName, rows::Row}; use extenddb_core::types::{ BillingMode, BillingModeSummary, GsiDescription, LsiDescription, @@ -34,7 +36,8 @@ impl CassandraEngine { let table_result = self .session - .query_with_values( + .run( + Stmt::Read, &table_query, cdrs_tokio::query_values!(account_id, table_name), ) @@ -63,7 +66,11 @@ impl CassandraEngine { let index_result = self .session - .query_with_values(&index_query, cdrs_tokio::query_values!(table_id.as_str())) + .run( + Stmt::Read, + &index_query, + cdrs_tokio::query_values!(table_id.as_str()), + ) .await .map_err(|e| StorageError::Internal(format!("Query indexes failed: {e}")))?; diff --git a/crates/storage-cassandra/src/ttl_worker.rs b/crates/storage-cassandra/src/ttl_worker.rs index c644f9a87..f388f0a3c 100644 --- a/crates/storage-cassandra/src/ttl_worker.rs +++ b/crates/storage-cassandra/src/ttl_worker.rs @@ -296,7 +296,7 @@ pub async fn reconcile_pending_older_than( }; let reconcile = match storage - .fetch_table_key_info_quorum(&account_id, &table_name) + .fetch_table_key_info(&account_id, &table_name) .await { Ok(key_info) if key_info.table_id == table_id => { @@ -325,7 +325,7 @@ pub async fn reconcile_pending_older_than( "DELETE FROM {keyspace}.ttl_reconcile_pending \ WHERE worker_partition = ? AND id = ?" ); - if let Err(error) = crate::cassandra_util::execute_quorum::( + if let Err(error) = crate::cassandra_util::execute::( &storage.session, &delete, cdrs_tokio::query_values!( @@ -378,7 +378,7 @@ pub async fn reconcile_inflight_repairs_once( let mut observed = 0usize; let mut processed = 0usize; for keyspace in crate::workers::list_account_keyspaces(storage).await? { - let registry = match crate::cassandra_util::query_rows_quorum( + let registry = match crate::cassandra_util::query_rows( &storage.session, &format!("SELECT worker_partition FROM {keyspace}.ttl_repair_inflight_partitions"), cdrs_tokio::query::QueryValues::SimpleValues(Vec::new()), @@ -433,7 +433,7 @@ pub async fn reconcile_inflight_repairs_once( FROM {keyspace}.ttl_repair_inflight \ WHERE worker_partition = ? AND repair_id <= ? LIMIT 256" ); - let mut rows = match crate::cassandra_util::query_rows_quorum::( + let mut rows = match crate::cassandra_util::query_rows::( &storage.session, &page_query, cdrs_tokio::query_values!(partition, cursor_bytes.clone()), @@ -452,7 +452,7 @@ pub async fn reconcile_inflight_repairs_once( let exhausted_forward = rows.len() < 256; if exhausted_forward { let remaining = 256 - rows.len(); - match crate::cassandra_util::query_rows_quorum::( + match crate::cassandra_util::query_rows::( &storage.session, &wrap_query, cdrs_tokio::query_values!(partition, cursor_bytes), @@ -540,7 +540,7 @@ pub async fn reconcile_inflight_repairs_once( }; let (reconcile, terminal) = match storage - .fetch_table_key_info_quorum(&account_id, &table_name) + .fetch_table_key_info(&account_id, &table_name) .await { Ok(key_info) if key_info.table_id == table_id => { @@ -576,19 +576,18 @@ pub async fn reconcile_inflight_repairs_once( "DELETE FROM {keyspace}.ttl_repair_inflight \ WHERE worker_partition = ? AND repair_id = ?" ); - if let Err(error) = - crate::cassandra_util::execute_quorum::( - &storage.session, - &delete, - cdrs_tokio::query_values!( - partition, - cdrs_tokio::types::value::Bytes::new( - repair_id.as_bytes().to_vec() - ) - ), - "retire obsolete TTL repair inflight marker", - ) - .await + if let Err(error) = crate::cassandra_util::execute::( + &storage.session, + &delete, + cdrs_tokio::query_values!( + partition, + cdrs_tokio::types::value::Bytes::new( + repair_id.as_bytes().to_vec() + ) + ), + "retire obsolete TTL repair inflight marker", + ) + .await { tracing::warn!( "TTL worker: obsolete inflight marker cleanup failed: {error}" diff --git a/crates/storage-cassandra/src/update_table.rs b/crates/storage-cassandra/src/update_table.rs index 385c522a1..116c69260 100644 --- a/crates/storage-cassandra/src/update_table.rs +++ b/crates/storage-cassandra/src/update_table.rs @@ -3,7 +3,7 @@ //! `update_table` implementation for the Cassandra backend. -use cdrs_tokio::consistency::Consistency; +use crate::cassandra_util::PolicySession as _; use cdrs_tokio::query::BatchQueryBuilder; use cdrs_tokio::query::QueryValues; use cdrs_tokio::types::IntoRustByName; @@ -110,7 +110,7 @@ impl CassandraEngine { // created with IF NOT EXISTS. See ADR-0021. let mut table_cols: Vec<(&'static str, Value)> = Vec::new(); // Separate plain batch for `indexes` (plain INSERT/DELETE, no LWT mixing issue). - let mut indexes_batch = BatchQueryBuilder::new().with_consistency(Consistency::LocalQuorum); + let mut indexes_batch = crate::cassandra_util::batch(); let mut indexes_batch_has_statements = false; macro_rules! add_update { @@ -659,7 +659,7 @@ impl CassandraEngine { if indexes_batch_has_statements && let Err(e) = self .session - .batch( + .run_batch( indexes_batch .build() .map_err(|e| StorageError::Internal(e.to_string()))?, diff --git a/crates/storage-cassandra/src/worker_store.rs b/crates/storage-cassandra/src/worker_store.rs index 19d2c9ffc..eb18ee355 100755 --- a/crates/storage-cassandra/src/worker_store.rs +++ b/crates/storage-cassandra/src/worker_store.rs @@ -3,6 +3,8 @@ //! `WorkerStore` trait implementation and control plane transition processing. +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use cdrs_tokio::types::IntoRustByName; use futures::future::BoxFuture; @@ -52,16 +54,13 @@ impl CassandraEngine { ALLOW FILTERING" ); - let result = - self.session.query(&query).await.map_err(|e| { - StorageError::Internal(format!("Failed to query CREATING tables: {e}")) - })?; - - let body = result.response_body().map_err(|e| { - StorageError::Internal(format!("Failed to parse CREATING tables response: {e}")) - })?; - - let rows = body.into_rows().unwrap_or_default(); + let rows: Vec = crate::cassandra_util::query_rows( + &self.session, + &query, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + "Failed to query CREATING tables", + ) + .await?; for row in rows { let account_id: String = row @@ -95,16 +94,13 @@ impl CassandraEngine { ALLOW FILTERING" ); - let result = - self.session.query(&query).await.map_err(|e| { - StorageError::Internal(format!("Failed to query DELETING tables: {e}")) - })?; - - let body = result.response_body().map_err(|e| { - StorageError::Internal(format!("Failed to parse DELETING tables response: {e}")) - })?; - - let rows = body.into_rows().unwrap_or_default(); + let rows: Vec = crate::cassandra_util::query_rows( + &self.session, + &query, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + "Failed to query DELETING tables", + ) + .await?; for row in rows { let account_id: String = row @@ -123,7 +119,11 @@ impl CassandraEngine { // Delete tags let tag_delete = format!("DELETE FROM {catalog_keyspace}.tags WHERE resource_arn = ?"); self.session - .query_with_values(&tag_delete, cdrs_tokio::query_values!(table_arn.as_str())) + .run( + Stmt::Write, + &tag_delete, + cdrs_tokio::query_values!(table_arn.as_str()), + ) .await .map_err(|e| StorageError::Internal(format!("Failed to delete tags: {e}")))?; diff --git a/crates/storage-cassandra/src/workers.rs b/crates/storage-cassandra/src/workers.rs index 4313c6473..ff2b83cca 100644 --- a/crates/storage-cassandra/src/workers.rs +++ b/crates/storage-cassandra/src/workers.rs @@ -3,6 +3,7 @@ //! Cassandra-specific background workers. +use crate::cassandra_util::PolicySession as _; use std::sync::Arc; use std::time::Duration; @@ -189,19 +190,13 @@ pub(crate) async fn list_account_keyspaces( engine: &CassandraEngine, ) -> Result, extenddb_storage::error::StorageError> { let prefix = format!("{}_account_", engine.keyspace_prefix); - let rows = engine - .session - .query("SELECT keyspace_name FROM system_schema.keyspaces") - .await - .map_err(|e| { - extenddb_storage::error::StorageError::Internal(format!("list keyspaces: {e}")) - })? - .response_body() - .map_err(|e| { - extenddb_storage::error::StorageError::Internal(format!("list keyspaces body: {e}")) - })? - .into_rows() - .unwrap_or_default(); + let rows: Vec = crate::cassandra_util::system_read( + &engine.session, + "SELECT keyspace_name FROM system_schema.keyspaces", + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + "list keyspaces", + ) + .await?; use cdrs_tokio::types::IntoRustByName as _; let mut keyspaces = Vec::new(); @@ -552,8 +547,6 @@ async fn gsi_apply_index( delete_index_row_multi, insert_index_row_multi, item_has_index_keys, project_item_for_index, same_index_row, }; - use cdrs_tokio::consistency::Consistency; - use cdrs_tokio::query::BatchQueryBuilder; let idx = &context.index; let idx_table = crate::data::ddl::index_table_name(&idx.index_id); @@ -563,7 +556,7 @@ async fn gsi_apply_index( // The entry's stamp is the base-row version its write committed, so a // later version's tombstone beats an earlier version's insert on the index // table even when the worker applies the entries in the other order. - let mut batch = BatchQueryBuilder::new().with_consistency(Consistency::LocalQuorum); + let mut batch = crate::cassandra_util::batch(); if let Some(stamp) = context.index_stamp { batch = batch.with_timestamp(stamp); } @@ -621,7 +614,7 @@ async fn gsi_apply_index( .build() .map_err(|e| extenddb_storage::error::StorageError::Internal(e.to_string()))?; if !built.request.queries.is_empty() { - engine.session.batch(built).await.map_err(|e| { + engine.session.run_batch(built).await.map_err(|e| { extenddb_storage::error::StorageError::Internal(format!("gsi_apply: {e}")) })?; } diff --git a/crates/storage-cassandra/tests/consistency_policy.rs b/crates/storage-cassandra/tests/consistency_policy.rs new file mode 100644 index 000000000..2e712c781 --- /dev/null +++ b/crates/storage-cassandra/tests/consistency_policy.rs @@ -0,0 +1,660 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Every statement outside the consistency policy runs through it (#770). +//! +//! `cassandra_util` sets the consistency level of every statement: `Stmt` and +//! `params` for one statement, `batch` for a batch, and `PolicySession::run` +//! to send it. A driver call that builds its own parameters, or sends a +//! statement with the driver's default level (`ONE`), would bypass that. This +//! test reads the crate's non-test source and fails on each such call. +//! +//! Two escapes are deliberate. Files that set their own levels on purpose are +//! exempt by path, each with a reason. And one call may opt out with a +//! `// consistency-policy-ok: ` comment on its line or the line above. + +use std::path::{Path, PathBuf}; + +/// Driver methods that send a statement or a batch, and what to use instead. +/// [`forbidden`] matches each one as a method call (`.m(`), a method call +/// with type arguments (`.m::<`), a path call (`Session::m(&s, …)`), and a +/// method taken as a value (`let send = Session::m;`). +const SEND_METHODS: &[(&str, &str)] = &[ + ("query", "PolicySession::run"), + ("query_with_values", "PolicySession::run"), + ("query_with_params", "PolicySession::run"), + ("exec", "PolicySession::run"), + ("exec_with_values", "PolicySession::run"), + ("exec_with_params", "PolicySession::run"), + ("batch", "PolicySession::run_batch"), + ("batch_with_params", "PolicySession::run_batch"), + // `session.paged(n)` returns a pager that sends at the default level. + ("paged", "PolicySession::run"), + ("query_with_pager_state", "PolicySession::run"), + ("query_with_pager_state_params", "PolicySession::run"), + ("exec_with_pager_state", "PolicySession::run"), +]; + +/// The characters that can follow a method taken as a value, such as +/// `Session::query_with_values;` or `.map(Session::query)`. The end of a line +/// ends it too: rustfmt can put the method path last on a line. Text such as +/// `cdrs_tokio::query::QueryBatch` continues with `::` and is not a method. +const VALUE_END_CHARS: &str = ";,)]} \t"; + +/// Other text that bypasses the policy, and what to use instead. +const FORBIDDEN_TEXT: &[(&str, &str)] = &[ + ("StatementParamsBuilder::new(", "cassandra_util::params"), + ("BatchQueryBuilder::new(", "cassandra_util::batch"), + ("BatchQueryBuilder::default(", "cassandra_util::batch"), + ("QueryBatch::new(", "cassandra_util::batch"), + ("Consistency::", "a Stmt kind"), + // A raw request frame on a connection, as `migrations/agreement.rs` sends. + ("Envelope::new_req_query(", "PolicySession::run"), + ("Envelope::new_req_execute(", "PolicySession::run"), + ("Envelope::new_req_batch(", "PolicySession::run_batch"), + ("Envelope::new_query(", "PolicySession::run"), + ("BodyReqQuery::new(", "PolicySession::run"), + ("BodyReqBatch::new(", "PolicySession::run_batch"), + // The driver functions that send a frame to the nodes of a query plan, + // or to one connection. + ("send_envelope(", "PolicySession::run"), + ("write_envelope(", "PolicySession::run"), + // The driver call that gives a raw connection to a node, and the + // constructor of a request frame that has no level checked. + ("persistent_connection(", "PolicySession::run"), + ("Envelope::new(", "PolicySession::run"), +]; + +/// Text that contains a forbidden pattern but is the policy's own API. The +/// scan blanks it out before it matches. +const ALLOWED: &[&str] = &["cassandra_util::batch(", "cassandra_util::batch;"]; + +/// Each forbidden pattern, and what to use instead. +fn forbidden() -> Vec<(String, &'static str)> { + let mut patterns = Vec::new(); + for (method, instead) in SEND_METHODS { + for form in [".{m}(", ".{m}::<", "::{m}(", "::{m}::<"] { + patterns.push((form.replace("{m}", method), *instead)); + } + // A method taken as a value. The `$` ends the pattern: it matches + // only when [`VALUE_END_CHARS`] or the end of the line follows. + patterns.push((format!("::{method}$"), *instead)); + } + for (text, instead) in FORBIDDEN_TEXT { + patterns.push(((*text).to_owned(), *instead)); + } + patterns +} + +/// Calls that bypass the policy, each with the pattern that must find it. +/// A pattern removed from [`SEND_METHODS`], [`FORBIDDEN_TEXT`] or the call +/// forms in [`forbidden`] fails `the_scan_finds_each_known_bypass`. +const KNOWN_BYPASSES: &[(&str, &str)] = &[ + (r#"session.query("SELECT a FROM t").await"#, ".query("), + ( + "session.query_with_values(q, values).await", + ".query_with_values(", + ), + ( + "session.query_with_params(q, params).await", + ".query_with_params(", + ), + ("session.exec(&prepared).await", ".exec("), + ( + "session.exec_with_values(&prepared, values).await", + ".exec_with_values(", + ), + ( + "session.exec_with_params(&prepared, ¶ms).await", + ".exec_with_params(", + ), + ("session.batch(built).await", ".batch("), + ( + "session.batch_with_params(built, params).await", + ".batch_with_params(", + ), + ("let pager = session.paged(100);", ".paged("), + ( + "pager.query_with_pager_state(q, state)", + ".query_with_pager_state(", + ), + ( + "pager.query_with_pager_state_params(q, state, params)", + ".query_with_pager_state_params(", + ), + ( + "pager.exec_with_pager_state(&prepared, state)", + ".exec_with_pager_state(", + ), + ("Session::query(&session, cql).await", "::query("), + ( + "CassandraSession::query_with_values(&session, q, values).await", + "::query_with_values(", + ), + ("Session::batch(&session, built).await", "::batch("), + ("session.query::(cql).await", ".query::<"), + ( + "Session::query::(&session, cql).await", + "::query::<", + ), + ( + "let p = StatementParamsBuilder::new().build();", + "StatementParamsBuilder::new(", + ), + ( + "let b = BatchQueryBuilder::new();", + "BatchQueryBuilder::new(", + ), + ( + "let b = BatchQueryBuilder::default();", + "BatchQueryBuilder::default(", + ), + ("let b = QueryBatch::new(r, m);", "QueryBatch::new("), + ("let level = Consistency::One;", "Consistency::"), + ( + "let e = Envelope::new_req_query(q, level, None, false, version);", + "Envelope::new_req_query(", + ), + ( + "let e = Envelope::new_req_execute(id, None, ¶ms, flags, version);", + "Envelope::new_req_execute(", + ), + ( + "let e = Envelope::new_req_batch(built, flags, version);", + "Envelope::new_req_batch(", + ), + ( + "let e = Envelope::new_query(body, flags, version);", + "Envelope::new_query(", + ), + ( + "let body = BodyReqQuery::new(q, Default::default(), None, false, None, None, None, None, None, None);", + "BodyReqQuery::new(", + ), + ( + "let body = BodyReqBatch::new(queries, kind, level, serial, None, None);", + "BodyReqBatch::new(", + ), + ( + "send_envelope(plan.into_iter(), &envelope, true, retry).await", + "send_envelope(", + ), + ( + "connection.write_envelope(&envelope, false).await", + "write_envelope(", + ), + ( + "let connection = node.persistent_connection().await?;", + "persistent_connection(", + ), + ( + "let e = Envelope::new(version, flags, opcode, stream, body, tracing_id);", + "Envelope::new(", + ), + ( + "let send = CassandraSession::query_with_values;", + "::query_with_values$", + ), + ("let send = Session::batch;", "::batch$"), + ("run_all(rows, Session::query)", "::query$"), + ("let f = (Session::exec, Session::paged);", "::exec$"), + ( + "let f = [Session::query_with_params];", + "::query_with_params$", + ), +]; + +/// Source paths, relative to the crate, that set their own levels. +/// +/// Each entry states why, because an unexplained exemption is how a check +/// becomes decoration. +const EXEMPT: &[(&str, &str)] = &[ + ( + "src/cassandra_util.rs", + "the policy itself: Stmt, params, batch and PolicySession::run set every level", + ), + ( + "src/migrations/", + "migrations set their own levels: QUORUM, SERIAL, ALL and LOCAL_QUORUM, each at \ + least as strong as the policy's level, and ONE only for reads of node-local \ + system tables (system.local, system_schema, system_views)", + ), +]; + +/// A trailing comment that lets one line keep a forbidden call. +const MARKER: &str = "// consistency-policy-ok:"; + +fn crate_root() -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) +} + +fn rust_files(dir: &Path, out: &mut Vec) { + let entries = std::fs::read_dir(dir).unwrap_or_else(|e| panic!("{}: {e}", dir.display())); + for entry in entries.flatten() { + let path = entry.path(); + if path.is_dir() { + rust_files(&path, out); + } else if path.extension().is_some_and(|e| e == "rs") { + out.push(path); + } + } +} + +/// `source` with comments blanked out and each `#[cfg(test)] mod … { … }` +/// removed. Newlines stay, so line numbers do not move. String and char +/// literals are kept, and `//` inside a string is not a comment. +fn code_only(source: &str) -> String { + let chars: Vec = source.chars().collect(); + let mut out = String::with_capacity(source.len()); + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + let next = chars.get(i + 1).copied(); + if c == '/' && next == Some('/') { + while i < chars.len() && chars[i] != '\n' { + i += 1; + } + } else if c == '/' && next == Some('*') { + i += 2; + while i < chars.len() && !(chars[i] == '*' && chars.get(i + 1) == Some(&'/')) { + if chars[i] == '\n' { + out.push('\n'); + } + i += 1; + } + i += 2; + } else if let Some(hashes) = raw_string_start(&chars, i) { + // r"…" or r#"…"#: ends at a quote followed by the same hashes. + let close: Vec = std::iter::once('"') + .chain(std::iter::repeat_n('#', hashes)) + .collect(); + let body = i + 2 + hashes; + out.extend(&chars[i..body]); + i = body; + while i < chars.len() && !chars[i..].starts_with(&close) { + out.push(chars[i]); + i += 1; + } + out.extend(chars[i..].iter().take(close.len())); + i += close.len(); + } else if c == '"' { + out.push(c); + i += 1; + while i < chars.len() && chars[i] != '"' { + if chars[i] == '\\' { + out.push(chars[i]); + i += 1; + } + if i < chars.len() { + out.push(chars[i]); + i += 1; + } + } + if i < chars.len() { + out.push('"'); + i += 1; + } + } else if c == '\'' && (chars.get(i + 2) == Some(&'\'') || next == Some('\\')) { + // A char literal such as '"' or '\n', which must not open a string. + out.push(c); + i += 1; + while i < chars.len() && chars[i] != '\'' { + if chars[i] == '\\' { + out.push(chars[i]); + i += 1; + } + out.push(chars[i]); + i += 1; + } + out.push('\''); + i += 1; + } else { + out.push(c); + i += 1; + } + } + without_test_modules(&out) +} + +/// The number of `#` in the raw string literal that starts at `i`, or `None` +/// when no raw string starts there. `r` must not end an identifier. +fn raw_string_start(chars: &[char], i: usize) -> Option { + if chars[i] != 'r' || i > 0 && (chars[i - 1].is_alphanumeric() || chars[i - 1] == '_') { + return None; + } + let hashes = chars[i + 1..].iter().take_while(|c| **c == '#').count(); + (chars.get(i + 1 + hashes) == Some(&'"')).then_some(hashes) +} + +/// The index after the string, raw string or char literal that starts at +/// `chars[i]`, or `None` when no literal starts there. A `'` that starts a +/// lifetime is not a literal. +fn literal_end(chars: &[char], i: usize) -> Option { + if let Some(hashes) = raw_string_start(chars, i) { + let close: Vec = std::iter::once('"') + .chain(std::iter::repeat_n('#', hashes)) + .collect(); + let mut j = i + 2 + hashes; + while j < chars.len() && !chars[j..].starts_with(&close) { + j += 1; + } + return Some((j + close.len()).min(chars.len())); + } + let is_char_literal = + chars[i] == '\'' && (chars.get(i + 2) == Some(&'\'') || chars.get(i + 1) == Some(&'\\')); + if chars[i] == '"' || is_char_literal { + let quote = chars[i]; + let mut j = i + 1; + while j < chars.len() && chars[j] != quote { + j += if chars[j] == '\\' { 2 } else { 1 }; + } + return Some((j + 1).min(chars.len())); + } + None +} + +/// `code` with each `#[cfg(test)]` attribute followed by `mod NAME {` removed +/// up to its closing brace, keeping the newlines. An attribute inside a +/// string literal is not an attribute. +fn without_test_modules(code: &str) -> String { + let attribute: Vec = "#[cfg(test)]".chars().collect(); + let chars: Vec = code.chars().collect(); + let mut out = String::with_capacity(code.len()); + let mut i = 0; + while i < chars.len() { + if let Some(end) = literal_end(&chars, i) { + out.extend(&chars[i..end]); + i = end; + continue; + } + if chars[i..].starts_with(&attribute) { + let after = i + attribute.len(); + let rest: String = chars[after..].iter().collect(); + let brace = rest.find('{'); + let is_module = rest.trim_start().starts_with("mod ") + && brace.is_some_and(|brace| { + rest[..brace].trim_start().starts_with("mod ") && !rest[..brace].contains(';') + }); + if let (true, Some(brace)) = (is_module, brace) { + let open = after + rest[..brace].chars().count(); + let end = open + block_len(&chars[open..]); + out.extend(chars[i..end].iter().filter(|c| **c == '\n')); + i = end; + continue; + } + } + out.push(chars[i]); + i += 1; + } + out +} + +/// The length in chars of the block that `chars` starts with: up to and +/// including the `}` that closes its first `{`, or all of `chars` when no `}` +/// does. A brace inside a string, a raw string or a char literal does not +/// count. The text has no comments (see [`code_only`]). +fn block_len(chars: &[char]) -> usize { + let mut depth = 0_usize; + let mut i = 0; + while i < chars.len() { + if let Some(end) = literal_end(chars, i) { + i = end; + continue; + } + match chars[i] { + '{' => depth += 1, + '}' => { + depth = depth.saturating_sub(1); + if depth == 0 { + return i + 1; + } + } + _ => {} + } + i += 1; + } + chars.len() +} + +/// Each forbidden call in `source`: its line number, the call, and what to +/// use instead. A call is skipped when [`MARKER`] is on its line or on the +/// line above it (where `cargo fmt` keeps a comment). +fn bypasses(source: &str) -> Vec<(usize, String, &'static str)> { + let originals: Vec<&str> = source.lines().collect(); + let marked = |index: usize| originals.get(index).is_some_and(|l| l.contains(MARKER)); + let patterns = forbidden(); + let mut found = Vec::new(); + for (index, line) in code_only(source).lines().enumerate() { + if marked(index) || index > 0 && marked(index - 1) { + continue; + } + let mut line = line.to_owned(); + for allowed in ALLOWED { + line = line.replace(allowed, &" ".repeat(allowed.len())); + } + for (pattern, instead) in &patterns { + if matches_pattern(&line, pattern) { + found.push((index + 1, pattern.clone(), *instead)); + } + } + } + found +} + +/// Whether `line` holds `pattern`. A pattern that ends in `$` must be +/// followed by one of [`VALUE_END_CHARS`] or by the end of the line. +fn matches_pattern(line: &str, pattern: &str) -> bool { + match pattern.strip_suffix('$') { + None => line.contains(pattern), + Some(prefix) => line.match_indices(prefix).any(|(at, _)| { + line[at + prefix.len()..] + .chars() + .next() + .is_none_or(|c| VALUE_END_CHARS.contains(c)) + }), + } +} + +fn exempt(relative: &str) -> bool { + EXEMPT.iter().any(|(path, _)| { + if path.ends_with('/') { + relative.starts_with(path) + } else { + relative == *path + } + }) +} + +#[test] +fn no_statement_bypasses_the_consistency_policy() { + let root = crate_root(); + let mut files = Vec::new(); + rust_files(&root.join("src"), &mut files); + files.sort(); + assert!( + !files.is_empty(), + "no source files under {}", + root.display() + ); + + let mut problems = Vec::new(); + for file in &files { + let relative = file + .strip_prefix(&root) + .expect("under the crate") + .to_string_lossy() + .replace('\\', "/"); + if exempt(&relative) { + continue; + } + let source = std::fs::read_to_string(file).expect("readable source"); + for (line, call, instead) in bypasses(&source) { + problems.push(format!("{relative}:{line}: `{call}`; use {instead}")); + } + } + assert!( + problems.is_empty(), + "{} statement(s) bypass the consistency policy in cassandra_util:\n{}", + problems.len(), + problems.join("\n") + ); +} + +#[test] +fn each_exempt_path_exists() { + let root = crate_root(); + for (path, reason) in EXEMPT { + assert!(!reason.is_empty(), "{path} has no reason"); + assert!( + root.join(path.trim_end_matches('/')).exists(), + "{path} is exempt but does not exist; remove the entry" + ); + } +} + +#[test] +fn the_scan_finds_each_forbidden_call() { + for (call, _) in forbidden() { + let source = match call.strip_suffix('$') { + Some(prefix) => format!("fn f() {{\n let x = y{prefix}\n}}\n"), + None => format!("fn f() {{\n let x = y{call}a);\n}}\n"), + }; + let found = bypasses(&source); + assert!( + found.iter().any(|(line, c, _)| *line == 2 && *c == call), + "{call} was not found: {found:?}" + ); + } +} + +#[test] +fn the_scan_finds_each_known_bypass() { + for (bypass, pattern) in KNOWN_BYPASSES { + let source = format!("fn f() {{\n {bypass}\n}}\n"); + let found = bypasses(&source); + assert!( + found.iter().any(|(line, p, _)| *line == 2 && p == pattern), + "`{pattern}` did not find `{bypass}`: {found:?}" + ); + } +} + +#[test] +fn the_scan_allows_the_policy_batch_builder() { + let source = "use crate::cassandra_util::batch;\nfn f() {\n \ + let b = crate::cassandra_util::batch();\n \ + let c = cassandra_util::batch().add_query(q, v);\n}\n"; + assert_eq!( + bypasses(source), + [], + "cassandra_util::batch() is the policy" + ); +} + +#[test] +fn the_scan_skips_comments_test_modules_and_marked_lines() { + let source = r##" +// session.query("x") +/* session.query_with_values("x", v) */ +/// Use `BatchQueryBuilder::new()` here. +fn f() { + let s = "http://example//not.a.comment"; + let c = '"'; + let raw = r#"a "b" // c"#; session.query("x"); + session.run(Stmt::Read, "SELECT a FROM t", v); // not .query( + let b = QueryBatch::new(r, m); // consistency-policy-ok: on the same line + // consistency-policy-ok: on the line above + let b = QueryBatch::new(r, m); +} +#[cfg(test)] +mod tests { + fn g() { session.query("x"); let b = BatchQueryBuilder::new(); } +} +fn h() { + session.query_with_values("x", v); +} +"##; + let found = bypasses(source); + assert_eq!( + found + .iter() + .map(|(line, call, _)| (*line, call.as_str())) + .collect::>(), + [(8, ".query("), (19, ".query_with_values(")], + "{found:?}" + ); +} + +#[test] +fn a_brace_in_a_literal_does_not_hide_the_code_after_a_test_module() { + let source = r##" +#[cfg(test)] +mod tests { + fn g() { let a = "{"; let b = '{'; let c = r#"{ " {"#; let d = "\"{"; } +} +fn h() { + session.query("x"); +} +"##; + let found = bypasses(source); + assert_eq!( + found + .iter() + .map(|(line, call, _)| (*line, call.as_str())) + .collect::>(), + [(7, ".query(")], + "{found:?}" + ); +} + +#[test] +fn a_brace_in_a_literal_does_not_end_a_test_module_early() { + let source = r##" +#[cfg(test)] +mod tests { + fn g() { let a = "}"; let b = '}'; let c = r#"} " }"#; session.query("x"); } +} +"##; + assert_eq!(bypasses(source), [], "the call is in the test module"); +} + +#[test] +fn the_scan_finds_a_method_taken_as_a_value_at_the_end_of_a_line() { + // rustfmt writes a long `if` expression with the method on its own line. + let source = "fn f() {\n let send = if paged {\n \ + CassandraSession::query_with_values\n } else {\n \ + CassandraSession::query\n };\n \ + let all = [CassandraSession::batch];\n}\n"; + let found = bypasses(source); + assert_eq!( + found + .iter() + .map(|(line, call, _)| (*line, call.as_str())) + .collect::>(), + [ + (3, "::query_with_values$"), + (5, "::query$"), + (7, "::batch$") + ], + "{found:?}" + ); +} + +#[test] +fn a_test_module_attribute_inside_a_string_does_not_hide_the_code_after_it() { + let source = r##" +const SAMPLE: &str = "#[cfg(test)] mod x {"; +fn h() { + session.query("x"); +} +"##; + let found = bypasses(source); + assert_eq!( + found + .iter() + .map(|(line, call, _)| (*line, call.as_str())) + .collect::>(), + [(4, ".query(")], + "{found:?}" + ); +} diff --git a/crates/storage-cassandra/tests/direct/backup_engine.rs b/crates/storage-cassandra/tests/direct/backup_engine.rs index 559af9556..038529a83 100644 --- a/crates/storage-cassandra/tests/direct/backup_engine.rs +++ b/crates/storage-cassandra/tests/direct/backup_engine.rs @@ -1685,7 +1685,7 @@ async fn provision_account(engine: &CassandraEngine, account_id: &str) { /// The columns and tables catalog migration 6 adds are absent from /// `keyspace`, and migration 1's restore registration columns are present. async fn assert_catalog_lacks_migration_6(engine: &CassandraEngine, keyspace: &str) { - let rows = extenddb_storage_cassandra::cassandra_util::query_rows::( + let rows = extenddb_storage_cassandra::cassandra_util::system_read::( &engine.session_arc(), "SELECT column_name FROM system_schema.columns WHERE keyspace_name = ?", cdrs_tokio::query_values!(keyspace), @@ -1717,7 +1717,7 @@ async fn assert_catalog_lacks_migration_6(engine: &CassandraEngine, keyspace: &s ] { assert!(!columns.iter().any(|c| c == added), "{added} present"); } - let tables = extenddb_storage_cassandra::cassandra_util::query_rows::( + let tables = extenddb_storage_cassandra::cassandra_util::system_read::( &engine.session_arc(), "SELECT table_name FROM system_schema.tables WHERE keyspace_name = ?", cdrs_tokio::query_values!(keyspace), @@ -1872,7 +1872,7 @@ async fn orphan_restore_target( /// The names of the tables in `keyspace`, read from `system_schema`. async fn table_names_in(engine: &CassandraEngine, keyspace: &str) -> BTreeSet { use cdrs_tokio::types::IntoRustByName; - let rows = extenddb_storage_cassandra::cassandra_util::query_rows::( + let rows = extenddb_storage_cassandra::cassandra_util::system_read::( &engine.session_arc(), "SELECT table_name FROM system_schema.tables WHERE keyspace_name = ?", cdrs_tokio::query_values!(keyspace), @@ -2804,7 +2804,7 @@ async fn job_record( Option, ) { use cdrs_tokio::types::IntoRustByName; - let rows = extenddb_storage_cassandra::cassandra_util::query_rows_quorum::( + let rows = extenddb_storage_cassandra::cassandra_util::query_rows::( &engine.session_arc(), &format!( "SELECT restore_status, restore_kind, restore_owner_generation, restore_heartbeat_at, \ @@ -3220,7 +3220,7 @@ async fn test_an_abandoned_in_catalog_create_is_reported_once_stale_and_deleted( engine.account_keyspace(&account_id) ); for bucket in 0..4_i32 { - let rows = extenddb_storage_cassandra::cassandra_util::query_rows_quorum::( + let rows = extenddb_storage_cassandra::cassandra_util::query_rows::( &engine.session_arc(), &probe, cdrs_tokio::query_values!(backup_arn.as_str(), bucket), @@ -3914,7 +3914,7 @@ async fn test_a_failed_record_whose_target_is_deleting_is_listed_once_stale_and_ /// Whether `table` exists in `account_id`'s keyspace. async fn data_table_exists(engine: &CassandraEngine, account_id: &str, table: &str) -> bool { - !extenddb_storage_cassandra::cassandra_util::query_rows::( + !extenddb_storage_cassandra::cassandra_util::system_read::( &engine.session_arc(), "SELECT table_name FROM system_schema.tables WHERE keyspace_name = ? AND table_name = ?", cdrs_tokio::query_values!(engine.account_keyspace(account_id), table), @@ -3934,7 +3934,7 @@ async fn create_row_write_times( account_id: &str, ) -> Option<(Option, Option, String)> { use cdrs_tokio::types::IntoRustByName; - let rows = extenddb_storage_cassandra::cassandra_util::query_rows_quorum::( + let rows = extenddb_storage_cassandra::cassandra_util::query_rows::( &engine.session_arc(), &format!( "SELECT WRITETIME(heartbeat_at) AS beat, WRITETIME(backup_name) AS inserted, \ @@ -4078,7 +4078,7 @@ async fn raw_index_entries(engine: &CassandraEngine, row: &BackupRow) -> usize { ), ), ] { - let rows = extenddb_storage_cassandra::cassandra_util::query_rows_quorum::( + let rows = extenddb_storage_cassandra::cassandra_util::query_rows::( &engine.session_arc(), &cql, values, @@ -4094,7 +4094,7 @@ async fn raw_index_entries(engine: &CassandraEngine, row: &BackupRow) -> usize { /// Items of `backup_arn`'s payload in `account_id`'s keyspace, all buckets. async fn payload_item_count(engine: &CassandraEngine, account_id: &str, backup_arn: &str) -> i64 { use cdrs_tokio::types::IntoRustByName; - let rows = extenddb_storage_cassandra::cassandra_util::query_rows_quorum::( + let rows = extenddb_storage_cassandra::cassandra_util::query_rows::( &engine.session_arc(), &format!( "SELECT COUNT(*) AS n FROM {}.backup_items WHERE backup_arn = ? ALLOW FILTERING", @@ -4118,7 +4118,7 @@ async fn backup_status_of( backup_arn: &str, ) -> Option { use cdrs_tokio::types::IntoRustByName; - extenddb_storage_cassandra::cassandra_util::query_rows_quorum::( + extenddb_storage_cassandra::cassandra_util::query_rows::( &engine.session_arc(), &format!( "SELECT backup_status FROM {}.backups_by_arn WHERE account_id = ? AND backup_arn = ?", @@ -4645,7 +4645,7 @@ async fn test_a_migration_6_that_fails_in_its_backfill_stays_pending_and_resumes #[cfg(feature = "test-hooks")] async fn target_item_count(engine: &CassandraEngine, account_id: &str, table_id: &str) -> i64 { use cdrs_tokio::types::IntoRustByName; - let rows = extenddb_storage_cassandra::cassandra_util::query_rows_quorum::( + let rows = extenddb_storage_cassandra::cassandra_util::query_rows::( &engine.session_arc(), &format!( "SELECT COUNT(*) AS n FROM {}.items_{}", @@ -4870,7 +4870,7 @@ async fn test_a_target_claimed_to_deleting_stops_the_restore_copy_at_its_next_he assert_eq!(after, generation); let (table_status,): (Option,) = { use cdrs_tokio::types::IntoRustByName; - let rows = extenddb_storage_cassandra::cassandra_util::query_rows_quorum::( + let rows = extenddb_storage_cassandra::cassandra_util::query_rows::( &engine.session_arc(), &format!( "SELECT table_status FROM {}.tables WHERE account_id = ? AND table_name = ?", @@ -5319,7 +5319,7 @@ async fn status_entry( status: BackupStatus, arn: &str, ) -> Option<(String, String)> { - let rows = extenddb_storage_cassandra::cassandra_util::query_rows_quorum::( + let rows = extenddb_storage_cassandra::cassandra_util::query_rows::( &engine.session_arc(), &format!( "SELECT store_kind, store_id FROM {}.backup_index_by_status \ @@ -8062,7 +8062,7 @@ async fn registrations( ) -> std::collections::HashMap { use cdrs_tokio::types::AsRust; use cdrs_tokio::types::IntoRustByName; - let rows = extenddb_storage_cassandra::cassandra_util::query_rows_quorum::( + let rows = extenddb_storage_cassandra::cassandra_util::query_rows::( &engine.session_arc(), &format!( "SELECT active_restores FROM {}.backups_by_arn \ @@ -9136,7 +9136,7 @@ async fn index_rows( index_name: &str, ) -> i64 { use cdrs_tokio::types::IntoRustByName; - let rows = extenddb_storage_cassandra::cassandra_util::query_rows_quorum::( + let rows = extenddb_storage_cassandra::cassandra_util::query_rows::( &engine.session_arc(), &format!( "SELECT index_id FROM {}.indexes WHERE table_id = ? AND index_name = ?", @@ -9154,7 +9154,7 @@ async fn index_rows( .ok() .flatten() .expect("index_id"); - let rows = extenddb_storage_cassandra::cassandra_util::query_rows_quorum::( + let rows = extenddb_storage_cassandra::cassandra_util::query_rows::( &engine.session_arc(), &format!( "SELECT COUNT(*) AS c FROM {}.{}", @@ -9192,18 +9192,17 @@ async fn stamps_by_sk( table_id.replace('-', "_") ), Some(index_name) => { - let rows = - extenddb_storage_cassandra::cassandra_util::query_rows_quorum::( - &engine.session_arc(), - &format!( - "SELECT index_id FROM {}.indexes WHERE table_id = ? AND index_name = ?", - engine.catalog_keyspace() - ), - cdrs_tokio::query_values!(table_id, index_name), - "index id", - ) - .await - .expect("read the index"); + let rows = extenddb_storage_cassandra::cassandra_util::query_rows::( + &engine.session_arc(), + &format!( + "SELECT index_id FROM {}.indexes WHERE table_id = ? AND index_name = ?", + engine.catalog_keyspace() + ), + cdrs_tokio::query_values!(table_id, index_name), + "index id", + ) + .await + .expect("read the index"); let index_id: String = rows .first() .expect("the index exists") @@ -9217,7 +9216,7 @@ async fn stamps_by_sk( ) } }; - let rows = extenddb_storage_cassandra::cassandra_util::query_rows_quorum::( + let rows = extenddb_storage_cassandra::cassandra_util::query_rows::( &engine.session_arc(), &cql, cdrs_tokio::query_values!(), @@ -10258,7 +10257,7 @@ async fn test_a_beat_between_the_takeovers_read_and_its_write_refuses_the_takeov #[cfg(feature = "test-hooks")] async fn base_rows(engine: &CassandraEngine, account_id: &str, table_id: &str) -> i64 { use cdrs_tokio::types::IntoRustByName; - let rows = extenddb_storage_cassandra::cassandra_util::query_rows_quorum::( + let rows = extenddb_storage_cassandra::cassandra_util::query_rows::( &engine.session_arc(), &format!( "SELECT COUNT(item_data) AS c FROM {}.items_{}", @@ -10475,7 +10474,7 @@ async fn live_versions_by_sk( table_id: &str, ) -> BTreeMap { use cdrs_tokio::types::IntoRustByName; - let rows = extenddb_storage_cassandra::cassandra_util::query_rows_quorum::( + let rows = extenddb_storage_cassandra::cassandra_util::query_rows::( &engine.session_arc(), &format!( "SELECT item_data, version FROM {}.items_{}", @@ -10640,7 +10639,7 @@ async fn test_restore_target_ready_requires_every_index_table() { // The GSI's table is dropped, as a crash between the data table's DDL // and the index table's would leave it. use cdrs_tokio::types::IntoRustByName; - let rows = extenddb_storage_cassandra::cassandra_util::query_rows_quorum::( + let rows = extenddb_storage_cassandra::cassandra_util::query_rows::( &engine.session_arc(), &format!( "SELECT index_id FROM {}.indexes WHERE table_id = ? AND index_name = ?", @@ -11212,7 +11211,7 @@ async fn payload_in_order( use cdrs_tokio::types::IntoRustByName; let mut items = Vec::new(); for bucket in 0..buckets { - let rows = extenddb_storage_cassandra::cassandra_util::query_rows_quorum::( + let rows = extenddb_storage_cassandra::cassandra_util::query_rows::( &engine.session_arc(), &format!( "SELECT item_data FROM {}.backup_items WHERE backup_arn = ? AND bucket = ?", @@ -11681,7 +11680,7 @@ async fn test_a_conversion_whose_answer_is_lost_or_that_stopped_is_settled() { #[cfg(feature = "test-hooks")] async fn has_registration(engine: &CassandraEngine, account_id: &str, backup_arn: &str) -> bool { use cdrs_tokio::types::IntoRustByName; - extenddb_storage_cassandra::cassandra_util::query_rows_quorum::( + extenddb_storage_cassandra::cassandra_util::query_rows::( &engine.session_arc(), &format!( "SELECT active_restores FROM {}.backups_by_arn WHERE account_id = ? AND backup_arn = ?", diff --git a/crates/storage-cassandra/tests/direct/consistency_levels.rs b/crates/storage-cassandra/tests/direct/consistency_levels.rs new file mode 100644 index 000000000..5eeb0df03 --- /dev/null +++ b/crates/storage-cassandra/tests/direct/consistency_levels.rs @@ -0,0 +1,523 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! Each statement kind reaches Cassandra at its policy level (#770). +//! +//! Other tests check two parts of the policy. The unit tests on `params()` +//! check the level of each kind. The scan test checks that each statement +//! goes through `PolicySession::run`. These tests check the level that +//! `run`, the helpers and `run_batch` send to Cassandra. They use two +//! signals that one node gives: +//! +//! - The Unavailable error. The cluster has N nodes. The test keyspace has +//! a replication factor of 2N + 1, so a quorum of its replicas is N + 1 +//! nodes. The cluster cannot supply N + 1 nodes. Cassandra therefore +//! returns an Unavailable error for each statement at a quorum level. The +//! error names the level that Cassandra could not get. A statement at +//! `ONE` needs only one node, so Cassandra runs it. +//! +//! For a statement at `LOCAL_SERIAL`, Cassandra 4.1 names `LOCAL_QUORUM` +//! in the error. For a statement at `SERIAL`, it names `QUORUM`. So the +//! error does not tell `LOCAL_SERIAL` from `LOCAL_QUORUM`. +//! - The `system.paxos` table. A read at `LOCAL_SERIAL` starts a Paxos +//! round. Each replica of the partition saves a promise in its own +//! `system.paxos` table. A read at `LOCAL_QUORUM` saves no promise. So +//! this table tells a read at `LOCAL_SERIAL` from a read at +//! `LOCAL_QUORUM`. +//! +//! These tests do not check two levels: +//! +//! - The commit level of an LWT. An LWT fails in its Paxos round, before +//! its commit. The unit test on `params()` checks the commit level. +//! - The level of `Ddl` and `SystemRead`. A DDL statement and a read of +//! `system.local` do not wait for the replicas of the test keyspace, at +//! any level. These tests show only that the two kinds do not wait for +//! those replicas. +//! +//! The tests use their own session with `FallthroughRetryPolicy`. The +//! driver's default policy sends a statement that gets an Unavailable error +//! to the next node. When no node is left, the driver returns "No nodes +//! available in query plan!", not the Unavailable error. + +#[cfg(test)] +mod tests { + use std::sync::Arc; + + use cdrs_tokio::authenticators::StaticPasswordAuthenticatorProvider; + use cdrs_tokio::cluster::NodeTcpConfigBuilder; + use cdrs_tokio::cluster::session::{SessionBuilder, TcpSessionBuilder}; + use cdrs_tokio::consistency::Consistency; + use cdrs_tokio::frame::message_error::ErrorType; + use cdrs_tokio::load_balancing::RoundRobinLoadBalancingStrategy; + use cdrs_tokio::query::QueryValues; + use cdrs_tokio::retry::FallthroughRetryPolicy; + use extenddb_storage::error::StorageError; + use extenddb_storage_cassandra::CassandraSession; + use extenddb_storage_cassandra::cassandra_util::{self, PolicySession as _, Stmt}; + + fn none() -> QueryValues { + QueryValues::SimpleValues(vec![]) + } + + /// A session to the test cluster that returns each error as Cassandra + /// sends it. + async fn session_without_retries() -> Arc { + let config = crate::helpers::test_config(); + let mut node = NodeTcpConfigBuilder::new(); + for contact_point in &config.contact_points { + node = node.with_contact_point(contact_point.clone().into()); + } + let (Some(username), Some(password)) = (&config.username, &config.password) else { + panic!("test_config sets no credentials"); + }; + let cluster = node + .with_authenticator_provider(Arc::new(StaticPasswordAuthenticatorProvider::new( + username, password, + ))) + .build() + .await + .expect("cluster config"); + let session = TcpSessionBuilder::new(RoundRobinLoadBalancingStrategy::new(), cluster) + .with_retry_policy(Box::new(FallthroughRetryPolicy)) + .build() + .await + .expect("session"); + Arc::new(session) + } + + /// A test keyspace with one table `t (pk text PRIMARY KEY, v int)`, and + /// a session that does not retry. `drop` removes the keyspace. + struct TestKeyspace { + session: Arc, + keyspace: String, + } + + impl TestKeyspace { + /// A keyspace with `replicas` replicas in the test datacenter. + async fn with_replicas(replicas: usize) -> Self { + let session = session_without_retries().await; + let keyspace = format!("consistency_{}", crate::helpers::unique_test_id()); + let datacenter = crate::helpers::test_config().datacenter; + for cql in [ + format!( + "CREATE KEYSPACE {keyspace} WITH replication = \ + {{'class': 'NetworkTopologyStrategy', '{datacenter}': {replicas}}}" + ), + format!("CREATE TABLE {keyspace}.t (pk text PRIMARY KEY, v int)"), + ] { + cassandra_util::ddl::(&session, &cql, "set up") + .await + .expect("set up the keyspace"); + } + Self { session, keyspace } + } + + /// A keyspace whose quorum is one more than the cluster's node count. + async fn under_replicated() -> Self { + let session = session_without_retries().await; + let peers = cassandra_util::system_read::( + &session, + "SELECT peer FROM system.peers", + none(), + "count the peers", + ) + .await + .expect("read system.peers"); + Self::with_replicas(2 * (peers.len() + 1) + 1).await + } + + fn session(&self) -> Arc { + Arc::clone(&self.session) + } + + fn select(&self, pk: &str) -> String { + format!("SELECT v FROM {}.t WHERE pk = '{pk}'", self.keyspace) + } + + /// The number of Paxos promises that the node holds for partition + /// `pk` of table `t`. + async fn paxos_rows(&self, pk: &str) -> usize { + let ids = cassandra_util::system_read::( + &self.session, + "SELECT id FROM system_schema.tables WHERE keyspace_name = ? AND table_name = 't'", + cdrs_tokio::query_values!(self.keyspace.as_str()), + "table id", + ) + .await + .expect("read the table id"); + let id: uuid::Uuid = cassandra_util::get_column::<_, StorageError>(&ids[0], "id", "id") + .expect("the table id"); + cassandra_util::system_read::( + &self.session, + "SELECT cf_id FROM system.paxos WHERE row_key = textAsBlob((text) ?) AND cf_id = ?", + cdrs_tokio::query_values!(pk, id), + "paxos rows", + ) + .await + .expect("read system.paxos") + .len() + } + + async fn drop(self) { + let cql = format!("DROP KEYSPACE IF EXISTS {}", self.keyspace); + cassandra_util::ddl::(&self.session, &cql, "tear down") + .await + .expect("drop the keyspace"); + } + } + + /// Collect the `tracing` events emitted on the current thread. Each entry + /// is `" "`. The design is the one in + /// `storage-sqlite/src/schema.rs`: one process-wide subscriber forwards + /// each event to the buffer of the thread that emitted it. A per-thread + /// `set_default` could leave a callsite cached as disabled by a test on + /// another thread. + mod log_capture { + use std::cell::RefCell; + use std::sync::{Arc, Mutex}; + + pub(super) type Lines = Arc>>; + + thread_local! { + static CAPTURING: RefCell> = const { RefCell::new(None) }; + } + + struct Forward; + + struct Message(String); + + impl tracing::field::Visit for Message { + fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) { + if field.name() == "message" { + self.0 = format!("{value:?}"); + } + } + } + + impl tracing::Subscriber for Forward { + fn enabled(&self, _: &tracing::Metadata<'_>) -> bool { + true + } + fn new_span(&self, _: &tracing::span::Attributes<'_>) -> tracing::span::Id { + tracing::span::Id::from_u64(1) + } + fn record(&self, _: &tracing::span::Id, _: &tracing::span::Record<'_>) {} + fn record_follows_from(&self, _: &tracing::span::Id, _: &tracing::span::Id) {} + fn event(&self, event: &tracing::Event<'_>) { + CAPTURING.with(|c| { + if let Some(lines) = c.borrow().as_ref() { + let mut message = Message(String::new()); + event.record(&mut message); + if let Ok(mut lines) = lines.lock() { + lines.push(format!("{} {}", event.metadata().level(), message.0)); + } + } + }); + } + fn enter(&self, _: &tracing::span::Id) {} + fn exit(&self, _: &tracing::span::Id) {} + } + + /// Stops capturing on drop. + pub(super) struct Guard; + + impl Drop for Guard { + fn drop(&mut self) { + CAPTURING.with(|c| c.borrow_mut().take()); + } + } + + /// Capture this thread's events until the guard is dropped. Use it + /// from a current-thread runtime (the `#[tokio::test]` default). + pub(super) fn capture() -> (Guard, Lines) { + static INSTALL: std::sync::Once = std::sync::Once::new(); + INSTALL.call_once(|| { + tracing::subscriber::set_global_default(Forward) + .expect("no other global subscriber in this test binary"); + }); + let lines = Lines::default(); + CAPTURING.with(|c| *c.borrow_mut() = Some(Arc::clone(&lines))); + (Guard, lines) + } + } + + /// The level that Cassandra names in an Unavailable error, or a panic + /// that names what came back instead. + fn unavailable_level( + result: Result, + ) -> Consistency { + match result { + Err(cdrs_tokio::error::Error::Server { body, .. }) => match body.ty { + ErrorType::Unavailable(error) => error.cl, + other => panic!("not an Unavailable error: {other:?}"), + }, + other => panic!("not a server error: {other:?}"), + } + } + + /// The level named in the Unavailable error inside a helper's error + /// text. The helpers that return rows, and `query_lwt`, keep the + /// driver's error text. + fn level_in(error: &str) -> Consistency { + for (name, level) in [ + ("cl: LocalQuorum", Consistency::LocalQuorum), + ("cl: Quorum", Consistency::Quorum), + ("cl: One", Consistency::One), + ] { + if error.contains("Unavailable") && error.contains(name) { + return level; + } + } + panic!("no Unavailable level in: {error}") + } + + #[tokio::test] + async fn run_sends_each_kind_at_its_level() { + if crate::helpers::skip_without_cassandra() { + return; + } + let keyspace = TestKeyspace::under_replicated().await; + let session = keyspace.session(); + let ks = keyspace.keyspace.clone(); + let insert = format!("INSERT INTO {ks}.t (pk, v) VALUES ('a', 1)"); + + for (kind, cql) in [ + (Stmt::Read, keyspace.select("a")), + (Stmt::SerialRead, keyspace.select("a")), + (Stmt::Write, insert.clone()), + (Stmt::Lwt, format!("{insert} IF NOT EXISTS")), + ] { + let result = session.run(kind, &cql, none()).await; + assert_eq!( + unavailable_level(result), + Consistency::LocalQuorum, + "{kind:?}" + ); + } + + // `ReadAll` needs every replica, so Cassandra names `ALL`. + assert_eq!( + unavailable_level( + session + .run(Stmt::ReadAll, keyspace.select("a"), none()) + .await + ), + Consistency::All, + "ReadAll" + ); + + // A page of a read has the level of its kind. For `SerialRead`, + // Cassandra names `LOCAL_QUORUM`, as it does for `run`. + for (kind, level) in [ + (Stmt::Read, Consistency::LocalQuorum), + (Stmt::SerialRead, Consistency::LocalQuorum), + (Stmt::ReadAll, Consistency::All), + ] { + let result = session + .run_paged(kind, keyspace.select("a"), none(), 10, None) + .await; + assert_eq!(unavailable_level(result), level, "run_paged {kind:?}"); + } + + session + .run( + Stmt::Ddl, + format!("ALTER TABLE {ks}.t WITH comment = 'x'"), + none(), + ) + .await + .expect("Ddl does not wait for the keyspace replicas"); + session + .run( + Stmt::SystemRead, + "SELECT release_version FROM system.local", + none(), + ) + .await + .expect("SystemRead does not wait for the keyspace replicas"); + + keyspace.drop().await; + } + + #[tokio::test] + async fn only_a_serial_read_runs_a_paxos_round() { + if crate::helpers::skip_without_cassandra() { + return; + } + // `system.paxos` is local to each node, and the read of it can go to + // any node. On one node, that node holds every promise. + let session = session_without_retries().await; + let peers = cassandra_util::system_read::( + &session, + "SELECT peer FROM system.peers", + none(), + "count the peers", + ) + .await + .expect("read system.peers"); + if !peers.is_empty() { + eprintln!("skipping: system.paxos is checked on a one-node cluster only"); + return; + } + let keyspace = TestKeyspace::with_replicas(1).await; + let session = keyspace.session(); + + session + .run(Stmt::Read, keyspace.select("read"), none()) + .await + .expect("Read"); + session + .run(Stmt::SerialRead, keyspace.select("serial"), none()) + .await + .expect("SerialRead"); + cassandra_util::query_rows::(&session, &keyspace.select("rows"), none(), "t") + .await + .expect("query_rows"); + cassandra_util::query_optional::( + &session, + &keyspace.select("optional"), + none(), + "t", + ) + .await + .expect("query_optional"); + cassandra_util::query_rows_serial::( + &session, + &keyspace.select("rows_serial"), + none(), + "t", + ) + .await + .expect("query_rows_serial"); + + for (pk, promises) in [ + ("read", 0), + ("serial", 1), + ("rows", 0), + ("optional", 0), + ("rows_serial", 1), + ] { + assert_eq!(keyspace.paxos_rows(pk).await, promises, "{pk}"); + } + + keyspace.drop().await; + } + + #[tokio::test] + async fn the_helpers_send_at_their_levels() { + if crate::helpers::skip_without_cassandra() { + return; + } + let keyspace = TestKeyspace::under_replicated().await; + let session = keyspace.session(); + let ks = keyspace.keyspace.clone(); + let select = keyspace.select("a"); + let insert = format!("INSERT INTO {ks}.t (pk, v) VALUES ('a', 1)"); + let insert_if = format!("{insert} IF NOT EXISTS"); + + let rows = cassandra_util::query_rows::(&session, &select, none(), "t") + .await + .expect_err("query_rows"); + let serial = + cassandra_util::query_rows_serial::(&session, &select, none(), "t") + .await + .expect_err("query_rows_serial"); + let optional = + cassandra_util::query_optional::(&session, &select, none(), "t") + .await + .expect_err("query_optional"); + let lwt = cassandra_util::query_lwt(&session, &insert_if, none()) + .await + .expect_err("query_lwt"); + for (helper, error) in [ + ("query_rows", rows.to_string()), + ("query_rows_serial", serial.to_string()), + ("query_optional", optional.to_string()), + ("query_lwt", lwt.to_string()), + ] { + assert_eq!(level_in(&error), Consistency::LocalQuorum, "{helper}"); + } + + // `execute` and `apply_lwt` return only "Database error", and log the + // driver's error. The level comes from the log line. + let (guard, lines) = log_capture::capture(); + cassandra_util::execute::(&session, &insert, none(), "execute") + .await + .expect_err("execute"); + cassandra_util::apply_lwt::(&session, &insert_if, none(), "apply_lwt") + .await + .expect_err("apply_lwt"); + drop(guard); + let lines = lines.lock().expect("the log lines").clone(); + for helper in ["execute", "apply_lwt"] { + let line = lines + .iter() + .find(|line| line.contains(&format!("{helper} "))) + .unwrap_or_else(|| panic!("no log line for {helper}: {lines:?}")); + assert_eq!(level_in(line), Consistency::LocalQuorum, "{helper}"); + } + + cassandra_util::ddl::( + &session, + &format!("ALTER TABLE {ks}.t WITH comment = 'y'"), + "t", + ) + .await + .expect("ddl does not wait for the keyspace replicas"); + cassandra_util::system_read::( + &session, + "SELECT release_version FROM system.local", + none(), + "t", + ) + .await + .expect("system_read does not wait for the keyspace replicas"); + + keyspace.drop().await; + } + + #[tokio::test] + async fn run_batch_sends_a_batch_from_batch_at_its_levels() { + if crate::helpers::skip_without_cassandra() { + return; + } + let keyspace = TestKeyspace::under_replicated().await; + let session = keyspace.session(); + let ks = keyspace.keyspace.clone(); + + let plain = cassandra_util::batch() + .add_query( + format!("INSERT INTO {ks}.t (pk, v) VALUES ('a', 1)"), + none(), + ) + .add_query( + format!("INSERT INTO {ks}.t (pk, v) VALUES ('b', 2)"), + none(), + ) + .build() + .expect("a batch"); + assert_eq!( + unavailable_level(session.run_batch(plain).await), + Consistency::LocalQuorum, + "a batch with no condition" + ); + + // With no serial level, the Paxos round of a conditional batch runs + // at SERIAL, and Cassandra names QUORUM. LOCAL_QUORUM here shows + // that `batch()` sets LOCAL_SERIAL. + let conditional = cassandra_util::batch() + .add_query( + format!("INSERT INTO {ks}.t (pk, v) VALUES ('a', 1) IF NOT EXISTS"), + none(), + ) + .build() + .expect("a batch"); + assert_eq!( + unavailable_level(session.run_batch(conditional).await), + Consistency::LocalQuorum, + "a conditional batch" + ); + + keyspace.drop().await; + } +} diff --git a/crates/storage-cassandra/tests/direct/consistency_shape.rs b/crates/storage-cassandra/tests/direct/consistency_shape.rs new file mode 100644 index 000000000..1e7d5930a --- /dev/null +++ b/crates/storage-cassandra/tests/direct/consistency_shape.rs @@ -0,0 +1,120 @@ +// Copyright 2026 ExtendDB contributors +// SPDX-License-Identifier: Apache-2.0 + +//! `PolicySession::run` panics in a debug build when a statement's CQL does +//! not match its kind (#770). The unit tests on `shape_error` cover the rule +//! itself; this test covers that `run` applies it. The panic comes before +//! `run` sends anything, so the statement never reaches Cassandra. + +#[cfg(test)] +mod tests { + use extenddb_storage_cassandra::cassandra_util::{PolicySession as _, Stmt}; + + #[cfg(debug_assertions)] + #[tokio::test] + async fn run_panics_on_an_lwt_without_a_condition() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = crate::helpers::setup_engine().await; + let session = engine.session_arc(); + let task = tokio::spawn(async move { + session + .run( + Stmt::Lwt, + "UPDATE ks.t SET a = 1 WHERE pk = 1", + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ) + .await + }); + let error = task + .await + .expect_err("run() panics on an LWT with no IF condition"); + assert!(error.is_panic(), "{error:?}"); + let payload = error.into_panic(); + let message = payload + .downcast_ref::() + .cloned() + .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_owned())) + .unwrap_or_default(); + assert!( + message.contains("an LWT must have an IF condition"), + "{message}" + ); + assert!( + !message.contains("ks.t"), + "the message must not hold the CQL text: {message}" + ); + } + + /// `run_paged` panics on a kind that is not a read, before it sends + /// anything. + #[cfg(debug_assertions)] + #[tokio::test] + async fn run_paged_panics_on_a_kind_that_is_not_a_read() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = crate::helpers::setup_engine().await; + let session = engine.session_arc(); + let task = tokio::spawn(async move { + session + .run_paged( + Stmt::Write, + "INSERT INTO ks.t (a) VALUES (1)", + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + 10, + None, + ) + .await + }); + let error = task + .await + .expect_err("run_paged() panics on a kind that is not a read"); + assert!(error.is_panic(), "{error:?}"); + let payload = error.into_panic(); + let message = payload + .downcast_ref::() + .cloned() + .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_owned())) + .unwrap_or_default(); + assert!( + message.contains("a paged statement must be a read"), + "{message}" + ); + } + + /// `run_batch` panics on a batch that was not built by + /// `cassandra_util::batch()`, before it sends anything. + #[cfg(debug_assertions)] + #[tokio::test] + async fn run_batch_panics_on_a_batch_at_the_driver_default() { + if crate::helpers::skip_without_cassandra() { + return; + } + let engine = crate::helpers::setup_engine().await; + let session = engine.session_arc(); + let batch = cdrs_tokio::query::BatchQueryBuilder::default() + .add_query( + "INSERT INTO ks.t (id) VALUES (1)", + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ) + .build() + .expect("a batch"); + let task = tokio::spawn(async move { session.run_batch(batch).await }); + let error = task + .await + .expect_err("run_batch() panics on a batch at ONE"); + assert!(error.is_panic(), "{error:?}"); + let payload = error.into_panic(); + let message = payload + .downcast_ref::() + .cloned() + .or_else(|| payload.downcast_ref::<&str>().map(|s| (*s).to_owned())) + .unwrap_or_default(); + assert!( + message.contains("a batch must run at LOCAL_QUORUM"), + "{message}" + ); + } +} diff --git a/crates/storage-cassandra/tests/direct/index.rs b/crates/storage-cassandra/tests/direct/index.rs index 2b15c2d40..a90223578 100644 --- a/crates/storage-cassandra/tests/direct/index.rs +++ b/crates/storage-cassandra/tests/direct/index.rs @@ -1949,7 +1949,7 @@ async fn test_a_delete_removes_the_index_row_a_backfill_wrote() { async fn keyspace_tables(engine: &CassandraEngine, keyspace: &str) -> Vec { use cdrs_tokio::types::IntoRustByName as _; - extenddb_storage_cassandra::cassandra_util::query_rows::( + extenddb_storage_cassandra::cassandra_util::system_read::( &engine.session_arc(), "SELECT table_name FROM system_schema.tables WHERE keyspace_name = ?", cdrs_tokio::query_values!(keyspace), @@ -1971,7 +1971,7 @@ async fn schema_table_id( ) -> Option { use cdrs_tokio::types::IntoRustByName as _; - extenddb_storage_cassandra::cassandra_util::query_rows::( + extenddb_storage_cassandra::cassandra_util::system_read::( &engine.session_arc(), "SELECT id FROM system_schema.tables WHERE keyspace_name = ? AND table_name = ?", cdrs_tokio::query_values!(keyspace, table), diff --git a/crates/storage-cassandra/tests/direct/keyspace_migrations.rs b/crates/storage-cassandra/tests/direct/keyspace_migrations.rs index ecd1706a7..92b0cc6ec 100644 --- a/crates/storage-cassandra/tests/direct/keyspace_migrations.rs +++ b/crates/storage-cassandra/tests/direct/keyspace_migrations.rs @@ -23,7 +23,7 @@ use cdrs_tokio::cluster::session::{SessionBuilder, TcpSessionBuilder}; use cdrs_tokio::load_balancing::RoundRobinLoadBalancingStrategy; use extenddb_storage::error::StorageError; use extenddb_storage_cassandra::CassandraSession; -use extenddb_storage_cassandra::cassandra_util::{get_column, query_rows}; +use extenddb_storage_cassandra::cassandra_util::{get_column, system_read}; use extenddb_storage_cassandra::migrations::{migrate_account, migrate_catalog_keyspace}; /// Connections per node, the `max_connections` default. @@ -170,7 +170,7 @@ async fn schema_names( keyspace: &str, columns: &[&str], ) -> BTreeSet { - let rows = query_rows::( + let rows = system_read::( session, query, cdrs_tokio::query_values!(keyspace), diff --git a/crates/storage-cassandra/tests/direct/transaction_ledger.rs b/crates/storage-cassandra/tests/direct/transaction_ledger.rs index b74cd900b..d0263bc30 100644 --- a/crates/storage-cassandra/tests/direct/transaction_ledger.rs +++ b/crates/storage-cassandra/tests/direct/transaction_ledger.rs @@ -522,14 +522,17 @@ async fn test_committing_recovery_repairs_the_index_rows_of_a_row_it_commits() { let fence = format!( "UPDATE {keyspace}.{data_table} SET prepared_txn_id = ?, prepared_txn_timestamp = ? WHERE pk = ? IF prepared_txn_id = null" ); - extenddb_storage_cassandra::cassandra_util::execute::( - &engine.session_arc(), - &fence, - cdrs_tokio::query_values!(txn_id, 1_i64, "own"), - "prepare by hand", - ) - .await - .unwrap(); + assert!( + extenddb_storage_cassandra::cassandra_util::apply_lwt::( + &engine.session_arc(), + &fence, + cdrs_tokio::query_values!(txn_id, 1_i64, "own"), + "prepare by hand", + ) + .await + .unwrap(), + "the fence applied" + ); engine .write_ledger_entry( &keyspace, diff --git a/crates/storage-cassandra/tests/direct_integration.rs b/crates/storage-cassandra/tests/direct_integration.rs index 6149a04a1..135baf2f4 100644 --- a/crates/storage-cassandra/tests/direct_integration.rs +++ b/crates/storage-cassandra/tests/direct_integration.rs @@ -28,6 +28,10 @@ mod backup_engine; mod cassandra_engine; #[path = "direct/concurrent_account_creation.rs"] mod concurrent_account_creation; +#[path = "direct/consistency_levels.rs"] +mod consistency_levels; +#[path = "direct/consistency_shape.rs"] +mod consistency_shape; #[path = "direct/delete_item.rs"] mod delete_item; #[path = "direct/groups.rs"] diff --git a/docs/cassandra-setup.md b/docs/cassandra-setup.md index 884bbe16c..73c0056af 100644 --- a/docs/cassandra-setup.md +++ b/docs/cassandra-setup.md @@ -335,14 +335,29 @@ Logins read `system_auth` at `QUORUM` for the default superuser, so a `system_auth` replication factor above the node count makes those logins fail with `Cannot achieve consistency level QUORUM`. +ExtendDB runs each read and write at `LOCAL_QUORUM` or `LOCAL_SERIAL`, so a +request needs a quorum of its keyspace's replicas in the datacenter to be up. +When fewer replicas are up, the request fails with HTTP 500 (`InternalServerError`). +A replication factor of 3 keeps serving while one replica is down; a replication +factor of 2 or 1, requests will fail when any replica is down. Use a replication +factor of 3 on at least three nodes for any production deployment. For how Cassandra +counts a quorum, see +[Tunable Consistency](https://cassandra.apache.org/doc/4.1/cassandra/architecture/dynamo.html#tunable-consistency) +in the Cassandra documentation. + +Run `extenddb backup migrate-legacy` only when every replica of every account +keyspace is up. It reads the backup data that older versions wrote at `ALL`, so +it fails when any replica is down, even with a replication factor of 3. See +[Migrating legacy backups into the store](manuals/14-backup-and-restore.md#migrating-legacy-backups-into-the-store). + ExtendDB creates its keyspaces with `NetworkTopologyStrategy`, with `replication_factor` replicas in `datacenter`. Use the name your cluster's nodes report (`nodetool status` prints it); in the `ALTER KEYSPACE` statements above, replace `datacenter1` with it. -ExtendDB supports one datacenter. A keyspace that also replicates to a second -datacenter still works, but `serve` logs the start-up warning for it at every -start. +ExtendDB supports one Cassandra datacenter. A keyspace that also replicates to +a second datacenter still works, but `serve` logs the start-up warning for it +at every start. With a replication factor of 1, the catalog has one replica, so a restart of that node stops every request to it. A running server renews its serving @@ -352,6 +367,7 @@ through an outage of 25 to 30 s, depending on when the outage starts. After that, 30 to 35 s after its last successful renewal, it answers new requests with `ServiceUnavailable`, stops its background workers, and tries to register again every second for up to 30 s. + It registers again, starts its workers again and serves on only when the Cassandra driver has reconnected to the node within that time, which after a restart of 30 s or more it often has not; otherwise it stops with exit 1. Run @@ -407,8 +423,9 @@ backend is experimental rather than production-ready. are known (observed as intermittent integration-test failures) and are being worked. Under concurrent load, outcomes may occasionally diverge from DynamoDB semantics. -- **Single-datacenter writes per table.** Transaction and TTL lifecycle - operations use `LOCAL_QUORUM` / `LOCAL_SERIAL`, which are linearizable only +- **Single-datacenter writes per table.** Reads and writes use `LOCAL_QUORUM`, + so a read sees each write that its datacenter acknowledged before the read + started. Lightweight transactions use `LOCAL_SERIAL`, and are linearizable within one datacenter. Serve writes for a given table from one Cassandra datacenter. - **Multi-node ExtendDB needs node-id configuration.** Running more than one diff --git a/docs/design/11-high-availability.md b/docs/design/11-high-availability.md index 6dfde741d..a5a723862 100755 --- a/docs/design/11-high-availability.md +++ b/docs/design/11-high-availability.md @@ -136,11 +136,14 @@ This is the minimal mechanism needed to honor DynamoDB's consistency model. It w [Frontend B] ─┘ └→ [Cassandra Node 3] ``` -- Storage layer maps DynamoDB consistency to native consistency levels. - - `ConsistentRead = true` → `QUORUM` or `LOCAL_QUORUM` - - `ConsistentRead = false` → `ONE` or `LOCAL_ONE` +- The Cassandra backend performs every read and write at `LOCAL_QUORUM`, and + every lightweight transaction at `LOCAL_SERIAL`. Table reads are therefore + strongly consistent, for both DynamoDB consistent and eventually consistent + reads, when the clocks of the Cassandra nodes and the ExtendDB hosts are in + sync (see "Clock synchronization" in `docs/cassandra-setup.md`). - No separate primary/replica distinction — the storage adapter handles it. -- Suitable for: large-scale deployments, multi-datacenter. +- Suitable for: large-scale deployments in one datacenter. Multi-datacenter + deployments are not supported. ### Model 5: Multi-Region (Future)