Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
chore(seed_cli): Email data (#1540)
Evan Hutnik6b20f98810f1
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 44a7164139..a436925e4d 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -8049,16 +8049,21 @@ name = "seed_cli"version = "0.1.0"dependencies = ["anyhow",+ "chrono","clap","comms_db_client","csv",+ "email_db_client","fusionauth",+ "futures","macro_entrypoint","macro_env","macro_env_var","macro_user_id","mockall","model",+ "models_email",+ "rand 0.9.0","reqwest","serde","serde_json",diff --git a/rust/cloud-storage/seed_cli/.gitignore b/rust/cloud-storage/seed_cli/.gitignoredeleted file mode 100644index e69de29bb2..0000000000diff --git a/rust/cloud-storage/seed_cli/Cargo.toml b/rust/cloud-storage/seed_cli/Cargo.tomlindex ae8f7778ad..0443fdc90d 100644--- a/rust/cloud-storage/seed_cli/Cargo.toml+++ b/rust/cloud-storage/seed_cli/Cargo.toml@@ -23,6 +23,11 @@ comms_db_client = { path = "../comms_db_client" }model = { path = "../model" }csv = { workspace = true }uuid = { workspace = true }+email_db_client = { path = "../email_db_client" }+models_email = { path = "../models_email" }+chrono = { workspace = true }+rand = { workspace = true }+futures = { workspace = true }[dev-dependencies]tempfile = "3"diff --git a/rust/cloud-storage/seed_cli/seed/emails.json b/rust/cloud-storage/seed_cli/seed/emails.jsonnew file mode 100644index 0000000000..d77ebe4d6f--- /dev/null+++ b/rust/cloud-storage/seed_cli/seed/emails.json@@ -0,0 +1,649 @@+{+ "user_id": "019c59e0-6267-7732-abe7-b2fd0daa2234",+ "email_address": "[email protected]",+ "provider": "Gmail",+ "labels": [+ {+ "provider_label_id": "INBOX",+ "name": "INBOX",+ "label_type": "System"+ },+ {+ "provider_label_id": "SPAM",+ "name": "SPAM",+ "label_type": "System"+ },+ {+ "provider_label_id": "TRASH",+ "name": "TRASH",+ "label_type": "System"+ },+ {+ "provider_label_id": "UNREAD",+ "name": "UNREAD",+ "label_type": "System"+ },+ {+ "provider_label_id": "STARRED",+ "name": "STARRED",+ "label_type": "System"+ },+ {+ "provider_label_id": "IMPORTANT",+ "name": "IMPORTANT",+ "label_type": "System"+ },+ {+ "provider_label_id": "SENT",+ "name": "SENT",+ "label_type": "System"+ },+ {+ "provider_label_id": "DRAFT",+ "name": "DRAFT",+ "label_type": "System"+ },+ {+ "provider_label_id": "CATEGORY_PERSONAL",+ "name": "CATEGORY_PERSONAL",+ "label_type": "System"+ },+ {+ "provider_label_id": "CATEGORY_SOCIAL",+ "name": "CATEGORY_SOCIAL",+ "label_type": "System"+ },+ {+ "provider_label_id": "CATEGORY_PROMOTIONS",+ "name": "CATEGORY_PROMOTIONS",+ "label_type": "System"+ },+ {+ "provider_label_id": "CATEGORY_UPDATES",+ "name": "CATEGORY_UPDATES",+ "label_type": "System"+ },+ {+ "provider_label_id": "CATEGORY_FORUMS",+ "name": "CATEGORY_FORUMS",+ "label_type": "System"+ }+ ],+ "threads": [+ {+ "provider_id": "cc2018b20b64c8f9",+ "inbox_visible": true,+ "is_read": true,+ "messages": [+ {+ "provider_id": "44f57eda86ef48ac",+ "subject": "Project Update",+ "snippet": null,+ "sent_at": "2020-07-27T18:24:46Z",+ "is_read": true,+ "is_starred": false,+ "is_sent": false,+ "from": {+ "email": "[email protected]",+ "name": "Irene Taylor",+ "photo_url": null+ },+ "to": [+ {+ "email": "[email protected]",+ "name": "Me",+ "photo_url": null+ }+ ],+ "cc": [],+ "body_template": "invoice",+ "label_ids": [+ "INBOX"+ ]+ },+ {+ "provider_id": "be809cbc9d65a2f4",+ "subject": "Project Update",+ "snippet": null,+ "sent_at": "2020-07-27T19:38:46Z",+ "is_read": true,+ "is_starred": false,+ "is_sent": true,+ "from": {+ "email": "[email protected]",+ "name": "Me",+ "photo_url": null+ },+ "to": [+ {+ "email": "[email protected]",+ "name": "Henry Moore",+ "photo_url": null+ }+ ],+ "cc": [],+ "body_template": "quick_question",+ "label_ids": [+ "SENT",+ "CATEGORY_UPDATES"+ ]+ }+ ]+ },+ {+ "provider_id": "989c182333a03676",+ "inbox_visible": true,+ "is_read": false,+ "messages": [+ {+ "provider_id": "c4442d22af6618db",+ "subject": "Feedback on the proposal",+ "snippet": null,+ "sent_at": "2020-10-01T18:05:15Z",+ "is_read": true,+ "is_starred": false,+ "is_sent": false,+ "from": {+ "email": "[email protected]",+ "name": "Grace Wilson",+ "photo_url": null+ },+ "to": [+ {+ "email": "[email protected]",+ "name": "Me",+ "photo_url": null+ },+ {+ "email": "[email protected]",+ "name": "Grace Wilson",+ "photo_url": null+ }+ ],+ "cc": [],+ "body_template": "welcome",+ "label_ids": [+ "INBOX",+ "UNREAD"+ ]+ },+ {+ "provider_id": "e7794d3cf427d8c0",+ "subject": "Feedback on the proposal",+ "snippet": null,+ "sent_at": "2020-10-01T19:35:15Z",+ "is_read": false,+ "is_starred": false,+ "is_sent": false,+ "from": {+ "email": "[email protected]",+ "name": "Frank Miller",+ "photo_url": null+ },+ "to": [+ {+ "email": "[email protected]",+ "name": "Me",+ "photo_url": null+ }+ ],+ "cc": [],+ "body_template": "invoice",+ "label_ids": [+ "INBOX",+ "UNREAD"+ ]+ }+ ]+ },+ {+ "provider_id": "5d3fec426eac63be",+ "inbox_visible": true,+ "is_read": false,+ "messages": [+ {+ "provider_id": "e5a6c88fc03f3f5e",+ "subject": "Bug report: search not working",+ "snippet": null,+ "sent_at": "2021-05-07T05:16:46Z",+ "is_read": true,+ "is_starred": false,+ "is_sent": true,+ "from": {+ "email": "[email protected]",+ "name": "Me",+ "photo_url": null+ },+ "to": [+ {+ "email": "[email protected]",+ "name": "Alice Johnson",+ "photo_url": null+ },+ {+ "email": "[email protected]",+ "name": "Henry Moore",+ "photo_url": null+ }+ ],+ "cc": [],+ "body_template": "welcome",+ "label_ids": [+ "SENT",+ "UNREAD"+ ]+ },+ {+ "provider_id": "eff5ab05b66b7921",+ "subject": "Bug report: search not working",+ "snippet": null,+ "sent_at": "2021-05-07T05:53:46Z",+ "is_read": false,+ "is_starred": false,+ "is_sent": false,+ "from": {+ "email": "[email protected]",+ "name": "Eve Davis",+ "photo_url": null+ },+ "to": [+ {+ "email": "[email protected]",+ "name": "Me",+ "photo_url": null+ }+ ],+ "cc": [],+ "body_template": "project_update",+ "label_ids": [+ "INBOX",+ "UNREAD"+ ]+ }+ ]+ },+ {+ "provider_id": "d0d787c7c8f4795b",+ "inbox_visible": true,+ "is_read": false,+ "messages": [+ {+ "provider_id": "21cf47bd267dbd39",+ "subject": "Bug report: search not working",+ "snippet": null,+ "sent_at": "2022-03-09T13:47:11Z",+ "is_read": false,+ "is_starred": false,+ "is_sent": false,+ "from": {+ "email": "[email protected]",+ "name": "Carol Williams",+ "photo_url": null+ },+ "to": [+ {+ "email": "[email protected]",+ "name": "Me",+ "photo_url": null+ }+ ],+ "cc": [],+ "body_template": "meeting_followup",+ "label_ids": [+ "INBOX",+ "UNREAD",+ "CATEGORY_FORUMS"+ ]+ }+ ]+ },+ {+ "provider_id": "739b695aa411d84b",+ "inbox_visible": true,+ "is_read": false,+ "messages": [+ {+ "provider_id": "f250c7a2959135ad",+ "subject": "Project Update",+ "snippet": null,+ "sent_at": "2022-09-19T06:58:35Z",+ "is_read": true,+ "is_starred": true,+ "is_sent": false,+ "from": {+ "email": "[email protected]",+ "name": "Grace Wilson",+ "photo_url": null+ },+ "to": [+ {+ "email": "[email protected]",+ "name": "Me",+ "photo_url": null+ }+ ],+ "cc": [],+ "body_template": "quick_question",+ "label_ids": [+ "INBOX",+ "UNREAD"+ ]+ },+ {+ "provider_id": "90462477be6d1e9d",+ "subject": "Project Update",+ "snippet": null,+ "sent_at": "2022-09-19T07:33:35Z",+ "is_read": false,+ "is_starred": false,+ "is_sent": false,+ "from": {+ "email": "[email protected]",+ "name": "David Brown",+ "photo_url": null+ },+ "to": [+ {+ "email": "[email protected]",+ "name": "Me",+ "photo_url": null+ }+ ],+ "cc": [+ {+ "email": "[email protected]",+ "name": "Irene Taylor",+ "photo_url": null+ },+ {+ "email": "[email protected]",+ "name": "Grace Wilson",+ "photo_url": null+ }+ ],+ "body_template": "welcome",+ "label_ids": [+ "INBOX",+ "UNREAD"+ ]+ }+ ]+ },+ {+ "provider_id": "a66c3ab4b00b2085",+ "inbox_visible": true,+ "is_read": true,+ "messages": [+ {+ "provider_id": "e3d99a6c34b8f647",+ "subject": "Action Required: Q3 Planning",+ "snippet": null,+ "sent_at": "2023-06-23T12:32:36Z",+ "is_read": true,+ "is_starred": false,+ "is_sent": false,+ "from": {+ "email": "[email protected]",+ "name": "Henry Moore",+ "photo_url": null+ },+ "to": [+ {+ "email": "[email protected]",+ "name": "Me",+ "photo_url": null+ }+ ],+ "cc": [+ {+ "email": "[email protected]",+ "name": "Henry Moore",+ "photo_url": null+ }+ ],+ "body_template": "meeting_followup",+ "label_ids": [+ "INBOX",+ "CATEGORY_FORUMS"+ ]+ },+ {+ "provider_id": "a183b1eb3ddcfd4c",+ "subject": "Action Required: Q3 Planning",+ "snippet": null,+ "sent_at": "2023-06-23T14:06:36Z",+ "is_read": true,+ "is_starred": false,+ "is_sent": false,+ "from": {+ "email": "[email protected]",+ "name": "Eve Davis",+ "photo_url": null+ },+ "to": [+ {+ "email": "[email protected]",+ "name": "Me",+ "photo_url": null+ }+ ],+ "cc": [+ {+ "email": "[email protected]",+ "name": "Grace Wilson",+ "photo_url": null+ }+ ],+ "body_template": "invoice",+ "label_ids": [+ "INBOX"+ ]+ }+ ]+ },+ {+ "provider_id": "30027e5e0d946b70",+ "inbox_visible": true,+ "is_read": true,+ "messages": [+ {+ "provider_id": "6915ba8642f7f8e0",+ "subject": "Meeting Follow-up",+ "snippet": null,+ "sent_at": "2024-01-21T01:06:54Z",+ "is_read": true,+ "is_starred": true,+ "is_sent": false,+ "from": {+ "email": "[email protected]",+ "name": "Carol Williams",+ "photo_url": null+ },+ "to": [+ {+ "email": "[email protected]",+ "name": "Me",+ "photo_url": null+ }+ ],+ "cc": [],+ "body_template": "meeting_followup",+ "label_ids": [+ "INBOX",+ "CATEGORY_SOCIAL"+ ]+ }+ ]+ },+ {+ "provider_id": "d4ba3bb4f026c4f2",+ "inbox_visible": true,+ "is_read": false,+ "messages": [+ {+ "provider_id": "be8f186b8bf0836d",+ "subject": "Quick Question",+ "snippet": null,+ "sent_at": "2024-09-14T18:32:32Z",+ "is_read": true,+ "is_starred": false,+ "is_sent": true,+ "from": {+ "email": "[email protected]",+ "name": "Me",+ "photo_url": null+ },+ "to": [+ {+ "email": "[email protected]",+ "name": "Eve Davis",+ "photo_url": null+ },+ {+ "email": "[email protected]",+ "name": "Grace Wilson",+ "photo_url": null+ }+ ],+ "cc": [],+ "body_template": "meeting_followup",+ "label_ids": [+ "SENT",+ "UNREAD"+ ]+ },+ {+ "provider_id": "1d50b112994dae44",+ "subject": "Quick Question",+ "snippet": null,+ "sent_at": "2024-09-14T19:31:32Z",+ "is_read": false,+ "is_starred": true,+ "is_sent": false,+ "from": {+ "email": "[email protected]",+ "name": "Irene Taylor",+ "photo_url": null+ },+ "to": [+ {+ "email": "[email protected]",+ "name": "Me",+ "photo_url": null+ }+ ],+ "cc": [],+ "body_template": "meeting_followup",+ "label_ids": [+ "INBOX",+ "UNREAD"+ ]+ }+ ]+ },+ {+ "provider_id": "6765f4c498a6599e",+ "inbox_visible": true,+ "is_read": false,+ "messages": [+ {+ "provider_id": "e2dea21810af096b",+ "subject": "Lunch tomorrow?",+ "snippet": null,+ "sent_at": "2025-02-06T17:03:31Z",+ "is_read": false,+ "is_starred": true,+ "is_sent": false,+ "from": {+ "email": "[email protected]",+ "name": "Carol Williams",+ "photo_url": null+ },+ "to": [+ {+ "email": "[email protected]",+ "name": "Me",+ "photo_url": null+ }+ ],+ "cc": [],+ "body_template": "meeting_followup",+ "label_ids": [+ "INBOX",+ "UNREAD"+ ]+ }+ ]+ },+ {+ "provider_id": "5163cddad13a0c26",+ "inbox_visible": true,+ "is_read": true,+ "messages": [+ {+ "provider_id": "92c00fff21d4db8a",+ "subject": "Meeting Follow-up",+ "snippet": null,+ "sent_at": "2025-09-12T01:21:42Z",+ "is_read": true,+ "is_starred": false,+ "is_sent": false,+ "from": {+ "email": "[email protected]",+ "name": "David Brown",+ "photo_url": null+ },+ "to": [+ {+ "email": "[email protected]",+ "name": "Me",+ "photo_url": null+ }+ ],+ "cc": [],+ "body_template": "welcome",+ "label_ids": [+ "INBOX"+ ]+ },+ {+ "provider_id": "170713b2648daf53",+ "subject": "Meeting Follow-up",+ "snippet": null,+ "sent_at": "2025-09-12T02:21:42Z",+ "is_read": true,+ "is_starred": false,+ "is_sent": true,+ "from": {+ "email": "[email protected]",+ "name": "Me",+ "photo_url": null+ },+ "to": [+ {+ "email": "[email protected]",+ "name": "Alice Johnson",+ "photo_url": null+ },+ {+ "email": "[email protected]",+ "name": "Grace Wilson",+ "photo_url": null+ },+ {+ "email": "[email protected]",+ "name": "Irene Taylor",+ "photo_url": null+ }+ ],+ "cc": [],+ "body_template": "invoice",+ "label_ids": [+ "SENT",+ "CATEGORY_PERSONAL"+ ]+ }+ ]+ }+ ]+}\ No newline at end of filediff --git a/rust/cloud-storage/seed_cli/src/entity/email/README.md b/rust/cloud-storage/seed_cli/src/entity/email/README.mdnew file mode 100644index 0000000000..f1436fcc87--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/entity/email/README.md@@ -0,0 +1,80 @@+# Email Seed Data++Two-step workflow for populating your local Macro environment with email data.++## Prerequisites++1. Local database running (`docker-compose up -d macrodb`)+2. Environment set up (`just get_environment` from the `seed_cli` directory)+3. A FusionAuth user ID (create one with `cargo run -- user create --email [email protected]`)++## Step 1: Bulk Generate++Creates a JSON file with randomized email data (threads, messages, contacts, labels).++```bash+cargo run -- email bulk-generate \+ --user-id "<fusionauth-user-id>" \+ --email-address "[email protected]"+```++Output is written to `seed_cli/seed/emails.json`.++### Options++| Flag | Default | Description |+|------|---------|-------------|+| `--user-id` | required | FusionAuth user ID |+| `--email-address` | required | Email address for the user |+| `--thread-count` | 10 | Number of threads to generate |+| `--max-messages-per-thread` | 10 | Max messages per thread (random 1..max) |+| `--output` | `emails.json` | Output filename |++### What gets generated++- **13 system labels**: INBOX, SENT, SPAM, TRASH, UNREAD, STARRED, IMPORTANT, DRAFT, and 5 CATEGORY_* labels+- **N threads** each with a random number of messages, spread evenly from 2020 to now+- **Messages** with random sender/recipients from 9 fake contacts (`[email protected]` through `[email protected]`)+- **Body templates** — each message references a template name from `sample_bodies/` (bodies are resolved at import time, not stored in the JSON)+- **Provider IDs** (random hex strings) on all threads and messages++## Step 2: Seed++Reads the generated JSON and inserts everything into the database.++```bash+cargo run -- email seed+```++By default reads from `seed/emails.json`. Use `--file-path` to override.++### Options++| Flag | Default | Description |+|------|---------|-------------|+| `--file-path` | `seed/emails.json` | Path to the JSON file |+| `--concurrency` | 95 | Max concurrent database insertions |++### What gets inserted++1. `email_links` — connects the user to the Gmail provider+2. `email_labels` — all 13 system labels+3. For each thread: `email_threads`, `email_messages`, `email_contacts`, `email_message_recipients`, `email_message_labels`++## Sharing seed data++The generated JSON file is lightweight (bodies are template references). To share seed data with another developer:++1. Generate the file+2. Edit `user_id` and `email_address` in the JSON to match their local user+3. Send them the file to import++The `seed/` directory is gitignored by default.++## Sample bodies++Plaintext and HTML email body templates live in `sample_bodies/`. To add new ones:++1. Create matching `<name>.txt` and `<name>.html` files in `sample_bodies/`+2. Add the template name to `TEMPLATE_NAMES` in `sample_bodies.rs`+3. Add the `include_str!` entries in `load_sample_bodies()`diff --git a/rust/cloud-storage/seed_cli/src/entity/email/mod.rs b/rust/cloud-storage/seed_cli/src/entity/email/mod.rsnew file mode 100644index 0000000000..87384781e5--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/entity/email/mod.rs@@ -0,0 +1,608 @@+//! Email entity commands for seeding email data.+//!+//! Workflow:+//! 1. `generate` creates a JSON file with randomized email seed data+//! 2. `import` reads a JSON file and inserts the data into the database+//!+//! This two-step process allows developers to share seed data files.++#[cfg(test)]+mod test;++mod sample_bodies;++use std::path::Path;+use std::sync::Arc;+use std::sync::atomic::{AtomicU32, Ordering};++use anyhow::Context;+use chrono::{DateTime, Duration, Utc};+use clap::{Args, Subcommand};+use futures::stream::{self, StreamExt};+use models_email::email::service::address::ContactInfo;+use models_email::email::service::label::{+ Label, LabelListVisibility, LabelType, MessageListVisibility,+};+use models_email::email::service::link::UserProvider;+use models_email::email::service::message::Message;+use models_email::email::service::thread::Thread;+use rand::Rng;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use crate::config::SeedCliContext;++/// Arguments for the `email` entity subcommand.+#[derive(Debug, Args)]+pub struct EmailArgs {+ /// The action to perform on emails+ #[command(subcommand)]+ pub command: EmailCommand,+}++/// Available commands for the email entity.+#[derive(Debug, Subcommand)]+pub enum EmailCommand {+ /// Generate a JSON file of randomized email seed data+ BulkGenerate(BulkGenerateArgs),+ /// Import email data from a JSON file into the database+ Seed(SeedArgs),+}++/// Arguments for generating random email data.+#[derive(Debug, Args)]+pub struct BulkGenerateArgs {+ /// The user ID (fusionauth) to generate emails for+ #[arg(long)]+ pub user_id: String,+ /// The email address of the user+ #[arg(long)]+ pub email_address: String,+ /// Number of threads to generate+ #[arg(long, default_value = "10")]+ pub thread_count: u32,+ /// Max messages per thread (actual count is random between 1 and this value)+ #[arg(long, default_value = "10")]+ pub max_messages_per_thread: u32,+ /// Output file name for the generated JSON (written to seed_cli/seed/)+ #[arg(long, default_value = "emails.json")]+ pub output: String,+}++/// Arguments for importing email data from a file.+#[derive(Debug, Args)]+pub struct SeedArgs {+ /// Path to the JSON file containing email data to import (defaults to seed/emails.json)+ #[arg(long)]+ pub file_path: Option<String>,+ /// Max concurrent database insertions+ #[arg(long, default_value = "95")]+ pub concurrency: usize,+}++/// The top-level seed data structure that gets serialized to JSON.+#[derive(Debug, Serialize, Deserialize)]+pub struct SeedEmailData {+ /// The fusionauth user ID that owns this email data+ pub user_id: String,+ /// The email address of the owner+ pub email_address: String,+ /// The email provider+ pub provider: UserProvider,+ /// Labels to create for the user+ pub labels: Vec<SeedLabel>,+ /// Threads with their messages+ pub threads: Vec<SeedThread>,+}++/// A label in the seed data.+#[derive(Debug, Serialize, Deserialize)]+pub struct SeedLabel {+ /// The provider label ID (e.g. "INBOX", "SENT")+ pub provider_label_id: String,+ /// Display name+ pub name: String,+ /// Label type+ pub label_type: LabelType,+}++/// A thread in the seed data.+#[derive(Debug, Serialize, Deserialize)]+pub struct SeedThread {+ /// Provider thread ID (random hex string)+ pub provider_id: String,+ /// Whether the thread should appear in the inbox+ pub inbox_visible: bool,+ /// Whether the thread is read+ pub is_read: bool,+ /// The messages in this thread+ pub messages: Vec<SeedMessage>,+}++/// A message in the seed data.+#[derive(Debug, Serialize, Deserialize)]+pub struct SeedMessage {+ /// Provider message ID (random hex string)+ pub provider_id: String,+ /// The subject line+ pub subject: Option<String>,+ /// Short snippet+ pub snippet: Option<String>,+ /// When the message was sent+ pub sent_at: DateTime<Utc>,+ /// Whether the message has been read+ pub is_read: bool,+ /// Whether the message is starred+ pub is_starred: bool,+ /// Whether the message was sent by the owner+ pub is_sent: bool,+ /// Sender contact+ pub from: ContactInfo,+ /// To recipients+ pub to: Vec<ContactInfo>,+ /// CC recipients+ pub cc: Vec<ContactInfo>,+ /// Sample body template name (references a file in sample_bodies/)+ pub body_template: String,+ /// Label provider IDs to apply to this message+ pub label_ids: Vec<String>,+}++/// Fake contacts used for generating seed data.+const FAKE_CONTACTS: &[(&str, &str)] = &[+ ("[email protected]", "Alice Johnson"),+ ("[email protected]", "Bob Smith"),+ ("[email protected]", "Carol Williams"),+ ("[email protected]", "David Brown"),+ ("[email protected]", "Eve Davis"),+ ("[email protected]", "Frank Miller"),+ ("[email protected]", "Grace Wilson"),+ ("[email protected]", "Henry Moore"),+ ("[email protected]", "Irene Taylor"),+];++/// All system labels to create for each user.+const SYSTEM_LABELS: &[(&str, &str)] = &[+ ("INBOX", "INBOX"),+ ("SPAM", "SPAM"),+ ("TRASH", "TRASH"),+ ("UNREAD", "UNREAD"),+ ("STARRED", "STARRED"),+ ("IMPORTANT", "IMPORTANT"),+ ("SENT", "SENT"),+ ("DRAFT", "DRAFT"),+ ("CATEGORY_PERSONAL", "CATEGORY_PERSONAL"),+ ("CATEGORY_SOCIAL", "CATEGORY_SOCIAL"),+ ("CATEGORY_PROMOTIONS", "CATEGORY_PROMOTIONS"),+ ("CATEGORY_UPDATES", "CATEGORY_UPDATES"),+ ("CATEGORY_FORUMS", "CATEGORY_FORUMS"),+];++/// Subject lines to randomly pick from.+const SUBJECTS: &[&str] = &[+ "Meeting Follow-up",+ "Project Update",+ "Quick Question",+ "Welcome to the Team",+ "Invoice for January",+ "Re: Design Review",+ "Lunch tomorrow?",+ "Action Required: Q3 Planning",+ "FYI - Policy Update",+ "Thanks for your help!",+ "Scheduling conflict",+ "New feature request",+ "Bug report: search not working",+ "Weekly standup notes",+ "Feedback on the proposal",+];++/// Labels that can be randomly assigned to inbox messages (excluding structural ones).+const RANDOM_MESSAGE_LABELS: &[&str] = &[+ "CATEGORY_PERSONAL",+ "CATEGORY_SOCIAL",+ "CATEGORY_PROMOTIONS",+ "CATEGORY_UPDATES",+ "CATEGORY_FORUMS",+ "IMPORTANT",+];++impl EmailArgs {+ /// Execute the email command.+ pub async fn execute(self, ctx: SeedCliContext) -> anyhow::Result<()> {+ match self.command {+ EmailCommand::BulkGenerate(args) => bulk_generate(args).await,+ EmailCommand::Seed(args) => seed(args, ctx).await,+ }+ }+}++#[tracing::instrument(err)]+async fn bulk_generate(args: BulkGenerateArgs) -> anyhow::Result<()> {+ tracing::info!("generating email seed data");++ let mut rng = rand::rng();+ let template_names = sample_bodies::TEMPLATE_NAMES;++ let labels: Vec<SeedLabel> = SYSTEM_LABELS+ .iter()+ .map(|(id, name)| SeedLabel {+ provider_label_id: id.to_string(),+ name: name.to_string(),+ label_type: LabelType::System,+ })+ .collect();++ let owner_contact = ContactInfo {+ email: args.email_address.clone(),+ name: Some("Me".to_string()),+ photo_url: None,+ };++ let mut threads = Vec::with_capacity(args.thread_count as usize);+ let now = Utc::now();+ let earliest = DateTime::parse_from_rfc3339("2020-01-01T00:00:00Z")+ .expect("valid date")+ .with_timezone(&Utc);+ let total_seconds = (now - earliest).num_seconds();++ for i in 0..args.thread_count {+ let message_count = rng.random_range(1..=args.max_messages_per_thread);+ let is_read = rng.random_bool(0.6);+ let subject = SUBJECTS[rng.random_range(0..SUBJECTS.len())].to_string();++ // Spread threads evenly across [earliest, now], with some jitter+ let fraction = i as f64 / args.thread_count.max(1) as f64;+ let base_offset = (fraction * total_seconds as f64) as i64;+ let jitter = rng.random_range(0..total_seconds / args.thread_count.max(1) as i64);+ let thread_base_time = earliest + Duration::seconds(base_offset + jitter);++ let mut messages = Vec::with_capacity(message_count as usize);++ for j in 0..message_count {+ // Space messages within the thread by 5 minutes to 2 hours+ let msg_time =+ thread_base_time + Duration::minutes(j as i64 * rng.random_range(5..120));+ let is_sent_by_owner = rng.random_bool(0.3);++ let (from, to, cc) = if is_sent_by_owner {+ let recipient_count = rng.random_range(1..=3);+ let recipients = pick_random_contacts(&mut rng, recipient_count);+ let cc_contacts = if rng.random_bool(0.2) {+ pick_random_contacts(&mut rng, 1)+ } else {+ vec![]+ };+ (owner_contact.clone(), recipients, cc_contacts)+ } else {+ let sender_idx = rng.random_range(0..FAKE_CONTACTS.len());+ let sender = make_contact(FAKE_CONTACTS[sender_idx]);+ let mut to_list = vec![owner_contact.clone()];+ if rng.random_bool(0.2) {+ to_list.extend(pick_random_contacts(&mut rng, 1));+ }+ let cc_contacts = if rng.random_bool(0.15) {+ let cc_count = rng.random_range(1..=2);+ pick_random_contacts(&mut rng, cc_count)+ } else {+ vec![]+ };+ (sender, to_list, cc_contacts)+ };++ let body_template =+ template_names[rng.random_range(0..template_names.len())].to_string();++ // Build label set for this message+ let mut label_ids = Vec::new();+ if !is_sent_by_owner {+ label_ids.push("INBOX".to_string());+ }+ if is_sent_by_owner {+ label_ids.push("SENT".to_string());+ }+ if !is_read {+ label_ids.push("UNREAD".to_string());+ }+ // Add a random category/important label+ if rng.random_bool(0.5) {+ let random_label =+ RANDOM_MESSAGE_LABELS[rng.random_range(0..RANDOM_MESSAGE_LABELS.len())];+ if !label_ids.contains(&random_label.to_string()) {+ label_ids.push(random_label.to_string());+ }+ }++ messages.push(SeedMessage {+ provider_id: random_hex_id(&mut rng),+ subject: Some(subject.clone()),+ snippet: None,+ sent_at: msg_time,+ is_read: is_read || j < message_count - 1, // older messages in thread are read+ is_starred: rng.random_bool(0.1),+ is_sent: is_sent_by_owner,+ from,+ to,+ cc,+ body_template,+ label_ids,+ });+ }++ let has_inbound = messages.iter().any(|m| !m.is_sent);++ threads.push(SeedThread {+ provider_id: random_hex_id(&mut rng),+ inbox_visible: has_inbound,+ is_read,+ messages,+ });+ }++ let seed_data = SeedEmailData {+ user_id: args.user_id,+ email_address: args.email_address,+ provider: UserProvider::Gmail,+ labels,+ threads,+ };++ let json = serde_json::to_string_pretty(&seed_data).context("failed to serialize seed data")?;++ let output_dir = Path::new(env!("CARGO_MANIFEST_DIR")).join("seed");+ std::fs::create_dir_all(&output_dir).with_context(|| {+ format!(+ "failed to create output directory: {}",+ output_dir.display()+ )+ })?;++ let output_path = output_dir.join(&args.output);+ std::fs::write(&output_path, &json)+ .with_context(|| format!("failed to write output file: {}", output_path.display()))?;++ println!(+ "Generated seed data with {} threads to {}",+ args.thread_count,+ output_path.display()+ );++ Ok(())+}++#[tracing::instrument(skip(ctx), err)]+async fn seed(args: SeedArgs, ctx: SeedCliContext) -> anyhow::Result<()> {+ tracing::info!("importing email seed data");++ let default_path = Path::new(env!("CARGO_MANIFEST_DIR"))+ .join("seed")+ .join("emails.json");+ let file_path = args+ .file_path+ .map(std::path::PathBuf::from)+ .unwrap_or(default_path);++ let content = std::fs::read_to_string(&file_path)+ .with_context(|| format!("failed to read json file: {}", file_path.display()))?;++ let seed_data: SeedEmailData =+ serde_json::from_str(&content).context("failed to parse seed data json")?;++ // 1. Create the email link+ let macro_id = macro_user_id::user_id::MacroUserIdStr::try_from_email(&seed_data.email_address)+ .context("failed to create macro user id from email")?;+ let email_str = macro_user_id::email::EmailStr::try_from(seed_data.email_address.clone())+ .context("failed to parse email address")?;++ let now = Utc::now();+ let link = models_email::email::service::link::Link {+ id: Uuid::now_v7(),+ macro_id,+ fusionauth_user_id: seed_data.user_id.clone(),+ email_address: email_str,+ provider: seed_data.provider,+ is_sync_active: true,+ created_at: now,+ updated_at: now,+ };++ let link = ctx.db.upsert_email_link(link).await?;+ let link_id = link.id;+ println!("Created email link with id {link_id}");++ // 2. Create labels+ let labels: Vec<Label> = seed_data+ .labels+ .iter()+ .map(|l| Label {+ id: None,+ link_id,+ provider_label_id: l.provider_label_id.clone(),+ name: Some(l.name.clone()),+ created_at: now,+ message_list_visibility: Some(MessageListVisibility::Show),+ label_list_visibility: Some(LabelListVisibility::LabelShow),+ type_: Some(l.label_type),+ })+ .collect();++ ctx.db.insert_email_labels(labels).await?;+ println!("Created {} labels", seed_data.labels.len());++ // 3. Insert threads with messages concurrently+ let created = Arc::new(AtomicU32::new(0));+ let failed = Arc::new(AtomicU32::new(0));+ let db = Arc::new(ctx.db);+ let bodies = Arc::new(sample_bodies::load_sample_bodies());++ stream::iter(seed_data.threads.iter().map(|seed_thread| {+ let db = Arc::clone(&db);+ let created = Arc::clone(&created);+ let failed = Arc::clone(&failed);+ let bodies = Arc::clone(&bodies);++ async move {+ let thread = build_thread(seed_thread, link_id, now, &bodies);+ let subject_label = seed_thread+ .messages+ .first()+ .and_then(|m| m.subject.as_deref())+ .unwrap_or("<no subject>")+ .to_string();++ match db.insert_email_thread(thread, link_id).await {+ Ok(id) => {+ println!("Created thread \"{subject_label}\" with id {id}");+ created.fetch_add(1, Ordering::Relaxed);+ }+ Err(e) => {+ tracing::error!(error=?e, subject = subject_label, "failed to create thread");+ println!("Failed to create thread \"{subject_label}\": {e}");+ failed.fetch_add(1, Ordering::Relaxed);+ }+ }+ }+ }))+ .buffer_unordered(args.concurrency)+ .collect::<Vec<()>>()+ .await;++ let created = created.load(Ordering::Relaxed);+ let failed = failed.load(Ordering::Relaxed);++ println!("\nImport complete: {created} threads created, {failed} failed");++ Ok(())+}++/// Build a `Thread` from seed data for insertion.+fn build_thread(+ seed_thread: &SeedThread,+ link_id: Uuid,+ now: DateTime<Utc>,+ bodies: &std::collections::HashMap<String, sample_bodies::SampleBody>,+) -> Thread {+ let thread_id = Uuid::now_v7();+ let latest_sent_at = seed_thread.messages.last().map(|m| m.sent_at);+ let latest_inbound = seed_thread+ .messages+ .iter()+ .rev()+ .find(|m| !m.is_sent)+ .map(|m| m.sent_at);+ let latest_outbound = seed_thread+ .messages+ .iter()+ .rev()+ .find(|m| m.is_sent)+ .map(|m| m.sent_at);++ let messages: Vec<Message> = seed_thread+ .messages+ .iter()+ .map(|m| {+ let msg_labels: Vec<Label> = m+ .label_ids+ .iter()+ .map(|lid| Label {+ id: None,+ link_id,+ provider_label_id: lid.clone(),+ name: Some(lid.clone()),+ created_at: now,+ message_list_visibility: None,+ label_list_visibility: None,+ type_: None,+ })+ .collect();++ let (body_text, body_html) = bodies+ .get(&m.body_template)+ .map(|(t, h)| (Some(t.clone()), Some(h.clone())))+ .unwrap_or((None, None));++ let snippet = body_text+ .as_ref()+ .map(|t| t.chars().take(100).collect::<String>());++ Message {+ db_id: Uuid::now_v7(),+ provider_id: Some(m.provider_id.clone()),+ thread_db_id: thread_id,+ provider_thread_id: Some(seed_thread.provider_id.clone()),+ replying_to_id: None,+ global_id: None,+ link_id,+ subject: m.subject.clone(),+ snippet,+ provider_history_id: None,+ internal_date_ts: Some(m.sent_at),+ sent_at: Some(m.sent_at),+ size_estimate: None,+ is_read: m.is_read,+ is_starred: m.is_starred,+ is_sent: m.is_sent,+ is_draft: false,+ scheduled_send_time: None,+ has_attachments: false,+ from: Some(m.from.clone()),+ to: m.to.clone(),+ cc: m.cc.clone(),+ bcc: vec![],+ labels: msg_labels,+ body_text,+ body_html_sanitized: body_html,+ body_macro: None,+ attachments: vec![],+ attachments_draft: vec![],+ attachments_forwarded: vec![],+ headers_json: None,+ created_at: m.sent_at,+ updated_at: m.sent_at,+ }+ })+ .collect();++ Thread {+ db_id: thread_id,+ provider_id: Some(seed_thread.provider_id.clone()),+ link_id,+ inbox_visible: seed_thread.inbox_visible,+ is_read: seed_thread.is_read,+ latest_inbound_message_ts: latest_inbound,+ latest_outbound_message_ts: latest_outbound,+ latest_non_spam_message_ts: latest_sent_at,+ created_at: seed_thread+ .messages+ .first()+ .map(|m| m.sent_at)+ .unwrap_or(now),+ updated_at: latest_sent_at.unwrap_or(now),+ messages,+ }+}++fn make_contact(contact: (&str, &str)) -> ContactInfo {+ ContactInfo {+ email: contact.0.to_string(),+ name: Some(contact.1.to_string()),+ photo_url: None,+ }+}++fn pick_random_contacts(rng: &mut impl Rng, count: usize) -> Vec<ContactInfo> {+ let mut indices: Vec<usize> = (0..FAKE_CONTACTS.len()).collect();+ let mut selected = Vec::with_capacity(count);+ for _ in 0..count.min(FAKE_CONTACTS.len()) {+ let idx = rng.random_range(0..indices.len());+ let contact_idx = indices.swap_remove(idx);+ selected.push(make_contact(FAKE_CONTACTS[contact_idx]));+ }+ selected+}++/// Generate a random 16-character hex string (8 random bytes).+fn random_hex_id(rng: &mut impl Rng) -> String {+ let bytes: [u8; 8] = rng.random();+ bytes.iter().map(|b| format!("{b:02x}")).collect()+}diff --git a/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies.rs b/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies.rsnew file mode 100644index 0000000000..fe9fb99ca1--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies.rs@@ -0,0 +1,56 @@+//! Loads sample email body content from embedded files.++use std::collections::HashMap;++/// A pair of (plaintext body, html body).+pub type SampleBody = (String, String);++/// All available sample body template names.+pub const TEMPLATE_NAMES: &[&str] = &[+ "meeting_followup",+ "project_update",+ "quick_question",+ "welcome",+ "invoice",+];++/// Load all sample email bodies as a map of template name to (plaintext, html).+pub fn load_sample_bodies() -> HashMap<String, SampleBody> {+ HashMap::from([+ (+ "meeting_followup".to_string(),+ (+ include_str!("sample_bodies/meeting_followup.txt").to_string(),+ include_str!("sample_bodies/meeting_followup.html").to_string(),+ ),+ ),+ (+ "project_update".to_string(),+ (+ include_str!("sample_bodies/project_update.txt").to_string(),+ include_str!("sample_bodies/project_update.html").to_string(),+ ),+ ),+ (+ "quick_question".to_string(),+ (+ include_str!("sample_bodies/quick_question.txt").to_string(),+ include_str!("sample_bodies/quick_question.html").to_string(),+ ),+ ),+ (+ "welcome".to_string(),+ (+ include_str!("sample_bodies/welcome.txt").to_string(),+ include_str!("sample_bodies/welcome.html").to_string(),+ ),+ ),+ (+ "invoice".to_string(),+ (+ include_str!("sample_bodies/invoice.txt").to_string(),+ include_str!("sample_bodies/invoice.html").to_string(),+ ),+ ),+ ])+}diff --git a/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/invoice.html b/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/invoice.htmlnew file mode 100644index 0000000000..1bc92e55de--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/invoice.html@@ -0,0 +1,13 @@+<div>+ <p>Hi,</p>+ <p>Please find attached the invoice for services rendered in January 2025.</p>+ <table style="border-collapse: collapse; margin: 16px 0;">+ <tr><td style="padding: 4px 12px; font-weight: bold;">Invoice #:</td><td style="padding: 4px 12px;">INV-2025-0142</td></tr>+ <tr><td style="padding: 4px 12px; font-weight: bold;">Amount:</td><td style="padding: 4px 12px;">$4,500.00</td></tr>+ <tr><td style="padding: 4px 12px; font-weight: bold;">Due Date:</td><td style="padding: 4px 12px;">February 15, 2025</td></tr>+ </table>+ <p>Payment can be made via bank transfer using the details on the invoice, or through our payment portal.</p>+ <p>Please let me know if you have any questions or need any adjustments.</p>+ <p>Thank you for your business!</p>+ <p>Regards,</p>+</div>diff --git a/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/invoice.txt b/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/invoice.txtnew file mode 100644index 0000000000..da89f62a9c--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/invoice.txt@@ -0,0 +1,15 @@+Hi,++Please find attached the invoice for services rendered in January 2025.++Invoice #: INV-2025-0142+Amount: $4,500.00+Due Date: February 15, 2025++Payment can be made via bank transfer using the details on the invoice, or through our payment portal.++Please let me know if you have any questions or need any adjustments.++Thank you for your business!++Regards,diff --git a/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/meeting_followup.html b/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/meeting_followup.htmlnew file mode 100644index 0000000000..ba88f8354c--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/meeting_followup.html@@ -0,0 +1,17 @@+<div>+ <p>Hi team,</p>+ <p>Thanks for joining the meeting earlier today. Here's a quick summary of what we discussed:</p>+ <ol>+ <li>Q3 roadmap priorities have been finalized</li>+ <li>The new design system rollout is on track for next month</li>+ <li>We need to finalize the API migration plan by end of week</li>+ </ol>+ <p><strong>Action items:</strong></p>+ <ul>+ <li>Sarah: Share the updated timeline document</li>+ <li>Mike: Set up the staging environment for testing</li>+ <li>Everyone: Review the RFC and leave comments by Friday</li>+ </ul>+ <p>Let me know if I missed anything. Looking forward to making progress on these items!</p>+ <p>Best,</p>+</div>diff --git a/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/meeting_followup.txt b/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/meeting_followup.txtnew file mode 100644index 0000000000..33020f440e--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/meeting_followup.txt@@ -0,0 +1,16 @@+Hi team,++Thanks for joining the meeting earlier today. Here's a quick summary of what we discussed:++1. Q3 roadmap priorities have been finalized+2. The new design system rollout is on track for next month+3. We need to finalize the API migration plan by end of week++Action items:+- Sarah: Share the updated timeline document+- Mike: Set up the staging environment for testing+- Everyone: Review the RFC and leave comments by Friday++Let me know if I missed anything. Looking forward to making progress on these items!++Best,diff --git a/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/project_update.html b/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/project_update.htmlnew file mode 100644index 0000000000..c8c384024c--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/project_update.html@@ -0,0 +1,13 @@+<div>+ <p>Hey everyone,</p>+ <p>Quick update on the project status:</p>+ <p>We've completed the initial implementation of the new search feature and it's currently in code review. Early feedback has been positive - the response times are significantly better than what we had before.</p>+ <p>A few things to note:</p>+ <ul>+ <li>The indexing pipeline needs some optimization for large documents</li>+ <li>We found a minor bug in the sorting logic that's being patched</li>+ <li>Performance benchmarks are looking great, ~40% improvement over the previous version</li>+ </ul>+ <p>Next steps are to get this merged and deployed to staging by Wednesday. I'll send another update once we have QA results.</p>+ <p>Cheers,</p>+</div>diff --git a/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/project_update.txt b/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/project_update.txtnew file mode 100644index 0000000000..65767ee102--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/project_update.txt@@ -0,0 +1,14 @@+Hey everyone,++Quick update on the project status:++We've completed the initial implementation of the new search feature and it's currently in code review. Early feedback has been positive - the response times are significantly better than what we had before.++A few things to note:+- The indexing pipeline needs some optimization for large documents+- We found a minor bug in the sorting logic that's being patched+- Performance benchmarks are looking great, ~40% improvement over the previous version++Next steps are to get this merged and deployed to staging by Wednesday. I'll send another update once we have QA results.++Cheers,diff --git a/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/quick_question.html b/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/quick_question.htmlnew file mode 100644index 0000000000..6dd12d62d7--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/quick_question.html@@ -0,0 +1,6 @@+<div>+ <p>Hey,</p>+ <p>Do you have a few minutes to chat about the deployment plan? I had a couple of questions about the rollback strategy and wanted to make sure we're aligned before we push to production.</p>+ <p>No rush - tomorrow works too if you're busy today.</p>+ <p>Thanks!</p>+</div>diff --git a/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/quick_question.txt b/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/quick_question.txtnew file mode 100644index 0000000000..101e148a82--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/quick_question.txt@@ -0,0 +1,7 @@+Hey,++Do you have a few minutes to chat about the deployment plan? I had a couple of questions about the rollback strategy and wanted to make sure we're aligned before we push to production.++No rush - tomorrow works too if you're busy today.++Thanks!diff --git a/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/welcome.html b/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/welcome.htmlnew file mode 100644index 0000000000..4ccb5f05b4--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/welcome.html@@ -0,0 +1,12 @@+<div>+ <p>Welcome to the team! We're excited to have you on board.</p>+ <p>Here are a few things to get you started:</p>+ <ol>+ <li>Check out the onboarding guide in our wiki</li>+ <li>Set up your development environment using the README</li>+ <li>Join the #engineering and #general channels</li>+ <li>Schedule a 1:1 with your team lead this week</li>+ </ol>+ <p>If you run into any issues or have questions, don't hesitate to reach out. We have a very open culture and everyone is happy to help.</p>+ <p>Looking forward to working with you!</p>+</div>diff --git a/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/welcome.txt b/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/welcome.txtnew file mode 100644index 0000000000..03eaed3f09--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/entity/email/sample_bodies/welcome.txt@@ -0,0 +1,12 @@+Welcome to the team! We're excited to have you on board.++Here are a few things to get you started:++1. Check out the onboarding guide in our wiki+2. Set up your development environment using the README+3. Join the #engineering and #general channels+4. Schedule a 1:1 with your team lead this week++If you run into any issues or have questions, don't hesitate to reach out. We have a very open culture and everyone is happy to help.++Looking forward to working with you!diff --git a/rust/cloud-storage/seed_cli/src/entity/email/test.rs b/rust/cloud-storage/seed_cli/src/entity/email/test.rsnew file mode 100644index 0000000000..5a028bac0a--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/entity/email/test.rs@@ -0,0 +1,504 @@+use std::io::Write;++use clap::Parser;+use tempfile::NamedTempFile;++use crate::Cli;+use crate::config::SeedCliContext;+use crate::service::auth::Auth;+use crate::service::db::Db;++use super::*;++// ── Parsing tests ──────────────────────────────────────────++#[test]+fn parse_email_bulk_generate_minimal() {+ let cli = Cli::try_parse_from([+ "seed_cli",+ "email",+ "bulk-generate",+ "--user-id",+ "test-user-123",+ "--email-address",+ "[email protected]",+ ])+ .unwrap();++ match cli.command {+ crate::entity::EntityCommand::Email(args) => match args.command {+ EmailCommand::BulkGenerate(bulk) => {+ assert_eq!(bulk.user_id, "test-user-123");+ assert_eq!(bulk.email_address, "[email protected]");+ assert_eq!(bulk.thread_count, 10);+ assert_eq!(bulk.max_messages_per_thread, 10);+ assert_eq!(bulk.output, "emails.json");+ }+ other => panic!("expected BulkGenerate, got {other:?}"),+ },+ other => panic!("expected Email, got {other:?}"),+ }+}++#[test]+fn parse_email_bulk_generate_with_options() {+ let cli = Cli::try_parse_from([+ "seed_cli",+ "email",+ "bulk-generate",+ "--user-id",+ "test-user-123",+ "--email-address",+ "[email protected]",+ "--thread-count",+ "50",+ "--max-messages-per-thread",+ "5",+ "--output",+ "custom.json",+ ])+ .unwrap();++ match cli.command {+ crate::entity::EntityCommand::Email(args) => match args.command {+ EmailCommand::BulkGenerate(bulk) => {+ assert_eq!(bulk.thread_count, 50);+ assert_eq!(bulk.max_messages_per_thread, 5);+ assert_eq!(bulk.output, "custom.json");+ }+ other => panic!("expected BulkGenerate, got {other:?}"),+ },+ other => panic!("expected Email, got {other:?}"),+ }+}++#[test]+fn parse_email_bulk_generate_missing_user_id_fails() {+ let result = Cli::try_parse_from([+ "seed_cli",+ "email",+ "bulk-generate",+ "--email-address",+ "[email protected]",+ ]);+ assert!(result.is_err());+}++#[test]+fn parse_email_bulk_generate_missing_email_fails() {+ let result = Cli::try_parse_from([+ "seed_cli",+ "email",+ "bulk-generate",+ "--user-id",+ "test-user-123",+ ]);+ assert!(result.is_err());+}++#[test]+fn parse_email_seed_defaults() {+ let cli = Cli::try_parse_from(["seed_cli", "email", "seed"]).unwrap();++ match cli.command {+ crate::entity::EntityCommand::Email(args) => match args.command {+ EmailCommand::Seed(create) => {+ assert_eq!(create.file_path, None);+ assert_eq!(create.concurrency, 95);+ }+ other => panic!("expected Seed, got {other:?}"),+ },+ other => panic!("expected Email, got {other:?}"),+ }+}++#[test]+fn parse_email_seed_with_file_path_override() {+ let cli = Cli::try_parse_from([+ "seed_cli",+ "email",+ "seed",+ "--file-path",+ "/tmp/emails.json",+ ])+ .unwrap();++ match cli.command {+ crate::entity::EntityCommand::Email(args) => match args.command {+ EmailCommand::Seed(create) => {+ assert_eq!(create.file_path, Some("/tmp/emails.json".to_string()));+ assert_eq!(create.concurrency, 95);+ }+ other => panic!("expected Seed, got {other:?}"),+ },+ other => panic!("expected Email, got {other:?}"),+ }+}++#[test]+fn parse_email_seed_with_concurrency() {+ let cli = Cli::try_parse_from(["seed_cli", "email", "seed", "--concurrency", "10"]).unwrap();++ match cli.command {+ crate::entity::EntityCommand::Email(args) => match args.command {+ EmailCommand::Seed(create) => {+ assert_eq!(create.concurrency, 10);+ }+ other => panic!("expected Seed, got {other:?}"),+ },+ other => panic!("expected Email, got {other:?}"),+ }+}++// ── Helpers ────────────────────────────────────────────────++fn mock_ctx(db: Db) -> SeedCliContext {+ SeedCliContext {+ db,+ fusionauth_client: Auth::default(),+ }+}++fn write_temp_json(content: &str) -> NamedTempFile {+ let mut file = NamedTempFile::new().unwrap();+ file.write_all(content.as_bytes()).unwrap();+ file.flush().unwrap();+ file+}++fn minimal_seed_json(thread_count: usize) -> String {+ let mut threads = Vec::new();+ for _ in 0..thread_count {+ threads.push(serde_json::json!({+ "provider_id": "abcdef0123456789",+ "inbox_visible": true,+ "is_read": false,+ "messages": [{+ "provider_id": "1234567890abcdef",+ "subject": "Test Subject",+ "snippet": null,+ "sent_at": "2024-06-01T12:00:00Z",+ "is_read": false,+ "is_starred": false,+ "is_sent": false,+ "from": { "email": "[email protected]", "name": "Alice Johnson", "photo_url": null },+ "to": [{ "email": "[email protected]", "name": "Me", "photo_url": null }],+ "cc": [],+ "body_template": "meeting_followup",+ "label_ids": ["INBOX", "UNREAD"]+ }]+ }));+ }++ serde_json::json!({+ "user_id": "test-user-123",+ "email_address": "[email protected]",+ "provider": "Gmail",+ "labels": [+ { "provider_label_id": "INBOX", "name": "INBOX", "label_type": "System" },+ { "provider_label_id": "SENT", "name": "SENT", "label_type": "System" }+ ],+ "threads": threads+ })+ .to_string()+}++// ── Integration tests (seed) ──────────────────────────────++#[tokio::test]+async fn seed_inserts_link_labels_and_threads() {+ let json = minimal_seed_json(2);+ let file = write_temp_json(&json);++ let mut mock_db = Db::default();+ mock_db+ .expect_upsert_email_link()+ .times(1)+ .returning(|link| Ok(link));+ mock_db+ .expect_insert_email_labels()+ .times(1)+ .returning(|_| Ok(()));+ mock_db+ .expect_insert_email_thread()+ .times(2)+ .returning(|_, _| Ok(Uuid::nil()));++ let args = EmailArgs {+ command: EmailCommand::Seed(SeedArgs {+ file_path: Some(file.path().to_str().unwrap().to_string()),+ concurrency: 95,+ }),+ };++ let result = args.execute(mock_ctx(mock_db)).await;+ assert!(result.is_ok());+}++#[tokio::test]+async fn seed_single_thread() {+ let json = minimal_seed_json(1);+ let file = write_temp_json(&json);++ let mut mock_db = Db::default();+ mock_db+ .expect_upsert_email_link()+ .times(1)+ .returning(|link| Ok(link));+ mock_db+ .expect_insert_email_labels()+ .times(1)+ .returning(|_| Ok(()));+ mock_db+ .expect_insert_email_thread()+ .times(1)+ .returning(|_, _| Ok(Uuid::nil()));++ let args = EmailArgs {+ command: EmailCommand::Seed(SeedArgs {+ file_path: Some(file.path().to_str().unwrap().to_string()),+ concurrency: 95,+ }),+ };++ let result = args.execute(mock_ctx(mock_db)).await;+ assert!(result.is_ok());+}++#[tokio::test]+async fn seed_missing_file_fails() {+ let mock_db = Db::default();++ let args = EmailArgs {+ command: EmailCommand::Seed(SeedArgs {+ file_path: Some("/nonexistent/path.json".to_string()),+ concurrency: 95,+ }),+ };++ let result = args.execute(mock_ctx(mock_db)).await;+ let err = result.unwrap_err();+ assert!(err.to_string().contains("failed to read json file"));+}++#[tokio::test]+async fn seed_invalid_json_fails() {+ let file = write_temp_json("not valid json {{{");++ let mock_db = Db::default();++ let args = EmailArgs {+ command: EmailCommand::Seed(SeedArgs {+ file_path: Some(file.path().to_str().unwrap().to_string()),+ concurrency: 95,+ }),+ };++ let result = args.execute(mock_ctx(mock_db)).await;+ let err = result.unwrap_err();+ assert!(err.to_string().contains("failed to parse seed data json"));+}++#[tokio::test]+async fn seed_continues_on_thread_failure() {+ let json = minimal_seed_json(3);+ let file = write_temp_json(&json);++ let mut mock_db = Db::default();+ mock_db+ .expect_upsert_email_link()+ .times(1)+ .returning(|link| Ok(link));+ mock_db+ .expect_insert_email_labels()+ .times(1)+ .returning(|_| Ok(()));++ let call_count = Arc::new(AtomicU32::new(0));+ let call_count_clone = Arc::clone(&call_count);+ mock_db+ .expect_insert_email_thread()+ .times(3)+ .returning(move |_, _| {+ let n = call_count_clone.fetch_add(1, Ordering::Relaxed);+ if n == 1 {+ Err(anyhow::anyhow!("db error"))+ } else {+ Ok(Uuid::nil())+ }+ });++ let args = EmailArgs {+ command: EmailCommand::Seed(SeedArgs {+ file_path: Some(file.path().to_str().unwrap().to_string()),+ concurrency: 1, // sequential so ordering is predictable+ }),+ };++ let result = args.execute(mock_ctx(mock_db)).await;+ assert!(result.is_ok());+}++#[tokio::test]+async fn seed_link_failure_propagates() {+ let json = minimal_seed_json(1);+ let file = write_temp_json(&json);++ let mut mock_db = Db::default();+ mock_db+ .expect_upsert_email_link()+ .times(1)+ .returning(|_| Err(anyhow::anyhow!("link creation failed")));++ let args = EmailArgs {+ command: EmailCommand::Seed(SeedArgs {+ file_path: Some(file.path().to_str().unwrap().to_string()),+ concurrency: 95,+ }),+ };++ let result = args.execute(mock_ctx(mock_db)).await;+ let err = result.unwrap_err();+ assert!(err.to_string().contains("link creation failed"));+}++#[tokio::test]+async fn seed_label_failure_propagates() {+ let json = minimal_seed_json(1);+ let file = write_temp_json(&json);++ let mut mock_db = Db::default();+ mock_db+ .expect_upsert_email_link()+ .times(1)+ .returning(|link| Ok(link));+ mock_db+ .expect_insert_email_labels()+ .times(1)+ .returning(|_| Err(anyhow::anyhow!("label insertion failed")));++ let args = EmailArgs {+ command: EmailCommand::Seed(SeedArgs {+ file_path: Some(file.path().to_str().unwrap().to_string()),+ concurrency: 95,+ }),+ };++ let result = args.execute(mock_ctx(mock_db)).await;+ let err = result.unwrap_err();+ assert!(err.to_string().contains("label insertion failed"));+}++// ── build_thread unit tests ───────────────────────────────++#[test]+fn build_thread_sets_provider_id() {+ let bodies = sample_bodies::load_sample_bodies();+ let seed = SeedThread {+ provider_id: "abc123".to_string(),+ inbox_visible: true,+ is_read: false,+ messages: vec![make_seed_message()],+ };++ let thread = build_thread(&seed, Uuid::nil(), Utc::now(), &bodies);+ assert_eq!(thread.provider_id, Some("abc123".to_string()));+}++#[test]+fn build_thread_resolves_body_template() {+ let bodies = sample_bodies::load_sample_bodies();+ let seed = SeedThread {+ provider_id: "abc123".to_string(),+ inbox_visible: true,+ is_read: false,+ messages: vec![make_seed_message()],+ };++ let thread = build_thread(&seed, Uuid::nil(), Utc::now(), &bodies);+ assert!(thread.messages[0].body_text.is_some());+ assert!(thread.messages[0].body_html_sanitized.is_some());+}++#[test]+fn build_thread_computes_timestamps() {+ let bodies = sample_bodies::load_sample_bodies();+ let sent_at = DateTime::parse_from_rfc3339("2024-06-01T12:00:00Z")+ .unwrap()+ .with_timezone(&Utc);++ let mut msg = make_seed_message();+ msg.sent_at = sent_at;+ msg.is_sent = false;++ let seed = SeedThread {+ provider_id: "abc123".to_string(),+ inbox_visible: true,+ is_read: false,+ messages: vec![msg],+ };++ let thread = build_thread(&seed, Uuid::nil(), Utc::now(), &bodies);+ assert_eq!(thread.latest_inbound_message_ts, Some(sent_at));+ assert_eq!(thread.latest_outbound_message_ts, None);+ assert_eq!(thread.latest_non_spam_message_ts, Some(sent_at));+}++#[test]+fn build_thread_multiple_messages_correct_order() {+ let bodies = sample_bodies::load_sample_bodies();+ let t1 = DateTime::parse_from_rfc3339("2024-06-01T12:00:00Z")+ .unwrap()+ .with_timezone(&Utc);+ let t2 = DateTime::parse_from_rfc3339("2024-06-01T13:00:00Z")+ .unwrap()+ .with_timezone(&Utc);++ let mut msg1 = make_seed_message();+ msg1.sent_at = t1;+ msg1.is_sent = false;++ let mut msg2 = make_seed_message();+ msg2.sent_at = t2;+ msg2.is_sent = true;++ let seed = SeedThread {+ provider_id: "abc123".to_string(),+ inbox_visible: true,+ is_read: false,+ messages: vec![msg1, msg2],+ };++ let thread = build_thread(&seed, Uuid::nil(), Utc::now(), &bodies);+ assert_eq!(thread.messages.len(), 2);+ assert_eq!(thread.latest_inbound_message_ts, Some(t1));+ assert_eq!(thread.latest_outbound_message_ts, Some(t2));+ assert_eq!(thread.created_at, t1);+}++// ── Test helpers ──────────────────────────────────────────++fn make_seed_message() -> SeedMessage {+ SeedMessage {+ provider_id: "1234567890abcdef".to_string(),+ subject: Some("Test Subject".to_string()),+ snippet: None,+ sent_at: Utc::now(),+ is_read: false,+ is_starred: false,+ is_sent: false,+ from: ContactInfo {+ email: "[email protected]".to_string(),+ name: Some("Alice Johnson".to_string()),+ photo_url: None,+ },+ to: vec![ContactInfo {+ email: "[email protected]".to_string(),+ name: Some("Me".to_string()),+ photo_url: None,+ }],+ cc: vec![],+ body_template: "meeting_followup".to_string(),+ label_ids: vec!["INBOX".to_string(), "UNREAD".to_string()],+ }+}diff --git a/rust/cloud-storage/seed_cli/src/entity/mod.rs b/rust/cloud-storage/seed_cli/src/entity/mod.rsindex 7a8d37077d..ceaf9a7f14 100644--- a/rust/cloud-storage/seed_cli/src/entity/mod.rs+++ b/rust/cloud-storage/seed_cli/src/entity/mod.rs@@ -2,6 +2,7 @@pub mod channel;pub mod channel_message;+pub mod email;pub mod user;use clap::Subcommand;@@ -17,6 +18,8 @@ pub enum EntityCommand {Channel(channel::ChannelArgs),/// Manage channel message seed dataChannelMessage(channel_message::ChannelMessageArgs),+ /// Manage email seed data+ Email(email::EmailArgs),}impl EntityCommand {@@ -26,6 +29,7 @@ impl EntityCommand {EntityCommand::User(args) => args.execute(ctx).await,EntityCommand::Channel(args) => args.execute(ctx).await,EntityCommand::ChannelMessage(args) => args.execute(ctx).await,+ EntityCommand::Email(args) => args.execute(ctx).await,}}}diff --git a/rust/cloud-storage/seed_cli/src/main.rs b/rust/cloud-storage/seed_cli/src/main.rsindex 88ad6466ed..91d56fb25b 100644--- a/rust/cloud-storage/seed_cli/src/main.rs+++ b/rust/cloud-storage/seed_cli/src/main.rs@@ -35,7 +35,7 @@ pub async fn main() -> anyhow::Result<()> {let db = PgPoolOptions::new().min_connections(1)- .max_connections(50)+ .max_connections(95).connect(&env_vars.database_urldiff --git a/rust/cloud-storage/seed_cli/src/service/db/mod.rs b/rust/cloud-storage/seed_cli/src/service/db/mod.rsindex 146f6e538e..dbdecb4243 100644--- a/rust/cloud-storage/seed_cli/src/service/db/mod.rs+++ b/rust/cloud-storage/seed_cli/src/service/db/mod.rs@@ -12,6 +12,7 @@ use comms_db_client::channels::create_channel::CreateChannelOptions;use comms_db_client::channels::seed_channel::SeedChannelOptions;use comms_db_client::messages::create_message::CreateMessageOptions;use comms_db_client::messages::seed_message::SeedMessageOptions;+use models_email::email::service;/// Wrapper around the database connection pool.pub struct SeedDb {@@ -63,4 +64,39 @@ impl SeedDb {comms_db_client::messages::seed_message::seed_message(&self.inner, options).await?;Ok(message.id)}++ /// Upsert an email link (connects a user to an email provider).+ #[tracing::instrument(skip(self), err)]+ pub async fn upsert_email_link(+ &self,+ link: service::link::Link,+ ) -> anyhow::Result<service::link::Link> {+ let result = email_db_client::links::insert::upsert_link(&self.inner, link).await?;+ Ok(result)+ }++ /// Insert or update email labels for a link.+ #[tracing::instrument(skip(self), err)]+ pub async fn insert_email_labels(+ &self,+ labels: Vec<service::label::Label>,+ ) -> anyhow::Result<()> {+ email_db_client::labels::insert::insert_or_update_labels(&self.inner, labels).await+ }++ /// Insert an email thread with all its messages, contacts, recipients, and labels.+ #[tracing::instrument(skip(self), err)]+ pub async fn insert_email_thread(+ &self,+ thread: service::thread::Thread,+ link_id: uuid::Uuid,+ ) -> anyhow::Result<uuid::Uuid> {+ let id = email_db_client::threads::insert::insert_thread_and_messages(+ &self.inner,+ thread,+ link_id,+ )+ .await?;+ Ok(id)+ }}