Skip to content

World's first open-source enterprise world model.

Nothing under /api or /assets is a page (#615)

WaylandYangfe1d4549b7ff
diff --git a/Cargo.toml b/Cargo.toml
index 7efa074c..351d61cf 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -24,7 +24,7 @@ utopia-store = { path = "crates/utopia-store" }
tokio = { version = "1", features = ["full"] }
axum = { version = "0.8", features = ["multipart"] }
axum-extra = { version = "0.10", features = ["cookie"] }
-tower-http = { version = "0.6", features = ["cors", "trace", "fs"] }
+tower-http = { version = "0.6", features = ["cors", "trace", "fs", "set-header"] }
sqlx = { version = "0.8", default-features = false, features = [
# mysql 只为问数引擎而开(query_engine::mysql):一条线协议顺带覆盖
# TiDB / OceanBase / Doris / StarRocks。本体的库始终是 postgres。
diff --git a/crates/utopia-server/src/api/mod.rs b/crates/utopia-server/src/api/mod.rs
index ff44353c..a9e56e37 100644
--- a/crates/utopia-server/src/api/mod.rs
+++ b/crates/utopia-server/src/api/mod.rs
@@ -25,13 +25,17 @@ mod workspaces;
use axum::extract::DefaultBodyLimit;
use axum::http::{header, HeaderValue, Method};
-use axum::routing::{get, patch, post};
+use axum::routing::{any, get, patch, post};
use axum::{Json, Router};
use serde_json::json;
use tower_http::cors::CorsLayer;
use tower_http::services::{ServeDir, ServeFile};
+use tower_http::set_header::SetResponseHeaderLayer;
use tower_http::trace::TraceLayer;
use utopia_core::config::AppConfig;
+use utopia_core::error::AppError;
+
+use crate::error::ApiErr;
use crate::state::AppState;
@@ -484,13 +488,52 @@ pub fn router(state: AppState, cfg: &AppConfig) -> Router {
.allow_headers([header::CONTENT_TYPE, header::AUTHORIZATION])
.allow_credentials(true);
- let mut app = Router::new().nest("/api/v1", api).layer(cors);
+ /* **`/api` 下面认不出来的路径是 404,不是首页。**
+ 下面那个 history fallback 是给页面路由用的:刷新 /graph 要拿到 index.html。
+ 可它挂在**整个应用**上,于是拼错或已经删掉的接口也落进同一张网,回的是
+ `200 text/html`。客户端那头 `res.json()` 抛 "Unexpected token '<'",
+ 报错的位置离原因十万八千里;对着 MCP 与 RDF 那两个对外契约的集成方更糟,
+ 通用 HTTP 客户端看到 200 当成功,解析器看到的是一张网页。
+ 给嵌套的 API 路由自己一个兜底,形状与其余错误一致(error.rs 里
+ `NotFound` 就映射成 404)。 */
+ let api = api.fallback(|| async { ApiErr(AppError::NotFound) });
+ let mut app = Router::new()
+ .nest("/api/v1", api)
+ /* 版本号写错、或者干脆忘了写的请求(`/api/kbs`、`/api/v2/...`)落不进上面
+ 那个嵌套,还是会掉到首页去。**`/api` 底下没有页面**,所以整条前缀都收住;
+ 静态段比通配更具体,`/api/v1/...` 仍然走上面那个路由。 */
+ .route("/api/{*rest}", any(|| async { ApiErr(AppError::NotFound) }))
+ .layer(cors);
+
+ /* SPA 托管。**分两条路,因为它们的失败方式不一样**:
+
+ `/assets` 下面是构建产物,文件名带内容哈希。这里的 ServeDir **不带兜底**,
+ 所以缺文件就是 404。从前它和页面共用一个带 history fallback 的服务,于是
+ 升级之后旧哈希的请求拿到的是 `200 text/html` 的首页——浏览器按模块脚本
+ 解析一张网页,光凭 MIME 就拒绝执行,界面白屏(#616)。
- // SPA 托管:产物存在则挂载,history fallback 到 index.html
+ 缓存指示按文件名本来的含义给:带哈希的产物换了内容就换名字,可以
+ `immutable` 存一年;`index.html` 每次都要回源确认,否则它会指着一批
+ 已经不存在的哈希。少了这一条,升级要等浏览器的启发式缓存自己过期。 */
let index = std::path::Path::new(&cfg.web_dist).join("index.html");
if index.exists() {
- let serve = ServeDir::new(&cfg.web_dist).fallback(ServeFile::new(index));
- app = app.fallback_service(serve);
+ /* 每条路各自套自己的头。**层要挂在这一段的 Router 上,不能挂在整个
+ app 上**——挂在 app 上,API 的响应也会跟着被扣上 `immutable`。 */
+ let assets = Router::new()
+ .fallback_service(ServeDir::new(
+ std::path::Path::new(&cfg.web_dist).join("assets"),
+ ))
+ .layer(SetResponseHeaderLayer::overriding(
+ header::CACHE_CONTROL,
+ HeaderValue::from_static("public, max-age=31536000, immutable"),
+ ));
+ let spa = Router::new()
+ .fallback_service(ServeDir::new(&cfg.web_dist).fallback(ServeFile::new(index)))
+ .layer(SetResponseHeaderLayer::overriding(
+ header::CACHE_CONTROL,
+ HeaderValue::from_static("no-cache"),
+ ));
+ app = app.nest("/assets", assets).fallback_service(spa);
tracing::info!("已托管前端产物: {}", cfg.web_dist);
}