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:
1 parent
199a5efaef
commit
22887fef03
100 files changed
+9740
-429
No files matched your search
@@ -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
|
||||
|
||||
Reference in new issue
Block a user