From 1cf98b82c2629931373cbcd381e577ad24ad0aaa Mon Sep 17 00:00:00 2001 From: Joel Shepherd Date: Mon, 9 Nov 2026 02:49:02 +0000 Subject: [PATCH 01/12] refactor(storage-cassandra): set every helper's consistency level in one place Add the Stmt enum and params(), which set the consistency level for each kind of statement: - Read, Write: LOCAL_QUORUM. - Lwt: Paxos at LOCAL_SERIAL, commit at LOCAL_QUORUM. - SerialRead: LOCAL_SERIAL. - Ddl, SystemRead: ONE. Add batch(), which returns a batch builder at LOCAL_QUORUM with LOCAL_SERIAL, and the ddl() and system_read() helpers. query_rows, query_optional and execute now run at LOCAL_QUORUM, not ONE. apply_lwt now commits at LOCAL_QUORUM, not ONE, and runs Paxos at LOCAL_SERIAL, not SERIAL. The _quorum helpers now call these helpers. A later commit removes them. Refs #770 --- .../storage-cassandra/src/cassandra_util.rs | 302 +++++++++++------- 1 file changed, 191 insertions(+), 111 deletions(-) diff --git a/crates/storage-cassandra/src/cassandra_util.rs b/crates/storage-cassandra/src/cassandra_util.rs index 2b846cc79..80c9d4243 100644 --- a/crates/storage-cassandra/src/cassandra_util.rs +++ b/crates/storage-cassandra/src/cassandra_util.rs @@ -17,25 +17,127 @@ 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, + /// `CREATE`, `ALTER` or `DROP`: `ONE`. + Ddl, + /// A read of a node-local system table (`system.local`, `system.peers`, + /// `system_schema`): `ONE`. + SystemRead, +} + +/// 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::consistency::Consistency; use cdrs_tokio::statement::StatementParamsBuilder; - let params = StatementParamsBuilder::new() + let builder = StatementParamsBuilder::new().with_values(values); + let builder = match kind { + Stmt::Read | Stmt::Write => builder.with_consistency(Consistency::LocalQuorum), + Stmt::Lwt => builder + .with_consistency(Consistency::LocalQuorum) + .with_serial_consistency(Consistency::LocalSerial), + Stmt::SerialRead => builder.with_consistency(Consistency::LocalSerial), + Stmt::Ddl | Stmt::SystemRead => builder.with_consistency(Consistency::One), + }; + builder.build() +} + +/// 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(Stmt::Ddl, 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, params(Stmt::SystemRead, values), context).await +} + +/// Run `query` with `params` and return its rows. +async fn rows_at( + session: &Arc, + query: &str, + params: cdrs_tokio::statement::StatementParams, + context: &str, +) -> Result, E> { + let result = session .query_with_params(query, params) .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 + .query_with_params(query, params(Stmt::Lwt, values)) + .await .map_err(|error| { extenddb_storage::error::StorageError::Internal(format!("LWT query failed: {error}")) }) @@ -85,7 +187,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 +197,17 @@ 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()) + rows_at(session, query, params(Stmt::Read, values), context).await } -/// 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. +/// The same as [`query_rows`]. A later commit removes it. 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()) + query_rows(session, query, values, context).await } /// Execute a query at `LOCAL_SERIAL` and return all rows: the read sees @@ -157,27 +220,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, params(Stmt::SerialRead, values), context).await } /// Execute a query and return the first row, if any. @@ -196,7 +239,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. @@ -207,7 +250,7 @@ pub async fn execute( context: &str, ) -> Result<(), E> { session - .query_with_values(query, values) + .query_with_params(query, params(Stmt::Write, values)) .await .map_err(|e| { tracing::error!("{context} execute failed: {e}"); @@ -217,10 +260,8 @@ pub async fn execute( 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. +/// [`execute`], but the error names `context` and the driver's error, as +/// before. A later commit removes it. /// /// # Errors /// Returns an error if Cassandra does not acknowledge the statement at quorum. @@ -230,15 +271,8 @@ pub async fn execute_quorum( 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(); session - .query_with_params(query, params) + .query_with_params(query, params(Stmt::Write, values)) .await .map_err(|error| { tracing::error!("{context} quorum execute failed: {error}"); @@ -376,6 +410,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. @@ -389,7 +425,7 @@ pub async fn apply_lwt( context: &str, ) -> Result { let result = session - .query_with_values(query, values) + .query_with_params(query, params(Stmt::Lwt, values)) .await .map_err(|e| { tracing::error!("{context} lwt failed: {e}"); @@ -398,12 +434,7 @@ pub async fn apply_lwt( 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. +/// The same as [`apply_lwt`]. A later commit removes it. /// /// # Errors /// Returns an error if Cassandra does not acknowledge the statement at quorum @@ -414,21 +445,7 @@ pub async fn apply_lwt_quorum( 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()) - })?; - lwt_applied_flag(&result, context) + apply_lwt(session, query, values, context).await } /// The `[applied]` flag of an LWT response, `false` when the response has no row. @@ -449,3 +466,66 @@ 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, params}; + 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 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) + ); + } +} From 33c7d8273bed12ca0a645cd9361442e06838691f Mon Sep 17 00:00:00 2001 From: Joel Shepherd Date: Mon, 9 Nov 2026 04:54:45 +0000 Subject: [PATCH 02/12] refactor(storage-cassandra): move item paths onto the consistency policy The wrappers in data/mod.rs now run each statement at the level that params() gives its kind. query_with_pk_sk and select_by_pk_at take the kind from the caller. The three wrappers with a transaction id run only LWTs, so they use Stmt::Lwt. PutItem, GetItem, DeleteItem, UpdateItem, Scan, index writes and table DDL now use the helpers and batch(): - Reads and plain writes run at LOCAL_QUORUM, not ONE. - LWTs commit at LOCAL_QUORUM, not ONE, and run Paxos at LOCAL_SERIAL, not SERIAL. - DDL stays at ONE. - Batches stay at LOCAL_QUORUM. A conditional batch now runs Paxos at LOCAL_SERIAL. --- crates/storage-cassandra/src/data/ddl.rs | 45 ++-- .../storage-cassandra/src/data/delete_item.rs | 61 +++--- crates/storage-cassandra/src/data/index.rs | 6 +- crates/storage-cassandra/src/data/mod.rs | 205 ++++++------------ .../src/data/put_get_item.rs | 31 ++- crates/storage-cassandra/src/data/scan.rs | 15 +- .../src/data/transactions.rs | 26 ++- .../storage-cassandra/src/data/update_item.rs | 9 +- 8 files changed, 181 insertions(+), 217 deletions(-) diff --git a/crates/storage-cassandra/src/data/ddl.rs b/crates/storage-cassandra/src/data/ddl.rs index 74cc6fb7e..98f7917cc 100644 --- a/crates/storage-cassandra/src/data/ddl.rs +++ b/crates/storage-cassandra/src/data/ddl.rs @@ -12,6 +12,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 { @@ -270,10 +271,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 +290,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 +309,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 +416,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 +452,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 +502,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 { diff --git a/crates/storage-cassandra/src/data/delete_item.rs b/crates/storage-cassandra/src/data/delete_item.rs index e7848bf6e..f040217b3 100644 --- a/crates/storage-cassandra/src/data/delete_item.rs +++ b/crates/storage-cassandra/src/data/delete_item.rs @@ -3,8 +3,6 @@ //! `delete_item` implementation for the Cassandra backend. -use cdrs_tokio::consistency::Consistency; -use cdrs_tokio::query::BatchQueryBuilder; use cdrs_tokio::types::IntoRustByName; use extenddb_core::expression::{Expr, ExpressionMaps}; use extenddb_core::types::{Item, TableKeyInfo}; @@ -16,6 +14,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, params}; use crate::stream_util::stream_record_statement; /// Lifetime of the base-row claim an ordinary request holds while it commits @@ -222,8 +221,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() @@ -398,7 +403,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![ @@ -418,9 +430,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() @@ -679,7 +689,10 @@ impl CassandraEngine { && ttl_claim.is_none() { self.session - .query_with_values(&delete_cql, cdrs_tokio::query_values!(pk_text.as_str())) + .query_with_params( + &delete_cql, + params(Stmt::Write, cdrs_tokio::query_values!(pk_text.as_str())), + ) .await .map_err(|e| StorageError::Internal(format!("Delete failed: {e}")))?; } else { @@ -699,9 +712,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() @@ -829,7 +840,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() @@ -1012,9 +1023,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, @@ -1078,9 +1087,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( @@ -1474,7 +1481,10 @@ impl CassandraEngine { let result = self .session - .query_with_values(&query_null, cdrs_tokio::query_values!(now_ms, pk)) + .query_with_params( + &query_null, + params(Stmt::Lwt, cdrs_tokio::query_values!(now_ms, pk)), + ) .await .map_err(|e| { tracing::error!("update_partition_max_delete_timestamp (null): {e}"); @@ -1502,9 +1512,9 @@ impl CassandraEngine { ); self.session - .query_with_values( + .query_with_params( &query_compare, - cdrs_tokio::query_values!(now_ms, pk, now_ms), + params(Stmt::Lwt, cdrs_tokio::query_values!(now_ms, pk, now_ms)), ) .await .map_err(|e| { @@ -1539,7 +1549,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| { @@ -1603,10 +1613,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( diff --git a/crates/storage-cassandra/src/data/index.rs b/crates/storage-cassandra/src/data/index.rs index 2b2c0ef9f..30e4e1f1f 100644 --- a/crates/storage-cassandra/src/data/index.rs +++ b/crates/storage-cassandra/src/data/index.rs @@ -493,7 +493,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 +577,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 +656,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..c45b9a030 100644 --- a/crates/storage-cassandra/src/data/mod.rs +++ b/crates/storage-cassandra/src/data/mod.rs @@ -3,15 +3,16 @@ //! Data table operations for Cassandra. +use crate::cassandra_util::{Stmt, params}; 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 +88,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 + .query_with_params(query, params(kind, 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 +129,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 +149,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 +171,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 +193,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 +219,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 +232,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 c626383ef..4dea2ad94 100644 --- a/crates/storage-cassandra/src/data/put_get_item.rs +++ b/crates/storage-cassandra/src/data/put_get_item.rs @@ -3,8 +3,6 @@ //! `put_item` and `get_item` implementations for the Cassandra backend. -use cdrs_tokio::consistency::Consistency; -use cdrs_tokio::query::BatchQueryBuilder; use cdrs_tokio::types::IntoRustByName; use extenddb_core::expression::{Expr, ExpressionMaps}; use extenddb_core::types::{Item, TableKeyInfo}; @@ -15,6 +13,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, params}; use crate::stream_util::stream_record_statement; /// How a put maintains GSIs. @@ -151,8 +150,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() { @@ -322,8 +320,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() @@ -605,7 +609,7 @@ impl CassandraEngine { let result = self .session - .query_with_values(&insert_cql, insert_qv) + .query_with_params(&insert_cql, params(Stmt::Lwt, insert_qv)) .await .map_err(|e| StorageError::Internal(format!("put_item_if_not_exists: {e}")))?; @@ -652,7 +656,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( @@ -793,7 +797,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() @@ -813,7 +818,13 @@ impl CassandraEngine { let result = self .session - .query_with_values(&query, cdrs_tokio::query_values!(pk_text.as_ref() as &str)) + .query_with_params( + &query, + params( + Stmt::Read, + 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..aacf97394 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 { diff --git a/crates/storage-cassandra/src/data/transactions.rs b/crates/storage-cassandra/src/data/transactions.rs index b6a64f5cf..3a8757259 100644 --- a/crates/storage-cassandra/src/data/transactions.rs +++ b/crates/storage-cassandra/src/data/transactions.rs @@ -1331,7 +1331,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) } @@ -1347,8 +1352,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. @@ -1357,7 +1363,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); @@ -1373,7 +1379,7 @@ impl CassandraEngine { pk_text.as_str(), sk.as_ref(), sk_col.as_deref(), - consistency, + read, ) .await? else { @@ -1673,7 +1679,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); @@ -1727,7 +1733,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()); @@ -1777,7 +1783,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); @@ -2413,7 +2419,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())) @@ -2440,7 +2446,7 @@ impl CassandraEngine { pk, sk.map(|(value, _)| value), sk.map(|(_, col)| col.as_str()), - Some(Consistency::LocalSerial), + crate::cassandra_util::Stmt::SerialRead, ) .await? else { diff --git a/crates/storage-cassandra/src/data/update_item.rs b/crates/storage-cassandra/src/data/update_item.rs index 9e54124c2..dd74242d3 100644 --- a/crates/storage-cassandra/src/data/update_item.rs +++ b/crates/storage-cassandra/src/data/update_item.rs @@ -3,8 +3,6 @@ //! `update_item` implementation for the Cassandra backend. -use cdrs_tokio::consistency::Consistency; -use cdrs_tokio::query::BatchQueryBuilder; use extenddb_core::expression::{self, Expr, ExpressionMaps, UpdateAction}; use extenddb_core::types::{Item, KeyType, TableKeyInfo}; use extenddb_core::validation; @@ -15,6 +13,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, params}; use crate::stream_util::stream_record_statement; // 400 KB limit from DynamoDB specification @@ -287,7 +286,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}")))? @@ -430,7 +429,7 @@ impl CassandraEngine { // Preserve f997485's Paxos linearization for ordinary writes. let result = self .session - .query_with_values(&lwt_cql, lwt_qv) + .query_with_params(&lwt_cql, params(Stmt::Lwt, lwt_qv)) .await .map_err(|e| StorageError::Internal(format!("occ_write lwt: {e}")))?; if !crate::cassandra_util::lwt_applied(&result)? { @@ -451,7 +450,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); } From 2928b2405a659ac7df5f1dad77324583204bf5ea Mon Sep 17 00:00:00 2001 From: Joel Shepherd Date: Mon, 9 Nov 2026 17:39:29 +0000 Subject: [PATCH 03/12] refactor(storage-cassandra): move transactions onto the consistency policy TransactWriteItems, TransactGetItems and the transaction ledger now use params() and batch(): - The partition read in PREPARE runs at LOCAL_QUORUM, not ONE. - The PREPARE, COMMIT and rollback LWTs, and the ledger INSERT, commit at LOCAL_QUORUM, not ONE, and run Paxos at LOCAL_SERIAL, not SERIAL. - The ledger's state and items updates and its DELETE run at LOCAL_QUORUM, not ONE. - The commit batch stays at LOCAL_QUORUM. Refs #770 --- .../src/data/transaction_ledger.rs | 46 +++--- .../src/data/transactions.rs | 143 +++++++++++------- 2 files changed, 121 insertions(+), 68 deletions(-) diff --git a/crates/storage-cassandra/src/data/transaction_ledger.rs b/crates/storage-cassandra/src/data/transaction_ledger.rs index 9068370f9..b1cc13bdd 100644 --- a/crates/storage-cassandra/src/data/transaction_ledger.rs +++ b/crates/storage-cassandra/src/data/transaction_ledger.rs @@ -9,7 +9,7 @@ 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, params, query_optional, query_rows}; /// Transaction states (from DynamoDB paper). #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -120,15 +120,18 @@ impl CassandraEngine { let result = self .session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!( - Bytes::new(txn_id.as_bytes().to_vec()), - state.as_str(), - started_at, - client_token, - request_fingerprint, - items_blob + params( + Stmt::Lwt, + cdrs_tokio::query_values!( + Bytes::new(txn_id.as_bytes().to_vec()), + state.as_str(), + started_at, + client_token, + request_fingerprint, + items_blob + ), ), ) .await @@ -167,11 +170,14 @@ impl CassandraEngine { let query = format!("UPDATE {keyspace}.transaction_ledger SET state = ? WHERE txn_id = ?"); self.session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!( - new_state.as_str(), - Bytes::new(txn_id.as_bytes().to_vec()) + params( + Stmt::Write, + cdrs_tokio::query_values!( + new_state.as_str(), + Bytes::new(txn_id.as_bytes().to_vec()) + ), ), ) .await @@ -198,9 +204,12 @@ impl CassandraEngine { let query = format!("UPDATE {keyspace}.transaction_ledger SET items_blob = ? WHERE txn_id = ?"); self.session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!(blob, Bytes::new(txn_id.as_bytes().to_vec())), + params( + Stmt::Write, + cdrs_tokio::query_values!(blob, Bytes::new(txn_id.as_bytes().to_vec())), + ), ) .await .map_err(|e| { @@ -304,9 +313,12 @@ impl CassandraEngine { let query = format!("DELETE FROM {keyspace}.transaction_ledger WHERE txn_id = ?"); self.session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!(Bytes::new(txn_id.as_bytes().to_vec())), + params( + Stmt::Write, + cdrs_tokio::query_values!(Bytes::new(txn_id.as_bytes().to_vec())), + ), ) .await .map_err(|e| { diff --git a/crates/storage-cassandra/src/data/transactions.rs b/crates/storage-cassandra/src/data/transactions.rs index 3a8757259..15c0d014d 100644 --- a/crates/storage-cassandra/src/data/transactions.rs +++ b/crates/storage-cassandra/src/data/transactions.rs @@ -4,9 +4,7 @@ //! DynamoDB transaction implementations for Cassandra backend. use super::transact_stream::{commit_old_image, secondary_effect_batches}; -use cdrs_tokio::consistency::Consistency; 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 +21,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, params, query_optional}; use crate::data::ddl::data_table_name; use crate::data::transaction_ledger::{LedgerOp, TransactionState}; use crate::data::{ @@ -1537,7 +1535,10 @@ impl CassandraEngine { let result = self .session - .query_with_values(&query, cdrs_tokio::query_values!(pk_text.as_str())) + .query_with_params( + &query, + params(Stmt::Read, cdrs_tokio::query_values!(pk_text.as_str())), + ) .await .map_err(|e| { tracing::error!("check_partition_max_delete_timestamp: {e}"); @@ -1619,7 +1620,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)) + .query_with_params(&query, params(Stmt::Lwt, 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 { @@ -1628,7 +1629,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())) + .query_with_params(&query, params(Stmt::Lwt, cdrs_tokio::query_values!(txn_id_bytes, txn_timestamp, pk_text.as_str()))) .await .map_err(|e| StorageError::Internal(e.to_string())) } @@ -1809,9 +1810,12 @@ impl CassandraEngine { let result = self .session - .query_with_values( + .query_with_params( &update_max_ts_null_query, - cdrs_tokio::query_values!(txn_timestamp, pk_text.as_str()), + params( + Stmt::Lwt, + cdrs_tokio::query_values!(txn_timestamp, pk_text.as_str()), + ), ) .await .map_err(|e| { @@ -1830,12 +1834,15 @@ impl CassandraEngine { let _result2 = self .session - .query_with_values( + .query_with_params( &update_max_ts_query, - cdrs_tokio::query_values!( - txn_timestamp, - pk_text.as_str(), - txn_timestamp + params( + Stmt::Lwt, + cdrs_tokio::query_values!( + txn_timestamp, + pk_text.as_str(), + txn_timestamp + ), ), ) .await @@ -1873,9 +1880,9 @@ impl CassandraEngine { "DELETE FROM {keyspace}.{ddb_table} WHERE pk = ? IF prepared_txn_id = ?" ); self.session - .query_with_values( + .query_with_params( &delete_query, - cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes), + params(Stmt::Lwt, cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes)), ) .await .map_err(|e| StorageError::Internal(e.to_string())) @@ -1953,9 +1960,12 @@ impl CassandraEngine { IF prepared_txn_id = ? AND created_to_prepare = true" ); self.session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes), + params( + Stmt::Lwt, + cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes), + ), ) .await .map_err(|e| StorageError::Internal(e.to_string())) @@ -2020,16 +2030,16 @@ impl CassandraEngine { WHERE pk = ? AND {sk_col} = ? IF prepared_txn_id = ?" ); self.session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query::QueryValues::SimpleValues(vec![ + params(Stmt::Lwt, 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())) @@ -2039,7 +2049,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)) + .query_with_params(&query, params(Stmt::Lwt, 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())) } @@ -2148,7 +2158,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() { @@ -2273,7 +2283,7 @@ impl CassandraEngine { ); let dr = self.session - .query_with_values(&delete_query, cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes.clone())) + .query_with_params(&delete_query, params(Stmt::Lwt, 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 })?; @@ -2281,7 +2291,7 @@ impl CassandraEngine { return Ok(()); } self.session - .query_with_values(&update_query, cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes)) + .query_with_params(&update_query, params(Stmt::Lwt, cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes))) .await .map_err(|e| StorageError::Internal(e.to_string())) } @@ -2578,7 +2588,13 @@ 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)) + .query_with_params( + &dq, + params( + Stmt::Lwt, + cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes), + ), + ) .await .map_err(|e| StorageError::Internal(e.to_string())) } @@ -2620,16 +2636,19 @@ impl CassandraEngine { WHERE pk = ? AND {sk_col} = ? IF prepared_txn_id = ?", ); self.session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query::QueryValues::SimpleValues(vec![ - item_data.into(), - next_version.into(), - txn_timestamp.into(), - cdrs_tokio::types::value::Value::from(op.pk.as_str()), - super::index::sk_to_value(sk_val), - txn_id_bytes.into(), - ]), + params( + Stmt::Lwt, + cdrs_tokio::query::QueryValues::SimpleValues(vec![ + item_data.into(), + next_version.into(), + txn_timestamp.into(), + cdrs_tokio::types::value::Value::from(op.pk.as_str()), + super::index::sk_to_value(sk_val), + txn_id_bytes.into(), + ]), + ), ) .await .map_err(|e| StorageError::Internal(e.to_string())) @@ -2641,14 +2660,17 @@ impl CassandraEngine { WHERE pk = ? IF prepared_txn_id = ?", ); self.session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!( - item_data, - next_version, - txn_timestamp, - op.pk.as_str(), - txn_id_bytes + params( + Stmt::Lwt, + cdrs_tokio::query_values!( + item_data, + next_version, + txn_timestamp, + op.pk.as_str(), + txn_id_bytes + ), ), ) .await @@ -2693,9 +2715,12 @@ impl CassandraEngine { ); let r1 = self .session - .query_with_values( + .query_with_params( &update_null, - cdrs_tokio::query_values!(txn_timestamp, op.pk.as_str()), + params( + Stmt::Lwt, + cdrs_tokio::query_values!(txn_timestamp, op.pk.as_str()), + ), ) .await .map_err(|e| StorageError::Internal(e.to_string())) @@ -2711,9 +2736,16 @@ impl CassandraEngine { ); let _ = self .session - .query_with_values( + .query_with_params( &update_cmp, - cdrs_tokio::query_values!(txn_timestamp, op.pk.as_str(), txn_timestamp), + params( + Stmt::Lwt, + cdrs_tokio::query_values!( + txn_timestamp, + op.pk.as_str(), + txn_timestamp + ), + ), ) .await .map_err(|e| StorageError::Internal(e.to_string())) @@ -2736,9 +2768,12 @@ impl CassandraEngine { "DELETE FROM {keyspace}.{table} WHERE pk = ? IF prepared_txn_id = ?", ); self.session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes), + params( + Stmt::Lwt, + cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes), + ), ) .await .map_err(|e| StorageError::Internal(e.to_string())) @@ -2808,9 +2843,12 @@ impl CassandraEngine { ); let dr = self .session - .query_with_values( + .query_with_params( &dq, - cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes.clone()), + params( + Stmt::Lwt, + cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes.clone()), + ), ) .await .map_err(|e| StorageError::Internal(e.to_string())) @@ -2830,9 +2868,12 @@ 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( + .query_with_params( &update_query, - cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes), + params( + Stmt::Lwt, + cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes), + ), ) .await .map_err(|e| StorageError::Internal(e.to_string())) From da61089619b11fe1b0348c4f31cb18747b313567 Mon Sep 17 00:00:00 2001 From: Joel Shepherd Date: Mon, 9 Nov 2026 19:05:11 +0000 Subject: [PATCH 04/12] refactor(storage-cassandra): move TTL, streams and workers onto the consistency policy Stream reads, TTL queue and bucket deletes, and table worker's scans and tag delete now use params(), query_rows and batch(): - The 11 stream reads and the 2 table worker scans run at LOCAL_QUORUM, not ONE. - The TTL queue and bucket DELETEs and the tag DELETE run at LOCAL_QUORUM, not ONE. - The read of system_schema.keyspaces runs at ONE through system_read() (consistent with Cassandra behavior) - The TTL repair batch and the GSI worker batch stay at LOCAL_QUORUM. Refs #770 --- crates/storage-cassandra/src/data/ttl.rs | 26 ++++--- crates/storage-cassandra/src/stream_engine.rs | 75 ++++++++++++++----- crates/storage-cassandra/src/worker_store.rs | 40 +++++----- crates/storage-cassandra/src/workers.rs | 24 ++---- 4 files changed, 98 insertions(+), 67 deletions(-) diff --git a/crates/storage-cassandra/src/data/ttl.rs b/crates/storage-cassandra/src/data/ttl.rs index e2b2b0fea..99b4a6962 100644 --- a/crates/storage-cassandra/src/data/ttl.rs +++ b/crates/storage-cassandra/src/data/ttl.rs @@ -8,6 +8,7 @@ //! indexed into day-bucketed, 64-way sharded partitions and are deleted through //! the normal item mutation path. +use crate::cassandra_util::{Stmt, params}; use cdrs_tokio::query::BatchQueryBuilder; use cdrs_tokio::types::IntoRustByName; use extenddb_core::types::{AttributeValue, Item, TableKeyInfo}; @@ -143,7 +144,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 +320,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 \ @@ -1294,13 +1294,16 @@ pub(crate) async fn clear_ttl_entries( ); engine .session - .query_with_values( + .query_with_params( &delete, - cdrs_tokio::query_values!( - table_id, - cdrs_tokio::types::value::Bytes::new(generation.as_bytes().to_vec()), - bucket, - shard + params( + Stmt::Write, + cdrs_tokio::query_values!( + table_id, + cdrs_tokio::types::value::Bytes::new(generation.as_bytes().to_vec()), + bucket, + shard + ), ), ) .await @@ -1310,7 +1313,10 @@ 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)) + .query_with_params( + &delete_buckets, + params(Stmt::Write, 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/stream_engine.rs b/crates/storage-cassandra/src/stream_engine.rs index 8c83b0927..ab2df0ca2 100755 --- a/crates/storage-cassandra/src/stream_engine.rs +++ b/crates/storage-cassandra/src/stream_engine.rs @@ -3,6 +3,7 @@ //! `StreamEngine` trait implementation for `CassandraEngine`. +use crate::cassandra_util::{Stmt, params}; use cdrs_tokio::types::IntoRustByName; use extenddb_core::types::{ SequenceNumberRange, Shard, StreamDescription, StreamRecord, StreamStatus, StreamSummary, @@ -40,7 +41,10 @@ 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)) + .query_with_params( + &query, + params(Stmt::Read, cdrs_tokio::query_values!(table_id)), + ) .await .map_err(|e| StorageError::Internal(e.to_string()))?; @@ -75,7 +79,13 @@ impl CassandraEngine { ); let result = self .session - .query_with_values(&query, cdrs_tokio::query_values!(account_id, table_name)) + .query_with_params( + &query, + params( + Stmt::Read, + cdrs_tokio::query_values!(account_id, table_name), + ), + ) .await .map_err(|e| StorageError::Internal(e.to_string()))?; let rows = result @@ -167,9 +177,10 @@ impl StreamEngine for CassandraEngine { let shard_query = format!("SELECT table_id 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.query_with_params( + &shard_query, + params(Stmt::Read, cdrs_tokio::query_values!(shard_id.as_str())), + ); let query = if let Some(ref after) = after_sequence { format!( @@ -187,14 +198,20 @@ impl StreamEngine for CassandraEngine { let records_read = async { if let Some(ref after) = after_sequence { self.session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!(shard_id.as_str(), after.as_str()), + params( + Stmt::Read, + cdrs_tokio::query_values!(shard_id.as_str(), after.as_str()), + ), ) .await } else { self.session - .query_with_values(&query, cdrs_tokio::query_values!(shard_id.as_str())) + .query_with_params( + &query, + params(Stmt::Read, cdrs_tokio::query_values!(shard_id.as_str())), + ) .await } }; @@ -261,12 +278,15 @@ impl StreamEngine for CassandraEngine { ); let result = self .session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!( - account_id.as_str(), - table_name.as_str(), - stream_label.as_str() + params( + Stmt::Read, + cdrs_tokio::query_values!( + account_id.as_str(), + table_name.as_str(), + stream_label.as_str() + ), ), ) .await @@ -327,14 +347,20 @@ impl StreamEngine for CassandraEngine { let shard_result = if let Some(ref start) = exclusive_start_shard_id { self.session - .query_with_values( + .query_with_params( &shard_query, - cdrs_tokio::query_values!(table_id.as_str(), start.as_str()), + params( + Stmt::Read, + cdrs_tokio::query_values!(table_id.as_str(), start.as_str()), + ), ) .await } else { self.session - .query_with_values(&shard_query, cdrs_tokio::query_values!(table_id.as_str())) + .query_with_params( + &shard_query, + params(Stmt::Read, cdrs_tokio::query_values!(table_id.as_str())), + ) .await } .map_err(|e| StorageError::Internal(e.to_string()))?; @@ -422,7 +448,10 @@ impl StreamEngine for CassandraEngine { ); let result = self .session - .query_with_values(&query, cdrs_tokio::query_values!(account_id.as_str())) + .query_with_params( + &query, + params(Stmt::Read, cdrs_tokio::query_values!(account_id.as_str())), + ) .await .map_err(|e| StorageError::Internal(e.to_string()))?; @@ -546,9 +575,12 @@ impl StreamEngine for CassandraEngine { ); let shard_result = self .session - .query_with_values( + .query_with_params( &shard_query, - cdrs_tokio::query_values!(shard_id.as_str(), table_id.as_str()), + params( + Stmt::Read, + cdrs_tokio::query_values!(shard_id.as_str(), table_id.as_str()), + ), ) .await .map_err(|e| StorageError::Internal(e.to_string()))?; @@ -579,7 +611,10 @@ impl StreamEngine for CassandraEngine { ); let result = self .session - .query_with_values(&query, cdrs_tokio::query_values!(shard_id.as_str())) + .query_with_params( + &query, + params(Stmt::Read, cdrs_tokio::query_values!(shard_id.as_str())), + ) .await .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..4479a55d7 100755 --- a/crates/storage-cassandra/src/worker_store.rs +++ b/crates/storage-cassandra/src/worker_store.rs @@ -3,6 +3,7 @@ //! `WorkerStore` trait implementation and control plane transition processing. +use crate::cassandra_util::{Stmt, params}; use cdrs_tokio::types::IntoRustByName; use futures::future::BoxFuture; @@ -52,16 +53,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 +93,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 +118,10 @@ 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())) + .query_with_params( + &tag_delete, + params(Stmt::Write, 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 cc23fea0f..3242ed036 100644 --- a/crates/storage-cassandra/src/workers.rs +++ b/crates/storage-cassandra/src/workers.rs @@ -183,19 +183,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(); @@ -430,8 +424,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); @@ -441,7 +433,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); } From 84f84b20b4136ec07d2754984546ac4fe9840d92 Mon Sep 17 00:00:00 2001 From: Joel Shepherd Date: Mon, 9 Nov 2026 20:42:01 +0000 Subject: [PATCH 05/12] refactor(storage-cassandra): move catalog, tables and backup onto the consistency policy The catalog store, table DDL and metadata, the engine and the backup code now use params() and batch(): - Catalog, table, tag, settings and backup reads and writes run at LOCAL_QUORUM, not ONE. - The CreateTable INSERT ... IF NOT EXISTS commits at LOCAL_QUORUM, not ONE, and runs Paxos at LOCAL_SERIAL, not SERIAL. - CREATE KEYSPACE and DROP KEYSPACE run at ONE through Stmt::Ddl. The read of system_schema.keyspaces runs at ONE through Stmt::SystemRead. - The backup catalog's conditional writes, its list read and the batches keep their levels; params() and batch() now set them. Refs #770 --- .../storage-cassandra/src/backup_catalog.rs | 31 ++-- crates/storage-cassandra/src/backup_engine.rs | 76 +++++--- crates/storage-cassandra/src/catalog_store.rs | 167 +++++++++++++----- crates/storage-cassandra/src/create_table.rs | 88 +++++---- crates/storage-cassandra/src/delete_table.rs | 24 ++- crates/storage-cassandra/src/engine.rs | 19 +- crates/storage-cassandra/src/lib.rs | 17 +- .../storage-cassandra/src/metadata_engine.rs | 26 ++- crates/storage-cassandra/src/table_engine.rs | 19 +- crates/storage-cassandra/src/table_helpers.rs | 13 +- crates/storage-cassandra/src/update_table.rs | 3 +- 11 files changed, 334 insertions(+), 149 deletions(-) diff --git a/crates/storage-cassandra/src/backup_catalog.rs b/crates/storage-cassandra/src/backup_catalog.rs index 36f767dd7..81b765d9d 100644 --- a/crates/storage-cassandra/src/backup_catalog.rs +++ b/crates/storage-cassandra/src/backup_catalog.rs @@ -62,13 +62,12 @@ //! 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::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; @@ -179,12 +178,10 @@ 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 + .query_with_params(query, crate::cassandra_util::params(Stmt::Lwt, values)) + .await + { Ok(result) => Ok(if crate::cassandra_util::lwt_applied(&result)? { WriteOutcome::Matched } else { @@ -419,8 +416,7 @@ impl CassandraEngine { async fn remove_index_entries(&self, row: &BackupRow) -> Result<(), StorageError> { let catalog = self.catalog_keyspace(); let created_at = seconds_to_millis(row.created_at); - let batch = BatchQueryBuilder::new() - .with_consistency(Consistency::LocalQuorum) + let batch = crate::cassandra_util::batch() .add_query( format!( "DELETE FROM {catalog}.backup_index_by_status \ @@ -500,8 +496,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 \ @@ -969,8 +964,7 @@ impl BackupCatalog for CassandraEngine { } // The index rows, after the authoritative row. let created_at = seconds_to_millis(row.created_at); - 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, \ @@ -1141,10 +1135,8 @@ 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 params = + crate::cassandra_util::params(Stmt::Read, QueryValues::SimpleValues(values)); let listed = self .session .query_with_params(&query, params) @@ -2331,6 +2323,7 @@ impl MaintenanceClaim for CassandraMaintenanceClaim { 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 ecb73e318..51cf0d023 100755 --- a/crates/storage-cassandra/src/backup_engine.rs +++ b/crates/storage-cassandra/src/backup_engine.rs @@ -70,13 +70,12 @@ //! returns the CREATING description, so a dropped request does not stop the //! restore. +use crate::cassandra_util::{Stmt, params}; 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::{ @@ -593,7 +592,13 @@ impl CassandraEngine { } } self.session - .query_with_values(&delete, cdrs_tokio::query_values!(backup_arn, bucket_i32)) + .query_with_params( + &delete, + params( + Stmt::Read, + cdrs_tokio::query_values!(backup_arn, bucket_i32), + ), + ) .await .map_err(|e| StorageError::Internal(format!("Delete backup payload: {e}")))?; bucket += 1; @@ -606,12 +611,15 @@ impl CassandraEngine { "DELETE FROM {catalog}.backups_by_account WHERE account_id = ? AND created_at = ? AND backup_arn = ?" ); self.session - .query_with_values( + .query_with_params( &by_account, - cdrs_tokio::query_values!( - backup.account_id.as_str(), - backup.created_at, - backup.backup_arn.as_str() + params( + Stmt::Write, + cdrs_tokio::query_values!( + backup.account_id.as_str(), + backup.created_at, + backup.backup_arn.as_str() + ), ), ) .await @@ -621,13 +629,16 @@ 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( + .query_with_params( &by_table, - cdrs_tokio::query_values!( - backup.account_id.as_str(), - backup.table_name.as_str(), - backup.created_at, - backup.backup_arn.as_str() + params( + Stmt::Write, + cdrs_tokio::query_values!( + backup.account_id.as_str(), + backup.table_name.as_str(), + backup.created_at, + backup.backup_arn.as_str() + ), ), ) .await @@ -1202,9 +1213,12 @@ impl CassandraEngine { let bucket_i32 = bucket as i32; let rows = self .session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!(job.backup_arn.as_str(), bucket_i32), + params( + Stmt::Read, + cdrs_tokio::query_values!(job.backup_arn.as_str(), bucket_i32), + ), ) .await .map_err(|e| { @@ -1869,13 +1883,16 @@ impl LegacyBackupReader for CassandraEngine { #[allow(clippy::cast_possible_truncation)] let bucket_i32 = bucket as i32; self.session - .query_with_values( + .query_with_params( &insert_item, - cdrs_tokio::query_values!( - backup_arn.as_str(), - bucket_i32, - item_count, - item_data.as_str() + params( + Stmt::Write, + cdrs_tokio::query_values!( + backup_arn.as_str(), + bucket_i32, + item_count, + item_data.as_str() + ), ), ) .await @@ -1941,8 +1958,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!( @@ -2076,9 +2092,12 @@ impl LegacyBackupReader for CassandraEngine { "SELECT backup_arn FROM {catalog}.backups_by_table WHERE account_id = ? AND table_name = ?" ); self.session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!(account_id.as_str(), table_name), + params( + Stmt::Read, + cdrs_tokio::query_values!(account_id.as_str(), table_name), + ), ) .await } else { @@ -2086,7 +2105,10 @@ 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())) + .query_with_params( + &query, + params(Stmt::Read, cdrs_tokio::query_values!(account_id.as_str())), + ) .await }; let rows = result diff --git a/crates/storage-cassandra/src/catalog_store.rs b/crates/storage-cassandra/src/catalog_store.rs index 50a3c8206..ef1b1380c 100644 --- a/crates/storage-cassandra/src/catalog_store.rs +++ b/crates/storage-cassandra/src/catalog_store.rs @@ -7,6 +7,7 @@ //! `CassandraCatalogStore` wraps a Cassandra session connected to the catalog //! keyspace and implements the operational traits defined in `extenddb_storage`. +use crate::cassandra_util::{Stmt, params}; use std::sync::Arc; use cdrs_tokio::cluster::TcpConnectionManager; @@ -198,7 +199,16 @@ 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 + .query_with_params( + cql, + params( + Stmt::Ddl, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ), + ) + .await + .map_err(|e| failed(&e))?; crate::migrations::migrate_account( self.session.clone(), &self.keyspace_prefix, @@ -215,10 +225,19 @@ 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 + .query_with_params( + cql, + params( + Stmt::Ddl, + 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(()) } @@ -357,9 +376,18 @@ 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 + .query_with_params( + &query, + params( + Stmt::Read, + 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()) @@ -383,9 +411,18 @@ 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 + .query_with_params( + &query, + params( + Stmt::Read, + 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()) @@ -414,11 +451,20 @@ 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 + .query_with_params( + &query, + params( + Stmt::Read, + 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()) @@ -435,11 +481,20 @@ 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 + .query_with_params( + &test_query, + params( + Stmt::Read, + 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); } @@ -474,9 +529,16 @@ impl RateLimitStore for CassandraCatalogStore { AND source_ip = ? ALLOW FILTERING" ); let result = session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!(principal.as_str(), cutoff_ms, source_ip.as_str()), + params( + Stmt::Read, + cdrs_tokio::query_values!( + principal.as_str(), + cutoff_ms, + source_ip.as_str() + ), + ), ) .await .map_err(|e| { @@ -513,9 +575,12 @@ impl RateLimitStore for CassandraCatalogStore { ALLOW FILTERING" ); let result = session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!(source_ip.as_str(), cutoff_ms), + params( + Stmt::Read, + cdrs_tokio::query_values!(source_ip.as_str(), cutoff_ms), + ), ) .await .map_err(|e| { @@ -545,9 +610,12 @@ impl RateLimitStore for CassandraCatalogStore { (principal, attempted_at, success, source_ip) VALUES (?, ?, false, ?)" ); if let Err(e) = session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!(principal.as_str(), now_ms, source_ip.as_deref()), + params( + Stmt::Write, + cdrs_tokio::query_values!(principal.as_str(), now_ms, source_ip.as_deref()), + ), ) .await { @@ -569,7 +637,13 @@ impl RateLimitStore for CassandraCatalogStore { let select = format!("SELECT DISTINCT principal FROM {catalog_keyspace}.login_attempts"); let principals = match session - .query(&select) + .query_with_params( + &select, + params( + Stmt::Read, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ), + ) .await .and_then(|r| r.response_body()) .map(|b| b.into_rows().unwrap_or_default()) @@ -589,9 +663,12 @@ impl RateLimitStore for CassandraCatalogStore { continue; }; if let Err(e) = session - .query_with_values( + .query_with_params( &delete, - cdrs_tokio::query_values!(principal.as_str(), cutoff_ms), + params( + Stmt::Write, + cdrs_tokio::query_values!(principal.as_str(), cutoff_ms), + ), ) .await { @@ -620,18 +697,21 @@ 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( + .query_with_params( &query, - cdrs_tokio::query_values!( - bucket_ms, - row.metric.as_str(), - row.table_name.as_deref().unwrap_or(""), - row.index_name.as_deref().unwrap_or(""), - row.operation.as_deref().unwrap_or(""), - row.sum, - row.count, - row.min, - row.max + params( + Stmt::Write, + cdrs_tokio::query_values!( + bucket_ms, + row.metric.as_str(), + row.table_name.as_deref().unwrap_or(""), + row.index_name.as_deref().unwrap_or(""), + row.operation.as_deref().unwrap_or(""), + row.sum, + row.count, + row.min, + row.max + ), ), ) .await @@ -669,7 +749,10 @@ 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)) + .query_with_params( + &query, + params(Stmt::Read, 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 6758e71e8..b6da563ab 100644 --- a/crates/storage-cassandra/src/create_table.rs +++ b/crates/storage-cassandra/src/create_table.rs @@ -3,6 +3,7 @@ //! `create_table` implementation for `CassandraEngine`. +use crate::cassandra_util::{Stmt, params}; use cdrs_tokio::types::value::Value; use extenddb_core::types::{ BillingMode, BillingModeSummary, CreateTableInput, GsiDescription, LsiDescription, @@ -69,7 +70,17 @@ impl CassandraEngine { // Note: values are interpolated rather than bound because Cassandra LOGGED BATCH // does not support parameterized statements spanning multiple tables. // All interpolated values are server-generated (UUIDs, timestamps, label from chrono). - if let Err(e) = self.session.query(&batch).await { + if let Err(e) = self + .session + .query_with_params( + &batch, + params( + Stmt::Write, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ), + ) + .await + { tracing::error!("init_stream_shards batch: {e}"); // Clear the label so ListStreams does not report a stream with no shards. let clear_cql = format!( @@ -203,9 +214,12 @@ impl CassandraEngine { let delay_query = format!("SELECT value FROM {catalog_keyspace}.settings WHERE key = ?"); let delay_seconds: f64 = self .session - .query_with_values( + .query_with_params( &delay_query, - cdrs_tokio::query_values!("control_plane_delay_seconds"), + params( + Stmt::Read, + cdrs_tokio::query_values!("control_plane_delay_seconds"), + ), ) .await .ok() @@ -329,9 +343,12 @@ impl CassandraEngine { let result = self .session - .query_with_values( + .query_with_params( &insert_table_cql, - cdrs_tokio::query::QueryValues::SimpleValues(values), + params( + Stmt::Lwt, + cdrs_tokio::query::QueryValues::SimpleValues(values), + ), ) .await .map_err(|e| { @@ -418,19 +435,22 @@ impl CassandraEngine { ); self.session - .query_with_values( + .query_with_params( &insert_index_cql, - cdrs_tokio::query::QueryValues::SimpleValues(vec![ - Value::from(table_id.as_str()), - Value::from(gsi.index_name.as_str()), - Value::from(index_id.as_str()), - Value::from(gsi_ks.to_string().as_str()), - Value::from(gsi_proj.to_string().as_str()), - match gsi_pt.as_ref() { - Some(v) => Value::from(v.to_string().as_str()), - None => Value::NotSet, - }, - ]), + params( + Stmt::Write, + cdrs_tokio::query::QueryValues::SimpleValues(vec![ + Value::from(table_id.as_str()), + Value::from(gsi.index_name.as_str()), + Value::from(index_id.as_str()), + Value::from(gsi_ks.to_string().as_str()), + Value::from(gsi_proj.to_string().as_str()), + match gsi_pt.as_ref() { + Some(v) => Value::from(v.to_string().as_str()), + None => Value::NotSet, + }, + ]), + ), ) .await .map_err(|e| { @@ -459,16 +479,19 @@ impl CassandraEngine { ); self.session - .query_with_values( + .query_with_params( &insert_index_cql, - cdrs_tokio::query::QueryValues::SimpleValues(vec![ - Value::from(table_id.as_str()), - Value::from(lsi.index_name.as_str()), - Value::from(index_id.as_str()), - Value::from(lsi_ks.to_string().as_str()), - Value::from(lsi_proj.to_string().as_str()), - Value::NotSet, - ]), + params( + Stmt::Write, + cdrs_tokio::query::QueryValues::SimpleValues(vec![ + Value::from(table_id.as_str()), + Value::from(lsi.index_name.as_str()), + Value::from(index_id.as_str()), + Value::from(lsi_ks.to_string().as_str()), + Value::from(lsi_proj.to_string().as_str()), + Value::NotSet, + ]), + ), ) .await .map_err(|e| { @@ -488,12 +511,15 @@ impl CassandraEngine { ); self.session - .query_with_values( + .query_with_params( &insert_tag_cql, - cdrs_tokio::query_values!( - table_arn.as_str(), - tag.key.as_str(), - tag.value.as_str() + params( + Stmt::Write, + cdrs_tokio::query_values!( + table_arn.as_str(), + tag.key.as_str(), + tag.value.as_str() + ), ), ) .await diff --git a/crates/storage-cassandra/src/delete_table.rs b/crates/storage-cassandra/src/delete_table.rs index 052bc4e92..f2cf0aefc 100644 --- a/crates/storage-cassandra/src/delete_table.rs +++ b/crates/storage-cassandra/src/delete_table.rs @@ -3,6 +3,7 @@ //! `delete_table` implementation for `CassandraEngine`. +use crate::cassandra_util::{Stmt, params}; use cdrs_tokio::types::IntoRustByName; use extenddb_core::types::{DeleteTableInput, TableDescription}; use extenddb_storage::error::StorageError; @@ -53,9 +54,12 @@ impl CassandraEngine { let table_result = self .session - .query_with_values( + .query_with_params( &table_query, - cdrs_tokio::query_values!(account_id, input.table_name.as_str()), + params( + Stmt::Read, + cdrs_tokio::query_values!(account_id, input.table_name.as_str()), + ), ) .await .map_err(|e| StorageError::Internal(format!("Query table: {e}")))?; @@ -114,7 +118,10 @@ impl CassandraEngine { let index_result = self .session - .query_with_values(&index_query, cdrs_tokio::query_values!(table_id.as_str())) + .query_with_params( + &index_query, + params(Stmt::Read, cdrs_tokio::query_values!(table_id.as_str())), + ) .await .map_err(|e| StorageError::Internal(format!("Query indexes: {e}")))?; @@ -156,9 +163,9 @@ impl CassandraEngine { let delete_indexes_query = format!("DELETE FROM {catalog_keyspace}.indexes WHERE table_id = ?"); self.session - .query_with_values( + .query_with_params( &delete_indexes_query, - cdrs_tokio::query_values!(table_id.as_str()), + params(Stmt::Write, cdrs_tokio::query_values!(table_id.as_str())), ) .await .map_err(|e| StorageError::Internal(format!("Delete indexes: {e}")))?; @@ -167,9 +174,12 @@ impl CassandraEngine { let delete_tags_query = format!("DELETE FROM {catalog_keyspace}.tags WHERE resource_arn = ?"); self.session - .query_with_values( + .query_with_params( &delete_tags_query, - cdrs_tokio::query_values!(description.table_arn.as_str()), + params( + Stmt::Write, + cdrs_tokio::query_values!(description.table_arn.as_str()), + ), ) .await .map_err(|e| StorageError::Internal(format!("Delete tags: {e}")))?; diff --git a/crates/storage-cassandra/src/engine.rs b/crates/storage-cassandra/src/engine.rs index 474e32043..5042dc657 100644 --- a/crates/storage-cassandra/src/engine.rs +++ b/crates/storage-cassandra/src/engine.rs @@ -3,6 +3,7 @@ //! Cassandra storage engine implementation. +use crate::cassandra_util::{Stmt, params}; use std::sync::Arc; use cdrs_tokio::authenticators::{NoneAuthenticatorProvider, StaticPasswordAuthenticatorProvider}; @@ -275,7 +276,13 @@ impl CassandraEngine { ); self.session - .query(cql) + .query_with_params( + cql, + params( + Stmt::Ddl, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ), + ) .await .map_err(|e| StorageError::Internal(format!("Failed to create keyspace: {e}")))?; @@ -287,7 +294,13 @@ impl CassandraEngine { let cql = format!("DROP KEYSPACE IF EXISTS {keyspace_name}"); self.session - .query(cql) + .query_with_params( + cql, + params( + Stmt::Ddl, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ), + ) .await .map_err(|e| StorageError::Internal(format!("Failed to drop keyspace: {e}")))?; @@ -300,7 +313,7 @@ impl CassandraEngine { let rows = self .session - .query_with_values(cql, query_values!(keyspace_name)) + .query_with_params(cql, params(Stmt::SystemRead, 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 bcc0b9d0c..de1dead52 100644 --- a/crates/storage-cassandra/src/lib.rs +++ b/crates/storage-cassandra/src/lib.rs @@ -52,6 +52,7 @@ pub use config::CassandraStorageConfig; pub use engine::{CassandraEngine, CassandraSession}; pub use metadata_engine::TtlBackfillCursor; +use crate::cassandra_util::{Stmt, params}; use cdrs_tokio::types::IntoRustByName; use extenddb_storage::hooks::{ServerRuntimeHooks, ServingRegistrar, WorkerContext}; use extenddb_storage::server_components::{BackendError, ServerComponents}; @@ -364,9 +365,19 @@ 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 + .query_with_params( + &enc_key_query, + params( + Stmt::Read, + 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/metadata_engine.rs b/crates/storage-cassandra/src/metadata_engine.rs index 94c9bfd58..8631ed453 100755 --- a/crates/storage-cassandra/src/metadata_engine.rs +++ b/crates/storage-cassandra/src/metadata_engine.rs @@ -3,6 +3,7 @@ //! `MetadataEngine` trait implementation for `CassandraEngine`. +use crate::cassandra_util::{Stmt, params}; use cdrs_tokio::types::IntoRustByName; use extenddb_core::types::{Item, Tag, TimeToLiveDescription, TimeToLiveStatus}; use extenddb_storage::MetadataEngine; @@ -1106,12 +1107,15 @@ impl MetadataEngine for CassandraEngine { "INSERT INTO {catalog}.tags (resource_arn, tag_key, tag_value) VALUES (?, ?, ?)" ); self.session_arc() - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!( - arn.as_str(), - tag.key.as_str(), - tag.value.as_str() + params( + Stmt::Write, + cdrs_tokio::query_values!( + arn.as_str(), + tag.key.as_str(), + tag.value.as_str() + ), ), ) .await @@ -1137,9 +1141,12 @@ impl MetadataEngine for CassandraEngine { let query = format!("DELETE FROM {catalog}.tags WHERE resource_arn = ? AND tag_key = ?"); self.session_arc() - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!(arn.as_str(), key.as_str()), + params( + Stmt::Write, + cdrs_tokio::query_values!(arn.as_str(), key.as_str()), + ), ) .await .map_err(|error| { @@ -1159,7 +1166,10 @@ 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())) + .query_with_params( + &query, + params(Stmt::Read, cdrs_tokio::query_values!(arn.as_str())), + ) .await .map_err(|e| { tracing::error!("list_tags: {e}"); diff --git a/crates/storage-cassandra/src/table_engine.rs b/crates/storage-cassandra/src/table_engine.rs index d2ffdb56f..28943cecf 100644 --- a/crates/storage-cassandra/src/table_engine.rs +++ b/crates/storage-cassandra/src/table_engine.rs @@ -3,6 +3,7 @@ //! `TableEngine` trait implementation for `CassandraEngine`. +use crate::cassandra_util::{Stmt, params}; use cdrs_tokio::types::IntoRustByName; use futures::future::BoxFuture; @@ -69,16 +70,26 @@ impl TableEngine for CassandraEngine { let result = if let Some(ref start) = input.exclusive_start_table_name { self.session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!(account_id.as_str(), start.as_str(), limit + 1), + params( + Stmt::Read, + cdrs_tokio::query_values!( + account_id.as_str(), + start.as_str(), + limit + 1 + ), + ), ) .await } else { self.session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!(account_id.as_str(), limit + 1), + params( + Stmt::Read, + cdrs_tokio::query_values!(account_id.as_str(), limit + 1), + ), ) .await }; diff --git a/crates/storage-cassandra/src/table_helpers.rs b/crates/storage-cassandra/src/table_helpers.rs index 94b6eb0cf..c37f26e13 100644 --- a/crates/storage-cassandra/src/table_helpers.rs +++ b/crates/storage-cassandra/src/table_helpers.rs @@ -3,6 +3,7 @@ //! Helper methods for `TableEngine` operations. +use crate::cassandra_util::{Stmt, params}; use cdrs_tokio::types::{IntoRustByName, rows::Row}; use extenddb_core::types::{ BillingMode, BillingModeSummary, GsiDescription, LsiDescription, @@ -34,9 +35,12 @@ impl CassandraEngine { let table_result = self .session - .query_with_values( + .query_with_params( &table_query, - cdrs_tokio::query_values!(account_id, table_name), + params( + Stmt::Read, + cdrs_tokio::query_values!(account_id, table_name), + ), ) .await .map_err(|e| StorageError::Internal(format!("Query tables failed: {e}")))?; @@ -63,7 +67,10 @@ impl CassandraEngine { let index_result = self .session - .query_with_values(&index_query, cdrs_tokio::query_values!(table_id.as_str())) + .query_with_params( + &index_query, + params(Stmt::Read, 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/update_table.rs b/crates/storage-cassandra/src/update_table.rs index 4a20b8618..2a908db10 100644 --- a/crates/storage-cassandra/src/update_table.rs +++ b/crates/storage-cassandra/src/update_table.rs @@ -3,7 +3,6 @@ //! `update_table` implementation for the Cassandra backend. -use cdrs_tokio::consistency::Consistency; use cdrs_tokio::query::BatchQueryBuilder; use cdrs_tokio::query::QueryValues; use cdrs_tokio::types::IntoRustByName; @@ -108,7 +107,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 { From 25ad86901975595eecf63b2e5e0966d58f535552 Mon Sep 17 00:00:00 2001 From: Joel Shepherd Date: Mon, 9 Nov 2026 21:51:56 +0000 Subject: [PATCH 06/12] refactor(storage-cassandra): move IAM and bootstrap onto the consistency policy refactor(storage-cassandra): move IAM and bootstrap onto the consistency policy The IAM, credential, admin and account stores and the bootstrapper now use params(): - IAM policy, group, boundary, session and tag reads, and access key reads, run at LOCAL_QUORUM, not ONE. - The admin, account and access key LWTs commit at LOCAL_QUORUM, not ONE, and run Paxos at LOCAL_SERIAL, not SERIAL. - The self-service policy INSERT runs at LOCAL_QUORUM, not ONE. - init's reads of system_auth and of the catalog run at LOCAL_QUORUM, not ONE. - CREATE ROLE and GRANT use Stmt::Ddl. Cassandra ignores the client's consistency level for these statements. - The read of system_schema.keyspaces runs at ONE through Stmt::SystemRead. Refs #770 --- crates/storage-cassandra/src/admin_store.rs | 8 ++- .../src/authorization_store.rs | 61 ++++++++++++----- crates/storage-cassandra/src/bootstrapper.rs | 68 +++++++++++++++---- .../storage-cassandra/src/credential_store.rs | 11 ++- .../src/management_store/access_keys.rs | 8 ++- .../src/management_store/accounts.rs | 9 ++- .../src/management_store/users.rs | 14 ++-- 7 files changed, 135 insertions(+), 44 deletions(-) diff --git a/crates/storage-cassandra/src/admin_store.rs b/crates/storage-cassandra/src/admin_store.rs index 2189233b9..8d14b52ef 100755 --- a/crates/storage-cassandra/src/admin_store.rs +++ b/crates/storage-cassandra/src/admin_store.rs @@ -3,6 +3,7 @@ //! `AdminStore` implementation for `CassandraCatalogStore`. +use crate::cassandra_util::{Stmt, params}; use cdrs_tokio::types::IntoRustByName; use extenddb_storage::management_store::{AdminEntry, OpError, OpResult}; use futures::future::BoxFuture; @@ -39,9 +40,12 @@ impl extenddb_storage::management_store::AdminStore for CassandraCatalogStore { ); let result = session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!(admin_name.as_str(), password_hash.as_str()), + params( + Stmt::Lwt, + cdrs_tokio::query_values!(admin_name.as_str(), password_hash.as_str()), + ), ) .await .map_err(|e| { diff --git a/crates/storage-cassandra/src/authorization_store.rs b/crates/storage-cassandra/src/authorization_store.rs index b66bf0402..f5a43faf0 100755 --- a/crates/storage-cassandra/src/authorization_store.rs +++ b/crates/storage-cassandra/src/authorization_store.rs @@ -3,6 +3,7 @@ //! `AuthorizationStore` implementation for `CassandraCatalogStore`. +use crate::cassandra_util::{Stmt, params}; use cdrs_tokio::types::IntoRustByName; use extenddb_storage::authorization_store::{AuthorizationStore, SessionData}; use extenddb_storage::management_store::{OpError, OpResult}; @@ -26,9 +27,12 @@ impl AuthorizationStore for CassandraCatalogStore { WHERE account_id = ? AND principal_type = 'user' AND principal_name = ?" ); let result = session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!(account_id.as_str(), user_name.as_str()), + params( + Stmt::Read, + cdrs_tokio::query_values!(account_id.as_str(), user_name.as_str()), + ), ) .await .map_err(|e| { @@ -73,9 +77,12 @@ impl AuthorizationStore for CassandraCatalogStore { WHERE account_id = ? AND user_name = ? ALLOW FILTERING" ); let groups_result = session - .query_with_values( + .query_with_params( &groups_query, - cdrs_tokio::query_values!(account_id.as_str(), user_name.as_str()), + params( + Stmt::Read, + cdrs_tokio::query_values!(account_id.as_str(), user_name.as_str()), + ), ) .await .map_err(|e| { @@ -103,9 +110,12 @@ impl AuthorizationStore for CassandraCatalogStore { WHERE account_id = ? AND principal_type = 'group' AND principal_name = ?" ); let policy_result = session - .query_with_values( + .query_with_params( &policy_query, - cdrs_tokio::query_values!(account_id.as_str(), group_name.as_str()), + params( + Stmt::Read, + cdrs_tokio::query_values!(account_id.as_str(), group_name.as_str()), + ), ) .await .map_err(|e| { @@ -151,9 +161,12 @@ impl AuthorizationStore for CassandraCatalogStore { WHERE account_id = ? AND principal_type = 'user' AND principal_name = ?" ); let result = session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!(account_id.as_str(), user_name.as_str()), + params( + Stmt::Read, + cdrs_tokio::query_values!(account_id.as_str(), user_name.as_str()), + ), ) .await .map_err(|e| { @@ -266,12 +279,15 @@ impl AuthorizationStore for CassandraCatalogStore { ); let result = session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!( - account_id.as_str(), - role_name.as_str(), - session_name.as_str() + params( + Stmt::Read, + cdrs_tokio::query_values!( + account_id.as_str(), + role_name.as_str(), + session_name.as_str() + ), ), ) .await @@ -354,9 +370,12 @@ impl AuthorizationStore for CassandraCatalogStore { ); let result = session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!(account_id.as_str(), user_name.as_str()), + params( + Stmt::Read, + cdrs_tokio::query_values!(account_id.as_str(), user_name.as_str()), + ), ) .await .map_err(|e| { @@ -408,9 +427,12 @@ impl AuthorizationStore for CassandraCatalogStore { ); let result = session - .query_with_values( + .query_with_params( &query, - cdrs_tokio::query_values!(account_id.as_str(), role_name.as_str()), + params( + Stmt::Read, + cdrs_tokio::query_values!(account_id.as_str(), role_name.as_str()), + ), ) .await .map_err(|e| { @@ -456,7 +478,10 @@ impl AuthorizationStore for CassandraCatalogStore { ); let result = session - .query_with_values(&query, cdrs_tokio::query_values!(arn.as_str())) + .query_with_params( + &query, + params(Stmt::Read, 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/bootstrapper.rs b/crates/storage-cassandra/src/bootstrapper.rs index caf9ecc2b..a18c62c1c 100644 --- a/crates/storage-cassandra/src/bootstrapper.rs +++ b/crates/storage-cassandra/src/bootstrapper.rs @@ -3,6 +3,7 @@ //! Cassandra implementation of `Bootstrapper`. +use crate::cassandra_util::{Stmt, params}; use async_trait::async_trait; use cdrs_tokio::TryFromRow; use cdrs_tokio::frame::TryFromRow as TryFromRowTrait; @@ -415,7 +416,10 @@ impl Bootstrapper for CassandraBootstrapper { let exists = self .engine .session() - .query_with_values(check_cql, cdrs_tokio::query_values!(user.as_str())) + .query_with_params( + check_cql, + params(Stmt::Read, cdrs_tokio::query_values!(user.as_str())), + ) .await .ok() .and_then(|frame| frame.response_body().ok()) @@ -452,7 +456,13 @@ impl Bootstrapper for CassandraBootstrapper { ); self.engine .session() - .query(create_cql) + .query_with_params( + create_cql, + params( + Stmt::Ddl, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ), + ) .await .map_err(|e| OpError::Internal(format!("Create user: {e}")))?; @@ -471,11 +481,14 @@ impl Bootstrapper for CassandraBootstrapper { let already_granted = self .engine .session() - .query_with_values( + .query_with_params( check_cql, - cdrs_tokio::query_values!( - self.config.app_user.as_str(), - self.config.admin_user.as_str() + params( + Stmt::Read, + cdrs_tokio::query_values!( + self.config.app_user.as_str(), + self.config.admin_user.as_str() + ), ), ) .await @@ -492,12 +505,22 @@ 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() + .query_with_params( + grant_cql, + params( + Stmt::Ddl, + 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(()) } @@ -704,7 +727,18 @@ 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() + .query_with_params( + cql, + params( + Stmt::Read, + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), + ), + ) + .await + { Ok(frame) => frame .response_body() .ok() @@ -743,7 +777,13 @@ impl Bootstrapper for CassandraBootstrapper { let rows = self .engine .session() - .query(cql) + .query_with_params( + cql, + params( + Stmt::SystemRead, + 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/credential_store.rs b/crates/storage-cassandra/src/credential_store.rs index 26a00ef9b..913e84c39 100644 --- a/crates/storage-cassandra/src/credential_store.rs +++ b/crates/storage-cassandra/src/credential_store.rs @@ -7,6 +7,7 @@ //! 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::{Stmt, params}; use std::sync::Arc; use async_trait::async_trait; @@ -84,7 +85,10 @@ impl CassandraCredentialStore { let result = self .session - .query_with_values(&query, cdrs_tokio::query_values!(access_key_id)) + .query_with_params( + &query, + params(Stmt::Read, cdrs_tokio::query_values!(access_key_id)), + ) .await .map_err(|e| { tracing::error!("Credential lookup failed for access key {access_key_id}: {e}"); @@ -159,7 +163,10 @@ impl CassandraCredentialStore { let result = self .session - .query_with_values(&query, cdrs_tokio::query_values!(access_key_id)) + .query_with_params( + &query, + params(Stmt::Read, cdrs_tokio::query_values!(access_key_id)), + ) .await .map_err(|e| { tracing::error!( diff --git a/crates/storage-cassandra/src/management_store/access_keys.rs b/crates/storage-cassandra/src/management_store/access_keys.rs index 5e2f409ae..f12a583f3 100755 --- a/crates/storage-cassandra/src/management_store/access_keys.rs +++ b/crates/storage-cassandra/src/management_store/access_keys.rs @@ -3,6 +3,7 @@ //! Access key, session, and caller-tag operations for `CassandraCatalogStore`. +use crate::cassandra_util::{Stmt, params}; use crate::catalog_store::CassandraCatalogStore; use cdrs_tokio::types::IntoRustByName; use cdrs_tokio::types::blob::Blob; @@ -98,9 +99,12 @@ impl CassandraCatalogStore { let result = self .session() - .query_with_values( + .query_with_params( &delete_query, - cdrs_tokio::query_values!(key_id, account_id, user_name), + params( + Stmt::Lwt, + cdrs_tokio::query_values!(key_id, account_id, user_name), + ), ) .await .map_err(|e| OpError::Internal(e.to_string()))?; diff --git a/crates/storage-cassandra/src/management_store/accounts.rs b/crates/storage-cassandra/src/management_store/accounts.rs index 1fd9b2179..76f76f1e4 100644 --- a/crates/storage-cassandra/src/management_store/accounts.rs +++ b/crates/storage-cassandra/src/management_store/accounts.rs @@ -3,6 +3,7 @@ //! Account management operations for `CassandraCatalogStore`. +use crate::cassandra_util::{Stmt, params}; use cdrs_tokio::types::IntoRustByName; use extenddb_storage::management_store::{AccountDetail, OpError, OpResult}; @@ -32,7 +33,13 @@ impl CassandraCatalogStore { let result = self .session() - .query_with_values(&query, cdrs_tokio::query_values!(account_id, account_name)) + .query_with_params( + &query, + params( + Stmt::Lwt, + cdrs_tokio::query_values!(account_id, account_name), + ), + ) .await .map_err(|e| { tracing::error!("create_account query failed: {e}"); diff --git a/crates/storage-cassandra/src/management_store/users.rs b/crates/storage-cassandra/src/management_store/users.rs index 0db1e676d..f6e0f0dbe 100644 --- a/crates/storage-cassandra/src/management_store/users.rs +++ b/crates/storage-cassandra/src/management_store/users.rs @@ -3,6 +3,7 @@ //! User management operations for `CassandraCatalogStore`. +use crate::cassandra_util::{Stmt, params}; use crate::catalog_store::CassandraCatalogStore; use cdrs_tokio::types::IntoRustByName; use extenddb_storage::management_store::{OpError, OpResult, UserDetail}; @@ -72,12 +73,15 @@ impl CassandraCatalogStore { ); session - .query_with_values( + .query_with_params( &policy_query, - cdrs_tokio::query_values!( - account_id.as_str(), - user_name.as_str(), - self_service_policy.to_string().as_str() + params( + Stmt::Write, + cdrs_tokio::query_values!( + account_id.as_str(), + user_name.as_str(), + self_service_policy.to_string().as_str() + ), ), ) .await From 334575ad0f902910a10186aaddee5bf4f8b9083a Mon Sep 17 00:00:00 2001 From: Joel Shepherd Date: Mon, 9 Nov 2026 23:45:05 +0000 Subject: [PATCH 07/12] refactor(storage-cassandra): check each statement against its declared 'kind' Add PolicySession::run, which runs one statement at the level that params() gives its kind. In a debug build, run() panics when the CQL does not match the kind (shape_error): a read must be a SELECT, a write must have no IF condition, an LWT must have one, and DDL must be CREATE, ALTER, DROP, GRANT or REVOKE. Every helper and every statement outside cassandra_util.rs and migrations/ now goes through run(). The check found two statements with the wrong kind: - The backup payload DELETE used Stmt::Read. It now uses Stmt::Write. Both run at LOCAL_QUORUM. - A transaction ledger test sent an LWT through execute(). It now uses apply_lwt() and asserts that the fence applied. Refs #770 --- crates/storage-cassandra/src/admin_store.rs | 11 +- .../src/authorization_store.rs | 70 ++--- .../storage-cassandra/src/backup_catalog.rs | 10 +- crates/storage-cassandra/src/backup_engine.rs | 78 +++-- crates/storage-cassandra/src/bootstrapper.rs | 52 ++-- .../storage-cassandra/src/cassandra_util.rs | 281 ++++++++++++++++-- crates/storage-cassandra/src/catalog_store.rs | 126 ++++---- crates/storage-cassandra/src/create_table.rs | 91 +++--- .../storage-cassandra/src/credential_store.rs | 13 +- .../storage-cassandra/src/data/delete_item.rs | 18 +- crates/storage-cassandra/src/data/mod.rs | 5 +- .../src/data/put_get_item.rs | 13 +- .../src/data/transaction_ledger.rs | 51 ++-- .../src/data/transactions.rs | 152 ++++------ crates/storage-cassandra/src/data/ttl.rs | 24 +- .../storage-cassandra/src/data/update_item.rs | 5 +- crates/storage-cassandra/src/delete_table.rs | 29 +- crates/storage-cassandra/src/engine.rs | 21 +- crates/storage-cassandra/src/lib.rs | 11 +- .../src/management_store/access_keys.rs | 11 +- .../src/management_store/accounts.rs | 11 +- .../src/management_store/users.rs | 17 +- .../storage-cassandra/src/metadata_engine.rs | 30 +- crates/storage-cassandra/src/stream_engine.rs | 79 +++-- crates/storage-cassandra/src/table_engine.rs | 23 +- crates/storage-cassandra/src/table_helpers.rs | 16 +- crates/storage-cassandra/src/worker_store.rs | 8 +- .../tests/direct/transaction_ledger.rs | 19 +- 28 files changed, 680 insertions(+), 595 deletions(-) diff --git a/crates/storage-cassandra/src/admin_store.rs b/crates/storage-cassandra/src/admin_store.rs index 8d14b52ef..f61cb427f 100755 --- a/crates/storage-cassandra/src/admin_store.rs +++ b/crates/storage-cassandra/src/admin_store.rs @@ -3,7 +3,8 @@ //! `AdminStore` implementation for `CassandraCatalogStore`. -use crate::cassandra_util::{Stmt, params}; +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; @@ -40,12 +41,10 @@ impl extenddb_storage::management_store::AdminStore for CassandraCatalogStore { ); let result = session - .query_with_params( + .run( + Stmt::Lwt, &query, - params( - Stmt::Lwt, - cdrs_tokio::query_values!(admin_name.as_str(), password_hash.as_str()), - ), + cdrs_tokio::query_values!(admin_name.as_str(), password_hash.as_str()), ) .await .map_err(|e| { diff --git a/crates/storage-cassandra/src/authorization_store.rs b/crates/storage-cassandra/src/authorization_store.rs index f5a43faf0..93f01d3bc 100755 --- a/crates/storage-cassandra/src/authorization_store.rs +++ b/crates/storage-cassandra/src/authorization_store.rs @@ -3,7 +3,8 @@ //! `AuthorizationStore` implementation for `CassandraCatalogStore`. -use crate::cassandra_util::{Stmt, params}; +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}; @@ -27,12 +28,10 @@ impl AuthorizationStore for CassandraCatalogStore { WHERE account_id = ? AND principal_type = 'user' AND principal_name = ?" ); let result = session - .query_with_params( + .run( + Stmt::Read, &query, - params( - Stmt::Read, - cdrs_tokio::query_values!(account_id.as_str(), user_name.as_str()), - ), + cdrs_tokio::query_values!(account_id.as_str(), user_name.as_str()), ) .await .map_err(|e| { @@ -77,12 +76,10 @@ impl AuthorizationStore for CassandraCatalogStore { WHERE account_id = ? AND user_name = ? ALLOW FILTERING" ); let groups_result = session - .query_with_params( + .run( + Stmt::Read, &groups_query, - params( - Stmt::Read, - cdrs_tokio::query_values!(account_id.as_str(), user_name.as_str()), - ), + cdrs_tokio::query_values!(account_id.as_str(), user_name.as_str()), ) .await .map_err(|e| { @@ -110,12 +107,10 @@ impl AuthorizationStore for CassandraCatalogStore { WHERE account_id = ? AND principal_type = 'group' AND principal_name = ?" ); let policy_result = session - .query_with_params( + .run( + Stmt::Read, &policy_query, - params( - Stmt::Read, - cdrs_tokio::query_values!(account_id.as_str(), group_name.as_str()), - ), + cdrs_tokio::query_values!(account_id.as_str(), group_name.as_str()), ) .await .map_err(|e| { @@ -161,12 +156,10 @@ impl AuthorizationStore for CassandraCatalogStore { WHERE account_id = ? AND principal_type = 'user' AND principal_name = ?" ); let result = session - .query_with_params( + .run( + Stmt::Read, &query, - params( - Stmt::Read, - cdrs_tokio::query_values!(account_id.as_str(), user_name.as_str()), - ), + cdrs_tokio::query_values!(account_id.as_str(), user_name.as_str()), ) .await .map_err(|e| { @@ -279,15 +272,13 @@ impl AuthorizationStore for CassandraCatalogStore { ); let result = session - .query_with_params( + .run( + Stmt::Read, &query, - params( - Stmt::Read, - cdrs_tokio::query_values!( - account_id.as_str(), - role_name.as_str(), - session_name.as_str() - ), + cdrs_tokio::query_values!( + account_id.as_str(), + role_name.as_str(), + session_name.as_str() ), ) .await @@ -370,12 +361,10 @@ impl AuthorizationStore for CassandraCatalogStore { ); let result = session - .query_with_params( + .run( + Stmt::Read, &query, - params( - Stmt::Read, - cdrs_tokio::query_values!(account_id.as_str(), user_name.as_str()), - ), + cdrs_tokio::query_values!(account_id.as_str(), user_name.as_str()), ) .await .map_err(|e| { @@ -427,12 +416,10 @@ impl AuthorizationStore for CassandraCatalogStore { ); let result = session - .query_with_params( + .run( + Stmt::Read, &query, - params( - Stmt::Read, - cdrs_tokio::query_values!(account_id.as_str(), role_name.as_str()), - ), + cdrs_tokio::query_values!(account_id.as_str(), role_name.as_str()), ) .await .map_err(|e| { @@ -478,10 +465,7 @@ impl AuthorizationStore for CassandraCatalogStore { ); let result = session - .query_with_params( - &query, - params(Stmt::Read, 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 81b765d9d..2d97d52ff 100644 --- a/crates/storage-cassandra/src/backup_catalog.rs +++ b/crates/storage-cassandra/src/backup_catalog.rs @@ -62,6 +62,7 @@ //! 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; @@ -178,10 +179,7 @@ pub(crate) async fn conditional_write( query: &str, values: QueryValues, ) -> Result { - match session - .query_with_params(query, crate::cassandra_util::params(Stmt::Lwt, values)) - .await - { + match session.run(Stmt::Lwt, query, values).await { Ok(result) => Ok(if crate::cassandra_util::lwt_applied(&result)? { WriteOutcome::Matched } else { @@ -1135,11 +1133,9 @@ impl BackupCatalog for CassandraEngine { query.push_str(" AND created_at < ?"); values.push(Value::from((upper * 1_000.0).ceil() as i64)); } - let params = - crate::cassandra_util::params(Stmt::Read, QueryValues::SimpleValues(values)); 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() diff --git a/crates/storage-cassandra/src/backup_engine.rs b/crates/storage-cassandra/src/backup_engine.rs index 51cf0d023..92433740f 100755 --- a/crates/storage-cassandra/src/backup_engine.rs +++ b/crates/storage-cassandra/src/backup_engine.rs @@ -70,7 +70,8 @@ //! returns the CREATING description, so a dropped request does not stop the //! restore. -use crate::cassandra_util::{Stmt, params}; +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}; @@ -592,12 +593,10 @@ impl CassandraEngine { } } self.session - .query_with_params( + .run( + Stmt::Write, &delete, - params( - Stmt::Read, - cdrs_tokio::query_values!(backup_arn, bucket_i32), - ), + cdrs_tokio::query_values!(backup_arn, bucket_i32), ) .await .map_err(|e| StorageError::Internal(format!("Delete backup payload: {e}")))?; @@ -611,15 +610,13 @@ impl CassandraEngine { "DELETE FROM {catalog}.backups_by_account WHERE account_id = ? AND created_at = ? AND backup_arn = ?" ); self.session - .query_with_params( + .run( + Stmt::Write, &by_account, - params( - Stmt::Write, - cdrs_tokio::query_values!( - backup.account_id.as_str(), - backup.created_at, - backup.backup_arn.as_str() - ), + cdrs_tokio::query_values!( + backup.account_id.as_str(), + backup.created_at, + backup.backup_arn.as_str() ), ) .await @@ -629,16 +626,14 @@ impl CassandraEngine { "DELETE FROM {catalog}.backups_by_table WHERE account_id = ? AND table_name = ? AND created_at = ? AND backup_arn = ?" ); self.session - .query_with_params( + .run( + Stmt::Write, &by_table, - params( - Stmt::Write, - cdrs_tokio::query_values!( - backup.account_id.as_str(), - backup.table_name.as_str(), - backup.created_at, - backup.backup_arn.as_str() - ), + cdrs_tokio::query_values!( + backup.account_id.as_str(), + backup.table_name.as_str(), + backup.created_at, + backup.backup_arn.as_str() ), ) .await @@ -1213,12 +1208,10 @@ impl CassandraEngine { let bucket_i32 = bucket as i32; let rows = self .session - .query_with_params( + .run( + Stmt::Read, &query, - params( - Stmt::Read, - cdrs_tokio::query_values!(job.backup_arn.as_str(), bucket_i32), - ), + cdrs_tokio::query_values!(job.backup_arn.as_str(), bucket_i32), ) .await .map_err(|e| { @@ -1883,16 +1876,14 @@ impl LegacyBackupReader for CassandraEngine { #[allow(clippy::cast_possible_truncation)] let bucket_i32 = bucket as i32; self.session - .query_with_params( + .run( + Stmt::Write, &insert_item, - params( - Stmt::Write, - cdrs_tokio::query_values!( - backup_arn.as_str(), - bucket_i32, - item_count, - item_data.as_str() - ), + cdrs_tokio::query_values!( + backup_arn.as_str(), + bucket_i32, + item_count, + item_data.as_str() ), ) .await @@ -2092,12 +2083,10 @@ impl LegacyBackupReader for CassandraEngine { "SELECT backup_arn FROM {catalog}.backups_by_table WHERE account_id = ? AND table_name = ?" ); self.session - .query_with_params( + .run( + Stmt::Read, &query, - params( - Stmt::Read, - cdrs_tokio::query_values!(account_id.as_str(), table_name), - ), + cdrs_tokio::query_values!(account_id.as_str(), table_name), ) .await } else { @@ -2105,9 +2094,10 @@ impl LegacyBackupReader for CassandraEngine { "SELECT backup_arn FROM {catalog}.backups_by_account WHERE account_id = ?" ); self.session - .query_with_params( + .run( + Stmt::Read, &query, - params(Stmt::Read, cdrs_tokio::query_values!(account_id.as_str())), + cdrs_tokio::query_values!(account_id.as_str()), ) .await }; diff --git a/crates/storage-cassandra/src/bootstrapper.rs b/crates/storage-cassandra/src/bootstrapper.rs index a18c62c1c..37f1a6aa8 100644 --- a/crates/storage-cassandra/src/bootstrapper.rs +++ b/crates/storage-cassandra/src/bootstrapper.rs @@ -3,7 +3,8 @@ //! Cassandra implementation of `Bootstrapper`. -use crate::cassandra_util::{Stmt, params}; +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; @@ -416,9 +417,10 @@ impl Bootstrapper for CassandraBootstrapper { let exists = self .engine .session() - .query_with_params( + .run( + Stmt::Read, check_cql, - params(Stmt::Read, cdrs_tokio::query_values!(user.as_str())), + cdrs_tokio::query_values!(user.as_str()), ) .await .ok() @@ -456,12 +458,10 @@ impl Bootstrapper for CassandraBootstrapper { ); self.engine .session() - .query_with_params( + .run( + Stmt::Ddl, create_cql, - params( - Stmt::Ddl, - cdrs_tokio::query::QueryValues::SimpleValues(vec![]), - ), + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), ) .await .map_err(|e| OpError::Internal(format!("Create user: {e}")))?; @@ -481,14 +481,12 @@ impl Bootstrapper for CassandraBootstrapper { let already_granted = self .engine .session() - .query_with_params( + .run( + Stmt::Read, check_cql, - params( - Stmt::Read, - cdrs_tokio::query_values!( - self.config.app_user.as_str(), - self.config.admin_user.as_str() - ), + cdrs_tokio::query_values!( + self.config.app_user.as_str(), + self.config.admin_user.as_str() ), ) .await @@ -507,12 +505,10 @@ impl Bootstrapper for CassandraBootstrapper { ); self.engine .session() - .query_with_params( + .run( + Stmt::Ddl, grant_cql, - params( - Stmt::Ddl, - cdrs_tokio::query::QueryValues::SimpleValues(vec![]), - ), + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), ) .await .map_err(|e| { @@ -730,12 +726,10 @@ impl Bootstrapper for CassandraBootstrapper { let rows = match self .engine .session() - .query_with_params( + .run( + Stmt::Read, cql, - params( - Stmt::Read, - cdrs_tokio::query::QueryValues::SimpleValues(vec![]), - ), + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), ) .await { @@ -777,12 +771,10 @@ impl Bootstrapper for CassandraBootstrapper { let rows = self .engine .session() - .query_with_params( + .run( + Stmt::SystemRead, cql, - params( - Stmt::SystemRead, - cdrs_tokio::query::QueryValues::SimpleValues(vec![]), - ), + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), ) .await .map_err(|e| OpError::Internal(format!("List keyspaces: {e}")))? diff --git a/crates/storage-cassandra/src/cassandra_util.rs b/crates/storage-cassandra/src/cassandra_util.rs index 80c9d4243..53a132018 100644 --- a/crates/storage-cassandra/src/cassandra_util.rs +++ b/crates/storage-cassandra/src/cassandra_util.rs @@ -60,6 +60,132 @@ pub fn params(kind: Stmt, values: QueryValues) -> cdrs_tokio::statement::Stateme 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; +} + +impl PolicySession for CassandraSession { + 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(), + "{kind:?} statement: {}: {query}", + shape_error(kind, &query).unwrap_or_default() + ); + async move { self.query_with_params(query, params(kind, values)).await } + } +} + +/// What is wrong with `query` as a statement of `kind`, or `None` when its +/// CQL matches `kind`: +/// +/// - [`Stmt::Read`] and [`Stmt::SerialRead`]: a `SELECT`. +/// - [`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"); + match kind { + Stmt::Read | Stmt::SerialRead => (first != "SELECT").then_some("a read must be a SELECT"), + Stmt::SystemRead => { + let system = words + .iter() + .skip_while(|word| *word != "FROM") + .nth(1) + .is_some_and(|table| { + table.starts_with("SYSTEM.") || table.starts_with("SYSTEM_SCHEMA.") + }); + 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"), + } +} + +/// 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] @@ -81,7 +207,7 @@ pub async fn ddl( context: &str, ) -> Result<(), E> { session - .query_with_params(query, params(Stmt::Ddl, QueryValues::SimpleValues(vec![]))) + .run(Stmt::Ddl, query, QueryValues::SimpleValues(vec![])) .await .map_err(|e| { tracing::error!("{context} DDL failed: {e}"); @@ -101,23 +227,21 @@ pub async fn system_read( values: QueryValues, context: &str, ) -> Result, E> { - rows_at(session, query, params(Stmt::SystemRead, values), context).await + rows_at(session, query, Stmt::SystemRead, values, context).await } -/// Run `query` with `params` and return its rows. +/// Run `query` with `values` as a statement of `kind` and return its rows. async fn rows_at( session: &Arc, query: &str, - params: cdrs_tokio::statement::StatementParams, + kind: Stmt, + values: QueryValues, context: &str, ) -> Result, E> { - let result = session - .query_with_params(query, params) - .await - .map_err(|e| { - tracing::error!("{context} query failed: {e}"); - E::db_error(format!("{context}: {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}"); @@ -136,7 +260,7 @@ pub async fn query_lwt( values: QueryValues, ) -> Result { session - .query_with_params(query, params(Stmt::Lwt, values)) + .run(Stmt::Lwt, query, values) .await .map_err(|error| { extenddb_storage::error::StorageError::Internal(format!("LWT query failed: {error}")) @@ -197,7 +321,7 @@ pub async fn query_rows( values: QueryValues, context: &str, ) -> Result, E> { - rows_at(session, query, params(Stmt::Read, values), context).await + rows_at(session, query, Stmt::Read, values, context).await } /// The same as [`query_rows`]. A later commit removes it. @@ -220,7 +344,7 @@ pub async fn query_rows_serial( values: QueryValues, context: &str, ) -> Result, E> { - rows_at(session, query, params(Stmt::SerialRead, values), context).await + rows_at(session, query, Stmt::SerialRead, values, context).await } /// Execute a query and return the first row, if any. @@ -249,13 +373,10 @@ pub async fn execute( values: QueryValues, context: &str, ) -> Result<(), E> { - session - .query_with_params(query, params(Stmt::Write, values)) - .await - .map_err(|e| { - tracing::error!("{context} execute failed: {e}"); - E::db_error("Database error".to_owned()) - })?; + session.run(Stmt::Write, query, values).await.map_err(|e| { + tracing::error!("{context} execute failed: {e}"); + E::db_error("Database error".to_owned()) + })?; Ok(()) } @@ -272,7 +393,7 @@ pub async fn execute_quorum( context: &str, ) -> Result<(), E> { session - .query_with_params(query, params(Stmt::Write, values)) + .run(Stmt::Write, query, values) .await .map_err(|error| { tracing::error!("{context} quorum execute failed: {error}"); @@ -424,13 +545,10 @@ pub async fn apply_lwt( values: QueryValues, context: &str, ) -> Result { - let result = session - .query_with_params(query, params(Stmt::Lwt, values)) - .await - .map_err(|e| { - tracing::error!("{context} 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) } @@ -469,7 +587,110 @@ fn lwt_applied_flag( #[cfg(test)] mod tests { - use super::{Stmt, batch, params}; + use super::{Stmt, batch, params, shape_error}; + + #[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!(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; diff --git a/crates/storage-cassandra/src/catalog_store.rs b/crates/storage-cassandra/src/catalog_store.rs index ef1b1380c..133f93430 100644 --- a/crates/storage-cassandra/src/catalog_store.rs +++ b/crates/storage-cassandra/src/catalog_store.rs @@ -7,7 +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::{Stmt, params}; +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use std::sync::Arc; use cdrs_tokio::cluster::TcpConnectionManager; @@ -200,12 +201,10 @@ impl CassandraCatalogStore { "CREATE KEYSPACE IF NOT EXISTS {keyspace_name} WITH replication = {replication}" ); self.session - .query_with_params( + .run( + Stmt::Ddl, cql, - params( - Stmt::Ddl, - cdrs_tokio::query::QueryValues::SimpleValues(vec![]), - ), + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), ) .await .map_err(|e| failed(&e))?; @@ -226,12 +225,10 @@ impl CassandraCatalogStore { let cql = format!("DROP KEYSPACE IF EXISTS {keyspace_name}"); self.session - .query_with_params( + .run( + Stmt::Ddl, cql, - params( - Stmt::Ddl, - cdrs_tokio::query::QueryValues::SimpleValues(vec![]), - ), + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), ) .await .map_err(|e| { @@ -377,12 +374,10 @@ impl extenddb_storage::diagnostics::DiagnosticsStore for CassandraCatalogStore { Box::pin(async move { let query = format!("SELECT COUNT(*) FROM {catalog_keyspace}.tables"); let result = session - .query_with_params( + .run( + Stmt::Read, &query, - params( - Stmt::Read, - cdrs_tokio::query::QueryValues::SimpleValues(vec![]), - ), + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), ) .await .map_err(|e| { @@ -412,12 +407,10 @@ impl extenddb_storage::diagnostics::DiagnosticsStore for CassandraCatalogStore { Box::pin(async move { let query = format!("SELECT COUNT(*) FROM {catalog_keyspace}.indexes"); let result = session - .query_with_params( + .run( + Stmt::Read, &query, - params( - Stmt::Read, - cdrs_tokio::query::QueryValues::SimpleValues(vec![]), - ), + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), ) .await .map_err(|e| { @@ -452,12 +445,10 @@ impl extenddb_storage::diagnostics::DiagnosticsStore for CassandraCatalogStore { // 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_with_params( + .run( + Stmt::Read, &query, - params( - Stmt::Read, - cdrs_tokio::query::QueryValues::SimpleValues(vec![]), - ), + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), ) .await .map_err(|e| { @@ -482,12 +473,10 @@ impl extenddb_storage::diagnostics::DiagnosticsStore for CassandraCatalogStore { let test_query = format!("SELECT COUNT(*) FROM {account_keyspace}.schema_history"); session - .query_with_params( + .run( + Stmt::Read, &test_query, - params( - Stmt::Read, - cdrs_tokio::query::QueryValues::SimpleValues(vec![]), - ), + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), ) .await .map_err(|e| { @@ -529,16 +518,10 @@ impl RateLimitStore for CassandraCatalogStore { AND source_ip = ? ALLOW FILTERING" ); let result = session - .query_with_params( + .run( + Stmt::Read, &query, - params( - Stmt::Read, - cdrs_tokio::query_values!( - principal.as_str(), - cutoff_ms, - source_ip.as_str() - ), - ), + cdrs_tokio::query_values!(principal.as_str(), cutoff_ms, source_ip.as_str()), ) .await .map_err(|e| { @@ -575,12 +558,10 @@ impl RateLimitStore for CassandraCatalogStore { ALLOW FILTERING" ); let result = session - .query_with_params( + .run( + Stmt::Read, &query, - params( - Stmt::Read, - cdrs_tokio::query_values!(source_ip.as_str(), cutoff_ms), - ), + cdrs_tokio::query_values!(source_ip.as_str(), cutoff_ms), ) .await .map_err(|e| { @@ -610,12 +591,10 @@ impl RateLimitStore for CassandraCatalogStore { (principal, attempted_at, success, source_ip) VALUES (?, ?, false, ?)" ); if let Err(e) = session - .query_with_params( + .run( + Stmt::Write, &query, - params( - Stmt::Write, - cdrs_tokio::query_values!(principal.as_str(), now_ms, source_ip.as_deref()), - ), + cdrs_tokio::query_values!(principal.as_str(), now_ms, source_ip.as_deref()), ) .await { @@ -637,12 +616,10 @@ impl RateLimitStore for CassandraCatalogStore { let select = format!("SELECT DISTINCT principal FROM {catalog_keyspace}.login_attempts"); let principals = match session - .query_with_params( + .run( + Stmt::Read, &select, - params( - Stmt::Read, - cdrs_tokio::query::QueryValues::SimpleValues(vec![]), - ), + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), ) .await .and_then(|r| r.response_body()) @@ -663,12 +640,10 @@ impl RateLimitStore for CassandraCatalogStore { continue; }; if let Err(e) = session - .query_with_params( + .run( + Stmt::Write, &delete, - params( - Stmt::Write, - cdrs_tokio::query_values!(principal.as_str(), cutoff_ms), - ), + cdrs_tokio::query_values!(principal.as_str(), cutoff_ms), ) .await { @@ -697,21 +672,19 @@ 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_params( + .run( + Stmt::Write, &query, - params( - Stmt::Write, - cdrs_tokio::query_values!( - bucket_ms, - row.metric.as_str(), - row.table_name.as_deref().unwrap_or(""), - row.index_name.as_deref().unwrap_or(""), - row.operation.as_deref().unwrap_or(""), - row.sum, - row.count, - row.min, - row.max - ), + cdrs_tokio::query_values!( + bucket_ms, + row.metric.as_str(), + row.table_name.as_deref().unwrap_or(""), + row.index_name.as_deref().unwrap_or(""), + row.operation.as_deref().unwrap_or(""), + row.sum, + row.count, + row.min, + row.max ), ) .await @@ -749,9 +722,10 @@ impl MetricsStore for CassandraCatalogStore { WHERE bucket >= ? AND bucket <= ? ALLOW FILTERING" ); let result = session - .query_with_params( + .run( + Stmt::Read, &query, - params(Stmt::Read, cdrs_tokio::query_values!(start_ms, end_ms)), + cdrs_tokio::query_values!(start_ms, end_ms), ) .await .map_err(|e| { diff --git a/crates/storage-cassandra/src/create_table.rs b/crates/storage-cassandra/src/create_table.rs index b6da563ab..39512870e 100644 --- a/crates/storage-cassandra/src/create_table.rs +++ b/crates/storage-cassandra/src/create_table.rs @@ -3,7 +3,8 @@ //! `create_table` implementation for `CassandraEngine`. -use crate::cassandra_util::{Stmt, params}; +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, @@ -72,12 +73,10 @@ impl CassandraEngine { // All interpolated values are server-generated (UUIDs, timestamps, label from chrono). if let Err(e) = self .session - .query_with_params( + .run( + Stmt::Write, &batch, - params( - Stmt::Write, - cdrs_tokio::query::QueryValues::SimpleValues(vec![]), - ), + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), ) .await { @@ -214,12 +213,10 @@ impl CassandraEngine { let delay_query = format!("SELECT value FROM {catalog_keyspace}.settings WHERE key = ?"); let delay_seconds: f64 = self .session - .query_with_params( + .run( + Stmt::Read, &delay_query, - params( - Stmt::Read, - cdrs_tokio::query_values!("control_plane_delay_seconds"), - ), + cdrs_tokio::query_values!("control_plane_delay_seconds"), ) .await .ok() @@ -343,12 +340,10 @@ impl CassandraEngine { let result = self .session - .query_with_params( + .run( + Stmt::Lwt, &insert_table_cql, - params( - Stmt::Lwt, - cdrs_tokio::query::QueryValues::SimpleValues(values), - ), + cdrs_tokio::query::QueryValues::SimpleValues(values), ) .await .map_err(|e| { @@ -435,22 +430,20 @@ impl CassandraEngine { ); self.session - .query_with_params( + .run( + Stmt::Write, &insert_index_cql, - params( - Stmt::Write, - cdrs_tokio::query::QueryValues::SimpleValues(vec![ - Value::from(table_id.as_str()), - Value::from(gsi.index_name.as_str()), - Value::from(index_id.as_str()), - Value::from(gsi_ks.to_string().as_str()), - Value::from(gsi_proj.to_string().as_str()), - match gsi_pt.as_ref() { - Some(v) => Value::from(v.to_string().as_str()), - None => Value::NotSet, - }, - ]), - ), + cdrs_tokio::query::QueryValues::SimpleValues(vec![ + Value::from(table_id.as_str()), + Value::from(gsi.index_name.as_str()), + Value::from(index_id.as_str()), + Value::from(gsi_ks.to_string().as_str()), + Value::from(gsi_proj.to_string().as_str()), + match gsi_pt.as_ref() { + Some(v) => Value::from(v.to_string().as_str()), + None => Value::NotSet, + }, + ]), ) .await .map_err(|e| { @@ -479,19 +472,17 @@ impl CassandraEngine { ); self.session - .query_with_params( + .run( + Stmt::Write, &insert_index_cql, - params( - Stmt::Write, - cdrs_tokio::query::QueryValues::SimpleValues(vec![ - Value::from(table_id.as_str()), - Value::from(lsi.index_name.as_str()), - Value::from(index_id.as_str()), - Value::from(lsi_ks.to_string().as_str()), - Value::from(lsi_proj.to_string().as_str()), - Value::NotSet, - ]), - ), + cdrs_tokio::query::QueryValues::SimpleValues(vec![ + Value::from(table_id.as_str()), + Value::from(lsi.index_name.as_str()), + Value::from(index_id.as_str()), + Value::from(lsi_ks.to_string().as_str()), + Value::from(lsi_proj.to_string().as_str()), + Value::NotSet, + ]), ) .await .map_err(|e| { @@ -511,15 +502,13 @@ impl CassandraEngine { ); self.session - .query_with_params( + .run( + Stmt::Write, &insert_tag_cql, - params( - Stmt::Write, - cdrs_tokio::query_values!( - table_arn.as_str(), - tag.key.as_str(), - tag.value.as_str() - ), + cdrs_tokio::query_values!( + table_arn.as_str(), + tag.key.as_str(), + tag.value.as_str() ), ) .await diff --git a/crates/storage-cassandra/src/credential_store.rs b/crates/storage-cassandra/src/credential_store.rs index 913e84c39..0e50abd15 100644 --- a/crates/storage-cassandra/src/credential_store.rs +++ b/crates/storage-cassandra/src/credential_store.rs @@ -7,7 +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::{Stmt, params}; +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use std::sync::Arc; use async_trait::async_trait; @@ -85,10 +86,7 @@ impl CassandraCredentialStore { let result = self .session - .query_with_params( - &query, - params(Stmt::Read, 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}"); @@ -163,10 +161,7 @@ impl CassandraCredentialStore { let result = self .session - .query_with_params( - &query, - params(Stmt::Read, 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/delete_item.rs b/crates/storage-cassandra/src/data/delete_item.rs index f040217b3..86b51b4d1 100644 --- a/crates/storage-cassandra/src/data/delete_item.rs +++ b/crates/storage-cassandra/src/data/delete_item.rs @@ -3,6 +3,7 @@ //! `delete_item` implementation for the Cassandra backend. +use crate::cassandra_util::PolicySession as _; use cdrs_tokio::types::IntoRustByName; use extenddb_core::expression::{Expr, ExpressionMaps}; use extenddb_core::types::{Item, TableKeyInfo}; @@ -14,7 +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, params}; +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 @@ -689,9 +690,10 @@ impl CassandraEngine { && ttl_claim.is_none() { self.session - .query_with_params( + .run( + Stmt::Write, &delete_cql, - params(Stmt::Write, cdrs_tokio::query_values!(pk_text.as_str())), + cdrs_tokio::query_values!(pk_text.as_str()), ) .await .map_err(|e| StorageError::Internal(format!("Delete failed: {e}")))?; @@ -1481,9 +1483,10 @@ impl CassandraEngine { let result = self .session - .query_with_params( + .run( + Stmt::Lwt, &query_null, - params(Stmt::Lwt, cdrs_tokio::query_values!(now_ms, pk)), + cdrs_tokio::query_values!(now_ms, pk), ) .await .map_err(|e| { @@ -1512,9 +1515,10 @@ impl CassandraEngine { ); self.session - .query_with_params( + .run( + Stmt::Lwt, &query_compare, - params(Stmt::Lwt, cdrs_tokio::query_values!(now_ms, pk, now_ms)), + cdrs_tokio::query_values!(now_ms, pk, now_ms), ) .await .map_err(|e| { diff --git a/crates/storage-cassandra/src/data/mod.rs b/crates/storage-cassandra/src/data/mod.rs index c45b9a030..86806a120 100644 --- a/crates/storage-cassandra/src/data/mod.rs +++ b/crates/storage-cassandra/src/data/mod.rs @@ -3,7 +3,8 @@ //! Data table operations for Cassandra. -use crate::cassandra_util::{Stmt, params}; +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; @@ -97,7 +98,7 @@ async fn run( values: cdrs_tokio::query::QueryValues, ) -> Result { session - .query_with_params(query, params(kind, values)) + .run(kind, query, values) .await .map_err(|e| StorageError::Internal(format!("Query failed: {e}"))) } diff --git a/crates/storage-cassandra/src/data/put_get_item.rs b/crates/storage-cassandra/src/data/put_get_item.rs index 4dea2ad94..891208389 100644 --- a/crates/storage-cassandra/src/data/put_get_item.rs +++ b/crates/storage-cassandra/src/data/put_get_item.rs @@ -3,6 +3,7 @@ //! `put_item` and `get_item` implementations for the Cassandra backend. +use crate::cassandra_util::PolicySession as _; use cdrs_tokio::types::IntoRustByName; use extenddb_core::expression::{Expr, ExpressionMaps}; use extenddb_core::types::{Item, TableKeyInfo}; @@ -13,7 +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, params}; +use crate::cassandra_util::{Stmt, batch}; use crate::stream_util::stream_record_statement; /// How a put maintains GSIs. @@ -609,7 +610,7 @@ impl CassandraEngine { let result = self .session - .query_with_params(&insert_cql, params(Stmt::Lwt, insert_qv)) + .run(Stmt::Lwt, &insert_cql, insert_qv) .await .map_err(|e| StorageError::Internal(format!("put_item_if_not_exists: {e}")))?; @@ -818,12 +819,10 @@ impl CassandraEngine { let result = self .session - .query_with_params( + .run( + Stmt::Read, &query, - params( - Stmt::Read, - cdrs_tokio::query_values!(pk_text.as_ref() as &str), - ), + 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/transaction_ledger.rs b/crates/storage-cassandra/src/data/transaction_ledger.rs index b1cc13bdd..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::{Stmt, get_column, params, 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,18 +121,16 @@ impl CassandraEngine { let result = self .session - .query_with_params( + .run( + Stmt::Lwt, &query, - params( - Stmt::Lwt, - cdrs_tokio::query_values!( - Bytes::new(txn_id.as_bytes().to_vec()), - state.as_str(), - started_at, - client_token, - request_fingerprint, - items_blob - ), + cdrs_tokio::query_values!( + Bytes::new(txn_id.as_bytes().to_vec()), + state.as_str(), + started_at, + client_token, + request_fingerprint, + items_blob ), ) .await @@ -170,14 +169,12 @@ impl CassandraEngine { let query = format!("UPDATE {keyspace}.transaction_ledger SET state = ? WHERE txn_id = ?"); self.session - .query_with_params( + .run( + Stmt::Write, &query, - params( - Stmt::Write, - cdrs_tokio::query_values!( - new_state.as_str(), - Bytes::new(txn_id.as_bytes().to_vec()) - ), + cdrs_tokio::query_values!( + new_state.as_str(), + Bytes::new(txn_id.as_bytes().to_vec()) ), ) .await @@ -204,12 +201,10 @@ impl CassandraEngine { let query = format!("UPDATE {keyspace}.transaction_ledger SET items_blob = ? WHERE txn_id = ?"); self.session - .query_with_params( + .run( + Stmt::Write, &query, - params( - Stmt::Write, - cdrs_tokio::query_values!(blob, Bytes::new(txn_id.as_bytes().to_vec())), - ), + cdrs_tokio::query_values!(blob, Bytes::new(txn_id.as_bytes().to_vec())), ) .await .map_err(|e| { @@ -313,12 +308,10 @@ impl CassandraEngine { let query = format!("DELETE FROM {keyspace}.transaction_ledger WHERE txn_id = ?"); self.session - .query_with_params( + .run( + Stmt::Write, &query, - params( - Stmt::Write, - cdrs_tokio::query_values!(Bytes::new(txn_id.as_bytes().to_vec())), - ), + cdrs_tokio::query_values!(Bytes::new(txn_id.as_bytes().to_vec())), ) .await .map_err(|e| { diff --git a/crates/storage-cassandra/src/data/transactions.rs b/crates/storage-cassandra/src/data/transactions.rs index 15c0d014d..5166764b8 100644 --- a/crates/storage-cassandra/src/data/transactions.rs +++ b/crates/storage-cassandra/src/data/transactions.rs @@ -4,6 +4,7 @@ //! DynamoDB transaction implementations for Cassandra backend. use super::transact_stream::{commit_old_image, secondary_effect_batches}; +use crate::cassandra_util::PolicySession as _; use cdrs_tokio::frame::Envelope; use cdrs_tokio::types::IntoRustByName; use cdrs_tokio::types::value::Bytes; @@ -21,7 +22,7 @@ use std::time::Duration; use uuid::Uuid; use crate::CassandraEngine; -use crate::cassandra_util::{Stmt, get_column, params, 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::{ @@ -1535,9 +1536,10 @@ impl CassandraEngine { let result = self .session - .query_with_params( + .run( + Stmt::Read, &query, - params(Stmt::Read, cdrs_tokio::query_values!(pk_text.as_str())), + cdrs_tokio::query_values!(pk_text.as_str()), ) .await .map_err(|e| { @@ -1620,7 +1622,7 @@ impl CassandraEngine { VALUES (?, ?, ?, ?, true) IF NOT EXISTS" ); self.session - .query_with_params(&query, params(Stmt::Lwt, 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 { @@ -1629,7 +1631,7 @@ impl CassandraEngine { WHERE pk = ? IF prepared_txn_id = null" ); self.session - .query_with_params(&query, params(Stmt::Lwt, 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())) } @@ -1810,12 +1812,10 @@ impl CassandraEngine { let result = self .session - .query_with_params( + .run( + Stmt::Lwt, &update_max_ts_null_query, - params( - Stmt::Lwt, - cdrs_tokio::query_values!(txn_timestamp, pk_text.as_str()), - ), + cdrs_tokio::query_values!(txn_timestamp, pk_text.as_str()), ) .await .map_err(|e| { @@ -1834,15 +1834,13 @@ impl CassandraEngine { let _result2 = self .session - .query_with_params( + .run( + Stmt::Lwt, &update_max_ts_query, - params( - Stmt::Lwt, - cdrs_tokio::query_values!( - txn_timestamp, - pk_text.as_str(), - txn_timestamp - ), + cdrs_tokio::query_values!( + txn_timestamp, + pk_text.as_str(), + txn_timestamp ), ) .await @@ -1880,10 +1878,7 @@ impl CassandraEngine { "DELETE FROM {keyspace}.{ddb_table} WHERE pk = ? IF prepared_txn_id = ?" ); self.session - .query_with_params( - &delete_query, - params(Stmt::Lwt, 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())) } @@ -1960,12 +1955,10 @@ impl CassandraEngine { IF prepared_txn_id = ? AND created_to_prepare = true" ); self.session - .query_with_params( + .run( + Stmt::Lwt, &query, - params( - Stmt::Lwt, - cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes), - ), + cdrs_tokio::query_values!(pk_text.as_str(), txn_id_bytes), ) .await .map_err(|e| StorageError::Internal(e.to_string())) @@ -2030,17 +2023,14 @@ impl CassandraEngine { WHERE pk = ? AND {sk_col} = ? IF prepared_txn_id = ?" ); self.session - .query_with_params( - &query, - params(Stmt::Lwt, 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 { @@ -2049,7 +2039,7 @@ impl CassandraEngine { WHERE pk = ? IF prepared_txn_id = ?" ); self.session - .query_with_params(&query, params(Stmt::Lwt, 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())) } @@ -2283,7 +2273,7 @@ impl CassandraEngine { ); let dr = self.session - .query_with_params(&delete_query, params(Stmt::Lwt, 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 })?; @@ -2291,7 +2281,7 @@ impl CassandraEngine { return Ok(()); } self.session - .query_with_params(&update_query, params(Stmt::Lwt, 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())) } @@ -2588,12 +2578,10 @@ impl CassandraEngine { IF prepared_txn_id = ? AND created_to_prepare = true", ); self.session - .query_with_params( + .run( + Stmt::Lwt, &dq, - params( - Stmt::Lwt, - cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes), - ), + cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes), ) .await .map_err(|e| StorageError::Internal(e.to_string())) @@ -2636,19 +2624,17 @@ impl CassandraEngine { WHERE pk = ? AND {sk_col} = ? IF prepared_txn_id = ?", ); self.session - .query_with_params( + .run( + Stmt::Lwt, &query, - params( - Stmt::Lwt, - cdrs_tokio::query::QueryValues::SimpleValues(vec![ - item_data.into(), - next_version.into(), - txn_timestamp.into(), - cdrs_tokio::types::value::Value::from(op.pk.as_str()), - super::index::sk_to_value(sk_val), - txn_id_bytes.into(), - ]), - ), + cdrs_tokio::query::QueryValues::SimpleValues(vec![ + item_data.into(), + next_version.into(), + txn_timestamp.into(), + cdrs_tokio::types::value::Value::from(op.pk.as_str()), + super::index::sk_to_value(sk_val), + txn_id_bytes.into(), + ]), ) .await .map_err(|e| StorageError::Internal(e.to_string())) @@ -2660,17 +2646,15 @@ impl CassandraEngine { WHERE pk = ? IF prepared_txn_id = ?", ); self.session - .query_with_params( + .run( + Stmt::Lwt, &query, - params( - Stmt::Lwt, - cdrs_tokio::query_values!( - item_data, - next_version, - txn_timestamp, - op.pk.as_str(), - txn_id_bytes - ), + cdrs_tokio::query_values!( + item_data, + next_version, + txn_timestamp, + op.pk.as_str(), + txn_id_bytes ), ) .await @@ -2715,12 +2699,10 @@ impl CassandraEngine { ); let r1 = self .session - .query_with_params( + .run( + Stmt::Lwt, &update_null, - params( - Stmt::Lwt, - cdrs_tokio::query_values!(txn_timestamp, op.pk.as_str()), - ), + cdrs_tokio::query_values!(txn_timestamp, op.pk.as_str()), ) .await .map_err(|e| StorageError::Internal(e.to_string())) @@ -2736,16 +2718,10 @@ impl CassandraEngine { ); let _ = self .session - .query_with_params( + .run( + Stmt::Lwt, &update_cmp, - params( - Stmt::Lwt, - cdrs_tokio::query_values!( - txn_timestamp, - op.pk.as_str(), - txn_timestamp - ), - ), + cdrs_tokio::query_values!(txn_timestamp, op.pk.as_str(), txn_timestamp), ) .await .map_err(|e| StorageError::Internal(e.to_string())) @@ -2768,12 +2744,10 @@ impl CassandraEngine { "DELETE FROM {keyspace}.{table} WHERE pk = ? IF prepared_txn_id = ?", ); self.session - .query_with_params( + .run( + Stmt::Lwt, &query, - params( - Stmt::Lwt, - cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes), - ), + cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes), ) .await .map_err(|e| StorageError::Internal(e.to_string())) @@ -2843,12 +2817,10 @@ impl CassandraEngine { ); let dr = self .session - .query_with_params( + .run( + Stmt::Lwt, &dq, - params( - Stmt::Lwt, - cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes.clone()), - ), + cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes.clone()), ) .await .map_err(|e| StorageError::Internal(e.to_string())) @@ -2868,12 +2840,10 @@ impl CassandraEngine { query_with_pk_sk_txnid(&self.session, &update_query, &op.pk, sk_val, txn_id_bytes).await } else { self.session - .query_with_params( + .run( + Stmt::Lwt, &update_query, - params( - Stmt::Lwt, - cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes), - ), + cdrs_tokio::query_values!(op.pk.as_str(), txn_id_bytes), ) .await .map_err(|e| StorageError::Internal(e.to_string())) diff --git a/crates/storage-cassandra/src/data/ttl.rs b/crates/storage-cassandra/src/data/ttl.rs index 99b4a6962..5e551fafb 100644 --- a/crates/storage-cassandra/src/data/ttl.rs +++ b/crates/storage-cassandra/src/data/ttl.rs @@ -8,7 +8,8 @@ //! indexed into day-bucketed, 64-way sharded partitions and are deleted through //! the normal item mutation path. -use crate::cassandra_util::{Stmt, params}; +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}; @@ -1294,16 +1295,14 @@ pub(crate) async fn clear_ttl_entries( ); engine .session - .query_with_params( + .run( + Stmt::Write, &delete, - params( - Stmt::Write, - cdrs_tokio::query_values!( - table_id, - cdrs_tokio::types::value::Bytes::new(generation.as_bytes().to_vec()), - bucket, - shard - ), + cdrs_tokio::query_values!( + table_id, + cdrs_tokio::types::value::Bytes::new(generation.as_bytes().to_vec()), + bucket, + shard ), ) .await @@ -1313,9 +1312,10 @@ pub(crate) async fn clear_ttl_entries( format!("DELETE FROM {account_keyspace}.{TTL_BUCKET_TABLE} WHERE table_id = ?"); engine .session - .query_with_params( + .run( + Stmt::Write, &delete_buckets, - params(Stmt::Write, cdrs_tokio::query_values!(table_id)), + cdrs_tokio::query_values!(table_id), ) .await .map_err(|error| StorageError::Internal(format!("Clear TTL buckets: {error}")))?; diff --git a/crates/storage-cassandra/src/data/update_item.rs b/crates/storage-cassandra/src/data/update_item.rs index dd74242d3..4bbaa5538 100644 --- a/crates/storage-cassandra/src/data/update_item.rs +++ b/crates/storage-cassandra/src/data/update_item.rs @@ -3,6 +3,7 @@ //! `update_item` implementation for the Cassandra backend. +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; @@ -13,7 +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, params}; +use crate::cassandra_util::{Stmt, batch}; use crate::stream_util::stream_record_statement; // 400 KB limit from DynamoDB specification @@ -429,7 +430,7 @@ impl CassandraEngine { // Preserve f997485's Paxos linearization for ordinary writes. let result = self .session - .query_with_params(&lwt_cql, params(Stmt::Lwt, 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)? { diff --git a/crates/storage-cassandra/src/delete_table.rs b/crates/storage-cassandra/src/delete_table.rs index f2cf0aefc..b4b493d0e 100644 --- a/crates/storage-cassandra/src/delete_table.rs +++ b/crates/storage-cassandra/src/delete_table.rs @@ -3,7 +3,8 @@ //! `delete_table` implementation for `CassandraEngine`. -use crate::cassandra_util::{Stmt, params}; +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; @@ -54,12 +55,10 @@ impl CassandraEngine { let table_result = self .session - .query_with_params( + .run( + Stmt::Read, &table_query, - params( - Stmt::Read, - cdrs_tokio::query_values!(account_id, input.table_name.as_str()), - ), + cdrs_tokio::query_values!(account_id, input.table_name.as_str()), ) .await .map_err(|e| StorageError::Internal(format!("Query table: {e}")))?; @@ -118,9 +117,10 @@ impl CassandraEngine { let index_result = self .session - .query_with_params( + .run( + Stmt::Read, &index_query, - params(Stmt::Read, cdrs_tokio::query_values!(table_id.as_str())), + cdrs_tokio::query_values!(table_id.as_str()), ) .await .map_err(|e| StorageError::Internal(format!("Query indexes: {e}")))?; @@ -163,9 +163,10 @@ impl CassandraEngine { let delete_indexes_query = format!("DELETE FROM {catalog_keyspace}.indexes WHERE table_id = ?"); self.session - .query_with_params( + .run( + Stmt::Write, &delete_indexes_query, - params(Stmt::Write, cdrs_tokio::query_values!(table_id.as_str())), + cdrs_tokio::query_values!(table_id.as_str()), ) .await .map_err(|e| StorageError::Internal(format!("Delete indexes: {e}")))?; @@ -174,12 +175,10 @@ impl CassandraEngine { let delete_tags_query = format!("DELETE FROM {catalog_keyspace}.tags WHERE resource_arn = ?"); self.session - .query_with_params( + .run( + Stmt::Write, &delete_tags_query, - params( - Stmt::Write, - cdrs_tokio::query_values!(description.table_arn.as_str()), - ), + cdrs_tokio::query_values!(description.table_arn.as_str()), ) .await .map_err(|e| StorageError::Internal(format!("Delete tags: {e}")))?; diff --git a/crates/storage-cassandra/src/engine.rs b/crates/storage-cassandra/src/engine.rs index 5042dc657..3098e1325 100644 --- a/crates/storage-cassandra/src/engine.rs +++ b/crates/storage-cassandra/src/engine.rs @@ -3,7 +3,8 @@ //! Cassandra storage engine implementation. -use crate::cassandra_util::{Stmt, params}; +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use std::sync::Arc; use cdrs_tokio::authenticators::{NoneAuthenticatorProvider, StaticPasswordAuthenticatorProvider}; @@ -276,12 +277,10 @@ impl CassandraEngine { ); self.session - .query_with_params( + .run( + Stmt::Ddl, cql, - params( - Stmt::Ddl, - cdrs_tokio::query::QueryValues::SimpleValues(vec![]), - ), + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), ) .await .map_err(|e| StorageError::Internal(format!("Failed to create keyspace: {e}")))?; @@ -294,12 +293,10 @@ impl CassandraEngine { let cql = format!("DROP KEYSPACE IF EXISTS {keyspace_name}"); self.session - .query_with_params( + .run( + Stmt::Ddl, cql, - params( - Stmt::Ddl, - cdrs_tokio::query::QueryValues::SimpleValues(vec![]), - ), + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), ) .await .map_err(|e| StorageError::Internal(format!("Failed to drop keyspace: {e}")))?; @@ -313,7 +310,7 @@ impl CassandraEngine { let rows = self .session - .query_with_params(cql, params(Stmt::SystemRead, 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 de1dead52..73b7e2878 100644 --- a/crates/storage-cassandra/src/lib.rs +++ b/crates/storage-cassandra/src/lib.rs @@ -52,7 +52,8 @@ pub use config::CassandraStorageConfig; pub use engine::{CassandraEngine, CassandraSession}; pub use metadata_engine::TtlBackfillCursor; -use crate::cassandra_util::{Stmt, params}; +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}; @@ -367,12 +368,10 @@ fn server_components_factory( format!("SELECT value FROM {catalog_keyspace}.settings WHERE key = 'encryption_key'"); let enc_key_result = engine .session - .query_with_params( + .run( + Stmt::Read, &enc_key_query, - params( - Stmt::Read, - cdrs_tokio::query::QueryValues::SimpleValues(vec![]), - ), + cdrs_tokio::query::QueryValues::SimpleValues(vec![]), ) .await .map_err(|e| { diff --git a/crates/storage-cassandra/src/management_store/access_keys.rs b/crates/storage-cassandra/src/management_store/access_keys.rs index f12a583f3..1f2fc29f3 100755 --- a/crates/storage-cassandra/src/management_store/access_keys.rs +++ b/crates/storage-cassandra/src/management_store/access_keys.rs @@ -3,7 +3,8 @@ //! Access key, session, and caller-tag operations for `CassandraCatalogStore`. -use crate::cassandra_util::{Stmt, params}; +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; @@ -99,12 +100,10 @@ impl CassandraCatalogStore { let result = self .session() - .query_with_params( + .run( + Stmt::Lwt, &delete_query, - params( - Stmt::Lwt, - cdrs_tokio::query_values!(key_id, account_id, user_name), - ), + cdrs_tokio::query_values!(key_id, account_id, user_name), ) .await .map_err(|e| OpError::Internal(e.to_string()))?; diff --git a/crates/storage-cassandra/src/management_store/accounts.rs b/crates/storage-cassandra/src/management_store/accounts.rs index 76f76f1e4..b370c5e44 100644 --- a/crates/storage-cassandra/src/management_store/accounts.rs +++ b/crates/storage-cassandra/src/management_store/accounts.rs @@ -3,7 +3,8 @@ //! Account management operations for `CassandraCatalogStore`. -use crate::cassandra_util::{Stmt, params}; +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use cdrs_tokio::types::IntoRustByName; use extenddb_storage::management_store::{AccountDetail, OpError, OpResult}; @@ -33,12 +34,10 @@ impl CassandraCatalogStore { let result = self .session() - .query_with_params( + .run( + Stmt::Lwt, &query, - params( - Stmt::Lwt, - cdrs_tokio::query_values!(account_id, account_name), - ), + cdrs_tokio::query_values!(account_id, account_name), ) .await .map_err(|e| { diff --git a/crates/storage-cassandra/src/management_store/users.rs b/crates/storage-cassandra/src/management_store/users.rs index f6e0f0dbe..cd6ade80f 100644 --- a/crates/storage-cassandra/src/management_store/users.rs +++ b/crates/storage-cassandra/src/management_store/users.rs @@ -3,7 +3,8 @@ //! User management operations for `CassandraCatalogStore`. -use crate::cassandra_util::{Stmt, params}; +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}; @@ -73,15 +74,13 @@ impl CassandraCatalogStore { ); session - .query_with_params( + .run( + Stmt::Write, &policy_query, - params( - Stmt::Write, - cdrs_tokio::query_values!( - account_id.as_str(), - user_name.as_str(), - self_service_policy.to_string().as_str() - ), + cdrs_tokio::query_values!( + account_id.as_str(), + user_name.as_str(), + self_service_policy.to_string().as_str() ), ) .await diff --git a/crates/storage-cassandra/src/metadata_engine.rs b/crates/storage-cassandra/src/metadata_engine.rs index 8631ed453..8121b3b52 100755 --- a/crates/storage-cassandra/src/metadata_engine.rs +++ b/crates/storage-cassandra/src/metadata_engine.rs @@ -3,7 +3,8 @@ //! `MetadataEngine` trait implementation for `CassandraEngine`. -use crate::cassandra_util::{Stmt, params}; +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; @@ -1107,15 +1108,13 @@ impl MetadataEngine for CassandraEngine { "INSERT INTO {catalog}.tags (resource_arn, tag_key, tag_value) VALUES (?, ?, ?)" ); self.session_arc() - .query_with_params( + .run( + Stmt::Write, &query, - params( - Stmt::Write, - cdrs_tokio::query_values!( - arn.as_str(), - tag.key.as_str(), - tag.value.as_str() - ), + cdrs_tokio::query_values!( + arn.as_str(), + tag.key.as_str(), + tag.value.as_str() ), ) .await @@ -1141,12 +1140,10 @@ impl MetadataEngine for CassandraEngine { let query = format!("DELETE FROM {catalog}.tags WHERE resource_arn = ? AND tag_key = ?"); self.session_arc() - .query_with_params( + .run( + Stmt::Write, &query, - params( - Stmt::Write, - cdrs_tokio::query_values!(arn.as_str(), key.as_str()), - ), + cdrs_tokio::query_values!(arn.as_str(), key.as_str()), ) .await .map_err(|error| { @@ -1166,10 +1163,7 @@ impl MetadataEngine for CassandraEngine { format!("SELECT tag_key, tag_value FROM {catalog}.tags WHERE resource_arn = ?"); let result = self .session_arc() - .query_with_params( - &query, - params(Stmt::Read, 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/stream_engine.rs b/crates/storage-cassandra/src/stream_engine.rs index ab2df0ca2..c8725275b 100755 --- a/crates/storage-cassandra/src/stream_engine.rs +++ b/crates/storage-cassandra/src/stream_engine.rs @@ -3,7 +3,8 @@ //! `StreamEngine` trait implementation for `CassandraEngine`. -use crate::cassandra_util::{Stmt, params}; +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use cdrs_tokio::types::IntoRustByName; use extenddb_core::types::{ SequenceNumberRange, Shard, StreamDescription, StreamRecord, StreamStatus, StreamSummary, @@ -41,10 +42,7 @@ impl CassandraEngine { let query = format!("SELECT account_id FROM {catalog_keyspace}.tables WHERE table_id = ?"); let result = self .session - .query_with_params( - &query, - params(Stmt::Read, 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,12 +77,10 @@ impl CassandraEngine { ); let result = self .session - .query_with_params( + .run( + Stmt::Read, &query, - params( - Stmt::Read, - cdrs_tokio::query_values!(account_id, table_name), - ), + cdrs_tokio::query_values!(account_id, table_name), ) .await .map_err(|e| StorageError::Internal(e.to_string()))?; @@ -177,9 +173,10 @@ impl StreamEngine for CassandraEngine { let shard_query = format!("SELECT table_id FROM {keyspace}.stream_shards WHERE shard_id = ?"); - let shard_read = self.session.query_with_params( + let shard_read = self.session.run( + Stmt::Read, &shard_query, - params(Stmt::Read, cdrs_tokio::query_values!(shard_id.as_str())), + cdrs_tokio::query_values!(shard_id.as_str()), ); let query = if let Some(ref after) = after_sequence { @@ -198,19 +195,18 @@ impl StreamEngine for CassandraEngine { let records_read = async { if let Some(ref after) = after_sequence { self.session - .query_with_params( + .run( + Stmt::Read, &query, - params( - Stmt::Read, - cdrs_tokio::query_values!(shard_id.as_str(), after.as_str()), - ), + cdrs_tokio::query_values!(shard_id.as_str(), after.as_str()), ) .await } else { self.session - .query_with_params( + .run( + Stmt::Read, &query, - params(Stmt::Read, cdrs_tokio::query_values!(shard_id.as_str())), + cdrs_tokio::query_values!(shard_id.as_str()), ) .await } @@ -278,15 +274,13 @@ impl StreamEngine for CassandraEngine { ); let result = self .session - .query_with_params( + .run( + Stmt::Read, &query, - params( - Stmt::Read, - cdrs_tokio::query_values!( - account_id.as_str(), - table_name.as_str(), - stream_label.as_str() - ), + cdrs_tokio::query_values!( + account_id.as_str(), + table_name.as_str(), + stream_label.as_str() ), ) .await @@ -347,19 +341,18 @@ impl StreamEngine for CassandraEngine { let shard_result = if let Some(ref start) = exclusive_start_shard_id { self.session - .query_with_params( + .run( + Stmt::Read, &shard_query, - params( - Stmt::Read, - cdrs_tokio::query_values!(table_id.as_str(), start.as_str()), - ), + cdrs_tokio::query_values!(table_id.as_str(), start.as_str()), ) .await } else { self.session - .query_with_params( + .run( + Stmt::Read, &shard_query, - params(Stmt::Read, cdrs_tokio::query_values!(table_id.as_str())), + cdrs_tokio::query_values!(table_id.as_str()), ) .await } @@ -448,9 +441,10 @@ impl StreamEngine for CassandraEngine { ); let result = self .session - .query_with_params( + .run( + Stmt::Read, &query, - params(Stmt::Read, cdrs_tokio::query_values!(account_id.as_str())), + cdrs_tokio::query_values!(account_id.as_str()), ) .await .map_err(|e| StorageError::Internal(e.to_string()))?; @@ -575,12 +569,10 @@ impl StreamEngine for CassandraEngine { ); let shard_result = self .session - .query_with_params( + .run( + Stmt::Read, &shard_query, - params( - Stmt::Read, - cdrs_tokio::query_values!(shard_id.as_str(), table_id.as_str()), - ), + cdrs_tokio::query_values!(shard_id.as_str(), table_id.as_str()), ) .await .map_err(|e| StorageError::Internal(e.to_string()))?; @@ -611,9 +603,10 @@ impl StreamEngine for CassandraEngine { ); let result = self .session - .query_with_params( + .run( + Stmt::Read, &query, - params(Stmt::Read, cdrs_tokio::query_values!(shard_id.as_str())), + cdrs_tokio::query_values!(shard_id.as_str()), ) .await .map_err(|e| StorageError::Internal(e.to_string()))?; diff --git a/crates/storage-cassandra/src/table_engine.rs b/crates/storage-cassandra/src/table_engine.rs index 28943cecf..c256d28d1 100644 --- a/crates/storage-cassandra/src/table_engine.rs +++ b/crates/storage-cassandra/src/table_engine.rs @@ -3,7 +3,8 @@ //! `TableEngine` trait implementation for `CassandraEngine`. -use crate::cassandra_util::{Stmt, params}; +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use cdrs_tokio::types::IntoRustByName; use futures::future::BoxFuture; @@ -70,26 +71,18 @@ impl TableEngine for CassandraEngine { let result = if let Some(ref start) = input.exclusive_start_table_name { self.session - .query_with_params( + .run( + Stmt::Read, &query, - params( - Stmt::Read, - cdrs_tokio::query_values!( - account_id.as_str(), - start.as_str(), - limit + 1 - ), - ), + cdrs_tokio::query_values!(account_id.as_str(), start.as_str(), limit + 1), ) .await } else { self.session - .query_with_params( + .run( + Stmt::Read, &query, - params( - Stmt::Read, - cdrs_tokio::query_values!(account_id.as_str(), limit + 1), - ), + cdrs_tokio::query_values!(account_id.as_str(), limit + 1), ) .await }; diff --git a/crates/storage-cassandra/src/table_helpers.rs b/crates/storage-cassandra/src/table_helpers.rs index c37f26e13..b4fe99400 100644 --- a/crates/storage-cassandra/src/table_helpers.rs +++ b/crates/storage-cassandra/src/table_helpers.rs @@ -3,7 +3,8 @@ //! Helper methods for `TableEngine` operations. -use crate::cassandra_util::{Stmt, params}; +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, @@ -35,12 +36,10 @@ impl CassandraEngine { let table_result = self .session - .query_with_params( + .run( + Stmt::Read, &table_query, - params( - Stmt::Read, - cdrs_tokio::query_values!(account_id, table_name), - ), + cdrs_tokio::query_values!(account_id, table_name), ) .await .map_err(|e| StorageError::Internal(format!("Query tables failed: {e}")))?; @@ -67,9 +66,10 @@ impl CassandraEngine { let index_result = self .session - .query_with_params( + .run( + Stmt::Read, &index_query, - params(Stmt::Read, cdrs_tokio::query_values!(table_id.as_str())), + 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/worker_store.rs b/crates/storage-cassandra/src/worker_store.rs index 4479a55d7..eb18ee355 100755 --- a/crates/storage-cassandra/src/worker_store.rs +++ b/crates/storage-cassandra/src/worker_store.rs @@ -3,7 +3,8 @@ //! `WorkerStore` trait implementation and control plane transition processing. -use crate::cassandra_util::{Stmt, params}; +use crate::cassandra_util::PolicySession as _; +use crate::cassandra_util::Stmt; use cdrs_tokio::types::IntoRustByName; use futures::future::BoxFuture; @@ -118,9 +119,10 @@ impl CassandraEngine { // Delete tags let tag_delete = format!("DELETE FROM {catalog_keyspace}.tags WHERE resource_arn = ?"); self.session - .query_with_params( + .run( + Stmt::Write, &tag_delete, - params(Stmt::Write, cdrs_tokio::query_values!(table_arn.as_str())), + 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/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, From 5c45a4b72ac4fd8a7f020dadf9623f6ca1ebe71b Mon Sep 17 00:00:00 2001 From: Joel Shepherd Date: Mon, 9 Nov 2026 23:57:18 +0000 Subject: [PATCH 08/12] test(storage-cassandra): fail on a statement that bypasses the consistency policy Add tests/consistency_policy.rs. It reads every non-test source file of the crate and fails on a driver call that sets its own consistency level or uses the driver's default: .query(, .query_with_values(, .query_with_params(, .exec*(, StatementParamsBuilder::new(, BatchQueryBuilder::new( or ::default(, QueryBatch::new( and Consistency::. Two paths are exempt, each with its reason: cassandra_util.rs, which sets every level, and migrations/, which uses QUORUM, SERIAL, ALL and LOCAL_QUORUM, and ONE only for reads of node-local system tables. One call opts out with a comment: the stream record batch copies the levels of the index batch that batch() built. Refs #770 --- .../src/data/transact_stream.rs | 1 + .../tests/consistency_policy.rs | 317 ++++++++++++++++++ 2 files changed, 318 insertions(+) create mode 100644 crates/storage-cassandra/tests/consistency_policy.rs diff --git a/crates/storage-cassandra/src/data/transact_stream.rs b/crates/storage-cassandra/src/data/transact_stream.rs index 4df80819a..c43815b3f 100644 --- a/crates/storage-cassandra/src/data/transact_stream.rs +++ b/crates/storage-cassandra/src/data/transact_stream.rs @@ -85,6 +85,7 @@ 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( BodyReqBatch::new( request.batch_type, diff --git a/crates/storage-cassandra/tests/consistency_policy.rs b/crates/storage-cassandra/tests/consistency_policy.rs new file mode 100644 index 000000000..394a1b336 --- /dev/null +++ b/crates/storage-cassandra/tests/consistency_policy.rs @@ -0,0 +1,317 @@ +// 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}; + +/// Calls that bypass the policy, and what to use instead. +const FORBIDDEN: &[(&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"), + ("StatementParamsBuilder::new(", "cassandra_util::params"), + ("BatchQueryBuilder::new(", "cassandra_util::batch"), + ("BatchQueryBuilder::default(", "cassandra_util::batch"), + ("QueryBatch::new(", "cassandra_util::batch"), + ("Consistency::", "a Stmt kind"), +]; + +/// 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) +} + +/// `code` with each `#[cfg(test)]` attribute followed by `mod NAME {` removed +/// up to its closing brace, keeping the newlines. +fn without_test_modules(code: &str) -> String { + let mut out = String::with_capacity(code.len()); + let mut rest = code; + while let Some(at) = rest.find("#[cfg(test)]") { + let after = &rest[at + "#[cfg(test)]".len()..]; + let is_module = after.trim_start().starts_with("mod ") + && after.find('{').is_some_and(|brace| { + after[..brace].trim_start().starts_with("mod ") && !after[..brace].contains(';') + }); + if !is_module { + out.push_str(&rest[..at + "#[cfg(test)]".len()]); + rest = after; + continue; + } + out.push_str(&rest[..at]); + let open = after.find('{').expect("a module body"); + let mut depth = 0_usize; + let mut end = after.len(); + for (offset, c) in after[open..].char_indices() { + match c { + '{' => depth += 1, + '}' => { + depth -= 1; + if depth == 0 { + end = open + offset + 1; + break; + } + } + _ => {} + } + } + let removed = &rest[at..at + "#[cfg(test)]".len() + end]; + out.extend(removed.chars().filter(|c| *c == '\n')); + rest = &after[end..]; + } + out.push_str(rest); + out +} + +/// 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, &'static str, &'static str)> { + let originals: Vec<&str> = source.lines().collect(); + let marked = |index: usize| originals.get(index).is_some_and(|l| l.contains(MARKER)); + let mut found = Vec::new(); + for (index, line) in code_only(source).lines().enumerate() { + if marked(index) || index > 0 && marked(index - 1) { + continue; + } + for (call, instead) in FORBIDDEN { + if line.contains(call) { + found.push((index + 1, *call, *instead)); + } + } + } + found +} + +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 = 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_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)) + .collect::>(), + [(8, ".query("), (19, ".query_with_values(")], + "{found:?}" + ); +} From 58d276379bec77f54fba2d66cdccdeddf7457301 Mon Sep 17 00:00:00 2001 From: Joel Shepherd Date: Tue, 10 Nov 2026 23:30:21 +0000 Subject: [PATCH 09/12] feat(storage-cassandra): send batches and system reads through the consistency policy handler Add PolicySession::run_batch. Refuses a batch that does not have the policy levels. The scan test now forbids .batch() and .batch_with_params(). Change 17 batch sends to use run_batch. Convert 3 reads of node-local system tables to SystemRead: the token read in scan, the system_schema.tables read in restore, and coordinator_now_millis in the backup catalog. shape_error now refuses a Read or SerialRead of system.* or system_schema.*. Change the test helpers in index, backup_engine and keyspace_migrations to read system tables with system_read. docs: the Known Limitations bullet now names LOCAL_QUORUM and LOCAL_SERIAL for reads, writes and lightweight transactions. --- crates/storage-cassandra/src/admin_store.rs | 4 +- .../storage-cassandra/src/backup_catalog.rs | 32 ++-- crates/storage-cassandra/src/backup_engine.rs | 14 +- crates/storage-cassandra/src/bootstrapper.rs | 9 +- .../storage-cassandra/src/cassandra_util.rs | 161 ++++++++++++------ crates/storage-cassandra/src/data/ddl.rs | 43 +---- .../storage-cassandra/src/data/delete_item.rs | 42 +++-- crates/storage-cassandra/src/data/index.rs | 47 +---- .../src/data/put_get_item.rs | 32 ++-- crates/storage-cassandra/src/data/scan.rs | 2 +- .../src/data/transactions.rs | 2 +- crates/storage-cassandra/src/data/ttl.rs | 24 +-- .../storage-cassandra/src/data/update_item.rs | 2 +- .../src/management_store/users.rs | 4 +- .../storage-cassandra/src/metadata_engine.rs | 49 ++---- .../src/password_hash_store.rs | 4 +- .../storage-cassandra/src/restore_engine.rs | 6 +- crates/storage-cassandra/src/ttl_worker.rs | 37 ++-- crates/storage-cassandra/src/update_table.rs | 3 +- crates/storage-cassandra/src/workers.rs | 3 +- .../tests/consistency_policy.rs | 2 + .../tests/direct/backup_engine.rs | 59 ++++--- .../tests/direct/consistency_shape.rs | 79 +++++++++ .../storage-cassandra/tests/direct/index.rs | 4 +- .../tests/direct/keyspace_migrations.rs | 4 +- .../tests/direct_integration.rs | 2 + docs/cassandra-setup.md | 4 +- 27 files changed, 361 insertions(+), 313 deletions(-) create mode 100644 crates/storage-cassandra/tests/direct/consistency_shape.rs diff --git a/crates/storage-cassandra/src/admin_store.rs b/crates/storage-cassandra/src/admin_store.rs index f61cb427f..ba73263f4 100755 --- a/crates/storage-cassandra/src/admin_store.rs +++ b/crates/storage-cassandra/src/admin_store.rs @@ -122,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()), @@ -150,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/backup_catalog.rs b/crates/storage-cassandra/src/backup_catalog.rs index 2d97d52ff..fba72eb93 100644 --- a/crates/storage-cassandra/src/backup_catalog.rs +++ b/crates/storage-cassandra/src/backup_catalog.rs @@ -121,7 +121,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!(), @@ -378,7 +378,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!( @@ -450,7 +450,7 @@ impl CassandraEngine { ), ); self.session - .batch( + .run_batch( batch .build() .map_err(|e| StorageError::Internal(e.to_string()))?, @@ -469,7 +469,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), @@ -518,7 +518,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 { @@ -541,7 +541,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.store_root.as_str(), status.as_str()), @@ -651,7 +651,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), @@ -844,7 +844,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!( @@ -887,7 +887,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!(), @@ -1012,7 +1012,7 @@ impl BackupCatalog for CassandraEngine { ), ); self.session - .batch( + .run_batch( batch .build() .map_err(|e| StorageError::Internal(e.to_string()))?, @@ -1523,7 +1523,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!(), @@ -1702,7 +1702,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), @@ -1786,7 +1786,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!(), @@ -1956,7 +1956,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()), @@ -1995,7 +1995,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()), @@ -2071,7 +2071,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()), diff --git a/crates/storage-cassandra/src/backup_engine.rs b/crates/storage-cassandra/src/backup_engine.rs index 92433740f..4ebf81aaa 100755 --- a/crates/storage-cassandra/src/backup_engine.rs +++ b/crates/storage-cassandra/src/backup_engine.rs @@ -498,7 +498,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), @@ -581,7 +581,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), @@ -826,7 +826,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), @@ -859,7 +859,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), @@ -899,7 +899,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), @@ -1977,7 +1977,7 @@ impl LegacyBackupReader for CassandraEngine { ), ); self.session - .batch( + .run_batch( batch .build() .map_err(|e| StorageError::Internal(e.to_string()))?, @@ -2343,7 +2343,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), diff --git a/crates/storage-cassandra/src/bootstrapper.rs b/crates/storage-cassandra/src/bootstrapper.rs index 37f1a6aa8..ef6833c31 100644 --- a/crates/storage-cassandra/src/bootstrapper.rs +++ b/crates/storage-cassandra/src/bootstrapper.rs @@ -329,7 +329,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!(), @@ -699,16 +699,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!(), diff --git a/crates/storage-cassandra/src/cassandra_util.rs b/crates/storage-cassandra/src/cassandra_util.rs index 53a132018..b3014f241 100644 --- a/crates/storage-cassandra/src/cassandra_util.rs +++ b/crates/storage-cassandra/src/cassandra_util.rs @@ -35,7 +35,8 @@ pub enum Stmt { Lwt, /// A read at `LOCAL_SERIAL`, which sees every committed Paxos round. SerialRead, - /// `CREATE`, `ALTER` or `DROP`: `ONE`. + /// `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`. @@ -78,9 +79,35 @@ pub trait PolicySession { ) -> 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, @@ -102,7 +129,8 @@ impl PolicySession for CassandraSession { /// What is wrong with `query` as a statement of `kind`, or `None` when its /// CQL matches `kind`: /// -/// - [`Stmt::Read`] and [`Stmt::SerialRead`]: a `SELECT`. +/// - [`Stmt::Read`] and [`Stmt::SerialRead`]: 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. @@ -116,16 +144,23 @@ 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 => (first != "SELECT").then_some("a read must be a SELECT"), + Stmt::Read | Stmt::SerialRead => { + 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 => { - let system = words - .iter() - .skip_while(|word| *word != "FROM") - .nth(1) - .is_some_and(|table| { - table.starts_with("SYSTEM.") || table.starts_with("SYSTEM_SCHEMA.") - }); if first != "SELECT" { Some("a system read must be a SELECT") } else if system { @@ -157,6 +192,22 @@ pub fn shape_error(kind: Stmt, query: &str) -> Option<&'static str> { } } +/// 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 { @@ -324,16 +375,6 @@ pub async fn query_rows( rows_at(session, query, Stmt::Read, values, context).await } -/// The same as [`query_rows`]. A later commit removes it. -pub async fn query_rows_quorum( - session: &Arc, - query: &str, - values: QueryValues, - context: &str, -) -> Result, E> { - query_rows(session, query, values, context).await -} - /// Execute a query at `LOCAL_SERIAL` and return all rows: the read sees /// every Paxos round that committed, so a row an LWT wrote (a claim taken, /// a heartbeat refreshed) is read as written. For the reads whose answer @@ -381,27 +422,6 @@ pub async fn execute( Ok(()) } -/// [`execute`], but the error names `context` and the driver's error, as -/// before. A later commit removes it. -/// -/// # 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> { - session - .run(Stmt::Write, query, values) - .await - .map_err(|error| { - tracing::error!("{context} quorum execute failed: {error}"); - E::db_error(format!("{context}: {error}")) - })?; - Ok(()) -} - // ══════════════════════════════════════════════════════════════════════════════ // Type Conversion Helpers // ══════════════════════════════════════════════════════════════════════════════ @@ -552,20 +572,6 @@ pub async fn apply_lwt( lwt_applied_flag(&result, context) } -/// The same as [`apply_lwt`]. A later commit removes it. -/// -/// # 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 { - apply_lwt(session, query, values, context).await -} - /// The `[applied]` flag of an LWT response, `false` when the response has no row. fn lwt_applied_flag( result: &cdrs_tokio::frame::Envelope, @@ -587,7 +593,34 @@ fn lwt_applied_flag( #[cfg(test)] mod tests { - use super::{Stmt, batch, params, shape_error}; + use super::{Stmt, batch, batch_level_error, params, 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() { @@ -596,6 +629,22 @@ mod tests { 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()); } diff --git a/crates/storage-cassandra/src/data/ddl.rs b/crates/storage-cassandra/src/data/ddl.rs index 98f7917cc..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, @@ -56,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); @@ -85,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() @@ -543,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 86b51b4d1..c904cb0fa 100644 --- a/crates/storage-cassandra/src/data/delete_item.rs +++ b/crates/storage-cassandra/src/data/delete_item.rs @@ -297,9 +297,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 @@ -505,7 +506,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}"))); @@ -590,9 +591,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 @@ -788,7 +790,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}"))); @@ -976,13 +978,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()); @@ -1004,10 +1002,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(), @@ -1053,7 +1051,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(); @@ -1153,7 +1151,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() { @@ -1664,7 +1662,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 30e4e1f1f..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| { diff --git a/crates/storage-cassandra/src/data/put_get_item.rs b/crates/storage-cassandra/src/data/put_get_item.rs index 891208389..c1a5e9f83 100644 --- a/crates/storage-cassandra/src/data/put_get_item.rs +++ b/crates/storage-cassandra/src/data/put_get_item.rs @@ -170,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(()) @@ -697,7 +697,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}")) })?; @@ -707,19 +707,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, @@ -756,13 +749,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); }; @@ -770,6 +759,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, diff --git a/crates/storage-cassandra/src/data/scan.rs b/crates/storage-cassandra/src/data/scan.rs index aacf97394..3c4c2d4f2 100644 --- a/crates/storage-cassandra/src/data/scan.rs +++ b/crates/storage-cassandra/src/data/scan.rs @@ -309,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/transactions.rs b/crates/storage-cassandra/src/data/transactions.rs index 5166764b8..6fdf90139 100644 --- a/crates/storage-cassandra/src/data/transactions.rs +++ b/crates/storage-cassandra/src/data/transactions.rs @@ -2185,7 +2185,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}")) })?; } diff --git a/crates/storage-cassandra/src/data/ttl.rs b/crates/storage-cassandra/src/data/ttl.rs index 5e551fafb..e2c189fc0 100644 --- a/crates/storage-cassandra/src/data/ttl.rs +++ b/crates/storage-cassandra/src/data/ttl.rs @@ -350,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}")))?; @@ -387,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 \ @@ -405,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 \ @@ -433,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} \ @@ -463,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} \ @@ -478,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} \ @@ -513,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} \ @@ -946,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!( @@ -1022,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), @@ -1106,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 \ @@ -1162,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} \ @@ -1207,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 \ diff --git a/crates/storage-cassandra/src/data/update_item.rs b/crates/storage-cassandra/src/data/update_item.rs index 4bbaa5538..b827b4e9a 100644 --- a/crates/storage-cassandra/src/data/update_item.rs +++ b/crates/storage-cassandra/src/data/update_item.rs @@ -547,7 +547,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/management_store/users.rs b/crates/storage-cassandra/src/management_store/users.rs index cd6ade80f..ffac28ca8 100644 --- a/crates/storage-cassandra/src/management_store/users.rs +++ b/crates/storage-cassandra/src/management_store/users.rs @@ -202,7 +202,7 @@ impl CassandraCatalogStore { .await?; // iam_users last: user is only gone once all dependent rows are cleaned up. // Quorum commit, so the console's quorum session check sees the deletion. - crate::cassandra_util::apply_lwt_quorum( + crate::cassandra_util::apply_lwt( &session, &format!("DELETE FROM {ks}.iam_users WHERE account_id = ? AND user_name = ? IF EXISTS"), cdrs_tokio::query_values!(account_id, user_name), @@ -421,7 +421,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 8121b3b52..b0d2f7ac3 100755 --- a/crates/storage-cassandra/src/metadata_engine.rs +++ b/crates/storage-cassandra/src/metadata_engine.rs @@ -52,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() @@ -85,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 \ @@ -115,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()) } }; diff --git a/crates/storage-cassandra/src/password_hash_store.rs b/crates/storage-cassandra/src/password_hash_store.rs index 7038b2617..f6fad83dc 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/ttl_worker.rs b/crates/storage-cassandra/src/ttl_worker.rs index b85b9900b..4585c8e9f 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 2a908db10..b5b7a3661 100644 --- a/crates/storage-cassandra/src/update_table.rs +++ b/crates/storage-cassandra/src/update_table.rs @@ -3,6 +3,7 @@ //! `update_table` implementation for the Cassandra backend. +use crate::cassandra_util::PolicySession as _; use cdrs_tokio::query::BatchQueryBuilder; use cdrs_tokio::query::QueryValues; use cdrs_tokio::types::IntoRustByName; @@ -567,7 +568,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/workers.rs b/crates/storage-cassandra/src/workers.rs index 3242ed036..adbeb57ae 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; @@ -491,7 +492,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 index 394a1b336..1cb05ba28 100644 --- a/crates/storage-cassandra/tests/consistency_policy.rs +++ b/crates/storage-cassandra/tests/consistency_policy.rs @@ -23,6 +23,8 @@ const FORBIDDEN: &[(&str, &str)] = &[ (".exec(", "PolicySession::run"), (".exec_with_values(", "PolicySession::run"), (".exec_with_params(", "PolicySession::run"), + (".batch(", "PolicySession::run_batch"), + (".batch_with_params(", "PolicySession::run_batch"), ("StatementParamsBuilder::new(", "cassandra_util::params"), ("BatchQueryBuilder::new(", "cassandra_util::batch"), ("BatchQueryBuilder::default(", "cassandra_util::batch"), diff --git a/crates/storage-cassandra/tests/direct/backup_engine.rs b/crates/storage-cassandra/tests/direct/backup_engine.rs index 4f1e7f99a..dc078d732 100644 --- a/crates/storage-cassandra/tests/direct/backup_engine.rs +++ b/crates/storage-cassandra/tests/direct/backup_engine.rs @@ -1683,7 +1683,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), @@ -1715,7 +1715,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), @@ -1870,7 +1870,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), @@ -2595,7 +2595,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, \ @@ -3008,7 +3008,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), @@ -3582,7 +3582,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), @@ -3602,7 +3602,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, \ @@ -3710,7 +3710,7 @@ async fn test_the_in_catalog_create_heartbeats_its_row_while_the_items_copy() { /// 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", @@ -3735,7 +3735,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 = ?", @@ -4257,7 +4257,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_{}", @@ -4482,7 +4482,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 = ?", @@ -5651,7 +5651,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 \ @@ -6724,7 +6724,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 = ?", @@ -6742,7 +6742,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 {}.{}", @@ -6780,18 +6780,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") @@ -6805,7 +6804,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!(), @@ -7846,7 +7845,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_{}", @@ -8063,7 +8062,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_{}", @@ -8228,7 +8227,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 = ?", 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..34ef10730 --- /dev/null +++ b/crates/storage-cassandra/tests/direct/consistency_shape.rs @@ -0,0 +1,79 @@ +// 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}" + ); + } + + /// `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 d7fa605c9..3109c4607 100644 --- a/crates/storage-cassandra/tests/direct/index.rs +++ b/crates/storage-cassandra/tests/direct/index.rs @@ -1946,7 +1946,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), @@ -1968,7 +1968,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 2c5476647..1578f355a 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. @@ -169,7 +169,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_integration.rs b/crates/storage-cassandra/tests/direct_integration.rs index 863bbda69..fbaee4a57 100644 --- a/crates/storage-cassandra/tests/direct_integration.rs +++ b/crates/storage-cassandra/tests/direct_integration.rs @@ -27,6 +27,8 @@ mod backup_engine; mod cassandra_engine; #[path = "direct/concurrent_account_creation.rs"] mod concurrent_account_creation; +#[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 6b08f4ce7..02fb3e202 100644 --- a/docs/cassandra-setup.md +++ b/docs/cassandra-setup.md @@ -364,8 +364,8 @@ 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, writes and lightweight + transactions use `LOCAL_QUORUM` / `LOCAL_SERIAL`, which are linearizable only within one datacenter. Serve writes for a given table from one Cassandra datacenter. - **Multi-node ExtendDB needs node-id configuration.** Running more than one From 0d8e61a2e9e4e3b8e4b594a8d9e88f062dd0c4b0 Mon Sep 17 00:00:00 2001 From: Joel Shepherd Date: Wed, 11 Nov 2026 01:15:22 +0000 Subject: [PATCH 10/12] fix(storage-cassandra): keep the CQL text out of the run() panic message The shape check in PolicySession::run printed the statement's CQL when the CQL did not match its kind. The CQL can hold a password (CREATE ROLE ... WITH PASSWORD) and account keyspace names. CodeQL reported this as cleartext logging of sensitive information. The message now names the kind and the shape error only. The consistency_shape test checks that the message does not hold the CQL text. --- crates/storage-cassandra/src/cassandra_util.rs | 4 +++- crates/storage-cassandra/tests/direct/consistency_shape.rs | 4 ++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/crates/storage-cassandra/src/cassandra_util.rs b/crates/storage-cassandra/src/cassandra_util.rs index b3014f241..75ca193f8 100644 --- a/crates/storage-cassandra/src/cassandra_util.rs +++ b/crates/storage-cassandra/src/cassandra_util.rs @@ -119,7 +119,9 @@ impl PolicySession for CassandraSession { let query = query.as_ref().to_owned(); debug_assert!( shape_error(kind, &query).is_none(), - "{kind:?} statement: {}: {query}", + // 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 } diff --git a/crates/storage-cassandra/tests/direct/consistency_shape.rs b/crates/storage-cassandra/tests/direct/consistency_shape.rs index 34ef10730..266ce83e5 100644 --- a/crates/storage-cassandra/tests/direct/consistency_shape.rs +++ b/crates/storage-cassandra/tests/direct/consistency_shape.rs @@ -41,6 +41,10 @@ mod tests { 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_batch` panics on a batch that was not built by From 47c09c83f763063fc6c55e78ead69e45b84f349f Mon Sep 17 00:00:00 2001 From: Joel Shepherd Date: Thu, 12 Nov 2026 00:57:25 +0000 Subject: [PATCH 11/12] test(storage-cassandra): check the consistency level of each statement 'kind' Add direct::consistency_levels. The 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 test keyspace has a replication factor of 2N + 1 on an N-node cluster. So a quorum of its replicas is N + 1 nodes, and the cluster cannot supply them. Each statement at a quorum level gets an Unavailable error that names the level. execute and apply_lwt return only "Database error". For these two, the test reads the level from the error that they log. - The system.paxos table. A read at LOCAL_SERIAL saves a Paxos promise there. A read at LOCAL_QUORUM saves none. The tests do not check the commit level of an LWT. The unit test on params() checks it. The policy scan now finds each send method in three forms: a method call, a method call with type arguments, and a path call. It also finds the pager methods, the raw request frames and send_envelope. KNOWN_BYPASSES lists one bypass for each pattern, so a removed pattern fails a test. The stream record batch in transact_stream.rs gets a second opt-out comment for its BodyReqBatch::new call. The comment on index_propagation_delay in engine.rs now says that the read and the settings write run at LOCAL_QUORUM. docs: cassandra-setup.md says that each request needs a quorum of its keyspace's replicas, and that a request fails with HTTP 500 while fewer are up. It recommends a replication factor of 3 on at least three nodes. It uses "linearizable" only for lightweight transactions. 11-high-availability.md no longer maps ConsistentRead = false to ONE. It also clarifies that table reads are strongly consistent when the clocks are in sync. --- .../src/data/transact_stream.rs | 1 + crates/storage-cassandra/src/engine.rs | 7 +- .../tests/consistency_policy.rs | 195 ++++++- .../tests/direct/consistency_levels.rs | 499 ++++++++++++++++++ .../tests/direct_integration.rs | 2 + docs/cassandra-setup.md | 15 +- docs/design/11-high-availability.md | 11 +- 7 files changed, 702 insertions(+), 28 deletions(-) create mode 100644 crates/storage-cassandra/tests/direct/consistency_levels.rs diff --git a/crates/storage-cassandra/src/data/transact_stream.rs b/crates/storage-cassandra/src/data/transact_stream.rs index c43815b3f..54a2185fd 100644 --- a/crates/storage-cassandra/src/data/transact_stream.rs +++ b/crates/storage-cassandra/src/data/transact_stream.rs @@ -87,6 +87,7 @@ 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/engine.rs b/crates/storage-cassandra/src/engine.rs index 4828f400c..8c86b8c2d 100644 --- a/crates/storage-cassandra/src/engine.rs +++ b/crates/storage-cassandra/src/engine.rs @@ -298,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')", diff --git a/crates/storage-cassandra/tests/consistency_policy.rs b/crates/storage-cassandra/tests/consistency_policy.rs index 1cb05ba28..62311debd 100644 --- a/crates/storage-cassandra/tests/consistency_policy.rs +++ b/crates/storage-cassandra/tests/consistency_policy.rs @@ -15,21 +15,154 @@ use std::path::{Path, PathBuf}; -/// Calls that bypass the policy, and what to use instead. -const FORBIDDEN: &[(&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"), +/// 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::<`), and a path call (`Session::m(&s, …)`). +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"), +]; + +/// 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 function that sends a frame to the nodes of a query plan. + ("send_envelope(", "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("]; + +/// 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)); + } + } + 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(", + ), ]; /// Source paths, relative to the crate, that set their own levels. @@ -198,17 +331,22 @@ fn without_test_modules(code: &str) -> String { /// 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, &'static str, &'static str)> { +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; } - for (call, instead) in FORBIDDEN { - if line.contains(call) { - found.push((index + 1, *call, *instead)); + let mut line = line.to_owned(); + for allowed in ALLOWED { + line = line.replace(allowed, &" ".repeat(allowed.len())); + } + for (pattern, instead) in &patterns { + if line.contains(pattern.as_str()) { + found.push((index + 1, pattern.clone(), *instead)); } } } @@ -274,16 +412,39 @@ fn each_exempt_path_exists() { #[test] fn the_scan_finds_each_forbidden_call() { - for (call, _) in FORBIDDEN { + for (call, _) in forbidden() { let source = 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), + 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 = "fn 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##" @@ -311,7 +472,7 @@ fn h() { assert_eq!( found .iter() - .map(|(line, call, _)| (*line, *call)) + .map(|(line, call, _)| (*line, call.as_str())) .collect::>(), [(8, ".query("), (19, ".query_with_values(")], "{found:?}" 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..dfa1c7eef --- /dev/null +++ b/crates/storage-cassandra/tests/direct/consistency_levels.rs @@ -0,0 +1,499 @@ +// 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:?}" + ); + } + + 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_integration.rs b/crates/storage-cassandra/tests/direct_integration.rs index fa8cca8ea..135baf2f4 100644 --- a/crates/storage-cassandra/tests/direct_integration.rs +++ b/crates/storage-cassandra/tests/direct_integration.rs @@ -28,6 +28,8 @@ 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"] diff --git a/docs/cassandra-setup.md b/docs/cassandra-setup.md index 02fb3e202..d15b23121 100644 --- a/docs/cassandra-setup.md +++ b/docs/cassandra-setup.md @@ -295,6 +295,16 @@ 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. +While 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 stops while any replica is +down. Use a replication factor of 3 on at least three nodes. 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. + The `datacenter` must be `datacenter1`: `init` hardcodes that name into the keyspace definitions and provides no flag to change it, so your cluster's local datacenter has to be named `datacenter1` @@ -364,8 +374,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.** Reads, writes and lightweight - transactions 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 b51069590..04dda51b2 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) From c2cbbb61f62d052f607f5e3faeb9a273edc8e4ea Mon Sep 17 00:00:00 2001 From: Joel Shepherd Date: Tue, 17 Nov 2026 18:22:19 +0000 Subject: [PATCH 12/12] test(storage-cassandra): make the scan find raw frames, methods taken as values, and code after a brace in a string --- .../tests/consistency_policy.rs | 252 +++++++++++++++--- 1 file changed, 216 insertions(+), 36 deletions(-) diff --git a/crates/storage-cassandra/tests/consistency_policy.rs b/crates/storage-cassandra/tests/consistency_policy.rs index 62311debd..2e712c781 100644 --- a/crates/storage-cassandra/tests/consistency_policy.rs +++ b/crates/storage-cassandra/tests/consistency_policy.rs @@ -17,7 +17,8 @@ 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::<`), and a path call (`Session::m(&s, …)`). +/// 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"), @@ -34,6 +35,12 @@ const SEND_METHODS: &[(&str, &str)] = &[ ("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"), @@ -48,13 +55,19 @@ const FORBIDDEN_TEXT: &[(&str, &str)] = &[ ("Envelope::new_query(", "PolicySession::run"), ("BodyReqQuery::new(", "PolicySession::run"), ("BodyReqBatch::new(", "PolicySession::run_batch"), - // The driver function that sends a frame to the nodes of a query plan. + // 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("]; +const ALLOWED: &[&str] = &["cassandra_util::batch(", "cassandra_util::batch;"]; /// Each forbidden pattern, and what to use instead. fn forbidden() -> Vec<(String, &'static str)> { @@ -63,6 +76,9 @@ fn forbidden() -> Vec<(String, &'static str)> { 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)); @@ -163,6 +179,29 @@ const KNOWN_BYPASSES: &[(&str, &str)] = &[ "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. @@ -287,47 +326,96 @@ fn raw_string_start(chars: &[char], i: usize) -> Option { (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. +/// 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 rest = code; - while let Some(at) = rest.find("#[cfg(test)]") { - let after = &rest[at + "#[cfg(test)]".len()..]; - let is_module = after.trim_start().starts_with("mod ") - && after.find('{').is_some_and(|brace| { - after[..brace].trim_start().starts_with("mod ") && !after[..brace].contains(';') - }); - if !is_module { - out.push_str(&rest[..at + "#[cfg(test)]".len()]); - rest = after; + let mut i = 0; + while i < chars.len() { + if let Some(end) = literal_end(&chars, i) { + out.extend(&chars[i..end]); + i = end; continue; } - out.push_str(&rest[..at]); - let open = after.find('{').expect("a module body"); - let mut depth = 0_usize; - let mut end = after.len(); - for (offset, c) in after[open..].char_indices() { - match c { - '{' => depth += 1, - '}' => { - depth -= 1; - if depth == 0 { - end = open + offset + 1; - break; - } - } - _ => {} + 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; } } - let removed = &rest[at..at + "#[cfg(test)]".len() + end]; - out.extend(removed.chars().filter(|c| *c == '\n')); - rest = &after[end..]; + out.push(chars[i]); + i += 1; } - out.push_str(rest); 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). @@ -345,7 +433,7 @@ fn bypasses(source: &str) -> Vec<(usize, String, &'static str)> { line = line.replace(allowed, &" ".repeat(allowed.len())); } for (pattern, instead) in &patterns { - if line.contains(pattern.as_str()) { + if matches_pattern(&line, pattern) { found.push((index + 1, pattern.clone(), *instead)); } } @@ -353,6 +441,20 @@ fn bypasses(source: &str) -> Vec<(usize, String, &'static str)> { 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('/') { @@ -413,7 +515,10 @@ fn each_exempt_path_exists() { #[test] fn the_scan_finds_each_forbidden_call() { for (call, _) in forbidden() { - let source = format!("fn f() {{\n let x = y{call}a);\n}}\n"); + 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), @@ -436,7 +541,8 @@ fn the_scan_finds_each_known_bypass() { #[test] fn the_scan_allows_the_policy_batch_builder() { - let source = "fn f() {\n let b = crate::cassandra_util::batch();\n \ + 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), @@ -478,3 +584,77 @@ fn h() { "{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:?}" + ); +}