ci: expand CI checks and make consumer sync opt-in

- Add Go, npm, Python, and Java validation to CI
- Run Go tests against PostgreSQL
- Record performance fixes in the report
This commit is contained in:
Gabriel20xx committed 2026-10-19 21:14:31 +00:00
1 parent 199a5efaef
commit 22887fef03
100 files changed
+9740 -429

No files matched your search

+156 -45
View File
@@ -19,7 +19,10 @@ package syncsocket
import (
"context"
"crypto/rand"
"encoding/hex"
"encoding/json"
"errors"
"math"
"net/http"
"net/url"
@@ -31,18 +34,22 @@ import (
)
const (
maxSyncIdentifier = 128
maxSyncSessions = 1000
maxSyncConnections = 1000
maxSyncIdentifier = 128
maxSyncSessions = 1000
maxSyncConnections = 1000
maxPeerWriteQueue = 64
maxPeerMessagesPerSecond = 120
)
type peer struct {
conn *websocket.Conn
writeMu sync.Mutex
out chan []byte
done chan struct{}
closeOnce sync.Once
messageWindow time.Time
messageCount int
clientID string
sessionID string
userAgent string
ipAddress string
remoteControlEnabled bool
uiView string
uiMediaID any
@@ -77,11 +84,15 @@ func NewHub() *Hub {
// add registers a peer, or reports false when the hub already holds maxSyncConnections peers.
func (h *Hub) add(p *peer) bool {
h.mu.Lock()
defer h.mu.Unlock()
if len(h.peers) >= maxSyncConnections {
h.mu.Unlock()
return false
}
p.out = make(chan []byte, maxPeerWriteQueue)
p.done = make(chan struct{})
h.peers[p] = struct{}{}
h.mu.Unlock()
go p.writeLoop()
return true
}
@@ -89,6 +100,7 @@ func (h *Hub) remove(p *peer) string {
h.mu.Lock()
defer h.mu.Unlock()
delete(h.peers, p)
p.closeOnce.Do(func() { close(p.done) })
if p.clientID != "" && !h.hasClientLocked(p.clientID) {
delete(h.controlOwners, p.clientID)
for targetID, ownerID := range h.controlOwners {
@@ -109,11 +121,8 @@ func (h *Hub) hasClientLocked(clientID string) bool {
return false
}
func (h *Hub) updatePeer(p *peer, clientID, sessionID string) {
func (h *Hub) updatePeer(p *peer, sessionID string) {
h.mu.Lock()
if clientID != "" {
p.clientID = clientID
}
if sessionID != "" {
p.sessionID = sessionID
}
@@ -151,8 +160,6 @@ func (h *Hub) clientsLocked(sessionID string) []map[string]any {
if !exists {
entry = map[string]any{
"clientId": p.clientID,
"userAgent": p.userAgent,
"ipAddress": p.ipAddress,
"remoteControlEnabled": p.remoteControlEnabled,
"controlOwnerClientId": nil,
}
@@ -250,9 +257,13 @@ func (h *Hub) Broadcast(sessionID string) {
h.mu.Unlock()
message := map[string]any{"type": "sync:state", "state": state, "clients": clients}
data, err := json.Marshal(message)
if err != nil {
return
}
for _, p := range peers {
if err := p.send(message); err != nil {
_ = p.conn.Close(websocket.StatusGoingAway, "write failed")
if err := p.sendData(data); err != nil {
p.drop(websocket.StatusGoingAway, "slow or closed peer")
}
}
}
@@ -262,20 +273,76 @@ func (p *peer) send(message any) error {
if err != nil {
return err
}
p.writeMu.Lock()
defer p.writeMu.Unlock()
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
return p.conn.Write(ctx, websocket.MessageText, data)
return p.sendData(data)
}
func (p *peer) sendData(data []byte) error {
select {
case <-p.done:
return context.Canceled
default:
}
select {
case p.out <- data:
return nil
case <-p.done:
return context.Canceled
default:
return errPeerWriteQueueFull
}
}
var errPeerWriteQueueFull = errors.New("sync websocket peer write queue is full")
func (p *peer) writeLoop() {
for {
select {
case <-p.done:
return
case data := <-p.out:
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
err := p.conn.Write(ctx, websocket.MessageText, data)
cancel()
if err != nil {
p.stop(websocket.StatusGoingAway, "write failed")
return
}
}
}
}
func (p *peer) allowMessage(now time.Time) bool {
if now.Sub(p.messageWindow) >= time.Second {
p.messageWindow = now
p.messageCount = 0
}
p.messageCount++
return p.messageCount <= maxPeerMessagesPerSecond
}
func (p *peer) close() {
p.stop(websocket.StatusPolicyViolation, "message rate exceeded")
}
func (p *peer) stop(status websocket.StatusCode, reason string) {
p.closeOnce.Do(func() { close(p.done) })
_ = p.conn.Close(status, reason)
}
// drop stops a peer on behalf of code that is serving other peers or an HTTP request. Close waits
// for the peer's close frame (up to five seconds), which a stuck peer never sends, so it runs in
// its own goroutine instead of holding up the caller.
func (p *peer) drop(status websocket.StatusCode, reason string) {
p.closeOnce.Do(func() { close(p.done) })
go func() { _ = p.conn.Close(status, reason) }()
}
// websocketAcceptOptions enables origin verification for every connection. A
// configured origin and the request's own host are accepted. "*" adds no
// extra origin, so it does not turn the check off: a page on another site
// cannot open the socket unless its origin is listed explicitly.
func websocketAcceptOptions(r *http.Request, allowedOrigin string) *websocket.AcceptOptions {
options := &websocket.AcceptOptions{}
if allowedOrigin == "*" {
options.InsecureSkipVerify = true
return options
}
patterns := make([]string, 0, 2)
addOrigin := func(value string) {
parsed, err := url.Parse(strings.TrimSpace(value))
@@ -293,19 +360,51 @@ func websocketAcceptOptions(r *http.Request, allowedOrigin string) *websocket.Ac
return options
}
// newClientID returns a random identifier for one connection. The hub issues it
// at upgrade time and clients cannot choose it, so two connections never share
// an identity.
func newClientID() (string, error) {
var buf [16]byte
if _, err := rand.Read(buf[:]); err != nil {
return "", err
}
return hex.EncodeToString(buf[:]), nil
}
// acceptsClientID reports whether a message's clientId, if it carries one,
// names the identity issued to this connection. A message without clientId
// is taken as this connection's own.
func (p *peer) acceptsClientID(message map[string]any) bool {
requested := boundedSyncString(syncString(message, "clientId"))
return requested == "" || requested == p.clientID
}
// refuseClientID drops a message that named another identity. The connection
// stays open, and the error frame repeats the identity the client holds.
func (p *peer) refuseClientID() {
_ = p.send(map[string]any{"type": "error", "code": "client-id-mismatch", "clientId": p.clientID})
}
// ServeWebSocket upgrades the request to a websocket connection and services
// it until the client disconnects. allowedOrigin should be the service's own
// CORS_ORIGIN config value (or "*" to accept any origin).
// explicit CORS_ORIGIN value; "*" does not bypass origin verification.
//
// Each connection is issued a clientId at upgrade time. It is sent in the
// first "hello" frame, and every later message must either omit clientId or
// repeat it. A message naming any other identity gets a "client-id-mismatch"
// error frame and is otherwise ignored. A reconnect is a new connection with a
// new identity.
func (h *Hub) ServeWebSocket(w http.ResponseWriter, r *http.Request, allowedOrigin string) {
conn, err := websocket.Accept(w, r, websocketAcceptOptions(r, allowedOrigin))
if err != nil {
return
}
p := &peer{
conn: conn,
userAgent: firstNonEmpty(r.Header.Get("User-Agent"), "Unknown"),
ipAddress: firstNonEmpty(strings.Split(r.Header.Get("X-Forwarded-For"), ",")[0], r.RemoteAddr, "Unknown"),
clientID, err := newClientID()
if err != nil {
_ = conn.Close(websocket.StatusInternalError, "could not issue client identity")
return
}
p := &peer{conn: conn, clientID: clientID}
if !h.add(p) {
_ = conn.Close(websocket.StatusTryAgainLater, "too many sync connections")
return
@@ -318,12 +417,16 @@ func (h *Hub) ServeWebSocket(w http.ResponseWriter, r *http.Request, allowedOrig
}
}()
_ = p.send(map[string]any{"type": "hello", "ts": time.Now().UnixMilli()})
_ = p.send(map[string]any{"type": "hello", "clientId": clientID, "ts": time.Now().UnixMilli()})
for {
messageType, payload, readErr := conn.Read(r.Context())
if readErr != nil {
return
}
if !p.allowMessage(time.Now()) {
p.close()
return
}
if messageType != websocket.MessageText {
continue
}
@@ -346,20 +449,23 @@ func (h *Hub) handleMessage(p *peer, message map[string]any) {
"serverReceivedAt": time.Now().UnixMilli(),
})
case "sync:hello":
clientID := boundedSyncString(syncString(message, "clientId"))
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), "default"))
if clientID == "" || sessionID == "" {
if !p.acceptsClientID(message) {
p.refuseClientID()
return
}
h.updatePeer(p, clientID, sessionID)
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), "default"))
if sessionID == "" {
return
}
h.updatePeer(p, sessionID)
h.Broadcast(sessionID)
case "client:status":
clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), p.clientID))
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
if clientID == "" {
if !p.acceptsClientID(message) {
p.refuseClientID()
return
}
h.updatePeer(p, clientID, sessionID)
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
h.updatePeer(p, sessionID)
mediaID, mediaIDSet := syncMediaID(message)
remote, remoteSet := message["remoteControlEnabled"].(bool)
h.clientStatus(p, sessionID, boundedSyncString(syncString(message, "uiView")), mediaID, mediaIDSet, remoteSet, remote)
@@ -372,10 +478,14 @@ func (h *Hub) handleMessage(p *peer, message map[string]any) {
}
func (h *Hub) handleControlMessage(p *peer, typ string, message map[string]any) {
requesterID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), p.clientID))
if !p.acceptsClientID(message) {
p.refuseClientID()
return
}
requesterID := p.clientID
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
targetID := boundedSyncString(syncString(message, "targetClientId"))
if requesterID == "" || targetID == "" || requesterID != p.clientID {
if targetID == "" {
return
}
@@ -422,11 +532,12 @@ func (h *Hub) handleControlMessage(p *peer, typ string, message map[string]any)
}
func (h *Hub) handleSyncUpdate(p *peer, message map[string]any) {
clientID := boundedSyncString(firstNonEmpty(syncString(message, "clientId"), p.clientID))
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
if clientID == "" || clientID != p.clientID {
if !p.acceptsClientID(message) {
p.refuseClientID()
return
}
clientID := p.clientID
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
mediaID, _ := syncMediaID(message)
paused := syncBool(message, "paused")
state := map[string]any{
@@ -490,7 +601,7 @@ func (h *Hub) handleSyncUpdate(p *peer, message map[string]any) {
if toClientID != "" {
for _, target := range peers {
if err := target.send(messageOut); err != nil {
_ = target.conn.Close(websocket.StatusGoingAway, "write failed")
target.drop(websocket.StatusGoingAway, "write failed")
}
}
return
+272
View File
@@ -1,8 +1,17 @@
package syncsocket
import (
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"slices"
"strings"
"testing"
"time"
"github.com/coder/websocket"
)
// TestSessionTimingMapsStayBounded checks that fresh client-chosen session IDs cannot grow the
@@ -44,3 +53,266 @@ func TestHubRefusesPeersBeyondTheConnectionCap(t *testing.T) {
t.Fatal("add accepted a peer beyond maxSyncConnections")
}
}
// TestWildcardOriginKeepsOriginVerification checks that CORS_ORIGIN "*" does not disable the
// websocket origin check: only the request's own host is accepted.
func TestWildcardOriginKeepsOriginVerification(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "http://hub.example.com/ws", nil)
options := websocketAcceptOptions(req, "*")
if options.InsecureSkipVerify {
t.Fatal("wildcard origin disabled origin verification")
}
if want := []string{"http://hub.example.com"}; !slices.Equal(options.OriginPatterns, want) {
t.Fatalf("origin patterns = %v, want %v", options.OriginPatterns, want)
}
}
// TestExplicitOriginIsAcceptedAlongsideTheRequestHost checks that a listed origin is accepted
// without turning the check off.
func TestExplicitOriginIsAcceptedAlongsideTheRequestHost(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "https://hub.example.com/ws", nil)
options := websocketAcceptOptions(req, "https://app.example.com/")
if options.InsecureSkipVerify {
t.Fatal("explicit origin disabled origin verification")
}
for _, want := range []string{"https://app.example.com", "https://hub.example.com"} {
if !slices.Contains(options.OriginPatterns, want) {
t.Errorf("origin patterns %v missing %q", options.OriginPatterns, want)
}
}
}
// TestClientListOmitsPeerAddressAndUserAgent checks that broadcast client entries carry no peer
// IP address or user agent.
func TestClientListOmitsPeerAddressAndUserAgent(t *testing.T) {
hub := NewHub()
hub.add(&peer{clientID: "client-1", sessionID: "session-1", remoteControlEnabled: true})
clients := hub.clientsLocked("session-1")
if len(clients) != 1 {
t.Fatalf("clients = %d, want 1", len(clients))
}
for _, key := range []string{"ipAddress", "userAgent"} {
if _, ok := clients[0][key]; ok {
t.Errorf("client entry carries %q", key)
}
}
if clients[0]["clientId"] != "client-1" {
t.Errorf("clientId = %v, want client-1", clients[0]["clientId"])
}
}
// TestClientIdentityIsIssuedAtUpgradeAndEnforced checks the protocol change: each connection gets a
// server-issued clientId in its hello frame, a message naming another identity is refused with an
// error frame, and a message carrying the issued identity is applied.
func TestClientIdentityIsIssuedAtUpgradeAndEnforced(t *testing.T) {
hub := NewHub()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hub.ServeWebSocket(w, r, "")
}))
defer server.Close()
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
url := "ws" + strings.TrimPrefix(server.URL, "http")
first := dialSyncSocket(t, ctx, url)
defer first.CloseNow()
second := dialSyncSocket(t, ctx, url)
defer second.CloseNow()
firstID := readSyncFrame(t, ctx, first, "hello")["clientId"].(string)
secondID := readSyncFrame(t, ctx, second, "hello")["clientId"].(string)
if len(firstID) != 32 || firstID == secondID {
t.Fatalf("issued identities = %q and %q, want two distinct 32-character IDs", firstID, secondID)
}
writeSyncFrame(t, ctx, first, map[string]any{"type": "sync:hello", "clientId": secondID, "sessionId": "s1"})
refusal := readSyncFrame(t, ctx, first, "error")
if refusal["code"] != "client-id-mismatch" || refusal["clientId"] != firstID {
t.Fatalf("refusal = %v, want client-id-mismatch carrying the issued identity", refusal)
}
writeSyncFrame(t, ctx, first, map[string]any{"type": "sync:hello", "clientId": firstID, "sessionId": "s1"})
state := readSyncFrame(t, ctx, first, "sync:state")
clients, _ := state["clients"].([]any)
found := false
for _, entry := range clients {
if client, ok := entry.(map[string]any); ok && client["clientId"] == firstID {
found = true
}
}
if !found {
t.Fatalf("clients = %v, want the issued identity %q listed", clients, firstID)
}
}
func TestAcceptsClientIDOnlyForTheIssuedIdentity(t *testing.T) {
p := &peer{clientID: "issued"}
for _, tt := range []struct {
name string
message map[string]any
want bool
}{
{"no clientId", map[string]any{}, true},
{"the issued identity", map[string]any{"clientId": "issued"}, true},
{"another identity", map[string]any{"clientId": "other"}, false},
{"an oversized identity", map[string]any{"clientId": strings.Repeat("x", maxSyncIdentifier+1)}, false},
} {
if got := p.acceptsClientID(tt.message); got != tt.want {
t.Errorf("%s: acceptsClientID = %v, want %v", tt.name, got, tt.want)
}
}
}
// TestPeerMessageRateWindow checks the per-peer limit: maxPeerMessagesPerSecond messages are
// allowed in a one-second window, the next is refused, and the count restarts with the next window.
func TestPeerMessageRateWindow(t *testing.T) {
p := &peer{}
start := time.Unix(1000, 0)
for i := 0; i < maxPeerMessagesPerSecond; i++ {
if !p.allowMessage(start.Add(time.Duration(i) * time.Millisecond)) {
t.Fatalf("message %d refused inside the limit", i+1)
}
}
if p.allowMessage(start.Add(500 * time.Millisecond)) {
t.Fatal("a message past the limit was allowed")
}
if !p.allowMessage(start.Add(time.Second)) {
t.Fatal("the count did not restart with the next window")
}
}
// TestPeerExceedingTheMessageRateIsDisconnected checks that a client flooding messages is closed
// with a policy-violation status instead of being fanned out.
func TestPeerExceedingTheMessageRateIsDisconnected(t *testing.T) {
hub := NewHub()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hub.ServeWebSocket(w, r, "")
}))
defer server.Close()
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
conn := dialSyncSocket(t, ctx, "ws"+strings.TrimPrefix(server.URL, "http"))
defer conn.CloseNow()
readSyncFrame(t, ctx, conn, "hello")
go func() {
for i := 0; i < maxPeerMessagesPerSecond*4; i++ {
if conn.Write(ctx, websocket.MessageText, []byte(`{"type":"ws:ping"}`)) != nil {
return
}
}
}()
for {
if _, _, err := conn.Read(ctx); err != nil {
if got := websocket.CloseStatus(err); got != websocket.StatusPolicyViolation {
t.Fatalf("close status = %v (error %v), want policy violation", got, err)
}
return
}
}
}
// TestBroadcastDropsAPeerWithAFullQueueWithoutBlocking checks that a peer that never drains its
// write queue is stopped by Broadcast, which returns at once, and that a healthy peer in the same
// session still receives the state.
func TestBroadcastDropsAPeerWithAFullQueueWithoutBlocking(t *testing.T) {
hub := NewHub()
slowReady := make(chan *peer, 1)
release := make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/slow" {
hub.ServeWebSocket(w, r, "")
return
}
conn, err := websocket.Accept(w, r, nil)
if err != nil {
return
}
defer conn.CloseNow()
p := &peer{
conn: conn, clientID: "slow", sessionID: "s1",
out: make(chan []byte, maxPeerWriteQueue), done: make(chan struct{}),
}
for i := 0; i < maxPeerWriteQueue; i++ {
p.out <- []byte("{}")
}
hub.mu.Lock()
hub.peers[p] = struct{}{}
hub.mu.Unlock()
slowReady <- p
<-release
}))
defer server.Close()
defer close(release)
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
url := "ws" + strings.TrimPrefix(server.URL, "http")
fast := dialSyncSocket(t, ctx, url)
defer fast.CloseNow()
fastID := readSyncFrame(t, ctx, fast, "hello")["clientId"].(string)
writeSyncFrame(t, ctx, fast, map[string]any{"type": "sync:hello", "clientId": fastID, "sessionId": "s1"})
readSyncFrame(t, ctx, fast, "sync:state")
slowClient := dialSyncSocket(t, ctx, url+"/slow")
defer slowClient.CloseNow()
slow := <-slowReady
// Stopping a peer waits for a close frame that a stuck peer never sends, so Broadcast must not
// do it inline: it would hold up the caller (an HTTP request, or another peer's read loop).
started := time.Now()
hub.Broadcast("s1")
if elapsed := time.Since(started); elapsed > time.Second {
t.Fatalf("Broadcast took %v behind a stuck peer, want it to return at once", elapsed)
}
select {
case <-slow.done:
default:
t.Fatal("the peer with a full queue was not stopped")
}
state := readSyncFrame(t, ctx, fast, "sync:state")
if _, ok := state["clients"].([]any); !ok {
t.Fatalf("the healthy peer got %v, want a state with the client list", state)
}
if elapsed := time.Since(started); elapsed > time.Second {
t.Fatalf("the healthy peer's state took %v, want it at once", elapsed)
}
}
func dialSyncSocket(t *testing.T, ctx context.Context, url string) *websocket.Conn {
t.Helper()
conn, _, err := websocket.Dial(ctx, url, nil)
if err != nil {
t.Fatalf("dial %s: %v", url, err)
}
return conn
}
func writeSyncFrame(t *testing.T, ctx context.Context, conn *websocket.Conn, message map[string]any) {
t.Helper()
data, err := json.Marshal(message)
if err != nil {
t.Fatal(err)
}
if err := conn.Write(ctx, websocket.MessageText, data); err != nil {
t.Fatalf("write %v: %v", message["type"], err)
}
}
// readSyncFrame reads frames until one of the wanted type arrives, failing if the connection ends first.
func readSyncFrame(t *testing.T, ctx context.Context, conn *websocket.Conn, want string) map[string]any {
t.Helper()
for {
_, data, err := conn.Read(ctx)
if err != nil {
t.Fatalf("read while waiting for %q: %v", want, err)
}
var message map[string]any
if err := json.Unmarshal(data, &message); err != nil {
t.Fatalf("decode frame: %v", err)
}
if message["type"] == want {
return message
}
}
}