Lines
99.28 %
Functions
81.82 %
Branches
100 %
pub mod user {
use crate::attempt::{Attempt, Tries};
use crate::db::DBError;
use crate::error::ServerError;
use crate::tag::{artifact, lock};
use crate::user::User;
use finance::tag::Tag;
use sqlx::types::Uuid;
use std::convert::identity;
pub(crate) const KIND_AUTOMATION: &str = "automation";
const KIND_TEMPLATE: &str = "template";
pub struct ScriptInfo {
pub id: Uuid,
pub name: Option<String>,
pub size: i32,
/// False for a script uploaded as bytecode only.
pub has_source: bool,
pub enabled: Option<String>,
}
pub struct ScriptDetail {
pub bytecode: Vec<u8>,
pub source: Option<String>,
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TemplateInfo {
pub struct TemplateDetail {
pub source_text: String,
fn artifact_tag(name: &str, value: &str) -> Tag {
Tag {
id: Uuid::new_v4(),
tag_name: name.to_string(),
tag_value: value.to_string(),
description: None,
/// A blank name is no name.
fn clean_name(name: Option<String>) -> Option<String> {
name.filter(|name| !name.trim().is_empty())
fn new_artifact_tags(kind: &str, name: Option<String>) -> Vec<Tag> {
let name = name.map(|name| artifact_tag("name", &name));
std::iter::once(artifact_tag("kind", kind))
.chain(name)
.collect()
fn disabled_tag(enabled: bool) -> Option<Tag> {
(!enabled).then(|| artifact_tag("enabled", "false"))
fn found(rows: u64) -> Result<(), ServerError> {
match rows {
0 => Err(db_err(sqlx::Error::RowNotFound)),
_ => Ok(()),
fn db_err(err: sqlx::Error) -> ServerError {
tracing::error!("{}", t!("Database error: %{err}", err = err : {:?}));
ServerError::DB(DBError::Sqlx(err))
impl User {
pub async fn list_scripts(&self) -> Result<Vec<ScriptInfo>, ServerError> {
let mut conn = self.get_connection().await?;
let rows = sqlx::query_file!("sql/select/artifacts/by_kind.sql", KIND_AUTOMATION)
.fetch_all(&mut *conn)
.await
.map_err(db_err)?;
Ok(rows
.into_iter()
.map(|r| ScriptInfo {
id: r.id,
name: r.artifact_name,
size: r.size.unwrap_or(0),
has_source: r.has_source,
enabled: r.enabled,
})
.collect())
pub async fn get_script(&self, id: Uuid) -> Result<ScriptDetail, ServerError> {
let row = sqlx::query_file!("sql/select/artifacts/by_id.sql", &id, KIND_AUTOMATION)
.fetch_one(&mut *conn)
Ok(ScriptDetail {
id: row.id,
name: row.artifact_name,
bytecode: row.bytecode.unwrap_or_default(),
source: row.source_text,
enabled: row.enabled,
/// A script stored as bytecode alone, the shape a pre-source script has.
#[cfg(any(test, feature = "test-utils"))]
pub async fn create_script(
&self,
bytecode: Vec<u8>,
name: Option<String>,
) -> Result<Uuid, ServerError> {
self.insert_script(bytecode, None, name, true).await
/// Store a script with the `bytecode` compiled from its `source`.
pub async fn create_script_from_source(
source: String,
enabled: bool,
self.insert_script(bytecode, Some(source), name, enabled)
async fn insert_script(
source: Option<String>,
let mut tags = new_artifact_tags(KIND_AUTOMATION, name);
tags.extend(disabled_tag(enabled));
let tags: Vec<&Tag> = tags.iter().collect();
let mut tx = lock::begin(&mut conn).await.map_err(db_err)?;
artifact::lock_new(&mut tx, &tags).await?;
let id = Uuid::new_v4();
sqlx::query_file!(
"sql/insert/artifacts/artifact.sql",
&id,
Some(&bytecode[..]),
source.as_deref()
)
.execute(&mut *tx)
artifact::link(&mut tx, id, &tags).await?;
tx.commit().await.map_err(db_err)?;
Ok(id)
/// Replace a script's source and its bytecode in one statement.
///
/// # Errors
/// A missing script, or a failing write.
pub async fn update_script_source(
id: Uuid,
) -> Result<(), ServerError> {
let done = sqlx::query_file!(
"sql/update/artifacts/script.sql",
&source,
&bytecode,
KIND_AUTOMATION
.execute(&mut *conn)
found(done.rows_affected())
/// Replace the script's name, enabled state, source and bytecode in one
/// transaction under the name and enabled keys, refusing with
/// [`ServerError::StaleScript`] when it no longer matches `revision`.
/// A missing script, a stale revision, or a failing write.
pub async fn update_script(
revision: &str,
code: (&str, &[u8]),
let name = clean_name(name).map(|name| artifact_tag("name", &name));
let enabled = disabled_tag(enabled);
let mut tries = Tries::default();
while tries
.step(Attempt::of(
artifact::update_script(
&mut conn,
id,
revision,
(name.as_ref(), enabled.as_ref()),
code,
.await,
ServerError::is_retryable,
identity,
))?
.is_none()
{}
Ok(())
/// Whether the script existed.
pub async fn delete_script(&self, id: Uuid) -> Result<bool, ServerError> {
let found = sqlx::query_file!("sql/select/artifacts/by_id.sql", &id, KIND_AUTOMATION)
.fetch_optional(&mut *conn)
drop(conn);
match found {
Some(_) => self.delete_artifact(id).await,
None => Ok(false),
pub async fn set_script_enabled(&self, id: Uuid, enabled: bool) -> Result<(), ServerError> {
self.set_artifact_enabled(id, enabled).await
pub async fn update_script_name(
self.update_artifact_name(id, name).await
pub async fn list_templates(&self) -> Result<Vec<TemplateInfo>, ServerError> {
let rows = sqlx::query_file!("sql/select/artifacts/by_kind.sql", KIND_TEMPLATE)
.map(|r| TemplateInfo {
pub async fn get_template(&self, id: Uuid) -> Result<TemplateDetail, ServerError> {
self.find_template(id)
.await?
.ok_or(ServerError::DB(DBError::Sqlx(sqlx::Error::RowNotFound)))
pub async fn find_template(&self, id: Uuid) -> Result<Option<TemplateDetail>, ServerError> {
let row = sqlx::query_file!("sql/select/artifacts/by_id.sql", &id, KIND_TEMPLATE)
Ok(row.map(|row| TemplateDetail {
source_text: row.source_text.unwrap_or_default(),
}))
pub async fn create_template(
let tags = new_artifact_tags(KIND_TEMPLATE, clean_name(name));
None::<&[u8]>,
Some(source.as_str())
/// Replace the template's name and source in one transaction under the
/// name keys, refusing with [`ServerError::StaleTemplate`] when it no
/// longer matches `revision`.
/// A missing template, a stale revision, or a failing write.
pub async fn update_template(
source: &str,
artifact::update_template(&mut conn, id, revision, name.as_ref(), source).await,
/// Whether the template existed.
pub async fn delete_template(&self, id: Uuid) -> Result<bool, ServerError> {
match self.find_template(id).await? {
/// Lifecycle delete: detach links and drop the row in ONE transaction so
/// the deferred kind-tag DELETE guard sees the parent gone at commit.
async fn delete_artifact(&self, id: Uuid) -> Result<bool, ServerError> {
loop {
let attempt = Attempt::of(
artifact::delete(&mut conn, id).await,
);
if let Some(existed) = tries.step(attempt)? {
return Ok(existed);
async fn set_artifact_enabled(&self, id: Uuid, enabled: bool) -> Result<(), ServerError> {
let tag = disabled_tag(enabled);
self.replace_artifact_tag(id, "enabled", tag.as_ref()).await
async fn update_artifact_name(
let tag = name.map(|name| artifact_tag("name", &name));
self.replace_artifact_tag(id, "name", tag.as_ref()).await
async fn replace_artifact_tag(
name: &str,
tag: Option<&Tag>,
artifact::replace(&mut conn, id, name, tag).await,
#[cfg(test)]
mod artifact_mgmt_tests;