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.

fix: long response times (#1805)

Sean Aye2817f9e6a3bc
diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lock
index ca2fc015c2..0a3af349e8 100644
--- a/rust/cloud-storage/Cargo.lock
+++ b/rust/cloud-storage/Cargo.lock
@@ -3630,6 +3630,18 @@ dependencies = [
"uuid",
]
+[[package]]
+name = "enum-as-inner"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a1e6a265c649f3f5979b601d26f1d05ada116434c87741c9493cb56218f76cbc"
+dependencies = [
+ "heck",
+ "proc-macro2",
+ "quote",
+ "syn 2.0.98",
+]
+
[[package]]
name = "equator"
version = "0.4.2"
@@ -4358,6 +4370,51 @@ version = "0.4.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
+[[package]]
+name = "hickory-proto"
+version = "0.24.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "92652067c9ce6f66ce53cc38d1169daa36e6e7eb7dd3b63b5103bd9d97117248"
+dependencies = [
+ "async-trait",
+ "cfg-if",
+ "data-encoding",
+ "enum-as-inner",
+ "futures-channel",
+ "futures-io",
+ "futures-util",
+ "idna",
+ "ipnet",
+ "once_cell",
+ "rand 0.8.5",
+ "thiserror 1.0.69",
+ "tinyvec",
+ "tokio",
+ "tracing",
+ "url",
+]
+
+[[package]]
+name = "hickory-resolver"
+version = "0.24.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cbb117a1ca520e111743ab2f6688eddee69db4e0ea242545a604dce8a66fd22e"
+dependencies = [
+ "cfg-if",
+ "futures-util",
+ "hickory-proto",
+ "ipconfig",
+ "lru-cache",
+ "once_cell",
+ "parking_lot",
+ "rand 0.8.5",
+ "resolv-conf",
+ "smallvec",
+ "thiserror 1.0.69",
+ "tokio",
+ "tracing",
+]
+
[[package]]
name = "hkdf"
version = "0.12.4"
@@ -5032,6 +5089,18 @@ dependencies = [
"syn 2.0.98",
]
+[[package]]
+name = "ipconfig"
+version = "0.3.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b58db92f96b720de98181bbbe63c831e87005ab460c1bf306eb2622b4707997f"
+dependencies = [
+ "socket2 0.5.10",
+ "widestring",
+ "windows-sys 0.48.0",
+ "winreg",
+]
+
[[package]]
name = "ipnet"
version = "2.11.0"
@@ -5308,6 +5377,12 @@ dependencies = [
"glob",
]
+[[package]]
+name = "linked-hash-map"
+version = "0.5.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0717cef1bc8b636c6e1c1bbdefc09e6322da8a9321966e8928ef80d20f7f770f"
+
[[package]]
name = "linux-raw-sys"
version = "0.9.4"
@@ -5394,6 +5469,15 @@ dependencies = [
"hashbrown 0.16.1",
]
+[[package]]
+name = "lru-cache"
+version = "0.1.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "31e24f1ad8321ca0e8a1e0ac13f23cb668e6f5466c2c57319f6a5cf1cc8e3b1c"
+dependencies = [
+ "linked-hash-map",
+]
+
[[package]]
name = "lzma-rs"
version = "0.3.0"
@@ -5660,7 +5744,9 @@ dependencies = [
name = "macro_tower_layers"
version = "0.1.0"
dependencies = [
+ "axum",
"http 1.3.1",
+ "tokio",
"tower 0.5.2",
"tower-http",
"tracing",
@@ -6495,6 +6581,7 @@ dependencies = [
"macro_env",
"macro_env_var",
"macro_middleware",
+ "macro_tower_layers",
"macro_user_id",
"macro_uuid",
"mention_utils",
@@ -7808,6 +7895,7 @@ dependencies = [
"futures-core",
"futures-util",
"h2 0.4.13",
+ "hickory-resolver",
"http 1.3.1",
"http-body 1.0.1",
"http-body-util",
@@ -7820,6 +7908,7 @@ dependencies = [
"mime",
"mime_guess",
"native-tls",
+ "once_cell",
"percent-encoding",
"pin-project-lite",
"quinn",
@@ -7874,6 +7963,12 @@ dependencies = [
"tower-service",
]
+[[package]]
+name = "resolv-conf"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e061d1b48cb8d38042de4ae0a7a6401009d6143dc80d2e2d6f31f0bdd6470c7"
+
[[package]]
name = "rfc6979"
version = "0.3.1"
@@ -10731,6 +10826,12 @@ dependencies = [
"wasite",
]
+[[package]]
+name = "widestring"
+version = "1.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "72069c3113ab32ab29e5584db3c6ec55d416895e60715417b5b883a357c3e471"
+
[[package]]
name = "winapi"
version = "0.3.9"
@@ -11052,6 +11153,16 @@ dependencies = [
"memchr",
]
+[[package]]
+name = "winreg"
+version = "0.50.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "524e57b2c537c0f9b1e69f1965311ec12182b4122e45035b1508cd24d2adadb1"
+dependencies = [
+ "cfg-if",
+ "windows-sys 0.48.0",
+]
+
[[package]]
name = "wit-bindgen-rt"
version = "0.33.0"
diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.toml
index 2e96664c72..be67b00943 100644
--- a/rust/cloud-storage/Cargo.toml
+++ b/rust/cloud-storage/Cargo.toml
@@ -161,7 +161,9 @@ http = "1"
http-body-util = "0.1.2"
inquire = "0.7"
itertools = "0.14"
-jsonwebtoken = { git = "https://github.com/whutchinson98/jsonwebtoken", features = ["rust_crypto"] }
+jsonwebtoken = { git = "https://github.com/whutchinson98/jsonwebtoken", features = [
+ "rust_crypto",
+] }
lambda_runtime = "0.13.0"
lazy_static = "1.5.0"
log = "0.4.26"
@@ -179,7 +181,7 @@ rand = "0.9.0"
recursion = "0.5.4"
redis = "1.0.3"
regex = "1.11.1"
-reqwest = { version = "0.12.12", features = ["json"] }
+reqwest = { version = "0.12.12", features = ["hickory-dns", "json"] }
reqwest-middleware = { git = "https://github.com/seanaye/reqwest-middleware" }
rootcause = "0.11"
schemars = { version = "1.0.4", features = ["chrono04", "uuid1"] }
diff --git a/rust/cloud-storage/macro_auth/src/middleware/decode_jwt.rs b/rust/cloud-storage/macro_auth/src/middleware/decode_jwt.rs
index 45ee768c0a..550c7c17b8 100644
--- a/rust/cloud-storage/macro_auth/src/middleware/decode_jwt.rs
+++ b/rust/cloud-storage/macro_auth/src/middleware/decode_jwt.rs
@@ -1,3 +1,5 @@
+use std::sync::OnceLock;
+
use anyhow::Context;
use jsonwebtoken::{Algorithm, DecodingKey, Validation, decode};
use macro_env::Environment;
@@ -194,6 +196,8 @@ fn validate_macro_access_token_inner(
Ok(decoded_jwt)
}
+static DECODING_KEY: OnceLock<Result<DecodingKey, MacroAuthError>> = OnceLock::new();
+
#[tracing::instrument(skip_all)]
fn validate_macro_api_token(
macro_api_token: &str,
@@ -205,12 +209,18 @@ fn validate_macro_api_token(
validation.set_issuer(&[issuer.as_ref()]);
- let decoding_key = DecodingKey::from_rsa_pem(public_key.as_ref().as_bytes())
- .context("unable to decode key")?;
+ let init = move || {
+ Ok(DecodingKey::from_rsa_pem(public_key.as_ref().as_bytes())
+ .context("unable to decode key")?)
+ };
+ let decoding_key = DECODING_KEY
+ .get_or_init(init)
+ .as_ref()
+ .context("cached key failed to decode")?;
// Attempt to decode the token.
let decoded_jwt: MacroApiToken =
- match decode::<MacroApiToken>(macro_api_token, &decoding_key, &validation) {
+ match decode::<MacroApiToken>(macro_api_token, decoding_key, &validation) {
Ok(decoded) => decoded.claims,
Err(e) => match e.kind() {
jsonwebtoken::errors::ErrorKind::ExpiredSignature => {
diff --git a/rust/cloud-storage/macro_tower_layers/Cargo.toml b/rust/cloud-storage/macro_tower_layers/Cargo.toml
index cccda9f4ad..b6b9c310af 100644
--- a/rust/cloud-storage/macro_tower_layers/Cargo.toml
+++ b/rust/cloud-storage/macro_tower_layers/Cargo.toml
@@ -8,4 +8,8 @@ version = "0.1.0"
http = { workspace = true }
tower = { workspace = true }
tower-http = { workspace = true, features = ["request-id", "util"] }
+tokio = { workspace = true, features = ["time", "rt"] }
tracing = { workspace = true }
+
+[dev-dependencies]
+axum = { workspace = true }
diff --git a/rust/cloud-storage/macro_tower_layers/src/lib.rs b/rust/cloud-storage/macro_tower_layers/src/lib.rs
index f2df415e05..519d3c4dfa 100644
--- a/rust/cloud-storage/macro_tower_layers/src/lib.rs
+++ b/rust/cloud-storage/macro_tower_layers/src/lib.rs
@@ -1,5 +1,8 @@
#![deny(missing_docs)]
//! This crate provides small reusable tower-http utilities which are useful across macro's http services
+
+#[cfg(test)]
+mod test;
use std::{
cmp,
sync::{
@@ -10,6 +13,7 @@ use std::{
};
use http::{HeaderValue, Request, Response};
+use tokio::time::MissedTickBehavior;
use tower::{
ServiceBuilder,
layer::util::{Identity, Stack},
@@ -145,6 +149,33 @@ type ServiceBuilderAlias = ServiceBuilder<
>,
>;
+/// Spawns a background task that detects tokio runtime starvation.
+///
+/// Ticks on `interval` and warns if the actual time between ticks exceeds it.
+/// A large gap indicates the tokio runtime is not polling tasks promptly, typically caused
+/// by blocking work (e.g. synchronous DNS resolution) on the runtime threads.
+pub fn spawn_starvation_detector(interval: Duration) {
+ tokio::spawn(async move {
+ let mut tick = tokio::time::interval(interval);
+ tick.set_missed_tick_behavior(MissedTickBehavior::Skip);
+ // consume the immediate first tick
+ tick.tick().await;
+ loop {
+ let before = tokio::time::Instant::now();
+ tick.tick().await;
+ let elapsed = before.elapsed();
+ if elapsed > interval {
+ tracing::warn!(
+ expected_ms = interval.as_millis() as u64,
+ actual_ms = elapsed.as_millis() as u64,
+ delay_ms = elapsed.saturating_sub(interval).as_millis() as u64,
+ "tokio runtime starvation detected"
+ );
+ }
+ }
+ });
+}
+
/// A wrapper over a [ServiceBuilder] which handles both request id and tracing.
/// See [CustomOnResponse] and [RequestIdBuilder] for more info.
pub struct MacroRequestIdAndTracingLayer {
@@ -153,7 +184,12 @@ pub struct MacroRequestIdAndTracingLayer {
impl MacroRequestIdAndTracingLayer {
/// contruct a new instance of self with the input warning threshold
+ ///
+ /// Also spawns a background [starvation detector](spawn_starvation_detector) that
+ /// warns when the tokio runtime is not polling tasks promptly.
pub fn new(warning_threshold: Duration) -> Self {
+ spawn_starvation_detector(Duration::from_millis(250));
+
let svc_builder = ServiceBuilder::new()
.set_x_request_id(RequestIdBuilder::default())
.layer(
diff --git a/rust/cloud-storage/macro_tower_layers/src/test.rs b/rust/cloud-storage/macro_tower_layers/src/test.rs
new file mode 100644
index 0000000000..87c82a7835
--- /dev/null
+++ b/rust/cloud-storage/macro_tower_layers/src/test.rs
@@ -0,0 +1,114 @@
+use super::*;
+use std::sync::atomic::{AtomicBool, Ordering};
+use tower_http::trace::OnResponse;
+use tracing::subscriber::{set_default, with_default};
+
+/// Minimal tracing subscriber that records whether WARN or INFO events were emitted.
+struct LevelCapture {
+ saw_warn: Arc<AtomicBool>,
+ saw_info: Arc<AtomicBool>,
+}
+
+impl LevelCapture {
+ fn new() -> (Self, Arc<AtomicBool>, Arc<AtomicBool>) {
+ let saw_warn = Arc::new(AtomicBool::new(false));
+ let saw_info = Arc::new(AtomicBool::new(false));
+ (
+ Self {
+ saw_warn: saw_warn.clone(),
+ saw_info: saw_info.clone(),
+ },
+ saw_warn,
+ saw_info,
+ )
+ }
+}
+
+impl tracing::Subscriber for LevelCapture {
+ fn enabled(&self, _metadata: &tracing::Metadata<'_>) -> bool {
+ true
+ }
+
+ fn new_span(&self, _attrs: &tracing::span::Attributes<'_>) -> tracing::span::Id {
+ tracing::span::Id::from_u64(1)
+ }
+
+ fn record(&self, _span: &tracing::span::Id, _values: &tracing::span::Record<'_>) {}
+
+ fn record_follows_from(&self, _span: &tracing::span::Id, _follows: &tracing::span::Id) {}
+
+ fn event(&self, event: &tracing::Event<'_>) {
+ match *event.metadata().level() {
+ Level::WARN => self.saw_warn.store(true, Ordering::SeqCst),
+ Level::INFO => self.saw_info.store(true, Ordering::SeqCst),
+ _ => {}
+ }
+ }
+
+ fn enter(&self, _span: &tracing::span::Id) {}
+
+ fn exit(&self, _span: &tracing::span::Id) {}
+}
+
+#[test]
+fn warns_when_latency_exceeds_threshold() {
+ let (subscriber, saw_warn, saw_info) = LevelCapture::new();
+
+ with_default(subscriber, || {
+ let on_response = CustomOnResponse::new_with_threshold(Duration::from_millis(200));
+ let response = http::Response::builder().status(200).body(()).unwrap();
+ let span = tracing::info_span!("test");
+ on_response.on_response(&response, Duration::from_millis(300), &span);
+ });
+
+ assert!(saw_warn.load(Ordering::SeqCst));
+ assert!(!saw_info.load(Ordering::SeqCst));
+}
+
+#[test]
+fn info_when_latency_below_threshold() {
+ let (subscriber, saw_warn, saw_info) = LevelCapture::new();
+
+ with_default(subscriber, || {
+ let on_response = CustomOnResponse::new_with_threshold(Duration::from_millis(200));
+ let response = http::Response::builder().status(200).body(()).unwrap();
+ let span = tracing::info_span!("test");
+ on_response.on_response(&response, Duration::from_millis(50), &span);
+ });
+
+ assert!(!saw_warn.load(Ordering::SeqCst));
+ assert!(saw_info.load(Ordering::SeqCst));
+}
+
+#[test]
+fn warns_when_latency_equals_threshold() {
+ let (subscriber, saw_warn, _saw_info) = LevelCapture::new();
+
+ with_default(subscriber, || {
+ let on_response = CustomOnResponse::new_with_threshold(Duration::from_millis(200));
+ let response = http::Response::builder().status(200).body(()).unwrap();
+ let span = tracing::info_span!("test");
+ on_response.on_response(&response, Duration::from_millis(200), &span);
+ });
+
+ assert!(saw_warn.load(Ordering::SeqCst));
+}
+
+#[tokio::test]
+async fn starvation_detector_warns_when_runtime_blocked() {
+ let (subscriber, saw_warn, _saw_info) = LevelCapture::new();
+ let _guard = set_default(subscriber);
+
+ spawn_starvation_detector(Duration::from_millis(10));
+
+ // Let the detector initialize, consume its first tick, and enter the timing loop
+ tokio::time::sleep(Duration::from_millis(15)).await;
+
+ // Block the runtime thread — simulates starvation
+ std::thread::sleep(Duration::from_millis(50));
+
+ // Let the detector observe the delay and emit the warning
+ tokio::time::sleep(Duration::from_millis(15)).await;
+
+ assert!(saw_warn.load(Ordering::SeqCst));
+}
diff --git a/rust/cloud-storage/notification_service/Cargo.toml b/rust/cloud-storage/notification_service/Cargo.toml
index dd60641fe0..71a79bf439 100644
--- a/rust/cloud-storage/notification_service/Cargo.toml
+++ b/rust/cloud-storage/notification_service/Cargo.toml
@@ -38,6 +38,7 @@ macro_env_var = { path = "../macro_env_var" }
macro_middleware = { path = "../macro_middleware", default-features = false, features = [
"auth",
] }
+macro_tower_layers = { path = "../macro_tower_layers" }
macro_user_id = { path = "../macro_user_id" }
macro_uuid = { path = "../macro_uuid" }
mention_utils = { path = "../mention_utils" }
diff --git a/rust/cloud-storage/notification_service/src/api/mod.rs b/rust/cloud-storage/notification_service/src/api/mod.rs
index 91fe47ab3e..d71c24a68f 100644
--- a/rust/cloud-storage/notification_service/src/api/mod.rs
+++ b/rust/cloud-storage/notification_service/src/api/mod.rs
@@ -2,9 +2,11 @@ use crate::api::context::ApiContext;
use ::notification::inbound::http::NotificationRouterState;
use anyhow::Context;
use axum::Router;
+use macro_tower_layers::MacroRequestIdAndTracingLayer;
use model::version::{ServiceNameState, VersionedApiServiceName, validate_api_version};
+use std::time::Duration;
use tower::ServiceBuilder;
-use tower_http::{compression::CompressionLayer, trace::TraceLayer};
+use tower_http::compression::CompressionLayer;
use utoipa::OpenApi;
use utoipa_swagger_ui::SwaggerUi;
@@ -29,7 +31,7 @@ pub async fn setup_and_serve<S: ::notification::domain::service::NotificationRea
.merge(health::router())
.layer(
ServiceBuilder::new()
- .layer(TraceLayer::new_for_http())
+ .layer(MacroRequestIdAndTracingLayer::new(Duration::from_millis(200)).into_inner())
.layer(axum::middleware::from_fn_with_state(
ServiceNameState {
service_name: VersionedApiServiceName::NotificationService,