Lines
100 %
Functions
Branches
//! The single-tag writers on transactions, splits, commodities, artifacts and
//! accounts, and `delete_tag`, on the tag lock protocol under forced
//! interleavings.
use super::lock_protocol::link_raw_tag;
use super::*;
use finance::commodity::Commodity;
use sqlx::Connection;
/// The linked `cat` is renamed while `SetTransactionTag` waits for its key:
/// the retry locks the new key and links the tag.
#[local_db_sqlx_test]
async fn set_transaction_tag_retries_a_rename_before_the_lock(pool: PgPool) -> anyhow::Result<()> {
let fx = fixture().await?;
let tx_id = fx.create_tx(None).await?;
let linked = link_raw_tag(&pool, tx_id, "cat", "k0").await?;
let mut conn = fx.user.get_connection().await?;
let mut renamer = conn.begin().await?;
hold_key(&mut renamer, "cat", "k0").await?;
rename(&mut renamer, linked, "k1").await?;
let set = SetTransactionTag::new()
.user_id(fx.user.id)
.transaction_id(tx_id)
.tag_name("zone".to_string())
.tag_value("z".to_string())
.run();
let steer = release_after(wait_for_key_waiter(&fx, "cat", "k0"), renamer);
let (set, steered) = tokio::join!(set, steer);
steered?;
set?;
assert_eq!(
fx.tx_tags(tx_id).await?,
vec![pair("cat", "k1"), pair("zone", "z")]
);
}
/// `SetSplitTag` and `create_split_tag` hold the owning transaction's row and
/// wait for the written key before touching any tag row.
async fn split_tag_writers_wait_for_the_key(pool: PgPool) -> anyhow::Result<()> {
let [first, second] = fx.split_ids(tx_id).await?[..] else {
anyhow::bail!("two splits");
};
let mut holder = conn.begin().await?;
hold_key(&mut holder, "memo", "m").await?;
let set = SetSplitTag::new()
.split_id(first)
.tag_name("memo".to_string())
.tag_value("m".to_string())
let attach = fx
.user
.create_split_tag(second, "memo".to_string(), "m".to_string(), None);
let checked = async {
wait_for_blocked(&fx, 2).await?;
let none_written = fx.tag_rows_with_value("m").await? == 0;
anyhow::Ok(none_written)
let release = release_after(checked, holder);
let (set, attach, released) = tokio::join!(set, attach, release);
assert!(released?, "a tag row was written before its key was locked");
attach?;
for split in [first, second] {
assert_eq!(fx.split_tag_values(split).await?, vec!["m"]);
/// The tag is renamed while `delete_tag` waits for its key: the retry deletes
/// the renamed row and its link.
async fn delete_tag_retries_a_rename_before_the_lock(pool: PgPool) -> anyhow::Result<()> {
let (deleted, steered) = tokio::join!(fx.user.delete_tag(linked), steer);
deleted?;
assert!(fx.tx_tags(tx_id).await?.is_empty());
assert!(fx.user.stored_tag(linked).await.is_err());
/// Lock the tag rows of `(name, value)` for each value, creating them.
async fn hold_tag_rows(
conn: &mut sqlx::PgConnection,
pool: &PgPool,
name: &str,
values: &[&str],
) -> anyhow::Result<()> {
for value in values {
let id = fx_tag(pool, name, value).await?;
sqlx::query_file!("sql/select/tags/lock_by_id.sql", id)
.fetch_one(&mut *conn)
.await?;
Ok(())
async fn fx_tag(pool: &PgPool, name: &str, value: &str) -> anyhow::Result<Uuid> {
let id = Uuid::new_v4();
sqlx::query("INSERT INTO tags (id, tag_name, tag_value) VALUES ($1, $2, $3)")
.bind(id)
.bind(name)
.bind(value)
.execute(pool)
Ok(id)
/// Two first values of one name on a commodity both queue on their tag rows,
/// so neither saw the other's link when it started: the commodity row lock
/// and the reread under it keep one value.
async fn two_first_commodity_values_keep_one(pool: PgPool) -> anyhow::Result<()> {
let commodity = Commodity { id: fx.commodity };
hold_tag_rows(&mut holder, &pool, "region", &["eu", "us"]).await?;
let (eu, us) = (tag("region", "eu"), tag("region", "us"));
let release = release_after(wait_for_blocked(&fx, 2), holder);
let (a, b, r) = tokio::join!(
fx.user.set_commodity_tag(&commodity, &eu),
fx.user.set_commodity_tag(&commodity, &us),
release
r?;
a?;
b?;
let regions = fx
.get_commodity_tags(&commodity)
.await?
.into_iter()
.filter(|t| t.tag_name == "region")
.count();
assert_eq!(regions, 1);
async fn artifact_names(pool: &PgPool, artifact: Uuid) -> anyhow::Result<Vec<String>> {
Ok(sqlx::query_scalar(
"SELECT t.tag_value FROM artifact_tags AS art
INNER JOIN tags AS t ON art.tag_id = t.id
WHERE art.artifact_id = $1 AND t.tag_name = 'name'",
)
.bind(artifact)
.fetch_all(pool)
.await?)
/// Two first names of one script both queue on their tag rows: the artifact
/// row lock and the reread under it keep one name.
async fn two_first_script_names_keep_one(pool: PgPool) -> anyhow::Result<()> {
let script = fx.user.create_script(vec![0], None).await?;
hold_tag_rows(&mut holder, &pool, "name", &["one", "two"]).await?;
fx.user.update_script_name(script, Some("one".to_string())),
fx.user.update_script_name(script, Some("two".to_string())),
assert_eq!(artifact_names(&pool, script).await?.len(), 1);
/// Creating and deleting a script take its tag keys before the artifact row
/// and the links: both queue on the held `kind` key and change nothing.
async fn script_create_and_delete_wait_for_the_tag_keys(pool: PgPool) -> anyhow::Result<()> {
let doomed = fx
.create_script(vec![0], Some("doomed".to_string()))
hold_key(&mut holder, "kind", "automation").await?;
let created = fx.user.create_script(vec![0], Some("fresh".to_string()));
let deleted = fx.user.delete_script(doomed);
let untouched = fx.user.list_scripts().await?.len() == 1
&& artifact_names(&pool, doomed).await? == vec!["doomed"];
anyhow::Ok(untouched)
let (created, deleted, released) = tokio::join!(created, deleted, release);
assert!(released?, "a script changed before its keys were locked");
let created = created?;
assert_eq!(artifact_names(&pool, created).await?, vec!["fresh"]);
assert_eq!(fx.user.list_scripts().await?.len(), 1);
/// A new account takes its name key before its row, whose insert key-shares
/// the parent: while the key is held, the parent stays free to lock.
async fn a_new_account_takes_its_name_key_before_its_row(pool: PgPool) -> anyhow::Result<()> {
let parent = fx.accounts[0];
hold_key(&mut holder, "name", "Child").await?;
let created = fx.user.create_account("Child", Some(parent));
wait_for_key_waiter(&fx, "name", "Child").await?;
let mut probe_conn = fx.user.get_connection().await?;
let mut probe = probe_conn.begin().await?;
let parent_free = sqlx::query("SELECT id FROM accounts WHERE id = $1 FOR UPDATE NOWAIT")
.bind(parent)
.fetch_one(&mut *probe)
.await
.is_ok();
probe.rollback().await?;
anyhow::Ok(parent_free)
let (created, released) = tokio::join!(created, release);
assert!(
released?,
"the account row was inserted before its name key"
assert_eq!(created?.parent, Some(parent));