diff --git a/src/db.rs b/src/db.rs index c404c669..441be9cc 100644 --- a/src/db.rs +++ b/src/db.rs @@ -30,6 +30,47 @@ use crate::types::{ CommandDef, GLOBAL_SCOPE, GuildSettings, GuildSettingsOverride, RuleDef, resolve_settings, }; +mod bounded_write { + use super::{Connection, Db, Result}; + use tokio::time::Instant; + + /// Borrows the connection checked out by [`Db::with_conn_before`] with its deadline. + pub(crate) struct BoundedConnection<'conn> { + connection: &'conn Connection, + write_deadline: Option, + } + + impl BoundedConnection<'_> { + pub(crate) fn connection_and_deadline(&self) -> (&Connection, Option) { + (self.connection, self.write_deadline) + } + } + + impl Db { + /// Applies the pinned write deadline to pool waits, checkout, and the connection + /// passed to `f`. Use [`crate::db_compat::DbRuntime::capture_write_deadline`] + /// to pin the deadline before the first checkout attempt. + pub(crate) async fn with_conn_before( + &self, + write_deadline: Option, + f: F, + ) -> Result + where + F: FnOnce(BoundedConnection<'_>) -> Result + Send + 'static, + T: Send + 'static, + { + self.with_conn_deadline(write_deadline, move |connection| { + f(BoundedConnection { + connection, + write_deadline, + }) + }) + .await + } + } +} +pub(crate) use bounded_write::BoundedConnection; + mod primary_outage; use primary_outage::{Admission, PrimaryBackoff, PrimaryOutageGate, PrimaryOutageReported}; @@ -1600,10 +1641,10 @@ impl Db { F: FnOnce(&mut Connection) -> Result + Send + 'static, T: Send + 'static, { - self.with_conn_before(None, f).await + self.with_conn_deadline(None, f).await } - async fn with_conn_before( + async fn with_conn_deadline( &self, write_deadline: Option, f: F, diff --git a/src/db/bot_actions.rs b/src/db/bot_actions.rs index 931e3cc4..71424629 100644 --- a/src/db/bot_actions.rs +++ b/src/db/bot_actions.rs @@ -478,7 +478,6 @@ pub async fn claim_advised_bot_action(db: &Db, now: i64) -> Result Result Result, now: i64, promote: bool, - write_deadline: Option, #[cfg(test)] after_due_read: Option, ) -> Result> { + let (connection, deadline) = conn.connection_and_deadline(); let mut tx = if promote { - conn.transaction_capture_before(write_deadline, false)? + conn.transaction_capture(false)? } else { - conn.transaction_primary_snapshot_before(write_deadline)? + connection.transaction_primary_snapshot_before(deadline)? }; let due: bool = tx.query_row(&poll_due_sql(), params![now], |r| Ok(r.get(0)?))?; if !due { @@ -539,7 +537,7 @@ fn claim_advised_bot_action_conn( tx } else { tx.finish_read()?; - conn.transaction_immediate_before(write_deadline)? + connection.transaction_immediate_before(deadline)? }; claim_bot_action_tx(tx, now) } diff --git a/src/db/guild_data/snapshots.rs b/src/db/guild_data/snapshots.rs index c3196e33..908d81a1 100644 --- a/src/db/guild_data/snapshots.rs +++ b/src/db/guild_data/snapshots.rs @@ -514,16 +514,18 @@ impl GuildDataStore { let first = operation.clone(); match self .db - .with_conn(move |conn| first(conn.transaction_capture_before(deadline, false)?)) + .with_conn_before(deadline, move |conn| { + first(conn.transaction_capture(false)?) + }) .await { Err(error) if crate::db_compat::is_database_busy(&error) => { - // The failed transaction was rolled back before with_conn + // The failed transaction was rolled back before checkout // returned. Re-read everything under the existing writer path // once, instead of repeatedly trying to promote stale reads. self.db - .with_conn(move |conn| { - operation(conn.transaction_capture_before(deadline, true)?) + .with_conn_before(deadline, move |conn| { + operation(conn.transaction_capture(true)?) }) .await } diff --git a/src/db/guild_data/tests/snapshots.rs b/src/db/guild_data/tests/snapshots.rs index 2e9344fd..cd2ff96f 100644 --- a/src/db/guild_data/tests/snapshots.rs +++ b/src/db/guild_data/tests/snapshots.rs @@ -1404,3 +1404,58 @@ async fn remote_capture_keeps_the_pooled_write_deadline_through_commit_and_retry fixture.assert_committed_within_lifetime(0); } } + +#[tokio::test(start_paused = true)] +async fn remote_capture_permit_wait_uses_the_captured_write_deadline() { + let (f, _, local, scope) = ready().await; + let (fixture, _) = HranaFixture::modeled_latency_database( + &f.store_path, + Duration::ZERO, + Duration::from_secs(5), + Default::default(), + ) + .await; + let write_limit = Duration::from_millis(100); + let remote = GuildDataStore { + db: fixture.db_with_operation_timeout(write_limit), + expected: local.expected.clone(), + core: None, + }; + let clock = crate::db_compat::ManualClock::new(); + remote + .db + .runtime + .install_manual_clock(Some(std::sync::Arc::clone(&clock))); + let _held = std::sync::Arc::clone(&remote.db.permits) + .try_acquire_many_owned(2) + .unwrap(); + let capture = remote.observe_snapshot(scope, observation(41, Some("queued"), None, 1)); + tokio::pin!(capture); + + tokio::select! { + biased; + result = &mut capture => panic!("capture returned before checkout queued: {result:?}"), + () = std::future::ready(()) => {} + } + clock.advance(write_limit - Duration::from_millis(1)); + tokio::select! { + biased; + result = &mut capture => panic!("checkout returned before the write deadline: {result:?}"), + () = std::future::ready(()) => {} + } + clock.advance(Duration::from_millis(1)); + let error = tokio::select! { + biased; + result = &mut capture => result.expect_err("capture succeeded at the deadline"), + () = std::future::ready(()) => panic!("capture still waiting at the captured write deadline"), + }; + + assert_eq!( + crate::db_compat::local_database_timeout_operation(&error), + Some(crate::db::WAIT_FOR_CONNECTION), + "{error:#}" + ); + assert_eq!(remote.db.connections.outage.failure_count(), 0); + assert!(fixture.take_statements().is_empty(), "capture started SQL"); + assert_eq!(remote.db.permits.available_permits(), 0); +} diff --git a/src/db/tests/remote_stream.rs b/src/db/tests/remote_stream.rs index ef126902..07dbe1e2 100644 --- a/src/db/tests/remote_stream.rs +++ b/src/db/tests/remote_stream.rs @@ -1993,6 +1993,23 @@ async fn slow_advised_due_check_leaves_time_to_prepare_the_claim() { super::cleanup_db(&path); } +#[tokio::test(flavor = "multi_thread", worker_threads = 2)] +async fn remote_capture_requires_a_checkout_write_deadline() { + let fixture = HranaFixture::start().await; + let remote = fixture.db_with_operation_timeout(Duration::from_secs(5)); + + let error = remote + .with_conn_before(None, |conn| conn.transaction_capture(false)?.finish_read()) + .await + .unwrap_err(); + + assert_eq!( + error.to_string(), + "remote capture requires a checkout write deadline" + ); + assert!(fixture.take_statements().is_empty(), "capture started SQL"); +} + #[tokio::test(flavor = "multi_thread", worker_threads = 2)] async fn capture_promotes_after_the_read_deadline_within_the_write_budget() { let path = super::tmp_db_path("remote_capture_promotion"); @@ -2003,8 +2020,8 @@ async fn capture_promotes_after_the_read_deadline_within_the_write_budget() { let deadline = remote.connections.runtime.capture_write_deadline(); remote - .with_conn(move |conn| { - let mut tx = conn.transaction_capture_before(deadline, false)?; + .with_conn_before(deadline, move |conn| { + let mut tx = conn.transaction_capture(false)?; let _: i64 = tx.query_row("SELECT 1", (), |row| Ok(row.get(0)?))?; // The final read succeeded before the interactive deadline. clock.advance(crate::db_compat::INTERACTIVE_READ_BUDGET + Duration::from_millis(500)); @@ -2041,8 +2058,8 @@ async fn expired_capture_cannot_prepare_growth_or_reclaim_receipts() { let clock = Arc::clone(&clock); let deadline = remote.runtime.capture_write_deadline(); let error = remote - .with_conn(move |conn| { - let mut tx = conn.transaction_capture_before(deadline, false)?; + .with_conn_before(deadline, move |conn| { + let mut tx = conn.transaction_capture(false)?; let _: i64 = tx.query_row("SELECT 1", (), |row| Ok(row.get(0)?))?; // Preflight returned successfully, then the budget expired // before the first required write. diff --git a/src/db_compat.rs b/src/db_compat.rs index b0bd1ab5..0febcd28 100644 --- a/src/db_compat.rs +++ b/src/db_compat.rs @@ -1953,11 +1953,8 @@ impl Connection { Ok(transaction) } - /// Snapshot capture reads before acquiring the writer lock. A concurrent - /// writer can invalidate promotion; the capture owner must restart the - /// entire operation on a proven busy error, never reuse the read results. #[track_caller] - pub(crate) fn transaction_capture_before( + fn transaction_capture_with_deadline( &self, write_deadline: Option, immediate: bool, @@ -2160,6 +2157,23 @@ impl Connection { } } +impl crate::db::BoundedConnection<'_> { + /// Opens capture on the connection supplied by [`crate::db::Db::with_conn_before`]. + /// + /// Deferred capture reads before acquiring the writer lock. A concurrent + /// writer can invalidate promotion. On a proven busy error, the capture + /// owner restarts the entire operation using the original write deadline. + #[track_caller] + pub(crate) fn transaction_capture(&self, immediate: bool) -> Result { + let (connection, write_deadline) = self.connection_and_deadline(); + anyhow::ensure!( + write_deadline.is_some() || !connection.runtime.is_remote(), + "remote capture requires a checkout write deadline" + ); + connection.transaction_capture_with_deadline(write_deadline, immediate) + } +} + impl SqlExecutor for Connection { fn execute(&self, sql: &str, params: impl IntoParams + Send) -> Result { require_read_sql(sql)?; @@ -4109,7 +4123,7 @@ mod tests { .unwrap(); let writer = Connection::open(&path).unwrap(); let mut capture = reader - .transaction_capture_before(reader.runtime.capture_write_deadline(), false) + .transaction_capture_with_deadline(reader.runtime.capture_write_deadline(), false) .unwrap(); let before: i64 = capture .query_row("SELECT value FROM counter", (), |r| Ok(r.get(0)?))