feat(web): Go W-G8 WebSocket routes and access_log
Register route_ws/ws_connect ABIs with an in-process broadcast hub so offline WS broadcast and access_log smokes pass on libweb.so. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
1 parent
23e4bc406e
commit
4c06851e0e
11 files changed
+495
-1
No files matched your search
@@ -393,7 +393,7 @@ scripts/build-web-plugin.sh # go build -buildmode=c-shared -o …/libweb.so
|
||||
| **W-G5** | session/auth/password/rate limit/gate/admin | ✅ offline:`web-security` / `web-c0` / `web-c1`;login rate limit 包已就位(HTTP 接线随 listen hardening) |
|
||||
| **W-G6** | upload/download/gallery/ETag + assets W8 | ✅ `web-upload` / `web-assets` / `web-p3` |
|
||||
| **W-G7** | SEO RSS sitemap robots redirect error paginate markdown | ✅ `web-content` / `web-w7-*` |
|
||||
| **W-G8** | WS echo/broadcast + access_log | `web-ws-broadcast-*` |
|
||||
| **W-G8** | WS echo/broadcast + access_log | ✅ `web-ws-broadcast-*` |
|
||||
| **W-G9** | Postgres + Redis cache + file/S3 storage | `web-drivers-smoke` |
|
||||
| **W-G10** | proxy + invoke + nested plugin | `web-proxy-invoke` / hosting live |
|
||||
| **W-G11** | 定制 C2–C4 shell/layout/style/nav | `web-c2`–`c4` |
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
package main
|
||||
|
||||
/*
|
||||
#cgo CFLAGS: -I${SRCDIR}/abi
|
||||
#include "marqdo_abi_cgo.h"
|
||||
|
||||
extern int web_app_route_ws(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_ws_connect(char *args_json, char **out_json, char **err_msg);
|
||||
*/
|
||||
import "C"
|
||||
|
||||
import (
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/ws"
|
||||
)
|
||||
|
||||
//export web_app_route_ws
|
||||
func web_app_route_ws(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
args, err := parseArgs(argsJSON)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
path, err := argStrReq(args, "path", "路径")
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
out, err := ws.RouteWS(asPageMap(args["app"]), path, args)
|
||||
return replyJSON(outJSON, errMsg, out, err)
|
||||
}
|
||||
|
||||
//export web_ws_connect
|
||||
func web_ws_connect(argsJSON *C.char, outJSON **C.char, errMsg **C.char) C.int {
|
||||
args, err := parseArgs(argsJSON)
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
url, err := argStrReq(args, "url", "地址")
|
||||
if err != nil {
|
||||
return replyJSON(outJSON, errMsg, nil, err)
|
||||
}
|
||||
message, _ := argStr(args, "message", "消息")
|
||||
var headers map[string]any
|
||||
if h, ok := args["headers"]; ok && h != nil {
|
||||
if m, ok := h.(map[string]any); ok {
|
||||
headers = m
|
||||
}
|
||||
}
|
||||
timeout := argUint64(args, 30, "timeout_sec", "timeout", "超时")
|
||||
out := ws.Connect(url, message, headers, timeout)
|
||||
return replyJSON(outJSON, errMsg, out, nil)
|
||||
}
|
||||
@@ -10,6 +10,7 @@ require (
|
||||
require (
|
||||
github.com/dustin/go-humanize v1.0.1 // indirect
|
||||
github.com/google/uuid v1.6.0 // indirect
|
||||
github.com/gorilla/websocket v1.5.3 // indirect
|
||||
github.com/mattn/go-isatty v0.0.24 // indirect
|
||||
github.com/ncruces/go-strftime v1.0.0 // indirect
|
||||
github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
|
||||
|
||||
@@ -4,6 +4,8 @@ github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlG
|
||||
github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/gorilla/websocket v1.5.3 h1:saDtZ6Pbx/0u+bgYQ3q96pZgCzfhKXGPqt7kZ72aNNg=
|
||||
github.com/gorilla/websocket v1.5.3/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
|
||||
github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
|
||||
github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI=
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
package ws
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
)
|
||||
|
||||
// Connect dials url, sends one text message, collects text replies until close or timeout.
|
||||
// Mirrors Rust ws::connect; errors are returned as {ok:false, error}.
|
||||
func Connect(url, message string, headers map[string]any, timeoutSec uint64) map[string]any {
|
||||
if !(strings.HasPrefix(url, "ws://") || strings.HasPrefix(url, "wss://")) {
|
||||
return map[string]any{"ok": false, "error": "ws url must start with ws:// or wss://"}
|
||||
}
|
||||
if timeoutSec < 1 {
|
||||
timeoutSec = 1
|
||||
}
|
||||
timeout := time.Duration(timeoutSec) * time.Second
|
||||
hdr := http.Header{}
|
||||
for k, v := range headersFromValue(headers) {
|
||||
hdr.Set(k, v)
|
||||
}
|
||||
dialer := websocket.Dialer{HandshakeTimeout: timeout}
|
||||
conn, _, err := dialer.Dial(url, hdr)
|
||||
if err != nil {
|
||||
return map[string]any{"ok": false, "error": fmt.Sprintf("ws connect: %v", err)}
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
if err := conn.SetWriteDeadline(time.Now().Add(timeout)); err != nil {
|
||||
return map[string]any{"ok": false, "error": fmt.Sprintf("ws send: %v", err)}
|
||||
}
|
||||
if err := conn.WriteMessage(websocket.TextMessage, []byte(message)); err != nil {
|
||||
return map[string]any{"ok": false, "error": fmt.Sprintf("ws send: %v", err)}
|
||||
}
|
||||
|
||||
var messages []string
|
||||
deadline := time.Now().Add(timeout)
|
||||
for {
|
||||
if err := conn.SetReadDeadline(deadline); err != nil {
|
||||
break
|
||||
}
|
||||
mt, data, err := conn.ReadMessage()
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
if mt == websocket.TextMessage {
|
||||
messages = append(messages, string(data))
|
||||
}
|
||||
if mt == websocket.CloseMessage {
|
||||
break
|
||||
}
|
||||
}
|
||||
return map[string]any{"ok": true, "messages": toAnyList(messages)}
|
||||
}
|
||||
|
||||
func headersFromValue(headers map[string]any) map[string]string {
|
||||
out := map[string]string{}
|
||||
if headers == nil {
|
||||
return out
|
||||
}
|
||||
for k, v := range headers {
|
||||
switch t := v.(type) {
|
||||
case string:
|
||||
out[k] = t
|
||||
case nil:
|
||||
out[k] = ""
|
||||
default:
|
||||
out[k] = fmt.Sprint(t)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func toAnyList(ss []string) []any {
|
||||
out := make([]any, len(ss))
|
||||
for i, s := range ss {
|
||||
out[i] = s
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package ws
|
||||
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
const hubCap = 256
|
||||
|
||||
type hub struct {
|
||||
mu sync.Mutex
|
||||
room map[string]*broadcastRoom
|
||||
}
|
||||
|
||||
type broadcastRoom struct {
|
||||
mu sync.Mutex
|
||||
subs map[chan string]struct{}
|
||||
}
|
||||
|
||||
var globalHub = &hub{room: map[string]*broadcastRoom{}}
|
||||
|
||||
func subscribe(path string) chan string {
|
||||
ch := make(chan string, hubCap)
|
||||
globalHub.mu.Lock()
|
||||
room := globalHub.room[path]
|
||||
if room == nil {
|
||||
room = &broadcastRoom{subs: map[chan string]struct{}{}}
|
||||
globalHub.room[path] = room
|
||||
}
|
||||
room.mu.Lock()
|
||||
room.subs[ch] = struct{}{}
|
||||
room.mu.Unlock()
|
||||
globalHub.mu.Unlock()
|
||||
return ch
|
||||
}
|
||||
|
||||
func unsubscribe(path string, ch chan string) {
|
||||
globalHub.mu.Lock()
|
||||
room := globalHub.room[path]
|
||||
globalHub.mu.Unlock()
|
||||
if room == nil {
|
||||
return
|
||||
}
|
||||
room.mu.Lock()
|
||||
delete(room.subs, ch)
|
||||
room.mu.Unlock()
|
||||
}
|
||||
|
||||
// Publish fans out text to all subscribers on path (Rust ws_hub::publish).
|
||||
func Publish(path string, text string) {
|
||||
globalHub.mu.Lock()
|
||||
room := globalHub.room[path]
|
||||
globalHub.mu.Unlock()
|
||||
if room == nil {
|
||||
return
|
||||
}
|
||||
room.mu.Lock()
|
||||
for ch := range room.subs {
|
||||
select {
|
||||
case ch <- text:
|
||||
default:
|
||||
}
|
||||
}
|
||||
room.mu.Unlock()
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package ws
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestBroadcastFanout(t *testing.T) {
|
||||
path := "/t-fanout-go"
|
||||
ch := subscribe(path)
|
||||
ch2 := subscribe(path)
|
||||
Publish(path, "hi")
|
||||
if got := readOne(ch); got != "hi" {
|
||||
t.Fatalf("ch1=%q", got)
|
||||
}
|
||||
if got := readOne(ch2); got != "hi" {
|
||||
t.Fatalf("ch2=%q", got)
|
||||
}
|
||||
unsubscribe(path, ch)
|
||||
unsubscribe(path, ch2)
|
||||
}
|
||||
|
||||
func readOne(ch chan string) string {
|
||||
select {
|
||||
case s := <-ch:
|
||||
return s
|
||||
case <-time.After(time.Second):
|
||||
return ""
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
// Package ws ports WebSocket route registration and client connect from the Rust web plugin.
|
||||
package ws
|
||||
|
||||
import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Mode is the server-side WebSocket handler mode for a path.
|
||||
type Mode string
|
||||
|
||||
const (
|
||||
ModeEcho Mode = "echo"
|
||||
ModeBroadcast Mode = "broadcast"
|
||||
ModeDrain Mode = "drain"
|
||||
)
|
||||
|
||||
// ParseMode mirrors Rust ws_hub::WsMode::parse.
|
||||
func ParseMode(v any) Mode {
|
||||
switch t := v.(type) {
|
||||
case bool:
|
||||
if t {
|
||||
return ModeEcho
|
||||
}
|
||||
return ModeDrain
|
||||
case string:
|
||||
switch strings.TrimSpace(strings.ToLower(t)) {
|
||||
case "broadcast", "广播":
|
||||
return ModeBroadcast
|
||||
case "drain", "false", "0", "no", "drain_only":
|
||||
return ModeDrain
|
||||
default:
|
||||
return ModeEcho
|
||||
}
|
||||
case map[string]any:
|
||||
if m, ok := t["mode"]; ok {
|
||||
return ParseMode(m)
|
||||
}
|
||||
if m, ok := t["模式"]; ok {
|
||||
return ParseMode(m)
|
||||
}
|
||||
if e, ok := t["echo"]; ok {
|
||||
return ParseMode(e)
|
||||
}
|
||||
if e, ok := t["回显"]; ok {
|
||||
return ParseMode(e)
|
||||
}
|
||||
return ModeEcho
|
||||
default:
|
||||
return ModeEcho
|
||||
}
|
||||
}
|
||||
|
||||
// ModeFromArgs picks mode from route_ws ABI args (mode/模式 or echo/回显, default echo).
|
||||
func ModeFromArgs(args map[string]any) Mode {
|
||||
if v, ok := first(args, "mode", "模式"); ok {
|
||||
return ParseMode(v)
|
||||
}
|
||||
echo := true
|
||||
if v, ok := first(args, "echo", "回显"); ok {
|
||||
echo = boolish(v)
|
||||
}
|
||||
if echo {
|
||||
return ModeEcho
|
||||
}
|
||||
return ModeDrain
|
||||
}
|
||||
|
||||
func first(m map[string]any, keys ...string) (any, bool) {
|
||||
for _, k := range keys {
|
||||
if v, ok := m[k]; ok && v != nil {
|
||||
return v, true
|
||||
}
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
func boolish(v any) bool {
|
||||
switch t := v.(type) {
|
||||
case bool:
|
||||
return t
|
||||
case string:
|
||||
switch strings.TrimSpace(t) {
|
||||
case "true", "True", "1", "yes", "on", "真":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
case float64:
|
||||
return t != 0
|
||||
case int:
|
||||
return t != 0
|
||||
case int64:
|
||||
return t != 0
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package ws
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/app"
|
||||
)
|
||||
|
||||
// RouteWS registers path → {mode} on app.ws_routes (Rust web_app_route_ws).
|
||||
func RouteWS(appBag map[string]any, path string, args map[string]any) (map[string]any, error) {
|
||||
path, err := app.NormalizeRoutePath(path, appBag)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mode := ModeFromArgs(args)
|
||||
out := clone(appBag)
|
||||
wsRoutes := map[string]any{}
|
||||
if r, ok := out["ws_routes"].(map[string]any); ok {
|
||||
wsRoutes = clone(r)
|
||||
}
|
||||
wsRoutes[path] = map[string]any{"mode": string(mode)}
|
||||
out["ws_routes"] = wsRoutes
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// RoutesOf reads ws_routes from an app bag.
|
||||
func RoutesOf(appBag map[string]any) map[string]Mode {
|
||||
out := map[string]Mode{}
|
||||
obj, ok := appBag["ws_routes"].(map[string]any)
|
||||
if !ok {
|
||||
return out
|
||||
}
|
||||
for path, spec := range obj {
|
||||
switch t := spec.(type) {
|
||||
case map[string]any:
|
||||
if m, ok := t["mode"]; ok {
|
||||
out[path] = ParseMode(m)
|
||||
continue
|
||||
}
|
||||
out[path] = ParseMode(t)
|
||||
case string:
|
||||
out[path] = ParseMode(t)
|
||||
default:
|
||||
out[path] = ParseMode(spec)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func clone(m map[string]any) map[string]any {
|
||||
out := make(map[string]any, len(m))
|
||||
for k, v := range m {
|
||||
out[k] = v
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ModeOf returns the mode for one ws route path, or error if missing.
|
||||
func ModeOf(appBag map[string]any, path string) (Mode, error) {
|
||||
routes, ok := appBag["ws_routes"].(map[string]any)
|
||||
if !ok {
|
||||
return "", fmt.Errorf("missing ws route %s", path)
|
||||
}
|
||||
spec, ok := routes[path]
|
||||
if !ok {
|
||||
return "", fmt.Errorf("missing ws route %s", path)
|
||||
}
|
||||
if m, ok := spec.(map[string]any); ok {
|
||||
if mode, ok := m["mode"]; ok {
|
||||
return ParseMode(mode), nil
|
||||
}
|
||||
return ParseMode(m), nil
|
||||
}
|
||||
return ParseMode(spec), nil
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
package ws_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/app"
|
||||
"github.com/marqdo/marqdo/plugins/web/internal/ws"
|
||||
)
|
||||
|
||||
func TestRouteWSBroadcastMode(t *testing.T) {
|
||||
a := app.New(map[string]any{"page": map[string]any{"title": "w6b"}})
|
||||
out, err := ws.RouteWS(a, "/room", map[string]any{"mode": "broadcast"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mode, err := ws.ModeOf(out, "/room")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if mode != ws.ModeBroadcast {
|
||||
t.Fatalf("mode=%q want broadcast", mode)
|
||||
}
|
||||
routes := out["ws_routes"].(map[string]any)
|
||||
room := routes["/room"].(map[string]any)
|
||||
if room["mode"] != "broadcast" {
|
||||
t.Fatalf("bag mode=%v", room["mode"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteWSEchoDefault(t *testing.T) {
|
||||
a := app.New(nil)
|
||||
out, err := ws.RouteWS(a, "/live", map[string]any{"echo": true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mode, err := ws.ModeOf(out, "/live")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if mode != ws.ModeEcho {
|
||||
t.Fatalf("mode=%q want echo", mode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRouteWSDrainFromEchoFalse(t *testing.T) {
|
||||
a := app.New(nil)
|
||||
out, err := ws.RouteWS(a, "/sink", map[string]any{"echo": false})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
mode, err := ws.ModeOf(out, "/sink")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if mode != ws.ModeDrain {
|
||||
t.Fatalf("mode=%q want drain", mode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseModeVariants(t *testing.T) {
|
||||
cases := []struct {
|
||||
in any
|
||||
want ws.Mode
|
||||
}{
|
||||
{true, ws.ModeEcho},
|
||||
{false, ws.ModeDrain},
|
||||
{"broadcast", ws.ModeBroadcast},
|
||||
{"广播", ws.ModeBroadcast},
|
||||
{"drain", ws.ModeDrain},
|
||||
{"nope", ws.ModeEcho},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := ws.ParseMode(c.in); got != c.want {
|
||||
t.Fatalf("ParseMode(%#v)=%q want %q", c.in, got, c.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConnectRefusesBadURL(t *testing.T) {
|
||||
out := ws.Connect("http://127.0.0.1:1", "hi", nil, 1)
|
||||
if out["ok"] == true {
|
||||
t.Fatal("expected ok=false for http url")
|
||||
}
|
||||
err, _ := out["error"].(string)
|
||||
if err == "" || !strings.Contains(err, "ws://") {
|
||||
t.Fatalf("error=%q", err)
|
||||
}
|
||||
}
|
||||
@@ -122,6 +122,8 @@ extern int web_app_error_page(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_app_sitemap(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_app_robots(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_sitemap_build(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_app_route_ws(char *args_json, char **out_json, char **err_msg);
|
||||
extern int web_ws_connect(char *args_json, char **out_json, char **err_msg);
|
||||
|
||||
static int register_core(void) {
|
||||
if (host_register((char *)"web_go_ready", (char *)"", web_go_ready) != 0) return 1;
|
||||
@@ -197,6 +199,8 @@ static int register_core(void) {
|
||||
if (host_register((char *)"web_app_sitemap", (char *)"app,path,base,table,loc,limit,items", web_app_sitemap) != 0) return 1;
|
||||
if (host_register((char *)"web_app_robots", (char *)"app,body,sitemap", web_app_robots) != 0) return 1;
|
||||
if (host_register((char *)"web_sitemap_build", (char *)"base,items", web_sitemap_build) != 0) return 1;
|
||||
if (host_register((char *)"web_app_route_ws", (char *)"app,path,echo,mode", web_app_route_ws) != 0) return 1;
|
||||
if (host_register((char *)"web_ws_connect", (char *)"url,message,headers,timeout_sec", web_ws_connect) != 0) return 1;
|
||||
return 0;
|
||||
}
|
||||
*/
|
||||
|
||||
Reference in new issue
Block a user