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
use crate::api::context::ApiContext;
use ::unfurl::{
domain::{ports::UnfurlFetcher, service::UnfurlServiceImpl},
inbound::axum_router::UnfurlRouterState,
};
use anyhow::Context;
use axum::Router;
use utoipa::OpenApi;
use utoipa_swagger_ui::SwaggerUi;
pub mod context;
mod health;
mod proxy;
pub(crate) mod swagger;
mod unfurl;
pub async fn setup_and_serve<F>(
state: ApiContext,
unfurl_state: UnfurlRouterState<UnfurlServiceImpl<F>>,
port: usize,
) -> anyhow::Result<()>
where
F: UnfurlFetcher,
anyhow::Error: From<F::Err>,
{
let cors = macro_cors::cors_layer();
let env = state.environment;
let app = app_router(state, unfurl_state)
.layer(cors)
.merge(SwaggerUi::new("/docs").url("/api-doc/openapi.json", swagger::ApiDoc::openapi()))
.merge(
SwaggerUi::new("/unfurl/docs")
.url("/unfurl/api-doc/openapi.json", swagger::ApiDoc::openapi()),
);
let listener = tokio::net::TcpListener::bind(format!("0.0.0.0:{}", port))
.await
.unwrap();
tracing::info!(
"\n📜 unfurl_service 📜\nenvironment {:?}\nport: {}",
&env,
&port
);
axum::serve(listener, app.into_make_service())
.await
.context("error starting service")
}
fn api_router<F>(unfurl_state: UnfurlRouterState<UnfurlServiceImpl<F>>) -> Router<ApiContext>
where
F: UnfurlFetcher,
anyhow::Error: From<F::Err>,
{
Router::new()
.nest("/unfurl", unfurl::router(unfurl_state))
.nest("/proxy", proxy::router())
}
fn app_router<F>(state: ApiContext, unfurl_state: UnfurlRouterState<UnfurlServiceImpl<F>>) -> Router
where
F: UnfurlFetcher,
anyhow::Error: From<F::Err>,
{
let inner = api_router(unfurl_state)
.with_state(state)
.merge(health::router());
Router::new().merge(inner.clone()).nest("/unfurl", inner)
}
#[cfg(test)]
mod tests {
use crate::api::unfurl::get_unfurl::{GetUnfurlBulkBody, GetUnfurlBulkResponse};
use super::*;
use crate::http_safety::SsrfSafeHttpClient;
use crate::unfurl::{GetUnfurlResponse, GetUnfurlResponseList};
use ::unfurl::outbound::ReqwestUnfurlFetcher;
use axum::{
body::Body,
http::{Request, StatusCode},
};
use http_body_util::BodyExt; // for `collect`
use macro_env::Environment;
use tower::ServiceExt;
fn test_state() -> ApiContext {
ApiContext {
environment: Environment::Local,
http_client: SsrfSafeHttpClient::new().expect("build safe test HTTP client"),
}
}
fn test_unfurl_state() -> UnfurlRouterState<UnfurlServiceImpl<ReqwestUnfurlFetcher>> {
UnfurlRouterState::new(UnfurlServiceImpl::new(
ReqwestUnfurlFetcher::new().expect("build unfurl fetcher"),
))
}
#[tokio::test]
async fn test_not_found() {
let api = api_router(test_unfurl_state()).with_state(test_state());
let response = api
.oneshot(
Request::builder()
.uri("/does-not-exist")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::NOT_FOUND);
let body = response.into_body().collect().await.unwrap().to_bytes();
assert!(body.is_empty());
}
async fn health_body(app: Router, uri: &str) -> (StatusCode, String) {
let response = app
.oneshot(
Request::builder()
.uri(uri)
.method("GET")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
let status = response.status();
let body = String::from_utf8(
response
.into_body()
.collect()
.await
.unwrap()
.to_bytes()
.to_vec(),
)
.unwrap();
(status, body)
}
#[tokio::test]
async fn test_health_is_served_at_root_and_gateway_prefix() {
let (root_status, root_body) =
health_body(app_router(test_state(), test_unfurl_state()), "/health").await;
assert_eq!(root_status, StatusCode::OK);
assert_eq!(root_body, "healthy");
let (prefixed_status, prefixed_body) = health_body(
app_router(test_state(), test_unfurl_state()),
"/unfurl/health",
)
.await;
assert_eq!(prefixed_status, StatusCode::OK);
assert_eq!(prefixed_body, "healthy");
}
#[tokio::test]
async fn test_gateway_prefixed_unfurl_path_is_reachable() {
let api = app_router(test_state(), test_unfurl_state());
let response = api
.oneshot(
Request::builder()
.uri("/unfurl/unfurl?url=https://doesnotexist.com")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
}
#[tokio::test]
async fn test_unfurl_url_nonexistent() {
let api = api_router(test_unfurl_state()).with_state(test_state());
let response = api
.oneshot(
Request::builder()
.uri("/unfurl?url=https://doesnotexist.com")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
let body = response.into_body();
let bytes = axum::body::to_bytes(body, 2048).await.unwrap();
let body_str = String::from_utf8(bytes.to_vec()).unwrap();
let unfurled_link: Option<GetUnfurlResponse> = serde_json::from_str(&body_str).unwrap();
assert!(
unfurled_link.is_none(),
"non-existent link should return an empty response"
);
}
#[ignore]
#[tokio::test]
async fn test_unfurl_hello_url() {
let api = api_router(test_unfurl_state()).with_state(test_state());
let response = api
.oneshot(
Request::builder()
.uri("/unfurl?url=https://hello.com")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = response.into_body();
let bytes = axum::body::to_bytes(body, 2048).await.unwrap();
let body_str = String::from_utf8(bytes.to_vec()).unwrap();
let unfurled_link: Option<GetUnfurlResponse> = serde_json::from_str(&body_str).unwrap();
let unfurled_link = unfurled_link.unwrap();
assert_eq!(&unfurled_link.title, "Hello");
assert_eq!(
&unfurled_link.description.unwrap(),
"This is a description."
);
assert_eq!(&unfurled_link.url, "https://hello.com");
}
#[ignore]
#[tokio::test]
async fn test_bulk() {
let api = api_router(test_unfurl_state()).with_state(test_state());
let body = GetUnfurlBulkBody {
url_list: ["https://hello.com", "https://example.com"]
.iter()
.map(|s| s.to_string())
.collect(),
};
let body: Body = serde_json::to_string(&body).unwrap().into();
let req = Request::builder()
.method(http::Method::POST)
.uri("/unfurl/bulk")
.header(reqwest::header::CONTENT_TYPE, "application/json")
.body(body)
.unwrap();
let response = api.oneshot(req).await.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = response.into_body();
let bytes = axum::body::to_bytes(body, 8192).await.unwrap();
let body_str = String::from_utf8(bytes.to_vec()).unwrap();
let resp: GetUnfurlBulkResponse = serde_json::from_str(&body_str).unwrap();
let unfurled_links: GetUnfurlResponseList = resp.responses;
assert_eq!(&unfurled_links[0].as_ref().unwrap().title, "Hello");
assert_eq!(
&unfurled_links[1].as_ref().unwrap().title,
"Example Website"
);
}
// Make sure 404 fetched links return expected outputs in bulk list
#[ignore]
#[tokio::test]
async fn test_bulk_404_links() {
let api = api_router(test_unfurl_state()).with_state(test_state());
let body = GetUnfurlBulkBody {
url_list: [
"https://hello.com",
"https://example.com",
// does not exist with mock fetcher
"https://nonexistent.com",
]
.iter()
.map(|s| s.to_string())
.collect(),
};
let body: Body = serde_json::to_string(&body).unwrap().into();
let response = api
.oneshot(
Request::builder()
.method(http::Method::POST)
.header(http::header::CONTENT_TYPE, "application/json")
.uri("/unfurl/bulk")
.body(body)
.unwrap(),
)
.await
.unwrap();
assert_eq!(response.status(), StatusCode::OK);
let body = response.into_body();
let bytes = axum::body::to_bytes(body, 8192).await.unwrap();
let body_str = String::from_utf8(bytes.to_vec()).unwrap();
let resp: GetUnfurlBulkResponse = serde_json::from_str(&body_str).unwrap();
let unfurled_links: GetUnfurlResponseList = resp.responses;
assert_eq!(&unfurled_links[0].as_ref().unwrap().title, "Hello");
assert_eq!(
&unfurled_links[1].as_ref().unwrap().title,
"Example Website"
);
// 404s with mock fetch, should be None
assert!(&unfurled_links[2].as_ref().is_none());
}
}