Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 43 additions & 2 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Instant>,
}

impl BoundedConnection<'_> {
pub(crate) fn connection_and_deadline(&self) -> (&Connection, Option<Instant>) {
(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<T, F>(
&self,
write_deadline: Option<Instant>,
f: F,
) -> Result<T>
where
F: FnOnce(BoundedConnection<'_>) -> Result<T> + 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};

Expand Down Expand Up @@ -1600,10 +1641,10 @@ impl Db {
F: FnOnce(&mut Connection) -> Result<T> + Send + 'static,
T: Send + 'static,
{
self.with_conn_before(None, f).await
self.with_conn_deadline(None, f).await
}

async fn with_conn_before<T, F>(
async fn with_conn_deadline<T, F>(
&self,
write_deadline: Option<tokio::time::Instant>,
f: F,
Expand Down
12 changes: 5 additions & 7 deletions src/db/bot_actions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -478,7 +478,6 @@ pub async fn claim_advised_bot_action(db: &Db, now: i64) -> Result<Option<BotAct
conn,
now,
true,
write_deadline,
#[cfg(test)]
after_due_read,
)
Expand All @@ -504,7 +503,6 @@ pub async fn claim_advised_bot_action(db: &Db, now: i64) -> Result<Option<BotAct
conn,
now,
false,
write_deadline,
#[cfg(test)]
None,
)
Expand All @@ -513,16 +511,16 @@ pub async fn claim_advised_bot_action(db: &Db, now: i64) -> Result<Option<BotAct
}

fn claim_advised_bot_action_conn(
conn: &Connection,
conn: super::BoundedConnection<'_>,
now: i64,
promote: bool,
write_deadline: Option<tokio::time::Instant>,
#[cfg(test)] after_due_read: Option<super::AdvisedClaimHook>,
) -> Result<Option<BotAction>> {
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 {
Expand All @@ -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)
}
Expand Down
10 changes: 6 additions & 4 deletions src/db/guild_data/snapshots.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down
55 changes: 55 additions & 0 deletions src/db/guild_data/tests/snapshots.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
25 changes: 21 additions & 4 deletions src/db/tests/remote_stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -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));
Expand Down Expand Up @@ -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.
Expand Down
24 changes: 19 additions & 5 deletions src/db_compat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Instant>,
immediate: bool,
Expand Down Expand Up @@ -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<Transaction> {
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<usize> {
require_read_sql(sql)?;
Expand Down Expand Up @@ -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)?))
Expand Down
Loading