1
//! Single-tag writes on a transaction or a split on the tag lock protocol:
2
//! the owning transaction's row lock, then the keys of every tag it links and
3
//! of the written tag, then the write, retried in a fresh DB transaction like
4
//! an edit.
5

            
6
use finance::tag::Tag;
7
use sqlx::{PgConnection, types::Uuid};
8
use std::convert::identity;
9

            
10
use super::db_err;
11
use crate::attempt::{Attempt, Tries};
12
use crate::command::transaction_edit::lock_tag_keys;
13
use crate::error::ServerError;
14
use crate::tag::lock::{KeyChanged, begin};
15

            
16
#[derive(Clone, Copy)]
17
pub(super) enum TagOwner {
18
    Transaction(Uuid),
19
    Split(Uuid),
20
}
21

            
22
78211
async fn lock_transaction(conn: &mut PgConnection, tx_id: Uuid) -> Result<(), sqlx::Error> {
23
78211
    sqlx::query_file!("sql/select/transactions/by_id_locked.sql", tx_id)
24
78211
        .fetch_one(conn)
25
78211
        .await?;
26
78146
    Ok(())
27
78211
}
28

            
29
15905
fn ensure_same_owner(locked: Uuid, current: Uuid) -> Result<(), sqlx::Error> {
30
15905
    if locked == current {
31
15904
        Ok(())
32
    } else {
33
1
        Err(sqlx::Error::RowNotFound)
34
    }
35
15905
}
36

            
37
32019
async fn split_owner(conn: &mut PgConnection, split_id: Uuid) -> Result<Uuid, sqlx::Error> {
38
32019
    let row = sqlx::query_file!("sql/select/splits/tx_id_by_id.sql", &split_id)
39
32019
        .fetch_one(conn)
40
32019
        .await?;
41
31820
    Ok(row.tx_id)
42
32019
}
43

            
44
/// Take the owning transaction's row lock first (a split's owner is its
45
/// transaction), the same order as Create/Update/DeleteTransaction, and
46
/// return its id. A missing owner is `RowNotFound`, so no tag SQL ever runs
47
/// unlocked.
48
78396
async fn lock_owner(conn: &mut PgConnection, owner: TagOwner) -> Result<Uuid, sqlx::Error> {
49
78396
    match owner {
50
        TagOwner::Transaction(tx_id) => {
51
62294
            lock_transaction(conn, tx_id).await?;
52
62229
            Ok(tx_id)
53
        }
54
        TagOwner::Split(split_id) => {
55
16102
            let tx_id = split_owner(conn, split_id).await?;
56
15917
            lock_transaction(conn, tx_id).await?;
57
            // An edit may have replaced the split while we waited for the lock.
58
15917
            ensure_same_owner(tx_id, split_owner(conn, split_id).await?)?;
59
15903
            Ok(tx_id)
60
        }
61
    }
62
78396
}
63

            
64
/// Upsert `tag` and link it to the owner; returns the canonical tag id.
65
74247
pub(super) async fn attach(
66
74247
    conn: &mut PgConnection,
67
74247
    owner: TagOwner,
68
74247
    tag: &Tag,
69
74247
) -> Result<Uuid, ServerError> {
70
74247
    let tag_id = tag.commit(&mut *conn).await.map_err(|err| {
71
        tracing::error!("{}", t!("Database error: %{err}", err = err : {:?}));
72
        ServerError::Finance(err)
73
    })?;
74
74247
    match owner {
75
        TagOwner::Transaction(tx_id) => {
76
61250
            sqlx::query_file!(
77
                "sql/insert/transaction_tags/transaction_tag.sql",
78
                &tx_id,
79
                &tag_id
80
            )
81
61250
            .execute(conn)
82
61250
            .await
83
61250
            .map_err(db_err)?;
84
        }
85
        TagOwner::Split(split_id) => {
86
12997
            sqlx::query_file!("sql/insert/split_tags/split_tag.sql", &split_id, &tag_id)
87
12997
                .execute(conn)
88
12997
                .await
89
12997
                .map_err(db_err)?;
90
        }
91
    }
92
74247
    Ok(tag_id)
93
74247
}
94

            
95
/// Link `tag` to the owner in place of another value of its name.
96
3879
pub(super) async fn set(
97
3879
    conn: &mut PgConnection,
98
3879
    owner: TagOwner,
99
3879
    tag: &Tag,
100
3879
) -> Result<(), ServerError> {
101
2028
    match owner {
102
79
        TagOwner::Transaction(tx_id) => super::links::set_transaction_tag(conn, tx_id, tag).await,
103
1949
        TagOwner::Split(split_id) => super::links::set_split_tag(conn, split_id, tag).await,
104
    }
105
2028
}
106

            
107
/// Run `write` of `tag` on the owner under the owner and key locks, at most
108
/// [`ATTEMPTS`](crate::tag::lock::ATTEMPTS) times.
109
///
110
/// # Errors
111
/// A missing owner, a failing write, or [`DBError::WriteConflict`] when
112
/// every attempt met a concurrent write.
113
76363
pub(super) async fn write<T>(
114
76363
    conn: &mut PgConnection,
115
76363
    owner: TagOwner,
116
76363
    tag: &Tag,
117
76363
    write: impl AsyncFn(&mut PgConnection, TagOwner, &Tag) -> Result<T, ServerError>,
118
76363
) -> Result<T, ServerError> {
119
76363
    let mut tries = Tries::default();
120
    loop {
121
76366
        let outcome = Attempt::of(
122
76366
            attempt(conn, owner, tag, &write).await,
123
76366
            ServerError::is_retryable,
124
76366
            identity,
125
        );
126
76366
        if let Some(written) = tries.step(outcome)? {
127
76270
            return Ok(written);
128
3
        }
129
    }
130
76363
}
131

            
132
76366
async fn attempt<T>(
133
76366
    conn: &mut PgConnection,
134
76366
    owner: TagOwner,
135
76366
    tag: &Tag,
136
76366
    write: &impl AsyncFn(&mut PgConnection, TagOwner, &Tag) -> Result<T, ServerError>,
137
76366
) -> Result<Result<T, KeyChanged>, ServerError> {
138
76366
    let mut tx = begin(conn).await.map_err(db_err)?;
139
76366
    let tx_id = lock_owner(&mut tx, owner).await.map_err(db_err)?;
140
76281
    if let Err(changed) = lock_tag_keys(&mut tx, tx_id, &[tag])
141
76281
        .await
142
76281
        .map_err(db_err)?
143
    {
144
4
        tx.rollback().await.map_err(db_err)?;
145
4
        return Ok(Err(changed));
146
76275
    }
147
76275
    let written = write(&mut tx, owner, tag).await?;
148
76270
    tx.commit().await.map_err(db_err)?;
149
76270
    Ok(Ok(written))
150
76366
}
151

            
152
#[cfg(test)]
153
#[path = "owner_tests.rs"]
154
mod tests;