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): channel message seed cli (#1480)
Will Hutchinson934e79f906ed
diff --git a/rust/cloud-storage/seed_cli/src/entity/channel_message/mod.rs b/rust/cloud-storage/seed_cli/src/entity/channel_message/mod.rsnew file mode 100644index 0000000000..5ec431edb0--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/entity/channel_message/mod.rs@@ -0,0 +1,146 @@+//! Channel message entity commands for seeding message data.++#[cfg(test)]+mod test;++use std::path::Path;++use anyhow::Context;+use clap::{Args, Subcommand};+use comms_db_client::messages::create_message::CreateMessageOptions;+use serde::Deserialize;+use uuid::Uuid;++use crate::config::SeedCliContext;++/// Arguments for the `channel-message` entity subcommand.+#[derive(Debug, Args)]+pub struct ChannelMessageArgs {+ /// The action to perform on channel messages+ #[command(subcommand)]+ pub command: ChannelMessageCommand,+}++/// Available commands for the channel message entity.+#[derive(Debug, Subcommand)]+pub enum ChannelMessageCommand {+ /// Create a single channel message+ Create(CreateArgs),+ /// Bulk create multiple channel messages+ BulkCreate(BulkCreateArgs),+}++/// Arguments for creating a single channel message.+#[derive(Debug, Args)]+pub struct CreateArgs {+ /// The channel ID to post the message to+ #[arg(long)]+ pub channel_id: Uuid,+ /// The user ID of the message sender+ #[arg(long)]+ pub sender_id: String,+ /// The message content+ #[arg(long)]+ pub content: String,+ /// Optional thread ID if this is a reply+ #[arg(long)]+ pub thread_id: Option<Uuid>,+}++/// Arguments for bulk creating channel messages.+#[derive(Debug, Args)]+pub struct BulkCreateArgs {+ /// Path to the CSV file containing messages to create+ #[arg(long)]+ pub file_path: String,+}++/// A row in the bulk-create CSV file.+#[derive(Debug, Deserialize)]+struct CsvMessageRow {+ /// The channel ID to post the message to+ channel_id: Uuid,+ /// The user ID of the message sender+ sender_id: String,+ /// The message content+ content: String,+ /// Optional thread ID if this is a reply+ thread_id: Option<Uuid>,+}++impl ChannelMessageArgs {+ /// Execute the channel message command.+ pub async fn execute(self, ctx: SeedCliContext) -> anyhow::Result<()> {+ match self.command {+ ChannelMessageCommand::Create(args) => create(args, ctx).await,+ ChannelMessageCommand::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 message");++ let options = CreateMessageOptions {+ channel_id: args.channel_id,+ sender_id: args.sender_id,+ content: args.content,+ thread_id: args.thread_id,+ };++ let message_id = ctx.db.create_message(options).await?;+ println!("Created message with id {message_id}");++ Ok(())+}++#[tracing::instrument(skip(ctx), err)]+async fn bulk_create(args: BulkCreateArgs, ctx: SeedCliContext) -> anyhow::Result<()> {+ tracing::info!("bulk creating channel messages");++ 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<CsvMessageRow> = reader+ .deserialize()+ .collect::<Result<Vec<_>, _>>()+ .context("failed to parse csv")?;++ if rows.is_empty() {+ anyhow::bail!("no messages found in csv file");+ }++ println!("Found {} messages to create", rows.len());++ let mut created = 0;+ let mut failed = 0;++ for row in rows {+ let message_label = format!("channel={} sender={}", row.channel_id, row.sender_id);++ let options = CreateMessageOptions {+ channel_id: row.channel_id,+ sender_id: row.sender_id,+ content: row.content,+ thread_id: row.thread_id,+ };++ match ctx.db.create_message(options).await {+ Ok(message_id) => {+ println!("Created message {message_label} with id {message_id}");+ created += 1;+ }+ Err(e) => {+ tracing::error!(error=?e, message = message_label, "failed to create message");+ println!("Failed to create message {message_label}: {e}");+ failed += 1;+ }+ }+ }++ println!("\nBulk create complete: {created} created, {failed} failed");++ Ok(())+}diff --git a/rust/cloud-storage/seed_cli/src/entity/channel_message/test.rs b/rust/cloud-storage/seed_cli/src/entity/channel_message/test.rsnew file mode 100644index 0000000000..c59b09a112--- /dev/null+++ b/rust/cloud-storage/seed_cli/src/entity/channel_message/test.rs@@ -0,0 +1,393 @@+use std::io::Write;++use clap::Parser;+use tempfile::NamedTempFile;+use uuid::Uuid;++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_message_create_minimal() {+ let channel_id = Uuid::nil().to_string();+ let cli = Cli::try_parse_from([+ "seed_cli",+ "channel-message",+ "create",+ "--channel-id",+ &channel_id,+ "--sender-id",+ "macro|[email protected]",+ "--content",+ "Hello, world!",+ ])+ .unwrap();++ match cli.command {+ crate::entity::EntityCommand::ChannelMessage(args) => match args.command {+ ChannelMessageCommand::Create(create) => {+ assert_eq!(create.channel_id, Uuid::nil());+ assert_eq!(create.sender_id, "macro|[email protected]");+ assert_eq!(create.content, "Hello, world!");+ assert!(create.thread_id.is_none());+ }+ other => panic!("expected Create, got {other:?}"),+ },+ other => panic!("expected ChannelMessage, got {other:?}"),+ }+}++#[test]+fn parse_channel_message_create_with_thread_id() {+ let channel_id = Uuid::nil().to_string();+ let thread_id = Uuid::from_u128(1).to_string();+ let cli = Cli::try_parse_from([+ "seed_cli",+ "channel-message",+ "create",+ "--channel-id",+ &channel_id,+ "--sender-id",+ "macro|[email protected]",+ "--content",+ "This is a reply",+ "--thread-id",+ &thread_id,+ ])+ .unwrap();++ match cli.command {+ crate::entity::EntityCommand::ChannelMessage(args) => match args.command {+ ChannelMessageCommand::Create(create) => {+ assert_eq!(create.channel_id, Uuid::nil());+ assert_eq!(create.sender_id, "macro|[email protected]");+ assert_eq!(create.content, "This is a reply");+ assert_eq!(create.thread_id, Some(Uuid::from_u128(1)));+ }+ other => panic!("expected Create, got {other:?}"),+ },+ other => panic!("expected ChannelMessage, got {other:?}"),+ }+}++#[test]+fn parse_channel_message_create_missing_channel_id_fails() {+ let result = Cli::try_parse_from([+ "seed_cli",+ "channel-message",+ "create",+ "--sender-id",+ "macro|[email protected]",+ "--content",+ "Hello",+ ]);+ assert!(result.is_err());+}++#[test]+fn parse_channel_message_create_missing_sender_id_fails() {+ let channel_id = Uuid::nil().to_string();+ let result = Cli::try_parse_from([+ "seed_cli",+ "channel-message",+ "create",+ "--channel-id",+ &channel_id,+ "--content",+ "Hello",+ ]);+ assert!(result.is_err());+}++#[test]+fn parse_channel_message_create_missing_content_fails() {+ let channel_id = Uuid::nil().to_string();+ let result = Cli::try_parse_from([+ "seed_cli",+ "channel-message",+ "create",+ "--channel-id",+ &channel_id,+ "--sender-id",+ "macro|[email protected]",+ ]);+ assert!(result.is_err());+}++#[test]+fn parse_channel_message_create_invalid_channel_id_fails() {+ let result = Cli::try_parse_from([+ "seed_cli",+ "channel-message",+ "create",+ "--channel-id",+ "not-a-uuid",+ "--sender-id",+ "macro|[email protected]",+ "--content",+ "Hello",+ ]);+ assert!(result.is_err());+}++#[test]+fn parse_channel_message_bulk_create() {+ let cli = Cli::try_parse_from([+ "seed_cli",+ "channel-message",+ "bulk-create",+ "--file-path",+ "messages.csv",+ ])+ .unwrap();++ match cli.command {+ crate::entity::EntityCommand::ChannelMessage(args) => match args.command {+ ChannelMessageCommand::BulkCreate(bulk) => {+ assert_eq!(bulk.file_path, "messages.csv");+ }+ other => panic!("expected BulkCreate, got {other:?}"),+ },+ other => panic!("expected ChannelMessage, 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_message_success() {+ let channel_id = Uuid::nil();++ let mut mock_db = Db::default();+ mock_db+ .expect_create_message()+ .times(1)+ .withf(move |opts| {+ opts.channel_id == channel_id+ && opts.sender_id == "macro|[email protected]"+ && opts.content == "Hello, world!"+ && opts.thread_id.is_none()+ })+ .returning(|_| Ok(Uuid::nil()));++ let args = ChannelMessageArgs {+ command: ChannelMessageCommand::Create(CreateArgs {+ channel_id,+ sender_id: "macro|[email protected]".to_string(),+ content: "Hello, world!".to_string(),+ thread_id: None,+ }),+ };++ let result = args.execute(mock_ctx(mock_db)).await;+ assert!(result.is_ok());+}++#[tokio::test]+async fn create_message_with_thread_id() {+ let channel_id = Uuid::nil();+ let thread_id = Uuid::from_u128(1);++ let mut mock_db = Db::default();+ mock_db+ .expect_create_message()+ .times(1)+ .withf(move |opts| {+ opts.channel_id == channel_id+ && opts.sender_id == "macro|[email protected]"+ && opts.content == "This is a reply"+ && opts.thread_id == Some(thread_id)+ })+ .returning(|_| Ok(Uuid::nil()));++ let args = ChannelMessageArgs {+ command: ChannelMessageCommand::Create(CreateArgs {+ channel_id,+ sender_id: "macro|[email protected]".to_string(),+ content: "This is a reply".to_string(),+ thread_id: Some(thread_id),+ }),+ };++ let result = args.execute(mock_ctx(mock_db)).await;+ assert!(result.is_ok());+}++#[tokio::test]+async fn create_message_db_failure_propagates_error() {+ let mut mock_db = Db::default();+ mock_db+ .expect_create_message()+ .times(1)+ .returning(|_| Err(anyhow::anyhow!("db connection failed")));++ let args = ChannelMessageArgs {+ command: ChannelMessageCommand::Create(CreateArgs {+ channel_id: Uuid::nil(),+ sender_id: "macro|[email protected]".to_string(),+ content: "Hello".to_string(),+ thread_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_messages() {+ let channel_id = Uuid::nil();+ let csv = format!(+ "channel_id,sender_id,content,thread_id\n\+ {channel_id},macro|[email protected],Hello world,\n\+ {channel_id},macro|[email protected],Hi there,\n"+ );+ let file = write_temp_csv(&csv);++ let mut mock_db = Db::default();+ mock_db+ .expect_create_message()+ .times(2)+ .returning(|_| Ok(Uuid::nil()));++ let args = ChannelMessageArgs {+ command: ChannelMessageCommand::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_thread_id() {+ let channel_id = Uuid::nil();+ let thread_id = Uuid::from_u128(1);+ let csv = format!(+ "channel_id,sender_id,content,thread_id\n\+ {channel_id},macro|[email protected],Thread reply,{thread_id}\n"+ );+ let file = write_temp_csv(&csv);++ let mut mock_db = Db::default();+ mock_db+ .expect_create_message()+ .times(1)+ .withf(move |opts| opts.thread_id == Some(thread_id) && opts.content == "Thread reply")+ .returning(|_| Ok(Uuid::nil()));++ let args = ChannelMessageArgs {+ command: ChannelMessageCommand::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 = "channel_id,sender_id,content,thread_id\n";+ let file = write_temp_csv(csv);++ let mock_db = Db::default();++ let args = ChannelMessageArgs {+ command: ChannelMessageCommand::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 messages found"));+}++#[tokio::test]+async fn bulk_create_missing_file_fails() {+ let mock_db = Db::default();++ let args = ChannelMessageArgs {+ command: ChannelMessageCommand::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 channel_id = Uuid::nil();+ let csv = format!(+ "channel_id,sender_id,content,thread_id\n\+ {channel_id},macro|[email protected],Good message 1,\n\+ {channel_id},macro|[email protected],Bad message,\n\+ {channel_id},macro|[email protected],Good message 2,\n"+ );+ let file = write_temp_csv(&csv);++ let mut mock_db = Db::default();+ mock_db.expect_create_message().times(3).returning(|opts| {+ if opts.sender_id == "macro|[email protected]" {+ Err(anyhow::anyhow!("db error"))+ } else {+ Ok(Uuid::nil())+ }+ });++ let args = ChannelMessageArgs {+ command: ChannelMessageCommand::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\nfoo,bar,baz,qux\n";+ let file = write_temp_csv(csv);++ let mock_db = Db::default();++ let args = ChannelMessageArgs {+ command: ChannelMessageCommand::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 ae8742bb36..7a8d37077d 100644--- a/rust/cloud-storage/seed_cli/src/entity/mod.rs+++ b/rust/cloud-storage/seed_cli/src/entity/mod.rs@@ -1,6 +1,7 @@//! Entity module containing all seed CLI entity subcommands.pub mod channel;+pub mod channel_message;pub mod user;use clap::Subcommand;@@ -14,6 +15,8 @@ pub enum EntityCommand {User(user::UserArgs),/// Manage channel seed dataChannel(channel::ChannelArgs),+ /// Manage channel message seed data+ ChannelMessage(channel_message::ChannelMessageArgs),}impl EntityCommand {@@ -22,6 +25,7 @@ impl EntityCommand {match self {EntityCommand::User(args) => args.execute(ctx).await,EntityCommand::Channel(args) => args.execute(ctx).await,+ EntityCommand::ChannelMessage(args) => args.execute(ctx).await,}}}diff --git a/rust/cloud-storage/seed_cli/src/service/db/mod.rs b/rust/cloud-storage/seed_cli/src/service/db/mod.rsindex d7bfea576c..1699ec2bf9 100644--- a/rust/cloud-storage/seed_cli/src/service/db/mod.rs+++ b/rust/cloud-storage/seed_cli/src/service/db/mod.rs@@ -9,6 +9,7 @@ pub use SeedDb as Db;use mockall::automock;use comms_db_client::channels::create_channel::CreateChannelOptions;+use comms_db_client::messages::create_message::CreateMessageOptions;/// Wrapper around the database connection pool.pub struct SeedDb {@@ -33,4 +34,15 @@ impl SeedDb {comms_db_client::channels::create_channel::create_channel(&self.inner, options).await?;Ok(id)}++ /// Create a message in the database.+ #[tracing::instrument(skip(self), err)]+ pub async fn create_message(+ &self,+ options: CreateMessageOptions,+ ) -> anyhow::Result<uuid::Uuid> {+ let message =+ comms_db_client::messages::create_message::create_message(&self.inner, options).await?;+ Ok(message.id)+ }}