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
seanaye/chore/split and move code (#1529)
Sean Aye06ed6a453953
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex a436925e4d..bdc930a447 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -1986,6 +1986,7 @@ dependencies = ["axum","chrono","cool_asserts",+ "cowlike","dashmap","ensure_exists","frecency",@@ -2212,6 +2213,10 @@ dependencies = ["memchr",]+[[package]]+name = "cowlike"+version = "0.1.0"+[[package]]name = "cpufeatures"version = "0.2.17"@@ -2771,6 +2776,7 @@ dependencies = ["comms_service","connection_gateway","cool_asserts",+ "cowlike","document_sub_type","documents","dynamodb_client",@@ -3666,6 +3672,7 @@ dependencies = ["anyhow","chrono","cool_asserts",+ "cowlike","filter_ast","item_filters","macro_db_migrator",@@ -3680,6 +3687,7 @@ dependencies = ["serde","serde_json","sqlx",+ "strum","thiserror 2.0.17","tokio","tower 0.5.2",@@ -5307,6 +5315,7 @@ dependencies = [name = "macro_user_id"version = "0.1.0"dependencies = [+ "cowlike","doppleganger","nom 8.0.0","serde",@@ -5619,6 +5628,7 @@ name = "model-entity"version = "0.1.0"dependencies = ["cool_asserts",+ "cowlike","serde","serde_json","strum",@@ -6018,6 +6028,7 @@ dependencies = ["aws-sdk-sqs","axum","chrono",+ "cowlike","either","hex","itertools 0.14.0",@@ -8556,6 +8567,7 @@ dependencies = ["chrono","comms","cool_asserts",+ "cowlike","document_sub_type","doppleganger","either",diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex 7d5dcf3bae..3fa343578a 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -17,6 +17,7 @@ members = ["contacts_db_client","contacts_service","convert_service",+ "cowlike","dataloss_prevention_handler","delete_chat_handler","delete_document_worker",diff --git a/rust/cloud-storage/connection_gateway/Cargo.toml b/rust/cloud-storage/connection_gateway/Cargo.tomlindex 174412ac3d..b2d5fb5ce6 100644--- a/rust/cloud-storage/connection_gateway/Cargo.toml+++ b/rust/cloud-storage/connection_gateway/Cargo.toml@@ -30,6 +30,7 @@ macro_aws_config = { path = "../macro_aws_config" }aws-sdk-secretsmanager = { workspace = true }axum = { workspace = true, features = ["macros", "tower-log", "ws"] }chrono = { workspace = true }+cowlike = { path = "../cowlike" }dashmap = { workspace = true }ensure_exists = { path = "../ensure_exists", features = ["dynamodb"] }frecency = { path = "../frecency", features = [diff --git a/rust/cloud-storage/connection_gateway/src/api/connection/messages.rs b/rust/cloud-storage/connection_gateway/src/api/connection/messages.rsindex a40486ed2e..f0763df8d2 100644--- a/rust/cloud-storage/connection_gateway/src/api/connection/messages.rs+++ b/rust/cloud-storage/connection_gateway/src/api/connection/messages.rs@@ -1,13 +1,15 @@use crate::{model::{- connection::ConnectionContext, message::OutgoingMessage, websocket::ToWebsocketMessage,+ connection::ConnectionContext,+ message::OutgoingMessage,+ tracking::{EntityConnectionExt, TrackingData},+ websocket::ToWebsocketMessage,},service::tracker,};use anyhow::{Context, Result};use axum::extract::ws::{Message, WebSocket};use futures::{StreamExt, stream::SplitStream};-use model_entity::TrackingData;use std::error::Error;use tokio::sync::mpsc::Sender;use tungstenite::error::{Error as TungsteniteError, ProtocolError};diff --git a/rust/cloud-storage/connection_gateway/src/api/connection/mod.rs b/rust/cloud-storage/connection_gateway/src/api/connection/mod.rsindex 6c9e6c2755..1569c0216f 100644--- a/rust/cloud-storage/connection_gateway/src/api/connection/mod.rs+++ b/rust/cloud-storage/connection_gateway/src/api/connection/mod.rs@@ -1,7 +1,9 @@use crate::{config::Config,context::{ApiContext, AppState},- model::{connection::ConnectionContext, message::OutgoingMessage},+ model::{+ connection::ConnectionContext, message::OutgoingMessage, tracking::EntityConnectionExt,+ },};use anyhow::Result;use axum::{diff --git a/rust/cloud-storage/connection_gateway/src/api/swagger.rs b/rust/cloud-storage/connection_gateway/src/api/swagger.rsindex a21ea9ac9b..81a9a2de29 100644--- a/rust/cloud-storage/connection_gateway/src/api/swagger.rs+++ b/rust/cloud-storage/connection_gateway/src/api/swagger.rs@@ -3,9 +3,10 @@ use super::message;use super::message::{BatchSendMessageBody, SendMessageBody, SendMessageResponse};use crate::model::connection::StoredConnectionEntity;use crate::model::sender::MessageReceipt;+use crate::model::tracking::TrackAction;use crate::model::websocket::{ToWebsocketMessage, TrackEntityMessage};use model::response::{GenericErrorResponse, StringIDResponse};-use model_entity::{Entity, EntityType, TrackAction};+use model_entity::{Entity, EntityType};use models_bulk_upload::UploadFolderStatusUpdate;use utoipa::OpenApi;diff --git a/rust/cloud-storage/connection_gateway/src/model/connection.rs b/rust/cloud-storage/connection_gateway/src/model/connection.rsindex bd8c602b44..863bb7beb1 100644--- a/rust/cloud-storage/connection_gateway/src/model/connection.rs+++ b/rust/cloud-storage/connection_gateway/src/model/connection.rs@@ -1,10 +1,11 @@use crate::{config::Config, context::ApiContext};use model::user::UserContext;-use model_entity::{EntityType, UserEntityConnection};+use model_entity::EntityType;use std::time::{SystemTime, UNIX_EPOCH};use utoipa::ToSchema;use super::message::OutgoingMessage;+use super::tracking::UserEntityConnection;use tokio::{sync::mpsc::Sender, task::AbortHandle};pub struct Connection {diff --git a/rust/cloud-storage/connection_gateway/src/model/mod.rs b/rust/cloud-storage/connection_gateway/src/model/mod.rsindex 7215a634d8..dc69b7d4ee 100644--- a/rust/cloud-storage/connection_gateway/src/model/mod.rs+++ b/rust/cloud-storage/connection_gateway/src/model/mod.rs@@ -2,4 +2,5 @@ pub mod connection;pub mod message;pub mod sender;pub mod stream;+pub mod tracking;pub mod websocket;diff --git a/rust/cloud-storage/connection_gateway/src/model/tracking.rs b/rust/cloud-storage/connection_gateway/src/model/tracking.rsnew file mode 100644index 0000000000..839bb6e436--- /dev/null+++ b/rust/cloud-storage/connection_gateway/src/model/tracking.rs@@ -0,0 +1,140 @@+//! Types for tracking entity connections and actions++use cowlike::CowLike;+use model_entity::Entity;+use serde::{Deserialize, Serialize};+use std::borrow::Cow;+use strum::{Display, EnumString, IntoStaticStr};+use utoipa::ToSchema;++/// Uniquely describes a connection to an [Entity]+#[non_exhaustive]+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]+pub struct EntityConnection<'a> {+ /// the [Entity] we are connected to with this connection+ #[serde(flatten)]+ pub extra: Entity<'a>,+ /// the id of this connection+ pub connection_id: Cow<'a, str>,+}++impl<'a> EntityConnection<'a> {+ /// provide a user id string slice to upgrade this type into a [UserEntityConnection]+ pub fn with_user_str(self, user_id: &'a str) -> UserEntityConnection<'a> {+ UserEntityConnection {+ user_id: Cow::Borrowed(user_id),+ extra: self,+ }+ }+ /// provides a user id string to upgrade this type into a [UserEntityConnection]+ pub fn with_user_string(self, user_id: String) -> UserEntityConnection<'a> {+ UserEntityConnection {+ user_id: Cow::Owned(user_id),+ extra: self,+ }+ }+}++/// Uniquely describes a user and their connection id to an [Entity]+#[non_exhaustive]+#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]+pub struct UserEntityConnection<'a> {+ /// The user id of the connection we are describing+ pub user_id: Cow<'a, str>,+ /// the [EntityConnection]+ #[serde(flatten)]+ pub extra: EntityConnection<'a>,+}++/// The type of action that can occur on an [Entity]+#[derive(+ Serialize, Deserialize, Debug, ToSchema, Clone, Copy, Display, IntoStaticStr, EnumString,+)]+#[serde(rename_all = "snake_case")]+#[strum(serialize_all = "snake_case")]+pub enum TrackAction {+ /// the [Entity] was opened+ Open,+ /// the [Entity] was pinged+ Ping,+ /// the [Entity] was closed+ Close,+}++/// The data that describes an action a user has taken on a document+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct TrackingData<'a> {+ /// the [UserEntityConnection] where the event occurred+ pub entity: UserEntityConnection<'a>,+ /// the event that occurred+ pub action: TrackAction,+}++/// Extension trait to add connection builder methods to [Entity]+pub trait EntityConnectionExt<'a> {+ /// provide a connection_id string slice to upgrade this type into an [EntityConnection]+ fn with_connection_str(self, connection_id: &'a str) -> EntityConnection<'a>;+}++impl<'a> EntityConnectionExt<'a> for Entity<'a> {+ fn with_connection_str(self, connection_id: &'a str) -> EntityConnection<'a> {+ EntityConnection {+ extra: self,+ connection_id: Cow::Borrowed(connection_id),+ }+ }+}++impl<'a> CowLike<'a> for EntityConnection<'a> {+ type Owned<'b> = EntityConnection<'b>;++ fn into_owned(self) -> EntityConnection<'static> {+ EntityConnection {+ extra: self.extra.into_owned(),+ connection_id: Cow::Owned(self.connection_id.into_owned()),+ }+ }++ fn copied(&'a self) -> Self {+ EntityConnection {+ extra: self.extra.copied(),+ connection_id: Cow::Borrowed(&self.connection_id),+ }+ }+}++impl<'a> CowLike<'a> for UserEntityConnection<'a> {+ type Owned<'b> = UserEntityConnection<'b>;++ fn into_owned(self) -> UserEntityConnection<'static> {+ UserEntityConnection {+ user_id: Cow::Owned(self.user_id.into_owned()),+ extra: self.extra.into_owned(),+ }+ }++ fn copied(&'a self) -> Self {+ UserEntityConnection {+ user_id: Cow::Borrowed(&self.user_id),+ extra: self.extra.copied(),+ }+ }+}++impl<'a> CowLike<'a> for TrackingData<'a> {+ type Owned<'b> = TrackingData<'b>;++ fn into_owned(self) -> TrackingData<'static> {+ TrackingData {+ entity: self.entity.into_owned(),+ action: self.action,+ }+ }++ fn copied(&'a self) -> Self {+ TrackingData {+ entity: self.entity.copied(),+ action: self.action,+ }+ }+}diff --git a/rust/cloud-storage/connection_gateway/src/model/websocket.rs b/rust/cloud-storage/connection_gateway/src/model/websocket.rsindex cb04283149..7aa3d573e4 100644--- a/rust/cloud-storage/connection_gateway/src/model/websocket.rs+++ b/rust/cloud-storage/connection_gateway/src/model/websocket.rs@@ -1,4 +1,5 @@-use model_entity::{Entity, TrackAction};+use super::tracking::TrackAction;+use model_entity::Entity;use utoipa::ToSchema;#[cfg(test)]diff --git a/rust/cloud-storage/connection_gateway/src/model/websocket/tests.rs b/rust/cloud-storage/connection_gateway/src/model/websocket/tests.rsindex c792dd2d8a..be37a2ef2e 100644--- a/rust/cloud-storage/connection_gateway/src/model/websocket/tests.rs+++ b/rust/cloud-storage/connection_gateway/src/model/websocket/tests.rs@@ -1,7 +1,8 @@use cool_asserts::assert_matches;-use model_entity::{Entity, EntityType, TrackAction};+use model_entity::{Entity, EntityType};use serde_json::{Value, json};+use crate::model::tracking::TrackAction;use crate::model::websocket::{ToWebsocketMessage, TrackEntityMessage};fn get_json() -> Value {diff --git a/rust/cloud-storage/connection_gateway/src/service/connection.rs b/rust/cloud-storage/connection_gateway/src/service/connection.rsindex 446f232bc8..1e54166733 100644--- a/rust/cloud-storage/connection_gateway/src/service/connection.rs+++ b/rust/cloud-storage/connection_gateway/src/service/connection.rs@@ -1,11 +1,12 @@use crate::model::{connection::{Connection, StoredConnectionEntity},message::{Message, OutgoingMessage},+ tracking::{EntityConnection, UserEntityConnection},};use anyhow::Result;use axum::async_trait;use dashmap::DashMap;-use model_entity::{Entity, EntityConnection, UserEntityConnection};+use model_entity::Entity;use std::{sync::{Arc, atomic::AtomicUsize},time::{SystemTime, UNIX_EPOCH},diff --git a/rust/cloud-storage/connection_gateway/src/service/dynamodb.rs b/rust/cloud-storage/connection_gateway/src/service/dynamodb.rsindex fb3a348f4a..340c1fd19e 100644--- a/rust/cloud-storage/connection_gateway/src/service/dynamodb.rs+++ b/rust/cloud-storage/connection_gateway/src/service/dynamodb.rs@@ -1,4 +1,5 @@use crate::model::connection::StoredConnectionEntity;+use crate::model::tracking::{EntityConnection, UserEntityConnection};use crate::service::connection::{ConnectionGatewayPersistence, ConnectionManager};use anyhow::{Context, Result};use aws_sdk_dynamodb::error::ProvideErrorMetadata;@@ -7,7 +8,7 @@ use axum::async_trait;use ensure_exists::dynamodb::{CreateTableErr, DefineTable, DynamoClientWrapper};use ensure_exists::{DoesExist, EnsureExists};use macro_env_var::env_var;-use model_entity::{Entity, EntityConnection, EntityType, UserEntityConnection};+use model_entity::{Entity, EntityType};use std::collections::HashMap;env_var! {diff --git a/rust/cloud-storage/connection_gateway/src/service/tracker.rs b/rust/cloud-storage/connection_gateway/src/service/tracker.rsindex bdde7404d7..15dcbec61c 100644--- a/rust/cloud-storage/connection_gateway/src/service/tracker.rs+++ b/rust/cloud-storage/connection_gateway/src/service/tracker.rs@@ -3,28 +3,49 @@ use crate::{model::{connection::ConnectionContext,message::{Message, OutgoingMessage},+ tracking::{TrackAction, TrackingData},},};use anyhow::Result;-use frecency::domain::{models::EventRecord, ports::EventIngestorService};+use frecency::domain::{+ models::{EventRecord, FrecencyAction, FrecencyEntity, FrecencyEvent},+ ports::EventIngestorService,+};use futures::StreamExt;use futures::TryFutureExt;use itertools::Itertools;-use model_entity::{Entity, EntityType, TrackAction, TrackingData};+use model_entity::{Entity, EntityType};use tokio::sync::mpsc::Sender;use tracing::Level;use super::sender::send_message_to_entity;+/// Convert TrackAction to FrecencyAction+fn to_frecency_action(action: TrackAction) -> FrecencyAction {+ match action {+ TrackAction::Open => FrecencyAction::Open,+ TrackAction::Ping => FrecencyAction::Ping,+ TrackAction::Close => FrecencyAction::Close,+ }+}+pub async fn track_entity(sender: &Sender<OutgoingMessage>,ctx: ConnectionContext<'_>,data: TrackingData<'_>,) -> Result<()> {+ // Convert TrackingData to FrecencyEvent for the frecency service+ let frecency_event = FrecencyEvent {+ entity: FrecencyEntity {+ user_id: data.entity.user_id.clone(),+ entity: data.entity.extra.extra.clone(),+ },+ action: to_frecency_action(data.action),+ };let fut = ctx.api_context.frecency_ingestor_service- .track_event(EventRecord::new(data.clone()));+ .track_event(EventRecord::new(frecency_event));match data.action {TrackAction::Open => {diff --git a/rust/cloud-storage/cowlike/Cargo.toml b/rust/cloud-storage/cowlike/Cargo.tomlnew file mode 100644index 0000000000..6dafdce7d2--- /dev/null+++ b/rust/cloud-storage/cowlike/Cargo.toml@@ -0,0 +1,7 @@+[package]+edition = "2024"+name = "cowlike"+publish = false+version = "0.1.0"++[dependencies]diff --git a/rust/cloud-storage/macro_user_id/src/cowlike.rs b/rust/cloud-storage/cowlike/src/lib.rssimilarity index 95%rename from rust/cloud-storage/macro_user_id/src/cowlike.rsrename to rust/cloud-storage/cowlike/src/lib.rsindex ac3a1f8566..09702254f5 100644--- a/rust/cloud-storage/macro_user_id/src/cowlike.rs+++ b/rust/cloud-storage/cowlike/src/lib.rs@@ -1,4 +1,6 @@-//! This module exposes the [CowLike] trait+#![deny(missing_docs)]+//! This crate exposes the [CowLike] trait+//! And the ArcCowStruse std::sync::Arc;diff --git a/rust/cloud-storage/document_storage_service/Cargo.toml b/rust/cloud-storage/document_storage_service/Cargo.tomlindex 7793343d86..a1eebce9f6 100644--- a/rust/cloud-storage/document_storage_service/Cargo.toml+++ b/rust/cloud-storage/document_storage_service/Cargo.toml@@ -31,6 +31,7 @@ location_check = [][dependencies]anyhow = { workspace = true }aws-sdk-dynamodb = { workspace = true }+cowlike = { path = "../cowlike" }aws-sdk-s3 = { workspace = true }aws-sdk-secretsmanager = { workspace = true }aws-sdk-sqs = { workspace = true }diff --git a/rust/cloud-storage/document_storage_service/src/api/items/soup.rs b/rust/cloud-storage/document_storage_service/src/api/items/soup.rsindex aea7c4aa15..d198f162ad 100644--- a/rust/cloud-storage/document_storage_service/src/api/items/soup.rs+++ b/rust/cloud-storage/document_storage_service/src/api/items/soup.rs@@ -12,12 +12,12 @@ use frecency::domain::models::JoinFrecency;use frecency::domain::ports::FrecencyQueryService;use frecency::domain::services::FrecencyQueryServiceImpl;use frecency::outbound::postgres::FrecencyPgStorage;-use macro_user_id::cowlike::CowLike;+use cowlike::CowLike;+use macro_user_id::cowlike::CowLike as _;use macro_user_id::user_id::MacroUserIdStr;use model::response::ErrorResponse;use model::response::GenericErrorResponse;use model::user::UserContext;-use model_entity::as_owned::ShallowClone;use models_pagination::CursorExtractor;use models_pagination::CursorVal;use models_pagination::CursorWithVal;@@ -209,7 +209,7 @@ where}).await?;- let entities: Vec<_> = res.ids().map(|f| f.entity.shallow_clone()).collect();+ let entities: Vec<_> = res.ids().map(|f| f.entity.copied()).collect();let res: Vec<_> = self.soup_storagediff --git a/rust/cloud-storage/frecency/Cargo.toml b/rust/cloud-storage/frecency/Cargo.tomlindex 0c2db0b7c9..3789ace601 100644--- a/rust/cloud-storage/frecency/Cargo.toml+++ b/rust/cloud-storage/frecency/Cargo.toml@@ -15,6 +15,7 @@ postgres = ["dep:recursion", "dep:serde_json", "dep:sqlx"][dependencies]anyhow = { workspace = true }chrono = { workspace = true, features = ["serde"] }+cowlike = { path = "../cowlike" }filter_ast = { path = "../filter_ast" }item_filters = { path = "../item_filters" }macro_env_var = { path = "../macro_env_var", optional = true }@@ -25,6 +26,7 @@ num-traits = { version = "0.2" }ordered-float = { workspace = true }recursion = { workspace = true, optional = true }serde = { workspace = true }+strum = { workspace = true, features = ["derive"] }serde_json = { workspace = true, optional = true }sqlx = { workspace = true, optional = true }thiserror = { workspace = true }@@ -34,6 +36,7 @@ tracing = { workspace = true, optional = true }[dev-dependencies]cool_asserts = "2"+serde_json = { workspace = true }item_filters = { path = "../item_filters", features = ["mock"] }macro_db_migrator = { path = "../macro_db_migrator" }rand = { workspace = true }diff --git a/rust/cloud-storage/frecency/src/domain/models.rs b/rust/cloud-storage/frecency/src/domain/models.rsindex d118dbfed0..57a1fa8fce 100644--- a/rust/cloud-storage/frecency/src/domain/models.rs+++ b/rust/cloud-storage/frecency/src/domain/models.rs@@ -1,17 +1,50 @@//! This crate provides the utilities to compute aggregate frecency scores from some input eventuse chrono::{DateTime, Utc};+use cowlike::CowLike;use item_filters::ast::EntityFilterAst;-use macro_user_id::{cowlike::CowLike, error::ParseErr, user_id::MacroUserIdStr};-use model_entity::{- Entity, TrackAction, TrackingData,- as_owned::{IntoOwned, ShallowClone},-};+use macro_user_id::{error::ParseErr, user_id::MacroUserIdStr};+use model_entity::Entity;use num_traits::ToPrimitive;use ordered_float::OrderedFloat;use serde::{Deserialize, Serialize};+use std::borrow::Cow;use std::collections::{HashMap, VecDeque};+use strum::{Display, EnumString, IntoStaticStr};use thiserror::Error;+/// Action types for frecency weight calculation+#[derive(Debug, Clone, Copy, Display, EnumString, IntoStaticStr, Serialize, Deserialize)]+#[strum(serialize_all = "snake_case")]+#[serde(rename_all = "snake_case")]+pub enum FrecencyAction {+ /// the entity was opened+ Open,+ /// the entity was pinged+ Ping,+ /// the entity was closed+ Close,+}++/// Entity reference with user for frecency tracking+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct FrecencyEntity<'a> {+ /// The user id that triggered this event+ pub user_id: Cow<'a, str>,+ /// the entity being tracked+ #[serde(flatten)]+ pub entity: Entity<'a>,+ // connection_id is intentionally omitted - serde will ignore it during deserialization+}++/// Event data for frecency tracking (replaces TrackingData)+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct FrecencyEvent<'a> {+ /// the entity and user context for this event+ pub entity: FrecencyEntity<'a>,+ /// the action that occurred+ pub action: FrecencyAction,+}+#[cfg(test)]mod tests;@@ -20,7 +53,7 @@ mod tests;#[non_exhaustive]pub struct EventRecord<'a> {/// the entity on which the event occured + the user that triggered it- pub event: TrackingData<'a>,+ pub event: FrecencyEvent<'a>,/// the timestamp of the eventpub timestamp: chrono::DateTime<Utc>,}@@ -38,15 +71,15 @@ pub struct EventRecordWithId<'a, T> {}impl EventRecord<'_> {- /// grants a caller read only access to the [TrackingData]- pub fn event(&self) -> &TrackingData<'_> {+ /// grants a caller read only access to the [FrecencyEvent]+ pub fn event(&self) -> &FrecencyEvent<'_> {&self.event}}impl<'a> EventRecord<'a> {/// create a new [EventRecord] using the current UTC time as the timestamp- pub fn new(event: TrackingData<'a>) -> Self {+ pub fn new(event: FrecencyEvent<'a>) -> Self {EventRecord {event,timestamp: Utc::now(),@@ -76,7 +109,7 @@ impl<'a> AggregateId<'a> {pub(crate) fn from_event_record<T>(r: &'a EventRecordWithId<'a, T>) -> Result<Self, ParseErr> {Ok(AggregateId {user_id: MacroUserIdStr::parse_from_str(r.event_record.event.entity.user_id.as_ref())?,- entity: r.event_record.event.entity.extra.extra.shallow_clone(),+ entity: r.event_record.event.entity.entity.copied(),})}@@ -151,12 +184,12 @@ trait WeightForAction {fn get_weight(&self) -> f64;}-impl WeightForAction for TrackAction {+impl WeightForAction for FrecencyAction {fn get_weight(&self) -> f64 {match self {- TrackAction::Open => 2.0,- TrackAction::Ping => 0.0,- TrackAction::Close => -1.0,+ FrecencyAction::Open => 2.0,+ FrecencyAction::Ping => 0.0,+ FrecencyAction::Close => -1.0,}}}@@ -171,7 +204,7 @@ const RECENCY_DECAY_RATE: f64 = 0.1;const FREQUENCY_PERCENT: f64 = 0.7;impl AggregateFrecency {- /// Create a new inital record from a given [TrackingData] event+ /// Create a new inital record from a given [FrecencyEvent] event/// This should only be called if there is not yet an aggregate record for/// this user/this entitypub fn new_from_initial_action(@@ -181,7 +214,7 @@ impl AggregateFrecency {let mut out = Self {id: AggregateId {user_id: MacroUserIdStr::parse_from_str(&event.event.entity.user_id)?.into_owned(),- entity: event.event.entity.extra.extra.into_owned(),+ entity: event.event.entity.entity.into_owned(),},data: FrecencyData {event_count: 0,@@ -210,7 +243,7 @@ impl AggregateFrecency {let mut out = Self {id: AggregateId {user_id,- entity: event.event.entity.extra.extra.into_owned(),+ entity: event.event.entity.entity.into_owned(),},data: FrecencyData {event_count: 0,diff --git a/rust/cloud-storage/frecency/src/domain/models/tests.rs b/rust/cloud-storage/frecency/src/domain/models/tests.rsindex 1d007ac225..9a1cd1c7be 100644--- a/rust/cloud-storage/frecency/src/domain/models/tests.rs+++ b/rust/cloud-storage/frecency/src/domain/models/tests.rs@@ -1,18 +1,20 @@use crate::domain::models::{- AggregateFrecency, AggregateId, EventRecord, FrecencyData, MAX_RECENT_EVENTS, TimestampWeight,+ AggregateFrecency, AggregateId, EventRecord, FrecencyAction, FrecencyData, FrecencyEntity,+ FrecencyEvent, MAX_RECENT_EVENTS, TimestampWeight,};use chrono::DateTime;use cool_asserts::assert_matches;-use model_entity::{Entity, EntityType, TrackAction, TrackingData};+use model_entity::{Entity, EntityType};+use std::borrow::Cow;fn create_event() -> EventRecord<'static> {EventRecord {- event: TrackingData {- entity: EntityType::Document- .with_entity_str("my_document_id")- .with_connection_str("my_connection")- .with_user_str("macro|[email protected]"),- action: TrackAction::Open,+ event: FrecencyEvent {+ entity: FrecencyEntity {+ user_id: Cow::Borrowed("macro|[email protected]"),+ entity: EntityType::Document.with_entity_str("my_document_id"),+ },+ action: FrecencyAction::Open,},timestamp: DateTime::UNIX_EPOCH,}@@ -62,3 +64,53 @@ fn it_trims_above_max_events() {assert_eq!(event_count, create_events + 1); // plus 1 for the initial event})}++#[test]+fn old_tracking_data_deserializes_to_frecency_event() {+ // Old TrackingData format: {"entity": {...nested UserEntityConnection...}, "action": "..."}+ let old_json = serde_json::json!({+ "entity": {+ "user_id": "macro|[email protected]",+ "entity_type": "document",+ "entity_id": "doc-123",+ "connection_id": "conn-456" // This field will be ignored+ },+ "action": "open"+ });++ // Should deserialize successfully, ignoring connection_id+ let event: FrecencyEvent<'static> = serde_json::from_value(old_json).unwrap();+ assert_eq!(event.entity.user_id, "macro|[email protected]");+ assert_eq!(event.entity.entity.entity_type, EntityType::Document);+ assert_eq!(event.entity.entity.entity_id, "doc-123");+ assert!(matches!(event.action, FrecencyAction::Open));+}++#[test]+fn frecency_event_serializes_without_connection_id() {+ let event = FrecencyEvent {+ entity: FrecencyEntity {+ user_id: Cow::Borrowed("macro|[email protected]"),+ entity: EntityType::Document.with_entity_str("doc-123"),+ },+ action: FrecencyAction::Open,+ };++ let json = serde_json::to_value(&event).unwrap();++ // Should NOT have connection_id in the output+ assert!(json.get("entity").unwrap().get("connection_id").is_none());+ assert_eq!(+ json.get("entity").unwrap().get("user_id").unwrap(),+ "macro|[email protected]"+ );+ assert_eq!(+ json.get("entity").unwrap().get("entity_type").unwrap(),+ "document"+ );+ assert_eq!(+ json.get("entity").unwrap().get("entity_id").unwrap(),+ "doc-123"+ );+ assert_eq!(json.get("action").unwrap(), "open");+}diff --git a/rust/cloud-storage/frecency/src/outbound/postgres.rs b/rust/cloud-storage/frecency/src/outbound/postgres.rsindex 216446fa46..96a491074f 100644--- a/rust/cloud-storage/frecency/src/outbound/postgres.rs+++ b/rust/cloud-storage/frecency/src/outbound/postgres.rs@@ -1,15 +1,15 @@//! This module provides the implementation for storing frecency data in postgresuse crate::domain::{models::{- AggregateFrecency, AggregateId, EventRecord, EventRecordWithId, FrecencyData,- FrecencyPageRequest, TimestampWeight,+ AggregateFrecency, AggregateId, EventRecord, EventRecordWithId, FrecencyAction,+ FrecencyData, FrecencyEntity, FrecencyEvent, FrecencyPageRequest, TimestampWeight,},ports::{AggregateFrecencyStorage, EventRecordStorage, UnprocessedEventsRepo},};use chrono::{DateTime, Utc};use item_filters::ast::EntityFilterAst;use macro_user_id::{cowlike::CowLike, error::ParseErr, user_id::MacroUserIdStr};-use model_entity::{Entity, EntityType, TrackAction, TrackingData};+use model_entity::{Entity, EntityType};use sqlx::{PgPool, Postgres, QueryBuilder, Row, Transaction, prelude::FromRow};use std::{borrow::Cow, collections::VecDeque, str::FromStr};use thiserror::Error;@@ -119,13 +119,12 @@ impl<'a> EventRow<'a, ()> {EventRow {id: (),user_id: event.event.entity.user_id,- entity_type: Cow::Borrowed(<&'static str>::from(- event.event.entity.extra.extra.entity_type,- )),+ entity_type: Cow::Borrowed(<&'static str>::from(event.event.entity.entity.entity_type)),event_type: Cow::Borrowed(<&'static str>::from(event.event.action)),timestamp: event.timestamp,- connection_id: event.event.entity.extra.connection_id,- entity_id: event.event.entity.extra.extra.entity_id,+ // connection_id is no longer in FrecencyEvent, use empty string for backwards compatibility+ connection_id: Cow::Borrowed(""),+ entity_id: event.event.entity.entity.entity_id,was_processed: false,}}@@ -139,19 +138,20 @@ impl<'a> EventRow<'a, i64> {entity_type,event_type,timestamp,- connection_id,+ connection_id: _, // connection_id is no longer neededentity_id,was_processed: _,} = self;Ok(EventRecordWithId {event_record: EventRecord {- event: TrackingData {- entity: EntityType::from_str(&entity_type)?- .with_entity_string(entity_id.into_owned())- .with_connection_string(connection_id.into_owned())- .with_user_string(user_id.into_owned()),- action: TrackAction::from_str(&event_type)?,+ event: FrecencyEvent {+ entity: FrecencyEntity {+ user_id,+ entity: EntityType::from_str(&entity_type)?+ .with_entity_string(entity_id.into_owned()),+ },+ action: FrecencyAction::from_str(&event_type)?,},timestamp,},diff --git a/rust/cloud-storage/frecency/src/outbound/postgres/tests.rs b/rust/cloud-storage/frecency/src/outbound/postgres/tests.rsindex 9663770882..fd0994900a 100644--- a/rust/cloud-storage/frecency/src/outbound/postgres/tests.rs+++ b/rust/cloud-storage/frecency/src/outbound/postgres/tests.rs@@ -1,11 +1,13 @@-use crate::domain::models::{AggregateId, FrecencyData};+use crate::domain::models::{+ AggregateId, FrecencyAction, FrecencyData, FrecencyEntity, FrecencyEvent,+};use super::*;use chrono::Utc;use item_filters::ChatFilters;use macro_db_migrator::MACRO_DB_MIGRATIONS;use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};-use model_entity::{EntityType, TrackAction};+use model_entity::EntityType;use std::collections::VecDeque;#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]@@ -15,12 +17,12 @@ async fn test_set_event(pool: PgPool) {// Create a test event recordlet event = EventRecord {- event: TrackingData {- entity: EntityType::Document- .with_entity_str("doc123")- .with_connection_str("conn456")- .with_user_str(test_user_id),- action: TrackAction::Open,+ event: FrecencyEvent {+ entity: FrecencyEntity {+ user_id: Cow::Borrowed(test_user_id),+ entity: EntityType::Document.with_entity_str("doc123"),+ },+ action: FrecencyAction::Open,},timestamp: Utc::now(),};@@ -32,7 +34,7 @@ async fn test_set_event(pool: PgPool) {// Verify the event was insertedlet row = sqlx::query!(r#"- SELECT user_id, entity_type, event_type, entity_id, connection_id, was_processed+ SELECT user_id, entity_type, event_type, entity_id, was_processedFROM frecency_eventsWHERE user_id = $1 AND entity_id = $2"#,@@ -47,7 +49,6 @@ async fn test_set_event(pool: PgPool) {assert_eq!(row.entity_type, "document");assert_eq!(row.event_type, "open");assert_eq!(row.entity_id, "doc123");- assert_eq!(row.connection_id, "conn456");assert!(!row.was_processed);}@@ -485,8 +486,7 @@ async fn test_processor_get_unprocessed_events(pool: PgPool) {.event_record.event.entity- .extra- .extra+ .entity.entity_id.starts_with("doc_"));diff --git a/rust/cloud-storage/macro_user_id/Cargo.toml b/rust/cloud-storage/macro_user_id/Cargo.tomlindex f92945dda5..125fbeadd1 100644--- a/rust/cloud-storage/macro_user_id/Cargo.toml+++ b/rust/cloud-storage/macro_user_id/Cargo.toml@@ -5,6 +5,7 @@ publish = falseversion = "0.1.0"[dependencies]+cowlike = { path = "../cowlike" }doppleganger = { workspace = true }nom = { workspace = true }serde = { workspace = true }diff --git a/rust/cloud-storage/macro_user_id/src/lib.rs b/rust/cloud-storage/macro_user_id/src/lib.rsindex 9f4ee7d240..fb9e8c5937 100644--- a/rust/cloud-storage/macro_user_id/src/lib.rs+++ b/rust/cloud-storage/macro_user_id/src/lib.rs@@ -3,8 +3,9 @@//! This follows the newtype pattern and parse don't validate, where possiblepub(crate) mod byte_range;-pub mod cowlike;pub mod email;pub mod error;pub mod lowercased;pub mod user_id;++pub use cowlike;diff --git a/rust/cloud-storage/model-entity/Cargo.toml b/rust/cloud-storage/model-entity/Cargo.tomlindex 7451961340..f0fc1d9e45 100644--- a/rust/cloud-storage/model-entity/Cargo.toml+++ b/rust/cloud-storage/model-entity/Cargo.toml@@ -5,6 +5,7 @@ publish = falseversion = "0.1.0"[dependencies]+cowlike = { path = "../cowlike" }serde = { workspace = true, features = ["derive"] }strum = { workspace = true, features = ["derive"] }utoipa = { workspace = true }diff --git a/rust/cloud-storage/model-entity/src/as_owned.rs b/rust/cloud-storage/model-entity/src/as_owned.rsdeleted file mode 100644index dd1effd770..0000000000--- a/rust/cloud-storage/model-entity/src/as_owned.rs+++ /dev/null@@ -1,96 +0,0 @@-//! This module provides a utility trait for converting potentially borrowed lifetimes into static ones-use super::*;--/// Trait for creating a statically owned version of self-pub trait IntoOwned {- /// the output owned type- type Owned;- /// convert self into an owned version- fn into_owned(self) -> Self::Owned;-}--impl IntoOwned for Entity<'_> {- type Owned = Entity<'static>;- fn into_owned(self) -> Self::Owned {- Entity {- entity_type: self.entity_type,- entity_id: Cow::Owned(self.entity_id.into_owned()),- }- }-}--impl IntoOwned for EntityConnection<'_> {- type Owned = EntityConnection<'static>;-- fn into_owned(self) -> Self::Owned {- EntityConnection {- extra: self.extra.into_owned(),- connection_id: Cow::Owned(self.connection_id.into_owned()),- }- }-}--impl IntoOwned for UserEntityConnection<'_> {- type Owned = UserEntityConnection<'static>;-- fn into_owned(self) -> Self::Owned {- UserEntityConnection {- user_id: Cow::Owned(self.user_id.into_owned()),- extra: self.extra.into_owned(),- }- }-}--impl IntoOwned for TrackingData<'_> {- type Owned = TrackingData<'static>;-- fn into_owned(self) -> Self::Owned {- TrackingData {- entity: self.entity.into_owned(),- action: self.action,- }- }-}--/// A variant of [Clone] which always performs cheap shallow bitwise copies-/// This has the same performance characteristics as [Copy]-pub trait ShallowClone<'b> {- /// create a shallow clone- fn shallow_clone(&'b self) -> Self;-}--impl<'b> ShallowClone<'b> for Entity<'b> {- fn shallow_clone(&'b self) -> Self {- Entity {- entity_type: self.entity_type,- entity_id: Cow::Borrowed(&self.entity_id),- }- }-}--impl<'b> ShallowClone<'b> for EntityConnection<'b> {- fn shallow_clone(&'b self) -> Self {- EntityConnection {- extra: self.extra.shallow_clone(),- connection_id: Cow::Borrowed(&self.connection_id),- }- }-}--impl<'b> ShallowClone<'b> for UserEntityConnection<'b> {- fn shallow_clone(&'b self) -> Self {- UserEntityConnection {- user_id: Cow::Borrowed(&self.user_id),- extra: self.extra.shallow_clone(),- }- }-}--impl<'b> ShallowClone<'b> for TrackingData<'b> {- fn shallow_clone(&'b self) -> Self {- TrackingData {- entity: self.entity.shallow_clone(),- action: self.action,- }- }-}diff --git a/rust/cloud-storage/model-entity/src/lib.rs b/rust/cloud-storage/model-entity/src/lib.rsindex 1e2a73f57f..349afd0a23 100644--- a/rust/cloud-storage/model-entity/src/lib.rs+++ b/rust/cloud-storage/model-entity/src/lib.rs@@ -3,6 +3,7 @@//! Please avoid writing real business logic in this crate unless it is applicable specifically to only the//! types that exist inside this crate.+use cowlike::CowLike;use serde::{Deserialize, Serialize};use std::{borrow::Cow, str::FromStr};pub use strum::ParseError;@@ -12,8 +13,6 @@ use utoipa::ToSchema;#[cfg(test)]mod tests;-pub mod as_owned;-/// The type of an entity in Macro#[derive(Debug,@@ -90,90 +89,20 @@ pub struct Entity<'a> {pub entity_id: Cow<'a, str>,}-impl<'a> Entity<'a> {- /// provide a connection_id string slice to upgrade this type into a [ConnectionEntity]- pub fn with_connection_str(self, connection_id: &'a str) -> EntityConnection<'a> {- EntityConnection {- extra: self,- connection_id: Cow::Borrowed(connection_id),- }- }- /// provide a connection_id string to upgrade this type into a [ConnectionEntity]- pub fn with_connection_string(self, connection_id: String) -> EntityConnection<'a> {- EntityConnection {- extra: self,- connection_id: Cow::Owned(connection_id),- }- }-}+impl<'a> CowLike<'a> for Entity<'a> {+ type Owned<'b> = Entity<'b>;-/// Uniquely describes a connection to an [Entity]-#[non_exhaustive]-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]-pub struct EntityConnection<'a> {- /// the [Entity] we are connected to with this connection- #[serde(flatten)]- pub extra: Entity<'a>,- /// the id of this connection- pub connection_id: Cow<'a, str>,-}--impl<'a> EntityConnection<'a> {- /// provide a user id string slice to upgrade this type into a [NewConnectionEntity]- pub fn with_user_str(self, user_id: &'a str) -> UserEntityConnection<'a> {- UserEntityConnection {- user_id: Cow::Borrowed(user_id),- extra: self,+ fn into_owned(self) -> Entity<'static> {+ Entity {+ entity_type: self.entity_type,+ entity_id: Cow::Owned(self.entity_id.into_owned()),}}- /// provides a user id string to upgrade this type into a [NewConnectionEntity]- pub fn with_user_string(self, user_id: String) -> UserEntityConnection<'a> {- UserEntityConnection {- user_id: Cow::Owned(user_id),- extra: self,++ fn copied(&'a self) -> Self {+ Entity {+ entity_type: self.entity_type,+ entity_id: Cow::Borrowed(&self.entity_id),}}}--/// Uniquely describes a user and their connection id to an [Entity]-#[non_exhaustive]-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]-pub struct UserEntityConnection<'a> {- /// The user id of the connection we are describing- pub user_id: Cow<'a, str>,- /// the [ConnectionEntity]- #[serde(flatten)]- pub extra: EntityConnection<'a>,-}--/// The type of action that can occur on an [Entity]-#[derive(- serde::Serialize,- serde::Deserialize,- Debug,- ToSchema,- Clone,- Copy,- Display,- IntoStaticStr,- EnumString,-)]-#[serde(rename_all = "snake_case")]-#[strum(serialize_all = "snake_case")]-pub enum TrackAction {- /// the [Entity] was opened- Open,- /// the [Entity] was pinged- Ping,- /// the [Entity] was closed- Close,-}--/// The data that describes an action a user has taken on a document-#[derive(Debug, Clone, Serialize, Deserialize)]-pub struct TrackingData<'a> {- /// the [UserEntityConnection] where the event occurred- pub entity: UserEntityConnection<'a>,- /// the event that occurred- pub action: TrackAction,-}diff --git a/rust/cloud-storage/model-entity/src/tests.rs b/rust/cloud-storage/model-entity/src/tests.rsindex f71e54ef34..070541a687 100644--- a/rust/cloud-storage/model-entity/src/tests.rs+++ b/rust/cloud-storage/model-entity/src/tests.rs@@ -1,27 +1,8 @@-use crate::{EntityType, UserEntityConnection};-use serde_json::{Value, json};--fn get_json() -> Value {- json!({- "user_id": "myuser",- "connection_id": "my_connection_id",- "entity_id": "my_entity_id",- "entity_type": "document"- })-}--#[test]-fn it_should_deserialize_user_entity_connection() {- let obj = get_json();- let _res = serde_json::from_value::<UserEntityConnection<'static>>(obj).unwrap();-}+use crate::EntityType;#[test]-fn it_should_serialize_user_entity_connection() {- let conn = EntityType::Document- .with_entity_str("my_entity_id")- .with_connection_str("my_connection_id")- .with_user_str("myuser");-- assert_eq!(serde_json::to_value(&conn).unwrap(), get_json());+fn it_should_build_entity_from_type() {+ let entity = EntityType::Document.with_entity_str("my_entity_id");+ assert_eq!(entity.entity_id, "my_entity_id");+ assert_eq!(entity.entity_type, EntityType::Document);}diff --git a/rust/cloud-storage/notification/Cargo.toml b/rust/cloud-storage/notification/Cargo.tomlindex 02a79658d5..9aa2e5329c 100644--- a/rust/cloud-storage/notification/Cargo.toml+++ b/rust/cloud-storage/notification/Cargo.toml@@ -19,6 +19,7 @@ schema = ["dep:utoipa"][dependencies]aquamarine = { version = "0.6", optional = true }aws-sdk-sesv2 = { workspace = true }+cowlike = { path = "../cowlike" }aws-sdk-sns = { workspace = true }aws-sdk-sqs = { workspace = true }axum = { workspace = true, optional = true }diff --git a/rust/cloud-storage/notification/src/domain/models/queue_message.rs b/rust/cloud-storage/notification/src/domain/models/queue_message.rsindex f0b3a8ae40..69851eb3d7 100644--- a/rust/cloud-storage/notification/src/domain/models/queue_message.rs+++ b/rust/cloud-storage/notification/src/domain/models/queue_message.rs@@ -5,8 +5,9 @@ use crate::domain::models::{apple::APNSPushNotification, mobile::MessageAttributes,};use chrono::{DateTime, Utc};-use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};-use model_entity::{Entity, as_owned::IntoOwned};+use cowlike::CowLike;+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::Entity;use serde::{Deserialize, Serialize};use thiserror::Error;use uuid::Uuid;diff --git a/rust/cloud-storage/notification/src/domain/models/request.rs b/rust/cloud-storage/notification/src/domain/models/request.rsindex b77d9b8653..27f98223ee 100644--- a/rust/cloud-storage/notification/src/domain/models/request.rs+++ b/rust/cloud-storage/notification/src/domain/models/request.rs@@ -8,9 +8,10 @@ use crate::domain::{},service::SendNotificationError,};+use cowlike::CowLike;use itertools::Itertools;-use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};-use model_entity::{Entity, as_owned::IntoOwned};+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::Entity;use rootcause::{Report, report};use serde::{Deserialize, Serialize};use std::collections::HashSet;diff --git a/rust/cloud-storage/soup/Cargo.toml b/rust/cloud-storage/soup/Cargo.tomlindex dda3f3a27e..52c4823025 100644--- a/rust/cloud-storage/soup/Cargo.toml+++ b/rust/cloud-storage/soup/Cargo.toml@@ -43,6 +43,7 @@ ports = ["dep:tokio", "frecency/ports"][dependencies]ai = { path = "../ai", optional = true }anyhow = { workspace = true }+cowlike = { path = "../cowlike" }async-trait = { workspace = true, optional = true }axum = { workspace = true, optional = true }axum-extra = { workspace = true, optional = true }diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rsindex 8fd644fcff..a1b5b42965 100644--- a/rust/cloud-storage/soup/src/domain/service.rs+++ b/rust/cloud-storage/soup/src/domain/service.rs@@ -6,6 +6,7 @@ use crate::domain::{ports::{SoupOutput, SoupRepo, SoupService},};use comms::domain::{models::GetChannelsRequest, ports::ChannelsService};+use cowlike::CowLike;use doppleganger::Mirror;use either::Either;use email::domain::{@@ -17,8 +18,7 @@ use frecency::domain::{ports::FrecencyQueryService,};use item_filters::{EntityFilters, ast::EntityFilterAst};-use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};-use model_entity::as_owned::ShallowClone;+use macro_user_id::user_id::MacroUserIdStr;use models_pagination::{Cursor, CursorVal, Frecency, FrecencyValue, PaginateOn, Query, SimpleSortMethod,};@@ -226,7 +226,7 @@ where}).await?;- let entities: Vec<_> = res.ids().map(|f| f.entity.shallow_clone()).collect();+ let entities: Vec<_> = res.ids().map(|f| f.entity.copied()).collect();let res = self.handle_soup_by_ids(