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
feat seed cli (#1477)
Will Hutchinson5dce8c8423be
diff --git a/docker-compose.yml b/docker-compose.ymlindex 9468cafa26..8d5d1ef69f 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -21,6 +21,7 @@ services:ports:- "8080:8080"depends_on:+ - postgres- fusionauth- redisnetworks:diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 959642d12b..82ddfc959d 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -7935,6 +7935,27 @@ dependencies = ["libc",]+[[package]]+name = "seed_cli"+version = "0.1.0"+dependencies = [+ "anyhow",+ "clap",+ "fusionauth",+ "macro_entrypoint",+ "macro_env",+ "macro_env_var",+ "macro_user_id",+ "mockall",+ "reqwest",+ "serde",+ "serde_json",+ "sqlx",+ "tempfile",+ "tokio",+ "tracing",+]+[[package]]name = "selectors"version = "0.25.0"diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex e0e574599c..bd4fff2559 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -100,6 +100,7 @@ members = ["search_service_client","search_upload_handler","secretsmanager_client",+ "seed_cli","ses_client","sha_cleanup_worker","sns_client",diff --git a/rust/cloud-storage/seed_cli/.gitignore b/rust/cloud-storage/seed_cli/.gitignorenew file mode 100644index 0000000000..afed0735dc--- /dev/null+++ b/rust/cloud-storage/seed_cli/.gitignore@@ -0,0 +1 @@+*.csvdiff --git a/rust/cloud-storage/seed_cli/Cargo.toml b/rust/cloud-storage/seed_cli/Cargo.tomlnew file mode 100644index 0000000000..a7fca85cd6--- /dev/null+++ b/rust/cloud-storage/seed_cli/Cargo.toml@@ -0,0 +1,24 @@+[package]+edition = "2024"+name = "seed_cli"+publish = false+version = "0.1.0"++[dependencies]+anyhow = { workspace = true }+serde = { workspace = true }+serde_json = { workspace = true }+clap = { workspace = true }+reqwest = { workspace = true }+macro_entrypoint = { path = "../macro_entrypoint" }+tracing = { workspace = true }+tokio = { workspace = true }+macro_env_var = { path = "../macro_env_var" }+macro_env = { path = "../macro_env" }+sqlx = { workspace = true }+macro_user_id = { path = "../macro_user_id" }+fusionauth = { path = "../fusionauth" }+mockall = { workspace = true }++[dev-dependencies]+tempfile = "3"diff --git a/rust/cloud-storage/seed_cli/justfile b/rust/cloud-storage/seed_cli/justfilenew file mode 100644index 0000000000..dd242c68bd--- /dev/null+++ b/rust/cloud-storage/seed_cli/justfile@@ -0,0 +1,8 @@+# Decrypts the root .env-local.enc into a .env file here+get_environment:+ @echo "Getting base .env file"+ just ../../../get_environment+ @echo "Adding in Fusionauth values"+ just ../../../infra/stacks/fusionauth-instance/insert_local_fusionauth_variables+ @echo "Copying env file"+ cp ../../../.env ./diff --git a/rust/cloud-storage/seed_cli/src/config.rs b/rust/cloud-storage/seed_cli/src/config.rsnew file mode 100644index 0000000000..fe419ad16c--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/config.rs@@ -0,0 +1,30 @@+use macro_env_var::env_var;++use crate::service::{auth::Auth, db::Db};++env_var! {+ pub struct EnvVars {+ /// macrodb url+ pub DatabaseUrl,+ /// fusionauth url+ pub FusionauthBaseUrl,+ /// fusionauth api key+ pub FusionauthApiKeySecretKey,+ /// fusionauth tenant id+ pub FusionauthTenantId,+ /// fusionauth client id+ pub FusionauthClientId,+ /// fusionauth client secret key+ pub FusionauthClientSecretKey,+ /// Fusionauth oauth redirect uri+ pub FusionauthOauthRedirectUri,+ }+}++/// The context containing everything we need to use in the CLI+pub struct SeedCliContext {+ /// Database connection to macrodb+ pub db: Db,+ /// Fusionauth client+ pub fusionauth_client: Auth,+}diff --git a/rust/cloud-storage/seed_cli/src/entity/mod.rs b/rust/cloud-storage/seed_cli/src/entity/mod.rsnew file mode 100644index 0000000000..7644df0053--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/entity/mod.rs@@ -0,0 +1,23 @@+//! Entity module containing all seed CLI entity subcommands.++pub mod user;++use clap::Subcommand;++use crate::config::SeedCliContext;++/// Top-level entity subcommands for the seed CLI.+#[derive(Debug, Subcommand)]+pub enum EntityCommand {+ /// Manage user seed data+ User(user::UserArgs),+}++impl EntityCommand {+ /// Execute the entity command.+ pub async fn execute(self, ctx: SeedCliContext) -> anyhow::Result<()> {+ match self {+ EntityCommand::User(args) => args.execute(ctx).await,+ }+ }+}diff --git a/rust/cloud-storage/seed_cli/src/entity/user/mod.rs b/rust/cloud-storage/seed_cli/src/entity/user/mod.rsnew file mode 100644index 0000000000..717ee31ce4--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/entity/user/mod.rs@@ -0,0 +1,122 @@+//! User entity commands for seeding user data.++#[cfg(test)]+mod test;++use std::borrow::Cow;+use std::path::Path;++use anyhow::Context;+use clap::{Args, Subcommand};++use crate::config::SeedCliContext;++/// Arguments for the `user` entity subcommand.+#[derive(Debug, Args)]+pub struct UserArgs {+ /// The action to perform on users+ #[command(subcommand)]+ pub command: UserCommand,+}++/// Available commands for the user entity.+#[derive(Debug, Subcommand)]+pub enum UserCommand {+ /// Create a single user+ Create(CreateArgs),+ /// Bulk create multiple users+ BulkCreate(BulkCreateArgs),+}++/// Arguments for creating a single user.+#[derive(Debug, Args)]+pub struct CreateArgs {+ /// The email of the user to create+ #[arg(long)]+ pub email: String,+}++/// Arguments for bulk creating users.+#[derive(Debug, Args)]+pub struct BulkCreateArgs {+ /// Path to the csv containing users to create+ #[arg(long)]+ pub file_path: String,+}++impl UserArgs {+ /// Execute the user command.+ pub async fn execute(self, ctx: SeedCliContext) -> anyhow::Result<()> {+ match self.command {+ UserCommand::Create(args) => create(args, ctx).await,+ UserCommand::BulkCreate(args) => bulk_create(args, ctx).await,+ }+ }+}++#[tracing::instrument(skip(ctx), err)]+async fn create(args: CreateArgs, ctx: SeedCliContext) -> anyhow::Result<()> {+ tracing::info!("creating user");+ let user_id = ctx+ .fusionauth_client+ .create_user(fusionauth::user::create::User {+ email: Cow::Borrowed(&args.email),+ username: Some(Cow::Borrowed(&args.email)),+ // TODO: do we want to bother with random generated passwords?+ password: "hardcodeLocalPassword123!".into(),+ })+ .await?;++ println!("Created FusionAuth user with id {user_id}");++ Ok(())+}++#[tracing::instrument(skip(ctx), err)]+async fn bulk_create(args: BulkCreateArgs, ctx: SeedCliContext) -> anyhow::Result<()> {+ tracing::info!("bulk creating users");++ let content = std::fs::read_to_string(Path::new(&args.file_path))+ .with_context(|| format!("failed to read csv file: {}", args.file_path))?;++ let emails: Vec<&str> = content+ .lines()+ .map(|line| line.trim())+ .filter(|line| !line.is_empty() && *line != "email")+ .collect();++ if emails.is_empty() {+ anyhow::bail!("no emails found in csv file");+ }++ println!("Found {} emails to create", emails.len());++ let mut created = 0;+ let mut failed = 0;++ for email in &emails {+ match ctx+ .fusionauth_client+ .create_user(fusionauth::user::create::User {+ email: Cow::Borrowed(email),+ username: Some(Cow::Borrowed(email)),+ password: "hardcodeLocalPassword123!".into(),+ })+ .await+ {+ Ok(user_id) => {+ println!("Created user {email} with id {user_id}");+ created += 1;+ }+ Err(e) => {+ tracing::error!(error=?e, email, "failed to create user");+ println!("Failed to create user {email}: {e}");+ failed += 1;+ }+ }+ }++ println!("\nBulk create complete: {created} created, {failed} failed");++ Ok(())+}diff --git a/rust/cloud-storage/seed_cli/src/entity/user/test.rs b/rust/cloud-storage/seed_cli/src/entity/user/test.rsnew file mode 100644index 0000000000..8ee727a6dc--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/entity/user/test.rs@@ -0,0 +1,265 @@+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::*;++#[test]+fn parse_user_create() {+ let cli = Cli::try_parse_from(["seed_cli", "user", "create", "--email", "[email protected]"])+ .unwrap();++ match cli.command {+ crate::entity::EntityCommand::User(args) => match args.command {+ super::UserCommand::Create(create) => {+ assert_eq!(create.email, "[email protected]");+ }+ other => panic!("expected Create, got {other:?}"),+ },+ }+}++#[test]+fn parse_user_bulk_create() {+ let cli = Cli::try_parse_from(["seed_cli", "user", "bulk-create", "--file-path", "test.csv"])+ .unwrap();++ match cli.command {+ crate::entity::EntityCommand::User(args) => match args.command {+ super::UserCommand::BulkCreate(bulk) => {+ assert_eq!(bulk.file_path, "test.csv");+ }+ other => panic!("expected BulkCreate, got {other:?}"),+ },+ }+}++#[test]+fn parse_user_create_missing_email_fails() {+ let result = Cli::try_parse_from(["seed_cli", "user", "create"]);+ assert!(result.is_err());+}++#[test]+fn parse_unknown_entity_fails() {+ let result = Cli::try_parse_from(["seed_cli", "bogus", "create"]);+ assert!(result.is_err());+}++#[test]+fn parse_unknown_user_command_fails() {+ let result = Cli::try_parse_from(["seed_cli", "user", "bogus"]);+ assert!(result.is_err());+}++fn mock_ctx(auth: Auth) -> SeedCliContext {+ SeedCliContext {+ db: Db::default(),+ fusionauth_client: auth,+ }+}++#[tokio::test]+async fn create_user_success() {+ let mut mock_auth = Auth::default();+ mock_auth+ .expect_create_user()+ .times(1)+ .withf(|user| user.email == "[email protected]")+ .returning(|_| Ok("new-user-id-123".to_string()));++ let args = UserArgs {+ command: UserCommand::Create(CreateArgs {+ email: "[email protected]".to_string(),+ }),+ };++ let result = args.execute(mock_ctx(mock_auth)).await;+ assert!(result.is_ok());+}++#[tokio::test]+async fn create_user_passes_email_as_username() {+ let mut mock_auth = Auth::default();+ mock_auth+ .expect_create_user()+ .times(1)+ .withf(|user| user.username.as_deref() == Some("[email protected]"))+ .returning(|_| Ok("user-id".to_string()));++ let args = UserArgs {+ command: UserCommand::Create(CreateArgs {+ email: "[email protected]".to_string(),+ }),+ };++ let result = args.execute(mock_ctx(mock_auth)).await;+ assert!(result.is_ok());+}++#[tokio::test]+async fn create_user_auth_failure_propagates_error() {+ let mut mock_auth = Auth::default();+ mock_auth+ .expect_create_user()+ .times(1)+ .returning(|_| Err(anyhow::anyhow!("user already exists")));++ let args = UserArgs {+ command: UserCommand::Create(CreateArgs {+ email: "[email protected]".to_string(),+ }),+ };++ let result = args.execute(mock_ctx(mock_auth)).await;+ let err = result.unwrap_err();+ assert!(err.to_string().contains("user already exists"));+}++#[tokio::test]+async fn create_user_network_error_propagates() {+ let mut mock_auth = Auth::default();+ mock_auth+ .expect_create_user()+ .times(1)+ .returning(|_| Err(anyhow::anyhow!("connection refused")));++ let args = UserArgs {+ command: UserCommand::Create(CreateArgs {+ email: "[email protected]".to_string(),+ }),+ };++ let result = args.execute(mock_ctx(mock_auth)).await;+ let err = result.unwrap_err();+ assert!(err.to_string().contains("connection refused"));+}++fn write_temp_csv(content: &str) -> NamedTempFile {+ let mut file = NamedTempFile::new().unwrap();+ file.write_all(content.as_bytes()).unwrap();+ file.flush().unwrap();+ file+}++#[tokio::test]+async fn bulk_create_creates_all_users() {+ let file = write_temp_csv("[email protected]\[email protected]\n");++ let mut mock_auth = Auth::default();+ mock_auth+ .expect_create_user()+ .times(2)+ .returning(|user| Ok(format!("id-for-{}", user.email)));++ let args = UserArgs {+ command: UserCommand::BulkCreate(BulkCreateArgs {+ file_path: file.path().to_str().unwrap().to_string(),+ }),+ };++ let result = args.execute(mock_ctx(mock_auth)).await;+ assert!(result.is_ok());+}++#[tokio::test]+async fn bulk_create_skips_email_header() {+ let file = write_temp_csv("email\[email protected]\n");++ let mut mock_auth = Auth::default();+ mock_auth+ .expect_create_user()+ .times(1)+ .withf(|user| user.email == "[email protected]")+ .returning(|_| Ok("user-id".to_string()));++ let args = UserArgs {+ command: UserCommand::BulkCreate(BulkCreateArgs {+ file_path: file.path().to_str().unwrap().to_string(),+ }),+ };++ let result = args.execute(mock_ctx(mock_auth)).await;+ assert!(result.is_ok());+}++#[tokio::test]+async fn bulk_create_skips_empty_lines() {+ let file = write_temp_csv("\[email protected]\n\n\[email protected]\n\n");++ let mut mock_auth = Auth::default();+ mock_auth+ .expect_create_user()+ .times(2)+ .returning(|_| Ok("user-id".to_string()));++ let args = UserArgs {+ command: UserCommand::BulkCreate(BulkCreateArgs {+ file_path: file.path().to_str().unwrap().to_string(),+ }),+ };++ let result = args.execute(mock_ctx(mock_auth)).await;+ assert!(result.is_ok());+}++#[tokio::test]+async fn bulk_create_empty_file_fails() {+ let file = write_temp_csv("");++ let mock_auth = Auth::default();++ let args = UserArgs {+ command: UserCommand::BulkCreate(BulkCreateArgs {+ file_path: file.path().to_str().unwrap().to_string(),+ }),+ };++ let result = args.execute(mock_ctx(mock_auth)).await;+ let err = result.unwrap_err();+ assert!(err.to_string().contains("no emails found"));+}++#[tokio::test]+async fn bulk_create_missing_file_fails() {+ let mock_auth = Auth::default();++ let args = UserArgs {+ command: UserCommand::BulkCreate(BulkCreateArgs {+ file_path: "/nonexistent/path.csv".to_string(),+ }),+ };++ let result = args.execute(mock_ctx(mock_auth)).await;+ let err = result.unwrap_err();+ assert!(err.to_string().contains("failed to read csv file"));+}++#[tokio::test]+async fn bulk_create_continues_on_failure() {++ let mut mock_auth = Auth::default();+ mock_auth.expect_create_user().times(3).returning(|user| {+ if user.email == "[email protected]" {+ Err(anyhow::anyhow!("user already exists"))+ } else {+ Ok(format!("id-for-{}", user.email))+ }+ });++ let args = UserArgs {+ command: UserCommand::BulkCreate(BulkCreateArgs {+ file_path: file.path().to_str().unwrap().to_string(),+ }),+ };++ let result = args.execute(mock_ctx(mock_auth)).await;+ assert!(result.is_ok());+}diff --git a/rust/cloud-storage/seed_cli/src/main.rs b/rust/cloud-storage/seed_cli/src/main.rsnew file mode 100644index 0000000000..88ad6466ed--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/main.rs@@ -0,0 +1,77 @@+#![deny(missing_docs)]+//! The Seed CLI to enable easy populate Macro with seed data++mod config;+mod entity;+mod service;++use anyhow::Context;+use clap::Parser;+use entity::EntityCommand;+use fusionauth::FusionAuthClient;+use macro_entrypoint::MacroEntrypoint;+use macro_env::Environment;+use service::{auth::Auth, db::Db};+use sqlx::postgres::PgPoolOptions;++use crate::config::{EnvVars, SeedCliContext};++/// The Seed CLI for populating Macro with seed data.+#[derive(Debug, Parser)]+#[command(name = "seed_cli", about = "Seed CLI to populate Macro with seed data")]+pub struct Cli {+ /// The entity and action to perform+ #[command(subcommand)]+ pub command: EntityCommand,+}++/// Entrypoint for cli+#[tokio::main]+pub async fn main() -> anyhow::Result<()> {+ // Force to use local tracing+ MacroEntrypoint::new(Environment::Local).init();+ let env_vars = EnvVars::new()?;+ tracing::trace!("initializing");++ let db = PgPoolOptions::new()+ .min_connections(1)+ .max_connections(50)+ .connect(+ &env_vars+ .database_url+ .replace("postgres:5432", "localhost:5432"),+ )+ .await+ .context("could not connect to db")?;+ tracing::trace!("initialized db");++ let fusionauth_client = FusionAuthClient::new(+ env_vars.fusionauth_tenant_id.to_string(),+ env_vars.fusionauth_api_key_secret_key.to_string(),+ env_vars.fusionauth_client_id.to_string(),+ env_vars.fusionauth_client_secret_key.to_string(),+ transform_docker_url(&env_vars.fusionauth_base_url),+ "".to_string(), // NOTE: Not needed. Oauth redirect uri+ "".to_string(), // NOTE: Not needed. Google Client id+ "".to_string(), // NOTE: Not needed. Google client secret+ );+ tracing::trace!("initialized fusionauth client");++ let context = SeedCliContext {+ db: Db::new(db),+ fusionauth_client: Auth::new(fusionauth_client),+ };++ let cli = Cli::parse();+ cli.command.execute(context).await+}++/// Transforms the docker-network url to be localhost+fn transform_docker_url(url: &str) -> String {+ if let Some(rest) = url.strip_prefix("http://")+ && let Some(colon_pos) = rest.find(':')+ {+ return format!("http://localhost{}", &rest[colon_pos..]);+ }+ url.to_string()+}diff --git a/rust/cloud-storage/seed_cli/src/service/auth/mod.rs b/rust/cloud-storage/seed_cli/src/service/auth/mod.rsnew file mode 100644index 0000000000..727c2a7228--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/service/auth/mod.rs@@ -0,0 +1,37 @@+//! Auth service wrapper.++#[cfg(test)]+pub use MockSeedAuth as Auth;+#[cfg(not(test))]+pub use SeedAuth as Auth;++use fusionauth::FusionAuthClient;+#[allow(unused_imports)]+use mockall::automock;++/// Wrapper around the FusionAuth client.+pub struct SeedAuth {+ /// Fusionauth client+ inner: FusionAuthClient,+}++#[cfg_attr(test, automock)]+impl SeedAuth {+ /// Create a new auth wrapper.+ pub fn new(inner: FusionAuthClient) -> Self {+ Self { inner }+ }++ #[tracing::instrument(skip(self), err)]+ pub async fn create_user<'a>(+ &self,+ user: fusionauth::user::create::User<'a>,+ ) -> anyhow::Result<String> {+ let result = self+ .inner+ .create_user(user, true /*skip_verification*/)+ .await?;++ Ok(result)+ }+}diff --git a/rust/cloud-storage/seed_cli/src/service/db/mod.rs b/rust/cloud-storage/seed_cli/src/service/db/mod.rsnew file mode 100644index 0000000000..baee5f2c2a--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/service/db/mod.rs@@ -0,0 +1,24 @@+//! Database service wrapper.++#[cfg(test)]+pub use MockSeedDb as Db;+#[cfg(not(test))]+pub use SeedDb as Db;++#[allow(unused_imports)]+use mockall::automock;++/// Wrapper around the database connection pool.+pub struct SeedDb {+ /// The macrodb pool+ #[allow(unused)]+ inner: sqlx::PgPool,+}++#[cfg_attr(test, automock)]+impl SeedDb {+ /// Create a new database wrapper.+ pub fn new(inner: sqlx::PgPool) -> Self {+ Self { inner }+ }+}diff --git a/rust/cloud-storage/seed_cli/src/service/mod.rs b/rust/cloud-storage/seed_cli/src/service/mod.rsnew file mode 100644index 0000000000..c2d45c5b72--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/service/mod.rs@@ -0,0 +1,4 @@+//! Service wrappers for external dependencies.++pub mod auth;+pub mod db;