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: connection hex crate (#1842)

Will Hutchinson82ec0497bda3
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index a66bbf1227..dc0c60784e 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2048,6 +2048,23 @@ dependencies = [
"crossbeam-utils",
]
+[[package]]
+name = "connection"
+version = "0.1.0"
+dependencies = [
+ "anyhow",
+ "chrono",
+ "connection_gateway_client",
+ "entity_access",
+ "macro_user_id",
+ "model-entity",
+ "serde",
+ "serde_json",
+ "thiserror 2.0.17",
+ "tracing",
+ "uuid",
+]
+
[[package]]
name = "connection_gateway"
version = "0.1.0"
@@ -3051,6 +3068,7 @@ dependencies = [
"base64 0.22.1",
"chrono",
"cloudfront_sign",
+ "connection",
"document_sub_type",
"dotenvy",
"entity_access",
diff --git a/rust/cloud-storage/connection/Cargo.toml b/rust/cloud-storage/connection/Cargo.toml
new file mode 100644
index 0000000000..f15902f30c
--- /dev/null
+++ b/rust/cloud-storage/connection/Cargo.toml
@@ -0,0 +1,26 @@
+[package]
+edition = "2024"
+name = "connection"
+publish = false
+version = "0.1.0"
+
+[features]
+default = ["outbound", "ports"]
+outbound = ["dep:connection_gateway_client", "dep:model-entity", "ports"]
+ports = ["entity_access/ports"]
+
+[dependencies]
+# Core
+anyhow = { workspace = true }
+chrono = { workspace = true }
+entity_access = { path = "../entity_access", default-features = false }
+macro_user_id = { path = "../macro_user_id" }
+serde = { workspace = true }
+serde_json = { workspace = true }
+thiserror = { workspace = true }
+tracing = { workspace = true }
+uuid = { workspace = true }
+
+# Outbound
+connection_gateway_client = { path = "../connection_gateway_client", optional = true }
+model-entity = { path = "../model-entity", optional = true }
diff --git a/rust/cloud-storage/connection/src/domain.rs b/rust/cloud-storage/connection/src/domain.rs
new file mode 100644
index 0000000000..a947d9653b
--- /dev/null
+++ b/rust/cloud-storage/connection/src/domain.rs
@@ -0,0 +1,9 @@
+//! Domain layer: models, ports (trait interfaces), and service implementation.
+
+pub mod models;
+
+#[cfg(feature = "ports")]
+pub mod ports;
+
+#[cfg(feature = "ports")]
+pub mod service;
diff --git a/rust/cloud-storage/connection/src/domain/models.rs b/rust/cloud-storage/connection/src/domain/models.rs
new file mode 100644
index 0000000000..5259f0a6ba
--- /dev/null
+++ b/rust/cloud-storage/connection/src/domain/models.rs
@@ -0,0 +1,43 @@
+//! Domain models for the connection crate.
+
+use std::borrow::Cow;
+
+use entity_access::domain::models::EntityType;
+use macro_user_id::user_id::MacroUserIdStr;
+
+/// The invalidation message type
+pub const INVALIDATION_MESSAGE_TYPE: &str = "invalidation";
+
+/// Errors that can occur during connection operations.
+#[derive(Debug, thiserror::Error)]
+pub enum ConnectionError {
+ /// An internal error occurred.
+ #[error("{0}")]
+ Internal(#[from] anyhow::Error),
+}
+
+/// Reason for an entity to be invalidated
+#[derive(Debug, serde::Serialize)]
+pub enum InvalidationReason {
+ /// The entity was deleted
+ Deleted,
+ /// The entities metadata was modified
+ Metadata,
+ /// The entities content was modified
+ Content,
+}
+
+/// An invalidation event
+#[derive(Debug, serde::Serialize)]
+pub struct InvalidationEvent<'a, T: std::fmt::Debug + serde::Serialize> {
+ /// The id of the entity to invalidate
+ pub entity_id: Cow<'a, str>,
+ /// The type of the entity to invalidate
+ pub entity_type: EntityType,
+ /// The reason for invalidation
+ pub invalidation_reason: InvalidationReason,
+ /// The user who created the invalidation
+ pub invalidated_by: MacroUserIdStr<'a>,
+ /// Any additional metadata
+ pub metadata: T,
+}
diff --git a/rust/cloud-storage/connection/src/domain/ports.rs b/rust/cloud-storage/connection/src/domain/ports.rs
new file mode 100644
index 0000000000..9bff03c90f
--- /dev/null
+++ b/rust/cloud-storage/connection/src/domain/ports.rs
@@ -0,0 +1,29 @@
+//! Port definitions for the connection domain.
+//!
+//! These traits define the contracts that adapters must implement.
+
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+
+use crate::domain::models::{ConnectionError, InvalidationEvent};
+
+/// Repository for handling github oauth related actions.
+pub trait ConnectionGateway: Send + Sync + 'static {
+ /// The error type returned by repository operations.
+ type Err: Into<anyhow::Error> + Send + std::fmt::Debug;
+
+ /// Bulk sends an invalidation event
+ fn bulk_send_invalidation_event<'a, T: std::fmt::Debug + serde::Serialize + Send>(
+ &self,
+ users: &[MacroUserId<Lowercase<'a>>],
+ invalidation_event: InvalidationEvent<'a, T>,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+}
+
+/// Service interface for connection operations
+pub trait ConnectionService: Send + Sync + 'static {
+ /// Sends an invalidation event
+ fn send_invalidation_event<'a, T: std::fmt::Debug + serde::Serialize + Send>(
+ &self,
+ invalidation_event: InvalidationEvent<'a, T>,
+ ) -> impl Future<Output = Result<(), ConnectionError>> + Send;
+}
diff --git a/rust/cloud-storage/connection/src/domain/service.rs b/rust/cloud-storage/connection/src/domain/service.rs
new file mode 100644
index 0000000000..7928912ba3
--- /dev/null
+++ b/rust/cloud-storage/connection/src/domain/service.rs
@@ -0,0 +1,73 @@
+//! Connection service implementation.
+
+use std::sync::Arc;
+
+use entity_access::domain::ports::EntityAccessService;
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+
+use crate::domain::{
+ models::{ConnectionError, InvalidationEvent},
+ ports::{ConnectionGateway, ConnectionService},
+};
+
+/// The connection service implementation
+pub struct ConnectionServiceImpl<E: EntityAccessService, Cgw: ConnectionGateway> {
+ /// The entity access service
+ entity_access_service: Arc<E>,
+ /// The connection gateway
+ connection_gateway: Arc<Cgw>,
+}
+
+impl<E: EntityAccessService, Cgw: ConnectionGateway> ConnectionServiceImpl<E, Cgw> {
+ /// Create new instance
+ pub fn new(entity_access_service: Arc<E>, connection_gateway: Arc<Cgw>) -> Self {
+ Self {
+ entity_access_service,
+ connection_gateway,
+ }
+ }
+}
+
+impl<E: EntityAccessService, Cgw: ConnectionGateway> ConnectionService
+ for ConnectionServiceImpl<E, Cgw>
+{
+ #[tracing::instrument(skip(self), err)]
+ async fn send_invalidation_event<'a, T: std::fmt::Debug + serde::Serialize + Send>(
+ &self,
+ invalidation_event: InvalidationEvent<'a, T>,
+ ) -> Result<(), ConnectionError> {
+ let users = self
+ .entity_access_service
+ .get_users_by_entity(
+ &invalidation_event.entity_id,
+ invalidation_event.entity_type,
+ )
+ .await
+ .map_err(|e| ConnectionError::Internal(e.into()))?;
+
+ // Filter out user who made the invalidation
+ let users = users
+ .into_iter()
+ .filter_map(|p| {
+ if p.as_ref() != invalidation_event.invalidated_by.as_ref() {
+ Some(p.0)
+ } else {
+ None
+ }
+ })
+ .collect::<Vec<MacroUserId<Lowercase<'a>>>>();
+
+ if users.is_empty() {
+ tracing::trace!("no users to send invalidation to");
+ return Ok(());
+ }
+
+ // send event to all users
+ self.connection_gateway
+ .bulk_send_invalidation_event(&users, invalidation_event)
+ .await
+ .map_err(|e| ConnectionError::Internal(e.into()))?;
+
+ Ok(())
+ }
+}
diff --git a/rust/cloud-storage/connection/src/lib.rs b/rust/cloud-storage/connection/src/lib.rs
new file mode 100644
index 0000000000..523b58b65f
--- /dev/null
+++ b/rust/cloud-storage/connection/src/lib.rs
@@ -0,0 +1,16 @@
+//! Connection hexagonal architecture crate.
+//!
+//! Encapsulates connection gateway operations using a ports-and-adapters pattern.
+//!
+//! # Architecture
+//!
+//! - **domain**: Contains domain models, ports (traits), and the service implementation
+//! - **outbound**: Contains adapters for external dependencies
+//! - **inbound**: Contains adapters for incoming requests (Axum handlers)
+
+#![deny(missing_docs)]
+
+pub mod domain;
+
+#[cfg(feature = "outbound")]
+pub mod outbound;
diff --git a/rust/cloud-storage/connection/src/outbound.rs b/rust/cloud-storage/connection/src/outbound.rs
new file mode 100644
index 0000000000..12176bf0ca
--- /dev/null
+++ b/rust/cloud-storage/connection/src/outbound.rs
@@ -0,0 +1,3 @@
+//! Outbound adapters for the connection domain.
+
+pub mod connection_gateway_client;
diff --git a/rust/cloud-storage/connection/src/outbound/connection_gateway_client.rs b/rust/cloud-storage/connection/src/outbound/connection_gateway_client.rs
new file mode 100644
index 0000000000..82a960487d
--- /dev/null
+++ b/rust/cloud-storage/connection/src/outbound/connection_gateway_client.rs
@@ -0,0 +1,50 @@
+//! Implementation of GW port using the ConnectionGatewayClient
+
+use connection_gateway_client::ConnectionGatewayClient;
+use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+
+use crate::domain::{
+ models::{INVALIDATION_MESSAGE_TYPE, InvalidationEvent},
+ ports::ConnectionGateway,
+};
+
+/// Implementation of the ConnectionGateway trait
+#[derive(Clone)]
+pub struct ConnectionGatewayImpl {
+ /// Inner connection gateway client
+ client: ConnectionGatewayClient,
+}
+
+impl ConnectionGatewayImpl {
+ /// Create a new ConnectionGatewayImpl
+ pub fn new(client: ConnectionGatewayClient) -> Self {
+ Self { client }
+ }
+}
+
+impl ConnectionGateway for ConnectionGatewayImpl {
+ type Err = anyhow::Error;
+
+ #[tracing::instrument(skip(self), err)]
+ async fn bulk_send_invalidation_event<'a, T: std::fmt::Debug + serde::Serialize + Send>(
+ &self,
+ users: &[MacroUserId<Lowercase<'a>>],
+ invalidation_event: InvalidationEvent<'a, T>,
+ ) -> Result<(), Self::Err> {
+ let message = serde_json::to_value(&invalidation_event)?;
+ let entities = users
+ .iter()
+ .map(|u| model_entity::EntityType::User.with_entity_str(u.as_ref()))
+ .collect();
+
+ // Transform the users to a list of connection gateway entities
+ let result = self
+ .client
+ .batch_send_message(INVALIDATION_MESSAGE_TYPE.to_string(), message, entities)
+ .await?;
+
+ tracing::trace!(result=?result, "batch send message");
+
+ Ok(())
+ }
+}
diff --git a/rust/cloud-storage/connection_gateway_client/src/client/mod.rs b/rust/cloud-storage/connection_gateway_client/src/client/mod.rs
index 236c58f930..8cf5a158f4 100644
--- a/rust/cloud-storage/connection_gateway_client/src/client/mod.rs
+++ b/rust/cloud-storage/connection_gateway_client/src/client/mod.rs
@@ -4,6 +4,7 @@ use connection_gateway_models::{
BatchSendMessageBody, BatchSendUniqueMessagesBody, MessageReceipt, SendMessageBody,
UniqueMessage,
};
+
use model_entity::Entity;
mod email;
diff --git a/rust/cloud-storage/documents/Cargo.toml b/rust/cloud-storage/documents/Cargo.toml
index dc5c68b149..79c0788bbc 100644
--- a/rust/cloud-storage/documents/Cargo.toml
+++ b/rust/cloud-storage/documents/Cargo.toml
@@ -5,29 +5,34 @@ publish = false
version = "0.1.0"
[features]
-default = ["ports", "inbound", "outbound", "axum", "ai_tools"]
-ports = ["dep:tokio"]
-inbound = ["axum", "ports"]
-outbound = ["ports", "dep:aws-sdk-s3", "dep:base64", "dep:hex"]
ai_tools = [
- "dep:ai",
- "dep:async-trait",
- "dep:schemars",
- "dep:lexical_client",
- "dep:model_file_type",
- "dep:reqwest",
- "dep:sha2",
- "ports",
- "outbound"
+ "dep:ai",
+ "dep:async-trait",
+ "dep:lexical_client",
+ "dep:model_file_type",
+ "dep:reqwest",
+ "dep:schemars",
+ "dep:sha2",
+ "outbound",
+ "ports",
]
axum = [
- "dep:axum",
- "dep:axum-extra",
- "dep:model_user",
- "dep:model-error-response",
- "dep:utoipa",
- "entity_access/axum",
+ "dep:axum",
+ "dep:axum-extra",
+ "dep:model-error-response",
+ "dep:model_user",
+ "dep:utoipa",
+ "entity_access/axum",
+]
+default = ["ai_tools", "axum", "inbound", "outbound", "ports"]
+inbound = ["axum", "ports"]
+outbound = [
+ "dep:aws-sdk-s3",
+ "dep:base64",
+ "dep:hex",
+ "ports",
]
+ports = ["dep:tokio"]
[dependencies]
# Core
@@ -40,13 +45,16 @@ tracing = { workspace = true }
uuid = { workspace = true }
# Domain models (always included)
+connection = { path = "../connection", default-features = false, features = [
+ "ports",
+] }
document_sub_type = { path = "../document_sub_type" }
entity_access = { path = "../entity_access" }
+macro_aws_config = { path = "../macro_aws_config", features = ["s3"] }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
model = { path = "../model" }
models_permissions = { path = "../models_permissions" }
-macro_aws_config = { path = "../macro_aws_config", features = ["s3"] }
# Async runtime (for ports)
tokio = { workspace = true, optional = true }
@@ -54,8 +62,8 @@ tokio = { workspace = true, optional = true }
# Axum dependencies (for inbound)
axum = { workspace = true, optional = true }
axum-extra = { workspace = true, optional = true }
-model_user = { path = "../model_user", optional = true, features = ["axum"] }
model-error-response = { path = "../model-error-response", optional = true }
+model_user = { path = "../model_user", optional = true, features = ["axum"] }
utoipa = { workspace = true, optional = true }
# Outbound dependencies
@@ -72,17 +80,17 @@ urlencoding = { workspace = true }
# AI Tool dependencies
ai = { path = "../ai", optional = true }
async-trait = { workspace = true, optional = true }
-schemars = { workspace = true, optional = true }
lexical_client = { path = "../lexical_client", optional = true }
model_file_type = { path = "../model_file_type", optional = true }
reqwest = { workspace = true, optional = true }
+schemars = { workspace = true, optional = true }
sha2 = { workspace = true, optional = true }
[dev-dependencies]
+dotenvy = { workspace = true }
http-body-util = { workspace = true }
macro_db_migrator = { path = "../macro_db_migrator" }
mockall = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
tower = { workspace = true }
-dotenvy = { workspace = true }