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.

seanaye/feat/email digest ports (#1530)

Sean Aye2d0080f22e63
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index f077f3a39a..dc30ba36fb 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -1993,12 +1993,14 @@ dependencies = [
"futures",
"http-body-util",
"itertools 0.14.0",
+ "last_online_tracker",
"macro_auth",
"macro_aws_config",
"macro_entrypoint",
"macro_env",
"macro_env_var",
"macro_middleware",
+ "macro_user_id",
"mockall",
"model",
"model-entity",
@@ -4879,6 +4881,18 @@ dependencies = [
"tracing-subscriber",
]
+[[package]]
+name = "last_online_tracker"
+version = "0.1.0"
+dependencies = [
+ "chrono",
+ "macro_user_id",
+ "redis",
+ "rootcause",
+ "tokio",
+ "tracing",
+]
+
[[package]]
name = "lazy_static"
version = "1.5.0"
diff --git a/rust/cloud-storage/connection_gateway/Cargo.toml b/rust/cloud-storage/connection_gateway/Cargo.toml
index b2d5fb5ce6..84811e670b 100644
--- a/rust/cloud-storage/connection_gateway/Cargo.toml
+++ b/rust/cloud-storage/connection_gateway/Cargo.toml
@@ -26,7 +26,6 @@ path = "src/openapi.rs"
[dependencies]
anyhow = { workspace = true }
aws-sdk-dynamodb = { workspace = true }
-macro_aws_config = { path = "../macro_aws_config" }
aws-sdk-secretsmanager = { workspace = true }
axum = { workspace = true, features = ["macros", "tower-log", "ws"] }
chrono = { workspace = true }
@@ -41,7 +40,10 @@ frecency = { path = "../frecency", features = [
futures = { workspace = true }
http-body-util = { workspace = true }
itertools = { workspace = true }
+last_online_tracker = { path = "../last_online_tracker" }
macro_auth = { path = "../macro_auth" }
+macro_user_id = { path = "../macro_user_id" }
+macro_aws_config = { path = "../macro_aws_config" }
macro_entrypoint = { path = "../macro_entrypoint" }
macro_env = { path = "../macro_env" }
macro_env_var = { path = "../macro_env_var" }
diff --git a/rust/cloud-storage/connection_gateway/src/api/connection/mod.rs b/rust/cloud-storage/connection_gateway/src/api/connection/mod.rs
index 1569c0216f..cfb06bb483 100644
--- a/rust/cloud-storage/connection_gateway/src/api/connection/mod.rs
+++ b/rust/cloud-storage/connection_gateway/src/api/connection/mod.rs
@@ -15,11 +15,13 @@ use axum::{
response::IntoResponse,
routing::get,
};
+use cowlike::CowLike;
use futures::{
FutureExt,
sink::SinkExt,
stream::{SplitSink, StreamExt},
};
+use macro_user_id::user_id::MacroUserIdStr;
use messages::handle_websocket_stream;
use model::user::UserContext;
use model_entity::EntityType;
@@ -59,7 +61,13 @@ async fn handle_websocket_connection(
let (sink, stream) = socket.split();
let (sender, receiver) = tokio::sync::mpsc::channel::<OutgoingMessage>(100);
let connection_id = uuid::Uuid::new_v4().to_string();
- let user_id = user_context.user_id.clone();
+ let Ok(user_id) = MacroUserIdStr::parse_from_str(&user_context.user_id) else {
+ return;
+ };
+ let user_id = user_id.into_owned();
+
+ // Create guard that records last online time when websocket connection closes
+ let last_online_guard = ctx.last_online_worker.new_guard(user_id.clone());
let sender_task = tokio::spawn(async move { forwarder(sink, receiver).await });
@@ -67,9 +75,9 @@ async fn handle_websocket_connection(
.connection_manager
.add_connection(
EntityType::User
- .with_entity_str(&user_id)
+ .with_entity_str(user_id.as_ref())
.with_connection_str(&connection_id)
- .with_user_str(&user_id),
+ .with_user_str(user_id.as_ref()),
sender.clone(),
sender_task.abort_handle(),
)
@@ -116,6 +124,7 @@ async fn handle_websocket_connection(
);
})
.ok();
+ drop(last_online_guard);
}
/// Forwards messages from a [Receiver] to a [SplitSink]
diff --git a/rust/cloud-storage/connection_gateway/src/context.rs b/rust/cloud-storage/connection_gateway/src/context.rs
index af6b089b49..8eb32b807e 100644
--- a/rust/cloud-storage/connection_gateway/src/context.rs
+++ b/rust/cloud-storage/connection_gateway/src/context.rs
@@ -5,6 +5,7 @@ use frecency::{
inbound::polling_aggregator::FrecencyAggregatorWorkerHandle,
outbound::postgres::FrecencyPgStorage,
};
+use last_online_tracker::inbound::LastOnlineWorker;
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
use redis::{RedisError, aio::MultiplexedConnection};
@@ -18,6 +19,7 @@ pub struct ApiContext {
pub frecency_ingestor_service: EventIngestorImpl<FrecencyPgStorage>,
pub redis_client: Arc<redis::Client>,
pub stream_manager: Arc<dyn StreamManager + Send + Sync>,
+ pub last_online_worker: Arc<LastOnlineWorker>,
}
impl ApiContext {
diff --git a/rust/cloud-storage/connection_gateway/src/main.rs b/rust/cloud-storage/connection_gateway/src/main.rs
index 2129b47f5a..a4f94e8d11 100644
--- a/rust/cloud-storage/connection_gateway/src/main.rs
+++ b/rust/cloud-storage/connection_gateway/src/main.rs
@@ -22,6 +22,11 @@ use frecency::{
time::DefaultTime,
},
};
+use last_online_tracker::{
+ domain::services::LastOnlineService,
+ inbound::LastOnlineWorker,
+ outbound::{redis::RedisLastOnlineRepo, time::DefaultTime as LastOnlineDefaultTime},
+};
use macro_auth::middleware::decode_jwt::JwtValidationArgs;
use macro_entrypoint::MacroEntrypoint;
use macro_env_var::env_var;
@@ -86,6 +91,11 @@ async fn main() -> Result<()> {
let connection_manager = create_dynamo_db_connection_manager(dynamodb_client.clone()).await?;
+ let last_online_redis_conn = redis_client.get_multiplexed_async_connection().await?;
+ let last_online_worker = Arc::new(LastOnlineWorker::new(LastOnlineService::new(
+ LastOnlineDefaultTime,
+ RedisLastOnlineRepo::new(last_online_redis_conn),
+ )));
let pgpool = PgPoolOptions::new()
.min_connections(3)
.max_connections(20)
@@ -107,6 +117,7 @@ async fn main() -> Result<()> {
redis_client: Arc::clone(&redis_client),
frecency_ingestor_service: EventIngestorImpl::new(FrecencyPgStorage::new(pgpool.clone())),
stream_manager,
+ last_online_worker,
};
tokio::spawn(poll_messages(context.clone()));
diff --git a/rust/cloud-storage/last_online_tracker/Cargo.toml b/rust/cloud-storage/last_online_tracker/Cargo.toml
new file mode 100644
index 0000000000..304576e255
--- /dev/null
+++ b/rust/cloud-storage/last_online_tracker/Cargo.toml
@@ -0,0 +1,13 @@
+[package]
+edition = "2024"
+name = "last_online_tracker"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+chrono = { workspace = true }
+macro_user_id = { path = "../macro_user_id" }
+redis = { workspace = true, features = ["aio", "tokio-comp"] }
+rootcause = { workspace = true }
+tokio = { workspace = true, features = ["sync"] }
+tracing = { workspace = true }
diff --git a/rust/cloud-storage/last_online_tracker/src/domain.rs b/rust/cloud-storage/last_online_tracker/src/domain.rs
new file mode 100644
index 0000000000..6fb7cc3f99
--- /dev/null
+++ b/rust/cloud-storage/last_online_tracker/src/domain.rs
@@ -0,0 +1,3 @@
+pub mod models;
+pub mod ports;
+pub mod services;
diff --git a/rust/cloud-storage/last_online_tracker/src/domain/models.rs b/rust/cloud-storage/last_online_tracker/src/domain/models.rs
new file mode 100644
index 0000000000..8b13789179
--- /dev/null
+++ b/rust/cloud-storage/last_online_tracker/src/domain/models.rs
@@ -0,0 +1 @@
+
diff --git a/rust/cloud-storage/last_online_tracker/src/domain/ports.rs b/rust/cloud-storage/last_online_tracker/src/domain/ports.rs
new file mode 100644
index 0000000000..97a493efa5
--- /dev/null
+++ b/rust/cloud-storage/last_online_tracker/src/domain/ports.rs
@@ -0,0 +1,20 @@
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use rootcause::Report;
+
+pub trait SystemTime: Send + Sync + 'static {
+ fn now(&self) -> DateTime<Utc>;
+}
+
+pub trait LastOnlineRepo: Send + Sync + 'static {
+ fn set_last_online(
+ &self,
+ user: MacroUserIdStr<'_>,
+ now: DateTime<Utc>,
+ ) -> impl Future<Output = Result<(), Report>> + Send;
+
+ fn get_last_online(
+ &self,
+ user: MacroUserIdStr<'_>,
+ ) -> impl Future<Output = Result<Option<DateTime<Utc>>, Report>> + Send;
+}
diff --git a/rust/cloud-storage/last_online_tracker/src/domain/services.rs b/rust/cloud-storage/last_online_tracker/src/domain/services.rs
new file mode 100644
index 0000000000..33beafc61b
--- /dev/null
+++ b/rust/cloud-storage/last_online_tracker/src/domain/services.rs
@@ -0,0 +1,44 @@
+use crate::domain::ports::{LastOnlineRepo, SystemTime};
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use rootcause::Report;
+use std::time::Duration;
+
+#[cfg(test)]
+mod test;
+
+pub struct LastOnlineService<T, R> {
+ time: T,
+ repo: R,
+}
+
+impl<T: SystemTime, R: LastOnlineRepo> LastOnlineService<T, R> {
+ pub fn new(time: T, repo: R) -> Self {
+ LastOnlineService { time, repo }
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ pub async fn record_last_online(&self, user: MacroUserIdStr<'_>) -> Result<(), Report> {
+ let now = self.time.now();
+ self.repo.set_last_online(user, now).await
+ }
+
+ pub async fn get_last_online(
+ &self,
+ user: MacroUserIdStr<'_>,
+ ) -> Result<Option<DateTime<Utc>>, Report> {
+ self.repo.get_last_online(user).await
+ }
+
+ pub async fn time_since_last_online(
+ &self,
+ user: MacroUserIdStr<'_>,
+ ) -> Result<Option<Duration>, Report> {
+ let last = self.get_last_online(user).await?;
+ let now = self.time.now();
+
+ Ok(last
+ .map(|time| now.signed_duration_since(time).to_std())
+ .transpose()?)
+ }
+}
diff --git a/rust/cloud-storage/last_online_tracker/src/domain/services/test.rs b/rust/cloud-storage/last_online_tracker/src/domain/services/test.rs
new file mode 100644
index 0000000000..c1bded29a0
--- /dev/null
+++ b/rust/cloud-storage/last_online_tracker/src/domain/services/test.rs
@@ -0,0 +1,200 @@
+use super::*;
+use chrono::TimeZone;
+use macro_user_id::cowlike::CowLike;
+use macro_user_id::user_id::MacroUserIdStr;
+use std::collections::HashMap;
+use std::sync::Mutex;
+
+struct MockTime {
+ time: DateTime<Utc>,
+}
+
+impl MockTime {
+ fn new(time: DateTime<Utc>) -> Self {
+ MockTime { time }
+ }
+}
+
+impl SystemTime for MockTime {
+ fn now(&self) -> DateTime<Utc> {
+ self.time
+ }
+}
+
+struct MockRepo {
+ data: Mutex<HashMap<String, DateTime<Utc>>>,
+}
+
+impl MockRepo {
+ fn new() -> Self {
+ MockRepo {
+ data: Mutex::new(HashMap::new()),
+ }
+ }
+
+ fn with_data(data: HashMap<String, DateTime<Utc>>) -> Self {
+ MockRepo {
+ data: Mutex::new(data),
+ }
+ }
+}
+
+impl LastOnlineRepo for MockRepo {
+ async fn set_last_online(
+ &self,
+ user: MacroUserIdStr<'_>,
+ now: DateTime<Utc>,
+ ) -> Result<(), Report> {
+ self.data
+ .lock()
+ .unwrap()
+ .insert(user.as_ref().to_string(), now);
+ Ok(())
+ }
+
+ async fn get_last_online(
+ &self,
+ user: MacroUserIdStr<'_>,
+ ) -> Result<Option<DateTime<Utc>>, Report> {
+ Ok(self.data.lock().unwrap().get(user.as_ref()).copied())
+ }
+}
+
+fn test_user() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()
+}
+
+#[tokio::test]
+async fn record_last_online_stores_current_time() {
+ let now = Utc.with_ymd_and_hms(2024, 1, 15, 12, 0, 0).unwrap();
+ let time = MockTime::new(now);
+ let repo = MockRepo::new();
+
+ let service = LastOnlineService::new(time, repo);
+
+ service.record_last_online(test_user()).await.unwrap();
+
+ let stored = service.get_last_online(test_user()).await.unwrap();
+ assert_eq!(stored, Some(now));
+}
+
+#[tokio::test]
+async fn get_last_online_returns_none_for_unknown_user() {
+ let now = Utc.with_ymd_and_hms(2024, 1, 15, 12, 0, 0).unwrap();
+ let time = MockTime::new(now);
+ let repo = MockRepo::new();
+
+ let service = LastOnlineService::new(time, repo);
+
+ let result = service.get_last_online(test_user()).await.unwrap();
+ assert_eq!(result, None);
+}
+
+#[tokio::test]
+async fn get_last_online_returns_stored_time() {
+ let stored_time = Utc.with_ymd_and_hms(2024, 1, 15, 10, 0, 0).unwrap();
+ let now = Utc.with_ymd_and_hms(2024, 1, 15, 12, 0, 0).unwrap();
+
+ let mut data = HashMap::new();
+ data.insert("macro|[email protected]".to_string(), stored_time);
+
+ let time = MockTime::new(now);
+ let repo = MockRepo::with_data(data);
+
+ let service = LastOnlineService::new(time, repo);
+
+ let result = service.get_last_online(test_user()).await.unwrap();
+ assert_eq!(result, Some(stored_time));
+}
+
+#[tokio::test]
+async fn time_since_last_online_returns_none_for_unknown_user() {
+ let now = Utc.with_ymd_and_hms(2024, 1, 15, 12, 0, 0).unwrap();
+ let time = MockTime::new(now);
+ let repo = MockRepo::new();
+
+ let service = LastOnlineService::new(time, repo);
+
+ let result = service.time_since_last_online(test_user()).await.unwrap();
+ assert_eq!(result, None);
+}
+
+#[tokio::test]
+async fn time_since_last_online_returns_duration() {
+ let stored_time = Utc.with_ymd_and_hms(2024, 1, 15, 10, 0, 0).unwrap();
+ let now = Utc.with_ymd_and_hms(2024, 1, 15, 12, 0, 0).unwrap();
+
+ let mut data = HashMap::new();
+ data.insert("macro|[email protected]".to_string(), stored_time);
+
+ let time = MockTime::new(now);
+ let repo = MockRepo::with_data(data);
+
+ let service = LastOnlineService::new(time, repo);
+
+ let result = service.time_since_last_online(test_user()).await.unwrap();
+ assert_eq!(result, Some(Duration::from_secs(2 * 60 * 60))); // 2 hours
+}
+
+#[tokio::test]
+async fn time_since_last_online_handles_just_now() {
+ let now = Utc.with_ymd_and_hms(2024, 1, 15, 12, 0, 0).unwrap();
+
+ let mut data = HashMap::new();
+ data.insert("macro|[email protected]".to_string(), now);
+
+ let time = MockTime::new(now);
+ let repo = MockRepo::with_data(data);
+
+ let service = LastOnlineService::new(time, repo);
+
+ let result = service.time_since_last_online(test_user()).await.unwrap();
+ assert_eq!(result, Some(Duration::from_secs(0)));
+}
+
+#[tokio::test]
+async fn record_updates_existing_last_online() {
+ let first_time = Utc.with_ymd_and_hms(2024, 1, 15, 10, 0, 0).unwrap();
+ let second_time = Utc.with_ymd_and_hms(2024, 1, 15, 12, 0, 0).unwrap();
+
+ let mut data = HashMap::new();
+ data.insert("macro|[email protected]".to_string(), first_time);
+
+ let time = MockTime::new(second_time);
+ let repo = MockRepo::with_data(data);
+
+ let service = LastOnlineService::new(time, repo);
+
+ // Verify initial value
+ let initial = service.get_last_online(test_user()).await.unwrap();
+ assert_eq!(initial, Some(first_time));
+
+ // Record new time
+ service.record_last_online(test_user()).await.unwrap();
+
+ // Verify updated value
+ let updated = service.get_last_online(test_user()).await.unwrap();
+ assert_eq!(updated, Some(second_time));
+}
+
+#[tokio::test]
+async fn multiple_users_tracked_independently() {
+ let now = Utc.with_ymd_and_hms(2024, 1, 15, 12, 0, 0).unwrap();
+ let time = MockTime::new(now);
+ let repo = MockRepo::new();
+
+ let service = LastOnlineService::new(time, repo);
+
+ let user1 = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ let user2 = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+
+ service.record_last_online(user1.copied()).await.unwrap();
+
+ // user1 should have a record
+ let result1 = service.get_last_online(user1.copied()).await.unwrap();
+ assert_eq!(result1, Some(now));
+
+ // user2 should not have a record
+ let result2 = service.get_last_online(user2).await.unwrap();
+ assert_eq!(result2, None);
+}
diff --git a/rust/cloud-storage/last_online_tracker/src/inbound.rs b/rust/cloud-storage/last_online_tracker/src/inbound.rs
new file mode 100644
index 0000000000..0e34611404
--- /dev/null
+++ b/rust/cloud-storage/last_online_tracker/src/inbound.rs
@@ -0,0 +1,50 @@
+use macro_user_id::user_id::MacroUserIdStr;
+use tokio::task::JoinHandle;
+
+use crate::domain::{
+ ports::{LastOnlineRepo, SystemTime},
+ services::LastOnlineService,
+};
+
+pub struct LastOnlineWorker {
+ tx: tokio::sync::mpsc::Sender<MacroUserIdStr<'static>>,
+ #[expect(dead_code)]
+ handle: JoinHandle<()>,
+}
+
+pub struct RecordOnDrop {
+ val: MacroUserIdStr<'static>,
+ tx: tokio::sync::mpsc::Sender<MacroUserIdStr<'static>>,
+}
+
+impl Drop for RecordOnDrop {
+ fn drop(&mut self) {
+ if let Err(e) = self.tx.try_send(self.val.clone()) {
+ tracing::error!("{e:?}");
+ }
+ }
+}
+
+impl LastOnlineWorker {
+ pub fn new<T: SystemTime, R: LastOnlineRepo>(service: LastOnlineService<T, R>) -> Self {
+ let (tx, mut rx) = tokio::sync::mpsc::channel(100);
+
+ let handle = tokio::task::spawn(async move {
+ while let Some(user) = rx.recv().await {
+ let _ = service.record_last_online(user).await;
+ }
+ });
+
+ LastOnlineWorker { tx, handle }
+ }
+
+ /// returns a guard which records the users online time during creation and also during drop
+ pub fn new_guard(&self, user: MacroUserIdStr<'static>) -> RecordOnDrop {
+ let tx = self.tx.clone();
+ if let Err(e) = tx.try_send(user.clone()) {
+ tracing::error!("{e:?}");
+ }
+
+ RecordOnDrop { val: user, tx }
+ }
+}
diff --git a/rust/cloud-storage/last_online_tracker/src/lib.rs b/rust/cloud-storage/last_online_tracker/src/lib.rs
new file mode 100644
index 0000000000..a65f027d93
--- /dev/null
+++ b/rust/cloud-storage/last_online_tracker/src/lib.rs
@@ -0,0 +1,3 @@
+pub mod domain;
+pub mod inbound;
+pub mod outbound;
diff --git a/rust/cloud-storage/last_online_tracker/src/outbound.rs b/rust/cloud-storage/last_online_tracker/src/outbound.rs
new file mode 100644
index 0000000000..213a8243e3
--- /dev/null
+++ b/rust/cloud-storage/last_online_tracker/src/outbound.rs
@@ -0,0 +1,4 @@
+//! Outbound adapters for the last_online_tracker domain
+
+pub mod redis;
+pub mod time;
diff --git a/rust/cloud-storage/last_online_tracker/src/outbound/redis.rs b/rust/cloud-storage/last_online_tracker/src/outbound/redis.rs
new file mode 100644
index 0000000000..8c80fc7a48
--- /dev/null
+++ b/rust/cloud-storage/last_online_tracker/src/outbound/redis.rs
@@ -0,0 +1,54 @@
+//! Redis implementation of [LastOnlineRepo]
+
+use crate::domain::ports::LastOnlineRepo;
+use chrono::{DateTime, Utc};
+use macro_user_id::user_id::MacroUserIdStr;
+use redis::AsyncCommands;
+use redis::aio::MultiplexedConnection;
+use rootcause::Report;
+
+/// TTL for last_online keys: 30 days
+const TTL_SECONDS: u64 = 30 * 24 * 60 * 60;
+
+/// Redis-backed implementation of [LastOnlineRepo]
+pub struct RedisLastOnlineRepo {
+ conn: MultiplexedConnection,
+}
+
+impl RedisLastOnlineRepo {
+ /// Create a new [RedisLastOnlineRepo] with the given Redis connection
+ pub fn new(conn: MultiplexedConnection) -> Self {
+ Self { conn }
+ }
+
+ fn key(user: &MacroUserIdStr<'_>) -> String {
+ format!("last_online:{}", user.as_ref())
+ }
+}
+
+impl LastOnlineRepo for RedisLastOnlineRepo {
+ async fn set_last_online(
+ &self,
+ user: MacroUserIdStr<'_>,
+ now: DateTime<Utc>,
+ ) -> Result<(), Report> {
+ let mut conn = self.conn.clone();
+ let key = Self::key(&user);
+ let value = now.to_rfc3339();
+ conn.set_ex::<_, _, ()>(&key, value, TTL_SECONDS).await?;
+ Ok(())
+ }
+
+ async fn get_last_online(
+ &self,
+ user: MacroUserIdStr<'_>,
+ ) -> Result<Option<DateTime<Utc>>, Report> {
+ let mut conn = self.conn.clone();
+ let key = Self::key(&user);
+ let value: Option<String> = conn.get(&key).await?;
+ match value {
+ Some(s) => Ok(Some(DateTime::parse_from_rfc3339(&s)?.with_timezone(&Utc))),
+ None => Ok(None),
+ }
+ }
+}
diff --git a/rust/cloud-storage/last_online_tracker/src/outbound/time.rs b/rust/cloud-storage/last_online_tracker/src/outbound/time.rs
new file mode 100644
index 0000000000..bec3195144
--- /dev/null
+++ b/rust/cloud-storage/last_online_tracker/src/outbound/time.rs
@@ -0,0 +1,13 @@
+//! Default implementation of [SystemTime]
+
+use crate::domain::ports::SystemTime;
+use chrono::{DateTime, Utc};
+
+/// Default implementation that returns the current UTC time
+pub struct DefaultTime;
+
+impl SystemTime for DefaultTime {
+ fn now(&self) -> DateTime<Utc> {
+ Utc::now()
+ }
+}
diff --git a/rust/cloud-storage/notification/src/domain/models/email_notification_digest/ports.rs b/rust/cloud-storage/notification/src/domain/models/email_notification_digest/ports.rs
index e930a2e6f3..ac4b7ee66e 100644
--- a/rust/cloud-storage/notification/src/domain/models/email_notification_digest/ports.rs
+++ b/rust/cloud-storage/notification/src/domain/models/email_notification_digest/ports.rs
@@ -1,7 +1,6 @@
-use std::time::Duration;
-
use macro_user_id::user_id::MacroUserIdStr;
use rootcause::Report;
+use std::time::Duration;
/// trait for checking whether or not a user exists
pub trait UserExistenceChecker: Send + Sync + 'static {
diff --git a/rust/cloud-storage/notification/src/domain/service/ingress.rs b/rust/cloud-storage/notification/src/domain/service/ingress.rs
index 5e6ee2e3ae..b81f336124 100644
--- a/rust/cloud-storage/notification/src/domain/service/ingress.rs
+++ b/rust/cloud-storage/notification/src/domain/service/ingress.rs
@@ -199,7 +199,7 @@ where
&self,
request: SendNotificationRequest<'a, T, U>,
) -> Result<Option<NotificationResult<'a>>, Report<SendNotificationError>> {
- let request = self
+ let mut request = self
.filter_recipients(request)
.await
.context(SendNotificationError::Other)?;
@@ -208,9 +208,6 @@ where
return Ok(None);
}
- // Build queue messages first so we can extract the APNS collapse key
- let mut request = request;
-
let notification_id = Uuid::now_v7();
let (queue_messages, apns_collapse_key) = self
.build_queue_message(notification_id, &mut request)
diff --git a/rust/cloud-storage/notification/src/outbound.rs b/rust/cloud-storage/notification/src/outbound.rs
index 223a6436d8..c2b244c0e4 100644
--- a/rust/cloud-storage/notification/src/outbound.rs
+++ b/rust/cloud-storage/notification/src/outbound.rs
@@ -5,7 +5,9 @@
pub mod email;
pub mod mobile;
+pub mod push_notification_checker;
pub mod queue;
pub mod rate_limit;
pub mod repository;
+pub mod user_existence_checker;
pub mod websocket;
diff --git a/rust/cloud-storage/notification/src/outbound/push_notification_checker.rs b/rust/cloud-storage/notification/src/outbound/push_notification_checker.rs
new file mode 100644
index 0000000000..5f2ee15110
--- /dev/null
+++ b/rust/cloud-storage/notification/src/outbound/push_notification_checker.rs
@@ -0,0 +1,41 @@
+//! This module provides an implementation of [PushNotificationChecker] which is a wrapper over some T which is a [NotificationRepository]
+//!
+use crate::domain::{
+ models::email_notification_digest::ports::PushNotificationChecker,
+ ports::NotificationRepository,
+};
+use cowlike::CowLike;
+
+/// Struct which implements [PushNotificationChecker] for some T where T is [NotificationRepository]
+pub struct PushNotificationCheckerImpl<T> {
+ inner: T,
+}
+
+impl<T: NotificationRepository> PushNotificationCheckerImpl<T> {
+ /// create a new instance of self
+ pub fn new(repo: T) -> Self {
+ PushNotificationCheckerImpl { inner: repo }
+ }
+}
+
+impl<T: NotificationRepository> PushNotificationChecker for PushNotificationCheckerImpl<T> {
+ async fn push_notification_enabled<'a>(
+ &self,
+ user: macro_user_id::user_id::MacroUserIdStr<'a>,
+ ) -> Result<bool, rootcause::Report> {
+ // a user with push notifications enabled is currently defined as someone
+ // who does not have notifications muted and who has registered device endpoints.
+ // This is subject to change though
+ let res = self.inner.get_muted_users(&[user.copied()]).await?;
+
+ if !res.is_empty() {
+ return Ok(false);
+ }
+ let endpoints = self.inner.get_device_endpoints(&[user.copied()]).await?;
+
+ Ok(match endpoints.len() {
+ 0 => false,
+ 1.. => true,
+ })
+ }
+}
diff --git a/rust/cloud-storage/notification/src/outbound/user_existence_checker.rs b/rust/cloud-storage/notification/src/outbound/user_existence_checker.rs
new file mode 100644
index 0000000000..7af5a74c6c
--- /dev/null
+++ b/rust/cloud-storage/notification/src/outbound/user_existence_checker.rs
@@ -0,0 +1,39 @@
+//! Implementation of [UserExistenceChecker] that queries the database.
+
+use crate::domain::models::email_notification_digest::ports::UserExistenceChecker;
+use macro_user_id::user_id::MacroUserIdStr;
+use rootcause::Report;
+use sqlx::PgPool;
+
+/// Database-backed implementation of [UserExistenceChecker].
+///
+/// Checks if a user exists by querying the User table.
+pub struct DbUserExistenceChecker {
+ db: PgPool,
+}
+
+impl DbUserExistenceChecker {
+ /// Create a new [DbUserExistenceChecker] with the given database pool.
+ pub fn new(db: PgPool) -> Self {
+ Self { db }
+ }
+}
+
+impl UserExistenceChecker for DbUserExistenceChecker {
+ async fn user_exists<'a>(&self, id: MacroUserIdStr<'a>) -> Result<bool, Report> {
+ let email = id.email_part();
+
+ let result = sqlx::query!(
+ r#"
+ SELECT id
+ FROM "User"
+ WHERE email = $1
+ "#,
+ email.as_ref()
+ )
+ .fetch_optional(&self.db)
+ .await?;
+
+ Ok(result.is_some())
+ }
+}