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

Generated
+3
View File
@@ -1024,6 +1024,7 @@ dependencies = [
"assert_cmd",
"chrono",
"clap",
"futures-util",
"idna_adapter",
"include_dir",
"libc",
@@ -1033,6 +1034,8 @@ dependencies = [
"serde_json",
"thiserror 1.0.69",
"tiny_http",
"tokio",
"tokio-tungstenite 0.24.0",
"ureq",
"zeroize",
]
+3
View File
@@ -34,3 +34,6 @@ resolver = "2"
[dev-dependencies]
assert_cmd = "=2.0.14"
predicates = "=3.1.0"
tokio = { version = "1", features = ["rt-multi-thread", "macros", "time", "net"] }
tokio-tungstenite = "0.24"
futures-util = "0.3"
+2 -2
View File
@@ -120,7 +120,7 @@
| A5 | **文件上传接收**(multipart extractor → 校验类型/大小 → 落盘)与**下载**(`Content-Disposition`) | ✅ **已实现(W5)**:`app.upload` / `app.download`;`file:` storage;离线 + curl live 金样 | `plugins/web` | P1 ✅ |
| A6 | **HTTPS / TLS**(rustls 终止或反代提示) | 生产部署安全 | `plugins/web`(或文档指引反代) | P2 |
| A7 | **gzip / br 压缩** + **ETag / Cache-Control 缓存头** | gzip ✅ **已实现(W1,`压缩=真`)**;ETag/Cache-Control 待补 | `plugins/web`(tower-http 现成) | P2 |
| A8 | **访问日志**(请求方法/路径/状态/耗时) | 排障、审计 | `plugins/web`(tower-http TraceLayer) | P2 |
| A8 | **访问日志**(请求方法/路径/状态/耗时) | ✅ **已实现(W6b)**:`configure access_log=True` → stderr | `plugins/web` | P2 ✅ |
| A9 | **自定义 404/500 错误页** | 用户体感 | `plugins/web` | P2 |
| A10 | **重定向增强**(permanent/自定义状态码) | 301 SEO | `plugins/web` | P3 |
@@ -180,7 +180,7 @@
| **W3** | 安全硬化 | 密码哈希 + CSRF + 会话持久化 + CSPRNG session id + cookie 增强 + 登录限速/锁定 | C1–C7 |
| **W4** | 内容站点标配 | SEO 元数据 + sitemap/robots + RSS + Markdown 渲染 + 分页导航 UI + 标签/分类 | D1–D6 |
| **W5** | 上传与媒体 | multipart 文件上传接收 + 落盘 + 下载 + 图片库 | A5 D9 ✅ **A5 done**(D9 相册 UI 后续) |
| **W6** | 进阶 | 全文搜索(FTS5) + 迁移机制 + 评论系统 + 草稿/发布 + WS 广播 | B6 B9 ✅;D7/D8 用表+where;WS 广播后续 |
| **W6** | 进阶 | 全文搜索(FTS5) + 迁移机制 + 评论系统 + 草稿/发布 + WS 广播 | B6 B9 ✅;WS 广播 + access_log ✅;D7/D8 用表+where |
### 4.2 边界判定要点(严格遵守既有约束)
+1 -1
View File
@@ -31,7 +31,7 @@
| **W4** | Postgres;Redis / S3 驱动(见 [ext-web-drivers.md](../design/ext-web-drivers.md)) | **done** |
| **W4c** | 内容标配:SEO / Markdown / RSS / 分页 UI(见 [web-net-capabilities.md](../design/web-net-capabilities.md)) | **done** |
| **W5** | 上传与媒体:multipart 接收 + 落盘 + 下载(见 [web-net-capabilities.md](../design/web-net-capabilities.md) A5) | **done** |
| **W6** | 迁移 + FTS5 搜索;草稿/评论用既有 where/表(WS 广播后续) | **done**(核心) |
| **W6** | 迁移 + FTS5 搜索;草稿/评论用既有 where/表;WS 广播 + 访问日志 | **done** |
验收金样:`tests/ext/web-smoke.mq.md`、`tests/ext/web-security-smoke.mq.md`、`tests/ext/web-drivers-smoke.mq.md`、`tests/ext/web-upload-smoke.mq.md`、`tests/ext/web-db-w6-smoke.mq.md`、`ext_cli_add_web`。
+7 -5
View File
@@ -437,26 +437,28 @@ Serve files from `dir` under `mount` (default `/static`). Path is resolved from
+ `compress`=None
+ `body_limit`=None
+ `json`=None
+ `access_log`=None
Each capability is declared as a data table and assembled at listen time. The `cors` parameter takes a `|允许来源|方法|头|暴露头|凭证|` table (one row per origin; an empty `允许来源` column means any origin). The `security` parameter takes a `|头|值|` response-header table (e.g. `X-Frame-Options`, `Content-Security-Policy`, `X-Content-Type-Options`, `Referrer-Policy`, `Strict-Transport-Security`). Set `compress` to `True` to gzip response bodies. `body_limit` is the max request body bytes (e.g. `1048576`). The `json` parameter takes a `|路径|方法|表|条件|排序|上限|` table of JSON API endpoints backed by DB queries (each returns `application/json`).
Each capability is declared as a data table and assembled at listen time. The `cors` parameter takes a `|允许来源|方法|头|暴露头|凭证|` table (one row per origin; an empty `允许来源` column means any origin). The `security` parameter takes a `|头|值|` response-header table (e.g. `X-Frame-Options`, `Content-Security-Policy`, `X-Content-Type-Options`, `Referrer-Policy`, `Strict-Transport-Security`). Set `compress` to `True` to gzip response bodies. `body_limit` is the max request body bytes (e.g. `1048576`). The `json` parameter takes a `|路径|方法|表|条件|排序|上限|` table of JSON API endpoints backed by DB queries (each returns `application/json`). Set `access_log` to `True` to log `METHOD path status duration_ms` on stderr.
Tables stay as data; `configure` assembles them. 配置即数据、装配即函数.
**> web_app_middleware app=`self` cors=`cors` security=`security` compress=`compress` body_limit=`body_limit` json_routes=`json`**
**> web_app_middleware app=`self` cors=`cors` security=`security` compress=`compress` body_limit=`body_limit` json_routes=`json` access_log=`access_log`**
## listen
Serve `/`, routed pages, `/_part/{id}` (home) and `{path}/_part/{id}` (routes), `/_form/{id}` (from mounts + page embeds), optional `/static` (or custom mount), optional `/admin`, and any `upload` / `download` routes.
Serve `/`, routed pages, `/_part/{id}` (home) and `{path}/_part/{id}` (routes), `/_form/{id}` (from mounts + page embeds), optional `/static` (or custom mount), optional `/admin`, and any `upload` / `download` / WebSocket routes.
**> web_listen app=`self`**
## route_ws
+ `path`
+ `echo`=True
+ `mode`=None
Register a WebSocket endpoint at `path` (e.g. `/live`). With `echo=True` (default) the server replies to each received text frame; otherwise frames are drained. Connect from a client with `web.ws.connect`.
Register a WebSocket endpoint at `path` (e.g. `/live`). `mode` is `echo` (default), `broadcast` (fan-out text to all sockets on this path), or `drain`. Legacy `echo=False` maps to `drain`. Connect from a client with `web.ws.connect`.
**> web_app_route_ws app=`self` path=`path` echo=`echo`**
**> web_app_route_ws app=`self` path=`path` echo=`echo` mode=`mode`**
## auth
+ `users`
+7 -5
View File
@@ -419,26 +419,28 @@ SEO / OpenGraph 元数据表(`|键|值|`)。如 `title`、`description`、`c
+ `压缩`=None
+ `请求体上限`=None
+ `接口`=None
+ `访问日志`=None
每项能力用数据表声明,`监听` 时统一装配。`跨域` 参数接受 `|允许来源|方法|头|暴露头|凭证|` 表(每来源一行;`允许来源` 留空表示允许任意来源)。`安全` 参数接受 `|头|值|` 响应头表(如 `X-Frame-Options`、`Content-Security-Policy`、`X-Content-Type-Options`、`Referrer-Policy`、`Strict-Transport-Security`)。`压缩` 为 `真` 时对响应体做 gzip 压缩。`请求体上限` 是请求体最大字节数(如 `1048576`)。`接口` 参数接受 `|路径|方法|表|条件|排序|上限|` JSON API 端点表(每个返回 `application/json`)。
每项能力用数据表声明,`监听` 时统一装配。`跨域` 参数接受 `|允许来源|方法|头|暴露头|凭证|` 表(每来源一行;`允许来源` 留空表示允许任意来源)。`安全` 参数接受 `|头|值|` 响应头表(如 `X-Frame-Options`、`Content-Security-Policy`、`X-Content-Type-Options`、`Referrer-Policy`、`Strict-Transport-Security`)。`压缩` 为 `真` 时对响应体做 gzip 压缩。`请求体上限` 是请求体最大字节数(如 `1048576`)。`接口` 参数接受 `|路径|方法|表|条件|排序|上限|` JSON API 端点表(每个返回 `application/json`)。`访问日志` 为 `真` 时在 stderr 打印 `METHOD path status duration_ms`。
表仍是数据,`装配` 把它们变成能力。配置即数据、装配即函数。
**> web_app_middleware app=`self` cors=`跨域` security=`安全` compress=`压缩` body_limit=`请求体上限` json_routes=`接口`**
**> web_app_middleware app=`self` cors=`跨域` security=`安全` compress=`压缩` body_limit=`请求体上限` json_routes=`接口` access_log=`访问日志`**
## 监听
提供 `/`、路由页、首页 `/_part/{id}`、路由 `{路径}/_part/{id}`、`/_form/{id}`、可选静态目录、可选 `/admin`,以及已挂载的 `上传` / `下载` 路由。
提供 `/`、路由页、首页 `/_part/{id}`、路由 `{路径}/_part/{id}`、`/_form/{id}`、可选静态目录、可选 `/admin`,以及已挂载的 `上传` / `下载` / WebSocket 路由。
**> web_listen app=`self`**
## 路由实时
+ `路径`
+ `回显`=真
+ `模式`=None
在 `路径`(如 `/live`)注册 WebSocket 端点。`回显=真`(默认)时服务器对每条收到的文本帧原样回复;否则仅读取丢弃。客户端用 `网页.实时` 的 `连接` 接入。
在 `路径`(如 `/live`)注册 WebSocket 端点。`模式` 为 `echo`(默认)、`broadcast`(同路径全体广播)或 `drain`。旧参数 `回显=假` 等价于 `drain`。客户端用 `网页.实时` 的 `连接` 接入。
**> web_app_route_ws app=`self` path=`路径` echo=`回显`**
**> web_app_route_ws app=`self` path=`路径` echo=`回显` mode=`模式`**
## 鉴权
+ `用户表`
+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");
}
}
@@ -0,0 +1,20 @@
---
title: web ws broadcast live server
import web:ext/web/web.mq.md
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
---
# main
*p = > plugin.native_path name="web"*
1. `p`
> plugin.load path=`p`
2. *
> sys.exit code=1
*pg = > web.page title="ws-live"*
*app = > web.app page=`pg` port=18112*
*app = > `app`.configure access_log=True*
*app = > `app`.route_ws path="/room" mode="broadcast"*
> `app`.listen
+33
View File
@@ -0,0 +1,33 @@
---
title: web ws broadcast + access_log smoke (offline)
import web:ext/web/web.mq.md
import plugin:lib/plugin.mq.md
import sys:lib/sys.mq.md
---
# main
*p = > plugin.native_path name="web"*
1. `p`
> plugin.load path=`p`
2. *
> sys.exit code=1
*pg = > web.page title="w6b"*
*app = > web.app page=`pg` port=18111*
*app = > `app`.route_ws path="/room" mode="broadcast"*
*routes = app[^ws_routes]*
*room = routes[^/room]*
*mode = room[^mode]*
1. `mode` == "broadcast"
> print text=ws-broadcast-route-ok
2. *
> print text=ws-broadcast-route-fail
*app = > `app`.configure access_log=True compress=False*
*mw = app[^middleware]*
*al = mw[^access_log]*
1. `al`
> print text=access-log-ok
2. *
> print text=access-log-fail
+120
View File
@@ -1963,6 +1963,126 @@ fts-row-ok",
);
}
#[test]
fn ext_web_ws_broadcast_smoke() {
let status = Command::new("cargo")
.args(["build", "-p", "marqdo_plugin_web"])
.current_dir(env!("CARGO_MANIFEST_DIR"))
.status()
.expect("build web plugin");
assert!(status.success(), "failed to build marqdo_plugin_web");
assert_out(
"tests/ext/web-ws-broadcast-smoke.mq.md",
"ws-broadcast-route-ok
access-log-ok",
);
}
#[test]
fn ext_web_ws_broadcast_live() {
use futures_util::{SinkExt, StreamExt};
use tokio_tungstenite::tungstenite::Message;
let status = Command::new("cargo")
.args(["build", "-p", "marqdo_plugin_web"])
.current_dir(env!("CARGO_MANIFEST_DIR"))
.status()
.expect("build web plugin");
assert!(status.success(), "failed to build marqdo_plugin_web");
let script = "tests/ext/web-ws-broadcast-live-server.mq.md";
let bin = env!("CARGO_BIN_EXE_marqdo");
let mut child = Command::new(bin)
.args(["run", script])
.current_dir(env!("CARGO_MANIFEST_DIR"))
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.expect("spawn ws live server");
let base = "http://127.0.0.1:18112";
let ready = std::time::Instant::now();
loop {
if ready.elapsed().as_secs() > 10 {
let _ = child.kill();
panic!("ws live server did not start in time");
}
let out = Command::new("curl")
.args([
"-s",
"-o",
"/dev/null",
"-w",
"%{http_code}",
&format!("{base}/"),
])
.output()
.expect("curl probe");
if String::from_utf8_lossy(&out.stdout) == "200" {
break;
}
std::thread::sleep(std::time::Duration::from_millis(300));
}
let rt = tokio::runtime::Runtime::new().expect("rt");
rt.block_on(async {
let (a, _) = tokio_tungstenite::connect_async("ws://127.0.0.1:18112/room")
.await
.expect("connect a");
let (b, _) = tokio_tungstenite::connect_async("ws://127.0.0.1:18112/room")
.await
.expect("connect b");
let (mut a_sink, mut a_src) = a.split();
let (mut b_sink, mut b_src) = b.split();
// Give subscriptions a moment to register.
tokio::time::sleep(std::time::Duration::from_millis(50)).await;
b_sink
.send(Message::Text("ping-from-b".into()))
.await
.expect("send b");
let got_a = tokio::time::timeout(
std::time::Duration::from_secs(3),
a_src.next(),
)
.await
.expect("a timeout")
.expect("a closed")
.expect("a err");
let got_b = tokio::time::timeout(
std::time::Duration::from_secs(3),
b_src.next(),
)
.await
.expect("b timeout")
.expect("b closed")
.expect("b err");
match got_a {
Message::Text(t) => assert_eq!(t, "ping-from-b"),
other => panic!("a unexpected {other:?}"),
}
match got_b {
Message::Text(t) => assert_eq!(t, "ping-from-b"),
other => panic!("b unexpected {other:?}"),
}
let _ = a_sink.close().await;
let _ = b_sink.close().await;
});
// Access log should have recorded the probe GET /.
let _ = child.kill();
let out = child.wait_with_output().expect("wait");
let stderr = String::from_utf8_lossy(&out.stderr);
assert!(
stderr.contains("marqdo web GET / 200"),
"access log missing in stderr={stderr}"
);
}
#[test]
fn ext_web_db_w2_smoke() {
// W2 data layer: transactions, connection pooling, pagination, query