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(multi-inbox): narrow-graph dispatch for cross-account inbox add (#3614)
gbirman1a7906665040
diff --git a/js/app/packages/service-clients/service-email/generated/schemas/index.ts b/js/app/packages/service-clients/service-email/generated/schemas/index.tsindex 3623381c7d..0bc64427b4 100644--- a/js/app/packages/service-clients/service-email/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-email/generated/schemas/index.ts@@ -174,6 +174,7 @@ export * from './getThreadMessagesHandlerParams';export * from './getThreadParams';export * from './getThreadResponse';export * from './initResponse';+export * from './initResponseBackfillJobId';export * from './initUserParams';export * from './label';export * from './labelId';diff --git a/js/app/packages/service-clients/service-email/generated/schemas/initResponse.ts b/js/app/packages/service-clients/service-email/generated/schemas/initResponse.tsindex 335bcf52b8..87be334052 100644--- a/js/app/packages/service-clients/service-email/generated/schemas/initResponse.ts+++ b/js/app/packages/service-clients/service-email/generated/schemas/initResponse.ts@@ -4,8 +4,14 @@* email_service* OpenAPI spec version: 0.1.0*/+import type { InitResponseBackfillJobId } from './initResponseBackfillJobId';export interface InitResponse {- backfill_job_id: string;+ /** Present when init enqueued a backfill job. Absent for the graph path,+where the child link's backfill already ran under its own macro_id. */+ backfill_job_id?: InitResponseBackfillJobId;+ /** The email_links row id for the now-accessible inbox. For the graph path+(cross-account add) this is the *existing* child link the caller now+delegates over; for the data-source path it's a freshly upserted row. */link_id: string;}diff --git a/js/app/packages/service-clients/service-email/generated/schemas/initResponseBackfillJobId.ts b/js/app/packages/service-clients/service-email/generated/schemas/initResponseBackfillJobId.tsnew file mode 100644index 0000000000..69a6dee19e--- /dev/null+++ b/js/app/packages/service-clients/service-email/generated/schemas/initResponseBackfillJobId.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * email_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Present when init enqueued a backfill job. Absent for the graph path,+where the child link's backfill already ran under its own macro_id.+ */+export type InitResponseBackfillJobId = string | null;diff --git a/js/app/packages/service-clients/service-email/openapi.json b/js/app/packages/service-clients/service-email/openapi.jsonindex 28333f7640..142f47ac4d 100644--- a/js/app/packages/service-clients/service-email/openapi.json+++ b/js/app/packages/service-clients/service-email/openapi.json@@ -3896,15 +3896,17 @@},"InitResponse": {"type": "object",- "required": ["link_id", "backfill_job_id"],+ "required": ["link_id"],"properties": {"backfill_job_id": {- "type": "string",- "format": "uuid"+ "type": ["string", "null"],+ "format": "uuid",+ "description": "Present when init enqueued a backfill job. Absent for the graph path,\nwhere the child link's backfill already ran under its own macro_id."},"link_id": {"type": "string",- "format": "uuid"+ "format": "uuid",+ "description": "The email_links row id for the now-accessible inbox. For the graph path\n(cross-account add) this is the *existing* child link the caller now\ndelegates over; for the data-source path it's a freshly upserted row."}}},diff --git a/rust/cloud-storage/.sqlx/query-012063ce1220cd6f1b04eeefa088324d50ac472be760c0efe10b5060b0878c75.json b/rust/cloud-storage/.sqlx/query-012063ce1220cd6f1b04eeefa088324d50ac472be760c0efe10b5060b0878c75.jsonnew file mode 100644index 0000000000..4a8de045bb--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-012063ce1220cd6f1b04eeefa088324d50ac472be760c0efe10b5060b0878c75.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT child_macro_id\n FROM macro_user_links\n WHERE primary_macro_id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "child_macro_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "012063ce1220cd6f1b04eeefa088324d50ac472be760c0efe10b5060b0878c75"+}diff --git a/rust/cloud-storage/.sqlx/query-11ac63a8975bc8587b4c3b8f64201b8999a0cec4a928d253fb4fa49f78a8626e.json b/rust/cloud-storage/.sqlx/query-11ac63a8975bc8587b4c3b8f64201b8999a0cec4a928d253fb4fa49f78a8626e.jsonnew file mode 100644index 0000000000..9d4460d0dd--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-11ac63a8975bc8587b4c3b8f64201b8999a0cec4a928d253fb4fa49f78a8626e.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO macro_user_links (primary_macro_id, child_macro_id)\n VALUES ($1, $2)\n ON CONFLICT (primary_macro_id, child_macro_id) DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "11ac63a8975bc8587b4c3b8f64201b8999a0cec4a928d253fb4fa49f78a8626e"+}diff --git a/rust/cloud-storage/.sqlx/query-547e3772bb1def3090b8647fcec5795696c6d02cbabc4619d6c384bfb5bff330.json b/rust/cloud-storage/.sqlx/query-547e3772bb1def3090b8647fcec5795696c6d02cbabc4619d6c384bfb5bff330.jsonnew file mode 100644index 0000000000..9ddc4e92bd--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-547e3772bb1def3090b8647fcec5795696c6d02cbabc4619d6c384bfb5bff330.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM macro_user_links\n WHERE primary_macro_id = $1\n AND child_macro_id = $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "547e3772bb1def3090b8647fcec5795696c6d02cbabc4619d6c384bfb5bff330"+}diff --git a/rust/cloud-storage/.sqlx/query-7bdcbf27b9edb2a2efc0e30c83230f6400385b295a50b48776985089d6ae3c84.json b/rust/cloud-storage/.sqlx/query-7bdcbf27b9edb2a2efc0e30c83230f6400385b295a50b48776985089d6ae3c84.jsonnew file mode 100644index 0000000000..ee23701453--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-7bdcbf27b9edb2a2efc0e30c83230f6400385b295a50b48776985089d6ae3c84.json@@ -0,0 +1,73 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT id as \"id!\", macro_id as \"macro_id!\",\n fusionauth_user_id as \"fusionauth_user_id!\",\n email_address as \"email_address!\",\n provider as \"provider!: _\",\n is_sync_active as \"is_sync_active!\",\n created_at as \"created_at!\",\n updated_at as \"updated_at!\"\n FROM (\n SELECT el.id, el.macro_id, el.fusionauth_user_id, el.email_address,\n el.provider, el.is_sync_active, el.created_at, el.updated_at\n FROM email_links el\n WHERE el.macro_id = $1\n UNION\n SELECT el.id, el.macro_id, el.fusionauth_user_id, el.email_address,\n el.provider, el.is_sync_active, el.created_at, el.updated_at\n FROM email_links el\n JOIN macro_user_links mul ON el.macro_id = mul.child_macro_id\n WHERE mul.primary_macro_id = $1\n ) AS combined\n ORDER BY created_at DESC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id!",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "macro_id!",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "fusionauth_user_id!",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "email_address!",+ "type_info": "Varchar"+ },+ {+ "ordinal": 4,+ "name": "provider!: _",+ "type_info": {+ "Custom": {+ "name": "email_user_provider_enum",+ "kind": {+ "Enum": [+ "GMAIL"+ ]+ }+ }+ }+ },+ {+ "ordinal": 5,+ "name": "is_sync_active!",+ "type_info": "Bool"+ },+ {+ "ordinal": 6,+ "name": "created_at!",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 7,+ "name": "updated_at!",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ null,+ null,+ null,+ null,+ null,+ null,+ null,+ null+ ]+ },+ "hash": "7bdcbf27b9edb2a2efc0e30c83230f6400385b295a50b48776985089d6ae3c84"+}diff --git a/rust/cloud-storage/authentication_service/src/api/merge/verify_merge_request.rs b/rust/cloud-storage/authentication_service/src/api/merge/verify_merge_request.rsindex ac766fa8a2..dff81e8882 100644--- a/rust/cloud-storage/authentication_service/src/api/merge/verify_merge_request.rs+++ b/rust/cloud-storage/authentication_service/src/api/merge/verify_merge_request.rs@@ -145,6 +145,7 @@ pub async fn handler(identity_provider_user_id: Cow::Borrowed(&link.identity_provider_user_id),user_id: Cow::Borrowed(&user_context.fusion_user_id),token: Cow::Borrowed(&link.token),+ data: None,},}).collect::<Vec<_>>();diff --git a/rust/cloud-storage/authentication_service/src/api/oauth2/google.rs b/rust/cloud-storage/authentication_service/src/api/oauth2/google.rsindex 27329967dd..aef6330f2c 100644--- a/rust/cloud-storage/authentication_service/src/api/oauth2/google.rs+++ b/rust/cloud-storage/authentication_service/src/api/oauth2/google.rs@@ -19,7 +19,9 @@ use crate::api::{},};use fusionauth::error::FusionAuthClientError;-use fusionauth::identity_provider::{IdentityProviderLink, LinkUserRequest};+use fusionauth::identity_provider::{+ IdentityProviderLink, IdentityProviderLinkData, IdentityProviderLinkRole, LinkUserRequest,+};async fn link_user(ctx: &ApiContext,@@ -62,21 +64,15 @@ async fn link_user()})?;- // Reject account-merge attempts: a different macro user already owns this email.- // Same-user re-linking (e.g. user adds their primary Gmail again) is allowed — init's- // idempotency check on email_links will short-circuit downstream.- if let Some(existing_macro_user_id) =- macro_db_client::user::get::get_macro_user_id_by_email(&ctx.db, &user_info_email)- .await- .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))?- && existing_macro_user_id != macro_user_id- {- return Err((- StatusCode::NOT_IMPLEMENTED,- "user profile already exists".to_string(),- ));- }-+ // Attempt to create the FA IdP link for the calling user. Three terminal cases:+ // Ok → fresh link created; data-source path downstream.+ // Err(alreadyLinked, owned by self) → idempotent relink; data-source path no-ops downstream.+ // Err(alreadyLinked, owned by other) → cross-account add; init promotes to graph edge.+ // The FA error doesn't distinguish self vs other in the typed variant, but it doesn't need+ // to — init re-derives ownership via macrodb's User table to pick its dispatch path.+ // Any link we create here is a secondary inbox-add (the primary FA link was already+ // created at signup). Tag accordingly so login routing can reject sign-in attempts+ // against this link — enforcement lands in a follow-up; this PR only writes the tag.match ctx.auth_client.link_user(LinkUserRequest {@@ -86,13 +82,14 @@ async fn link_user(identity_provider_user_id: Cow::Borrowed(&user_info.sub),user_id: Cow::Borrowed(¯o_user_id.to_string()),token: Cow::Borrowed(&token_response.refresh_token),+ data: Some(IdentityProviderLinkData {+ role: Some(IdentityProviderLinkRole::Secondary),+ }),},}).await{Ok(()) => {}- // Same Google identity already linked to this FA user → init's idempotency- // check on email_links will short-circuit downstream. No-op.Err(FusionAuthClientError::IdentityProviderLinkAlreadyExists) => {tracing::info!(fusion_user_id = %macro_user_id,diff --git a/rust/cloud-storage/email_db_client/src/links/get.rs b/rust/cloud-storage/email_db_client/src/links/get.rsindex f6b8eb2bda..c1e440b596 100644--- a/rust/cloud-storage/email_db_client/src/links/get.rs+++ b/rust/cloud-storage/email_db_client/src/links/get.rs@@ -64,6 +64,56 @@ pub async fn fetch_link_by_macro_id(Ok(db_link.map(service::link::Link::try_from).transpose()?)}+/// Fetches all email_links the user can access via their macro_id, including any+/// inboxes delegated via macro_user_links. The union is the read-side half of the+/// multi-inbox narrow-graph design — it surfaces both the user's own inboxes+/// (same macro_id) and inboxes belonging to other macro users they've been delegated.+#[tracing::instrument(skip(pool), err)]+pub async fn fetch_inboxes_for_macro_id(+ pool: &PgPool,+ macro_id: &str,+) -> anyhow::Result<Vec<link::Link>> {+ if macro_id.is_empty() {+ anyhow::bail!("macro_id cannot be empty");+ }++ let db_links = sqlx::query_as!(+ DbLink,+ r#"+ SELECT id as "id!", macro_id as "macro_id!",+ fusionauth_user_id as "fusionauth_user_id!",+ email_address as "email_address!",+ provider as "provider!: _",+ is_sync_active as "is_sync_active!",+ created_at as "created_at!",+ updated_at as "updated_at!"+ FROM (+ SELECT el.id, el.macro_id, el.fusionauth_user_id, el.email_address,+ el.provider, el.is_sync_active, el.created_at, el.updated_at+ FROM email_links el+ WHERE el.macro_id = $1+ UNION+ SELECT el.id, el.macro_id, el.fusionauth_user_id, el.email_address,+ el.provider, el.is_sync_active, el.created_at, el.updated_at+ FROM email_links el+ JOIN macro_user_links mul ON el.macro_id = mul.child_macro_id+ WHERE mul.primary_macro_id = $1+ ) AS combined+ ORDER BY created_at DESC+ "#,+ macro_id+ )+ .fetch_all(pool)+ .await?;++ let service_links: Result<Vec<_>, _> = db_links+ .into_iter()+ .map(service::link::Link::try_from)+ .collect();++ Ok(service_links?)+}+/// fetches email_links given a fusionauth_user_id. a fusionauth_user_id can have multiple email_links, each with a unique macro_id#[tracing::instrument(skip(pool), err)]pub async fn fetch_links_by_fusionauth_user_id(diff --git a/rust/cloud-storage/email_service/src/api/email/init.rs b/rust/cloud-storage/email_service/src/api/email/init.rsindex b466d505b9..a18ff1abbb 100644--- a/rust/cloud-storage/email_service/src/api/email/init.rs+++ b/rust/cloud-storage/email_service/src/api/email/init.rs@@ -66,8 +66,14 @@ impl IntoResponse for InitError {#[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)]pub struct InitResponse {+ /// The email_links row id for the now-accessible inbox. For the graph path+ /// (cross-account add) this is the *existing* child link the caller now+ /// delegates over; for the data-source path it's a freshly upserted row.pub link_id: Uuid,- pub backfill_job_id: Uuid,+ /// Present when init enqueued a backfill job. Absent for the graph path,+ /// where the child link's backfill already ran under its own macro_id.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub backfill_job_id: Option<Uuid>,}#[derive(Debug, serde::Deserialize)]@@ -124,6 +130,70 @@ pub async fn handler(InitError::BadRequest("link has not completed authentication yet".to_string())})?;+ // Dispatch on whether the linked email already belongs to another macro user.+ // Same-user → fall through to the data-source path. Cross-user → add a graph+ // edge instead of creating a duplicate email_links row.+ //+ // Distinguish "no user with this email" (Ok(None)) from a transient DB error+ // (Err) — collapsing the latter to None would silently fall through to the+ // data-source upsert path and create a duplicate email_links row.+ let existing_owner =+ match macro_db_client::user::get::get_user_id_by_email(ctx.db.clone(), &linked_email)+ .await+ {+ Ok(macro_id) => Some(macro_id),+ Err(sqlx::Error::RowNotFound) => None,+ Err(e) => {+ return Err(InitError::DatabaseError(+ anyhow::Error::from(e)+ .context("Failed to look up existing macro user by linked_email"),+ ));+ }+ };++ if let Some(child_macro_id) = existing_owner.as_deref()+ && child_macro_id != user_context.user_id+ {+ // Graph path: link primary (caller) → child so primary can read child's inbox.+ macro_db_client::macro_user_links::insert_edge(+ &ctx.db,+ &user_context.user_id,+ child_macro_id,+ )+ .await+ .context("Failed to insert macro_user_links edge")?;++ macro_db_client::in_progress_user_link::delete_in_progress_user_link(&ctx.db, &link_id)+ .await+ .inspect_err(|e| {+ tracing::error!(error=?e, ?link_id, "Failed to delete in_progress_user_link after graph delegation");+ })+ .ok();++ let child_link = email_db_client::links::get::fetch_link_by_email(+ &ctx.db,+ &linked_email,+ link::UserProvider::Gmail,+ )+ .await+ .context("Failed to look up child link after delegation")?+ .ok_or_else(|| {+ InitError::BadRequest(+ "child macro user exists but has no email_links row".to_string(),+ )+ })?;++ return Ok((+ StatusCode::OK,+ Json(InitResponse {+ link_id: child_link.id,+ backfill_job_id: None,+ }),+ )+ .into_response());+ }++ // Data-source path (same-user re-link or brand-new email with no prior signup).if pg_repo.link_by_fusionauth_email_provider(&user_context.fusion_user_id,@@ -275,7 +345,7 @@ pub async fn handler(StatusCode::OK,Json(InitResponse {link_id: link.id,- backfill_job_id: backfill_job.id,+ backfill_job_id: Some(backfill_job.id),}),).into_response())diff --git a/rust/cloud-storage/email_service/src/api/email/links/list.rs b/rust/cloud-storage/email_service/src/api/email/links/list.rsindex 67bf6c4978..8faf18b0ac 100644--- a/rust/cloud-storage/email_service/src/api/email/links/list.rs+++ b/rust/cloud-storage/email_service/src/api/email/links/list.rs@@ -70,12 +70,10 @@ pub async fn list_links_handler(user_context: Extension<UserContext>,Query(query_params): Query<QueryParams>,) -> Result<Response, ListLinksError> {- let links = email_db_client::links::get::fetch_links_by_fusionauth_user_id(- &ctx.db,- &user_context.fusion_user_id,- )- .await- .map_err(ListLinksError::DatabaseError)?;+ let links =+ email_db_client::links::get::fetch_inboxes_for_macro_id(&ctx.db, &user_context.user_id)+ .await+ .map_err(ListLinksError::DatabaseError)?;let tasks = links.into_iter().map(|link| {let ctx = ctx.clone();diff --git a/rust/cloud-storage/fusionauth/src/identity_provider/link.rs b/rust/cloud-storage/fusionauth/src/identity_provider/link.rsindex e9f37f3124..42743ceffc 100644--- a/rust/cloud-storage/fusionauth/src/identity_provider/link.rs+++ b/rust/cloud-storage/fusionauth/src/identity_provider/link.rs@@ -115,6 +115,24 @@ pub(crate) async fn get_links(}}+/// Role this link plays in our application+#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, PartialEq, Eq)]+#[serde(rename_all = "lowercase")]+pub enum IdentityProviderLinkRole {+ /// Created at signup+ Primary,+ /// Created via /link/gmail+ Secondary,+}++/// Application metadata stored on the FA link+#[derive(serde::Serialize, serde::Deserialize, Debug, Default)]+pub struct IdentityProviderLinkData {+ /// Role+ #[serde(skip_serializing_if = "Option::is_none")]+ pub role: Option<IdentityProviderLinkRole>,+}+#[derive(serde::Serialize, serde::Deserialize, Debug)]#[serde(rename_all = "camelCase")]/// An identity provider link for creating a link.@@ -129,6 +147,9 @@ pub struct IdentityProviderLink<'a> {pub user_id: Cow<'a, str>,/// The tokenpub token: Cow<'a, str>,+ /// Application metadata+ #[serde(skip_serializing_if = "Option::is_none", default)]+ pub data: Option<IdentityProviderLinkData>,}#[derive(serde::Serialize, serde::Deserialize, Debug)]diff --git a/rust/cloud-storage/fusionauth/src/identity_provider/mod.rs b/rust/cloud-storage/fusionauth/src/identity_provider/mod.rsindex 61150fc5aa..f51a75a27a 100644--- a/rust/cloud-storage/fusionauth/src/identity_provider/mod.rs+++ b/rust/cloud-storage/fusionauth/src/identity_provider/mod.rs@@ -8,7 +8,10 @@ mod lookup;mod search;mod unlink;-pub use link::{IdentityProviderLink, Link, LinkUserRequest, RetrieveLinkResponse};+pub use link::{+ IdentityProviderLink, IdentityProviderLinkData, IdentityProviderLinkRole, Link,+ LinkUserRequest, RetrieveLinkResponse,+};impl FusionAuthClient {/// Searches for an identity provider by name and returns its ID.#[tracing::instrument(skip(self), fields(application_id=%self.client_id, fusion_auth_base_url=%self.fusion_auth_base_url))]diff --git a/rust/cloud-storage/github/src/outbound/github_auth_client.rs b/rust/cloud-storage/github/src/outbound/github_auth_client.rsindex 7f4eb8ec23..1519636d6e 100644--- a/rust/cloud-storage/github/src/outbound/github_auth_client.rs+++ b/rust/cloud-storage/github/src/outbound/github_auth_client.rs@@ -63,6 +63,7 @@ impl Auth for GithubAuthImpl {identity_provider_user_id: github_user_id.into(),user_id: fusionauth_user_id.to_string().into(),token: access_token.into(),+ data: None,},}).await?;diff --git a/rust/cloud-storage/macro_db_client/migrations/20260528154851_macro_user_links.sql b/rust/cloud-storage/macro_db_client/migrations/20260528154851_macro_user_links.sqlnew file mode 100644index 0000000000..9fccd99d6d--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260528154851_macro_user_links.sql@@ -0,0 +1,14 @@+-- Directed link between two macro_ids: primary holds an inbox-delegation over child.+-- Multi-inbox is currently the only consumer; the semantic ("primary can read child's+-- email_links") is implicit. If we ever need other capabilities we'll add a column then.+CREATE TABLE IF NOT EXISTS macro_user_links (+ primary_macro_id TEXT NOT NULL REFERENCES "User"("id") ON DELETE CASCADE,+ child_macro_id TEXT NOT NULL REFERENCES "User"("id") ON DELETE CASCADE,+ created_at TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ PRIMARY KEY (primary_macro_id, child_macro_id),+ CHECK (primary_macro_id <> child_macro_id)+);++-- Reverse lookup: "which primaries delegate from this child?"+CREATE INDEX IF NOT EXISTS macro_user_links_child_idx+ ON macro_user_links (child_macro_id);diff --git a/rust/cloud-storage/macro_db_client/src/lib.rs b/rust/cloud-storage/macro_db_client/src/lib.rsindex 59a538d47f..3f37aaf349 100644--- a/rust/cloud-storage/macro_db_client/src/lib.rs+++ b/rust/cloud-storage/macro_db_client/src/lib.rs@@ -24,6 +24,7 @@ pub mod items;pub mod job;pub mod macro_user;pub mod macro_user_email_verification;+pub mod macro_user_links;pub mod macros;pub mod notification;pub mod organization;diff --git a/rust/cloud-storage/macro_db_client/src/macro_user_links.rs b/rust/cloud-storage/macro_db_client/src/macro_user_links.rsnew file mode 100644index 0000000000..b5f3a9d20f--- /dev/null+++ b/rust/cloud-storage/macro_db_client/src/macro_user_links.rs@@ -0,0 +1,74 @@+//! Directed links between macro_ids. Used by multi-inbox so a primary macro user can+//! read another macro user's inbox without merging identities. The "what" of the+//! delegation is implicit — primary may read child's email_links rows.++use sqlx::{Pool, Postgres};++#[cfg(test)]+mod test;++/// Insert an edge `(primary, child)`. Idempotent: if the edge already exists+/// the conflict is swallowed.+#[tracing::instrument(skip(db), err)]+pub async fn insert_edge(+ db: &Pool<Postgres>,+ primary_macro_id: &str,+ child_macro_id: &str,+) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ INSERT INTO macro_user_links (primary_macro_id, child_macro_id)+ VALUES ($1, $2)+ ON CONFLICT (primary_macro_id, child_macro_id) DO NOTHING+ "#,+ primary_macro_id,+ child_macro_id,+ )+ .execute(db)+ .await?;++ Ok(())+}++/// Remove an edge. No-op if the edge does not exist.+#[tracing::instrument(skip(db), err)]+pub async fn delete_edge(+ db: &Pool<Postgres>,+ primary_macro_id: &str,+ child_macro_id: &str,+) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ DELETE FROM macro_user_links+ WHERE primary_macro_id = $1+ AND child_macro_id = $2+ "#,+ primary_macro_id,+ child_macro_id,+ )+ .execute(db)+ .await?;++ Ok(())+}++/// Returns the `child_macro_id`s the given primary delegates from.+/// Used by email-service to union linked inboxes with the user's own.+#[tracing::instrument(skip(db), err)]+pub async fn children_for_primary(+ db: &Pool<Postgres>,+ primary_macro_id: &str,+) -> anyhow::Result<Vec<String>> {+ let rows = sqlx::query_scalar!(+ r#"+ SELECT child_macro_id+ FROM macro_user_links+ WHERE primary_macro_id = $1+ "#,+ primary_macro_id+ )+ .fetch_all(db)+ .await?;++ Ok(rows)+}diff --git a/rust/cloud-storage/macro_db_client/src/macro_user_links/test.rs b/rust/cloud-storage/macro_db_client/src/macro_user_links/test.rsnew file mode 100644index 0000000000..34ff486616--- /dev/null+++ b/rust/cloud-storage/macro_db_client/src/macro_user_links/test.rs@@ -0,0 +1,89 @@+use super::*;++async fn insert_user(pool: &Pool<Postgres>, id: &str) -> anyhow::Result<()> {+ let macro_user_id = macro_uuid::generate_uuid_v7();+ let stripe_customer_id = format!("cus_{macro_user_id}");+ sqlx::query!(+ r#"+ INSERT INTO macro_user (id, username, email, stripe_customer_id)+ VALUES ($1, $2, $3, $4)+ "#,+ ¯o_user_id,+ id,+ id,+ stripe_customer_id,+ )+ .execute(pool)+ .await?;++ sqlx::query!(+ r#"+ INSERT INTO "User" (id, email, macro_user_id)+ VALUES ($1, $2, $3)+ "#,+ id,+ id,+ ¯o_user_id,+ )+ .execute(pool)+ .await?;++ Ok(())+}++#[sqlx::test]+async fn insert_then_list_children(pool: Pool<Postgres>) -> anyhow::Result<()> {+ insert_user(&pool, "macro|[email protected]").await?;+ insert_user(&pool, "macro|[email protected]").await?;+ insert_user(&pool, "macro|[email protected]").await?;++ insert_edge(&pool, "macro|[email protected]", "macro|[email protected]").await?;+ insert_edge(&pool, "macro|[email protected]", "macro|[email protected]").await?;++ let mut children = children_for_primary(&pool, "macro|[email protected]").await?;+ children.sort();+ assert_eq!(children, vec!["macro|[email protected]", "macro|[email protected]"]);++ Ok(())+}++#[sqlx::test]+async fn insert_is_idempotent(pool: Pool<Postgres>) -> anyhow::Result<()> {+ insert_user(&pool, "macro|[email protected]").await?;+ insert_user(&pool, "macro|[email protected]").await?;++ insert_edge(&pool, "macro|[email protected]", "macro|[email protected]").await?;+ insert_edge(&pool, "macro|[email protected]", "macro|[email protected]").await?;++ let children = children_for_primary(&pool, "macro|[email protected]").await?;+ assert_eq!(children, vec!["macro|[email protected]"]);++ Ok(())+}++#[sqlx::test]+async fn delete_edge_removes_row(pool: Pool<Postgres>) -> anyhow::Result<()> {+ insert_user(&pool, "macro|[email protected]").await?;+ insert_user(&pool, "macro|[email protected]").await?;++ insert_edge(&pool, "macro|[email protected]", "macro|[email protected]").await?;+ delete_edge(&pool, "macro|[email protected]", "macro|[email protected]").await?;++ let children = children_for_primary(&pool, "macro|[email protected]").await?;+ assert!(children.is_empty());++ Ok(())+}++#[sqlx::test]+async fn self_referential_edge_rejected(pool: Pool<Postgres>) -> anyhow::Result<()> {+ insert_user(&pool, "macro|[email protected]").await?;++ let result = insert_edge(&pool, "macro|[email protected]", "macro|[email protected]").await;+ assert!(+ result.is_err(),+ "self-referential edge should be rejected by CHECK constraint"+ );++ Ok(())+}