Lines
100 %
Functions
90 %
Branches
//! The tag key lock protocol: advisory key locks for the whole key set, then
//! the tag rows by key, both in canonical (name, value) byte order.
//!
//! A writer that read tag rows before locking passes them as `touched` to
//! [`lock`], which rechecks their keys under the locks and returns
//! [`KeyChanged`] when one was renamed meanwhile; the writer then rolls back
//! and runs again in a fresh DB transaction, at most [`ATTEMPTS`] times.
use std::collections::{BTreeMap, BTreeSet};
use finance::tag::Tag;
use sqlx::{Connection, PgConnection, Postgres, Transaction, types::Uuid};
/// A stored `(tag_name, tag_value)`.
pub(crate) type Key = (String, String);
/// Attempts a writer makes before giving up with [`crate::db::DBError::WriteConflict`].
pub(crate) const ATTEMPTS: usize = 3;
/// The longest a tag writer waits for any one lock before failing with
/// SQLSTATE 55P03. A blocked wait inside Postgres ignores a cancelled future,
/// so no deadline of the caller can interrupt it. A lock timeout is not
/// retried: the holder that stalled is likely still there.
pub(crate) const LOCK_TIMEOUT: &str = "3s";
/// Begin a DB transaction whose lock waits end after [`LOCK_TIMEOUT`].
pub(crate) async fn begin(conn: &mut PgConnection) -> sqlx::Result<Transaction<'_, Postgres>> {
let mut tx = conn.begin().await?;
bound_waits(&mut tx).await?;
Ok(tx)
}
/// Bound the lock waits of the current DB transaction by [`LOCK_TIMEOUT`].
pub(crate) async fn bound_waits(conn: &mut PgConnection) -> sqlx::Result<()> {
bound_waits_to(conn, LOCK_TIMEOUT).await
async fn bound_waits_to(conn: &mut PgConnection, timeout: &str) -> sqlx::Result<()> {
sqlx::query_file!("sql/select/tags/set_lock_timeout.sql", timeout)
.fetch_one(conn)
.await?;
Ok(())
/// SQLSTATEs of a deadlock and a serialization failure.
const RETRYABLE_SQLSTATES: [&str; 2] = ["40P01", "40001"];
/// SQLSTATE of a lock wait cut short by `lock_timeout`.
const LOCK_TIMEOUT_SQLSTATE: &str = "55P03";
fn has_sqlstate(err: &sqlx::Error, sqlstates: &[&str]) -> bool {
err.as_database_error()
.and_then(|db| db.code())
.is_some_and(|code| sqlstates.contains(&code.as_ref()))
/// A deadlock or serialization failure: the attempt may succeed when run again.
pub(crate) fn is_retryable(err: &sqlx::Error) -> bool {
has_sqlstate(err, &RETRYABLE_SQLSTATES)
/// A lock wait that hit [`LOCK_TIMEOUT`]: the caller is told to try again
/// later, the writer does not.
pub(crate) fn is_lock_timeout(err: &sqlx::Error) -> bool {
has_sqlstate(err, &[LOCK_TIMEOUT_SQLSTATE])
/// A touched tag row no longer has the key it was read with.
#[derive(Debug, PartialEq, Eq)]
pub(crate) struct KeyChanged;
/// The normalized keys `tags` are stored under.
pub(crate) fn destination_keys<'a>(tags: impl IntoIterator<Item = &'a Tag>) -> BTreeSet<Key> {
tags.into_iter()
.map(|tag| {
let (name, value) = tag.normalized();
(name.to_string(), value.to_string())
})
.collect()
/// Lock, until commit, every key in `keys`: first all advisory key locks, then
/// the existing tag rows. Returns the id of each key's row. A key with no row
/// yet cannot be row-locked; its advisory lock makes writers that create it
/// serialize like writers of an existing row.
pub(crate) async fn lock_keys(
conn: &mut PgConnection,
keys: &BTreeSet<Key>,
) -> Result<BTreeMap<Key, Uuid>, sqlx::Error> {
for (name, value) in keys {
sqlx::query_file!("sql/select/tags/lock_key.sql", name, value)
.fetch_one(&mut *conn)
let mut locked = BTreeMap::new();
for key in keys {
let (name, value) = key;
if let Some(row) = sqlx::query_file!("sql/select/tags/lock_by_key.sql", name, value)
.fetch_optional(&mut *conn)
.await?
{
locked.insert(key.clone(), row.id);
Ok(locked)
/// Lock the stored keys of the `touched` rows, as read before this call, and
/// the normalized keys of `destinations`, inside the caller's DB transaction.
/// `KeyChanged` when a touched row no longer holds its key: the caller must
/// roll back and retry.
pub(crate) async fn lock(
touched: &[(Uuid, Key)],
destinations: &[&Tag],
) -> Result<Result<(), KeyChanged>, sqlx::Error> {
let mut keys = destination_keys(destinations.iter().copied());
keys.extend(touched.iter().map(|(_, key)| key.clone()));
let locked = lock_keys(conn, &keys).await?;
match touched.iter().all(|(id, key)| locked.get(key) == Some(id)) {
true => Ok(Ok(())),
false => Ok(Err(KeyChanged)),
/// Roll back an attempt that found a touched key changed.
pub(crate) async fn retry(
tx: Transaction<'_, Postgres>,
tx.rollback().await?;
Ok(Err(KeyChanged))
/// Rows of one tag name in canonical byte order of their values.
pub(crate) fn in_key_order(
name: &str,
rows: impl Iterator<Item = (Uuid, String)>,
) -> Vec<(Uuid, Key)> {
sorted_keys(rows.map(|(id, value)| (id, (name.to_string(), value))))
/// Keyed rows in canonical byte order of their keys.
pub(crate) fn sorted_keys(rows: impl Iterator<Item = (Uuid, Key)>) -> Vec<(Uuid, Key)> {
let mut keyed: Vec<(Uuid, Key)> = rows.collect();
keyed.sort_by(|a, b| a.1.cmp(&b.1));
keyed
#[cfg(test)]
#[path = "lock_tests.rs"]
mod tests;