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.

feat(properties): properties kafka topic (#5224)

Will Hutchinsona65fe58eb723
diff --git a/.github/kafka-cluster-topics.json b/.github/kafka-cluster-topics.json
index 7318542b84..7ba9774f6c 100644
--- a/.github/kafka-cluster-topics.json
+++ b/.github/kafka-cluster-topics.json
@@ -8,6 +8,7 @@
"macro.example",
"macro.mentions",
"macro.projects",
+ "macro.properties",
"macro.soup",
"macro.teams",
"macro.webhooks"
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index 87f70fd639..34814fbe0c 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -1275,11 +1275,14 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/invite_email",
+ "crates/kafka_util",
"crates/last_online_tracker",
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_env",
"crates/macro_env_var",
+ "crates/macro_event_broker",
+ "crates/macro_event_topics",
"crates/macro_service_urls",
"crates/macro_user_id",
"crates/macro_uuid",
@@ -2929,11 +2932,14 @@
"crates/graphql_properties",
"crates/invite_email",
"crates/item_filters",
+ "crates/kafka_util",
"crates/last_online_tracker",
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_env",
"crates/macro_env_var",
+ "crates/macro_event_broker",
+ "crates/macro_event_topics",
"crates/macro_service_urls",
"crates/macro_user_id",
"crates/macro_uuid",
@@ -3118,11 +3124,14 @@
"crates/entity_access_db_utils",
"crates/import",
"crates/invite_email",
+ "crates/kafka_util",
"crates/last_online_tracker",
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_env",
"crates/macro_env_var",
+ "crates/macro_event_broker",
+ "crates/macro_event_topics",
"crates/macro_service_urls",
"crates/macro_user_id",
"crates/macro_uuid",
@@ -4363,11 +4372,14 @@
"crates/generic_email_domains",
"crates/import",
"crates/invite_email",
+ "crates/kafka_util",
"crates/last_online_tracker",
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_env",
"crates/macro_env_var",
+ "crates/macro_event_broker",
+ "crates/macro_event_topics",
"crates/macro_service_urls",
"crates/macro_user_id",
"crates/macro_uuid",
@@ -4610,11 +4622,14 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/invite_email",
+ "crates/kafka_util",
"crates/last_online_tracker",
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_env",
"crates/macro_env_var",
+ "crates/macro_event_broker",
+ "crates/macro_event_topics",
"crates/macro_service_urls",
"crates/macro_user_id",
"crates/macro_uuid",
@@ -4651,11 +4666,14 @@
"crates/entity_access",
"crates/entity_access_db_utils",
"crates/invite_email",
+ "crates/kafka_util",
"crates/last_online_tracker",
"crates/macro_auth",
"crates/macro_authorization",
"crates/macro_env",
"crates/macro_env_var",
+ "crates/macro_event_broker",
+ "crates/macro_event_topics",
"crates/macro_service_urls",
"crates/macro_user_id",
"crates/macro_uuid",
diff --git a/.sqlx/query-17abbeaf7ccbb5164cf1d29f7c553e34a9164ae5129763481771597a731cc25f.json b/.sqlx/query-17abbeaf7ccbb5164cf1d29f7c553e34a9164ae5129763481771597a731cc25f.json
deleted file mode 100644
index 3effad5d4c..0000000000
--- a/.sqlx/query-17abbeaf7ccbb5164cf1d29f7c553e34a9164ae5129763481771597a731cc25f.json
+++ /dev/null
@@ -1,34 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE entity_properties\n SET values = jsonb_set(\n values,\n '{value}',\n COALESCE(\n (\n SELECT jsonb_agg(elem)\n FROM jsonb_array_elements(values -> 'value') AS elem\n WHERE elem <> to_jsonb($4::text)\n ),\n '[]'::jsonb\n )\n ),\n updated_at = NOW()\n WHERE entity_id = $1\n AND entity_type = $2\n AND property_definition_id = $3\n AND values ->> 'type' = 'SelectOption'\n AND values -> 'value' @> jsonb_build_array($4::text)\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Text",
- {
- "Custom": {
- "name": "property_entity_type",
- "kind": {
- "Enum": [
- "CHANNEL",
- "CHAT",
- "DOCUMENT",
- "PROJECT",
- "THREAD",
- "USER",
- "COMPANY",
- "TASK",
- "CALL_RECORD"
- ]
- }
- }
- },
- "Uuid",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "17abbeaf7ccbb5164cf1d29f7c553e34a9164ae5129763481771597a731cc25f"
-}
diff --git a/.sqlx/query-5134eaf499b4af2b204e15c0679682ffc5177b8db9314042f145d8eb2526bde3.json b/.sqlx/query-5134eaf499b4af2b204e15c0679682ffc5177b8db9314042f145d8eb2526bde3.json
deleted file mode 100644
index 440caf8209..0000000000
--- a/.sqlx/query-5134eaf499b4af2b204e15c0679682ffc5177b8db9314042f145d8eb2526bde3.json
+++ /dev/null
@@ -1,34 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "\n UPDATE entity_properties\n SET values = $4, updated_at = NOW()\n WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3\n ",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Text",
- {
- "Custom": {
- "name": "property_entity_type",
- "kind": {
- "Enum": [
- "CHANNEL",
- "CHAT",
- "DOCUMENT",
- "PROJECT",
- "THREAD",
- "USER",
- "COMPANY",
- "TASK",
- "CALL_RECORD"
- ]
- }
- }
- },
- "Uuid",
- "Jsonb"
- ]
- },
- "nullable": []
- },
- "hash": "5134eaf499b4af2b204e15c0679682ffc5177b8db9314042f145d8eb2526bde3"
-}
diff --git a/.sqlx/query-55299a8cfe6d8e27bdd1f419daa0acc0f3dbaf2b8b4c88c4cac9aa4447664009.json b/.sqlx/query-55299a8cfe6d8e27bdd1f419daa0acc0f3dbaf2b8b4c88c4cac9aa4447664009.json
new file mode 100644
index 0000000000..b20cd00e77
--- /dev/null
+++ b/.sqlx/query-55299a8cfe6d8e27bdd1f419daa0acc0f3dbaf2b8b4c88c4cac9aa4447664009.json
@@ -0,0 +1,95 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE entity_properties\n SET values = $4, updated_at = NOW()\n WHERE entity_id = $1 AND entity_type = $2 AND property_definition_id = $3\n RETURNING\n id,\n entity_id,\n entity_type as \"entity_type: EntityType\",\n property_definition_id,\n values as \"value: serde_json::Value\",\n created_at,\n updated_at\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "entity_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "entity_type: EntityType",
+ "type_info": {
+ "Custom": {
+ "name": "property_entity_type",
+ "kind": {
+ "Enum": [
+ "CHANNEL",
+ "CHAT",
+ "DOCUMENT",
+ "PROJECT",
+ "THREAD",
+ "USER",
+ "COMPANY",
+ "TASK",
+ "CALL_RECORD"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 3,
+ "name": "property_definition_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "value: serde_json::Value",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ {
+ "Custom": {
+ "name": "property_entity_type",
+ "kind": {
+ "Enum": [
+ "CHANNEL",
+ "CHAT",
+ "DOCUMENT",
+ "PROJECT",
+ "THREAD",
+ "USER",
+ "COMPANY",
+ "TASK",
+ "CALL_RECORD"
+ ]
+ }
+ }
+ },
+ "Uuid",
+ "Jsonb"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "55299a8cfe6d8e27bdd1f419daa0acc0f3dbaf2b8b4c88c4cac9aa4447664009"
+}
diff --git a/.sqlx/query-c132d149b4610459f6c2ff333a128c8aa28e0bd9409ec0e9232f0edd27531887.json b/.sqlx/query-bee9a8c6f98a24b798c0a60184002169fde0953aa9371dc56a9481e4b8526110.json
similarity index 51%
rename from .sqlx/query-c132d149b4610459f6c2ff333a128c8aa28e0bd9409ec0e9232f0edd27531887.json
rename to .sqlx/query-bee9a8c6f98a24b798c0a60184002169fde0953aa9371dc56a9481e4b8526110.json
index c9784d61eb..d0ee7130af 100644
--- a/.sqlx/query-c132d149b4610459f6c2ff333a128c8aa28e0bd9409ec0e9232f0edd27531887.json
+++ b/.sqlx/query-bee9a8c6f98a24b798c0a60184002169fde0953aa9371dc56a9481e4b8526110.json
@@ -1,8 +1,61 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n VALUES (\n $1, $2, $3, $4,\n jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array($5::text))\n )\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET\n values = CASE\n WHEN entity_properties.values ->> 'type' = 'SelectOption'\n AND entity_properties.values -> 'value' @> jsonb_build_array($5::text)\n THEN entity_properties.values\n WHEN entity_properties.values ->> 'type' = 'SelectOption'\n THEN jsonb_set(\n entity_properties.values,\n '{value}',\n (entity_properties.values -> 'value') || jsonb_build_array($5::text)\n )\n ELSE jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array($5::text))\n END,\n updated_at = NOW()\n ",
+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n VALUES (\n $1, $2, $3, $4,\n jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array($5::text))\n )\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET\n values = CASE\n WHEN entity_properties.values ->> 'type' = 'SelectOption'\n AND entity_properties.values -> 'value' @> jsonb_build_array($5::text)\n THEN entity_properties.values\n WHEN entity_properties.values ->> 'type' = 'SelectOption'\n THEN jsonb_set(\n entity_properties.values,\n '{value}',\n (entity_properties.values -> 'value') || jsonb_build_array($5::text)\n )\n ELSE jsonb_build_object('type', 'SelectOption', 'value', jsonb_build_array($5::text))\n END,\n updated_at = NOW()\n RETURNING\n id,\n entity_id,\n entity_type as \"entity_type: EntityType\",\n property_definition_id,\n values as \"value: serde_json::Value\",\n created_at,\n updated_at\n ",
"describe": {
- "columns": [],
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "entity_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "entity_type: EntityType",
+ "type_info": {
+ "Custom": {
+ "name": "property_entity_type",
+ "kind": {
+ "Enum": [
+ "CHANNEL",
+ "CHAT",
+ "DOCUMENT",
+ "PROJECT",
+ "THREAD",
+ "USER",
+ "COMPANY",
+ "TASK",
+ "CALL_RECORD"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 3,
+ "name": "property_definition_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "value: serde_json::Value",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
"parameters": {
"Left": [
"Uuid",
@@ -29,7 +82,15 @@
"Text"
]
},
- "nullable": []
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ false
+ ]
},
- "hash": "c132d149b4610459f6c2ff333a128c8aa28e0bd9409ec0e9232f0edd27531887"
+ "hash": "bee9a8c6f98a24b798c0a60184002169fde0953aa9371dc56a9481e4b8526110"
}
diff --git a/.sqlx/query-e3ccac58c457d255e4af2af8f97f4e155410c45baa5a63b9420e8448317bf825.json b/.sqlx/query-e3ccac58c457d255e4af2af8f97f4e155410c45baa5a63b9420e8448317bf825.json
new file mode 100644
index 0000000000..01d2427d83
--- /dev/null
+++ b/.sqlx/query-e3ccac58c457d255e4af2af8f97f4e155410c45baa5a63b9420e8448317bf825.json
@@ -0,0 +1,95 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE entity_properties\n SET values = jsonb_set(\n values,\n '{value}',\n COALESCE(\n (\n SELECT jsonb_agg(elem)\n FROM jsonb_array_elements(values -> 'value') AS elem\n WHERE elem <> to_jsonb($4::text)\n ),\n '[]'::jsonb\n )\n ),\n updated_at = NOW()\n WHERE entity_id = $1\n AND entity_type = $2\n AND property_definition_id = $3\n AND values ->> 'type' = 'SelectOption'\n AND values -> 'value' @> jsonb_build_array($4::text)\n RETURNING\n id,\n entity_id,\n entity_type as \"entity_type: EntityType\",\n property_definition_id,\n values as \"value: serde_json::Value\",\n created_at,\n updated_at\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "entity_id",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "entity_type: EntityType",
+ "type_info": {
+ "Custom": {
+ "name": "property_entity_type",
+ "kind": {
+ "Enum": [
+ "CHANNEL",
+ "CHAT",
+ "DOCUMENT",
+ "PROJECT",
+ "THREAD",
+ "USER",
+ "COMPANY",
+ "TASK",
+ "CALL_RECORD"
+ ]
+ }
+ }
+ }
+ },
+ {
+ "ordinal": 3,
+ "name": "property_definition_id",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 4,
+ "name": "value: serde_json::Value",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 5,
+ "name": "created_at",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 6,
+ "name": "updated_at",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ {
+ "Custom": {
+ "name": "property_entity_type",
+ "kind": {
+ "Enum": [
+ "CHANNEL",
+ "CHAT",
+ "DOCUMENT",
+ "PROJECT",
+ "THREAD",
+ "USER",
+ "COMPANY",
+ "TASK",
+ "CALL_RECORD"
+ ]
+ }
+ }
+ },
+ "Uuid",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ true,
+ false,
+ false
+ ]
+ },
+ "hash": "e3ccac58c457d255e4af2af8f97f4e155410c45baa5a63b9420e8448317bf825"
+}
diff --git a/Cargo.lock b/Cargo.lock
index d39738bb28..514054e236 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -11281,6 +11281,8 @@ dependencies = [
"futures",
"macro_authorization",
"macro_db_migrator",
+ "macro_event_broker",
+ "macro_event_topics",
"macro_user_id",
"macro_uuid",
"mockall",
diff --git a/crates/macro_event_topics/src/lib.rs b/crates/macro_event_topics/src/lib.rs
index c05b08b2dd..7e9ad316e0 100644
--- a/crates/macro_event_topics/src/lib.rs
+++ b/crates/macro_event_topics/src/lib.rs
@@ -57,6 +57,8 @@ topics! {
MacroSoupRealtimeTopic => "macro.soup",
/// Project lifecycle events (created, updated, deleted, restored, permanently deleted, and uploaded).
MacroProjectsTopic => "macro.projects",
+ /// Property definition, option, and entity property value mutation events.
+ MacroPropertiesTopic => "macro.properties",
/// Team lifecycle, invite, and membership events.
MacroTeamsTopic => "macro.teams",
/// Channel lifecycle, message, participant, and attachment events.
diff --git a/crates/macro_event_topics/src/test.rs b/crates/macro_event_topics/src/test.rs
index 9960770730..a97147950c 100644
--- a/crates/macro_event_topics/src/test.rs
+++ b/crates/macro_event_topics/src/test.rs
@@ -21,6 +21,7 @@ fn all_topic_names_includes_declared_topics() {
assert!(all_topic_names().contains(&MacroDocumentsTopic::TOPIC_STR));
assert!(all_topic_names().contains(&MacroSoupRealtimeTopic::TOPIC_STR));
assert!(all_topic_names().contains(&MacroProjectsTopic::TOPIC_STR));
+ assert!(all_topic_names().contains(&MacroPropertiesTopic::TOPIC_STR));
assert!(all_topic_names().contains(&MacroTeamsTopic::TOPIC_STR));
assert!(all_topic_names().contains(&MacroChannelsTopic::TOPIC_STR));
assert!(all_topic_names().contains(&MacroBotsTopic::TOPIC_STR));
diff --git a/crates/properties/Cargo.toml b/crates/properties/Cargo.toml
index c13bba9b3a..6a45f4c910 100644
--- a/crates/properties/Cargo.toml
+++ b/crates/properties/Cargo.toml
@@ -9,7 +9,6 @@ ai_tools = [
"dep:ai_toolset",
"dep:async-trait",
"dep:schemars",
- "dep:serde",
"dep:serde_json",
"ports",
]
@@ -17,7 +16,6 @@ default = ["ai_tools", "inbound", "outbound", "ports"]
inbound = [
"dep:axum",
"dep:macro_authorization",
- "dep:serde",
"dep:serde_json",
"dep:tokio",
"dep:utoipa",
@@ -53,6 +51,8 @@ futures = { workspace = true, optional = true }
macro_authorization = { path = "../macro_authorization", default-features = false, features = [
"axum",
], optional = true }
+macro_event_broker = { path = "../macro_event_broker", default-features = false }
+macro_event_topics = { path = "../macro_event_topics" }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid", optional = true }
model-entity = { path = "../model-entity", optional = true }
@@ -61,7 +61,7 @@ models_permissions = { path = "../models_permissions", optional = true }
models_properties = { path = "../models_properties" }
notification = { path = "../notification", optional = true }
schemars = { workspace = true, optional = true }
-serde = { workspace = true, optional = true }
+serde = { workspace = true }
serde_json = { workspace = true, optional = true }
sqlx = { workspace = true, optional = true }
system_properties = { path = "../system_properties" }
diff --git a/crates/properties/README.md b/crates/properties/README.md
new file mode 100644
index 0000000000..71f25132d1
--- /dev/null
+++ b/crates/properties/README.md
@@ -0,0 +1,181 @@
+# Properties crate
+
+This crate owns property definitions, selectable options, entity property values,
+persistence ports, service policy, and the HTTP, GraphQL, and tool adapters for
+properties. Its broker-aware domain service also produces property mutation events
+after successful writes.
+
+## Properties event producer
+
+The events below use schema version 1 and are published to the
+`macro.properties` Kafka topic in the standard broker envelope:
+
+```json
+{
+ "event_id": "<uuidv7>",
+ "schema_version": 1,
+ "event_type": "<domain>.<action>",
+ "metadata": { "...": "typed fields described below" }
+}
+```
+
+The Kafka record key is not part of this JSON envelope. Every metadata object
+includes `actor_user_id`, which is a nullable Macro user ID. It identifies the
+authenticated user responsible for the mutation and is `null` for internal,
+machine, bot, or unauthenticated callers. In particular, document-deletion
+cleanup is an internal call and produces `entity_properties.cleared` with a null
+actor. Optional metadata fields are serialized as `null` unless their reused
+nested model specifies otherwise.
+
+| Event name | Emitted after | Metadata |
+| --- | --- | --- |
+| `property.created` | A property definition is persisted. A newly created TAG definition from `ensure_tag_set` also emits this event; the get-existing path does not. | `property_definition_id`, `actor_user_id`, `owner`, `display_name`, `data_type`, `is_multi_select`, `specific_entity_type`, `created_at` |
+| `property.deleted` | A property definition is deleted. | `property_definition_id`, `actor_user_id`, `owner`, `display_name`, `data_type` |
+| `property_option.created` | An option is added to a SELECT or TAG definition. | `option_id`, `property_definition_id`, `actor_user_id`, `value`, `color`, `display_order` |
+| `property_option.updated` | An option is renamed, recolored, or reordered. The metadata is the full post-update state, not a delta. | `option_id`, `property_definition_id`, `actor_user_id`, `value`, `color`, `display_order` |
+| `property_option.deleted` | An option is deleted. `value` is the pre-delete snapshot. | `option_id`, `property_definition_id`, `actor_user_id`, `value` |
+| `entity_property.updated` | An entity value is set, replaced, attached with a null value, or changed by an option add/remove. Bulk operations emit one event for each actual `(entity, property_definition)` mutation. | `entity_property_id`, `entity_id`, `entity_type`, `property_definition_id`, `actor_user_id`, `value`, `updated_at` |
+| `entity_property.deleted` | One entity-property row is deleted. | `entity_property_id`, `entity_id`, `entity_type`, `property_definition_id`, `actor_user_id` |
+| `entity_properties.cleared` | `delete_entity_properties` successfully wipes all property values for an entity, including the document-deletion path. One clear event replaces per-value deletion events. | `entity_id`, `entity_type`, `actor_user_id` |
+
+`entity_property.updated.value` is the complete new value and may be `null` when
+the row remains attached without a value. UUID and timestamp fields serialize as
+strings.
+
+### Keys and ordering
+
+Keys are exact, bare ID strings with no domain prefix:
+
+- Definition and option records use the bare `property_definition_id` UUID, for
+ example `3f6f8b0a-6f9f-4a3f-9c3a-2b1e5d4c7a90`, not
+ `property|3f6f8b0a-6f9f-4a3f-9c3a-2b1e5d4c7a90`.
+- Entity-property records use the bare `entity_id` string, not an
+ `entity|<id>` or `<entity_type>|<id>` value.
+
+Definition creation, its option mutations, and definition deletion therefore
+retain per-definition ordering. All property value mutations for one entity
+retain per-entity ordering, even when they concern different definitions.
+
+There is no ordering guarantee between definition-keyed records and
+entity-keyed records. A consumer may observe an `entity_property.updated`
+referencing a definition before or after that definition's lifecycle event.
+There is likewise no ordering guarantee across different definition IDs or
+across different entity IDs.
+
+## Wire representations
+
+The event types directly reuse `DataType`, `EntityType`, `PropertyOwner`,
+`PropertyValue`, and `PropertyOptionValue` from `models_properties`. Their serde
+representations are public wire-contract dependencies. Changes to those model
+representations must therefore be treated as changes to the Kafka contract, not
+as crate-internal refactors.
+
+The current representations include:
+
+- `DataType` and `EntityType` as `SCREAMING_SNAKE_CASE` strings, such as
+ `"SELECT_STRING"`, `"TAG"`, `"DOCUMENT"`, and `"TASK"`.
+- `PropertyOwner` as an internally tagged object:
+ `{"scope":"user","user_id":"macro|[email protected]"}`,
+ `{"scope":"team","team_id":"<uuid>"}`, or `{"scope":"system"}`.
+- `PropertyOptionValue` as `{"type":"string","value":"..."}` or
+ `{"type":"number","value":42.5}`.
+- `PropertyValue` as a `type`/`value` object. Its type names are `Boolean`,
+ `Number`, `String`, `Date`, `SelectOption`, `EntityReference`, and `Link`.
+ Select options, entity references, and links use arrays as defined by
+ `models_properties`, including for single-select values.
+
+Consumers should use these exact representations rather than independently
+normalizing enum names or tagged-union shapes.
+
+## Sanitization and data handling
+
+Payloads intentionally contain property metadata and complete property values.
+Property display names, string option values, string property values, and link
+values can contain user-authored text. `actor_user_id`, user-scoped
+`owner.user_id`, and user entity references such as task assignees can contain
+Macro user IDs serialized as `macro|<email address>` and must be handled as
+personal data.
+
+The producer does not redact those contract fields. Its sanitization boundary
+excludes document and message content, authentication material, secrets, and
+billing identifiers; it does not make property names, options, values, entity
+references, or actor identities non-sensitive. Consumers must apply storage,
+logging, and access controls appropriate for PII and user-authored values.
+
+## Implied mutations and known gaps
+
+Definition and option deletion have effects beyond the single event:
+
+- `property.deleted` implies removal of every option and every entity-property
+ value under that definition. The database cascade does not emit
+ `property_option.deleted` or per-entity deletion events.
+- `property_option.deleted` implies that the option ID was stripped from every
+ entity value that referenced it. This does not fan out
+ `entity_property.updated` records.
+
+Consumers maintaining derived state must apply these implications. Definition
+and entity records use different keys, so the lack of cross-key ordering also
+applies while handling these cascades.
+
+Parent Task and Subtasks writes update reciprocal task relationships in the
+same transaction. Version 1 emits `entity_property.updated` only for the entity
+targeted by the API call; it omits a separate event for each reciprocally
+updated task.
+
+There is no `property.updated` event because no endpoint currently edits a
+property definition. A future definition-edit operation can add that event as a
+forward-compatible enum variant. TAG definition creation uses
+`property.created`; there is no separate `tag_set.created` event.
+
+The launch is producer-only. No `macro.properties` consumer ships in this
+repository change.
+
+## Producer composition
+
+The document storage service (DSS) is the broker-aware production composition.
+Its shared `PropertiesServiceImpl` publishes for DSS REST and GraphQL writes,
+task-property adapter writes, and document-deletion cleanup.
+
+`PropertiesServiceImpl` defaults to `NoopMacroEventBroker` when a composition
+does not call `with_event_broker`. The following composition sites retain that
+no-op default and do not publish property events:
+
+- `crates/properties_service/src/api/context.rs` omits the broker generic from
+ its concrete `PropertiesService` alias.
+- `crates/ai_tools/src/tool_context.rs` omits the broker generic from
+ `ToolPropertiesService`, and `build_properties_service` does not attach a
+ broker. Property and task-property writes through contexts built there,
+ including document cognition, MCP, memory, and the shared AI tool context,
+ therefore do not publish.
+
+These are explicit producer coverage boundaries, not fallback delivery paths.
+
+## Delivery semantics and compatibility
+
+Publication is scheduled after the relevant database mutation commits and is
+fire-and-forget. Scheduling or Kafka publication failure is logged without
+rolling back the mutation or failing an otherwise successful request. There is
+no transactional outbox and no retry coupling persistence to publication.
+Producer delivery is therefore at-most-once relative to mutations: a committed
+mutation can have no corresponding event.
+
+Kafka consumers commonly receive at-least-once delivery when they commit an
+offset only after successful processing. Consumers must be idempotent under
+redelivery and downstream retries. They can use `event_id` for deduplication and
+should make full-state updates and deletion implications safe to apply more than
+once. Consumers requiring strong consistency must reconcile against the source
+API or database because the producer cannot guarantee an event for every
+commit.
+
+Consumers must check `schema_version` before interpreting a known event. Every
+event documented here currently uses version 1. To remain forward compatible,
+consumers must tolerate unknown `event_type` values and ignore unknown metadata
+fields; additive event variants and fields do not require a version change.
+
+## Rollout
+
+Provision `macro.properties` before or alongside deploying DSS. Deploy the
+Kafka cluster stack so it consumes the regenerated
+`.github/kafka-cluster-topics.json`, then deploy DSS in the same release or
+afterward. If DSS starts producing before the topic is available, mutations
+still succeed but events may be lost under the at-most-once contract.
diff --git a/crates/properties/src/domain.rs b/crates/properties/src/domain.rs
index 63f50f1e03..0d4561eb5c 100644
--- a/crates/properties/src/domain.rs
+++ b/crates/properties/src/domain.rs
@@ -1,4 +1,5 @@
pub mod error;
+pub mod events;
pub mod metadata;
pub mod model;
pub mod ports;
diff --git a/crates/properties/src/domain/events.rs b/crates/properties/src/domain/events.rs
new file mode 100644
index 0000000000..b634cb16a1
--- /dev/null
+++ b/crates/properties/src/domain/events.rs
@@ -0,0 +1,277 @@
+//! Kafka event models for the `macro.properties` topic.
+//!
+//! Property definition and option events are keyed by property definition id.
+//! Entity property events are keyed by entity id to preserve per-entity ordering.
+
+#[cfg(test)]
+mod test;
+
+use chrono::{DateTime, Utc};
+use macro_event_broker::{Event, MacroEvent, TopicEvent};
+use macro_event_topics::MacroPropertiesTopic;
+use macro_user_id::user_id::MacroUserIdStr;
+use models_properties::service::property_option::PropertyOptionValue;
+use models_properties::service::property_value::PropertyValue;
+use models_properties::{DataType, EntityType, PropertyOwner};
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+/// Metadata for [`PropertyTopicEvent::Created`].
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct PropertyCreatedMetadata {
+ /// Identifier of the created property definition.
+ pub property_definition_id: Uuid,
+ /// Authenticated user who created the property, or `None` for a system operation.
+ pub actor_user_id: Option<MacroUserIdStr<'static>>,
+ /// Scope that owns the property definition.
+ pub owner: PropertyOwner,
+ /// Human-readable property name.
+ pub display_name: String,
+ /// Data type accepted by the property.
+ pub data_type: DataType,
+ /// Whether the property accepts multiple values.
+ pub is_multi_select: bool,
+ /// Entity type accepted by an entity-reference property.
+ pub specific_entity_type: Option<EntityType>,
+ /// Time the property definition was created.
+ pub created_at: DateTime<Utc>,
+}
+
+/// Metadata for [`PropertyTopicEvent::Deleted`].
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct PropertyDeletedMetadata {
+ /// Identifier of the deleted property definition.
+ pub property_definition_id: Uuid,
+ /// Authenticated user who deleted the property, or `None` for a system operation.
+ pub actor_user_id: Option<MacroUserIdStr<'static>>,
+ /// Scope that owned the property definition.
+ pub owner: PropertyOwner,
+ /// Property name at deletion time.
+ pub display_name: String,
+ /// Property data type at deletion time.
+ pub data_type: DataType,
+}
+
+/// Metadata for [`PropertyTopicEvent::OptionCreated`].
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct PropertyOptionCreatedMetadata {
+ /// Identifier of the created option.
+ pub option_id: Uuid,
+ /// Identifier of the option's property definition.
+ pub property_definition_id: Uuid,
+ /// Authenticated user who created the option, or `None` for a system operation.
+ pub actor_user_id: Option<MacroUserIdStr<'static>>,
+ /// Selectable option value.
+ pub value: PropertyOptionValue,
+ /// Optional hexadecimal display color.
+ pub color: Option<String>,
+ /// Option ordering position.
+ pub display_order: i32,
+}
+
+/// Metadata for [`PropertyTopicEvent::OptionUpdated`].
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct PropertyOptionUpdatedMetadata {
+ /// Identifier of the updated option.
+ pub option_id: Uuid,
+ /// Identifier of the option's property definition.
+ pub property_definition_id: Uuid,
+ /// Authenticated user who updated the option, or `None` for a system operation.
+ pub actor_user_id: Option<MacroUserIdStr<'static>>,
+ /// Full option value after the update.
+ pub value: PropertyOptionValue,
+ /// Full optional display color after the update.
+ pub color: Option<String>,
+ /// Full ordering position after the update.
+ pub display_order: i32,
+}
+
+/// Metadata for [`PropertyTopicEvent::OptionDeleted`].
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct PropertyOptionDeletedMetadata {
+ /// Identifier of the deleted option.
+ pub option_id: Uuid,
+ /// Identifier of the option's property definition.
+ pub property_definition_id: Uuid,
+ /// Authenticated user who deleted the option, or `None` for a system operation.
+ pub actor_user_id: Option<MacroUserIdStr<'static>>,
+ /// Option value at deletion time.
+ pub value: PropertyOptionValue,
+}
+
+/// Metadata for [`PropertyTopicEvent::EntityPropertyUpdated`].
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct EntityPropertyUpdatedMetadata {
+ /// Identifier of the entity-property row.
+ pub entity_property_id: Uuid,
+ /// Identifier of the entity whose property changed.
+ pub entity_id: String,
+ /// Type of the entity whose property changed.
+ pub entity_type: EntityType,
+ /// Identifier of the property definition.
+ pub property_definition_id: Uuid,
+ /// Authenticated user who changed the value, or `None` for a system operation.
+ pub actor_user_id: Option<MacroUserIdStr<'static>>,
+ /// Full value after the update, or `None` when cleared without deleting the row.
+ pub value: Option<PropertyValue>,
+ /// Time the entity-property row was updated.
+ pub updated_at: DateTime<Utc>,
+}
+
+/// Metadata for [`PropertyTopicEvent::EntityPropertyDeleted`].
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct EntityPropertyDeletedMetadata {
+ /// Identifier of the deleted entity-property row.
+ pub entity_property_id: Uuid,
+ /// Identifier of the entity whose property was deleted.
+ pub entity_id: String,
+ /// Type of the entity whose property was deleted.
+ pub entity_type: EntityType,
+ /// Identifier of the property definition.
+ pub property_definition_id: Uuid,
+ /// Authenticated user who deleted the value, or `None` for a system operation.
+ pub actor_user_id: Option<MacroUserIdStr<'static>>,
+}
+
+/// Metadata for [`PropertyTopicEvent::EntityPropertiesCleared`].
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct EntityPropertiesClearedMetadata {
+ /// Identifier of the entity whose properties were cleared.
+ pub entity_id: String,
+ /// Type of the entity whose properties were cleared.
+ pub entity_type: EntityType,
+ /// Authenticated user who cleared the values, or `None` for a system operation.
+ pub actor_user_id: Option<MacroUserIdStr<'static>>,
+}
+
+/// Property mutation events published to [`MacroPropertiesTopic`].
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+#[serde(tag = "event_type", content = "metadata")]
+pub enum PropertyTopicEvent {
+ /// A property definition was created.
+ #[serde(rename = "property.created")]
+ Created(PropertyCreatedMetadata),
+ /// A property definition was deleted.
+ #[serde(rename = "property.deleted")]
+ Deleted(PropertyDeletedMetadata),
+ /// A property option was created.
+ #[serde(rename = "property_option.created")]
+ OptionCreated(PropertyOptionCreatedMetadata),
+ /// A property option was updated.
+ #[serde(rename = "property_option.updated")]
+ OptionUpdated(PropertyOptionUpdatedMetadata),
+ /// A property option was deleted.
+ #[serde(rename = "property_option.deleted")]
+ OptionDeleted(PropertyOptionDeletedMetadata),
+ /// An entity's property value was updated.
+ #[serde(rename = "entity_property.updated")]
+ EntityPropertyUpdated(EntityPropertyUpdatedMetadata),
+ /// An entity's property value was deleted.
+ #[serde(rename = "entity_property.deleted")]
+ EntityPropertyDeleted(EntityPropertyDeletedMetadata),
+ /// All property values on an entity were cleared.
+ #[serde(rename = "entity_properties.cleared")]
+ EntityPropertiesCleared(EntityPropertiesClearedMetadata),
+}
+
+impl TopicEvent for PropertyTopicEvent {
+ type Topic = MacroPropertiesTopic;
+
+ const SCHEMA_VERSION: u8 = 1;
+}
+
+/// Publishable event for [`MacroPropertiesTopic`].
+pub struct PropertyMacroEvent {
+ key: String,
+ event: Event<PropertyTopicEvent>,
+}
+
+impl PropertyMacroEvent {
+ /// Build a property-created event keyed by the bare property definition id.
+ pub fn created(metadata: PropertyCreatedMetadata) -> Self {
+ Self::new(
+ metadata.property_definition_id.to_string(),
+ PropertyTopicEvent::Created(metadata),
+ )
+ }
+
+ /// Build a property-deleted event keyed by the bare property definition id.
+ pub fn deleted(metadata: PropertyDeletedMetadata) -> Self {
+ Self::new(
+ metadata.property_definition_id.to_string(),
+ PropertyTopicEvent::Deleted(metadata),
+ )
+ }
+
+ /// Build an option-created event keyed by the bare property definition id.
+ pub fn property_option_created(metadata: PropertyOptionCreatedMetadata) -> Self {
+ Self::new(
+ metadata.property_definition_id.to_string(),
+ PropertyTopicEvent::OptionCreated(metadata),
+ )
+ }
+
+ /// Build an option-updated event keyed by the bare property definition id.
+ pub fn property_option_updated(metadata: PropertyOptionUpdatedMetadata) -> Self {
+ Self::new(
+ metadata.property_definition_id.to_string(),
+ PropertyTopicEvent::OptionUpdated(metadata),
+ )
+ }
+
+ /// Build an option-deleted event keyed by the bare property definition id.
+ pub fn property_option_deleted(metadata: PropertyOptionDeletedMetadata) -> Self {
+ Self::new(
+ metadata.property_definition_id.to_string(),
+ PropertyTopicEvent::OptionDeleted(metadata),
+ )
+ }
+
+ /// Build an entity-property-updated event keyed by the bare entity id.
+ pub fn entity_property_updated(metadata: EntityPropertyUpdatedMetadata) -> Self {
+ Self::new(
+ metadata.entity_id.clone(),
+ PropertyTopicEvent::EntityPropertyUpdated(metadata),
+ )
+ }
+
+ /// Build an entity-property-deleted event keyed by the bare entity id.
+ pub fn entity_property_deleted(metadata: EntityPropertyDeletedMetadata) -> Self {
+ Self::new(
+ metadata.entity_id.clone(),
+ PropertyTopicEvent::EntityPropertyDeleted(metadata),
+ )
+ }
+
+ /// Build an entity-properties-cleared event keyed by the bare entity id.
+ pub fn entity_properties_cleared(metadata: EntityPropertiesClearedMetadata) -> Self {
+ Self::new(
+ metadata.entity_id.clone(),
+ PropertyTopicEvent::EntityPropertiesCleared(metadata),
+ )
+ }
+
+ fn new(key: String, event: PropertyTopicEvent) -> Self {
+ Self::with_event(key, Event::new(event))
+ }
+
+ fn with_event(key: String, event: Event<PropertyTopicEvent>) -> Self {
+ Self { key, event }
+ }
+}
+
+impl MacroEvent for PropertyMacroEvent {
+ type EventPayload = PropertyTopicEvent;
+
+ fn key(&self) -> &str {
+ &self.key
+ }
+
+ fn event(&self) -> &Event<Self::EventPayload> {
+ &self.event
+ }
+
+ fn from_event(key: String, event: Event<Self::EventPayload>) -> Self {
+ Self::with_event(key, event)
+ }
+}
diff --git a/crates/properties/src/domain/events/test.rs b/crates/properties/src/domain/events/test.rs
new file mode 100644
index 0000000000..305940cde0
--- /dev/null
+++ b/crates/properties/src/domain/events/test.rs
@@ -0,0 +1,352 @@
+use macro_event_broker::{Event, MacroEvent};
+use macro_event_topics::{MacroPropertiesTopic, Topic};
+use serde_json::{Value, json};
+
+use super::*;
+
+const PROPERTY_DEFINITION_ID: &str = "6e95d5f0-2bb8-4c0a-ae01-197301fdb56e";
+const OPTION_ID: &str = "8a123d67-074f-4666-b3aa-214f99e7eb85";
+const ENTITY_PROPERTY_ID: &str = "bb672788-40c1-47d1-a2e1-565d20fe40ef";
+const TEAM_ID: &str = "94badb72-b7f7-46e4-89fb-497527836152";
+const ENTITY_ID: &str = "document-bare-id";
+const EVENT_ID: &str = "01998a30-1a2b-7c3d-9e4f-5a6b7c8d9e0f";
+const CREATED_AT: &str = "2026-07-27T18:30:00Z";
+const UPDATED_AT: &str = "2026-07-27T18:45:00Z";
+
+fn uuid(value: &str) -> Uuid {
+ Uuid::parse_str(value).expect("valid uuid")
+}
+
+fn timestamp(value: &str) -> DateTime<Utc> {
+ value.parse().expect("valid timestamp")
+}
+
+fn user_id(value: &str) -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from(value.to_string()).expect("valid user id")
+}
+
+fn topic_events(
+ actor_user_id: Option<MacroUserIdStr<'static>>,
+) -> Vec<(PropertyTopicEvent, Value)> {
+ let actor_json = serde_json::to_value(&actor_user_id).expect("serializable actor");
+
+ vec![
+ (
+ PropertyTopicEvent::Created(PropertyCreatedMetadata {
+ property_definition_id: uuid(PROPERTY_DEFINITION_ID),
+ actor_user_id: actor_user_id.clone(),
+ owner: PropertyOwner::User {
+ user_id: "macro|[email protected]".to_string(),
+ },
+ display_name: "Related task".to_string(),
+ data_type: DataType::Entity,
+ is_multi_select: false,
+ specific_entity_type: Some(EntityType::Task),
+ created_at: timestamp(CREATED_AT),
+ }),
+ json!({
+ "event_type": "property.created",
+ "metadata": {
+ "property_definition_id": PROPERTY_DEFINITION_ID,
+ "actor_user_id": actor_json.clone(),
+ "owner": {
+ "scope": "user",
+ "user_id": "macro|[email protected]"
+ },
+ "display_name": "Related task",
+ "data_type": "ENTITY",
+ "is_multi_select": false,
+ "specific_entity_type": "TASK",
+ "created_at": CREATED_AT
+ }
+ }),
+ ),
+ (
+ PropertyTopicEvent::Deleted(PropertyDeletedMetadata {
+ property_definition_id: uuid(PROPERTY_DEFINITION_ID),
+ actor_user_id: actor_user_id.clone(),
+ owner: PropertyOwner::Team {
+ team_id: uuid(TEAM_ID),
+ },
+ display_name: "Priority".to_string(),
+ data_type: DataType::SelectString,
+ }),
+ json!({
+ "event_type": "property.deleted",
+ "metadata": {
+ "property_definition_id": PROPERTY_DEFINITION_ID,
+ "actor_user_id": actor_json.clone(),
+ "owner": {
+ "scope": "team",
+ "team_id": TEAM_ID
+ },
+ "display_name": "Priority",
+ "data_type": "SELECT_STRING"
+ }
+ }),
+ ),
+ (
+ PropertyTopicEvent::OptionCreated(PropertyOptionCreatedMetadata {
+ option_id: uuid(OPTION_ID),
+ property_definition_id: uuid(PROPERTY_DEFINITION_ID),
+ actor_user_id: actor_user_id.clone(),
+ value: PropertyOptionValue::String("High".to_string()),
+ color: Some("#FF0000".to_string()),
+ display_order: 10,
+ }),
+ json!({
+ "event_type": "property_option.created",
+ "metadata": {
+ "option_id": OPTION_ID,
+ "property_definition_id": PROPERTY_DEFINITION_ID,
+ "actor_user_id": actor_json.clone(),
+ "value": {
+ "type": "string",
+ "value": "High"
+ },
+ "color": "#FF0000",
+ "display_order": 10
+ }
+ }),
+ ),
+ (
+ PropertyTopicEvent::OptionUpdated(PropertyOptionUpdatedMetadata {
+ option_id: uuid(OPTION_ID),
+ property_definition_id: uuid(PROPERTY_DEFINITION_ID),
+ actor_user_id: actor_user_id.clone(),
+ value: PropertyOptionValue::Number(42.5),
+ color: None,
+ display_order: 20,
+ }),
+ json!({
+ "event_type": "property_option.updated",
+ "metadata": {
+ "option_id": OPTION_ID,
+ "property_definition_id": PROPERTY_DEFINITION_ID,
+ "actor_user_id": actor_json.clone(),
+ "value": {
+ "type": "number",
+ "value": 42.5
+ },
+ "color": null,
+ "display_order": 20
+ }
+ }),
+ ),
+ (
+ PropertyTopicEvent::OptionDeleted(PropertyOptionDeletedMetadata {
+ option_id: uuid(OPTION_ID),
+ property_definition_id: uuid(PROPERTY_DEFINITION_ID),
+ actor_user_id: actor_user_id.clone(),
+ value: PropertyOptionValue::String("Retired".to_string()),
+ }),
+ json!({
+ "event_type": "property_option.deleted",
+ "metadata": {
+ "option_id": OPTION_ID,
+ "property_definition_id": PROPERTY_DEFINITION_ID,
+ "actor_user_id": actor_json.clone(),
+ "value": {
+ "type": "string",
+ "value": "Retired"
+ }
+ }
+ }),
+ ),
+ (
+ PropertyTopicEvent::EntityPropertyUpdated(EntityPropertyUpdatedMetadata {
+ entity_property_id: uuid(ENTITY_PROPERTY_ID),
+ entity_id: ENTITY_ID.to_string(),
+ entity_type: EntityType::Document,
+ property_definition_id: uuid(PROPERTY_DEFINITION_ID),
+ actor_user_id: actor_user_id.clone(),
+ value: Some(PropertyValue::SelectOption(vec![uuid(OPTION_ID)])),
+ updated_at: timestamp(UPDATED_AT),
+ }),
+ json!({
+ "event_type": "entity_property.updated",
+ "metadata": {
+ "entity_property_id": ENTITY_PROPERTY_ID,
+ "entity_id": ENTITY_ID,
+ "entity_type": "DOCUMENT",
+ "property_definition_id": PROPERTY_DEFINITION_ID,
+ "actor_user_id": actor_json.clone(),
+ "value": {
+ "type": "SelectOption",
+ "value": [OPTION_ID]
+ },
+ "updated_at": UPDATED_AT
+ }
+ }),
+ ),
+ (
+ PropertyTopicEvent::EntityPropertyDeleted(EntityPropertyDeletedMetadata {
+ entity_property_id: uuid(ENTITY_PROPERTY_ID),
+ entity_id: ENTITY_ID.to_string(),
+ entity_type: EntityType::Document,
+ property_definition_id: uuid(PROPERTY_DEFINITION_ID),
+ actor_user_id: actor_user_id.clone(),
+ }),
+ json!({
+ "event_type": "entity_property.deleted",
+ "metadata": {
+ "entity_property_id": ENTITY_PROPERTY_ID,
+ "entity_id": ENTITY_ID,
+ "entity_type": "DOCUMENT",
+ "property_definition_id": PROPERTY_DEFINITION_ID,
+ "actor_user_id": actor_json.clone()
+ }
+ }),
+ ),
+ (
+ PropertyTopicEvent::EntityPropertiesCleared(EntityPropertiesClearedMetadata {
+ entity_id: ENTITY_ID.to_string(),
+ entity_type: EntityType::Document,
+ actor_user_id,
+ }),
+ json!({
+ "event_type": "entity_properties.cleared",
+ "metadata": {
+ "entity_id": ENTITY_ID,
+ "entity_type": "DOCUMENT",
+ "actor_user_id": actor_json
+ }
+ }),
+ ),
+ ]
+}
+
+fn macro_events() -> Vec<(PropertyMacroEvent, &'static str)> {
+ topic_events(Some(user_id("macro|[email protected]")))
+ .into_iter()
+ .map(|(event, _)| match event {
+ PropertyTopicEvent::Created(metadata) => (
+ PropertyMacroEvent::created(metadata),
+ PROPERTY_DEFINITION_ID,
+ ),
+ PropertyTopicEvent::Deleted(metadata) => (
+ PropertyMacroEvent::deleted(metadata),
+ PROPERTY_DEFINITION_ID,
+ ),
+ PropertyTopicEvent::OptionCreated(metadata) => (
+ PropertyMacroEvent::property_option_created(metadata),
+ PROPERTY_DEFINITION_ID,
+ ),
+ PropertyTopicEvent::OptionUpdated(metadata) => (
+ PropertyMacroEvent::property_option_updated(metadata),
+ PROPERTY_DEFINITION_ID,
+ ),
+ PropertyTopicEvent::OptionDeleted(metadata) => (
+ PropertyMacroEvent::property_option_deleted(metadata),
+ PROPERTY_DEFINITION_ID,
+ ),
+ PropertyTopicEvent::EntityPropertyUpdated(metadata) => (
+ PropertyMacroEvent::entity_property_updated(metadata),
+ ENTITY_ID,
+ ),
+ PropertyTopicEvent::EntityPropertyDeleted(metadata) => (
+ PropertyMacroEvent::entity_property_deleted(metadata),
+ ENTITY_ID,
+ ),
+ PropertyTopicEvent::EntityPropertiesCleared(metadata) => (
+ PropertyMacroEvent::entity_properties_cleared(metadata),
+ ENTITY_ID,
+ ),
+ })
+ .collect()
+}
+
+#[test]
+fn every_variant_has_exact_json_envelope() {
+ let event_id = uuid(EVENT_ID);
+
+ for (event, expected_payload) in topic_events(Some(user_id("macro|[email protected]"))) {
+ let mut expected = expected_payload;
+ let object = expected.as_object_mut().expect("expected object");
+ object.insert("event_id".to_string(), json!(EVENT_ID));
+ object.insert("schema_version".to_string(), json!(1));
+
+ assert_eq!(
+ serde_json::to_value(Event::with_event_id(event_id, event))
+ .expect("serializable event"),
+ expected
+ );
+ }
+}
+
+#[test]
+fn every_variant_round_trips() {
+ for (original, expected_key) in macro_events() {
+ let payload = serde_json::to_vec(original.event()).expect("serializable event");
+ let decoded =
+ PropertyMacroEvent::decode(original.key(), &payload).expect("decodable event");
+
+ assert_eq!(decoded.key(), expected_key);
+ assert_eq!(decoded.event(), original.event());
+ assert_eq!(decoded.topic(), MacroPropertiesTopic::TOPIC_STR);
+ assert_eq!(decoded.topic(), "macro.properties");
+ }
+}
+
+#[test]
+fn constructors_use_exact_bare_keys_topic_and_schema_version() {
+ for (event, expected_key) in macro_events() {
+ assert_eq!(event.key(), expected_key);
+ assert_eq!(event.topic(), "macro.properties");
+ assert_eq!(event.event().schema_version, 1);
+ }
+}
+
+#[test]
+fn every_variant_supports_a_null_actor() {
+ for (event, expected) in topic_events(None) {
+ let serialized = serde_json::to_value(&event).expect("serializable event");
+
+ assert_eq!(serialized, expected);
+ assert_eq!(serialized["metadata"]["actor_user_id"], Value::Null);
+ assert_eq!(
+ serde_json::from_value::<PropertyTopicEvent>(serialized).expect("decodable event"),
+ event
+ );
+ }
+}
+
+#[test]
+fn shared_owner_and_value_types_keep_exact_wire_representations() {
+ let owner_representations = [
+ (
+ PropertyOwner::User {
+ user_id: "macro|[email protected]".to_string(),
+ },
+ json!({"scope": "user", "user_id": "macro|[email protected]"}),
+ ),
+ (
+ PropertyOwner::Team {
+ team_id: uuid(TEAM_ID),
+ },
+ json!({"scope": "team", "team_id": TEAM_ID}),
+ ),
+ (PropertyOwner::System, json!({"scope": "system"})),
+ ];
+
+ for (owner, expected) in owner_representations {
+ assert_eq!(serde_json::to_value(owner).unwrap(), expected);
+ }
+
+ assert_eq!(
+ serde_json::to_value(PropertyOptionValue::String("High".to_string())).unwrap(),
+ json!({"type": "string", "value": "High"})
+ );
+ assert_eq!(
+ serde_json::to_value(PropertyOptionValue::Number(42.5)).unwrap(),
+ json!({"type": "number", "value": 42.5})
+ );
+ assert_eq!(
+ serde_json::to_value(PropertyValue::SelectOption(vec![uuid(OPTION_ID)])).unwrap(),
+ json!({"type": "SelectOption", "value": [OPTION_ID]})
+ );
+ assert_eq!(
+ serde_json::to_value(PropertyValue::Str("free text".to_string())).unwrap(),
+ json!({"type": "String", "value": "free text"})
+ );
+}
diff --git a/crates/properties/src/domain/model.rs b/crates/properties/src/domain/model.rs
index c02c8e05fb..eaec4f59ca 100644
--- a/crates/properties/src/domain/model.rs
+++ b/crates/properties/src/domain/model.rs
@@ -5,6 +5,7 @@ use entity_access::domain::models::{
RequiredPermission, ViewAccessLevel,
};
use macro_user_id::user_id::MacroUserIdStr;
+use models_properties::service::entity_property::EntityProperty;
use models_properties::service::property_definition::PropertyDefinition;
use models_properties::service::property_option::{PropertyOption, PropertyOptionValue};
use models_properties::service::property_value::PropertyValue;
@@ -154,6 +155,15 @@ impl<'a> PropertyDefinitionOwner<'a> {
}
}
+/// Result of getting or creating an owner's tag definition.
+#[derive(Debug, Clone)]
+pub struct GetOrCreateTagDefinitionResult {
+ /// The owner's tag property definition.
+ pub definition: PropertyDefinition,
+ /// Whether this operation created the definition.
+ pub created: bool,
+}
+
/// Which owner a tag set belongs to.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TagScope {
@@ -191,6 +201,19 @@ pub struct EntityPropertyOptionUpdate {
pub remove_option_ids: Vec<Uuid>,
}
+/// The full persisted state of an entity property after a mutation.
+///
+/// This is an internal persistence receipt used for post-commit side effects;
+/// it is not part of the service or HTTP response contract.
+#[doc(hidden)]
+#[derive(Debug, Clone)]
+pub struct EntityPropertyMutationSnapshot {
+ /// The canonical persisted entity-property assignment.
+ pub property: EntityProperty,
+ /// The complete value after the mutation.
+ pub value: Option<PropertyValue>,
+}
+
/// The reconciled final option ids for one property after a bulk update. The
/// caller uses these to reconcile its cache with the value the server actually
/// persisted (which may differ from the requested delta if a concurrent edit
@@ -201,6 +224,12 @@ pub struct EntityPropertyOptionSelection {
pub property_definition_id: Uuid,
/// The final option ids stored for the entity's property, in stored order.
pub option_ids: Vec<Uuid>,
+ /// The post-mutation persistence receipt, or `None` when no row was changed.
+ #[allow(
+ dead_code,
+ reason = "internal persistence receipt is intentionally omitted from public responses"
+ )]
+ pub(crate) mutation: Option<EntityPropertyMutationSnapshot>,
}
/// The outcome of applying one shared option delta to a single entity in a
diff --git a/crates/properties/src/domain/ports.rs b/crates/properties/src/domain/ports.rs
index b21bdf2a79..8a2c875ddb 100644
--- a/crates/properties/src/domain/ports.rs
+++ b/crates/properties/src/domain/ports.rs
@@ -21,9 +21,9 @@ use models_properties::{DataType, EntityPropertyReference, EntityReference, Enti
use uuid::Uuid;
use super::model::{
- EditReceipt, EntityPropertiesKey, EntityPropertyInfo, EntityPropertyOptionSelection,
- EntityPropertyOptionUpdate, PropertyDefinitionOwner, TaskAssignedNotification,
- UpdatePropertyOptionOutcome, ViewReceipt,
+ EditReceipt, EntityPropertiesKey, EntityPropertyInfo, EntityPropertyMutationSnapshot,
+ EntityPropertyOptionSelection, EntityPropertyOptionUpdate, GetOrCreateTagDefinitionResult,
+ PropertyDefinitionOwner, TaskAssignedNotification, UpdatePropertyOptionOutcome, ViewReceipt,
};
/// Repository trait for property operations.
@@ -147,13 +147,13 @@ pub trait PropertiesRepo: Send + Sync + 'static {
owner: PropertyDefinitionOwner<'a>,
) -> impl Future<Output = Result<Option<PropertyDefinition>, Self::Err>> + Send;
- /// Return the owner's tag definition, creating it on first use.
+ /// Return the owner's tag definition and whether it was created on this call.
// Explicit lifetime required by mockall's automock expansion.
#[allow(clippy::needless_lifetimes)]
fn get_or_create_tag_definition<'a>(
&self,
owner: PropertyDefinitionOwner<'a>,
- ) -> impl Future<Output = Result<PropertyDefinition, Self::Err>> + Send;
+ ) -> impl Future<Output = Result<GetOrCreateTagDefinitionResult, Self::Err>> + Send;
/// Count how many of the provided option IDs exist for the property definition.
fn count_valid_property_options(
@@ -174,25 +174,27 @@ pub trait PropertiesRepo: Send + Sync + 'static {
) -> impl Future<Output = Result<EntityProperty, Self::Err>> + Send;
/// Atomically add one option to a multi-select entity property value,
- /// attaching the property if needed. Re-adding a present option is a no-op.
- /// Composes with concurrent option changes without a lost update.
+ /// attaching the property if needed. Re-adding a present option is deduped.
+ /// Composes with concurrent option changes without a lost update and returns
+ /// the complete persisted state.
fn add_entity_property_option(
&self,
entity_id: &str,
entity_type: EntityType,
property_definition_id: Uuid,
option_id: Uuid,
- ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+ ) -> impl Future<Output = Result<EntityPropertyMutationSnapshot, Self::Err>> + Send;
/// 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.
+ /// Returns no snapshot if the property is unattached or the option is not
+ /// present, because no row was mutated.
fn remove_entity_property_option(
&self,
entity_id: &str,
entity_type: EntityType,
property_definition_id: Uuid,
option_id: Uuid,
- ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+ ) -> impl Future<Output = Result<Option<EntityPropertyMutationSnapshot>, Self::Err>> + Send;
/// Apply option deltas to several of an entity's multi-select property values
/// in a single transaction, returning each property's final option ids.
diff --git a/crates/properties/src/domain/service_impl/mod.rs b/crates/properties/src/domain/service_impl/mod.rs
index da85b8afb0..9605744c66 100644
--- a/crates/properties/src/domain/service_impl/mod.rs
+++ b/crates/properties/src/domain/service_impl/mod.rs
@@ -9,6 +9,8 @@ use document_sub_type::DocumentSubType;
use entity_access::domain::models::{
EntityAccessReceipt, EntityType as AccessEntityType, RequiredPermission,
};
+use macro_event_broker::{MacroEventBroker, NoopMacroEventBroker};
+use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
use models_properties::DataType;
use models_properties::api::requests::SetPropertyValue;
@@ -17,6 +19,7 @@ use models_properties::api::{
PropertyDataType, UpdatePropertyOptionRequest, is_valid_hex_color,
};
use models_properties::convert_set_property_value_to_property_value;
+use models_properties::service::entity_property::EntityProperty;
use models_properties::service::entity_property_with_definition::EntityPropertyWithDefinition;
use models_properties::service::property_definition::PropertyDefinition;
use models_properties::service::property_definition_with_options::PropertyDefinitionWithOptions;
@@ -29,6 +32,11 @@ use uuid::Uuid;
use std::sync::Arc;
use super::error::PropertiesErr;
+use super::events::{
+ EntityPropertiesClearedMetadata, EntityPropertyDeletedMetadata, EntityPropertyUpdatedMetadata,
+ PropertyCreatedMetadata, PropertyDeletedMetadata, PropertyMacroEvent,
+ PropertyOptionCreatedMetadata, PropertyOptionDeletedMetadata, PropertyOptionUpdatedMetadata,
+};
use super::metadata;
use super::model::{
EditReceipt, EntityOptionUpdateOutcome, EntityPropertyInfo, EntityPropertyOptionSelection,
@@ -57,18 +65,21 @@ fn is_search_indexed(entity_type: EntityType) -> bool {
)
}
-/// Implementation of PropertiesService using a repository and optional permission service.
+/// Implementation of [`PropertiesService`] using repository, permission,
+/// notification, search-indexing, and event-publishing ports.
#[derive(Debug)]
-pub struct PropertiesServiceImpl<R, P, N>
+pub struct PropertiesServiceImpl<R, P, N, B = NoopMacroEventBroker>
where
R: PropertiesRepo,
P: PermissionService,
N: NotificationService,
+ B: MacroEventBroker,
{
repository: R,
permission_service: Option<P>,
notification_service: Option<N>,
search_indexer: Option<Arc<dyn PropertySearchIndexer>>,
+ event_broker: B,
}
impl<R, P, N> PropertiesServiceImpl<R, P, N>
@@ -88,6 +99,29 @@ where
permission_service,
notification_service,
search_indexer: None,
+ event_broker: NoopMacroEventBroker,
+ }
+ }
+}
+
+impl<R, P, N, B> PropertiesServiceImpl<R, P, N, B>
+where
+ R: PropertiesRepo,
+ P: PermissionService,
+ N: NotificationService,
+ B: MacroEventBroker,
+{
+ /// Replace the event broker while preserving every other service dependency.
+ pub fn with_event_broker<B2: MacroEventBroker>(
+ self,
+ event_broker: B2,
+ ) -> PropertiesServiceImpl<R, P, N, B2> {
+ PropertiesServiceImpl {
+ repository: self.repository,
+ permission_service: self.permission_service,
+ notification_service: self.notification_service,
+ search_indexer: self.search_indexer,
+ event_broker,
}
}
@@ -98,6 +132,109 @@ where
self
}
+ /// Publish a property lifecycle event without coupling broker availability
+ /// to a completed mutation.
+ fn publish_property_event(&self, event: PropertyMacroEvent) {
+ drop(self.event_broker.send_event(&event).inspect_err(|error| {
+ tracing::error!(error = ?error, "failed to schedule property event");
+ }));
+ }
+
+ /// Build a creation event from the authoritative persisted definition.
+ fn property_created_event(
+ property: &PropertyDefinition,
+ actor_user_id: &MacroUserIdStr<'_>,
+ ) -> PropertyMacroEvent {
+ PropertyMacroEvent::created(PropertyCreatedMetadata {
+ property_definition_id: property.id,
+ actor_user_id: Some(actor_user_id.clone().into_owned()),
+ owner: property.owner.clone(),
+ display_name: property.display_name.clone(),
+ data_type: property.data_type,
+ is_multi_select: property.is_multi_select,
+ specific_entity_type: property.specific_entity_type,
+ created_at: property.created_at,
+ })
+ }
+
+ /// Build an option creation event from the authoritative persisted state.
+ fn property_option_created_event(
+ option: &PropertyOption,
+ actor_user_id: &MacroUserIdStr<'_>,
+ ) -> PropertyMacroEvent {
+ PropertyMacroEvent::property_option_created(PropertyOptionCreatedMetadata {
+ option_id: option.id,
+ property_definition_id: option.property_definition_id,
+ actor_user_id: Some(actor_user_id.clone().into_owned()),
+ value: option.value.clone(),
+ color: option.color.clone(),
+ display_order: option.display_order,
+ })
+ }
+
+ /// Build an option update event from the authoritative post-update state.
+ fn property_option_updated_event(
+ option: &PropertyOption,
+ actor_user_id: &MacroUserIdStr<'_>,
+ ) -> PropertyMacroEvent {
+ PropertyMacroEvent::property_option_updated(PropertyOptionUpdatedMetadata {
+ option_id: option.id,
+ property_definition_id: option.property_definition_id,
+ actor_user_id: Some(actor_user_id.clone().into_owned()),
+ value: option.value.clone(),
+ color: option.color.clone(),
+ display_order: option.display_order,
+ })
+ }
+
+ /// Build an option deletion event from the value captured before deletion.
+ fn property_option_deleted_event(
+ option: &PropertyOption,
+ actor_user_id: &MacroUserIdStr<'_>,
+ ) -> PropertyMacroEvent {
+ PropertyMacroEvent::property_option_deleted(PropertyOptionDeletedMetadata {
+ option_id: option.id,
+ property_definition_id: option.property_definition_id,
+ actor_user_id: Some(actor_user_id.clone().into_owned()),
+ value: option.value.clone(),
+ })
+ }
+
+ /// Build an entity-property update event from committed persistence state.
+ fn entity_property_updated_event(
+ property: &EntityProperty,
+ value: &Option<PropertyValue>,
+ access: &EditReceipt,
+ ) -> PropertyMacroEvent {
+ PropertyMacroEvent::entity_property_updated(EntityPropertyUpdatedMetadata {
+ entity_property_id: property.id,
+ entity_id: property.entity_id.clone(),
+ entity_type: property.entity_type,
+ property_definition_id: property.property_definition_id,
+ actor_user_id: access.authenticated_user().cloned(),
+ value: value.clone(),
+ updated_at: property.updated_at,
+ })
+ }
+
+ /// Publish each authoritative mutation returned by a bulk transaction.
+ fn publish_entity_property_selection_events(
+ &self,
+ selections: &[EntityPropertyOptionSelection],
+ access: &EditReceipt,
+ ) {
+ for mutation in selections
+ .iter()
+ .filter_map(|selection| selection.mutation.as_ref())
+ {
+ self.publish_property_event(Self::entity_property_updated_event(
+ &mutation.property,
+ &mutation.value,
+ access,
+ ));
+ }
+ }
+
/// The permission service, or the error every receipt-minting path maps a
/// missing one to.
fn permission_service(&self) -> Result<&P, PropertiesErr> {
@@ -297,11 +434,12 @@ where
}
}
-impl<R, P, N> PropertiesService for PropertiesServiceImpl<R, P, N>
+impl<R, P, N, B> PropertiesService for PropertiesServiceImpl<R, P, N, B>
where
R: PropertiesRepo,
P: PermissionService,
N: NotificationService,
+ B: MacroEventBroker,
anyhow::Error: From<R::Err> + From<P::Err> + From<N::Err>,
{
#[tracing::instrument(skip(self, access), fields(entity_id = %access.entity_id(), entity_type = ?access.entity_type()), err)]
@@ -448,6 +586,11 @@ where
let property = self
.handle_task_relationship_property(access, property_definition_id, value)
.await?;
+ self.publish_property_event(Self::entity_property_updated_event(
+ &property,
+ &property_value,
+ access,
+ ));
return Ok(EntityPropertyWithDefinition {
property,
definition: property_definition,
@@ -475,6 +618,11 @@ where
.map_err(anyhow::Error::from)?;
self.enqueue_property_upsert(entity_id, entity_type).await;
+ self.publish_property_event(Self::entity_property_updated_event(
+ &property,
+ &property_value,
+ access,
+ ));
Ok(EntityPropertyWithDefinition {
property,
@@ -527,7 +675,8 @@ where
self.validate_property_options(property_definition_id, &[option_id])
.await?;
- self.repository
+ let mutation = self
+ .repository
.add_entity_property_option(
access.entity_id(),
subject.storage_entity_type,
@@ -539,6 +688,11 @@ where
self.enqueue_property_upsert(access.entity_id(), subject.storage_entity_type)
.await;
+ self.publish_property_event(Self::entity_property_updated_event(
+ &mutation.property,
+ &mutation.value,
+ access,
+ ));
Ok(())
}
@@ -559,7 +713,8 @@ where
option_id: Uuid,
) -> Result<(), PropertiesErr> {
let subject = self.resolve_subject(access).await?;
- self.repository
+ let mutation = self
+ .repository
.remove_entity_property_option(
access.entity_id(),
subject.storage_entity_type,
@@ -571,6 +726,13 @@ where
self.enqueue_property_upsert(access.entity_id(), subject.storage_entity_type)
.await;
+ if let Some(mutation) = mutation {
+ self.publish_property_event(Self::entity_property_updated_event(
+ &mutation.property,
+ &mutation.value,
+ access,
+ ));
+ }
Ok(())
}
@@ -638,6 +800,7 @@ where
self.enqueue_property_upsert(access.entity_id(), entity_type)
.await;
+ self.publish_entity_property_selection_events(&selections, access);
Ok(selections)
}
@@ -737,12 +900,13 @@ where
.map_err(anyhow::Error::from);
match update_result {
- Ok(mut selections) => {
+ Ok(selections) => {
let option_ids = selections
- .pop()
- .map(|selection| selection.option_ids)
+ .last()
+ .map(|selection| selection.option_ids.clone())
.unwrap_or_default();
self.enqueue_property_upsert(entity_id, entity_type).await;
+ self.publish_entity_property_selection_events(&selections, &access[index]);
outcomes[index] = Some(EntityOptionUpdateOutcome::Applied { option_ids });
}
Err(error) => {
@@ -873,6 +1037,8 @@ where
"successfully created property definition"
);
+ self.publish_property_event(Self::property_created_event(&property, user_id));
+
Ok(property)
}
@@ -913,6 +1079,14 @@ where
tracing::info!("successfully deleted property definition");
+ self.publish_property_event(PropertyMacroEvent::deleted(PropertyDeletedMetadata {
+ property_definition_id: property.id,
+ actor_user_id: Some(user_id.clone().into_owned()),
+ owner: property.owner,
+ display_name: property.display_name,
+ data_type: property.data_type,
+ }));
+
Ok(())
}
@@ -999,6 +1173,8 @@ where
"successfully added property option"
);
+ self.publish_property_event(Self::property_option_created_event(&option, user_id));
+
Ok(option)
}
@@ -1064,7 +1240,10 @@ where
.await
.map_err(anyhow::Error::from)?
{
- UpdatePropertyOptionOutcome::Updated(updated) => Ok(updated),
+ UpdatePropertyOptionOutcome::Updated(updated) => {
+ self.publish_property_event(Self::property_option_updated_event(&updated, user_id));
+ Ok(updated)
+ }
UpdatePropertyOptionOutcome::NotFound => Err(PropertiesErr::OptionNotFound),
UpdatePropertyOptionOutcome::DuplicateValue => Err(PropertiesErr::DuplicateOptionValue),
}
@@ -1102,12 +1281,14 @@ where
.await
.map_err(anyhow::Error::from)?;
- if deleted {
- tracing::info!("successfully deleted property option");
- Ok(())
- } else {
- Err(PropertiesErr::OptionNotFound)
+ if !deleted {
+ return Err(PropertiesErr::OptionNotFound);
}
+
+ tracing::info!("successfully deleted property option");
+ self.publish_property_event(Self::property_option_deleted_event(&option, user_id));
+
+ Ok(())
}
#[tracing::instrument(skip(self, team), err)]
@@ -1151,13 +1332,17 @@ where
),
};
- let definition = self
+ let result = self
.repository
.get_or_create_tag_definition(owner)
.await
.map_err(anyhow::Error::from)?;
- self.build_tag_set(scope, Some(definition)).await
+ if result.created {
+ self.publish_property_event(Self::property_created_event(&result.definition, user_id));
+ }
+
+ self.build_tag_set(scope, Some(result.definition)).await
}
#[tracing::instrument(skip(self, access), fields(entity_id = %access.entity_id(), entity_type = ?access.entity_type()), err)]
@@ -1272,11 +1457,20 @@ where
let subject = self.resolve_subject(access).await?;
let entity_reference =
EntityReference::new(access.entity_id().to_string(), subject.storage_entity_type);
- Ok(self
- .repository
+ self.repository
.delete_entity_properties(&entity_reference)
.await
- .map_err(anyhow::Error::from)?)
+ .map_err(anyhow::Error::from)?;
+
+ self.publish_property_event(PropertyMacroEvent::entity_properties_cleared(
+ EntityPropertiesClearedMetadata {
+ entity_id: access.entity_id().to_string(),
+ entity_type: subject.storage_entity_type,
+ actor_user_id: access.authenticated_user().cloned(),
+ },
+ ));
+
+ Ok(())
}
#[tracing::instrument(skip(self), fields(entity_property_id = %entity_property_id), err)]
@@ -1344,6 +1538,16 @@ where
tracing::info!("successfully removed entity property");
+ self.publish_property_event(PropertyMacroEvent::entity_property_deleted(
+ EntityPropertyDeletedMetadata {
+ entity_property_id,
+ entity_id: property_info.entity_id,
+ entity_type: property_info.entity_type,
+ property_definition_id: property_info.property_definition_id,
+ actor_user_id: access.authenticated_user().cloned(),
+ },
+ ));
+
Ok(())
}
}
diff --git a/crates/properties/src/domain/service_impl/task_properties.rs b/crates/properties/src/domain/service_impl/task_properties.rs
index 86a5dbb454..177efb4649 100644
--- a/crates/properties/src/domain/service_impl/task_properties.rs
+++ b/crates/properties/src/domain/service_impl/task_properties.rs
@@ -3,6 +3,7 @@
use std::collections::HashSet;
use entity_access::domain::models::EntityAccessAuth;
+use macro_event_broker::MacroEventBroker;
use macro_user_id::cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
use models_properties::EntityType;
@@ -16,11 +17,12 @@ use crate::domain::model::{EditReceipt, PropertyAccessReceiptExt, TaskAssignedNo
use crate::domain::ports::{NotificationService, PermissionService, PropertiesRepo};
use crate::domain::service_impl::PropertiesServiceImpl;
-impl<R, P, N> PropertiesServiceImpl<R, P, N>
+impl<R, P, N, B> PropertiesServiceImpl<R, P, N, B>
where
R: PropertiesRepo,
P: PermissionService,
N: NotificationService,
+ B: MacroEventBroker,
anyhow::Error: From<R::Err> + From<P::Err> + From<N::Err>,
{
/// Require edit access to every referenced task before linking: linking
diff --git a/crates/properties/src/domain/test.rs b/crates/properties/src/domain/test.rs
index ca361636e3..19108ca4f6 100644
--- a/crates/properties/src/domain/test.rs
+++ b/crates/properties/src/domain/test.rs
@@ -1,8 +1,11 @@
//! Unit tests for PropertiesServiceImpl using mockall-generated repo.
use super::service_impl::PropertiesServiceImpl;
+use crate::domain::error::PropertiesErr;
use crate::domain::model::{
- EditReceipt, PropertyAccessReceiptExt, ViewReceipt, canonical_entity_type,
+ EditReceipt, EntityPropertyMutationSnapshot, GetOrCreateTagDefinitionResult,
+ PropertyAccessReceiptExt, TagScope, UpdatePropertyOptionOutcome, ViewReceipt,
+ canonical_entity_type,
};
use crate::domain::{
ports::{MockNotificationService, MockPermissionService, MockPropertiesRepo},
@@ -14,35 +17,1019 @@ use entity_access::domain::models::{
AccessLevel, BotId, BotReceiptScope, Entity, EntityAccessAuth, EntityAccessReceipt,
EntityPermission, EntityType as AccessEntityType, ViewAccessLevel,
};
-use macro_user_id::user_id::MacroUserIdStr;
+use macro_event_broker::{EventBrokerError, MacroEvent, MacroEventBroker};
+use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use models_properties::{
- EntityType,
+ DataType, EntityType, PropertyOwner,
+ api::{
+ AddNumberOptionRequest, AddPropertyOptionRequest, AddStringOptionRequest,
+ CreatePropertyDefinitionRequest, CreatePropertyScope, PropertyDataType,
+ UpdatePropertyOptionRequest,
+ },
service::{
- entity_property::EntityProperty, property_definition::PropertyDefinition,
+ entity_property::EntityProperty,
+ property_definition::PropertyDefinition,
+ property_option::{PropertyOption, PropertyOptionValue},
property_value::PropertyValue,
},
};
use std::collections::HashMap;
+use std::sync::{Arc, Mutex};
use system_properties::{StatusOption, SystemPropertyKey};
use uuid::Uuid;
-fn entity_property(
- entity_id: &str,
- entity_type: EntityType,
- property_definition_id: Uuid,
-) -> EntityProperty {
- EntityProperty {
- id: Uuid::new_v4(),
- entity_id: entity_id.to_owned(),
- entity_type,
+fn entity_property(
+ entity_id: &str,
+ entity_type: EntityType,
+ property_definition_id: Uuid,
+) -> EntityProperty {
+ EntityProperty {
+ id: Uuid::new_v4(),
+ entity_id: entity_id.to_owned(),
+ entity_type,
+ property_definition_id,
+ created_at: chrono::Utc::now(),
+ updated_at: chrono::Utc::now(),
+ }
+}
+
+fn entity_property_for_event(
+ id: Uuid,
+ entity_id: &str,
+ entity_type: EntityType,
+ property_definition_id: Uuid,
+ updated_at: chrono::DateTime<chrono::Utc>,
+) -> EntityProperty {
+ EntityProperty {
+ id,
+ entity_id: entity_id.to_owned(),
+ entity_type,
+ property_definition_id,
+ created_at: updated_at,
+ updated_at,
+ }
+}
+
+fn entity_property_mutation(
+ entity_id: &str,
+ entity_type: EntityType,
+ property_definition_id: Uuid,
+ value: Option<PropertyValue>,
+) -> EntityPropertyMutationSnapshot {
+ EntityPropertyMutationSnapshot {
+ property: entity_property(entity_id, entity_type, property_definition_id),
+ value,
+ }
+}
+
+fn entity_property_option_selection_for_event(
+ entity_property_id: Uuid,
+ entity_id: &str,
+ entity_type: EntityType,
+ property_definition_id: Uuid,
+ option_ids: Vec<Uuid>,
+) -> crate::domain::model::EntityPropertyOptionSelection {
+ crate::domain::model::EntityPropertyOptionSelection {
+ property_definition_id,
+ option_ids: option_ids.clone(),
+ mutation: Some(EntityPropertyMutationSnapshot {
+ property: entity_property_for_event(
+ entity_property_id,
+ entity_id,
+ entity_type,
+ property_definition_id,
+ event_timestamp(),
+ ),
+ value: Some(PropertyValue::SelectOption(option_ids)),
+ }),
+ }
+}
+
+fn event_timestamp() -> chrono::DateTime<chrono::Utc> {
+ chrono::DateTime::parse_from_rfc3339("2026-07-27T18:45:00Z")
+ .unwrap()
+ .with_timezone(&chrono::Utc)
+}
+
+fn caller_user_id() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()
+}
+
+#[derive(Clone, Debug, PartialEq)]
+struct PublishedPropertyEvent {
+ topic: &'static str,
+ key: String,
+ envelope: serde_json::Value,
+}
+
+#[derive(Clone, Default)]
+struct RecordingEventBroker {
+ events: Arc<Mutex<Vec<PublishedPropertyEvent>>>,
+ fail_scheduling: bool,
+}
+
+impl RecordingEventBroker {
+ fn failing() -> Self {
+ Self {
+ fail_scheduling: true,
+ ..Self::default()
+ }
+ }
+
+ fn events(&self) -> Vec<PublishedPropertyEvent> {
+ self.events.lock().unwrap().clone()
+ }
+}
+
+impl MacroEventBroker for RecordingEventBroker {
+ fn send_event<E: MacroEvent + ?Sized>(
+ &self,
+ event: &E,
+ ) -> Result<tokio::task::JoinHandle<Result<(), EventBrokerError>>, EventBrokerError> {
+ if self.fail_scheduling {
+ return Err(EventBrokerError::Publish(
+ "intentional scheduling failure".to_string(),
+ ));
+ }
+
+ self.events.lock().unwrap().push(PublishedPropertyEvent {
+ topic: event.topic(),
+ key: event.key().to_string(),
+ envelope: serde_json::to_value(event.event())?,
+ });
+
+ Ok(tokio::spawn(async { Ok(()) }))
+ }
+}
+
+fn service_with_event_broker<B: MacroEventBroker>(
+ repo: MockPropertiesRepo,
+ event_broker: B,
+) -> PropertiesServiceImpl<MockPropertiesRepo, MockPermissionService, MockNotificationService, B> {
+ PropertiesServiceImpl::new(
+ repo,
+ None::<MockPermissionService>,
+ None::<MockNotificationService>,
+ )
+ .with_event_broker(event_broker)
+}
+
+fn property_definition_for_event(
+ id: Uuid,
+ display_name: &str,
+ data_type: DataType,
+ is_multi_select: bool,
+) -> PropertyDefinition {
+ let created_at = chrono::DateTime::parse_from_rfc3339("2026-07-27T12:34:56Z")
+ .unwrap()
+ .with_timezone(&chrono::Utc);
+
+ PropertyDefinition {
+ id,
+ owner: PropertyOwner::User {
+ user_id: caller_user_id().to_string(),
+ },
+ display_name: display_name.to_string(),
+ data_type,
+ is_multi_select,
+ specific_entity_type: None,
+ created_at,
+ updated_at: created_at,
+ is_system: false,
+ is_metadata: false,
+ }
+}
+
+fn create_property_definition_request() -> CreatePropertyDefinitionRequest {
+ CreatePropertyDefinitionRequest {
+ scope: CreatePropertyScope::User,
+ display_name: "Priority".to_string(),
+ data_type: PropertyDataType::Entity {
+ specific_type: Some(EntityType::Document),
+ multi: true,
+ },
+ }
+}
+
+fn property_option_for_event(
+ id: Uuid,
+ property_definition_id: Uuid,
+ display_order: i32,
+ value: PropertyOptionValue,
+ color: Option<&str>,
+) -> PropertyOption {
+ let created_at = chrono::DateTime::parse_from_rfc3339("2026-07-27T12:34:56Z")
+ .unwrap()
+ .with_timezone(&chrono::Utc);
+ let updated_at = chrono::DateTime::parse_from_rfc3339("2026-07-27T13:45:00Z")
+ .unwrap()
+ .with_timezone(&chrono::Utc);
+
+ PropertyOption {
+ id,
+ property_definition_id,
+ display_order,
+ value,
+ color: color.map(str::to_string),
+ created_at,
+ updated_at,
+ }
+}
+
+fn expect_owned_modifiable_definition(
+ repo: &mut MockPropertiesRepo,
+ definition: PropertyDefinition,
+) {
+ let authorized_definition = definition.clone();
+ repo.expect_get_property_definition()
+ .return_once(move |_| Box::pin(async move { Ok(Some(definition)) }));
+ repo.expect_get_property_definition_with_owner()
+ .return_once(move |_, _, _| Box::pin(async move { Ok(Some(authorized_definition)) }));
+}
+
+fn only_published_property_event(event_broker: &RecordingEventBroker) -> PublishedPropertyEvent {
+ let events = event_broker.events();
+ assert_eq!(events.len(), 1);
+ events.into_iter().next().unwrap()
+}
+
+#[tokio::test]
+async fn property_definition_event_create_publishes_authoritative_snapshot() {
+ let property_definition_id = Uuid::from_u128(0xA1);
+ let mut property =
+ property_definition_for_event(property_definition_id, "Priority", DataType::Entity, true);
+ property.specific_entity_type = Some(EntityType::Document);
+
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_create_property_definition()
+ .return_once(move |_, _, _, _, _, _| Box::pin(async move { Ok(property) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ let result = service
+ .create_property_definition(
+ &caller_user_id(),
+ None,
+ &create_property_definition_request(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(result.id, property_definition_id);
+ let published = only_published_property_event(&event_broker);
+ assert_eq!(published.topic, "macro.properties");
+ assert_eq!(published.key, property_definition_id.to_string());
+ assert_eq!(published.envelope["schema_version"], 1);
+ assert_eq!(published.envelope["event_type"], "property.created");
+ assert_eq!(
+ published.envelope["metadata"]["property_definition_id"],
+ property_definition_id.to_string()
+ );
+ assert_eq!(
+ published.envelope["metadata"]["actor_user_id"],
+ caller_user_id().to_string()
+ );
+ assert_eq!(
+ published.envelope["metadata"]["owner"],
+ serde_json::json!({
+ "scope": "user",
+ "user_id": caller_user_id().to_string(),
+ })
+ );
+ assert_eq!(published.envelope["metadata"]["display_name"], "Priority");
+ assert_eq!(published.envelope["metadata"]["data_type"], "ENTITY");
+ assert_eq!(published.envelope["metadata"]["is_multi_select"], true);
+ assert_eq!(
+ published.envelope["metadata"]["specific_entity_type"],
+ "DOCUMENT"
+ );
+ assert_eq!(
+ published.envelope["metadata"]["created_at"],
+ "2026-07-27T12:34:56Z"
+ );
+}
+
+#[tokio::test]
+async fn property_definition_event_ensure_tag_set_publishes_only_when_created() {
+ let property_definition_id = Uuid::from_u128(0xA2);
+ let property =
+ property_definition_for_event(property_definition_id, "Tags", DataType::Tag, true);
+
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_or_create_tag_definition()
+ .return_once(move |_| {
+ Box::pin(async move {
+ Ok(GetOrCreateTagDefinitionResult {
+ definition: property,
+ created: true,
+ })
+ })
+ });
+ repo.expect_get_property_options()
+ .return_once(|_| Box::pin(async { Ok(Vec::new()) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ let tag_set = service
+ .ensure_tag_set(&caller_user_id(), None, TagScope::User)
+ .await
+ .unwrap();
+
+ assert_eq!(tag_set.definition.unwrap().id, property_definition_id);
+ let published = only_published_property_event(&event_broker);
+ assert_eq!(published.topic, "macro.properties");
+ assert_eq!(published.key, property_definition_id.to_string());
+ assert_eq!(published.envelope["event_type"], "property.created");
+ assert_eq!(published.envelope["metadata"]["data_type"], "TAG");
+ assert_eq!(
+ published.envelope["metadata"]["actor_user_id"],
+ caller_user_id().to_string()
+ );
+}
+
+#[tokio::test]
+async fn property_definition_event_existing_tag_set_publishes_nothing() {
+ let property =
+ property_definition_for_event(Uuid::from_u128(0xA3), "Tags", DataType::Tag, true);
+
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_or_create_tag_definition()
+ .return_once(move |_| {
+ Box::pin(async move {
+ Ok(GetOrCreateTagDefinitionResult {
+ definition: property,
+ created: false,
+ })
+ })
+ });
+ repo.expect_get_property_options()
+ .return_once(|_| Box::pin(async { Ok(Vec::new()) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ service
+ .ensure_tag_set(&caller_user_id(), None, TagScope::User)
+ .await
+ .unwrap();
+
+ assert!(event_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn property_definition_event_delete_publishes_pre_delete_snapshot() {
+ let property_definition_id = Uuid::from_u128(0xA4);
+ let property = property_definition_for_event(
+ property_definition_id,
+ "Archived priority",
+ DataType::SelectString,
+ false,
+ );
+ let authorized_property = property.clone();
+
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_property_definition()
+ .return_once(move |_| Box::pin(async move { Ok(Some(property)) }));
+ repo.expect_get_property_definition_with_owner()
+ .return_once(move |_, _, _| Box::pin(async move { Ok(Some(authorized_property)) }));
+ repo.expect_delete_property_definition()
+ .return_once(|_| Box::pin(async { Ok(()) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ service
+ .delete_property_definition(property_definition_id, &caller_user_id(), None)
+ .await
+ .unwrap();
+
+ let published = only_published_property_event(&event_broker);
+ assert_eq!(published.topic, "macro.properties");
+ assert_eq!(published.key, property_definition_id.to_string());
+ assert_eq!(published.envelope["event_type"], "property.deleted");
+ assert_eq!(
+ published.envelope["metadata"]["actor_user_id"],
+ caller_user_id().to_string()
+ );
+ assert_eq!(
+ published.envelope["metadata"]["owner"],
+ serde_json::json!({
+ "scope": "user",
+ "user_id": caller_user_id().to_string(),
+ })
+ );
+ assert_eq!(
+ published.envelope["metadata"]["display_name"],
+ "Archived priority"
+ );
+ assert_eq!(published.envelope["metadata"]["data_type"], "SELECT_STRING");
+}
+
+#[tokio::test]
+async fn property_definition_event_create_repository_failure_publishes_nothing() {
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_create_property_definition()
+ .return_once(|_, _, _, _, _, _| {
+ Box::pin(async { Err(anyhow!("property definition create failed")) })
+ });
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ let result = service
+ .create_property_definition(
+ &caller_user_id(),
+ None,
+ &create_property_definition_request(),
+ )
+ .await;
+
+ assert!(result.is_err());
+ assert!(event_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn property_definition_event_ensure_tag_set_repository_failure_publishes_nothing() {
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_or_create_tag_definition()
+ .return_once(|_| Box::pin(async { Err(anyhow!("tag set create failed")) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ let result = service
+ .ensure_tag_set(&caller_user_id(), None, TagScope::User)
+ .await;
+
+ assert!(result.is_err());
+ assert!(event_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn property_definition_event_delete_repository_failure_publishes_nothing() {
+ let property_definition_id = Uuid::from_u128(0xA5);
+ let property =
+ property_definition_for_event(property_definition_id, "Priority", DataType::String, false);
+ let authorized_property = property.clone();
+
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_property_definition()
+ .return_once(move |_| Box::pin(async move { Ok(Some(property)) }));
+ repo.expect_get_property_definition_with_owner()
+ .return_once(move |_, _, _| Box::pin(async move { Ok(Some(authorized_property)) }));
+ repo.expect_delete_property_definition()
+ .return_once(|_| Box::pin(async { Err(anyhow!("property definition delete failed")) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ let result = service
+ .delete_property_definition(property_definition_id, &caller_user_id(), None)
+ .await;
+
+ assert!(result.is_err());
+ assert!(event_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn property_definition_event_broker_scheduling_failure_is_non_fatal() {
+ let property_definition_id = Uuid::from_u128(0xA6);
+ let property =
+ property_definition_for_event(property_definition_id, "Priority", DataType::Entity, true);
+
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_create_property_definition()
+ .return_once(move |_, _, _, _, _, _| Box::pin(async move { Ok(property) }));
+ let service = service_with_event_broker(repo, RecordingEventBroker::failing());
+
+ let result = service
+ .create_property_definition(
+ &caller_user_id(),
+ None,
+ &create_property_definition_request(),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(result.id, property_definition_id);
+}
+
+#[tokio::test]
+async fn property_option_event_add_string_publishes_full_returned_state_and_exact_key() {
+ let property_definition_id = Uuid::from_u128(0xB1);
+ let option_id = Uuid::from_u128(0xB2);
+ let definition =
+ property_definition_for_event(property_definition_id, "Tags", DataType::Tag, true);
+ let option = property_option_for_event(
+ option_id,
+ property_definition_id,
+ 7,
+ PropertyOptionValue::String("Persisted tag".to_string()),
+ Some("#ABCDEF"),
+ );
+
+ let mut repo = MockPropertiesRepo::new();
+ expect_owned_modifiable_definition(&mut repo, definition);
+ repo.expect_create_property_option()
+ .return_once(move |_, _, _, _| Box::pin(async move { Ok(option) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+ let request = AddPropertyOptionRequest::SelectString {
+ option: AddStringOptionRequest {
+ display_order: 3,
+ value: "Requested tag".to_string(),
+ color: Some("#123456".to_string()),
+ },
+ };
+
+ let created = service
+ .add_property_option(&caller_user_id(), None, property_definition_id, &request)
+ .await
+ .unwrap();
+
+ assert_eq!(created.id, option_id);
+ let published = only_published_property_event(&event_broker);
+ assert_eq!(published.topic, "macro.properties");
+ assert_eq!(published.key, property_definition_id.to_string());
+ assert_eq!(published.envelope["event_type"], "property_option.created");
+ assert_eq!(
+ published.envelope["metadata"],
+ serde_json::json!({
+ "option_id": option_id,
+ "property_definition_id": property_definition_id,
+ "actor_user_id": caller_user_id().to_string(),
+ "value": { "type": "string", "value": "Persisted tag" },
+ "color": "#ABCDEF",
+ "display_order": 7,
+ })
+ );
+}
+
+#[tokio::test]
+async fn property_option_event_add_number_publishes_number_payload() {
+ let property_definition_id = Uuid::from_u128(0xB3);
+ let option_id = Uuid::from_u128(0xB4);
+ let definition = property_definition_for_event(
+ property_definition_id,
+ "Estimate",
+ DataType::SelectNumber,
+ false,
+ );
+ let option = property_option_for_event(
+ option_id,
+ property_definition_id,
+ 4,
+ PropertyOptionValue::Number(13.5),
+ None,
+ );
+
+ let mut repo = MockPropertiesRepo::new();
+ expect_owned_modifiable_definition(&mut repo, definition);
+ repo.expect_create_property_option()
+ .return_once(move |_, _, _, _| Box::pin(async move { Ok(option) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+ let request = AddPropertyOptionRequest::SelectNumber {
+ option: AddNumberOptionRequest {
+ display_order: 4,
+ value: 13.5,
+ },
+ };
+
+ service
+ .add_property_option(&caller_user_id(), None, property_definition_id, &request)
+ .await
+ .unwrap();
+
+ let published = only_published_property_event(&event_broker);
+ assert_eq!(published.key, property_definition_id.to_string());
+ assert_eq!(published.envelope["event_type"], "property_option.created");
+ assert_eq!(
+ published.envelope["metadata"]["value"],
+ serde_json::json!({ "type": "number", "value": 13.5 })
+ );
+ assert_eq!(
+ published.envelope["metadata"]["color"],
+ serde_json::Value::Null
+ );
+}
+
+#[tokio::test]
+async fn property_option_event_add_repository_failure_publishes_nothing() {
+ let property_definition_id = Uuid::from_u128(0xB5);
+ let definition = property_definition_for_event(
+ property_definition_id,
+ "Estimate",
+ DataType::SelectNumber,
+ false,
+ );
+
+ let mut repo = MockPropertiesRepo::new();
+ expect_owned_modifiable_definition(&mut repo, definition);
+ repo.expect_create_property_option()
+ .return_once(|_, _, _, _| Box::pin(async { Err(anyhow!("option create failed")) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+ let request = AddPropertyOptionRequest::SelectNumber {
+ option: AddNumberOptionRequest {
+ display_order: 0,
+ value: 1.0,
+ },
+ };
+
+ let result = service
+ .add_property_option(&caller_user_id(), None, property_definition_id, &request)
+ .await;
+
+ assert!(result.is_err());
+ assert!(event_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn property_option_event_update_publishes_full_post_update_state_and_exact_key() {
+ let property_definition_id = Uuid::from_u128(0xB6);
+ let option_id = Uuid::from_u128(0xB7);
+ let definition =
+ property_definition_for_event(property_definition_id, "Tags", DataType::Tag, true);
+ let existing = property_option_for_event(
+ option_id,
+ property_definition_id,
+ 1,
+ PropertyOptionValue::String("Before".to_string()),
+ Some("#111111"),
+ );
+ let updated = property_option_for_event(
+ option_id,
+ property_definition_id,
+ 9,
+ PropertyOptionValue::String("Persisted after".to_string()),
+ Some("#FEDCBA"),
+ );
+
+ let mut repo = MockPropertiesRepo::new();
+ expect_owned_modifiable_definition(&mut repo, definition);
+ repo.expect_get_property_option()
+ .return_once(move |_| Box::pin(async move { Ok(Some(existing)) }));
+ repo.expect_update_property_option()
+ .return_once(move |_, _, _, _| {
+ Box::pin(async move { Ok(UpdatePropertyOptionOutcome::Updated(updated)) })
+ });
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+ let request = UpdatePropertyOptionRequest {
+ value: Some("Requested after".to_string()),
+ color: Some("#123456".to_string()),
+ display_order: Some(8),
+ };
+
+ let result = service
+ .update_property_option(
+ &caller_user_id(),
+ None,
+ property_definition_id,
+ option_id,
+ &request,
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(result.display_order, 9);
+ let published = only_published_property_event(&event_broker);
+ assert_eq!(published.topic, "macro.properties");
+ assert_eq!(published.key, property_definition_id.to_string());
+ assert_eq!(published.envelope["event_type"], "property_option.updated");
+ assert_eq!(
+ published.envelope["metadata"],
+ serde_json::json!({
+ "option_id": option_id,
+ "property_definition_id": property_definition_id,
+ "actor_user_id": caller_user_id().to_string(),
+ "value": { "type": "string", "value": "Persisted after" },
+ "color": "#FEDCBA",
+ "display_order": 9,
+ })
+ );
+}
+
+#[tokio::test]
+async fn property_option_event_update_not_found_outcome_publishes_nothing() {
+ let property_definition_id = Uuid::from_u128(0xB8);
+ let option_id = Uuid::from_u128(0xB9);
+ let definition = property_definition_for_event(
+ property_definition_id,
+ "Priority",
+ DataType::SelectString,
+ false,
+ );
+ let existing = property_option_for_event(
+ option_id,
+ property_definition_id,
+ 0,
+ PropertyOptionValue::String("Before".to_string()),
+ None,
+ );
+
+ let mut repo = MockPropertiesRepo::new();
+ expect_owned_modifiable_definition(&mut repo, definition);
+ repo.expect_get_property_option()
+ .return_once(move |_| Box::pin(async move { Ok(Some(existing)) }));
+ repo.expect_update_property_option()
+ .return_once(|_, _, _, _| Box::pin(async { Ok(UpdatePropertyOptionOutcome::NotFound) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ let result = service
+ .update_property_option(
+ &caller_user_id(),
+ None,
+ property_definition_id,
+ option_id,
+ &empty_update_property_option_request(),
+ )
+ .await;
+
+ assert!(matches!(result, Err(PropertiesErr::OptionNotFound)));
+ assert!(event_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn property_option_event_update_duplicate_value_publishes_nothing() {
+ let property_definition_id = Uuid::from_u128(0xBA);
+ let option_id = Uuid::from_u128(0xBB);
+ let definition = property_definition_for_event(
+ property_definition_id,
+ "Priority",
+ DataType::SelectString,
+ false,
+ );
+ let existing = property_option_for_event(
+ option_id,
+ property_definition_id,
+ 0,
+ PropertyOptionValue::String("Before".to_string()),
+ None,
+ );
+
+ let mut repo = MockPropertiesRepo::new();
+ expect_owned_modifiable_definition(&mut repo, definition);
+ repo.expect_get_property_option()
+ .return_once(move |_| Box::pin(async move { Ok(Some(existing)) }));
+ repo.expect_update_property_option()
+ .return_once(|_, _, _, _| {
+ Box::pin(async { Ok(UpdatePropertyOptionOutcome::DuplicateValue) })
+ });
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+ let request = UpdatePropertyOptionRequest {
+ value: Some("Duplicate".to_string()),
+ color: None,
+ display_order: None,
+ };
+
+ let result = service
+ .update_property_option(
+ &caller_user_id(),
+ None,
+ property_definition_id,
+ option_id,
+ &request,
+ )
+ .await;
+
+ assert!(matches!(result, Err(PropertiesErr::DuplicateOptionValue)));
+ assert!(event_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn property_option_event_update_repository_error_publishes_nothing() {
+ let property_definition_id = Uuid::from_u128(0xBC);
+ let option_id = Uuid::from_u128(0xBD);
+ let definition = property_definition_for_event(
+ property_definition_id,
+ "Priority",
+ DataType::SelectString,
+ false,
+ );
+ let existing = property_option_for_event(
+ option_id,
+ property_definition_id,
+ 0,
+ PropertyOptionValue::String("Before".to_string()),
+ None,
+ );
+
+ let mut repo = MockPropertiesRepo::new();
+ expect_owned_modifiable_definition(&mut repo, definition);
+ repo.expect_get_property_option()
+ .return_once(move |_| Box::pin(async move { Ok(Some(existing)) }));
+ repo.expect_update_property_option()
+ .return_once(|_, _, _, _| Box::pin(async { Err(anyhow!("option update failed")) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ let result = service
+ .update_property_option(
+ &caller_user_id(),
+ None,
+ property_definition_id,
+ option_id,
+ &empty_update_property_option_request(),
+ )
+ .await;
+
+ assert!(result.is_err());
+ assert!(event_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn property_option_event_update_missing_option_publishes_nothing() {
+ let property_definition_id = Uuid::from_u128(0xBE);
+ let option_id = Uuid::from_u128(0xBF);
+ let definition = property_definition_for_event(
+ property_definition_id,
+ "Priority",
+ DataType::SelectString,
+ false,
+ );
+
+ let mut repo = MockPropertiesRepo::new();
+ expect_owned_modifiable_definition(&mut repo, definition);
+ repo.expect_get_property_option()
+ .return_once(|_| Box::pin(async { Ok(None) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ let result = service
+ .update_property_option(
+ &caller_user_id(),
+ None,
+ property_definition_id,
+ option_id,
+ &empty_update_property_option_request(),
+ )
+ .await;
+
+ assert!(matches!(result, Err(PropertiesErr::OptionNotFound)));
+ assert!(event_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn property_option_event_update_mismatched_option_publishes_nothing() {
+ let property_definition_id = Uuid::from_u128(0xC0);
+ let option_id = Uuid::from_u128(0xC1);
+ let definition = property_definition_for_event(
+ property_definition_id,
+ "Priority",
+ DataType::SelectString,
+ false,
+ );
+ let mismatched = property_option_for_event(
+ option_id,
+ Uuid::from_u128(0xC2),
+ 0,
+ PropertyOptionValue::String("Other property".to_string()),
+ None,
+ );
+
+ let mut repo = MockPropertiesRepo::new();
+ expect_owned_modifiable_definition(&mut repo, definition);
+ repo.expect_get_property_option()
+ .return_once(move |_| Box::pin(async move { Ok(Some(mismatched)) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ let result = service
+ .update_property_option(
+ &caller_user_id(),
+ None,
+ property_definition_id,
+ option_id,
+ &empty_update_property_option_request(),
+ )
+ .await;
+
+ assert!(matches!(result, Err(PropertiesErr::OptionNotFound)));
+ assert!(event_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn property_option_event_delete_publishes_one_pre_delete_snapshot_with_exact_key() {
+ let property_definition_id = Uuid::from_u128(0xC3);
+ let option_id = Uuid::from_u128(0xC4);
+ let definition = property_definition_for_event(
property_definition_id,
- created_at: chrono::Utc::now(),
- updated_at: chrono::Utc::now(),
- }
+ "Estimate",
+ DataType::SelectNumber,
+ false,
+ );
+ let option = property_option_for_event(
+ option_id,
+ property_definition_id,
+ 2,
+ PropertyOptionValue::Number(21.5),
+ None,
+ );
+
+ let mut repo = MockPropertiesRepo::new();
+ expect_owned_modifiable_definition(&mut repo, definition);
+ repo.expect_get_property_option()
+ .return_once(move |_| Box::pin(async move { Ok(Some(option)) }));
+ repo.expect_delete_property_option()
+ .return_once(|_, _| Box::pin(async { Ok(true) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ service
+ .delete_property_option(&caller_user_id(), None, property_definition_id, option_id)
+ .await
+ .unwrap();
+
+ let published = only_published_property_event(&event_broker);
+ assert_eq!(published.topic, "macro.properties");
+ assert_eq!(published.key, property_definition_id.to_string());
+ assert_eq!(published.envelope["event_type"], "property_option.deleted");
+ assert_eq!(
+ published.envelope["metadata"],
+ serde_json::json!({
+ "option_id": option_id,
+ "property_definition_id": property_definition_id,
+ "actor_user_id": caller_user_id().to_string(),
+ "value": { "type": "number", "value": 21.5 },
+ })
+ );
}
-fn caller_user_id() -> MacroUserIdStr<'static> {
- MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()
+#[tokio::test]
+async fn property_option_event_delete_not_found_outcome_publishes_nothing() {
+ let property_definition_id = Uuid::from_u128(0xC5);
+ let option_id = Uuid::from_u128(0xC6);
+ let definition = property_definition_for_event(
+ property_definition_id,
+ "Priority",
+ DataType::SelectString,
+ false,
+ );
+ let option = property_option_for_event(
+ option_id,
+ property_definition_id,
+ 0,
+ PropertyOptionValue::String("Gone".to_string()),
+ None,
+ );
+
+ let mut repo = MockPropertiesRepo::new();
+ expect_owned_modifiable_definition(&mut repo, definition);
+ repo.expect_get_property_option()
+ .return_once(move |_| Box::pin(async move { Ok(Some(option)) }));
+ repo.expect_delete_property_option()
+ .return_once(|_, _| Box::pin(async { Ok(false) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ let result = service
+ .delete_property_option(&caller_user_id(), None, property_definition_id, option_id)
+ .await;
+
+ assert!(matches!(result, Err(PropertiesErr::OptionNotFound)));
+ assert!(event_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn property_option_event_delete_repository_error_publishes_nothing() {
+ let property_definition_id = Uuid::from_u128(0xC7);
+ let option_id = Uuid::from_u128(0xC8);
+ let definition = property_definition_for_event(
+ property_definition_id,
+ "Priority",
+ DataType::SelectString,
+ false,
+ );
+ let option = property_option_for_event(
+ option_id,
+ property_definition_id,
+ 0,
+ PropertyOptionValue::String("Still present".to_string()),
+ None,
+ );
+
+ let mut repo = MockPropertiesRepo::new();
+ expect_owned_modifiable_definition(&mut repo, definition);
+ repo.expect_get_property_option()
+ .return_once(move |_| Box::pin(async move { Ok(Some(option)) }));
+ repo.expect_delete_property_option()
+ .return_once(|_, _| Box::pin(async { Err(anyhow!("option delete failed")) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ let result = service
+ .delete_property_option(&caller_user_id(), None, property_definition_id, option_id)
+ .await;
+
+ assert!(result.is_err());
+ assert!(event_broker.events().is_empty());
+}
+
+fn empty_update_property_option_request() -> UpdatePropertyOptionRequest {
+ UpdatePropertyOptionRequest {
+ value: None,
+ color: None,
+ display_order: None,
+ }
}
/// An edit receipt for the test caller, minted without an access check.
@@ -54,6 +1041,16 @@ fn edit_receipt(entity_id: &str, entity_type: EntityType) -> EditReceipt {
)
}
+fn edit_receipt_for_user(user_id: &str, entity_id: &str, entity_type: EntityType) -> EditReceipt {
+ EditReceipt::dangerously_assert_authenticated_user(
+ MacroUserIdStr::parse_from_str(user_id)
+ .unwrap()
+ .into_owned(),
+ entity_id,
+ canonical_entity_type(entity_type),
+ )
+}
+
/// A view receipt for the test caller, minted without an access check.
fn view_receipt(entity_id: &str, entity_type: EntityType) -> ViewReceipt {
ViewReceipt::dangerously_assert_authenticated_user(
@@ -63,6 +1060,172 @@ fn view_receipt(entity_id: &str, entity_type: EntityType) -> ViewReceipt {
)
}
+#[tokio::test]
+async fn entity_property_event_set_publishes_null_authoritative_snapshot() {
+ let property_definition_id = Uuid::from_u128(0xE701);
+ let entity_property_id = Uuid::from_u128(0xE702);
+ let updated_at = event_timestamp();
+ let assignment = entity_property_for_event(
+ entity_property_id,
+ "doc1",
+ EntityType::Document,
+ property_definition_id,
+ updated_at,
+ );
+
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_property_definition().return_once(move |_| {
+ Box::pin(async move { Ok(Some(multi_select_definition(property_definition_id, false))) })
+ });
+ repo.expect_upsert_entity_property()
+ .withf(move |entity_id, entity_type, definition_id, value| {
+ entity_id == "doc1"
+ && *entity_type == EntityType::Document
+ && *definition_id == property_definition_id
+ && value.is_none()
+ })
+ .return_once(move |_, _, _, _| Box::pin(async move { Ok(assignment) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ service
+ .set_entity_property(
+ &edit_receipt("doc1", EntityType::Document),
+ property_definition_id,
+ None,
+ )
+ .await
+ .unwrap();
+
+ let published = only_published_property_event(&event_broker);
+ assert_eq!(published.topic, "macro.properties");
+ assert_eq!(published.key, "doc1");
+ assert_eq!(published.envelope["event_type"], "entity_property.updated");
+ assert_eq!(
+ published.envelope["metadata"],
+ serde_json::json!({
+ "entity_property_id": entity_property_id,
+ "entity_id": "doc1",
+ "entity_type": "DOCUMENT",
+ "property_definition_id": property_definition_id,
+ "actor_user_id": caller_user_id(),
+ "value": null,
+ "updated_at": updated_at,
+ })
+ );
+}
+
+#[tokio::test]
+async fn entity_property_event_set_failures_do_not_publish_before_commit() {
+ let property_definition_id = Uuid::from_u128(0xE703);
+
+ let mut validation_repo = MockPropertiesRepo::new();
+ validation_repo
+ .expect_get_property_definition()
+ .return_once(|_| Box::pin(async { Ok(None) }));
+ validation_repo.expect_upsert_entity_property().times(0);
+ let validation_broker = RecordingEventBroker::default();
+ let validation_service = service_with_event_broker(validation_repo, validation_broker.clone());
+
+ let validation_result = validation_service
+ .set_entity_property(
+ &edit_receipt("doc1", EntityType::Document),
+ property_definition_id,
+ None,
+ )
+ .await;
+
+ assert!(matches!(
+ validation_result,
+ Err(PropertiesErr::Validation(_))
+ ));
+ assert!(validation_broker.events().is_empty());
+
+ let mut repository_failure_repo = MockPropertiesRepo::new();
+ repository_failure_repo
+ .expect_get_property_definition()
+ .return_once(move |_| {
+ Box::pin(
+ async move { Ok(Some(multi_select_definition(property_definition_id, false))) },
+ )
+ });
+ repository_failure_repo
+ .expect_upsert_entity_property()
+ .return_once(|_, _, _, _| Box::pin(async { Err(anyhow!("upsert failed")) }));
+ let repository_failure_broker = RecordingEventBroker::default();
+ let repository_failure_service =
+ service_with_event_broker(repository_failure_repo, repository_failure_broker.clone());
+
+ let repository_result = repository_failure_service
+ .set_entity_property(
+ &edit_receipt("doc1", EntityType::Document),
+ property_definition_id,
+ None,
+ )
+ .await;
+
+ assert!(repository_result.is_err());
+ assert!(repository_failure_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn entity_property_event_actor_is_only_an_authenticated_user() {
+ let bot_id = BotId::new_from_uuid(uuid::uuid!("00000000-0000-0000-0000-000000000123"));
+ let bot_access = EditReceipt::dangerously_assert_bot(
+ bot_id.into_storage_id(),
+ BotReceiptScope::Team {
+ team_id: Uuid::new_v4(),
+ },
+ "doc1",
+ AccessEntityType::Document,
+ );
+ let unauthenticated_access = EditReceipt::try_new(
+ EntityAccessAuth::Unauthenticated,
+ Entity {
+ entity_id: "doc1".to_string(),
+ entity_type: AccessEntityType::Document,
+ },
+ EntityPermission::AccessLevel {
+ access_level: AccessLevel::Owner,
+ },
+ )
+ .unwrap();
+ let internal_access =
+ EditReceipt::dangerously_assert_internal_user("doc1", AccessEntityType::Document);
+
+ for access in [bot_access, unauthenticated_access, internal_access] {
+ let property_definition_id = Uuid::from_u128(0xE704);
+ let assignment = entity_property_for_event(
+ Uuid::from_u128(0xE705),
+ "doc1",
+ EntityType::Document,
+ property_definition_id,
+ event_timestamp(),
+ );
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_property_definition().return_once(move |_| {
+ Box::pin(
+ async move { Ok(Some(multi_select_definition(property_definition_id, false))) },
+ )
+ });
+ repo.expect_upsert_entity_property()
+ .return_once(move |_, _, _, _| Box::pin(async move { Ok(assignment) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ service
+ .set_entity_property(&access, property_definition_id, None)
+ .await
+ .unwrap();
+
+ let published = only_published_property_event(&event_broker);
+ assert_eq!(
+ published.envelope["metadata"]["actor_user_id"],
+ serde_json::Value::Null
+ );
+ }
+}
+
#[test]
fn bot_receipt_has_no_authenticated_user_identity() {
let bot_id = BotId::new_from_uuid(uuid::uuid!("00000000-0000-0000-0000-000000000123"));
@@ -196,6 +1359,227 @@ fn subtasks_value(subtask_ids: &[Uuid]) -> models_properties::api::requests::Set
}
}
+fn task_relationship_definition(property_definition_id: Uuid) -> PropertyDefinition {
+ PropertyDefinition {
+ id: property_definition_id,
+ owner: PropertyOwner::System,
+ display_name: "Task relationship".to_string(),
+ data_type: DataType::Entity,
+ is_multi_select: property_definition_id == SystemPropertyKey::SUBTASKS_UUID,
+ specific_entity_type: Some(EntityType::Task),
+ created_at: event_timestamp(),
+ updated_at: event_timestamp(),
+ is_system: true,
+ is_metadata: false,
+ }
+}
+
+fn expect_task_storage(repo: &mut MockPropertiesRepo, task_id: Uuid) {
+ repo.expect_get_document_sub_types()
+ .withf(move |ids| ids == [task_id])
+ .return_once(move |_| {
+ Box::pin(async move { Ok(HashMap::from([(task_id, DocumentSubType::Task)])) })
+ });
+}
+
+#[tokio::test]
+async fn entity_property_event_parent_task_uses_primary_task_snapshot_only() {
+ let task_id = Uuid::from_u128(0xE710);
+ let parent_id = Uuid::from_u128(0xE711);
+ let entity_property_id = Uuid::from_u128(0xE712);
+ let updated_at = event_timestamp();
+ let assignment = entity_property_for_event(
+ entity_property_id,
+ &task_id.to_string(),
+ EntityType::Task,
+ SystemPropertyKey::PARENT_TASK_UUID,
+ updated_at,
+ );
+ let mut repo = MockPropertiesRepo::new();
+ expect_task_storage(&mut repo, task_id);
+ repo.expect_get_property_definition().return_once(|_| {
+ Box::pin(async {
+ Ok(Some(task_relationship_definition(
+ SystemPropertyKey::PARENT_TASK_UUID,
+ )))
+ })
+ });
+ repo.expect_link_parent_task()
+ .withf(move |target_task_id, target_parent_id| {
+ *target_task_id == task_id && *target_parent_id == Some(parent_id)
+ })
+ .return_once(move |_, _| Box::pin(async move { Ok(Some(assignment)) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = PropertiesServiceImpl::new(
+ repo,
+ Some(create_mock_permission_service()),
+ None::<MockNotificationService>,
+ )
+ .with_event_broker(event_broker.clone());
+
+ service
+ .set_entity_property(
+ &edit_receipt(&task_id.to_string(), EntityType::Task),
+ SystemPropertyKey::PARENT_TASK_UUID,
+ Some(parent_task_value(parent_id)),
+ )
+ .await
+ .unwrap();
+
+ let published = only_published_property_event(&event_broker);
+ assert_eq!(published.key, task_id.to_string());
+ assert_eq!(published.envelope["event_type"], "entity_property.updated");
+ assert_eq!(
+ published.envelope["metadata"],
+ serde_json::json!({
+ "entity_property_id": entity_property_id,
+ "entity_id": task_id,
+ "entity_type": "TASK",
+ "property_definition_id": SystemPropertyKey::PARENT_TASK_UUID,
+ "actor_user_id": caller_user_id(),
+ "value": {
+ "type": "EntityReference",
+ "value": [{
+ "entity_id": parent_id,
+ "entity_type": "TASK",
+ }],
+ },
+ "updated_at": updated_at,
+ })
+ );
+}
+
+#[tokio::test]
+async fn entity_property_event_subtasks_publishes_complete_primary_value_only() {
+ let task_id = Uuid::from_u128(0xE713);
+ let subtask_ids = [Uuid::from_u128(0xE714), Uuid::from_u128(0xE715)];
+ let assignment = entity_property_for_event(
+ Uuid::from_u128(0xE716),
+ &task_id.to_string(),
+ EntityType::Task,
+ SystemPropertyKey::SUBTASKS_UUID,
+ event_timestamp(),
+ );
+ let mut repo = MockPropertiesRepo::new();
+ expect_task_storage(&mut repo, task_id);
+ repo.expect_get_property_definition().return_once(|_| {
+ Box::pin(async {
+ Ok(Some(task_relationship_definition(
+ SystemPropertyKey::SUBTASKS_UUID,
+ )))
+ })
+ });
+ repo.expect_link_subtasks()
+ .withf(move |target_task_id, target_subtask_ids| {
+ *target_task_id == task_id && target_subtask_ids.as_slice() == subtask_ids
+ })
+ .return_once(move |_, _| Box::pin(async move { Ok(Some(assignment)) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = PropertiesServiceImpl::new(
+ repo,
+ Some(create_mock_permission_service()),
+ None::<MockNotificationService>,
+ )
+ .with_event_broker(event_broker.clone());
+
+ service
+ .set_entity_property(
+ &edit_receipt(&task_id.to_string(), EntityType::Task),
+ SystemPropertyKey::SUBTASKS_UUID,
+ Some(subtasks_value(&subtask_ids)),
+ )
+ .await
+ .unwrap();
+
+ let published = only_published_property_event(&event_broker);
+ assert_eq!(published.key, task_id.to_string());
+ assert_eq!(published.envelope["metadata"]["entity_type"], "TASK");
+ assert_eq!(
+ published.envelope["metadata"]["value"],
+ serde_json::json!({
+ "type": "EntityReference",
+ "value": [
+ {"entity_id": subtask_ids[0], "entity_type": "TASK"},
+ {"entity_id": subtask_ids[1], "entity_type": "TASK"},
+ ],
+ })
+ );
+}
+
+#[tokio::test]
+async fn entity_property_event_task_permission_and_transaction_failures_publish_nothing() {
+ let task_id = Uuid::from_u128(0xE717);
+ let parent_id = Uuid::from_u128(0xE718);
+
+ let mut permission_repo = MockPropertiesRepo::new();
+ expect_task_storage(&mut permission_repo, task_id);
+ permission_repo
+ .expect_get_property_definition()
+ .return_once(|_| {
+ Box::pin(async {
+ Ok(Some(task_relationship_definition(
+ SystemPropertyKey::PARENT_TASK_UUID,
+ )))
+ })
+ });
+ permission_repo.expect_link_parent_task().times(0);
+ let mut permission_service = MockPermissionService::new();
+ permission_service
+ .expect_mint_edit_receipt()
+ .return_once(|_, _, _| Box::pin(async { Err(anyhow!("permission denied")) }));
+ let permission_broker = RecordingEventBroker::default();
+ let service = PropertiesServiceImpl::new(
+ permission_repo,
+ Some(permission_service),
+ None::<MockNotificationService>,
+ )
+ .with_event_broker(permission_broker.clone());
+
+ let result = service
+ .set_entity_property(
+ &edit_receipt(&task_id.to_string(), EntityType::Task),
+ SystemPropertyKey::PARENT_TASK_UUID,
+ Some(parent_task_value(parent_id)),
+ )
+ .await;
+
+ assert!(matches!(result, Err(PropertiesErr::PermissionDenied)));
+ assert!(permission_broker.events().is_empty());
+
+ let mut transaction_repo = MockPropertiesRepo::new();
+ expect_task_storage(&mut transaction_repo, task_id);
+ transaction_repo
+ .expect_get_property_definition()
+ .return_once(|_| {
+ Box::pin(async {
+ Ok(Some(task_relationship_definition(
+ SystemPropertyKey::PARENT_TASK_UUID,
+ )))
+ })
+ });
+ transaction_repo
+ .expect_link_parent_task()
+ .return_once(|_, _| Box::pin(async { Err(anyhow!("transaction failed")) }));
+ let transaction_broker = RecordingEventBroker::default();
+ let service = PropertiesServiceImpl::new(
+ transaction_repo,
+ Some(create_mock_permission_service()),
+ None::<MockNotificationService>,
+ )
+ .with_event_broker(transaction_broker.clone());
+
+ let result = service
+ .set_entity_property(
+ &edit_receipt(&task_id.to_string(), EntityType::Task),
+ SystemPropertyKey::PARENT_TASK_UUID,
+ Some(parent_task_value(parent_id)),
+ )
+ .await;
+
+ assert!(result.is_err());
+ assert!(transaction_broker.events().is_empty());
+}
+
#[tokio::test]
async fn test_link_parent_task_delegates_to_repo() {
let mut repo = MockPropertiesRepo::new();
@@ -661,7 +2045,7 @@ async fn test_get_system_property_value_error_path() {
// ============================================================================
#[tokio::test]
-async fn test_delete_entity_property_rejects_receipt_for_other_entity() {
+async fn entity_property_event_delete_permission_failure_publishes_nothing() {
let mut repo = MockPropertiesRepo::new();
let entity_property_id = Uuid::from_u128(0xC3);
@@ -676,11 +2060,8 @@ async fn test_delete_entity_property_rejects_receipt_for_other_entity() {
});
repo.expect_delete_entity_property().times(0);
- let service = PropertiesServiceImpl::new(
- repo,
- Some(create_mock_permission_service()),
- None::<MockNotificationService>,
- );
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
let err = service
.delete_entity_property(
@@ -690,23 +2071,22 @@ async fn test_delete_entity_property_rejects_receipt_for_other_entity() {
.await
.unwrap_err();
- assert!(matches!(
- err,
- crate::domain::error::PropertiesErr::PermissionDenied
- ));
+ assert!(matches!(err, PropertiesErr::PermissionDenied));
+ assert!(event_broker.events().is_empty());
}
#[tokio::test]
-async fn test_delete_entity_property_happy_path() {
+async fn entity_property_event_delete_uses_lookup_snapshot_and_requested_id() {
let mut repo = MockPropertiesRepo::new();
let entity_property_id = Uuid::from_u128(0xC3);
+ let property_definition_id = Uuid::from_u128(0xA1);
repo.expect_lookup_entity_property().returning(move |_| {
Box::pin(async move {
Ok(Some(models_properties::EntityPropertyReference {
entity_id: "doc1".to_string(),
entity_type: EntityType::Document,
- property_definition_id: Uuid::from_u128(0xA1),
+ property_definition_id,
}))
})
});
@@ -714,11 +2094,8 @@ async fn test_delete_entity_property_happy_path() {
.withf(move |id| *id == entity_property_id)
.returning(|_| Box::pin(async { Ok(()) }));
- let service = PropertiesServiceImpl::new(
- repo,
- Some(create_mock_permission_service()),
- None::<MockNotificationService>,
- );
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
service
.delete_entity_property(
@@ -727,6 +2104,79 @@ async fn test_delete_entity_property_happy_path() {
)
.await
.unwrap();
+
+ let published = only_published_property_event(&event_broker);
+ assert_eq!(published.key, "doc1");
+ assert_eq!(published.envelope["event_type"], "entity_property.deleted");
+ assert_eq!(
+ published.envelope["metadata"],
+ serde_json::json!({
+ "entity_property_id": entity_property_id,
+ "entity_id": "doc1",
+ "entity_type": "DOCUMENT",
+ "property_definition_id": property_definition_id,
+ "actor_user_id": caller_user_id(),
+ })
+ );
+}
+
+#[tokio::test]
+async fn entity_property_event_delete_repository_failure_publishes_nothing() {
+ let entity_property_id = Uuid::from_u128(0xE720);
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_lookup_entity_property().return_once(|_| {
+ Box::pin(async {
+ Ok(Some(models_properties::EntityPropertyReference {
+ entity_id: "doc1".to_string(),
+ entity_type: EntityType::Document,
+ property_definition_id: Uuid::from_u128(0xE721),
+ }))
+ })
+ });
+ repo.expect_delete_entity_property()
+ .return_once(|_| Box::pin(async { Err(anyhow!("delete failed")) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ let result = service
+ .delete_entity_property(
+ &edit_receipt("doc1", EntityType::Document),
+ entity_property_id,
+ )
+ .await;
+
+ assert!(result.is_err());
+ assert!(event_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn entity_property_event_required_property_failure_publishes_nothing() {
+ let task_id = Uuid::from_u128(0xE722);
+ let entity_property_id = Uuid::from_u128(0xE723);
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_lookup_entity_property().return_once(move |_| {
+ Box::pin(async move {
+ Ok(Some(models_properties::EntityPropertyReference {
+ entity_id: task_id.to_string(),
+ entity_type: EntityType::Task,
+ property_definition_id: SystemPropertyKey::STATUS_UUID,
+ }))
+ })
+ });
+ expect_task_storage(&mut repo, task_id);
+ repo.expect_delete_entity_property().times(0);
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ let result = service
+ .delete_entity_property(
+ &edit_receipt(&task_id.to_string(), EntityType::Task),
+ entity_property_id,
+ )
+ .await;
+
+ assert!(matches!(result, Err(PropertiesErr::RequiredProperty)));
+ assert!(event_broker.events().is_empty());
}
// ============================================================================
@@ -1116,11 +2566,26 @@ fn multi_select_definition(id: Uuid, is_multi_select: bool) -> PropertyDefinitio
}
#[tokio::test]
-async fn test_add_entity_property_option_happy_path() {
- let mut repo = MockPropertiesRepo::new();
+async fn entity_property_event_add_option_uses_full_mutation_snapshot() {
let def_id = Uuid::from_u128(0xA1);
- let option_id = Uuid::from_u128(0xB2);
-
+ let existing_option_id = Uuid::from_u128(0xB1);
+ let added_option_id = Uuid::from_u128(0xB2);
+ let entity_property_id = Uuid::from_u128(0xE730);
+ let updated_at = event_timestamp();
+ let mutation = EntityPropertyMutationSnapshot {
+ property: entity_property_for_event(
+ entity_property_id,
+ "doc1",
+ EntityType::Document,
+ def_id,
+ updated_at,
+ ),
+ value: Some(PropertyValue::SelectOption(vec![
+ existing_option_id,
+ added_option_id,
+ ])),
+ };
+ let mut repo = MockPropertiesRepo::new();
repo.expect_get_property_definition().returning(move |_| {
Box::pin(async move { Ok(Some(multi_select_definition(def_id, true))) })
});
@@ -1131,24 +2596,39 @@ async fn test_add_entity_property_option_happy_path() {
entity_id == "doc1"
&& *entity_type == EntityType::Document
&& *prop == def_id
- && *opt == option_id
+ && *opt == added_option_id
})
- .returning(|_, _, _, _| Box::pin(async { Ok(()) }));
-
- let service = PropertiesServiceImpl::new(
- repo,
- Some(create_mock_permission_service()),
- None::<MockNotificationService>,
- );
+ .return_once(move |_, _, _, _| Box::pin(async move { Ok(mutation) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
service
.add_entity_property_option(
&edit_receipt("doc1", EntityType::Document),
def_id,
- option_id,
+ added_option_id,
)
.await
.unwrap();
+
+ let published = only_published_property_event(&event_broker);
+ assert_eq!(published.key, "doc1");
+ assert_eq!(published.envelope["event_type"], "entity_property.updated");
+ assert_eq!(
+ published.envelope["metadata"],
+ serde_json::json!({
+ "entity_property_id": entity_property_id,
+ "entity_id": "doc1",
+ "entity_type": "DOCUMENT",
+ "property_definition_id": def_id,
+ "actor_user_id": caller_user_id(),
+ "value": {
+ "type": "SelectOption",
+ "value": [existing_option_id, added_option_id],
+ },
+ "updated_at": updated_at,
+ })
+ );
}
#[tokio::test]
@@ -1215,25 +2695,71 @@ async fn test_add_entity_property_option_rejects_invalid_option() {
}
#[tokio::test]
-async fn test_remove_entity_property_option_happy_path() {
- let mut repo = MockPropertiesRepo::new();
+async fn entity_property_event_remove_option_uses_full_mutation_snapshot() {
let def_id = Uuid::from_u128(0xA1);
- let option_id = Uuid::from_u128(0xB2);
-
+ let removed_option_id = Uuid::from_u128(0xB2);
+ let remaining_option_id = Uuid::from_u128(0xB3);
+ let entity_property_id = Uuid::from_u128(0xE731);
+ let updated_at = event_timestamp();
+ let mutation = EntityPropertyMutationSnapshot {
+ property: entity_property_for_event(
+ entity_property_id,
+ "doc1",
+ EntityType::Document,
+ def_id,
+ updated_at,
+ ),
+ value: Some(PropertyValue::SelectOption(vec![remaining_option_id])),
+ };
+ let mut repo = MockPropertiesRepo::new();
repo.expect_remove_entity_property_option()
.withf(move |entity_id, entity_type, prop, opt| {
entity_id == "doc1"
&& *entity_type == EntityType::Document
&& *prop == def_id
- && *opt == option_id
+ && *opt == removed_option_id
})
- .returning(|_, _, _, _| Box::pin(async { Ok(()) }));
+ .return_once(move |_, _, _, _| Box::pin(async move { Ok(Some(mutation)) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
- let service = PropertiesServiceImpl::new(
- repo,
- Some(create_mock_permission_service()),
- None::<MockNotificationService>,
+ service
+ .remove_entity_property_option(
+ &edit_receipt("doc1", EntityType::Document),
+ def_id,
+ removed_option_id,
+ )
+ .await
+ .unwrap();
+
+ let published = only_published_property_event(&event_broker);
+ assert_eq!(published.key, "doc1");
+ assert_eq!(
+ published.envelope["metadata"]["entity_property_id"],
+ entity_property_id.to_string()
+ );
+ assert_eq!(
+ published.envelope["metadata"]["updated_at"],
+ updated_at.to_rfc3339_opts(chrono::SecondsFormat::Secs, true)
+ );
+ assert_eq!(
+ published.envelope["metadata"]["value"],
+ serde_json::json!({
+ "type": "SelectOption",
+ "value": [remaining_option_id],
+ })
);
+}
+
+#[tokio::test]
+async fn entity_property_event_remove_option_no_mutation_publishes_nothing() {
+ let def_id = Uuid::from_u128(0xE732);
+ let option_id = Uuid::from_u128(0xE733);
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_remove_entity_property_option()
+ .return_once(|_, _, _, _| Box::pin(async { Ok(None) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
service
.remove_entity_property_option(
@@ -1243,6 +2769,8 @@ async fn test_remove_entity_property_option_happy_path() {
)
.await
.unwrap();
+
+ assert!(event_broker.events().is_empty());
}
#[tokio::test]
@@ -1509,6 +3037,392 @@ async fn mixed_document_bulk_read_batches_subtypes_and_returns_canonical_keys()
);
}
+#[tokio::test]
+async fn entity_properties_cleared_event_publishes_once_for_authenticated_and_internal_actors() {
+ let cases = [
+ (
+ edit_receipt("doc1", EntityType::Document),
+ serde_json::json!(caller_user_id()),
+ ),
+ (
+ EditReceipt::dangerously_assert_internal_user("doc1", AccessEntityType::Document),
+ serde_json::Value::Null,
+ ),
+ ];
+
+ for (access, expected_actor) in cases {
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_delete_entity_properties()
+ .withf(|entity| {
+ entity.entity_id == "doc1" && entity.entity_type == EntityType::Document
+ })
+ .return_once(|_| Box::pin(async { Ok(()) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ service.delete_entity_properties(&access).await.unwrap();
+
+ let published = only_published_property_event(&event_broker);
+ assert_eq!(published.topic, "macro.properties");
+ assert_eq!(published.key, "doc1");
+ assert_eq!(
+ published.envelope["event_type"],
+ "entity_properties.cleared"
+ );
+ assert_eq!(
+ published.envelope["metadata"],
+ serde_json::json!({
+ "entity_id": "doc1",
+ "entity_type": "DOCUMENT",
+ "actor_user_id": expected_actor,
+ })
+ );
+ }
+}
+
+#[tokio::test]
+async fn entity_properties_cleared_event_repository_failure_publishes_nothing() {
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_delete_entity_properties()
+ .return_once(|_| Box::pin(async { Err(anyhow!("clear failed")) }));
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ let result = service
+ .delete_entity_properties(&edit_receipt("doc1", EntityType::Document))
+ .await;
+
+ assert!(result.is_err());
+ assert!(event_broker.events().is_empty());
+}
+
+#[tokio::test]
+async fn bulk_entity_property_event_publishes_every_property_snapshot() {
+ use crate::domain::model::EntityPropertyOptionUpdate;
+
+ let first_definition_id = Uuid::from_u128(0xB001);
+ let second_definition_id = Uuid::from_u128(0xB002);
+ let first_entity_property_id = Uuid::from_u128(0xB003);
+ let second_entity_property_id = Uuid::from_u128(0xB004);
+ let first_requested_option_id = Uuid::from_u128(0xB005);
+ let second_requested_option_id = Uuid::from_u128(0xB006);
+ let first_final_option_ids = vec![Uuid::from_u128(0xB007), first_requested_option_id];
+ let second_final_option_ids = vec![Uuid::from_u128(0xB008), second_requested_option_id];
+
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_property_definition()
+ .times(2)
+ .returning(|property_definition_id| {
+ Box::pin(async move { Ok(Some(multi_select_definition(property_definition_id, true))) })
+ });
+ repo.expect_count_valid_property_options()
+ .times(2)
+ .returning(|_, option_ids| {
+ let option_count = option_ids.len() as i64;
+ Box::pin(async move { Ok(option_count) })
+ });
+ let persisted_first_final_option_ids = first_final_option_ids.clone();
+ let persisted_second_final_option_ids = second_final_option_ids.clone();
+ repo.expect_bulk_update_entity_property_options()
+ .return_once(move |_, _, _| {
+ Box::pin(async move {
+ Ok(vec![
+ entity_property_option_selection_for_event(
+ first_entity_property_id,
+ "doc1",
+ EntityType::Document,
+ first_definition_id,
+ persisted_first_final_option_ids,
+ ),
+ entity_property_option_selection_for_event(
+ second_entity_property_id,
+ "doc1",
+ EntityType::Document,
+ second_definition_id,
+ persisted_second_final_option_ids,
+ ),
+ ])
+ })
+ });
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+
+ let selections = service
+ .bulk_update_entity_property_options(
+ &edit_receipt("doc1", EntityType::Document),
+ vec![
+ EntityPropertyOptionUpdate {
+ property_definition_id: first_definition_id,
+ add_option_ids: vec![first_requested_option_id],
+ remove_option_ids: Vec::new(),
+ },
+ EntityPropertyOptionUpdate {
+ property_definition_id: second_definition_id,
+ add_option_ids: vec![second_requested_option_id],
+ remove_option_ids: Vec::new(),
+ },
+ ],
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(selections[0].option_ids, first_final_option_ids);
+ assert_eq!(selections[1].option_ids, second_final_option_ids);
+
+ let events = event_broker.events();
+ assert_eq!(events.len(), 2);
+ for event in &events {
+ assert_eq!(event.topic, "macro.properties");
+ assert_eq!(event.key, "doc1");
+ assert_eq!(event.envelope["event_type"], "entity_property.updated");
+ assert_eq!(
+ event.envelope["metadata"]["actor_user_id"],
+ caller_user_id().to_string()
+ );
+ }
+ assert_eq!(
+ events[0].envelope["metadata"],
+ serde_json::json!({
+ "entity_property_id": first_entity_property_id,
+ "entity_id": "doc1",
+ "entity_type": "DOCUMENT",
+ "property_definition_id": first_definition_id,
+ "actor_user_id": caller_user_id(),
+ "value": {
+ "type": "SelectOption",
+ "value": first_final_option_ids,
+ },
+ "updated_at": event_timestamp(),
+ })
+ );
+ assert_eq!(
+ events[1].envelope["metadata"],
+ serde_json::json!({
+ "entity_property_id": second_entity_property_id,
+ "entity_id": "doc1",
+ "entity_type": "DOCUMENT",
+ "property_definition_id": second_definition_id,
+ "actor_user_id": caller_user_id(),
+ "value": {
+ "type": "SelectOption",
+ "value": second_final_option_ids,
+ },
+ "updated_at": event_timestamp(),
+ })
+ );
+}
+
+#[tokio::test]
+async fn bulk_entity_property_event_cross_entity_preserves_outcomes_and_source_actors() {
+ use crate::domain::model::EntityOptionUpdateOutcome;
+
+ let property_definition_id = Uuid::from_u128(0xB101);
+ let requested_option_id = Uuid::from_u128(0xB102);
+ let a_final_option_id = Uuid::from_u128(0xB103);
+ let z_final_option_id = Uuid::from_u128(0xB104);
+ let a_entity_property_id = Uuid::from_u128(0xB105);
+ let z_entity_property_id = Uuid::from_u128(0xB106);
+
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_property_definition().return_once(move |_| {
+ Box::pin(async move { Ok(Some(multi_select_definition(property_definition_id, true))) })
+ });
+ repo.expect_count_valid_property_options()
+ .return_once(|_, _| Box::pin(async { Ok(1) }));
+ repo.expect_bulk_update_entity_property_options()
+ .times(3)
+ .returning(move |entity_id, _, _| match entity_id {
+ "a-good" => Box::pin(async move {
+ Ok(vec![entity_property_option_selection_for_event(
+ a_entity_property_id,
+ "a-good",
+ EntityType::Document,
+ property_definition_id,
+ vec![a_final_option_id],
+ )])
+ }),
+ "m-failed" => Box::pin(async { Err(anyhow!("entity transaction failed")) }),
+ "z-good" => Box::pin(async move {
+ Ok(vec![entity_property_option_selection_for_event(
+ z_entity_property_id,
+ "z-good",
+ EntityType::Document,
+ property_definition_id,
+ vec![z_final_option_id],
+ )])
+ }),
+ unexpected => panic!("unexpected entity {unexpected}"),
+ });
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+ let receipts = vec![
+ edit_receipt_for_user("macro|[email protected]", "z-good", EntityType::Document),
+ edit_receipt_for_user(
+ "m-failed",
+ EntityType::Document,
+ ),
+ edit_receipt_for_user("macro|[email protected]", "a-good", EntityType::Document),
+ ];
+
+ let outcomes = service
+ .bulk_update_entities_property_options(
+ &receipts,
+ property_definition_id,
+ vec![requested_option_id],
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+
+ assert!(matches!(
+ &outcomes[0],
+ EntityOptionUpdateOutcome::Applied { option_ids }
+ if option_ids == &[z_final_option_id]
+ ));
+ assert!(matches!(
+ &outcomes[1],
+ EntityOptionUpdateOutcome::Failed { .. }
+ ));
+ assert!(matches!(
+ &outcomes[2],
+ EntityOptionUpdateOutcome::Applied { option_ids }
+ if option_ids == &[a_final_option_id]
+ ));
+
+ // Input order is z, m, a, while lock order is a, m, z. Successful
+ // transactions publish in lock order without disturbing response alignment.
+ let events = event_broker.events();
+ assert_eq!(events.len(), 2);
+ assert_eq!(events[0].key, "a-good");
+ assert_eq!(events[1].key, "z-good");
+ assert_eq!(
+ events[0].envelope["metadata"]["actor_user_id"],
+ );
+ assert_eq!(
+ events[1].envelope["metadata"]["actor_user_id"],
+ );
+ assert_eq!(
+ events[0].envelope["metadata"]["value"],
+ serde_json::json!({
+ "type": "SelectOption",
+ "value": [a_final_option_id],
+ })
+ );
+ assert_eq!(
+ events[1].envelope["metadata"]["value"],
+ serde_json::json!({
+ "type": "SelectOption",
+ "value": [z_final_option_id],
+ })
+ );
+}
+
+#[tokio::test]
+async fn bulk_entity_property_event_cross_entity_invalid_type_does_not_publish() {
+ use crate::domain::model::EntityOptionUpdateOutcome;
+
+ let property_definition_id = SystemPropertyKey::STAGE_UUID;
+ let requested_option_id = Uuid::from_u128(0xB201);
+ let company_final_option_id = Uuid::from_u128(0xB202);
+ let company_entity_property_id = Uuid::from_u128(0xB203);
+
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_property_definition().return_once(move |_| {
+ Box::pin(async move { Ok(Some(multi_select_definition(property_definition_id, true))) })
+ });
+ repo.expect_count_valid_property_options()
+ .return_once(|_, _| Box::pin(async { Ok(1) }));
+ repo.expect_bulk_update_entity_property_options()
+ .times(1)
+ .withf(|entity_id, _, _| entity_id == "company1")
+ .return_once(move |_, _, _| {
+ Box::pin(async move {
+ Ok(vec![entity_property_option_selection_for_event(
+ company_entity_property_id,
+ "company1",
+ EntityType::Company,
+ property_definition_id,
+ vec![company_final_option_id],
+ )])
+ })
+ });
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+ let receipts = vec![
+ edit_receipt("doc1", EntityType::Document),
+ edit_receipt("company1", EntityType::Company),
+ ];
+
+ let outcomes = service
+ .bulk_update_entities_property_options(
+ &receipts,
+ property_definition_id,
+ vec![requested_option_id],
+ Vec::new(),
+ )
+ .await
+ .unwrap();
+
+ assert!(matches!(
+ &outcomes[0],
+ EntityOptionUpdateOutcome::Failed { .. }
+ ));
+ assert!(matches!(
+ &outcomes[1],
+ EntityOptionUpdateOutcome::Applied { option_ids }
+ if option_ids == &[company_final_option_id]
+ ));
+ let published = only_published_property_event(&event_broker);
+ assert_eq!(published.key, "company1");
+ assert_eq!(published.envelope["metadata"]["entity_type"], "COMPANY");
+}
+
+#[tokio::test]
+async fn bulk_entity_property_event_removal_only_no_row_does_not_publish() {
+ use crate::domain::model::{EntityOptionUpdateOutcome, EntityPropertyOptionSelection};
+
+ let property_definition_id = Uuid::from_u128(0xB301);
+ let absent_option_id = Uuid::from_u128(0xB302);
+
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_property_definition().return_once(move |_| {
+ Box::pin(async move { Ok(Some(multi_select_definition(property_definition_id, true))) })
+ });
+ repo.expect_count_valid_property_options().never();
+ repo.expect_bulk_update_entity_property_options()
+ .return_once(move |_, _, _| {
+ Box::pin(async move {
+ Ok(vec![EntityPropertyOptionSelection {
+ property_definition_id,
+ option_ids: Vec::new(),
+ mutation: None,
+ }])
+ })
+ });
+ let event_broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, event_broker.clone());
+ let receipts = vec![edit_receipt("doc1", EntityType::Document)];
+
+ let outcomes = service
+ .bulk_update_entities_property_options(
+ &receipts,
+ property_definition_id,
+ Vec::new(),
+ vec![absent_option_id],
+ )
+ .await
+ .unwrap();
+
+ assert!(matches!(
+ &outcomes[0],
+ EntityOptionUpdateOutcome::Applied { option_ids } if option_ids.is_empty()
+ ));
+ assert!(event_broker.events().is_empty());
+}
+
#[tokio::test]
async fn test_bulk_update_entity_property_options_happy_path() {
use crate::domain::model::{EntityPropertyOptionSelection, EntityPropertyOptionUpdate};
@@ -1539,6 +3453,12 @@ async fn test_bulk_update_entity_property_options_happy_path() {
Ok(vec![EntityPropertyOptionSelection {
property_definition_id: def_id,
option_ids: vec![add_id],
+ mutation: Some(entity_property_mutation(
+ "doc1",
+ EntityType::Document,
+ def_id,
+ Some(PropertyValue::SelectOption(vec![add_id])),
+ )),
}])
})
});
@@ -1564,6 +3484,15 @@ async fn test_bulk_update_entity_property_options_happy_path() {
assert_eq!(selections.len(), 1);
assert_eq!(selections[0].property_definition_id, def_id);
assert_eq!(selections[0].option_ids, vec![add_id]);
+ let mutation = selections[0]
+ .mutation
+ .as_ref()
+ .expect("persisted update should carry its mutation snapshot");
+ assert_eq!(mutation.property.entity_id, "doc1");
+ assert_eq!(
+ mutation.value,
+ Some(PropertyValue::SelectOption(vec![add_id]))
+ );
}
#[tokio::test]
@@ -1665,6 +3594,7 @@ async fn test_bulk_update_entity_property_options_dedupes_added_options() {
Ok(vec![EntityPropertyOptionSelection {
property_definition_id: def_id,
option_ids: vec![add_id],
+ mutation: None,
}])
})
});
@@ -1724,6 +3654,7 @@ async fn test_bulk_update_entities_applies_delta_in_input_order() {
Ok(vec![EntityPropertyOptionSelection {
property_definition_id: def_id,
option_ids: vec![final_id],
+ mutation: None,
}])
})
});
@@ -1787,6 +3718,7 @@ async fn test_bulk_update_entities_is_best_effort_on_per_entity_write_failure()
Ok(vec![EntityPropertyOptionSelection {
property_definition_id: def_id,
option_ids: vec![add_id],
+ mutation: None,
}])
})
}
@@ -1842,6 +3774,7 @@ async fn test_bulk_update_entities_fails_entity_that_rejects_property_type() {
Ok(vec![EntityPropertyOptionSelection {
property_definition_id: def_id,
option_ids: vec![add_id],
+ mutation: None,
}])
})
});
diff --git a/crates/properties/src/inbound/axum_router/test.rs b/crates/properties/src/inbound/axum_router/test.rs
index 26a94fdcd6..c772bf4e7a 100644
--- a/crates/properties/src/inbound/axum_router/test.rs
+++ b/crates/properties/src/inbound/axum_router/test.rs
@@ -522,6 +522,7 @@ async fn bulk_options_across_entities_skips_denied_and_applies_granted() {
Ok(vec![EntityPropertyOptionSelection {
property_definition_id: property_id,
option_ids: vec![option_id],
+ mutation: None,
}])
})
});
diff --git a/crates/properties/src/outbound/entity_property_queries.rs b/crates/properties/src/outbound/entity_property_queries.rs
index a155740c6b..c5af634460 100644
--- a/crates/properties/src/outbound/entity_property_queries.rs
+++ b/crates/properties/src/outbound/entity_property_queries.rs
@@ -5,7 +5,40 @@ use models_properties::{EntityReference, EntityType};
use sqlx::{Pool, Postgres};
use uuid::Uuid;
-use crate::domain::model::{EntityPropertyOptionSelection, EntityPropertyOptionUpdate};
+use crate::domain::model::{
+ EntityPropertyMutationSnapshot, EntityPropertyOptionSelection, EntityPropertyOptionUpdate,
+};
+
+struct EntityPropertyMutationRow {
+ id: Uuid,
+ entity_id: String,
+ entity_type: EntityType,
+ property_definition_id: Uuid,
+ value: Option<serde_json::Value>,
+ created_at: chrono::DateTime<chrono::Utc>,
+ updated_at: chrono::DateTime<chrono::Utc>,
+}
+
+impl EntityPropertyMutationRow {
+ fn into_snapshot(self) -> anyhow::Result<EntityPropertyMutationSnapshot> {
+ let value = match self.value {
+ Some(value) if !value.is_null() => Some(serde_json::from_value(value)?),
+ Some(_) | None => None,
+ };
+
+ 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,
+ })
+ }
+}
/// Upsert an entity property value (insert or update).
/// If the property doesn't exist, it will be created and attached to the entity.
@@ -72,10 +105,11 @@ pub async fn add_entity_property_option(
entity_type: EntityType,
property_definition_id: Uuid,
option_id: Uuid,
-) -> anyhow::Result<()> {
+) -> anyhow::Result<EntityPropertyMutationSnapshot> {
let id = macro_uuid::generate_uuid_v7();
- sqlx::query!(
+ let row = sqlx::query_as!(
+ EntityPropertyMutationRow,
r#"
INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)
VALUES (
@@ -97,6 +131,14 @@ pub async fn add_entity_property_option(
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",
+ created_at,
+ updated_at
"#,
id,
entity_id,
@@ -104,10 +146,10 @@ pub async fn add_entity_property_option(
property_definition_id,
option_id.to_string(),
)
- .execute(pool)
+ .fetch_one(pool)
.await?;
- Ok(())
+ row.into_snapshot()
}
/// Atomically remove one option from a multi-select entity property value. A
@@ -120,8 +162,9 @@ pub async fn remove_entity_property_option(
entity_type: EntityType,
property_definition_id: Uuid,
option_id: Uuid,
-) -> anyhow::Result<()> {
- sqlx::query!(
+) -> anyhow::Result<Option<EntityPropertyMutationSnapshot>> {
+ let row = sqlx::query_as!(
+ EntityPropertyMutationRow,
r#"
UPDATE entity_properties
SET values = jsonb_set(
@@ -142,16 +185,25 @@ pub async fn remove_entity_property_option(
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",
+ created_at,
+ updated_at
"#,
entity_id,
entity_type as EntityType,
property_definition_id,
option_id.to_string(),
)
- .execute(pool)
+ .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
@@ -235,29 +287,42 @@ pub async fn bulk_update_entity_property_options(
);
// Nothing to add and no row to remove from: a no-op, leave the DB alone.
- if row_exists {
+ let mutation = if row_exists {
let value_json = serde_json::json!({
"type": "SelectOption",
"value": final_ids,
});
- sqlx::query!(
+ 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",
+ created_at,
+ updated_at
"#,
entity_id,
entity_type as EntityType,
update.property_definition_id,
value_json,
)
- .execute(&mut *tx)
+ .fetch_one(&mut *tx)
.await?;
- }
+ Some(row.into_snapshot()?)
+ } else {
+ None
+ };
selections.push(EntityPropertyOptionSelection {
property_definition_id: update.property_definition_id,
option_ids: final_ids,
+ mutation,
});
}
diff --git a/crates/properties/src/outbound/options_test.rs b/crates/properties/src/outbound/options_test.rs
index 3e07f258ca..2630d7a71d 100644
--- a/crates/properties/src/outbound/options_test.rs
+++ b/crates/properties/src/outbound/options_test.rs
@@ -352,12 +352,38 @@ async fn get_or_create_tag_definition_is_idempotent(pool: Pool<Postgres>) -> any
let owner = PropertyDefinitionOwner::Team(team_1());
let first = repo.get_or_create_tag_definition(owner).await?;
- assert_eq!(first.data_type, DataType::Tag);
- assert!(first.is_multi_select);
+ assert!(first.created);
+ assert_eq!(first.definition.data_type, DataType::Tag);
+ assert!(first.definition.is_multi_select);
// A second call returns the same definition rather than creating a duplicate.
let second = repo.get_or_create_tag_definition(owner).await?;
- assert_eq!(first.id, second.id);
+ assert!(!second.created);
+ assert_eq!(first.definition.id, second.definition.id);
+
+ Ok(())
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties"))
+)]
+async fn get_or_create_tag_definition_race_reuses_winner(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let first_repo = PropertiesPgRepo::new(pool.clone());
+ let second_repo = PropertiesPgRepo::new(pool);
+ let owner = PropertyDefinitionOwner::Team(team_1());
+
+ let (first, second) = tokio::join!(
+ first_repo.get_or_create_tag_definition(owner),
+ second_repo.get_or_create_tag_definition(owner),
+ );
+ let first = first?;
+ let second = second?;
+
+ assert_ne!(first.created, second.created);
+ assert_eq!(first.definition.id, second.definition.id);
Ok(())
}
@@ -374,9 +400,13 @@ async fn get_tag_definition_none_then_some(pool: Pool<Postgres>) -> anyhow::Resu
assert!(before.is_none());
let created = repo.get_or_create_tag_definition(owner).await?;
+ assert!(created.created);
let after = repo.get_tag_definition(owner).await?;
- assert_eq!(after.map(|d| d.id), Some(created.id));
+ assert_eq!(
+ after.map(|definition| definition.id),
+ Some(created.definition.id)
+ );
Ok(())
}
@@ -397,11 +427,13 @@ async fn get_or_create_tag_definition_coexists_with_same_named_property(
// Provisioning the tag set still succeeds: tag definitions are exempt from the
// display-name uniqueness that applies to user-created properties.
- let tag_def = repo.get_or_create_tag_definition(owner).await?;
- assert_eq!(tag_def.data_type, DataType::Tag);
+ let tag_definition = repo.get_or_create_tag_definition(owner).await?;
+ assert!(tag_definition.created);
+ assert_eq!(tag_definition.definition.data_type, DataType::Tag);
let again = repo.get_or_create_tag_definition(owner).await?;
- assert_eq!(tag_def.id, again.id);
+ assert!(!again.created);
+ assert_eq!(tag_definition.definition.id, again.definition.id);
Ok(())
}
diff --git a/crates/properties/src/outbound/properties_pg_repo.rs b/crates/properties/src/outbound/properties_pg_repo.rs
index 3a096bb5ba..caccb16cb8 100644
--- a/crates/properties/src/outbound/properties_pg_repo.rs
+++ b/crates/properties/src/outbound/properties_pg_repo.rs
@@ -14,7 +14,8 @@ use super::{
property_definition_queries, property_option_queries, task_property_queries,
};
use crate::domain::model::{
- EntityPropertiesKey, EntityPropertyInfo, PropertyDefinitionOwner, UpdatePropertyOptionOutcome,
+ EntityPropertiesKey, EntityPropertyInfo, EntityPropertyMutationSnapshot,
+ GetOrCreateTagDefinitionResult, PropertyDefinitionOwner, UpdatePropertyOptionOutcome,
};
use crate::domain::ports::PropertiesRepo;
use models_properties::DataType;
@@ -228,7 +229,7 @@ impl PropertiesRepo for PropertiesPgRepo {
async fn get_or_create_tag_definition(
&self,
owner: PropertyDefinitionOwner<'_>,
- ) -> Result<PropertyDefinition, Self::Err> {
+ ) -> Result<GetOrCreateTagDefinitionResult, Self::Err> {
property_definition_queries::get_or_create_tag_definition(&self.pool, owner).await
}
@@ -271,7 +272,7 @@ impl PropertiesRepo for PropertiesPgRepo {
entity_type: EntityType,
property_definition_id: Uuid,
option_id: Uuid,
- ) -> Result<(), Self::Err> {
+ ) -> Result<EntityPropertyMutationSnapshot, Self::Err> {
entity_property_queries::add_entity_property_option(
&self.pool,
entity_id,
@@ -289,7 +290,7 @@ impl PropertiesRepo for PropertiesPgRepo {
entity_type: EntityType,
property_definition_id: Uuid,
option_id: Uuid,
- ) -> Result<(), Self::Err> {
+ ) -> Result<Option<EntityPropertyMutationSnapshot>, Self::Err> {
entity_property_queries::remove_entity_property_option(
&self.pool,
entity_id,
diff --git a/crates/properties/src/outbound/property_definition_queries.rs b/crates/properties/src/outbound/property_definition_queries.rs
index 081ebb627a..8b4146d95d 100644
--- a/crates/properties/src/outbound/property_definition_queries.rs
+++ b/crates/properties/src/outbound/property_definition_queries.rs
@@ -10,7 +10,7 @@ use models_properties::{DataType, EntityType, db};
use sqlx::{Pool, Postgres};
use uuid::Uuid;
-use crate::domain::model::PropertyDefinitionOwner;
+use crate::domain::model::{GetOrCreateTagDefinitionResult, PropertyDefinitionOwner};
/// Gets a single property definition by ID (includes system properties).
pub async fn get_property_definition(
@@ -483,9 +483,12 @@ pub async fn get_tag_definition(
pub async fn get_or_create_tag_definition(
pool: &Pool<Postgres>,
owner: PropertyDefinitionOwner<'_>,
-) -> anyhow::Result<PropertyDefinition> {
- if let Some(existing) = get_tag_definition(pool, owner).await? {
- return Ok(existing);
+) -> anyhow::Result<GetOrCreateTagDefinitionResult> {
+ if let Some(definition) = get_tag_definition(pool, owner).await? {
+ return Ok(GetOrCreateTagDefinitionResult {
+ definition,
+ created: false,
+ });
}
match create_property_definition(
@@ -499,10 +502,16 @@ pub async fn get_or_create_tag_definition(
)
.await
{
- Ok(def) => Ok(def),
- Err(create_err) => match get_tag_definition(pool, owner).await? {
- Some(existing) => Ok(existing),
- None => Err(create_err),
+ Ok(definition) => Ok(GetOrCreateTagDefinitionResult {
+ definition,
+ created: true,
+ }),
+ Err(create_error) => match get_tag_definition(pool, owner).await? {
+ Some(definition) => Ok(GetOrCreateTagDefinitionResult {
+ definition,
+ created: false,
+ }),
+ None => Err(create_error),
},
}
}
diff --git a/crates/properties/src/outbound/test.rs b/crates/properties/src/outbound/test.rs
index e5a19fff23..003a628eb7 100644
--- a/crates/properties/src/outbound/test.rs
+++ b/crates/properties/src/outbound/test.rs
@@ -2,12 +2,13 @@
use super::properties_pg_repo::PropertiesPgRepo;
use crate::PropertiesServiceImpl;
-use crate::domain::model::{EditReceipt, canonical_entity_type};
+use crate::domain::model::{EditReceipt, EntityPropertyMutationSnapshot, canonical_entity_type};
use crate::domain::ports::{MockNotificationService, MockPermissionService, PropertiesRepo};
use crate::domain::service::PropertiesService;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use macro_user_id::user_id::MacroUserIdStr;
use models_properties::EntityType;
+use models_properties::service::property_value::PropertyValue;
use sqlx::{Pool, Postgres};
use std::sync::Arc;
use system_properties::SystemPropertyKey;
@@ -747,6 +748,26 @@ async fn read_select_value(
.expect("read value")
}
+fn assert_option_mutation(
+ mutation: &EntityPropertyMutationSnapshot,
+ entity_id: &str,
+ property_definition_id: Uuid,
+ option_ids: Vec<Uuid>,
+) {
+ assert_ne!(mutation.property.id, Uuid::nil());
+ assert_eq!(mutation.property.entity_id, entity_id);
+ assert_eq!(mutation.property.entity_type, EntityType::Document);
+ assert_eq!(
+ mutation.property.property_definition_id,
+ property_definition_id
+ );
+ assert!(mutation.property.created_at <= mutation.property.updated_at);
+ assert_eq!(
+ mutation.value,
+ Some(PropertyValue::SelectOption(option_ids))
+ );
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../fixtures", scripts("properties_seed"))
@@ -758,15 +779,29 @@ async fn add_option_attaches_appends_and_dedupes(pool: Pool<Postgres>) -> anyhow
let opt_a = macro_uuid::generate_uuid_v7();
let opt_b = macro_uuid::generate_uuid_v7();
- // First add attaches the property and creates the value.
- repo.add_entity_property_option(entity_id, EntityType::Document, def_id, opt_a)
+ // First add attaches the property and returns its complete persisted state.
+ let first = repo
+ .add_entity_property_option(entity_id, EntityType::Document, def_id, opt_a)
.await?;
- // Second add appends to the current stored value.
- repo.add_entity_property_option(entity_id, EntityType::Document, def_id, opt_b)
+ assert_option_mutation(&first, entity_id, def_id, vec![opt_a]);
+
+ // Second add appends to the current stored value while preserving row identity.
+ let second = repo
+ .add_entity_property_option(entity_id, EntityType::Document, def_id, opt_b)
.await?;
- // Re-adding a present option is a no-op.
- repo.add_entity_property_option(entity_id, EntityType::Document, def_id, opt_a)
+ assert_option_mutation(&second, entity_id, def_id, vec![opt_a, opt_b]);
+ assert_eq!(second.property.id, first.property.id);
+ assert_eq!(second.property.created_at, first.property.created_at);
+ assert!(second.property.updated_at >= first.property.updated_at);
+
+ // Re-adding a present option is deduped in both storage and the snapshot.
+ let duplicate = repo
+ .add_entity_property_option(entity_id, EntityType::Document, def_id, opt_a)
.await?;
+ assert_option_mutation(&duplicate, entity_id, def_id, vec![opt_a, opt_b]);
+ assert_eq!(duplicate.property.id, first.property.id);
+ assert_eq!(duplicate.property.created_at, first.property.created_at);
+ assert!(duplicate.property.updated_at >= second.property.updated_at);
assert_eq!(
read_select_value(&pool, entity_id, def_id).await,
@@ -788,33 +823,63 @@ async fn remove_option_strips_and_is_tolerant(pool: Pool<Postgres>) -> anyhow::R
let opt_b = macro_uuid::generate_uuid_v7();
let opt_c = macro_uuid::generate_uuid_v7();
- for opt in [opt_a, opt_b, opt_c] {
- repo.add_entity_property_option(entity_id, EntityType::Document, def_id, opt)
- .await?;
- }
-
- // Remove a middle option.
- repo.remove_entity_property_option(entity_id, EntityType::Document, def_id, opt_b)
+ let attached = repo
+ .add_entity_property_option(entity_id, EntityType::Document, def_id, opt_a)
+ .await?;
+ repo.add_entity_property_option(entity_id, EntityType::Document, def_id, opt_b)
.await?;
+ repo.add_entity_property_option(entity_id, EntityType::Document, def_id, opt_c)
+ .await?;
+
+ // Remove a middle option and return the full remaining value.
+ let removed_middle = repo
+ .remove_entity_property_option(entity_id, EntityType::Document, def_id, opt_b)
+ .await?
+ .expect("present option should produce a mutation snapshot");
+ assert_option_mutation(&removed_middle, entity_id, def_id, vec![opt_a, opt_c]);
+ assert_eq!(removed_middle.property.id, attached.property.id);
assert_eq!(
- read_select_value(&pool, entity_id, def_id).await,
- serde_json::json!({"type": "SelectOption", "value": [opt_a, opt_c]})
+ removed_middle.property.created_at,
+ attached.property.created_at
);
+ assert!(removed_middle.property.updated_at >= attached.property.updated_at);
- // Removing an absent option is a no-op.
+ // Removing an absent option reports no mutation and leaves the value unchanged.
let absent = macro_uuid::generate_uuid_v7();
- repo.remove_entity_property_option(entity_id, EntityType::Document, def_id, absent)
+ let absent_result = repo
+ .remove_entity_property_option(entity_id, EntityType::Document, def_id, absent)
.await?;
+ assert!(absent_result.is_none());
assert_eq!(
read_select_value(&pool, entity_id, def_id).await,
serde_json::json!({"type": "SelectOption", "value": [opt_a, opt_c]})
);
- // Removing the rest leaves an empty array, not NULL.
- repo.remove_entity_property_option(entity_id, EntityType::Document, def_id, opt_a)
- .await?;
- repo.remove_entity_property_option(entity_id, EntityType::Document, def_id, opt_c)
+ // Removing from an unattached property is also represented as no mutation.
+ let unattached_result = repo
+ .remove_entity_property_option(
+ "entity-tags-remove-unattached",
+ EntityType::Document,
+ def_id,
+ absent,
+ )
.await?;
+ assert!(unattached_result.is_none());
+
+ // Removing the rest leaves an empty array, not NULL.
+ let removed_a = repo
+ .remove_entity_property_option(entity_id, EntityType::Document, def_id, opt_a)
+ .await?
+ .expect("present option should produce a mutation snapshot");
+ assert_option_mutation(&removed_a, entity_id, def_id, vec![opt_c]);
+ let removed_c = repo
+ .remove_entity_property_option(entity_id, EntityType::Document, def_id, opt_c)
+ .await?
+ .expect("present option should produce a mutation snapshot");
+ assert_option_mutation(&removed_c, entity_id, def_id, Vec::new());
+ assert_eq!(removed_c.property.id, attached.property.id);
+ assert_eq!(removed_c.property.created_at, attached.property.created_at);
+ assert!(removed_c.property.updated_at >= removed_a.property.updated_at);
assert_eq!(
read_select_value(&pool, entity_id, def_id).await,
serde_json::json!({"type": "SelectOption", "value": []})
@@ -872,6 +937,11 @@ async fn bulk_update_options_composes_and_returns_finals(
assert_eq!(first.len(), 1);
assert_eq!(first[0].property_definition_id, def_id);
assert_eq!(first[0].option_ids, vec![opt_a, opt_b]);
+ let first_mutation = first[0]
+ .mutation
+ .as_ref()
+ .expect("attached property should carry a mutation snapshot");
+ assert_option_mutation(first_mutation, entity_id, def_id, vec![opt_a, opt_b]);
// Second bulk update removes A and adds C, composing with the stored value.
let second = repo
@@ -882,6 +952,17 @@ async fn bulk_update_options_composes_and_returns_finals(
)
.await?;
assert_eq!(second[0].option_ids, vec![opt_b, opt_c]);
+ let second_mutation = second[0]
+ .mutation
+ .as_ref()
+ .expect("updated property should carry a mutation snapshot");
+ assert_option_mutation(second_mutation, entity_id, def_id, vec![opt_b, opt_c]);
+ assert_eq!(second_mutation.property.id, first_mutation.property.id);
+ assert_eq!(
+ second_mutation.property.created_at,
+ first_mutation.property.created_at
+ );
+ assert!(second_mutation.property.updated_at >= first_mutation.property.updated_at);
assert_eq!(
read_select_value(&pool, entity_id, def_id).await,
serde_json::json!({"type": "SelectOption", "value": [opt_b, opt_c]})
@@ -1023,6 +1104,10 @@ async fn bulk_update_options_removal_only_on_unattached_is_noop(
.await?;
assert_eq!(result.len(), 1);
assert_eq!(result[0].option_ids, Vec::<Uuid>::new());
+ assert!(
+ result[0].mutation.is_none(),
+ "unattached removal-only update must not report a mutation"
+ );
let row_count: i64 = sqlx::query_scalar(
r#"
diff --git a/services/document_storage_service/src/api/context.rs b/services/document_storage_service/src/api/context.rs
index c124d31529..13ce02e84b 100644
--- a/services/document_storage_service/src/api/context.rs
+++ b/services/document_storage_service/src/api/context.rs
@@ -87,8 +87,8 @@ use projects_hex::{
};
use properties::{
NotificationServiceImpl, PermissionServiceImpl, PropertiesPgRepo, PropertiesServiceImpl,
+ inbound::axum_router::PropertiesRouterState,
};
-use properties_service::PropertiesHandlerState;
use readonly_pool::ReadOnlyPool;
use search_service::SearchHandlerState;
use soup::{
@@ -180,8 +180,13 @@ pub(crate) type PropertiesService = PropertiesServiceImpl<
PropertiesPgRepo,
PermissionServiceImpl<EntityAccessService>,
NotificationServiceImpl<NotificationIngressType>,
+ DssEventBroker,
>;
+/// Concrete properties router state wired into DSS.
+pub(crate) type PropertiesHandlerState =
+ PropertiesRouterState<PropertiesService, EntityAccessService, AuthorizationService>;
+
/// Type alias for the entity access service.
pub(crate) type EntityAccessService = EntityAccessServiceImpl<PgAccessRepository>;
diff --git a/services/document_storage_service/src/api/mod.rs b/services/document_storage_service/src/api/mod.rs
index edb7e9f1ff..959cfe6887 100644
--- a/services/document_storage_service/src/api/mod.rs
+++ b/services/document_storage_service/src/api/mod.rs
@@ -1,4 +1,4 @@
-use crate::api::context::ApiContext;
+use crate::api::context::{ApiContext, PropertiesHandlerState};
use anyhow::Context;
use axum::Router;
use axum::extract::FromRef;
@@ -9,7 +9,6 @@ use github::inbound::github_sync_router::GithubSyncRouterState;
use macro_axum_utils::compose_layers;
use macro_tower_layers::MacroRequestIdAndTracingLayer;
use model::version::{ServiceNameState, VersionedApiServiceName, validate_api_version};
-use properties_service::PropertiesHandlerState;
use search_service::SearchHandlerState;
use std::time::Duration;
use tower::ServiceBuilder;
@@ -183,7 +182,7 @@ fn api_router(state: ApiContext) -> Router {
)
.nest(
"/properties",
- properties_service::properties_router()
+ properties::inbound::axum_router::router()
.with_state(PropertiesHandlerState::from_ref(&state)),
)
.nest(
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index bb5e1031fc..0175ac1bc5 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -375,6 +375,7 @@ async fn main() -> anyhow::Result<()> {
Some(permission_checker),
Some(notification_service),
)
+ .with_event_broker(macro_event_broker.clone())
.with_search_indexer(Arc::new(
crate::service::property_search_indexer::SqsPropertySearchIndexer::new(
sqs_client.clone(),
@@ -1099,6 +1100,7 @@ async fn main() -> anyhow::Result<()> {
redis_client: api_context.redis_client.clone(),
sync_service_client: api_context.sync_service_client.clone(),
editing_worker_client,
+ properties_service: api_context.properties_service.clone(),
};
tokio::spawn(async move {
diff --git a/services/document_storage_service/src/service/delete_document_worker/handle.rs b/services/document_storage_service/src/service/delete_document_worker/handle.rs
index 406df57e6d..64a27cee4c 100644
--- a/services/document_storage_service/src/service/delete_document_worker/handle.rs
+++ b/services/document_storage_service/src/service/delete_document_worker/handle.rs
@@ -1,7 +1,7 @@
use anyhow::Context;
use documents_hex::domain::ports::editing::EditingWorkerService;
-use models_properties::{EntityReference, EntityType};
-use properties::outbound::entity_property_queries as entity_properties_delete;
+use entity_access::domain::models::EntityType;
+use properties::{EditReceipt, PropertiesService as _};
use super::DeleteDocumentWorkerContext;
@@ -112,8 +112,10 @@ pub async fn handle(
// Delete document properties
tracing::trace!(document_id=%document_id, "deleting document properties");
- let entity_reference = EntityReference::new(document_id, EntityType::Document);
- let _ = entity_properties_delete::delete_entity_properties(&ctx.db, &entity_reference)
+ let cleanup_receipt = document_cleanup_receipt(document_id);
+ let _ = ctx
+ .properties_service
+ .delete_entity_properties(&cleanup_receipt)
.await
.inspect_err(|e| tracing::error!(error=?e, "failed to delete entity properties"));
tracing::trace!(document_id=%document_id, "deleted document properties");
@@ -125,6 +127,10 @@ pub async fn handle(
Ok(())
}
+pub(crate) fn document_cleanup_receipt(document_id: &str) -> EditReceipt {
+ EditReceipt::dangerously_assert_internal_user(document_id, EntityType::Document)
+}
+
pub(crate) fn count_occurrences(strings: Vec<String>) -> Vec<(String, i64)> {
use std::collections::HashMap;
diff --git a/services/document_storage_service/src/service/delete_document_worker/mod.rs b/services/document_storage_service/src/service/delete_document_worker/mod.rs
index 99244a089f..4528fef691 100644
--- a/services/document_storage_service/src/service/delete_document_worker/mod.rs
+++ b/services/document_storage_service/src/service/delete_document_worker/mod.rs
@@ -4,7 +4,7 @@ use documents_hex::outbound::editing_worker_client::ReqwestEditingWorkerClient;
use macro_sha_count_client::Redis;
use sync_service_client::SyncServiceClient;
-use crate::service::s3::S3;
+use crate::{api::context::PropertiesService, service::s3::S3};
mod handle;
#[cfg(test)]
@@ -19,6 +19,7 @@ pub struct DeleteDocumentWorkerContext {
pub redis_client: Arc<Redis>,
pub sync_service_client: Arc<SyncServiceClient>,
pub editing_worker_client: Arc<ReqwestEditingWorkerClient>,
+ pub properties_service: Arc<PropertiesService>,
}
/// Runs the delete document worker in an infinite loop, restarting on failure.
diff --git a/services/document_storage_service/src/service/delete_document_worker/test.rs b/services/document_storage_service/src/service/delete_document_worker/test.rs
index c3b3b3b873..088a8a5f13 100644
--- a/services/document_storage_service/src/service/delete_document_worker/test.rs
+++ b/services/document_storage_service/src/service/delete_document_worker/test.rs
@@ -1,4 +1,17 @@
-use super::handle::count_occurrences;
+use entity_access::domain::models::{EntityAccessAuth, EntityType};
+
+use super::handle::{count_occurrences, document_cleanup_receipt};
+
+#[test]
+fn document_cleanup_receipt_is_internal_for_the_document() {
+ let document_id = "410ee0f3-80df-4ae7-b9a6-5c87fe5408af";
+
+ let receipt = document_cleanup_receipt(document_id);
+
+ assert_eq!(receipt.entity().entity_id, document_id);
+ assert_eq!(receipt.entity().entity_type, EntityType::Document);
+ assert!(matches!(receipt.auth(), EntityAccessAuth::Internal));
+}
#[test]
fn test_count_occurrences() {