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
feat(http): add macro tower layers (#1775)
Sean Aye1367040eeb99
diff --git a/infra/stacks/authentication-service/index.ts b/infra/stacks/authentication-service/index.tsindex b377ebe672..9e12a15945 100644--- a/infra/stacks/authentication-service/index.ts+++ b/infra/stacks/authentication-service/index.ts@@ -192,7 +192,7 @@ const service = new AuthenticationService('authentication-service', {{ name: 'ENVIRONMENT', value: stack },{name: 'RUST_LOG',- value: `authentication_service=${stack === 'prod' ? 'info' : 'trace'},tower_http=${stack === 'prod' ? 'info' : 'debug'},macro_auth=${stack === 'prod' ? 'info' : 'debug'},macro_middleware=${stack === 'prod' ? 'info' : 'debug'},github=${stack === 'prod' ? 'info' : 'debug'},fusionauth=debug`,+ value: `authentication_service=${stack === 'prod' ? 'info' : 'trace'},tower_http=${stack === 'prod' ? 'info' : 'debug'},macro_auth=${stack === 'prod' ? 'info' : 'debug'},macro_middleware=${stack === 'prod' ? 'info' : 'debug'},github=${stack === 'prod' ? 'info' : 'debug'},fusionauth=debug,warn`,},{name: 'DATABASE_URL',diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex acfaeb8e76..a0ea86d2dc 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -583,6 +583,7 @@ dependencies = ["macro_env","macro_env_var","macro_middleware",+ "macro_tower_layers","macro_user_id","macro_uuid","maud",@@ -5648,6 +5649,16 @@ dependencies = ["tracing",]+[[package]]+name = "macro_tower_layers"+version = "0.1.0"+dependencies = [+ "http 1.3.1",+ "tower 0.5.2",+ "tower-http",+ "tracing",+]+[[package]]name = "macro_user_id"version = "0.1.0"@@ -9991,6 +10002,7 @@ dependencies = ["tower-layer","tower-service","tracing",+ "uuid",][[package]]diff --git a/rust/cloud-storage/authentication_service/Cargo.toml b/rust/cloud-storage/authentication_service/Cargo.tomlindex 610833d2d7..18cdc8db93 100644--- a/rust/cloud-storage/authentication_service/Cargo.toml+++ b/rust/cloud-storage/authentication_service/Cargo.toml@@ -72,6 +72,7 @@ macro_middleware = { path = "../macro_middleware", default-features = false, fea"tracking","user_permissions",] }+macro_tower_layers = { path = "../macro_tower_layers" }macro_user_id = { path = "../macro_user_id" }macro_uuid = { path = "../macro_uuid" }maud = { version = "0.27.0" }diff --git a/rust/cloud-storage/authentication_service/src/api/mod.rs b/rust/cloud-storage/authentication_service/src/api/mod.rsindex 795feadeb9..74db7561c4 100644--- a/rust/cloud-storage/authentication_service/src/api/mod.rs+++ b/rust/cloud-storage/authentication_service/src/api/mod.rs@@ -3,9 +3,10 @@ use anyhow::Context;use axum::Router;use axum::http::HeaderName;use macro_auth::constant::MACRO_REFRESH_TOKEN_HEADER;+use macro_tower_layers::MacroRequestIdAndTracingLayer;use native_app_service::inbound::RouterState;+use std::time::Duration;use tower::ServiceBuilder;-use tower_http::trace::TraceLayer;use utoipa::OpenApi;use utoipa_swagger_ui::SwaggerUi;@@ -43,9 +44,10 @@ pub async fn setup_and_serve(state: ApiContext, port: usize) -> anyhow::Result<()]);let env = state.environment;+let app = api_router(state.clone()).with_state(state)- .layer(ServiceBuilder::new().layer(TraceLayer::new_for_http()))+ .layer(MacroRequestIdAndTracingLayer::new(Duration::from_millis(200)).into_inner())// The health router is attached here so we don't attach the logging middleware to it.merge(health::router()).layer(cors)diff --git a/rust/cloud-storage/macro_tower_layers/Cargo.toml b/rust/cloud-storage/macro_tower_layers/Cargo.tomlnew file mode 100644index 0000000000..cccda9f4ad--- /dev/null+++ b/rust/cloud-storage/macro_tower_layers/Cargo.toml@@ -0,0 +1,11 @@+[package]+edition = "2024"+name = "macro_tower_layers"+publish = false+version = "0.1.0"++[dependencies]+http = { workspace = true }+tower = { workspace = true }+tower-http = { workspace = true, features = ["request-id", "util"] }+tracing = { workspace = true }diff --git a/rust/cloud-storage/macro_tower_layers/src/lib.rs b/rust/cloud-storage/macro_tower_layers/src/lib.rsnew file mode 100644index 0000000000..f2df415e05--- /dev/null+++ b/rust/cloud-storage/macro_tower_layers/src/lib.rs@@ -0,0 +1,173 @@+#![deny(missing_docs)]+//! This crate provides small reusable tower-http utilities which are useful across macro's http services+use std::{+ cmp,+ sync::{+ Arc,+ atomic::{self, AtomicU64},+ },+ time::Duration,+};++use http::{HeaderValue, Request, Response};+use tower::{+ ServiceBuilder,+ layer::util::{Identity, Stack},+};+use tower_http::{+ ServiceBuilderExt,+ classify::{ServerErrorsAsFailures, SharedClassifier},+ request_id::{MakeRequestId, PropagateRequestIdLayer, RequestId, SetRequestIdLayer},+ trace::{DefaultMakeSpan, DefaultOnRequest, OnResponse, TraceLayer},+};+use tracing::{Level, Span};++/// A very simple builder for x-request-ids+#[derive(Default, Clone)]+pub struct RequestIdBuilder(Arc<AtomicU64>);++impl MakeRequestId for RequestIdBuilder {+ fn make_request_id<B>(+ &mut self,+ _request: &Request<B>,+ ) -> Option<tower_http::request_id::RequestId> {+ Some(RequestId::new(HeaderValue::from(+ self.0.fetch_add(1, atomic::Ordering::SeqCst),+ )))+ }+}++/// fork of the [DefaultOnResponse] which is deisgined to work with [RequestIdBuilder]+/// This emits a tracing warn event if a request takes more than a certain threshold to complete.+#[derive(Clone)]+pub struct CustomOnResponse {+ warning_threshold: Duration,+}++impl CustomOnResponse {+ /// create a new instance of self given a warning threshold duration+ pub fn new_with_threshold(warning_threshold: Duration) -> Self {+ CustomOnResponse { warning_threshold }+ }+}++/// dynamic tracing event macro+/// copied from [`tower_http`] source (its not public)+macro_rules! event_dynamic_lvl {+ ( $(target: $target:expr,)? $(parent: $parent:expr,)? $lvl:expr, $($tt:tt)* ) => {+ match $lvl {+ tracing::Level::ERROR => {+ tracing::event!(+ $(target: $target,)?+ $(parent: $parent,)?+ tracing::Level::ERROR,+ $($tt)*+ );+ }+ tracing::Level::WARN => {+ tracing::event!(+ $(target: $target,)?+ $(parent: $parent,)?+ tracing::Level::WARN,+ $($tt)*+ );+ }+ tracing::Level::INFO => {+ tracing::event!(+ $(target: $target,)?+ $(parent: $parent,)?+ tracing::Level::INFO,+ $($tt)*+ );+ }+ tracing::Level::DEBUG => {+ tracing::event!(+ $(target: $target,)?+ $(parent: $parent,)?+ tracing::Level::DEBUG,+ $($tt)*+ );+ }+ tracing::Level::TRACE => {+ tracing::event!(+ $(target: $target,)?+ $(parent: $parent,)?+ tracing::Level::TRACE,+ $($tt)*+ );+ }+ }+ };+}++impl<B> OnResponse<B> for CustomOnResponse {+ fn on_response(self, response: &Response<B>, latency: Duration, _span: &Span) {+ struct Latency {+ duration: Duration,+ }++ impl std::fmt::Display for Latency {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{} ms", self.duration.as_millis())+ }+ }++ let level = match latency.cmp(&self.warning_threshold) {+ cmp::Ordering::Less => Level::INFO,+ cmp::Ordering::Equal | cmp::Ordering::Greater => Level::WARN,+ };++ let latency = Latency { duration: latency };++ let response_headers = tracing::field::debug(response.headers());+ event_dynamic_lvl!(+ level,+ %latency,+ status = response.status().as_u16(),+ response_headers,+ "finished processing request"+ );+ }+}++type ServiceBuilderAlias = ServiceBuilder<+ Stack<+ PropagateRequestIdLayer,+ Stack<+ TraceLayer<+ SharedClassifier<ServerErrorsAsFailures>,+ DefaultMakeSpan,+ DefaultOnRequest,+ CustomOnResponse,+ >,+ Stack<SetRequestIdLayer<RequestIdBuilder>, Identity>,+ >,+ >,+>;++/// A wrapper over a [ServiceBuilder] which handles both request id and tracing.+/// See [CustomOnResponse] and [RequestIdBuilder] for more info.+pub struct MacroRequestIdAndTracingLayer {+ inner: ServiceBuilderAlias,+}++impl MacroRequestIdAndTracingLayer {+ /// contruct a new instance of self with the input warning threshold+ pub fn new(warning_threshold: Duration) -> Self {+ let svc_builder = ServiceBuilder::new()+ .set_x_request_id(RequestIdBuilder::default())+ .layer(+ TraceLayer::new_for_http()+ .make_span_with(DefaultMakeSpan::new().include_headers(true))+ .on_response(CustomOnResponse::new_with_threshold(warning_threshold)),+ )+ .propagate_x_request_id();++ MacroRequestIdAndTracingLayer { inner: svc_builder }+ }++ /// return the inner [ServiceBuilder] so that you can call the .layer method+ pub fn into_inner(self) -> ServiceBuilderAlias {+ self.inner+ }+}