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.

perf(cors): cache preflights for two hours (#7763)

Wolf Mermelstein40ceda68ebe8
diff --git a/Cargo.lock b/Cargo.lock
index 99492b0ace..4d2c1f0706 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -11483,6 +11483,8 @@ name = "macro_cors"
version = "0.1.0"
dependencies = [
"axum",
+ "tokio",
+ "tower 0.5.3",
"tower-http",
"workspace-hack",
]
diff --git a/crates/macro_cors/Cargo.toml b/crates/macro_cors/Cargo.toml
index 26eb67eb58..d2390ab5f6 100644
--- a/crates/macro_cors/Cargo.toml
+++ b/crates/macro_cors/Cargo.toml
@@ -8,3 +8,7 @@ version = "0.1.0"
axum = { workspace = true }
tower-http = { workspace = true }
workspace-hack = { version = "0.1", path = "../workspace-hack" }
+
+[dev-dependencies]
+tokio = { workspace = true }
+tower = { workspace = true }
diff --git a/crates/macro_cors/src/lib.rs b/crates/macro_cors/src/lib.rs
index d5987d691c..56b906fbb9 100644
--- a/crates/macro_cors/src/lib.rs
+++ b/crates/macro_cors/src/lib.rs
@@ -1,7 +1,7 @@
#[cfg(test)]
mod test;
-use std::borrow::Cow;
+use std::{borrow::Cow, time::Duration};
use axum::http::{
HeaderName, HeaderValue, Method,
@@ -30,6 +30,10 @@ static EXTRA_HEADERS: [&str; 4] = [
"x-email-link-id",
];
+/// Chrome caps preflight caching at two hours. Without a max age it caches for
+/// five seconds, so any API call after a short idle pays an extra round trip.
+const PREFLIGHT_MAX_AGE: Duration = Duration::from_secs(2 * 60 * 60);
+
fn get_allowed_origins() -> Vec<Cow<'static, str>> {
#[allow(
clippy::disallowed_methods,
@@ -86,6 +90,7 @@ pub fn cors_layer_with_headers(additional_headers: Vec<HeaderName>) -> CorsLayer
);
CorsLayer::new()
+ .max_age(PREFLIGHT_MAX_AGE)
.allow_credentials(true)
.allow_headers(headers)
.allow_methods(vec![
diff --git a/crates/macro_cors/src/test.rs b/crates/macro_cors/src/test.rs
index 498012788f..1f9de0d4f9 100644
--- a/crates/macro_cors/src/test.rs
+++ b/crates/macro_cors/src/test.rs
@@ -33,3 +33,30 @@ fn allows_static_origins() {
assert!(is_allowed_origin("https://macro.com"));
assert!(is_allowed_origin("tauri://localhost"));
}
+
+#[tokio::test]
+async fn preflight_is_cacheable_for_two_hours() {
+ use axum::{
+ Router,
+ body::Body,
+ http::{Request, header},
+ routing::post,
+ };
+ use tower::ServiceExt;
+
+ let app = Router::new()
+ .route("/items/soup/graphql", post(|| async {}))
+ .layer(cors_layer());
+ let preflight = Request::builder()
+ .method(Method::OPTIONS)
+ .uri("/items/soup/graphql")
+ .header(header::ORIGIN, "https://macro.com")
+ .header(header::ACCESS_CONTROL_REQUEST_METHOD, "POST")
+ .header(header::ACCESS_CONTROL_REQUEST_HEADERS, "content-type")
+ .body(Body::empty())
+ .unwrap();
+
+ let response = app.oneshot(preflight).await.unwrap();
+
+ assert_eq!(response.headers()[header::ACCESS_CONTROL_MAX_AGE], "7200");
+}