1
//! Lock waits that tests force and observe, so a test cannot pass without the
2
//! contention it claims to exercise.
3

            
4
use super::Fixture;
5
use sqlx::types::Uuid;
6
use sqlx::{PgConnection, Postgres, Transaction};
7

            
8
/// The advisory key of `sql/select/tags/lock_key.sql`, as a SQL expression.
9
macro_rules! key_hash {
10
    () => {
11
        "hashtextextended(length($1::text)::text || ':' || $1 || $2::text, 0)"
12
    };
13
}
14

            
15
/// Every wait gives up after `POLLS * POLL_PAUSE` (30 s) and fails the test.
16
const POLLS: usize = 1500;
17
const POLL_PAUSE: std::time::Duration = std::time::Duration::from_millis(20);
18

            
19
/// Polls until at least `count` backends of this database wait on a lock.
20
45
pub(in crate::command) async fn wait_for_blocked(fx: &Fixture, count: i64) -> anyhow::Result<()> {
21
45
    let mut conn = fx.user.get_connection().await?;
22
45
    wait_for_blocked_on(&mut conn, count).await
23
45
}
24

            
25
/// Same, polling on an already held connection, for tests whose commands
26
/// leave no pooled connection free to poll with. Inside a transaction
27
/// `pg_stat_activity` is a frozen snapshot that misses backends connecting
28
/// later, so each poll clears it.
29
56
pub(in crate::command) async fn wait_for_blocked_on(
30
56
    conn: &mut PgConnection,
31
56
    count: i64,
32
56
) -> anyhow::Result<()> {
33
56
    for _ in 0..POLLS {
34
99
        sqlx::query("SELECT pg_stat_clear_snapshot()")
35
99
            .execute(&mut *conn)
36
99
            .await?;
37
99
        let waiting: i64 = sqlx::query_scalar(
38
99
            "SELECT count(*) FROM pg_stat_activity
39
99
             WHERE datname = current_database() AND wait_event_type = 'Lock'",
40
99
        )
41
99
        .fetch_one(&mut *conn)
42
99
        .await?;
43
99
        if waiting >= count {
44
56
            return Ok(());
45
43
        }
46
43
        tokio::time::sleep(POLL_PAUSE).await;
47
    }
48
    anyhow::bail!("fewer than {count} backends ever waited on a lock")
49
56
}
50

            
51
/// Polls until a backend waits for the advisory lock of `(name, value)`.
52
47
pub(in crate::command) async fn wait_for_key_waiter(
53
47
    fx: &Fixture,
54
47
    name: &str,
55
47
    value: &str,
56
47
) -> anyhow::Result<()> {
57
47
    let mut conn = fx.user.get_connection().await?;
58
47
    let query = concat!(
59
        "SELECT count(*) FROM pg_locks
60
         WHERE locktype = 'advisory' AND NOT granted
61
           AND database = (SELECT oid FROM pg_database WHERE datname = current_database())
62
           AND ((classid::bigint << 32) | objid::bigint) = ",
63
        key_hash!()
64
    );
65
47
    for _ in 0..POLLS {
66
84
        let waiting: i64 = sqlx::query_scalar(query)
67
84
            .bind(name)
68
84
            .bind(value)
69
84
            .fetch_one(&mut *conn)
70
84
            .await?;
71
84
        if waiting > 0 {
72
47
            return Ok(());
73
37
        }
74
37
        tokio::time::sleep(POLL_PAUSE).await;
75
    }
76
    anyhow::bail!("nobody ever waited for the key ({name}, {value})")
77
47
}
78

            
79
/// Take the advisory lock of `(name, value)` until `conn`'s transaction ends.
80
53
pub(in crate::command) async fn hold_key(
81
53
    conn: &mut PgConnection,
82
53
    name: &str,
83
53
    value: &str,
84
53
) -> anyhow::Result<()> {
85
53
    sqlx::query_file!("sql/select/tags/lock_key.sql", name, value)
86
53
        .fetch_one(conn)
87
53
        .await?;
88
53
    Ok(())
89
53
}
90

            
91
/// Whether no other transaction holds the advisory lock of `(name, value)`.
92
2
pub(in crate::command) async fn key_is_free(
93
2
    fx: &Fixture,
94
2
    name: &str,
95
2
    value: &str,
96
2
) -> anyhow::Result<bool> {
97
2
    let mut conn = fx.user.get_connection().await?;
98
2
    let free: bool = sqlx::query_scalar(concat!("SELECT pg_try_advisory_lock(", key_hash!(), ")"))
99
2
        .bind(name)
100
2
        .bind(value)
101
2
        .fetch_one(&mut *conn)
102
2
        .await?;
103
2
    if free {
104
2
        sqlx::query(concat!("SELECT pg_advisory_unlock(", key_hash!(), ")"))
105
2
            .bind(name)
106
2
            .bind(value)
107
2
            .execute(&mut *conn)
108
2
            .await?;
109
    }
110
2
    Ok(free)
111
2
}
112

            
113
/// Await `waited`, then commit `holder` whatever it returned: a wait that
114
/// fails must not leave the holder's locks blocking the commands under test,
115
/// since dropping a transaction only queues its rollback.
116
33
pub(in crate::command) async fn release_after<T>(
117
33
    waited: impl Future<Output = anyhow::Result<T>>,
118
33
    holder: Transaction<'_, Postgres>,
119
33
) -> anyhow::Result<T> {
120
33
    let waited = waited.await;
121
33
    holder.commit().await?;
122
33
    waited
123
33
}
124

            
125
/// Set the stored value of the tag row `id`.
126
41
pub(in crate::command) async fn rename(
127
41
    conn: &mut PgConnection,
128
41
    id: Uuid,
129
41
    value: &str,
130
41
) -> anyhow::Result<()> {
131
41
    sqlx::query("UPDATE tags SET tag_value = $2 WHERE id = $1")
132
41
        .bind(id)
133
41
        .bind(value)
134
41
        .execute(conn)
135
41
        .await?;
136
41
    Ok(())
137
41
}
138

            
139
/// Each `(holder, held, next)` in turn: once a backend waits for the held
140
/// key `(name, held)`, rename the tag row `id` to `next` and commit. A failed
141
/// wait rolls back this and every later holder before failing.
142
12
pub(in crate::command) async fn rename_in_turn(
143
12
    fx: &Fixture,
144
12
    name: &str,
145
12
    id: Uuid,
146
12
    holders: Vec<(Transaction<'_, Postgres>, &str, &str)>,
147
12
) -> anyhow::Result<()> {
148
12
    let mut pending = holders.into_iter();
149
48
    while let Some((mut holder, held, next)) = pending.next() {
150
36
        let renamed = async {
151
36
            wait_for_key_waiter(fx, name, held).await?;
152
36
            rename(&mut holder, id, next).await
153
36
        }
154
36
        .await;
155
36
        if let Err(err) = renamed {
156
            holder.rollback().await?;
157
            for (rest, _, _) in pending {
158
                rest.rollback().await?;
159
            }
160
            return Err(err);
161
36
        }
162
36
        holder.commit().await?;
163
    }
164
12
    Ok(())
165
12
}
166

            
167
/// Keeps the cycle holder from running its own deadlock check, so the command
168
/// under test is always the one that detects the cycle.
169
///
170
/// Only a superuser may set `deadlock_timeout`; the suites run as one in the
171
/// xtask private cluster.
172
2
async fn defer_deadlock_check(conn: &mut PgConnection) -> anyhow::Result<()> {
173
2
    sqlx::query("SET LOCAL deadlock_timeout = '1min'")
174
2
        .execute(conn)
175
2
        .await
176
        .map_err(|err| {
177
            anyhow::anyhow!(
178
                "setting deadlock_timeout needs a superuser; run the tests in the xtask \
179
                 private cluster (`cargo run -p xtask -- postgres -- cargo nextest run ...`): {err}"
180
            )
181
        })?;
182
2
    Ok(())
183
2
}
184

            
185
/// Abort the command under test with a deadlock once: when it waits on
186
/// `stall`'s lock, run `during`; then `cycle` waits for the key `(name,
187
/// value)` the command holds, and `stall` is released, so the command meets
188
/// `cycle`. Both holders end on every path.
189
2
pub(in crate::command) async fn steer_deadlock(
190
2
    fx: &Fixture,
191
2
    stall: Transaction<'_, Postgres>,
192
2
    mut cycle: Transaction<'_, Postgres>,
193
2
    (name, value): (&str, &str),
194
2
    during: impl Future<Output = anyhow::Result<()>>,
195
2
) -> anyhow::Result<()> {
196
2
    let started = async {
197
2
        defer_deadlock_check(&mut cycle).await?;
198
2
        wait_for_blocked(fx, 1).await?;
199
2
        during.await
200
2
    }
201
2
    .await;
202
2
    if let Err(err) = started {
203
        stall.rollback().await?;
204
        cycle.rollback().await?;
205
        return Err(err);
206
2
    }
207
2
    let waiter = async {
208
2
        let held = hold_key(&mut cycle, name, value).await;
209
2
        cycle.commit().await?;
210
2
        held
211
2
    };
212
2
    let stalled = async {
213
2
        wait_for_key_waiter(fx, name, value).await?;
214
2
        anyhow::Ok(())
215
2
    };
216
2
    let (w, r) = tokio::join!(waiter, release_after(stalled, stall));
217
2
    w?;
218
2
    r
219
2
}