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
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};
use sqlx::{Pool, Postgres};
use crate::domain::models::GithubLink;
use crate::domain::ports::GithubRepo;
use crate::outbound::pg_github_repo::PgGithubRepo;
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("github_test_data"))
)]
async fn test_get_github_link_by_user_id(pool: Pool<Postgres>) {
let repo = PgGithubRepo::new(pool);
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
let link = repo
.get_github_link_by_user_id(&user_id.0)
.await
.unwrap()
.expect("fixture user has a github link");
assert_eq!(link.macro_id.as_ref(), "macro|[email protected]");
assert_eq!(link.github_username, "testuser");
assert_eq!(link.github_user_id, "12345");
assert_eq!(
link.fusionauth_user_id.to_string(),
"bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
);
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("github_test_data"))
)]
async fn test_get_github_link_by_user_id_not_found(pool: Pool<Postgres>) {
let repo = PgGithubRepo::new(pool);
let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
let result = repo.get_github_link_by_user_id(&user_id.0).await;
assert!(matches!(result, Ok(None)));
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("github_test_data"))
)]
async fn test_get_github_link_by_github_user_id(pool: Pool<Postgres>) {
let repo = PgGithubRepo::new(pool);
let link = repo
.get_github_link_by_github_user_id("12345")
.await
.unwrap()
.expect("fixture github account is linked");
assert_eq!(link.macro_id.as_ref(), "macro|[email protected]");
assert_eq!(link.github_username, "testuser");
assert_eq!(link.github_user_id, "12345");
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("github_test_data"))
)]
async fn test_get_github_link_by_github_user_id_not_found(pool: Pool<Postgres>) {
let repo = PgGithubRepo::new(pool);
let result = repo.get_github_link_by_github_user_id("99999").await;
assert!(matches!(result, Ok(None)));
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("github_test_data"))
)]
async fn test_get_github_link_by_id(pool: Pool<Postgres>) {
let repo = PgGithubRepo::new(pool);
let id = uuid::Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap();
let link = repo.get_github_link_by_id(&id).await.unwrap();
assert_eq!(link.macro_id.as_ref(), "macro|[email protected]");
assert_eq!(link.github_username, "testuser");
assert_eq!(link.github_user_id, "12345");
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("github_test_data"))
)]
async fn test_get_github_link_by_id_not_found(pool: Pool<Postgres>) {
let repo = PgGithubRepo::new(pool);
let id = uuid::Uuid::parse_str("dddddddd-dddd-dddd-dddd-dddddddddddd").unwrap();
let result = repo.get_github_link_by_id(&id).await;
assert!(matches!(result, Err(sqlx::Error::RowNotFound)));
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("github_insert_test_data"))
)]
async fn test_insert_github_link(pool: Pool<Postgres>) {
let repo = PgGithubRepo::new(pool.clone());
let now = chrono::Utc::now();
let link = GithubLink {
id: uuid::Uuid::parse_str("eeeeeeee-eeee-eeee-eeee-eeeeeeeeeeee").unwrap(),
macro_id: MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned(),
fusionauth_user_id: uuid::Uuid::parse_str("ffffffff-ffff-ffff-ffff-ffffffffffff").unwrap(),
github_username: "newuser".to_string(),
github_user_id: "67890".to_string(),
created_at: now,
updated_at: now,
};
repo.insert_github_link(&link).await.unwrap();
// Verify it was inserted by reading it back
let fetched = repo.get_github_link_by_id(&link.id).await.unwrap();
assert_eq!(fetched.macro_id.as_ref(), "macro|[email protected]");
assert_eq!(fetched.github_username, "newuser");
assert_eq!(fetched.github_user_id, "67890");
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("github_test_data"))
)]
async fn test_insert_github_link_shared_github_user_id_succeeds(pool: Pool<Postgres>) {
let repo = PgGithubRepo::new(pool);
let now = chrono::Utc::now();
let id = uuid::Uuid::new_v4();
let link = GithubLink {
id,
// Different macro user than the fixture owner of github_user_id 12345.
macro_id: MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned(),
fusionauth_user_id: uuid::Uuid::new_v4(),
github_username: "shareruser".to_string(),
github_user_id: "12345".to_string(), // same github account as fixture
created_at: now,
updated_at: now,
};
// A different macro user may now link the same github_user_id, since the
// unique constraint is on (macro_id, github_user_id) rather than github_user_id.
let result = repo.insert_github_link(&link).await;
assert!(result.is_ok());
// Confirm the row was actually persisted.
let fetched = repo.get_github_link_by_id(&id).await.unwrap();
assert_eq!(fetched.macro_id.as_ref(), "macro|[email protected]");
assert_eq!(fetched.github_user_id, "12345");
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("github_test_data"))
)]
async fn test_insert_github_link_duplicate_macro_and_github_user_id_fails(pool: Pool<Postgres>) {
let repo = PgGithubRepo::new(pool);
let now = chrono::Utc::now();
let link = GithubLink {
id: uuid::Uuid::new_v4(),
// Existing fixture user who already owns github_user_id 12345.
macro_id: MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned(),
fusionauth_user_id: uuid::Uuid::new_v4(),
github_username: "testuser".to_string(),
github_user_id: "12345".to_string(), // same (macro_id, github_user_id) as fixture
created_at: now,
updated_at: now,
};
// Re-using the same (macro_id, github_user_id) pair must violate the
// composite unique constraint.
let result = repo.insert_github_link(&link).await;
assert!(result.is_err());
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("github_test_data"))
)]
async fn test_get_github_link_by_github_user_id_returns_owner(pool: Pool<Postgres>) {
let repo = PgGithubRepo::new(pool);
// Insert a second link for github_user_id 12345 belonging to a different
// macro user, with a created_at strictly later than the fixture row
// (aaaa..., default/earlier timestamp) so the owner is unambiguous.
let later = chrono::Utc::now() + chrono::Duration::days(1);
let sharer_link = GithubLink {
id: uuid::Uuid::new_v4(),
macro_id: MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned(),
fusionauth_user_id: uuid::Uuid::new_v4(),
github_username: "shareruser".to_string(),
github_user_id: "12345".to_string(),
created_at: later,
updated_at: later,
};
repo.insert_github_link(&sharer_link).await.unwrap();
// The owner is the earliest-created row (the fixture row), not the sharer.
let link = repo
.get_github_link_by_github_user_id("12345")
.await
.unwrap()
.expect("fixture github account is linked");
assert_eq!(link.macro_id.as_ref(), "macro|[email protected]");
assert_eq!(link.github_username, "testuser");
assert_eq!(link.github_user_id, "12345");
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("github_test_data"))
)]
async fn test_count_github_links_by_github_user_id(pool: Pool<Postgres>) {
let repo = PgGithubRepo::new(pool);
// The fixture has a single row for github_user_id 12345.
let count = repo
.count_github_links_by_github_user_id("12345")
.await
.unwrap();
assert_eq!(count, 1);
// Add a second link for the same github account under a different macro user.
let now = chrono::Utc::now();
let sharer_link = GithubLink {
id: uuid::Uuid::new_v4(),
macro_id: MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned(),
fusionauth_user_id: uuid::Uuid::new_v4(),
github_username: "shareruser".to_string(),
github_user_id: "12345".to_string(),
created_at: now,
updated_at: now,
};
repo.insert_github_link(&sharer_link).await.unwrap();
let count = repo
.count_github_links_by_github_user_id("12345")
.await
.unwrap();
assert_eq!(count, 2);
// An absent github_user_id has no links.
let count = repo
.count_github_links_by_github_user_id("99999")
.await
.unwrap();
assert_eq!(count, 0);
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("github_test_data"))
)]
async fn test_delete_in_progress_user_link(pool: Pool<Postgres>) {
let repo = PgGithubRepo::new(pool.clone());
let id = uuid::Uuid::parse_str("cccccccc-cccc-cccc-cccc-cccccccccccc").unwrap();
repo.delete_in_progress_user_link(&id).await.unwrap();
// Verify it was deleted
let row = sqlx::query!("SELECT id FROM in_progress_user_link WHERE id = $1", id)
.fetch_optional(&pool)
.await
.unwrap();
assert!(row.is_none());
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("github_test_data"))
)]
async fn test_delete_github_link(pool: Pool<Postgres>) {
let repo = PgGithubRepo::new(pool.clone());
let id = uuid::Uuid::parse_str("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa").unwrap();
repo.delete_github_link(&id).await.unwrap();
// Verify it was deleted
let row = sqlx::query!("SELECT id FROM github_links WHERE id = $1", id)
.fetch_optional(&pool)
.await
.unwrap();
assert!(row.is_none());
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn test_delete_in_progress_user_link_nonexistent(pool: Pool<Postgres>) {
let repo = PgGithubRepo::new(pool);
let id = uuid::Uuid::parse_str("dddddddd-dddd-dddd-dddd-dddddddddddd").unwrap();
// Deleting a nonexistent row should not error (DELETE affects 0 rows)
repo.delete_in_progress_user_link(&id).await.unwrap();
}
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("github_test_data"))
)]
async fn reassign_grant_moves_all_sharers_without_overwriting_other_accounts_or_repairs(
pool: Pool<Postgres>,
) {
let repo = PgGithubRepo::new(pool);
let original = repo
.get_github_link_by_github_user_id("12345")
.await
.unwrap()
.unwrap();
let old_owner = original.fusionauth_user_id;
let new_owner = uuid::Uuid::from_u128(42);
let mut sharer = original.clone();
sharer.id = uuid::Uuid::from_u128(43);
sharer.macro_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
.unwrap()
.into_owned();
repo.insert_github_link(&sharer).await.unwrap();
let mut unrelated = original.clone();
unrelated.id = uuid::Uuid::from_u128(44);
unrelated.github_user_id = "67890".into();
repo.insert_github_link(&unrelated).await.unwrap();
repo.reassign_github_grant("12345", &old_owner, &new_owner)
.await
.unwrap();
// A late repair based on the former owner must not undo the completed repair.
repo.reassign_github_grant("12345", &old_owner, &uuid::Uuid::from_u128(45))
.await
.unwrap();
assert_eq!(
repo.get_github_link_by_id(&original.id)
.await
.unwrap()
.fusionauth_user_id,
new_owner
);
assert_eq!(
repo.get_github_link_by_id(&sharer.id)
.await
.unwrap()
.fusionauth_user_id,
new_owner
);
assert_eq!(
repo.get_github_link_by_id(&unrelated.id)
.await
.unwrap()
.fusionauth_user_id,
old_owner
);
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn link_guard_holds_user_and_shared_account_locks_until_operation_finishes(
pool: Pool<Postgres>,
) {
let repo = PgGithubRepo::new(pool.clone());
let mut guard = repo.lock_user_link("macro|[email protected]").await.unwrap();
repo.lock_github_account(&mut guard, "1").await.unwrap();
let mut other = pool.begin().await.unwrap();
for key in [
"github-link-user:macro|[email protected]",
"github-link-account:1",
] {
let locked = sqlx::query_scalar!(
r#"SELECT pg_try_advisory_xact_lock(hashtextextended($1, 0)) AS "locked!""#,
key
)
.fetch_one(&mut *other)
.await
.unwrap();
assert!(!locked);
}
guard.rollback().await.unwrap();
for key in [
"github-link-user:macro|[email protected]",
"github-link-account:1",
] {
let locked = sqlx::query_scalar!(
r#"SELECT pg_try_advisory_xact_lock(hashtextextended($1, 0)) AS "locked!""#,
key
)
.fetch_one(&mut *other)
.await
.unwrap();
assert!(locked);
}
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn contended_link_locks_time_out_and_release_the_waiters_user_lock(pool: Pool<Postgres>) {
let repo = PgGithubRepo::new(pool);
let mut owner = repo
.lock_user_link("macro|[email protected]")
.await
.unwrap();
repo.lock_github_account(&mut owner, "1").await.unwrap();
let user_error = tokio::time::timeout(
std::time::Duration::from_secs(15),
repo.lock_user_link("macro|[email protected]"),
)
.await
.expect("user lock wait must be bounded")
.unwrap_err();
assert_eq!(
user_error.as_database_error().unwrap().code().as_deref(),
Some("55P03")
);
let mut waiter = repo
.lock_user_link("macro|[email protected]")
.await
.unwrap();
let account_error = tokio::time::timeout(
std::time::Duration::from_secs(15),
repo.lock_github_account(&mut waiter, "1"),
)
.await
.expect("account lock wait must be bounded")
.unwrap_err();
assert_eq!(
account_error.as_database_error().unwrap().code().as_deref(),
Some("55P03")
);
drop(waiter);
// The failed transaction must not leave the waiter's user lock behind.
let recovered = repo
.lock_user_link("macro|[email protected]")
.await
.unwrap();
recovered.rollback().await.unwrap();
owner.rollback().await.unwrap();
repo.locks.close().await;
}