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(foreign_entity): create foreign entity service (#3554)

Will Hutchinson989a1a3ae848
diff --git a/rust/cloud-storage/.sqlx/query-2765a1391d0f36121f7b42445e00be69a87c2a9c380a8fc2c64afa9fb509e9d8.json b/rust/cloud-storage/.sqlx/query-2765a1391d0f36121f7b42445e00be69a87c2a9c380a8fc2c64afa9fb509e9d8.json
new file mode 100644
index 0000000000..d54e213bf6
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-2765a1391d0f36121f7b42445e00be69a87c2a9c380a8fc2c64afa9fb509e9d8.json
@@ -0,0 +1,64 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n id as \"id!: Uuid\",\n foreign_entity_id as \"foreign_entity_id!: String\",\n foreign_entity_source as \"foreign_entity_source!: String\",\n metadata as \"metadata!: serde_json::Value\",\n stored_for_id as \"stored_for_id!: String\",\n stored_for_auth_entity as \"stored_for_auth_entity!: String\",\n created_at as \"created_at!: DateTime<Utc>\",\n updated_at as \"updated_at!: DateTime<Utc>\"\n FROM foreign_entity\n WHERE id = $1\n LIMIT 1\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id!: Uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "foreign_entity_id!: String",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "foreign_entity_source!: String",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "metadata!: serde_json::Value",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 4,
+ "name": "stored_for_id!: String",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "stored_for_auth_entity!: String",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_at!: DateTime<Utc>",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "updated_at!: DateTime<Utc>",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "2765a1391d0f36121f7b42445e00be69a87c2a9c380a8fc2c64afa9fb509e9d8"
+}
diff --git a/rust/cloud-storage/.sqlx/query-5fd401a3c1bd6de73881967420cd5056b6e87465a3e8c7bcde2db81b75ba2f57.json b/rust/cloud-storage/.sqlx/query-5fd401a3c1bd6de73881967420cd5056b6e87465a3e8c7bcde2db81b75ba2f57.json
new file mode 100644
index 0000000000..de122edc97
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-5fd401a3c1bd6de73881967420cd5056b6e87465a3e8c7bcde2db81b75ba2f57.json
@@ -0,0 +1,14 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n DELETE FROM foreign_entity\n WHERE id = $1\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "5fd401a3c1bd6de73881967420cd5056b6e87465a3e8c7bcde2db81b75ba2f57"
+}
diff --git a/rust/cloud-storage/.sqlx/query-9e8c46a871c582ee7016d87a3b0e3494eae0e23c6dbbbccfb139da68193690c7.json b/rust/cloud-storage/.sqlx/query-9e8c46a871c582ee7016d87a3b0e3494eae0e23c6dbbbccfb139da68193690c7.json
new file mode 100644
index 0000000000..cc5277d1eb
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-9e8c46a871c582ee7016d87a3b0e3494eae0e23c6dbbbccfb139da68193690c7.json
@@ -0,0 +1,69 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n UPDATE foreign_entity\n SET foreign_entity_id = COALESCE($2::text, foreign_entity_id),\n foreign_entity_source = COALESCE($3::text, foreign_entity_source),\n metadata = COALESCE($4::jsonb, metadata),\n stored_for_id = COALESCE($5::text, stored_for_id),\n stored_for_auth_entity = COALESCE($6::text, stored_for_auth_entity),\n updated_at = NOW()\n WHERE id = $1\n RETURNING\n id as \"id!: Uuid\",\n foreign_entity_id as \"foreign_entity_id!: String\",\n foreign_entity_source as \"foreign_entity_source!: String\",\n metadata as \"metadata!: serde_json::Value\",\n stored_for_id as \"stored_for_id!: String\",\n stored_for_auth_entity as \"stored_for_auth_entity!: String\",\n created_at as \"created_at!: DateTime<Utc>\",\n updated_at as \"updated_at!: DateTime<Utc>\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id!: Uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "foreign_entity_id!: String",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "foreign_entity_source!: String",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "metadata!: serde_json::Value",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 4,
+ "name": "stored_for_id!: String",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "stored_for_auth_entity!: String",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_at!: DateTime<Utc>",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "updated_at!: DateTime<Utc>",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Jsonb",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "9e8c46a871c582ee7016d87a3b0e3494eae0e23c6dbbbccfb139da68193690c7"
+}
diff --git a/rust/cloud-storage/.sqlx/query-b493e6fd1c1d8c34366f756fed903ef53cc87fab0b12cff50d2e3474ff997bd6.json b/rust/cloud-storage/.sqlx/query-b493e6fd1c1d8c34366f756fed903ef53cc87fab0b12cff50d2e3474ff997bd6.json
new file mode 100644
index 0000000000..6954ba0a21
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-b493e6fd1c1d8c34366f756fed903ef53cc87fab0b12cff50d2e3474ff997bd6.json
@@ -0,0 +1,65 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT\n id as \"id!: Uuid\",\n foreign_entity_id as \"foreign_entity_id!: String\",\n foreign_entity_source as \"foreign_entity_source!: String\",\n metadata as \"metadata!: serde_json::Value\",\n stored_for_id as \"stored_for_id!: String\",\n stored_for_auth_entity as \"stored_for_auth_entity!: String\",\n created_at as \"created_at!: DateTime<Utc>\",\n updated_at as \"updated_at!: DateTime<Utc>\"\n FROM foreign_entity\n WHERE foreign_entity_id = $1\n AND ($2::text IS NULL OR foreign_entity_source = $2)\n ORDER BY created_at ASC, id ASC\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id!: Uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "foreign_entity_id!: String",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "foreign_entity_source!: String",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "metadata!: serde_json::Value",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 4,
+ "name": "stored_for_id!: String",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "stored_for_auth_entity!: String",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_at!: DateTime<Utc>",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "updated_at!: DateTime<Utc>",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "b493e6fd1c1d8c34366f756fed903ef53cc87fab0b12cff50d2e3474ff997bd6"
+}
diff --git a/rust/cloud-storage/.sqlx/query-fd2b153cf0275acd708641fc7908abfce69d431447fcbf846e60aa60febb1433.json b/rust/cloud-storage/.sqlx/query-fd2b153cf0275acd708641fc7908abfce69d431447fcbf846e60aa60febb1433.json
new file mode 100644
index 0000000000..50aff8134c
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-fd2b153cf0275acd708641fc7908abfce69d431447fcbf846e60aa60febb1433.json
@@ -0,0 +1,69 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO foreign_entity (\n id,\n foreign_entity_id,\n foreign_entity_source,\n metadata,\n stored_for_id,\n stored_for_auth_entity\n )\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING\n id as \"id!: Uuid\",\n foreign_entity_id as \"foreign_entity_id!: String\",\n foreign_entity_source as \"foreign_entity_source!: String\",\n metadata as \"metadata!: serde_json::Value\",\n stored_for_id as \"stored_for_id!: String\",\n stored_for_auth_entity as \"stored_for_auth_entity!: String\",\n created_at as \"created_at!: DateTime<Utc>\",\n updated_at as \"updated_at!: DateTime<Utc>\"\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "id!: Uuid",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "foreign_entity_id!: String",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 2,
+ "name": "foreign_entity_source!: String",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "metadata!: serde_json::Value",
+ "type_info": "Jsonb"
+ },
+ {
+ "ordinal": 4,
+ "name": "stored_for_id!: String",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 5,
+ "name": "stored_for_auth_entity!: String",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 6,
+ "name": "created_at!: DateTime<Utc>",
+ "type_info": "Timestamptz"
+ },
+ {
+ "ordinal": 7,
+ "name": "updated_at!: DateTime<Utc>",
+ "type_info": "Timestamptz"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Text",
+ "Text",
+ "Jsonb",
+ "Text",
+ "Text"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false,
+ false
+ ]
+ },
+ "hash": "fd2b153cf0275acd708641fc7908abfce69d431447fcbf846e60aa60febb1433"
+}
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 4ab868bbb8..644c1a5a9e 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -4439,6 +4439,23 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"
+[[package]]
+name = "foreign_entity"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "chrono",
+ "macro_db_migrator",
+ "macro_uuid",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "thiserror 2.0.17",
+ "tokio",
+ "tracing",
+ "uuid",
+]
+
[[package]]
name = "form_urlencoded"
version = "1.2.2"
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 06cb28307f..c19ce19b6d 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -25,6 +25,7 @@ members = [
"email_service",
"email_sfs_delete_handler",
"email_suppression_handler",
+ "foreign_entity",
"image_optimizer",
"image_proxy_service",
"integration_tests/local_e2e",
diff --git a/rust/cloud-storage/foreign_entity/Cargo.toml b/rust/cloud-storage/foreign_entity/Cargo.toml
new file mode 100644
index 0000000000..303fd40d05
--- /dev/null
+++ b/rust/cloud-storage/foreign_entity/Cargo.toml
@@ -0,0 +1,27 @@
+[package]
+edition = "2024"
+name = "foreign_entity"
+publish = false
+version = "0.1.0"
+
+[features]
+default = ["outbound", "ports", "service"]
+outbound = ["dep:sqlx", "ports"]
+ports = ["dep:tokio"]
+service = ["ports"]
+
+[dependencies]
+anyhow = { workspace = true }
+chrono = { workspace = true }
+macro_uuid = { path = "../macro_uuid" }
+serde = { workspace = true }
+serde_json = { workspace = true }
+sqlx = { workspace = true, optional = true }
+thiserror = { workspace = true }
+tokio = { workspace = true, optional = true }
+tracing = { workspace = true }
+uuid = { workspace = true }
+
+[dev-dependencies]
+macro_db_migrator = { path = "../macro_db_migrator" }
+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
diff --git a/rust/cloud-storage/foreign_entity/src/domain.rs b/rust/cloud-storage/foreign_entity/src/domain.rs
new file mode 100644
index 0000000000..6e34618b64
--- /dev/null
+++ b/rust/cloud-storage/foreign_entity/src/domain.rs
@@ -0,0 +1,9 @@
+//! Domain layer: models, ports, and service implementation.
+
+pub mod models;
+
+#[cfg(feature = "ports")]
+pub mod ports;
+
+#[cfg(feature = "service")]
+pub mod service;
diff --git a/rust/cloud-storage/foreign_entity/src/domain/models.rs b/rust/cloud-storage/foreign_entity/src/domain/models.rs
new file mode 100644
index 0000000000..2b4813f4ba
--- /dev/null
+++ b/rust/cloud-storage/foreign_entity/src/domain/models.rs
@@ -0,0 +1,146 @@
+//! Domain models for foreign entity records.
+
+use chrono::{DateTime, Utc};
+use serde_json::Value;
+use uuid::Uuid;
+
+/// A persisted mapping to an entity owned by an external system.
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct ForeignEntity {
+ /// Internal primary key for this foreign entity record.
+ pub id: Uuid,
+ /// Identifier assigned by the external system.
+ pub foreign_entity_id: String,
+ /// Source system that owns the external identifier.
+ pub foreign_entity_source: String,
+ /// Arbitrary metadata stored with the mapping.
+ pub metadata: Value,
+ /// Internal entity identifier this foreign entity is stored for.
+ pub stored_for_id: String,
+ /// Internal auth entity namespace this foreign entity is stored for.
+ pub stored_for_auth_entity: String,
+ /// Timestamp when the record was created.
+ pub created_at: DateTime<Utc>,
+ /// Timestamp when the record was last updated.
+ pub updated_at: DateTime<Utc>,
+}
+
+/// Fields required to create a foreign entity record.
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct CreateForeignEntity {
+ /// Identifier assigned by the external system.
+ pub foreign_entity_id: String,
+ /// Source system that owns the external identifier.
+ pub foreign_entity_source: String,
+ /// Arbitrary metadata to store with the mapping.
+ #[serde(default = "default_metadata")]
+ pub metadata: Value,
+ /// Internal entity identifier this foreign entity is stored for.
+ pub stored_for_id: String,
+ /// Internal auth entity namespace this foreign entity is stored for.
+ pub stored_for_auth_entity: String,
+}
+
+/// Optional fields for patching a foreign entity record.
+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Default, PartialEq)]
+#[serde(rename_all = "camelCase")]
+pub struct PatchForeignEntity {
+ /// New external identifier. `None` leaves the current value unchanged.
+ pub foreign_entity_id: Option<String>,
+ /// New source system. `None` leaves the current value unchanged.
+ pub foreign_entity_source: Option<String>,
+ /// New metadata value. `None` leaves the current value unchanged.
+ pub metadata: Option<Value>,
+ /// New internal entity identifier. `None` leaves the current value unchanged.
+ pub stored_for_id: Option<String>,
+ /// New internal auth entity namespace. `None` leaves the current value unchanged.
+ pub stored_for_auth_entity: Option<String>,
+}
+
+/// Errors that can occur during foreign entity operations.
+#[derive(Debug, thiserror::Error)]
+pub enum ForeignEntityError {
+ /// The requested foreign entity record was not found.
+ #[error("foreign entity not found: {0}")]
+ NotFound(Uuid),
+ /// The request was invalid.
+ #[error("bad request: {0}")]
+ BadRequest(String),
+ /// An unexpected internal error occurred.
+ #[error("{0}")]
+ Internal(#[from] anyhow::Error),
+}
+
+impl CreateForeignEntity {
+ pub(crate) fn validate(&self) -> Result<(), ForeignEntityError> {
+ validate_non_blank("foreignEntityId", &self.foreign_entity_id)?;
+ validate_non_blank("foreignEntitySource", &self.foreign_entity_source)?;
+ validate_non_blank("storedForId", &self.stored_for_id)?;
+ validate_non_blank("storedForAuthEntity", &self.stored_for_auth_entity)?;
+
+ Ok(())
+ }
+}
+
+impl PatchForeignEntity {
+ pub(crate) fn validate(&self) -> Result<(), ForeignEntityError> {
+ if self.is_empty() {
+ return Err(ForeignEntityError::BadRequest(
+ "patch must include at least one field".to_string(),
+ ));
+ }
+
+ validate_optional_non_blank("foreignEntityId", self.foreign_entity_id.as_deref())?;
+ validate_optional_non_blank("foreignEntitySource", self.foreign_entity_source.as_deref())?;
+ validate_optional_non_blank("storedForId", self.stored_for_id.as_deref())?;
+ validate_optional_non_blank(
+ "storedForAuthEntity",
+ self.stored_for_auth_entity.as_deref(),
+ )?;
+
+ Ok(())
+ }
+
+ fn is_empty(&self) -> bool {
+ self.foreign_entity_id.is_none()
+ && self.foreign_entity_source.is_none()
+ && self.metadata.is_none()
+ && self.stored_for_id.is_none()
+ && self.stored_for_auth_entity.is_none()
+ }
+}
+
+pub(crate) fn validate_foreign_entity_lookup(
+ foreign_entity_id: &str,
+ foreign_entity_source: Option<&str>,
+) -> Result<(), ForeignEntityError> {
+ validate_non_blank("foreignEntityId", foreign_entity_id)?;
+ validate_optional_non_blank("foreignEntitySource", foreign_entity_source)
+}
+
+fn default_metadata() -> Value {
+ Value::Object(serde_json::Map::new())
+}
+
+fn validate_optional_non_blank(
+ field_name: &str,
+ value: Option<&str>,
+) -> Result<(), ForeignEntityError> {
+ if let Some(value) = value {
+ validate_non_blank(field_name, value)?;
+ }
+
+ Ok(())
+}
+
+fn validate_non_blank(field_name: &str, value: &str) -> Result<(), ForeignEntityError> {
+ if value.trim().is_empty() {
+ return Err(ForeignEntityError::BadRequest(format!(
+ "{field_name} must not be blank"
+ )));
+ }
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/foreign_entity/src/domain/ports.rs b/rust/cloud-storage/foreign_entity/src/domain/ports.rs
new file mode 100644
index 0000000000..dd4d6529c0
--- /dev/null
+++ b/rust/cloud-storage/foreign_entity/src/domain/ports.rs
@@ -0,0 +1,99 @@
+//! Port definitions for the foreign entity domain.
+//!
+//! These traits define the contracts that adapters and service consumers use.
+
+use std::future::Future;
+
+use uuid::Uuid;
+
+use super::models::{CreateForeignEntity, ForeignEntity, ForeignEntityError, PatchForeignEntity};
+
+/// Repository for persisting and fetching foreign entity records.
+///
+/// Implementations are responsible for database operations and should return
+/// `Ok(None)` or `Ok(false)` when a requested row does not exist.
+pub trait ForeignEntityRepository: Send + Sync + 'static {
+ /// Error type returned by repository operations.
+ type Err: Into<anyhow::Error> + Send + std::fmt::Debug;
+
+ /// Fetch a foreign entity record by its internal primary key.
+ fn get_foreign_entity_by_id(
+ &self,
+ id: Uuid,
+ ) -> impl Future<Output = Result<Option<ForeignEntity>, Self::Err>> + Send;
+
+ /// Fetch foreign entity records by their external identifier.
+ ///
+ /// When `foreign_entity_source` is provided, only records from that source
+ /// should be returned. An empty result is a successful lookup.
+ fn get_foreign_entities_by_foreign_entity_id(
+ &self,
+ foreign_entity_id: &str,
+ foreign_entity_source: Option<&str>,
+ ) -> impl Future<Output = Result<Vec<ForeignEntity>, Self::Err>> + Send;
+
+ /// Create a foreign entity record using the supplied internal primary key.
+ fn create_foreign_entity(
+ &self,
+ id: Uuid,
+ create: CreateForeignEntity,
+ ) -> impl Future<Output = Result<ForeignEntity, Self::Err>> + Send;
+
+ /// Delete a foreign entity record by internal primary key.
+ ///
+ /// Returns `true` when a row was deleted and `false` when no row matched.
+ fn delete_foreign_entity(
+ &self,
+ id: Uuid,
+ ) -> impl Future<Output = Result<bool, Self::Err>> + Send;
+
+ /// Patch selected fields on a foreign entity record.
+ ///
+ /// Returns `Ok(None)` when no row matched the supplied internal primary key.
+ fn patch_foreign_entity(
+ &self,
+ id: Uuid,
+ patch: PatchForeignEntity,
+ ) -> impl Future<Output = Result<Option<ForeignEntity>, Self::Err>> + Send;
+}
+
+/// Service interface for foreign entity CRUD operations.
+///
+/// The service owns validation, ID generation, and mapping repository misses to
+/// domain errors.
+pub trait ForeignEntityService: Send + Sync + 'static {
+ /// Fetch a foreign entity record by its internal primary key.
+ fn get_foreign_entity_by_id(
+ &self,
+ id: Uuid,
+ ) -> impl Future<Output = Result<ForeignEntity, ForeignEntityError>> + Send;
+
+ /// Fetch foreign entity records by their external identifier.
+ ///
+ /// When `foreign_entity_source` is provided, only records from that source
+ /// are returned. An empty result is a successful lookup.
+ fn get_foreign_entities_by_foreign_entity_id(
+ &self,
+ foreign_entity_id: &str,
+ foreign_entity_source: Option<&str>,
+ ) -> impl Future<Output = Result<Vec<ForeignEntity>, ForeignEntityError>> + Send;
+
+ /// Create a foreign entity record.
+ fn create_foreign_entity(
+ &self,
+ create: CreateForeignEntity,
+ ) -> impl Future<Output = Result<ForeignEntity, ForeignEntityError>> + Send;
+
+ /// Delete a foreign entity record by internal primary key.
+ fn delete_foreign_entity(
+ &self,
+ id: Uuid,
+ ) -> impl Future<Output = Result<(), ForeignEntityError>> + Send;
+
+ /// Patch selected fields on a foreign entity record.
+ fn patch_foreign_entity(
+ &self,
+ id: Uuid,
+ patch: PatchForeignEntity,
+ ) -> impl Future<Output = Result<ForeignEntity, ForeignEntityError>> + Send;
+}
diff --git a/rust/cloud-storage/foreign_entity/src/domain/service.rs b/rust/cloud-storage/foreign_entity/src/domain/service.rs
new file mode 100644
index 0000000000..f95cb19b9f
--- /dev/null
+++ b/rust/cloud-storage/foreign_entity/src/domain/service.rs
@@ -0,0 +1,101 @@
+//! Foreign entity service implementation.
+
+#[cfg(test)]
+mod tests;
+
+use uuid::Uuid;
+
+use super::models::{
+ CreateForeignEntity, ForeignEntity, ForeignEntityError, PatchForeignEntity,
+ validate_foreign_entity_lookup,
+};
+use super::ports::{ForeignEntityRepository, ForeignEntityService};
+
+/// Concrete foreign entity service implementation.
+pub struct ForeignEntityServiceImpl<R> {
+ repo: R,
+}
+
+impl<R> ForeignEntityServiceImpl<R>
+where
+ R: ForeignEntityRepository,
+{
+ /// Create a foreign entity service backed by the provided repository.
+ pub fn new(repo: R) -> Self {
+ Self { repo }
+ }
+}
+
+impl<R> ForeignEntityService for ForeignEntityServiceImpl<R>
+where
+ R: ForeignEntityRepository,
+{
+ #[tracing::instrument(err, skip(self))]
+ async fn get_foreign_entity_by_id(
+ &self,
+ id: Uuid,
+ ) -> Result<ForeignEntity, ForeignEntityError> {
+ self.repo
+ .get_foreign_entity_by_id(id)
+ .await
+ .map_err(|error| ForeignEntityError::Internal(error.into()))?
+ .ok_or(ForeignEntityError::NotFound(id))
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_foreign_entities_by_foreign_entity_id(
+ &self,
+ foreign_entity_id: &str,
+ foreign_entity_source: Option<&str>,
+ ) -> Result<Vec<ForeignEntity>, ForeignEntityError> {
+ validate_foreign_entity_lookup(foreign_entity_id, foreign_entity_source)?;
+
+ self.repo
+ .get_foreign_entities_by_foreign_entity_id(foreign_entity_id, foreign_entity_source)
+ .await
+ .map_err(|error| ForeignEntityError::Internal(error.into()))
+ }
+
+ #[tracing::instrument(err, skip(self, create))]
+ async fn create_foreign_entity(
+ &self,
+ create: CreateForeignEntity,
+ ) -> Result<ForeignEntity, ForeignEntityError> {
+ create.validate()?;
+
+ self.repo
+ .create_foreign_entity(macro_uuid::generate_uuid_v7(), create)
+ .await
+ .map_err(|error| ForeignEntityError::Internal(error.into()))
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn delete_foreign_entity(&self, id: Uuid) -> Result<(), ForeignEntityError> {
+ let deleted = self
+ .repo
+ .delete_foreign_entity(id)
+ .await
+ .map_err(|error| ForeignEntityError::Internal(error.into()))?;
+
+ if deleted {
+ Ok(())
+ } else {
+ Err(ForeignEntityError::NotFound(id))
+ }
+ }
+
+ #[tracing::instrument(err, skip(self, patch))]
+ async fn patch_foreign_entity(
+ &self,
+ id: Uuid,
+ patch: PatchForeignEntity,
+ ) -> Result<ForeignEntity, ForeignEntityError> {
+ patch.validate()?;
+
+ self.repo
+ .patch_foreign_entity(id, patch)
+ .await
+ .map_err(|error| ForeignEntityError::Internal(error.into()))?
+ .ok_or(ForeignEntityError::NotFound(id))
+ }
+}
diff --git a/rust/cloud-storage/foreign_entity/src/domain/service/tests.rs b/rust/cloud-storage/foreign_entity/src/domain/service/tests.rs
new file mode 100644
index 0000000000..703bf0a511
--- /dev/null
+++ b/rust/cloud-storage/foreign_entity/src/domain/service/tests.rs
@@ -0,0 +1,332 @@
+use std::collections::HashMap;
+use std::sync::{Arc, Mutex};
+
+use chrono::Utc;
+use serde_json::json;
+use uuid::Uuid;
+
+use super::*;
+
+#[derive(Clone, Default)]
+struct FakeForeignEntityRepository {
+ records: Arc<Mutex<HashMap<Uuid, ForeignEntity>>>,
+}
+
+impl FakeForeignEntityRepository {
+ fn records(&self) -> std::sync::MutexGuard<'_, HashMap<Uuid, ForeignEntity>> {
+ self.records
+ .lock()
+ .expect("fake foreign entity repository lock poisoned")
+ }
+}
+
+impl ForeignEntityRepository for FakeForeignEntityRepository {
+ type Err = anyhow::Error;
+
+ async fn get_foreign_entity_by_id(&self, id: Uuid) -> Result<Option<ForeignEntity>, Self::Err> {
+ Ok(self.records().get(&id).cloned())
+ }
+
+ async fn get_foreign_entities_by_foreign_entity_id(
+ &self,
+ foreign_entity_id: &str,
+ foreign_entity_source: Option<&str>,
+ ) -> Result<Vec<ForeignEntity>, Self::Err> {
+ let records = self
+ .records()
+ .values()
+ .filter(|record| {
+ record.foreign_entity_id == foreign_entity_id
+ && foreign_entity_source
+ .map(|source| record.foreign_entity_source == source)
+ .unwrap_or(true)
+ })
+ .cloned()
+ .collect();
+
+ Ok(records)
+ }
+
+ async fn create_foreign_entity(
+ &self,
+ id: Uuid,
+ create: CreateForeignEntity,
+ ) -> Result<ForeignEntity, Self::Err> {
+ let now = Utc::now();
+ let entity = ForeignEntity {
+ id,
+ foreign_entity_id: create.foreign_entity_id,
+ foreign_entity_source: create.foreign_entity_source,
+ metadata: create.metadata,
+ stored_for_id: create.stored_for_id,
+ stored_for_auth_entity: create.stored_for_auth_entity,
+ created_at: now,
+ updated_at: now,
+ };
+
+ self.records().insert(id, entity.clone());
+
+ Ok(entity)
+ }
+
+ async fn delete_foreign_entity(&self, id: Uuid) -> Result<bool, Self::Err> {
+ Ok(self.records().remove(&id).is_some())
+ }
+
+ async fn patch_foreign_entity(
+ &self,
+ id: Uuid,
+ patch: PatchForeignEntity,
+ ) -> Result<Option<ForeignEntity>, Self::Err> {
+ let mut records = self.records();
+ let Some(entity) = records.get_mut(&id) else {
+ return Ok(None);
+ };
+
+ if let Some(foreign_entity_id) = patch.foreign_entity_id {
+ entity.foreign_entity_id = foreign_entity_id;
+ }
+ if let Some(foreign_entity_source) = patch.foreign_entity_source {
+ entity.foreign_entity_source = foreign_entity_source;
+ }
+ if let Some(metadata) = patch.metadata {
+ entity.metadata = metadata;
+ }
+ if let Some(stored_for_id) = patch.stored_for_id {
+ entity.stored_for_id = stored_for_id;
+ }
+ if let Some(stored_for_auth_entity) = patch.stored_for_auth_entity {
+ entity.stored_for_auth_entity = stored_for_auth_entity;
+ }
+
+ entity.updated_at = Utc::now();
+
+ Ok(Some(entity.clone()))
+ }
+}
+
+fn service() -> ForeignEntityServiceImpl<FakeForeignEntityRepository> {
+ ForeignEntityServiceImpl::new(FakeForeignEntityRepository::default())
+}
+
+fn valid_create() -> CreateForeignEntity {
+ CreateForeignEntity {
+ foreign_entity_id: "external-entity-1".to_string(),
+ foreign_entity_source: "linear".to_string(),
+ metadata: json!({ "team": "engineering" }),
+ stored_for_id: "document-1".to_string(),
+ stored_for_auth_entity: "document".to_string(),
+ }
+}
+
+fn assert_bad_request(error: ForeignEntityError, expected_message: &str) {
+ let ForeignEntityError::BadRequest(message) = error else {
+ panic!("expected bad request error, got {error:?}");
+ };
+
+ assert!(
+ message.contains(expected_message),
+ "expected bad request message '{message}' to contain '{expected_message}'"
+ );
+}
+
+fn assert_not_found(error: ForeignEntityError, expected_id: Uuid) {
+ let ForeignEntityError::NotFound(actual_id) = error else {
+ panic!("expected not found error, got {error:?}");
+ };
+
+ assert_eq!(actual_id, expected_id);
+}
+
+#[tokio::test]
+async fn create_persists_foreign_entity_with_generated_id() {
+ let service = service();
+
+ let created = service
+ .create_foreign_entity(valid_create())
+ .await
+ .expect("valid foreign entity should be created");
+
+ assert_ne!(created.id, Uuid::nil());
+ assert_eq!(created.foreign_entity_id, "external-entity-1");
+ assert_eq!(created.foreign_entity_source, "linear");
+ assert_eq!(created.metadata, json!({ "team": "engineering" }));
+ assert_eq!(created.stored_for_id, "document-1");
+ assert_eq!(created.stored_for_auth_entity, "document");
+
+ let fetched = service
+ .get_foreign_entity_by_id(created.id)
+ .await
+ .expect("created foreign entity should be fetched");
+
+ assert_eq!(fetched, created);
+}
+
+#[tokio::test]
+async fn get_by_foreign_entity_id_returns_all_matching_records() {
+ let service = service();
+ let mut second_create = valid_create();
+ second_create.foreign_entity_source = "github".to_string();
+
+ service
+ .create_foreign_entity(valid_create())
+ .await
+ .expect("first foreign entity should be created");
+ service
+ .create_foreign_entity(second_create)
+ .await
+ .expect("second foreign entity should be created");
+
+ let all_matches = service
+ .get_foreign_entities_by_foreign_entity_id("external-entity-1", None)
+ .await
+ .expect("matching foreign entities should be returned");
+ let source_matches = service
+ .get_foreign_entities_by_foreign_entity_id("external-entity-1", Some("github"))
+ .await
+ .expect("source-filtered foreign entities should be returned");
+
+ assert_eq!(all_matches.len(), 2);
+ assert_eq!(source_matches.len(), 1);
+ assert_eq!(source_matches[0].foreign_entity_source, "github");
+}
+
+#[tokio::test]
+async fn get_missing_foreign_entity_by_id_returns_not_found() {
+ let service = service();
+ let id = Uuid::new_v4();
+
+ let error = service
+ .get_foreign_entity_by_id(id)
+ .await
+ .expect_err("missing foreign entity should return not found");
+
+ assert_not_found(error, id);
+}
+
+#[tokio::test]
+async fn create_rejects_blank_required_fields() {
+ let service = service();
+ let cases: Vec<(&str, fn(&mut CreateForeignEntity))> = vec![
+ ("foreignEntityId", |create| {
+ create.foreign_entity_id = " \t".to_string();
+ }),
+ ("foreignEntitySource", |create| {
+ create.foreign_entity_source = "\n".to_string();
+ }),
+ ("storedForId", |create| {
+ create.stored_for_id = " ".to_string();
+ }),
+ ("storedForAuthEntity", |create| {
+ create.stored_for_auth_entity = "\r\n".to_string();
+ }),
+ ];
+
+ for (field_name, make_blank) in cases {
+ let mut create = valid_create();
+ make_blank(&mut create);
+
+ let error = service
+ .create_foreign_entity(create)
+ .await
+ .expect_err("blank create field should be rejected");
+
+ assert_bad_request(error, field_name);
+ }
+}
+
+#[tokio::test]
+async fn patch_rejects_empty_patch() {
+ let service = service();
+
+ let error = service
+ .patch_foreign_entity(Uuid::new_v4(), PatchForeignEntity::default())
+ .await
+ .expect_err("empty patch should be rejected");
+
+ assert_bad_request(error, "at least one field");
+}
+
+#[tokio::test]
+async fn patch_rejects_blank_string_fields() {
+ let service = service();
+ let cases = vec![
+ (
+ "foreignEntityId",
+ PatchForeignEntity {
+ foreign_entity_id: Some(" ".to_string()),
+ ..Default::default()
+ },
+ ),
+ (
+ "foreignEntitySource",
+ PatchForeignEntity {
+ foreign_entity_source: Some("\t".to_string()),
+ ..Default::default()
+ },
+ ),
+ (
+ "storedForId",
+ PatchForeignEntity {
+ stored_for_id: Some("\n".to_string()),
+ ..Default::default()
+ },
+ ),
+ (
+ "storedForAuthEntity",
+ PatchForeignEntity {
+ stored_for_auth_entity: Some("\r\n".to_string()),
+ ..Default::default()
+ },
+ ),
+ ];
+
+ for (field_name, patch) in cases {
+ let error = service
+ .patch_foreign_entity(Uuid::new_v4(), patch)
+ .await
+ .expect_err("blank patch field should be rejected");
+
+ assert_bad_request(error, field_name);
+ }
+}
+
+#[tokio::test]
+async fn patch_missing_foreign_entity_returns_not_found() {
+ let service = service();
+ let id = Uuid::new_v4();
+
+ let error = service
+ .patch_foreign_entity(
+ id,
+ PatchForeignEntity {
+ metadata: Some(json!({ "status": "updated" })),
+ ..Default::default()
+ },
+ )
+ .await
+ .expect_err("missing foreign entity should return not found");
+
+ assert_not_found(error, id);
+}
+
+#[tokio::test]
+async fn delete_returns_ok_when_deleted_and_not_found_when_missing() {
+ let service = service();
+ let created = service
+ .create_foreign_entity(valid_create())
+ .await
+ .expect("valid foreign entity should be created");
+
+ service
+ .delete_foreign_entity(created.id)
+ .await
+ .expect("existing foreign entity should be deleted");
+
+ let error = service
+ .delete_foreign_entity(created.id)
+ .await
+ .expect_err("second delete should return not found");
+
+ assert_not_found(error, created.id);
+}
diff --git a/rust/cloud-storage/foreign_entity/src/lib.rs b/rust/cloud-storage/foreign_entity/src/lib.rs
new file mode 100644
index 0000000000..09c179a631
--- /dev/null
+++ b/rust/cloud-storage/foreign_entity/src/lib.rs
@@ -0,0 +1,16 @@
+//! Foreign entity hexagonal architecture crate.
+//!
+//! Encapsulates CRUD operations for external entity mappings using a
+//! ports-and-adapters pattern.
+//!
+//! # Architecture
+//!
+//! - **domain**: Contains domain models, ports, and service implementation.
+//! - **outbound**: Contains adapters for external persistence systems.
+
+#![deny(missing_docs)]
+
+pub mod domain;
+
+#[cfg(feature = "outbound")]
+pub mod outbound;
diff --git a/rust/cloud-storage/foreign_entity/src/outbound.rs b/rust/cloud-storage/foreign_entity/src/outbound.rs
new file mode 100644
index 0000000000..cfe8b3bfdf
--- /dev/null
+++ b/rust/cloud-storage/foreign_entity/src/outbound.rs
@@ -0,0 +1,4 @@
+//! Outbound adapters for foreign entity persistence.
+
+/// PostgreSQL repository implementation for foreign entity persistence.
+pub mod pg_foreign_entity_repo;
diff --git a/rust/cloud-storage/foreign_entity/src/outbound/pg_foreign_entity_repo.rs b/rust/cloud-storage/foreign_entity/src/outbound/pg_foreign_entity_repo.rs
new file mode 100644
index 0000000000..18ef4f0697
--- /dev/null
+++ b/rust/cloud-storage/foreign_entity/src/outbound/pg_foreign_entity_repo.rs
@@ -0,0 +1,182 @@
+//! PostgreSQL implementation of the [`ForeignEntityRepository`] port.
+
+#[cfg(test)]
+mod tests;
+
+use chrono::{DateTime, Utc};
+use sqlx::PgPool;
+use uuid::Uuid;
+
+use crate::domain::models::{CreateForeignEntity, ForeignEntity, PatchForeignEntity};
+use crate::domain::ports::ForeignEntityRepository;
+
+/// PostgreSQL-backed foreign entity repository.
+#[derive(Clone)]
+pub struct PgForeignEntityRepo {
+ pool: PgPool,
+}
+
+impl PgForeignEntityRepo {
+ /// Create a new repository backed by the given connection pool.
+ pub fn new(pool: PgPool) -> Self {
+ Self { pool }
+ }
+}
+
+impl ForeignEntityRepository for PgForeignEntityRepo {
+ type Err = sqlx::Error;
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_foreign_entity_by_id(&self, id: Uuid) -> Result<Option<ForeignEntity>, Self::Err> {
+ sqlx::query_as!(
+ ForeignEntity,
+ r#"
+ SELECT
+ id as "id!: Uuid",
+ foreign_entity_id as "foreign_entity_id!: String",
+ foreign_entity_source as "foreign_entity_source!: String",
+ metadata as "metadata!: serde_json::Value",
+ stored_for_id as "stored_for_id!: String",
+ stored_for_auth_entity as "stored_for_auth_entity!: String",
+ created_at as "created_at!: DateTime<Utc>",
+ updated_at as "updated_at!: DateTime<Utc>"
+ FROM foreign_entity
+ WHERE id = $1
+ LIMIT 1
+ "#,
+ id,
+ )
+ .fetch_optional(&self.pool)
+ .await
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn get_foreign_entities_by_foreign_entity_id(
+ &self,
+ foreign_entity_id: &str,
+ foreign_entity_source: Option<&str>,
+ ) -> Result<Vec<ForeignEntity>, Self::Err> {
+ sqlx::query_as!(
+ ForeignEntity,
+ r#"
+ SELECT
+ id as "id!: Uuid",
+ foreign_entity_id as "foreign_entity_id!: String",
+ foreign_entity_source as "foreign_entity_source!: String",
+ metadata as "metadata!: serde_json::Value",
+ stored_for_id as "stored_for_id!: String",
+ stored_for_auth_entity as "stored_for_auth_entity!: String",
+ created_at as "created_at!: DateTime<Utc>",
+ updated_at as "updated_at!: DateTime<Utc>"
+ FROM foreign_entity
+ WHERE foreign_entity_id = $1
+ AND ($2::text IS NULL OR foreign_entity_source = $2)
+ ORDER BY created_at ASC, id ASC
+ "#,
+ foreign_entity_id,
+ foreign_entity_source,
+ )
+ .fetch_all(&self.pool)
+ .await
+ }
+
+ #[tracing::instrument(err, skip(self, create))]
+ async fn create_foreign_entity(
+ &self,
+ id: Uuid,
+ create: CreateForeignEntity,
+ ) -> Result<ForeignEntity, Self::Err> {
+ sqlx::query_as!(
+ ForeignEntity,
+ r#"
+ INSERT INTO foreign_entity (
+ id,
+ foreign_entity_id,
+ foreign_entity_source,
+ metadata,
+ stored_for_id,
+ stored_for_auth_entity
+ )
+ VALUES ($1, $2, $3, $4, $5, $6)
+ RETURNING
+ id as "id!: Uuid",
+ foreign_entity_id as "foreign_entity_id!: String",
+ foreign_entity_source as "foreign_entity_source!: String",
+ metadata as "metadata!: serde_json::Value",
+ stored_for_id as "stored_for_id!: String",
+ stored_for_auth_entity as "stored_for_auth_entity!: String",
+ created_at as "created_at!: DateTime<Utc>",
+ updated_at as "updated_at!: DateTime<Utc>"
+ "#,
+ id,
+ create.foreign_entity_id,
+ create.foreign_entity_source,
+ create.metadata,
+ create.stored_for_id,
+ create.stored_for_auth_entity,
+ )
+ .fetch_one(&self.pool)
+ .await
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn delete_foreign_entity(&self, id: Uuid) -> Result<bool, Self::Err> {
+ let result = sqlx::query!(
+ r#"
+ DELETE FROM foreign_entity
+ WHERE id = $1
+ "#,
+ id,
+ )
+ .execute(&self.pool)
+ .await?;
+
+ Ok(result.rows_affected() > 0)
+ }
+
+ #[tracing::instrument(err, skip(self, patch))]
+ async fn patch_foreign_entity(
+ &self,
+ id: Uuid,
+ patch: PatchForeignEntity,
+ ) -> Result<Option<ForeignEntity>, Self::Err> {
+ let PatchForeignEntity {
+ foreign_entity_id,
+ foreign_entity_source,
+ metadata,
+ stored_for_id,
+ stored_for_auth_entity,
+ } = patch;
+
+ sqlx::query_as!(
+ ForeignEntity,
+ r#"
+ UPDATE foreign_entity
+ SET foreign_entity_id = COALESCE($2::text, foreign_entity_id),
+ foreign_entity_source = COALESCE($3::text, foreign_entity_source),
+ metadata = COALESCE($4::jsonb, metadata),
+ stored_for_id = COALESCE($5::text, stored_for_id),
+ stored_for_auth_entity = COALESCE($6::text, stored_for_auth_entity),
+ updated_at = NOW()
+ WHERE id = $1
+ RETURNING
+ id as "id!: Uuid",
+ foreign_entity_id as "foreign_entity_id!: String",
+ foreign_entity_source as "foreign_entity_source!: String",
+ metadata as "metadata!: serde_json::Value",
+ stored_for_id as "stored_for_id!: String",
+ stored_for_auth_entity as "stored_for_auth_entity!: String",
+ created_at as "created_at!: DateTime<Utc>",
+ updated_at as "updated_at!: DateTime<Utc>"
+ "#,
+ id,
+ foreign_entity_id,
+ foreign_entity_source,
+ metadata,
+ stored_for_id,
+ stored_for_auth_entity,
+ )
+ .fetch_optional(&self.pool)
+ .await
+ }
+}
diff --git a/rust/cloud-storage/foreign_entity/src/outbound/pg_foreign_entity_repo/tests.rs b/rust/cloud-storage/foreign_entity/src/outbound/pg_foreign_entity_repo/tests.rs
new file mode 100644
index 0000000000..50123f161e
--- /dev/null
+++ b/rust/cloud-storage/foreign_entity/src/outbound/pg_foreign_entity_repo/tests.rs
@@ -0,0 +1,217 @@
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use serde_json::json;
+use sqlx::PgPool;
+use uuid::Uuid;
+
+use super::PgForeignEntityRepo;
+use crate::domain::models::{CreateForeignEntity, ForeignEntity, PatchForeignEntity};
+use crate::domain::ports::ForeignEntityRepository;
+
+fn create_request(
+ foreign_entity_id: impl Into<String>,
+ foreign_entity_source: impl Into<String>,
+) -> CreateForeignEntity {
+ CreateForeignEntity {
+ foreign_entity_id: foreign_entity_id.into(),
+ foreign_entity_source: foreign_entity_source.into(),
+ metadata: json!({ "origin": "test" }),
+ stored_for_id: "document-1".to_string(),
+ stored_for_auth_entity: "document".to_string(),
+ }
+}
+
+async fn insert_foreign_entity(
+ repo: &PgForeignEntityRepo,
+ foreign_entity_id: &str,
+ foreign_entity_source: &str,
+) -> ForeignEntity {
+ repo.create_foreign_entity(
+ Uuid::now_v7(),
+ create_request(foreign_entity_id, foreign_entity_source),
+ )
+ .await
+ .expect("foreign entity should be inserted")
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn create_inserts_row_and_returns_persisted_fields(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool.clone());
+ let id = Uuid::now_v7();
+ let create = CreateForeignEntity {
+ foreign_entity_id: "external-entity-1".to_string(),
+ foreign_entity_source: "linear".to_string(),
+ metadata: json!({ "team": "engineering" }),
+ stored_for_id: "document-1".to_string(),
+ stored_for_auth_entity: "document".to_string(),
+ };
+
+ let entity = repo
+ .create_foreign_entity(id, create)
+ .await
+ .expect("foreign entity should be created");
+
+ assert_eq!(entity.id, id);
+ assert_eq!(entity.foreign_entity_id, "external-entity-1");
+ assert_eq!(entity.foreign_entity_source, "linear");
+ assert_eq!(entity.metadata, json!({ "team": "engineering" }));
+ assert_eq!(entity.stored_for_id, "document-1");
+ assert_eq!(entity.stored_for_auth_entity, "document");
+ assert!(entity.created_at <= chrono::Utc::now());
+ assert!(entity.updated_at >= entity.created_at);
+
+ let row = sqlx::query!(
+ r#"
+ SELECT COUNT(*) as "persisted_count!"
+ FROM foreign_entity
+ WHERE id = $1
+ "#,
+ id,
+ )
+ .fetch_one(&pool)
+ .await
+ .expect("persisted row count should be fetched");
+
+ assert_eq!(row.persisted_count, 1);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn get_by_id_returns_some_for_existing_and_none_for_missing(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool);
+ let entity = insert_foreign_entity(&repo, "external-entity-1", "linear").await;
+
+ let fetched = repo
+ .get_foreign_entity_by_id(entity.id)
+ .await
+ .expect("existing foreign entity lookup should succeed");
+ let missing = repo
+ .get_foreign_entity_by_id(Uuid::now_v7())
+ .await
+ .expect("missing foreign entity lookup should succeed");
+
+ assert_eq!(fetched, Some(entity));
+ assert_eq!(missing, None);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn get_by_foreign_entity_id_returns_all_matches_and_supports_source_filter(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool);
+ let first = insert_foreign_entity(&repo, "shared-external-id", "linear").await;
+ let second = insert_foreign_entity(&repo, "shared-external-id", "github").await;
+ insert_foreign_entity(&repo, "other-external-id", "linear").await;
+
+ let all_matches = repo
+ .get_foreign_entities_by_foreign_entity_id("shared-external-id", None)
+ .await
+ .expect("unfiltered lookup should succeed");
+ let source_matches = repo
+ .get_foreign_entities_by_foreign_entity_id("shared-external-id", Some("github"))
+ .await
+ .expect("source-filtered lookup should succeed");
+ let missing_source_matches = repo
+ .get_foreign_entities_by_foreign_entity_id("shared-external-id", Some("salesforce"))
+ .await
+ .expect("missing source lookup should succeed");
+
+ let mut all_match_ids = all_matches
+ .iter()
+ .map(|entity| entity.id)
+ .collect::<Vec<_>>();
+ all_match_ids.sort_unstable();
+
+ let mut expected_ids = vec![first.id, second.id];
+ expected_ids.sort_unstable();
+
+ assert_eq!(all_match_ids, expected_ids);
+ assert_eq!(source_matches, vec![second]);
+ assert!(missing_source_matches.is_empty());
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn patch_updates_selected_fields_preserves_others_and_refreshes_updated_at(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool.clone());
+ let entity = insert_foreign_entity(&repo, "external-entity-1", "linear").await;
+
+ sqlx::query!(
+ r#"
+ UPDATE foreign_entity
+ SET updated_at = NOW() - INTERVAL '1 hour'
+ WHERE id = $1
+ "#,
+ entity.id,
+ )
+ .execute(&pool)
+ .await
+ .expect("updated_at should be backdated");
+
+ let backdated = repo
+ .get_foreign_entity_by_id(entity.id)
+ .await
+ .expect("backdated foreign entity lookup should succeed")
+ .expect("backdated foreign entity should exist");
+
+ let patched = repo
+ .patch_foreign_entity(
+ entity.id,
+ PatchForeignEntity {
+ foreign_entity_id: Some("external-entity-2".to_string()),
+ metadata: Some(json!({ "patched": true })),
+ ..Default::default()
+ },
+ )
+ .await
+ .expect("patch should succeed")
+ .expect("existing foreign entity should be patched");
+
+ assert_eq!(patched.id, entity.id);
+ assert_eq!(patched.foreign_entity_id, "external-entity-2");
+ assert_eq!(patched.foreign_entity_source, entity.foreign_entity_source);
+ assert_eq!(patched.metadata, json!({ "patched": true }));
+ assert_eq!(patched.stored_for_id, entity.stored_for_id);
+ assert_eq!(
+ patched.stored_for_auth_entity,
+ entity.stored_for_auth_entity
+ );
+ assert_eq!(patched.created_at, entity.created_at);
+ assert!(patched.updated_at > backdated.updated_at);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn patch_missing_id_returns_none(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool);
+
+ let result = repo
+ .patch_foreign_entity(
+ Uuid::now_v7(),
+ PatchForeignEntity {
+ foreign_entity_source: Some("github".to_string()),
+ ..Default::default()
+ },
+ )
+ .await
+ .expect("missing patch should succeed");
+
+ assert_eq!(result, None);
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn delete_returns_true_once_and_false_when_repeated(pool: PgPool) {
+ let repo = PgForeignEntityRepo::new(pool);
+ let entity = insert_foreign_entity(&repo, "external-entity-1", "linear").await;
+
+ let first_delete = repo
+ .delete_foreign_entity(entity.id)
+ .await
+ .expect("first delete should succeed");
+ let second_delete = repo
+ .delete_foreign_entity(entity.id)
+ .await
+ .expect("second delete should succeed");
+ let fetched = repo
+ .get_foreign_entity_by_id(entity.id)
+ .await
+ .expect("deleted foreign entity lookup should succeed");
+
+ assert!(first_delete);
+ assert!(!second_delete);
+ assert_eq!(fetched, None);
+}
diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfile
index 4cb95eed5d..8e0addfcf1 100644
--- a/rust/cloud-storage/justfile
+++ b/rust/cloud-storage/justfile
@@ -85,6 +85,7 @@ setup_test_envs:
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./channels/.env
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./comms_service/.env
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./documents/.env
+ echo "DATABASE_URL={{ DATABASE_URL }}" >> ./foreign_entity/.env
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./stream/.env
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./macro_project_utils/.env
echo "DATABASE_URL={{ DATABASE_URL }}" >> ./entity_access/.env