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
tooling(notif): add digest sandbox cli (#1686)
Sean Ayeccfa5264d4dc
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 02f9db13dc..232e5ad314 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -1464,7 +1464,7 @@ version = "0.71.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3"dependencies = [- "bitflags",+ "bitflags 2.8.0","cexpr","clang-sys","itertools 0.12.1",@@ -1499,6 +1499,12 @@ version = "0.10.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "dc827186963e592360843fb5ba4b973e145841266c1357f7180c43526f2e5b61"+[[package]]+name = "bitflags"+version = "1.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"+[[package]]name = "bitflags"version = "2.8.0"@@ -2315,6 +2321,31 @@ version = "0.8.21"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"+[[package]]+name = "crossterm"+version = "0.25.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e64e6c0fbe2c17357405f7c758c1ef960fce08bdfb2c03d88d2a18d7e09c4b67"+dependencies = [+ "bitflags 1.3.2",+ "crossterm_winapi",+ "libc",+ "mio 0.8.11",+ "parking_lot",+ "signal-hook",+ "signal-hook-mio",+ "winapi",+]++[[package]]+name = "crossterm_winapi"+version = "0.9.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "acdd7c62a3665c7f6830a51635d9ac9b23ed385797f70a83bb8bafe9c572ab2b"+dependencies = [+ "winapi",+]+[[package]]name = "crunchy"version = "0.2.3"@@ -3960,6 +3991,15 @@ dependencies = ["slab",]+[[package]]+name = "fuzzy-matcher"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "54614a3312934d066701a80f20f15fa3b56d67ac7722b39eea5b4c9dd1d66c94"+dependencies = [+ "thread_local",+]+[[package]]name = "fxhash"version = "0.2.1"@@ -4832,6 +4872,23 @@ dependencies = ["generic-array",]+[[package]]+name = "inquire"+version = "0.7.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fddf93031af70e75410a2511ec04d49e758ed2f26dad3404a934e0fb45cc12a"+dependencies = [+ "bitflags 2.8.0",+ "crossterm",+ "dyn-clone",+ "fuzzy-matcher",+ "fxhash",+ "newline-converter",+ "once_cell",+ "unicode-segmentation",+ "unicode-width 0.1.14",+]+[[package]]name = "instant"version = "0.1.13"@@ -5185,7 +5242,7 @@ version = "2.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "26a24302899fc10d7a785ea5d810ba3c41faa37d0f77847d9f0b16195d3c7a6c"dependencies = [- "bitflags",+ "bitflags 2.8.0","cfg-if","cssparser 0.35.0","encoding_rs",@@ -5717,6 +5774,18 @@ dependencies = ["simd-adler32",]+[[package]]+name = "mio"+version = "0.8.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a4a650543ca06a924e8b371db273b2756685faae30f8487da1b56505a8f78b0c"+dependencies = [+ "libc",+ "log",+ "wasi 0.11.0+wasi-snapshot-preview1",+ "windows-sys 0.48.0",+]+[[package]]name = "mio"version = "1.0.3"@@ -6142,13 +6211,22 @@ version = "1.0.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086"+[[package]]+name = "newline-converter"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47b6b097ecb1cbfed438542d16e84fd7ad9b0c76c8a65b7f9039212a3d14dc7f"+dependencies = [+ "unicode-segmentation",+]+[[package]]name = "nix"version = "0.29.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"dependencies = [- "bitflags",+ "bitflags 2.8.0","cfg-if","cfg_aliases","libc",@@ -6243,6 +6321,31 @@ dependencies = ["uuid",]+[[package]]+name = "notification_sandbox"+version = "0.1.0"+dependencies = [+ "aws-sdk-sesv2",+ "aws-sdk-sns",+ "chrono",+ "either",+ "inquire",+ "macro_aws_config",+ "macro_user_id",+ "model-entity",+ "models_pagination",+ "notification",+ "redis",+ "rootcause",+ "serde",+ "serde_json",+ "sqlx",+ "tokio",+ "tracing",+ "tracing-subscriber",+ "uuid",+]+[[package]]name = "notification_service"version = "0.1.0"@@ -6464,7 +6567,7 @@ version = "0.10.73"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8505734d46c8ab1e19a1dce3aef597ad87dcb4c37e7188231769bd6bd51cebf8"dependencies = [- "bitflags",+ "bitflags 2.8.0","cfg-if","foreign-types","libc",@@ -6730,7 +6833,7 @@ version = "0.8.30"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2773a939ec2c736640f5f2e62a325c2e1a997d694961c50f17cadfb4c8682e84"dependencies = [- "bitflags",+ "bitflags 2.8.0","bytemuck","bytes","chrono",@@ -6955,7 +7058,7 @@ version = "0.18.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "97baced388464909d42d89643fe4361939af9b7ce7a31ee32a168f832a70f2a0"dependencies = [- "bitflags",+ "bitflags 2.8.0","crc32fast","fdeflate","flate2",@@ -7507,7 +7610,7 @@ version = "0.5.8"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "03a862b389f93e68874fbf580b9de08dd02facb9a788ebadaf4a3fd33cf58834"dependencies = [- "bitflags",+ "bitflags 2.8.0",][[package]]@@ -7824,7 +7927,7 @@ version = "1.0.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d97817398dd4bb2e6da002002db259209759911da105da92bec29ccb12cf58bf"dependencies = [- "bitflags",+ "bitflags 2.8.0","errno","libc","linux-raw-sys",@@ -8251,7 +8354,7 @@ version = "2.11.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"dependencies = [- "bitflags",+ "bitflags 2.8.0","core-foundation 0.9.4","core-foundation-sys","libc",@@ -8264,7 +8367,7 @@ version = "3.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "271720403f46ca04f7ba6f55d438f8bd878d6b8ca0a1046e8228c4145bcbb316"dependencies = [- "bitflags",+ "bitflags 2.8.0","core-foundation 0.10.0","core-foundation-sys","libc",@@ -8320,7 +8423,7 @@ version = "0.25.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4eb30575f3638fc8f6815f448d50cb1a2e255b0897985c8c59f4d37b72a07b06"dependencies = [- "bitflags",+ "bitflags 2.8.0","cssparser 0.31.2","derive_more","fxhash",@@ -8339,7 +8442,7 @@ version = "0.27.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "5b75e048a93e14929e68e37b82e207db957cbb368375a80ed3ca28ac75080856"dependencies = [- "bitflags",+ "bitflags 2.8.0","cssparser 0.35.0","derive_more","fxhash",@@ -8636,6 +8739,27 @@ version = "1.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"+[[package]]+name = "signal-hook"+version = "0.3.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2"+dependencies = [+ "libc",+ "signal-hook-registry",+]++[[package]]+name = "signal-hook-mio"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b75a19a7a740b25bc7944bdee6172368f988763b744e3d4dfe753f6b4ece40cc"+dependencies = [+ "libc",+ "mio 0.8.11",+ "signal-hook",+]+[[package]]name = "signal-hook-registry"version = "1.4.2"@@ -8966,7 +9090,7 @@ checksum = "aa003f0038df784eb8fecbbac13affe3da23b45194bd57dba231c8f48199c526"dependencies = ["atoi","base64 0.22.1",- "bitflags",+ "bitflags 2.8.0","byteorder","bytes","chrono",@@ -9010,7 +9134,7 @@ checksum = "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46"dependencies = ["atoi","base64 0.22.1",- "bitflags",+ "bitflags 2.8.0","byteorder","chrono","crc",@@ -9301,7 +9425,7 @@ version = "0.6.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b"dependencies = [- "bitflags",+ "bitflags 2.8.0","core-foundation 0.9.4","system-configuration-sys",]@@ -9552,7 +9676,7 @@ checksum = "ff360e02eab121e0bc37a2d3b4d4dc622e6eda3a8e5253d5435ecf5bd4c68408"dependencies = ["bytes","libc",- "mio",+ "mio 1.0.3","parking_lot","pin-project-lite","signal-hook-registry",@@ -9744,7 +9868,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2"dependencies = ["async-compression",- "bitflags",+ "bitflags 2.8.0","bytes","futures-core","futures-util",@@ -10487,6 +10611,22 @@ dependencies = ["wasite",]+[[package]]+name = "winapi"+version = "0.3.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419"+dependencies = [+ "winapi-i686-pc-windows-gnu",+ "winapi-x86_64-pc-windows-gnu",+]++[[package]]+name = "winapi-i686-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"+[[package]]name = "winapi-util"version = "0.1.9"@@ -10496,6 +10636,12 @@ dependencies = ["windows-sys 0.59.0",]+[[package]]+name = "winapi-x86_64-pc-windows-gnu"+version = "0.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"+[[package]]name = "windows-core"version = "0.52.0"@@ -10783,7 +10929,7 @@ version = "0.33.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3268f3d866458b787f390cf61f4bbb563b922d091359f9608842999eaee3943c"dependencies = [- "bitflags",+ "bitflags 2.8.0",][[package]]diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex 227a152368..c1cc29c330 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -84,6 +84,7 @@ members = ["non_empty","notification","notification_db_client",+ "notification_sandbox","notification_service","notification_service_client","opensearch_client",@@ -154,6 +155,7 @@ dashmap = "6.1.0"dotenvy = "0.15.7"ego-tree = "0.6.2"either = "1"+inquire = "0.7"futures = "0.3.31"hex = "0.4.3"http = "1"diff --git a/rust/cloud-storage/deny.toml b/rust/cloud-storage/deny.tomlindex 75917be48b..003272025e 100644--- a/rust/cloud-storage/deny.toml+++ b/rust/cloud-storage/deny.toml@@ -187,6 +187,7 @@ deny = [{ crate = "tracing-subscriber", wrappers = ["lambda_runtime_api_client", # External crate allowed to use tracing-subscriber"macro_entrypoint",+ "notification_sandbox", # This is not production code its just tooling"tracing-opentelemetry", # OpenTelemetry integration requires tracing-subscriber"tracing-panic", # External crate allowed to use tracing-subscriber"tracing-tree",diff --git a/rust/cloud-storage/hx b/rust/cloud-storage/hxnew file mode 100644index 0000000000..6f0fd4c396--- /dev/null+++ b/rust/cloud-storage/hx@@ -0,0 +1 @@+advisories ok, bans FAILED, licenses ok, sources okdiff --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.rsindex e3427beb47..fafcebead0 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@@ -25,15 +25,28 @@ pub struct DigestBatch {/// Result of attempting to claim a digest batch.#[derive(Debug)]-pub enum ClaimResult {+pub enum ClaimResult<T> {/// A digest batch is ready and was claimed.- Ready(DigestBatch),+ Ready(T),/// No digests are pending.Empty,/// Digests are pending but none are ready yet. Contains duration until the next one is ready.Wait(Duration),}+impl<T> ClaimResult<T> {+ pub(crate) fn map<F, U>(self, f: F) -> ClaimResult<U>+ where+ F: FnOnce(T) -> U,+ {+ match self {+ ClaimResult::Ready(v) => ClaimResult::Ready(f(v)),+ ClaimResult::Empty => ClaimResult::Empty,+ ClaimResult::Wait(duration) => ClaimResult::Wait(duration),+ }+ }+}+/// Trait for batching notifications into digests for delayed email delivery.////// Implementations should handle:@@ -60,7 +73,9 @@ pub trait DigestBatcher: Send + Sync + 'static {////// The claim is atomic - only one caller will receive a given user's digest/// even with concurrent workers.- fn claim_ready_digest(&self) -> impl Future<Output = Result<ClaimResult, Report>> + Send;+ fn claim_ready_digest(+ &self,+ ) -> impl Future<Output = Result<ClaimResult<DigestBatch>, Report>> + Send;}/// trait for checking whether or not a user has push notifications enableddiff --git a/rust/cloud-storage/notification/src/domain/ports.rs b/rust/cloud-storage/notification/src/domain/ports.rsindex 0bf9b000bb..08e01f0736 100644--- a/rust/cloud-storage/notification/src/domain/ports.rs+++ b/rust/cloud-storage/notification/src/domain/ports.rs@@ -15,12 +15,12 @@ use uuid::Uuid;use models_pagination::{CreatedAt, Query};-use crate::domain::models::NotificationExtEmail;-use crate::domain::models::email_notification_digest::ports::DigestBatch;+use crate::domain::models::email_notification_digest::ports::{ClaimResult, DigestBatch};use crate::domain::models::{- DeviceEndpoint, Notification, NotificationIdAndCollapseKey, RateLimitConfig, RateLimitKey,- RateLimitResult, SendNotificationRequestBuilder, UserNotificationRow, android::FCMMessage,- apple::APNSPushNotification, mobile::MessageAttributes,+ DeviceEndpoint, Notification, NotificationExtEmail, NotificationIdAndCollapseKey,+ RateLimitConfig, RateLimitKey, RateLimitResult, SendNotificationRequestBuilder,+ UserNotificationRow, android::FCMMessage, apple::APNSPushNotification,+ mobile::MessageAttributes,};/// Port for sending mobile push notifications (iOS/Android via SNS).@@ -229,7 +229,7 @@ pub trait NotificationEgress: Send + Sync + 'static {fn poll_email_digests<T: NotificationExtEmail>(&self,f: fn(DigestBatch) -> Result<T, Report>,- ) -> impl Future<Output = Result<(), Report>> + Send;+ ) -> impl Future<Output = Result<ClaimResult<()>, Report>> + Send;}/// Port for deleting a device registration from the database by its SNS endpoint ARN.diff --git a/rust/cloud-storage/notification/src/domain/service/egress.rs b/rust/cloud-storage/notification/src/domain/service/egress.rsindex efa15e56dd..86af465b51 100644--- a/rust/cloud-storage/notification/src/domain/service/egress.rs+++ b/rust/cloud-storage/notification/src/domain/service/egress.rs@@ -263,10 +263,10 @@ whereasync fn poll_email_digests<T: NotificationExtEmail>(&self,f: fn(DigestBatch) -> Result<T, Report>,- ) -> Result<(), Report> {+ ) -> Result<ClaimResult<()>, Report> {let batch = match self.digest_batcher.claim_ready_digest().await? {ClaimResult::Ready(batch) => batch,- ClaimResult::Empty | ClaimResult::Wait(_) => return Ok(()),+ v @ ClaimResult::Empty | v @ ClaimResult::Wait(_) => return Ok(v.map(|_| ())),};let recipient = batch.user_id.clone();@@ -283,6 +283,6 @@ wheretracing::error!(error=?e, "failed to queue digest email");})?;- Ok(())+ Ok(ClaimResult::Ready(()))}}diff --git a/rust/cloud-storage/notification/src/domain/service/test.rs b/rust/cloud-storage/notification/src/domain/service/test.rsindex 850eb4219d..5c6ee53e84 100644--- a/rust/cloud-storage/notification/src/domain/service/test.rs+++ b/rust/cloud-storage/notification/src/domain/service/test.rs@@ -972,7 +972,7 @@ impl DigestBatcher for MockDigestBatcher {Ok(())}- async fn claim_ready_digest(&self) -> Result<ClaimResult, Report> {+ async fn claim_ready_digest(&self) -> Result<ClaimResult<DigestBatch>, Report> {Ok(ClaimResult::Empty)}}@@ -1540,7 +1540,7 @@ impl DigestBatcher for ReadyDigestBatcher {Ok(())}- async fn claim_ready_digest(&self) -> Result<ClaimResult, Report> {+ async fn claim_ready_digest(&self) -> Result<ClaimResult<DigestBatch>, Report> {match self.batch.lock().unwrap().take() {Some(batch) => Ok(ClaimResult::Ready(batch)),None => Ok(ClaimResult::Empty),diff --git a/rust/cloud-storage/notification/src/outbound/digest_batcher.rs b/rust/cloud-storage/notification/src/outbound/digest_batcher.rsindex 7a8c05c3c3..b8b578bf49 100644--- a/rust/cloud-storage/notification/src/outbound/digest_batcher.rs+++ b/rust/cloud-storage/notification/src/outbound/digest_batcher.rs@@ -109,7 +109,7 @@ impl DigestBatcher for RedisDigestBatcher {Ok(())}- async fn claim_ready_digest(&self) -> Result<ClaimResult, Report> {+ async fn claim_ready_digest(&self) -> Result<ClaimResult<DigestBatch>, Report> {let mut conn = self.conn.clone();let now = Utc::now().timestamp();let pending_users_key = self.pending_users_key();diff --git a/rust/cloud-storage/notification/src/outbound/digest_batcher/test.rs b/rust/cloud-storage/notification/src/outbound/digest_batcher/test.rsindex 0f8233640e..f0a27655a0 100644--- a/rust/cloud-storage/notification/src/outbound/digest_batcher/test.rs+++ b/rust/cloud-storage/notification/src/outbound/digest_batcher/test.rs@@ -1,5 +1,5 @@use super::*;-use crate::domain::models::{Notification, RateLimitConfig, RateLimitKey, TaggedContent};+use crate::domain::models::{Notification, TaggedContent};use model_entity::EntityType;use redis::AsyncCommands;use serde::{Deserialize, Serialize};diff --git a/rust/cloud-storage/notification_sandbox/Cargo.toml b/rust/cloud-storage/notification_sandbox/Cargo.tomlnew file mode 100644index 0000000000..780d71f381--- /dev/null+++ b/rust/cloud-storage/notification_sandbox/Cargo.toml@@ -0,0 +1,26 @@+[package]+edition = "2024"+name = "notification_sandbox"+publish = false+version = "0.1.0"++[dependencies]+aws-sdk-sesv2 = { workspace = true }+aws-sdk-sns = { workspace = true }+chrono = { workspace = true }+either = { workspace = true }+inquire = { workspace = true }+macro_aws_config = { path = "../macro_aws_config" }+macro_user_id = { path = "../macro_user_id" }+model-entity = { path = "../model-entity" }+models_pagination = { path = "../models_pagination" }+notification = { path = "../notification" }+redis = { workspace = true, features = ["aio", "tokio-comp", "tokio-native-tls-comp"] }+rootcause = { workspace = true }+serde = { workspace = true }+serde_json = { workspace = true }+sqlx = { workspace = true }+tokio = { workspace = true, features = ["macros", "rt-multi-thread", "signal", "sync"] }+tracing = { workspace = true }+tracing-subscriber = { workspace = true, features = ["fmt"] }+uuid = { workspace = true }diff --git a/rust/cloud-storage/notification_sandbox/src/adapters/interactive_mobile.rs b/rust/cloud-storage/notification_sandbox/src/adapters/interactive_mobile.rsnew file mode 100644index 0000000000..00d37966e8--- /dev/null+++ b/rust/cloud-storage/notification_sandbox/src/adapters/interactive_mobile.rs@@ -0,0 +1,106 @@+use notification::domain::models::android::FCMMessage;+use notification::domain::models::apple::APNSPushNotification;+use notification::domain::models::mobile::MessageAttributes;+use notification::domain::ports::NotificationSender;+use notification::outbound::mobile::MobilePushAdapter;+use rootcause::Report;+use serde::Serialize;+use tokio::sync::mpsc;++/// A prompt request sent from the background egress task to the foreground.+pub struct PushPromptRequest {+ /// The endpoint ARN being pushed to.+ pub endpoint_arn: String,+ /// Channel to send back whether the push "succeeded".+ pub reply: tokio::sync::oneshot::Sender<bool>,+}++/// Mobile push sender that delegates interactive prompts to the foreground via a channel.+pub struct InteractiveMobileSender {+ /// Sender half — sends prompt requests to the foreground loop.+ pub prompt_tx: mpsc::UnboundedSender<PushPromptRequest>,+}++impl NotificationSender for InteractiveMobileSender {+ async fn send_ios_push_notification<T: Serialize + Send + Sync>(+ &self,+ endpoint_arn: &str,+ _notification: &APNSPushNotification<T>,+ _attributes: &MessageAttributes,+ ) -> Result<String, Report> {+ let (reply_tx, reply_rx) = tokio::sync::oneshot::channel();+ self.prompt_tx+ .send(PushPromptRequest {+ endpoint_arn: endpoint_arn.to_string(),+ reply: reply_tx,+ })+ .map_err(|_| rootcause::report!("foreground prompt channel closed"))?;++ let succeeded = reply_rx+ .await+ .map_err(|_| rootcause::report!("foreground prompt reply dropped"))?;++ if succeeded {+ let msg_id = format!("mock-msg-{}", uuid::Uuid::new_v4());+ Ok(msg_id)+ } else {+ rootcause::bail!("Simulated push failure for {endpoint_arn}");+ }+ }++ async fn send_android_push_notification<T: Serialize + Send + Sync>(+ &self,+ _endpoint_arn: &str,+ _notification: &FCMMessage<T>,+ _attributes: &MessageAttributes,+ ) -> Result<String, Report> {+ let msg_id = format!("mock-msg-{}", uuid::Uuid::new_v4());+ Ok(msg_id)+ }+}++/// Dispatches between interactive (mock) and real SNS mobile push.+pub enum SandboxMobileSender {+ /// Interactive mode: prompts user for success/failure.+ Interactive(InteractiveMobileSender),+ /// Real mode: sends via AWS SNS.+ Real(MobilePushAdapter<aws_sdk_sns::Client>),+}++impl NotificationSender for SandboxMobileSender {+ async fn send_ios_push_notification<T: Serialize + Send + Sync>(+ &self,+ endpoint_arn: &str,+ notification: &APNSPushNotification<T>,+ attributes: &MessageAttributes,+ ) -> Result<String, Report> {+ match self {+ Self::Interactive(m) => {+ m.send_ios_push_notification(endpoint_arn, notification, attributes)+ .await+ }+ Self::Real(r) => {+ r.send_ios_push_notification(endpoint_arn, notification, attributes)+ .await+ }+ }+ }++ async fn send_android_push_notification<T: Serialize + Send + Sync>(+ &self,+ endpoint_arn: &str,+ notification: &FCMMessage<T>,+ attributes: &MessageAttributes,+ ) -> Result<String, Report> {+ match self {+ Self::Interactive(m) => {+ m.send_android_push_notification(endpoint_arn, notification, attributes)+ .await+ }+ Self::Real(r) => {+ r.send_android_push_notification(endpoint_arn, notification, attributes)+ .await+ }+ }+ }+}diff --git a/rust/cloud-storage/notification_sandbox/src/adapters/logging_websocket.rs b/rust/cloud-storage/notification_sandbox/src/adapters/logging_websocket.rsnew file mode 100644index 0000000000..01ec71f354--- /dev/null+++ b/rust/cloud-storage/notification_sandbox/src/adapters/logging_websocket.rs@@ -0,0 +1,24 @@+use std::collections::HashSet;++use macro_user_id::cowlike::CowLike;+use macro_user_id::user_id::MacroUserIdStr;+use notification::domain::ports::WebSocketSender;+use rootcause::Report;+use serde::Serialize;++/// WebSocket sender that logs delivery info instead of sending.+pub struct LoggingWebSocketSender;++impl WebSocketSender for LoggingWebSocketSender {+ async fn send_notifications<'a, T: Serialize + Send + Sync>(+ &self,+ recipients: &[MacroUserIdStr<'a>],+ _notification: &T,+ ) -> Result<HashSet<MacroUserIdStr<'static>>, Report> {+ println!(+ " [egress] WebSocket: delivered to {} recipient(s)",+ recipients.len()+ );+ Ok(recipients.iter().map(|r| r.clone().into_owned()).collect())+ }+}diff --git a/rust/cloud-storage/notification_sandbox/src/adapters/mod.rs b/rust/cloud-storage/notification_sandbox/src/adapters/mod.rsnew file mode 100644index 0000000000..ddf05adbb1--- /dev/null+++ b/rust/cloud-storage/notification_sandbox/src/adapters/mod.rs@@ -0,0 +1,10 @@+/// Interactive mobile push sender for sandbox.+pub mod interactive_mobile;+/// WebSocket sender that logs delivery info.+pub mod logging_websocket;+/// Tokio mpsc-backed notification queue.+pub mod mpsc_queue;+/// Rate limiter that always allows.+pub mod noop_rate_limiter;+/// Notification repository wrapper with sandbox-configured device endpoints.+pub mod sandbox_repository;diff --git a/rust/cloud-storage/notification_sandbox/src/adapters/mpsc_queue.rs b/rust/cloud-storage/notification_sandbox/src/adapters/mpsc_queue.rsnew file mode 100644index 0000000000..293bec77e4--- /dev/null+++ b/rust/cloud-storage/notification_sandbox/src/adapters/mpsc_queue.rs@@ -0,0 +1,75 @@+use std::sync::Arc;++use notification::domain::models::queue_message::{QueueMessage, RawQueueMessage};+use notification::domain::ports::NotificationQueue;+use rootcause::Report;+use serde::Serialize;+use tokio::sync::Mutex;+use tokio::sync::mpsc;++/// In-process notification queue backed by a tokio mpsc channel.+///+/// Both the ingress (publish) and egress (receive) sides share the same channel.+/// Messages are serialized to JSON on publish and deserialized on receive,+/// matching the behavior of the SQS/FileQueue adapters.+pub struct MpscQueue {+ tx: mpsc::UnboundedSender<RawQueueMessage>,+ rx: Arc<Mutex<mpsc::UnboundedReceiver<RawQueueMessage>>>,+}++impl MpscQueue {+ /// Create a new mpsc-backed queue.+ pub fn new() -> Self {+ let (tx, rx) = mpsc::unbounded_channel();+ Self {+ tx,+ rx: Arc::new(Mutex::new(rx)),+ }+ }+}++impl Clone for MpscQueue {+ fn clone(&self) -> Self {+ Self {+ tx: self.tx.clone(),+ rx: self.rx.clone(),+ }+ }+}++impl NotificationQueue for MpscQueue {+ async fn publish<'a, T: Serialize + Send + Sync, U: Serialize + Send + Sync>(+ &self,+ messages: impl Iterator<Item = QueueMessage<'a, T, U>> + Send,+ ) -> Result<(), Report> {+ for message in messages {+ let json = serde_json::to_value(&message)?;+ let body = serde_json::from_value(json)?;+ let raw = RawQueueMessage {+ body,+ receipt_handle: uuid::Uuid::new_v4().to_string(),+ };+ self.tx.send(raw)?;+ }+ Ok(())+ }++ async fn receive_messages(&self) -> Result<Vec<RawQueueMessage>, Report> {+ let mut rx = self.rx.lock().await;+ let mut messages = Vec::new();+ while messages.len() < 10 {+ match rx.try_recv() {+ Ok(msg) => messages.push(msg),+ Err(mpsc::error::TryRecvError::Empty | mpsc::error::TryRecvError::Disconnected) => {+ break;+ }+ }+ }+ Ok(messages)+ }++ async fn delete_message(&self, _receipt_handle: &str) -> Result<(), Report> {+ // No-op: messages are consumed from the channel on receive.+ Ok(())+ }+}diff --git a/rust/cloud-storage/notification_sandbox/src/adapters/noop_rate_limiter.rs b/rust/cloud-storage/notification_sandbox/src/adapters/noop_rate_limiter.rsnew file mode 100644index 0000000000..481544bc44--- /dev/null+++ b/rust/cloud-storage/notification_sandbox/src/adapters/noop_rate_limiter.rs@@ -0,0 +1,16 @@+use notification::domain::models::{RateLimitConfig, RateLimitKey, RateLimitResult};+use notification::domain::ports::RateLimitPort;+use rootcause::Report;++/// Rate limiter that always allows (no-op for sandbox).+pub struct NoOpRateLimiter;++impl RateLimitPort for NoOpRateLimiter {+ async fn check_and_increment(+ &self,+ _key: &RateLimitKey,+ _config: &RateLimitConfig,+ ) -> Result<RateLimitResult, Report> {+ Ok(RateLimitResult::Allowed { current_count: 0 })+ }+}diff --git a/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs b/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rsnew file mode 100644index 0000000000..82ed4681ec--- /dev/null+++ b/rust/cloud-storage/notification_sandbox/src/adapters/sandbox_repository.rs@@ -0,0 +1,166 @@+use std::collections::HashMap;+use std::collections::HashSet;+use std::sync::Arc;++use macro_user_id::user_id::MacroUserIdStr;+use models_pagination::{CreatedAt, Query};+use notification::domain::models::{+ DeviceEndpoint, Notification, NotificationIdAndCollapseKey, SendNotificationRequestBuilder,+ UserNotificationRow,+};+use notification::domain::ports::NotificationRepository;+use notification::outbound::repository::DbNotificationRepository;+use rootcause::Report;+use serde::de::DeserializeOwned;+use sqlx::PgPool;+use uuid::Uuid;++/// Notification repository that wraps the real DB repository but overrides+/// `get_device_endpoints` to return sandbox-configured endpoints.+///+/// This avoids needing real device registration records in the database.+pub struct SandboxNotificationRepository {+ inner: DbNotificationRepository<PgPool>,+ device_endpoints: HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>>,+}++impl SandboxNotificationRepository {+ /// Create a new sandbox repository.+ pub fn new(+ inner: DbNotificationRepository<PgPool>,+ device_endpoints: HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>>,+ ) -> Self {+ Self {+ inner,+ device_endpoints,+ }+ }+}++impl NotificationRepository for SandboxNotificationRepository {+ async fn get_muted_users<'a>(+ &self,+ user_ids: &[MacroUserIdStr<'a>],+ ) -> Result<HashSet<MacroUserIdStr<'static>>, Report> {+ self.inner.get_muted_users(user_ids).await+ }++ async fn get_unsubscribed_users<'a>(+ &self,+ item_id: &str,+ user_ids: &[MacroUserIdStr<'a>],+ ) -> Result<HashSet<MacroUserIdStr<'static>>, Report> {+ self.inner.get_unsubscribed_users(item_id, user_ids).await+ }++ async fn create_notification<'a, T: Notification + Send + Sync>(+ &self,+ request: SendNotificationRequestBuilder<'a, T>,+ notification_id: Uuid,+ service_sender: &str,+ apns_collapse_key: Option<&str>,+ ) -> Result<Option<Vec<UserNotificationRow<Arc<T>>>>, Report> {+ self.inner+ .create_notification(request, notification_id, service_sender, apns_collapse_key)+ .await+ }++ async fn update_sent_status<'a>(+ &self,+ notification_id: Uuid,+ user_ids: &[MacroUserIdStr<'a>],+ ) -> Result<(), Report> {+ self.inner+ .update_sent_status(notification_id, user_ids)+ .await+ }++ async fn get_device_endpoints<'a>(+ &self,+ _user_ids: &[MacroUserIdStr<'a>],+ ) -> Result<HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>>, Report> {+ // Return sandbox-configured endpoints instead of querying DB.+ Ok(self.device_endpoints.clone())+ }++ async fn mark_notifications_seen(+ &self,+ user_id: &MacroUserIdStr<'_>,+ notification_ids: &[Uuid],+ ) -> Result<(), Report> {+ self.inner+ .mark_notifications_seen(user_id, notification_ids)+ .await+ }++ async fn mark_notifications_done(+ &self,+ user_id: &MacroUserIdStr<'_>,+ notification_ids: &[Uuid],+ done: bool,+ ) -> Result<(), Report> {+ self.inner+ .mark_notifications_done(user_id, notification_ids, done)+ .await+ }++ async fn get_basic_notifications(+ &self,+ notification_ids: &[Uuid],+ ) -> Result<Vec<NotificationIdAndCollapseKey>, Report> {+ self.inner.get_basic_notifications(notification_ids).await+ }++ async fn get_user_notifications<T: DeserializeOwned + Send>(+ &self,+ user_id: &str,+ limit: u32,+ cursor: Query<Uuid, CreatedAt, ()>,+ ) -> Result<Vec<UserNotificationRow<T>>, Report> {+ self.inner+ .get_user_notifications(user_id, limit, cursor)+ .await+ }++ async fn get_user_notifications_by_event_item_ids<T: DeserializeOwned + Send>(+ &self,+ user_id: &str,+ event_item_ids: &[Uuid],+ limit: u32,+ cursor: Query<Uuid, CreatedAt, ()>,+ ) -> Result<Vec<UserNotificationRow<T>>, Report> {+ self.inner+ .get_user_notifications_by_event_item_ids(user_id, event_item_ids, limit, cursor)+ .await+ }++ async fn get_user_notification_by_id<T: DeserializeOwned + Send>(+ &self,+ user_id: &str,+ notification_id: Uuid,+ ) -> Result<Option<UserNotificationRow<T>>, Report> {+ self.inner+ .get_user_notification_by_id(user_id, notification_id)+ .await+ }++ async fn delete_user_notification(+ &self,+ user_id: &str,+ notification_id: Uuid,+ ) -> Result<(), Report> {+ self.inner+ .delete_user_notification(user_id, notification_id)+ .await+ }++ async fn bulk_delete_user_notifications(+ &self,+ user_id: &str,+ notification_ids: &[Uuid],+ ) -> Result<(), Report> {+ self.inner+ .bulk_delete_user_notifications(user_id, notification_ids)+ .await+ }+}diff --git a/rust/cloud-storage/notification_sandbox/src/interactive/last_online.rs b/rust/cloud-storage/notification_sandbox/src/interactive/last_online.rsnew file mode 100644index 0000000000..dfecd0f94c--- /dev/null+++ b/rust/cloud-storage/notification_sandbox/src/interactive/last_online.rs@@ -0,0 +1,18 @@+use macro_user_id::user_id::MacroUserIdStr;+use notification::domain::models::email_notification_digest::ports::LastOnlineChecker;+use rootcause::Report;+use std::time::Duration;++/// Prompts the user to provide how long since a user was last online.+pub struct InteractiveLastOnlineChecker;++impl LastOnlineChecker for InteractiveLastOnlineChecker {+ async fn last_online_checker<'a>(&self, user: MacroUserIdStr<'a>) -> Result<Duration, Report> {+ let minutes: u64 =+ inquire::CustomType::new(&format!("Minutes since user \"{user}\" was last online?"))+ .with_default(60)+ .prompt()+ .map_err(|e| rootcause::report!("{e}"))?;+ Ok(Duration::from_secs(minutes * 60))+ }+}diff --git a/rust/cloud-storage/notification_sandbox/src/interactive/mod.rs b/rust/cloud-storage/notification_sandbox/src/interactive/mod.rsnew file mode 100644index 0000000000..9f6316ee94--- /dev/null+++ b/rust/cloud-storage/notification_sandbox/src/interactive/mod.rs@@ -0,0 +1,3 @@+pub mod last_online;+pub mod push_checker;+pub mod user_existence;diff --git a/rust/cloud-storage/notification_sandbox/src/interactive/push_attempt.rs b/rust/cloud-storage/notification_sandbox/src/interactive/push_attempt.rsnew file mode 100644index 0000000000..7273806011--- /dev/null+++ b/rust/cloud-storage/notification_sandbox/src/interactive/push_attempt.rs@@ -0,0 +1,37 @@+use notification::domain::models::email_notification_digest::ports::{+ MessageId, NotificationSendChecker,+};+use rootcause::Report;++/// A mock push attempt that prompts the user to decide success or failure.+///+/// One instance is created per endpoint and consumed by StateMachineB.+pub struct InteractivePushAttempt {+ /// A human-readable name for the endpoint.+ pub endpoint_name: String,+}++impl NotificationSendChecker for InteractivePushAttempt {+ type Ok = String;+ type Err = Report;++ async fn send_notification(self) -> Result<String, Report> {+ let succeed =+ inquire::Confirm::new(&format!("Did push to \"{}\" succeed?", self.endpoint_name))+ .with_default(true)+ .prompt()+ .map_err(|e| rootcause::report!("{e}"))?;++ if succeed {+ let msg_id = format!("msg-{}", uuid::Uuid::new_v4());+ println!(" -> Generated message ID: {msg_id}");+ Ok(msg_id)+ } else {+ rootcause::bail!("simulated push failure for {}", self.endpoint_name)+ }+ }++ fn extract_message_id(res: &String) -> MessageId {+ MessageId(res.clone())+ }+}diff --git a/rust/cloud-storage/notification_sandbox/src/interactive/push_checker.rs b/rust/cloud-storage/notification_sandbox/src/interactive/push_checker.rsnew file mode 100644index 0000000000..6d0ab1f10f--- /dev/null+++ b/rust/cloud-storage/notification_sandbox/src/interactive/push_checker.rs@@ -0,0 +1,21 @@+use macro_user_id::user_id::MacroUserIdStr;+use notification::domain::models::email_notification_digest::ports::PushNotificationChecker;+use rootcause::Report;++/// Prompts the user to decide whether push notifications are enabled for a user.+pub struct InteractivePushNotificationChecker;++impl PushNotificationChecker for InteractivePushNotificationChecker {+ async fn push_notification_enabled<'a>(+ &self,+ user: MacroUserIdStr<'a>,+ ) -> Result<bool, Report> {+ let enabled = inquire::Confirm::new(&format!(+ "Does user \"{user}\" have push notifications enabled?"+ ))+ .with_default(true)+ .prompt()+ .map_err(|e| rootcause::report!("{e}"))?;+ Ok(enabled)+ }+}diff --git a/rust/cloud-storage/notification_sandbox/src/interactive/real_push_attempt.rs b/rust/cloud-storage/notification_sandbox/src/interactive/real_push_attempt.rsnew file mode 100644index 0000000000..92c866311b--- /dev/null+++ b/rust/cloud-storage/notification_sandbox/src/interactive/real_push_attempt.rs@@ -0,0 +1,44 @@+use notification::domain::models::email_notification_digest::ports::{+ MessageId, NotificationSendChecker,+};+use rootcause::Report;++/// A push attempt that actually sends via AWS SNS.+///+/// Sends a minimal APNS payload to the given endpoint ARN and returns the real+/// SNS message ID.+pub struct RealSnsPushAttempt {+ /// The AWS SNS client.+ pub sns_client: aws_sdk_sns::Client,+ /// The target endpoint ARN.+ pub endpoint_arn: String,+}++impl NotificationSendChecker for RealSnsPushAttempt {+ type Ok = String;+ type Err = Report;++ async fn send_notification(self) -> Result<String, Report> {+ println!(" -> Sending real push to {}...", self.endpoint_arn);++ let payload = r#"{"APNS":"{\"aps\":{\"alert\":\"sandbox test\",\"sound\":\"default\"}}"}"#;++ let result = self+ .sns_client+ .publish()+ .target_arn(&self.endpoint_arn)+ .message(payload)+ .message_structure("json")+ .send()+ .await+ .map_err(|e| rootcause::report!("SNS publish failed: {e}"))?;++ let msg_id = result.message_id().unwrap_or_default().to_string();+ println!(" -> Real SNS message ID: {msg_id}");+ Ok(msg_id)+ }++ fn extract_message_id(res: &String) -> MessageId {+ MessageId(res.clone())+ }+}diff --git a/rust/cloud-storage/notification_sandbox/src/interactive/user_existence.rs b/rust/cloud-storage/notification_sandbox/src/interactive/user_existence.rsnew file mode 100644index 0000000000..c3b49a351b--- /dev/null+++ b/rust/cloud-storage/notification_sandbox/src/interactive/user_existence.rs@@ -0,0 +1,16 @@+use macro_user_id::user_id::MacroUserIdStr;+use notification::domain::models::email_notification_digest::ports::UserExistenceChecker;+use rootcause::Report;++/// Prompts the user to decide whether a given user exists.+pub struct InteractiveUserExistenceChecker;++impl UserExistenceChecker for InteractiveUserExistenceChecker {+ async fn user_exists<'a>(&self, id: MacroUserIdStr<'a>) -> Result<bool, Report> {+ let exists = inquire::Confirm::new(&format!("Does user \"{id}\" have a Macro account?"))+ .with_default(true)+ .prompt()+ .map_err(|e| rootcause::report!("{e}"))?;+ Ok(exists)+ }+}diff --git a/rust/cloud-storage/notification_sandbox/src/main.rs b/rust/cloud-storage/notification_sandbox/src/main.rsnew file mode 100644index 0000000000..b8dee04e7a--- /dev/null+++ b/rust/cloud-storage/notification_sandbox/src/main.rs@@ -0,0 +1,461 @@+mod adapters;+mod interactive;+mod sandbox_notification;++use std::collections::{HashMap, HashSet};+use std::sync::{Arc, Mutex};+use std::time::Duration;++use macro_user_id::cowlike::CowLike;+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::EntityType;+use notification::domain::models::email_notification_digest::ports::MessageId;+use notification::domain::models::email_notification_digest::{+ EmailBlockList, ExplicitInviteAllowList, NotificationSetBuilder, StateMachineDecisionC,+ StateMachineDriverA, StateMachineDriverB, StateMachineDriverC,+};+use notification::domain::models::{DeviceEndpoint, SendNotificationRequestBuilder};+use notification::domain::ports::NotificationEgress;+use notification::domain::service::{+ NotificationEgressService, NotificationIngress, NotificationIngressService,+};+use notification::outbound::digest_batcher::RedisDigestBatcher;+use notification::outbound::email::EmailAdapter;+use notification::outbound::message_receipt_repository::DbMessageReceiptRepository;+use notification::outbound::mobile::MobilePushAdapter;+use notification::outbound::repository::DbNotificationRepository;+use rootcause::Report;+use sandbox_notification::{NeverMatchNotification, SandboxNotification};+use sqlx::PgPool;+use sqlx::postgres::PgPoolOptions;++use adapters::interactive_mobile::{+ InteractiveMobileSender, PushPromptRequest, SandboxMobileSender,+};+use adapters::logging_websocket::LoggingWebSocketSender;+use adapters::mpsc_queue::MpscQueue;+use adapters::noop_rate_limiter::NoOpRateLimiter;+use adapters::sandbox_repository::SandboxNotificationRepository;++/// Configuration collected from the interactive wizard.+struct SandboxConfig {+ digest_window: Duration,+ online_threshold: Duration,+ is_blocked: bool,+ is_invite: bool,+ sns_mode: SnsMode,+ num_endpoints: usize,+}++enum SnsMode {+ Mock,+ Real {+ sns_client: aws_sdk_sns::Client,+ endpoint_arn: String,+ },+}++#[tokio::main]+async fn main() -> Result<(), Report> {+ tracing_subscriber::fmt::init();++ tokio::spawn(async {+ tokio::signal::ctrl_c().await.ok();+ std::process::exit(0);+ });++ println!("\n=== Notification Digest Sandbox ===\n");++ // --- Phase 1: Connect to persistence ---+ let default_db = std::env::var("DATABASE_URL")+ .unwrap_or_else(|_| "postgres://user:password@localhost:5432/macrodb".to_string());+ let database_url = inquire::Text::new("Postgres URL?")+ .with_default(&default_db)+ .prompt()?;++ let default_redis =+ std::env::var("REDIS_URI").unwrap_or_else(|_| "redis://localhost:6379".to_string());+ let redis_uri = inquire::Text::new("Redis URL?")+ .with_default(&default_redis)+ .prompt()?;++ let db = PgPoolOptions::new()+ .max_connections(5)+ .connect(&database_url)+ .await?;+ println!("Connected to Postgres.");++ let redis_client = redis::Client::open(redis_uri.as_str())?;+ let redis_conn = redis_client.get_multiplexed_async_connection().await?;+ println!("Connected to Redis.\n");++ // --- Phase 2: Configuration wizard ---+ let config = run_config_wizard().await?;++ // --- Wire up services ---+ let user_email = inquire::Text::new("Recipient email?")+ .with_default("[email protected]")+ .prompt()?;+ let user_id = MacroUserIdStr::try_from_email(&user_email)?;++ let queue = MpscQueue::new();++ // Build sandbox device endpoints from config+ let device_endpoints = build_device_endpoints(&user_id, &config);+ let sandbox_repo = SandboxNotificationRepository::new(+ DbNotificationRepository::new(db.clone()),+ device_endpoints,+ );++ // Ingress: StateMachineDriverA with interactive checkers+ let block_list = if config.is_blocked {+ EmailBlockList::new::<SandboxNotification>()+ } else {+ EmailBlockList::new::<NeverMatchNotification>()+ };++ let invite_list = if config.is_invite {+ ExplicitInviteAllowList::new::<SandboxNotification>()+ } else {+ ExplicitInviteAllowList::new::<NeverMatchNotification>()+ };++ let state_machine_a = StateMachineDriverA {+ user_checker: interactive::user_existence::InteractiveUserExistenceChecker,+ notification_checker: interactive::push_checker::InteractivePushNotificationChecker,+ online_checker: interactive::last_online::InteractiveLastOnlineChecker,+ digest_batcher: RedisDigestBatcher::new(redis_conn.clone()),+ block_list,+ invite_list,+ digest_window: config.digest_window,+ online_duration_threshold: config.online_threshold,+ };++ let ingress_service =+ NotificationIngressService::new(sandbox_repo, queue.clone(), state_machine_a);++ // Egress: interactive mobile push, SES email, real state machine B+ let aws_config = macro_aws_config::get_macro_aws_config().await;+ let (prompt_tx, mut prompt_rx) = tokio::sync::mpsc::unbounded_channel::<PushPromptRequest>();+ let mobile_sender = match &config.sns_mode {+ SnsMode::Mock => SandboxMobileSender::Interactive(InteractiveMobileSender { prompt_tx }),+ SnsMode::Real {+ sns_client,+ endpoint_arn: _,+ } => SandboxMobileSender::Real(MobilePushAdapter::new(+ sns_client.clone(),+ "com.macro.app.prod".to_string(),+ )),+ };+ let email_adapter = EmailAdapter::new(+ aws_sdk_sesv2::Client::new(&aws_config),+ "[email protected]".to_string(),+ );++ let egress_service = Arc::new(NotificationEgressService {+ queue: queue.clone(),+ repository: DbNotificationRepository::new(db.clone()),+ websocket: LoggingWebSocketSender,+ mobile: mobile_sender,+ email: email_adapter,+ rate_limiter: NoOpRateLimiter,+ state_machine: StateMachineDriverB {+ message_receipt_repo: DbMessageReceiptRepository::new(db.clone()),+ digest_batcher: RedisDigestBatcher::new(redis_conn.clone()),+ digest_window: config.digest_window,+ },+ digest_batcher: RedisDigestBatcher::new(redis_conn.clone()),+ });++ // Shared log buffer so background egress output doesn't corrupt inquire prompts+ let egress_log: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));++ // Spawn background egress loop to continuously deliver queued messages+ let egress_bg = egress_service.clone();+ let egress_log_bg = egress_log.clone();+ tokio::spawn(async move {+ loop {+ let results = egress_bg.poll_and_deliver().await;+ if !results.is_empty() {+ let mut log = egress_log_bg.lock().unwrap();+ for result in &results {+ match result {+ Ok(success) => log.push(format!(" [egress] SUCCESS ({success:?})")),+ Err(e) => log.push(format!(" [egress] FAILED ({e})")),+ }+ }+ }+ tokio::time::sleep(Duration::from_millis(500)).await;+ }+ });++ // StateMachineC for interactive SNS failure reconciliation+ let state_machine_c = StateMachineDriverC {+ message_receipt_repo: DbMessageReceiptRepository::new(db.clone()),+ digest_batcher: RedisDigestBatcher::new(redis_conn.clone()),+ notif_repo: DbNotificationRepository::new(db.clone()),+ digest_window: config.digest_window,+ };++ println!("\nServices wired up. Entering interactive loop.\n");++ // --- Interactive loop ---+ loop {+ // Drain buffered egress log and handle any stale push prompts+ drain_egress_log(&egress_log);+ handle_pending_prompts(&mut prompt_rx);+ drain_egress_log(&egress_log);++ let action = inquire::Select::new(+ "What would you like to do?",+ vec![+ "Create and send a notification",+ "Run StateMachineC (SNS failure reconciliation)",+ "Poll digest status",+ "Quit",+ ],+ )+ .prompt()?;++ match action {+ "Create and send a notification" => {+ run_notification_cycle(&user_id, &ingress_service).await?;+ // Handle push prompts from the background egress task until it's done+ drain_push_prompts(&mut prompt_rx, &egress_log).await;+ }+ "Run StateMachineC (SNS failure reconciliation)" => {+ run_state_machine_c(&state_machine_c).await?;+ }+ "Poll digest status" => {+ poll_email_digests(&*egress_service).await?;+ }+ "Quit" => break,+ _ => unreachable!(),+ }++ drain_egress_log(&egress_log);+ println!();+ }++ println!("\nSandbox complete.");+ Ok(())+}++/// Print any buffered egress log lines.+fn drain_egress_log(log: &Arc<Mutex<Vec<String>>>) {+ let lines: Vec<String> = log.lock().unwrap().drain(..).collect();+ for line in lines {+ println!("{line}");+ }+}++/// Handle any push-prompt requests already queued (non-blocking).+fn handle_pending_prompts(rx: &mut tokio::sync::mpsc::UnboundedReceiver<PushPromptRequest>) {+ while let Ok(req) = rx.try_recv() {+ prompt_push_result(req);+ }+}++/// Wait for push prompts from the background egress task until it's idle.+///+/// After ingress publishes to the queue, the background egress picks it up and may send+/// multiple push prompt requests (one per endpoint). We wait for each one, answer it,+/// and continue until no more arrive within a short timeout.+async fn drain_push_prompts(+ rx: &mut tokio::sync::mpsc::UnboundedReceiver<PushPromptRequest>,+ egress_log: &Arc<Mutex<Vec<String>>>,+) {+ while let Ok(Some(req)) = tokio::time::timeout(Duration::from_secs(2), rx.recv()).await {+ prompt_push_result(req);+ drain_egress_log(egress_log);+ }+}++/// Show an interactive prompt for a single push result and send the reply.+fn prompt_push_result(req: PushPromptRequest) {+ let succeeded =+ inquire::Confirm::new(&format!("Did push to \"{}\" succeed?", req.endpoint_arn))+ .with_default(true)+ .prompt()+ .unwrap_or(false);++ if succeeded {+ println!(" -> SUCCESS");+ } else {+ println!(" -> FAILED");+ }++ let _ = req.reply.send(succeeded);+}++/// Create a notification via the ingress service. The background egress task delivers it.+async fn run_notification_cycle<I: NotificationIngress>(+ user_id: &MacroUserIdStr<'static>,+ ingress: &I,+) -> Result<(), Report> {+ println!("\n--- Ingress: Creating notification ---\n");++ let request = SendNotificationRequestBuilder {+ notification_entity: EntityType::Channel.with_entity_str("sandbox-entity-id"),+ notification: SandboxNotification {+ message: "Sandbox test notification".to_string(),+ },+ sender_id: None,+ recipient_ids: HashSet::from([user_id.copied()]),+ }+ .into_request()+ .with_apns();++ match ingress.send_notification(request).await {+ Ok(Some(result)) => {+ println!(+ "\nIngress complete: notification {} created for {} recipient(s). Published to queue.",+ result.notification_id,+ result.notified_recipients.len()+ );+ }+ Ok(None) => {+ println!("\nIngress: no recipients remaining after filtering.");+ }+ Err(e) => {+ println!("\nIngress failed: {e}");+ }+ }++ Ok(())+}++/// Interactively run StateMachineC to simulate SNS delivery failure.+async fn run_state_machine_c(+ state_machine_c: &StateMachineDriverC<+ RedisDigestBatcher,+ DbMessageReceiptRepository,+ DbNotificationRepository<PgPool>,+ >,+) -> Result<(), Report> {+ println!("\n--- StateMachineC: SNS Failure Reconciliation ---\n");++ let msg_id = inquire::Text::new("Enter SNS message ID to mark as failed (from egress output):")+ .prompt()?;++ if msg_id.trim().is_empty() {+ println!(" Skipped (empty message ID).");+ return Ok(());+ }++ match state_machine_c+ .mark_message_as_failed(MessageId(msg_id.clone()))+ .await+ {+ Ok(StateMachineDecisionC::NoAction) => {+ println!(" -> NoAction (not all endpoints have failed yet)");+ }+ Ok(StateMachineDecisionC::BatchWasQueued(_)) => {+ println!(" -> BatchWasQueued! (all endpoints failed, added to digest)");+ }+ Err(e) => {+ println!(" -> Error: {e}");+ }+ }++ Ok(())+}++/// Poll for ready digest batches via the egress service.+async fn poll_email_digests(egress: &impl NotificationEgress) -> Result<(), Report> {+ println!("\n--- Poll Email Digests ---\n");++ fn digest_to_sandbox(+ batch: notification::domain::models::email_notification_digest::ports::DigestBatch,+ ) -> Result<SandboxNotification, Report> {+ Ok(SandboxNotification {+ message: format!(+ "You have {} new notification(s) \n\n {:#?}",+ batch.notifications.len(),+ batch+ ),+ })+ }++ let res = egress.poll_email_digests(digest_to_sandbox).await?;+ println!("{res:?}");+ Ok(())+}++/// Build sandbox device endpoints based on the config wizard.+fn build_device_endpoints(+ user_id: &MacroUserIdStr<'static>,+ config: &SandboxConfig,+) -> HashMap<MacroUserIdStr<'static>, Vec<DeviceEndpoint>> {+ let endpoints: Vec<DeviceEndpoint> = match &config.sns_mode {+ SnsMode::Mock => (1..=config.num_endpoints)+ .map(|i| {+ DeviceEndpoint::Ios(format!(+ "arn:aws:sns:sandbox:000:endpoint/APNS/sandbox/endpoint-{i}"+ ))+ })+ .collect(),+ SnsMode::Real { endpoint_arn, .. } => {+ if config.num_endpoints == 1 {+ vec![DeviceEndpoint::Ios(endpoint_arn.clone())]+ } else {+ (1..=config.num_endpoints)+ .map(|i| {+ let arn = inquire::Text::new(&format!("Endpoint ARN for endpoint-{i}?"))+ .with_default(endpoint_arn)+ .prompt()+ .expect("prompt failed");+ DeviceEndpoint::Ios(arn)+ })+ .collect()+ }+ }+ };++ HashMap::from([(user_id.clone().into_owned(), endpoints)])+}++async fn run_config_wizard() -> Result<SandboxConfig, Report> {+ let digest_minutes: u64 = inquire::CustomType::new("Digest window (minutes)?")+ .with_default(30)+ .prompt()?;++ let online_minutes: u64 = inquire::CustomType::new("Online duration threshold (minutes)?")+ .with_default(5)+ .prompt()?;++ let is_blocked = inquire::Confirm::new("Is this notification type blocked from email?")+ .with_default(false)+ .prompt()?;++ let is_invite = inquire::Confirm::new("Is this notification type an invite?")+ .with_default(false)+ .prompt()?;++ let sns_options = vec!["Mock (interactive)", "Real (AWS)"];+ let sns_choice = inquire::Select::new("SNS mode?", sns_options).prompt()?;++ let sns_mode = if sns_choice == "Real (AWS)" {+ let endpoint_arn = inquire::Text::new("SNS endpoint ARN?").prompt()?;+ let aws_config = macro_aws_config::get_macro_aws_config().await;+ SnsMode::Real {+ sns_client: aws_sdk_sns::Client::new(&aws_config),+ endpoint_arn,+ }+ } else {+ SnsMode::Mock+ };++ let num_endpoints: usize = inquire::CustomType::new("Number of iOS endpoints for user?")+ .with_default(2usize)+ .prompt()?;++ Ok(SandboxConfig {+ digest_window: Duration::from_secs(digest_minutes * 60),+ online_threshold: Duration::from_secs(online_minutes * 60),+ is_blocked,+ is_invite,+ sns_mode,+ num_endpoints,+ })+}diff --git a/rust/cloud-storage/notification_sandbox/src/sandbox_notification.rs b/rust/cloud-storage/notification_sandbox/src/sandbox_notification.rsnew file mode 100644index 0000000000..956b3bc6b7--- /dev/null+++ b/rust/cloud-storage/notification_sandbox/src/sandbox_notification.rs@@ -0,0 +1,64 @@+use macro_user_id::user_id::MacroUserIdStr;+use notification::domain::models::apple::APNSPushNotification;+use notification::domain::models::mobile::NotifCollapseKey;+use notification::domain::models::queue_message::EmailContent;+use notification::domain::models::rate_limit::{RateLimitConfig, RateLimitKey};+use notification::domain::models::{Notification, NotificationExtEmail, NotificationExtIos};+use serde::{Deserialize, Serialize};++/// A minimal notification type for sandbox testing.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SandboxNotification {+ /// A test message.+ pub message: String,+}++impl Notification for SandboxNotification {+ const TYPE_NAME: &'static str = "sandbox_notification";+}++impl NotificationExtIos for SandboxNotification {+ type NotifData = SandboxNotification;++ fn collapse_key(&self, _entity: &model_entity::Entity<'_>) -> NotifCollapseKey {+ NotifCollapseKey::new("sandbox")+ }++ fn into_apns<'a>(+ self,+ _sender_id: Option<MacroUserIdStr<'a>>,+ _entity: &model_entity::Entity<'_>,+ _notification_id: uuid::Uuid,+ ) -> Option<APNSPushNotification<Self::NotifData>> {+ Some(APNSPushNotification {+ aps: Default::default(),+ push_notification_data: self,+ })+ }+}++impl NotificationExtEmail for SandboxNotification {+ fn format_email(&self) -> EmailContent {+ EmailContent {+ subject: "Sandbox Notification".to_string(),+ body: self.message.clone(),+ }+ }++ fn rate_limit_config() -> RateLimitConfig {+ RateLimitConfig::new(u64::MAX, std::time::Duration::from_secs(3600))+ }++ fn rate_limit_key(&self) -> RateLimitKey {+ RateLimitKey::from_str_hashed("sandbox")+ }+}++/// A notification type that will never match any real notification.+/// Used to create block/invite lists where nothing matches.+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct NeverMatchNotification;++impl Notification for NeverMatchNotification {+ const TYPE_NAME: &'static str = "__never__";+}