// Package syncsocket is the media-backend family's 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. Promoted unchanged from each service's own internal sync.go into // this shared library so the 6 media-family backends that mount it (every one // except KioskDisplay) use one copy instead of duplicating it. // // 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 mediacore's shared GET/PUT /sync HTTP routes call hub.HTTPState/ // SetHTTPState/Broadcast to read and mutate the same session state the // websocket peers see. package syncsocket import ( "context" "crypto/rand" "encoding/hex" "encoding/json" "errors" "math" "net/http" "net/url" "strings" "sync" "time" "github.com/coder/websocket" ) const ( maxSyncIdentifier = 128 maxSyncSessions = 1000 maxSyncConnections = 1000 maxPeerWriteQueue = 64 maxPeerMessagesPerSecond = 120 ) type peer struct { conn *websocket.Conn out chan []byte done chan struct{} closeOnce sync.Once messageWindow time.Time messageCount int clientID string sessionID string remoteControlEnabled bool uiView string uiMediaID any uiMediaIDSet bool } // 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 { mu sync.Mutex peers map[*peer]struct{} states map[string]map[string]any playAt map[string]string playAtLocalMs map[string]int64 capturedAtMs map[string]int64 controlOwners map[string]string } // 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{}), 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), } } // add registers a peer, or reports false when the hub already holds maxSyncConnections peers. func (h *Hub) add(p *peer) bool { h.mu.Lock() 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 } 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 { if ownerID == p.clientID { delete(h.controlOwners, targetID) } } } return p.sessionID } func (h *Hub) hasClientLocked(clientID string) bool { for p := range h.peers { if p.clientID == clientID { return true } } return false } func (h *Hub) updatePeer(p *peer, sessionID string) { h.mu.Lock() if sessionID != "" { p.sessionID = sessionID } h.mu.Unlock() } func (h *Hub) clientStatus(p *peer, sessionID, view string, mediaID any, mediaIDSet bool, remoteSet, remote bool) { h.mu.Lock() defer h.mu.Unlock() if sessionID != "" { p.sessionID = sessionID } if view != "" { p.uiView = view } if mediaIDSet { p.uiMediaID = mediaID p.uiMediaIDSet = true } if remoteSet { p.remoteControlEnabled = remote if !remote && h.controlOwners[p.clientID] != "" { delete(h.controlOwners, p.clientID) } } } func (h *Hub) clientsLocked(sessionID string) []map[string]any { byID := make(map[string]map[string]any) for p := range h.peers { if p.sessionID != sessionID || p.clientID == "" { continue } entry, exists := byID[p.clientID] if !exists { entry = map[string]any{ "clientId": p.clientID, "remoteControlEnabled": p.remoteControlEnabled, "controlOwnerClientId": nil, } byID[p.clientID] = entry } else if p.remoteControlEnabled { entry["remoteControlEnabled"] = true } if p.uiView != "" { entry["uiView"] = p.uiView } if p.uiMediaIDSet { entry["uiMediaId"] = p.uiMediaID } } 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 } func (h *Hub) stateLocked(sessionID string) map[string]any { 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) } // HTTPState returns the current playback state for a session, as seen by the // GET /sync HTTP endpoint (mounted by mediacore). func (h *Hub) HTTPState(sessionID string) map[string]any { h.mu.Lock() defer h.mu.Unlock() return h.timingLocked(sessionID, h.stateLocked(sessionID)) } // SetHTTPState overwrites a session's playback state, as driven by the // PUT /sync HTTP endpoint (mounted by mediacore) - callers should follow this // with Broadcast to notify connected websocket peers. func (h *Hub) SetHTTPState(sessionID string, state map[string]any) { 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 } } } func (h *Hub) timingLocked(sessionID string, state map[string]any) map[string]any { 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 } // Broadcast pushes the current state of sessionID to every connected // websocket peer sharing that session. func (h *Hub) Broadcast(sessionID string) { h.mu.Lock() state := h.timingLocked(sessionID, h.stateLocked(sessionID)) clients := h.clientsLocked(sessionID) peers := make([]*peer, 0) for p := range h.peers { if p.sessionID == sessionID { peers = append(peers, p) } } 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.sendData(data); err != nil { p.drop(websocket.StatusGoingAway, "slow or closed peer") } } } func (p *peer) send(message any) error { data, err := json.Marshal(message) if err != nil { return err } 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{} 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) } } addOrigin(allowedOrigin) 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}) } // 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. 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 } 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 } defer func() { sessionID := h.remove(p) _ = conn.Close(websocket.StatusNormalClosure, "") if sessionID != "" { h.Broadcast(sessionID) } }() _ = 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 } var message map[string]any if json.Unmarshal(payload, &message) != nil { continue } h.handleMessage(p, message) } } func (h *Hub) handleMessage(p *peer, message map[string]any) { typ, _ := message["type"].(string) switch typ { case "ws:ping": _ = p.send(map[string]any{ "type": "ws:pong", "nonce": syncString(message, "nonce"), "clientSentAt": syncNumberValue(message, "clientSentAt"), "serverReceivedAt": time.Now().UnixMilli(), }) case "sync:hello": if !p.acceptsClientID(message) { p.refuseClientID() return } sessionID := boundedSyncString(firstNonEmpty(syncString(message, "sessionId"), "default")) if sessionID == "" { return } h.updatePeer(p, sessionID) h.Broadcast(sessionID) case "client:status": if !p.acceptsClientID(message) { p.refuseClientID() return } 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) h.Broadcast(sessionID) case "control:claim", "control:release": h.handleControlMessage(p, typ, message) case "sync:update": h.handleSyncUpdate(p, message) } } func (h *Hub) handleControlMessage(p *peer, typ string, message map[string]any) { 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 targetID == "" { return } h.mu.Lock() owner := h.controlOwners[targetID] ok := false reason := "" if typ == "control:claim" { enabled := false for candidate := range h.peers { if candidate.clientID == targetID && candidate.remoteControlEnabled { enabled = true break } } switch { case !enabled: reason = "disabled" case owner != "" && owner != requesterID: reason = "busy" default: h.controlOwners[targetID] = requesterID owner = requesterID ok = true } } else if owner != "" && owner != requesterID { reason = "not-owner" } else { delete(h.controlOwners, targetID) owner = "" ok = true } h.mu.Unlock() _ = p.send(map[string]any{ "type": "control:ack", "ok": ok, "action": strings.TrimPrefix(typ, "control:"), "targetClientId": targetID, "ownerClientId": nullableString(owner), "reason": nullableString(reason), }) h.Broadcast(sessionID) } func (h *Hub) handleSyncUpdate(p *peer, message map[string]any) { 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{ "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"] h.mu.Lock() if paused || !hasPlayAt || strings.TrimSpace(syncStringValue(playAtRaw)) == "" { delete(h.playAt, sessionID) delete(h.playAtLocalMs, sessionID) } else if parsed, err := time.Parse(time.RFC3339Nano, strings.TrimSpace(syncStringValue(playAtRaw))); err == nil { h.playAt[sessionID] = parsed.UTC().Format(time.RFC3339Nano) if local := syncInt(message, "playAtLocalMs", 0); local > 0 { h.playAtLocalMs[sessionID] = local } else { delete(h.playAtLocalMs, sessionID) } } if captured := syncInt(message, "capturedAtLocalMs", 0); captured > 0 { h.capturedAtMs[sessionID] = captured } trimSessionMap(h.playAt) trimSessionMap(h.playAtLocalMs) trimSessionMap(h.capturedAtMs) if toClientID == "" { h.states[sessionID] = cloneMap(state) if len(h.states) > maxSyncSessions { for key := range h.states { delete(h.states, key) break } } } state = h.timingLocked(sessionID, state) clients := h.clientsLocked(sessionID) peers := make([]*peer, 0) if toClientID != "" { for candidate := range h.peers { if candidate.sessionID == sessionID && candidate.clientID == toClientID { peers = append(peers, candidate) } } } h.mu.Unlock() 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") } } return } h.Broadcast(sessionID) } 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 } // 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 } } } func firstNonEmpty(values ...string) string { for _, value := range values { if strings.TrimSpace(value) != "" { return value } } return "" }