Lines
97.67 %
Functions
79.75 %
Branches
100 %
//! Artifact tag writes on the tag lock protocol: the tag keys, then the
//! artifact row, then the links. Each attempt runs in its own DB transaction.
use finance::tag::Tag;
use sqlx::{PgConnection, types::Uuid};
use super::lock::{
Key, KeyChanged, begin, destination_keys, in_key_order, lock, lock_keys, retry, sorted_keys,
};
use crate::artifact_mgmt::user::KIND_AUTOMATION;
use crate::error::ServerError;
use crate::script_state::{is_enabled, script_revision};
use crate::template_state::template_revision;
fn db_err(err: sqlx::Error) -> ServerError {
tracing::error!("{}", t!("Database error: %{err}", err = err : {:?}));
ServerError::DB(crate::db::DBError::Sqlx(err))
}
/// Upsert each tag and link it to the artifact, whose row and tag keys the
/// caller holds.
pub(crate) async fn link(
conn: &mut PgConnection,
artifact: Uuid,
tags: &[&Tag],
) -> Result<(), ServerError> {
for tag in tags {
let tag_id = tag.commit(&mut *conn).await.map_err(|err| {
ServerError::Finance(err)
})?;
sqlx::query_file!(
"sql/insert/artifact_tags/artifact_tag.sql",
&artifact,
&tag_id
)
.execute(&mut *conn)
.await
.map_err(db_err)?;
Ok(())
/// Lock the keys of the tags a new artifact is created with.
pub(crate) async fn lock_new(conn: &mut PgConnection, tags: &[&Tag]) -> Result<(), ServerError> {
lock_keys(conn, &destination_keys(tags.iter().copied()))
/// Replace the artifact's tags named `name` with `tag`, or drop them when
/// `tag` is `None`.
pub(crate) async fn replace(
name: &str,
tag: Option<&Tag>,
) -> Result<Result<(), KeyChanged>, ServerError> {
let mut tx = begin(conn).await.map_err(db_err)?;
let touched = linked_of_name(&mut tx, artifact, name).await?;
if lock(&mut tx, &touched, tag.as_slice())
.map_err(db_err)?
.is_err()
{
return retry(tx).await.map_err(db_err);
sqlx::query_file!("sql/select/artifacts/by_id_locked.sql", artifact)
.fetch_one(&mut *tx)
if linked_of_name(&mut tx, artifact, name).await? != touched {
"sql/delete/artifact_tags/by_artifact_and_name.sql",
artifact,
name
.execute(&mut *tx)
link(&mut tx, artifact, tag.as_slice()).await?;
tx.commit().await.map_err(db_err)?;
Ok(Ok(()))
/// Delete the artifact and its tag links under the keys of its tags.
pub(crate) async fn delete(
) -> Result<Result<bool, KeyChanged>, ServerError> {
let touched = linked(&mut tx, artifact).await?;
if lock(&mut tx, &touched, &[]).await.map_err(db_err)?.is_err() {
return Ok(retry(tx).await.map_err(db_err)?.map(|()| false));
let existed = sqlx::query_file!("sql/select/artifacts/by_id_locked.sql", artifact)
.fetch_optional(&mut *tx)
.is_some();
if linked(&mut tx, artifact).await? != touched {
sqlx::query_file!("sql/delete/artifact_tags/by_artifact.sql", &artifact)
sqlx::query_file!("sql/delete/artifacts/by_id.sql", &artifact)
Ok(Ok(existed))
/// Replace the template's `name` tag and source text under the name keys;
/// refused as stale when the locked template no longer matches `revision`.
pub(crate) async fn update_template(
id: Uuid,
revision: &str,
name: Option<&Tag>,
source: &str,
let touched = linked_of_name(&mut tx, id, "name").await?;
if lock(&mut tx, &touched, name.as_slice())
sqlx::query_file!("sql/select/artifacts/by_id_locked.sql", id)
if linked_of_name(&mut tx, id, "name").await? != touched {
refuse_stale(&mut tx, id, revision).await?;
sqlx::query_file!("sql/update/artifacts/source_text.sql", &id, source)
id,
"name"
link(&mut tx, id, name.as_slice()).await?;
/// Replace the script's `name` and `enabled` tags, source and bytecode under
/// those keys; refused as stale when the locked script no longer matches `revision`.
pub(crate) async fn update_script(
tags: (Option<&Tag>, Option<&Tag>),
code: (&str, &[u8]),
let (name, enabled) = tags;
let destinations: Vec<&Tag> = name.into_iter().chain(enabled).collect();
let touched = linked_of_names(&mut tx, id).await?;
if lock(&mut tx, &touched, &destinations)
if linked_of_names(&mut tx, id).await? != touched {
refuse_stale_script(&mut tx, id, revision).await?;
let (source, bytecode) = code;
"sql/update/artifacts/script.sql",
&id,
source,
bytecode,
KIND_AUTOMATION
for tag_name in ["name", "enabled"] {
tag_name
link(&mut tx, id, &destinations).await?;
async fn refuse_stale_script(
let row = sqlx::query_file!("sql/select/artifacts/by_id.sql", id, KIND_AUTOMATION)
.fetch_one(conn)
let current = script_revision(
row.artifact_name.as_deref(),
row.source_text.as_deref(),
is_enabled(row.enabled.as_deref()),
);
match current == revision {
true => Ok(()),
false => Err(ServerError::StaleScript),
async fn linked_of_names(
) -> Result<Vec<(Uuid, Key)>, ServerError> {
let mut touched = linked_of_name(conn, artifact, "name").await?;
touched.extend(linked_of_name(conn, artifact, "enabled").await?);
Ok(sorted_keys(touched.into_iter()))
async fn refuse_stale(
let row = sqlx::query_file!("sql/select/artifacts/by_id.sql", id, "template")
let source = row.source_text.unwrap_or_default();
match template_revision(row.artifact_name.as_deref(), &source) == revision {
false => Err(ServerError::StaleTemplate),
async fn linked_of_name(
let rows = sqlx::query_file!("sql/select/tags/by_artifact_and_name.sql", artifact, name)
.fetch_all(conn)
Ok(in_key_order(
name,
rows.into_iter().map(|row| (row.id, row.tag_value)),
))
async fn linked(conn: &mut PgConnection, artifact: Uuid) -> Result<Vec<(Uuid, Key)>, ServerError> {
let rows = sqlx::query_file!("sql/select/tags/by_artifact.sql", artifact)
Ok(rows
.into_iter()
.map(|row| (row.id, (row.tag_name, row.tag_value)))
.collect())