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(ownership): scheduled_action register scheduled actions in the entity table (#6588)
Will Hutchinson2b5304d38925
diff --git a/Cargo.lock b/Cargo.lockindex 9c437bb688..a9498c22db 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -14632,6 +14632,7 @@ dependencies = ["cron","database_env_vars","doppler-config",+ "entity_registry_db_utils","futures","macro_auth","macro_authorization",@@ -14639,6 +14640,7 @@ dependencies = ["macro_config","macro_cors","macro_db_client",+ "macro_db_migrator","macro_entrypoint","macro_env","macro_env_var",@@ -14650,6 +14652,7 @@ dependencies = ["model","model-entity","model_notifications",+ "model_owner","models_permissions","notification","secretsmanager_client",diff --git a/services/scheduled_action/Cargo.toml b/services/scheduled_action/Cargo.tomlindex 82d17545d8..f498a7ab77 100644--- a/services/scheduled_action/Cargo.toml+++ b/services/scheduled_action/Cargo.toml@@ -56,6 +56,8 @@ macro_db_client = { path = "../../crates/macro_db_client" }memory = { path = "../../crates/memory" }model = { path = "../../crates/model" }model-entity = { path = "../../crates/model-entity" }+model_owner = { path = "../../crates/model_owner" }+entity_registry_db_utils = { path = "../../crates/entity_registry/entity_registry_db_utils" }model_notifications = { path = "../../crates/model_notifications" }notification = { path = "../../crates/notification" }utoipa = { workspace = true, features = ["axum_extras", "chrono"] }@@ -72,3 +74,6 @@ aws-sdk-secretsmanager = { workspace = true }macro_service_urls = { path = "../../crates/macro_service_urls" }workspace-hack = { version = "0.1", path = "../../crates/workspace-hack" }++[dev-dependencies]+macro_db_migrator = { path = "../../crates/macro_db_migrator" }diff --git a/services/scheduled_action/src/outbound/pg_scheduled_action_repo.rs b/services/scheduled_action/src/outbound/pg_scheduled_action_repo.rsindex b6c1043659..9db76b75cf 100644--- a/services/scheduled_action/src/outbound/pg_scheduled_action_repo.rs+++ b/services/scheduled_action/src/outbound/pg_scheduled_action_repo.rs@@ -1,9 +1,14 @@use anyhow::{Result, bail};use chrono::{DateTime, Utc};use chrono_tz::Tz;+use entity_registry_db_utils::{+ InsertOutcome, NewEntityRecord, RegisteredEntityType, WriteOutcome, delete_entity,+ insert_entity,+};use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;+use model_owner::Owner;use sqlx::PgPool;use std::str::FromStr;@@ -13,6 +18,9 @@ use crate::domain::models::{};use crate::domain::ports::ScheduledActionRepo;+#[cfg(test)]+mod test;+pub struct PgScheduledActionRepo {pool: PgPool,}@@ -46,6 +54,7 @@ impl ScheduledActionRepo for PgScheduledActionRepo {let timezone = action.timezone.to_string();let kind = kind_to_str(&action.kind);+ let mut tx = self.pool.begin().await?;let row = sqlx::query!(r#"INSERT INTO scheduled_action (owner, name, schedule, kind, timezone, task, next_run_at, enabled)@@ -61,10 +70,10 @@ impl ScheduledActionRepo for PgScheduledActionRepo {action.next_run_at,action.enabled,)- .fetch_one(&self.pool)+ .fetch_one(&mut *tx).await?;- Ok(ScheduledAction {+ let created = ScheduledAction {id: Some(row.id),owner: MacroUserIdStr::parse_from_str(&row.owner)?.into_owned(),name: row.name,@@ -77,7 +86,21 @@ impl ScheduledActionRepo for PgScheduledActionRepo {claimed: row.claimed,next_run_at: row.next_run_at,enabled: row.enabled,- })+ };+ match insert_entity(+ &mut tx,+ NewEntityRecord::new(+ row.id,+ RegisteredEntityType::ScheduledAction,+ Owner::User(created.owner.clone()),+ ),+ )+ .await?+ {+ InsertOutcome::Inserted | InsertOutcome::AlreadyRegistered => {}+ }+ tx.commit().await?;+ Ok(created)}async fn get_actions(&self, user_id: MacroUserIdStr<'static>) -> Result<Vec<ScheduledAction>> {@@ -206,6 +229,7 @@ impl ScheduledActionRepo for PgScheduledActionRepo {id: &Uuid,_macro_user_id: MacroUserIdStr<'static>,) -> Result<()> {+ let mut tx = self.pool.begin().await?;sqlx::query!(r#"DELETE FROM scheduled_action@@ -213,9 +237,13 @@ impl ScheduledActionRepo for PgScheduledActionRepo {"#,*id)- .execute(&self.pool)+ .execute(&mut *tx).await?;+ match delete_entity(&mut tx, *id).await? {+ WriteOutcome::Applied | WriteOutcome::NotFound => {}+ }+ tx.commit().await?;Ok(())}@@ -307,8 +335,6 @@ impl ScheduledActionRepo for PgScheduledActionRepo {}async fn update_next_run_at(&self, id: &Uuid) -> Result<()> {- // Fetch the schedule + timezone so we can recompute `next_run_at`- // without the caller having to hold the action in memory.let row = sqlx::query!(r#"SELECT schedule, timezone@@ -323,7 +349,6 @@ impl ScheduledActionRepo for PgScheduledActionRepo {let tz = parse_timezone(&row.timezone)?;let schedule = Schedule::from_cron(row.schedule)?;let Some(next_run_at) = schedule.next_run_after_now(tz) else {- // No future fire time — leave next_run_at untouched.return Ok(());};diff --git a/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs b/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rsnew file mode 100644index 0000000000..d78e039c52--- /dev/null+++ b/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs@@ -0,0 +1,270 @@+use chrono::{DateTime, Utc};+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use macro_user_id::user_id::MacroUserIdStr;+use macro_uuid::Uuid;+use serde_json::json;+use sqlx::{PgPool, Row};++use super::*;+use crate::domain::models::{ActionKind, AlreadyRunningError, Schedule, ScheduledAction};+use crate::domain::ports::ScheduledActionRepo;++const USER_A: &str = "macro|[email protected]";+const USER_B: &str = "macro|[email protected]";+const DAILY_9AM: &str = "0 0 9 * * *";++fn user(id: &'static str) -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str(id).expect("valid user id")+}++async fn insert_user(pool: &PgPool, id: &str) {+ let macro_user_id = macro_uuid::generate_uuid_v7();+ sqlx::query(+ r#"INSERT INTO macro_user (id, username, email, stripe_customer_id) VALUES ($1, $2, $2, $2)"#,+ )+ .bind(macro_user_id)+ .bind(id)+ .execute(pool)+ .await+ .expect("macro_user should insert");+ sqlx::query(r#"INSERT INTO "User" (id, email, macro_user_id) VALUES ($1, $1, $2)"#)+ .bind(id)+ .bind(macro_user_id)+ .execute(pool)+ .await+ .expect("user should insert");+}++fn sample_action(owner: MacroUserIdStr<'static>, name: &str) -> ScheduledAction {+ let now = Utc::now();+ let schedule = Schedule::from_cron(DAILY_9AM.to_string()).expect("valid cron");+ let timezone = chrono_tz::UTC;+ let next_run_at = schedule+ .next_run_after_now(timezone)+ .expect("schedule has a future firing");+ ScheduledAction {+ id: None,+ owner,+ name: name.to_string(),+ schedule,+ kind: ActionKind::Agent,+ created_at: now,+ updated_at: now,+ timezone,+ task: json!({}),+ claimed: None,+ next_run_at,+ enabled: true,+ }+}++async fn fetch_entity_row(pool: &PgPool, id: Uuid) -> sqlx::postgres::PgRow {+ sqlx::query(+ r#"+ SELECT+ owner_type::text AS owner_type,+ owner_id,+ entity_type,+ deleted_at+ FROM entity+ WHERE id = $1+ "#,+ )+ .bind(id)+ .fetch_one(pool)+ .await+ .unwrap()+}++async fn entity_row_count(pool: &PgPool, id: Uuid) -> i64 {+ sqlx::query_scalar("SELECT COUNT(*) FROM entity WHERE id = $1")+ .bind(id)+ .fetch_one(pool)+ .await+ .unwrap()+}++async fn scheduled_action_row_count(pool: &PgPool, id: Uuid) -> i64 {+ sqlx::query_scalar("SELECT COUNT(*) FROM scheduled_action WHERE id = $1")+ .bind(id)+ .fetch_one(pool)+ .await+ .unwrap()+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn create_action_returns_id_and_is_listable_by_owner(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgScheduledActionRepo::new(pool);++ let created = repo+ .create_action(sample_action(user(USER_A), "standup"))+ .await+ .expect("create should succeed");+ assert!(created.id.is_some());++ let listed = repo+ .get_actions(user(USER_A))+ .await+ .expect("list should succeed");+ assert_eq!(listed.len(), 1);+ assert_eq!(listed[0].name, "standup");+ assert_eq!(listed[0].id, created.id);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn other_owner_list_is_empty(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ insert_user(&pool, USER_B).await;+ let repo = PgScheduledActionRepo::new(pool);++ repo.create_action(sample_action(user(USER_A), "standup"))+ .await+ .expect("create should succeed");++ let owner_listed = repo+ .get_actions(user(USER_A))+ .await+ .expect("owner list should succeed");+ assert_eq!(owner_listed.len(), 1);++ let listed = repo+ .get_actions(user(USER_B))+ .await+ .expect("list should succeed");+ assert!(listed.is_empty());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn update_action_changes_name_schedule_and_enabled(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgScheduledActionRepo::new(pool);++ let created = repo+ .create_action(sample_action(user(USER_A), "standup"))+ .await+ .expect("create should succeed");++ let schedule = Schedule::from_cron("0 0 18 * * *".to_string()).expect("valid cron");+ let next_run_at = schedule+ .next_run_after_now(chrono_tz::UTC)+ .expect("schedule has a future firing");+ let updated = repo+ .update_action(ScheduledAction {+ name: "evening standup".to_string(),+ schedule,+ enabled: false,+ next_run_at,+ ..created+ })+ .await+ .expect("update should succeed");++ assert_eq!(updated.name, "evening standup");+ assert_eq!(updated.schedule.as_str(), "0 0 18 * * *");+ assert!(!updated.enabled);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn second_claim_returns_already_running(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgScheduledActionRepo::new(pool);++ let created = repo+ .create_action(sample_action(user(USER_A), "standup"))+ .await+ .expect("create should succeed");+ let id = created.id.expect("create returns Some(id)");++ repo.claim_action(&id)+ .await+ .expect("first claim should succeed");+ let error = repo+ .claim_action(&id)+ .await+ .expect_err("second claim should fail");+ assert!(error.downcast_ref::<AlreadyRunningError>().is_some());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn delete_action_removes_row_from_owner_list(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgScheduledActionRepo::new(pool.clone());++ let created = repo+ .create_action(sample_action(user(USER_A), "standup"))+ .await+ .expect("create should succeed");+ let id = created.id.expect("create returns Some(id)");++ repo.delete_action(&id, user(USER_A))+ .await+ .expect("delete should succeed");++ let listed = repo+ .get_actions(user(USER_A))+ .await+ .expect("list should succeed");+ assert!(listed.is_empty());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn create_action_registers_entity_row(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgScheduledActionRepo::new(pool.clone());++ let created = repo+ .create_action(sample_action(user(USER_A), "standup"))+ .await+ .expect("create should succeed");+ let id = created.id.expect("create returns Some(id)");++ let row = fetch_entity_row(&pool, id).await;+ assert_eq!(row.get::<String, _>("entity_type"), "scheduled_action");+ assert_eq!(row.get::<String, _>("owner_type"), "user");+ assert_eq!(row.get::<String, _>("owner_id"), USER_A);+ assert_eq!(row.get::<Option<DateTime<Utc>>, _>("deleted_at"), None);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn delete_action_removes_entity_row(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgScheduledActionRepo::new(pool.clone());++ let created = repo+ .create_action(sample_action(user(USER_A), "standup"))+ .await+ .expect("create should succeed");+ let id = created.id.expect("create returns Some(id)");++ repo.delete_action(&id, user(USER_A))+ .await+ .expect("delete should succeed");++ assert_eq!(entity_row_count(&pool, id).await, 0);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn delete_action_succeeds_when_entity_row_is_missing(pool: PgPool) {+ insert_user(&pool, USER_A).await;+ let repo = PgScheduledActionRepo::new(pool.clone());++ let created = repo+ .create_action(sample_action(user(USER_A), "standup"))+ .await+ .expect("create should succeed");+ let id = created.id.expect("create returns Some(id)");++ sqlx::query("DELETE FROM entity WHERE id = $1")+ .bind(id)+ .execute(&pool)+ .await+ .expect("entity row should delete");++ repo.delete_action(&id, user(USER_A))+ .await+ .expect("delete should succeed");++ assert_eq!(entity_row_count(&pool, id).await, 0);+ assert_eq!(scheduled_action_row_count(&pool, id).await, 0);+}