Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

24.5 KB
Raw Blame
//! General entity property query helpers.

#[cfg(test)]
mod test;

use anyhow::Context as _;
use models_properties::service::{entity_property::EntityProperty, property_value::PropertyValue};
use models_properties::{EntityReference, EntityType};
use sqlx::{PgExecutor, Pool, Postgres};
use uuid::Uuid;

use super::query_error::PropertyQueryError;

use crate::domain::error::InvalidStoredPropertyValue;
use crate::domain::model::{
    EntityPropertyMutationSnapshot, EntityPropertyOptionSelection, EntityPropertyOptionUpdate,
};

pub(super) fn decode_stored_property_value(
    value: Option<serde_json::Value>,
) -> anyhow::Result<Option<PropertyValue>> {
    value
        .filter(|value| !value.is_null())
        .map(|value| serde_json::from_value(value).context(InvalidStoredPropertyValue))
        .transpose()
}

pub(super) struct EntityPropertyMutationRow {
    pub(super) id: Uuid,
    pub(super) entity_id: String,
    pub(super) entity_type: EntityType,
    pub(super) property_definition_id: Uuid,
    pub(super) value: Option<serde_json::Value>,
    pub(super) previous: Option<serde_json::Value>,
    pub(super) created_at: chrono::DateTime<chrono::Utc>,
    pub(super) updated_at: chrono::DateTime<chrono::Utc>,
}

impl EntityPropertyMutationRow {
    pub(super) fn into_snapshot(self) -> Result<EntityPropertyMutationSnapshot, serde_json::Error> {
        let value = match self.value {
            Some(value) if !value.is_null() => Some(serde_json::from_value(value)?),
            Some(_) | None => None,
        };
        // The pre-write value supports display metadata and change triggers.
        // Treat undecodable legacy values as absent so a mutation can fix them.
        let previous_value = self
            .previous
            .filter(|value| !value.is_null())
            .and_then(|value| serde_json::from_value(value).ok());

        Ok(EntityPropertyMutationSnapshot {
            property: EntityProperty {
                id: self.id,
                entity_id: self.entity_id,
                entity_type: self.entity_type,
                property_definition_id: self.property_definition_id,
                created_at: self.created_at,
                updated_at: self.updated_at,
            },
            value,
            previous_value,
        })
    }
}

/// What entities of one type hold, inside a caller's transaction: every
/// property with a value, or only those of `definitions` when given.
/// Undecodable values are left out.
pub async fn entity_values_in_transaction(
    tx: &mut sqlx::PgConnection,
    entity_type: EntityType,
    entity_ids: &[String],
    definitions: Option<&[Uuid]>,
) -> Result<Vec<(String, Uuid, PropertyValue)>, PropertyQueryError> {
    if entity_ids.is_empty() {
        return Ok(Vec::new());
    }
    let rows = sqlx::query!(
        r#"
        SELECT entity_id, property_definition_id, values as "values: serde_json::Value"
        FROM entity_properties
        WHERE entity_type = $1 AND entity_id = ANY($2)
          AND ($3::uuid[] IS NULL OR property_definition_id = ANY($3))
          AND values IS NOT NULL
        "#,
        entity_type as EntityType,
        entity_ids,
        definitions as Option<&[Uuid]>,
    )
    .fetch_all(&mut *tx)
    .await?;
    Ok(rows
        .into_iter()
        .filter_map(|row| {
            let value = row.values.filter(|value| !value.is_null())?;
            let value = serde_json::from_value(value).ok()?;
            Some((row.entity_id, row.property_definition_id, value))
        })
        .collect())
}

/// Set one property on many entities of one type inside a caller's
/// transaction, each to its value or, with `None`, cleared: a few
/// statements however many entities there are. A value already stored is
/// left untouched; answers how many stored values changed. The caller
/// serializes writers of these values.
pub async fn set_entity_values_in_transaction(
    tx: &mut sqlx::PgConnection,
    entity_type: EntityType,
    property_definition_id: Uuid,
    values: &[(String, Option<PropertyValue>)],
) -> Result<u64, PropertyQueryError> {
    let mut ids = Vec::new();
    let mut set = Vec::new();
    let mut stored = Vec::new();
    let mut cleared = Vec::new();
    let mut changed = 0;
    for (entity_id, value) in values {
        match value {
            Some(value) => {
                ids.push(macro_uuid::generate_uuid_v7());
                set.push(entity_id.clone());
                stored.push(serde_json::to_value(value)?);
            }
            None => cleared.push(entity_id.clone()),
        }
    }
    if !set.is_empty() {
        // Updating the cells already there first keeps the insert, and the
        // checks its triggers run per row, to the cells that are new.
        changed += sqlx::query!(
            r#"
            UPDATE entity_properties
            SET values = cell.value, updated_at = NOW()
            FROM UNNEST($1::text[], $2::jsonb[]) AS cell(entity_id, value)
            WHERE entity_properties.entity_type = $3
              AND entity_properties.property_definition_id = $4
              AND entity_properties.entity_id = cell.entity_id
              AND entity_properties.values IS DISTINCT FROM cell.value
            "#,
            &set,
            &stored,
            entity_type as EntityType,
            property_definition_id,
        )
        .execute(&mut *tx)
        .await?
        .rows_affected();
        changed += sqlx::query!(
            r#"
            INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)
            SELECT cell.id, cell.entity_id, $3, $4, cell.value
            FROM UNNEST($1::uuid[], $2::text[], $5::jsonb[]) AS cell(id, entity_id, value)
            WHERE NOT EXISTS (
                SELECT 1 FROM entity_properties stored
                WHERE stored.entity_id = cell.entity_id
                  AND stored.entity_type = $3
                  AND stored.property_definition_id = $4
            )
            ON CONFLICT (entity_id, entity_type, property_definition_id)
            DO UPDATE SET values = EXCLUDED.values, updated_at = NOW()
            "#,
            &ids,
            &set,
            entity_type as EntityType,
            property_definition_id,
            &stored,
        )
        .execute(&mut *tx)
        .await?
        .rows_affected();
    }
    if !cleared.is_empty() {
        changed += sqlx::query!(
            r#"
            DELETE FROM entity_properties
            WHERE entity_type = $1 AND property_definition_id = $2 AND entity_id = ANY($3)
            "#,
            entity_type as EntityType,
            property_definition_id,
            &cleared,
        )
        .execute(&mut *tx)
        .await?
        .rows_affected();
    }
    Ok(changed)
}

/// Upsert an entity property value (insert or update).
/// If the property doesn't exist, it will be created and attached to the entity.
/// If it exists, the value will be updated. The returned snapshot carries the
/// pre-write value captured after serializing concurrent writes, so consumers
/// can distinguish newly assigned agents from unchanged values.
pub async fn upsert_entity_property(
    pool: &Pool<Postgres>,
    entity_id: &str,
    entity_type: EntityType,
    property_definition_id: Uuid,
    value: Option<PropertyValue>,
) -> Result<EntityPropertyMutationSnapshot, PropertyQueryError> {
    let mut tx = pool.begin().await?;
    let snapshot = upsert_entity_property_in_transaction(
        &mut tx,
        entity_id,
        entity_type,
        property_definition_id,
        value,
    )
    .await?;
    tx.commit().await?;
    Ok(snapshot)
}

/// [`upsert_entity_property`] inside a caller's transaction, so the write
/// commits or rolls back with the caller's other statements. The serializing
/// locks are held until that transaction ends.
pub async fn upsert_entity_property_in_transaction(
    tx: &mut sqlx::PgConnection,
    entity_id: &str,
    entity_type: EntityType,
    property_definition_id: Uuid,
    value: Option<PropertyValue>,
) -> Result<EntityPropertyMutationSnapshot, PropertyQueryError> {
    if let Some(PropertyValue::SelectOption(options)) = &value {
        super::property_option_queries::hold_selected_options(tx, property_definition_id, options)
            .await?;
    }
    mutate_entity_property_in_transaction(
        tx,
        entity_id,
        entity_type,
        property_definition_id,
        |_| Ok(value),
    )
    .await
}

/// Append references under the same locks as replacement writes so concurrent
/// task assignments cannot overwrite each other's assignees.
pub async fn add_entity_property_references(
    pool: &Pool<Postgres>,
    entity_id: &str,
    entity_type: EntityType,
    property_definition_id: Uuid,
    references: Vec<EntityReference>,
) -> anyhow::Result<EntityPropertyMutationSnapshot> {
    let mut tx = pool.begin().await?;
    let snapshot = mutate_entity_property_in_transaction(
        &mut tx,
        entity_id,
        entity_type,
        property_definition_id,
        |previous| -> anyhow::Result<Option<PropertyValue>> {
            let mut current = match decode_stored_property_value(previous)? {
                Some(PropertyValue::EntityRef(current)) => current,
                None => Vec::new(),
                Some(_) => return Err(InvalidStoredPropertyValue.into()),
            };
            for reference in references {
                if !current.contains(&reference) {
                    current.push(reference);
                }
            }
            Ok(Some(PropertyValue::EntityRef(current)))
        },
    )
    .await?;
    tx.commit().await?;
    Ok(snapshot)
}

async fn mutate_entity_property_in_transaction<Error>(
    tx: &mut sqlx::PgConnection,
    entity_id: &str,
    entity_type: EntityType,
    property_definition_id: Uuid,
    update: impl FnOnce(Option<serde_json::Value>) -> Result<Option<PropertyValue>, Error>,
) -> Result<EntityPropertyMutationSnapshot, Error>
where
    Error: From<sqlx::Error> + From<serde_json::Error>,
{
    // Serialize first assignments even when no row exists to lock yet. Keep
    // this separate from the UPSERT so its statement snapshot starts after
    // the preceding writer commits, rather than before waiting for that row.
    sqlx::query!(
        r#"SELECT pg_advisory_xact_lock(hashtextextended($1, 0))"#,
        format!("entity_property:{entity_type}:{entity_id}:{property_definition_id}"),
    )
    .execute(&mut *tx)
    .await?;

    // Other property operations use row locks rather than this advisory lock.
    // Wait for those writers too before the UPSERT captures its previous value.
    let previous = sqlx::query_scalar!(
        r#"
            SELECT values as "values: serde_json::Value"
            FROM entity_properties
            WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3
            FOR UPDATE
            "#,
        entity_id,
        entity_type as EntityType,
        property_definition_id,
    )
    .fetch_optional(&mut *tx)
    .await?;

    let value = update(previous.flatten())?;

    let id = macro_uuid::generate_uuid_v7();

    // Serialize PropertyValue to JSONB (or NULL if None)
    let value_json = match value {
        Some(v) => serde_json::to_value(&v)?,
        None => serde_json::Value::Null,
    };

    tracing::debug!(value_json = ?value_json, "upserting entity property");

    // The locks above make this fresh statement snapshot authoritative.
    let row = sqlx::query_as!(
        EntityPropertyMutationRow,
        r#"
        WITH previous AS (
            SELECT values FROM entity_properties
            WHERE entity_id = $2 AND entity_type = $3 AND property_definition_id = $4
        )
        INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)
        VALUES ($1, $2, $3, $4, $5)
        ON CONFLICT (entity_id, entity_type, property_definition_id)
        DO UPDATE SET
            values = EXCLUDED.values,
            updated_at = NOW()
        RETURNING
            id,
            entity_id,
            entity_type as "entity_type: EntityType",
            property_definition_id,
            values as "value: serde_json::Value",
            (SELECT values FROM previous) as "previous: serde_json::Value",
            created_at,
            updated_at
        "#,
        id,
        entity_id,
        entity_type as EntityType,
        property_definition_id,
        value_json
    )
    .fetch_one(&mut *tx)
    .await?;

    tracing::debug!("successfully upserted entity property");

    Ok(row.into_snapshot()?)
}

/// Atomically add one option to a multi-select entity property value, creating
/// the row if the property is not yet attached. Re-adding a present option is a
/// no-op (deduped). The whole change is one row-locked statement applied to the
/// current stored value, so concurrent adds merge instead of one overwriting
/// the other (no read-modify-write lost update). A NULL or non-SelectOption
/// existing value is coerced to a single-element SelectOption.
pub async fn add_entity_property_option(
    pool: &Pool<Postgres>,
    entity_id: &str,
    entity_type: EntityType,
    property_definition_id: Uuid,
    option_id: Uuid,
) -> anyhow::Result<EntityPropertyMutationSnapshot> {
    let mut tx = pool.begin().await?;
    super::property_option_queries::hold_selected_options(
        &mut tx,
        property_definition_id,
        &[option_id],
    )
    .await?;
    let id = macro_uuid::generate_uuid_v7();

    let row = sqlx::query_as!(
        EntityPropertyMutationRow,
        r#"
        WITH previous AS (
            SELECT values FROM entity_properties
            WHERE entity_id = $2 AND entity_type = $3 AND property_definition_id = $4
        )
        INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)
        VALUES (
            $1, $2, $3, $4,
            jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array($5::text))
        )
        ON CONFLICT (entity_id, entity_type, property_definition_id)
        DO UPDATE SET
            values = CASE
                WHEN entity_properties.values ->> 'type' = 'SelectOption'
                     AND entity_properties.values -> 'value' @> jsonb_build_array($5::text)
                    THEN entity_properties.values
                WHEN entity_properties.values ->> 'type' = 'SelectOption'
                    THEN jsonb_set(
                            entity_properties.values,
                            '{value}',
                            (entity_properties.values -> 'value') || jsonb_build_array($5::text)
                        )
                ELSE jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array($5::text))
            END,
            updated_at = NOW()
        RETURNING
            id,
            entity_id,
            entity_type as "entity_type: EntityType",
            property_definition_id,
            values as "value: serde_json::Value",
            (SELECT values FROM previous) as "previous: serde_json::Value",
            created_at,
            updated_at
        "#,
        id,
        entity_id,
        entity_type as EntityType,
        property_definition_id,
        option_id.to_string(),
    )
    .fetch_one(&mut *tx)
    .await?;

    tx.commit().await?;
    Ok(row.into_snapshot()?)
}

/// Atomically remove one option from a multi-select entity property value. A
/// no-op if the property is unattached or the option is not present. One
/// row-locked statement applied to the current stored value, so it composes
/// with concurrent adds/removes without a lost update.
pub async fn remove_entity_property_option(
    pool: &Pool<Postgres>,
    entity_id: &str,
    entity_type: EntityType,
    property_definition_id: Uuid,
    option_id: Uuid,
) -> anyhow::Result<Option<EntityPropertyMutationSnapshot>> {
    let row = sqlx::query_as!(
        EntityPropertyMutationRow,
        r#"
        WITH previous AS (
            SELECT values FROM entity_properties
            WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3
        )
        UPDATE entity_properties
        SET values = jsonb_set(
                values,
                '{value}',
                COALESCE(
                    (
                        SELECT jsonb_agg(elem)
                        FROM jsonb_array_elements(values -> 'value') AS elem
                        WHERE elem <> to_jsonb($4::text)
                    ),
                    '[]'::jsonb
                )
            ),
            updated_at = NOW()
        WHERE entity_id = $1
          AND entity_type = $2
          AND property_definition_id = $3
          AND values ->> 'type' = 'SelectOption'
          AND values -> 'value' @> jsonb_build_array($4::text)
        RETURNING
            id,
            entity_id,
            entity_type as "entity_type: EntityType",
            property_definition_id,
            values as "value: serde_json::Value",
            (SELECT values FROM previous) as "previous: serde_json::Value",
            created_at,
            updated_at
        "#,
        entity_id,
        entity_type as EntityType,
        property_definition_id,
        option_id.to_string(),
    )
    .fetch_optional(pool)
    .await?;

    Ok(row
        .map(EntityPropertyMutationRow::into_snapshot)
        .transpose()?)
}

/// Apply option deltas to several of an entity's multi-select property values in
/// one transaction, returning each property's final option ids.
///
/// A property is only attached (row created) when there are options to add;
/// otherwise the row is locked with `SELECT ... FOR UPDATE` before its current
/// value is read, diffed, and rewritten. A removal-only update on an unattached
/// property is a no-op — it does not create an empty row. Because each delta is
/// applied to the freshly locked value, two bulk updates racing on the same row
/// compose instead of overwriting each other (no lost update). The whole batch
/// shares one transaction, so a failure on any property rolls back the batch.
pub async fn bulk_update_entity_property_options(
    pool: &Pool<Postgres>,
    entity_id: &str,
    entity_type: EntityType,
    updates: &[EntityPropertyOptionUpdate],
) -> anyhow::Result<Vec<EntityPropertyOptionSelection>> {
    let mut tx = pool.begin().await?;
    let mut selections = Vec::with_capacity(updates.len());

    // Acquire row locks in a consistent order across all callers so two bulk
    // updates touching the same properties in different orders can't deadlock.
    let mut ordered: Vec<&EntityPropertyOptionUpdate> = updates.iter().collect();
    ordered.sort_by_key(|update| update.property_definition_id);

    for update in ordered {
        super::property_option_queries::hold_selected_options(
            &mut tx,
            update.property_definition_id,
            &update.add_option_ids,
        )
        .await?;
        let has_additions = !update.add_option_ids.is_empty();

        // Attach the property only when adding options. A concurrent creator
        // blocks on the unique index here until it commits, after which this
        // insert is a no-op and the FOR UPDATE below sequences the two writers.
        if has_additions {
            let id = macro_uuid::generate_uuid_v7();
            sqlx::query!(
                r#"
                INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)
                VALUES (
                    $1, $2, $3, $4,
                    jsonb_build_object('type', 'SelectOption', 'value', '[]'::jsonb)
                )
                ON CONFLICT (entity_id, entity_type, property_definition_id) DO NOTHING
                "#,
                id,
                entity_id,
                entity_type as EntityType,
                update.property_definition_id,
            )
            .execute(&mut *tx)
            .await?;
        }

        // Lock the row (if any) and read the current stored value before diffing.
        let existing = sqlx::query_scalar!(
            r#"
            SELECT values as "values: serde_json::Value"
            FROM entity_properties
            WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3
            FOR UPDATE
            "#,
            entity_id,
            entity_type as EntityType,
            update.property_definition_id,
        )
        .fetch_optional(&mut *tx)
        .await?;

        let row_exists = existing.is_some();
        // The locked pre-write value doubles as the activity transition's
        // "from" side.
        let previous_value: Option<PropertyValue> = existing
            .flatten()
            .and_then(|value| serde_json::from_value(value).ok());
        let current_ids = match &previous_value {
            Some(PropertyValue::SelectOption(ids)) => ids.clone(),
            _ => Vec::new(),
        };

        let final_ids = apply_option_delta(
            current_ids,
            &update.add_option_ids,
            &update.remove_option_ids,
        );

        // Nothing to add and no row to remove from: a no-op, leave the DB alone.
        let mutation = if row_exists {
            let value_json = serde_json::json!({
                "type": "SelectOption",
                "value": final_ids,
            });
            let row = sqlx::query_as!(
                EntityPropertyMutationRow,
                r#"
                UPDATE entity_properties
                SET values = $4, updated_at = NOW()
                WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3
                RETURNING
                    id,
                    entity_id,
                    entity_type as "entity_type: EntityType",
                    property_definition_id,
                    values as "value: serde_json::Value",
                    NULL as "previous: serde_json::Value",
                    created_at,
                    updated_at
                "#,
                entity_id,
                entity_type as EntityType,
                update.property_definition_id,
                value_json,
            )
            .fetch_one(&mut *tx)
            .await?;
            // The FOR UPDATE read above is the authoritative pre-write value;
            // the query returns a NULL placeholder for it.
            let mut snapshot = row.into_snapshot()?;
            snapshot.previous_value = previous_value;
            Some(snapshot)
        } else {
            None
        };

        selections.push(EntityPropertyOptionSelection {
            property_definition_id: update.property_definition_id,
            option_ids: final_ids,
            mutation,
        });
    }

    tx.commit().await?;
    Ok(selections)
}

/// Apply an add/remove delta to a stored option-id list, keeping the order of
/// surviving options and appending new ones. An id named in both add and remove
/// is removed (removals win), matching a delta where the two sets are disjoint.
fn apply_option_delta(current: Vec<Uuid>, add: &[Uuid], remove: &[Uuid]) -> Vec<Uuid> {
    let remove_set: std::collections::HashSet<Uuid> = remove.iter().copied().collect();
    let mut result: Vec<Uuid> = current
        .into_iter()
        .filter(|id| !remove_set.contains(id))
        .collect();
    for id in add {
        if !remove_set.contains(id) && !result.contains(id) {
            result.push(*id);
        }
    }
    result
}

/// Counts how many of the provided option IDs exist for the property definition.
#[allow(clippy::disallowed_methods, reason = "legacy code. fix later")]
pub async fn count_valid_property_options(
    pool: &Pool<Postgres>,
    property_definition_id: Uuid,
    option_ids: &[Uuid],
) -> anyhow::Result<i64> {
    let count: (i64,) = sqlx::query_as(
        r#"
        SELECT COUNT(*) 
        FROM property_options 
        WHERE property_definition_id = $1
        AND id = ANY($2)
        "#,
    )
    .bind(property_definition_id)
    .bind(option_ids)
    .fetch_one(pool)
    .await?;

    Ok(count.0)
}

/// Deletes an entity property by its ID.
#[tracing::instrument(skip(pool))]
pub async fn delete_entity_property(
    pool: &Pool<Postgres>,
    entity_property_id: Uuid,
) -> anyhow::Result<()> {
    sqlx::query!(
        "DELETE FROM entity_properties WHERE id = $1",
        entity_property_id
    )
    .execute(pool)
    .await?;

    Ok(())
}

/// Deletes all properties attached to an entity.
#[tracing::instrument(skip(executor))]
pub async fn delete_entity_properties(
    executor: impl PgExecutor<'_>,
    entity_reference: &EntityReference,
) -> anyhow::Result<()> {
    sqlx::query!(
        "DELETE FROM entity_properties WHERE entity_id = $1 AND entity_type = $2",
        entity_reference.entity_id,
        entity_reference.entity_type as _,
    )
    .execute(executor)
    .await?;

    Ok(())
}