Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(ownership): entity_registry owning crate for the entity table (#6418)
Will Hutchinson1e5a44ad0ebd
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex ebb3bf4243..5d0cfcfcb5 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -3944,6 +3944,26 @@"crates/remote_env_var","crates/workspace-hack"],+ "entity_registry": [+ "crates/bot_id",+ "crates/cowlike",+ "crates/entity_registry/entity_registry",+ "crates/entity_registry/shared_entity_registry",+ "crates/macro_user_id",+ "crates/model-entity",+ "crates/model_owner",+ "crates/workspace-hack"+ ],+ "entity_registry_db_utils": [+ "crates/bot_id",+ "crates/cowlike",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry",+ "crates/macro_user_id",+ "crates/model-entity",+ "crates/model_owner",+ "crates/workspace-hack"+ ],"favorites": ["crates/agent","crates/ai_toolset",@@ -7465,6 +7485,15 @@"crates/share_permission_db_utils","crates/workspace-hack"],+ "shared_entity_registry": [+ "crates/bot_id",+ "crates/cowlike",+ "crates/entity_registry/shared_entity_registry",+ "crates/macro_user_id",+ "crates/model-entity",+ "crates/model_owner",+ "crates/workspace-hack"+ ],"skills": ["crates/activity","crates/agent",diff --git a/.sqlx/query-02a6f6ca11f7e3b0e3a3f4483c40b3342f2ee0f4f364262d07bff4053d56091a.json b/.sqlx/query-02a6f6ca11f7e3b0e3a3f4483c40b3342f2ee0f4f364262d07bff4053d56091a.jsonnew file mode 100644index 0000000000..f599ee3f78--- /dev/null+++ b/.sqlx/query-02a6f6ca11f7e3b0e3a3f4483c40b3342f2ee0f4f364262d07bff4053d56091a.json@@ -0,0 +1,34 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT created_at, updated_at, deleted_at\n FROM entity\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 1,+ "name": "updated_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 2,+ "name": "deleted_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ true+ ]+ },+ "hash": "02a6f6ca11f7e3b0e3a3f4483c40b3342f2ee0f4f364262d07bff4053d56091a"+}diff --git a/.sqlx/query-0a3bab7815e0c81376377a61b42bf1cc7f7170f806e5b3e5b5aa0707fc6e1a34.json b/.sqlx/query-0a3bab7815e0c81376377a61b42bf1cc7f7170f806e5b3e5b5aa0707fc6e1a34.jsonnew file mode 100644index 0000000000..dd105edbe3--- /dev/null+++ b/.sqlx/query-0a3bab7815e0c81376377a61b42bf1cc7f7170f806e5b3e5b5aa0707fc6e1a34.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE entity SET deleted_at = $2 WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "0a3bab7815e0c81376377a61b42bf1cc7f7170f806e5b3e5b5aa0707fc6e1a34"+}diff --git a/.sqlx/query-26385b083444e21e4a6099957ae602a5f868f000b123f30cd90c5d1a878001e5.json b/.sqlx/query-26385b083444e21e4a6099957ae602a5f868f000b123f30cd90c5d1a878001e5.jsonnew file mode 100644index 0000000000..4ee3b36f55--- /dev/null+++ b/.sqlx/query-26385b083444e21e4a6099957ae602a5f868f000b123f30cd90c5d1a878001e5.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT count(*) AS \"count!\"\n FROM entity\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "count!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "26385b083444e21e4a6099957ae602a5f868f000b123f30cd90c5d1a878001e5"+}diff --git a/.sqlx/query-2bc51ed67fd55ee4a5c52ce23334a8d5ea4ebbd9fca215b43f38720faca4de68.json b/.sqlx/query-2bc51ed67fd55ee4a5c52ce23334a8d5ea4ebbd9fca215b43f38720faca4de68.jsonnew file mode 100644index 0000000000..de1be84b86--- /dev/null+++ b/.sqlx/query-2bc51ed67fd55ee4a5c52ce23334a8d5ea4ebbd9fca215b43f38720faca4de68.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT deleted_at\n FROM entity\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "deleted_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "2bc51ed67fd55ee4a5c52ce23334a8d5ea4ebbd9fca215b43f38720faca4de68"+}diff --git a/.sqlx/query-2fef588eb0c7c780c425d80b68e1ee5c64de8e69b9962c11040424d5965589df.json b/.sqlx/query-2fef588eb0c7c780c425d80b68e1ee5c64de8e69b9962c11040424d5965589df.jsonnew file mode 100644index 0000000000..0519674f8b--- /dev/null+++ b/.sqlx/query-2fef588eb0c7c780c425d80b68e1ee5c64de8e69b9962c11040424d5965589df.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT count(*) FILTER (WHERE deleted_at IS NULL) AS \"live!\",\n count(*) FILTER (WHERE deleted_at IS NOT NULL) AS \"deleted!\"\n FROM entity WHERE entity_type = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "live!",+ "type_info": "Int8"+ },+ {+ "ordinal": 1,+ "name": "deleted!",+ "type_info": "Int8"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null,+ null+ ]+ },+ "hash": "2fef588eb0c7c780c425d80b68e1ee5c64de8e69b9962c11040424d5965589df"+}diff --git a/.sqlx/query-5314b6e4dec58805c137520859d80a20dfc397852af41276d4296fcb22716467.json b/.sqlx/query-5314b6e4dec58805c137520859d80a20dfc397852af41276d4296fcb22716467.jsonnew file mode 100644index 0000000000..6fd04370b4--- /dev/null+++ b/.sqlx/query-5314b6e4dec58805c137520859d80a20dfc397852af41276d4296fcb22716467.json@@ -0,0 +1,82 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, entity_type, owner_type AS \"owner_type: OwnerType\", owner_id,\n created_at, updated_at, deleted_at\n FROM entity\n WHERE owner_type = $1 AND owner_id = $2\n AND deleted_at IS NULL\n AND ($3::text IS NULL OR entity_type = $3)\n ORDER BY created_at DESC, id DESC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "entity_type",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "owner_type: OwnerType",+ "type_info": {+ "Custom": {+ "name": "entity_owner_type",+ "kind": {+ "Enum": [+ "user",+ "bot",+ "team"+ ]+ }+ }+ }+ },+ {+ "ordinal": 3,+ "name": "owner_id",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 5,+ "name": "updated_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 6,+ "name": "deleted_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ {+ "Custom": {+ "name": "entity_owner_type",+ "kind": {+ "Enum": [+ "user",+ "bot",+ "team"+ ]+ }+ }+ },+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false,+ true+ ]+ },+ "hash": "5314b6e4dec58805c137520859d80a20dfc397852af41276d4296fcb22716467"+}diff --git a/.sqlx/query-5df695a17a7f19c489348dc3e65d0e5c64358eb51196c26b7e1ebcab44303e90.json b/.sqlx/query-5df695a17a7f19c489348dc3e65d0e5c64358eb51196c26b7e1ebcab44303e90.jsonnew file mode 100644index 0000000000..d45c527cb6--- /dev/null+++ b/.sqlx/query-5df695a17a7f19c489348dc3e65d0e5c64358eb51196c26b7e1ebcab44303e90.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT created_at, updated_at\n FROM entity\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 1,+ "name": "updated_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "5df695a17a7f19c489348dc3e65d0e5c64358eb51196c26b7e1ebcab44303e90"+}diff --git a/.sqlx/query-6de453bd3bf250ae93753e375141608951500bba94fc3181aa29198489d4b44a.json b/.sqlx/query-6de453bd3bf250ae93753e375141608951500bba94fc3181aa29198489d4b44a.jsonnew file mode 100644index 0000000000..a14f8b94ee--- /dev/null+++ b/.sqlx/query-6de453bd3bf250ae93753e375141608951500bba94fc3181aa29198489d4b44a.json@@ -0,0 +1,69 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, entity_type, owner_type AS \"owner_type: OwnerType\", owner_id,\n created_at, updated_at, deleted_at\n FROM entity\n WHERE id = ANY($1)\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "entity_type",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "owner_type: OwnerType",+ "type_info": {+ "Custom": {+ "name": "entity_owner_type",+ "kind": {+ "Enum": [+ "user",+ "bot",+ "team"+ ]+ }+ }+ }+ },+ {+ "ordinal": 3,+ "name": "owner_id",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 5,+ "name": "updated_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 6,+ "name": "deleted_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "UuidArray"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false,+ true+ ]+ },+ "hash": "6de453bd3bf250ae93753e375141608951500bba94fc3181aa29198489d4b44a"+}diff --git a/.sqlx/query-6dea3e8741eefdd13756f768d7dfe731965bffc289104851a57c996c9584fb7d.json b/.sqlx/query-6dea3e8741eefdd13756f768d7dfe731965bffc289104851a57c996c9584fb7d.jsonnew file mode 100644index 0000000000..0738027649--- /dev/null+++ b/.sqlx/query-6dea3e8741eefdd13756f768d7dfe731965bffc289104851a57c996c9584fb7d.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE entity SET deleted_at = NULL WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "6dea3e8741eefdd13756f768d7dfe731965bffc289104851a57c996c9584fb7d"+}diff --git a/.sqlx/query-935e8fe906d9aee138cf007ce73d2f7e5c1cabab073366b0975a4d22e134f255.json b/.sqlx/query-935e8fe906d9aee138cf007ce73d2f7e5c1cabab073366b0975a4d22e134f255.jsonnew file mode 100644index 0000000000..afa93aa0bc--- /dev/null+++ b/.sqlx/query-935e8fe906d9aee138cf007ce73d2f7e5c1cabab073366b0975a4d22e134f255.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM entity WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "935e8fe906d9aee138cf007ce73d2f7e5c1cabab073366b0975a4d22e134f255"+}diff --git a/.sqlx/query-9930d7fd97a40d14df9fb2f1c54a64dc3562ad9e10dd564a972254cc0f2b03ab.json b/.sqlx/query-9930d7fd97a40d14df9fb2f1c54a64dc3562ad9e10dd564a972254cc0f2b03ab.jsonnew file mode 100644index 0000000000..13f1afb64b--- /dev/null+++ b/.sqlx/query-9930d7fd97a40d14df9fb2f1c54a64dc3562ad9e10dd564a972254cc0f2b03ab.json@@ -0,0 +1,20 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT now() AS \"now!\"",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "now!",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": []+ },+ "nullable": [+ null+ ]+ },+ "hash": "9930d7fd97a40d14df9fb2f1c54a64dc3562ad9e10dd564a972254cc0f2b03ab"+}diff --git a/.sqlx/query-a383d3ab095c24025440ea3210953c2dd7d8bcebab9549e1b0adaf430f0b6ff3.json b/.sqlx/query-a383d3ab095c24025440ea3210953c2dd7d8bcebab9549e1b0adaf430f0b6ff3.jsonnew file mode 100644index 0000000000..61f2382a73--- /dev/null+++ b/.sqlx/query-a383d3ab095c24025440ea3210953c2dd7d8bcebab9549e1b0adaf430f0b6ff3.json@@ -0,0 +1,45 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT owner_type AS \"owner_type: OwnerType\", owner_id, entity_type\n FROM entity\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "owner_type: OwnerType",+ "type_info": {+ "Custom": {+ "name": "entity_owner_type",+ "kind": {+ "Enum": [+ "user",+ "bot",+ "team"+ ]+ }+ }+ }+ },+ {+ "ordinal": 1,+ "name": "owner_id",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "entity_type",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false+ ]+ },+ "hash": "a383d3ab095c24025440ea3210953c2dd7d8bcebab9549e1b0adaf430f0b6ff3"+}diff --git a/.sqlx/query-a67fa6a323e15741039e8879190110d547bdd485bd282cb99b29fcf08e7ecb21.json b/.sqlx/query-a67fa6a323e15741039e8879190110d547bdd485bd282cb99b29fcf08e7ecb21.jsonnew file mode 100644index 0000000000..c744060c62--- /dev/null+++ b/.sqlx/query-a67fa6a323e15741039e8879190110d547bdd485bd282cb99b29fcf08e7ecb21.json@@ -0,0 +1,69 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id, entity_type, owner_type AS \"owner_type: OwnerType\", owner_id,\n created_at, updated_at, deleted_at\n FROM entity\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "entity_type",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "owner_type: OwnerType",+ "type_info": {+ "Custom": {+ "name": "entity_owner_type",+ "kind": {+ "Enum": [+ "user",+ "bot",+ "team"+ ]+ }+ }+ }+ },+ {+ "ordinal": 3,+ "name": "owner_id",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 5,+ "name": "updated_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 6,+ "name": "deleted_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ false,+ false,+ true+ ]+ },+ "hash": "a67fa6a323e15741039e8879190110d547bdd485bd282cb99b29fcf08e7ecb21"+}diff --git a/.sqlx/query-b539eeb9d4f9e9c08e53421f7e312749fa30a8aea7ee2e18b76067dae88248c5.json b/.sqlx/query-b539eeb9d4f9e9c08e53421f7e312749fa30a8aea7ee2e18b76067dae88248c5.jsonnew file mode 100644index 0000000000..ea80c0fc65--- /dev/null+++ b/.sqlx/query-b539eeb9d4f9e9c08e53421f7e312749fa30a8aea7ee2e18b76067dae88248c5.json@@ -0,0 +1,30 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO entity (id, entity_type, owner_type, owner_id, created_at, updated_at)\n VALUES ($1, $2, $3, $4, COALESCE($5::timestamptz, now()), COALESCE($6::timestamptz, now()))\n ON CONFLICT (id) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ {+ "Custom": {+ "name": "entity_owner_type",+ "kind": {+ "Enum": [+ "user",+ "bot",+ "team"+ ]+ }+ }+ },+ "Text",+ "Timestamptz",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "b539eeb9d4f9e9c08e53421f7e312749fa30a8aea7ee2e18b76067dae88248c5"+}diff --git a/.sqlx/query-d9ee439f6e09cee9add59d9ae2997b2fd6bc3e38e26a8c6b1571ff2a783a9e2e.json b/.sqlx/query-d9ee439f6e09cee9add59d9ae2997b2fd6bc3e38e26a8c6b1571ff2a783a9e2e.jsonnew file mode 100644index 0000000000..c0be316d98--- /dev/null+++ b/.sqlx/query-d9ee439f6e09cee9add59d9ae2997b2fd6bc3e38e26a8c6b1571ff2a783a9e2e.json@@ -0,0 +1,30 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO entity (id, entity_type, owner_type, owner_id, created_at, updated_at)\n VALUES ($1, $2, $3, $4, COALESCE($5::timestamptz, now()), COALESCE($6::timestamptz, now()))\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ {+ "Custom": {+ "name": "entity_owner_type",+ "kind": {+ "Enum": [+ "user",+ "bot",+ "team"+ ]+ }+ }+ },+ "Text",+ "Timestamptz",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "d9ee439f6e09cee9add59d9ae2997b2fd6bc3e38e26a8c6b1571ff2a783a9e2e"+}diff --git a/.sqlx/query-e1f683522c98d542fa8cfd432e85c135de1ad0aa1bc935efaff2bc76e63d196f.json b/.sqlx/query-e1f683522c98d542fa8cfd432e85c135de1ad0aa1bc935efaff2bc76e63d196f.jsonnew file mode 100644index 0000000000..a3ee67dabe--- /dev/null+++ b/.sqlx/query-e1f683522c98d542fa8cfd432e85c135de1ad0aa1bc935efaff2bc76e63d196f.json@@ -0,0 +1,39 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT owner_type AS \"owner_type: OwnerType\", owner_id\n FROM entity\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "owner_type: OwnerType",+ "type_info": {+ "Custom": {+ "name": "entity_owner_type",+ "kind": {+ "Enum": [+ "user",+ "bot",+ "team"+ ]+ }+ }+ }+ },+ {+ "ordinal": 1,+ "name": "owner_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false,+ false+ ]+ },+ "hash": "e1f683522c98d542fa8cfd432e85c135de1ad0aa1bc935efaff2bc76e63d196f"+}diff --git a/.sqlx/query-e8922297e98525c41f7828c0b5b67b275e6f78063b173af7d4969b9a27334c87.json b/.sqlx/query-e8922297e98525c41f7828c0b5b67b275e6f78063b173af7d4969b9a27334c87.jsonnew file mode 100644index 0000000000..15e74a6c98--- /dev/null+++ b/.sqlx/query-e8922297e98525c41f7828c0b5b67b275e6f78063b173af7d4969b9a27334c87.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE entity SET updated_at = $2 WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "e8922297e98525c41f7828c0b5b67b275e6f78063b173af7d4969b9a27334c87"+}diff --git a/.sqlx/query-f97f5ecab8c45210d2f056e514894d9d0680fd80ef0f7ba48f672dc3214abe6e.json b/.sqlx/query-f97f5ecab8c45210d2f056e514894d9d0680fd80ef0f7ba48f672dc3214abe6e.jsonnew file mode 100644index 0000000000..1b53b5828a--- /dev/null+++ b/.sqlx/query-f97f5ecab8c45210d2f056e514894d9d0680fd80ef0f7ba48f672dc3214abe6e.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE entity SET deleted_at = $2 WHERE id = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Timestamptz"+ ]+ },+ "nullable": []+ },+ "hash": "f97f5ecab8c45210d2f056e514894d9d0680fd80ef0f7ba48f672dc3214abe6e"+}diff --git a/.sqlx/query-fad1a7ec3b2d02e913a8f675cc735d0bd486f543621c6ab6a3d90caa4716c01c.json b/.sqlx/query-fad1a7ec3b2d02e913a8f675cc735d0bd486f543621c6ab6a3d90caa4716c01c.jsonnew file mode 100644index 0000000000..1cb9540fe6--- /dev/null+++ b/.sqlx/query-fad1a7ec3b2d02e913a8f675cc735d0bd486f543621c6ab6a3d90caa4716c01c.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT entity_type\n FROM entity\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "entity_type",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "fad1a7ec3b2d02e913a8f675cc735d0bd486f543621c6ab6a3d90caa4716c01c"+}diff --git a/Cargo.lock b/Cargo.lockindex 8f403d7331..50fc4ef63b 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -6318,6 +6318,39 @@ dependencies = ["workspace-hack",]+[[package]]+name = "entity_registry"+version = "0.1.0"+dependencies = [+ "chrono",+ "macro_db_migrator",+ "model-entity",+ "model_owner",+ "rootcause",+ "shared_entity_registry",+ "sqlx",+ "tokio",+ "tracing",+ "uuid",+ "workspace-hack",+]++[[package]]+name = "entity_registry_db_utils"+version = "0.1.0"+dependencies = [+ "chrono",+ "macro_db_migrator",+ "model_owner",+ "rootcause",+ "shared_entity_registry",+ "sqlx",+ "tokio",+ "tracing",+ "uuid",+ "workspace-hack",+]+[[package]]name = "enum-as-inner"version = "0.5.1"@@ -15231,6 +15264,19 @@ dependencies = ["workspace-hack",]+[[package]]+name = "shared_entity_registry"+version = "0.1.0"+dependencies = [+ "chrono",+ "model-entity",+ "model_owner",+ "rootcause",+ "thiserror 2.0.18",+ "uuid",+ "workspace-hack",+]+[[package]]name = "shell-words"version = "1.1.1"diff --git a/Cargo.toml b/Cargo.tomlindex c555f01844..1b322aa45f 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -30,6 +30,9 @@ members = ["crates/embedding","crates/email_api_client","crates/entity_mutation",+ "crates/entity_registry/entity_registry",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/favorites","crates/foreign_entity","crates/genai_telemetry",diff --git a/crates/entity_registry/entity_registry/Cargo.toml b/crates/entity_registry/entity_registry/Cargo.tomlnew file mode 100644index 0000000000..5f6bcdec3a--- /dev/null+++ b/crates/entity_registry/entity_registry/Cargo.toml@@ -0,0 +1,25 @@+[package]+edition = "2024"+name = "entity_registry"+publish = false+version = "0.1.0"++[features]+default = []+postgres = ["dep:sqlx", "model_owner/sqlx"]++[dependencies]+chrono = { workspace = true }+model-entity = { path = "../../model-entity" }+model_owner = { path = "../../model_owner" }+rootcause = { workspace = true }+shared_entity_registry = { path = "../shared_entity_registry" }+tracing = { workspace = true }+sqlx = { workspace = true, optional = true }+uuid = { workspace = true }+workspace-hack = { version = "0.1", path = "../../workspace-hack" }++[dev-dependencies]+macro_db_migrator = { path = "../../macro_db_migrator" }+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }+uuid = { workspace = true, features = ["v7"] }diff --git a/crates/entity_registry/entity_registry/justfile b/crates/entity_registry/entity_registry/justfilenew file mode 100644index 0000000000..ee539f3ebc--- /dev/null+++ b/crates/entity_registry/entity_registry/justfile@@ -0,0 +1,6 @@+import '../../../tooling/just/database.just'++mod sqlx '../../../tooling/just/sqlx.just'++prepare_db:+ just sqlx::prepare_db {{ DATABASE_URL }}diff --git a/crates/entity_registry/entity_registry/src/domain.rs b/crates/entity_registry/entity_registry/src/domain.rsnew file mode 100644index 0000000000..7100f49ec7--- /dev/null+++ b/crates/entity_registry/entity_registry/src/domain.rs@@ -0,0 +1,5 @@+//! Domain models, ports, and the service implementation.++pub mod models;+pub mod ports;+pub mod service;diff --git a/crates/entity_registry/entity_registry/src/domain/models.rs b/crates/entity_registry/entity_registry/src/domain/models.rsnew file mode 100644index 0000000000..a4dd671616--- /dev/null+++ b/crates/entity_registry/entity_registry/src/domain/models.rs@@ -0,0 +1,48 @@+//! Read-side registry records.++use chrono::{DateTime, Utc};+use model_owner::Owner;+use shared_entity_registry::RegisteredEntityType;+use uuid::Uuid;++/// One row of the registry: who owns the resource `id`, and its lifecycle stamps.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct EntityRecord {+ /// The resource's id.+ pub id: Uuid,+ /// The kind of resource.+ pub entity_type: RegisteredEntityType,+ /// The recorded owner.+ pub owner: Owner,+ /// When the row was registered (or the resource's own `createdAt` if backfilled).+ pub created_at: DateTime<Utc>,+ /// Mirror of the resource's `updatedAt`; written by `touch_updated`.+ pub updated_at: DateTime<Utc>,+ /// Set while the resource is soft-deleted; `None` for a live resource.+ pub deleted_at: Option<DateTime<Utc>>,+}++impl EntityRecord {+ /// `true` when `deleted_at` is unset.+ #[must_use]+ pub fn is_live(&self) -> bool {+ self.deleted_at.is_none()+ }+}++/// Row counts for one kind, split by liveness.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]+pub struct EntityTypeCount {+ /// Rows with `deleted_at IS NULL`.+ pub live: u64,+ /// Rows with `deleted_at IS NOT NULL`.+ pub deleted: u64,+}++impl EntityTypeCount {+ /// `live + deleted`: every registered row of the kind.+ #[must_use]+ pub fn total(self) -> u64 {+ self.live + self.deleted+ }+}diff --git a/crates/entity_registry/entity_registry/src/domain/ports.rs b/crates/entity_registry/entity_registry/src/domain/ports.rsnew file mode 100644index 0000000000..17cea8e37a--- /dev/null+++ b/crates/entity_registry/entity_registry/src/domain/ports.rs@@ -0,0 +1,67 @@+//! Read-side ports.++use model_owner::Owner;+use shared_entity_registry::{EntityRegistryResult, RegisteredEntityType};+use uuid::Uuid;++use super::models::{EntityRecord, EntityTypeCount};++/// Persistence port for the registry.+pub trait EntityRegistryRepository: Clone + Send + Sync + 'static {+ /// The row for `id`, deleted or not. `None` if never registered or hard-deleted.+ fn get(+ &self,+ id: Uuid,+ ) -> impl Future<Output = EntityRegistryResult<Option<EntityRecord>>> + Send;++ /// Rows for the ids that exist, deleted or not, in no particular order.+ /// Duplicate ids collapse; missing ids are simply absent. Empty in, empty out.+ fn get_many(+ &self,+ ids: &[Uuid],+ ) -> impl Future<Output = EntityRegistryResult<Vec<EntityRecord>>> + Send;++ /// Live rows owned by `owner`, optionally of one kind, newest-created+ /// first with `id` as the tie-break.+ fn list_owned_by(+ &self,+ owner: &Owner,+ entity_type: Option<RegisteredEntityType>,+ ) -> impl Future<Output = EntityRegistryResult<Vec<EntityRecord>>> + Send;++ /// Live and deleted row counts for one kind.+ fn count_by_type(+ &self,+ entity_type: RegisteredEntityType,+ ) -> impl Future<Output = EntityRegistryResult<EntityTypeCount>> + Send;+}++/// Inbound service port: registry reads used by drivers.+pub trait EntityRegistryService: Clone + Send + Sync + 'static {+ /// The row for `id`, deleted or not. `None` if never registered or hard-deleted.+ fn get(+ &self,+ id: Uuid,+ ) -> impl Future<Output = EntityRegistryResult<Option<EntityRecord>>> + Send;++ /// Rows for the ids that exist, deleted or not, in no particular order.+ /// Duplicate ids collapse; missing ids are simply absent. Empty in, empty out.+ fn get_many(+ &self,+ ids: &[Uuid],+ ) -> impl Future<Output = EntityRegistryResult<Vec<EntityRecord>>> + Send;++ /// Live rows owned by `owner`, optionally of one kind, newest-created+ /// first with `id` as the tie-break.+ fn list_owned_by(+ &self,+ owner: &Owner,+ entity_type: Option<RegisteredEntityType>,+ ) -> impl Future<Output = EntityRegistryResult<Vec<EntityRecord>>> + Send;++ /// Live and deleted row counts for one kind.+ fn count_by_type(+ &self,+ entity_type: RegisteredEntityType,+ ) -> impl Future<Output = EntityRegistryResult<EntityTypeCount>> + Send;+}diff --git a/crates/entity_registry/entity_registry/src/domain/service.rs b/crates/entity_registry/entity_registry/src/domain/service.rsnew file mode 100644index 0000000000..7f840553b8--- /dev/null+++ b/crates/entity_registry/entity_registry/src/domain/service.rs@@ -0,0 +1,60 @@+//! Registry service implementation.++#[cfg(test)]+mod test;++use model_owner::Owner;+use shared_entity_registry::{EntityRegistryResult, RegisteredEntityType};+use uuid::Uuid;++use super::models::{EntityRecord, EntityTypeCount};+use super::ports::{EntityRegistryRepository, EntityRegistryService};++/// Concrete registry service backed by an [`EntityRegistryRepository`].+#[derive(Clone)]+pub struct EntityRegistryServiceImpl<R> {+ repo: R,+}++impl<R> EntityRegistryServiceImpl<R>+where+ R: EntityRegistryRepository,+{+ /// A service over `repo`.+ #[must_use]+ pub fn new(repo: R) -> Self {+ Self { repo }+ }+}++impl<R> EntityRegistryService for EntityRegistryServiceImpl<R>+where+ R: EntityRegistryRepository,+{+ #[tracing::instrument(skip(self), err)]+ async fn get(&self, id: Uuid) -> EntityRegistryResult<Option<EntityRecord>> {+ self.repo.get(id).await+ }++ #[tracing::instrument(skip(self, ids), fields(count = ids.len()), err)]+ async fn get_many(&self, ids: &[Uuid]) -> EntityRegistryResult<Vec<EntityRecord>> {+ self.repo.get_many(ids).await+ }++ #[tracing::instrument(skip(self, owner), fields(owner.kind = ?owner.owner_type()), err)]+ async fn list_owned_by(+ &self,+ owner: &Owner,+ entity_type: Option<RegisteredEntityType>,+ ) -> EntityRegistryResult<Vec<EntityRecord>> {+ self.repo.list_owned_by(owner, entity_type).await+ }++ #[tracing::instrument(skip(self), err)]+ async fn count_by_type(+ &self,+ entity_type: RegisteredEntityType,+ ) -> EntityRegistryResult<EntityTypeCount> {+ self.repo.count_by_type(entity_type).await+ }+}diff --git a/crates/entity_registry/entity_registry/src/domain/service/test.rs b/crates/entity_registry/entity_registry/src/domain/service/test.rsnew file mode 100644index 0000000000..2b7451c642--- /dev/null+++ b/crates/entity_registry/entity_registry/src/domain/service/test.rs@@ -0,0 +1,106 @@+use chrono::{DateTime, Utc};+use model_owner::{Owner, OwnerType};+use shared_entity_registry::{EntityRegistryResult, RegisteredEntityType};+use uuid::Uuid;++use super::EntityRegistryServiceImpl;+use crate::domain::models::{EntityRecord, EntityTypeCount};+use crate::domain::ports::{EntityRegistryRepository, EntityRegistryService};++fn user_owner() -> Owner {+ Owner::parse(OwnerType::User, "macro|[email protected]").unwrap()+}++fn ts() -> DateTime<Utc> {+ DateTime::parse_from_rfc3339("2024-01-01T00:00:00Z")+ .unwrap()+ .with_timezone(&Utc)+}++fn sample_record(id: u128) -> EntityRecord {+ EntityRecord {+ id: Uuid::from_u128(id),+ entity_type: RegisteredEntityType::Chat,+ owner: user_owner(),+ created_at: ts(),+ updated_at: ts(),+ deleted_at: None,+ }+}++#[derive(Clone, Default)]+struct FakeRepo {+ get: Option<EntityRecord>,+ get_many: Vec<EntityRecord>,+ list: Vec<EntityRecord>,+ count: EntityTypeCount,+}++impl EntityRegistryRepository for FakeRepo {+ async fn get(&self, _id: Uuid) -> EntityRegistryResult<Option<EntityRecord>> {+ Ok(self.get.clone())+ }++ async fn get_many(&self, _ids: &[Uuid]) -> EntityRegistryResult<Vec<EntityRecord>> {+ Ok(self.get_many.clone())+ }++ async fn list_owned_by(+ &self,+ _owner: &Owner,+ _entity_type: Option<RegisteredEntityType>,+ ) -> EntityRegistryResult<Vec<EntityRecord>> {+ Ok(self.list.clone())+ }++ async fn count_by_type(+ &self,+ _entity_type: RegisteredEntityType,+ ) -> EntityRegistryResult<EntityTypeCount> {+ Ok(self.count)+ }+}++#[tokio::test]+async fn get_returns_the_repository_row() {+ let record = sample_record(1);+ let service = EntityRegistryServiceImpl::new(FakeRepo {+ get: Some(record.clone()),+ ..FakeRepo::default()+ });+ assert_eq!(service.get(record.id).await.unwrap(), Some(record));+}++#[tokio::test]+async fn get_many_list_and_count_return_repository_values() {+ let record = sample_record(1);+ let count = EntityTypeCount {+ live: 2,+ deleted: 1,+ };+ let service = EntityRegistryServiceImpl::new(FakeRepo {+ get_many: vec![record.clone()],+ list: vec![record.clone()],+ count,+ ..FakeRepo::default()+ });++ assert_eq!(+ service.get_many(&[record.id]).await.unwrap(),+ vec![record.clone()]+ );+ assert_eq!(+ service+ .list_owned_by(&user_owner(), Some(RegisteredEntityType::Chat))+ .await+ .unwrap(),+ vec![record]+ );+ assert_eq!(+ service+ .count_by_type(RegisteredEntityType::Chat)+ .await+ .unwrap(),+ count+ );+}diff --git a/crates/entity_registry/entity_registry/src/lib.rs b/crates/entity_registry/entity_registry/src/lib.rsnew file mode 100644index 0000000000..afb864cc0a--- /dev/null+++ b/crates/entity_registry/entity_registry/src/lib.rs@@ -0,0 +1,40 @@+#![deny(missing_docs)]+//! Owning crate for the `entity` table: one recorded owner per in-scope resource.+//!+//! Effective access lives in `entity_access`, not here. Reads go through+//! [`EntityRegistryService`], backed by [`EntityRegistryRepository`].+//! Transactional writes live in `entity_registry_db_utils` so other crates can+//! join them to their own resource-row transactions. Shared types live in+//! `shared_entity_registry`; this crate does not depend on the write helpers.+//!+//! [`RegisteredEntityType`] is the table CHECK as a type. Use+//! [`NewEntityRecord::try_new`] when the caller holds a wide+//! [`model_entity::EntityType`].+//!+//! ```+//! use entity_registry::{NewEntityRecord, Owner, RegisteredEntityType};+//! use model_entity::EntityType;+//! use model_owner::OwnerType;+//! use uuid::Uuid;+//!+//! let owner = Owner::parse(OwnerType::User, "macro|[email protected]").unwrap();+//! let record = NewEntityRecord::try_new(Uuid::nil(), EntityType::Chat, owner.clone()).unwrap();+//! assert_eq!(record.entity_type, RegisteredEntityType::Chat);+//! assert!(NewEntityRecord::try_new(Uuid::nil(), EntityType::Initiative, owner).is_err());+//! ```++pub mod domain;++#[cfg(feature = "postgres")]+pub mod outbound;++pub use domain::models::{EntityRecord, EntityTypeCount};+pub use domain::ports::{EntityRegistryRepository, EntityRegistryService};+pub use domain::service::EntityRegistryServiceImpl;+pub use shared_entity_registry::{+ EntityRegistryError, EntityRegistryResult, InsertOutcome, NewEntityRecord, Owner,+ RegisteredEntityType, UnregisteredEntityType, WriteOutcome,+};++#[cfg(feature = "postgres")]+pub use outbound::pg_entity_registry_repo::PgEntityRegistryRepository;diff --git a/crates/entity_registry/entity_registry/src/outbound.rs b/crates/entity_registry/entity_registry/src/outbound.rsnew file mode 100644index 0000000000..b9d104520d--- /dev/null+++ b/crates/entity_registry/entity_registry/src/outbound.rs@@ -0,0 +1,3 @@+//! Postgres adapter for [`EntityRegistryRepository`].++pub mod pg_entity_registry_repo;diff --git a/crates/entity_registry/entity_registry/src/outbound/pg_entity_registry_repo.rs b/crates/entity_registry/entity_registry/src/outbound/pg_entity_registry_repo.rsnew file mode 100644index 0000000000..e780c134be--- /dev/null+++ b/crates/entity_registry/entity_registry/src/outbound/pg_entity_registry_repo.rs@@ -0,0 +1,168 @@+//! Pool-backed implementation of [`EntityRegistryRepository`].++#[cfg(test)]+mod test;++use chrono::{DateTime, Utc};+use model_entity::EntityType;+use model_owner::{Owner, OwnerType};+use rootcause::Report;+use rootcause::prelude::*;+use shared_entity_registry::{EntityRegistryError, EntityRegistryResult, RegisteredEntityType};+use sqlx::PgPool;+use uuid::Uuid;++use crate::domain::models::{EntityRecord, EntityTypeCount};+use crate::domain::ports::EntityRegistryRepository;++/// Reads `entity` through a pool.+#[derive(Debug, Clone)]+pub struct PgEntityRegistryRepository {+ pool: PgPool,+}++impl PgEntityRegistryRepository {+ /// A repository over `pool`.+ #[must_use]+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }+}++struct EntityRow {+ id: Uuid,+ entity_type: String,+ owner_type: OwnerType,+ owner_id: String,+ created_at: DateTime<Utc>,+ updated_at: DateTime<Utc>,+ deleted_at: Option<DateTime<Utc>>,+}++impl EntityRow {+ fn into_record(self) -> EntityRegistryResult<EntityRecord> {+ let id = self.id;+ let owner = Owner::parse(self.owner_type, &self.owner_id).map_err(|_| corrupt_row(id))?;+ let entity_type = self+ .entity_type+ .parse::<EntityType>()+ .map_err(|_| corrupt_row(id))?;+ let entity_type =+ RegisteredEntityType::try_from(entity_type).map_err(|_| corrupt_row(id))?;+ Ok(EntityRecord {+ id,+ entity_type,+ owner,+ created_at: self.created_at,+ updated_at: self.updated_at,+ deleted_at: self.deleted_at,+ })+ }+}++fn corrupt_row(id: Uuid) -> Report<EntityRegistryError> {+ report!(EntityRegistryError::CorruptRow).attach(id)+}++impl EntityRegistryRepository for PgEntityRegistryRepository {+ #[tracing::instrument(skip(self), err)]+ async fn get(&self, id: Uuid) -> EntityRegistryResult<Option<EntityRecord>> {+ sqlx::query_as!(+ EntityRow,+ r#"+ SELECT id, entity_type, owner_type AS "owner_type: OwnerType", owner_id,+ created_at, updated_at, deleted_at+ FROM entity+ WHERE id = $1+ "#,+ id,+ )+ .fetch_optional(&self.pool)+ .await+ .context(EntityRegistryError::Infrastructure)?+ .map(EntityRow::into_record)+ .transpose()+ }++ #[tracing::instrument(skip(self, ids), fields(count = ids.len()), err)]+ async fn get_many(&self, ids: &[Uuid]) -> EntityRegistryResult<Vec<EntityRecord>> {+ if ids.is_empty() {+ return Ok(Vec::new());+ }+ sqlx::query_as!(+ EntityRow,+ r#"+ SELECT id, entity_type, owner_type AS "owner_type: OwnerType", owner_id,+ created_at, updated_at, deleted_at+ FROM entity+ WHERE id = ANY($1)+ "#,+ ids,+ )+ .fetch_all(&self.pool)+ .await+ .context(EntityRegistryError::Infrastructure)?+ .into_iter()+ .map(EntityRow::into_record)+ .collect()+ }++ #[tracing::instrument(skip(self, owner), fields(owner.kind = ?owner.owner_type()), err)]+ async fn list_owned_by(+ &self,+ owner: &Owner,+ entity_type: Option<RegisteredEntityType>,+ ) -> EntityRegistryResult<Vec<EntityRecord>> {+ let owner_type = owner.owner_type();+ let owner_id = owner.principal_id();+ let entity_type = entity_type.map(RegisteredEntityType::as_str);+ sqlx::query_as!(+ EntityRow,+ r#"+ SELECT id, entity_type, owner_type AS "owner_type: OwnerType", owner_id,+ created_at, updated_at, deleted_at+ FROM entity+ WHERE owner_type = $1 AND owner_id = $2+ AND deleted_at IS NULL+ AND ($3::text IS NULL OR entity_type = $3)+ ORDER BY created_at DESC, id DESC+ "#,+ owner_type as _,+ owner_id,+ entity_type,+ )+ .fetch_all(&self.pool)+ .await+ .context(EntityRegistryError::Infrastructure)?+ .into_iter()+ .map(EntityRow::into_record)+ .collect()+ }++ #[tracing::instrument(skip(self), err)]+ async fn count_by_type(+ &self,+ entity_type: RegisteredEntityType,+ ) -> EntityRegistryResult<EntityTypeCount> {+ let row = sqlx::query!(+ r#"+ SELECT count(*) FILTER (WHERE deleted_at IS NULL) AS "live!",+ count(*) FILTER (WHERE deleted_at IS NOT NULL) AS "deleted!"+ FROM entity WHERE entity_type = $1+ "#,+ entity_type.as_str(),+ )+ .fetch_one(&self.pool)+ .await+ .context(EntityRegistryError::Infrastructure)?;++ Ok(EntityTypeCount {+ live: as_count(row.live),+ deleted: as_count(row.deleted),+ })+ }+}++fn as_count(value: i64) -> u64 {+ u64::try_from(value).unwrap_or(0)+}diff --git a/crates/entity_registry/entity_registry/src/outbound/pg_entity_registry_repo/test.rs b/crates/entity_registry/entity_registry/src/outbound/pg_entity_registry_repo/test.rsnew file mode 100644index 0000000000..9af69bdea6--- /dev/null+++ b/crates/entity_registry/entity_registry/src/outbound/pg_entity_registry_repo/test.rs@@ -0,0 +1,309 @@+use chrono::{DateTime, Utc};+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use model_owner::{Owner, OwnerType};+use shared_entity_registry::{EntityRegistryError, NewEntityRecord, RegisteredEntityType};+use sqlx::PgPool;+use uuid::Uuid;++use super::{EntityRow, PgEntityRegistryRepository};+use crate::domain::ports::EntityRegistryRepository;++fn user_owner() -> Owner {+ Owner::parse(OwnerType::User, "macro|[email protected]").unwrap()+}++fn bot_owner() -> Owner {+ Owner::parse(OwnerType::Bot, "bot|00000000-0000-0000-0000-00000000a1a1").unwrap()+}++fn team_owner() -> Owner {+ Owner::parse(OwnerType::Team, "01234567-89ab-cdef-0123-456789abcdef").unwrap()+}++fn ts(rfc3339: &str) -> DateTime<Utc> {+ DateTime::parse_from_rfc3339(rfc3339)+ .unwrap()+ .with_timezone(&Utc)+}++async fn insert_committed(pool: &PgPool, record: NewEntityRecord) {+ let owner_type = record.owner.owner_type();+ let owner_id = record.owner.principal_id();+ sqlx::query!(+ r#"+ INSERT INTO entity (id, entity_type, owner_type, owner_id, created_at, updated_at)+ VALUES ($1, $2, $3, $4, COALESCE($5::timestamptz, now()), COALESCE($6::timestamptz, now()))+ "#,+ record.id,+ record.entity_type.as_str(),+ owner_type as _,+ owner_id,+ record.created_at,+ record.updated_at,+ )+ .execute(pool)+ .await+ .unwrap();+}++async fn mark_deleted_committed(pool: &PgPool, id: Uuid, at: DateTime<Utc>) {+ sqlx::query!(+ r#"+ UPDATE entity SET deleted_at = $2 WHERE id = $1+ "#,+ id,+ at,+ )+ .execute(pool)+ .await+ .unwrap();+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_returns_live_and_soft_deleted_rows_and_none_for_unknown(pool: PgPool) {+ let live_id = Uuid::from_u128(1);+ let deleted_id = Uuid::from_u128(2);+ let owner = user_owner();+ insert_committed(+ &pool,+ NewEntityRecord::new(live_id, RegisteredEntityType::Chat, owner.clone()),+ )+ .await;+ insert_committed(+ &pool,+ NewEntityRecord::new(deleted_id, RegisteredEntityType::Document, owner.clone()),+ )+ .await;+ mark_deleted_committed(&pool, deleted_id, ts("2024-01-01T00:00:00Z")).await;++ let repo = PgEntityRegistryRepository::new(pool);+ let live = repo.get(live_id).await.unwrap().unwrap();+ assert_eq!(live.id, live_id);+ assert_eq!(live.entity_type, RegisteredEntityType::Chat);+ assert_eq!(live.owner, owner);+ assert!(live.is_live());++ let deleted = repo.get(deleted_id).await.unwrap().unwrap();+ assert_eq!(deleted.id, deleted_id);+ assert_eq!(deleted.deleted_at, Some(ts("2024-01-01T00:00:00Z")));+ assert!(!deleted.is_live());++ assert_eq!(repo.get(Uuid::from_u128(99)).await.unwrap(), None);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_many_returns_present_ids_only_and_collapses_duplicates(pool: PgPool) {+ let present = Uuid::from_u128(1);+ let missing = Uuid::from_u128(2);+ insert_committed(+ &pool,+ NewEntityRecord::new(present, RegisteredEntityType::Chat, user_owner()),+ )+ .await;+ let repo = PgEntityRegistryRepository::new(pool.clone());++ assert_eq!(repo.get_many(&[]).await.unwrap(), Vec::new());++ let rows = repo.get_many(&[present, missing, present]).await.unwrap();+ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0].id, present);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_owned_by_user_bot_and_team_each_see_only_their_rows(pool: PgPool) {+ let user = user_owner();+ let bot = bot_owner();+ let team = team_owner();+ let user_id = Uuid::from_u128(1);+ let bot_id = Uuid::from_u128(2);+ let team_id = Uuid::from_u128(3);+ insert_committed(+ &pool,+ NewEntityRecord::new(user_id, RegisteredEntityType::Chat, user.clone()),+ )+ .await;+ insert_committed(+ &pool,+ NewEntityRecord::new(bot_id, RegisteredEntityType::Document, bot.clone()),+ )+ .await;+ insert_committed(+ &pool,+ NewEntityRecord::new(team_id, RegisteredEntityType::Project, team.clone()),+ )+ .await;++ let repo = PgEntityRegistryRepository::new(pool);+ let user_rows = repo.list_owned_by(&user, None).await.unwrap();+ assert_eq!(user_rows.len(), 1);+ assert_eq!(user_rows[0].id, user_id);+ assert_eq!(user_rows[0].owner, user);++ let bot_rows = repo.list_owned_by(&bot, None).await.unwrap();+ assert_eq!(bot_rows.len(), 1);+ assert_eq!(bot_rows[0].id, bot_id);+ assert_eq!(bot_rows[0].owner, bot);++ let team_rows = repo.list_owned_by(&team, None).await.unwrap();+ assert_eq!(team_rows.len(), 1);+ assert_eq!(team_rows[0].id, team_id);+ assert_eq!(team_rows[0].owner, team);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_owned_by_filters_by_kind_and_skips_soft_deleted(pool: PgPool) {+ let owner = user_owner();+ let live_chat = Uuid::from_u128(1);+ let live_document = Uuid::from_u128(2);+ let deleted_chat = Uuid::from_u128(3);+ insert_committed(+ &pool,+ NewEntityRecord::new(live_chat, RegisteredEntityType::Chat, owner.clone()),+ )+ .await;+ insert_committed(+ &pool,+ NewEntityRecord::new(live_document, RegisteredEntityType::Document, owner.clone()),+ )+ .await;+ insert_committed(+ &pool,+ NewEntityRecord::new(deleted_chat, RegisteredEntityType::Chat, owner.clone()),+ )+ .await;+ mark_deleted_committed(&pool, deleted_chat, ts("2024-01-01T00:00:00Z")).await;++ let repo = PgEntityRegistryRepository::new(pool);+ let chats = repo+ .list_owned_by(&owner, Some(RegisteredEntityType::Chat))+ .await+ .unwrap();+ assert_eq!(chats.len(), 1);+ assert_eq!(chats[0].id, live_chat);++ let documents = repo+ .list_owned_by(&owner, Some(RegisteredEntityType::Document))+ .await+ .unwrap();+ assert_eq!(documents.len(), 1);+ assert_eq!(documents[0].id, live_document);++ let all = repo.list_owned_by(&owner, None).await.unwrap();+ let mut ids: Vec<_> = all.iter().map(|row| row.id).collect();+ ids.sort();+ assert_eq!(ids, vec![live_chat, live_document]);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn list_owned_by_orders_newest_created_first(pool: PgPool) {+ let owner = user_owner();+ let older = Uuid::from_u128(1);+ let newer_low = Uuid::from_u128(2);+ let newer_high = Uuid::from_u128(3);+ let old_ts = ts("2024-01-01T00:00:00Z");+ let new_ts = ts("2024-06-01T00:00:00Z");+ insert_committed(+ &pool,+ NewEntityRecord::new(older, RegisteredEntityType::Chat, owner.clone())+ .with_timestamps(old_ts, old_ts),+ )+ .await;+ insert_committed(+ &pool,+ NewEntityRecord::new(newer_low, RegisteredEntityType::Chat, owner.clone())+ .with_timestamps(new_ts, new_ts),+ )+ .await;+ insert_committed(+ &pool,+ NewEntityRecord::new(newer_high, RegisteredEntityType::Chat, owner.clone())+ .with_timestamps(new_ts, new_ts),+ )+ .await;++ let repo = PgEntityRegistryRepository::new(pool);+ let rows = repo.list_owned_by(&owner, None).await.unwrap();+ assert_eq!(+ rows.iter().map(|row| row.id).collect::<Vec<_>>(),+ vec![newer_high, newer_low, older]+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn count_by_type_splits_live_and_deleted(pool: PgPool) {+ let owner = user_owner();+ insert_committed(+ &pool,+ NewEntityRecord::new(+ Uuid::from_u128(1),+ RegisteredEntityType::Chat,+ owner.clone(),+ ),+ )+ .await;+ insert_committed(+ &pool,+ NewEntityRecord::new(+ Uuid::from_u128(2),+ RegisteredEntityType::Chat,+ owner.clone(),+ ),+ )+ .await;+ insert_committed(+ &pool,+ NewEntityRecord::new(+ Uuid::from_u128(3),+ RegisteredEntityType::Chat,+ owner.clone(),+ ),+ )+ .await;+ insert_committed(+ &pool,+ NewEntityRecord::new(Uuid::from_u128(4), RegisteredEntityType::Document, owner),+ )+ .await;+ mark_deleted_committed(&pool, Uuid::from_u128(3), ts("2024-01-01T00:00:00Z")).await;++ let repo = PgEntityRegistryRepository::new(pool);+ let chats = repo+ .count_by_type(RegisteredEntityType::Chat)+ .await+ .unwrap();+ assert_eq!(chats.live, 2);+ assert_eq!(chats.deleted, 1);+ assert_eq!(chats.total(), 3);++ let documents = repo+ .count_by_type(RegisteredEntityType::Document)+ .await+ .unwrap();+ assert_eq!(documents.live, 1);+ assert_eq!(documents.deleted, 0);+ assert_eq!(documents.total(), 1);++ let projects = repo+ .count_by_type(RegisteredEntityType::Project)+ .await+ .unwrap();+ assert_eq!(projects.live, 0);+ assert_eq!(projects.deleted, 0);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn decode_of_a_row_outside_the_checks_is_corrupt_row(_pool: PgPool) {+ let id = Uuid::from_u128(1);+ let now = ts("2024-01-01T00:00:00Z");+ let row = EntityRow {+ id,+ entity_type: "initiative".to_string(),+ owner_type: OwnerType::User,+ owner_id: "macro|[email protected]".to_string(),+ created_at: now,+ updated_at: now,+ deleted_at: None,+ };+ let err = row.into_record().unwrap_err();+ assert_eq!(*err.current_context(), EntityRegistryError::CorruptRow);+}diff --git a/crates/entity_registry/entity_registry_db_utils/Cargo.toml b/crates/entity_registry/entity_registry_db_utils/Cargo.tomlnew file mode 100644index 0000000000..85d7b789b6--- /dev/null+++ b/crates/entity_registry/entity_registry_db_utils/Cargo.toml@@ -0,0 +1,19 @@+[package]+edition = "2024"+name = "entity_registry_db_utils"+publish = false+version = "0.1.0"++[dependencies]+chrono = { workspace = true }+model_owner = { path = "../../model_owner", features = ["sqlx"] }+rootcause = { workspace = true }+shared_entity_registry = { path = "../shared_entity_registry" }+sqlx = { workspace = true }+tracing = { workspace = true }+uuid = { workspace = true }+workspace-hack = { version = "0.1", path = "../../workspace-hack" }++[dev-dependencies]+macro_db_migrator = { path = "../../macro_db_migrator" }+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }diff --git a/crates/entity_registry/entity_registry_db_utils/justfile b/crates/entity_registry/entity_registry_db_utils/justfilenew file mode 100644index 0000000000..ee539f3ebc--- /dev/null+++ b/crates/entity_registry/entity_registry_db_utils/justfile@@ -0,0 +1,6 @@+import '../../../tooling/just/database.just'++mod sqlx '../../../tooling/just/sqlx.just'++prepare_db:+ just sqlx::prepare_db {{ DATABASE_URL }}diff --git a/crates/entity_registry/entity_registry_db_utils/src/lib.rs b/crates/entity_registry/entity_registry_db_utils/src/lib.rsnew file mode 100644index 0000000000..4ee0d729fa--- /dev/null+++ b/crates/entity_registry/entity_registry_db_utils/src/lib.rs@@ -0,0 +1,147 @@+#![deny(missing_docs)]+//! Transactional writes to the `entity` table.+//!+//! Other crates call these helpers from inside their own resource-row+//! transactions. The helpers never commit. Reads go through+//! `entity_registry::EntityRegistryService`. Shared types live in+//! `shared_entity_registry`; this crate does not depend on the read service.++#[cfg(test)]+mod test;++use chrono::{DateTime, Utc};+use model_owner::{Owner, OwnerType};+use rootcause::prelude::*;+use sqlx::{Postgres, Transaction};+use uuid::Uuid;++pub use shared_entity_registry::{+ EntityRegistryError, EntityRegistryResult, InsertOutcome, NewEntityRecord,+ RegisteredEntityType, WriteOutcome,+};++fn bind_owner(owner: &Owner) -> (OwnerType, String) {+ (owner.owner_type(), owner.principal_id())+}++/// Register `record`. Idempotent: `ON CONFLICT (id) DO NOTHING`.+#[tracing::instrument(+ skip_all,+ fields(entity.id = %record.id, entity.kind = %record.entity_type),+ err+)]+pub async fn insert_entity(+ tx: &mut Transaction<'_, Postgres>,+ record: NewEntityRecord,+) -> EntityRegistryResult<InsertOutcome> {+ let (owner_type, owner_id) = bind_owner(&record.owner);+ let result = sqlx::query!(+ r#"+ INSERT INTO entity (id, entity_type, owner_type, owner_id, created_at, updated_at)+ VALUES ($1, $2, $3, $4, COALESCE($5::timestamptz, now()), COALESCE($6::timestamptz, now()))+ ON CONFLICT (id) DO NOTHING+ "#,+ record.id,+ record.entity_type.as_str(),+ owner_type as _,+ owner_id,+ record.created_at,+ record.updated_at,+ )+ .execute(tx.as_mut())+ .await+ .context(EntityRegistryError::Infrastructure)?;++ if result.rows_affected() == 1 {+ Ok(InsertOutcome::Inserted)+ } else {+ Ok(InsertOutcome::AlreadyRegistered)+ }+}++/// Set `deleted_at = at`. Last write wins.+#[tracing::instrument(skip(tx), err)]+pub async fn mark_deleted(+ tx: &mut Transaction<'_, Postgres>,+ id: Uuid,+ at: DateTime<Utc>,+) -> EntityRegistryResult<WriteOutcome> {+ write_by_id(+ sqlx::query!(+ r#"+ UPDATE entity SET deleted_at = $2 WHERE id = $1+ "#,+ id,+ at,+ )+ .execute(tx.as_mut())+ .await,+ )+}++/// Set `deleted_at = NULL`. The restore mirror of [`mark_deleted`].+#[tracing::instrument(skip(tx), err)]+pub async fn clear_deleted(+ tx: &mut Transaction<'_, Postgres>,+ id: Uuid,+) -> EntityRegistryResult<WriteOutcome> {+ write_by_id(+ sqlx::query!(+ r#"+ UPDATE entity SET deleted_at = NULL WHERE id = $1+ "#,+ id,+ )+ .execute(tx.as_mut())+ .await,+ )+}++/// Set `updated_at = at`.+#[tracing::instrument(skip(tx), err)]+pub async fn touch_updated(+ tx: &mut Transaction<'_, Postgres>,+ id: Uuid,+ at: DateTime<Utc>,+) -> EntityRegistryResult<WriteOutcome> {+ write_by_id(+ sqlx::query!(+ r#"+ UPDATE entity SET updated_at = $2 WHERE id = $1+ "#,+ id,+ at,+ )+ .execute(tx.as_mut())+ .await,+ )+}++/// Remove the row.+#[tracing::instrument(skip(tx), err)]+pub async fn delete_entity(+ tx: &mut Transaction<'_, Postgres>,+ id: Uuid,+) -> EntityRegistryResult<WriteOutcome> {+ write_by_id(+ sqlx::query!(+ r#"+ DELETE FROM entity WHERE id = $1+ "#,+ id,+ )+ .execute(tx.as_mut())+ .await,+ )+}++fn write_by_id(+ result: Result<sqlx::postgres::PgQueryResult, sqlx::Error>,+) -> EntityRegistryResult<WriteOutcome> {+ let result = result.context(EntityRegistryError::Infrastructure)?;+ if result.rows_affected() == 1 {+ Ok(WriteOutcome::Applied)+ } else {+ Ok(WriteOutcome::NotFound)+ }+}diff --git a/crates/entity_registry/entity_registry_db_utils/src/test.rs b/crates/entity_registry/entity_registry_db_utils/src/test.rsnew file mode 100644index 0000000000..de1c2423bc--- /dev/null+++ b/crates/entity_registry/entity_registry_db_utils/src/test.rs@@ -0,0 +1,384 @@+use chrono::{DateTime, Utc};+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use model_owner::{Owner, OwnerType};+use shared_entity_registry::{InsertOutcome, NewEntityRecord, RegisteredEntityType, WriteOutcome};+use sqlx::{PgPool, Postgres, Transaction};+use uuid::Uuid;++use super::{clear_deleted, delete_entity, insert_entity, mark_deleted, touch_updated};++fn user_owner() -> Owner {+ Owner::parse(OwnerType::User, "macro|[email protected]").unwrap()+}++fn bot_owner() -> Owner {+ Owner::parse(OwnerType::Bot, "bot|00000000-0000-0000-0000-00000000a1a1").unwrap()+}++fn team_owner() -> Owner {+ Owner::parse(OwnerType::Team, "01234567-89ab-cdef-0123-456789abcdef").unwrap()+}++fn ts(rfc3339: &str) -> DateTime<Utc> {+ DateTime::parse_from_rfc3339(rfc3339)+ .unwrap()+ .with_timezone(&Utc)+}++async fn insert(tx: &mut Transaction<'_, Postgres>, record: NewEntityRecord) -> InsertOutcome {+ insert_entity(tx, record).await.unwrap()+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn insert_registers_a_row_for_each_registered_kind(pool: PgPool) {+ let owner = user_owner();+ let mut tx = pool.begin().await.unwrap();+ for (index, kind) in RegisteredEntityType::ALL.into_iter().enumerate() {+ let id = Uuid::from_u128(index as u128 + 1);+ assert_eq!(+ insert(&mut tx, NewEntityRecord::new(id, kind, owner.clone())).await,+ InsertOutcome::Inserted+ );+ let row = sqlx::query!(+ r#"+ SELECT entity_type+ FROM entity+ WHERE id = $1+ "#,+ id,+ )+ .fetch_one(tx.as_mut())+ .await+ .unwrap();+ assert_eq!(row.entity_type, kind.as_str());+ }+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn insert_twice_is_a_no_op(pool: PgPool) {+ let id = Uuid::from_u128(1);+ let first = user_owner();+ let second = bot_owner();+ let mut tx = pool.begin().await.unwrap();++ assert_eq!(+ insert(+ &mut tx,+ NewEntityRecord::new(id, RegisteredEntityType::Chat, first.clone())+ )+ .await,+ InsertOutcome::Inserted+ );+ assert_eq!(+ insert(+ &mut tx,+ NewEntityRecord::new(id, RegisteredEntityType::Document, second)+ )+ .await,+ InsertOutcome::AlreadyRegistered+ );++ let rows = sqlx::query!(+ r#"+ SELECT owner_type AS "owner_type: OwnerType", owner_id, entity_type+ FROM entity+ WHERE id = $1+ "#,+ id,+ )+ .fetch_all(tx.as_mut())+ .await+ .unwrap();+ assert_eq!(rows.len(), 1);+ assert_eq!(rows[0].owner_type, OwnerType::User);+ assert_eq!(rows[0].owner_id, first.principal_id());+ assert_eq!(rows[0].entity_type, "chat");+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn insert_encodes_user_bot_and_team_owners(pool: PgPool) {+ let cases = [+ (+ Uuid::from_u128(1),+ user_owner(),+ OwnerType::User,+ "macro|[email protected]",+ ),+ (+ Uuid::from_u128(2),+ bot_owner(),+ OwnerType::Bot,+ "bot|00000000-0000-0000-0000-00000000a1a1",+ ),+ (+ Uuid::from_u128(3),+ team_owner(),+ OwnerType::Team,+ "01234567-89ab-cdef-0123-456789abcdef",+ ),+ ];+ let mut tx = pool.begin().await.unwrap();+ for (id, owner, owner_type, owner_id) in cases {+ assert_eq!(+ insert(+ &mut tx,+ NewEntityRecord::new(id, RegisteredEntityType::Project, owner)+ )+ .await,+ InsertOutcome::Inserted+ );+ let row = sqlx::query!(+ r#"+ SELECT owner_type AS "owner_type: OwnerType", owner_id+ FROM entity+ WHERE id = $1+ "#,+ id,+ )+ .fetch_one(tx.as_mut())+ .await+ .unwrap();+ assert_eq!(row.owner_type, owner_type);+ assert_eq!(row.owner_id, owner_id);+ }+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn insert_without_timestamps_matches_transaction_now(pool: PgPool) {+ let id = Uuid::from_u128(1);+ let mut tx = pool.begin().await.unwrap();+ let now = sqlx::query_scalar!(r#"SELECT now() AS "now!""#)+ .fetch_one(tx.as_mut())+ .await+ .unwrap();++ insert(+ &mut tx,+ NewEntityRecord::new(id, RegisteredEntityType::Chat, user_owner()),+ )+ .await;++ let row = sqlx::query!(+ r#"+ SELECT created_at, updated_at+ FROM entity+ WHERE id = $1+ "#,+ id,+ )+ .fetch_one(tx.as_mut())+ .await+ .unwrap();+ assert_eq!(row.created_at, now);+ assert_eq!(row.updated_at, now);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn insert_with_timestamps_stores_them(pool: PgPool) {+ let id = Uuid::from_u128(1);+ let created_at = ts("2024-03-15T12:00:00Z");+ let updated_at = ts("2024-03-16T08:30:00Z");+ let mut tx = pool.begin().await.unwrap();++ insert(+ &mut tx,+ NewEntityRecord::new(id, RegisteredEntityType::Document, user_owner())+ .with_timestamps(created_at, updated_at),+ )+ .await;++ let row = sqlx::query!(+ r#"+ SELECT created_at, updated_at, deleted_at+ FROM entity+ WHERE id = $1+ "#,+ id,+ )+ .fetch_one(tx.as_mut())+ .await+ .unwrap();+ assert_eq!(row.created_at, created_at);+ assert_eq!(row.updated_at, updated_at);+ assert_eq!(row.deleted_at, None);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn mark_deleted_sets_the_instant_and_last_write_wins(pool: PgPool) {+ let id = Uuid::from_u128(1);+ let first = ts("2024-01-01T00:00:00Z");+ let second = ts("2024-01-02T00:00:00Z");+ let mut tx = pool.begin().await.unwrap();+ insert(+ &mut tx,+ NewEntityRecord::new(id, RegisteredEntityType::Chat, user_owner()),+ )+ .await;++ assert_eq!(+ mark_deleted(&mut tx, id, first).await.unwrap(),+ WriteOutcome::Applied+ );+ let after_first = sqlx::query!(+ r#"+ SELECT deleted_at+ FROM entity+ WHERE id = $1+ "#,+ id,+ )+ .fetch_one(tx.as_mut())+ .await+ .unwrap();+ assert_eq!(after_first.deleted_at, Some(first));++ assert_eq!(+ mark_deleted(&mut tx, id, second).await.unwrap(),+ WriteOutcome::Applied+ );+ let after_second = sqlx::query!(+ r#"+ SELECT deleted_at+ FROM entity+ WHERE id = $1+ "#,+ id,+ )+ .fetch_one(tx.as_mut())+ .await+ .unwrap();+ assert_eq!(after_second.deleted_at, Some(second));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn mark_deleted_on_missing_row_is_not_found_not_error(pool: PgPool) {+ let mut tx = pool.begin().await.unwrap();+ assert_eq!(+ mark_deleted(&mut tx, Uuid::from_u128(99), ts("2024-01-01T00:00:00Z"))+ .await+ .unwrap(),+ WriteOutcome::NotFound+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn clear_deleted_nulls_deleted_at(pool: PgPool) {+ let id = Uuid::from_u128(1);+ let mut tx = pool.begin().await.unwrap();+ insert(+ &mut tx,+ NewEntityRecord::new(id, RegisteredEntityType::Chat, user_owner()),+ )+ .await;+ mark_deleted(&mut tx, id, ts("2024-01-01T00:00:00Z"))+ .await+ .unwrap();++ assert_eq!(+ clear_deleted(&mut tx, id).await.unwrap(),+ WriteOutcome::Applied+ );+ let row = sqlx::query!(+ r#"+ SELECT deleted_at+ FROM entity+ WHERE id = $1+ "#,+ id,+ )+ .fetch_one(tx.as_mut())+ .await+ .unwrap();+ assert_eq!(row.deleted_at, None);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn touch_updated_sets_updated_at_only(pool: PgPool) {+ let id = Uuid::from_u128(1);+ let created_at = ts("2024-03-15T12:00:00Z");+ let original_updated = ts("2024-03-16T08:30:00Z");+ let touched = ts("2024-04-01T00:00:00Z");+ let mut tx = pool.begin().await.unwrap();+ insert(+ &mut tx,+ NewEntityRecord::new(id, RegisteredEntityType::Chat, user_owner())+ .with_timestamps(created_at, original_updated),+ )+ .await;++ assert_eq!(+ touch_updated(&mut tx, id, touched).await.unwrap(),+ WriteOutcome::Applied+ );+ let row = sqlx::query!(+ r#"+ SELECT created_at, updated_at, deleted_at+ FROM entity+ WHERE id = $1+ "#,+ id,+ )+ .fetch_one(tx.as_mut())+ .await+ .unwrap();+ assert_eq!(row.created_at, created_at);+ assert_eq!(row.updated_at, touched);+ assert_eq!(row.deleted_at, None);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn delete_entity_removes_the_row_and_reports_not_found_second_time(pool: PgPool) {+ let id = Uuid::from_u128(1);+ let mut tx = pool.begin().await.unwrap();+ insert(+ &mut tx,+ NewEntityRecord::new(id, RegisteredEntityType::Chat, user_owner()),+ )+ .await;++ assert_eq!(+ delete_entity(&mut tx, id).await.unwrap(),+ WriteOutcome::Applied+ );+ let missing = sqlx::query_scalar!(+ r#"+ SELECT count(*) AS "count!"+ FROM entity+ WHERE id = $1+ "#,+ id,+ )+ .fetch_one(tx.as_mut())+ .await+ .unwrap();+ assert_eq!(missing, 0);+ assert_eq!(+ delete_entity(&mut tx, id).await.unwrap(),+ WriteOutcome::NotFound+ );+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn helpers_never_commit(pool: PgPool) {+ let id = Uuid::from_u128(1);+ let mut tx = pool.begin().await.unwrap();+ insert(+ &mut tx,+ NewEntityRecord::new(id, RegisteredEntityType::Chat, user_owner()),+ )+ .await;+ tx.rollback().await.unwrap();++ let count = sqlx::query_scalar!(+ r#"+ SELECT count(*) AS "count!"+ FROM entity+ WHERE id = $1+ "#,+ id,+ )+ .fetch_one(&pool)+ .await+ .unwrap();+ assert_eq!(count, 0);+}diff --git a/crates/entity_registry/shared_entity_registry/Cargo.toml b/crates/entity_registry/shared_entity_registry/Cargo.tomlnew file mode 100644index 0000000000..f555ff7b18--- /dev/null+++ b/crates/entity_registry/shared_entity_registry/Cargo.toml@@ -0,0 +1,14 @@+[package]+edition = "2024"+name = "shared_entity_registry"+publish = false+version = "0.1.0"++[dependencies]+chrono = { workspace = true }+model-entity = { path = "../../model-entity" }+model_owner = { path = "../../model_owner" }+rootcause = { workspace = true }+thiserror = { workspace = true }+uuid = { workspace = true }+workspace-hack = { version = "0.1", path = "../../workspace-hack" }diff --git a/crates/entity_registry/shared_entity_registry/src/lib.rs b/crates/entity_registry/shared_entity_registry/src/lib.rsnew file mode 100644index 0000000000..f7bcffe887--- /dev/null+++ b/crates/entity_registry/shared_entity_registry/src/lib.rs@@ -0,0 +1,192 @@+#![deny(missing_docs)]+//! Types shared by `entity_registry` and `entity_registry_db_utils`.+//!+//! Reads go through `entity_registry`. Transactional writes go through+//! `entity_registry_db_utils`. Neither crate depends on the other.+//!+//! ```+//! use model_entity::EntityType;+//! use model_owner::OwnerType;+//! use shared_entity_registry::{NewEntityRecord, Owner, RegisteredEntityType};+//! use uuid::Uuid;+//!+//! let owner = Owner::parse(OwnerType::User, "macro|[email protected]").unwrap();+//! let record = NewEntityRecord::try_new(Uuid::nil(), EntityType::Chat, owner.clone()).unwrap();+//! assert_eq!(record.entity_type, RegisteredEntityType::Chat);+//! assert!(NewEntityRecord::try_new(Uuid::nil(), EntityType::Initiative, owner).is_err());+//! ```++#[cfg(test)]+mod test;++use chrono::{DateTime, Utc};+use model_entity::EntityType;+use rootcause::Report;+use uuid::Uuid;++pub use model_owner::Owner;++/// The entity kinds the `entity` table accepts: its CHECK constraint as a type.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]+pub enum RegisteredEntityType {+ /// `project`+ Project,+ /// `document`+ Document,+ /// `chat`+ Chat,+ /// `agent_session`+ AgentSession,+ /// `scheduled_action`+ ScheduledAction,+}++impl RegisteredEntityType {+ /// Every registered kind.+ pub const ALL: [Self; 5] = [+ Self::Project,+ Self::Document,+ Self::Chat,+ Self::AgentSession,+ Self::ScheduledAction,+ ];++ /// The stored spelling.+ #[must_use]+ pub fn as_str(self) -> &'static str {+ EntityType::from(self).into()+ }+}++impl From<RegisteredEntityType> for EntityType {+ fn from(kind: RegisteredEntityType) -> Self {+ match kind {+ RegisteredEntityType::Project => Self::Project,+ RegisteredEntityType::Document => Self::Document,+ RegisteredEntityType::Chat => Self::Chat,+ RegisteredEntityType::AgentSession => Self::AgentSession,+ RegisteredEntityType::ScheduledAction => Self::ScheduledAction,+ }+ }+}++/// An [`EntityType`] the registry does not record.+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]+#[error("{0} is not a registered entity type")]+pub struct UnregisteredEntityType(pub EntityType);++impl TryFrom<EntityType> for RegisteredEntityType {+ type Error = UnregisteredEntityType;++ fn try_from(value: EntityType) -> Result<Self, Self::Error> {+ match value {+ EntityType::Project => Ok(Self::Project),+ EntityType::Document => Ok(Self::Document),+ EntityType::Chat => Ok(Self::Chat),+ EntityType::AgentSession => Ok(Self::AgentSession),+ EntityType::ScheduledAction => Ok(Self::ScheduledAction),+ other => Err(UnregisteredEntityType(other)),+ }+ }+}++impl std::fmt::Display for RegisteredEntityType {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.write_str(self.as_str())+ }+}++/// Input to register a row.+///+/// `None` timestamps take the database clock. Inside one transaction that+/// is the same instant the caller's own `DEFAULT now()` columns received,+/// so a create path passes nothing and the two rows agree.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct NewEntityRecord {+ /// The resource's id.+ pub id: Uuid,+ /// The kind of resource.+ pub entity_type: RegisteredEntityType,+ /// Who owns it.+ pub owner: Owner,+ /// `None` = database `now()`.+ pub created_at: Option<DateTime<Utc>>,+ /// `None` = database `now()`.+ pub updated_at: Option<DateTime<Utc>>,+}++impl NewEntityRecord {+ /// A record stamped by the database clock. The create-path constructor.+ #[must_use]+ pub fn new(id: Uuid, entity_type: RegisteredEntityType, owner: Owner) -> Self {+ Self {+ id,+ entity_type,+ owner,+ created_at: None,+ updated_at: None,+ }+ }++ /// Narrow a wide [`EntityType`] at the caller that holds it.+ pub fn try_new(+ id: Uuid,+ entity_type: EntityType,+ owner: Owner,+ ) -> Result<Self, UnregisteredEntityType> {+ Ok(Self::new(+ id,+ RegisteredEntityType::try_from(entity_type)?,+ owner,+ ))+ }++ /// Carry the resource row's own stamps. The backfill constructor.+ #[must_use]+ pub fn with_timestamps(self, created_at: DateTime<Utc>, updated_at: DateTime<Utc>) -> Self {+ Self {+ created_at: Some(created_at),+ updated_at: Some(updated_at),+ ..self+ }+ }+}++/// What an insert into the registry did.+///+/// `AlreadyRegistered` means a row with this id existed; it does **not**+/// mean that row matches the input.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum InsertOutcome {+ /// A new row was written.+ Inserted,+ /// A row with this id already existed; nothing was written.+ AlreadyRegistered,+}++/// What an id-targeted write did.+///+/// `NotFound` is an outcome, not an error. Callers that want strictness check+/// the value.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum WriteOutcome {+ /// Exactly one row matched and was written.+ Applied,+ /// No row with that id exists.+ NotFound,+}++/// Failure kinds of the registry.+#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]+pub enum EntityRegistryError {+ /// A stored row could not be decoded into a registry record.+ /// The attached id says which row.+ #[error("entity row is corrupt")]+ CorruptRow,+ /// The database failed. The attached cause is the driver error.+ #[error("entity registry persistence failed")]+ Infrastructure,+}++/// Typed report returned by every registry operation, read or write.+pub type EntityRegistryResult<T> = Result<T, Report<EntityRegistryError>>;diff --git a/crates/entity_registry/shared_entity_registry/src/test.rs b/crates/entity_registry/shared_entity_registry/src/test.rsnew file mode 100644index 0000000000..ae54cca648--- /dev/null+++ b/crates/entity_registry/shared_entity_registry/src/test.rs@@ -0,0 +1,77 @@+use model_entity::EntityType;+use model_owner::OwnerType;+use uuid::Uuid;++use super::*;++#[test]+fn registered_kinds_round_trip_and_match_check_spellings() {+ let expected = [+ (RegisteredEntityType::Project, "project"),+ (RegisteredEntityType::Document, "document"),+ (RegisteredEntityType::Chat, "chat"),+ (RegisteredEntityType::AgentSession, "agent_session"),+ (RegisteredEntityType::ScheduledAction, "scheduled_action"),+ ];+ assert_eq!(+ RegisteredEntityType::ALL,+ [+ RegisteredEntityType::Project,+ RegisteredEntityType::Document,+ RegisteredEntityType::Chat,+ RegisteredEntityType::AgentSession,+ RegisteredEntityType::ScheduledAction,+ ]+ );+ for (kind, spelling) in expected {+ assert_eq!(kind.as_str(), spelling);+ assert_eq!(kind.to_string(), spelling);+ let wide = EntityType::from(kind);+ assert_eq!(wide.as_ref(), spelling);+ assert_eq!(RegisteredEntityType::try_from(wide), Ok(kind));+ }+}++#[test]+fn try_from_rejects_every_unregistered_entity_type() {+ let unregistered = [+ EntityType::User,+ EntityType::Channel,+ EntityType::ChannelMessage,+ EntityType::EmailThread,+ EntityType::CalendarEvent,+ EntityType::Team,+ EntityType::Call,+ EntityType::ForeignEntity,+ EntityType::StaticFile,+ EntityType::CrmCompany,+ EntityType::CrmContact,+ EntityType::Reminder,+ EntityType::Skill,+ EntityType::Initiative,+ ];+ for ty in unregistered {+ assert_eq!(+ RegisteredEntityType::try_from(ty),+ Err(UnregisteredEntityType(ty))+ );+ }+}++#[test]+fn try_new_accepts_chat_and_rejects_initiative() {+ let owner = Owner::parse(OwnerType::User, "macro|[email protected]").unwrap();+ let id = Uuid::from_u128(1);++ let record = NewEntityRecord::try_new(id, EntityType::Chat, owner.clone()).unwrap();+ assert_eq!(record.id, id);+ assert_eq!(record.entity_type, RegisteredEntityType::Chat);+ assert_eq!(record.owner, owner);+ assert_eq!(record.created_at, None);+ assert_eq!(record.updated_at, None);++ assert_eq!(+ NewEntityRecord::try_new(id, EntityType::Initiative, owner),+ Err(UnregisteredEntityType(EntityType::Initiative))+ );+}diff --git a/tooling/just/rust.just b/tooling/just/rust.justindex 49127fe9e5..7c5762cb2f 100644--- a/tooling/just/rust.just+++ b/tooling/just/rust.just@@ -109,6 +109,8 @@ setup_test_envs:echo "DATABASE_URL={{ DATABASE_URL }}" >> ./crates/entity_access_management/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./crates/mobile_welcome_email_db_client/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./crates/entity_access_db_utils/.env+ echo "DATABASE_URL={{ DATABASE_URL }}" >> ./crates/entity_registry/entity_registry/.env+ echo "DATABASE_URL={{ DATABASE_URL }}" >> ./crates/entity_registry/entity_registry_db_utils/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./crates/mcp_client/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./services/document_storage_service/.envecho "DATABASE_URL={{ DATABASE_URL }}" >> ./crates/task_dedup/.env