use crate::action::{
ApiResponse, Request, RequestId, RequestMeta, ResponseAttachment, TENANT_ID_HEADER,
};
use crate::definition::{
schema_subtree_contains_binary, ActionHandle, ActionMediaType, ActionRef, BuiltApp,
MultipartSpec,
};
use crate::error::{BaseError, ErrorCategory};
use axum::body::{to_bytes, Body};
use axum::extract::{
ConnectInfo, DefaultBodyLimit, FromRequest, Multipart, Path, Request as AxumRequest, State,
};
use axum::http::{header, HeaderName, HeaderValue, Method, StatusCode};
use axum::response::{IntoResponse, Response};
use axum::routing::{on, MethodFilter};
use axum::{Json, Router};
use serde_json::json;
use serde_json::{map::Entry, Map, Value};
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::AsyncWriteExt;
use tower::limit::ConcurrencyLimitLayer;
use tower_http::compression::CompressionLayer;
use tower_http::cors::{Any, CorsLayer};
use tower_http::timeout::TimeoutLayer;
use tower_http::trace::TraceLayer;
const DEFAULT_MAX_BODY_BYTES: usize = 2 * 1024 * 1024;
#[derive(Debug, Clone)]
pub struct CorsConfig {
pub origins: Vec<String>,
pub methods: Vec<String>,
pub headers: Vec<String>,
pub credentials: bool,
pub max_age_secs: u64,
}
impl Default for CorsConfig {
fn default() -> Self {
Self {
origins: Vec::new(),
methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"]
.iter()
.map(|method| (*method).to_string())
.collect(),
headers: [
"content-type",
"authorization",
"x-request-id",
"x-step-up-proof",
TENANT_ID_HEADER,
]
.iter()
.map(|name| (*name).to_string())
.collect(),
credentials: false,
max_age_secs: 86400,
}
}
}
#[derive(Debug, Clone)]
pub struct AxumTransportConfig {
pub max_body_bytes: usize,
pub cors: CorsConfig,
pub request_timeout: Option<Duration>,
pub max_concurrency: Option<usize>,
pub compression: bool,
}
impl Default for AxumTransportConfig {
fn default() -> Self {
Self {
max_body_bytes: DEFAULT_MAX_BODY_BYTES,
cors: CorsConfig::default(),
request_timeout: None,
max_concurrency: None,
compression: true,
}
}
}
#[derive(Clone)]
struct HttpState {
app: Arc<BuiltApp>,
local_addr: Option<SocketAddr>,
max_body_bytes: usize,
}
#[derive(Clone)]
enum RequestDecoder {
Json,
Multipart {
spec: MultipartSpec,
input_schema: Value,
},
}
struct DecodedBody {
value: Value,
resource_guard: Option<Arc<tempfile::TempDir>>,
}
pub fn router(app: Arc<BuiltApp>, config: AxumTransportConfig) -> Result<Router, BaseError> {
router_with_addr(app, config, None)
}
pub async fn serve(
bind: SocketAddr,
app: Arc<BuiltApp>,
config: AxumTransportConfig,
) -> Result<(), BaseError> {
let listener = tokio::net::TcpListener::bind(bind)
.await
.map_err(|error| BaseError::ConfigError(format!("绑定 HTTP 地址失败 {bind}: {error}")))?;
let local_addr = listener
.local_addr()
.map_err(|error| BaseError::ConfigError(format!("读取 HTTP 监听地址失败: {error}")))?;
let router = router_with_addr(app, config, Some(local_addr))?;
tracing::info!(address = %local_addr, "HTTP 服务已启动");
axum::serve(
listener,
router.into_make_service_with_connect_info::<SocketAddr>(),
)
.with_graceful_shutdown(crate::lifecycle::wait_for_shutdown_signal())
.await
.map_err(|error| BaseError::ConfigError(format!("HTTP 服务运行失败: {error}")))
}
fn router_with_addr(
app: Arc<BuiltApp>,
config: AxumTransportConfig,
local_addr: Option<SocketAddr>,
) -> Result<Router, BaseError> {
let state = HttpState {
app,
local_addr,
max_body_bytes: config.max_body_bytes,
};
let mut router = Router::new()
.route("/health/live", axum::routing::get(live))
.route("/health/ready", axum::routing::get(ready));
for addon in state.app.catalog().addons() {
for module in &addon.modules {
for action in module.actions() {
let method_filter = method_filter(action.route.method.as_str())?;
let path = action.route.path.clone();
let reference = ActionRef::new(module.name.clone(), action.name.clone());
let handle = state.app.registry().resolve(&reference).ok_or_else(|| {
BaseError::ConfigError(format!("Action 未预编译到 Registry: {reference}"))
})?;
let success_status = action.success_status;
let (decoder, body_limit) = match action.request_media_type {
ActionMediaType::Json => (RequestDecoder::Json, state.max_body_bytes),
ActionMediaType::Multipart => {
let spec = action.multipart.clone().ok_or_else(|| {
BaseError::ConfigError(format!(
"multipart Action 缺少资源限制: {reference}"
))
})?;
let action_limit = usize::try_from(spec.max_total_bytes).map_err(|_| {
BaseError::ConfigError(format!(
"multipart Action 请求上限超出平台 usize: {reference}"
))
})?;
if action_limit > state.max_body_bytes {
return Err(BaseError::ConfigError(format!(
"multipart Action {reference} 的 max_total_bytes={} 超过 AxumTransportConfig.max_body_bytes={}",
spec.max_total_bytes, state.max_body_bytes
)));
}
(
RequestDecoder::Multipart {
spec,
input_schema: action.input_schema.clone(),
},
action_limit,
)
}
};
let method_router = on(
method_filter,
move |State(state): State<HttpState>,
ConnectInfo(peer): ConnectInfo<SocketAddr>,
Path(path_params): Path<HashMap<String, String>>,
request: AxumRequest| {
let decoder = decoder.clone();
async move {
dispatch_request(
state,
peer,
path_params,
request,
handle,
success_status,
decoder,
)
.await
}
},
)
.layer(DefaultBodyLimit::max(body_limit));
router = router.route(&path, method_router);
}
}
}
let mut router = router.with_state(state);
if config.compression {
router = router.layer(CompressionLayer::new());
}
if let Some(max_concurrency) = config.max_concurrency {
if max_concurrency == 0 {
return Err(BaseError::ConfigError(
"HTTP max_concurrency 必须大于 0".to_string(),
));
}
router = router.layer(ConcurrencyLimitLayer::new(max_concurrency));
}
if let Some(timeout) = config.request_timeout {
router = router.layer(TimeoutLayer::with_status_code(
StatusCode::REQUEST_TIMEOUT,
timeout,
));
}
if let Some(cors) = cors_layer(&config.cors)? {
router = router.layer(cors);
}
Ok(router.layer(TraceLayer::new_for_http()))
}
fn cors_layer(config: &CorsConfig) -> Result<Option<CorsLayer>, BaseError> {
if config.origins.is_empty() {
return Ok(None);
}
let wildcard = config.origins.iter().any(|origin| origin == "*");
if wildcard && config.credentials {
return Err(BaseError::ConfigError(
"CORS 禁止通配来源与 credentials 同用(浏览器规范拒绝该组合)".to_string(),
));
}
let methods = config
.methods
.iter()
.map(|method| {
Method::from_bytes(method.as_bytes()).map_err(|_| {
BaseError::ConfigError(format!("CORS 配置包含非法 HTTP 方法: {method}"))
})
})
.collect::<Result<Vec<_>, _>>()?;
let headers = config
.headers
.iter()
.map(|name| {
HeaderName::from_bytes(name.as_bytes())
.map_err(|_| BaseError::ConfigError(format!("CORS 配置包含非法请求头: {name}")))
})
.collect::<Result<Vec<_>, _>>()?;
let layer = CorsLayer::new()
.allow_methods(methods)
.allow_headers(headers)
.max_age(Duration::from_secs(config.max_age_secs));
let layer = if wildcard {
layer.allow_origin(Any)
} else {
let origins = config
.origins
.iter()
.map(|origin| {
HeaderValue::from_str(origin)
.map_err(|_| BaseError::ConfigError(format!("CORS 配置包含非法来源: {origin}")))
})
.collect::<Result<Vec<_>, _>>()?;
layer.allow_origin(origins)
};
let layer = if config.credentials {
layer.allow_credentials(true)
} else {
layer
};
Ok(Some(layer))
}
async fn live() -> impl IntoResponse {
Json(ApiResponse::success_value(
json!({"status": "live"}),
"服务存活",
))
}
async fn ready(State(state): State<HttpState>) -> Response {
let health = state.app.tools().health_check().await;
if health.is_healthy() {
(
StatusCode::OK,
Json(ApiResponse::success_value(
json!({"status": "ready"}),
"服务就绪",
)),
)
.into_response()
} else {
tracing::warn!(?health, "就绪检查失败");
(
StatusCode::SERVICE_UNAVAILABLE,
Json(ApiResponse::fail(900001, "服务尚未就绪")),
)
.into_response()
}
}
async fn dispatch_request(
state: HttpState,
peer: SocketAddr,
path_params: HashMap<String, String>,
request: AxumRequest,
handle: ActionHandle,
success_status: u16,
decoder: RequestDecoder,
) -> Response {
let method = request.method().clone();
let uri = request.uri().clone();
let headers: HashMap<String, String> = request
.headers()
.iter()
.filter_map(|(name, value)| {
value
.to_str()
.ok()
.map(|value| (name.as_str().to_string(), value.to_string()))
})
.collect();
let request_id = headers
.get("x-request-id")
.and_then(|raw| RequestId::parse_hex(raw))
.unwrap_or_default();
let query = match uri.query() {
Some(raw) => match serde_urlencoded::from_str::<HashMap<String, String>>(raw) {
Ok(query) => query,
Err(_) => {
return with_request_id_header(
error_response(
StatusCode::BAD_REQUEST,
BaseError::ParamInvalid(
"query".to_string(),
"查询参数编码无效".to_string(),
),
),
request_id,
);
}
},
None => HashMap::new(),
};
let decoded = match decode_request_body(&state, request, decoder).await {
Ok(decoded) => decoded,
Err((status, error)) => {
return with_request_id_header(error_response(status, error), request_id);
}
};
let mut action_request = Request::new(decoded.value)
.headers(headers)
.queries(query)
.path_params(path_params);
if let Some(resource_guard) = decoded.resource_guard {
action_request = action_request.retain_resource(resource_guard);
}
let request_meta = RequestMeta::new()
.with_method(method.to_string())
.with_original_uri(uri.to_string())
.with_scheme(uri.scheme_str().unwrap_or("http"))
.with_peer_addr(peer);
let request_meta = match state.local_addr {
Some(addr) => request_meta.with_local_addr(addr),
None => request_meta,
};
let context = state
.app
.context(action_request)
.with_request_meta(request_meta)
.with_request_id(request_id);
let response = match state.app.dispatch_context(handle, context).await {
Ok(response) => match response.attachment.clone() {
Some(attachment) => attachment_response(attachment).await,
None => {
let status = StatusCode::from_u16(success_status).unwrap_or(StatusCode::OK);
(status, Json(response)).into_response()
}
},
Err(error) => {
let status = status_for_error(&error);
if status.is_server_error() {
tracing::error!(error = %error, code = error.code(), "请求处理失败");
}
error_response(status, error)
}
};
with_request_id_header(response, request_id)
}
async fn decode_request_body(
state: &HttpState,
request: AxumRequest,
decoder: RequestDecoder,
) -> Result<DecodedBody, (StatusCode, BaseError)> {
match decoder {
RequestDecoder::Json => {
let body = to_bytes(request.into_body(), state.max_body_bytes)
.await
.map_err(|_| {
(
StatusCode::PAYLOAD_TOO_LARGE,
BaseError::ParamInvalid("body".to_string(), "请求体过大".to_string()),
)
})?;
let value = if body.is_empty() {
json!({})
} else {
serde_json::from_slice(&body).map_err(|_| {
(
StatusCode::BAD_REQUEST,
BaseError::ParamInvalid(
"body".to_string(),
"请求体必须是 JSON".to_string(),
),
)
})?
};
Ok(DecodedBody {
value,
resource_guard: None,
})
}
RequestDecoder::Multipart { spec, input_schema } => {
decode_multipart(state, request, &spec, &input_schema).await
}
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum MultipartPartKind {
Text,
File,
}
async fn decode_multipart(
state: &HttpState,
request: AxumRequest,
spec: &MultipartSpec,
input_schema: &Value,
) -> Result<DecodedBody, (StatusCode, BaseError)> {
let content_type = request
.headers()
.get(header::CONTENT_TYPE)
.and_then(|value| value.to_str().ok())
.unwrap_or_default();
let media_type = content_type.split(';').next().unwrap_or_default().trim();
if !media_type.eq_ignore_ascii_case("multipart/form-data") {
return Err(multipart_error(
StatusCode::UNSUPPORTED_MEDIA_TYPE,
"body",
"请求 Content-Type 必须是 multipart/form-data",
));
}
if request
.headers()
.get(header::CONTENT_LENGTH)
.and_then(|value| value.to_str().ok())
.and_then(|value| value.parse::<u64>().ok())
.is_some_and(|length| length > spec.max_total_bytes)
{
return Err(multipart_error(
StatusCode::PAYLOAD_TOO_LARGE,
"body",
"multipart 请求体过大",
));
}
let scope = Arc::new(tempfile::tempdir().map_err(|error| {
(
StatusCode::INTERNAL_SERVER_ERROR,
BaseError::IoError(format!("创建上传临时目录失败: {error}")),
)
})?);
let mut multipart = Multipart::from_request(request, state)
.await
.map_err(|rejection| {
let status = rejection.status();
let status = if status == StatusCode::PAYLOAD_TOO_LARGE {
status
} else {
StatusCode::BAD_REQUEST
};
multipart_error(status, "body", "multipart 请求格式无效")
})?;
let mut body = Map::new();
let mut kinds = HashMap::new();
let mut field_count = 0_u16;
let mut file_count = 0_u16;
let mut payload_bytes = 0_u64;
while let Some(mut field) = multipart.next_field().await.map_err(|error| {
let status = error.status();
let status = if status == StatusCode::PAYLOAD_TOO_LARGE {
status
} else {
StatusCode::BAD_REQUEST
};
multipart_error(status, "body", "multipart 字段读取失败")
})? {
let name = field
.name()
.filter(|name| !name.is_empty() && name.len() <= 255)
.map(str::to_string)
.ok_or_else(|| {
multipart_error(
StatusCode::BAD_REQUEST,
"body",
"multipart 字段名缺失或过长",
)
})?;
let raw_filename = field.file_name().map(str::to_string);
if let Some(raw_filename) = raw_filename {
file_count = file_count.checked_add(1).ok_or_else(|| {
multipart_error(StatusCode::PAYLOAD_TOO_LARGE, &name, "文件数量超过上限")
})?;
if file_count > spec.max_files {
return Err(multipart_error(
StatusCode::PAYLOAD_TOO_LARGE,
&name,
"文件数量超过上限",
));
}
let content_type = field
.content_type()
.map(|value| {
value
.split(';')
.next()
.unwrap_or_default()
.trim()
.to_ascii_lowercase()
})
.ok_or_else(|| {
multipart_error(
StatusCode::UNSUPPORTED_MEDIA_TYPE,
&name,
"上传文件缺少 Content-Type",
)
})?;
if !spec
.allowed_content_types
.iter()
.any(|allowed| allowed == &content_type)
{
return Err(multipart_error(
StatusCode::UNSUPPORTED_MEDIA_TYPE,
&name,
"上传文件 Content-Type 不在 Action 白名单中",
));
}
let named = tempfile::Builder::new()
.prefix("yang-upload-")
.tempfile_in(scope.path())
.map_err(|error| {
(
StatusCode::INTERNAL_SERVER_ERROR,
BaseError::IoError(format!("创建上传临时文件失败: {error}")),
)
})?;
let (file, path) = named.keep().map_err(|error| {
(
StatusCode::INTERNAL_SERVER_ERROR,
BaseError::IoError(format!("持有上传临时文件失败: {}", error.error)),
)
})?;
let mut output = tokio::fs::File::from_std(file);
let mut file_bytes = 0_u64;
while let Some(chunk) = field.chunk().await.map_err(|error| {
let status = error.status();
let status = if status == StatusCode::PAYLOAD_TOO_LARGE {
status
} else {
StatusCode::BAD_REQUEST
};
multipart_error(status, &name, "上传文件读取失败")
})? {
file_bytes = checked_payload_size(file_bytes, chunk.len(), spec.max_file_bytes)
.map_err(|_| {
multipart_error(StatusCode::PAYLOAD_TOO_LARGE, &name, "单文件大小超过上限")
})?;
payload_bytes =
checked_payload_size(payload_bytes, chunk.len(), spec.max_total_bytes)
.map_err(|_| {
multipart_error(
StatusCode::PAYLOAD_TOO_LARGE,
"body",
"multipart 请求体过大",
)
})?;
output.write_all(&chunk).await.map_err(|error| {
(
StatusCode::INTERNAL_SERVER_ERROR,
BaseError::IoError(format!("写入上传临时文件失败: {error}")),
)
})?;
}
output.flush().await.map_err(|error| {
(
StatusCode::INTERNAL_SERVER_ERROR,
BaseError::IoError(format!("刷新上传临时文件失败: {error}")),
)
})?;
drop(output);
let value = json!({
"field_name": name,
"original_filename": sanitize_filename(&raw_filename),
"content_type": content_type,
"size": file_bytes,
"path": path,
"temp_root": scope.path()
});
insert_multipart_value(&mut body, &mut kinds, name, MultipartPartKind::File, value)?;
} else {
field_count = field_count.checked_add(1).ok_or_else(|| {
multipart_error(StatusCode::PAYLOAD_TOO_LARGE, &name, "表单字段数量超过上限")
})?;
if field_count > spec.max_fields {
return Err(multipart_error(
StatusCode::PAYLOAD_TOO_LARGE,
&name,
"表单字段数量超过上限",
));
}
let mut bytes = Vec::new();
let mut field_bytes = 0_u64;
while let Some(chunk) = field.chunk().await.map_err(|error| {
let status = error.status();
let status = if status == StatusCode::PAYLOAD_TOO_LARGE {
status
} else {
StatusCode::BAD_REQUEST
};
multipart_error(status, &name, "表单字段读取失败")
})? {
field_bytes =
checked_payload_size(field_bytes, chunk.len(), spec.max_text_field_bytes)
.map_err(|_| {
multipart_error(
StatusCode::PAYLOAD_TOO_LARGE,
&name,
"表单字段大小超过上限",
)
})?;
payload_bytes =
checked_payload_size(payload_bytes, chunk.len(), spec.max_total_bytes)
.map_err(|_| {
multipart_error(
StatusCode::PAYLOAD_TOO_LARGE,
"body",
"multipart 请求体过大",
)
})?;
bytes.extend_from_slice(&chunk);
}
let text = String::from_utf8(bytes).map_err(|_| {
multipart_error(
StatusCode::BAD_REQUEST,
&name,
"multipart 文本字段必须是 UTF-8",
)
})?;
if text_part_targets_binary(input_schema, &name) {
return Err(multipart_error(
StatusCode::BAD_REQUEST,
&name,
"包含文件字段的字段必须以文件形式上传",
));
}
let value = decode_text_value(input_schema, &name, text)?;
insert_multipart_value(&mut body, &mut kinds, name, MultipartPartKind::Text, value)?;
}
}
Ok(DecodedBody {
value: Value::Object(body),
resource_guard: Some(scope),
})
}
fn checked_payload_size(current: u64, added: usize, limit: u64) -> Result<u64, ()> {
let added = u64::try_from(added).map_err(|_| ())?;
let next = current.checked_add(added).ok_or(())?;
(next <= limit).then_some(next).ok_or(())
}
fn insert_multipart_value(
body: &mut Map<String, Value>,
kinds: &mut HashMap<String, MultipartPartKind>,
name: String,
kind: MultipartPartKind,
value: Value,
) -> Result<(), (StatusCode, BaseError)> {
if kinds.get(&name).is_some_and(|existing| *existing != kind) {
return Err(multipart_error(
StatusCode::BAD_REQUEST,
&name,
"同名 multipart 字段不能混用文本和文件",
));
}
kinds.entry(name.clone()).or_insert(kind);
match body.entry(name) {
Entry::Vacant(entry) => {
entry.insert(value);
}
Entry::Occupied(mut entry) => match entry.get_mut() {
Value::Array(values) => values.push(value),
existing => {
let first = std::mem::take(existing);
*existing = Value::Array(vec![first, value]);
}
},
}
Ok(())
}
fn text_part_targets_binary(input_schema: &Value, name: &str) -> bool {
input_schema
.get("properties")
.and_then(|properties| properties.get(name))
.is_some_and(|property| schema_subtree_contains_binary(input_schema, property))
}
fn decode_text_value(
input_schema: &Value,
name: &str,
text: String,
) -> Result<Value, (StatusCode, BaseError)> {
let property = input_schema
.get("properties")
.and_then(|properties| properties.get(name));
let schema_type = property
.and_then(non_null_type)
.or_else(|| property.and_then(any_of_non_null_type));
match schema_type {
Some("integer") => text
.parse::<i64>()
.map(Value::from)
.map_err(|_| multipart_error(StatusCode::BAD_REQUEST, name, "表单字段必须是整数")),
Some("number") => text
.parse::<f64>()
.ok()
.and_then(serde_json::Number::from_f64)
.map(Value::Number)
.ok_or_else(|| {
multipart_error(StatusCode::BAD_REQUEST, name, "表单字段必须是有限数值")
}),
Some("boolean") => match text.as_str() {
"true" => Ok(Value::Bool(true)),
"false" => Ok(Value::Bool(false)),
_ => Err(multipart_error(
StatusCode::BAD_REQUEST,
name,
"表单字段必须是 true 或 false",
)),
},
Some("object" | "array") => serde_json::from_str(&text)
.map_err(|_| multipart_error(StatusCode::BAD_REQUEST, name, "表单字段 JSON 格式无效")),
_ => Ok(Value::String(text)),
}
}
fn non_null_type(schema: &Value) -> Option<&str> {
match schema.get("type") {
Some(Value::String(kind)) if kind != "null" => Some(kind.as_str()),
Some(Value::Array(kinds)) => kinds
.iter()
.filter_map(Value::as_str)
.find(|kind| *kind != "null"),
_ => None,
}
}
fn any_of_non_null_type(schema: &Value) -> Option<&str> {
schema
.get("anyOf")?
.as_array()?
.iter()
.find_map(non_null_type)
}
fn sanitize_filename(raw: &str) -> String {
let leaf = raw.rsplit(['/', '\\']).next().unwrap_or_default().trim();
let mut safe = String::new();
for character in leaf.chars().filter(|character| !character.is_control()) {
if safe.len() + character.len_utf8() > 255 {
break;
}
safe.push(character);
}
if safe.is_empty() || matches!(safe.as_str(), "." | "..") {
"upload.bin".to_string()
} else {
safe
}
}
fn multipart_error(status: StatusCode, field: &str, message: &str) -> (StatusCode, BaseError) {
(
status,
BaseError::ParamInvalid(field.to_string(), message.to_string()),
)
}
async fn attachment_response(attachment: ResponseAttachment) -> Response {
match attachment {
ResponseAttachment::Redirect { url } => match HeaderValue::from_str(&url) {
Ok(location) => (StatusCode::FOUND, [(header::LOCATION, location)]).into_response(),
Err(_) => error_response(
StatusCode::INTERNAL_SERVER_ERROR,
BaseError::ConfigError("重定向地址包含非法字符".to_string()),
),
},
ResponseAttachment::Download { path, filename } => {
file_response(&path, Disposition::Attachment(&filename)).await
}
ResponseAttachment::Preview { path } => file_response(&path, Disposition::Inline).await,
}
}
enum Disposition<'a> {
Attachment(&'a str),
Inline,
}
async fn file_response(path: &std::path::Path, disposition: Disposition<'_>) -> Response {
let bytes = match tokio::fs::read(path).await {
Ok(bytes) => bytes,
Err(_) => {
return error_response(
StatusCode::NOT_FOUND,
BaseError::RecordNotFound(format!("文件不存在: {}", path.display())),
)
}
};
let mut response = Response::new(Body::from(bytes));
let headers = response.headers_mut();
match disposition {
Disposition::Attachment(filename) => {
headers.insert(
header::CONTENT_DISPOSITION,
content_disposition_value(filename),
);
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/octet-stream"),
);
}
Disposition::Inline => {
headers.insert(
header::CONTENT_DISPOSITION,
HeaderValue::from_static("inline"),
);
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static(mime_for(path)),
);
}
}
response
}
fn content_disposition_value(filename: &str) -> HeaderValue {
let fallback: String = filename
.chars()
.map(|ch| match ch {
'"' | '\r' | '\n' | '\\' => '_',
ch if ch.is_ascii() => ch,
_ => '_',
})
.collect();
let fallback = if fallback.trim_matches('_').is_empty() {
"download".to_string()
} else {
fallback
};
let encoded = percent_encode(filename.as_bytes());
let value = format!("attachment; filename=\"{fallback}\"; filename*=UTF-8''{encoded}");
HeaderValue::from_str(&value)
.unwrap_or_else(|_| HeaderValue::from_static("attachment; filename=\"download\""))
}
fn percent_encode(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len());
for byte in bytes {
match byte {
b'A'..=b'Z'
| b'a'..=b'z'
| b'0'..=b'9'
| b'!'
| b'#'
| b'$'
| b'&'
| b'+'
| b'-'
| b'.'
| b'^'
| b'_'
| b'`'
| b'|'
| b'~' => out.push(*byte as char),
_ => out.push_str(&format!("%{byte:02X}")),
}
}
out
}
fn mime_for(path: &std::path::Path) -> &'static str {
let extension = path
.extension()
.and_then(|ext| ext.to_str())
.map(|ext| ext.to_ascii_lowercase());
match extension.as_deref() {
Some("txt") | Some("log") | Some("md") | Some("csv") => "text/plain",
Some("html") | Some("htm") => "text/html",
Some("json") => "application/json",
Some("pdf") => "application/pdf",
Some("png") => "image/png",
Some("jpg") | Some("jpeg") => "image/jpeg",
Some("gif") => "image/gif",
Some("svg") => "image/svg+xml",
Some("webp") => "image/webp",
Some("mp4") => "video/mp4",
Some("mp3") => "audio/mpeg",
_ => "application/octet-stream",
}
}
fn method_filter(method: &str) -> Result<MethodFilter, BaseError> {
match method {
"GET" => Ok(MethodFilter::GET),
"POST" => Ok(MethodFilter::POST),
"PUT" => Ok(MethodFilter::PUT),
"PATCH" => Ok(MethodFilter::PATCH),
"DELETE" => Ok(MethodFilter::DELETE),
"HEAD" => Ok(MethodFilter::HEAD),
"OPTIONS" => Ok(MethodFilter::OPTIONS),
"TRACE" => Ok(MethodFilter::TRACE),
other => Err(BaseError::ConfigError(format!(
"不支持的 HTTP 方法: {other}"
))),
}
}
fn status_for_error(error: &BaseError) -> StatusCode {
match error {
#[cfg(feature = "token")]
BaseError::StepUpRequired(_) => StatusCode::PRECONDITION_REQUIRED,
BaseError::RateLimitExceeded { .. } => StatusCode::TOO_MANY_REQUESTS,
BaseError::Unauthorized(_)
| BaseError::InvalidPassword
| BaseError::TokenKeyInvalid(_)
| BaseError::TokenGenerateFailed(_)
| BaseError::TokenVerifyFailed(_)
| BaseError::TokenParseFailed(_)
| BaseError::TokenExpired
| BaseError::TokenRevoked
| BaseError::TokenTypeInvalid(_) => StatusCode::UNAUTHORIZED,
BaseError::PermissionDenied(_) | BaseError::FieldPermissionDenied(_, _, _) => {
StatusCode::FORBIDDEN
}
_ => match error.category() {
ErrorCategory::Client => StatusCode::BAD_REQUEST,
ErrorCategory::Auth => StatusCode::UNAUTHORIZED,
ErrorCategory::NotFound => StatusCode::NOT_FOUND,
ErrorCategory::Conflict => StatusCode::CONFLICT,
ErrorCategory::Transient => StatusCode::SERVICE_UNAVAILABLE,
_ => StatusCode::INTERNAL_SERVER_ERROR,
},
}
}
fn with_request_id_header(mut response: Response, request_id: RequestId) -> Response {
match HeaderValue::from_str(&request_id.to_string()) {
Ok(value) => {
response
.headers_mut()
.insert(HeaderName::from_static("x-request-id"), value);
}
Err(error) => {
tracing::error!(%request_id, %error, "request_id 无法写入 HTTP 响应头");
}
}
response
}
fn error_response(status: StatusCode, error: BaseError) -> Response {
#[cfg(feature = "token")]
if let BaseError::StepUpRequired(challenge) = &error {
let mut response = ApiResponse::from_error(&error);
response.data = Some(serde_json::json!({
"challenge": challenge.challenge,
"expires_in": challenge.expires_in,
}));
return (status, Json(response)).into_response();
}
if let BaseError::RateLimitExceeded {
retry_after_seconds,
} = &error
{
let mut response = (status, Json(ApiResponse::from_error(&error))).into_response();
if let Ok(value) = HeaderValue::from_str(&retry_after_seconds.to_string()) {
response.headers_mut().insert(header::RETRY_AFTER, value);
}
return response;
}
let response = if status.is_server_error() {
let message = if status == StatusCode::SERVICE_UNAVAILABLE {
"服务暂时不可用"
} else {
"服务器内部错误"
};
ApiResponse::fail(error.code(), message)
} else {
ApiResponse::from_error(&error)
};
(status, Json(response)).into_response()
}