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
//! This module exposes the http adapter for inbound http requests via an axum router
#[cfg(test)]
mod test;
pub mod device;
pub mod preferences;
use axum::{
Json, Router,
extract::{FromRef, Path, Query, State},
routing::{delete, get, patch, put},
};
use hmac::Hmac;
use macro_authorization::{
MacroAuthorizationExtractor, MacroAuthorizationService, MacroAuthorizationState, UserOrInternal,
};
use macro_user_id::user_id::MacroUserIdStr;
use model_error_response::ErrorResponse;
use models_pagination::{CreatedAt, CursorOptionExt, CursorWithValAndFilter};
use reqwest::StatusCode;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use sha2::Sha256;
use std::{collections::HashSet, sync::Arc};
use utoipa::ToSchema;
use uuid::Uuid;
use crate::domain::{
models::{
UserNotificationRow,
request::{
GetNotificationsByEventItemIdsRequest, NotificationListFilters, NotificationStatus,
UpdateNotificationsRequest,
},
},
service::NotificationReader,
};
/// Path parameter for a single event item ID.
#[derive(Deserialize)]
pub struct EventItemIdPath {
/// The event item ID.
pub event_item_id: Uuid,
}
/// Path parameter for a single notification ID.
#[derive(Deserialize)]
pub struct NotificationIdPath {
/// The notification ID.
pub notification_id: Uuid,
}
/// the router state for a notification router
pub struct NotificationRouterState<S, Auth> {
/// the inner S wrapped in an [Arc]
pub inner: Arc<S>,
/// the statically known list of notification typenames which can be blocked by the user
pub blockable_notification_typenames: &'static HashSet<&'static str>,
/// The value which is used to verify the presigned url requests
pub hmac_signing_key: Hmac<Sha256>,
/// State used to authorize requests.
pub authorization_state: MacroAuthorizationState<Auth>,
}
impl<S, Auth> FromRef<NotificationRouterState<S, Auth>> for MacroAuthorizationState<Auth> {
fn from_ref(input: &NotificationRouterState<S, Auth>) -> Self {
input.authorization_state.clone()
}
}
// Manual implementation so `Auth` does not need to implement `Clone`.
impl<S, Auth> Clone for NotificationRouterState<S, Auth> {
fn clone(&self) -> Self {
Self {
inner: Arc::clone(&self.inner),
blockable_notification_typenames: self.blockable_notification_typenames,
hmac_signing_key: self.hmac_signing_key.clone(),
authorization_state: self.authorization_state.clone(),
}
}
}
impl<S: NotificationReader, Auth> NotificationRouterState<S, Auth> {
/// create a new instance of self
pub fn new(
val: S,
blockable_notification_typenames: &'static HashSet<&'static str>,
hmac_signing_key: Hmac<Sha256>,
authorization_state: MacroAuthorizationState<Auth>,
) -> Self {
NotificationRouterState {
inner: Arc::new(val),
blockable_notification_typenames,
hmac_signing_key,
authorization_state,
}
}
}
/// construct the router
pub fn router<S, Auth, T>() -> Router<NotificationRouterState<S, Auth>>
where
S: NotificationReader,
Auth: MacroAuthorizationService,
T: Serialize + DeserializeOwned + Send + 'static,
{
Router::new()
.nest(
"/bulk",
Router::new()
.route("/", delete(bulk_delete_notifications::<S, Auth>))
.route("/seen", patch(bulk_mark_seen::<S, Auth>))
.route("/done", patch(bulk_mark_done::<S, Auth>))
.route("/undone", patch(bulk_mark_undone::<S, Auth>)),
)
.route(
"/preferences",
get(preferences::get_notification_type_preferences::<S, Auth>),
)
.route(
"/preferences/{notification_event_type}/disable",
put(preferences::disable_notification_type::<S, Auth>)
.get(preferences::presigned_disable_notification_type::<S, Auth>),
)
.route(
"/preferences/{notification_event_type}/enable",
put(preferences::enable_notification_type::<S, Auth>),
)
}
/// the params for pagination
#[serde_with::serde_as]
#[derive(serde::Deserialize)]
pub struct Params {
/// the limit on the number of items to return in a page
pub limit: Option<u32>,
/// Comma-separated exact states. Omitted defaults to unseen and seen;
/// an empty string explicitly disables state filtering.
#[serde(default)]
#[serde_as(
as = "Option<serde_with::StringWithSeparator<serde_with::formats::CommaSeparator, crate::domain::models::NotificationState>>"
)]
pub states: Option<Vec<crate::domain::models::NotificationState>>,
}
/// the response from listing the users notifications
#[derive(Debug, Serialize)]
pub struct GetAllUserNotificationsResponse<T> {
/// the list of items returned
pub items: Vec<UserNotificationRow<T>>,
/// the next page cursor if it exists
pub next_cursor: Option<String>,
}
/// List user notifications with generic metadata type `T`.
pub async fn list_user_notifications<
S: NotificationReader,
Auth: MacroAuthorizationService,
T: Serialize + DeserializeOwned + Send,
>(
service: &NotificationRouterState<S, Auth>,
user_id: MacroUserIdStr<'static>,
Query(Params { limit, states }): Query<Params>,
cursor: Option<CursorWithValAndFilter<Uuid, CreatedAt, ()>>,
) -> Result<Json<GetAllUserNotificationsResponse<T>>, (StatusCode, Json<ErrorResponse<'static>>)> {
let query = cursor.into_query(CreatedAt, ());
let result = service
.inner
.get_user_notifications::<T>(
user_id,
limit,
query,
NotificationListFilters {
states: states
.unwrap_or_else(|| crate::domain::models::NotificationState::ACTIVE.to_vec()),
include_types: Vec::new(),
entities: Vec::new(),
},
)
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to get user notifications");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
message: "failed to get notifications".into(),
}),
)
})?;
Ok(Json(GetAllUserNotificationsResponse {
items: result.items,
next_cursor: result.next_cursor,
}))
}
/// Request body for bulk-fetching notifications by event item IDs.
#[derive(Serialize, Deserialize, Debug, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct BulkGetByEventItemIdsRequest {
/// The event item IDs to filter notifications by.
pub event_item_ids: Vec<Uuid>,
}
/// Get user notifications filtered by event item IDs.
#[utoipa::path(
post,
operation_id = "bulk_get_user_notifications_by_event_item_ids",
path = "/v1/user_notifications/item/bulk",
params(
("limit" = Option<u32>, Query, description = "Size limit per page. Default 20, max 500."),
("states" = Option<String>, Query, description = "Comma-separated exact states: unseen,seen,done. Omitted defaults to unseen,seen; empty includes all states."),
("cursor" = Option<String>, Query, description = "Cursor value. Base64 encoded timestamp and item id."),
),
request_body = BulkGetByEventItemIdsRequest,
responses(
(status = 200),
(status = 400, body = ErrorResponse),
(status = 401, body = ErrorResponse),
(status = 500, body = ErrorResponse),
)
)]
pub async fn bulk_get_by_event_item_ids<
S: NotificationReader,
Auth: MacroAuthorizationService,
T: Serialize + DeserializeOwned + Send,
>(
State(service): State<NotificationRouterState<S, Auth>>,
user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Query(Params { limit, states }): Query<Params>,
cursor: Option<CursorWithValAndFilter<Uuid, CreatedAt, ()>>,
Json(req): Json<BulkGetByEventItemIdsRequest>,
) -> Result<Json<GetAllUserNotificationsResponse<T>>, (StatusCode, Json<ErrorResponse<'static>>)> {
let result = service
.inner
.get_user_notifications_by_event_item_ids::<T>(GetNotificationsByEventItemIdsRequest {
user_id: user.authorization.user.macro_user_id,
event_item_ids: &req.event_item_ids,
limit,
cursor: cursor.into_query(CreatedAt, ()),
filters: NotificationListFilters {
states: states
.unwrap_or_else(|| crate::domain::models::NotificationState::ACTIVE.to_vec()),
include_types: Vec::new(),
entities: Vec::new(),
},
})
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to get user notifications by event item ids");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
message: "failed to get notifications".into(),
}),
)
})?;
Ok(Json(GetAllUserNotificationsResponse {
items: result.items,
next_cursor: result.next_cursor,
}))
}
/// the notification ids that we are bulk updating
#[derive(Serialize, Deserialize, Debug, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct NotificationBulkRequest {
/// The ids of the notifications to handle
pub notification_ids: Vec<uuid::Uuid>,
}
/// Mark notifications as seen.
#[utoipa::path(
patch,
operation_id = "bulk_mark_notifications_seen",
path = "/v1/user_notifications/bulk/seen",
request_body = NotificationBulkRequest,
responses(
(status = 200),
(status = 400, body = ErrorResponse),
(status = 401, body = ErrorResponse),
(status = 500, body = ErrorResponse),
)
)]
pub async fn bulk_mark_seen<S: NotificationReader, Auth: MacroAuthorizationService>(
State(service): State<NotificationRouterState<S, Auth>>,
user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(req): Json<NotificationBulkRequest>,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
bulk_update(
&service,
user.authorization.user.macro_user_id,
&req,
NotificationStatus::Seen,
)
.await
}
/// Mark notifications as done.
#[utoipa::path(
patch,
operation_id = "bulk_mark_notifications_done",
path = "/v1/user_notifications/bulk/done",
request_body = NotificationBulkRequest,
responses(
(status = 200),
(status = 400, body = ErrorResponse),
(status = 401, body = ErrorResponse),
(status = 500, body = ErrorResponse),
)
)]
pub async fn bulk_mark_done<S: NotificationReader, Auth: MacroAuthorizationService>(
State(service): State<NotificationRouterState<S, Auth>>,
user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(req): Json<NotificationBulkRequest>,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
bulk_update(
&service,
user.authorization.user.macro_user_id,
&req,
NotificationStatus::Done(true),
)
.await
}
/// Mark notifications as not done.
#[utoipa::path(
patch,
operation_id = "bulk_mark_notifications_undone",
path = "/v1/user_notifications/bulk/undone",
request_body = NotificationBulkRequest,
responses(
(status = 200),
(status = 400, body = ErrorResponse),
(status = 401, body = ErrorResponse),
(status = 500, body = ErrorResponse),
)
)]
pub async fn bulk_mark_undone<S: NotificationReader, Auth: MacroAuthorizationService>(
State(service): State<NotificationRouterState<S, Auth>>,
user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(req): Json<NotificationBulkRequest>,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
bulk_update(
&service,
user.authorization.user.macro_user_id,
&req,
NotificationStatus::Done(false),
)
.await
}
async fn bulk_update<S: NotificationReader, Auth: MacroAuthorizationService>(
service: &NotificationRouterState<S, Auth>,
user_id: MacroUserIdStr<'static>,
req: &NotificationBulkRequest,
status: NotificationStatus,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
service
.inner
.update_notifications(UpdateNotificationsRequest {
user_id,
notification_ids: &req.notification_ids,
status,
})
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to update notifications");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
message: "failed to update notifications".into(),
}),
)
})?;
Ok(Json(()))
}
/// Get user notifications for a single event item ID.
#[utoipa::path(
get,
operation_id = "get_user_notifications_by_event_item_id",
path = "/v1/user_notifications/item/{event_item_id}",
params(
("event_item_id" = Uuid, Path, description = "The event item ID"),
("limit" = Option<u32>, Query, description = "Size limit per page. Default 20, max 500."),
("states" = Option<String>, Query, description = "Comma-separated exact states: unseen,seen,done. Omitted defaults to unseen,seen; empty includes all states."),
("cursor" = Option<String>, Query, description = "Cursor value. Base64 encoded timestamp and item id."),
),
responses(
(status = 200),
(status = 400, body = ErrorResponse),
(status = 401, body = ErrorResponse),
(status = 500, body = ErrorResponse),
)
)]
pub async fn get_by_event_item_id<
S: NotificationReader,
Auth: MacroAuthorizationService,
T: Serialize + DeserializeOwned + Send,
>(
State(service): State<NotificationRouterState<S, Auth>>,
user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(EventItemIdPath { event_item_id }): Path<EventItemIdPath>,
Query(Params { limit, states }): Query<Params>,
cursor: Option<CursorWithValAndFilter<Uuid, CreatedAt, ()>>,
) -> Result<Json<GetAllUserNotificationsResponse<T>>, (StatusCode, Json<ErrorResponse<'static>>)> {
let result = service
.inner
.get_user_notifications_by_event_item_ids::<T>(GetNotificationsByEventItemIdsRequest {
user_id: user.authorization.user.macro_user_id,
event_item_ids: &[event_item_id],
limit,
cursor: cursor.into_query(CreatedAt, ()),
filters: NotificationListFilters {
states: states
.unwrap_or_else(|| crate::domain::models::NotificationState::ACTIVE.to_vec()),
include_types: Vec::new(),
entities: Vec::new(),
},
})
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to get user notifications by event item id");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
message: "failed to get notifications".into(),
}),
)
})?;
Ok(Json(GetAllUserNotificationsResponse {
items: result.items,
next_cursor: result.next_cursor,
}))
}
/// Get a single user notification by ID.
#[utoipa::path(
get,
operation_id = "get_user_notification_by_id_v2",
path = "/v1/user_notifications/{notification_id}",
params(
("notification_id" = Uuid, Path, description = "ID of the notification"),
),
responses(
(status = 200),
(status = 400, body = ErrorResponse),
(status = 401, body = ErrorResponse),
(status = 404, body = ErrorResponse),
(status = 500, body = ErrorResponse),
)
)]
pub async fn get_notification_by_id<
S: NotificationReader,
Auth: MacroAuthorizationService,
T: Serialize + DeserializeOwned + Send,
>(
State(service): State<NotificationRouterState<S, Auth>>,
user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(NotificationIdPath { notification_id }): Path<NotificationIdPath>,
) -> Result<Json<UserNotificationRow<T>>, (StatusCode, Json<ErrorResponse<'static>>)> {
let result = service
.inner
.get_user_notification_by_id::<T>(user.authorization.user.macro_user_id, notification_id)
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to get user notification by id");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
message: "failed to get notification".into(),
}),
)
})?;
let Some(notification) = result else {
return Err((
StatusCode::NOT_FOUND,
Json(ErrorResponse {
message: "notification not found".into(),
}),
));
};
Ok(Json(notification))
}
/// Soft-delete a single user notification.
#[utoipa::path(
delete,
operation_id = "delete_user_notification_v2",
path = "/v1/user_notifications/{notification_id}",
params(
("notification_id" = Uuid, Path, description = "ID of the notification"),
),
responses(
(status = 200),
(status = 400, body = ErrorResponse),
(status = 401, body = ErrorResponse),
(status = 500, body = ErrorResponse),
)
)]
pub async fn delete_notification<S: NotificationReader, Auth: MacroAuthorizationService>(
State(service): State<NotificationRouterState<S, Auth>>,
user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Path(NotificationIdPath { notification_id }): Path<NotificationIdPath>,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
service
.inner
.delete_user_notification(user.authorization.user.macro_user_id, notification_id)
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to delete user notification");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
message: "failed to delete notification".into(),
}),
)
})?;
Ok(Json(()))
}
/// Soft-delete multiple user notifications.
#[utoipa::path(
delete,
operation_id = "bulk_delete_user_notifications_v2",
path = "/v1/user_notifications/bulk",
request_body = NotificationBulkRequest,
responses(
(status = 200),
(status = 400, body = ErrorResponse),
(status = 401, body = ErrorResponse),
(status = 500, body = ErrorResponse),
)
)]
pub async fn bulk_delete_notifications<S: NotificationReader, Auth: MacroAuthorizationService>(
State(service): State<NotificationRouterState<S, Auth>>,
user: MacroAuthorizationExtractor<Auth, UserOrInternal>,
Json(req): Json<NotificationBulkRequest>,
) -> Result<Json<()>, (StatusCode, Json<ErrorResponse<'static>>)> {
service
.inner
.bulk_delete_user_notifications(
user.authorization.user.macro_user_id,
&req.notification_ids,
)
.await
.map_err(|e| {
tracing::error!(error=?e, "failed to delete user notifications");
(
StatusCode::INTERNAL_SERVER_ERROR,
Json(ErrorResponse {
message: "failed to delete notifications".into(),
}),
)
})?;
Ok(Json(()))
}