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
fix(contacts): read gateway responses and URL-encode user ids in invalidation calls (#7895)
teo58bdef86d62c
diff --git a/Cargo.lock b/Cargo.lockindex 0e85e7ecc9..847e64d6e2 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -4757,6 +4757,7 @@ dependencies = ["aws-sdk-sqs","axum","axum-extra",+ "futures","http-body-util","macro_authorization","macro_db_migrator",@@ -4771,6 +4772,7 @@ dependencies = ["tokio","tower 0.5.3","tracing",+ "urlencoding","utoipa","uuid","workspace-hack",diff --git a/crates/contacts/Cargo.toml b/crates/contacts/Cargo.tomlindex 9e96b27c72..ca53413386 100644--- a/crates/contacts/Cargo.toml+++ b/crates/contacts/Cargo.toml@@ -14,7 +14,13 @@ axum = []default = ["axum", "inbound", "outbound", "ports"]inbound = ["axum", "dep:aws-sdk-sqs", "dep:sqs_worker", "ports"]-outbound = ["dep:aws-sdk-sqs", "dep:reqwest", "dep:sqlx", "ports"]+outbound = [+ "dep:aws-sdk-sqs",+ "dep:reqwest",+ "dep:sqlx",+ "dep:urlencoding",+ "ports",+]ports = [][dependencies]@@ -34,11 +40,13 @@ sqlx = { workspace = true, optional = true }sqs_worker = { path = "../sqs_worker", optional = true }tokio = { workspace = true }tracing = { workspace = true }+urlencoding = { workspace = true, optional = true }utoipa = { workspace = true, optional = true }uuid = { workspace = true }workspace-hack = { version = "0.1", path = "../workspace-hack" }[dev-dependencies]+futures = { workspace = true }macro_db_migrator = { path = "../macro_db_migrator" }http-body-util = { workspace = true }rate_limit = { path = "../rate_limit", features = ["axum", "testing"] }diff --git a/crates/contacts/src/outbound/gateway.rs b/crates/contacts/src/outbound/gateway.rsindex d98920a922..211d545da9 100644--- a/crates/contacts/src/outbound/gateway.rs+++ b/crates/contacts/src/outbound/gateway.rs@@ -1,3 +1,6 @@+#[cfg(test)]+mod test;+use crate::domain::ports::ContactsNotifier;use macro_user_id::user_id::MacroUserIdStr;use rootcause::Report;@@ -21,12 +24,22 @@ impl ConnectionGatewayNotifier {#[tracing::instrument(skip(self), err)]async fn invalidate_contacts(&self, user_id: &str) -> Result<(), Report> {- self.client- .post(format!("{}/message/send/user/{}", self.url, user_id))+ let response = self+ .client+ .post(format!(+ "{}/message/send/user/{}",+ self.url,+ urlencoding::encode(user_id)+ )).json(&serde_json::json!({"message_type": "contacts_invalidation", "message": {}})).send()- .await?- .error_for_status()?;+ .await?;+ let status = response.error_for_status_ref().map(drop);+ // Read the body even on error statuses: h2 only refunds its small-DATA-frame+ // budget for frames that are read, and once that budget is spent the client+ // tears down its own pooled connection (GOAWAY `too_many_data_frames`).+ response.bytes().await?;+ status?;Ok(())}}diff --git a/crates/contacts/src/outbound/gateway/test.rs b/crates/contacts/src/outbound/gateway/test.rsnew file mode 100644index 0000000000..941dcf6955--- /dev/null+++ b/crates/contacts/src/outbound/gateway/test.rs@@ -0,0 +1,108 @@+use super::*;+use axum::{+ Router,+ body::Body,+ extract::{ConnectInfo, Path, State},+ http::StatusCode,+ response::{IntoResponse, Response},+ routing::post,+};+use std::{+ collections::HashSet,+ convert::Infallible,+ net::SocketAddr,+ sync::{Arc, Mutex},+ time::Duration,+};++#[derive(Clone)]+struct Gateway {+ status: StatusCode,+ received: Arc<Mutex<Vec<Received>>>,+}++struct Received {+ entity_type: String,+ entity_id: String,+ peer: SocketAddr,+}++async fn send_message(+ State(gateway): State<Gateway>,+ ConnectInfo(peer): ConnectInfo<SocketAddr>,+ Path((entity_type, entity_id)): Path<(String, String)>,+) -> Response {+ gateway.received.lock().unwrap().push(Received {+ entity_type,+ entity_id,+ peer,+ });+ let body = futures::stream::once(async {+ tokio::time::sleep(Duration::from_millis(10)).await;+ Ok::<_, Infallible>(r#"{"receipts":[]}"#)+ });+ (gateway.status, Body::from_stream(body)).into_response()+}++async fn spawn_gateway(+ status: StatusCode,+) -> (ConnectionGatewayNotifier, Arc<Mutex<Vec<Received>>>) {+ let received = Arc::new(Mutex::new(Vec::new()));+ let router = Router::new()+ .route(+ "/message/send/{entity_type}/{entity_id}",+ post(send_message),+ )+ .with_state(Gateway {+ status,+ received: received.clone(),+ });+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let url = format!("http://{}", listener.local_addr().unwrap());+ tokio::spawn(async move {+ axum::serve(+ listener,+ router.into_make_service_with_connect_info::<SocketAddr>(),+ )+ .await+ .unwrap();+ });+ let notifier = ConnectionGatewayNotifier::new("test-key".to_string(), url).unwrap();+ (notifier, received)+}++#[tokio::test]+async fn user_id_reaches_the_gateway_as_one_path_segment() {+ let (notifier, received) = spawn_gateway(StatusCode::OK).await;+ let user_ids = [+ "macro|accounts/[email protected]",+ "macro|//[email protected]",+ "macro|a#b?c%[email protected]",+ ];++ for user_id in user_ids {+ notifier.invalidate_contacts(user_id).await.unwrap();+ }++ let received = received.lock().unwrap();+ let entity_ids: Vec<_> = received.iter().map(|r| r.entity_id.as_str()).collect();+ assert_eq!(entity_ids, user_ids);+ assert!(received.iter().all(|r| r.entity_type == "user"));+}++/// The fake gateway sends each body after its headers, so the pooled connection+/// is only reused if every response body is read to the end.+#[tokio::test]+async fn sequential_invalidations_reuse_one_connection() {+ for status in [StatusCode::OK, StatusCode::INTERNAL_SERVER_ERROR] {+ let (notifier, received) = spawn_gateway(status).await;++ for _ in 0..20 {+ let result = notifier.invalidate_contacts("macro|[email protected]").await;+ assert_eq!(result.is_ok(), status.is_success(), "{status}");+ }++ let peers: HashSet<_> = received.lock().unwrap().iter().map(|r| r.peer).collect();+ assert_eq!(peers.len(), 1, "{status}");+ }+}