1
//! The single-tag writers on transactions, splits, commodities, artifacts and
2
//! accounts, and `delete_tag`, on the tag lock protocol under forced
3
//! interleavings.
4

            
5
use super::lock_protocol::link_raw_tag;
6
use super::*;
7
use finance::commodity::Commodity;
8
use sqlx::Connection;
9

            
10
/// The linked `cat` is renamed while `SetTransactionTag` waits for its key:
11
/// the retry locks the new key and links the tag.
12
#[local_db_sqlx_test]
13
async fn set_transaction_tag_retries_a_rename_before_the_lock(pool: PgPool) -> anyhow::Result<()> {
14
    let fx = fixture().await?;
15
    let tx_id = fx.create_tx(None).await?;
16
    let linked = link_raw_tag(&pool, tx_id, "cat", "k0").await?;
17
    let mut conn = fx.user.get_connection().await?;
18
    let mut renamer = conn.begin().await?;
19
    hold_key(&mut renamer, "cat", "k0").await?;
20
    rename(&mut renamer, linked, "k1").await?;
21

            
22
    let set = SetTransactionTag::new()
23
        .user_id(fx.user.id)
24
        .transaction_id(tx_id)
25
        .tag_name("zone".to_string())
26
        .tag_value("z".to_string())
27
        .run();
28
    let steer = release_after(wait_for_key_waiter(&fx, "cat", "k0"), renamer);
29
    let (set, steered) = tokio::join!(set, steer);
30
    steered?;
31
    set?;
32
    assert_eq!(
33
        fx.tx_tags(tx_id).await?,
34
        vec![pair("cat", "k1"), pair("zone", "z")]
35
    );
36
}
37

            
38
/// `SetSplitTag` and `create_split_tag` hold the owning transaction's row and
39
/// wait for the written key before touching any tag row.
40
#[local_db_sqlx_test]
41
async fn split_tag_writers_wait_for_the_key(pool: PgPool) -> anyhow::Result<()> {
42
    let fx = fixture().await?;
43
    let tx_id = fx.create_tx(None).await?;
44
    let [first, second] = fx.split_ids(tx_id).await?[..] else {
45
        anyhow::bail!("two splits");
46
    };
47
    let mut conn = fx.user.get_connection().await?;
48
    let mut holder = conn.begin().await?;
49
    hold_key(&mut holder, "memo", "m").await?;
50

            
51
    let set = SetSplitTag::new()
52
        .user_id(fx.user.id)
53
        .split_id(first)
54
        .tag_name("memo".to_string())
55
        .tag_value("m".to_string())
56
        .run();
57
    let attach = fx
58
        .user
59
        .create_split_tag(second, "memo".to_string(), "m".to_string(), None);
60
1
    let checked = async {
61
1
        wait_for_blocked(&fx, 2).await?;
62
1
        let none_written = fx.tag_rows_with_value("m").await? == 0;
63
1
        anyhow::Ok(none_written)
64
1
    };
65
    let release = release_after(checked, holder);
66
    let (set, attach, released) = tokio::join!(set, attach, release);
67
    assert!(released?, "a tag row was written before its key was locked");
68
    set?;
69
    attach?;
70
    for split in [first, second] {
71
        assert_eq!(fx.split_tag_values(split).await?, vec!["m"]);
72
    }
73
}
74

            
75
/// The tag is renamed while `delete_tag` waits for its key: the retry deletes
76
/// the renamed row and its link.
77
#[local_db_sqlx_test]
78
async fn delete_tag_retries_a_rename_before_the_lock(pool: PgPool) -> anyhow::Result<()> {
79
    let fx = fixture().await?;
80
    let tx_id = fx.create_tx(None).await?;
81
    let linked = link_raw_tag(&pool, tx_id, "cat", "k0").await?;
82
    let mut conn = fx.user.get_connection().await?;
83
    let mut renamer = conn.begin().await?;
84
    hold_key(&mut renamer, "cat", "k0").await?;
85
    rename(&mut renamer, linked, "k1").await?;
86

            
87
    let steer = release_after(wait_for_key_waiter(&fx, "cat", "k0"), renamer);
88
    let (deleted, steered) = tokio::join!(fx.user.delete_tag(linked), steer);
89
    steered?;
90
    deleted?;
91
    assert!(fx.tx_tags(tx_id).await?.is_empty());
92
    assert!(fx.user.stored_tag(linked).await.is_err());
93
}
94

            
95
/// Lock the tag rows of `(name, value)` for each value, creating them.
96
2
async fn hold_tag_rows(
97
2
    conn: &mut sqlx::PgConnection,
98
2
    pool: &PgPool,
99
2
    name: &str,
100
2
    values: &[&str],
101
2
) -> anyhow::Result<()> {
102
2
    for value in values {
103
4
        let id = fx_tag(pool, name, value).await?;
104
4
        sqlx::query_file!("sql/select/tags/lock_by_id.sql", id)
105
4
            .fetch_one(&mut *conn)
106
4
            .await?;
107
    }
108
2
    Ok(())
109
2
}
110

            
111
4
async fn fx_tag(pool: &PgPool, name: &str, value: &str) -> anyhow::Result<Uuid> {
112
4
    let id = Uuid::new_v4();
113
4
    sqlx::query("INSERT INTO tags (id, tag_name, tag_value) VALUES ($1, $2, $3)")
114
4
        .bind(id)
115
4
        .bind(name)
116
4
        .bind(value)
117
4
        .execute(pool)
118
4
        .await?;
119
4
    Ok(id)
120
4
}
121

            
122
/// Two first values of one name on a commodity both queue on their tag rows,
123
/// so neither saw the other's link when it started: the commodity row lock
124
/// and the reread under it keep one value.
125
#[local_db_sqlx_test]
126
async fn two_first_commodity_values_keep_one(pool: PgPool) -> anyhow::Result<()> {
127
    let fx = fixture().await?;
128
    let commodity = Commodity { id: fx.commodity };
129
    let mut conn = fx.user.get_connection().await?;
130
    let mut holder = conn.begin().await?;
131
    hold_tag_rows(&mut holder, &pool, "region", &["eu", "us"]).await?;
132

            
133
    let (eu, us) = (tag("region", "eu"), tag("region", "us"));
134
    let release = release_after(wait_for_blocked(&fx, 2), holder);
135
    let (a, b, r) = tokio::join!(
136
        fx.user.set_commodity_tag(&commodity, &eu),
137
        fx.user.set_commodity_tag(&commodity, &us),
138
        release
139
    );
140
    r?;
141
    a?;
142
    b?;
143
    let regions = fx
144
        .user
145
        .get_commodity_tags(&commodity)
146
        .await?
147
        .into_iter()
148
3
        .filter(|t| t.tag_name == "region")
149
        .count();
150
    assert_eq!(regions, 1);
151
}
152

            
153
3
async fn artifact_names(pool: &PgPool, artifact: Uuid) -> anyhow::Result<Vec<String>> {
154
3
    Ok(sqlx::query_scalar(
155
3
        "SELECT t.tag_value FROM artifact_tags AS art
156
3
         INNER JOIN tags AS t ON art.tag_id = t.id
157
3
         WHERE art.artifact_id = $1 AND t.tag_name = 'name'",
158
3
    )
159
3
    .bind(artifact)
160
3
    .fetch_all(pool)
161
3
    .await?)
162
3
}
163

            
164
/// Two first names of one script both queue on their tag rows: the artifact
165
/// row lock and the reread under it keep one name.
166
#[local_db_sqlx_test]
167
async fn two_first_script_names_keep_one(pool: PgPool) -> anyhow::Result<()> {
168
    let fx = fixture().await?;
169
    let script = fx.user.create_script(vec![0], None).await?;
170
    let mut conn = fx.user.get_connection().await?;
171
    let mut holder = conn.begin().await?;
172
    hold_tag_rows(&mut holder, &pool, "name", &["one", "two"]).await?;
173

            
174
    let release = release_after(wait_for_blocked(&fx, 2), holder);
175
    let (a, b, r) = tokio::join!(
176
        fx.user.update_script_name(script, Some("one".to_string())),
177
        fx.user.update_script_name(script, Some("two".to_string())),
178
        release
179
    );
180
    r?;
181
    a?;
182
    b?;
183
    assert_eq!(artifact_names(&pool, script).await?.len(), 1);
184
}
185

            
186
/// Creating and deleting a script take its tag keys before the artifact row
187
/// and the links: both queue on the held `kind` key and change nothing.
188
#[local_db_sqlx_test]
189
async fn script_create_and_delete_wait_for_the_tag_keys(pool: PgPool) -> anyhow::Result<()> {
190
    let fx = fixture().await?;
191
    let doomed = fx
192
        .user
193
        .create_script(vec![0], Some("doomed".to_string()))
194
        .await?;
195
    let mut conn = fx.user.get_connection().await?;
196
    let mut holder = conn.begin().await?;
197
    hold_key(&mut holder, "kind", "automation").await?;
198

            
199
    let created = fx.user.create_script(vec![0], Some("fresh".to_string()));
200
    let deleted = fx.user.delete_script(doomed);
201
1
    let checked = async {
202
1
        wait_for_blocked(&fx, 2).await?;
203
1
        let untouched = fx.user.list_scripts().await?.len() == 1
204
1
            && artifact_names(&pool, doomed).await? == vec!["doomed"];
205
1
        anyhow::Ok(untouched)
206
1
    };
207
    let release = release_after(checked, holder);
208
    let (created, deleted, released) = tokio::join!(created, deleted, release);
209
    assert!(released?, "a script changed before its keys were locked");
210
    deleted?;
211
    let created = created?;
212
    assert_eq!(artifact_names(&pool, created).await?, vec!["fresh"]);
213
    assert_eq!(fx.user.list_scripts().await?.len(), 1);
214
}
215

            
216
/// A new account takes its name key before its row, whose insert key-shares
217
/// the parent: while the key is held, the parent stays free to lock.
218
#[local_db_sqlx_test]
219
async fn a_new_account_takes_its_name_key_before_its_row(pool: PgPool) -> anyhow::Result<()> {
220
    let fx = fixture().await?;
221
    let parent = fx.accounts[0];
222
    let mut conn = fx.user.get_connection().await?;
223
    let mut holder = conn.begin().await?;
224
    hold_key(&mut holder, "name", "Child").await?;
225

            
226
    let created = fx.user.create_account("Child", Some(parent));
227
1
    let checked = async {
228
1
        wait_for_key_waiter(&fx, "name", "Child").await?;
229
1
        let mut probe_conn = fx.user.get_connection().await?;
230
1
        let mut probe = probe_conn.begin().await?;
231
1
        let parent_free = sqlx::query("SELECT id FROM accounts WHERE id = $1 FOR UPDATE NOWAIT")
232
1
            .bind(parent)
233
1
            .fetch_one(&mut *probe)
234
1
            .await
235
            .is_ok();
236
1
        probe.rollback().await?;
237
1
        anyhow::Ok(parent_free)
238
1
    };
239
    let release = release_after(checked, holder);
240
    let (created, released) = tokio::join!(created, release);
241
    assert!(
242
        released?,
243
        "the account row was inserted before its name key"
244
    );
245
    assert_eq!(created?.parent, Some(parent));
246
}