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): create channel (#1478)
Will Hutchinson40302812f05d
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 82ddfc959d..bdd334c219 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -2346,6 +2346,27 @@ dependencies = ["syn 2.0.98",]+[[package]]+name = "csv"+version = "1.4.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "52cd9d68cf7efc6ddfaaee42e7288d3a99d613d4b50f76ce9827ae0c6e14f938"+dependencies = [+ "csv-core",+ "itoa",+ "ryu",+ "serde_core",+]++[[package]]+name = "csv-core"+version = "0.1.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "704a3c26996a80471189265814dbc2c257598b96b8a7feae2d31ace646bb9782"+dependencies = [+ "memchr",+]+[[package]]name = "darling"version = "0.20.10"@@ -7941,12 +7962,15 @@ version = "0.1.0"dependencies = ["anyhow","clap",+ "comms_db_client",+ "csv","fusionauth","macro_entrypoint","macro_env","macro_env_var","macro_user_id","mockall",+ "model","reqwest","serde","serde_json",@@ -7954,6 +7978,7 @@ dependencies = ["tempfile","tokio","tracing",+ "uuid",][[package]]diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex bd4fff2559..f18cd6d591 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -143,6 +143,7 @@ base64 = "0.22.1"cached = { version = "0.54.0", features = ["async_tokio_rt_multi_thread"] }chrono = { version = "0.4.39", features = ["serde"] }clap = { version = "4.5.20", features = ["derive"] }+csv = "1"cloudfront_sign = "0.3.0"cookie = "0.18.1"dashmap = "6.1.0"diff --git a/rust/cloud-storage/seed_cli/Cargo.toml b/rust/cloud-storage/seed_cli/Cargo.tomlindex a7fca85cd6..ae8f7778ad 100644--- a/rust/cloud-storage/seed_cli/Cargo.toml+++ b/rust/cloud-storage/seed_cli/Cargo.toml@@ -19,6 +19,10 @@ sqlx = { workspace = true }macro_user_id = { path = "../macro_user_id" }fusionauth = { path = "../fusionauth" }mockall = { workspace = true }+comms_db_client = { path = "../comms_db_client" }+model = { path = "../model" }+csv = { workspace = true }+uuid = { workspace = true }[dev-dependencies]tempfile = "3"diff --git a/rust/cloud-storage/seed_cli/src/entity/channel/mod.rs b/rust/cloud-storage/seed_cli/src/entity/channel/mod.rsnew file mode 100644index 0000000000..607bec2a1e--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/entity/channel/mod.rs@@ -0,0 +1,192 @@+//! Channel entity commands for seeding channel data.++#[cfg(test)]+mod test;++use std::path::Path;++use anyhow::Context;+use clap::{Args, Subcommand, ValueEnum};+use comms_db_client::channels::create_channel::CreateChannelOptions;+use model::comms::ChannelType;+use serde::Deserialize;++use crate::config::SeedCliContext;++/// Arguments for the `channel` entity subcommand.+#[derive(Debug, Args)]+pub struct ChannelArgs {+ /// The action to perform on channels+ #[command(subcommand)]+ pub command: ChannelCommand,+}++/// Available commands for the channel entity.+#[derive(Debug, Subcommand)]+pub enum ChannelCommand {+ /// Create a single channel+ Create(CreateArgs),+ /// Bulk create multiple channels+ BulkCreate(BulkCreateArgs),+}++/// CLI-friendly channel type enum with kebab-case values.+#[derive(Debug, Clone, ValueEnum)]+pub enum CliChannelType {+ /// Public channel+ Public,+ /// Organization channel+ Organization,+ /// Private channel+ Private,+ /// Direct message channel+ DirectMessage,+}++impl From<CliChannelType> for ChannelType {+ fn from(value: CliChannelType) -> Self {+ match value {+ CliChannelType::Public => ChannelType::Public,+ CliChannelType::Organization => ChannelType::Organization,+ CliChannelType::Private => ChannelType::Private,+ CliChannelType::DirectMessage => ChannelType::DirectMessage,+ }+ }+}++/// Arguments for creating a single channel.+#[derive(Debug, Args)]+pub struct CreateArgs {+ /// The name of the channel (optional)+ #[arg(long)]+ pub channel_name: Option<String>,+ /// The user ID of the channel owner+ #[arg(long)]+ pub channel_owner: String,+ /// The type of channel to create+ #[arg(long)]+ pub channel_type: CliChannelType,+ /// Comma-delimited list of member user IDs+ #[arg(long, value_delimiter = ',')]+ pub channel_members: Vec<String>,+ /// Organization ID (optional)+ #[arg(long)]+ pub org_id: Option<i64>,+}++/// Arguments for bulk creating channels.+#[derive(Debug, Args)]+pub struct BulkCreateArgs {+ /// Path to the CSV file containing channels to create+ #[arg(long)]+ pub file_path: String,+}++/// A row in the bulk-create CSV file.+#[derive(Debug, Deserialize)]+struct CsvChannelRow {+ /// Channel name (optional)+ name: Option<String>,+ /// User ID of the channel owner+ owner_id: String,+ /// Channel type+ channel_type: ChannelType,+ /// Organization ID (optional)+ org_id: Option<i64>,+ /// Semicolon-separated list of participant user IDs+ #[serde(default, deserialize_with = "deserialize_semicolon_list")]+ participants: Vec<String>,+}++fn deserialize_semicolon_list<'de, D>(deserializer: D) -> Result<Vec<String>, D::Error>+where+ D: serde::Deserializer<'de>,+{+ let s = String::deserialize(deserializer)?;+ if s.is_empty() {+ return Ok(Vec::new());+ }+ Ok(s.split(';').map(|s| s.trim().to_string()).collect())+}++impl ChannelArgs {+ /// Execute the channel command.+ pub async fn execute(self, ctx: SeedCliContext) -> anyhow::Result<()> {+ match self.command {+ ChannelCommand::Create(args) => create(args, ctx).await,+ ChannelCommand::BulkCreate(args) => bulk_create(args, ctx).await,+ }+ }+}++#[tracing::instrument(skip(ctx), err)]+async fn create(args: CreateArgs, ctx: SeedCliContext) -> anyhow::Result<()> {+ tracing::info!("creating channel");++ let options = CreateChannelOptions {+ name: args.channel_name,+ owner_id: args.channel_owner,+ channel_type: args.channel_type.into(),+ org_id: args.org_id,+ participants: args.channel_members,+ };++ let channel_id = ctx.db.create_channel(options).await?;+ println!("Created channel with id {channel_id}");++ Ok(())+}++#[tracing::instrument(skip(ctx), err)]+async fn bulk_create(args: BulkCreateArgs, ctx: SeedCliContext) -> anyhow::Result<()> {+ tracing::info!("bulk creating channels");++ let content = std::fs::read_to_string(Path::new(&args.file_path))+ .with_context(|| format!("failed to read csv file: {}", args.file_path))?;++ let mut reader = csv::Reader::from_reader(content.as_bytes());+ let rows: Vec<CsvChannelRow> = reader+ .deserialize()+ .collect::<Result<Vec<_>, _>>()+ .context("failed to parse csv")?;++ if rows.is_empty() {+ anyhow::bail!("no channels found in csv file");+ }++ println!("Found {} channels to create", rows.len());++ let mut created = 0;+ let mut failed = 0;++ for row in rows {+ let channel_label = row+ .name+ .as_deref()+ .map_or_else(|| format!("{:?}", row.channel_type), str::to_string);++ let options = CreateChannelOptions {+ name: row.name,+ owner_id: row.owner_id,+ channel_type: row.channel_type,+ org_id: row.org_id,+ participants: row.participants,+ };++ match ctx.db.create_channel(options).await {+ Ok(channel_id) => {+ println!("Created channel {channel_label} with id {channel_id}");+ created += 1;+ }+ Err(e) => {+ tracing::error!(error=?e, channel = channel_label, "failed to create channel");+ println!("Failed to create channel {channel_label}: {e}");+ failed += 1;+ }+ }+ }++ println!("\nBulk create complete: {created} created, {failed} failed");++ Ok(())+}diff --git a/rust/cloud-storage/seed_cli/src/entity/channel/test.rs b/rust/cloud-storage/seed_cli/src/entity/channel/test.rsnew file mode 100644index 0000000000..09a6c9d4c5--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/entity/channel/test.rs@@ -0,0 +1,383 @@+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_channel_create_minimal() {+ let cli = Cli::try_parse_from([+ "seed_cli",+ "channel",+ "create",+ "--channel-owner",+ "macro|[email protected]",+ "--channel-type",+ "public",+ ])+ .unwrap();++ match cli.command {+ crate::entity::EntityCommand::Channel(args) => match args.command {+ ChannelCommand::Create(create) => {+ assert_eq!(create.channel_owner, "macro|[email protected]");+ assert!(matches!(create.channel_type, CliChannelType::Public));+ assert!(create.channel_name.is_none());+ assert!(create.channel_members.is_empty());+ assert!(create.org_id.is_none());+ }+ other => panic!("expected Create, got {other:?}"),+ },+ other => panic!("expected Channel, got {other:?}"),+ }+}++#[test]+fn parse_channel_create_full() {+ let cli = Cli::try_parse_from([+ "seed_cli",+ "channel",+ "create",+ "--channel-name",+ "general",+ "--channel-owner",+ "macro|[email protected]",+ "--channel-type",+ "organization",+ "--channel-members",+ "macro|[email protected],macro|[email protected]",+ "--org-id",+ "42",+ ])+ .unwrap();++ match cli.command {+ crate::entity::EntityCommand::Channel(args) => match args.command {+ ChannelCommand::Create(create) => {+ assert_eq!(create.channel_name.as_deref(), Some("general"));+ assert_eq!(create.channel_owner, "macro|[email protected]");+ assert!(matches!(create.channel_type, CliChannelType::Organization));+ assert_eq!(+ create.channel_members,+ vec!["macro|[email protected]", "macro|[email protected]"]+ );+ assert_eq!(create.org_id, Some(42));+ }+ other => panic!("expected Create, got {other:?}"),+ },+ other => panic!("expected Channel, got {other:?}"),+ }+}++#[test]+fn parse_channel_create_direct_message_type() {+ let cli = Cli::try_parse_from([+ "seed_cli",+ "channel",+ "create",+ "--channel-owner",+ "macro|[email protected]",+ "--channel-type",+ "direct-message",+ ])+ .unwrap();++ match cli.command {+ crate::entity::EntityCommand::Channel(args) => match args.command {+ ChannelCommand::Create(create) => {+ assert!(matches!(create.channel_type, CliChannelType::DirectMessage));+ }+ other => panic!("expected Create, got {other:?}"),+ },+ other => panic!("expected Channel, got {other:?}"),+ }+}++#[test]+fn parse_channel_create_missing_owner_fails() {+ let result = Cli::try_parse_from(["seed_cli", "channel", "create", "--channel-type", "public"]);+ assert!(result.is_err());+}++#[test]+fn parse_channel_create_missing_type_fails() {+ let result = Cli::try_parse_from([+ "seed_cli",+ "channel",+ "create",+ "--channel-owner",+ "macro|[email protected]",+ ]);+ assert!(result.is_err());+}++#[test]+fn parse_channel_create_invalid_type_fails() {+ let result = Cli::try_parse_from([+ "seed_cli",+ "channel",+ "create",+ "--channel-owner",+ "macro|[email protected]",+ "--channel-type",+ "bogus",+ ]);+ assert!(result.is_err());+}++#[test]+fn parse_channel_bulk_create() {+ let cli = Cli::try_parse_from([+ "seed_cli",+ "channel",+ "bulk-create",+ "--file-path",+ "test.csv",+ ])+ .unwrap();++ match cli.command {+ crate::entity::EntityCommand::Channel(args) => match args.command {+ ChannelCommand::BulkCreate(bulk) => {+ assert_eq!(bulk.file_path, "test.csv");+ }+ other => panic!("expected BulkCreate, got {other:?}"),+ },+ other => panic!("expected Channel, got {other:?}"),+ }+}++// ── Helpers ────────────────────────────────────────────────++fn mock_ctx(db: Db) -> SeedCliContext {+ SeedCliContext {+ db,+ fusionauth_client: Auth::default(),+ }+}++fn write_temp_csv(content: &str) -> NamedTempFile {+ let mut file = NamedTempFile::new().unwrap();+ file.write_all(content.as_bytes()).unwrap();+ file.flush().unwrap();+ file+}++// ── Integration tests (single create) ─────────────────────++#[tokio::test]+async fn create_channel_success() {+ let mut mock_db = Db::default();+ mock_db+ .expect_create_channel()+ .times(1)+ .withf(|opts| {+ opts.name.as_deref() == Some("general")+ && opts.owner_id == "macro|[email protected]"+ && opts.channel_type == ChannelType::Public+ })+ .returning(|_| Ok(uuid::Uuid::nil()));++ let args = ChannelArgs {+ command: ChannelCommand::Create(CreateArgs {+ channel_name: Some("general".to_string()),+ channel_owner: "macro|[email protected]".to_string(),+ channel_type: CliChannelType::Public,+ channel_members: vec!["macro|[email protected]".to_string()],+ org_id: None,+ }),+ };++ let result = args.execute(mock_ctx(mock_db)).await;+ assert!(result.is_ok());+}++#[tokio::test]+async fn create_channel_without_name() {+ let mut mock_db = Db::default();+ mock_db+ .expect_create_channel()+ .times(1)+ .withf(|opts| opts.name.is_none() && opts.channel_type == ChannelType::DirectMessage)+ .returning(|_| Ok(uuid::Uuid::nil()));++ let args = ChannelArgs {+ command: ChannelCommand::Create(CreateArgs {+ channel_name: None,+ channel_owner: "macro|[email protected]".to_string(),+ channel_type: CliChannelType::DirectMessage,+ channel_members: vec!["macro|[email protected]".to_string()],+ org_id: None,+ }),+ };++ let result = args.execute(mock_ctx(mock_db)).await;+ assert!(result.is_ok());+}++#[tokio::test]+async fn create_channel_db_failure_propagates_error() {+ let mut mock_db = Db::default();+ mock_db+ .expect_create_channel()+ .times(1)+ .returning(|_| Err(anyhow::anyhow!("db connection failed")));++ let args = ChannelArgs {+ command: ChannelCommand::Create(CreateArgs {+ channel_name: Some("general".to_string()),+ channel_owner: "macro|[email protected]".to_string(),+ channel_type: CliChannelType::Public,+ channel_members: vec![],+ org_id: None,+ }),+ };++ let result = args.execute(mock_ctx(mock_db)).await;+ let err = result.unwrap_err();+ assert!(err.to_string().contains("db connection failed"));+}++// ── Bulk CSV tests ────────────────────────────────────────++#[tokio::test]+async fn bulk_create_creates_all_channels() {+ let csv = "\+name,owner_id,channel_type,org_id,participants+,macro|[email protected],direct_message,,macro|[email protected]+";+ let file = write_temp_csv(csv);++ let mut mock_db = Db::default();+ mock_db+ .expect_create_channel()+ .times(2)+ .returning(|_| Ok(uuid::Uuid::nil()));++ let args = ChannelArgs {+ command: ChannelCommand::BulkCreate(BulkCreateArgs {+ file_path: file.path().to_str().unwrap().to_string(),+ }),+ };++ let result = args.execute(mock_ctx(mock_db)).await;+ assert!(result.is_ok());+}++#[tokio::test]+async fn bulk_create_with_optional_fields() {+ let csv = "\+name,owner_id,channel_type,org_id,participants+team-chat,macro|[email protected],organization,42,macro|[email protected]+";+ let file = write_temp_csv(csv);++ let mut mock_db = Db::default();+ mock_db+ .expect_create_channel()+ .times(1)+ .withf(|opts| {+ opts.name.as_deref() == Some("team-chat")+ && opts.channel_type == ChannelType::Organization+ && opts.org_id == Some(42)+ && opts.participants == vec!["macro|[email protected]"]+ })+ .returning(|_| Ok(uuid::Uuid::nil()));++ let args = ChannelArgs {+ command: ChannelCommand::BulkCreate(BulkCreateArgs {+ file_path: file.path().to_str().unwrap().to_string(),+ }),+ };++ let result = args.execute(mock_ctx(mock_db)).await;+ assert!(result.is_ok());+}++#[tokio::test]+async fn bulk_create_empty_file_fails() {+ let csv = "name,owner_id,channel_type,org_id,participants\n";+ let file = write_temp_csv(csv);++ let mock_db = Db::default();++ let args = ChannelArgs {+ command: ChannelCommand::BulkCreate(BulkCreateArgs {+ file_path: file.path().to_str().unwrap().to_string(),+ }),+ };++ let result = args.execute(mock_ctx(mock_db)).await;+ let err = result.unwrap_err();+ assert!(err.to_string().contains("no channels found"));+}++#[tokio::test]+async fn bulk_create_missing_file_fails() {+ let mock_db = Db::default();++ let args = ChannelArgs {+ command: ChannelCommand::BulkCreate(BulkCreateArgs {+ file_path: "/nonexistent/path.csv".to_string(),+ }),+ };++ let result = args.execute(mock_ctx(mock_db)).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 csv = "\+name,owner_id,channel_type,org_id,participants+good-1,macro|[email protected],public,,+bad,macro|[email protected],public,,+good-2,macro|[email protected],private,,+";+ let file = write_temp_csv(csv);++ let mut mock_db = Db::default();+ mock_db.expect_create_channel().times(3).returning(|opts| {+ if opts.owner_id == "macro|[email protected]" {+ Err(anyhow::anyhow!("db error"))+ } else {+ Ok(uuid::Uuid::nil())+ }+ });++ let args = ChannelArgs {+ command: ChannelCommand::BulkCreate(BulkCreateArgs {+ file_path: file.path().to_str().unwrap().to_string(),+ }),+ };++ let result = args.execute(mock_ctx(mock_db)).await;+ assert!(result.is_ok());+}++#[tokio::test]+async fn bulk_create_invalid_csv_fails() {+ let csv = "not,a,valid,header,set\nfoo,bar,baz,qux,quux\n";+ let file = write_temp_csv(csv);++ let mock_db = Db::default();++ let args = ChannelArgs {+ command: ChannelCommand::BulkCreate(BulkCreateArgs {+ file_path: file.path().to_str().unwrap().to_string(),+ }),+ };++ let result = args.execute(mock_ctx(mock_db)).await;+ assert!(result.is_err());+}diff --git a/rust/cloud-storage/seed_cli/src/entity/mod.rs b/rust/cloud-storage/seed_cli/src/entity/mod.rsindex 7644df0053..ae8742bb36 100644--- a/rust/cloud-storage/seed_cli/src/entity/mod.rs+++ b/rust/cloud-storage/seed_cli/src/entity/mod.rs@@ -1,5 +1,6 @@//! Entity module containing all seed CLI entity subcommands.+pub mod channel;pub mod user;use clap::Subcommand;@@ -11,6 +12,8 @@ use crate::config::SeedCliContext;pub enum EntityCommand {/// Manage user seed dataUser(user::UserArgs),+ /// Manage channel seed data+ Channel(channel::ChannelArgs),}impl EntityCommand {@@ -18,6 +21,7 @@ impl EntityCommand {pub async fn execute(self, ctx: SeedCliContext) -> anyhow::Result<()> {match self {EntityCommand::User(args) => args.execute(ctx).await,+ EntityCommand::Channel(args) => args.execute(ctx).await,}}}diff --git a/rust/cloud-storage/seed_cli/src/entity/user/test.rs b/rust/cloud-storage/seed_cli/src/entity/user/test.rsindex 8ee727a6dc..e0993c22a6 100644--- a/rust/cloud-storage/seed_cli/src/entity/user/test.rs+++ b/rust/cloud-storage/seed_cli/src/entity/user/test.rs@@ -22,6 +22,7 @@ fn parse_user_create() {}other => panic!("expected Create, got {other:?}"),},+ other => panic!("expected User, got {other:?}"),}}@@ -37,6 +38,7 @@ fn parse_user_bulk_create() {}other => panic!("expected BulkCreate, got {other:?}"),},+ other => panic!("expected User, got {other:?}"),}}diff --git a/rust/cloud-storage/seed_cli/src/service/db/mod.rs b/rust/cloud-storage/seed_cli/src/service/db/mod.rsindex baee5f2c2a..d7bfea576c 100644--- a/rust/cloud-storage/seed_cli/src/service/db/mod.rs+++ b/rust/cloud-storage/seed_cli/src/service/db/mod.rs@@ -8,10 +8,11 @@ pub use SeedDb as Db;#[allow(unused_imports)]use mockall::automock;+use comms_db_client::channels::create_channel::CreateChannelOptions;+/// Wrapper around the database connection pool.pub struct SeedDb {/// The macrodb pool- #[allow(unused)]inner: sqlx::PgPool,}@@ -21,4 +22,15 @@ impl SeedDb {pub fn new(inner: sqlx::PgPool) -> Self {Self { inner }}++ /// Create a channel in the database.+ #[tracing::instrument(skip(self), err)]+ pub async fn create_channel(+ &self,+ options: CreateChannelOptions,+ ) -> anyhow::Result<uuid::Uuid> {+ let id =+ comms_db_client::channels::create_channel::create_channel(&self.inner, options).await?;+ Ok(id)+ }}