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(ownership): modelowner typed owner reference crate (#6358)

Will Hutchinsona92de1c5a4ff
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index b5362708ae..acfe3dbc7d 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -5627,6 +5627,13 @@
"crates/remote_env_var",
"crates/workspace-hack"
],
+ "model_owner": [
+ "crates/bot_id",
+ "crates/cowlike",
+ "crates/macro_user_id",
+ "crates/model_owner",
+ "crates/workspace-hack"
+ ],
"model_user": [
"crates/cowlike",
"crates/macro_user_id",
diff --git a/Cargo.lock b/Cargo.lock
index 784796e9a3..82e3aebd1f 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -10713,6 +10713,20 @@ dependencies = [
"workspace-hack",
]
+[[package]]
+name = "model_owner"
+version = "0.1.0"
+dependencies = [
+ "bot_id",
+ "macro_user_id",
+ "serde",
+ "serde_json",
+ "sqlx",
+ "thiserror 2.0.18",
+ "uuid",
+ "workspace-hack",
+]
+
[[package]]
name = "model_user"
version = "0.1.0"
diff --git a/Cargo.toml b/Cargo.toml
index 16f3e730fa..932425af2b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -60,6 +60,7 @@ members = [
"crates/macro_sync_service_jwt",
"crates/maybe_send",
"crates/memory",
+ "crates/model_owner",
"crates/mcp_select",
"crates/mcp_toolset",
"crates/notification_state",
diff --git a/crates/model_owner/Cargo.toml b/crates/model_owner/Cargo.toml
new file mode 100644
index 0000000000..d462bebcfb
--- /dev/null
+++ b/crates/model_owner/Cargo.toml
@@ -0,0 +1,20 @@
+[package]
+edition = "2024"
+name = "model_owner"
+publish = false
+version = "0.1.0"
+
+[features]
+sqlx = ["dep:sqlx"]
+
+[dependencies]
+bot_id = { path = "../bot_id" }
+macro_user_id = { path = "../macro_user_id" }
+serde = { workspace = true }
+sqlx = { workspace = true, optional = true }
+thiserror = { workspace = true }
+uuid = { workspace = true }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
+
+[dev-dependencies]
+serde_json = { workspace = true }
diff --git a/crates/model_owner/src/lib.rs b/crates/model_owner/src/lib.rs
new file mode 100644
index 0000000000..bdd8fad694
--- /dev/null
+++ b/crates/model_owner/src/lib.rs
@@ -0,0 +1,176 @@
+#![deny(missing_docs)]
+
+//! Typed owner reference for Macro entities.
+//!
+//! [`Owner`] is the domain value. [`OwnerType`] is the closed string set for
+//! the sqlx type `entity_owner_type` and the matching wire discriminator.
+//!
+//! ```
+//! use model_owner::{Owner, OwnerType};
+//!
+//! let owner = Owner::parse(OwnerType::User, "macro|[email protected]").unwrap();
+//! assert_eq!(owner.principal_id(), "macro|[email protected]");
+//! ```
+
+use std::fmt::{Display, Formatter, Result as FmtResult};
+use std::str::FromStr;
+
+use bot_id::{BotId, BotIdStr};
+use macro_user_id::cowlike::CowLike;
+use macro_user_id::user_id::MacroUserIdStr;
+use serde::{Deserialize, Serialize};
+use uuid::Uuid;
+
+#[cfg(test)]
+mod test;
+
+const USER_PRINCIPAL_PREFIX: &str = "macro|";
+const BOT_PRINCIPAL_PREFIX: &str = "bot|";
+const TEAM_UUID_HYPHENATED_LEN: usize = 36;
+
+const OWNER_TYPE_USER: &str = "user";
+const OWNER_TYPE_BOT: &str = "bot";
+const OWNER_TYPE_TEAM: &str = "team";
+
+/// Who owns an entity.
+#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(into = "String", try_from = "String")]
+pub enum Owner {
+ /// A Macro user (`macro|<email>`).
+ User(MacroUserIdStr<'static>),
+ /// A bot (`bot|<uuid>`).
+ Bot(BotId),
+ /// A team (hyphenated UUID, no prefix).
+ Team(Uuid),
+}
+
+/// Closed owner-type set for the sqlx type `entity_owner_type`.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
+#[serde(rename_all = "lowercase")]
+#[cfg_attr(feature = "sqlx", derive(sqlx::Type))]
+#[cfg_attr(
+ feature = "sqlx",
+ sqlx(type_name = "entity_owner_type", rename_all = "lowercase")
+)]
+pub enum OwnerType {
+ /// A Macro user.
+ User,
+ /// A bot.
+ Bot,
+ /// A team.
+ Team,
+}
+
+/// Error returned when an owner principal or type string cannot be parsed.
+#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
+#[error("invalid owner: {value}")]
+pub struct OwnerParseError {
+ value: String,
+}
+
+impl OwnerParseError {
+ fn invalid(value: &str) -> Self {
+ Self {
+ value: value.to_string(),
+ }
+ }
+}
+
+impl Owner {
+ /// Discriminator for this owner.
+ #[must_use]
+ pub fn owner_type(&self) -> OwnerType {
+ match self {
+ Self::User(_) => OwnerType::User,
+ Self::Bot(_) => OwnerType::Bot,
+ Self::Team(_) => OwnerType::Team,
+ }
+ }
+
+ /// Canonical principal string for this owner.
+ #[must_use]
+ pub fn principal_id(&self) -> String {
+ match self {
+ Self::User(user_id) => user_id.to_string(),
+ Self::Bot(bot_id) => bot_id.into_storage_id().to_string(),
+ Self::Team(team_id) => team_id.hyphenated().to_string(),
+ }
+ }
+
+ /// Parse a principal under a known [`OwnerType`].
+ ///
+ /// This is strict: the string must match that type's storage form.
+ pub fn parse(owner_type: OwnerType, value: &str) -> Result<Self, OwnerParseError> {
+ match owner_type {
+ OwnerType::User => MacroUserIdStr::parse_from_str(value)
+ .map(CowLike::into_owned)
+ .map(Self::User)
+ .map_err(|_| OwnerParseError::invalid(value)),
+ OwnerType::Bot => BotIdStr::parse_from_str(value)
+ .map(|bot_id| Self::Bot(bot_id.bot_id()))
+ .map_err(|_| OwnerParseError::invalid(value)),
+ OwnerType::Team => parse_hyphenated_uuid(value).map(Self::Team),
+ }
+ }
+
+ /// Parse a principal by prefix.
+ pub fn from_principal_str(value: &str) -> Result<Self, OwnerParseError> {
+ if value.starts_with(USER_PRINCIPAL_PREFIX) {
+ Self::parse(OwnerType::User, value)
+ } else if value.starts_with(BOT_PRINCIPAL_PREFIX) {
+ Self::parse(OwnerType::Bot, value)
+ } else {
+ Self::parse(OwnerType::Team, value)
+ }
+ }
+}
+
+impl From<Owner> for String {
+ fn from(value: Owner) -> Self {
+ value.principal_id()
+ }
+}
+
+impl TryFrom<String> for Owner {
+ type Error = OwnerParseError;
+
+ fn try_from(value: String) -> Result<Self, Self::Error> {
+ Self::from_principal_str(&value)
+ }
+}
+
+impl Display for OwnerType {
+ fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
+ f.write_str(match self {
+ Self::User => OWNER_TYPE_USER,
+ Self::Bot => OWNER_TYPE_BOT,
+ Self::Team => OWNER_TYPE_TEAM,
+ })
+ }
+}
+
+impl FromStr for OwnerType {
+ type Err = OwnerParseError;
+
+ fn from_str(value: &str) -> Result<Self, Self::Err> {
+ match value {
+ OWNER_TYPE_USER => Ok(Self::User),
+ OWNER_TYPE_BOT => Ok(Self::Bot),
+ OWNER_TYPE_TEAM => Ok(Self::Team),
+ _ => Err(OwnerParseError::invalid(value)),
+ }
+ }
+}
+
+fn parse_hyphenated_uuid(value: &str) -> Result<Uuid, OwnerParseError> {
+ if value.len() != TEAM_UUID_HYPHENATED_LEN {
+ return Err(OwnerParseError::invalid(value));
+ }
+ if !value
+ .bytes()
+ .all(|byte| byte.is_ascii_hexdigit() || byte == b'-')
+ {
+ return Err(OwnerParseError::invalid(value));
+ }
+ Uuid::parse_str(value).map_err(|_| OwnerParseError::invalid(value))
+}
diff --git a/crates/model_owner/src/test.rs b/crates/model_owner/src/test.rs
new file mode 100644
index 0000000000..c628af83b3
--- /dev/null
+++ b/crates/model_owner/src/test.rs
@@ -0,0 +1,127 @@
+use super::*;
+
+#[test]
+fn user_round_trip() {
+ let owner = Owner::parse(OwnerType::User, "macro|[email protected]").unwrap();
+
+ assert_eq!(owner.owner_type(), OwnerType::User);
+ assert_eq!(owner.principal_id(), "macro|[email protected]");
+ assert_eq!(
+ Owner::from_principal_str("macro|[email protected]").unwrap(),
+ owner
+ );
+ assert_eq!(
+ serde_json::to_value(&owner).unwrap(),
+ serde_json::Value::String("macro|[email protected]".to_string())
+ );
+}
+
+#[test]
+fn bot_round_trip() {
+ let owner = Owner::parse(OwnerType::Bot, "bot|00000000-0000-0000-0000-00000000a1a1").unwrap();
+
+ assert_eq!(owner.owner_type(), OwnerType::Bot);
+ assert_eq!(
+ owner.principal_id(),
+ "bot|00000000-0000-0000-0000-00000000a1a1"
+ );
+ assert_eq!(
+ owner,
+ Owner::Bot(BotId::new_from_uuid(
+ Uuid::parse_str("00000000-0000-0000-0000-00000000a1a1").unwrap()
+ ))
+ );
+ assert_eq!(
+ serde_json::to_value(&owner).unwrap(),
+ serde_json::Value::String("bot|00000000-0000-0000-0000-00000000a1a1".to_string())
+ );
+}
+
+#[test]
+fn team_round_trip() {
+ let owner = Owner::parse(OwnerType::Team, "01234567-89ab-cdef-0123-456789abcdef").unwrap();
+
+ assert_eq!(owner.owner_type(), OwnerType::Team);
+ assert_eq!(owner.principal_id(), "01234567-89ab-cdef-0123-456789abcdef");
+ assert_eq!(
+ serde_json::to_value(&owner).unwrap(),
+ serde_json::Value::String("01234567-89ab-cdef-0123-456789abcdef".to_string())
+ );
+}
+
+#[test]
+fn parse_rejects_bot_principal_as_user() {
+ assert!(Owner::parse(OwnerType::User, "bot|00000000-0000-0000-0000-00000000a1a1").is_err());
+}
+
+#[test]
+fn parse_rejects_user_principal_as_bot() {
+ assert!(Owner::parse(OwnerType::Bot, "macro|[email protected]").is_err());
+}
+
+#[test]
+fn parse_rejects_bare_uuid_as_bot() {
+ assert!(Owner::parse(OwnerType::Bot, "00000000-0000-0000-0000-00000000a1a1").is_err());
+}
+
+#[test]
+fn parse_rejects_bot_principal_as_team() {
+ assert!(Owner::parse(OwnerType::Team, "bot|00000000-0000-0000-0000-00000000a1a1").is_err());
+}
+
+#[test]
+fn parse_rejects_malformed_uuids() {
+ assert!(Owner::parse(OwnerType::Bot, "bot|not-a-uuid").is_err());
+ assert!(Owner::parse(OwnerType::Team, "not-a-uuid").is_err());
+}
+
+#[test]
+fn parse_rejects_non_canonical_uuids() {
+ assert!(Owner::parse(OwnerType::Team, "0123456789abcdef0123456789abcdef").is_err());
+ assert!(Owner::parse(OwnerType::Bot, "bot|0123456789abcdef0123456789abcdef").is_err());
+}
+
+#[test]
+fn owner_type_lowercase_round_trips() {
+ for (owner_type, expected) in [
+ (OwnerType::User, "user"),
+ (OwnerType::Bot, "bot"),
+ (OwnerType::Team, "team"),
+ ] {
+ assert_eq!(owner_type.to_string(), expected);
+ assert_eq!(expected.parse::<OwnerType>().unwrap(), owner_type);
+ assert_eq!(
+ serde_json::to_value(owner_type).unwrap(),
+ serde_json::Value::String(expected.to_string())
+ );
+ assert_eq!(
+ serde_json::from_value::<OwnerType>(serde_json::Value::String(expected.to_string()))
+ .unwrap(),
+ owner_type
+ );
+ }
+
+ assert!("unknown".parse::<OwnerType>().is_err());
+}
+
+#[test]
+fn from_principal_str_classifies_by_prefix() {
+ assert_eq!(
+ Owner::from_principal_str("macro|[email protected]")
+ .unwrap()
+ .owner_type(),
+ OwnerType::User
+ );
+ assert_eq!(
+ Owner::from_principal_str("bot|00000000-0000-0000-0000-00000000a1a1")
+ .unwrap()
+ .owner_type(),
+ OwnerType::Bot
+ );
+ assert_eq!(
+ Owner::from_principal_str("01234567-89ab-cdef-0123-456789abcdef")
+ .unwrap()
+ .owner_type(),
+ OwnerType::Team
+ );
+}