ext/web W6b: WebSocket broadcast and access logging

Add route_ws mode=broadcast with a per-path hub, configure access_log
for stderr request lines, and cover both offline and live gold.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
cflmyandCursor committed 2026-08-28 11:13:24 +08:00
1 parent e3b0314382
commit 6808d56c9d
13 files changed
+409 -47

No files matched your search

+68 -17
View File
@@ -91,7 +91,7 @@ pub fn listen(
auth_users: Option<Value>,
session_ttl: u64,
cookie_secure: bool,
ws_routes: HashMap<String, bool>,
ws_routes: HashMap<String, crate::ws_hub::WsMode>,
rss_routes: HashMap<String, Value>,
upload_routes: HashMap<String, UploadRoute>,
download_routes: HashMap<String, DownloadRoute>,
@@ -192,15 +192,19 @@ pub fn listen(
}
}
// WebSocket endpoints (`ws://…/{path}`), echo-mode by default.
// WebSocket endpoints (`ws://…/{path}`).
let mut ws_paths: Vec<String> = ws_routes.keys().cloned().collect();
ws_paths.sort();
for path in ws_paths {
let echo = ws_routes.get(&path).copied().unwrap_or(true);
let mode = ws_routes
.get(&path)
.copied()
.unwrap_or(crate::ws_hub::WsMode::Echo);
let route_path = path.clone();
app = app.route(
&path,
axum::routing::get(move |ws: axum::extract::WebSocketUpgrade| {
ws_upgrade(ws, echo)
ws_upgrade(ws, mode, route_path.clone())
}),
);
}
@@ -1319,28 +1323,75 @@ fn esc(s: &str) -> String {
.replace('>', "&gt;")
}
/// WebSocket server endpoint: `echo=true` replies with each received text frame;
/// otherwise it just drains frames (extension point for custom logic).
/// WebSocket server endpoint.
/// - `echo`: reply each text frame to the same socket
/// - `broadcast`: fan-out text frames to all sockets on this path
/// - `drain`: read and discard frames
async fn ws_upgrade(
ws: axum::extract::WebSocketUpgrade,
echo: bool,
mode: crate::ws_hub::WsMode,
path: String,
) -> Response {
ws.on_upgrade(move |socket| ws_echo_loop(socket, echo))
ws.on_upgrade(move |socket| ws_socket_loop(socket, mode, path))
}
async fn ws_echo_loop(mut socket: axum::extract::ws::WebSocket, echo: bool) {
async fn ws_socket_loop(
mut socket: axum::extract::ws::WebSocket,
mode: crate::ws_hub::WsMode,
path: String,
) {
use axum::extract::ws::Message;
while let Some(Ok(msg)) = socket.recv().await {
match msg {
Message::Text(text) => {
if echo {
if socket.send(Message::Text(text)).await.is_err() {
break;
use futures_util::{SinkExt, StreamExt};
match mode {
crate::ws_hub::WsMode::Echo => {
while let Some(Ok(msg)) = socket.recv().await {
match msg {
Message::Text(text) => {
if socket.send(Message::Text(text)).await.is_err() {
break;
}
}
Message::Close(_) => break,
_ => {}
}
}
}
crate::ws_hub::WsMode::Drain => {
while let Some(Ok(msg)) = socket.recv().await {
if matches!(msg, Message::Close(_)) {
break;
}
}
}
crate::ws_hub::WsMode::Broadcast => {
let mut rx = crate::ws_hub::subscribe(&path);
let (mut sink, mut stream) = socket.split();
loop {
tokio::select! {
incoming = stream.next() => {
match incoming {
Some(Ok(Message::Text(text))) => {
crate::ws_hub::publish(&path, text.to_string());
}
Some(Ok(Message::Close(_))) | None => break,
Some(Ok(_)) => {}
Some(Err(_)) => break,
}
}
out = rx.recv() => {
match out {
Ok(text) => {
if sink.send(Message::Text(text.into())).await.is_err() {
break;
}
}
Err(tokio::sync::broadcast::error::RecvError::Lagged(_)) => continue,
Err(_) => break,
}
}
}
}
Message::Close(_) => break,
_ => {}
}
}
}
+22 -16
View File
@@ -18,6 +18,7 @@ mod storage;
mod table;
mod upload;
mod ws;
mod ws_hub;
use crate::table::as_css_named;
@@ -900,12 +901,10 @@ web_ffi!(web_app_route, |args: &Value| {
web_ffi!(web_app_route_ws, |args: &Value| {
let mut app = args.get("app").cloned().unwrap_or(json!({}));
let path = normalize_route_path(arg_str(args, "path")?)?;
let echo = match args.get("echo") {
None | Some(Value::Null) => true,
Some(Value::Bool(b)) => *b,
Some(Value::String(s)) => matches!(s.as_str(), "true" | "True" | "1" | "yes"),
Some(Value::Number(n)) => n.as_i64().unwrap_or(0) != 0,
Some(_) => true,
let mode = if let Some(m) = args.get("mode").or_else(|| args.get("模式")) {
crate::ws_hub::WsMode::parse(m)
} else {
crate::ws_hub::WsMode::parse(&args.get("echo").cloned().unwrap_or(json!(true)))
};
let obj = app
.as_object_mut()
@@ -916,7 +915,7 @@ web_ffi!(web_app_route_ws, |args: &Value| {
let wmap = ws_routes
.as_object_mut()
.ok_or_else(|| "app.ws_routes must be a map".to_string())?;
wmap.insert(path, json!(echo));
wmap.insert(path, json!({ "mode": mode.as_str() }));
Ok(app)
});
@@ -1085,6 +1084,18 @@ web_ffi!(web_app_middleware, |args: &Value| {
};
m.insert("compress".into(), json!(on));
}
if let Some(al) = args
.get("access_log")
.or_else(|| args.get("访问日志"))
{
let on = match al {
Value::Bool(b) => *b,
Value::String(s) => matches!(s.as_str(), "true" | "True" | "1" | "yes" | "on" | "真"),
Value::Number(n) => n.as_i64().unwrap_or(0) != 0,
_ => false,
};
m.insert("access_log".into(), json!(on));
}
if let Some(bl) = args.get("body_limit") {
let n = bl
.as_u64()
@@ -1253,7 +1264,7 @@ web_ffi!(web_listen, |args: &Value| {
static_mount,
auth_users,
session_ttl,
HashMap::new(),
HashMap::<String, crate::ws_hub::WsMode>::new(),
HashMap::new(),
HashMap::new(),
HashMap::new(),
@@ -1298,12 +1309,7 @@ web_ffi!(web_listen, |args: &Value| {
let mut ws_routes = HashMap::new();
if let Some(obj) = app.get("ws_routes").and_then(|v| v.as_object()) {
for (k, v) in obj {
let echo = match v {
Value::Bool(b) => *b,
Value::String(s) => matches!(s.as_str(), "true" | "True" | "1" | "yes"),
_ => true,
};
ws_routes.insert(k.clone(), echo);
ws_routes.insert(k.clone(), crate::ws_hub::WsMode::parse(v));
}
}
let mut rss_routes = HashMap::new();
@@ -1645,7 +1651,7 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
),
(
"web_app_middleware",
"app,cors,security,compress,body_limit,json_routes",
"app,cors,security,compress,body_limit,json_routes,access_log",
web_app_middleware as PluginFn,
),
("web_form_new", "table,action,id", web_form_new as PluginFn),
@@ -1681,7 +1687,7 @@ pub unsafe extern "C" fn marqdo_plugin_init(host: *const MarqdoHostApi) -> c_int
("web_app_auth", "app,users,session_ttl", web_app_auth as PluginFn),
(
"web_app_route_ws",
"app,path,echo",
"app,path,echo,mode",
web_app_route_ws as PluginFn,
),
(
+31 -1
View File
@@ -10,7 +10,8 @@ use std::sync::Arc;
use axum::body::Body;
use axum::extract::State;
use axum::http::{header, HeaderValue, Method, StatusCode};
use axum::http::{header, HeaderValue, Method, Request, StatusCode};
use axum::middleware::{self as axum_mw, Next};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use axum::Router;
@@ -40,6 +41,8 @@ pub struct Middleware {
pub security: Vec<(String, String)>,
pub compress: bool,
pub body_limit: Option<u64>,
/// Log `METHOD path status duration_ms` to stderr for each request.
pub access_log: bool,
/// JSON API routes: `path -> { method, table, where?, order?, limit? }`.
pub json_routes: Vec<(String, JsonRoute)>,
}
@@ -82,6 +85,10 @@ pub fn parse(app: &Value) -> Middleware {
.get("compress")
.and_then(|v| v.as_bool())
.unwrap_or(false);
mw.access_log = obj
.get("access_log")
.and_then(|v| v.as_bool())
.unwrap_or(false);
mw.body_limit = obj
.get("body_limit")
.and_then(|v| v.as_u64().or_else(|| v.as_i64().map(|i| i as u64)))
@@ -224,9 +231,29 @@ pub fn apply(
app = app.layer(RequestBodyLimitLayer::new(bytes as usize));
}
// Access log (outermost so status/duration include other layers).
if mw.access_log {
app = app.layer(axum_mw::from_fn(access_log_mw));
}
app
}
async fn access_log_mw(req: Request<Body>, next: Next) -> Response {
let method = req.method().clone();
let path = req.uri().path().to_string();
let start = std::time::Instant::now();
let resp = next.run(req).await;
eprintln!(
"marqdo web {} {} {} {}ms",
method,
path,
resp.status().as_u16(),
start.elapsed().as_millis()
);
resp
}
fn header_name_from(name: &str) -> Option<axum::http::HeaderName> {
let h = match name {
"x_frame_options" | "x-frame-options" => header::X_FRAME_OPTIONS,
@@ -427,6 +454,9 @@ pub fn summary(app: &Value) -> String {
if mw.body_limit.is_some() {
parts.push("body_limit".to_string());
}
if mw.access_log {
parts.push("access_log".to_string());
}
if !mw.json_routes.is_empty() {
parts.push(format!("json:{}", mw.json_routes.len()));
}
+92
View File
@@ -0,0 +1,92 @@
//! Per-path WebSocket broadcast hubs (W6 remainder).
use std::collections::HashMap;
use std::sync::Mutex;
use tokio::sync::broadcast;
const CAP: usize = 256;
static HUBS: Mutex<Option<HashMap<String, broadcast::Sender<String>>>> = Mutex::new(None);
fn with_hubs<T>(f: impl FnOnce(&mut HashMap<String, broadcast::Sender<String>>) -> T) -> T {
let mut g = HUBS.lock().unwrap_or_else(|e| e.into_inner());
let m = g.get_or_insert_with(HashMap::new);
f(m)
}
/// Subscribe to (or create) the broadcast channel for `path`.
pub fn subscribe(path: &str) -> broadcast::Receiver<String> {
with_hubs(|m| {
if let Some(tx) = m.get(path) {
return tx.subscribe();
}
let (tx, rx) = broadcast::channel(CAP);
m.insert(path.to_string(), tx);
rx
})
}
/// Publish a text frame to all subscribers on `path`.
pub fn publish(path: &str, text: String) {
with_hubs(|m| {
let tx = m.entry(path.to_string()).or_insert_with(|| {
let (tx, _) = broadcast::channel(CAP);
tx
});
let _ = tx.send(text);
});
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WsMode {
Echo,
Broadcast,
Drain,
}
impl WsMode {
pub fn parse(v: &serde_json::Value) -> Self {
match v {
serde_json::Value::Bool(true) => WsMode::Echo,
serde_json::Value::Bool(false) => WsMode::Drain,
serde_json::Value::String(s) => match s.trim().to_ascii_lowercase().as_str() {
"broadcast" | "广播" => WsMode::Broadcast,
"drain" | "false" | "0" | "no" | "drain_only" => WsMode::Drain,
_ => WsMode::Echo,
},
serde_json::Value::Object(m) => {
if let Some(mode) = m.get("mode").or_else(|| m.get("模式")) {
return Self::parse(mode);
}
if let Some(echo) = m.get("echo").or_else(|| m.get("回显")) {
return Self::parse(echo);
}
WsMode::Echo
}
_ => WsMode::Echo,
}
}
pub fn as_str(self) -> &'static str {
match self {
WsMode::Echo => "echo",
WsMode::Broadcast => "broadcast",
WsMode::Drain => "drain",
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn broadcast_fanout() {
let mut a = subscribe("/t-fanout");
let mut b = subscribe("/t-fanout");
publish("/t-fanout", "hi".into());
assert_eq!(a.try_recv().unwrap(), "hi");
assert_eq!(b.try_recv().unwrap(), "hi");
}
}