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): send referral emails (#2034)

Sean Ayede18c8b0a346
diff --git a/js/app/packages/service-clients/service-auth/generated/client.ts b/js/app/packages/service-clients/service-auth/generated/client.ts
index 8843a93ace..10323c0b88 100644
--- a/js/app/packages/service-clients/service-auth/generated/client.ts
+++ b/js/app/packages/service-clients/service-auth/generated/client.ts
@@ -37,8 +37,8 @@ import type {
ProfilePictures,
PutProfilePictureParams,
PutUserNameParams,
- ReferralCode,
ResendFusionauthVerifyUserEmailRequest,
+ SendInviteBody,
SsoLoginParams,
SsoRequiredResponse,
StripeSessionResponse,
@@ -1314,7 +1314,7 @@ export const getUserPermissions = async (
* @summary Handler for `GET /referral-code`.
*/
export type getReferralCodeResponse200 = {
- data: ReferralCode;
+ data: string;
status: 200;
};
@@ -1364,6 +1364,64 @@ export const getReferralCode = async (
} as getReferralCodeResponse;
};
+/**
+ * Sends a referral code via email to a user
+ * @summary Handler for `POST /referral/send`.
+ */
+export type sendReferralCodeResponse204 = {
+ data: void;
+ status: 204;
+};
+
+export type sendReferralCodeResponse401 = {
+ data: ErrorResponse;
+ status: 401;
+};
+
+export type sendReferralCodeResponse500 = {
+ data: ErrorResponse;
+ status: 500;
+};
+
+export type sendReferralCodeResponseSuccess = sendReferralCodeResponse204 & {
+ headers: Headers;
+};
+export type sendReferralCodeResponseError = (
+ | sendReferralCodeResponse401
+ | sendReferralCodeResponse500
+) & {
+ headers: Headers;
+};
+
+export type sendReferralCodeResponse =
+ | sendReferralCodeResponseSuccess
+ | sendReferralCodeResponseError;
+
+export const getSendReferralCodeUrl = () => {
+ return `/referral/send`;
+};
+
+export const sendReferralCode = async (
+ sendInviteBody: SendInviteBody,
+ options?: RequestInit
+): Promise<sendReferralCodeResponse> => {
+ const res = await fetch(getSendReferralCodeUrl(), {
+ ...options,
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json', ...options?.headers },
+ body: JSON.stringify(sendInviteBody),
+ });
+
+ const body = [204, 205, 304].includes(res.status) ? null : await res.text();
+
+ const data: sendReferralCodeResponse['data'] = body ? JSON.parse(body) : {};
+ return {
+ data,
+ status: res.status,
+ headers: res.headers,
+ } as sendReferralCodeResponse;
+};
+
/**
* @summary Refreshes a JWT token
*/
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts b/js/app/packages/service-clients/service-auth/generated/schemas/index.ts
index f2beabc7f2..c838b8a4f7 100644
--- a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/index.ts
@@ -49,8 +49,8 @@ export * from './putUserNameParams';
export * from './putUserNameQueryParams';
export * from './putUserNameQueryParamsFirstName';
export * from './putUserNameQueryParamsLastName';
-export * from './referralCode';
export * from './resendFusionauthVerifyUserEmailRequest';
+export * from './sendInviteBody';
export * from './ssoLoginParams';
export * from './ssoRequiredResponse';
export * from './stripeProductTier';
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/referralCode.ts b/js/app/packages/service-clients/service-auth/generated/schemas/referralCode.ts
deleted file mode 100644
index 6224fd9598..0000000000
--- a/js/app/packages/service-clients/service-auth/generated/schemas/referralCode.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
- * Generated by orval v7.13.0 🍺
- * Do not edit manually.
- * authentication_service
- * OpenAPI spec version: 0.1.0
- */
-
-/**
- * Wrapper for the referral code to make it type safe
- */
-export type ReferralCode = string;
diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/sendInviteBody.ts b/js/app/packages/service-clients/service-auth/generated/schemas/sendInviteBody.ts
new file mode 100644
index 0000000000..2a27d4e504
--- /dev/null
+++ b/js/app/packages/service-clients/service-auth/generated/schemas/sendInviteBody.ts
@@ -0,0 +1,14 @@
+/**
+ * Generated by orval v7.13.0 🍺
+ * Do not edit manually.
+ * authentication_service
+ * OpenAPI spec version: 0.1.0
+ */
+
+/**
+ * The body which is used to describe the recipient email
+ */
+export interface SendInviteBody {
+ /** the recipient of the referral email */
+ recipient: string;
+}
diff --git a/js/app/packages/service-clients/service-auth/openapi.json b/js/app/packages/service-clients/service-auth/openapi.json
index 1591ff46de..35fe53b84b 100644
--- a/js/app/packages/service-clients/service-auth/openapi.json
+++ b/js/app/packages/service-clients/service-auth/openapi.json
@@ -1106,15 +1106,58 @@
"operationId": "get_referral_code",
"responses": {
"200": {
+ "description": "",
+ "content": {
+ "text/plain": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "401": {
"description": "",
"content": {
"application/json": {
"schema": {
- "$ref": "#/components/schemas/ReferralCode"
+ "$ref": "#/components/schemas/ErrorResponse"
}
}
}
},
+ "500": {
+ "description": "",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ErrorResponse"
+ }
+ }
+ }
+ }
+ }
+ }
+ },
+ "/referral/send": {
+ "post": {
+ "tags": ["referral"],
+ "summary": "Handler for `POST /referral/send`.",
+ "description": "Sends a referral code via email to a user",
+ "operationId": "send_referral_code",
+ "requestBody": {
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/SendInviteBody"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "204": {
+ "description": ""
+ },
"401": {
"description": "",
"content": {
@@ -3380,10 +3423,6 @@
}
}
},
- "ReferralCode": {
- "type": "string",
- "description": "Wrapper for the referral code to make it type safe"
- },
"ResendFusionauthVerifyUserEmailRequest": {
"type": "object",
"required": ["email"],
@@ -3394,6 +3433,17 @@
}
}
},
+ "SendInviteBody": {
+ "type": "object",
+ "description": "The body which is used to describe the recipient email",
+ "required": ["recipient"],
+ "properties": {
+ "recipient": {
+ "type": "string",
+ "description": "the recipient of the referral email"
+ }
+ }
+ },
"SsoRequiredResponse": {
"type": "object",
"required": ["idp_id"],
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index 492866dae7..d635e6a0f3 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -617,6 +617,7 @@ dependencies = [
"notification",
"openssl",
"rand 0.9.0",
+ "rate_limit",
"redis",
"referral",
"remote_env_var",
@@ -6177,6 +6178,7 @@ dependencies = [
"models_pagination",
"notification",
"paste",
+ "referral_invitation",
"rootcause",
"serde",
"serde_json",
@@ -6555,6 +6557,7 @@ dependencies = [
"model-error-response",
"model_user",
"models_pagination",
+ "rate_limit",
"redis",
"reqwest",
"rootcause",
@@ -6607,6 +6610,7 @@ dependencies = [
"model_notifications",
"models_pagination",
"notification",
+ "rate_limit",
"redis",
"rootcause",
"serde",
@@ -6656,6 +6660,7 @@ dependencies = [
"notification",
"notification_db_client",
"paste",
+ "rate_limit",
"redis",
"regex",
"secretsmanager_client",
@@ -7762,6 +7767,21 @@ dependencies = [
"rand_core 0.5.1",
]
+[[package]]
+name = "rate_limit"
+version = "0.1.0"
+dependencies = [
+ "hex",
+ "redis",
+ "rootcause",
+ "serde",
+ "thiserror 2.0.17",
+ "tokio",
+ "tracing",
+ "twox-hash",
+ "uuid",
+]
+
[[package]]
name = "rav1e"
version = "0.8.1"
@@ -7910,8 +7930,13 @@ dependencies = [
"macro_user_id",
"macro_uuid",
"mockall",
+ "model-entity",
"model-error-response",
"model_user",
+ "notification",
+ "rate_limit",
+ "referral_invitation",
+ "rootcause",
"serde",
"serde_json",
"sqlx",
@@ -7924,6 +7949,15 @@ dependencies = [
"uuid",
]
+[[package]]
+name = "referral_invitation"
+version = "0.1.0"
+dependencies = [
+ "macro_user_id",
+ "notification",
+ "serde",
+]
+
[[package]]
name = "regex"
version = "1.12.2"
@@ -10349,6 +10383,15 @@ dependencies = [
"utf-8",
]
+[[package]]
+name = "twox-hash"
+version = "2.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9ea3136b675547379c4bd395ca6b938e5ad3c3d20fad76e7fe85f9e0d011419c"
+dependencies = [
+ "rand 0.9.0",
+]
+
[[package]]
name = "typenum"
version = "1.17.0"
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 75199ee6af..9fec5f2b2a 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -97,7 +97,9 @@ members = [
"properties",
"properties_db_client",
"properties_service",
+ "rate_limit",
"referral",
+ "referral_invitation",
"roles_and_permissions",
"rpc/axum_rpc",
"rpc/axum_rpc_emit",
@@ -144,9 +146,7 @@ aws-sdk-sns = "1.90.0"
aws-sdk-sqs = "1.91.0"
aws-smithy-types = "1.2.13"
aws_lambda_events = { version = "0.16.0", default-features = false }
-axum = { version = "0.8", features = [
- "tower-log",
-] }
+axum = { version = "0.8", features = ["tower-log"] }
axum-extra = { version = "0.10" }
base64 = "0.22.1"
cached = { version = "0.54.0", features = ["async_tokio_rt_multi_thread"] }
@@ -155,8 +155,8 @@ clap = { version = "4.5.20", features = ["derive"] }
cloudfront_sign = "0.3.0"
cookie = "0.18.1"
csv = "1"
-dateparser = "0.2.1"
dashmap = "6.1.0"
+dateparser = "0.2.1"
dotenvy = "0.15.7"
ego-tree = "0.6.2"
either = "1"
diff --git a/rust/cloud-storage/authentication_service/Cargo.toml b/rust/cloud-storage/authentication_service/Cargo.toml
index 5f1992ea60..160b6da708 100644
--- a/rust/cloud-storage/authentication_service/Cargo.toml
+++ b/rust/cloud-storage/authentication_service/Cargo.toml
@@ -89,8 +89,9 @@ non_empty = { path = "../non_empty" }
notification = { path = "../notification" }
openssl = { workspace = true }
rand = { workspace = true }
-referral = { path = "../referral" }
+rate_limit = { path = "../rate_limit" }
redis = { workspace = true }
+referral = { path = "../referral" }
remote_env_var = { path = "../remote_env_var" }
reqwest = { workspace = true }
roles_and_permissions = { path = "../roles_and_permissions" }
diff --git a/rust/cloud-storage/authentication_service/src/api/context.rs b/rust/cloud-storage/authentication_service/src/api/context.rs
index 076e6e0d19..49b80a9f21 100644
--- a/rust/cloud-storage/authentication_service/src/api/context.rs
+++ b/rust/cloud-storage/authentication_service/src/api/context.rs
@@ -12,8 +12,11 @@ use macro_env::Environment;
use macro_env_var::env_var;
use macro_middleware::auth::internal_access::InternalApiSecretKey;
use native_app_service::{domain::service::NativeAppServiceImpl, outbound::DefaultBundleFetcher};
-use notification::domain::service::SqsNotificationIngress;
use notification::outbound::queue::SqsIngressQueue;
+use notification::{
+ domain::service::SqsNotificationIngress, outbound::rate_limit::RedisRateLimitAdapter,
+};
+use rate_limit::domain::service::RateLimitServiceImpl;
use referral::{
domain::service::ReferralServiceImpl,
outbound::{pg_referral_repo::PgReferralRepo, stripe_discount_client::StripeDiscountClient},
@@ -35,7 +38,12 @@ pub(crate) type TeamsServiceType = teams::domain::team_service::TeamServiceImpl<
NotificationIngressType,
>;
-pub(crate) type ReferralServiceType = ReferralServiceImpl<PgReferralRepo, StripeDiscountClient>;
+pub(crate) type ReferralServiceType = ReferralServiceImpl<
+ PgReferralRepo,
+ StripeDiscountClient,
+ RateLimitServiceImpl<RedisRateLimitAdapter<redis::Client>>,
+ Arc<SqsNotificationIngress<SqsIngressQueue>>,
+>;
pub(crate) type GithubLinkServiceType =
GithubLinkServiceImpl<PgGithubRepo, GithubOauthImpl, GithubAuthImpl>;
diff --git a/rust/cloud-storage/authentication_service/src/api/swagger.rs b/rust/cloud-storage/authentication_service/src/api/swagger.rs
index d4b77b64c6..726f01487b 100644
--- a/rust/cloud-storage/authentication_service/src/api/swagger.rs
+++ b/rust/cloud-storage/authentication_service/src/api/swagger.rs
@@ -125,6 +125,7 @@ use model::user::{
/// /referral
referral::inbound::axum_router::get_referral_code_handler::<crate::api::context::ReferralServiceType>,
+ referral::inbound::axum_router::post_referral_invite_handler::<crate::api::context::ReferralServiceType>,
/// /merge
merge::create_merge_request::handler,
@@ -183,9 +184,6 @@ use model::user::{
TeamTeamInvitesResponse,
UserTeamInvitesResponse,
- // Referral
- referral::domain::models::ReferralCode,
-
// Merge
CreateAccountMergeRequest,
),
diff --git a/rust/cloud-storage/authentication_service/src/main.rs b/rust/cloud-storage/authentication_service/src/main.rs
index 4a461de05c..3a31a6ae62 100644
--- a/rust/cloud-storage/authentication_service/src/main.rs
+++ b/rust/cloud-storage/authentication_service/src/main.rs
@@ -17,8 +17,11 @@ use native_app_service::{
domain::{models::PlatformData, service::NativeAppServiceImpl},
outbound::DefaultBundleFetcher,
};
-use notification::domain::service::SqsNotificationIngress;
use notification::outbound::queue::SqsIngressQueue;
+use notification::{
+ domain::service::SqsNotificationIngress, outbound::rate_limit::RedisRateLimitAdapter,
+};
+use rate_limit::domain::service::RateLimitServiceImpl;
use roles_and_permissions::{
domain::service::UserRolesAndPermissionsServiceImpl, outbound::pgpool::MacroDB,
};
@@ -161,18 +164,20 @@ async fn main() -> anyhow::Result<()> {
JwtValidationArgs::new_with_secret_manager(config.environment, &secretsmanager_client)
.await?;
- let redis_client_for_github =
+ let redis_client =
redis::Client::open(config.redis_uri.as_str()).context("failed to create redis client")?;
- let redis_multiplexed_conn = redis_client_for_github
+ let redis_multiplexed_conn = redis_client
.get_multiplexed_async_connection()
.await
.context("failed to get multiplexed redis connection")?;
- let ingress_queue = SqsIngressQueue::new(
- aws_sdk_sqs::Client::new(&macro_aws_config::get_macro_aws_config().await),
- config.notification_queue.clone(),
- );
- let notification_ingress_service = SqsNotificationIngress::new(ingress_queue);
+ let ingress_queue = SqsIngressQueue {
+ client: aws_sdk_sqs::Client::new(&macro_aws_config::get_macro_aws_config().await),
+ queue_url: config.notification_queue.clone(),
+ };
+ let notification_ingress_service = SqsNotificationIngress {
+ queue: ingress_queue,
+ };
tracing::trace!("initialized notification ingress service");
let sqs_client = sqs_client::SQS::new(aws_sdk_sqs::Client::new(
@@ -242,10 +247,19 @@ async fn main() -> anyhow::Result<()> {
},
);
- let referral_service = ReferralServiceImpl::new(
- PgReferralRepo::new(db.clone()),
- StripeDiscountClient::new(stripe_client.clone(), 10000 /*100$ credit, in cents*/),
- );
+ let referral_service = ReferralServiceImpl {
+ repo: PgReferralRepo::new(db.clone()),
+ discount_client: StripeDiscountClient::new(
+ stripe_client.clone(),
+ 10000, /*100$ credit, in cents*/
+ ),
+ rate_limit: RateLimitServiceImpl {
+ repo: RedisRateLimitAdapter {
+ redis: redis_client,
+ },
+ },
+ notification_ingress: notification_ingress_service.clone(),
+ };
api::setup_and_serve(
ApiContext {
@@ -256,7 +270,7 @@ async fn main() -> anyhow::Result<()> {
stripe_client: Arc::new(stripe_client),
document_storage_service_client: Arc::new(document_storage_service_client),
ses_client: Arc::new(ses_client),
- notification_ingress_service: notification_ingress_service.clone(),
+ notification_ingress_service,
sqs_client: Arc::new(sqs_client),
environment: config.environment,
jwt_args,
diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
index 438edb258c..cb991c622b 100644
--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs
@@ -205,11 +205,13 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Ar
channels_service,
));
- let ingress_queue = SqsIngressQueue::new(
- aws_sdk_sqs::Client::from_conf(sqs_config),
- "test-notification-ingress-queue".to_string(),
- );
- let notification_ingress_service = Arc::new(SqsNotificationIngress::new(ingress_queue));
+ let ingress_queue = SqsIngressQueue {
+ client: aws_sdk_sqs::Client::from_conf(sqs_config),
+ queue_url: "test-notification-ingress-queue".to_string(),
+ };
+ let notification_ingress_service = Arc::new(SqsNotificationIngress {
+ queue: ingress_queue,
+ });
// Build document tool context for AI tools
let s3_config = aws_sdk_s3::Config::builder()
diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rs
index 34ebb1dc70..07b13f616a 100644
--- a/rust/cloud-storage/document_cognition_service/src/main.rs
+++ b/rust/cloud-storage/document_cognition_service/src/main.rs
@@ -197,11 +197,13 @@ async fn main() -> anyhow::Result<()> {
tracing::info!("initialized connection repo");
- let ingress_queue = SqsIngressQueue::new(
- aws_sdk_sqs::Client::new(&aws_config),
- config.notification_queue.clone(),
- );
- let notification_ingress_service = Arc::new(SqsNotificationIngress::new(ingress_queue));
+ let ingress_queue = SqsIngressQueue {
+ client: aws_sdk_sqs::Client::new(&aws_config),
+ queue_url: config.notification_queue.clone(),
+ };
+ let notification_ingress_service = Arc::new(SqsNotificationIngress {
+ queue: ingress_queue,
+ });
tracing::info!("initialized notification ingress service");
diff --git a/rust/cloud-storage/document_storage_service/src/main.rs b/rust/cloud-storage/document_storage_service/src/main.rs
index 7eeab4a6fd..fc4832faed 100644
--- a/rust/cloud-storage/document_storage_service/src/main.rs
+++ b/rust/cloud-storage/document_storage_service/src/main.rs
@@ -210,16 +210,19 @@ async fn main() -> anyhow::Result<()> {
);
let system_properties_service =
SystemPropertiesServiceImpl::new(PgSystemPropertiesRepository::new(db.clone()));
- let ingress_queue = SqsIngressQueue::new(
- aws_sdk_sqs::Client::new(&aws_config),
- config.vars.notification_queue.as_ref().to_string(),
- );
- let notification_ingress_service = Arc::new(SqsNotificationIngress::new(ingress_queue.clone()));
+ let ingress_queue = SqsIngressQueue {
+ client: aws_sdk_sqs::Client::new(&aws_config),
+ queue_url: config.vars.notification_queue.as_ref().to_string(),
+ };
+ let notification_ingress_service = Arc::new(SqsNotificationIngress {
+ queue: ingress_queue.clone(),
+ });
tracing::trace!("initialized notification ingress service");
let permission_checker = PermissionServiceImpl::new(db.clone());
- let notification_service =
- NotificationServiceImpl::new(SqsNotificationIngress::new(ingress_queue));
+ let notification_service = NotificationServiceImpl::new(SqsNotificationIngress {
+ queue: ingress_queue,
+ });
let properties_service = Arc::new(PropertiesServiceImpl::new(
PropertiesPgRepo::new(db.clone()),
Some(permission_checker),
diff --git a/rust/cloud-storage/email_formatting/src/lib.rs b/rust/cloud-storage/email_formatting/src/lib.rs
index c0f732c1e4..efe2f6f01b 100644
--- a/rust/cloud-storage/email_formatting/src/lib.rs
+++ b/rust/cloud-storage/email_formatting/src/lib.rs
@@ -97,6 +97,6 @@ impl NotificationExtEmail for EmailDigestNotification {
fn rate_limit_key(&self) -> RateLimitKey {
// NB: this key is currently intentionally shared across all users out of an abundance of caution to limit over-sending on SES
- RateLimitKey::from_str_hashed(Self::TYPE_NAME)
+ RateLimitKey::from_str_hashed(&Self::TYPE_NAME)
}
}
diff --git a/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs b/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs
index 59f6b18210..f09f7fc6b8 100644
--- a/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs
+++ b/rust/cloud-storage/email_service/src/bin/pubsub_workers/pubsub_workers.rs
@@ -169,11 +169,13 @@ async fn main() -> anyhow::Result<()> {
})
.context("failed to connect to redis")?;
- let ingress_queue = SqsIngressQueue::new(
- aws_sdk_sqs::Client::new(&aws_config),
- config.notification_queue.clone(),
- );
- let notification_ingress_service = Arc::new(SqsNotificationIngress::new(ingress_queue));
+ let ingress_queue = SqsIngressQueue {
+ client: aws_sdk_sqs::Client::new(&aws_config),
+ queue_url: config.notification_queue.clone(),
+ };
+ let notification_ingress_service = Arc::new(SqsNotificationIngress {
+ queue: ingress_queue,
+ });
let redis_client = email_service::util::redis::RedisClient::new(
redis_inner_client,
diff --git a/rust/cloud-storage/model-entity/src/lib.rs b/rust/cloud-storage/model-entity/src/lib.rs
index 86df3ae8ee..c20fbefd74 100644
--- a/rust/cloud-storage/model-entity/src/lib.rs
+++ b/rust/cloud-storage/model-entity/src/lib.rs
@@ -78,12 +78,8 @@ impl TryFrom<String> for EntityType {
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema, Hash, PartialEq, Eq)]
pub struct Entity<'a> {
/// The type of entity we are describing
- // TODO: we can remove this alias after a few weeks
- #[serde(alias = "eventItemType")]
pub entity_type: EntityType,
/// The id of that entity
- // TODO: we can remove this alias after a few weeks
- #[serde(alias = "eventItemId")]
pub entity_id: Cow<'a, str>,
}
diff --git a/rust/cloud-storage/model_notifications/Cargo.toml b/rust/cloud-storage/model_notifications/Cargo.toml
index 6ce7af0086..e1e2673724 100644
--- a/rust/cloud-storage/model_notifications/Cargo.toml
+++ b/rust/cloud-storage/model_notifications/Cargo.toml
@@ -15,6 +15,7 @@ models_comms = { path = "../models_comms" }
models_pagination = { path = "../models_pagination" }
notification = { path = "../notification" }
paste = { workspace = true }
+referral_invitation = { path = "../referral_invitation" }
rootcause = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
diff --git a/rust/cloud-storage/model_notifications/src/digest_state.rs b/rust/cloud-storage/model_notifications/src/digest_state.rs
index b55fa1be1e..1f8971eba1 100644
--- a/rust/cloud-storage/model_notifications/src/digest_state.rs
+++ b/rust/cloud-storage/model_notifications/src/digest_state.rs
@@ -1,12 +1,12 @@
use crate::{InviteToTeamMetadata, NewEmailMetadata};
use notification::domain::models::email_notification_digest::{
- EmailBlockList, ExplicitInviteAllowList, NotificationSetBuilder,
+ EmailBlockList, NotificationSetBuilder,
};
+use referral_invitation::InviteToMacro;
-pub fn common_email_block_list() -> EmailBlockList {
+/// define a blocklist of notification types which will never be templated into a digest email
+pub fn digest_email_block_list() -> EmailBlockList {
EmailBlockList::new::<NewEmailMetadata>()
-}
-
-pub fn common_explicit_invite_allow_list() -> ExplicitInviteAllowList {
- ExplicitInviteAllowList::new::<InviteToTeamMetadata>()
+ .append::<InviteToTeamMetadata>()
+ .append::<InviteToMacro>()
}
diff --git a/rust/cloud-storage/notification/Cargo.toml b/rust/cloud-storage/notification/Cargo.toml
index 65a0b1bfaa..342faf1757 100644
--- a/rust/cloud-storage/notification/Cargo.toml
+++ b/rust/cloud-storage/notification/Cargo.toml
@@ -36,11 +36,11 @@ itertools = { workspace = true }
last_online_tracker = { path = "../last_online_tracker" }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
-strum = { workspace = true }
model-entity = { path = "../model-entity" }
model-error-response = { path = "../model-error-response", optional = true }
model_user = { path = "../model_user", optional = true, features = ["axum"] }
models_pagination = { path = "../models_pagination" }
+rate_limit = { path = "../rate_limit" }
redis = { workspace = true, features = [
"aio",
"tokio-comp",
@@ -53,6 +53,7 @@ serde = { workspace = true }
serde_json = { workspace = true }
sha2 = { workspace = true }
sqlx = { workspace = true }
+strum = { workspace = true }
thiserror = { workspace = true }
tokio = { workspace = true, features = ["time"] }
tracing = { workspace = true }
diff --git a/rust/cloud-storage/notification/src/domain/models/email_notification_digest.rs b/rust/cloud-storage/notification/src/domain/models/email_notification_digest.rs
index 3e565aed10..39e5445797 100644
--- a/rust/cloud-storage/notification/src/domain/models/email_notification_digest.rs
+++ b/rust/cloud-storage/notification/src/domain/models/email_notification_digest.rs
@@ -55,9 +55,6 @@ impl<T> BatchSend<T> {
}
}
-/// Send immediately as a single notification email.
-pub struct SingleSend<T>(T);
-
/// Do not send an email for this notification.
pub struct DontSend(());
@@ -72,7 +69,7 @@ impl DontSend {
struct NotificationSet(HashSet<&'static str>);
/// trait used to create a set of notifications.
-/// implemented by [EmailBlockList] and [ExplicitInviteAllowList]
+/// implemented by [EmailBlockList]
pub trait NotificationSetBuilder {
/// create a new instance of self, blocking notifications of a specific value
/// from being sent via email digest
@@ -118,10 +115,8 @@ impl NotificationSet {
/// HasPush{"Push notifications on?"}
/// IsOnline{"Online recently?"}
/// GotPush{"Got push notification?"}
-/// IsInvite{"Explicit invite?"}
///
/// DontSend(["DON'T SEND"]):::red
-/// Send(["SEND"]):::green
/// BatchSend(["BATCH SEND"]):::blue
///
/// Start --> IsNewEmail
@@ -129,7 +124,7 @@ impl NotificationSet {
/// IsNewEmail -->|YES| DontSend
///
/// HasAccount -->|YES| HasPush
-/// HasAccount -->|NO| IsInvite
+/// HasAccount -->|NO| BatchSend
///
/// HasPush -->|NO| IsOnline
/// HasPush -->|YES| GotPush
@@ -140,11 +135,7 @@ impl NotificationSet {
/// GotPush -->|YES| DontSend
/// GotPush -->|NO| BatchSend
///
-/// IsInvite -->|YES| Send
-/// IsInvite -->|NO| BatchSend
-///
/// classDef red fill:#8B0000,stroke:#FF6B6B,color:#fff
-/// classDef green fill:#006400,stroke:#90EE90,color:#fff
/// classDef blue fill:#00008B,stroke:#6495ED,color:#fff
/// ```
pub struct EmailBlockList(NotificationSet);
@@ -175,7 +166,7 @@ impl EmailBlockList {
}
}
-/// represents a notification that is allowed to be sent as part of a [EmailSendDecision]
+/// A notification that has passed the block-list check and may proceed through the state machine.
pub struct AllowedNotification<T> {
inner: UserNotificationRow<Arc<T>>,
}
@@ -187,68 +178,24 @@ pub struct AccountExists<T> {
prev: AllowedNotification<T>,
}
-/// State indicating the notification recipient does not have a Macro account.
-///
-/// Next step: decide between single send (for invites) or batch send.
-pub struct AccountDoesNotExist<T> {
- prev: AllowedNotification<T>,
-}
-
impl<T> AllowedNotification<T> {
/// Check if the notification recipient has a Macro account.
///
/// Returns [`AccountExists`] if the user has an account (check push settings next),
- /// or [`AccountDoesNotExist`] if they don't (decide batch vs single send).
+ /// or [`BatchSend`] if they don't (no account means batch send immediately).
pub async fn check_user_existence(
self,
checker: &impl UserExistenceChecker,
- ) -> Result<Either<AccountExists<T>, AccountDoesNotExist<T>>, Report> {
+ ) -> Result<Either<AccountExists<T>, BatchSend<UserNotificationRow<Arc<T>>>>, Report> {
let owner = self.inner.owner_id.copied();
match checker.user_exists(owner).await {
Ok(true) => Ok(Either::Left(AccountExists { prev: self })),
- Ok(false) => Ok(Either::Right(AccountDoesNotExist { prev: self })),
+ Ok(false) => Ok(Either::Right(BatchSend(self.inner))),
Err(e) => Err(e),
}
}
}
-/// A set of notification types that should be sent immediately (not batched).
-///
-/// These are typically invite notifications where timely delivery matters
-/// more than batching for digest efficiency.
-pub struct ExplicitInviteAllowList(NotificationSet);
-
-impl NotificationSetBuilder for ExplicitInviteAllowList {
- fn new<T: Notification>() -> Self {
- Self(NotificationSet::new::<T>())
- }
-
- fn append<T: Notification>(self) -> Self {
- Self(NotificationSet::append::<T>(self.0))
- }
-}
-
-/// type alias for the data returned from [AccountDoesNotExist::batch_or_single_send]
-pub type EmailSendDecision<T> = Either<SingleSend<T>, BatchSend<T>>;
-impl<T> AccountDoesNotExist<T> {
- /// Decide whether to send immediately or batch for digest.
- ///
- /// Returns [`EmailSendDecision::SingleSend`] for explicit invite notifications,
- /// or [`EmailSendDecision::BatchSend`] for all other notification types.
- pub fn batch_or_single_send(
- self,
- invite_list: &ExplicitInviteAllowList,
- ) -> EmailSendDecision<UserNotificationRow<Arc<T>>> {
- match invite_list
- .0
- .is_member(&self.prev.inner.dangerous_get_typename())
- {
- true => EmailSendDecision::Left(SingleSend(self.prev.inner)),
- false => EmailSendDecision::Right(BatchSend(self.prev.inner)),
- }
- }
-}
-
/// State indicating the user has push notifications enabled.
///
/// If push was delivered successfully, don't send email. Otherwise, batch send.
@@ -337,7 +284,7 @@ pub trait BulkDigestStateMachine: Send + Sync + 'static {
fn ingest<T: Serialize + Send + Sync + 'static>(
&self,
notif: UserNotificationRow<Arc<T>>,
- ) -> impl Future<Output = Result<StateMachineDecisionA<T>, Report>> + Send;
+ ) -> impl Future<Output = Result<StateMachineDecisionA, Report>> + Send;
}
/// a struct which is able to drive the state machine to a decision on a given notification
@@ -355,8 +302,6 @@ pub struct StateMachineDriverA<U, N, O, B> {
pub digest_batcher: B,
/// The blocklist for notifications which are never forwarded to bulk.
pub block_list: EmailBlockList,
- /// The allow list for checking if a notification is analogous to an "invite to macro" notification.
- pub invite_list: ExplicitInviteAllowList,
/// The window of time in which the digest emails are collected for before sending.
pub digest_window: Duration,
/// The duration for how recently a user has been online.
@@ -372,7 +317,6 @@ impl<U, N, O, B> StateMachineDriverA<U, N, O, B> {
online_checker: O,
digest_batcher: B,
block_list: EmailBlockList,
- invite_list: ExplicitInviteAllowList,
) -> Self {
Self {
user_checker,
@@ -380,7 +324,6 @@ impl<U, N, O, B> StateMachineDriverA<U, N, O, B> {
online_checker,
digest_batcher,
block_list,
- invite_list,
digest_window: std::time::Duration::from_mins(30),
online_duration_threshold: std::time::Duration::from_mins(60),
}
@@ -388,7 +331,7 @@ impl<U, N, O, B> StateMachineDriverA<U, N, O, B> {
}
/// the initial decision created during notification ingress
-pub enum StateMachineDecisionA<T> {
+pub enum StateMachineDecisionA {
/// we will not send a batch email
DontSend(DontSend),
/// we already queued a batch email to send
@@ -398,10 +341,7 @@ pub enum StateMachineDecisionA<T> {
///
/// This allows the egress worker to continue the state machine after we know what the status
/// of the push notification is.
- Indeterminate(BatchSend<PushNotificationsEnabled>),
- /// we should template the contained notification into an email to send immediately.
- /// The caller is responsible for templating this notification into an email and queuing it for delivery
- SendImmediate(SingleSend<UserNotificationRow<Arc<T>>>),
+ Indeterminate(Box<BatchSend<PushNotificationsEnabled>>),
}
impl<U, N, O, B> StateMachineDriverA<U, N, O, B>
@@ -417,34 +357,28 @@ where
pub async fn ingest<T: Serialize>(
&self,
notif: UserNotificationRow<Arc<T>>,
- ) -> Result<StateMachineDecisionA<T>, Report> {
+ ) -> Result<StateMachineDecisionA, Report> {
let allowed = match self.block_list.notification_is_allowed(notif) {
Either::Left(l) => l,
Either::Right(r) => {
return Ok(StateMachineDecisionA::DontSend(r));
}
};
- let push_notification_state = match allowed
- .check_user_existence(&self.user_checker)
- .await?
- .map_right(|r| r.batch_or_single_send(&self.invite_list))
+ let push_notification_state = match allowed.check_user_existence(&self.user_checker).await?
{
Either::Left(l) => {
l.push_notifications_enabled(&self.notification_checker)
.await?
}
- Either::Right(Either::Left(rl)) => {
- return Ok(StateMachineDecisionA::SendImmediate(rl));
- }
- Either::Right(Either::Right(rr)) => {
+ Either::Right(r) => {
return Ok(StateMachineDecisionA::BatchWasQueued(
- self.inner_store_batch(rr).await?,
+ self.inner_store_batch(r).await?,
));
}
};
let last_online = match push_notification_state {
Either::Left(l) => {
- return Ok(StateMachineDecisionA::Indeterminate(BatchSend(l)));
+ return Ok(StateMachineDecisionA::Indeterminate(Box::new(BatchSend(l))));
}
Either::Right(r) => {
r.check_last_online_time(&self.online_checker, self.online_duration_threshold)
@@ -484,7 +418,7 @@ where
fn ingest<T: Serialize + Send + Sync + 'static>(
&self,
notif: UserNotificationRow<Arc<T>>,
- ) -> impl Future<Output = Result<StateMachineDecisionA<T>, Report>> + Send {
+ ) -> impl Future<Output = Result<StateMachineDecisionA, Report>> + Send {
self.ingest(notif)
}
}
diff --git a/rust/cloud-storage/notification/src/domain/models/email_notification_digest/test.rs b/rust/cloud-storage/notification/src/domain/models/email_notification_digest/test.rs
index 2b7bd11903..351084b1e1 100644
--- a/rust/cloud-storage/notification/src/domain/models/email_notification_digest/test.rs
+++ b/rust/cloud-storage/notification/src/domain/models/email_notification_digest/test.rs
@@ -32,24 +32,6 @@ impl Notification for BlockedNotification {
const TYPE_NAME: &'static str = "blocked_notification";
}
-/// An invite notification that should be sent immediately (single send).
-#[derive(Debug, Clone, Serialize, Deserialize)]
-struct InviteNotification {
- workspace_name: String,
-}
-
-impl Notification for InviteNotification {
- const TYPE_NAME: &'static str = "invite_notification";
-}
-
-/// A workspace invite notification for testing multiple invite types.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-struct WorkspaceInviteNotification;
-
-impl Notification for WorkspaceInviteNotification {
- const TYPE_NAME: &'static str = "workspace_invite_notification";
-}
-
// ============================================================================
// Mock Implementations
// ============================================================================
@@ -214,10 +196,6 @@ fn create_block_list() -> EmailBlockList {
EmailBlockList::new::<BlockedNotification>()
}
-fn create_invite_list() -> ExplicitInviteAllowList {
- ExplicitInviteAllowList::new::<InviteNotification>().append::<WorkspaceInviteNotification>()
-}
-
// ============================================================================
// EmailBlockList Tests
// ============================================================================
@@ -685,96 +663,6 @@ async fn test_check_last_online_time_edge_case_zero_last_online() {
);
}
-// ============================================================================
-// AccountDoesNotExist::batch_or_single_send Tests
-// ============================================================================
-
-#[tokio::test]
-async fn test_batch_or_single_send_returns_single_send_for_invite() {
- let block_list = create_block_list();
- let notif = create_test_notification_row(InviteNotification {
- workspace_name: "Test Workspace".to_string(),
- });
-
- let allowed = block_list
- .notification_is_allowed(notif)
- .left()
- .expect("Should be allowed");
-
- let user_checker = MockUserExistenceChecker::with_user_not_exists();
- let account_not_exists = allowed
- .check_user_existence(&user_checker)
- .await
- .unwrap()
- .right()
- .expect("Should be AccountDoesNotExist");
-
- let invite_list = create_invite_list();
- let result = account_not_exists.batch_or_single_send(&invite_list);
-
- assert!(
- result.is_left(),
- "Should return SingleSend for invite notifications"
- );
-}
-
-#[tokio::test]
-async fn test_batch_or_single_send_returns_batch_send_for_non_invite() {
- let block_list = create_block_list();
- let notif = create_test_notification_row(TestNotification {
- message: "hello".to_string(),
- });
-
- let allowed = block_list
- .notification_is_allowed(notif)
- .left()
- .expect("Should be allowed");
-
- let user_checker = MockUserExistenceChecker::with_user_not_exists();
- let account_not_exists = allowed
- .check_user_existence(&user_checker)
- .await
- .unwrap()
- .right()
- .expect("Should be AccountDoesNotExist");
-
- let invite_list = create_invite_list();
- let result = account_not_exists.batch_or_single_send(&invite_list);
-
- assert!(
- result.is_right(),
- "Should return BatchSend for non-invite notifications"
- );
-}
-
-#[tokio::test]
-async fn test_batch_or_single_send_with_multiple_invite_types() {
- // Test that workspace invite also gets single send
- let block_list = create_block_list();
- let notif = create_test_notification_row(WorkspaceInviteNotification);
-
- let allowed = block_list
- .notification_is_allowed(notif)
- .left()
- .expect("Should be allowed");
-
- let user_checker = MockUserExistenceChecker::with_user_not_exists();
- let account_not_exists = allowed
- .check_user_existence(&user_checker)
- .await
- .unwrap()
- .right()
- .expect("Should be AccountDoesNotExist");
-
- let invite_list = create_invite_list();
- let result = account_not_exists.batch_or_single_send(&invite_list);
-
- assert!(
- result.is_left(),
- "Should return SingleSend for workspace invite notifications"
- );
-}
-
// ============================================================================
// Full Flow Integration Tests
// ============================================================================
@@ -918,39 +806,7 @@ async fn test_full_flow_user_exists_push_disabled_offline() {
}
#[tokio::test]
-async fn test_full_flow_user_not_exists_invite() {
- let block_list = create_block_list();
- let notif = create_test_notification_row(InviteNotification {
- workspace_name: "Test Workspace".to_string(),
- });
-
- // Step 1: Check if allowed
- let allowed = block_list
- .notification_is_allowed(notif)
- .left()
- .expect("Should be allowed");
-
- // Step 2: Check user existence - does not exist
- let user_checker = MockUserExistenceChecker::with_user_not_exists();
- let account_not_exists = allowed
- .check_user_existence(&user_checker)
- .await
- .unwrap()
- .right()
- .expect("Should be AccountDoesNotExist");
-
- // Step 3: Decide batch vs single - invite should be single
- let invite_list = create_invite_list();
- let result = account_not_exists.batch_or_single_send(&invite_list);
-
- assert!(
- result.is_left(),
- "Full flow: user does not exist, invite notification should return SingleSend"
- );
-}
-
-#[tokio::test]
-async fn test_full_flow_user_not_exists_non_invite() {
+async fn test_full_flow_user_not_exists() {
let block_list = create_block_list();
let notif = create_test_notification_row(TestNotification {
message: "hello".to_string(),
@@ -962,21 +818,12 @@ async fn test_full_flow_user_not_exists_non_invite() {
.left()
.expect("Should be allowed");
- // Step 2: Check user existence - does not exist
+ // Step 2: Check user existence - does not exist → always BatchSend
let user_checker = MockUserExistenceChecker::with_user_not_exists();
- let account_not_exists = allowed
- .check_user_existence(&user_checker)
- .await
- .unwrap()
- .right()
- .expect("Should be AccountDoesNotExist");
-
- // Step 3: Decide batch vs single - non-invite should be batch
- let invite_list = create_invite_list();
- let result = account_not_exists.batch_or_single_send(&invite_list);
+ let result = allowed.check_user_existence(&user_checker).await.unwrap();
assert!(
result.is_right(),
- "Full flow: user does not exist, non-invite notification should return BatchSend"
+ "Full flow: user does not exist should return BatchSend"
);
}
diff --git a/rust/cloud-storage/notification/src/domain/models/queue_message.rs b/rust/cloud-storage/notification/src/domain/models/queue_message.rs
index e0a9559b68..8f5eca75d8 100644
--- a/rust/cloud-storage/notification/src/domain/models/queue_message.rs
+++ b/rust/cloud-storage/notification/src/domain/models/queue_message.rs
@@ -12,6 +12,7 @@ use chrono::{DateTime, Utc};
use cowlike::CowLike;
use macro_user_id::user_id::MacroUserIdStr;
use model_entity::Entity;
+use rate_limit::RateLimitExceeded;
use rootcause::Report;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
@@ -28,7 +29,7 @@ pub struct UserApnsEndpoints {
pub endpoints: Vec<String>,
/// State machine data if the ingress decision was indeterminate for this user.
#[serde(default)]
- pub digest_state: Option<BatchSend<PushNotificationsEnabled>>,
+ pub digest_state: Option<Box<BatchSend<PushNotificationsEnabled>>>,
}
/// APNS push notification targets.
@@ -55,13 +56,13 @@ pub struct EmailContent {
#[derive(Debug, Serialize, Deserialize)]
pub struct EmailNotification<'a> {
/// The recipient email/user ID.
- to: MacroUserIdStr<'a>,
+ pub(crate) to: MacroUserIdStr<'a>,
/// The email content (subject and body).
pub content: EmailContent,
- rate_limit_config: RateLimitConfig,
+ pub(crate) rate_limit_config: RateLimitConfig,
- rate_limit_key: RateLimitKey,
+ pub(crate) rate_limit_key: RateLimitKey,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -108,11 +109,6 @@ impl<'a> EmailNotification<'a> {
pub fn to(&'a self) -> MacroUserIdStr<'a> {
self.to.copied()
}
-
- /// return the rate limit configuration
- pub fn rate_limit(&self) -> (&RateLimitConfig, &RateLimitKey) {
- (&self.rate_limit_config, &self.rate_limit_key)
- }
}
/// the value of the inner payload inside [ConnGatewayNotification]
@@ -295,24 +291,25 @@ impl<'a, T, U> QueueMessageNeedsStateMachine<'a, T, U> {
/// open the inner container by applying the state machine output to the necessary fields
pub fn with_state_decisions(
self,
- states: Vec<Result<StateMachineDecisionA<T>, Report>>,
+ states: Vec<Result<StateMachineDecisionA, Report>>,
) -> impl Iterator<Item = QueueMessage<'a, T, U>> {
// Collect indeterminate decisions keyed by owner_id
- let indeterminates: HashMap<MacroUserIdStr<'static>, BatchSend<PushNotificationsEnabled>> =
- states
- .into_iter()
- .filter_map(|v| match v {
- Ok(StateMachineDecisionA::Indeterminate(indeterminate)) => Some(indeterminate),
- Err(_)
- | Ok(StateMachineDecisionA::DontSend(_))
- | Ok(StateMachineDecisionA::BatchWasQueued(_))
- | Ok(StateMachineDecisionA::SendImmediate(_)) => None,
- })
- .map(|batch| {
- let owner = batch.inner().owner_id().clone();
- (owner, batch)
- })
- .collect();
+ let indeterminates: HashMap<
+ MacroUserIdStr<'static>,
+ Box<BatchSend<PushNotificationsEnabled>>,
+ > = states
+ .into_iter()
+ .filter_map(|v| match v {
+ Ok(StateMachineDecisionA::Indeterminate(indeterminate)) => Some(indeterminate),
+ Err(_)
+ | Ok(StateMachineDecisionA::DontSend(_))
+ | Ok(StateMachineDecisionA::BatchWasQueued(_)) => None,
+ })
+ .map(|batch| {
+ let owner = batch.inner().owner_id().clone();
+ (owner, batch)
+ })
+ .collect();
let mut indeterminates = Some(indeterminates);
@@ -380,7 +377,7 @@ pub enum DeliverySuccess {
pub enum DeliveryFailure {
/// The rate limit for this notification type was exceeded.
#[error("The rate limit was exceeded")]
- RateLimit,
+ RateLimit(RateLimitExceeded),
/// a timeout limit was reached trying to deliver the notif
#[error("A timeout was reached")]
Timeout,
diff --git a/rust/cloud-storage/notification/src/domain/models/rate_limit.rs b/rust/cloud-storage/notification/src/domain/models/rate_limit.rs
index 6356335af4..552dcbf095 100644
--- a/rust/cloud-storage/notification/src/domain/models/rate_limit.rs
+++ b/rust/cloud-storage/notification/src/domain/models/rate_limit.rs
@@ -1,85 +1,3 @@
-//! Rate limiting models for the notification service.
+//! Rate limiting models — re-exported from the [`rate_limit`] crate.
-use serde::{Deserialize, Serialize};
-use std::time::Duration;
-use thiserror::Error;
-
-/// Newtype for rate limit keys.
-///
-/// Callers control what gets rate limited by constructing a key from relevant
-/// data (e.g., event type + sender email). The internal value is a hash.
-#[derive(Debug, Clone, Default, Serialize, Deserialize)]
-#[serde(transparent)]
-pub struct RateLimitKey(Vec<u8>);
-
-impl RateLimitKey {
- /// Create a rate limit key by hashing the input string.
- pub fn from_str_hashed(input: &str) -> Self {
- use std::hash::{DefaultHasher, Hash, Hasher};
- let mut hasher = DefaultHasher::new();
- input.hash(&mut hasher);
- Self(hasher.finish().to_le_bytes().to_vec())
- }
-
- /// Get the internal bytes.
- pub fn as_bytes(&self) -> &[u8] {
- &self.0
- }
-
- /// Convert to a hex string for use as a cache key.
- pub fn to_hex_string(&self) -> String {
- hex::encode(&self.0)
- }
-}
-
-/// Result of a rate limit check.
-#[derive(Debug)]
-pub enum RateLimitResult {
- /// The action is allowed. Contains the current count after increment.
- Allowed {
- /// The current count after increment.
- current_count: u64,
- },
- /// The rate limit has been exceeded.
- Exceeded(RateLimitExceeded),
-}
-
-/// Error returned when a rate limit is exceeded.
-#[derive(Debug, Error)]
-#[error(
- "Rate limit key: {key} was exceeded. Current count is {current_count} but max count is {max_count}"
-)]
-pub struct RateLimitExceeded {
- /// The key that is exceeded.
- pub key: String,
- /// The current count.
- pub current_count: u64,
- /// The maximum allowed count.
- pub max_count: u64,
-}
-
-/// Configuration for rate limiting.
-#[derive(Debug, Clone, Serialize, Deserialize)]
-pub struct RateLimitConfig {
- /// Maximum number of actions allowed in the window.
- pub max_count: u64,
- /// Time window for rate limiting.
- pub window: Duration,
-}
-
-impl RateLimitConfig {
- /// Create a new rate limit config.
- pub fn new(max_count: u64, window: Duration) -> Self {
- Self { max_count, window }
- }
-
- /// Rate limit for channel invites: 10 per hour.
- pub fn channel_invite() -> Self {
- Self::new(10, Duration::from_secs(3600))
- }
-
- /// Rate limit for team invites: 5 per hour.
- pub fn team_invite() -> Self {
- Self::new(5, Duration::from_secs(3600))
- }
-}
+pub use rate_limit::domain::models::*;
diff --git a/rust/cloud-storage/notification/src/domain/ports.rs b/rust/cloud-storage/notification/src/domain/ports.rs
index 43997bda8b..408d6b65a0 100644
--- a/rust/cloud-storage/notification/src/domain/ports.rs
+++ b/rust/cloud-storage/notification/src/domain/ports.rs
@@ -20,9 +20,9 @@ use crate::domain::models::device::DeviceType;
use crate::domain::models::email_notification_digest::ports::{ClaimResult, DigestBatch};
use crate::domain::models::{
- DeviceEndpoint, NotificationExtEmail, NotificationIdAndCollapseKey, RateLimitConfig,
- RateLimitKey, RateLimitResult, SendNotificationRequestBuilder, UserNotificationRow,
- android::FCMMessage, apple::APNSPushNotification, mobile::MessageAttributes,
+ DeviceEndpoint, NotificationExtEmail, NotificationIdAndCollapseKey,
+ SendNotificationRequestBuilder, UserNotificationRow, android::FCMMessage,
+ apple::APNSPushNotification, mobile::MessageAttributes,
};
/// Port for sending mobile push notifications (iOS/Android via SNS).
@@ -48,27 +48,7 @@ pub trait NotificationSender: Send + Sync + 'static {
) -> impl Future<Output = Result<String, Report>> + Send;
}
-/// Port for rate limiting operations.
-pub trait RateLimitPort: Send + Sync + 'static {
- /// Check if the action is allowed without incrementing the counter.
- ///
- /// The `RateLimitKey` is a hashed value - callers control what gets rate
- /// limited by constructing the key from relevant data.
- fn check(
- &self,
- key: &RateLimitKey,
- config: &RateLimitConfig,
- ) -> impl Future<Output = Result<RateLimitResult, Report>> + Send;
-
- /// Increment the rate limit counter for a key.
- ///
- /// Should only be called after a successful action.
- fn increment(
- &self,
- key: &RateLimitKey,
- config: &RateLimitConfig,
- ) -> impl Future<Output = Result<u64, Report>> + Send;
-}
+pub use rate_limit::{RateLimitPort, RateLimitService};
/// Port for notification persistence operations.
pub trait NotificationRepository: Send + Sync + 'static {
@@ -263,6 +243,16 @@ pub trait NotificationQueue: Send + Sync + 'static {
&self,
receipt_handle: &str,
) -> impl Future<Output = Result<(), Report>> + Send;
+
+ /// Delay a message by changing its visibility timeout.
+ ///
+ /// The message will not be redelivered to consumers until the duration elapses.
+ /// Uses SQS `ChangeMessageVisibility` under the hood.
+ fn delay_message(
+ &self,
+ receipt_handle: &str,
+ delay: std::time::Duration,
+ ) -> impl Future<Output = Result<(), Report>> + Send;
}
/// Port for delivering notifications from the queue.
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 a3f98ec59e..840bbc00a9 100644
--- a/rust/cloud-storage/notification/src/domain/service/device/test.rs
+++ b/rust/cloud-storage/notification/src/domain/service/device/test.rs
@@ -288,6 +288,14 @@ impl NotificationQueue for MockQueue {
async fn delete_message(&self, _: &str) -> Result<(), Report> {
Ok(())
}
+
+ async fn delay_message(
+ &self,
+ _receipt_handle: &str,
+ _delay: std::time::Duration,
+ ) -> Result<(), Report> {
+ Ok(())
+ }
}
fn test_config() -> PlatformArnConfig {
diff --git a/rust/cloud-storage/notification/src/domain/service/egress.rs b/rust/cloud-storage/notification/src/domain/service/egress.rs
index 1344804796..ba9162e811 100644
--- a/rust/cloud-storage/notification/src/domain/service/egress.rs
+++ b/rust/cloud-storage/notification/src/domain/service/egress.rs
@@ -3,8 +3,6 @@
//! This service handles the worker-facing side of notifications:
//! consuming from the queue and delivering via WebSocket, push, and email.
-use std::time::Duration;
-
use crate::domain::models::apple::APNSPushNotification;
use crate::domain::models::email_notification_digest::ports::{
ClaimResult, DigestBatch, DigestBatcher, MessageId, NotificationSendChecker,
@@ -20,7 +18,7 @@ use crate::domain::models::queue_message::{
use crate::domain::models::{NotificationExtEmail, NotificationTypeName, RateLimitResult};
use crate::domain::ports::{
EmailSender, NotificationEgress, NotificationQueue, NotificationRepository, NotificationSender,
- RateLimitPort, WebSocketSender,
+ RateLimitService, WebSocketSender,
};
use either::Either;
use futures::stream::{FuturesUnordered, StreamExt};
@@ -28,6 +26,7 @@ use macro_user_id::email::ReadEmailParts;
use macro_user_id::user_id::MacroUserIdStr;
use rootcause::prelude::ResultExt;
use rootcause::{Report, report};
+use std::time::Duration;
use tracing::Level;
/// Maximum time to wait for a single notification delivery before timing out.
@@ -88,7 +87,7 @@ where
W: WebSocketSender,
M: NotificationSender,
E: EmailSender,
- R: RateLimitPort,
+ R: RateLimitService,
S: BulkDigestEgressStateMachine,
D: DigestBatcher,
{
@@ -110,9 +109,7 @@ where
.deliver_conn_gateway(conn)
.await
.context(DeliveryFailure::Other)]),
- NotificationChannel::Email(ref email) => {
- Either::Left([self.deliver_email(email).await])
- }
+ NotificationChannel::Email(email) => Either::Left([self.deliver_email(email).await]),
NotificationChannel::Ios(apns) => Either::Right(
self.deliver_ios(&apns)
.await
@@ -200,36 +197,49 @@ where
/// Deliver via email.
async fn deliver_email(
&self,
- email: &EmailNotification<'static>,
+ email: EmailNotification<'static>,
) -> Result<DeliverySuccess, Report<DeliveryFailure>> {
- let (config, key) = email.rate_limit();
+ let EmailNotification {
+ content,
+ to: recipient,
+ rate_limit_config,
+ rate_limit_key,
+ } = email;
+
+ let ticket = self
+ .rate_limiter
+ .check_rate_limit(rate_limit_key, rate_limit_config)
+ .await
+ .context(DeliveryFailure::Other)?;
- match self.rate_limiter.check(key, config).await {
- Ok(RateLimitResult::Exceeded(exceeded)) => {
- return Err(report!(exceeded).context(DeliveryFailure::RateLimit));
- }
- Ok(RateLimitResult::Allowed { .. }) => {
- // Rate limit allowed, continue
+ match &*ticket {
+ RateLimitResult::Exceeded(exceeded) => {
+ return Err(report!(
+ "Rate limit key: {} was exceeded. Current count is {} but max count is {}",
+ exceeded.key,
+ exceeded.current_count,
+ exceeded.max_count
+ )
+ .context(DeliveryFailure::RateLimit(exceeded.clone())));
}
- Err(e) => return Err(e.context(DeliveryFailure::Other)),
+ RateLimitResult::Allowed { .. } => {}
}
- let recipient = email.to();
self.email
- .send_email(recipient.clone(), &email.content)
+ .send_email(recipient.clone(), &content)
.await
.inspect_err(|e| {
tracing::error!(
error = ?e,
recipient = %recipient,
- subject = %email.content.subject,
+ subject = %content.subject,
"Email delivery failed"
);
})
.context(DeliveryFailure::Other)?;
self.rate_limiter
- .increment(key, config)
+ .increment_ticket(ticket)
.await
.context(DeliveryFailure::Other)?;
@@ -245,7 +255,7 @@ where
W: WebSocketSender,
M: NotificationSender,
E: EmailSender,
- R: RateLimitPort,
+ R: RateLimitService,
S: BulkDigestEgressStateMachine,
D: DigestBatcher,
{
@@ -288,18 +298,37 @@ where
let all_ios_failed = delivery_results.iter().all(
|e| matches!(e, Err(e) if matches!(e.current_context(), DeliveryFailure::Ios )),
);
-
- for result in delivery_results {
- results.push(result.map_err(Report::from));
- }
+ let rate_limited = delivery_results.iter().find_map(|e| {
+ match e.as_ref().map_err(Report::current_context) {
+ Err(DeliveryFailure::RateLimit(rate_limit)) => Some(rate_limit),
+ Ok(_)
+ | Err(
+ DeliveryFailure::Ios | DeliveryFailure::Other | DeliveryFailure::Timeout,
+ ) => None,
+ }
+ });
// Delete from queue if any deliveries succeeded
// or all the failed notifs were ios
if (any_succeeded || all_ios_failed)
&& let Err(e) = self.queue.delete_message(&receipt_handle).await
{
+ // push the failed delete to errors
+ results.push(Err(e))
+ } else if let Some(rate_limited) = rate_limited
+ && let Err(e) = self
+ .queue
+ // if we got rate limited, delay this message by the rate limit expiry time
+ .delay_message(&receipt_handle, rate_limited.retry_after)
+ .await
+ {
+ // push the failed delay to errors
results.push(Err(e))
}
+
+ for result in delivery_results {
+ results.push(result.map_err(Report::from));
+ }
}
results
diff --git a/rust/cloud-storage/notification/src/domain/service/ingress.rs b/rust/cloud-storage/notification/src/domain/service/ingress.rs
index 912462967b..160d0cd79f 100644
--- a/rust/cloud-storage/notification/src/domain/service/ingress.rs
+++ b/rust/cloud-storage/notification/src/domain/service/ingress.rs
@@ -135,11 +135,7 @@ where
Q: NotificationQueue,
S: BulkDigestStateMachine,
{
- fn send_notification<
- 'a,
- T: Notification + Clone + 'static,
- U: Serialize + Send + Sync + 'static,
- >(
+ fn send_notification<'a, T: Notification + Clone, U: Serialize + Send + Sync + 'static>(
&'a self,
request: SendNotificationRequest<'a, T, U>,
) -> impl Future<Output = Result<Option<NotificationResult<'a>>, Report<SendNotificationError>>> + Send
@@ -369,21 +365,16 @@ where
///
/// `send_notification` always returns `Ok(None)` because the actual
/// processing is deferred to the worker.
+#[derive(Clone)]
pub struct SqsNotificationIngress<Q> {
- queue: Q,
-}
-
-impl<Q> SqsNotificationIngress<Q> {
- /// Create a new queue-backed notification ingress.
- pub fn new(queue: Q) -> Self {
- Self { queue }
- }
+ /// the inner queue
+ pub queue: Q,
}
impl<Q: NotificationIngressQueue> NotificationIngress for SqsNotificationIngress<Q> {
async fn send_notification<
'a,
- T: Notification + Clone + 'static,
+ T: Notification + Clone,
U: Serialize + Send + Sync + 'static,
>(
&'a self,
diff --git a/rust/cloud-storage/notification/src/domain/service/test.rs b/rust/cloud-storage/notification/src/domain/service/test.rs
index ba9076e4b0..2bdb451c73 100644
--- a/rust/cloud-storage/notification/src/domain/service/test.rs
+++ b/rust/cloud-storage/notification/src/domain/service/test.rs
@@ -18,7 +18,7 @@ use crate::domain::models::{
};
use crate::domain::ports::{
EmailSender, NotificationEgress, NotificationQueue, NotificationRepository, NotificationSender,
- RateLimitPort, SnsEndpointManager, WebSocketSender,
+ SnsEndpointManager, WebSocketSender,
};
use crate::domain::service::{
NotificationEgressService, NotificationIngress, NotificationIngressService, NotificationReader,
@@ -82,7 +82,7 @@ impl NotificationExtEmail for TestNotification {
}
fn rate_limit_key(&self) -> RateLimitKey {
- RateLimitKey::from_str_hashed("test-key")
+ RateLimitKey::from_str_hashed(&"test-key")
}
}
@@ -154,7 +154,7 @@ impl BulkDigestStateMachine for MockStateMachine {
async fn ingest<T: Serialize + Send + Sync + 'static>(
&self,
_notif: UserNotificationRow<Arc<T>>,
- ) -> Result<crate::domain::models::email_notification_digest::StateMachineDecisionA<T>, Report>
+ ) -> Result<crate::domain::models::email_notification_digest::StateMachineDecisionA, Report>
{
Err(report!("not implemented"))
}
@@ -540,6 +540,14 @@ impl NotificationQueue for MockQueue {
async fn delete_message(&self, _receipt_handle: &str) -> Result<(), Report> {
Ok(())
}
+
+ async fn delay_message(
+ &self,
+ _receipt_handle: &str,
+ _delay: std::time::Duration,
+ ) -> Result<(), Report> {
+ Ok(())
+ }
}
impl NotificationQueue for std::sync::Arc<MockQueue> {
@@ -557,6 +565,14 @@ impl NotificationQueue for std::sync::Arc<MockQueue> {
async fn delete_message(&self, _receipt_handle: &str) -> Result<(), Report> {
(**self).delete_message(_receipt_handle).await
}
+
+ async fn delay_message(
+ &self,
+ receipt_handle: &str,
+ delay: std::time::Duration,
+ ) -> Result<(), Report> {
+ (**self).delay_message(receipt_handle, delay).await
+ }
}
/// No-op mock for SNS endpoint management used in reader service tests.
@@ -1033,26 +1049,12 @@ impl EmailSender for MockEmailSender {
}
}
-/// Mock rate limiter that can be configured to allow or exceed.
-struct MockRateLimiter {
+/// Mock rate limit port that can be configured to allow or exceed.
+struct MockRateLimitPort {
should_exceed: bool,
}
-impl MockRateLimiter {
- fn allowing() -> Self {
- Self {
- should_exceed: false,
- }
- }
-
- fn exceeding() -> Self {
- Self {
- should_exceed: true,
- }
- }
-}
-
-impl RateLimitPort for MockRateLimiter {
+impl rate_limit::RateLimitPort for MockRateLimitPort {
async fn check(
&self,
_key: &RateLimitKey,
@@ -1063,6 +1065,7 @@ impl RateLimitPort for MockRateLimiter {
key: "test_key".to_string(),
current_count: config.max_count.saturating_add(1),
max_count: config.max_count,
+ retry_after: config.window,
}))
} else {
Ok(RateLimitResult::Allowed { current_count: 1 })
@@ -1078,6 +1081,22 @@ impl RateLimitPort for MockRateLimiter {
}
}
+fn allowing_rate_limiter() -> rate_limit::RateLimitServiceImpl<MockRateLimitPort> {
+ rate_limit::RateLimitServiceImpl {
+ repo: MockRateLimitPort {
+ should_exceed: false,
+ },
+ }
+}
+
+fn exceeding_rate_limiter() -> rate_limit::RateLimitServiceImpl<MockRateLimitPort> {
+ rate_limit::RateLimitServiceImpl {
+ repo: MockRateLimitPort {
+ should_exceed: true,
+ },
+ }
+}
+
/// Mock egress state machine that forwards sends without recording message IDs or batching.
struct MockDigestBatcher;
@@ -1139,7 +1158,7 @@ impl crate::domain::models::email_notification_digest::BulkDigestEgressStateMach
}
}
-fn create_egress_service<R: RateLimitPort>(
+fn create_egress_service<R: rate_limit::RateLimitService>(
rate_limiter: R,
) -> NotificationEgressService<
MockQueue,
@@ -1181,7 +1200,7 @@ fn create_mock_notif<T: Notification>(meta: T) -> ConnGatewayInnerNotif<T> {
#[tokio::test]
async fn test_egress_rate_limit_exceeded() {
- let service = create_egress_service(MockRateLimiter::exceeding());
+ let service = create_egress_service(exceeding_rate_limiter());
let recipient = test_user_id("[email protected]");
let email = EmailCreateBundle::new(&TestNotification {
@@ -1209,7 +1228,7 @@ async fn test_egress_rate_limit_exceeded() {
#[tokio::test]
async fn test_egress_rate_limit_allowed() {
- let service = create_egress_service(MockRateLimiter::allowing());
+ let service = create_egress_service(allowing_rate_limiter());
let recipient = test_user_id("[email protected]");
let email = EmailCreateBundle::new(&TestNotification {
@@ -1230,7 +1249,7 @@ async fn test_egress_rate_limit_allowed() {
#[tokio::test]
async fn test_egress_conn_gateway_not_rate_limited() {
- let service = create_egress_service(MockRateLimiter::exceeding());
+ let service = create_egress_service(exceeding_rate_limiter());
let recipient = test_user_id("[email protected]");
let message = QueueMessage::new_test(
@@ -1594,7 +1613,7 @@ async fn test_egress_ios_attempts_all_endpoints_even_if_some_fail() {
websocket: MockWebSocketSender,
mobile: mobile_sender.clone(),
email: MockEmailSender,
- rate_limiter: MockRateLimiter::allowing(),
+ rate_limiter: allowing_rate_limiter(),
state_machine: MockEgressStateMachine,
digest_batcher: MockDigestBatcher,
};
@@ -1730,7 +1749,7 @@ async fn test_poll_email_digests_sends_email_for_ready_batch() {
websocket: MockWebSocketSender,
mobile: MockMobileSender,
email: MockEmailSender,
- rate_limiter: MockRateLimiter::allowing(),
+ rate_limiter: allowing_rate_limiter(),
state_machine: MockEgressStateMachine,
digest_batcher: batcher,
};
@@ -1789,7 +1808,7 @@ async fn it_fails_to_send_to_non_macro_users() {
websocket: MockWebSocketSender,
mobile: MockMobileSender,
email: MockEmailSender,
- rate_limiter: MockRateLimiter::allowing(),
+ rate_limiter: allowing_rate_limiter(),
state_machine: MockEgressStateMachine,
digest_batcher: batcher,
};
@@ -1808,7 +1827,7 @@ async fn it_fails_to_send_to_non_macro_users() {
#[tokio::test]
async fn test_poll_email_digests_noop_when_empty() {
- let service = create_egress_service(MockRateLimiter::allowing());
+ let service = create_egress_service(allowing_rate_limiter());
fn digest_to_notif(_batch: DigestBatch) -> Result<TestNotification, Report> {
panic!("should not be called when empty")
@@ -1860,6 +1879,14 @@ impl NotificationQueue for EgressTestQueue {
.push(receipt_handle.to_string());
Ok(())
}
+
+ async fn delay_message(
+ &self,
+ _receipt_handle: &str,
+ _delay: std::time::Duration,
+ ) -> Result<(), Report> {
+ Ok(())
+ }
}
/// WebSocket sender that hangs indefinitely (simulates a stuck connection).
@@ -1929,7 +1956,7 @@ async fn test_poll_and_deliver_times_out_slow_delivery() {
websocket: HangingWebSocketSender,
mobile: MockMobileSender,
email: MockEmailSender,
- rate_limiter: MockRateLimiter::allowing(),
+ rate_limiter: allowing_rate_limiter(),
state_machine: MockEgressStateMachine,
digest_batcher: MockDigestBatcher,
};
@@ -1997,7 +2024,7 @@ async fn test_poll_and_deliver_deletes_message_when_all_ios_failures() {
websocket: MockWebSocketSender,
mobile: FailingMobileSender,
email: MockEmailSender,
- rate_limiter: MockRateLimiter::allowing(),
+ rate_limiter: allowing_rate_limiter(),
state_machine: MockEgressStateMachine,
digest_batcher: MockDigestBatcher,
};
@@ -2082,7 +2109,9 @@ async fn test_sqs_notification_ingress_publishes_to_queue() {
use crate::domain::service::SqsNotificationIngress;
let queue = Arc::new(MockIngressQueue::new());
- let ingress = SqsNotificationIngress::new(queue.clone());
+ let ingress = SqsNotificationIngress {
+ queue: queue.clone(),
+ };
let recipient = test_user_id("[email protected]");
let request = SendNotificationRequestBuilder {
diff --git a/rust/cloud-storage/notification/src/outbound/queue.rs b/rust/cloud-storage/notification/src/outbound/queue.rs
index e7413a51de..ea8ce7baee 100644
--- a/rust/cloud-storage/notification/src/outbound/queue.rs
+++ b/rust/cloud-storage/notification/src/outbound/queue.rs
@@ -77,6 +77,21 @@ impl NotificationQueue for SqsNotificationQueue {
.await?;
Ok(())
}
+
+ async fn delay_message(
+ &self,
+ receipt_handle: &str,
+ delay: std::time::Duration,
+ ) -> Result<(), Report> {
+ self.client
+ .change_message_visibility()
+ .queue_url(&self.queue_url)
+ .receipt_handle(receipt_handle)
+ .visibility_timeout(delay.as_secs() as i32)
+ .send()
+ .await?;
+ Ok(())
+ }
}
/// File-based queue for local development across multiple processes.
@@ -162,6 +177,15 @@ impl NotificationQueue for FileQueue {
}
Ok(())
}
+
+ async fn delay_message(
+ &self,
+ _receipt_handle: &str,
+ _delay: std::time::Duration,
+ ) -> Result<(), Report> {
+ // No-op for file-based queue.
+ Ok(())
+ }
}
/// SQS-backed implementation of the notification ingress queue port.
@@ -170,15 +194,10 @@ impl NotificationQueue for FileQueue {
/// type-erased notification requests, and by the ingress worker to consume them.
#[derive(Clone)]
pub struct SqsIngressQueue {
- client: SqsClient,
- queue_url: String,
-}
-
-impl SqsIngressQueue {
- /// Create a new SQS ingress queue adapter.
- pub fn new(client: SqsClient, queue_url: String) -> Self {
- Self { client, queue_url }
- }
+ /// the sqs client
+ pub client: SqsClient,
+ /// the url of the queue
+ pub queue_url: String,
}
impl NotificationIngressQueue for SqsIngressQueue {
diff --git a/rust/cloud-storage/notification/src/outbound/rate_limit.rs b/rust/cloud-storage/notification/src/outbound/rate_limit.rs
index 8af08a11e4..1072a08b83 100644
--- a/rust/cloud-storage/notification/src/outbound/rate_limit.rs
+++ b/rust/cloud-storage/notification/src/outbound/rate_limit.rs
@@ -1,94 +1,3 @@
-//! Redis-based rate limit adapter.
+//! Redis-based rate limit adapter — re-exported from the [`rate_limit`] crate.
-use redis::AsyncCommands;
-use rootcause::Report;
-
-use crate::domain::models::{RateLimitConfig, RateLimitExceeded, RateLimitKey, RateLimitResult};
-use crate::domain::ports::RateLimitPort;
-
-/// Redis-based implementation of the rate limit port.
-///
-/// This adapter uses Redis to store and check rate limit counters.
-/// The key is provided by the caller (already hashed), and this adapter
-/// handles the Redis operations.
-pub struct RedisRateLimitAdapter<R> {
- redis: R,
-}
-
-impl<R> RedisRateLimitAdapter<R> {
- /// Create a new Redis rate limit adapter.
- pub fn new(redis: R) -> Self {
- Self { redis }
- }
-}
-
-/// Trait for Redis operations needed by the rate limit adapter.
-///
-/// This allows the adapter to work with different Redis client implementations.
-pub trait RedisRateLimitOps {
- /// Get the current count for a key.
- fn get_count(
- &self,
- key: &str,
- ) -> impl std::future::Future<Output = Result<Option<u64>, Report>> + Send;
-
- /// Increment a key and set expiry if it's new.
- fn increment_with_expiry(
- &self,
- key: &str,
- expiry_seconds: u64,
- ) -> impl std::future::Future<Output = Result<u64, Report>> + Send;
-}
-
-impl RedisRateLimitOps for redis::Client {
- async fn get_count(&self, key: &str) -> Result<Option<u64>, Report> {
- let mut conn = self.get_multiplexed_async_connection().await?;
- let count: Option<u64> = conn.get(key).await?;
- Ok(count)
- }
-
- async fn increment_with_expiry(&self, key: &str, expiry_seconds: u64) -> Result<u64, Report> {
- let mut conn = self.get_multiplexed_async_connection().await?;
-
- // Use atomic pipeline: INCR + EXPIRE
- let (new_count,): (u64,) = redis::pipe()
- .atomic()
- .incr(key, 1u64)
- .expire(key, expiry_seconds as i64)
- .ignore()
- .query_async(&mut conn)
- .await?;
-
- Ok(new_count)
- }
-}
-
-impl<R: RedisRateLimitOps + Send + Sync + 'static> RateLimitPort for RedisRateLimitAdapter<R> {
- async fn check(
- &self,
- key: &RateLimitKey,
- config: &RateLimitConfig,
- ) -> Result<RateLimitResult, Report> {
- let key_str = format!("rtl:{}", key.to_hex_string());
-
- let current_count = self.redis.get_count(&key_str).await?.unwrap_or(0);
-
- if current_count >= config.max_count {
- Ok(RateLimitResult::Exceeded(RateLimitExceeded {
- key: key_str,
- current_count,
- max_count: config.max_count,
- }))
- } else {
- Ok(RateLimitResult::Allowed { current_count })
- }
- }
-
- async fn increment(&self, key: &RateLimitKey, config: &RateLimitConfig) -> Result<u64, Report> {
- let key_str = format!("rtl:{}", key.to_hex_string());
- let expiry_seconds = config.window.as_secs();
- self.redis
- .increment_with_expiry(&key_str, expiry_seconds)
- .await
- }
-}
+pub use rate_limit::outbound::redis::{RedisRateLimitAdapter, RedisRateLimitOps};
diff --git a/rust/cloud-storage/notification_sandbox/Cargo.toml b/rust/cloud-storage/notification_sandbox/Cargo.toml
index 87d933f2d8..a7dcdb0493 100644
--- a/rust/cloud-storage/notification_sandbox/Cargo.toml
+++ b/rust/cloud-storage/notification_sandbox/Cargo.toml
@@ -17,6 +17,7 @@ model-entity = { path = "../model-entity" }
model_notifications = { path = "../model_notifications" }
models_pagination = { path = "../models_pagination" }
notification = { path = "../notification" }
+rate_limit = { path = "../rate_limit" }
redis = { workspace = true, features = [
"aio",
"tokio-comp",
diff --git a/rust/cloud-storage/notification_sandbox/src/adapters/mpsc_queue.rs b/rust/cloud-storage/notification_sandbox/src/adapters/mpsc_queue.rs
index 81b94f69f8..3a61b0bd0d 100644
--- a/rust/cloud-storage/notification_sandbox/src/adapters/mpsc_queue.rs
+++ b/rust/cloud-storage/notification_sandbox/src/adapters/mpsc_queue.rs
@@ -72,4 +72,13 @@ impl NotificationQueue for MpscQueue {
// No-op: messages are consumed from the channel on receive.
Ok(())
}
+
+ async fn delay_message(
+ &self,
+ _receipt_handle: &str,
+ _delay: std::time::Duration,
+ ) -> Result<(), Report> {
+ // No-op: in-process queue doesn't support visibility changes.
+ 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.rs
index 93c93ee478..264c170ee2 100644
--- a/rust/cloud-storage/notification_sandbox/src/adapters/noop_rate_limiter.rs
+++ b/rust/cloud-storage/notification_sandbox/src/adapters/noop_rate_limiter.rs
@@ -1,11 +1,10 @@
-use notification::domain::models::{RateLimitConfig, RateLimitKey, RateLimitResult};
-use notification::domain::ports::RateLimitPort;
+use rate_limit::{RateLimitConfig, RateLimitKey, RateLimitPort, RateLimitResult};
use rootcause::Report;
-/// Rate limiter that always allows (no-op for sandbox).
-pub struct NoOpRateLimiter;
+/// Rate limit port that always allows (no-op for sandbox).
+pub struct NoOpRateLimitPort;
-impl RateLimitPort for NoOpRateLimiter {
+impl RateLimitPort for NoOpRateLimitPort {
async fn check(
&self,
_key: &RateLimitKey,
diff --git a/rust/cloud-storage/notification_sandbox/src/main.rs b/rust/cloud-storage/notification_sandbox/src/main.rs
index ac9e04e179..8f644a50c4 100644
--- a/rust/cloud-storage/notification_sandbox/src/main.rs
+++ b/rust/cloud-storage/notification_sandbox/src/main.rs
@@ -13,8 +13,8 @@ use model_entity::EntityType;
use model_notifications::ChannelMessageSendMetadata;
use notification::domain::models::email_notification_digest::ports::MessageId;
use notification::domain::models::email_notification_digest::{
- EmailBlockList, ExplicitInviteAllowList, NotificationSetBuilder, StateMachineDecisionC,
- StateMachineDriverA, StateMachineDriverB, StateMachineDriverC,
+ EmailBlockList, NotificationSetBuilder, StateMachineDecisionC, StateMachineDriverA,
+ StateMachineDriverB, StateMachineDriverC,
};
use notification::domain::models::{DeviceEndpoint, SendNotificationRequestBuilder};
use notification::domain::ports::NotificationEgress;
@@ -36,7 +36,7 @@ use adapters::interactive_mobile::{
};
use adapters::logging_websocket::LoggingWebSocketSender;
use adapters::mpsc_queue::MpscQueue;
-use adapters::noop_rate_limiter::NoOpRateLimiter;
+use adapters::noop_rate_limiter::NoOpRateLimitPort;
use adapters::sandbox_repository::SandboxNotificationRepository;
/// Configuration collected from the interactive wizard.
@@ -44,7 +44,6 @@ struct SandboxConfig {
digest_window: Duration,
online_threshold: Duration,
is_blocked: bool,
- is_invite: bool,
sns_mode: SnsMode,
num_endpoints: usize,
}
@@ -116,19 +115,12 @@ async fn main() -> Result<(), Report> {
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,
};
@@ -160,7 +152,9 @@ async fn main() -> Result<(), Report> {
websocket: LoggingWebSocketSender,
mobile: mobile_sender,
email: email_adapter,
- rate_limiter: NoOpRateLimiter,
+ rate_limiter: rate_limit::RateLimitServiceImpl {
+ repo: NoOpRateLimitPort,
+ },
state_machine: StateMachineDriverB {
message_receipt_repo: DbMessageReceiptRepository::new(db.clone()),
digest_batcher: RedisDigestBatcher::new(redis_conn.clone()),
@@ -433,10 +427,6 @@ async fn run_config_wizard() -> Result<SandboxConfig, Report> {
.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()?;
@@ -459,7 +449,6 @@ async fn run_config_wizard() -> Result<SandboxConfig, Report> {
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.rs
index 4288548b7b..b53f020146 100644
--- a/rust/cloud-storage/notification_sandbox/src/sandbox_notification.rs
+++ b/rust/cloud-storage/notification_sandbox/src/sandbox_notification.rs
@@ -48,7 +48,7 @@ impl NotificationExtEmail for SandboxNotification {
}
fn rate_limit_key(&self) -> RateLimitKey {
- RateLimitKey::from_str_hashed("sandbox")
+ RateLimitKey::from_str_hashed(&"sandbox")
}
}
diff --git a/rust/cloud-storage/notification_service/Cargo.toml b/rust/cloud-storage/notification_service/Cargo.toml
index 64ccdf716d..f7bf1170ed 100644
--- a/rust/cloud-storage/notification_service/Cargo.toml
+++ b/rust/cloud-storage/notification_service/Cargo.toml
@@ -53,6 +53,7 @@ model_user = { path = "../model_user", features = ["axum"] }
models_comms = { path = "../models_comms" }
models_pagination = { path = "../models_pagination", features = ["axum"] }
notification = { path = "../notification", features = ["axum"] }
+rate_limit = { path = "../rate_limit" }
notification_db_client = { path = "../notification_db_client" }
paste = { workspace = true }
redis = { workspace = true }
diff --git a/rust/cloud-storage/notification_service/src/api/user_notification.rs b/rust/cloud-storage/notification_service/src/api/user_notification.rs
index f214043d6b..171e952a71 100644
--- a/rust/cloud-storage/notification_service/src/api/user_notification.rs
+++ b/rust/cloud-storage/notification_service/src/api/user_notification.rs
@@ -207,15 +207,10 @@ where
fn filter_erors((uuid, err): (Uuid, serde_json::Error)) -> Option<Uuid> {
let err_str = err.to_string();
- let output = (err_str.contains("channel_message_document")
- || err_str.contains("missing field `toEmail`"))
- .then_some(uuid);
-
- if output.is_none() {
- tracing::warn!("{err:?}");
- }
- output
+ (err_str.contains("channel_message_document")
+ || err_str.contains("missing field `toEmail`"))
+ .then_some(uuid)
}
let to_delete: Vec<_> = failed_notifs.into_iter().filter_map(filter_erors).collect();
diff --git a/rust/cloud-storage/notification_service/src/main.rs b/rust/cloud-storage/notification_service/src/main.rs
index 5b68f63560..8e9526f6d2 100644
--- a/rust/cloud-storage/notification_service/src/main.rs
+++ b/rust/cloud-storage/notification_service/src/main.rs
@@ -6,6 +6,7 @@ use ::notification::outbound::email::EmailAdapter;
use ::notification::outbound::mobile::MobilePushAdapter;
use ::notification::outbound::rate_limit::RedisRateLimitAdapter;
use ::notification::outbound::websocket::{ConnectionGatewayClient, WebSocketGatewayAdapter};
+use ::rate_limit::RateLimitServiceImpl;
use anyhow::Context;
use config::Config;
use email_formatting::EmailDigestNotification;
@@ -166,7 +167,11 @@ pub async fn main() -> anyhow::Result<()> {
.get_multiplexed_async_connection()
.await
.context("failed to get multiplexed redis connection for egress state machine")?;
- let rate_limit_adapter = RedisRateLimitAdapter::new(redis_client);
+ let rate_limit_adapter = RateLimitServiceImpl {
+ repo: RedisRateLimitAdapter {
+ redis: redis_client,
+ },
+ };
let egress_state_machine =
::notification::domain::models::email_notification_digest::StateMachineDriverB {
@@ -232,8 +237,7 @@ pub async fn main() -> anyhow::Result<()> {
),
),
::notification::outbound::digest_batcher::RedisDigestBatcher::new(ingress_redis_conn),
- model_notifications::digest_state::common_email_block_list(),
- model_notifications::digest_state::common_explicit_invite_allow_list(),
+ model_notifications::digest_state::digest_email_block_list(),
);
let ingress_repository =
@@ -248,10 +252,10 @@ pub async fn main() -> anyhow::Result<()> {
ingress_state_machine,
);
- let ingress_queue = ::notification::outbound::queue::SqsIngressQueue::new(
- aws_sdk_sqs::Client::new(&aws_config),
- vars.notification_ingress_queue.as_ref().to_string(),
- );
+ let ingress_queue = ::notification::outbound::queue::SqsIngressQueue {
+ client: aws_sdk_sqs::Client::new(&aws_config),
+ queue_url: vars.notification_ingress_queue.as_ref().to_string(),
+ };
let ingress_worker =
::notification::inbound::ingress_worker::IngressWorker::new(ingress_service, ingress_queue);
diff --git a/rust/cloud-storage/rate_limit/Cargo.toml b/rust/cloud-storage/rate_limit/Cargo.toml
new file mode 100644
index 0000000000..2bf4c13236
--- /dev/null
+++ b/rust/cloud-storage/rate_limit/Cargo.toml
@@ -0,0 +1,22 @@
+[package]
+edition = "2024"
+name = "rate_limit"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+hex = { workspace = true }
+redis = { workspace = true, features = [
+ "aio",
+ "tokio-comp",
+ "tokio-native-tls-comp",
+] }
+rootcause = { workspace = true }
+serde = { workspace = true }
+thiserror = { workspace = true }
+tracing = { workspace = true }
+twox-hash = { version = "2" }
+
+[dev-dependencies]
+tokio = { workspace = true, features = ["macros", "rt-multi-thread"] }
+uuid = { workspace = true }
diff --git a/rust/cloud-storage/rate_limit/src/domain/mod.rs b/rust/cloud-storage/rate_limit/src/domain/mod.rs
new file mode 100644
index 0000000000..fec5bcea80
--- /dev/null
+++ b/rust/cloud-storage/rate_limit/src/domain/mod.rs
@@ -0,0 +1,6 @@
+//! Domain layer: models and port definitions.
+
+pub mod models;
+pub mod ports;
+/// Default [`ports::RateLimitService`] implementation.
+pub mod service;
diff --git a/rust/cloud-storage/rate_limit/src/domain/models.rs b/rust/cloud-storage/rate_limit/src/domain/models.rs
new file mode 100644
index 0000000000..137071eecc
--- /dev/null
+++ b/rust/cloud-storage/rate_limit/src/domain/models.rs
@@ -0,0 +1,127 @@
+//! Rate limiting models.
+
+use serde::{Deserialize, Serialize};
+use std::hash::{Hash, Hasher};
+use std::time::Duration;
+use thiserror::Error;
+use twox_hash::XxHash64;
+
+/// Newtype for rate limit keys.
+///
+/// Callers control what gets rate limited by constructing a key from relevant
+/// data (e.g., event type + sender email). The internal value is a hash.
+#[derive(Debug, Clone, Default, Serialize, Deserialize)]
+#[serde(transparent)]
+pub struct RateLimitKey(Vec<u8>);
+
+/// The builder struct for a [`RateLimitKey`].
+/// Callers can either append values or finish the building.
+pub struct RateLimitKeyBuilder(XxHash64);
+
+impl RateLimitKeyBuilder {
+ /// Finish the key building, returning a [`RateLimitKey`].
+ pub fn finish(self) -> RateLimitKey {
+ RateLimitKey(self.0.finish().to_le_bytes().to_vec())
+ }
+
+ /// Append a value to the builder.
+ pub fn append<T: Hash>(self, input: &T) -> Self {
+ let RateLimitKeyBuilder(mut hasher) = self;
+ input.hash(&mut hasher);
+ RateLimitKeyBuilder(hasher)
+ }
+}
+
+impl RateLimitKey {
+ /// Create a rate limit key by hashing the input string.
+ pub fn from_str_hashed<T: Hash>(input: &T) -> Self {
+ Self::builder(input).finish()
+ }
+
+ /// Create a builder from an initial value.
+ pub fn builder<T: Hash>(input: &T) -> RateLimitKeyBuilder {
+ let mut hasher = XxHash64::with_seed(0);
+ input.hash(&mut hasher);
+ RateLimitKeyBuilder(hasher)
+ }
+
+ /// Get the internal bytes.
+ pub fn as_bytes(&self) -> &[u8] {
+ &self.0
+ }
+
+ /// Convert to a hex string for use as a cache key.
+ pub fn to_hex_string(&self) -> String {
+ hex::encode(&self.0)
+ }
+}
+
+/// Result of a rate limit check.
+#[derive(Debug)]
+pub enum RateLimitResult {
+ /// The action is allowed. Contains the current count after increment.
+ Allowed {
+ /// The current count after increment.
+ current_count: u64,
+ },
+ /// The rate limit has been exceeded.
+ Exceeded(RateLimitExceeded),
+}
+
+/// The return value from the rate limit service
+#[derive(Debug)]
+pub struct RateLimitTicket {
+ pub(crate) result: RateLimitResult,
+ pub(crate) key: RateLimitKey,
+ pub(crate) config: RateLimitConfig,
+}
+
+impl std::ops::Deref for RateLimitTicket {
+ type Target = RateLimitResult;
+
+ fn deref(&self) -> &Self::Target {
+ &self.result
+ }
+}
+
+/// Error returned when a rate limit is exceeded.
+#[derive(Debug, Error, Clone)]
+#[error(
+ "Rate limit key: {key} was exceeded. Current count is {current_count} but max count is {max_count}"
+)]
+pub struct RateLimitExceeded {
+ /// The key that is exceeded.
+ pub key: String,
+ /// The current count.
+ pub current_count: u64,
+ /// The maximum allowed count.
+ pub max_count: u64,
+ /// How long until the rate limit window expires.
+ pub retry_after: Duration,
+}
+
+/// Configuration for rate limiting.
+#[derive(Debug, Clone, Serialize, Deserialize)]
+pub struct RateLimitConfig {
+ /// Maximum number of actions allowed in the window.
+ pub max_count: u64,
+ /// Time window for rate limiting.
+ pub window: Duration,
+}
+
+impl RateLimitConfig {
+ /// Create a new rate limit config.
+ pub fn new(max_count: u64, window: Duration) -> Self {
+ Self { max_count, window }
+ }
+
+ /// Rate limit for channel invites: 10 per hour.
+ pub fn channel_invite() -> Self {
+ Self::new(10, Duration::from_secs(3600))
+ }
+
+ /// Rate limit for team invites: 5 per hour.
+ pub fn team_invite() -> Self {
+ Self::new(5, Duration::from_secs(3600))
+ }
+}
diff --git a/rust/cloud-storage/rate_limit/src/domain/ports.rs b/rust/cloud-storage/rate_limit/src/domain/ports.rs
new file mode 100644
index 0000000000..401a56b0a4
--- /dev/null
+++ b/rust/cloud-storage/rate_limit/src/domain/ports.rs
@@ -0,0 +1,45 @@
+//! Port definitions (interfaces) for rate limiting.
+
+use std::future::Future;
+
+use rootcause::Report;
+
+use crate::domain::models::{RateLimitConfig, RateLimitKey, RateLimitResult, RateLimitTicket};
+
+/// Port for rate limiting operations.
+pub trait RateLimitPort: Send + Sync + 'static {
+ /// Check if the action is allowed without incrementing the counter.
+ ///
+ /// The `RateLimitKey` is a hashed value - callers control what gets rate
+ /// limited by constructing the key from relevant data.
+ fn check(
+ &self,
+ key: &RateLimitKey,
+ config: &RateLimitConfig,
+ ) -> impl Future<Output = Result<RateLimitResult, Report>> + Send;
+
+ /// Increment the rate limit counter for a key.
+ ///
+ /// Should only be called after a successful action.
+ fn increment(
+ &self,
+ key: &RateLimitKey,
+ config: &RateLimitConfig,
+ ) -> impl Future<Output = Result<u64, Report>> + Send;
+}
+
+/// the external facing service interface, this signature enforces that users are incrementing at most 1 time per ticket read
+pub trait RateLimitService: Send + Sync + 'static {
+ /// check the rate limit, returning a ticket which can be used to increment the counter
+ fn check_rate_limit(
+ &self,
+ key: RateLimitKey,
+ config: RateLimitConfig,
+ ) -> impl Future<Output = Result<RateLimitTicket, Report>> + Send;
+
+ /// increment the counter for a given ticket
+ fn increment_ticket(
+ &self,
+ ticket: RateLimitTicket,
+ ) -> impl Future<Output = Result<(), Report>> + Send;
+}
diff --git a/rust/cloud-storage/rate_limit/src/domain/service.rs b/rust/cloud-storage/rate_limit/src/domain/service.rs
new file mode 100644
index 0000000000..77318a57a9
--- /dev/null
+++ b/rust/cloud-storage/rate_limit/src/domain/service.rs
@@ -0,0 +1,36 @@
+use rootcause::Report;
+
+use crate::{
+ RateLimitConfig, RateLimitKey, RateLimitPort,
+ domain::{models::RateLimitTicket, ports::RateLimitService},
+};
+
+/// a concrete struct which implements [RateLimitService]
+pub struct RateLimitServiceImpl<R> {
+ /// the inner impl of [RateLimitPort]
+ pub repo: R,
+}
+
+impl<R> RateLimitService for RateLimitServiceImpl<R>
+where
+ R: RateLimitPort,
+{
+ async fn check_rate_limit(
+ &self,
+ key: RateLimitKey,
+ config: RateLimitConfig,
+ ) -> Result<RateLimitTicket, Report> {
+ let result = self.repo.check(&key, &config).await?;
+ Ok(RateLimitTicket {
+ result,
+ key,
+ config,
+ })
+ }
+
+ #[tracing::instrument(err, skip(self))]
+ async fn increment_ticket(&self, ticket: RateLimitTicket) -> Result<(), Report> {
+ self.repo.increment(&ticket.key, &ticket.config).await?;
+ Ok(())
+ }
+}
diff --git a/rust/cloud-storage/rate_limit/src/lib.rs b/rust/cloud-storage/rate_limit/src/lib.rs
new file mode 100644
index 0000000000..5c17ded118
--- /dev/null
+++ b/rust/cloud-storage/rate_limit/src/lib.rs
@@ -0,0 +1,17 @@
+#![deny(missing_docs)]
+//! Generic rate limiting library.
+//!
+//! Provides models, a service trait ([`RateLimitPort`]), and a Redis-backed
+//! adapter following hexagonal architecture.
+
+pub mod domain;
+pub mod outbound;
+
+// Re-export key types at crate root for convenience.
+pub use domain::models::{
+ RateLimitConfig, RateLimitExceeded, RateLimitKey, RateLimitKeyBuilder, RateLimitResult,
+ RateLimitTicket,
+};
+pub use domain::ports::{RateLimitPort, RateLimitService};
+pub use domain::service::RateLimitServiceImpl;
+pub use outbound::redis::{RedisRateLimitAdapter, RedisRateLimitOps};
diff --git a/rust/cloud-storage/rate_limit/src/outbound/mod.rs b/rust/cloud-storage/rate_limit/src/outbound/mod.rs
new file mode 100644
index 0000000000..0b12e7fd35
--- /dev/null
+++ b/rust/cloud-storage/rate_limit/src/outbound/mod.rs
@@ -0,0 +1,3 @@
+//! Outbound adapters.
+
+pub mod redis;
diff --git a/rust/cloud-storage/rate_limit/src/outbound/redis.rs b/rust/cloud-storage/rate_limit/src/outbound/redis.rs
new file mode 100644
index 0000000000..555ab5902a
--- /dev/null
+++ b/rust/cloud-storage/rate_limit/src/outbound/redis.rs
@@ -0,0 +1,109 @@
+//! Redis-based rate limit adapter.
+
+#[cfg(test)]
+mod test;
+
+use redis::AsyncCommands;
+use rootcause::Report;
+
+use crate::domain::models::{RateLimitConfig, RateLimitExceeded, RateLimitKey, RateLimitResult};
+use crate::domain::ports::RateLimitPort;
+
+/// Redis-based implementation of the rate limit port.
+///
+/// This adapter uses Redis to store and check rate limit counters.
+/// The key is provided by the caller (already hashed), and this adapter
+/// handles the Redis operations.
+pub struct RedisRateLimitAdapter<R> {
+ /// the inner redis client
+ pub redis: R,
+}
+
+/// Trait for Redis operations needed by the rate limit adapter.
+///
+/// This allows the adapter to work with different Redis client implementations.
+pub trait RedisRateLimitOps {
+ /// Get the current count for a key.
+ fn get_count(
+ &self,
+ key: &str,
+ ) -> impl std::future::Future<Output = Result<Option<u64>, Report>> + Send;
+
+ /// Get the remaining TTL in seconds for a key. Returns `None` if the key
+ /// does not exist or has no expiry.
+ fn get_ttl(
+ &self,
+ key: &str,
+ ) -> impl std::future::Future<Output = Result<Option<u64>, Report>> + Send;
+
+ /// Increment a key and set expiry if it's new.
+ fn increment_with_expiry(
+ &self,
+ key: &str,
+ expiry_seconds: u64,
+ ) -> impl std::future::Future<Output = Result<u64, Report>> + Send;
+}
+
+impl RedisRateLimitOps for redis::Client {
+ async fn get_count(&self, key: &str) -> Result<Option<u64>, Report> {
+ let mut conn = self.get_multiplexed_async_connection().await?;
+ let count: Option<u64> = conn.get(key).await?;
+ Ok(count)
+ }
+
+ async fn get_ttl(&self, key: &str) -> Result<Option<u64>, Report> {
+ let mut conn = self.get_multiplexed_async_connection().await?;
+ let ttl: i64 = conn.ttl(key).await?;
+ // Redis returns -2 if key doesn't exist, -1 if no expiry
+ Ok(if ttl > 0 { Some(ttl as u64) } else { None })
+ }
+
+ async fn increment_with_expiry(&self, key: &str, expiry_seconds: u64) -> Result<u64, Report> {
+ let mut conn = self.get_multiplexed_async_connection().await?;
+
+ // Use atomic pipeline: INCR + EXPIRE
+ let (new_count,): (u64,) = redis::pipe()
+ .atomic()
+ .incr(key, 1u64)
+ .expire(key, expiry_seconds as i64)
+ .ignore()
+ .query_async(&mut conn)
+ .await?;
+
+ Ok(new_count)
+ }
+}
+
+impl<R: RedisRateLimitOps + Send + Sync + 'static> RateLimitPort for RedisRateLimitAdapter<R> {
+ async fn check(
+ &self,
+ key: &RateLimitKey,
+ config: &RateLimitConfig,
+ ) -> Result<RateLimitResult, Report> {
+ let key_str = format!("rtl:{}", key.to_hex_string());
+
+ let current_count = self.redis.get_count(&key_str).await?.unwrap_or(0);
+
+ if current_count >= config.max_count {
+ let ttl = self.redis.get_ttl(&key_str).await?;
+ let retry_after =
+ std::time::Duration::from_secs(ttl.unwrap_or(config.window.as_secs()));
+ Ok(RateLimitResult::Exceeded(RateLimitExceeded {
+ key: key_str,
+ current_count,
+ max_count: config.max_count,
+ retry_after,
+ }))
+ } else {
+ Ok(RateLimitResult::Allowed { current_count })
+ }
+ }
+
+ async fn increment(&self, key: &RateLimitKey, config: &RateLimitConfig) -> Result<u64, Report> {
+ let key_str = format!("rtl:{}", key.to_hex_string());
+ let expiry_seconds = config.window.as_secs();
+ self.redis
+ .increment_with_expiry(&key_str, expiry_seconds)
+ .await
+ }
+}
diff --git a/rust/cloud-storage/rate_limit/src/outbound/redis/test.rs b/rust/cloud-storage/rate_limit/src/outbound/redis/test.rs
new file mode 100644
index 0000000000..9704b4de2b
--- /dev/null
+++ b/rust/cloud-storage/rate_limit/src/outbound/redis/test.rs
@@ -0,0 +1,108 @@
+use std::time::Duration;
+
+use crate::{
+ RateLimitConfig, RateLimitKey, RateLimitResult, RateLimitServiceImpl,
+ domain::ports::RateLimitService, outbound::redis::RedisRateLimitAdapter,
+};
+
+fn redis_client() -> redis::Client {
+ let url = std::env::var("REDIS_URL").unwrap_or_else(|_| "redis://127.0.0.1:6379".into());
+ redis::Client::open(url).expect("failed to create Redis client")
+}
+
+fn unique_key(name: &str) -> RateLimitKey {
+ RateLimitKey::builder(&format!("test_{name}_{}", uuid::Uuid::new_v4())).finish()
+}
+
+fn service() -> RateLimitServiceImpl<RedisRateLimitAdapter<redis::Client>> {
+ RateLimitServiceImpl {
+ repo: RedisRateLimitAdapter {
+ redis: redis_client(),
+ },
+ }
+}
+
+#[tokio::test]
+async fn retry_after_is_populated_when_rate_limit_exceeded() {
+ let svc = service();
+ let key = unique_key("retry_after");
+ let config = RateLimitConfig {
+ max_count: 1,
+ window: Duration::from_secs(30),
+ };
+
+ // First request succeeds and increments the counter.
+ let ticket = svc
+ .check_rate_limit(key.clone(), config.clone())
+ .await
+ .expect("check_rate_limit failed");
+ assert!(matches!(&*ticket, RateLimitResult::Allowed { .. }));
+ svc.increment_ticket(ticket)
+ .await
+ .expect("increment_ticket failed");
+
+ // Second request should be exceeded.
+ let ticket = svc
+ .check_rate_limit(key, config.clone())
+ .await
+ .expect("check_rate_limit failed");
+
+ match &*ticket {
+ RateLimitResult::Exceeded(exceeded) => {
+ assert!(
+ !exceeded.retry_after.is_zero(),
+ "retry_after should be non-zero"
+ );
+ assert!(
+ exceeded.retry_after <= config.window,
+ "retry_after ({:?}) should not exceed the window ({:?})",
+ exceeded.retry_after,
+ config.window,
+ );
+ }
+ RateLimitResult::Allowed { .. } => {
+ panic!("expected rate limit to be exceeded after max_count requests");
+ }
+ }
+}
+
+#[tokio::test]
+async fn retry_after_decreases_over_time() {
+ let svc = service();
+ let key = unique_key("retry_decreases");
+ let config = RateLimitConfig {
+ max_count: 1,
+ window: Duration::from_secs(30),
+ };
+
+ // Exhaust the rate limit.
+ let ticket = svc
+ .check_rate_limit(key.clone(), config.clone())
+ .await
+ .unwrap();
+ svc.increment_ticket(ticket).await.unwrap();
+
+ // Check immediately.
+ let ticket = svc
+ .check_rate_limit(key.clone(), config.clone())
+ .await
+ .unwrap();
+ let first_retry_after = match &*ticket {
+ RateLimitResult::Exceeded(e) => e.retry_after,
+ _ => panic!("expected exceeded"),
+ };
+
+ // Wait a bit then check again.
+ tokio::time::sleep(Duration::from_secs(2)).await;
+
+ let ticket = svc.check_rate_limit(key, config).await.unwrap();
+ let second_retry_after = match &*ticket {
+ RateLimitResult::Exceeded(e) => e.retry_after,
+ _ => panic!("expected exceeded"),
+ };
+
+ assert!(
+ second_retry_after < first_retry_after,
+ "retry_after should decrease over time: first={first_retry_after:?}, second={second_retry_after:?}",
+ );
+}
diff --git a/rust/cloud-storage/referral/Cargo.toml b/rust/cloud-storage/referral/Cargo.toml
index 3fd1b25777..5005479d07 100644
--- a/rust/cloud-storage/referral/Cargo.toml
+++ b/rust/cloud-storage/referral/Cargo.toml
@@ -21,6 +21,7 @@ ports = []
# Core
anyhow = { workspace = true }
chrono = { workspace = true }
+rootcause = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
@@ -30,6 +31,10 @@ uuid = { workspace = true }
# Domain models
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
+model-entity = { path = "../model-entity" }
+notification = { path = "../notification" }
+rate_limit = { path = "../rate_limit" }
+referral_invitation = { path = "../referral_invitation" }
# Axum dependencies (for inbound)
axum = { workspace = true, optional = true }
@@ -38,6 +43,7 @@ model-error-response = { path = "../model-error-response", optional = true }
model_user = { path = "../model_user", optional = true, features = ["axum"] }
utoipa = { workspace = true, optional = true }
+
async-stripe = { workspace = true, default-features = false, features = [
"billing",
"checkout",
diff --git a/rust/cloud-storage/referral/src/domain/models.rs b/rust/cloud-storage/referral/src/domain/models.rs
index 494c6e19de..49eb31d4fd 100644
--- a/rust/cloud-storage/referral/src/domain/models.rs
+++ b/rust/cloud-storage/referral/src/domain/models.rs
@@ -1,15 +1,16 @@
//! Domain models for the referral crate.
-use macro_uuid::ShortUuidConverter;
+pub use referral_invitation::{InviteToMacro, ReferralCode};
-/// Wrapper for the referral code to make it type safe
-#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
-#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]
-pub struct ReferralCode(pub String);
+use macro_uuid::ShortUuidConverter;
+use rate_limit::RateLimitExceeded;
/// Errors that can occur during referral operations.
#[derive(Debug, thiserror::Error)]
pub enum ReferralError {
+ /// we have exeeded a rate limit
+ #[error("Rate limit exceeded")]
+ RateLimitExceeded(#[from] RateLimitExceeded),
/// The requested referral code was not found.
#[error("referral not found: {0}")]
NotFound(String),
diff --git a/rust/cloud-storage/referral/src/domain/ports.rs b/rust/cloud-storage/referral/src/domain/ports.rs
index e3947b744a..cc70875c5f 100644
--- a/rust/cloud-storage/referral/src/domain/ports.rs
+++ b/rust/cloud-storage/referral/src/domain/ports.rs
@@ -2,7 +2,11 @@
//!
//! These traits define the contracts that adapters must implement.
-use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+use macro_user_id::{
+ email::EmailStr,
+ lowercased::Lowercase,
+ user_id::{MacroUserId, MacroUserIdStr},
+};
use crate::domain::models::{ReferralCode, ReferralError};
@@ -95,4 +99,11 @@ pub trait ReferralService: Send + Sync + 'static {
referred_user_id: &MacroUserId<Lowercase<'a>>,
referral_code: &ReferralCode,
) -> impl Future<Output = Result<(), ReferralError>> + Send;
+
+ /// Send a referral to an external user via email
+ fn send_referral_invite(
+ &self,
+ sending_user: MacroUserIdStr<'_>,
+ recipient: EmailStr<'static>,
+ ) -> impl Future<Output = Result<(), ReferralError>> + Send;
}
diff --git a/rust/cloud-storage/referral/src/domain/service.rs b/rust/cloud-storage/referral/src/domain/service.rs
index e0a45fcdc5..0efa624034 100644
--- a/rust/cloud-storage/referral/src/domain/service.rs
+++ b/rust/cloud-storage/referral/src/domain/service.rs
@@ -1,31 +1,91 @@
//! Referral service implementation.
-use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};
+#[cfg(test)]
+mod test;
+
+use std::{collections::HashSet, ops::Deref, time::Duration};
+
+use macro_user_id::{
+ email::EmailStr,
+ lowercased::Lowercase,
+ user_id::{MacroUserId, MacroUserIdStr},
+};
+use model_entity::EntityType;
+use notification::domain::{models::SendNotificationRequestBuilder, service::NotificationIngress};
+use rate_limit::{RateLimitConfig, RateLimitKey, RateLimitResult, domain::ports::RateLimitService};
+use rootcause::compat::boxed_error::IntoBoxedError;
use crate::domain::{
- models::{ReferralCode, ReferralError},
+ models::{InviteToMacro, ReferralCode, ReferralError},
ports::{DiscountClient, ReferralRepo, ReferralService},
};
/// The concrete referral service implementation.
-pub struct ReferralServiceImpl<R: ReferralRepo, Dc: DiscountClient> {
+pub struct ReferralServiceImpl<R, Dc, Rl, N> {
/// referral repo
- repo: R,
+ pub repo: R,
/// discount client
- discount_client: Dc,
+ pub discount_client: Dc,
+ /// rate limiter service
+ pub rate_limit: Rl,
+ /// the notification sender
+ pub notification_ingress: N,
}
-impl<R: ReferralRepo, Dc: DiscountClient> ReferralServiceImpl<R, Dc> {
- /// Create a new referral service.
- pub fn new(repo: R, discount_client: Dc) -> Self {
- Self {
- repo,
- discount_client,
- }
+impl<
+ R: ReferralRepo,
+ Dc: DiscountClient,
+ Rl: RateLimitService,
+ // the constructor for this is Arc<NI> so we use a different bound here
+ N: Deref<Target = NI> + Send + Sync + 'static,
+ NI: NotificationIngress,
+> ReferralServiceImpl<R, Dc, Rl, N>
+{
+ async fn send_referral_invite_inner(
+ &self,
+ sending_user: MacroUserIdStr<'_>,
+ recipient: EmailStr<'static>,
+ ) -> Result<(), ReferralError> {
+ let referral_code = self.get_referral_code_for_user(&sending_user.0).await?;
+
+ let notification = InviteToMacro {
+ recipient_email: recipient.clone(),
+ referral_code,
+ };
+
+ let _res = self
+ .notification_ingress
+ .send_notification(
+ SendNotificationRequestBuilder {
+ notification_entity: EntityType::User
+ .with_entity_string(sending_user.as_ref().to_string()),
+ notification,
+ sender_id: Some(sending_user),
+ recipient_ids: HashSet::from([MacroUserIdStr::try_from_email(
+ recipient.0.as_ref(),
+ )
+ .map_err(anyhow::Error::from)?]),
+ }
+ .into_request()
+ .with_email(),
+ )
+ .await
+ .map_err(|r| r.into_boxed_error())
+ .map_err(anyhow::Error::from_boxed)?;
+
+ Ok(())
}
}
-impl<R: ReferralRepo, Dc: DiscountClient> ReferralService for ReferralServiceImpl<R, Dc> {
+impl<
+ R: ReferralRepo,
+ Dc: DiscountClient,
+ Rl: RateLimitService,
+ // the constructor for this is Arc<NI> so we use a different bound here
+ N: Deref<Target = NI> + Send + Sync + 'static,
+ NI: NotificationIngress,
+> ReferralService for ReferralServiceImpl<R, Dc, Rl, N>
+{
#[tracing::instrument(skip(self), err)]
async fn get_referral_code_for_user<'a>(
&self,
@@ -86,4 +146,38 @@ impl<R: ReferralRepo, Dc: DiscountClient> ReferralService for ReferralServiceImp
Ok(())
}
+
+ async fn send_referral_invite(
+ &self,
+ sending_user: MacroUserIdStr<'_>,
+ recipient: EmailStr<'static>,
+ ) -> Result<(), ReferralError> {
+ let user_rate_limit = RateLimitKey::builder(&"user_sent_invites")
+ .append(&sending_user.as_ref())
+ .finish();
+ let ticket = self
+ .rate_limit
+ .check_rate_limit(user_rate_limit, RATE_LIMIT_CONFIG_PER_USER.clone())
+ .await
+ .map_err(|r| r.into_boxed_error())
+ .map_err(anyhow::Error::from_boxed)?;
+
+ if let RateLimitResult::Exceeded(err) = &*ticket {
+ return Err(ReferralError::RateLimitExceeded(err.clone()));
+ }
+
+ let () = self
+ .send_referral_invite_inner(sending_user, recipient)
+ .await?;
+
+ let _ = self.rate_limit.increment_ticket(ticket).await;
+
+ Ok(())
+ }
}
+
+/// The fixed window rate limit config for the number of invites a user can send to others
+const RATE_LIMIT_CONFIG_PER_USER: RateLimitConfig = RateLimitConfig {
+ max_count: 50,
+ window: Duration::from_mins(60),
+};
diff --git a/rust/cloud-storage/referral/src/domain/service/test.rs b/rust/cloud-storage/referral/src/domain/service/test.rs
new file mode 100644
index 0000000000..c6eebab165
--- /dev/null
+++ b/rust/cloud-storage/referral/src/domain/service/test.rs
@@ -0,0 +1,192 @@
+use std::ops::Deref;
+
+use macro_user_id::{email::EmailStr, user_id::MacroUserIdStr};
+use notification::domain::{
+ models::SendNotificationRequest, service::NotificationIngress, service::SendNotificationError,
+};
+use rate_limit::{
+ RateLimitConfig, RateLimitExceeded, RateLimitKey, RateLimitResult, RateLimitServiceImpl,
+};
+use rootcause::Report;
+
+use crate::domain::{
+ models::ReferralError,
+ ports::{MockDiscountClient, MockReferralRepo, ReferralService},
+ service::ReferralServiceImpl,
+};
+
+// -- Mock NotificationIngress --
+
+struct MockNotificationIngressInner;
+
+impl NotificationIngress for MockNotificationIngressInner {
+ async fn send_notification<
+ 'a,
+ T: notification::domain::models::Notification + Clone + 'static,
+ U: serde::Serialize + Send + Sync + 'static,
+ >(
+ &'a self,
+ _req: SendNotificationRequest<'a, T, U>,
+ ) -> Result<
+ Option<notification::domain::models::NotificationResult<'a>>,
+ Report<SendNotificationError>,
+ > {
+ Ok(None)
+ }
+}
+
+/// Wrapper that implements `Deref<Target = MockNotificationIngressInner>`
+/// to satisfy the `N: Deref<Target = NI>` bound on `ReferralServiceImpl`.
+struct MockNotificationIngress(MockNotificationIngressInner);
+
+impl Deref for MockNotificationIngress {
+ type Target = MockNotificationIngressInner;
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
+
+// -- Mock RateLimitPort --
+
+struct MockRateLimitPort {
+ should_exceed: bool,
+}
+
+impl rate_limit::RateLimitPort for MockRateLimitPort {
+ async fn check(
+ &self,
+ _key: &RateLimitKey,
+ config: &RateLimitConfig,
+ ) -> Result<RateLimitResult, Report> {
+ if self.should_exceed {
+ Ok(RateLimitResult::Exceeded(RateLimitExceeded {
+ key: "test_key".to_string(),
+ current_count: config.max_count.saturating_add(1),
+ max_count: config.max_count,
+ retry_after: config.window,
+ }))
+ } else {
+ Ok(RateLimitResult::Allowed { current_count: 1 })
+ }
+ }
+
+ async fn increment(
+ &self,
+ _key: &RateLimitKey,
+ _config: &RateLimitConfig,
+ ) -> Result<u64, Report> {
+ Ok(1)
+ }
+}
+
+fn allowing_rate_limiter() -> RateLimitServiceImpl<MockRateLimitPort> {
+ RateLimitServiceImpl {
+ repo: MockRateLimitPort {
+ should_exceed: false,
+ },
+ }
+}
+
+fn exceeding_rate_limiter() -> RateLimitServiceImpl<MockRateLimitPort> {
+ RateLimitServiceImpl {
+ repo: MockRateLimitPort {
+ should_exceed: true,
+ },
+ }
+}
+
+fn mock_repo() -> MockReferralRepo {
+ let mut repo = MockReferralRepo::new();
+ repo.expect_get_referral_code_for_user().returning(|_| {
+ Box::pin(async { Ok(referral_invitation::ReferralCode("TESTCODE".to_string())) })
+ });
+ repo
+}
+
+fn mock_discount_client() -> MockDiscountClient {
+ MockDiscountClient::new()
+}
+
+fn build_service(
+ rate_limiter: RateLimitServiceImpl<MockRateLimitPort>,
+) -> ReferralServiceImpl<
+ MockReferralRepo,
+ MockDiscountClient,
+ RateLimitServiceImpl<MockRateLimitPort>,
+ MockNotificationIngress,
+> {
+ ReferralServiceImpl {
+ repo: mock_repo(),
+ discount_client: mock_discount_client(),
+ rate_limit: rate_limiter,
+ notification_ingress: MockNotificationIngress(MockNotificationIngressInner),
+ }
+}
+
+fn test_user() -> MacroUserIdStr<'static> {
+ MacroUserIdStr::try_from_email("[email protected]").unwrap()
+}
+
+fn test_recipient() -> EmailStr<'static> {
+ EmailStr::try_from("[email protected]".to_string()).unwrap()
+}
+
+#[tokio::test]
+async fn send_referral_invite_succeeds_when_under_rate_limit() {
+ let service = build_service(allowing_rate_limiter());
+
+ let result: Result<(), ReferralError> = service
+ .send_referral_invite(test_user(), test_recipient())
+ .await;
+
+ assert!(result.is_ok());
+}
+
+#[tokio::test]
+async fn send_referral_invite_fails_when_rate_limit_exceeded() {
+ let service = build_service(exceeding_rate_limiter());
+
+ let result: Result<(), ReferralError> = service
+ .send_referral_invite(test_user(), test_recipient())
+ .await;
+
+ assert!(result.is_err());
+ assert!(
+ matches!(result.unwrap_err(), ReferralError::RateLimitExceeded(_)),
+ "expected RateLimitExceeded error"
+ );
+}
+
+#[tokio::test]
+async fn rate_limit_error_contains_exceeded_info() {
+ let service = build_service(exceeding_rate_limiter());
+
+ let err = service
+ .send_referral_invite(test_user(), test_recipient())
+ .await
+ .unwrap_err();
+
+ match err {
+ ReferralError::RateLimitExceeded(exceeded) => {
+ assert!(
+ exceeded.current_count > exceeded.max_count,
+ "current_count ({}) should exceed max_count ({})",
+ exceeded.current_count,
+ exceeded.max_count,
+ );
+ }
+ other => panic!("expected RateLimitExceeded, got: {other:?}"),
+ }
+}
+
+#[tokio::test]
+async fn multiple_invites_succeed_when_under_rate_limit() {
+ let service = build_service(allowing_rate_limiter());
+
+ for i in 0..5 {
+ let recipient = EmailStr::try_from(format!("recipient{i}@example.com")).unwrap();
+ let result: Result<(), ReferralError> =
+ service.send_referral_invite(test_user(), recipient).await;
+ assert!(result.is_ok(), "invite {i} should succeed under rate limit");
+ }
+}
diff --git a/rust/cloud-storage/referral/src/inbound/axum_router.rs b/rust/cloud-storage/referral/src/inbound/axum_router.rs
index 06d1ee9a4a..f30b2feb84 100644
--- a/rust/cloud-storage/referral/src/inbound/axum_router.rs
+++ b/rust/cloud-storage/referral/src/inbound/axum_router.rs
@@ -7,6 +7,7 @@
mod test;
mod get_referral_code;
+mod send_invite;
use std::sync::Arc;
@@ -17,10 +18,12 @@ use crate::domain::models::ReferralError;
use crate::domain::ports::ReferralService;
pub use get_referral_code::*;
+pub use send_invite::*;
impl IntoResponse for ReferralError {
fn into_response(self) -> axum::response::Response {
let status_code = match &self {
+ ReferralError::RateLimitExceeded(_) => StatusCode::TOO_MANY_REQUESTS,
ReferralError::NotFound(_) => StatusCode::NOT_FOUND,
ReferralError::Unauthorized => StatusCode::UNAUTHORIZED,
ReferralError::BadRequest(_) => StatusCode::BAD_REQUEST,
@@ -60,6 +63,10 @@ where
S: Send + Sync + 'static,
{
Router::new()
+ .route(
+ "/send",
+ axum::routing::post(post_referral_invite_handler::<T>),
+ )
.route("/code", axum::routing::get(get_referral_code_handler::<T>))
.with_state(state)
}
diff --git a/rust/cloud-storage/referral/src/inbound/axum_router/get_referral_code.rs b/rust/cloud-storage/referral/src/inbound/axum_router/get_referral_code.rs
index 20fcadd7a1..c63d960506 100644
--- a/rust/cloud-storage/referral/src/inbound/axum_router/get_referral_code.rs
+++ b/rust/cloud-storage/referral/src/inbound/axum_router/get_referral_code.rs
@@ -16,7 +16,7 @@ use crate::domain::ports::ReferralService;
path = "/referral/code",
operation_id = "get_referral_code",
responses(
- (status = 200, body = ReferralCode),
+ (status = 200, body = String),
(status = 401, body = model_error_response::ErrorResponse),
(status = 500, body = model_error_response::ErrorResponse),
)
diff --git a/rust/cloud-storage/referral/src/inbound/axum_router/send_invite.rs b/rust/cloud-storage/referral/src/inbound/axum_router/send_invite.rs
new file mode 100644
index 0000000000..bdfefd9f63
--- /dev/null
+++ b/rust/cloud-storage/referral/src/inbound/axum_router/send_invite.rs
@@ -0,0 +1,47 @@
+//! Handler for `POST /send`.
+
+use axum::http::StatusCode;
+use axum::{Json, extract::State};
+use macro_user_id::email::EmailStr;
+use model_user::axum_extractor::MacroUserExtractor;
+use serde::Deserialize;
+
+use super::ReferralRouterState;
+use crate::domain::models::ReferralError;
+use crate::domain::ports::ReferralService;
+
+/// The body which is used to describe the recipient email
+#[derive(Deserialize, utoipa::ToSchema)]
+pub struct SendInviteBody {
+ /// the recipient of the referral email
+ #[schema(value_type = String)]
+ recipient: EmailStr<'static>,
+}
+
+/// Handler for `POST /referral/send`.
+///
+/// Sends a referral code via email to a user
+#[utoipa::path(
+ tag = "referral",
+ post,
+ path = "/referral/send",
+ operation_id = "send_referral_code",
+ responses(
+ (status = StatusCode::NO_CONTENT),
+ (status = 401, body = model_error_response::ErrorResponse),
+ (status = 500, body = model_error_response::ErrorResponse),
+ )
+)]
+#[tracing::instrument(skip(state, user_context), err)]
+pub async fn post_referral_invite_handler<T: ReferralService>(
+ State(state): State<ReferralRouterState<T>>,
+ user_context: MacroUserExtractor,
+ Json(SendInviteBody { recipient }): Json<SendInviteBody>,
+) -> Result<StatusCode, ReferralError> {
+ let () = state
+ .service
+ .send_referral_invite(user_context.macro_user_id, recipient)
+ .await?;
+
+ Ok(StatusCode::NO_CONTENT)
+}
diff --git a/rust/cloud-storage/referral/src/inbound/axum_router/test.rs b/rust/cloud-storage/referral/src/inbound/axum_router/test.rs
index b536c370be..0b112ff86c 100644
--- a/rust/cloud-storage/referral/src/inbound/axum_router/test.rs
+++ b/rust/cloud-storage/referral/src/inbound/axum_router/test.rs
@@ -50,6 +50,14 @@ impl ReferralService for MockReferralService {
) -> Result<(), ReferralError> {
Ok(())
}
+
+ async fn send_referral_invite(
+ &self,
+ _sending_user: macro_user_id::user_id::MacroUserIdStr<'_>,
+ _recipient: macro_user_id::email::EmailStr<'static>,
+ ) -> Result<(), ReferralError> {
+ todo!()
+ }
}
fn test_user_context() -> UserContext {
diff --git a/rust/cloud-storage/referral_invitation/Cargo.toml b/rust/cloud-storage/referral_invitation/Cargo.toml
new file mode 100644
index 0000000000..2fbe0a2553
--- /dev/null
+++ b/rust/cloud-storage/referral_invitation/Cargo.toml
@@ -0,0 +1,11 @@
+[package]
+edition = "2024"
+name = "referral_invitation"
+publish = false
+version = "0.1.0"
+
+
+[dependencies]
+macro_user_id = { path = "../macro_user_id" }
+notification = { path = "../notification" }
+serde = { workspace = true }
diff --git a/rust/cloud-storage/referral_invitation/src/lib.rs b/rust/cloud-storage/referral_invitation/src/lib.rs
new file mode 100644
index 0000000000..907e41cc67
--- /dev/null
+++ b/rust/cloud-storage/referral_invitation/src/lib.rs
@@ -0,0 +1,55 @@
+#![deny(missing_docs)]
+//! Domain models for referral invitation notifications.
+//!
+//! Contains the [`InviteToMacro`] notification type and the [`ReferralCode`] newtype.
+
+use macro_user_id::email::EmailStr;
+use notification::domain::models::{
+ Notification, NotificationExtEmail, RateLimitConfig, RateLimitKey, queue_message::EmailContent,
+};
+use serde::{Deserialize, Serialize};
+use std::time::Duration;
+
+/// Wrapper for the referral code to make it type safe
+#[derive(Debug, Clone, Serialize, Deserialize)]
+#[serde(transparent)]
+pub struct ReferralCode(pub String);
+
+/// The metadata for a referral-to-macro notification.
+#[derive(Debug, Serialize, Deserialize, Clone)]
+pub struct InviteToMacro {
+ /// The recipient email.
+ pub recipient_email: EmailStr<'static>,
+ /// The referral code which is templated into the email to track the sender
+ /// and reward them.
+ pub referral_code: ReferralCode,
+}
+
+impl Notification for InviteToMacro {
+ const TYPE_NAME: &'static str = "invite_to_macro";
+}
+
+const MINUTES_PER_WEEK: u64 = 60 * 24 * 7;
+
+impl NotificationExtEmail for InviteToMacro {
+ fn format_email(&self) -> EmailContent {
+ EmailContent {
+ subject: "You have been invited to join Macro".to_string(),
+ body: "Temporary email body placeholder".to_string(),
+ }
+ }
+
+ fn rate_limit_config() -> RateLimitConfig {
+ // 1 invite email per user per week
+ RateLimitConfig {
+ max_count: 1,
+ window: Duration::from_mins(MINUTES_PER_WEEK),
+ }
+ }
+
+ fn rate_limit_key(&self) -> RateLimitKey {
+ RateLimitKey::builder(&Self::TYPE_NAME)
+ .append(&self.recipient_email.0.as_ref())
+ .finish()
+ }
+}