Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(seed): seed cli documents (#1561)

Will Hutchinsonddd0f4fab360
diff --git a/infra/stacks/fusionauth-instance/justfile b/infra/stacks/fusionauth-instance/justfile
index 554a30a2b5..9a07c50f38 100644
--- a/infra/stacks/fusionauth-instance/justfile
+++ b/infra/stacks/fusionauth-instance/justfile
@@ -68,8 +68,13 @@ insert_local_fusionauth_variables:
API_KEY="bf69486b-4733-4954-a44e-2e1b5f2c8a91"
APPLICATION_ID=$(pulumi stack output macroApplicationClientId -s local)
TENANT_ID=$(pulumi stack output defaultTenantId -s local)
- CLIENT_SECRET=$(curl -s "http://localhost:9011/api/application/${APPLICATION_ID}" \
- -H "Authorization: ${API_KEY}" | jq -r '.application.oauthConfiguration.clientSecret')
+ CURL_RESPONSE=$(curl -s "http://localhost:9011/api/application/${APPLICATION_ID}" \
+ -H "Authorization: ${API_KEY}")
+ if [ -z "$CURL_RESPONSE" ]; then
+ echo "Local FusionAuth instance is not running"
+ exit 1
+ fi
+ CLIENT_SECRET=$(echo "$CURL_RESPONSE" | jq -r '.application.oauthConfiguration.clientSecret')
ENV_FILE="{{justfile_directory()}}/../../../.env"
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index bdc930a447..f077f3a39a 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -8060,6 +8060,7 @@ name = "seed_cli"
version = "0.1.0"
dependencies = [
"anyhow",
+ "aws-sdk-s3",
"chrono",
"clap",
"comms_db_client",
@@ -8067,6 +8068,8 @@ dependencies = [
"email_db_client",
"fusionauth",
"futures",
+ "macro_aws_config",
+ "macro_db_client",
"macro_entrypoint",
"macro_env",
"macro_env_var",
@@ -8074,6 +8077,7 @@ dependencies = [
"mockall",
"model",
"models_email",
+ "models_permissions",
"rand 0.9.0",
"reqwest",
"serde",
diff --git a/rust/cloud-storage/seed_cli/Cargo.toml b/rust/cloud-storage/seed_cli/Cargo.toml
index 0443fdc90d..6c1e8ea3ea 100644
--- a/rust/cloud-storage/seed_cli/Cargo.toml
+++ b/rust/cloud-storage/seed_cli/Cargo.toml
@@ -28,6 +28,10 @@ models_email = { path = "../models_email" }
chrono = { workspace = true }
rand = { workspace = true }
futures = { workspace = true }
+macro_db_client = { path = "../macro_db_client" }
+macro_aws_config = {path = "../macro_aws_config" }
+aws-sdk-s3 = { workspace = true }
+models_permissions = { path = "../models_permissions" }
[dev-dependencies]
tempfile = "3"
diff --git a/rust/cloud-storage/seed_cli/README.md b/rust/cloud-storage/seed_cli/README.md
new file mode 100644
index 0000000000..6dea35cbaf
--- /dev/null
+++ b/rust/cloud-storage/seed_cli/README.md
@@ -0,0 +1,10 @@
+# Seed CLI
+
+Used to populate your local environment with sample data.
+
+Please ensure you have read [RUNNING\_LOCALLY](../../../RUNNING_LOCALLY.md) and
+have your local environment setup.
+
+## Usage
+You can explore the CLI and it's usage with `just seed help`. All commands can
+be run through the `just seed` base command.
diff --git a/rust/cloud-storage/seed_cli/justfile b/rust/cloud-storage/seed_cli/justfile
index dd242c68bd..10085a51cb 100644
--- a/rust/cloud-storage/seed_cli/justfile
+++ b/rust/cloud-storage/seed_cli/justfile
@@ -6,3 +6,6 @@ get_environment:
just ../../../infra/stacks/fusionauth-instance/insert_local_fusionauth_variables
@echo "Copying env file"
cp ../../../.env ./
+
+seed *ARGS:
+ cargo r {{ ARGS }}
diff --git a/rust/cloud-storage/seed_cli/seed/documents/documents.csv b/rust/cloud-storage/seed_cli/seed/documents/documents.csv
new file mode 100644
index 0000000000..8772770a18
--- /dev/null
+++ b/rust/cloud-storage/seed_cli/seed/documents/documents.csv
@@ -0,0 +1,101 @@
+document_id,document_name,file_name,is_public
+00000000-0000-0000-0002-000000000001,Project Roadmap,pdf.pdf,false
+00000000-0000-0000-0002-000000000002,Meeting Notes,md.md,false
+00000000-0000-0000-0002-000000000003,Architecture Diagram,canvas.canvas,false
+00000000-0000-0000-0002-000000000004,Q3 Budget Report,pdf.pdf,true
+00000000-0000-0000-0002-000000000005,Sprint Retro Notes,md.md,false
+00000000-0000-0000-0002-000000000006,System Design,canvas.canvas,false
+00000000-0000-0000-0002-000000000007,Employee Handbook,pdf.pdf,true
+00000000-0000-0000-0002-000000000008,API Documentation,md.md,false
+00000000-0000-0000-0002-000000000009,Wireframe Draft,canvas.canvas,false
+00000000-0000-0000-0002-00000000000a,Sales Pitch Deck,pdf.pdf,false
+00000000-0000-0000-0002-00000000000b,Release Checklist,md.md,false
+00000000-0000-0000-0002-00000000000c,User Flow Diagram,canvas.canvas,false
+00000000-0000-0000-0002-00000000000d,Annual Report,pdf.pdf,true
+00000000-0000-0000-0002-00000000000e,Onboarding Guide,md.md,true
+00000000-0000-0000-0002-00000000000f,Network Topology,canvas.canvas,false
+00000000-0000-0000-0002-000000000010,Product Requirements,pdf.pdf,false
+00000000-0000-0000-0002-000000000011,Dev Setup Guide,md.md,false
+00000000-0000-0000-0002-000000000012,ER Diagram,canvas.canvas,false
+00000000-0000-0000-0002-000000000013,Marketing Plan,pdf.pdf,false
+00000000-0000-0000-0002-000000000014,Incident Postmortem,md.md,false
+00000000-0000-0000-0002-000000000015,Component Layout,canvas.canvas,false
+00000000-0000-0000-0002-000000000016,Security Audit,pdf.pdf,false
+00000000-0000-0000-0002-000000000017,Changelog,md.md,true
+00000000-0000-0000-0002-000000000018,Data Flow Sketch,canvas.canvas,false
+00000000-0000-0000-0002-000000000019,Contract Template,pdf.pdf,false
+00000000-0000-0000-0002-00000000001a,Team Standup Notes,md.md,false
+00000000-0000-0000-0002-00000000001b,Infrastructure Map,canvas.canvas,false
+00000000-0000-0000-0002-00000000001c,Compliance Report,pdf.pdf,true
+00000000-0000-0000-0002-00000000001d,Migration Plan,md.md,false
+00000000-0000-0000-0002-00000000001e,Sequence Diagram,canvas.canvas,false
+00000000-0000-0000-0002-00000000001f,Vendor Proposal,pdf.pdf,false
+00000000-0000-0000-0002-000000000020,Troubleshooting Guide,md.md,false
+00000000-0000-0000-0002-000000000021,Deployment Pipeline,canvas.canvas,false
+00000000-0000-0000-0002-000000000022,Board Presentation,pdf.pdf,false
+00000000-0000-0000-0002-000000000023,Feature Spec,md.md,false
+00000000-0000-0000-0002-000000000024,Brainstorm Session,canvas.canvas,false
+00000000-0000-0000-0002-000000000025,Investor Update,pdf.pdf,false
+00000000-0000-0000-0002-000000000026,Code Review Checklist,md.md,false
+00000000-0000-0000-0002-000000000027,Service Architecture,canvas.canvas,false
+00000000-0000-0000-0002-000000000028,Performance Report,pdf.pdf,false
+00000000-0000-0000-0002-000000000029,Testing Strategy,md.md,false
+00000000-0000-0000-0002-00000000002a,Page Layout,canvas.canvas,false
+00000000-0000-0000-0002-00000000002b,NDA Template,pdf.pdf,false
+00000000-0000-0000-0002-00000000002c,Decision Log,md.md,false
+00000000-0000-0000-0002-00000000002d,Mind Map,canvas.canvas,false
+00000000-0000-0000-0002-00000000002e,Tax Filing,pdf.pdf,false
+00000000-0000-0000-0002-00000000002f,Knowledge Base Entry,md.md,true
+00000000-0000-0000-0002-000000000030,Org Chart,canvas.canvas,false
+00000000-0000-0000-0002-000000000031,Training Material,pdf.pdf,true
+00000000-0000-0000-0002-000000000032,Bug Report Template,md.md,false
+00000000-0000-0000-0002-000000000033,Concept Sketch,canvas.canvas,false
+00000000-0000-0000-0002-000000000034,Legal Review,pdf.pdf,false
+00000000-0000-0000-0002-000000000035,Architecture Decision Record,md.md,false
+00000000-0000-0000-0002-000000000036,Dashboard Mockup,canvas.canvas,false
+00000000-0000-0000-0002-000000000037,SLA Agreement,pdf.pdf,false
+00000000-0000-0000-0002-000000000038,Runbook,md.md,false
+00000000-0000-0000-0002-000000000039,Workflow Diagram,canvas.canvas,false
+00000000-0000-0000-0002-00000000003a,Research Paper,pdf.pdf,false
+00000000-0000-0000-0002-00000000003b,RFC Draft,md.md,false
+00000000-0000-0000-0002-00000000003c,Sitemap,canvas.canvas,false
+00000000-0000-0000-0002-00000000003d,Expense Report,pdf.pdf,false
+00000000-0000-0000-0002-00000000003e,Project Retrospective,md.md,false
+00000000-0000-0000-0002-00000000003f,State Machine,canvas.canvas,false
+00000000-0000-0000-0002-000000000040,Insurance Policy,pdf.pdf,false
+00000000-0000-0000-0002-000000000041,Style Guide,md.md,true
+00000000-0000-0000-0002-000000000042,UI Prototype,canvas.canvas,false
+00000000-0000-0000-0002-000000000043,Partnership Agreement,pdf.pdf,false
+00000000-0000-0000-0002-000000000044,API Changelog,md.md,false
+00000000-0000-0000-0002-000000000045,Database Schema,canvas.canvas,false
+00000000-0000-0000-0002-000000000046,Quarterly Review,pdf.pdf,false
+00000000-0000-0000-0002-000000000047,Configuration Guide,md.md,false
+00000000-0000-0000-0002-000000000048,Gantt Chart,canvas.canvas,false
+00000000-0000-0000-0002-000000000049,Warranty Document,pdf.pdf,false
+00000000-0000-0000-0002-00000000004a,Deployment Notes,md.md,false
+00000000-0000-0000-0002-00000000004b,Class Diagram,canvas.canvas,false
+00000000-0000-0000-0002-00000000004c,Customer Feedback Summary,pdf.pdf,false
+00000000-0000-0000-0002-00000000004d,Contributing Guidelines,md.md,true
+00000000-0000-0000-0002-00000000004e,Login Flow,canvas.canvas,false
+00000000-0000-0000-0002-00000000004f,Brand Guidelines,pdf.pdf,false
+00000000-0000-0000-0002-000000000050,Monitoring Setup,md.md,false
+00000000-0000-0000-0002-000000000051,Payment Flow,canvas.canvas,false
+00000000-0000-0000-0002-000000000052,Privacy Policy,pdf.pdf,true
+00000000-0000-0000-0002-000000000053,Environment Variables,md.md,false
+00000000-0000-0000-0002-000000000054,Notification Flow,canvas.canvas,false
+00000000-0000-0000-0002-000000000055,Terms of Service,pdf.pdf,true
+00000000-0000-0000-0002-000000000056,Dependency Audit,md.md,false
+00000000-0000-0000-0002-000000000057,Search Architecture,canvas.canvas,false
+00000000-0000-0000-0002-000000000058,Invoice Template,pdf.pdf,false
+00000000-0000-0000-0002-000000000059,Capacity Planning,md.md,false
+00000000-0000-0000-0002-00000000005a,Auth Flow,canvas.canvas,false
+00000000-0000-0000-0002-00000000005b,Compliance Checklist,pdf.pdf,false
+00000000-0000-0000-0002-00000000005c,Load Test Results,md.md,false
+00000000-0000-0000-0002-00000000005d,Microservices Map,canvas.canvas,false
+00000000-0000-0000-0002-00000000005e,Risk Assessment,pdf.pdf,false
+00000000-0000-0000-0002-00000000005f,Disaster Recovery Plan,md.md,false
+00000000-0000-0000-0002-000000000060,CI Pipeline,canvas.canvas,false
+00000000-0000-0000-0002-000000000061,Shipping Label,pdf.pdf,false
+00000000-0000-0000-0002-000000000062,Benchmarks,md.md,false
+00000000-0000-0000-0002-000000000063,Feature Flag Matrix,canvas.canvas,false
+00000000-0000-0000-0002-000000000064,Certificate,pdf.pdf,false
diff --git a/rust/cloud-storage/seed_cli/seed/documents/files/canvas.canvas b/rust/cloud-storage/seed_cli/seed/documents/files/canvas.canvas
new file mode 100644
index 0000000000..ab01faf62a
--- /dev/null
+++ b/rust/cloud-storage/seed_cli/seed/documents/files/canvas.canvas
@@ -0,0 +1 @@
+{"nodes":[],"edges":[]}
\ No newline at end of file
diff --git a/rust/cloud-storage/seed_cli/seed/documents/files/md.md b/rust/cloud-storage/seed_cli/seed/documents/files/md.md
new file mode 100644
index 0000000000..22bca87f80
--- /dev/null
+++ b/rust/cloud-storage/seed_cli/seed/documents/files/md.md
@@ -0,0 +1 @@
+new note
diff --git a/rust/cloud-storage/seed_cli/seed/documents/files/pdf.pdf b/rust/cloud-storage/seed_cli/seed/documents/files/pdf.pdf
new file mode 100644
index 0000000000..915278c180
Binary files /dev/null and b/rust/cloud-storage/seed_cli/seed/documents/files/pdf.pdf differ
diff --git a/rust/cloud-storage/seed_cli/src/config.rs b/rust/cloud-storage/seed_cli/src/config.rs
index fe419ad16c..60f0c50bc0 100644
--- a/rust/cloud-storage/seed_cli/src/config.rs
+++ b/rust/cloud-storage/seed_cli/src/config.rs
@@ -1,6 +1,6 @@
use macro_env_var::env_var;
-use crate::service::{auth::Auth, db::Db};
+use crate::service::{auth::Auth, db::Db, s3::S3};
env_var! {
pub struct EnvVars {
@@ -18,6 +18,8 @@ env_var! {
pub FusionauthClientSecretKey,
/// Fusionauth oauth redirect uri
pub FusionauthOauthRedirectUri,
+ /// The document storage bucket
+ pub DocumentStorageBucket,
}
}
@@ -27,4 +29,6 @@ pub struct SeedCliContext {
pub db: Db,
/// Fusionauth client
pub fusionauth_client: Auth,
+ /// S3 client
+ pub s3: S3,
}
diff --git a/rust/cloud-storage/seed_cli/src/entity/channel/test.rs b/rust/cloud-storage/seed_cli/src/entity/channel/test.rs
index 1103d08f16..74b87147bf 100644
--- a/rust/cloud-storage/seed_cli/src/entity/channel/test.rs
+++ b/rust/cloud-storage/seed_cli/src/entity/channel/test.rs
@@ -7,6 +7,7 @@ use crate::Cli;
use crate::config::SeedCliContext;
use crate::service::auth::Auth;
use crate::service::db::Db;
+use crate::service::s3::S3;
use super::*;
@@ -189,6 +190,7 @@ fn mock_ctx(db: Db) -> SeedCliContext {
SeedCliContext {
db,
fusionauth_client: Auth::default(),
+ s3: S3::default(),
}
}
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.rs
index 3629e19af1..cbb99b9b91 100644
--- a/rust/cloud-storage/seed_cli/src/entity/channel_message/test.rs
+++ b/rust/cloud-storage/seed_cli/src/entity/channel_message/test.rs
@@ -8,6 +8,7 @@ use crate::Cli;
use crate::config::SeedCliContext;
use crate::service::auth::Auth;
use crate::service::db::Db;
+use crate::service::s3::S3;
use super::*;
@@ -179,6 +180,7 @@ fn mock_ctx(db: Db) -> SeedCliContext {
SeedCliContext {
db,
fusionauth_client: Auth::default(),
+ s3: S3::default(),
}
}
diff --git a/rust/cloud-storage/seed_cli/src/entity/document/mod.rs b/rust/cloud-storage/seed_cli/src/entity/document/mod.rs
new file mode 100644
index 0000000000..5c977c3225
--- /dev/null
+++ b/rust/cloud-storage/seed_cli/src/entity/document/mod.rs
@@ -0,0 +1,261 @@
+//! Document entity commands for seeding document data.
+
+use std::path::Path;
+use std::str::FromStr;
+
+use anyhow::Context;
+use clap::{Args, Subcommand};
+use macro_db_client::document::v2::create::CreateDocumentArgs;
+use macro_user_id::user_id::MacroUserIdStr;
+use model::document::FileType;
+use models_permissions::share_permission::{SharePermissionV2, access_level::AccessLevel};
+use serde::Deserialize;
+use uuid::{NoContext, Timestamp, Uuid};
+
+use crate::config::SeedCliContext;
+
+#[cfg(test)]
+mod test;
+
+/// Arguments for the `document` entity subcommand.
+#[derive(Debug, Args)]
+pub struct DocumentArgs {
+ /// The action to perform on documents
+ #[command(subcommand)]
+ pub command: DocumentCommand,
+}
+
+/// Available commands for the document entity.
+#[derive(Debug, Subcommand)]
+pub enum DocumentCommand {
+ /// Create a single document
+ Create(CreateArgs),
+ /// Seed documents from a fixed CSV file with pre-defined UUIDs
+ Seed(SeedArgs),
+}
+
+/// Arguments for creating a single user.
+#[derive(Debug, Args)]
+pub struct CreateArgs {
+ /// The owner of the document
+ #[arg(long)]
+ pub owner: String,
+ /// The path to the file you want to upload
+ #[arg(long)]
+ pub file_path: String,
+ /// Whether the document should be public or not. If enabled this will give
+ /// the document view access publicly
+ #[arg(long, default_value = "false")]
+ pub is_public: bool,
+ /// If you have a public document you need to provide the public access level
+ #[arg(long)]
+ pub public_access_level: Option<String>,
+ /// Name of the document.
+ /// Without the extension
+ #[arg(long)]
+ pub document_name: String,
+ /// Specific id to give to document
+ #[arg(long)]
+ pub id: Option<String>,
+ /// Whether to skip adding document to history
+ #[arg(long, default_value = "false")]
+ pub skip_history: bool,
+}
+
+/// Arguments for seeding documents from a fixed CSV file.
+#[derive(Debug, Args)]
+pub struct SeedArgs {
+ /// The user ID to set as document owner
+ #[arg(long)]
+ pub user_id: String,
+}
+
+/// A row in the seed CSV file.
+#[derive(Debug, Deserialize)]
+struct CsvSeedDocumentRow {
+ /// Pre-defined document UUID.
+ document_id: Uuid,
+ /// Document name.
+ document_name: String,
+ /// File name from the seed/documents/files/ directory.
+ file_name: String,
+ /// Whether the document is public.
+ is_public: bool,
+}
+
+impl DocumentArgs {
+ /// Execute the user command.
+ pub async fn execute(self, ctx: SeedCliContext) -> anyhow::Result<()> {
+ match self.command {
+ DocumentCommand::Create(args) => create(args, ctx).await,
+ DocumentCommand::Seed(args) => seed(args, ctx).await,
+ }
+ }
+}
+
+#[tracing::instrument(skip(ctx), err)]
+async fn create(args: CreateArgs, ctx: SeedCliContext) -> anyhow::Result<()> {
+ tracing::info!("creating document");
+
+ let owner = MacroUserIdStr::parse_from_str(args.owner.leak()).context("valid owner id")?;
+
+ let generated_id;
+ let id = match args.id.as_deref() {
+ Some(id) => Some(id),
+ None => {
+ generated_id = Uuid::new_v7(Timestamp::now(NoContext)).to_string();
+ Some(generated_id.as_str())
+ }
+ };
+
+ let file_type = args
+ .file_path
+ .split('.')
+ .next_back()
+ .context("expected to have a file extension")?;
+
+ let file_type = FileType::from_str(file_type).context("valid file type")?;
+
+ // create file in db
+ let document = ctx
+ .db
+ .create_document(CreateDocumentArgs {
+ id,
+ sha: "sha",
+ document_name: &args.document_name,
+ user_id: owner.clone(),
+ file_type: Some(file_type),
+ project_id: None,
+ project_name: None,
+ share_permission: &SharePermissionV2 {
+ id: String::new(),
+ owner: owner.as_ref().to_string(),
+ is_public: args.is_public,
+ public_access_level: args
+ .public_access_level
+ .map(|s| AccessLevel::from_str(&s).unwrap()),
+ channel_share_permissions: None,
+ },
+ skip_history: args.skip_history,
+ email_attachment_id: None,
+ created_at: None,
+ is_task: false,
+ })
+ .await?;
+
+ let key = format!(
+ "{}/{}/{}.{}",
+ document.owner,
+ document.document_id,
+ document.document_version_id,
+ file_type.as_str()
+ );
+
+ ctx.s3.upload_file(&key, &args.file_path).await?;
+
+ Ok(())
+}
+
+#[tracing::instrument(skip(ctx), err)]
+async fn seed(args: SeedArgs, ctx: SeedCliContext) -> anyhow::Result<()> {
+ seed_from_file(args, ctx, Path::new("seed/documents/documents.csv")).await
+}
+
+async fn seed_from_file(args: SeedArgs, ctx: SeedCliContext, path: &Path) -> anyhow::Result<()> {
+ tracing::info!("seeding documents");
+
+ let content = std::fs::read_to_string(path)
+ .with_context(|| format!("failed to read csv file: {}", path.display()))?;
+
+ let mut reader = csv::Reader::from_reader(content.as_bytes());
+ let rows: Vec<CsvSeedDocumentRow> = reader
+ .deserialize()
+ .collect::<Result<Vec<_>, _>>()
+ .context("failed to parse csv")?;
+
+ if rows.is_empty() {
+ anyhow::bail!("no documents found in csv file");
+ }
+
+ println!("Found {} documents to seed", rows.len());
+
+ let owner = MacroUserIdStr::parse_from_str(args.user_id.leak()).context("valid owner id")?;
+
+ let mut created = 0;
+ let mut failed = 0;
+
+ for row in rows {
+ let file_path = format!("seed/documents/files/{}", row.file_name);
+ let file_type = row
+ .file_name
+ .split('.')
+ .next_back()
+ .context("expected file to have an extension")?;
+ let file_type = FileType::from_str(file_type).context("valid file type")?;
+ let doc_id = row.document_id.to_string();
+
+ let create_result = ctx
+ .db
+ .create_document(CreateDocumentArgs {
+ id: Some(&doc_id),
+ sha: "sha",
+ document_name: &row.document_name,
+ user_id: owner.clone(),
+ file_type: Some(file_type),
+ project_id: None,
+ project_name: None,
+ share_permission: &SharePermissionV2 {
+ id: String::new(),
+ owner: owner.as_ref().to_string(),
+ is_public: row.is_public,
+ public_access_level: if row.is_public {
+ Some(AccessLevel::View)
+ } else {
+ None
+ },
+ channel_share_permissions: None,
+ },
+ skip_history: true,
+ email_attachment_id: None,
+ created_at: None,
+ is_task: false,
+ })
+ .await;
+
+ match create_result {
+ Ok(document) => {
+ let key = format!(
+ "{}/{}/{}.{}",
+ document.owner,
+ document.document_id,
+ document.document_version_id,
+ file_type.as_str()
+ );
+
+ match ctx.s3.upload_file(&key, &file_path).await {
+ Ok(()) => {
+ println!("Seeded document '{}' with id {}", row.document_name, doc_id);
+ created += 1;
+ }
+ Err(e) => {
+ tracing::error!(error=?e, document = row.document_name, "failed to upload file to s3");
+ println!(
+ "Failed to upload file for document '{}': {e}",
+ row.document_name
+ );
+ failed += 1;
+ }
+ }
+ }
+ Err(e) => {
+ tracing::error!(error=?e, document = row.document_name, "failed to seed document");
+ println!("Failed to seed document '{}': {e}", row.document_name);
+ failed += 1;
+ }
+ }
+ }
+
+ println!("\nSeed complete: {created} created, {failed} failed");
+
+ Ok(())
+}
diff --git a/rust/cloud-storage/seed_cli/src/entity/document/test.rs b/rust/cloud-storage/seed_cli/src/entity/document/test.rs
new file mode 100644
index 0000000000..5511ed107c
--- /dev/null
+++ b/rust/cloud-storage/seed_cli/src/entity/document/test.rs
@@ -0,0 +1,481 @@
+use std::io::Write;
+
+use clap::Parser;
+use macro_user_id::user_id::MacroUserIdStr;
+use model::document::{DocumentMetadata, FileType};
+use tempfile::NamedTempFile;
+
+use crate::Cli;
+use crate::config::SeedCliContext;
+use crate::service::auth::Auth;
+use crate::service::db::Db;
+use crate::service::s3::S3;
+
+use super::*;
+
+// ── Parsing tests ──────────────────────────────────────────
+
+#[test]
+fn parse_document_create_minimal() {
+ let cli = Cli::try_parse_from([
+ "seed_cli",
+ "document",
+ "create",
+ "--owner",
+ "--file-path",
+ "/tmp/test.pdf",
+ "--document-name",
+ "My Document",
+ ])
+ .unwrap();
+
+ match cli.command {
+ crate::entity::EntityCommand::Document(args) => {
+ let DocumentCommand::Create(create) = args.command else {
+ panic!("expected Create");
+ };
+ assert_eq!(create.owner, "macro|[email protected]");
+ assert_eq!(create.file_path, "/tmp/test.pdf");
+ assert_eq!(create.document_name, "My Document");
+ assert!(!create.is_public);
+ assert!(create.public_access_level.is_none());
+ assert!(create.id.is_none());
+ assert!(!create.skip_history);
+ }
+ other => panic!("expected Document, got {other:?}"),
+ }
+}
+
+#[test]
+fn parse_document_create_full() {
+ let cli = Cli::try_parse_from([
+ "seed_cli",
+ "document",
+ "create",
+ "--owner",
+ "--file-path",
+ "/tmp/test.pdf",
+ "--document-name",
+ "My Document",
+ "--is-public",
+ "--public-access-level",
+ "view",
+ "--id",
+ "custom-doc-id",
+ "--skip-history",
+ ])
+ .unwrap();
+
+ match cli.command {
+ crate::entity::EntityCommand::Document(args) => {
+ let DocumentCommand::Create(create) = args.command else {
+ panic!("expected Create");
+ };
+ assert_eq!(create.owner, "macro|[email protected]");
+ assert_eq!(create.file_path, "/tmp/test.pdf");
+ assert_eq!(create.document_name, "My Document");
+ assert!(create.is_public);
+ assert_eq!(create.public_access_level.as_deref(), Some("view"));
+ assert_eq!(create.id.as_deref(), Some("custom-doc-id"));
+ assert!(create.skip_history);
+ }
+ other => panic!("expected Document, got {other:?}"),
+ }
+}
+
+#[test]
+fn parse_document_create_missing_owner_fails() {
+ let result = Cli::try_parse_from([
+ "seed_cli",
+ "document",
+ "create",
+ "--file-path",
+ "/tmp/test.pdf",
+ "--document-name",
+ "My Document",
+ ]);
+ assert!(result.is_err());
+}
+
+#[test]
+fn parse_document_create_missing_file_path_fails() {
+ let result = Cli::try_parse_from([
+ "seed_cli",
+ "document",
+ "create",
+ "--owner",
+ "--document-name",
+ "My Document",
+ ]);
+ assert!(result.is_err());
+}
+
+#[test]
+fn parse_document_create_missing_name_fails() {
+ let result = Cli::try_parse_from([
+ "seed_cli",
+ "document",
+ "create",
+ "--owner",
+ "--file-path",
+ "/tmp/test.pdf",
+ ]);
+ assert!(result.is_err());
+}
+
+// ── Parsing tests (seed) ──────────────────────────────────
+
+#[test]
+fn parse_document_seed() {
+ let cli = Cli::try_parse_from([
+ "seed_cli",
+ "document",
+ "seed",
+ "--user-id",
+ ])
+ .unwrap();
+
+ match cli.command {
+ crate::entity::EntityCommand::Document(args) => match args.command {
+ DocumentCommand::Seed(seed) => {
+ assert_eq!(seed.user_id, "macro|[email protected]");
+ }
+ other => panic!("expected Seed, got {other:?}"),
+ },
+ other => panic!("expected Document, got {other:?}"),
+ }
+}
+
+#[test]
+fn parse_document_seed_missing_user_id_fails() {
+ let result = Cli::try_parse_from(["seed_cli", "document", "seed"]);
+ assert!(result.is_err());
+}
+
+// ── Helpers ────────────────────────────────────────────────
+
+fn mock_ctx(db: Db, s3: S3) -> SeedCliContext {
+ SeedCliContext {
+ db,
+ fusionauth_client: Auth::default(),
+ s3,
+ }
+}
+
+fn write_temp_file(content: &[u8], suffix: &str) -> NamedTempFile {
+ let mut file = tempfile::Builder::new().suffix(suffix).tempfile().unwrap();
+ file.write_all(content).unwrap();
+ file.flush().unwrap();
+ file
+}
+
+fn write_temp_csv(content: &str) -> NamedTempFile {
+ let mut file = NamedTempFile::new().unwrap();
+ file.write_all(content.as_bytes()).unwrap();
+ file.flush().unwrap();
+ file
+}
+
+fn test_document_metadata() -> DocumentMetadata {
+ let owner = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ DocumentMetadata::new_document(
+ "doc-123",
+ 1,
+ owner,
+ "My Document",
+ Some(FileType::Pdf),
+ "sha",
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ )
+}
+
+fn test_document_metadata_with_type(file_type: FileType) -> DocumentMetadata {
+ let owner = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();
+ DocumentMetadata::new_document(
+ "doc-123",
+ 1,
+ owner,
+ "Test Doc",
+ Some(file_type),
+ "sha",
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ None,
+ )
+}
+
+// ── Execution tests ───────────────────────────────────────
+
+#[tokio::test]
+async fn create_document_success() {
+ let file = write_temp_file(b"%PDF-1.4 fake content", ".pdf");
+
+ let mut mock_db = Db::default();
+ mock_db
+ .expect_create_document()
+ .times(1)
+ .returning(|_| Ok(test_document_metadata()));
+
+ let mut mock_s3 = S3::default();
+ mock_s3
+ .expect_upload_file()
+ .times(1)
+ .returning(|_, _| Ok(()));
+
+ let args = DocumentArgs {
+ command: DocumentCommand::Create(CreateArgs {
+ owner: "macro|[email protected]".to_string(),
+ file_path: file.path().to_str().unwrap().to_string(),
+ document_name: "My Document".to_string(),
+ is_public: false,
+ public_access_level: None,
+ id: None,
+ skip_history: false,
+ }),
+ };
+
+ let result = args.execute(mock_ctx(mock_db, mock_s3)).await;
+ assert!(result.is_ok());
+}
+
+#[tokio::test]
+async fn create_document_db_failure_propagates() {
+ let file = write_temp_file(b"%PDF-1.4 fake content", ".pdf");
+
+ let mut mock_db = Db::default();
+ mock_db
+ .expect_create_document()
+ .times(1)
+ .returning(|_| Err(anyhow::anyhow!("db connection failed")));
+
+ let mock_s3 = S3::default();
+
+ let args = DocumentArgs {
+ command: DocumentCommand::Create(CreateArgs {
+ owner: "macro|[email protected]".to_string(),
+ file_path: file.path().to_str().unwrap().to_string(),
+ document_name: "My Document".to_string(),
+ is_public: false,
+ public_access_level: None,
+ id: None,
+ skip_history: false,
+ }),
+ };
+
+ let result = args.execute(mock_ctx(mock_db, mock_s3)).await;
+ let err = result.unwrap_err();
+ assert!(err.to_string().contains("db connection failed"));
+}
+
+#[tokio::test]
+async fn create_document_s3_failure_propagates() {
+ let file = write_temp_file(b"%PDF-1.4 fake content", ".pdf");
+
+ let mut mock_db = Db::default();
+ mock_db
+ .expect_create_document()
+ .times(1)
+ .returning(|_| Ok(test_document_metadata()));
+
+ let mut mock_s3 = S3::default();
+ mock_s3
+ .expect_upload_file()
+ .times(1)
+ .returning(|_, _| Err(anyhow::anyhow!("s3 upload failed")));
+
+ let args = DocumentArgs {
+ command: DocumentCommand::Create(CreateArgs {
+ owner: "macro|[email protected]".to_string(),
+ file_path: file.path().to_str().unwrap().to_string(),
+ document_name: "My Document".to_string(),
+ is_public: false,
+ public_access_level: None,
+ id: None,
+ skip_history: false,
+ }),
+ };
+
+ let result = args.execute(mock_ctx(mock_db, mock_s3)).await;
+ let err = result.unwrap_err();
+ assert!(err.to_string().contains("s3 upload failed"));
+}
+
+// ── Seed CSV tests ────────────────────────────────────────
+
+#[tokio::test]
+async fn seed_creates_all_documents() {
+ let doc1 = Uuid::new_v4();
+ let doc2 = Uuid::new_v4();
+ let csv = format!(
+ "document_id,document_name,file_name,is_public\n\
+ {doc1},Test PDF,pdf.pdf,false\n\
+ {doc2},Test Markdown,md.md,true\n"
+ );
+ let file = write_temp_csv(&csv);
+
+ let mut mock_db = Db::default();
+ mock_db
+ .expect_create_document()
+ .times(2)
+ .returning(|_| Ok(test_document_metadata()));
+
+ let mut mock_s3 = S3::default();
+ mock_s3
+ .expect_upload_file()
+ .times(2)
+ .returning(|_, _| Ok(()));
+
+ let args = SeedArgs {
+ user_id: "macro|[email protected]".to_string(),
+ };
+
+ let result = seed_from_file(args, mock_ctx(mock_db, mock_s3), file.path()).await;
+ assert!(result.is_ok());
+}
+
+#[tokio::test]
+async fn seed_empty_csv_fails() {
+ let csv = "document_id,document_name,file_name,is_public\n";
+ let file = write_temp_csv(csv);
+
+ let mock_db = Db::default();
+ let mock_s3 = S3::default();
+
+ let args = SeedArgs {
+ user_id: "macro|[email protected]".to_string(),
+ };
+
+ let result = seed_from_file(args, mock_ctx(mock_db, mock_s3), file.path()).await;
+ let err = result.unwrap_err();
+ assert!(err.to_string().contains("no documents found"));
+}
+
+#[tokio::test]
+async fn seed_continues_on_db_failure() {
+ let doc1 = Uuid::new_v4();
+ let doc2 = Uuid::new_v4();
+ let doc3 = Uuid::new_v4();
+ let csv = format!(
+ "document_id,document_name,file_name,is_public\n\
+ {doc1},Good Doc 1,pdf.pdf,false\n\
+ {doc2},Bad Doc,md.md,false\n\
+ {doc3},Good Doc 2,canvas.canvas,false\n"
+ );
+ let file = write_temp_csv(&csv);
+
+ let mut call_count = 0;
+ let mut mock_db = Db::default();
+ mock_db
+ .expect_create_document()
+ .times(3)
+ .returning(move |_| {
+ call_count += 1;
+ if call_count == 2 {
+ Err(anyhow::anyhow!("db error"))
+ } else {
+ Ok(test_document_metadata())
+ }
+ });
+
+ let mut mock_s3 = S3::default();
+ mock_s3
+ .expect_upload_file()
+ .times(2)
+ .returning(|_, _| Ok(()));
+
+ let args = SeedArgs {
+ user_id: "macro|[email protected]".to_string(),
+ };
+
+ let result = seed_from_file(args, mock_ctx(mock_db, mock_s3), file.path()).await;
+ assert!(result.is_ok());
+}
+
+#[tokio::test]
+async fn seed_continues_on_s3_failure() {
+ let doc1 = Uuid::new_v4();
+ let doc2 = Uuid::new_v4();
+ let csv = format!(
+ "document_id,document_name,file_name,is_public\n\
+ {doc1},Good Doc,pdf.pdf,false\n\
+ {doc2},S3 Fail Doc,md.md,false\n"
+ );
+ let file = write_temp_csv(&csv);
+
+ let mut mock_db = Db::default();
+ mock_db
+ .expect_create_document()
+ .times(2)
+ .returning(|_| Ok(test_document_metadata()));
+
+ let mut s3_call_count = 0;
+ let mut mock_s3 = S3::default();
+ mock_s3
+ .expect_upload_file()
+ .times(2)
+ .returning(move |_, _| {
+ s3_call_count += 1;
+ if s3_call_count == 2 {
+ Err(anyhow::anyhow!("s3 upload failed"))
+ } else {
+ Ok(())
+ }
+ });
+
+ let args = SeedArgs {
+ user_id: "macro|[email protected]".to_string(),
+ };
+
+ let result = seed_from_file(args, mock_ctx(mock_db, mock_s3), file.path()).await;
+ assert!(result.is_ok());
+}
+
+#[tokio::test]
+async fn seed_handles_all_file_types() {
+ let doc1 = Uuid::new_v4();
+ let doc2 = Uuid::new_v4();
+ let doc3 = Uuid::new_v4();
+ let csv = format!(
+ "document_id,document_name,file_name,is_public\n\
+ {doc1},PDF Doc,pdf.pdf,false\n\
+ {doc2},Markdown Doc,md.md,false\n\
+ {doc3},Canvas Doc,canvas.canvas,false\n"
+ );
+ let file = write_temp_csv(&csv);
+
+ let mut mock_db = Db::default();
+ mock_db.expect_create_document().times(3).returning(|args| {
+ let file_type = args.file_type.unwrap();
+ Ok(test_document_metadata_with_type(file_type))
+ });
+
+ let mut mock_s3 = S3::default();
+ mock_s3
+ .expect_upload_file()
+ .times(3)
+ .returning(|_, _| Ok(()));
+
+ let args = SeedArgs {
+ user_id: "macro|[email protected]".to_string(),
+ };
+
+ let result = seed_from_file(args, mock_ctx(mock_db, mock_s3), file.path()).await;
+ assert!(result.is_ok());
+}
diff --git a/rust/cloud-storage/seed_cli/src/entity/email/test.rs b/rust/cloud-storage/seed_cli/src/entity/email/test.rs
index 5a028bac0a..cf8eb549d7 100644
--- a/rust/cloud-storage/seed_cli/src/entity/email/test.rs
+++ b/rust/cloud-storage/seed_cli/src/entity/email/test.rs
@@ -7,6 +7,7 @@ use crate::Cli;
use crate::config::SeedCliContext;
use crate::service::auth::Auth;
use crate::service::db::Db;
+use crate::service::s3::S3;
use super::*;
@@ -156,6 +157,7 @@ fn mock_ctx(db: Db) -> SeedCliContext {
SeedCliContext {
db,
fusionauth_client: Auth::default(),
+ s3: S3::default(),
}
}
diff --git a/rust/cloud-storage/seed_cli/src/entity/mod.rs b/rust/cloud-storage/seed_cli/src/entity/mod.rs
index ceaf9a7f14..73976d7d59 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 document;
pub mod email;
pub mod user;
@@ -18,6 +19,8 @@ pub enum EntityCommand {
Channel(channel::ChannelArgs),
/// Manage channel message seed data
ChannelMessage(channel_message::ChannelMessageArgs),
+ /// Document commands
+ Document(document::DocumentArgs),
/// Manage email seed data
Email(email::EmailArgs),
}
@@ -29,6 +32,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::Document(args) => args.execute(ctx).await,
EntityCommand::Email(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.rs
index e0993c22a6..83b30e1be9 100644
--- a/rust/cloud-storage/seed_cli/src/entity/user/test.rs
+++ b/rust/cloud-storage/seed_cli/src/entity/user/test.rs
@@ -7,6 +7,7 @@ use crate::Cli;
use crate::config::SeedCliContext;
use crate::service::auth::Auth;
use crate::service::db::Db;
+use crate::service::s3::S3;
use super::*;
@@ -64,6 +65,7 @@ fn mock_ctx(auth: Auth) -> SeedCliContext {
SeedCliContext {
db: Db::default(),
fusionauth_client: auth,
+ s3: S3::default(),
}
}
diff --git a/rust/cloud-storage/seed_cli/src/main.rs b/rust/cloud-storage/seed_cli/src/main.rs
index 91d56fb25b..1bf65945ac 100644
--- a/rust/cloud-storage/seed_cli/src/main.rs
+++ b/rust/cloud-storage/seed_cli/src/main.rs
@@ -14,7 +14,10 @@ use macro_env::Environment;
use service::{auth::Auth, db::Db};
use sqlx::postgres::PgPoolOptions;
-use crate::config::{EnvVars, SeedCliContext};
+use crate::{
+ config::{EnvVars, SeedCliContext},
+ service::s3::S3,
+};
/// The Seed CLI for populating Macro with seed data.
#[derive(Debug, Parser)]
@@ -57,9 +60,18 @@ pub async fn main() -> anyhow::Result<()> {
);
tracing::trace!("initialized fusionauth client");
+ let aws_config = macro_aws_config::get_macro_aws_config().await;
+ let s3_config = aws_sdk_s3::config::Builder::from(&aws_config)
+ .force_path_style(macro_aws_config::is_local_aws())
+ .build();
+
let context = SeedCliContext {
db: Db::new(db),
fusionauth_client: Auth::new(fusionauth_client),
+ s3: S3::new(
+ &env_vars.document_storage_bucket,
+ aws_sdk_s3::Client::from_conf(s3_config),
+ ),
};
let cli = Cli::parse();
diff --git a/rust/cloud-storage/seed_cli/src/service/db/mod.rs b/rust/cloud-storage/seed_cli/src/service/db/mod.rs
index dbdecb4243..ef4740c495 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 model::document::DocumentMetadata;
use models_email::email::service;
/// Wrapper around the database connection pool.
@@ -27,6 +28,15 @@ impl SeedDb {
Self { inner }
}
+ /// Create a document in the database.
+ #[tracing::instrument(skip(self), err)]
+ pub async fn create_document<'a>(
+ &self,
+ args: macro_db_client::document::v2::create::CreateDocumentArgs<'a>,
+ ) -> anyhow::Result<DocumentMetadata> {
+ macro_db_client::document::v2::create::create_document(&self.inner, args).await
+ }
+
/// Create a channel in the database.
#[tracing::instrument(skip(self), err)]
pub async fn create_channel(
diff --git a/rust/cloud-storage/seed_cli/src/service/mod.rs b/rust/cloud-storage/seed_cli/src/service/mod.rs
index c2d45c5b72..aa040dbab4 100644
--- a/rust/cloud-storage/seed_cli/src/service/mod.rs
+++ b/rust/cloud-storage/seed_cli/src/service/mod.rs
@@ -2,3 +2,4 @@
pub mod auth;
pub mod db;
+pub mod s3;
diff --git a/rust/cloud-storage/seed_cli/src/service/s3.rs b/rust/cloud-storage/seed_cli/src/service/s3.rs
new file mode 100644
index 0000000000..94974802a2
--- /dev/null
+++ b/rust/cloud-storage/seed_cli/src/service/s3.rs
@@ -0,0 +1,45 @@
+//! S3 service wrapper.
+
+#[cfg(test)]
+pub use MockSeedS3 as S3;
+#[cfg(not(test))]
+pub use SeedS3 as S3;
+
+use anyhow::Context;
+#[allow(unused_imports)]
+use mockall::automock;
+
+/// Wrapper around the database connection pool.
+pub struct SeedS3 {
+ bucket: String,
+ /// The macrodb pool
+ inner: aws_sdk_s3::Client,
+}
+
+#[cfg_attr(test, automock)]
+impl SeedS3 {
+ /// Create a new database wrapper.
+ pub fn new(bucket: &str, inner: aws_sdk_s3::Client) -> Self {
+ Self {
+ bucket: bucket.to_string(),
+ inner,
+ }
+ }
+
+ /// Upload a file to s3
+ #[tracing::instrument(skip(self), err)]
+ pub async fn upload_file(&self, key: &str, local_file_path: &str) -> anyhow::Result<()> {
+ let bytes = std::fs::read(local_file_path).context("read file")?;
+ let body = aws_sdk_s3::primitives::ByteStream::from(bytes);
+
+ self.inner
+ .put_object()
+ .bucket(&self.bucket)
+ .key(key)
+ .body(body)
+ .send()
+ .await?;
+
+ Ok(())
+ }
+}