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(notif): filter read notifs out of digest (#4084)

Sean Aye42fa124e5643
diff --git a/.github/workflows/code-check-cloud-storage.yml b/.github/workflows/code-check-cloud-storage.yml
index d8f88808ea..3248e29f32 100644
--- a/.github/workflows/code-check-cloud-storage.yml
+++ b/.github/workflows/code-check-cloud-storage.yml
@@ -27,6 +27,11 @@ jobs:
with:
clean: false
fetch-depth: 0
+ - name: Setup Rust
+ uses: ./.github/actions/setup-rust
+ with:
+ sccache: 'false'
+ rust-cache: 'false'
- uses: dorny/paths-filter@v3
id: filter
with:
@@ -69,90 +74,7 @@ jobs:
exit 0
fi
- filterset="$(
- python3 <<'PY'
- import glob
- import re
- from pathlib import Path
-
- repo = Path.cwd().resolve()
- workspace = repo / 'rust' / 'cloud-storage'
- changed_files = [line for line in Path('/tmp/changed-files').read_text().splitlines() if line]
-
- def workspace_members(manifest: Path) -> list[str]:
- members = []
- in_workspace = False
- in_members = False
-
- for raw_line in manifest.read_text().splitlines():
- line = raw_line.split('#', 1)[0].strip()
- if not line:
- continue
- if line.startswith('['):
- in_workspace = line == '[workspace]'
- continue
- if not in_workspace:
- continue
- if line.startswith('members') and '[' in line:
- in_members = True
- if in_members:
- members.extend(re.findall(r'"([^"\\]*(?:\\.[^"\\]*)*)"', line))
- if ']' in line:
- in_members = False
- return members
-
- def package_name(manifest: Path) -> str | None:
- in_package = False
- for raw_line in manifest.read_text().splitlines():
- line = raw_line.split('#', 1)[0].strip()
- if not line:
- continue
- if line.startswith('['):
- in_package = line == '[package]'
- continue
- if in_package:
- match = re.match(r'name\s*=\s*"([^"]+)"', line)
- if match:
- return match.group(1)
- return None
-
- packages = []
- for member in workspace_members(workspace / 'Cargo.toml'):
- for member_dir in glob.glob(str(workspace / member)):
- manifest = Path(member_dir) / 'Cargo.toml'
- if not manifest.exists():
- continue
- name = package_name(manifest)
- if name:
- packages.append((manifest.parent.resolve(), name))
-
- changed_packages = set()
- for changed_file in changed_files:
- path = (repo / changed_file).resolve()
- if path != workspace and workspace not in path.parents:
- continue
-
- matching_packages = [
- (manifest_dir, name)
- for manifest_dir, name in packages
- if path == manifest_dir or manifest_dir in path.parents
- ]
- if matching_packages:
- _, name = max(matching_packages, key=lambda item: len(item[0].parts))
- changed_packages.add(name)
-
- def escape_nextest_name(name: str) -> str:
- return (
- name
- .replace('\\', '\\\\')
- .replace(')', '\\)')
- .replace(',', '\\,')
- )
-
- if changed_packages:
- print('|'.join(f'rdeps(={escape_nextest_name(name)})' for name in sorted(changed_packages)))
- PY
- )"
+ filterset="$(cargo run --manifest-path rust/cloud-storage/tools/xtask/Cargo.toml -- nextest-filter /tmp/changed-files)"
if [ -z "$filterset" ]; then
echo "No package-specific Rust changes detected; running all tests"
diff --git a/rust/cloud-storage/.sqlx/query-27870c565b270e952b13f4834c78e03264cd173670efaf774c21b77bf2aa8ecf.json b/rust/cloud-storage/.sqlx/query-27870c565b270e952b13f4834c78e03264cd173670efaf774c21b77bf2aa8ecf.json
new file mode 100644
index 0000000000..1920e46150
--- /dev/null
+++ b/rust/cloud-storage/.sqlx/query-27870c565b270e952b13f4834c78e03264cd173670efaf774c21b77bf2aa8ecf.json
@@ -0,0 +1,23 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT un.notification_id\n FROM user_notification un\n JOIN notification n ON n.id = un.notification_id\n WHERE un.user_id = $1\n AND un.notification_id = ANY($2)\n AND un.deleted_at IS NULL\n AND un.seen_at IS NULL\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "notification_id",
+ "type_info": "Uuid"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "UuidArray"
+ ]
+ },
+ "nullable": [
+ false
+ ]
+ },
+ "hash": "27870c565b270e952b13f4834c78e03264cd173670efaf774c21b77bf2aa8ecf"
+}
diff --git a/rust/cloud-storage/notification/src/domain/ports.rs b/rust/cloud-storage/notification/src/domain/ports.rs
index 2cb3a76311..d1d7bbb2c1 100644
--- a/rust/cloud-storage/notification/src/domain/ports.rs
+++ b/rust/cloud-storage/notification/src/domain/ports.rs
@@ -114,6 +114,15 @@ pub trait NotificationRepository: Send + Sync + 'static {
notification_ids: &[Uuid],
) -> impl Future<Output = Result<Vec<NotificationIdAndCollapseKey>, Report>> + Send;
+ /// Return notification IDs that still exist for the user and are eligible for digest email.
+ ///
+ /// Excludes notifications that are missing, soft-deleted, or already seen.
+ fn get_digest_eligible_notification_ids(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ notification_ids: &[Uuid],
+ ) -> impl Future<Output = Result<HashSet<Uuid>, Report>> + Send;
+
/// Get a user's non-deleted notifications with cursor-based pagination.
///
/// The metadata JSON column is deserialized into `T`. `filters` controls done/seen status.
diff --git a/rust/cloud-storage/notification/src/domain/service/device/test.rs b/rust/cloud-storage/notification/src/domain/service/device/test.rs
index 238eaf406d..33e8c5a04b 100644
--- a/rust/cloud-storage/notification/src/domain/service/device/test.rs
+++ b/rust/cloud-storage/notification/src/domain/service/device/test.rs
@@ -6,7 +6,7 @@ use crate::domain::service::ingress::{NotificationReaderService, PlatformArnConf
use macro_user_id::user_id::MacroUserIdStr;
use rootcause::Report;
use serde::Serialize;
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use std::sync::Mutex;
fn test_user_id() -> MacroUserIdStr<'static> {
@@ -165,6 +165,13 @@ impl NotificationRepository for MockNotifRepo {
) -> Result<Vec<crate::domain::models::NotificationIdAndCollapseKey>, Report> {
unimplemented!()
}
+ async fn get_digest_eligible_notification_ids(
+ &self,
+ _: macro_user_id::user_id::MacroUserIdStr<'_>,
+ _: &[uuid::Uuid],
+ ) -> Result<HashSet<uuid::Uuid>, Report> {
+ unimplemented!()
+ }
async fn get_user_notifications<T: serde::de::DeserializeOwned + Send>(
&self,
_: macro_user_id::user_id::MacroUserIdStr<'_>,
diff --git a/rust/cloud-storage/notification/src/domain/service/egress.rs b/rust/cloud-storage/notification/src/domain/service/egress.rs
index 794e246bf5..80f0d986be 100644
--- a/rust/cloud-storage/notification/src/domain/service/egress.rs
+++ b/rust/cloud-storage/notification/src/domain/service/egress.rs
@@ -347,7 +347,7 @@ where
&'a self,
f: &'a F,
) -> Result<ClaimResult<()>, Report> {
- let batch =
+ let mut batch =
match tokio::time::timeout(DELIVERY_TIMEOUT, self.digest_batcher.claim_ready_digest())
.await
.context("Dequeing redis batch exceeded timeout")??
@@ -357,6 +357,29 @@ where
};
let recipient: MacroUserIdStr<'static> = batch.user_id.clone();
+ let notification_ids: Vec<_> = batch
+ .notifications
+ .iter()
+ .map(|notification| notification.notification_id)
+ .collect();
+ let eligible_notification_ids = self
+ .repository
+ .get_digest_eligible_notification_ids(recipient.copied(), &notification_ids)
+ .await?;
+ let original_count = batch.notifications.len();
+ batch.notifications.retain(|notification| {
+ eligible_notification_ids.contains(&notification.notification_id)
+ });
+
+ if batch.notifications.is_empty() {
+ tracing::info!(
+ user_id = %recipient,
+ original_count,
+ "Skipping email digest publish — all queued notifications are now read, deleted, or missing"
+ );
+ return Ok(ClaimResult::Ready(()));
+ }
+
let email_notif = f(batch)?;
let typename = NotificationTypeName::new_from_notif(&email_notif);
diff --git a/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs b/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs
index f759b29a8f..5e1f003a04 100644
--- a/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs
+++ b/rust/cloud-storage/notification/src/domain/service/push_notification_event/test.rs
@@ -7,7 +7,7 @@ use crate::domain::models::push_notification_event::{EventType, SnsPushNotificat
use crate::domain::ports::{NotificationRepository, SnsEndpointManager};
use rootcause::Report;
use serde::Serialize;
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use std::sync::Mutex;
/// Mock notification repository that only implements delete_device_by_endpoint.
@@ -132,6 +132,13 @@ impl NotificationRepository for MockNotifRepo {
) -> Result<Vec<crate::domain::models::NotificationIdAndCollapseKey>, Report> {
unimplemented!()
}
+ async fn get_digest_eligible_notification_ids(
+ &self,
+ _: macro_user_id::user_id::MacroUserIdStr<'_>,
+ _: &[uuid::Uuid],
+ ) -> Result<HashSet<uuid::Uuid>, Report> {
+ unimplemented!()
+ }
async fn get_user_notifications<T: serde::de::DeserializeOwned + Send>(
&self,
_: macro_user_id::user_id::MacroUserIdStr<'_>,
diff --git a/rust/cloud-storage/notification/src/domain/service/test.rs b/rust/cloud-storage/notification/src/domain/service/test.rs
index ae50f33539..baeb2d05b5 100644
--- a/rust/cloud-storage/notification/src/domain/service/test.rs
+++ b/rust/cloud-storage/notification/src/domain/service/test.rs
@@ -103,6 +103,7 @@ struct MockRepository {
created_notifications: Mutex<Vec<Uuid>>,
stored_collapse_keys: Mutex<Vec<(Uuid, Option<String>)>>,
basic_notifications: Vec<NotificationIdAndCollapseKey>,
+ digest_eligible_notification_ids: Option<HashSet<Uuid>>,
mark_seen_calls: Mutex<Vec<(String, Vec<Uuid>)>>,
mark_done_calls: Mutex<Vec<(String, Vec<Uuid>, bool)>>,
}
@@ -117,6 +118,7 @@ impl MockRepository {
created_notifications: Mutex::new(Vec::new()),
stored_collapse_keys: Mutex::new(Vec::new()),
basic_notifications: Vec::new(),
+ digest_eligible_notification_ids: None,
mark_seen_calls: Mutex::new(Vec::new()),
mark_done_calls: Mutex::new(Vec::new()),
}
@@ -130,6 +132,14 @@ impl MockRepository {
self
}
+ fn with_digest_eligible_notification_ids(
+ mut self,
+ ids: impl IntoIterator<Item = Uuid>,
+ ) -> Self {
+ self.digest_eligible_notification_ids = Some(ids.into_iter().collect());
+ self
+ }
+
fn with_muted_user(mut self, user_id: MacroUserIdStr<'static>) -> Self {
self.muted_users.insert(user_id);
self
@@ -273,6 +283,17 @@ impl NotificationRepository for MockRepository {
Ok(self.basic_notifications.clone())
}
+ async fn get_digest_eligible_notification_ids(
+ &self,
+ _user_id: MacroUserIdStr<'_>,
+ notification_ids: &[Uuid],
+ ) -> Result<HashSet<Uuid>, Report> {
+ Ok(self
+ .digest_eligible_notification_ids
+ .clone()
+ .unwrap_or_else(|| notification_ids.iter().copied().collect()))
+ }
+
async fn get_user_notifications<T: DeserializeOwned + Send>(
&self,
_user_id: MacroUserIdStr<'_>,
@@ -454,6 +475,16 @@ impl NotificationRepository for std::sync::Arc<MockRepository> {
(**self).get_basic_notifications(notification_ids).await
}
+ async fn get_digest_eligible_notification_ids(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ notification_ids: &[Uuid],
+ ) -> Result<HashSet<Uuid>, Report> {
+ (**self)
+ .get_digest_eligible_notification_ids(user_id, notification_ids)
+ .await
+ }
+
async fn get_user_notifications<T: DeserializeOwned + Send>(
&self,
user_id: MacroUserIdStr<'_>,
@@ -1883,6 +1914,122 @@ async fn test_poll_email_digests_sends_email_for_ready_batch() {
assert!(published[0]["content"]["Email"].is_object());
}
+#[tokio::test]
+async fn test_poll_email_digests_skips_when_all_notifications_ineligible() {
+ use std::sync::Arc;
+
+ let user = test_user_id("[email protected]");
+ let notif = UserNotificationRow {
+ owner_id: user.clone(),
+ notification_id: Uuid::nil(),
+ notification_event_type: "test_notification".to_string(),
+ entity: EntityType::Document.with_entity_str("doc-1"),
+ sent: false,
+ done: false,
+ created_at: Utc::now(),
+ viewed_at: None,
+ updated_at: Utc::now(),
+ deleted_at: None,
+ notification_metadata: serde_json::to_value(TestNotification {
+ message: "already read".to_string(),
+ })
+ .unwrap(),
+ sender_id: None,
+ };
+
+ let batcher = ReadyDigestBatcher {
+ batch: Mutex::new(Some(DigestBatch {
+ user_id: user,
+ notifications: vec![notif.into_tagged()],
+ })),
+ };
+
+ let queue = Arc::new(MockQueue::new());
+ let service = NotificationEgressService {
+ queue: queue.clone(),
+ repository: MockRepository::new().with_digest_eligible_notification_ids([]),
+ websocket: MockWebSocketSender,
+ mobile: MockMobileSender,
+ email: MockEmailSender,
+ rate_limiter: allowing_rate_limiter(),
+ state_machine: MockEgressStateMachine,
+ digest_batcher: batcher,
+ };
+
+ let digest_to_notif = |_batch: DigestBatch| -> Result<TestNotification, Report> {
+ panic!("digest should not be rendered when no notifications remain eligible")
+ };
+
+ let result = service.poll_email_digests(&digest_to_notif).await.unwrap();
+
+ assert!(matches!(result, ClaimResult::Ready(())));
+ assert!(queue.get_published().is_empty());
+}
+
+#[tokio::test]
+async fn test_poll_email_digests_filters_ineligible_notifications_before_rendering() {
+ use std::sync::Arc;
+ use std::sync::atomic::{AtomicUsize, Ordering};
+
+ let user = test_user_id("[email protected]");
+ let eligible_id = Uuid::parse_str("0193b1ea-c742-7589-893b-2b4a509c1e77").unwrap();
+ let ineligible_id = Uuid::parse_str("0193b1ea-c742-7589-893b-2b4a509c1e78").unwrap();
+
+ let make_notif = |notification_id, message: &str| UserNotificationRow {
+ owner_id: user.clone(),
+ notification_id,
+ notification_event_type: "test_notification".to_string(),
+ entity: EntityType::Document.with_entity_str("doc-1"),
+ sent: false,
+ done: false,
+ created_at: Utc::now(),
+ viewed_at: None,
+ updated_at: Utc::now(),
+ deleted_at: None,
+ notification_metadata: serde_json::to_value(TestNotification {
+ message: message.to_string(),
+ })
+ .unwrap(),
+ sender_id: None,
+ };
+
+ let batcher = ReadyDigestBatcher {
+ batch: Mutex::new(Some(DigestBatch {
+ user_id: user.clone(),
+ notifications: vec![
+ make_notif(eligible_id, "keep").into_tagged(),
+ make_notif(ineligible_id, "drop").into_tagged(),
+ ],
+ })),
+ };
+
+ let rendered_count = Arc::new(AtomicUsize::new(0));
+ let rendered_count_for_closure = rendered_count.clone();
+ let digest_to_notif = move |batch: DigestBatch| -> Result<TestNotification, Report> {
+ rendered_count_for_closure.store(batch.notifications.len(), Ordering::SeqCst);
+ Ok(TestNotification {
+ message: format!("You have {} notification(s)", batch.notifications.len()),
+ })
+ };
+
+ let queue = Arc::new(MockQueue::new());
+ let service = NotificationEgressService {
+ queue: queue.clone(),
+ repository: MockRepository::new().with_digest_eligible_notification_ids([eligible_id]),
+ websocket: MockWebSocketSender,
+ mobile: MockMobileSender,
+ email: MockEmailSender,
+ rate_limiter: allowing_rate_limiter(),
+ state_machine: MockEgressStateMachine,
+ digest_batcher: batcher,
+ };
+
+ service.poll_email_digests(&digest_to_notif).await.unwrap();
+
+ assert_eq!(rendered_count.load(Ordering::SeqCst), 1);
+ assert_eq!(queue.get_published().len(), 1);
+}
+
#[tokio::test]
async fn test_poll_email_digests_noop_when_empty() {
let service = create_egress_service(allowing_rate_limiter());
diff --git a/rust/cloud-storage/notification/src/domain/service/voip/test.rs b/rust/cloud-storage/notification/src/domain/service/voip/test.rs
index 65d4a6a78f..9e2af1c621 100644
--- a/rust/cloud-storage/notification/src/domain/service/voip/test.rs
+++ b/rust/cloud-storage/notification/src/domain/service/voip/test.rs
@@ -1,4 +1,4 @@
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use std::sync::{Arc, Mutex};
use aws_sdk_sns::types::MessageAttributeValue;
@@ -154,6 +154,13 @@ impl NotificationRepository for MockRepo {
) -> Result<Vec<crate::domain::models::NotificationIdAndCollapseKey>, Report> {
unimplemented!()
}
+ async fn get_digest_eligible_notification_ids(
+ &self,
+ _: MacroUserIdStr<'_>,
+ _: &[uuid::Uuid],
+ ) -> Result<HashSet<uuid::Uuid>, Report> {
+ unimplemented!()
+ }
async fn get_user_notifications<T: serde::de::DeserializeOwned + Send>(
&self,
_: MacroUserIdStr<'_>,
diff --git a/rust/cloud-storage/notification/src/outbound/repository.rs b/rust/cloud-storage/notification/src/outbound/repository.rs
index 70423ffa18..6dfc859dc4 100644
--- a/rust/cloud-storage/notification/src/outbound/repository.rs
+++ b/rust/cloud-storage/notification/src/outbound/repository.rs
@@ -358,6 +358,15 @@ pub trait NotificationDbOps: DeviceRegistrationDbOps + Send + Sync + 'static {
notification_ids: &[Uuid],
) -> impl std::future::Future<Output = Result<Vec<NotificationIdAndCollapseKey>, Report>> + Send;
+ /// Return notification IDs that still exist for the user and are eligible for digest email.
+ ///
+ /// Excludes notifications that are missing, soft-deleted, or already seen.
+ fn get_digest_eligible_notification_ids(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ notification_ids: &[Uuid],
+ ) -> impl std::future::Future<Output = Result<HashSet<Uuid>, Report>> + Send;
+
/// Get a user's non-deleted notifications with cursor-based pagination.
///
/// The metadata JSON column is deserialized into `T`. `filters` controls done/seen status.
@@ -752,6 +761,32 @@ impl NotificationDbOps for PgPool {
.collect())
}
+ async fn get_digest_eligible_notification_ids(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ notification_ids: &[Uuid],
+ ) -> Result<HashSet<Uuid>, Report> {
+ let user_id_str = user_id.to_string();
+
+ let rows = sqlx::query!(
+ r#"
+ SELECT un.notification_id
+ FROM user_notification un
+ JOIN notification n ON n.id = un.notification_id
+ WHERE un.user_id = $1
+ AND un.notification_id = ANY($2)
+ AND un.deleted_at IS NULL
+ AND un.seen_at IS NULL
+ "#,
+ user_id_str,
+ notification_ids
+ )
+ .fetch_all(self)
+ .await?;
+
+ Ok(rows.into_iter().map(|row| row.notification_id).collect())
+ }
+
async fn get_user_notifications<T: DeserializeOwned + Send>(
&self,
user_id: MacroUserIdStr<'_>,
@@ -1247,6 +1282,16 @@ impl<D: NotificationDbOps + Send + Sync> NotificationRepository for DbNotificati
self.db.get_basic_notifications(notification_ids).await
}
+ async fn get_digest_eligible_notification_ids(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ notification_ids: &[Uuid],
+ ) -> Result<HashSet<Uuid>, Report> {
+ self.db
+ .get_digest_eligible_notification_ids(&user_id, notification_ids)
+ .await
+ }
+
async fn get_user_notifications<T: DeserializeOwned + Send>(
&self,
user_id: MacroUserIdStr<'_>,
diff --git a/rust/cloud-storage/notification/src/outbound/repository/test.rs b/rust/cloud-storage/notification/src/outbound/repository/test.rs
index fff4b7693a..b42468b3a9 100644
--- a/rust/cloud-storage/notification/src/outbound/repository/test.rs
+++ b/rust/cloud-storage/notification/src/outbound/repository/test.rs
@@ -320,6 +320,90 @@ async fn test_get_basic_notifications_empty(pool: Pool<Postgres>) {
assert!(result.is_empty());
}
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(
+ path = "../../../fixtures",
+ scripts("notifications_with_collapse_keys")
+ )
+)]
+async fn test_get_digest_eligible_notification_ids_filters_seen_deleted_missing_and_other_users(
+ pool: Pool<Postgres>,
+) {
+ let user = test_user("[email protected]");
+ let other_user = test_user("[email protected]");
+ let eligible_id = uuid::Uuid::parse_str("0193b1ea-a542-7589-893b-2b4a509c1e76").unwrap();
+ let seen_id = uuid::Uuid::parse_str("0193b1ea-b642-7589-893b-2b4a509c1e76").unwrap();
+ let deleted_id = uuid::Uuid::parse_str("0193b1ea-c742-7589-893b-2b4a509c1e76").unwrap();
+ let other_user_id = uuid::Uuid::parse_str("0193b1ea-d842-7589-893b-2b4a509c1e76").unwrap();
+ let missing_id = uuid::Uuid::parse_str("0193b1ea-e942-7589-893b-2b4a509c1e76").unwrap();
+
+ sqlx::query!(
+ r#"
+ INSERT INTO notification (id, notification_event_type, event_item_id, event_item_type, service_sender, metadata)
+ VALUES
+ ($1, 'test', 'item-3', 'document', 'test_service', '{}'),
+ ($2, 'test', 'item-4', 'document', 'test_service', '{}')
+ "#,
+ deleted_id,
+ other_user_id
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ sqlx::query!(
+ r#"
+ INSERT INTO user_notification (user_id, notification_id, created_at, deleted_at)
+ VALUES ($1, $2, '2025-01-01 00:00:02', '2025-01-01 00:01:00')
+ "#,
+ user.to_string(),
+ deleted_id
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ sqlx::query!(
+ r#"
+ INSERT INTO user_notification (user_id, notification_id, created_at)
+ VALUES ($1, $2, '2025-01-01 00:00:03')
+ "#,
+ other_user.to_string(),
+ other_user_id
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ pool.mark_notifications_seen(&user, &[seen_id])
+ .await
+ .unwrap();
+
+ let result = pool
+ .get_digest_eligible_notification_ids(
+ &user,
+ &[eligible_id, seen_id, deleted_id, other_user_id, missing_id],
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(result.len(), 1);
+ assert!(result.contains(&eligible_id));
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn test_get_digest_eligible_notification_ids_empty_input(pool: Pool<Postgres>) {
+ let user = test_user("[email protected]");
+
+ let result = pool
+ .get_digest_eligible_notification_ids(&user, &[])
+ .await
+ .unwrap();
+
+ assert!(result.is_empty());
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("user_notifications"))
diff --git a/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs b/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs
index 41cafcdf7a..7926a9e384 100644
--- a/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs
+++ b/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs
@@ -115,6 +115,16 @@ impl NotificationRepository for SandboxNotificationRepository {
self.inner.get_basic_notifications(notification_ids).await
}
+ async fn get_digest_eligible_notification_ids(
+ &self,
+ user_id: MacroUserIdStr<'_>,
+ notification_ids: &[Uuid],
+ ) -> Result<HashSet<Uuid>, Report> {
+ self.inner
+ .get_digest_eligible_notification_ids(user_id, notification_ids)
+ .await
+ }
+
async fn get_user_notifications<T: DeserializeOwned + Send>(
&self,
user_id: MacroUserIdStr<'_>,
diff --git a/rust/cloud-storage/tools/xtask/src/main.rs b/rust/cloud-storage/tools/xtask/src/main.rs
index 9c15a6e04e..03bd83c950 100644
--- a/rust/cloud-storage/tools/xtask/src/main.rs
+++ b/rust/cloud-storage/tools/xtask/src/main.rs
@@ -17,6 +17,7 @@
mod closures;
mod hakari_ops;
+mod nextest_filter;
use std::path::Path;
@@ -26,12 +27,20 @@ use guppy::MetadataCommand;
fn main() -> Result<()> {
let args: Vec<String> = std::env::args().skip(1).collect();
- let check = match args.iter().map(String::as_str).collect::<Vec<_>>()[..] {
- ["deps"] => false,
- ["deps", "--check"] => true,
- _ => bail!("usage: cargo run -p xtask -- deps [--check]"),
- };
+ match args.iter().map(String::as_str).collect::<Vec<_>>()[..] {
+ ["deps"] => run_deps(false),
+ ["deps", "--check"] => run_deps(true),
+ ["nextest-filter", changed_files_path] => {
+ let graph = build_graph(false)?;
+ nextest_filter::run(&graph, Path::new(changed_files_path))
+ }
+ _ => bail!(
+ "usage:\n cargo run -p xtask -- deps [--check]\n cargo run -p xtask -- nextest-filter <changed-files-path>"
+ ),
+ }
+}
+fn run_deps(check: bool) -> Result<()> {
let graph = build_graph(check)?;
let mut drift: Vec<String> = Vec::new();
diff --git a/rust/cloud-storage/tools/xtask/src/nextest_filter.rs b/rust/cloud-storage/tools/xtask/src/nextest_filter.rs
new file mode 100644
index 0000000000..e2c8054231
--- /dev/null
+++ b/rust/cloud-storage/tools/xtask/src/nextest_filter.rs
@@ -0,0 +1,76 @@
+//! Computes the cargo-nextest package filter for cloud-storage CI.
+//!
+//! Input is a newline-delimited file of paths relative to the repository root
+//! (typically `git diff --name-only ...`). For each changed path inside the
+//! cloud-storage workspace, find the deepest workspace package containing that
+//! path using Cargo's own workspace metadata via guppy. The resulting nextest
+//! expression runs tests for reverse dependencies of every changed package.
+
+use std::collections::BTreeSet;
+use std::path::{Path, PathBuf};
+
+use anyhow::{Context, Result};
+use guppy::graph::PackageGraph;
+
+pub fn run(graph: &PackageGraph, changed_files_path: &Path) -> Result<()> {
+ let workspace = graph.workspace();
+ let ws_root = workspace.root();
+ let repo_root = ws_root
+ .ancestors()
+ .nth(2)
+ .with_context(|| format!("no repo root two levels above {ws_root}"))?;
+
+ let packages = workspace
+ .iter()
+ .map(|package| {
+ let dir = package
+ .manifest_path()
+ .parent()
+ .with_context(|| format!("manifest {} has no parent", package.manifest_path()))?;
+ Ok((PathBuf::from(dir.as_std_path()), package.name().to_owned()))
+ })
+ .collect::<Result<Vec<_>>>()?;
+
+ let changed_files = std::fs::read_to_string(changed_files_path).with_context(|| {
+ format!(
+ "reading changed files from {}",
+ changed_files_path.display()
+ )
+ })?;
+
+ let mut changed_packages = BTreeSet::new();
+ for changed_file in changed_files.lines().filter(|line| !line.is_empty()) {
+ let path = repo_root
+ .join(changed_file)
+ .canonicalize()
+ .unwrap_or_else(|_| repo_root.join(changed_file).into());
+ if path != ws_root.as_std_path() && !path.starts_with(ws_root.as_std_path()) {
+ continue;
+ }
+
+ let package = packages
+ .iter()
+ .filter(|(dir, _)| path == *dir || path.starts_with(dir))
+ .max_by_key(|(dir, _)| dir.components().count())
+ .map(|(_, name)| name);
+
+ if let Some(name) = package {
+ changed_packages.insert(name.clone());
+ }
+ }
+
+ let filter = changed_packages
+ .into_iter()
+ .map(|name| format!("rdeps(={})", escape_nextest_name(&name)))
+ .collect::<Vec<_>>()
+ .join("|");
+
+ println!("{filter}");
+ Ok(())
+}
+
+fn escape_nextest_name(name: &str) -> String {
+ name.replace('\\', "\\\\")
+ .replace(')', "\\)")
+ .replace(',', "\\,")
+}