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
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user