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.

7.7 KB
Raw Blame
//! PostgreSQL implementation of the [`GithubRepo`] port.

#[cfg(test)]
mod test;

use macro_user_id::cowlike::CowLike;
use macro_user_id::{
    lowercased::Lowercase,
    user_id::{MacroUserId, MacroUserIdStr},
};
use sqlx::PgPool;
use std::time::Duration;
use uuid::Uuid;

use crate::domain::{models::GithubLink, ports::GithubRepo};

/// PostgreSQL-backed github repository.
#[derive(Clone)]
pub struct PgGithubRepo {
    pool: PgPool,
    locks: PgPool,
}

impl PgGithubRepo {
    /// Create a new repository backed by the given connection pool.
    pub fn new(pool: PgPool) -> Self {
        // Locks span external HTTP calls; keep waiters out of the data pool.
        let locks = sqlx::postgres::PgPoolOptions::new()
            .max_connections(5)
            .acquire_timeout(Duration::from_secs(5))
            .connect_lazy_with(
                (*pool.connect_options())
                    .clone()
                    .options([("lock_timeout", "5s"), ("statement_timeout", "10s")]),
            );
        Self { locks, pool }
    }

    async fn lock(
        pool: &PgPool,
        key: &str,
    ) -> Result<sqlx::Transaction<'static, sqlx::Postgres>, sqlx::Error> {
        let mut guard = pool.begin().await?;
        sqlx::query!("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", key)
            .execute(&mut *guard)
            .await?;
        Ok(guard)
    }
}

impl GithubRepo for PgGithubRepo {
    type Err = sqlx::Error;
    type LinkGuard = sqlx::Transaction<'static, sqlx::Postgres>;

    #[tracing::instrument(skip(self, user_id), err)]
    async fn lock_user_link(&self, user_id: &str) -> Result<Self::LinkGuard, Self::Err> {
        Self::lock(&self.locks, &format!("github-link-user:{user_id}")).await
    }

    #[tracing::instrument(skip(self, guard), err)]
    async fn lock_github_account(
        &self,
        guard: &mut Self::LinkGuard,
        github_user_id: &str,
    ) -> Result<(), Self::Err> {
        let key = format!("github-link-account:{github_user_id}");
        sqlx::query!("SELECT pg_advisory_xact_lock(hashtextextended($1, 0))", key)
            .execute(&mut **guard)
            .await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_github_link_by_user_id<'a>(
        &self,
        macro_user_id: &MacroUserId<Lowercase<'a>>,
    ) -> Result<Option<GithubLink>, Self::Err> {
        sqlx::query!(
        r#"
        SELECT id, macro_id, fusionauth_user_id as "fusionauth_user_id: Uuid", github_username, github_user_id, created_at, updated_at
        FROM github_links
        WHERE macro_id = $1
        "#,
        macro_user_id.as_ref()
        )
        .try_map(|r| Ok(GithubLink{
                id: r.id,
                macro_id: MacroUserIdStr::parse_from_str(&r.macro_id)
                .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
                .into_owned(),
                fusionauth_user_id: r.fusionauth_user_id,
                github_username: r.github_username,
                github_user_id: r.github_user_id,
                created_at: r.created_at,
                updated_at: r.updated_at,
            }))
        .fetch_optional(&self.pool)
        .await
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_github_link_by_github_user_id(
        &self,
        github_user_id: &str,
    ) -> Result<Option<GithubLink>, Self::Err> {
        sqlx::query!(
        r#"
        SELECT id, macro_id, fusionauth_user_id as "fusionauth_user_id: Uuid", github_username, github_user_id, created_at, updated_at
        FROM github_links
        WHERE github_user_id = $1
        ORDER BY created_at ASC
        LIMIT 1
        "#,
        github_user_id
        )
        .try_map(|r| Ok(GithubLink{
                id: r.id,
                macro_id: MacroUserIdStr::parse_from_str(&r.macro_id)
                .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
                .into_owned(),
                fusionauth_user_id: r.fusionauth_user_id,
                github_username: r.github_username,
                github_user_id: r.github_user_id,
                created_at: r.created_at,
                updated_at: r.updated_at,
            }))
        .fetch_optional(&self.pool)
        .await
    }

    #[tracing::instrument(skip(self), err)]
    async fn count_github_links_by_github_user_id(
        &self,
        github_user_id: &str,
    ) -> Result<i64, Self::Err> {
        let count = sqlx::query_scalar!(
            r#"
            SELECT COUNT(*)
            FROM github_links
            WHERE github_user_id = $1
            "#,
            github_user_id
        )
        .fetch_one(&self.pool)
        .await?;

        Ok(count.unwrap_or(0))
    }

    #[tracing::instrument(skip(self), err)]
    async fn get_github_link_by_id(&self, id: &uuid::Uuid) -> Result<GithubLink, Self::Err> {
        let link = sqlx::query!(
        r#"
        SELECT id, macro_id, fusionauth_user_id as "fusionauth_user_id: Uuid", github_username, github_user_id, created_at, updated_at
        FROM github_links
        WHERE id = $1
        "#,
        id
        )
        .try_map(|r| Ok(GithubLink{
                id: r.id,
                macro_id: MacroUserIdStr::parse_from_str(&r.macro_id)
                .map_err(|e| sqlx::Error::Decode(Box::new(e)))?
                .into_owned(),
                fusionauth_user_id: r.fusionauth_user_id,
                github_username: r.github_username,
                github_user_id: r.github_user_id,
                created_at: r.created_at,
                updated_at: r.updated_at,
            }))
        .fetch_optional(&self.pool)
        .await?;

        match link {
            Some(l) => Ok(l),
            None => Err(sqlx::Error::RowNotFound),
        }
    }

    #[tracing::instrument(skip(self), err)]
    async fn insert_github_link(&self, link: &GithubLink) -> Result<(), Self::Err> {
        sqlx::query!(
                  r#"
                  INSERT INTO github_links (id, macro_id, fusionauth_user_id, github_username, github_user_id, created_at, updated_at)
                  VALUES ($1, $2, $3, $4, $5, $6, $7)
                  "#,
                  link.id,
                  link.macro_id.as_ref(),
                  link.fusionauth_user_id,
                  link.github_username,
                  link.github_user_id,
                  link.created_at,
                  link.updated_at,
              )
              .execute(&self.pool)
              .await?;

        Ok(())
    }

    #[tracing::instrument(skip(self), err)]
    async fn reassign_github_grant(
        &self,
        github_user_id: &str,
        previous_owner: &uuid::Uuid,
        new_owner: &uuid::Uuid,
    ) -> Result<(), Self::Err> {
        sqlx::query!(
            r#"
            UPDATE github_links
            SET fusionauth_user_id = $3, updated_at = NOW()
            WHERE github_user_id = $1 AND fusionauth_user_id = $2
            "#,
            github_user_id,
            previous_owner,
            new_owner,
        )
        .execute(&self.pool)
        .await?;
        Ok(())
    }

    #[tracing::instrument(skip(self), err)]
    async fn delete_in_progress_user_link(
        &self,
        in_progress_link_id: &uuid::Uuid,
    ) -> Result<(), Self::Err> {
        sqlx::query!(
            r#"
            DELETE FROM
                in_progress_user_link
            WHERE
                id = $1
        "#,
            in_progress_link_id
        )
        .execute(&self.pool)
        .await?;

        Ok(())
    }

    #[tracing::instrument(skip(self), err)]
    async fn delete_github_link(&self, link_id: &uuid::Uuid) -> Result<(), Self::Err> {
        sqlx::query!(
            r#"
            DELETE FROM github_links
            WHERE id = $1
            "#,
            link_id
        )
        .execute(&self.pool)
        .await?;

        Ok(())
    }
}