1
//! Edits on the tag lock protocol under forced interleavings.
2

            
3
use super::*;
4
use crate::command::CmdError;
5
use crate::db::DBError;
6
use crate::error::ServerError;
7
use sqlx::Connection;
8

            
9
/// Insert the tag row `(name, value)` verbatim and link it to `tx_id`.
10
12
pub(super) async fn link_raw_tag(
11
12
    pool: &PgPool,
12
12
    tx_id: Uuid,
13
12
    name: &str,
14
12
    value: &str,
15
12
) -> anyhow::Result<Uuid> {
16
12
    let id = Uuid::new_v4();
17
12
    sqlx::query("INSERT INTO tags (id, tag_name, tag_value) VALUES ($1, $2, $3)")
18
12
        .bind(id)
19
12
        .bind(name)
20
12
        .bind(value)
21
12
        .execute(pool)
22
12
        .await?;
23
12
    sqlx::query_file!("sql/insert/transaction_tags/transaction_tag.sql", tx_id, id)
24
12
        .execute(pool)
25
12
        .await?;
26
12
    Ok(id)
27
12
}
28

            
29
3
fn edit_tags(
30
3
    fx: &Fixture,
31
3
    tx_id: Uuid,
32
3
    tags: &[(&str, &str)],
33
3
) -> impl std::future::Future<Output = Result<Option<CmdResult>, CmdError>> {
34
3
    UpdateTransaction::new()
35
3
        .user_id(fx.user.id)
36
3
        .transaction_id(tx_id)
37
3
        .tags(tag_map(tags))
38
3
        .run()
39
3
}
40

            
41
/// Two edits of transactions linked to a padded stored tag both write its
42
/// normalized key; the first queues on the padded row, the second on its key.
43
#[local_db_sqlx_test]
44
async fn padded_stored_key_and_normalized_destination_do_not_deadlock(
45
    pool: PgPool,
46
) -> anyhow::Result<()> {
47
    let fx = fixture().await?;
48
    let (first, second) = (fx.create_tx(None).await?, fx.create_tx(None).await?);
49
    let padded = link_raw_tag(&pool, first, "cat", " x").await?;
50
    sqlx::query_file!(
51
        "sql/insert/transaction_tags/transaction_tag.sql",
52
        second,
53
        padded
54
    )
55
    .execute(&pool)
56
    .await?;
57
    let mut conn = fx.user.get_connection().await?;
58
    let mut blocker = conn.begin().await?;
59
    sqlx::query_file!("sql/select/tags/lock_by_id.sql", padded)
60
        .fetch_one(&mut *blocker)
61
        .await?;
62

            
63
    let wanted = [("cat", "x"), ("zone", "z")];
64
1
    let release = async {
65
1
        let waited = wait_for_blocked(&fx, 2).await;
66
1
        blocker.commit().await?;
67
1
        waited
68
1
    };
69
    let (a, b, r) = tokio::join!(
70
        edit_tags(&fx, first, &wanted),
71
        edit_tags(&fx, second, &wanted),
72
        release
73
    );
74
    r?;
75
    a?;
76
    b?;
77
    for tx_id in [first, second] {
78
        assert_eq!(
79
            fx.tx_tags(tx_id).await?,
80
            vec![pair("cat", " x"), pair("zone", "z")]
81
        );
82
    }
83
}
84

            
85
/// A linked tag is renamed while the edit waits for its key: the attempt sees
86
/// `KeyChanged`, and the retry runs in a fresh DB transaction, since the
87
/// first attempt's key locks are gone while the retry waits.
88
#[local_db_sqlx_test]
89
async fn a_rename_before_the_lock_retries_in_a_fresh_transaction(
90
    pool: PgPool,
91
) -> anyhow::Result<()> {
92
    let fx = fixture().await?;
93
    let tx_id = fx.create_tx(None).await?;
94
    let linked = link_raw_tag(&pool, tx_id, "cat", "k0").await?;
95
    let mut first_conn = fx.user.get_connection().await?;
96
    let mut renamer = first_conn.begin().await?;
97
    hold_key(&mut renamer, "cat", "k0").await?;
98
    rename(&mut renamer, linked, "k1").await?;
99
    let mut second_conn = fx.user.get_connection().await?;
100
    let mut holder = second_conn.begin().await?;
101
    hold_key(&mut holder, "cat", "k1").await?;
102

            
103
    let edit = edit_tags(&fx, tx_id, &[("zone", "z")]);
104
1
    let steer = async {
105
1
        let renamed = release_after(wait_for_key_waiter(&fx, "cat", "k0"), renamer).await;
106
1
        let retry_waits = async {
107
1
            renamed?;
108
1
            wait_for_key_waiter(&fx, "cat", "k1").await?;
109
1
            anyhow::Ok(key_is_free(&fx, "cat", "k0").await? && key_is_free(&fx, "zone", "z").await?)
110
1
        };
111
1
        release_after(retry_waits, holder).await
112
1
    };
113
    let (edited, steered) = tokio::join!(edit, steer);
114
    assert!(steered?, "the retry still held the first attempt's locks");
115
    edited?;
116
    assert_eq!(fx.tx_tags(tx_id).await?, vec![pair("zone", "z")]);
117
}
118

            
119
/// Every attempt finds its linked tag renamed: after the last one the edit
120
/// fails and writes nothing.
121
#[local_db_sqlx_test]
122
async fn three_renames_fail_the_edit_without_writing(pool: PgPool) -> anyhow::Result<()> {
123
    let fx = fixture().await?;
124
    let tx_id = fx.create_tx(Some("kept")).await?;
125
    let linked = link_raw_tag(&pool, tx_id, "cat", "k0").await?;
126
    let before = fx.split_ids(tx_id).await?;
127
    let mut conns = Vec::new();
128
    for _ in 0..3 {
129
        conns.push(fx.user.get_connection().await?);
130
    }
131
    let mut holders = Vec::new();
132
    for ((conn, held), next) in conns
133
        .iter_mut()
134
        .zip(["k0", "k1", "k2"])
135
        .zip(["k1", "k2", "k3"])
136
    {
137
        let mut holder = conn.begin().await?;
138
        hold_key(&mut holder, "cat", held).await?;
139
        holders.push((holder, held, next));
140
    }
141

            
142
    let new_date = Utc.with_ymd_and_hms(2001, 2, 3, 4, 5, 6).single();
143
    let new_date = new_date.ok_or_else(|| anyhow::anyhow!("date"))?;
144
    let edit = UpdateTransaction::new()
145
        .user_id(fx.user.id)
146
        .transaction_id(tx_id)
147
        .tags(tag_map(&[("zone", "z")]))
148
        .post_date(new_date)
149
        .splits(fx.splits(tx_id, 7))
150
        .note("changed".to_string())
151
        .run();
152
    let steer = rename_in_turn(&fx, "cat", linked, holders);
153
    let (edited, steered) = tokio::join!(edit, steer);
154
    steered?;
155
    assert!(
156
        matches!(
157
            edited,
158
            Err(CmdError::Server(ServerError::DB(DBError::WriteConflict)))
159
        ),
160
        "{edited:?}"
161
    );
162

            
163
    assert_eq!(
164
        fx.tx_tags(tx_id).await?,
165
        vec![pair("cat", "k3"), pair("note", "kept")]
166
    );
167
    assert_eq!(fx.split_ids(tx_id).await?, before);
168
    assert_eq!(fx.tag_rows_with_value("z").await?, 0);
169
    let mut conn = fx.user.get_connection().await?;
170
    let row = sqlx::query_file!("sql/select/transactions/by_id.sql", tx_id)
171
        .fetch_one(&mut *conn)
172
        .await?;
173
    assert_ne!(row.post_date, new_date);
174
}