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.

4.3 KB
Raw Blame
use askama::Template;
use chrono::{DateTime, Utc};
use hmac::Hmac;
use macro_env::Environment;
use macro_service_urls::NotificationServiceUrl;
use macro_user_id::cowlike::CowLike;
use model_notifications::NotifEvent;
use notification::domain::models::{
    Notification, NotificationExtEmail, NotificationTitle, RateLimitConfig, RateLimitKey,
    UserNotificationRow,
    email_notification_digest::ports::DigestBatch,
    queue_message::EmailContent,
    signing::{self, SignedUrl},
};
use rootcause::{Report, report};
use serde::{Deserialize, Serialize};
use sha2::Sha256;
use std::time::Duration;

#[cfg(test)]
mod test;

#[derive(Template)]
#[template(path = "digest.html")]
struct DigestTemplate {
    notifs: Vec<NotifPreview>,
    num_truncated: usize,
    total_count: usize,
    /// the signed url which allows a client to unsubscribe from the email in an unauthenticated context
    unsubscribe_url: SignedUrl,
}

struct NotifPreview {
    created_at: DateTime<Utc>,
    title: String,
    body: String,
}

const TRUNCATE_LEN: usize = 15;
const BODY_MAX_CHARS: usize = 500;

fn truncate_body(s: String) -> String {
    if s.chars().count() <= BODY_MAX_CHARS {
        return s;
    }
    let byte_limit = s
        .char_indices()
        .nth(BODY_MAX_CHARS)
        .map(|(i, _)| i)
        .unwrap_or(s.len());
    let truncated = &s[..byte_limit];
    match truncated.rfind(' ') {
        Some(pos) => format!("{}…", s[..pos].trim_end()),
        None => format!("{}…", truncated),
    }
}

impl NotifPreview {
    #[tracing::instrument(err)]
    fn new(v: UserNotificationRow<NotifEvent>) -> Result<Self, Report> {
        let title = v
            .notification_metadata
            .format_title(v.sender_id.as_ref().map(CowLike::copied))?;
        let body = truncate_body(v.notification_metadata.format_body(v.sender_id)?);
        Ok(NotifPreview {
            created_at: v.created_at,
            title,
            body,
        })
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EmailDigestNotification {
    /// the templated html string of the email
    inner_html_string: String,
    /// the subject line of the notification
    subject: String,
}

impl EmailDigestNotification {
    pub fn new_from_digest_batch(
        digest: DigestBatch,
        env: Environment,
        sha: Hmac<Sha256>,
    ) -> Result<Self, Report> {
        let DigestBatch {
            user_id: _,
            notifications,
            ..
        } = digest;

        let input_len = notifications.len();

        fn log_err<E: std::fmt::Debug>(e: &E) {
            tracing::error!("{e:?}");
        }

        let notifs: Vec<_> = notifications
            .into_iter()
            .map(|v| v.deserialize_metadata::<NotifEvent>())
            .filter_map(|res| res.inspect_err(log_err).ok())
            .map(NotifPreview::new)
            .filter_map(Result::ok)
            .take(TRUNCATE_LEN)
            .collect();

        let preview_len = notifs.len();
        if preview_len == 0 {
            return Err(report!("Batch with 0 notifications"));
        }
        let num_truncated = input_len - preview_len;

        let unsubscribe_url = signing::unsubscribe_url(
            NotificationServiceUrl::new_for_environment(env)?.parse_url()?,
            Self::TYPE_NAME,
            digest.user_id.as_ref(),
            sha,
        );

        let inner_html_string = DigestTemplate {
            notifs,
            num_truncated,
            total_count: input_len,
            unsubscribe_url,
        }
        .render()?;

        Ok(EmailDigestNotification {
            inner_html_string,
            subject: format!("You have {input_len} new notifications on Macro"),
        })
    }
}

impl Notification for EmailDigestNotification {
    const TYPE_NAME: &'static str = "email-digest-notification";
}

impl NotificationExtEmail for EmailDigestNotification {
    fn format_email(&self) -> EmailContent {
        EmailContent::new(self.subject.clone(), self.inner_html_string.clone())
    }

    fn rate_limit_config() -> RateLimitConfig {
        RateLimitConfig {
            max_count: 600,
            window: Duration::from_hours(1),
        }
    }

    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)
    }
}