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.

5.7 KB
Raw Blame
#![recursion_limit = "256"]
mod config;
mod health;
use std::sync::Arc;

use anyhow::Context;
use axum::Router;
use config::{Config, Environment};
use contacts::domain::service::{ContactsDomainService, ContactsOutboxServiceImpl};
use contacts::inbound::http::{ApiDoc, ContactsRouterState, contacts_router};
use contacts::inbound::worker::{ContactsWorker, OutboxWorker};
use contacts::outbound::gateway::ConnectionGatewayNotifier;
use contacts::outbound::repository::DbContactsRepository;
use macro_authorization::{
    InternalAuthConfig, MacroAuthJwtValidator, MacroAuthorizationServiceImpl,
    MacroAuthorizationState, PgUserApiKeyAuthorizationRepo, PgUserApiKeyAuthorizer,
};
use macro_entrypoint::MacroEntrypoint;
use macro_service_urls::ConnectionGatewayUrl;
use rate_limit::{RateLimitServiceImpl, RedisRateLimitAdapter};
use sqlx::postgres::PgPoolOptions;
use sqs_worker::SQSWorker;
use utoipa::OpenApi;
use utoipa_swagger_ui::SwaggerUi;

async fn connect_to_database(config: &Config) -> anyhow::Result<sqlx::PgPool> {
    let (min_connections, max_connections): (u32, u32) = match config.environment {
        Environment::Production => (5, 30),
        Environment::Develop => (1, 25),
        Environment::Local => (1, 10),
    };

    let database_url = &config.database_url;

    let db = PgPoolOptions::new()
        .min_connections(min_connections)
        .max_connections(max_connections)
        .connect(database_url)
        .await
        .context("could not connect to db")?;
    Ok(db)
}

async fn create_sqs_worker(config: &Config) -> SQSWorker {
    let queue_url = macro_queues::ContactsQueue::new().to_string();
    let aws_config = macro_aws_config::get_macro_aws_config().await;

    let sqs_client = aws_sdk_sqs::Client::new(&aws_config);
    sqs_worker::SQSWorker::new(
        sqs_client,
        queue_url,
        config
            .contacts_queue_max_messages
            .value()
            .map(|p| p.parse::<i32>().expect("valid number"))
            .unwrap_or(10),
        config
            .contacts_queue_wait_time_seconds
            .value()
            .map(|p| p.parse::<i32>().expect("valid number"))
            .unwrap_or(10),
    )
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    MacroEntrypoint::default().init();

    let config = Config::from_env().context("expected to be able to generate config")?;

    let db = connect_to_database(&config).await?;
    let sqs_worker = create_sqs_worker(&config).await;

    let secretsmanager_client = secretsmanager_client::SecretsManager::new(
        aws_sdk_secretsmanager::Client::new(&macro_aws_config::get_macro_aws_config().await),
    );

    let notifier = Some(
        ConnectionGatewayNotifier::new(
            config.internal_api_key.to_string(),
            ConnectionGatewayUrl::new()?.to_string(),
        )
        .unwrap(),
    );

    let repository = DbContactsRepository::new(db.clone());
    let outbox_repo = DbContactsRepository::new(db.clone());
    let service = Arc::new(ContactsDomainService {
        repository,
        notifier,
    });

    let worker = ContactsWorker::new(sqs_worker, service.clone());
    tokio::spawn(async move {
        worker.poll().await;
    });

    let outbox_worker = OutboxWorker {
        service: ContactsOutboxServiceImpl {
            outbox_repo,
            inner_service: service.clone(),
        },
    };
    tokio::spawn(async move {
        outbox_worker.run().await;
    });

    let jwt_args = macro_auth::middleware::decode_jwt::JwtValidationArgs::new_with_secret_manager(
        config.environment,
        &secretsmanager_client,
    )
    .await?;
    let authorization_service = MacroAuthorizationServiceImpl::new(
        MacroAuthJwtValidator::new(jwt_args.clone()),
        InternalAuthConfig {
            api_key: config.internal_api_key.to_string(),
            default_user_id: None,
        },
        macro_authorization::NoBotAuthorizer,
        PgUserApiKeyAuthorizer::new(PgUserApiKeyAuthorizationRepo::new(db.clone())),
    );
    let authorization_state = MacroAuthorizationState::new(Arc::new(authorization_service));

    let redis_client = redis::Client::open(config.redis_uri.to_string().as_str())
        .context("failed to create redis client")?;

    let rate_limit_service = RateLimitServiceImpl {
        repo: RedisRateLimitAdapter {
            redis: redis_client,
        },
    };

    let cors = macro_cors::cors_layer();
    let port = config.port;

    let correlation = agent_correlation::inbound::CorrelationState::new(db.clone(), jwt_args);
    let app = mount_at_root_and_prefix(
        contacts_router(ContactsRouterState {
            contacts_service: service,
            rate_limit_service,
            authorization_state,
        })
        .layer(cors.clone())
        .merge(health::router().layer(cors)),
    )
    .merge(SwaggerUi::new("/docs").url("/api-doc/openapi.json", ApiDoc::openapi()))
    .merge(
        SwaggerUi::new("/contacts/docs").url("/contacts/api-doc/openapi.json", ApiDoc::openapi()),
    );

    let app = app.layer(axum::middleware::from_fn_with_state(
        correlation,
        agent_correlation::inbound::propagate,
    ));
    let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", port))
        .await
        .unwrap();

    tracing::info!("contacts service is up and running on port {}", &port);

    axum::serve(listener, app.into_make_service())
        .await
        .context("error starting service")?;
    Ok(())
}

/// Path prefix the shared gateway ALB forwards unmodified. Dual-mounted
/// alongside `/` so the dedicated ALB keeps working during cutover.
const GATEWAY_PATH_PREFIX: &str = "/contacts";

fn mount_at_root_and_prefix(inner: Router) -> Router {
    Router::new()
        .merge(inner.clone())
        .nest(GATEWAY_PATH_PREFIX, inner)
}

#[cfg(test)]
mod test;