1
//! `CreateTransaction` against an edit on the tag lock protocol, under forced
2
//! interleavings.
3

            
4
use super::*;
5
use sqlx::Connection;
6

            
7
/// Store the tag row `(name, value)` under `id`.
8
3
async fn put_tag(pool: &PgPool, id: Uuid, name: &str, value: &str) -> anyhow::Result<()> {
9
3
    sqlx::query("INSERT INTO tags (id, tag_name, tag_value) VALUES ($1, $2, $3)")
10
3
        .bind(id)
11
3
        .bind(name)
12
3
        .bind(value)
13
3
        .execute(pool)
14
3
        .await?;
15
3
    Ok(())
16
3
}
17

            
18
2
fn create_with_tags(
19
2
    fx: &Fixture,
20
2
    tags: &[(&str, &str)],
21
2
) -> (
22
2
    Uuid,
23
2
    impl std::future::Future<Output = Result<Option<CmdResult>, crate::command::CmdError>>,
24
2
) {
25
2
    let tx_id = Uuid::new_v4();
26
2
    let now = Utc::now();
27
2
    let run = CreateTransaction::new()
28
2
        .user_id(fx.user.id)
29
2
        .splits(fx.splits_on(tx_id, 10, [fx.accounts[0], fx.accounts[0]]))
30
2
        .id(tx_id)
31
2
        .post_date(now)
32
2
        .enter_date(now)
33
2
        .tags(tag_map(tags))
34
2
        .run();
35
2
    (tx_id, run)
36
2
}
37

            
38
/// Hold the second account row against the key-share lock a split insert
39
/// takes, so an edit replacing its splits stalls after locking its tags.
40
1
async fn lock_split_account(conn: &mut sqlx::PgConnection, account: Uuid) -> anyhow::Result<()> {
41
1
    sqlx::query("SELECT id FROM accounts WHERE id = $1 FOR UPDATE")
42
1
        .bind(account)
43
1
        .fetch_one(conn)
44
1
        .await?;
45
1
    Ok(())
46
1
}
47

            
48
/// The edit holds the keys of an absent `a` and an existing `b` and stalls;
49
/// the create starts meanwhile. Without advisory locks the create would insert
50
/// `a`, wait for the edit's lock on `b`, and the edit would wait for `a`.
51
#[local_db_sqlx_test]
52
async fn create_and_edit_with_an_absent_earlier_key_do_not_deadlock(
53
    pool: PgPool,
54
) -> anyhow::Result<()> {
55
    let fx = fixture().await?;
56
    let edited = fx.create_tx(None).await?;
57
    put_tag(&pool, Uuid::new_v4(), "b", "2").await?;
58
    let tags = [("a", "1"), ("b", "2")];
59
    let mut conn = fx.user.get_connection().await?;
60
    let mut blocker = conn.begin().await?;
61
    lock_split_account(&mut blocker, fx.accounts[1]).await?;
62

            
63
    let edit = UpdateTransaction::new()
64
        .user_id(fx.user.id)
65
        .transaction_id(edited)
66
        .splits(fx.splits(edited, 50))
67
        .tags(tag_map(&tags))
68
        .refuse_unkeepable(true)
69
        .run();
70
    let (created, create) = create_with_tags(&fx, &tags);
71
1
    let create = async {
72
1
        wait_for_blocked(&fx, 1).await?;
73
1
        create.await?;
74
1
        anyhow::Ok(())
75
1
    };
76
1
    let release = async {
77
1
        let waited = wait_for_blocked(&fx, 2).await;
78
1
        blocker.commit().await?;
79
1
        waited
80
1
    };
81
    let (e, c, r) = tokio::join!(edit, create, release);
82
    r?;
83
    e?;
84
    c?;
85
    let both = vec![pair("a", "1"), pair("b", "2")];
86
    assert_eq!(fx.tx_tags(edited).await?, both);
87
    assert_eq!(fx.tx_tags(created).await?, both);
88
}
89

            
90
/// Two existing tags whose id order is the opposite of their key order: the
91
/// create stalls on the later key's row, the edit queues behind it.
92
#[local_db_sqlx_test]
93
async fn create_and_edit_over_tags_in_reverse_id_order_do_not_deadlock(
94
    pool: PgPool,
95
) -> anyhow::Result<()> {
96
    let fx = fixture().await?;
97
    let edited = fx.create_tx(None).await?;
98
    let (early, late) = (Uuid::from_u128(u128::MAX), Uuid::from_u128(1));
99
    put_tag(&pool, early, "a", "1").await?;
100
    put_tag(&pool, late, "b", "2").await?;
101
    let tags = [("a", "1"), ("b", "2")];
102
    let mut conn = fx.user.get_connection().await?;
103
    let mut blocker = conn.begin().await?;
104
    sqlx::query_file!("sql/select/tags/lock_by_id.sql", late)
105
        .fetch_one(&mut *blocker)
106
        .await?;
107

            
108
    let (created, create) = create_with_tags(&fx, &tags);
109
1
    let edit = async {
110
1
        wait_for_blocked(&fx, 1).await?;
111
1
        UpdateTransaction::new()
112
1
            .user_id(fx.user.id)
113
1
            .transaction_id(edited)
114
1
            .tags(tag_map(&tags))
115
1
            .refuse_unkeepable(true)
116
1
            .run()
117
1
            .await?;
118
1
        anyhow::Ok(())
119
1
    };
120
1
    let release = async {
121
1
        let waited = wait_for_blocked(&fx, 2).await;
122
1
        blocker.commit().await?;
123
1
        waited
124
1
    };
125
    let (c, e, r) = tokio::join!(create, edit, release);
126
    r?;
127
    c?;
128
    e?;
129
    let both = vec![pair("a", "1"), pair("b", "2")];
130
    assert_eq!(fx.tx_tags(edited).await?, both);
131
    assert_eq!(fx.tx_tags(created).await?, both);
132
}
133

            
134
pub(super) const GROCERIES_SCRIPT_WASM: &[u8] =
135
    include_bytes!("../../../../web/static/wasm/groceries_markup.wasm");
136

            
137
2
async fn lock_account_row(conn: &mut sqlx::PgConnection, account: Uuid) -> anyhow::Result<()> {
138
2
    sqlx::query("SELECT id FROM accounts WHERE id = $1 FOR UPDATE")
139
2
        .bind(account)
140
2
        .fetch_one(conn)
141
2
        .await?;
142
2
    Ok(())
143
2
}
144

            
145
/// The create holds its tag keys and stalls on its first split's account; a
146
/// holder of the second split's account then waits for a key. Released, the
147
/// create meets the holder and is aborted with a deadlock, retries in a fresh
148
/// transaction and stores its scripted state once. The script is deleted
149
/// while the first attempt stalls, so a retry that reran scripts would lose
150
/// the script's tags.
151
#[local_db_sqlx_test]
152
async fn create_retries_a_deadlock_without_rerunning_scripts(pool: PgPool) -> anyhow::Result<()> {
153
    let fx = fixture().await?;
154
    let script = fx
155
        .user
156
        .create_script(GROCERIES_SCRIPT_WASM.to_vec(), None)
157
        .await?;
158
    let mut stall_conn = fx.user.get_connection().await?;
159
    let mut stall = stall_conn.begin().await?;
160
    lock_account_row(&mut stall, fx.accounts[0]).await?;
161
    let mut cycle_conn = fx.user.get_connection().await?;
162
    let mut cycle = cycle_conn.begin().await?;
163
    lock_account_row(&mut cycle, fx.accounts[1]).await?;
164

            
165
    let tx_id = Uuid::new_v4();
166
    let now = Utc::now();
167
    let splits = fx.splits(tx_id, 10);
168
    let split_ids: Vec<Uuid> = splits
169
        .iter()
170
2
        .filter_map(|entity| match entity {
171
2
            FinanceEntity::Split(split) => Some(split.id),
172
            _ => None,
173
2
        })
174
        .collect();
175
    let create = CreateTransaction::new()
176
        .user_id(fx.user.id)
177
        .splits(splits)
178
        .id(tx_id)
179
        .post_date(now)
180
        .enter_date(now)
181
        .note("groceries".to_string())
182
        .run();
183
1
    let steer = steer_deadlock(&fx, stall, cycle, ("note", "groceries"), async {
184
1
        fx.user.delete_script(script).await?;
185
1
        Ok(())
186
1
    });
187
    let (created, steered) = tokio::join!(create, steer);
188
    steered?;
189
    created?;
190

            
191
    assert_eq!(fx.transaction_count(tx_id).await?, 1);
192
    for split_id in split_ids {
193
        assert_eq!(fx.split_tag_values(split_id).await?, vec!["groceries"]);
194
    }
195
}