Files
CollabTable/shared/backend/syncsocket/syncsocket.go
T

714 lines
19 KiB
Go
Raw Normal View History

// Package syncsocket is a cross-device playback-sync websocket hub: multiple clients viewing the
// same media session (identified by a caller-chosen sessionId) see each other's
// play/pause/seek/remote-control state live. It is shared so every project that offers live sync
// uses one copy instead of duplicating it.
2026-09-07 16:00:08 +02:00
//
// A service wires this up as:
//
// hub := syncsocket.NewHub()
// router.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
// hub.ServeWebSocket(w, r, cfg.AllowedOrigin)
// })
//
// and MountRoutes' GET/PUT /sync HTTP routes call hub.HTTPState/
2026-09-07 16:00:08 +02:00
// SetHTTPState/Broadcast to read and mutate the same session state the
// websocket peers see.
package syncsocket
2026-09-01 08:43:25 +02:00
import (
"context"
"crypto/rand"
"encoding/hex"
2026-09-01 08:43:25 +02:00
"encoding/json"
"errors"
2026-09-01 08:43:25 +02:00
"math"
"net/http"
"net/url"
"strings"
"sync"
"time"
"github.com/coder/websocket"
)
const (
maxSyncIdentifier = 128
maxSyncSessions = 1000
maxSyncConnections = 1000
maxPeerWriteQueue = 64
maxPeerMessagesPerSecond = 120
2026-09-01 08:43:25 +02:00
)
2026-09-07 16:00:08 +02:00
type peer struct {
2026-09-01 08:43:25 +02:00
conn *websocket.Conn
out chan []byte
done chan struct{}
closeOnce sync.Once
messageWindow time.Time
messageCount int
2026-09-01 08:43:25 +02:00
clientID string
sessionID string
remoteControlEnabled bool
uiView string
uiMediaID any
uiMediaIDSet bool
}
2026-09-07 16:00:08 +02:00
// Hub tracks every connected sync websocket peer and the last-known playback
// state per session, broadcasting updates to every peer sharing a session.
type Hub struct {
2026-09-01 08:43:25 +02:00
mu sync.Mutex
2026-09-07 16:00:08 +02:00
peers map[*peer]struct{}
2026-09-01 08:43:25 +02:00
states map[string]map[string]any
playAt map[string]string
playAtLocalMs map[string]int64
capturedAtMs map[string]int64
controlOwners map[string]string
}
2026-09-07 16:00:08 +02:00
// NewHub returns an empty Hub ready to accept websocket connections and
// serve/mutate HTTP sync state.
func NewHub() *Hub {
return &Hub{
peers: make(map[*peer]struct{}),
2026-09-01 08:43:25 +02:00
states: make(map[string]map[string]any),
playAt: make(map[string]string),
playAtLocalMs: make(map[string]int64),
capturedAtMs: make(map[string]int64),
controlOwners: make(map[string]string),
}
}
2026-10-19 07:48:07 +00:00
// add registers a peer, or reports false when the hub already holds maxSyncConnections peers.
func (h *Hub) add(p *peer) bool {
2026-09-01 08:43:25 +02:00
h.mu.Lock()
2026-10-19 07:48:07 +00:00
if len(h.peers) >= maxSyncConnections {
h.mu.Unlock()
2026-10-19 07:48:07 +00:00
return false
}
p.out = make(chan []byte, maxPeerWriteQueue)
p.done = make(chan struct{})
2026-09-07 16:00:08 +02:00
h.peers[p] = struct{}{}
h.mu.Unlock()
go p.writeLoop()
2026-10-19 07:48:07 +00:00
return true
2026-09-01 08:43:25 +02:00
}
2026-09-07 16:00:08 +02:00
func (h *Hub) remove(p *peer) string {
2026-09-01 08:43:25 +02:00
h.mu.Lock()
defer h.mu.Unlock()
2026-09-07 16:00:08 +02:00
delete(h.peers, p)
p.closeOnce.Do(func() { close(p.done) })
2026-09-07 16:00:08 +02:00
if p.clientID != "" && !h.hasClientLocked(p.clientID) {
delete(h.controlOwners, p.clientID)
2026-09-01 08:43:25 +02:00
for targetID, ownerID := range h.controlOwners {
2026-09-07 16:00:08 +02:00
if ownerID == p.clientID {
2026-09-01 08:43:25 +02:00
delete(h.controlOwners, targetID)
}
}
}
2026-09-07 16:00:08 +02:00
return p.sessionID
2026-09-01 08:43:25 +02:00
}
2026-09-07 16:00:08 +02:00
func (h *Hub) hasClientLocked(clientID string) bool {
for p := range h.peers {
if p.clientID == clientID {
2026-09-01 08:43:25 +02:00
return true
}
}
return false
}
func (h *Hub) updatePeer(p *peer, sessionID string) {
2026-09-01 08:43:25 +02:00
h.mu.Lock()
if sessionID != "" {
2026-09-07 16:00:08 +02:00
p.sessionID = sessionID
2026-09-01 08:43:25 +02:00
}
h.mu.Unlock()
}
2026-09-07 16:00:08 +02:00
func (h *Hub) clientStatus(p *peer, sessionID, view string, mediaID any, mediaIDSet bool, remoteSet, remote bool) {
2026-09-01 08:43:25 +02:00
h.mu.Lock()
defer h.mu.Unlock()
if sessionID != "" {
2026-09-07 16:00:08 +02:00
p.sessionID = sessionID
2026-09-01 08:43:25 +02:00
}
if view != "" {
2026-09-07 16:00:08 +02:00
p.uiView = view
2026-09-01 08:43:25 +02:00
}
if mediaIDSet {
2026-09-07 16:00:08 +02:00
p.uiMediaID = mediaID
p.uiMediaIDSet = true
2026-09-01 08:43:25 +02:00
}
if remoteSet {
2026-09-07 16:00:08 +02:00
p.remoteControlEnabled = remote
if !remote && h.controlOwners[p.clientID] != "" {
delete(h.controlOwners, p.clientID)
2026-09-01 08:43:25 +02:00
}
}
}
2026-09-07 16:00:08 +02:00
func (h *Hub) clientsLocked(sessionID string) []map[string]any {
2026-09-01 08:43:25 +02:00
byID := make(map[string]map[string]any)
2026-09-07 16:00:08 +02:00
for p := range h.peers {
if p.sessionID != sessionID || p.clientID == "" {
2026-09-01 08:43:25 +02:00
continue
}
2026-09-07 16:00:08 +02:00
entry, exists := byID[p.clientID]
2026-09-01 08:43:25 +02:00
if !exists {
entry = map[string]any{
2026-09-07 16:00:08 +02:00
"clientId": p.clientID,
"remoteControlEnabled": p.remoteControlEnabled,
2026-09-01 08:43:25 +02:00
"controlOwnerClientId": nil,
}
2026-09-07 16:00:08 +02:00
byID[p.clientID] = entry
} else if p.remoteControlEnabled {
2026-09-01 08:43:25 +02:00
entry["remoteControlEnabled"] = true
}
2026-09-07 16:00:08 +02:00
if p.uiView != "" {
entry["uiView"] = p.uiView
2026-09-01 08:43:25 +02:00
}
2026-09-07 16:00:08 +02:00
if p.uiMediaIDSet {
entry["uiMediaId"] = p.uiMediaID
2026-09-01 08:43:25 +02:00
}
}
for clientID, entry := range byID {
if owner := h.controlOwners[clientID]; owner != "" {
entry["controlOwnerClientId"] = owner
}
}
clients := make([]map[string]any, 0, len(byID))
for _, entry := range byID {
clients = append(clients, entry)
}
return clients
}
2026-09-07 16:00:08 +02:00
func (h *Hub) stateLocked(sessionID string) map[string]any {
2026-09-01 08:43:25 +02:00
state, ok := h.states[sessionID]
if !ok {
return map[string]any{
"sessionId": sessionID,
"mediaId": nil,
"timeMs": int64(0),
"paused": true,
"fps": 30,
"frame": int64(0),
"fromClientId": "",
"updatedAt": time.Unix(0, 0).UTC().Format(time.RFC3339Nano),
}
}
return cloneMap(state)
}
2026-09-07 16:00:08 +02:00
// HTTPState returns the current playback state for a session, as seen by the
// GET /sync HTTP endpoint (mounted by MountRoutes).
2026-09-07 16:00:08 +02:00
func (h *Hub) HTTPState(sessionID string) map[string]any {
2026-09-01 08:43:25 +02:00
h.mu.Lock()
defer h.mu.Unlock()
return h.timingLocked(sessionID, h.stateLocked(sessionID))
}
2026-09-07 16:00:08 +02:00
// SetHTTPState overwrites a session's playback state, as driven by the
// PUT /sync HTTP endpoint (mounted by MountRoutes) - callers should follow this
2026-09-07 16:00:08 +02:00
// with Broadcast to notify connected websocket peers.
func (h *Hub) SetHTTPState(sessionID string, state map[string]any) {
2026-09-01 08:43:25 +02:00
h.mu.Lock()
defer h.mu.Unlock()
h.states[sessionID] = cloneMap(state)
if len(h.states) > maxSyncSessions {
for key := range h.states {
delete(h.states, key)
break
}
}
}
2026-09-07 16:00:08 +02:00
func (h *Hub) timingLocked(sessionID string, state map[string]any) map[string]any {
2026-09-01 08:43:25 +02:00
paused, _ := state["paused"].(bool)
if !paused {
if value := h.playAt[sessionID]; value != "" {
state["playAt"] = value
}
}
if value, ok := h.playAtLocalMs[sessionID]; ok {
state["playAtLocalMs"] = value
}
if value, ok := h.capturedAtMs[sessionID]; ok {
state["capturedAtLocalMs"] = value
}
return state
}
2026-09-07 16:00:08 +02:00
// Broadcast pushes the current state of sessionID to every connected
// websocket peer sharing that session.
func (h *Hub) Broadcast(sessionID string) {
2026-09-01 08:43:25 +02:00
h.mu.Lock()
state := h.timingLocked(sessionID, h.stateLocked(sessionID))
clients := h.clientsLocked(sessionID)
2026-09-07 16:00:08 +02:00
peers := make([]*peer, 0)
for p := range h.peers {
if p.sessionID == sessionID {
peers = append(peers, p)
2026-09-01 08:43:25 +02:00
}
}
h.mu.Unlock()
message := map[string]any{"type": "sync:state", "state": state, "clients": clients}
data, err := json.Marshal(message)
if err != nil {
return
}
2026-09-07 16:00:08 +02:00
for _, p := range peers {
if err := p.sendData(data); err != nil {
p.drop(websocket.StatusGoingAway, "slow or closed peer")
2026-09-01 08:43:25 +02:00
}
}
}
2026-09-07 16:00:08 +02:00
func (p *peer) send(message any) error {
2026-09-01 08:43:25 +02:00
data, err := json.Marshal(message)
if err != nil {
return err
}
return p.sendData(data)
2026-09-01 08:43:25 +02:00
}
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.
2026-09-07 16:00:08 +02:00
func websocketAcceptOptions(r *http.Request, allowedOrigin string) *websocket.AcceptOptions {
2026-09-01 08:43:25 +02:00
options := &websocket.AcceptOptions{}
patterns := make([]string, 0, 2)
addOrigin := func(value string) {
parsed, err := url.Parse(strings.TrimSpace(value))
if err == nil && parsed.Scheme != "" && parsed.Host != "" {
patterns = append(patterns, parsed.Scheme+"://"+parsed.Host)
}
}
2026-09-07 16:00:08 +02:00
addOrigin(allowedOrigin)
2026-09-01 08:43:25 +02:00
scheme := "http"
if r.TLS != nil {
scheme = "https"
}
addOrigin(scheme + "://" + r.Host)
options.OriginPatterns = patterns
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})
}
2026-09-07 16:00:08 +02:00
// ServeWebSocket upgrades the request to a websocket connection and services
// it until the client disconnects. allowedOrigin should be the service's own
// 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.
2026-09-07 16:00:08 +02:00
func (h *Hub) ServeWebSocket(w http.ResponseWriter, r *http.Request, allowedOrigin string) {
conn, err := websocket.Accept(w, r, websocketAcceptOptions(r, allowedOrigin))
2026-09-01 08:43:25 +02:00
if err != nil {
return
}
clientID, err := newClientID()
if err != nil {
_ = conn.Close(websocket.StatusInternalError, "could not issue client identity")
return
2026-09-01 08:43:25 +02:00
}
p := &peer{conn: conn, clientID: clientID}
2026-10-19 07:48:07 +00:00
if !h.add(p) {
_ = conn.Close(websocket.StatusTryAgainLater, "too many sync connections")
return
}
2026-09-01 08:43:25 +02:00
defer func() {
2026-09-07 16:00:08 +02:00
sessionID := h.remove(p)
2026-09-01 08:43:25 +02:00
_ = conn.Close(websocket.StatusNormalClosure, "")
if sessionID != "" {
2026-09-07 16:00:08 +02:00
h.Broadcast(sessionID)
2026-09-01 08:43:25 +02:00
}
}()
_ = p.send(map[string]any{"type": "hello", "clientId": clientID, "ts": time.Now().UnixMilli()})
2026-09-01 08:43:25 +02:00
for {
messageType, payload, readErr := conn.Read(r.Context())
if readErr != nil {
return
}
if !p.allowMessage(time.Now()) {
p.close()
return
}
2026-09-01 08:43:25 +02:00
if messageType != websocket.MessageText {
continue
}
var message map[string]any
if json.Unmarshal(payload, &message) != nil {
continue
}
2026-09-07 16:00:08 +02:00
h.handleMessage(p, message)
2026-09-01 08:43:25 +02:00
}
}
2026-09-07 16:00:08 +02:00
func (h *Hub) handleMessage(p *peer, message map[string]any) {
2026-09-01 08:43:25 +02:00
typ, _ := message["type"].(string)
switch typ {
case "ws:ping":
2026-09-07 16:00:08 +02:00
_ = p.send(map[string]any{
2026-09-01 08:43:25 +02:00
"type": "ws:pong",
"nonce": syncString(message, "nonce"),
"clientSentAt": syncNumberValue(message, "clientSentAt"),
"serverReceivedAt": time.Now().UnixMilli(),
})
case "sync:hello":
if !p.acceptsClientID(message) {
p.refuseClientID()
2026-09-01 08:43:25 +02:00
return
}
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), "default"))
if sessionID == "" {
return
}
h.updatePeer(p, sessionID)
2026-09-07 16:00:08 +02:00
h.Broadcast(sessionID)
2026-09-01 08:43:25 +02:00
case "client:status":
if !p.acceptsClientID(message) {
p.refuseClientID()
2026-09-01 08:43:25 +02:00
return
}
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
h.updatePeer(p, sessionID)
2026-09-01 08:43:25 +02:00
mediaID, mediaIDSet := syncMediaID(message)
remote, remoteSet := message["remoteControlEnabled"].(bool)
2026-09-07 16:00:08 +02:00
h.clientStatus(p, sessionID, boundedSyncString(syncString(message, "uiView")), mediaID, mediaIDSet, remoteSet, remote)
h.Broadcast(sessionID)
2026-09-01 08:43:25 +02:00
case "control:claim", "control:release":
2026-09-07 16:00:08 +02:00
h.handleControlMessage(p, typ, message)
2026-09-01 08:43:25 +02:00
case "sync:update":
2026-09-07 16:00:08 +02:00
h.handleSyncUpdate(p, message)
2026-09-01 08:43:25 +02:00
}
}
2026-09-07 16:00:08 +02:00
func (h *Hub) handleControlMessage(p *peer, typ string, message map[string]any) {
if !p.acceptsClientID(message) {
p.refuseClientID()
return
}
requesterID := p.clientID
2026-09-07 16:00:08 +02:00
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
2026-09-01 08:43:25 +02:00
targetID := boundedSyncString(syncString(message, "targetClientId"))
if targetID == "" {
2026-09-01 08:43:25 +02:00
return
}
2026-09-07 16:00:08 +02:00
h.mu.Lock()
owner := h.controlOwners[targetID]
2026-09-01 08:43:25 +02:00
ok := false
reason := ""
if typ == "control:claim" {
enabled := false
2026-09-07 16:00:08 +02:00
for candidate := range h.peers {
2026-09-01 08:43:25 +02:00
if candidate.clientID == targetID && candidate.remoteControlEnabled {
enabled = true
break
}
}
switch {
case !enabled:
reason = "disabled"
case owner != "" && owner != requesterID:
reason = "busy"
default:
2026-09-07 16:00:08 +02:00
h.controlOwners[targetID] = requesterID
2026-09-01 08:43:25 +02:00
owner = requesterID
ok = true
}
} else if owner != "" && owner != requesterID {
reason = "not-owner"
} else {
2026-09-07 16:00:08 +02:00
delete(h.controlOwners, targetID)
2026-09-01 08:43:25 +02:00
owner = ""
ok = true
}
2026-09-07 16:00:08 +02:00
h.mu.Unlock()
2026-09-01 08:43:25 +02:00
2026-09-07 16:00:08 +02:00
_ = p.send(map[string]any{
2026-09-01 08:43:25 +02:00
"type": "control:ack",
"ok": ok,
"action": strings.TrimPrefix(typ, "control:"),
"targetClientId": targetID,
"ownerClientId": nullableString(owner),
"reason": nullableString(reason),
})
2026-09-07 16:00:08 +02:00
h.Broadcast(sessionID)
2026-09-01 08:43:25 +02:00
}
2026-09-07 16:00:08 +02:00
func (h *Hub) handleSyncUpdate(p *peer, message map[string]any) {
if !p.acceptsClientID(message) {
p.refuseClientID()
2026-09-01 08:43:25 +02:00
return
}
clientID := p.clientID
sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), p.sessionID, "default"))
2026-09-01 08:43:25 +02:00
mediaID, _ := syncMediaID(message)
paused := syncBool(message, "paused")
state := map[string]any{
"sessionId": sessionID,
"mediaId": mediaID,
"timeMs": syncInt(message, "timeMs", 0),
"paused": paused,
"fps": syncFPS(message),
"frame": syncInt(message, "frame", 0),
"fromClientId": clientID,
"updatedAt": time.Now().UTC().Format(time.RFC3339Nano),
}
for _, key := range []string{"openInUi", "seekToken", "seekPhase", "seekWantPlay", "seekTargetClientId", "fullscreen", "goToGrid"} {
if value, ok := message[key]; ok {
state[key] = value
}
}
toClientID := boundedSyncString(syncString(message, "toClientId"))
playAtRaw, hasPlayAt := message["playAt"]
2026-09-07 16:00:08 +02:00
h.mu.Lock()
2026-09-01 08:43:25 +02:00
if paused || !hasPlayAt || strings.TrimSpace(syncStringValue(playAtRaw)) == "" {
2026-09-07 16:00:08 +02:00
delete(h.playAt, sessionID)
delete(h.playAtLocalMs, sessionID)
2026-09-01 08:43:25 +02:00
} else if parsed, err := time.Parse(time.RFC3339Nano, strings.TrimSpace(syncStringValue(playAtRaw))); err == nil {
2026-09-07 16:00:08 +02:00
h.playAt[sessionID] = parsed.UTC().Format(time.RFC3339Nano)
2026-09-01 08:43:25 +02:00
if local := syncInt(message, "playAtLocalMs", 0); local > 0 {
2026-09-07 16:00:08 +02:00
h.playAtLocalMs[sessionID] = local
2026-09-01 08:43:25 +02:00
} else {
2026-09-07 16:00:08 +02:00
delete(h.playAtLocalMs, sessionID)
2026-09-01 08:43:25 +02:00
}
}
if captured := syncInt(message, "capturedAtLocalMs", 0); captured > 0 {
2026-09-07 16:00:08 +02:00
h.capturedAtMs[sessionID] = captured
2026-09-01 08:43:25 +02:00
}
2026-10-19 07:48:07 +00:00
trimSessionMap(h.playAt)
trimSessionMap(h.playAtLocalMs)
trimSessionMap(h.capturedAtMs)
2026-09-01 08:43:25 +02:00
if toClientID == "" {
2026-09-07 16:00:08 +02:00
h.states[sessionID] = cloneMap(state)
if len(h.states) > maxSyncSessions {
for key := range h.states {
delete(h.states, key)
2026-09-01 08:43:25 +02:00
break
}
}
}
2026-09-07 16:00:08 +02:00
state = h.timingLocked(sessionID, state)
clients := h.clientsLocked(sessionID)
peers := make([]*peer, 0)
2026-09-01 08:43:25 +02:00
if toClientID != "" {
2026-09-07 16:00:08 +02:00
for candidate := range h.peers {
2026-09-01 08:43:25 +02:00
if candidate.sessionID == sessionID && candidate.clientID == toClientID {
peers = append(peers, candidate)
}
}
}
2026-09-07 16:00:08 +02:00
h.mu.Unlock()
2026-09-01 08:43:25 +02:00
messageOut := map[string]any{"type": "sync:state", "state": state, "clients": clients}
if toClientID != "" {
for _, target := range peers {
if err := target.send(messageOut); err != nil {
target.drop(websocket.StatusGoingAway, "write failed")
2026-09-01 08:43:25 +02:00
}
}
return
}
2026-09-07 16:00:08 +02:00
h.Broadcast(sessionID)
2026-09-01 08:43:25 +02:00
}
func syncMediaID(message map[string]any) (any, bool) {
value, ok := message["mediaId"]
if !ok {
return nil, false
}
if value == nil {
return nil, true
}
return boundedSyncString(syncStringValue(value)), true
}
func syncString(message map[string]any, key string) string {
return syncStringValue(message[key])
}
func syncStringValue(value any) string {
if value == nil {
return ""
}
if text, ok := value.(string); ok {
return strings.TrimSpace(text)
}
return ""
}
func boundedSyncString(value string) string {
value = strings.TrimSpace(value)
if len(value) > maxSyncIdentifier {
return value[:maxSyncIdentifier]
}
return value
}
func syncBool(message map[string]any, key string) bool {
value, _ := message[key].(bool)
return value
}
func syncNumberValue(message map[string]any, key string) any {
if value, ok := message[key]; ok {
return value
}
return nil
}
func syncInt(message map[string]any, key string, fallback int64) int64 {
value, ok := message[key].(float64)
if !ok || math.IsNaN(value) || math.IsInf(value, 0) {
return fallback
}
if value < 0 {
return 0
}
if value > float64(^uint64(0)>>1) {
return int64(^uint64(0) >> 1)
}
return int64(math.Round(value))
}
func syncFPS(message map[string]any) int64 {
fps := syncInt(message, "fps", 30)
if fps < 1 {
return 1
}
if fps > 240 {
return 240
}
return fps
}
func nullableString(value string) any {
if value == "" {
return nil
}
return value
}
func cloneMap(value map[string]any) map[string]any {
result := make(map[string]any, len(value))
for key, item := range value {
result[key] = item
}
return result
}
2026-09-07 16:00:08 +02:00
2026-10-19 07:48:07 +00:00
// trimSessionMap keeps a per-session map within maxSyncSessions by dropping entries, the same
// bound the states map uses. Session IDs come from clients, so without it each map would grow
// for every ID ever seen.
func trimSessionMap[V any](values map[string]V) {
for len(values) > maxSyncSessions {
for key := range values {
delete(values, key)
break
}
}
}
2026-09-07 16:00:08 +02:00
func firstNonEmpty(values ...string) string {
for _, value := range values {
if strings.TrimSpace(value) != "" {
return value
}
}
return ""
}