fix(app-proxy): serve bundled assets locally when a cdn is set (#3532)

This commit is contained in:
Hampus authored and GitHub committed 2026-10-19 11:50:42 +02:00
1 parent b8d43af191
commit 7dfd346448
7 files changed
+108 -9

No files matched your search

+98 -8
View File
@@ -23,14 +23,17 @@ pub async fn proxy_assets(
Path(path): Path<String>,
request: axum::extract::Request,
) -> Response {
let Some(cdn_endpoint) = &state.config.static_cdn_endpoint else {
return serve_local_asset(
&state.local_files,
&format!("assets/{path}"),
request.headers(),
state.csp.asset_header(),
)
.await;
let cdn_endpoint = match &state.config.static_cdn_endpoint {
Some(endpoint) if !state.bundled_app_assets => endpoint,
_ => {
return serve_local_asset(
&state.local_files,
&format!("assets/{path}"),
request.headers(),
state.csp.asset_header(),
)
.await;
}
};
if path
@@ -146,6 +149,18 @@ fn upstream_asset_body(
))
}
pub fn bundles_app_assets(static_dir: &str) -> bool {
let Ok(entries) = std::fs::read_dir(std::path::Path::new(static_dir).join("assets")) else {
return false;
};
entries.flatten().any(|entry| {
entry
.path()
.extension()
.is_some_and(|extension| extension == "js")
})
}
pub(super) async fn serve_local_asset(
files: &LocalFileStore,
relative_path: &str,
@@ -241,6 +256,7 @@ mod tests {
http_client: build_http_client().unwrap(),
spa_index_source: SpaIndexSource::bundled(""),
local_asset_prefixes: None,
bundled_app_assets: false,
budgets,
local_files,
}
@@ -1191,4 +1207,78 @@ mod tests {
"a response served past the read slot count had the wrong bytes"
);
}
async fn spawn_counting_upstream() -> (String, Arc<AtomicU64>) {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let hits = Arc::new(AtomicU64::new(0));
let counter = Arc::clone(&hits);
let router = Router::new().fallback(move || {
let counter = Arc::clone(&counter);
async move {
counter.fetch_add(1, Ordering::Relaxed);
Response::new(Body::from("cdn-bytes"))
}
});
tokio::spawn(async move {
axum::serve(listener, router).await.unwrap();
});
(format!("http://{addr}"), hits)
}
fn cdn_and_local_state(cdn_endpoint: &str, static_dir: &str) -> AppState {
let mut state = upstream_backed_state(cdn_endpoint);
let mut config = (*state.config).clone();
config.static_dir = static_dir.to_owned();
state.local_files =
LocalFileStore::load_blocking(std::path::Path::new(static_dir), &state.budgets)
.unwrap();
state.config = Arc::new(config);
state.bundled_app_assets = bundles_app_assets(static_dir);
state
}
async fn get_asset(state: AppState, asset_path: &str) -> Response {
super::super::build_router(state)
.oneshot(
HttpRequest::builder()
.uri(format!("/assets/{asset_path}"))
.body(Body::empty())
.unwrap(),
)
.await
.unwrap()
}
#[tokio::test]
async fn an_image_with_the_app_built_in_serves_assets_itself_when_a_cdn_is_set() {
let fixture = LocalAssetDir::with_asset("356aaade04a117b1.js", b"local-bytes");
let (endpoint, hits) = spawn_counting_upstream().await;
let state = cdn_and_local_state(&endpoint, fixture.dir());
assert!(state.bundled_app_assets);
let response = get_asset(state, "356aaade04a117b1.js").await;
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(body_bytes(response).await, b"local-bytes");
assert_eq!(
hits.load(Ordering::Relaxed),
0,
"a cdn that pulls from this instance would send the request back here"
);
}
#[tokio::test]
async fn an_image_without_the_app_built_in_still_takes_assets_from_the_cdn() {
let fixture = LocalAssetDir::with_asset("fonts-latin.txt", b"font list");
let (endpoint, hits) = spawn_counting_upstream().await;
let state = cdn_and_local_state(&endpoint, fixture.dir());
assert!(!state.bundled_app_assets);
let response = get_asset(state, "356aaade04a117b1.js").await;
assert_eq!(response.status(), StatusCode::OK);
assert_eq!(body_bytes(response).await, b"cdn-bytes");
assert_eq!(hits.load(Ordering::Relaxed), 1);
}
}
+1
View File
@@ -34,6 +34,7 @@ mod tests {
http_client: build_http_client().unwrap(),
spa_index_source: SpaIndexSource::bundled(""),
local_asset_prefixes: None,
bundled_app_assets: false,
budgets,
local_files,
}
+1
View File
@@ -8,6 +8,7 @@ mod health;
mod spa_index;
mod spa_static;
pub use assets_proxy::bundles_app_assets;
pub use spa_index::present_local_asset_prefixes;
use crate::state::AppState;
+1
View File
@@ -1346,6 +1346,7 @@ mod tests {
http_client: reqwest::Client::new(),
spa_index_source,
local_asset_prefixes: None,
bundled_app_assets: false,
budgets,
local_files,
}
@@ -402,6 +402,7 @@ mod tests {
http_client: reqwest::Client::new(),
spa_index_source: crate::state::SpaIndexSource::bundled(""),
local_asset_prefixes: None,
bundled_app_assets: false,
budgets,
local_files,
}
+4 -1
View File
@@ -4,7 +4,7 @@ use crate::branding_images::InstanceBranding;
use crate::config::{AppProxyConfig, HttpUrl};
use crate::csp::CompiledCspPolicy;
use crate::local_files::LocalFileStore;
use crate::routes::present_local_asset_prefixes;
use crate::routes::{bundles_app_assets, present_local_asset_prefixes};
use std::sync::Arc;
use std::time::Duration;
use tokio::io::AsyncReadExt;
@@ -87,6 +87,7 @@ pub struct AppState {
pub http_client: reqwest::Client,
pub spa_index_source: SpaIndexSource,
pub local_asset_prefixes: Option<Arc<[&'static str]>>,
pub bundled_app_assets: bool,
pub budgets: AppProxyBudgets,
pub(crate) local_files: LocalFileStore,
}
@@ -103,6 +104,7 @@ impl AppState {
let spa_index_source = SpaIndexSource::load(&config).await?;
let local_asset_prefixes = (!spa_index_source.is_upstream())
.then(|| present_local_asset_prefixes(&config.static_dir));
let bundled_app_assets = bundles_app_assets(&config.static_dir);
Ok(Self {
branding: InstanceBranding::from_config(&config),
config,
@@ -110,6 +112,7 @@ impl AppState {
http_client,
spa_index_source,
local_asset_prefixes,
bundled_app_assets,
budgets,
local_files,
})
@@ -250,6 +250,8 @@ Defaults to the derived endpoint. The public Media Proxy URL. The `gifs` service
Defaults to the derived endpoint. The static asset origin. Read by `api`, `worker`, `admin`, and `app-proxy`. When it is unset, `admin` gets the public origin, and every other service derives it itself.
The web app's JavaScript and CSS are built into the `app-proxy` image, which serves them under `/assets/` on the instance's own address whatever this is set to. In the web app, this setting moves only the favicon and the icons used when someone installs the app. To cache the web app's files on a CDN, put the CDN in front of the instance's own hostname. Every file under `/assets/` has a content hash in its name and is sent with a one-year cache lifetime.
#### `FLUXER_ADMIN_ENDPOINT`
Defaults to the derived endpoint. The admin origin. The API accepts exactly this value plus `/oauth2_callback` as the admin OAuth redirect URI. Compose forwards it from `.env`, and builds it from the public origin and `FLUXER_ADMIN_BASE_PATH` when it is unset.