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(notif): worker hanging (#1861)

Sean Aye1319c4f60d80
diff --git a/rust/cloud-storage/notification/Cargo.toml b/rust/cloud-storage/notification/Cargo.toml
index c4c6122c1c..65a0b1bfaa 100644
--- a/rust/cloud-storage/notification/Cargo.toml
+++ b/rust/cloud-storage/notification/Cargo.toml
@@ -61,4 +61,4 @@ uuid = { workspace = true }
[dev-dependencies]
macro_db_migrator = { path = "../macro_db_migrator" }
-tokio = { workspace = true, features = ["macros", "rt"] }
+tokio = { workspace = true, features = ["macros", "rt", "test-util"] }
diff --git a/rust/cloud-storage/notification/src/domain/models/queue_message.rs b/rust/cloud-storage/notification/src/domain/models/queue_message.rs
index 90227fd93d..88fb45d028 100644
--- a/rust/cloud-storage/notification/src/domain/models/queue_message.rs
+++ b/rust/cloud-storage/notification/src/domain/models/queue_message.rs
@@ -364,6 +364,12 @@ pub enum DeliveryFailure {
/// The rate limit for this notification type was exceeded.
#[error("The rate limit was exceeded")]
RateLimit,
+ /// a timeout limit was reached trying to deliver the notif
+ #[error("A timeout was reached")]
+ Timeout,
+ /// a delivery error occurred with apns
+ #[error("An apns delivery error occurred")]
+ Ios,
/// A delivery error occurred.
#[error("A delivery error occured")]
Other,
diff --git a/rust/cloud-storage/notification/src/domain/service/egress.rs b/rust/cloud-storage/notification/src/domain/service/egress.rs
index 86af465b51..71e08efe9c 100644
--- a/rust/cloud-storage/notification/src/domain/service/egress.rs
+++ b/rust/cloud-storage/notification/src/domain/service/egress.rs
@@ -3,6 +3,8 @@
//! This service handles the worker-facing side of notifications:
//! consuming from the queue and delivering via WebSocket, push, and email.
+use std::time::Duration;
+
use crate::domain::models::apple::APNSPushNotification;
use crate::domain::models::email_notification_digest::ports::{
ClaimResult, DigestBatch, DigestBatcher, MessageId, NotificationSendChecker,
@@ -21,9 +23,13 @@ use crate::domain::ports::{
RateLimitPort, WebSocketSender,
};
use either::Either;
+use futures::stream::{FuturesUnordered, StreamExt};
use rootcause::prelude::ResultExt;
use rootcause::{Report, report};
+/// Maximum time to wait for a single notification delivery before timing out.
+pub(crate) const DELIVERY_TIMEOUT: Duration = Duration::from_secs(15);
+
/// Wraps a single iOS push notification send for the bulk-digest state machine.
///
/// The state machine calls [`NotificationSendChecker::send_notification`] to perform the actual
@@ -107,7 +113,7 @@ where
self.deliver_ios(&apns)
.await
.into_iter()
- .map(|r| r.context(DeliveryFailure::Other)),
+ .map(|r| r.context(DeliveryFailure::Ios)),
),
};
@@ -235,23 +241,44 @@ where
let mut results = Vec::new();
- for message in messages {
- let receipt_handle = message.receipt_handle.clone();
+ // Deliver all messages concurrently
+ let delivery_futures: FuturesUnordered<_> = messages
+ .into_iter()
+ .map(async |message| {
+ let receipt_handle = message.receipt_handle;
+ let delivery_results = match tokio::time::timeout(
+ DELIVERY_TIMEOUT,
+ self.deliver_notification(message.body),
+ )
+ .await
+ {
+ Ok(x) => x,
+ Err(_) => {
+ tracing::warn!("Notification egress task timed out");
+ vec![Err(report!(DeliveryFailure::Timeout))]
+ }
+ };
+ (receipt_handle, delivery_results)
+ })
+ .collect();
- // Deliver the notification (body is already parsed as QueueMessage)
- let delivery_results = self.deliver_notification(message.body).await;
+ let outcomes: Vec<_> = delivery_futures.collect().await;
- // Check if any deliveries succeeded
+ for (receipt_handle, delivery_results) in outcomes {
let any_succeeded = delivery_results.iter().any(Result::is_ok);
+ let all_ios_failed = delivery_results.iter().all(
+ |e| matches!(e, Err(e) if matches!(e.current_context(), DeliveryFailure::Ios )),
+ );
- // Add results (stripping the DeliveryFailure context for the trait return type)
for result in delivery_results {
results.push(result.map_err(Report::from));
}
// Delete from queue if any deliveries succeeded
- if any_succeeded && let Err(e) = self.queue.delete_message(&receipt_handle).await {
- // if delete queue fails push it into the results
+ // or all the failed notifs were ios
+ if (any_succeeded || all_ios_failed)
+ && let Err(e) = self.queue.delete_message(&receipt_handle).await
+ {
results.push(Err(e))
}
}
diff --git a/rust/cloud-storage/notification/src/domain/service/test.rs b/rust/cloud-storage/notification/src/domain/service/test.rs
index 470ad5a26c..d62ec9f8fa 100644
--- a/rust/cloud-storage/notification/src/domain/service/test.rs
+++ b/rust/cloud-storage/notification/src/domain/service/test.rs
@@ -1752,6 +1752,205 @@ async fn test_poll_email_digests_noop_when_empty() {
service.poll_email_digests(digest_to_notif).await.unwrap();
}
+// ============================================================================
+// Poll-and-deliver tests (timeout + iOS delete)
+// ============================================================================
+
+/// Mock queue for poll_and_deliver tests that returns preset messages and tracks deletes.
+struct EgressTestQueue {
+ messages: Mutex<Vec<RawQueueMessage>>,
+ deleted_handles: Mutex<Vec<String>>,
+}
+
+impl EgressTestQueue {
+ fn new(messages: Vec<RawQueueMessage>) -> Self {
+ Self {
+ messages: Mutex::new(messages),
+ deleted_handles: Mutex::new(Vec::new()),
+ }
+ }
+
+ fn deleted_handles(&self) -> Vec<String> {
+ self.deleted_handles.lock().unwrap().clone()
+ }
+}
+
+impl NotificationQueue for EgressTestQueue {
+ async fn publish<'a, T: Serialize + Send + Sync, U: Serialize + Send + Sync>(
+ &self,
+ _messages: impl Iterator<Item = QueueMessage<'a, T, U>> + Send,
+ ) -> Result<(), Report> {
+ Ok(())
+ }
+
+ async fn receive_messages(&self) -> Result<Vec<RawQueueMessage>, Report> {
+ Ok(self.messages.lock().unwrap().drain(..).collect())
+ }
+
+ async fn delete_message(&self, receipt_handle: &str) -> Result<(), Report> {
+ self.deleted_handles
+ .lock()
+ .unwrap()
+ .push(receipt_handle.to_string());
+ Ok(())
+ }
+}
+
+/// WebSocket sender that hangs indefinitely (simulates a stuck connection).
+struct HangingWebSocketSender;
+
+impl WebSocketSender for HangingWebSocketSender {
+ async fn send_notifications<'a, T: Serialize + Send + Sync>(
+ &self,
+ _recipients: &[MacroUserIdStr<'a>],
+ _notification: &T,
+ ) -> Result<HashSet<MacroUserIdStr<'static>>, Report> {
+ // Sleep longer than DELIVERY_TIMEOUT to guarantee the timeout fires.
+ tokio::time::sleep(super::egress::DELIVERY_TIMEOUT + Duration::from_secs(1)).await;
+ Ok(HashSet::new())
+ }
+}
+
+/// Mobile sender that always fails.
+struct FailingMobileSender;
+
+impl NotificationSender for FailingMobileSender {
+ async fn send_ios_push_notification<T: Serialize + Send + Sync>(
+ &self,
+ _endpoint_arn: &str,
+ _notification: &crate::domain::models::apple::APNSPushNotification<T>,
+ _attributes: &crate::domain::models::mobile::MessageAttributes,
+ ) -> Result<String, Report> {
+ rootcause::bail!("Simulated APNS failure")
+ }
+
+ async fn send_android_push_notification<T: Serialize + Send + Sync>(
+ &self,
+ _endpoint_arn: &str,
+ _notification: &crate::domain::models::android::FCMMessage<T>,
+ _attributes: &crate::domain::models::mobile::MessageAttributes,
+ ) -> Result<String, Report> {
+ rootcause::bail!("Simulated FCM failure")
+ }
+}
+
+#[tokio::test]
+async fn test_poll_and_deliver_times_out_slow_delivery() {
+ tokio::time::pause();
+
+ let recipient = test_user_id("[email protected]");
+ let message = QueueMessage::new_test(
+ "test_notification".to_string(),
+ NotificationChannel::ConnGateway(
+ ConnGatewayNotification {
+ notif: create_mock_notif(TestNotification {
+ message: "Hello".to_string(),
+ }),
+ recipients: vec![recipient],
+ }
+ .testing_to_value(),
+ ),
+ );
+
+ let queue = EgressTestQueue::new(vec![RawQueueMessage {
+ body: message,
+ receipt_handle: "receipt-timeout".to_string(),
+ }]);
+
+ let service = NotificationEgressService {
+ queue,
+ repository: MockRepository::new(),
+ websocket: HangingWebSocketSender,
+ mobile: MockMobileSender,
+ email: MockEmailSender,
+ rate_limiter: MockRateLimiter::allowing(),
+ state_machine: MockEgressStateMachine,
+ digest_batcher: MockDigestBatcher,
+ };
+
+ let results = service.poll_and_deliver().await;
+
+ assert_eq!(results.len(), 1);
+ assert!(results[0].is_err());
+
+ let err = results[0].as_ref().unwrap_err();
+ assert!(
+ err.to_string().contains("timeout"),
+ "Expected timeout error, got: {}",
+ err
+ );
+
+ // Timed out messages should NOT be deleted (not an iOS failure)
+ let deleted = service.queue.deleted_handles();
+ assert!(
+ deleted.is_empty(),
+ "Timed out message should not be deleted from queue"
+ );
+}
+
+#[tokio::test]
+async fn test_poll_and_deliver_deletes_message_when_all_ios_failures() {
+ use crate::domain::models::apple::{APNSPushNotification, Aps};
+ use crate::domain::models::mobile::{MessageAttributes, PushType};
+ use crate::domain::models::queue_message::{APNSTargets, UserApnsEndpoints};
+
+ let user = test_user_id("[email protected]");
+
+ let message = QueueMessage::new_test(
+ "test_notification".to_string(),
+ NotificationChannel::Ios(Box::new(APNSTargets {
+ notif: APNSPushNotification {
+ aps: Aps::default(),
+ push_notification_data: json!({"message": "Hello"}),
+ },
+ attributes: MessageAttributes {
+ push_type: PushType::Alert,
+ collapse_key: "test_collapse".to_string(),
+ },
+ ios_device_endpoints: HashMap::from([(
+ user,
+ UserApnsEndpoints {
+ endpoints: vec![
+ "arn:endpoint/device1".to_string(),
+ "arn:endpoint/device2".to_string(),
+ ],
+ digest_state: None,
+ },
+ )]),
+ })),
+ );
+
+ let queue = EgressTestQueue::new(vec![RawQueueMessage {
+ body: message,
+ receipt_handle: "receipt-ios".to_string(),
+ }]);
+
+ let service = NotificationEgressService {
+ queue,
+ repository: MockRepository::new(),
+ websocket: MockWebSocketSender,
+ mobile: FailingMobileSender,
+ email: MockEmailSender,
+ rate_limiter: MockRateLimiter::allowing(),
+ state_machine: MockEgressStateMachine,
+ digest_batcher: MockDigestBatcher,
+ };
+
+ let results = service.poll_and_deliver().await;
+
+ // All results should be failures
+ assert!(!results.is_empty());
+ assert!(results.iter().all(|r| r.is_err()));
+
+ // Message should be deleted because all failures are iOS
+ let deleted = service.queue.deleted_handles();
+ assert_eq!(
+ deleted,
+ vec!["receipt-ios"],
+ "Message should be deleted when all failures are iOS"
+ );
+}
+
impl NotificationSender for std::sync::Arc<TrackingMobileSender> {
async fn send_ios_push_notification<T: Serialize + Send + Sync>(
&self,