- WS handshake: same-origin CheckOrigin instead of allow-all
- route_ws require_auth/需要登录: broadcast/room need a session by default,
explicit opt-out for public feeds; unauthenticated handshakes get 401
- WS limits: 1 MiB per message, 256 replies per connect; transport errors
return {ok:false, error} instead of an empty success; empty rooms GC'd
- net host: enforce the 8 MiB response cap while reading (incl. error and
SSE error paths) so a peer cannot exhaust memory
- url_encode: %20 for space (URL segment semantics, not form +)
- docs: sync 网页 (route_ws 需要登录, connect caps) and CHANGELOG
- tests: gold expectations, live fixture opt-out, hub GC, ws auth gate
Co-authored-by: Cursor <cursoragent@cursor.com>
95 lines
1.9 KiB
Go
95 lines
1.9 KiB
Go
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)
|
|
empty := len(room.subs) == 0
|
|
room.mu.Unlock()
|
|
if !empty {
|
|
return
|
|
}
|
|
// A room can be derived from a URL path. Remove empty rooms so a stream of
|
|
// one-off room names cannot leave metadata allocated for the process lifetime.
|
|
globalHub.mu.Lock()
|
|
if globalHub.room[path] == room {
|
|
room.mu.Lock()
|
|
if len(room.subs) == 0 {
|
|
delete(globalHub.room, path)
|
|
}
|
|
room.mu.Unlock()
|
|
}
|
|
globalHub.mu.Unlock()
|
|
}
|
|
|
|
// JoinRoom subscribes to a named room (G-WS1). Same backing store as path broadcast.
|
|
func JoinRoom(room string) chan string {
|
|
return subscribe(room)
|
|
}
|
|
|
|
// LeaveRoom unsubscribes from a named room (G-WS1).
|
|
func LeaveRoom(room string, ch chan string) {
|
|
unsubscribe(room, ch)
|
|
}
|
|
|
|
// PublishRoom fans out text to all subscribers in a named room (G-WS1).
|
|
func PublishRoom(room string, text string) {
|
|
Publish(room, text)
|
|
}
|
|
|
|
// 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()
|
|
}
|