1
//! The tag key lock protocol: advisory key locks for the whole key set, then
2
//! the tag rows by key, both in canonical (name, value) byte order.
3
//!
4
//! A writer that read tag rows before locking passes them as `touched` to
5
//! [`lock`], which rechecks their keys under the locks and returns
6
//! [`KeyChanged`] when one was renamed meanwhile; the writer then rolls back
7
//! and runs again in a fresh DB transaction, at most [`ATTEMPTS`] times.
8

            
9
use std::collections::{BTreeMap, BTreeSet};
10

            
11
use finance::tag::Tag;
12
use sqlx::{Connection, PgConnection, Postgres, Transaction, types::Uuid};
13

            
14
/// A stored `(tag_name, tag_value)`.
15
pub(crate) type Key = (String, String);
16

            
17
/// Attempts a writer makes before giving up with [`crate::db::DBError::WriteConflict`].
18
pub(crate) const ATTEMPTS: usize = 3;
19

            
20
/// The longest a tag writer waits for any one lock before failing with
21
/// SQLSTATE 55P03. A blocked wait inside Postgres ignores a cancelled future,
22
/// so no deadline of the caller can interrupt it. A lock timeout is not
23
/// retried: the holder that stalled is likely still there.
24
pub(crate) const LOCK_TIMEOUT: &str = "3s";
25

            
26
/// Begin a DB transaction whose lock waits end after [`LOCK_TIMEOUT`].
27
843661
pub(crate) async fn begin(conn: &mut PgConnection) -> sqlx::Result<Transaction<'_, Postgres>> {
28
843661
    let mut tx = conn.begin().await?;
29
843661
    bound_waits(&mut tx).await?;
30
843661
    Ok(tx)
31
843661
}
32

            
33
/// Bound the lock waits of the current DB transaction by [`LOCK_TIMEOUT`].
34
1005745
pub(crate) async fn bound_waits(conn: &mut PgConnection) -> sqlx::Result<()> {
35
1005745
    bound_waits_to(conn, LOCK_TIMEOUT).await
36
1005745
}
37

            
38
1005746
async fn bound_waits_to(conn: &mut PgConnection, timeout: &str) -> sqlx::Result<()> {
39
1005746
    sqlx::query_file!("sql/select/tags/set_lock_timeout.sql", timeout)
40
1005746
        .fetch_one(conn)
41
1005746
        .await?;
42
1005746
    Ok(())
43
1005746
}
44

            
45
/// SQLSTATEs of a deadlock and a serialization failure.
46
const RETRYABLE_SQLSTATES: [&str; 2] = ["40P01", "40001"];
47

            
48
/// SQLSTATE of a lock wait cut short by `lock_timeout`.
49
const LOCK_TIMEOUT_SQLSTATE: &str = "55P03";
50

            
51
13614
fn has_sqlstate(err: &sqlx::Error, sqlstates: &[&str]) -> bool {
52
13614
    err.as_database_error()
53
2722
        .and_then(|db| db.code())
54
2722
        .is_some_and(|code| sqlstates.contains(&code.as_ref()))
55
13614
}
56

            
57
/// A deadlock or serialization failure: the attempt may succeed when run again.
58
1182
pub(crate) fn is_retryable(err: &sqlx::Error) -> bool {
59
1182
    has_sqlstate(err, &RETRYABLE_SQLSTATES)
60
1182
}
61

            
62
/// A lock wait that hit [`LOCK_TIMEOUT`]: the caller is told to try again
63
/// later, the writer does not.
64
12432
pub(crate) fn is_lock_timeout(err: &sqlx::Error) -> bool {
65
12432
    has_sqlstate(err, &[LOCK_TIMEOUT_SQLSTATE])
66
12432
}
67

            
68
/// A touched tag row no longer has the key it was read with.
69
#[derive(Debug, PartialEq, Eq)]
70
pub(crate) struct KeyChanged;
71

            
72
/// The normalized keys `tags` are stored under.
73
607356
pub(crate) fn destination_keys<'a>(tags: impl IntoIterator<Item = &'a Tag>) -> BTreeSet<Key> {
74
607356
    tags.into_iter()
75
845785
        .map(|tag| {
76
845785
            let (name, value) = tag.normalized();
77
845785
            (name.to_string(), value.to_string())
78
845785
        })
79
        .collect()
80
607356
}
81

            
82
/// Lock, until commit, every key in `keys`: first all advisory key locks, then
83
/// the existing tag rows. Returns the id of each key's row. A key with no row
84
/// yet cannot be row-locked; its advisory lock makes writers that create it
85
/// serialize like writers of an existing row.
86
996817
pub(crate) async fn lock_keys(
87
996817
    conn: &mut PgConnection,
88
996817
    keys: &BTreeSet<Key>,
89
996817
) -> Result<BTreeMap<Key, Uuid>, sqlx::Error> {
90
996817
    for (name, value) in keys {
91
1259638
        sqlx::query_file!("sql/select/tags/lock_key.sql", name, value)
92
1259638
            .fetch_one(&mut *conn)
93
1259638
            .await?;
94
    }
95
996813
    let mut locked = BTreeMap::new();
96
996813
    for key in keys {
97
1259273
        let (name, value) = key;
98
1259273
        if let Some(row) = sqlx::query_file!("sql/select/tags/lock_by_key.sql", name, value)
99
1259273
            .fetch_optional(&mut *conn)
100
1259273
            .await?
101
        {
102
246931
            locked.insert(key.clone(), row.id);
103
1011801
        }
104
    }
105
996272
    Ok(locked)
106
996817
}
107

            
108
/// Lock the stored keys of the `touched` rows, as read before this call, and
109
/// the normalized keys of `destinations`, inside the caller's DB transaction.
110
/// `KeyChanged` when a touched row no longer holds its key: the caller must
111
/// roll back and retry.
112
229592
pub(crate) async fn lock(
113
229592
    conn: &mut PgConnection,
114
229592
    touched: &[(Uuid, Key)],
115
229592
    destinations: &[&Tag],
116
229592
) -> Result<Result<(), KeyChanged>, sqlx::Error> {
117
229592
    let mut keys = destination_keys(destinations.iter().copied());
118
230757
    keys.extend(touched.iter().map(|(_, key)| key.clone()));
119
229592
    let locked = lock_keys(conn, &keys).await?;
120
230359
    match touched.iter().all(|(id, key)| locked.get(key) == Some(id)) {
121
229146
        true => Ok(Ok(())),
122
83
        false => Ok(Err(KeyChanged)),
123
    }
124
229592
}
125

            
126
/// Roll back an attempt that found a touched key changed.
127
40
pub(crate) async fn retry(
128
40
    tx: Transaction<'_, Postgres>,
129
40
) -> Result<Result<(), KeyChanged>, sqlx::Error> {
130
40
    tx.rollback().await?;
131
40
    Ok(Err(KeyChanged))
132
40
}
133

            
134
/// Rows of one tag name in canonical byte order of their values.
135
10991
pub(crate) fn in_key_order(
136
10991
    name: &str,
137
10991
    rows: impl Iterator<Item = (Uuid, String)>,
138
10991
) -> Vec<(Uuid, Key)> {
139
10991
    sorted_keys(rows.map(|(id, value)| (id, (name.to_string(), value))))
140
10991
}
141

            
142
/// Keyed rows in canonical byte order of their keys.
143
714750
pub(crate) fn sorted_keys(rows: impl Iterator<Item = (Uuid, Key)>) -> Vec<(Uuid, Key)> {
144
714750
    let mut keyed: Vec<(Uuid, Key)> = rows.collect();
145
714750
    keyed.sort_by(|a, b| a.1.cmp(&b.1));
146
714750
    keyed
147
714750
}
148

            
149
#[cfg(test)]
150
#[path = "lock_tests.rs"]
151
mod tests;