1
//! The store-level tag writers give up with `WriteConflict` when every
2
//! attempt finds their tag renamed.
3

            
4
use super::lock_protocol::link_raw_tag;
5
use super::*;
6
use crate::command::CmdError;
7
use crate::command::account::SetAccountTag;
8
use crate::command::account_merge::MergeAccounts;
9
use crate::db::DBError;
10
use crate::error::ServerError;
11
use finance::commodity::Commodity;
12
use sqlx::Connection;
13

            
14
/// Every attempt of `write` finds the tag row `linked` (`type=k0`) renamed by
15
/// a holder of its key; returns what `write` ended with.
16
7
async fn three_renames<T>(
17
7
    fx: &Fixture,
18
7
    name: &str,
19
7
    linked: Uuid,
20
7
    write: impl std::future::Future<Output = T>,
21
7
) -> anyhow::Result<T> {
22
7
    let mut conns = Vec::new();
23
7
    for _ in 0..3 {
24
21
        conns.push(fx.user.get_connection().await?);
25
    }
26
7
    let mut holders = Vec::new();
27
7
    for ((conn, held), next) in conns
28
7
        .iter_mut()
29
7
        .zip(["k0", "k1", "k2"])
30
7
        .zip(["k1", "k2", "k3"])
31
    {
32
21
        let mut holder = conn.begin().await?;
33
21
        hold_key(&mut holder, name, held).await?;
34
21
        holders.push((holder, held, next));
35
    }
36
7
    let steer = rename_in_turn(fx, name, linked, holders);
37
7
    let (written, steered) = tokio::join!(write, steer);
38
7
    steered?;
39
7
    Ok(written)
40
7
}
41

            
42
6
fn is_conflict<T>(outcome: &Result<T, ServerError>) -> bool {
43
6
    matches!(outcome, Err(ServerError::DB(DBError::WriteConflict)))
44
6
}
45

            
46
#[local_db_sqlx_test]
47
async fn three_renames_fail_set_commodity_tag(pool: PgPool) -> anyhow::Result<()> {
48
    let fx = fixture().await?;
49
    let commodity = Commodity { id: fx.commodity };
50
    fx.user
51
        .set_commodity_tag(&commodity, &tag("type", "k0"))
52
        .await?;
53
    let linked: Uuid =
54
        sqlx::query_scalar("SELECT id FROM tags WHERE tag_name = 'type' AND tag_value = 'k0'")
55
            .fetch_one(&pool)
56
            .await?;
57
    let new = tag("type", "new");
58
    let written = three_renames(
59
        &fx,
60
        "type",
61
        linked,
62
        fx.user.set_commodity_tag(&commodity, &new),
63
    )
64
    .await?;
65
    assert!(is_conflict(&written), "{written:?}");
66
    let types: Vec<_> = fx
67
        .user
68
        .get_commodity_tags(&commodity)
69
        .await?
70
        .into_iter()
71
3
        .filter(|t| t.tag_name == "type")
72
1
        .map(|t| t.tag_value)
73
        .collect();
74
    assert_eq!(types, vec!["k3"]);
75
}
76

            
77
#[local_db_sqlx_test]
78
async fn three_renames_fail_update_tag(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, "type", "k0").await?;
82
    let update = fx
83
        .user
84
        .rename_tag(linked, "type".to_string(), "new".to_string(), None);
85
    let written = three_renames(&fx, "type", linked, update).await?;
86
    assert!(is_conflict(&written), "{written:?}");
87
    assert_eq!(fx.tx_tags(tx_id).await?, vec![pair("type", "k3")]);
88
}
89

            
90
#[local_db_sqlx_test]
91
async fn three_renames_fail_delete_tag(pool: PgPool) -> 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, "type", "k0").await?;
95
    let written = three_renames(&fx, "type", linked, fx.user.delete_tag(linked)).await?;
96
    assert!(is_conflict(&written), "{written:?}");
97
    assert_eq!(fx.tx_tags(tx_id).await?, vec![pair("type", "k3")]);
98
}
99

            
100
3
async fn tag_row(pool: &PgPool, name: &str, value: &str) -> anyhow::Result<Uuid> {
101
3
    let id = sqlx::query_scalar("SELECT id FROM tags WHERE tag_name = $1 AND tag_value = $2")
102
3
        .bind(name)
103
3
        .bind(value)
104
3
        .fetch_one(pool)
105
3
        .await?;
106
3
    Ok(id)
107
3
}
108

            
109
#[local_db_sqlx_test]
110
async fn three_renames_fail_set_transaction_tag(pool: PgPool) -> anyhow::Result<()> {
111
    let fx = fixture().await?;
112
    let tx_id = fx.create_tx(None).await?;
113
    let linked = link_raw_tag(&pool, tx_id, "type", "k0").await?;
114
    let new = tag("type", "new");
115
    let written = three_renames(
116
        &fx,
117
        "type",
118
        linked,
119
        fx.user.set_transaction_tag(tx_id, &new),
120
    )
121
    .await?;
122
    assert!(is_conflict(&written), "{written:?}");
123
    assert_eq!(fx.tx_tags(tx_id).await?, vec![pair("type", "k3")]);
124
}
125

            
126
#[local_db_sqlx_test]
127
async fn three_renames_fail_delete_script(pool: PgPool) -> anyhow::Result<()> {
128
    let fx = fixture().await?;
129
    let id = fx
130
        .user
131
        .create_script(vec![0, 0x61, 0x73, 0x6d], Some("k0".to_string()))
132
        .await?;
133
    let linked = tag_row(&pool, "name", "k0").await?;
134
    let deleted = three_renames(&fx, "name", linked, fx.user.delete_script(id)).await?;
135
    assert!(is_conflict(&deleted), "{deleted:?}");
136
    assert_eq!(fx.user.get_script(id).await?.name.as_deref(), Some("k3"));
137
}
138

            
139
#[local_db_sqlx_test]
140
async fn three_renames_fail_update_script_name(pool: PgPool) -> anyhow::Result<()> {
141
    let fx = fixture().await?;
142
    let id = fx
143
        .user
144
        .create_script(vec![0, 0x61, 0x73, 0x6d], Some("k0".to_string()))
145
        .await?;
146
    let linked = tag_row(&pool, "name", "k0").await?;
147
    let renamed = fx.user.update_script_name(id, Some("new".to_string()));
148
    let renamed = three_renames(&fx, "name", linked, renamed).await?;
149
    assert!(is_conflict(&renamed), "{renamed:?}");
150
    assert_eq!(fx.user.get_script(id).await?.name.as_deref(), Some("k3"));
151
}
152

            
153
#[local_db_sqlx_test]
154
async fn three_renames_fail_the_account_merge(pool: PgPool) -> anyhow::Result<()> {
155
    let fx = fixture().await?;
156
    let [into, from] = fx.accounts;
157
    SetAccountTag::new()
158
        .user_id(fx.user.id)
159
        .account_id(from)
160
        .tag_name("type".to_string())
161
        .tag_value("k0".to_string())
162
        .run()
163
        .await?;
164
    let linked = tag_row(&pool, "type", "k0").await?;
165
    let merge = MergeAccounts::new()
166
        .user_id(fx.user.id)
167
        .into(into)
168
        .from(from)
169
        .run();
170
    let merged = three_renames(&fx, "type", linked, merge).await?;
171
    assert!(
172
        matches!(
173
            merged,
174
            Err(CmdError::Server(ServerError::DB(DBError::WriteConflict)))
175
        ),
176
        "{merged:?}"
177
    );
178
}