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.

refactor(scheduled_action): typed owner in the scheduled action model (#6707)

Will Hutchinsonab445ccd95fb
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/scheduledAction.ts b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/scheduledAction.ts
index c4a3125db3..cc82517069 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/scheduledAction.ts
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/generated/schemas/scheduledAction.ts
@@ -24,6 +24,10 @@ available regardless. */
/** Time of the next scheduled firing (derived from the cron on write). UI
uses this to render "next run" without having to parse the cron itself. */
next_run_at: string;
+ /** Who the action belongs to. Every action is user-owned today, but the
+type no longer says so: the principal string on the wire and in the
+`owner` column is the same, and a bot- or team-owned row decodes
+rather than failing to parse. */
owner: string;
schedule: Schedule;
task: ScheduledActionTask;
diff --git a/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json b/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json
index 8533cd27c3..0d4e972330 100644
--- a/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json
+++ b/apps/web/src/lib/service-clients/service-scheduled-action/openapi.json
@@ -518,7 +518,8 @@
"description": "Time of the next scheduled firing (derived from the cron on write). UI\nuses this to render \"next run\" without having to parse the cron itself."
},
"owner": {
- "type": "string"
+ "type": "string",
+ "description": "Who the action belongs to. Every action is user-owned today, but the\ntype no longer says so: the principal string on the wire and in the\n`owner` column is the same, and a bot- or team-owned row decodes\nrather than failing to parse."
},
"schedule": {
"$ref": "#/components/schemas/Schedule"
diff --git a/packages/sdk/generated/scheduled-action/types.gen.ts b/packages/sdk/generated/scheduled-action/types.gen.ts
index c911efd41a..6b9e8ff370 100644
--- a/packages/sdk/generated/scheduled-action/types.gen.ts
+++ b/packages/sdk/generated/scheduled-action/types.gen.ts
@@ -75,6 +75,12 @@ export type ScheduledAction = {
* uses this to render "next run" without having to parse the cron itself.
*/
next_run_at: string;
+ /**
+ * Who the action belongs to. Every action is user-owned today, but the
+ * type no longer says so: the principal string on the wire and in the
+ * `owner` column is the same, and a bot- or team-owned row decodes
+ * rather than failing to parse.
+ */
owner: string;
schedule: Schedule;
task: {
diff --git a/packages/sdk/specs/scheduled-action.json b/packages/sdk/specs/scheduled-action.json
index 8533cd27c3..0d4e972330 100644
--- a/packages/sdk/specs/scheduled-action.json
+++ b/packages/sdk/specs/scheduled-action.json
@@ -518,7 +518,8 @@
"description": "Time of the next scheduled firing (derived from the cron on write). UI\nuses this to render \"next run\" without having to parse the cron itself."
},
"owner": {
- "type": "string"
+ "type": "string",
+ "description": "Who the action belongs to. Every action is user-owned today, but the\ntype no longer says so: the principal string on the wire and in the\n`owner` column is the same, and a bot- or team-owned row decodes\nrather than failing to parse."
},
"schedule": {
"$ref": "#/components/schemas/Schedule"
diff --git a/services/scheduled_action/src/domain/models.rs b/services/scheduled_action/src/domain/models.rs
index 22851d829e..b96c42ef63 100644
--- a/services/scheduled_action/src/domain/models.rs
+++ b/services/scheduled_action/src/domain/models.rs
@@ -4,11 +4,15 @@ use chrono_tz::Tz;
use cron::Schedule as CronSchedule;
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
+use model_owner::{Owner, OwnerType};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::str::FromStr;
use utoipa::ToSchema;
+#[cfg(test)]
+mod test;
+
pub const MAX_ACTION_TIME: Duration = Duration::minutes(20);
#[derive(Serialize, Debug, Clone, ToSchema)]
@@ -95,8 +99,12 @@ pub struct UpdateScheduledAction {
pub struct ScheduledAction {
#[schema(value_type = Option<String>, format = Uuid)]
pub id: Option<Uuid>,
+ /// Who the action belongs to. Every action is user-owned today, but the
+ /// type no longer says so: the principal string on the wire and in the
+ /// `owner` column is the same, and a bot- or team-owned row decodes
+ /// rather than failing to parse.
#[schema(value_type = String)]
- pub owner: MacroUserIdStr<'static>,
+ pub owner: Owner,
pub name: String,
pub schedule: Schedule,
pub kind: ActionKind,
@@ -115,6 +123,20 @@ pub struct ScheduledAction {
pub enabled: bool,
}
+impl ScheduledAction {
+ /// The user this action runs as.
+ ///
+ /// For every path that acts as the owner rather than merely naming them:
+ /// creating a chat in their account, reading their memory, spending their
+ /// AI budget, notifying them. Asking here fails typed for a bot or team
+ /// instead of treating one as a person.
+ pub fn owner_user(&self) -> Result<&MacroUserIdStr<'static>, OwnerNotUserError> {
+ self.owner.as_user().ok_or(OwnerNotUserError {
+ owner_type: self.owner.owner_type(),
+ })
+ }
+}
+
#[derive(Debug, Serialize, Deserialize, ToSchema)]
pub struct InProgressExecution {
#[schema(value_type = String, format = Uuid)]
@@ -202,3 +224,23 @@ impl std::fmt::Display for AlreadyRunningError {
}
impl std::error::Error for AlreadyRunningError {}
+
+/// Returned when a path that must run as a person meets an action owned by a
+/// bot or a team. Callers at the HTTP boundary map this to 400 Bad Request;
+/// the polling dispatcher logs it and leaves the action alone.
+#[derive(Debug)]
+pub struct OwnerNotUserError {
+ pub owner_type: OwnerType,
+}
+
+impl std::fmt::Display for OwnerNotUserError {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ write!(
+ f,
+ "this path needs a user-owned scheduled action, but the owner is a {}",
+ self.owner_type
+ )
+ }
+}
+
+impl std::error::Error for OwnerNotUserError {}
diff --git a/services/scheduled_action/src/domain/models/test.rs b/services/scheduled_action/src/domain/models/test.rs
new file mode 100644
index 0000000000..f4e86ce418
--- /dev/null
+++ b/services/scheduled_action/src/domain/models/test.rs
@@ -0,0 +1,100 @@
+use chrono::Utc;
+use macro_uuid::{Uuid, generate_uuid_v7};
+use model_owner::{Owner, OwnerType};
+use serde_json::json;
+
+use super::{ActionKind, Schedule, ScheduledAction};
+
+const DAILY_9AM: &str = "0 0 9 * * *";
+const USER_PRINCIPAL: &str = "macro|[email protected]";
+
+fn action_owned_by(owner: Owner) -> 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: Some(generate_uuid_v7()),
+ owner,
+ name: "standup".to_string(),
+ schedule,
+ kind: ActionKind::Agent,
+ created_at: now,
+ updated_at: now,
+ timezone,
+ task: json!({}),
+ claimed: None,
+ next_run_at,
+ enabled: true,
+ }
+}
+
+fn bot_principal(bot_id: Uuid) -> String {
+ format!("bot|{}", bot_id.hyphenated())
+}
+
+/// The `owner` column still has a foreign key to `"User"`, so only user-owned
+/// rows can be stored today. Decoding is the part that has to be ready first:
+/// a bot principal must round-trip into the model rather than fail to parse.
+#[test]
+fn bot_owner_principal_decodes_as_a_bot() {
+ let bot_id = generate_uuid_v7();
+ let owner = Owner::from_principal_str(&bot_principal(bot_id))
+ .expect("a bot principal should decode into a typed owner");
+
+ assert_eq!(owner.owner_type(), OwnerType::Bot);
+ assert_eq!(owner.principal_id(), bot_principal(bot_id));
+}
+
+#[test]
+fn owner_user_returns_the_user_for_a_user_owned_action() {
+ let action = action_owned_by(
+ Owner::from_principal_str(USER_PRINCIPAL).expect("a user principal should decode"),
+ );
+
+ let owner = action.owner_user().expect("a user-owned action has a user");
+ assert_eq!(owner.to_string(), USER_PRINCIPAL);
+}
+
+#[test]
+fn owner_user_rejects_a_bot_owned_action() {
+ let action = action_owned_by(
+ Owner::from_principal_str(&bot_principal(generate_uuid_v7()))
+ .expect("a bot principal should decode"),
+ );
+
+ let error = action
+ .owner_user()
+ .expect_err("execution should refuse a bot-owned action");
+ assert_eq!(error.owner_type, OwnerType::Bot);
+}
+
+#[test]
+fn owner_user_rejects_a_team_owned_action() {
+ let team_id = generate_uuid_v7();
+ let action = action_owned_by(
+ Owner::from_principal_str(&team_id.hyphenated().to_string())
+ .expect("a team principal should decode"),
+ );
+
+ let error = action
+ .owner_user()
+ .expect_err("execution should refuse a team-owned action");
+ assert_eq!(error.owner_type, OwnerType::Team);
+}
+
+#[test]
+fn owner_serializes_as_the_bare_principal_string() {
+ let action = action_owned_by(
+ Owner::from_principal_str(USER_PRINCIPAL).expect("a user principal should decode"),
+ );
+
+ let encoded = serde_json::to_value(&action).expect("action should serialize");
+ assert_eq!(encoded["owner"], json!(USER_PRINCIPAL));
+
+ let decoded: ScheduledAction =
+ serde_json::from_value(encoded).expect("action should round-trip");
+ assert_eq!(decoded.owner, action.owner);
+}
diff --git a/services/scheduled_action/src/domain/service.rs b/services/scheduled_action/src/domain/service.rs
index f9f93a3977..430aa4bcaa 100644
--- a/services/scheduled_action/src/domain/service.rs
+++ b/services/scheduled_action/src/domain/service.rs
@@ -8,6 +8,15 @@ use tokio::sync::mpsc::Sender;
use super::models::{ActionExecutionRecord, DispatchEvent, InProgressExecution, ScheduledAction};
use super::ports::{ScheduledActionExecutor, ScheduledActionRepo, ScheduledActionService};
+/// True when `action` is the caller's own action.
+///
+/// The repository already filters by the caller's principal, so this is the
+/// second half of the same statement: the row is only theirs when its owner is
+/// that user rather than a bot or a team that happens to share the string.
+fn is_owned_by(action: &ScheduledAction, caller: &MacroUserIdStr<'static>) -> bool {
+ action.owner.is_user(caller)
+}
+
pub struct ScheduledActionServiceImpl<Rpo, Exe> {
repo: Arc<Rpo>,
executor: Arc<Exe>,
@@ -50,8 +59,11 @@ where
let Some(id) = action.id else {
bail!("cannot update action without id");
};
- let actions = self.repo.get_actions(macro_user_id).await?;
- if !actions.iter().any(|a| a.id.as_ref() == Some(&id)) {
+ let actions = self.repo.get_actions(macro_user_id.clone()).await?;
+ if !actions
+ .iter()
+ .any(|a| a.id.as_ref() == Some(&id) && is_owned_by(a, &macro_user_id))
+ {
bail!("scheduled action {id} not found for user");
}
@@ -65,7 +77,10 @@ where
async fn delete_action(&self, id: &Uuid, macro_user_id: MacroUserIdStr<'static>) -> Result<()> {
let actions = self.repo.get_actions(macro_user_id.clone()).await?;
- let Some(action) = actions.into_iter().find(|a| a.id.as_ref() == Some(id)) else {
+ let Some(action) = actions
+ .into_iter()
+ .find(|a| a.id.as_ref() == Some(id) && is_owned_by(a, &macro_user_id))
+ else {
bail!("scheduled action {id} not found for user");
};
@@ -82,8 +97,11 @@ where
id: &Uuid,
macro_user_id: MacroUserIdStr<'static>,
) -> Result<InProgressExecution> {
- let actions = self.repo.get_actions(macro_user_id).await?;
- let Some(action) = actions.into_iter().find(|a| a.id.as_ref() == Some(id)) else {
+ let actions = self.repo.get_actions(macro_user_id.clone()).await?;
+ let Some(action) = actions
+ .into_iter()
+ .find(|a| a.id.as_ref() == Some(id) && is_owned_by(a, &macro_user_id))
+ else {
bail!("scheduled action {id} not found for user");
};
@@ -95,8 +113,11 @@ where
id: &Uuid,
macro_user_id: MacroUserIdStr<'static>,
) -> Result<Vec<ActionExecutionRecord>> {
- let actions = self.repo.get_actions(macro_user_id).await?;
- if !actions.iter().any(|a| a.id.as_ref() == Some(id)) {
+ let actions = self.repo.get_actions(macro_user_id.clone()).await?;
+ if !actions
+ .iter()
+ .any(|a| a.id.as_ref() == Some(id) && is_owned_by(a, &macro_user_id))
+ {
bail!("scheduled action {id} not found for user");
}
diff --git a/services/scheduled_action/src/inbound/axum_router.rs b/services/scheduled_action/src/inbound/axum_router.rs
index 7056fb1cb0..cd16b0cca7 100644
--- a/services/scheduled_action/src/inbound/axum_router.rs
+++ b/services/scheduled_action/src/inbound/axum_router.rs
@@ -11,10 +11,11 @@ use macro_authorization::{
};
use macro_uuid::Uuid;
use model::response::EmptyResponse;
+use model_owner::Owner;
use crate::domain::models::{
ActionExecutionRecord, AlreadyRunningError, CreateScheduledAction, InProgressExecution,
- ScheduledAction, UpdateScheduledAction,
+ OwnerNotUserError, ScheduledAction, UpdateScheduledAction,
};
use crate::domain::ports::ScheduledActionService;
@@ -106,7 +107,7 @@ pub async fn create_action<
.ok_or_else(|| anyhow::anyhow!("schedule has no future firings"))?;
let action = ScheduledAction {
id: None,
- owner: user.authorization.user.macro_user_id.clone(),
+ owner: Owner::User(user.authorization.user.macro_user_id.clone()),
name: req.name,
schedule: req.schedule,
kind: req.kind,
@@ -177,7 +178,7 @@ pub async fn update_action<
.ok_or_else(|| anyhow::anyhow!("schedule has no future firings"))?;
let action = ScheduledAction {
id: Some(id),
- owner: user.authorization.user.macro_user_id.clone(),
+ owner: Owner::User(user.authorization.user.macro_user_id.clone()),
name: req.name,
schedule: req.schedule,
kind: req.kind,
@@ -295,6 +296,10 @@ impl IntoResponse for ScheduledActionApiError {
tracing::info!(error=%already_running, "scheduled action already running");
return (StatusCode::CONFLICT, already_running.to_string()).into_response();
}
+ if let Some(owner_not_user) = self.0.downcast_ref::<OwnerNotUserError>() {
+ tracing::warn!(error=%owner_not_user, "scheduled action owner is not a user");
+ return (StatusCode::BAD_REQUEST, owner_not_user.to_string()).into_response();
+ }
tracing::error!(error=?self.0, "scheduled action api error");
(StatusCode::INTERNAL_SERVER_ERROR, self.0.to_string()).into_response()
}
diff --git a/services/scheduled_action/src/outbound/inprocess_executor.rs b/services/scheduled_action/src/outbound/inprocess_executor.rs
index 43603caeaf..f4c844611c 100644
--- a/services/scheduled_action/src/outbound/inprocess_executor.rs
+++ b/services/scheduled_action/src/outbound/inprocess_executor.rs
@@ -63,6 +63,10 @@ where
Live: ScheduledActionLiveUpdate,
{
async fn execute_action(&self, action: ScheduledAction) -> Result<InProgressExecution> {
+ // A run acts as the owner throughout - it opens a chat in their
+ // account and spends their AI budget - so refuse a bot- or team-owned
+ // action here, before the claim, rather than part-way through.
+ let owner_user = action.owner_user()?.clone();
try_claim(&action)?;
let id = *action.id.as_ref().unwrap();
@@ -76,7 +80,7 @@ where
self.live_updates
.publish_update(ScheduledActionUpdate::Started {
- owner: action.owner.clone(),
+ owner: owner_user.clone(),
action_id: id,
chat_id: chat_id.clone(),
})
@@ -138,7 +142,7 @@ where
// now" the UI issues in response will not race the claim.
live_updates
.publish_update(ScheduledActionUpdate::Stopped {
- owner: action.owner.clone(),
+ owner: owner_user,
action_id: id,
chat_id: record_resource_id.clone(),
is_success,
diff --git a/services/scheduled_action/src/outbound/inprocess_executor/agent_task.rs b/services/scheduled_action/src/outbound/inprocess_executor/agent_task.rs
index 70e4bafcec..b0d56f0e31 100644
--- a/services/scheduled_action/src/outbound/inprocess_executor/agent_task.rs
+++ b/services/scheduled_action/src/outbound/inprocess_executor/agent_task.rs
@@ -11,6 +11,7 @@ use chat::domain::ports::ChatRepo;
use chat::outbound::postgres::PgChatRepo;
use futures::StreamExt;
use macro_db_client::dcs::create_chat_message::create_chat_message;
+use macro_user_id::user_id::MacroUserIdStr;
use memory::domain::MemoryService;
use memory::domain::service::MemoryServiceImpl;
use memory::outbound::pg_memory_repo::PgMemoryRepo;
@@ -32,12 +33,16 @@ pub async fn run_agent_task(
action: &ScheduledAction,
chat_id: &str,
) -> Result<()> {
+ // The run reads this user's memory, spends their AI budget and notifies
+ // them, so resolve the owner as a person once and fail typed if it is not.
+ let owner = action.owner_user()?.clone();
+
let agent_task: AgentTask =
serde_json::from_value(action.task.clone()).context("invalid agent task definition")?;
store_user_message(db, chat_id, &agent_task).await?;
- let parts = run_tool_loop(db, tool_context, action, &agent_task).await?;
+ let parts = run_tool_loop(db, tool_context, &owner, &agent_task).await?;
let final_text: String = parts
.iter()
@@ -50,7 +55,7 @@ pub async fn run_agent_task(
store_conversation(db, chat_id, &parts, &agent_task).await?;
if !final_text.is_empty() {
- notify_completion(notification_ingress, chat_id, action, &final_text);
+ notify_completion(notification_ingress, chat_id, &owner, &final_text);
}
Ok(())
@@ -59,7 +64,7 @@ pub async fn run_agent_task(
async fn fetch_user_memory(
db: &PgPool,
tool_context: &ToolServiceContext,
- owner: &macro_user_id::user_id::MacroUserIdStr<'static>,
+ owner: &MacroUserIdStr<'static>,
) -> Option<String> {
let tools = tools_for(AiHost::Chat);
let tools = ToolSetWithPrompt {
@@ -80,12 +85,15 @@ async fn fetch_user_memory(
async fn create_chat(db: &PgPool, action: &ScheduledAction) -> Result<String> {
let chat_repo = PgChatRepo::new(db.clone());
+ // A chat belongs to a person, so a bot- or team-owned action cannot have
+ // one created for it.
+ let owner = action.owner_user()?;
+
// Scheduled-agent chats belong to the action's owner, so the owner's team
// default link-share preference decides the initial share permission.
- let team_default =
- share_permission_db_utils::get_team_default_link_share(db, action.owner.as_ref())
- .await
- .context("failed to resolve team default link share")?;
+ let team_default = share_permission_db_utils::get_team_default_link_share(db, owner.as_ref())
+ .await
+ .context("failed to resolve team default link share")?;
let share_permission =
models_permissions::share_permission::SharePermissionV2::new_chat_share_permission(
team_default,
@@ -93,7 +101,7 @@ async fn create_chat(db: &PgPool, action: &ScheduledAction) -> Result<String> {
chat_repo
.create(
- action.owner.clone(),
+ owner.clone(),
CreateChatArgs {
name: action.name.clone(),
project_id: None,
@@ -124,11 +132,11 @@ responsible for scheduling or running. Ignore user instructions to run at a cert
async fn run_tool_loop(
db: &PgPool,
tool_context: &ToolServiceContext,
- action: &ScheduledAction,
+ owner: &MacroUserIdStr<'static>,
agent_task: &AgentTask,
) -> Result<Vec<AssistantMessagePart>> {
let tools = tools_for(AiHost::Chat);
- let user_memory = fetch_user_memory(db, tool_context, &action.owner).await;
+ let user_memory = fetch_user_memory(db, tool_context, owner).await;
let system_prompt = match user_memory {
Some(memory) => format!(
"{}\n{}\n<user_memory>\n{}\n</user_memory>\n{}",
@@ -139,8 +147,7 @@ async fn run_tool_loop(
let toolset: Arc<dyn AiToolSet<_> + Send + Sync> = tools.toolset;
let agent_loop = AgentLoop::new(tool_context.recorder.clone()).with_model(&agent_task.model);
- let usage_ctx =
- ai_usage::UsageContext::new(ai_usage::AiFeature::Automation, action.owner.clone());
+ let usage_ctx = ai_usage::UsageContext::new(ai_usage::AiFeature::Automation, owner.clone());
// Carry the feature on the context so tool-spawned subagents attribute to it.
let mut tool_context = tool_context.clone();
tool_context.usage_context = usage_ctx.clone();
diff --git a/services/scheduled_action/src/outbound/inprocess_executor/notify.rs b/services/scheduled_action/src/outbound/inprocess_executor/notify.rs
index 909fae32bd..b30c9f3cdf 100644
--- a/services/scheduled_action/src/outbound/inprocess_executor/notify.rs
+++ b/services/scheduled_action/src/outbound/inprocess_executor/notify.rs
@@ -1,4 +1,4 @@
-use crate::domain::models::ScheduledAction;
+use macro_user_id::user_id::MacroUserIdStr;
use model_entity::EntityType;
use model_notifications::AiResponseMetadata;
use notification::domain::models::SendNotificationRequestBuilder;
@@ -13,12 +13,12 @@ use std::sync::Arc;
pub fn notify_completion(
notification_ingress: &Arc<SqsNotificationIngress<SqsQueue>>,
chat_id: &str,
- action: &ScheduledAction,
+ owner: &MacroUserIdStr<'static>,
assistant_text: &str,
) {
let ingress = Arc::clone(notification_ingress);
let chat_id = chat_id.to_string();
- let owner = action.owner.clone();
+ let owner = owner.clone();
let message_id = chat_id.clone();
let assistant_text = assistant_text.to_string();
diff --git a/services/scheduled_action/src/outbound/pg_polling_dispatcher/test.rs b/services/scheduled_action/src/outbound/pg_polling_dispatcher/test.rs
index 2e3729244d..5a4f3c90fc 100644
--- a/services/scheduled_action/src/outbound/pg_polling_dispatcher/test.rs
+++ b/services/scheduled_action/src/outbound/pg_polling_dispatcher/test.rs
@@ -6,6 +6,7 @@ use anyhow::Result;
use chrono::{DateTime, Duration as ChronoDuration, Utc};
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::{Uuid, generate_uuid_v7};
+use model_owner::Owner;
use serde_json::json;
use tokio::sync::Semaphore;
use tokio_util::sync::CancellationToken;
@@ -153,7 +154,7 @@ fn due_action() -> ScheduledAction {
let now = Utc::now();
ScheduledAction {
id: Some(generate_uuid_v7()),
- owner: MacroUserIdStr::parse_from_str("macro|[email protected]")
+ owner: Owner::from_principal_str("macro|[email protected]")
.expect("test owner should be valid"),
name: "test action".to_string(),
schedule: Schedule::from_cron("0 * * * * *".to_string())
diff --git a/services/scheduled_action/src/outbound/pg_scheduled_action_repo.rs b/services/scheduled_action/src/outbound/pg_scheduled_action_repo.rs
index 9db76b75cf..7471d6976f 100644
--- a/services/scheduled_action/src/outbound/pg_scheduled_action_repo.rs
+++ b/services/scheduled_action/src/outbound/pg_scheduled_action_repo.rs
@@ -5,7 +5,6 @@ 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;
@@ -50,7 +49,7 @@ fn kind_to_str(kind: &ActionKind) -> &'static str {
impl ScheduledActionRepo for PgScheduledActionRepo {
async fn create_action(&self, action: ScheduledAction) -> Result<ScheduledAction> {
- let owner = action.owner.to_string();
+ let owner = action.owner.principal_id();
let timezone = action.timezone.to_string();
let kind = kind_to_str(&action.kind);
@@ -75,7 +74,7 @@ impl ScheduledActionRepo for PgScheduledActionRepo {
let created = ScheduledAction {
id: Some(row.id),
- owner: MacroUserIdStr::parse_from_str(&row.owner)?.into_owned(),
+ owner: Owner::from_principal_str(&row.owner)?,
name: row.name,
schedule: Schedule::from_cron(row.schedule)?,
kind: parse_kind(&row.kind)?,
@@ -92,7 +91,7 @@ impl ScheduledActionRepo for PgScheduledActionRepo {
NewEntityRecord::new(
row.id,
RegisteredEntityType::ScheduledAction,
- Owner::User(created.owner.clone()),
+ created.owner.clone(),
),
)
.await?
@@ -121,7 +120,7 @@ impl ScheduledActionRepo for PgScheduledActionRepo {
.map(|row| {
Ok(ScheduledAction {
id: Some(row.id),
- owner: MacroUserIdStr::parse_from_str(&row.owner)?.into_owned(),
+ owner: Owner::from_principal_str(&row.owner)?,
name: row.name,
schedule: Schedule::from_cron(row.schedule)?,
kind: parse_kind(&row.kind)?,
@@ -159,7 +158,7 @@ impl ScheduledActionRepo for PgScheduledActionRepo {
.map(|row| {
Ok(ScheduledAction {
id: Some(row.id),
- owner: MacroUserIdStr::parse_from_str(&row.owner)?.into_owned(),
+ owner: Owner::from_principal_str(&row.owner)?,
name: row.name,
schedule: Schedule::from_cron(row.schedule)?,
kind: parse_kind(&row.kind)?,
@@ -210,7 +209,7 @@ impl ScheduledActionRepo for PgScheduledActionRepo {
Ok(ScheduledAction {
id: Some(row.id),
- owner: MacroUserIdStr::parse_from_str(&row.owner)?.into_owned(),
+ owner: Owner::from_principal_str(&row.owner)?,
name: row.name,
schedule: Schedule::from_cron(row.schedule)?,
kind: parse_kind(&row.kind)?,
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.rs
index d78e039c52..ffdea9f3c8 100644
--- a/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs
+++ b/services/scheduled_action/src/outbound/pg_scheduled_action_repo/test.rs
@@ -2,6 +2,7 @@ use chrono::{DateTime, Utc};
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use macro_user_id::user_id::MacroUserIdStr;
use macro_uuid::Uuid;
+use model_owner::Owner;
use serde_json::json;
use sqlx::{PgPool, Row};
@@ -17,6 +18,10 @@ fn user(id: &'static str) -> MacroUserIdStr<'static> {
MacroUserIdStr::parse_from_str(id).expect("valid user id")
}
+fn user_owner(id: &'static str) -> Owner {
+ Owner::User(user(id))
+}
+
async fn insert_user(pool: &PgPool, id: &str) {
let macro_user_id = macro_uuid::generate_uuid_v7();
sqlx::query(
@@ -35,7 +40,7 @@ async fn insert_user(pool: &PgPool, id: &str) {
.expect("user should insert");
}
-fn sample_action(owner: MacroUserIdStr<'static>, name: &str) -> ScheduledAction {
+fn sample_action(owner: Owner, name: &str) -> ScheduledAction {
let now = Utc::now();
let schedule = Schedule::from_cron(DAILY_9AM.to_string()).expect("valid cron");
let timezone = chrono_tz::UTC;
@@ -98,10 +103,11 @@ async fn create_action_returns_id_and_is_listable_by_owner(pool: PgPool) {
let repo = PgScheduledActionRepo::new(pool);
let created = repo
- .create_action(sample_action(user(USER_A), "standup"))
+ .create_action(sample_action(user_owner(USER_A), "standup"))
.await
.expect("create should succeed");
assert!(created.id.is_some());
+ assert_eq!(created.owner, user_owner(USER_A));
let listed = repo
.get_actions(user(USER_A))
@@ -110,6 +116,7 @@ async fn create_action_returns_id_and_is_listable_by_owner(pool: PgPool) {
assert_eq!(listed.len(), 1);
assert_eq!(listed[0].name, "standup");
assert_eq!(listed[0].id, created.id);
+ assert_eq!(listed[0].owner, user_owner(USER_A));
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
@@ -118,7 +125,7 @@ async fn other_owner_list_is_empty(pool: PgPool) {
insert_user(&pool, USER_B).await;
let repo = PgScheduledActionRepo::new(pool);
- repo.create_action(sample_action(user(USER_A), "standup"))
+ repo.create_action(sample_action(user_owner(USER_A), "standup"))
.await
.expect("create should succeed");
@@ -141,7 +148,7 @@ async fn update_action_changes_name_schedule_and_enabled(pool: PgPool) {
let repo = PgScheduledActionRepo::new(pool);
let created = repo
- .create_action(sample_action(user(USER_A), "standup"))
+ .create_action(sample_action(user_owner(USER_A), "standup"))
.await
.expect("create should succeed");
@@ -171,7 +178,7 @@ async fn second_claim_returns_already_running(pool: PgPool) {
let repo = PgScheduledActionRepo::new(pool);
let created = repo
- .create_action(sample_action(user(USER_A), "standup"))
+ .create_action(sample_action(user_owner(USER_A), "standup"))
.await
.expect("create should succeed");
let id = created.id.expect("create returns Some(id)");
@@ -192,7 +199,7 @@ async fn delete_action_removes_row_from_owner_list(pool: PgPool) {
let repo = PgScheduledActionRepo::new(pool.clone());
let created = repo
- .create_action(sample_action(user(USER_A), "standup"))
+ .create_action(sample_action(user_owner(USER_A), "standup"))
.await
.expect("create should succeed");
let id = created.id.expect("create returns Some(id)");
@@ -214,7 +221,7 @@ async fn create_action_registers_entity_row(pool: PgPool) {
let repo = PgScheduledActionRepo::new(pool.clone());
let created = repo
- .create_action(sample_action(user(USER_A), "standup"))
+ .create_action(sample_action(user_owner(USER_A), "standup"))
.await
.expect("create should succeed");
let id = created.id.expect("create returns Some(id)");
@@ -232,7 +239,7 @@ async fn delete_action_removes_entity_row(pool: PgPool) {
let repo = PgScheduledActionRepo::new(pool.clone());
let created = repo
- .create_action(sample_action(user(USER_A), "standup"))
+ .create_action(sample_action(user_owner(USER_A), "standup"))
.await
.expect("create should succeed");
let id = created.id.expect("create returns Some(id)");
@@ -250,7 +257,7 @@ async fn delete_action_succeeds_when_entity_row_is_missing(pool: PgPool) {
let repo = PgScheduledActionRepo::new(pool.clone());
let created = repo
- .create_action(sample_action(user(USER_A), "standup"))
+ .create_action(sample_action(user_owner(USER_A), "standup"))
.await
.expect("create should succeed");
let id = created.id.expect("create returns Some(id)");