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.

12.7 KB
Raw Blame
use std::sync::Arc;

use analytics_client::AnalyticsClient;
use axum::extract::FromRef;
use channels::{
    domain::{
        service::ChannelServiceImpl,
        side_effects::{ChannelSideEffectService, SpawnedChannelEventDispatcher},
    },
    outbound::{
        connection_gateway_realtime::ConnectionGatewayChannelRealtimePublisher,
        contacts_dispatcher::ContactsChannelDispatcher,
        notification_sender::NotificationChannelSender,
        pg_channel_reference_share_permissions::PgChannelReferenceSharePermissions,
        pg_channels_repo::PgChannelsRepo, pg_side_effect_context::PgChannelSideEffectContext,
    },
};
use contacts::{domain::service::SqsContactsIngress, outbound::ingress::SqsContactsQueue};
use entity_access::domain::service::EntityAccessServiceImpl;
use entity_access::outbound::PgAccessRepository;
use foreign_entity::domain::service::ForeignEntityServiceImpl;
use foreign_entity::outbound::pg_foreign_entity_repo::PgForeignEntityRepo;
use github::domain::service::GithubLinkServiceImpl;
use github::outbound::github_auth_client::GithubAuthImpl;
use github::outbound::github_oauth_client::GithubOauthImpl;
use github::outbound::pg_github_repo::PgGithubRepo;
use github_pull_requests::{
    domain::service::GithubPullRequestServiceImpl,
    outbound::pg_github_pull_request_repo::PgGithubPullRequestRepo,
};
use gtm_invite::{
    domain::service::GtmInviteServiceImpl, outbound::pg_gtm_invite_repo::PgGtmInviteRepo,
};
use loops_client::LoopsClient;
use macro_auth::{InternalApiKey, middleware::decode_jwt::JwtValidationArgs};
use macro_authorization::{
    MacroAuthJwtValidator, MacroAuthorizationServiceImpl, MacroAuthorizationState,
};
use macro_cache_client::MacroCache;
use macro_env::Environment;
use macro_env_var::env_var;
use macro_event_broker::{KafkaEventPublisher, MacroEventBrokerService};
use native_app_service::{domain::service::NativeAppServiceImpl, outbound::DefaultBundleFetcher};
use notification::outbound::queue::SqsQueue;
use notification::{
    domain::service::SqsNotificationIngress, outbound::rate_limit::RedisRateLimitAdapter,
};
use rate_limit::domain::service::RateLimitServiceImpl;
use referral::{domain::service::ReferralServiceImpl, outbound::pg_referral_repo::PgReferralRepo};
use remote_env_var::LocalOrRemoteSecret;
use roles_and_permissions::{
    domain::service::UserRolesAndPermissionsServiceImpl, outbound::pgpool::MacroDB,
};
use sqlx::PgPool;
use system_status::{
    domain::service::SystemStatusServiceImpl,
    outbound::{
        connection_gateway_broadcaster::ConnectionGatewayStatusBroadcaster,
        pg_system_status_repo::PgSystemStatusRepo,
    },
};
use tokio_util::task::TaskTracker;
use user_language::{
    domain::service::UserLanguageServiceImpl, outbound::pg_user_language_repo::PgUserLanguageRepo,
};

use crate::account_link_state::AccountLinkStateKey;
use crate::domain::microsoft::MicrosoftAuth;
use crate::service::signup_policy::SignupPolicy;
use cursor_api_key::cipher::CursorApiKeyCipher;

pub(crate) type NotificationIngressType = SqsNotificationIngress<SqsQueue>;
pub(crate) type AuthenticationEventBroker =
    MacroEventBrokerService<KafkaEventPublisher, TaskTracker>;

pub(crate) type ChannelServiceType = ChannelServiceImpl<
    PgChannelsRepo,
    SpawnedChannelEventDispatcher<
        ChannelSideEffectService<
            PgChannelSideEffectContext,
            ConnectionGatewayChannelRealtimePublisher,
            NotificationChannelSender<NotificationIngressType>,
            ContactsChannelDispatcher<SqsContactsIngress<SqsContactsQueue>>,
            AuthenticationEventBroker,
        >,
    >,
    PgChannelReferenceSharePermissions<EntityAccessServiceType>,
>;

/// The AI billing service: plan allowances, prepaid credits, and overage,
/// resolved through roles + teams and collected through Stripe.
pub(crate) type AiBillingServiceType = ai_billing::domain::BillingServiceImpl<
    ai_billing::outbound::RolesTeamsEntitlementSource<
        UserRolesAndPermissionsServiceImpl<MacroDB, MacroDB>,
        teams::outbound::team_repo::TeamRepositoryImpl,
    >,
    ai_billing::outbound::PgUsageReader,
    ai_billing::outbound::PgBillingRepo,
    ai_billing::outbound::StripePaymentGateway,
>;

pub(crate) type SubscriptionStatusServiceType =
    crate::service::subscription_status::SubscriptionStatusService<
        ai_billing::outbound::RolesTeamsEntitlementSource<
            UserRolesAndPermissionsServiceImpl<MacroDB, MacroDB>,
            teams::outbound::team_repo::TeamRepositoryImpl,
        >,
        crate::outbound::subscription_plan::StripePlanGateway<
            teams::outbound::customer_repo::CustomerRepositoryImpl,
        >,
    >;

pub(crate) type DomainNoticeServiceType = teams::domain::domain_notice::DomainNoticeServiceImpl<
    teams::outbound::colleague_directory::ContactsColleagueDirectory<
        contacts::outbound::repository::DbContactsRepository,
    >,
    teams::domain::join_announcement::JoinAnnouncementServiceImpl<
        teams::outbound::join_announcement_repo::JoinAnnouncementRepositoryImpl,
        NotificationIngressType,
    >,
>;

pub(crate) type TeamsServiceType = teams::domain::team_service::TeamServiceImpl<
    teams::outbound::team_repo::TeamRepositoryImpl,
    teams::outbound::customer_repo::CustomerRepositoryImpl,
    ChannelServiceType,
    UserRolesAndPermissionsServiceImpl<MacroDB, MacroDB>,
    NotificationIngressType,
    teams::outbound::crm_enqueuer::SqsCrmEnqueuer,
    teams::outbound::team_crm_settings_repo::TeamCrmSettingsRepositoryImpl,
    teams::outbound::team_analytics::AnalyticsClientTeamAnalytics,
    teams::outbound::contacts_enqueuer::ContactsIngressEnqueuer<
        SqsContactsIngress<SqsContactsQueue>,
    >,
    AuthenticationEventBroker,
    AiBillingServiceType,
    crate::outbound::team_owned_entity_cleanup::TeamOwnedEntityCleanupAdapter<
        bots::outbound::pg_bots_repo::PgBotsRepo,
        entity_registry::EntityRegistryServiceImpl<entity_registry::PgEntityRegistryRepository>,
    >,
>;

pub(crate) type RateLimiter = RateLimitServiceImpl<RedisRateLimitAdapter<redis::Client>>;

pub(crate) type InviteRewardsType = crate::outbound::invite_rewards::BillingInviteRewards<
    ai_billing::outbound::RolesTeamsEntitlementSource<
        UserRolesAndPermissionsServiceImpl<MacroDB, MacroDB>,
        teams::outbound::team_repo::TeamRepositoryImpl,
    >,
    ai_billing::outbound::PgCreditGrantRepo,
    ai_billing::outbound::PgCreditGrantRepo,
>;

pub(crate) type ReferralServiceType =
    ReferralServiceImpl<PgReferralRepo, InviteRewardsType, Arc<SqsNotificationIngress<SqsQueue>>>;

pub(crate) type GtmInviteServiceType = GtmInviteServiceImpl<PgGtmInviteRepo>;

pub(crate) type UserLanguageServiceType = UserLanguageServiceImpl<PgUserLanguageRepo>;
pub(crate) type SystemStatusServiceType =
    SystemStatusServiceImpl<PgSystemStatusRepo, ConnectionGatewayStatusBroadcaster>;

pub(crate) type GithubLinkServiceType = GithubLinkServiceImpl<
    PgGithubRepo,
    GithubOauthImpl,
    GithubAuthImpl,
    GithubPullRequestServiceImpl<
        ForeignEntityServiceImpl<PgForeignEntityRepo>,
        PgGithubPullRequestRepo,
    >,
>;

pub(crate) type EntityAccessServiceType = EntityAccessServiceImpl<PgAccessRepository>;

pub(crate) type FavoritesServiceType = favorites::domain::service::FavoritesServiceImpl<
    favorites::outbound::pg_favorites_repo::PgFavoritesRepo,
>;

pub(crate) type AuthorizationService = MacroAuthorizationServiceImpl<MacroAuthJwtValidator>;

pub(crate) type AgentApiKeysType = agent_api_keys::domain::AgentKeyService<
    agent_api_keys::outbound::PgAgentKeyRepo,
    agent_api_keys::outbound::KmsAgentKeyCipher<cursor_api_key::cipher::AwsKmsCiphertexts>,
    agent_api_keys::outbound::EntitlementKeyPlans<
        ai_billing::outbound::RolesTeamsEntitlementSource<
            UserRolesAndPermissionsServiceImpl<MacroDB, MacroDB>,
            teams::outbound::team_repo::TeamRepositoryImpl,
        >,
    >,
>;

pub(crate) type BotsServiceType = bots::domain::service::BotServiceImpl<
    bots::outbound::pg_bots_repo::PgBotsRepo,
    AuthenticationEventBroker,
>;

#[derive(Clone, FromRef)]
pub(crate) struct ApiContext {
    pub db: PgPool,
    pub inbox_connections:
        Arc<email::domain::inbox_entitlement::InboxConnectionService<email::outbound::EmailPgRepo>>,
    pub github_link_service: Arc<GithubLinkServiceType>,
    pub auth_client: Arc<fusionauth::FusionAuthClient>,
    pub microsoft_auth: Option<Arc<dyn MicrosoftAuth>>,
    /// Encrypts users' Cursor API keys.
    pub cursor_api_key_cipher: Arc<dyn CursorApiKeyCipher>,
    /// Agents' own Anthropic and OpenAI API keys.
    pub agent_api_keys: Arc<AgentApiKeysType>,
    /// Who may change an agent, for its API key.
    pub bots: Arc<BotsServiceType>,
    /// Owner-bound Codex OAuth lifecycle and cloud target settings.
    pub codex_connection: Option<Arc<dyn codex_connection::domain::ConnectionService>>,
    pub macro_cache_client: Arc<MacroCache>,
    pub stripe_client: Arc<stripe::Client>,
    pub subscription_status: Arc<SubscriptionStatusServiceType>,
    pub subscription_plan: Arc<
        crate::service::subscription_plan::PlanService<
            crate::outbound::subscription_plan::StripePlanGateway<
                teams::outbound::customer_repo::CustomerRepositoryImpl,
            >,
        >,
    >,
    pub subscription_checkout: Arc<
        crate::service::subscription_checkout::CheckoutService<
            crate::outbound::subscription_checkout::StripeCheckoutGateway<GtmInviteServiceType>,
        >,
    >,
    pub document_storage_service_client:
        Arc<document_storage_service_client::DocumentStorageServiceClient>,
    pub static_file_service_client: Arc<static_file_service_client::StaticFileServiceClient>,
    /// Browser-facing base URL of static files, which profile pictures use.
    pub static_file_public_url: String,
    pub user_deletion: Arc<
        crate::outbound::user_deletion::UserDeletionAdapter<
            TeamsServiceType,
            onboarding::outbound::pg_onboarding_repo::PgOnboardingRepo,
        >,
    >,
    pub email_service_client: Arc<email::outbound::EmailServiceHttpClient>,
    pub ses_client: Arc<ses_client::Ses>,
    pub notification_ingress_service: Arc<NotificationIngressType>,
    pub sqs_client: Arc<sqs_client::SQS>,
    pub environment: Environment,
    pub signup_policy: Arc<SignupPolicy>,
    pub jwt_args: JwtValidationArgs,
    pub authorization_state: MacroAuthorizationState<AuthorizationService>,
    pub token_context: MacroApiTokenContext,
    pub internal_api_key: InternalApiKey,
    pub stripe_webhook_secret: LocalOrRemoteSecret<StripeWebhookSecretKey>,
    pub user_roles_and_permissions_service:
        Arc<UserRolesAndPermissionsServiceImpl<MacroDB, MacroDB>>, // Note: since FromRef doesn't support generics we have to specify the concrete types here
    pub teams_service: Arc<TeamsServiceType>,
    pub domain_notice_service: Arc<DomainNoticeServiceType>,
    pub channel_service: Arc<ChannelServiceType>,
    pub channel_messages: Arc<dyn messages::domain::api::MessageCommands>,
    pub favorites_service: Arc<FavoritesServiceType>,
    pub entity_access_service: Arc<EntityAccessServiceType>,
    pub native_app_service: Arc<NativeAppServiceImpl<DefaultBundleFetcher>>,
    pub analytics_client: Arc<AnalyticsClient>,
    pub loops_client: Arc<LoopsClient>,
    pub referral_service: Arc<ReferralServiceType>,
    pub gtm_invite_service: Arc<GtmInviteServiceType>,
    pub user_language_service: Arc<UserLanguageServiceType>,
    pub system_status_service: Arc<SystemStatusServiceType>,
    pub rate_limit_service: RateLimiter,
    /// The stripe price ids for each paid plan's seat
    pub stripe_prices: crate::api::user::stripe::StripePrices,
    /// AI allowances, credits, and overage
    pub ai_billing_service: Arc<AiBillingServiceType>,
    pub ai_payment_gateway: Arc<ai_billing::outbound::StripePaymentGateway>,
    /// Whether Gmail link consent requests the Google Calendar scope.
    pub calendar_scope_enabled: bool,
    /// Signs and verifies the `state` on account-link OAuth round trips.
    pub account_link_state_key: AccountLinkStateKey,
}

env_var! {
    #[derive(Clone)]
    pub struct StripeWebhookSecretKey;
}

env_var! {
    #[derive(Clone)]
    pub struct MacroApiTokenIssuer;
}
env_var! {
    #[derive(Clone)]
    pub struct MacroApiTokenPrivateSecretKey;
}

env_var! {
    #[derive(Clone)]
    pub struct MacroApiTokenExpirySeconds;
}

#[derive(Clone)]
pub struct MacroApiTokenContext {
    /// The issuer of the macro-api-token
    pub issuer: MacroApiTokenIssuer,
    /// The macro api token private key used to sign macro-api tokens
    pub macro_api_token_private_key: LocalOrRemoteSecret<MacroApiTokenPrivateSecretKey>,
    /// The token expiry duration in seconds
    pub expiry_seconds: usize,
}

#[derive(Clone)]
pub struct TokenContext {
    /// The access token
    pub access_token: String,
    /// The refresh token
    pub refresh_token: String,
}