feat(server): add canary shell routing and document render caching

This commit is contained in:
DarkSky committed 2026-11-25 07:30:43 +09:00
1 parent 09b2a9b244
commit bc511a18bf
5 files changed
+361 -107

No files matched your search

+1 -4
View File
@@ -2236,10 +2236,7 @@ where
.configure_metrics_listener(cli.effective_host(), cli.metrics_port, built.role != ServerRole::Script);
let metrics_addr = match built.state.reconcile_metrics_listener().await {
Ok(a) => a,
Err(e) if cli.skip_schema_check => {
tracing::warn!(error = %e, "metrics reconcile skipped");
None
}
Err(_) if cli.skip_schema_check && built.state.app_config.app_configs_table_missing().await? => None,
Err(e) => return Err(e.into()),
};
@@ -133,6 +133,26 @@ async fn drop_empty_prisma_table(db_url: &str) {
reset_pool.close().await;
}
/// Reserves a free loopback TCP port strictly below the OS ephemeral client port pool
/// (`32768..60999`) with a per-process CSPRNG stride so neither outbound PG/Redis sockets
/// nor concurrent `nextest` / test-binary processes collide in the bind-and-drop window.
async fn reserve_non_ephemeral_loopback_port() -> u16 {
static NEXT_LOW_PORT: std::sync::OnceLock<std::sync::atomic::AtomicU16> = std::sync::OnceLock::new();
let counter = NEXT_LOW_PORT.get_or_init(|| {
let seed = 18_200 + (uuid::Uuid::new_v4().as_u128() % 10_000) as u16;
std::sync::atomic::AtomicU16::new(seed)
});
for _ in 0..4_000 {
let idx = counter.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
let candidate = 18_200 + (idx.wrapping_sub(18_200) % 10_000);
if let Ok(listener) = TcpListener::bind(("127.0.0.1", candidate)).await {
drop(listener);
return candidate;
}
}
panic!("unable to reserve non-ephemeral loopback port in 18200..28200");
}
/// Minimal local SMTP capture sink that records both raw SMTP commands (to detect
/// any unexpected `AUTH` credential leakage) and received message bodies.
struct LocalSmtpSink {
@@ -1766,9 +1786,7 @@ fn file_configured_metrics_port_and_dynamic_toggle_via_update_app_config() {
let pool = db.pool().clone();
// Reserve a free loopback port, then drop the probe listener and write it to config.json.
let probe = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let mport = probe.local_addr().unwrap().port();
drop(probe);
let mport = reserve_non_ephemeral_loopback_port().await;
std::fs::write(
&tmp_cfg_task,
serde_json::json!({ "metrics": { "enabled": true, "port": mport } }).to_string(),
@@ -2031,12 +2049,8 @@ fn dual_instance_metrics_broadcast_invalidates_cache_and_cli_port_priority() {
let cookie = format!("affine_session={session_id}; affine_user_id={admin_id}");
// Reserve two loopback ports for instances A and B.
let p_a = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port_a = p_a.local_addr().unwrap().port();
let p_b = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port_b = p_b.local_addr().unwrap().port();
drop(p_a);
drop(p_b);
let port_a = reserve_non_ephemeral_loopback_port().await;
let port_b = reserve_non_ephemeral_loopback_port().await;
let cfg_a = tmp_dir_task.join("a.json");
let cfg_b = tmp_dir_task.join("b.json");
@@ -2065,8 +2079,9 @@ fn dual_instance_metrics_broadcast_invalidates_cache_and_cli_port_priority() {
config_path: Some(cfg_path),
database_url: db_url.clone(),
redis_url: Some(redis_url.clone()),
redis_key_prefix: redis.key_prefix().to_owned(),
channel: Some("canary".into()),
db_max_connections: 4,
db_max_connections: 8,
skip_schema_check: true,
..ServerCli::default()
};
@@ -2250,12 +2265,8 @@ fn dual_instance_metrics_broadcast_invalidates_cache_and_cli_port_priority() {
b_url.set_password(Some("pw")).unwrap();
let b_db_url = b_url.to_string();
let p_a2 = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port_a2 = p_a2.local_addr().unwrap().port();
let p_b2 = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port_b2 = p_b2.local_addr().unwrap().port();
drop(p_a2);
drop(p_b2);
let port_a2 = reserve_non_ephemeral_loopback_port().await;
let port_b2 = reserve_non_ephemeral_loopback_port().await;
let cfg_a2 = tmp_dir_task.join("a2.json");
let cfg_b2 = tmp_dir_task.join("b2.json");
std::fs::write(
@@ -2437,9 +2448,7 @@ fn dual_instance_metrics_broadcast_invalidates_cache_and_cli_port_priority() {
// 4c. Isolated Redis PubSub channel regression for exact cache_generation, DB-read count,
// and 800ms backoff preservation under unrelated business and config events (immune to
// parallel tests sharing AFFINE_TEST_REDIS_URL on "affine:eventbus:v1").
let p_iso = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let port_iso = p_iso.local_addr().unwrap().port();
drop(p_iso);
let port_iso = reserve_non_ephemeral_loopback_port().await;
let cfg_iso = tmp_dir_task.join("iso.json");
std::fs::write(
&cfg_iso,
@@ -6,7 +6,7 @@ use std::sync::{Arc, Mutex, OnceLock};
use axum::Router;
use axum::extract::{Path as AxumPath, State};
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
use axum::http::{HeaderMap, HeaderValue, StatusCode, Uri, header};
use axum::response::{IntoResponse, Response};
use axum::routing::get;
use chrono::Utc;
@@ -168,6 +168,7 @@ pub fn render_doc_markdown_from_binary(bin: &[u8]) -> Option<(String, String, St
async fn handle_render_workspace_path(
State(state): State<RouterState>,
AxumPath(path): AxumPath<String>,
uri: Uri,
headers: HeaderMap,
) -> Response {
let resolved = match resolve_request_principal_with_policy(&state, &headers, true).await {
@@ -316,24 +317,45 @@ async fn handle_render_workspace_path(
}
}
let selfhosted = cfg.deployment_mode == DeploymentMode::Selfhosted;
let is_mobile = cfg.channel == "canary" && crate::rest::static_files::is_mobile_request(&headers);
let (shell, explicit_shell) = crate::rest::static_files::resolve_canary_shell(&uri, &headers, &cfg.channel);
let mut shell_dir = cfg.static_dir.as_deref().map(PathBuf::from);
if let Some(dir) = cfg.static_dir.as_deref()
&& cfg.channel == "canary"
{
for (cond, sub) in [
(shell == "legacy", "mobile-legacy"),
(matches!(shell, "legacy" | "native"), "mobile"),
] {
let candidate = dir.join(sub);
if cond
&& tokio::fs::metadata(candidate.join("index.html"))
.await
.is_ok_and(|m| m.is_file())
{
shell_dir = Some(candidate);
break;
}
}
}
let mut assets: AssetsManifest = (Vec::new(), Vec::new(), "/".into(), String::new(), String::new());
if let Some(dir) = cfg.static_dir.as_deref() {
type AssetsCache = Mutex<HashMap<(PathBuf, bool, bool), AssetsManifest>>;
static CACHE: OnceLock<AssetsCache> = OnceLock::new();
let (key, cache) = (
(dir.to_path_buf(), is_mobile, selfhosted),
CACHE.get_or_init(Default::default),
);
if let Some(c) = cache.lock().ok().and_then(|g| g.get(&key).cloned()) {
assets = c;
let mut native_shell_template: Option<String> = None;
if let Some(base) = shell_dir.as_deref() {
type ShellAssetsCache = Mutex<HashMap<(PathBuf, bool), (AssetsManifest, Option<String>)>>;
static CACHE: OnceLock<ShellAssetsCache> = OnceLock::new();
let (key, cache) = ((base.to_path_buf(), selfhosted), CACHE.get_or_init(Default::default));
if let Some((cached_assets, cached_tpl)) = cache.lock().ok().and_then(|g| g.get(&key).cloned()) {
assets = cached_assets;
native_shell_template = cached_tpl;
} else {
let base = if is_mobile {
dir.join("mobile")
} else {
dir.to_path_buf()
};
if let Ok(raw) = tokio::fs::read_to_string(base.join("assets-manifest.json")).await
let manifest_path = base.join("assets-manifest.json");
let has_manifest = tokio::fs::metadata(&manifest_path).await.is_ok_and(|m| m.is_file());
let mut cacheable = false;
if !has_manifest {
if let Ok(tpl) = tokio::fs::read_to_string(base.join("index.html")).await {
native_shell_template = Some(tpl);
cacheable = true;
}
} else if let Ok(raw) = tokio::fs::read_to_string(&manifest_path).await
&& let Ok(v) = serde_json::from_str::<Value>(&raw)
{
let pp_raw = v.get("publicPath").and_then(Value::as_str).unwrap_or("/");
@@ -346,12 +368,13 @@ async fn handle_render_workspace_path(
};
let gs = |k: &str| v.get(k).and_then(Value::as_str).unwrap_or("").to_owned();
assets = (list("css"), list("js"), pp, gs("gitHash"), gs("description"));
cacheable = true;
}
if let Ok(mut g) = cache.lock() {
if cacheable && let Ok(mut g) = cache.lock() {
if g.len() >= 64 {
g.clear();
}
g.insert(key, assets.clone());
g.insert(key, (assets.clone(), native_shell_template.clone()));
}
}
}
@@ -385,19 +408,26 @@ async fn handle_render_workspace_path(
} else {
r#"<meta name="robots" content="noindex, nofollow" />"#
};
let css: String = assets
.0
.iter()
.map(|u| format!(r#"<link rel="stylesheet" href="{}" crossorigin />"#, esc(u)))
.collect();
let js: String = assets
.1
.iter()
.map(|u| format!(r#"<script src="{}" crossorigin></script>"#, esc(u)))
.collect();
let html = format!(
r##"<!DOCTYPE html><html><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /><meta name="mobile-web-app-capable" content="yes" /><meta name="apple-mobile-web-app-capable" content="yes" /><meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />{itunes}<title>{title}</title><meta name="theme-color" content="#fafafa" />{preconnect}<link rel="manifest" href="/manifest.json" /><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" /><link rel="icon" sizes="192x192" href="/favicon-192.png" /><link rel="shortcut icon" href="/favicon.ico?v=2" /><meta name="emotion-insertion-point" content="" />{robots}<meta name="twitter:title" content="{title}" /><meta name="twitter:description" content="{summary}" /><meta name="twitter:site" content="@AffineOfficial" /><meta name="twitter:image" content="{image}" /><meta property="og:title" content="{title}" /><meta property="og:description" content="{summary}" /><meta property="og:image" content="{image}" /><meta name="env:publicPath" content="{pp}" /><meta name="env:subPath" content="{sp}" /><meta name="env:renderer" content="ssr" />{sh_meta}{css}</head><body><div id="app" data-version="{hash}"></div>{js}</body></html>"##
);
let html = if let Some(template) = native_shell_template {
let og_meta = format!(
r#"{robots}<meta name="twitter:title" content="{title}" /><meta name="twitter:description" content="{summary}" /><meta name="twitter:site" content="@AffineOfficial" /><meta name="twitter:image" content="{image}" /><meta property="og:title" content="{title}" /><meta property="og:description" content="{summary}" /><meta property="og:image" content="{image}" /><meta name="env:renderer" content="ssr" />"#
);
inject_ssr_meta_into_shell_html(&template, &title, &og_meta)
} else {
let css: String = assets
.0
.iter()
.map(|u| format!(r#"<link rel="stylesheet" href="{}" crossorigin />"#, esc(u)))
.collect();
let js: String = assets
.1
.iter()
.map(|u| format!(r#"<script src="{}" crossorigin></script>"#, esc(u)))
.collect();
format!(
r##"<!DOCTYPE html><html><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" /><meta name="mobile-web-app-capable" content="yes" /><meta name="apple-mobile-web-app-capable" content="yes" /><meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />{itunes}<title>{title}</title><meta name="theme-color" content="#fafafa" />{preconnect}<link rel="manifest" href="/manifest.json" /><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png" /><link rel="icon" sizes="192x192" href="/favicon-192.png" /><link rel="shortcut icon" href="/favicon.ico?v=2" /><meta name="emotion-insertion-point" content="" />{robots}<meta name="twitter:title" content="{title}" /><meta name="twitter:description" content="{summary}" /><meta name="twitter:site" content="@AffineOfficial" /><meta name="twitter:image" content="{image}" /><meta property="og:title" content="{title}" /><meta property="og:description" content="{summary}" /><meta property="og:image" content="{image}" /><meta name="env:publicPath" content="{pp}" /><meta name="env:subPath" content="{sp}" /><meta name="env:renderer" content="ssr" />{sh_meta}{css}</head><body><div id="app" data-version="{hash}"></div>{js}</body></html>"##
)
};
let mut resp = (
StatusCode::OK,
[(header::CONTENT_TYPE, "text/html; charset=utf-8")],
@@ -411,6 +441,31 @@ async fn handle_render_workspace_path(
HeaderValue::from_static("noindex"),
);
}
if cfg.channel == "canary" {
h.insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));
h.insert(header::VARY, HeaderValue::from_static("User-Agent, Cookie"));
}
if let Some(sh) = explicit_shell {
crate::rest::static_files::append_shell_cookie(h, sh, https);
}
resolved.cookie_action.apply_to(h, https);
resp
}
fn inject_ssr_meta_into_shell_html(template: &str, title: &str, meta_tags: &str) -> String {
let lower = template.to_ascii_lowercase();
let with_title = if let (Some(t_start), Some(t_end_rel)) = (lower.find("<title>"), lower.find("</title>"))
&& t_end_rel > t_start
{
let t_end = t_end_rel + "</title>".len();
format!("{}<title>{title}</title>{}", &template[..t_start], &template[t_end..])
} else {
template.to_owned()
};
let lower_wt = with_title.to_ascii_lowercase();
if let Some(head_close) = lower_wt.find("</head>") {
format!("{}{meta_tags}{}", &with_title[..head_close], &with_title[head_close..])
} else {
format!("{meta_tags}{with_title}")
}
}
@@ -23,6 +23,44 @@ fn parse_shell(raw: &str) -> Option<&'static str> {
.into_iter()
.find(|&s| raw.trim().eq_ignore_ascii_case(s))
}
pub(crate) fn resolve_canary_shell(
uri: &Uri,
headers: &HeaderMap,
channel: &str,
) -> (&'static str, Option<&'static str>) {
if channel != "canary" {
return ("desktop", None);
}
let q_shell = uri.query().and_then(|q| {
q.split('&').find_map(|p| {
p.split_once('=')
.and_then(|(k, v)| (k == "shell").then(|| parse_shell(v)).flatten())
})
});
if let Some(ex) = q_shell {
(ex, Some(ex))
} else {
let def = if is_mobile_request(headers) {
"native"
} else {
"desktop"
};
(
extract_cookie(&parse_cookies(headers), SHELL_COOKIE_NAME)
.and_then(parse_shell)
.unwrap_or(def),
None,
)
}
}
pub(crate) fn append_shell_cookie(headers: &mut HeaderMap, shell: &str, https: bool) {
if let Ok(v) = HeaderValue::from_str(&format!(
"{SHELL_COOKIE_NAME}={shell}; Path=/; SameSite=Lax{}",
if https { "; Secure" } else { "" }
)) {
headers.append(header::SET_COOKIE, v);
}
}
fn found_redirect(state: &RouterState, target: &str) -> Response {
let cfg = state.app.config.load();
let base = cfg.app_config_baseline.server.path.trim().trim_end_matches('/');
@@ -137,15 +175,14 @@ fn content_type_for_path(path: &Path) -> &'static str {
})
.unwrap_or("application/octet-stream")
}
async fn serve_file(
r: &Path,
rel: &str,
m: &Method,
h: &HeaderMap,
ns: bool,
sh: Option<&str>,
#[derive(Clone, Copy)]
struct ServeOpts<'a> {
no_store: bool,
vary_shell: bool,
set_shell: Option<&'a str>,
https: bool,
) -> Option<Response> {
}
async fn serve_file(r: &Path, rel: &str, m: &Method, h: &HeaderMap, opts: ServeOpts<'_>) -> Option<Response> {
let path = safe_join(r, rel)?;
let meta = tokio::fs::metadata(&path).await.ok()?;
if !meta.is_file() || meta.len() > 64 * 1024 * 1024 {
@@ -201,16 +238,14 @@ async fn serve_file(
}
}
}
if ns {
if opts.no_store || opts.set_shell.is_some() {
rh.insert(header::CACHE_CONTROL, HeaderValue::from_static(CACHE_CONTROL_NO_STORE));
}
if let Some(sh) = sh
&& let Ok(v) = HeaderValue::from_str(&format!(
"{SHELL_COOKIE_NAME}={sh}; Path=/; SameSite=Lax{}",
if https { "; Secure" } else { "" }
))
{
rh.append(header::SET_COOKIE, v);
if opts.vary_shell || opts.set_shell.is_some() {
rh.insert(header::VARY, HeaderValue::from_static("User-Agent, Cookie"));
}
if let Some(sh) = opts.set_shell {
append_shell_cookie(rh, sh, opts.https);
}
Some(resp)
}
@@ -233,10 +268,17 @@ async fn handle_static(state: RouterState, method: Method, uri: Uri, headers: He
cfg.deployment_mode == DeploymentMode::Selfhosted && matches!(method, Method::GET | Method::HEAD);
let is_setup_path = path == "/admin/setup";
let (m, h, https) = (&method, &headers, cfg.https);
let is_canary = cfg.channel == "canary";
let opts = |no_store, vary_shell, set_shell| ServeOpts {
no_store,
vary_shell,
set_shell,
https,
};
if path == "/admin" || path.starts_with("/admin/") {
let admin_root = static_root.join("admin");
if let Some(rel) = path.strip_prefix("/admin/").filter(|r| !r.is_empty())
&& let Some(resp) = serve_file(&admin_root, rel, m, h, false, None, https).await
&& let Some(resp) = serve_file(&admin_root, rel, m, h, opts(false, false, None)).await
{
return resp;
}
@@ -248,16 +290,16 @@ async fn handle_static(state: RouterState, method: Method, uri: Uri, headers: He
return found_redirect(&state, "/admin");
}
}
return or_404(serve_file(&admin_root, html_entry, m, h, true, None, https).await);
return or_404(serve_file(&admin_root, html_entry, m, h, opts(true, false, None)).await);
}
if !is_front {
let mobile = cfg.channel == "canary" && is_mobile_request(h);
let mobile = is_canary && is_mobile_request(h);
let mobile_root = static_root.join("mobile");
for root in [mobile.then_some(mobile_root.as_path()), Some(static_root)]
.into_iter()
.flatten()
{
if let Some(resp) = serve_file(root, path, m, h, false, None, https).await {
if let Some(resp) = serve_file(root, path, m, h, opts(false, is_canary, None)).await {
return resp;
}
}
@@ -272,36 +314,19 @@ async fn handle_static(state: RouterState, method: Method, uri: Uri, headers: He
} else {
static_root
};
return or_404(serve_file(fb, html_entry, m, h, true, None, https).await);
return or_404(serve_file(fb, html_entry, m, h, opts(true, is_canary, None)).await);
}
for (prefix, sub) in [
("/wasm/", "mobile/wasm"),
("/pkg/", "mobile/pkg"),
("/mobile/", "mobile"),
("/mobile-legacy/", "mobile-legacy"),
] {
if let Some(rel) = path.strip_prefix(prefix) {
return or_404(serve_file(&static_root.join(sub), rel, m, h, false, None, https).await);
return or_404(serve_file(&static_root.join(sub), rel, m, h, opts(false, false, None)).await);
}
}
let q_shell = uri.query().and_then(|q| {
q.split('&').find_map(|p| {
p.split_once('=')
.and_then(|(k, v)| (k == "shell").then(|| parse_shell(v)).flatten())
})
});
let (shell, explicit) = if cfg.channel != "canary" {
("desktop", None)
} else if let Some(ex) = q_shell {
(ex, Some(ex))
} else {
let def = if is_mobile_request(h) { "native" } else { "desktop" };
(
extract_cookie(&parse_cookies(h), SHELL_COOKIE_NAME)
.and_then(parse_shell)
.unwrap_or(def),
None,
)
};
let (shell, explicit) = resolve_canary_shell(&uri, h, &cfg.channel);
let (mut shell_root, mut is_mobile_shell) = (static_root.to_path_buf(), false);
for (cond, sub) in [
(shell == "legacy", "mobile-legacy"),
@@ -314,9 +339,9 @@ async fn handle_static(state: RouterState, method: Method, uri: Uri, headers: He
}
}
if STRICT_ASSET_PREFIXES.iter().any(|prefix| path.starts_with(prefix)) {
return or_404(serve_file(&shell_root, path, m, h, false, explicit, https).await);
return or_404(serve_file(&shell_root, path, m, h, opts(false, is_canary, None)).await);
}
if let Some(resp) = serve_file(&shell_root, path, m, h, true, explicit, https).await {
if let Some(resp) = serve_file(&shell_root, path, m, h, opts(true, is_canary, explicit)).await {
return resp;
}
if is_selfhost_get
@@ -328,11 +353,10 @@ async fn handle_static(state: RouterState, method: Method, uri: Uri, headers: He
let is_auth = MOBILE_AUTH_PATHS
.iter()
.any(|p| path == *p || path.strip_prefix(p).is_some_and(|r| r.starts_with('/')));
let fb =
if cfg.channel == "canary" && is_mobile_shell && is_auth && is_file_async(&shell_root.join("sign-in.html")).await {
"sign-in.html"
} else {
"index.html"
};
or_404(serve_file(&shell_root, fb, m, h, true, explicit, https).await)
let fb = if is_canary && is_mobile_shell && is_auth && is_file_async(&shell_root.join("sign-in.html")).await {
"sign-in.html"
} else {
"index.html"
};
or_404(serve_file(&shell_root, fb, m, h, opts(true, is_canary, explicit)).await)
}
@@ -236,12 +236,13 @@ fn static_files_front_canary_mobile_shell_contract_and_strict_404() {
resp.headers().get(header::CACHE_CONTROL).unwrap(),
"private, no-cache, no-store, max-age=0, must-revalidate"
);
assert_eq!(resp.headers().get(header::VARY).unwrap(), "User-Agent, Cookie");
assert_eq!(
axum::body::to_bytes(resp.into_body(), 1024).await.unwrap(),
"mobile-signin"
);
// 3. `?shell=legacy` overrides mobile UA and sets `affine_shell=legacy` cookie.
// 3. `?shell=legacy` overrides mobile UA, sets `affine_shell=legacy` cookie, and emits `Vary` + `no-store`.
let resp = app
.clone()
.oneshot(
@@ -254,6 +255,11 @@ fn static_files_front_canary_mobile_shell_contract_and_strict_404() {
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(
resp.headers().get(header::CACHE_CONTROL).unwrap(),
"private, no-cache, no-store, max-age=0, must-revalidate"
);
assert_eq!(resp.headers().get(header::VARY).unwrap(), "User-Agent, Cookie");
let set_cookie = resp.headers().get(header::SET_COOKIE).unwrap().to_str().unwrap();
assert!(set_cookie.contains("affine_shell=legacy"), "{set_cookie}");
assert_eq!(
@@ -261,7 +267,8 @@ fn static_files_front_canary_mobile_shell_contract_and_strict_404() {
"mobile-legacy-index"
);
// 4. `affine_shell=desktop` cookie overrides mobile UA.
// 4. `affine_shell=desktop` cookie overrides mobile UA, emits `Vary: User-Agent, Cookie`,
// and `?shell=` on strict static assets never sets `Set-Cookie` on cacheable responses.
let resp = app
.clone()
.oneshot(
@@ -275,11 +282,38 @@ fn static_files_front_canary_mobile_shell_contract_and_strict_404() {
.await
.unwrap();
assert_eq!(resp.status(), StatusCode::OK);
assert_eq!(resp.headers().get(header::VARY).unwrap(), "User-Agent, Cookie");
assert!(resp.headers().get(header::SET_COOKIE).is_none());
assert_eq!(
axum::body::to_bytes(resp.into_body(), 1024).await.unwrap(),
"desktop-js"
);
let asset_shell_query = app
.clone()
.oneshot(
Request::builder()
.uri("/assets/app.js?shell=legacy")
.header(header::USER_AGENT, mobile_ua)
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(asset_shell_query.status(), StatusCode::OK);
assert_eq!(
asset_shell_query.headers().get(header::VARY).unwrap(),
"User-Agent, Cookie"
);
assert!(
asset_shell_query.headers().get(header::SET_COOKIE).is_none(),
"strict static asset response must never attach Set-Cookie"
);
assert_eq!(
axum::body::to_bytes(asset_shell_query.into_body(), 1024).await.unwrap(),
"mobile-legacy-js"
);
// 5. `/wasm/` serves `application/wasm` from `mobile/wasm` and strictly 404s on miss.
let wasm_ok = app
.clone()
@@ -314,6 +348,141 @@ fn static_files_front_canary_mobile_shell_contract_and_strict_404() {
.unwrap();
assert_eq!(asset_miss.status(), StatusCode::NOT_FOUND);
// 7. `/mobile/` cookie-immune prefix serves native shell assets even when `affine_shell=legacy`.
let mobile_cookie_immune = app
.clone()
.oneshot(
Request::builder()
.uri("/mobile/assets/app.js")
.header(header::COOKIE, "affine_shell=legacy")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(mobile_cookie_immune.status(), StatusCode::OK);
assert_eq!(
axum::body::to_bytes(mobile_cookie_immune.into_body(), 1024)
.await
.unwrap(),
"mobile-native-js"
);
// 8. DocRenderer injects SSR OpenGraph into native `mobile/index.html` and respects `?shell=legacy`.
std::fs::write(
fixture.join("mobile/index.html"),
"<!doctype html><html><head><title>AFFiNE</title></head><body><canvas id=\"app-canvas\"></canvas></body></html>",
)
.unwrap();
std::fs::write(
fixture.join("mobile-legacy/assets-manifest.json"),
r#"{"publicPath":"/mobile-legacy/","css":[],"js":["bundle.js"],"gitHash":"abc","description":"Legacy"}"#,
)
.unwrap();
sqlx::query("INSERT INTO workspaces (id, name) VALUES ('ws-og', 'OG WS')")
.execute(db.pool())
.await
.unwrap();
let og_bin = build_sample_yjs_doc("Canary Share Title", "Public OG summary text");
sqlx::query("INSERT INTO snapshots (workspace_id, guid, blob, updated_at) VALUES ('ws-og', 'doc-og', $1, now())")
.bind(&og_bin)
.execute(db.pool())
.await
.unwrap();
sqlx::query("INSERT INTO workspace_pages (workspace_id, page_id, published_at) VALUES ('ws-og', 'doc-og', now())")
.execute(db.pool())
.await
.unwrap();
sqlx::query(
"INSERT INTO doc_access_policies (workspace_id, doc_id, visibility, public_role, published_at) \
VALUES ('ws-og', 'doc-og', 'public', 'external', now())",
)
.execute(db.pool())
.await
.unwrap();
let native_og = app
.clone()
.oneshot(
Request::builder()
.uri("/workspace/ws-og/doc-og")
.header(header::USER_AGENT, mobile_ua)
.header(header::ACCEPT, "text/html")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(native_og.status(), StatusCode::OK);
assert!(native_og.headers().get("x-robots-tag").is_none());
assert_eq!(
native_og
.headers()
.get(header::CACHE_CONTROL)
.and_then(|v| v.to_str().ok()),
Some("no-store")
);
assert_eq!(
native_og.headers().get(header::VARY).and_then(|v| v.to_str().ok()),
Some("User-Agent, Cookie")
);
let native_og_html = String::from_utf8(
axum::body::to_bytes(native_og.into_body(), 16 * 1024)
.await
.unwrap()
.to_vec(),
)
.unwrap();
assert!(native_og_html.contains("Canary Share Title"), "{native_og_html}");
assert!(native_og_html.contains("property=\"og:title\""), "{native_og_html}");
assert!(native_og_html.contains("id=\"app-canvas\""), "{native_og_html}");
let legacy_og = app
.clone()
.oneshot(
Request::builder()
.uri("/workspace/ws-og/doc-og?shell=legacy")
.header(header::USER_AGENT, mobile_ua)
.header(header::ACCEPT, "text/html")
.body(Body::empty())
.unwrap(),
)
.await
.unwrap();
assert_eq!(legacy_og.status(), StatusCode::OK);
assert_eq!(
legacy_og
.headers()
.get(header::CACHE_CONTROL)
.and_then(|v| v.to_str().ok()),
Some("no-store")
);
assert_eq!(
legacy_og.headers().get(header::VARY).and_then(|v| v.to_str().ok()),
Some("User-Agent, Cookie")
);
assert!(
legacy_og
.headers()
.get(header::SET_COOKIE)
.unwrap()
.to_str()
.unwrap()
.contains("affine_shell=legacy")
);
let legacy_og_html = String::from_utf8(
axum::body::to_bytes(legacy_og.into_body(), 16 * 1024)
.await
.unwrap()
.to_vec(),
)
.unwrap();
assert!(legacy_og_html.contains("Canary Share Title"), "{legacy_og_html}");
assert!(
legacy_og_html.contains("mobile-legacy&#x2f;bundle.js") || legacy_og_html.contains("/mobile-legacy/bundle.js"),
"{legacy_og_html}"
);
let _ = std::fs::remove_dir_all(&fixture);
db.pool().close().await;
});