1
//! Artifact tag writes on the tag lock protocol: the tag keys, then the
2
//! artifact row, then the links. Each attempt runs in its own DB transaction.
3

            
4
use finance::tag::Tag;
5
use sqlx::{PgConnection, types::Uuid};
6

            
7
use super::lock::{
8
    Key, KeyChanged, begin, destination_keys, in_key_order, lock, lock_keys, retry, sorted_keys,
9
};
10
use crate::artifact_mgmt::user::KIND_AUTOMATION;
11
use crate::error::ServerError;
12
use crate::script_state::{is_enabled, script_revision};
13
use crate::template_state::template_revision;
14

            
15
543
fn db_err(err: sqlx::Error) -> ServerError {
16
543
    tracing::error!("{}", t!("Database error: %{err}", err = err : {:?}));
17
543
    ServerError::DB(crate::db::DBError::Sqlx(err))
18
543
}
19

            
20
/// Upsert each tag and link it to the artifact, whose row and tag keys the
21
/// caller holds.
22
29783
pub(crate) async fn link(
23
29783
    conn: &mut PgConnection,
24
29783
    artifact: Uuid,
25
29783
    tags: &[&Tag],
26
29783
) -> Result<(), ServerError> {
27
15830
    for tag in tags {
28
26928
        let tag_id = tag.commit(&mut *conn).await.map_err(|err| {
29
1
            tracing::error!("{}", t!("Database error: %{err}", err = err : {:?}));
30
1
            ServerError::Finance(err)
31
1
        })?;
32
26927
        sqlx::query_file!(
33
            "sql/insert/artifact_tags/artifact_tag.sql",
34
            &artifact,
35
            &tag_id
36
        )
37
26927
        .execute(&mut *conn)
38
26927
        .await
39
26927
        .map_err(db_err)?;
40
    }
41
15829
    Ok(())
42
15830
}
43

            
44
/// Lock the keys of the tags a new artifact is created with.
45
24545
pub(crate) async fn lock_new(conn: &mut PgConnection, tags: &[&Tag]) -> Result<(), ServerError> {
46
13080
    lock_keys(conn, &destination_keys(tags.iter().copied()))
47
13080
        .await
48
13080
        .map_err(db_err)?;
49
13080
    Ok(())
50
13080
}
51

            
52
/// Replace the artifact's tags named `name` with `tag`, or drop them when
53
/// `tag` is `None`.
54
554
pub(crate) async fn replace(
55
554
    conn: &mut PgConnection,
56
554
    artifact: Uuid,
57
554
    name: &str,
58
554
    tag: Option<&Tag>,
59
554
) -> Result<Result<(), KeyChanged>, ServerError> {
60
17
    let mut tx = begin(conn).await.map_err(db_err)?;
61
17
    let touched = linked_of_name(&mut tx, artifact, name).await?;
62
17
    if lock(&mut tx, &touched, tag.as_slice())
63
17
        .await
64
17
        .map_err(db_err)?
65
        .is_err()
66
    {
67
3
        return retry(tx).await.map_err(db_err);
68
14
    }
69
14
    sqlx::query_file!("sql/select/artifacts/by_id_locked.sql", artifact)
70
14
        .fetch_one(&mut *tx)
71
14
        .await
72
14
        .map_err(db_err)?;
73
14
    if linked_of_name(&mut tx, artifact, name).await? != touched {
74
1
        return retry(tx).await.map_err(db_err);
75
13
    }
76
13
    sqlx::query_file!(
77
        "sql/delete/artifact_tags/by_artifact_and_name.sql",
78
        artifact,
79
        name
80
    )
81
13
    .execute(&mut *tx)
82
13
    .await
83
13
    .map_err(db_err)?;
84
13
    link(&mut tx, artifact, tag.as_slice()).await?;
85
13
    tx.commit().await.map_err(db_err)?;
86
13
    Ok(Ok(()))
87
17
}
88

            
89
/// Delete the artifact and its tag links under the keys of its tags.
90
1816
pub(crate) async fn delete(
91
1816
    conn: &mut PgConnection,
92
1816
    artifact: Uuid,
93
1816
) -> Result<Result<bool, KeyChanged>, ServerError> {
94
980
    let mut tx = begin(conn).await.map_err(db_err)?;
95
980
    let touched = linked(&mut tx, artifact).await?;
96
980
    if lock(&mut tx, &touched, &[]).await.map_err(db_err)?.is_err() {
97
3
        return Ok(retry(tx).await.map_err(db_err)?.map(|()| false));
98
977
    }
99
977
    let existed = sqlx::query_file!("sql/select/artifacts/by_id_locked.sql", artifact)
100
977
        .fetch_optional(&mut *tx)
101
977
        .await
102
977
        .map_err(db_err)?
103
        .is_some();
104
977
    if linked(&mut tx, artifact).await? != touched {
105
        return Ok(retry(tx).await.map_err(db_err)?.map(|()| false));
106
977
    }
107
977
    sqlx::query_file!("sql/delete/artifact_tags/by_artifact.sql", &artifact)
108
977
        .execute(&mut *tx)
109
977
        .await
110
977
        .map_err(db_err)?;
111
977
    sqlx::query_file!("sql/delete/artifacts/by_id.sql", &artifact)
112
977
        .execute(&mut *tx)
113
977
        .await
114
977
        .map_err(db_err)?;
115
977
    tx.commit().await.map_err(db_err)?;
116
977
    Ok(Ok(existed))
117
980
}
118

            
119
/// Replace the template's `name` tag and source text under the name keys;
120
/// refused as stale when the locked template no longer matches `revision`.
121
2527
pub(crate) async fn update_template(
122
2527
    conn: &mut PgConnection,
123
2527
    id: Uuid,
124
2527
    revision: &str,
125
2527
    name: Option<&Tag>,
126
2527
    source: &str,
127
2527
) -> Result<Result<(), KeyChanged>, ServerError> {
128
975
    let mut tx = begin(conn).await.map_err(db_err)?;
129
975
    let touched = linked_of_name(&mut tx, id, "name").await?;
130
975
    if lock(&mut tx, &touched, name.as_slice())
131
975
        .await
132
975
        .map_err(db_err)?
133
        .is_err()
134
    {
135
        return retry(tx).await.map_err(db_err);
136
975
    }
137
975
    sqlx::query_file!("sql/select/artifacts/by_id_locked.sql", id)
138
975
        .fetch_one(&mut *tx)
139
975
        .await
140
975
        .map_err(db_err)?;
141
973
    if linked_of_name(&mut tx, id, "name").await? != touched {
142
        return retry(tx).await.map_err(db_err);
143
973
    }
144
973
    refuse_stale(&mut tx, id, revision).await?;
145
810
    sqlx::query_file!("sql/update/artifacts/source_text.sql", &id, source)
146
810
        .execute(&mut *tx)
147
810
        .await
148
810
        .map_err(db_err)?;
149
810
    sqlx::query_file!(
150
        "sql/delete/artifact_tags/by_artifact_and_name.sql",
151
        id,
152
        "name"
153
    )
154
810
    .execute(&mut *tx)
155
810
    .await
156
810
    .map_err(db_err)?;
157
810
    link(&mut tx, id, name.as_slice()).await?;
158
810
    tx.commit().await.map_err(db_err)?;
159
810
    Ok(Ok(()))
160
975
}
161

            
162
/// Replace the script's `name` and `enabled` tags, source and bytecode under
163
/// those keys; refused as stale when the locked script no longer matches `revision`.
164
3787
pub(crate) async fn update_script(
165
3787
    conn: &mut PgConnection,
166
3787
    id: Uuid,
167
3787
    revision: &str,
168
3787
    tags: (Option<&Tag>, Option<&Tag>),
169
3787
    code: (&str, &[u8]),
170
3787
) -> Result<Result<(), KeyChanged>, ServerError> {
171
2254
    let (name, enabled) = tags;
172
2254
    let destinations: Vec<&Tag> = name.into_iter().chain(enabled).collect();
173
2254
    let mut tx = begin(conn).await.map_err(db_err)?;
174
2254
    let touched = linked_of_names(&mut tx, id).await?;
175
2254
    if lock(&mut tx, &touched, &destinations)
176
2254
        .await
177
2254
        .map_err(db_err)?
178
        .is_err()
179
    {
180
        return retry(tx).await.map_err(db_err);
181
2254
    }
182
2254
    sqlx::query_file!("sql/select/artifacts/by_id_locked.sql", id)
183
2254
        .fetch_one(&mut *tx)
184
2254
        .await
185
2254
        .map_err(db_err)?;
186
2252
    if linked_of_names(&mut tx, id).await? != touched {
187
        return retry(tx).await.map_err(db_err);
188
2252
    }
189
2252
    refuse_stale_script(&mut tx, id, revision).await?;
190
1927
    let (source, bytecode) = code;
191
1927
    sqlx::query_file!(
192
        "sql/update/artifacts/script.sql",
193
        &id,
194
        source,
195
        bytecode,
196
        KIND_AUTOMATION
197
    )
198
1927
    .execute(&mut *tx)
199
1927
    .await
200
1927
    .map_err(db_err)?;
201
1927
    for tag_name in ["name", "enabled"] {
202
3854
        sqlx::query_file!(
203
            "sql/delete/artifact_tags/by_artifact_and_name.sql",
204
            id,
205
            tag_name
206
        )
207
3854
        .execute(&mut *tx)
208
3854
        .await
209
3854
        .map_err(db_err)?;
210
    }
211
1927
    link(&mut tx, id, &destinations).await?;
212
1927
    tx.commit().await.map_err(db_err)?;
213
1927
    Ok(Ok(()))
214
2254
}
215

            
216
3606
async fn refuse_stale_script(
217
3606
    conn: &mut PgConnection,
218
3606
    id: Uuid,
219
3606
    revision: &str,
220
3606
) -> Result<(), ServerError> {
221
2252
    let row = sqlx::query_file!("sql/select/artifacts/by_id.sql", id, KIND_AUTOMATION)
222
2252
        .fetch_one(conn)
223
2252
        .await
224
2252
        .map_err(db_err)?;
225
2250
    let current = script_revision(
226
2250
        row.artifact_name.as_deref(),
227
2250
        row.source_text.as_deref(),
228
2250
        is_enabled(row.enabled.as_deref()),
229
2250
    );
230
2250
    match current == revision {
231
1927
        true => Ok(()),
232
323
        false => Err(ServerError::StaleScript),
233
    }
234
2252
}
235

            
236
7393
async fn linked_of_names(
237
7393
    conn: &mut PgConnection,
238
7393
    artifact: Uuid,
239
7393
) -> Result<Vec<(Uuid, Key)>, ServerError> {
240
4506
    let mut touched = linked_of_name(conn, artifact, "name").await?;
241
4506
    touched.extend(linked_of_name(conn, artifact, "enabled").await?);
242
4506
    Ok(sorted_keys(touched.into_iter()))
243
4506
}
244

            
245
2346
async fn refuse_stale(
246
2346
    conn: &mut PgConnection,
247
2346
    id: Uuid,
248
2346
    revision: &str,
249
2346
) -> Result<(), ServerError> {
250
973
    let row = sqlx::query_file!("sql/select/artifacts/by_id.sql", id, "template")
251
973
        .fetch_one(conn)
252
973
        .await
253
973
        .map_err(db_err)?;
254
973
    let source = row.source_text.unwrap_or_default();
255
973
    match template_revision(row.artifact_name.as_deref(), &source) == revision {
256
810
        true => Ok(()),
257
163
        false => Err(ServerError::StaleTemplate),
258
    }
259
973
}
260

            
261
20764
async fn linked_of_name(
262
20764
    conn: &mut PgConnection,
263
20764
    artifact: Uuid,
264
20764
    name: &str,
265
20764
) -> Result<Vec<(Uuid, Key)>, ServerError> {
266
10991
    let rows = sqlx::query_file!("sql/select/tags/by_artifact_and_name.sql", artifact, name)
267
10991
        .fetch_all(conn)
268
10991
        .await
269
10991
        .map_err(db_err)?;
270
10991
    Ok(in_key_order(
271
10991
        name,
272
10991
        rows.into_iter().map(|row| (row.id, row.tag_value)),
273
    ))
274
10991
}
275

            
276
3629
async fn linked(conn: &mut PgConnection, artifact: Uuid) -> Result<Vec<(Uuid, Key)>, ServerError> {
277
1957
    let rows = sqlx::query_file!("sql/select/tags/by_artifact.sql", artifact)
278
1957
        .fetch_all(conn)
279
1957
        .await
280
1957
        .map_err(db_err)?;
281
1957
    Ok(rows
282
1957
        .into_iter()
283
3570
        .map(|row| (row.id, (row.tag_name, row.tag_value)))
284
        .collect())
285
1957
}