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.

fix(contacts): contact syncing for both recipients and sender + frontend invalidations through cgw (#1216)

teo484824597e71
diff --git a/infra/stacks/contacts-service/index.ts b/infra/stacks/contacts-service/index.ts
index 326de80cc3..61435f0fe6 100644
--- a/infra/stacks/contacts-service/index.ts
+++ b/infra/stacks/contacts-service/index.ts
@@ -93,6 +93,10 @@ let containerEnvVars = [
name: 'MACRO_API_TOKEN_PUBLIC_KEY',
value: pulumi.interpolate`${MACRO_API_TOKENS.macroApiTokenPublicKey}`,
},
+ {
+ name: 'CONNECTION_GATEWAY_URL',
+ value: `https://connection-gateway${stack === 'prod' ? '' : `-${stack}`}.macro.com`,
+ },
];
const cloudStorageStack = new pulumi.StackReference('cloud-storage-stack', {
diff --git a/js/app/packages/core/user/contactService.ts b/js/app/packages/core/user/contactService.ts
index 3bfced6ec9..3310dea8c5 100644
--- a/js/app/packages/core/user/contactService.ts
+++ b/js/app/packages/core/user/contactService.ts
@@ -1,49 +1,2 @@
-import { ENABLE_CONTACTS } from '@core/constant/featureFlags';
-import type { IUser } from '@core/user';
-import { idToDisplayName, idToEmail } from '@core/user';
-import { isErr } from '@core/util/maybeResult';
-import { contactsClient } from '@service-contacts/client';
-import { createSingletonRoot } from '@solid-primitives/rootless';
-import { createMemo, createResource } from 'solid-js';
-
-async function getContacts() {
- if (!ENABLE_CONTACTS) {
- console.error('Contacts disabled, returning empty list');
- return [];
- }
-
- const result = await contactsClient.getContacts();
- if (isErr(result)) {
- console.error('Failed to get users', result);
- return [];
- }
- const [, data] = result;
- const { contacts } = data;
-
- return contacts;
-}
-
-const contactsResource = createSingletonRoot(() =>
- createResource(getContacts, {
- initialValue: [],
- })
-);
-
-export function useContacts() {
- const [resource] = contactsResource();
- return createMemo<IUser[]>(() => {
- const result = resource.latest;
- return result.map((c) => ({
- id: c,
- email: idToEmail(c),
- name: idToDisplayName(c),
- }));
- });
-}
-
-export async function refetchContacts(force = false) {
- const [resource, { refetch }] = contactsResource();
- if (force) return refetch();
- if (resource.loading) return resource.latest;
- return refetch();
-}
+// Re-export from TanStack Query-based implementation
+export { useContacts, invalidateContacts } from '@queries/contacts/contacts';
diff --git a/js/app/packages/core/util/channels.ts b/js/app/packages/core/util/channels.ts
index 4809815bde..7f4cf8a5d3 100644
--- a/js/app/packages/core/util/channels.ts
+++ b/js/app/packages/core/util/channels.ts
@@ -4,7 +4,7 @@ import { withAnalytics } from '@coparse/analytics';
import { TrackingEvents } from '@coparse/analytics/src/types/TrackingEvents';
import { invalidateListChannels } from '@queries/channel/channels';
import { toast } from '@core/component/Toast/Toast';
-import { refetchContacts } from '@core/user/contactService';
+import { invalidateContacts } from '@core/user/contactService';
import { isErr } from '@core/util/maybeResult';
import { commsServiceClient, type IdResponse } from '@service-comms/client';
import type {
@@ -65,7 +65,7 @@ export function useSendMessageToPeople() {
const messageResponse = message.at(1) as IdResponse;
invalidateListChannels();
- refetchContacts();
+ invalidateContacts();
const navigateToChannel = async () => {
replaceSplit({
diff --git a/js/app/packages/macro-entity/src/components/Provider.tsx b/js/app/packages/macro-entity/src/components/Provider.tsx
index 6ba58ff86f..cff10c646f 100644
--- a/js/app/packages/macro-entity/src/components/Provider.tsx
+++ b/js/app/packages/macro-entity/src/components/Provider.tsx
@@ -9,6 +9,7 @@ import { fetchApiToken } from '../queries/auth';
import { queryClient } from '../queries/client';
import { queryKeys } from '../queries/key';
import type { EntityData } from '../types/entity';
+import { QuerySyncProvider } from '@queries/sync/SyncProvider';
// NOTE: leaving this in as reference for now.
// Turning this off due to [M-5344]. This is likely unnecessary.
@@ -58,7 +59,7 @@ export function Provider(props: ParentProps) {
return (
<QueryClientProvider client={queryClient}>
- {props.children}
+ <QuerySyncProvider>{props.children}</QuerySyncProvider>
</QueryClientProvider>
);
}
diff --git a/js/app/packages/queries/contacts/contacts.ts b/js/app/packages/queries/contacts/contacts.ts
new file mode 100644
index 0000000000..9b00237ed0
--- /dev/null
+++ b/js/app/packages/queries/contacts/contacts.ts
@@ -0,0 +1,40 @@
+import type { IUser } from '@core/user/types';
+import { idToDisplayName, idToEmail } from '@core/user/util';
+import { throwOnErr } from '@core/util/maybeResult';
+import { contactsKeys } from './keys';
+import { contactsClient } from '@service-contacts/client';
+import { useQuery } from '@tanstack/solid-query';
+import { queryClient } from '@queries/client';
+import type { Accessor } from 'solid-js';
+
+function contactsQueryOptions() {
+ return {
+ queryKey: contactsKeys.all.queryKey,
+ queryFn: () => throwOnErr(() => contactsClient.getContacts()),
+ };
+}
+
+export function useContactsQuery() {
+ return useQuery(() => contactsQueryOptions());
+}
+
+/**
+ * Returns contacts as IUser objects.
+ * Compatible with the previous createResource-based implementation.
+ */
+export function useContacts(): Accessor<IUser[]> {
+ const query = useContactsQuery();
+ return () => {
+ if (!query.isSuccess) return [];
+ const contacts = query.data.contacts;
+ return contacts.map((c) => ({
+ id: c,
+ email: idToEmail(c),
+ name: idToDisplayName(c),
+ }));
+ };
+}
+
+export function invalidateContacts() {
+ return queryClient.invalidateQueries(contactsQueryOptions());
+}
diff --git a/js/app/packages/queries/contacts/keys.ts b/js/app/packages/queries/contacts/keys.ts
new file mode 100644
index 0000000000..be1a96757b
--- /dev/null
+++ b/js/app/packages/queries/contacts/keys.ts
@@ -0,0 +1,5 @@
+import { createQueryKeys } from '@lukemorales/query-key-factory';
+
+export const contactsKeys = createQueryKeys('contacts', {
+ all: null,
+});
diff --git a/js/app/packages/queries/sync/SyncProvider.tsx b/js/app/packages/queries/sync/SyncProvider.tsx
new file mode 100644
index 0000000000..2b7abec8a6
--- /dev/null
+++ b/js/app/packages/queries/sync/SyncProvider.tsx
@@ -0,0 +1,17 @@
+import { invalidateContacts } from '@queries/contacts/contacts';
+import { createConnectionWebsocketEffect } from '@service-connection/websocket';
+import type { ParentProps } from 'solid-js';
+import { match } from 'ts-pattern';
+
+// NOTE: This is a POC.
+// Needs to be fleshed out more. Also ideally the Provider from macto-entity should be
+// moved into the queries package first.
+export function QuerySyncProvider(props: ParentProps) {
+ createConnectionWebsocketEffect((data) => {
+ match(data).with({ type: 'contacts_invalidation' }, () => {
+ invalidateContacts();
+ });
+ });
+
+ return props.children;
+}
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 603266cbac..4761e7c362 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -2087,6 +2087,7 @@ dependencies = [
"aws-sdk-secretsmanager",
"aws-sdk-sqs",
"axum",
+ "connection_gateway",
"contacts_db_client",
"http-body-util",
"macro_auth",
diff --git a/rust/cloud-storage/connection_gateway/src/client/email.rs b/rust/cloud-storage/connection_gateway/src/client/email.rs
index 8a9a123305..71c9bafab1 100644
--- a/rust/cloud-storage/connection_gateway/src/client/email.rs
+++ b/rust/cloud-storage/connection_gateway/src/client/email.rs
@@ -17,4 +17,15 @@ impl ConnectionGatewayClient {
)
.await
}
+
+ #[tracing::instrument(skip(self), err)]
+ pub async fn invalidate_contacts(&self, user_id: &str) -> anyhow::Result<Vec<MessageReceipt>> {
+ self.send_message(
+ "user",
+ user_id,
+ "contacts_invalidation".to_string(),
+ json!({}),
+ )
+ .await
+ }
}
diff --git a/rust/cloud-storage/contacts_service/Cargo.toml b/rust/cloud-storage/contacts_service/Cargo.toml
index 1cd50bdce9..8bd0e0a140 100644
--- a/rust/cloud-storage/contacts_service/Cargo.toml
+++ b/rust/cloud-storage/contacts_service/Cargo.toml
@@ -20,6 +20,7 @@ aws-config = { workspace = true }
aws-sdk-secretsmanager = { workspace = true }
aws-sdk-sqs = { workspace = true }
axum = { workspace = true }
+connection_gateway = { path = "../connection_gateway" }
contacts_db_client = { path = "../contacts_db_client" }
http-body-util = { workspace = true }
macro_auth = { path = "../macro_auth" }
diff --git a/rust/cloud-storage/contacts_service/examples/worker.rs b/rust/cloud-storage/contacts_service/examples/worker.rs
index b1a6ec85a1..84528d63d1 100644
--- a/rust/cloud-storage/contacts_service/examples/worker.rs
+++ b/rust/cloud-storage/contacts_service/examples/worker.rs
@@ -31,7 +31,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
.await
.context("could not connect to db")?;
- let mut worker = MessageQueue::new(sqs, db);
+ let mut worker = MessageQueue::new(sqs, db, None);
worker.poll().await;
Ok(())
}
diff --git a/rust/cloud-storage/contacts_service/src/config.rs b/rust/cloud-storage/contacts_service/src/config.rs
index dd7997a53b..8565b7570c 100644
--- a/rust/cloud-storage/contacts_service/src/config.rs
+++ b/rust/cloud-storage/contacts_service/src/config.rs
@@ -14,6 +14,8 @@ pub struct Config {
pub queue_max_messages: i32,
/// The notification queue wait time seconds
pub queue_wait_time_seconds: i32,
+ /// Connection gateway URL for sending real-time notifications
+ pub connection_gateway_url: Option<String>,
}
impl Config {
@@ -39,6 +41,8 @@ impl Config {
.parse::<i32>()
.unwrap();
+ let connection_gateway_url = std::env::var("CONNECTION_GATEWAY_URL").ok();
+
let environment = Environment::new_or_prod();
Ok(Config {
@@ -48,6 +52,7 @@ impl Config {
queue_url,
queue_wait_time_seconds,
queue_max_messages,
+ connection_gateway_url,
})
}
@@ -60,6 +65,7 @@ impl Config {
queue_url: "".to_string(),
queue_max_messages: 0,
queue_wait_time_seconds: 0,
+ connection_gateway_url: None,
}
}
}
diff --git a/rust/cloud-storage/contacts_service/src/main.rs b/rust/cloud-storage/contacts_service/src/main.rs
index beca562752..0bb1f7d763 100644
--- a/rust/cloud-storage/contacts_service/src/main.rs
+++ b/rust/cloud-storage/contacts_service/src/main.rs
@@ -7,6 +7,7 @@ use std::sync::Arc;
use anyhow::Context;
use config::{Config, Environment};
+use connection_gateway_client::client::ConnectionGatewayClient;
use contacts_service::queue::MessageQueue;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_entrypoint::MacroEntrypoint;
@@ -70,7 +71,6 @@ async fn main() -> anyhow::Result<()> {
let db = connect_to_database(&config).await?;
let db_clone = db.clone();
let sqs_worker = create_sqs_worker(&config).await;
- let mut worker = MessageQueue::new(sqs_worker, db_clone);
let secretsmanager_client =
secretsmanager_client::SecretsManager::new(aws_sdk_secretsmanager::Client::new(
@@ -84,6 +84,12 @@ async fn main() -> anyhow::Result<()> {
.get_maybe_secret_value(config.environment, InternalApiSecretKey::new()?)
.await?;
+ let connection_gateway_client = config.connection_gateway_url.as_ref().map(|url| {
+ ConnectionGatewayClient::new(internal_api_secret.as_ref().to_string(), url.clone())
+ });
+
+ let mut worker = MessageQueue::new(sqs_worker, db_clone, connection_gateway_client);
+
tokio::spawn(async move {
worker.poll().await;
});
diff --git a/rust/cloud-storage/contacts_service/src/queue.rs b/rust/cloud-storage/contacts_service/src/queue.rs
index 50f8205b59..b83fd492db 100644
--- a/rust/cloud-storage/contacts_service/src/queue.rs
+++ b/rust/cloud-storage/contacts_service/src/queue.rs
@@ -2,6 +2,7 @@ use crate::user::{
Connection, Group, UserVertex, create_connections_message, create_user, unpack_connections,
unpack_users,
};
+use connection_gateway_client::client::ConnectionGatewayClient;
use contacts_db_client::create_connections;
use model::contacts::{
AddParticipantsMessageBody, ConnectionsMessage, CreateGroupMessageBody, Message,
@@ -45,10 +46,32 @@ pub async fn create_group(body: &CreateGroupMessageBody) -> Vec<(String, String)
.collect()
}
-#[derive(Debug)]
pub struct MessageQueue {
sqs: SQSWorker,
db: Pool<Postgres>,
+ connection_gateway_client: Option<ConnectionGatewayClient>,
+}
+
+/// Notify all affected users that their contacts have been updated
+async fn invalidate_contacts_for_users(
+ client: &Option<ConnectionGatewayClient>,
+ connection_pairs: &[(String, String)],
+) {
+ let Some(client) = client else {
+ return;
+ };
+
+ let mut user_ids: HashSet<&str> = HashSet::new();
+ for (user1, user2) in connection_pairs {
+ user_ids.insert(user1);
+ user_ids.insert(user2);
+ }
+
+ for user_id in user_ids {
+ if let Err(e) = client.invalidate_contacts(user_id).await {
+ tracing::error!(user_id = %user_id, error = ?e, "Failed to invalidate contacts");
+ }
+ }
}
async fn connections_message_handler(conmsg: &ConnectionsMessage, queue: &MessageQueue) {
@@ -62,7 +85,7 @@ async fn connections_message_handler(conmsg: &ConnectionsMessage, queue: &Messag
.into_iter()
.map(|e| (e.a.data.id.to_string(), e.b.data.id.to_string()))
.collect();
- let _ = create_connections(&mut transaction, connection_pairs)
+ let _ = create_connections(&mut transaction, connection_pairs.clone())
.await
.inspect_err(|e| {
tracing::error!("couldn't create connections: {:?}", e);
@@ -70,6 +93,8 @@ async fn connections_message_handler(conmsg: &ConnectionsMessage, queue: &Messag
let _ = transaction.commit().await.inspect_err(|e| {
tracing::error!("transaction error: {:?}", e);
});
+
+ invalidate_contacts_for_users(&queue.connection_gateway_client, &connection_pairs).await;
}
#[instrument(level = "info", skip(queue))]
@@ -78,7 +103,7 @@ async fn add_participants_handler(body: &AddParticipantsMessageBody, queue: &Mes
let db = &queue.db;
let connection_pairs = add_participants(body).await;
let mut transaction = db.begin().await.unwrap();
- let _ = create_connections(&mut transaction, connection_pairs)
+ let _ = create_connections(&mut transaction, connection_pairs.clone())
.await
.inspect_err(|e| {
tracing::error!("couldn't create connections: {:?}", e);
@@ -86,6 +111,9 @@ async fn add_participants_handler(body: &AddParticipantsMessageBody, queue: &Mes
let _ = transaction.commit().await.inspect_err(|e| {
tracing::error!("transaction error: {:?}", e);
});
+
+ // Notify affected users
+ invalidate_contacts_for_users(&queue.connection_gateway_client, &connection_pairs).await;
}
#[instrument(level = "info", skip(queue))]
@@ -94,7 +122,7 @@ async fn create_group_handler(body: &CreateGroupMessageBody, queue: &MessageQueu
let db = &queue.db;
let connection_pairs = create_group(body).await;
let mut transaction = db.begin().await.unwrap();
- let _ = create_connections(&mut transaction, connection_pairs)
+ let _ = create_connections(&mut transaction, connection_pairs.clone())
.await
.inspect_err(|e| {
tracing::error!("couldn't create connections: {:?}", e);
@@ -102,6 +130,9 @@ async fn create_group_handler(body: &CreateGroupMessageBody, queue: &MessageQueu
let _ = transaction.commit().await.inspect_err(|e| {
tracing::error!("transaction error: {:?}", e);
});
+
+ // Notify affected users
+ invalidate_contacts_for_users(&queue.connection_gateway_client, &connection_pairs).await;
}
#[cfg(test)]
@@ -135,8 +166,16 @@ pub async fn process(msg: &Message, queue: &MessageQueue) -> anyhow::Result<()>
#[allow(dead_code)]
impl MessageQueue {
- pub fn new(sqs: SQSWorker, db: Pool<Postgres>) -> MessageQueue {
- MessageQueue { sqs, db }
+ pub fn new(
+ sqs: SQSWorker,
+ db: Pool<Postgres>,
+ connection_gateway_client: Option<ConnectionGatewayClient>,
+ ) -> MessageQueue {
+ MessageQueue {
+ sqs,
+ db,
+ connection_gateway_client,
+ }
}
#[instrument(level = "info", skip(self))]
@@ -342,7 +381,7 @@ mod tests {
let message: Message = message_from_json(input_json).unwrap();
let db = pool.clone();
let sqs = sqs_dummy().await;
- let queue = MessageQueue::new(sqs, db);
+ let queue = MessageQueue::new(sqs, db, None);
match message {
Message::AddConnection(con) => connections_message_handler(&con, &queue).await,
_ => panic!("Message not matched properly"),
@@ -405,7 +444,7 @@ mod tests {
let message: Message = Message::AddParticipants(body);
let db = pool.clone();
let sqs = sqs_dummy().await;
- let queue = MessageQueue::new(sqs, db);
+ let queue = MessageQueue::new(sqs, db, None);
match message {
Message::AddParticipants(body) => add_participants_handler(&body, &queue).await,
_ => panic!("Message not matched properly"),
@@ -494,7 +533,7 @@ mod tests {
let message: Message = Message::CreateGroup(body);
let db = pool.clone();
let sqs = sqs_dummy().await;
- let queue = MessageQueue::new(sqs, db);
+ let queue = MessageQueue::new(sqs, db, None);
match message {
Message::CreateGroup(body) => create_group_handler(&body, &queue).await,
_ => panic!("Message not matched properly"),
diff --git a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs
index f50634bc9f..555d823bb9 100644
--- a/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs
+++ b/rust/cloud-storage/email_service/src/pubsub/inbox_sync/operations/upsert_message.rs
@@ -77,6 +77,12 @@ pub async fn upsert_message(
let is_sent = message.is_sent;
+ let sender_email = message
+ .from
+ .as_ref()
+ .map(|from| from.email.clone())
+ .filter(|e| !email_utils::is_generic_email(e));
+
// deduped list of all non-generic emails the message was sent to
let recipient_emails = dedupe_emails(
message
@@ -174,8 +180,8 @@ pub async fn upsert_message(
ctx,
link,
&recipient_emails,
+ sender_email.as_deref(),
is_sent,
- &payload.provider_message_id,
)
.await?;
@@ -303,34 +309,42 @@ async fn handle_attachment_upload(
Ok(())
}
-#[tracing::instrument(skip(ctx, link, recipient_emails))]
+#[tracing::instrument(skip(ctx, link, recipient_emails, sender_email))]
async fn handle_contacts_sync(
ctx: &PubSubContext,
link: &link::Link,
recipient_emails: &[String],
+ sender_email: Option<&str>,
is_sent: bool,
- provider_message_id: &str,
) -> result::Result<(), ProcessingError> {
- // if the user sent the message, upsert contacts for its recipients in contacts-service.
- if cfg!(not(feature = "contacts_sync")) || !is_sent || recipient_emails.is_empty() {
+ if cfg!(not(feature = "contacts_sync")) {
return Ok(());
}
- // Create users list starting with the sender, then all recipients
+ // Determine which emails to create connections to based on message direction
+ let connection_emails: Vec<&str> = if is_sent {
+ recipient_emails.iter().map(String::as_str).collect()
+ } else {
+ sender_email.into_iter().collect()
+ };
+
+ if connection_emails.is_empty() {
+ return Ok(());
+ }
+
+ // Build users list: current user at index 0, connection targets after
let mut users = vec![link.macro_id.to_string()];
users.extend(
- recipient_emails
+ connection_emails
.iter()
- .map(|email| format!("macro|{}", email)),
+ .map(|email| format!("macro|{email}")),
);
- // Create connections from sender (index 0) to each recipient
- let connections = (1..users.len()).map(|i| (0, i)).collect::<Vec<_>>();
-
- let connections_message = ConnectionsMessage { users, connections };
+ // Create connections from current user (index 0) to each other user
+ let connections = (1..users.len()).map(|i| (0, i)).collect();
ctx.sqs_client
- .enqueue_contacts_add_connection(connections_message)
+ .enqueue_contacts_add_connection(ConnectionsMessage { users, connections })
.await
.map_err(|e| {
ProcessingError::NonRetryable(DetailedError {