Skip to content

A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.

TypeScript fluxerfluxerapp

perf(app-proxy): refresh branding on page loads, not a timer

Hampus4e512917d496
diff --git a/fluxer_app_proxy/src/branding_images.rs b/fluxer_app_proxy/src/branding_images.rs
index ef24b61b0..903acd02b 100644
--- a/fluxer_app_proxy/src/branding_images.rs
+++ b/fluxer_app_proxy/src/branding_images.rs
@@ -6,8 +6,8 @@ use axum::http::header;
use reqwest::Url;
use std::sync::Arc;
use std::time::Duration;
-use tokio::sync::watch;
-use tokio::task::JoinHandle;
+use tokio::sync::{Mutex, watch};
+use tokio::time::Instant;
const BRANDING_IMAGES: [(&str, &str); 7] = [
("icon_url", "FLUXER_APP_ICON_URL"),
@@ -39,7 +39,7 @@ const FAVICON_URL: (&str, &str) = ("favicon_url", "FLUXER_APP_FAVICON_URL");
const FAVICON_DARK_URL: (&str, &str) = ("favicon_dark_url", "FLUXER_APP_FAVICON_DARK_URL");
const THEME_COLOR: (&str, &str) = ("theme_color", "FLUXER_APP_THEME_COLOR");
const STATUS_PAGE_URL: &str = "FLUXER_APP_STATUS_PAGE_URL";
-const DISCOVERY_FETCH_TIMEOUT: Duration = Duration::from_secs(5);
+const DISCOVERY_FETCH_TIMEOUT: Duration = Duration::from_secs(2);
const DISCOVERY_BODY_BYTES_MAX: usize = 1024 * 1024;
const REFRESH_INTERVAL_MIN: Duration = Duration::from_secs(1);
const REFRESH_BACKOFF_MAX: Duration = Duration::from_secs(300);
@@ -243,12 +243,24 @@ pub struct BrandingSnapshot {
pub custom_css: Option<Arc<str>>,
}
+#[derive(Debug, Default)]
+struct RefreshGate {
+ next_attempt: Option<Instant>,
+ consecutive_failures: u32,
+}
+
#[derive(Clone, Debug)]
-pub struct InstanceBranding(watch::Sender<Arc<BrandingSnapshot>>);
+pub struct InstanceBranding {
+ current: watch::Sender<Arc<BrandingSnapshot>>,
+ gate: Arc<Mutex<RefreshGate>>,
+}
impl InstanceBranding {
pub fn new(snapshot: BrandingSnapshot) -> Self {
- Self(watch::Sender::new(Arc::new(snapshot)))
+ Self {
+ current: watch::Sender::new(Arc::new(snapshot)),
+ gate: Arc::default(),
+ }
}
pub fn from_config(config: &AppProxyConfig) -> Self {
@@ -260,7 +272,7 @@ impl InstanceBranding {
}
pub fn snapshot(&self) -> Arc<BrandingSnapshot> {
- self.0.borrow().clone()
+ self.current.borrow().clone()
}
pub async fn refresh(
@@ -272,7 +284,7 @@ impl InstanceBranding {
let Some(snapshot) = snapshot_from_discovery(&discovery) else {
anyhow::bail!("upstream discovery has no app_public.branding object");
};
- let changed = self.0.send_if_modified(|current| {
+ let changed = self.current.send_if_modified(|current| {
if **current == snapshot {
return false;
}
@@ -300,47 +312,43 @@ impl InstanceBranding {
Ok(())
}
- pub fn start_background_refresh(
- &self,
- client: reqwest::Client,
- upstream_url: String,
- interval: Duration,
- ) -> JoinHandle<()> {
- self.spawn_refresh_loop(client, upstream_url, interval.max(REFRESH_INTERVAL_MIN))
- }
-
- fn spawn_refresh_loop(
+ pub async fn refresh_if_due(
&self,
- client: reqwest::Client,
- upstream_url: String,
+ client: &reqwest::Client,
+ upstream_url: &str,
interval: Duration,
- ) -> JoinHandle<()> {
- let branding = self.clone();
- tokio::spawn(async move {
- let mut consecutive_failures: u32 = 0;
- loop {
- let wait = match branding.refresh(&client, &upstream_url).await {
- Ok(()) => {
- consecutive_failures = 0;
- interval
- }
- Err(error) => {
- let backoff = interval
- .saturating_mul(1 << consecutive_failures.min(5))
- .min(REFRESH_BACKOFF_MAX);
- consecutive_failures = consecutive_failures.saturating_add(1);
- tracing::warn!(
- %error,
- url = %upstream_url,
- consecutive_failures,
- backoff_ms = backoff.as_millis() as u64,
- "instance branding refresh failed, keeping the previous branding"
- );
- backoff
- }
- };
- tokio::time::sleep(wait).await;
+ ) {
+ let Ok(mut gate) = tokio::time::timeout(DISCOVERY_FETCH_TIMEOUT, self.gate.lock()).await
+ else {
+ return;
+ };
+ if gate
+ .next_attempt
+ .is_some_and(|next_attempt| Instant::now() < next_attempt)
+ {
+ return;
+ }
+ let interval = interval.max(REFRESH_INTERVAL_MIN);
+ let wait = match self.refresh(client, upstream_url).await {
+ Ok(()) => {
+ gate.consecutive_failures = 0;
+ interval
}
- })
+ Err(error) => {
+ let backoff = interval
+ .saturating_mul(1 << gate.consecutive_failures.min(5))
+ .min(REFRESH_BACKOFF_MAX);
+ gate.consecutive_failures = gate.consecutive_failures.saturating_add(1);
+ tracing::warn!(
+ %error,
+ url = %upstream_url,
+ consecutive_failures = gate.consecutive_failures,
+ backoff_ms = backoff.as_millis() as u64,
+ "instance branding refresh failed, keeping the previous branding"
+ );
+ backoff
+ }
+ };
+ gate.next_attempt = Some(Instant::now() + wait);
}
}
diff --git a/fluxer_app_proxy/src/main.rs b/fluxer_app_proxy/src/main.rs
index 0697447c8..361b7157c 100644
--- a/fluxer_app_proxy/src/main.rs
+++ b/fluxer_app_proxy/src/main.rs
@@ -8,7 +8,6 @@ use fluxer_app_proxy::{
state::{AppState, build_http_client},
};
use std::sync::Arc;
-use std::time::Duration;
use tokio::{net::TcpListener, runtime::Builder};
use tracing_subscriber::{layer::SubscriberExt, util::SubscriberInitExt};
@@ -38,14 +37,6 @@ fn main() -> anyhow::Result<()> {
.await
.context("failed to load the Fluxer app proxy static directory")?;
- let branding_refresh = state.config.self_hosted.then(|| {
- state.branding.start_background_refresh(
- state.http_client.clone(),
- state.config.discovery_upstream_url.clone(),
- Duration::from_millis(state.config.discovery_refresh_interval_ms),
- )
- });
-
let router = build_router(state);
let listener = TcpListener::bind(&addr)
.await
@@ -57,9 +48,6 @@ fn main() -> anyhow::Result<()> {
.await
.context("app proxy server exited unexpectedly")?;
- if let Some(branding_refresh) = branding_refresh {
- branding_refresh.abort();
- }
Ok(())
})
}
diff --git a/fluxer_app_proxy/src/routes/spa_index.rs b/fluxer_app_proxy/src/routes/spa_index.rs
index 0f153bfe5..c7639e11e 100644
--- a/fluxer_app_proxy/src/routes/spa_index.rs
+++ b/fluxer_app_proxy/src/routes/spa_index.rs
@@ -201,11 +201,9 @@ async fn serve_spa_index(state: &AppState, headers: &HeaderMap, request_path: &s
Ok(content) => content,
Err(response) => return response,
};
+ let branding = state.branding_snapshot().await;
let raw_html = if state.config.self_hosted {
- apply_instance_branding(
- strip_link_preview_metadata(&raw_html),
- &state.branding.snapshot(),
- )
+ apply_instance_branding(strip_link_preview_metadata(&raw_html), &branding)
} else {
raw_html
};
@@ -242,8 +240,8 @@ async fn serve_spa_index(state: &AppState, headers: &HeaderMap, request_path: &s
};
let csp = state.csp.spa_headers(
&inline_script_hashes(&html),
- &state.branding.image_origins(),
- &state.branding.instance_sources(),
+ &branding.image_origins,
+ &branding.instance_sources,
);
build_spa_response(html.into_boxed_str(), &csp, should_bust_dev_assets)
}
diff --git a/fluxer_app_proxy/src/routes/spa_static.rs b/fluxer_app_proxy/src/routes/spa_static.rs
index 59106f699..16874f424 100644
--- a/fluxer_app_proxy/src/routes/spa_static.rs
+++ b/fluxer_app_proxy/src/routes/spa_static.rs
@@ -29,7 +29,11 @@ pub async fn version_json(State(state): State<AppState>, headers: HeaderMap) ->
}
pub async fn manifest_json(State(state): State<AppState>, headers: HeaderMap) -> Response {
- let branding = state.config.self_hosted.then(|| state.branding.snapshot());
+ let branding = if state.config.self_hosted {
+ Some(state.branding_snapshot().await)
+ } else {
+ None
+ };
serve_static_text_file_with_substitutions(
&state,
&headers,
@@ -110,7 +114,7 @@ pub async fn browserconfig_xml(State(state): State<AppState>, headers: HeaderMap
}
pub async fn favicon_ico(State(state): State<AppState>) -> Response {
- let location = match state.branding.snapshot().favicon_url.as_deref() {
+ let location = match state.branding_snapshot().await.favicon_url.as_deref() {
Some(favicon_url) => favicon_url.to_owned(),
None => format!(
"{}/web/favicon.ico",
diff --git a/fluxer_app_proxy/src/state.rs b/fluxer_app_proxy/src/state.rs
index 9924af98f..05a004e0f 100644
--- a/fluxer_app_proxy/src/state.rs
+++ b/fluxer_app_proxy/src/state.rs
@@ -1,6 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
-use crate::branding_images::InstanceBranding;
+use crate::branding_images::{BrandingSnapshot, InstanceBranding};
use crate::config::{AppProxyConfig, HttpUrl};
use crate::csp::CompiledCspPolicy;
use crate::local_files::LocalFileStore;
@@ -110,6 +110,19 @@ impl AppState {
local_files,
})
}
+
+ pub async fn branding_snapshot(&self) -> Arc<BrandingSnapshot> {
+ if self.config.self_hosted {
+ self.branding
+ .refresh_if_due(
+ &self.http_client,
+ &self.config.discovery_upstream_url,
+ Duration::from_millis(self.config.discovery_refresh_interval_ms),
+ )
+ .await;
+ }
+ self.branding.snapshot()
+ }
}
#[derive(Debug, thiserror::Error)]