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.0 KB
Raw Blame
use crate::{
    context::{AppState, AuthorizationService},
    model::message::Message,
    service::{redis::post_broadcast, sender::send_message_to_entity},
};
use axum::{
    Json as JsonResponse, Router,
    extract::{Json, Path, State},
    http::StatusCode,
    routing::post,
};
use connection_gateway_models::{
    BatchSendMessageBody, BatchSendUniqueMessagesBody, SendMessageBody, SendMessageResponse,
};
use futures::future::try_join_all;
use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
use model_entity::Entity;

pub fn router<S>(state: AppState) -> Router<S>
where
    S: Send + Sync + Clone + 'static,
{
    Router::new()
        .route(
            "/send/{entity_type}/{entity_id}",
            post(send_message_handler),
        )
        .route("/batch_send", post(batch_send_message_handler))
        .route(
            "/batch_send_unique",
            post(batch_send_unique_messages_handler),
        )
        .route("/broadcast", post(broadcast_message_handler))
        .with_state(state)
}

/// Sends a message to every open connection on every instance. Delivery is
/// best-effort and asynchronous, so there are no receipts.
#[utoipa::path(
    post,
    path = "/message/broadcast",
    security(("internal-api-key" = [])),
    request_body = SendMessageBody,
    responses(
        (status = 202, description = "Broadcast accepted"),
        (status = 401, body = String),
        (status = 500, body = String),
    )
)]
#[tracing::instrument(
    skip(_internal_authorization, ctx, body),
    fields(message_type = %body.message_type),
    err(Debug)
)]
pub async fn broadcast_message_handler(
    _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
    State(ctx): State<AppState>,
    Json(body): Json<SendMessageBody>,
) -> Result<StatusCode, (StatusCode, String)> {
    post_broadcast(
        ctx.context.redis_connection.clone(),
        Message::new(body.message_type, body.message.to_string()),
    )
    .await
    .map_err(|_| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            "unable to broadcast message".to_string(),
        )
    })?;

    Ok(StatusCode::ACCEPTED)
}

#[utoipa::path(
        post,
        path = "/message/send/{entity_type}/{entity_id}",
        security(("internal-api-key" = [])),
        params(
            ("entity_type" = String, Path, description = "the type of the entity to send the msssage to e.g. \"user\" | \"channel\" | \"document\" etc..."),
            ("entity_id" = String, Path, description = "the id of the entity to send the message to"),
        ),
        responses(
            (status = 201, body=SendMessageResponse),
            (status = 401, body=String),
            (status = 404, body=String),
            (status = 500, body=String),
        )
    )]
#[tracing::instrument(skip(_internal_authorization, ctx))]
#[axum::debug_handler(state = AppState)]
pub async fn send_message_handler(
    _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
    State(ctx): State<AppState>,
    Path(entity): Path<Entity<'static>>,
    Json(body): Json<SendMessageBody>,
) -> Result<(StatusCode, JsonResponse<SendMessageResponse>), (StatusCode, String)> {
    let redis_connection = ctx.context.redis_connection.clone();

    let res = send_message_to_entity(
        &ctx,
        &entity,
        Message::new(body.message_type.clone(), body.message.to_string()),
        redis_connection,
    )
    .await
    .map_err(|e| {
        tracing::error!(error=?e, "unable to send message");
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            "unable to send message".to_string(),
        )
    })?;

    Ok((
        StatusCode::OK,
        JsonResponse(SendMessageResponse { receipts: res }),
    ))
}

#[utoipa::path(
    post,
    path = "/batch_send",
    security(("internal-api-key" = [])),
    request_body = BatchSendMessageBody,
    responses(
        (status = 200, description = "Message sent successfully", body = SendMessageResponse),
        (status = 500, description = "Internal server error", body = String),
    )
)]
#[tracing::instrument(
    name = "send_messages",
    skip_all,
    fields(batch_kind = "shared", message_count = body.entities.len()),
    err(Debug)
)]
pub async fn batch_send_message_handler(
    _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
    State(ctx): State<AppState>,
    Json(body): Json<BatchSendMessageBody<'static>>,
) -> Result<(StatusCode, JsonResponse<SendMessageResponse>), (StatusCode, String)> {
    let redis_connection = ctx.context.redis_connection.clone();

    let all_receipts = try_join_all(body.entities.iter().map(|entity| {
        let redis_connection = redis_connection.clone();
        send_message_to_entity(
            &ctx,
            entity,
            Message::new(body.message_type.clone(), body.message.to_string()),
            redis_connection,
        )
    }))
    .await
    .inspect_err(|error| {
        tracing::error!(error = ?error, "unable to send message");
    })
    .map_err(|_| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            "unable to send message".to_string(),
        )
    })?;

    Ok((
        StatusCode::OK,
        JsonResponse(SendMessageResponse {
            receipts: all_receipts.into_iter().flatten().collect(),
        }),
    ))
}

// Send unique (different) messages to multiple entities
#[utoipa::path(
    post,
    path = "/batch_send_unique",
    request_body = BatchSendUniqueMessagesBody,
    responses(
        (status = 200, description = "Messages sent successfully", body = SendMessageResponse),
        (status = 500, description = "Internal server error", body = String),
    )
)]
#[tracing::instrument(
    name = "send_messages",
    skip_all,
    fields(batch_kind = "unique", message_count = body.messages.len()),
    err(Debug)
)]
#[axum::debug_handler(state = AppState)]
pub async fn batch_send_unique_messages_handler(
    _internal_authorization: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
    State(ctx): State<AppState>,
    Json(body): Json<BatchSendUniqueMessagesBody>,
) -> Result<(StatusCode, JsonResponse<SendMessageResponse>), (StatusCode, String)> {
    let redis_connection = ctx.context.redis_connection.clone();

    let all_receipts = try_join_all(body.messages.iter().map(|message| {
        let redis_connection = redis_connection.clone();
        send_message_to_entity(
            &ctx,
            &message.entity,
            Message::new(
                message.message_type.clone(),
                message.message_content.to_string(),
            ),
            redis_connection,
        )
    }))
    .await
    .inspect_err(|error| {
        tracing::error!(error = ?error, "unable to send message");
    })
    .map_err(|_| {
        (
            StatusCode::INTERNAL_SERVER_ERROR,
            "unable to send message".to_string(),
        )
    })?;

    Ok((
        StatusCode::OK,
        JsonResponse(SendMessageResponse {
            receipts: all_receipts.into_iter().flatten().collect(),
        }),
    ))
}