- Preview player can select FHD/HD/SD (or ABR master) from publish links - Embed dashboard screenshots in README; Linux streamd+agent setup guide - C4 Widevine wrap license mode + require --wvd; prefer Widevine PSSH - Channel 4 and My5 modules; streamd auth, variants, schedules, HLS gate
495 lines
13 KiB
Go
495 lines
13 KiB
Go
package ws
|
|
|
|
import (
|
|
"encoding/json"
|
|
"log/slog"
|
|
"net/http"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/gorilla/websocket"
|
|
|
|
"drmdecryption/apps/streamd/internal/auth"
|
|
"drmdecryption/apps/streamd/internal/db"
|
|
)
|
|
|
|
const (
|
|
agentHeartbeatEvery = 20 * time.Second
|
|
agentStaleAfter = 45 * time.Second
|
|
claimRenewTTL = 90 * time.Second
|
|
writeWait = 10 * time.Second
|
|
pongWait = 60 * time.Second
|
|
// captureDebounce stops a flapping stream from spamming every agent with
|
|
// the same request. One push per stream per window is plenty.
|
|
captureDebounce = 30 * time.Second
|
|
)
|
|
|
|
// Hub tracks agent WebSocket sessions and UI listeners.
|
|
type Hub struct {
|
|
Store *db.Store
|
|
Log *slog.Logger
|
|
// AllowedOrigins are extra origins permitted to open a socket, beyond the
|
|
// server's own. Empty means same-origin only.
|
|
AllowedOrigins []string
|
|
|
|
mu sync.Mutex
|
|
agents map[string]*agentConn // agent_id -> conn
|
|
uis map[*websocket.Conn]struct{}
|
|
// lastCapture debounces capture pushes per stream id.
|
|
lastCapture map[int64]time.Time
|
|
|
|
upgrader websocket.Upgrader
|
|
}
|
|
|
|
type agentConn struct {
|
|
conn *websocket.Conn
|
|
agentID string
|
|
lastSeen time.Time
|
|
send chan []byte
|
|
}
|
|
|
|
type inbound struct {
|
|
Type string `json:"type"`
|
|
AgentID string `json:"agent_id,omitempty"`
|
|
}
|
|
|
|
type outbound struct {
|
|
Type string `json:"type"`
|
|
AgentID string `json:"agent_id,omitempty"`
|
|
OK bool `json:"ok,omitempty"`
|
|
Error string `json:"error,omitempty"`
|
|
Agents []any `json:"agents,omitempty"`
|
|
Message string `json:"message,omitempty"`
|
|
|
|
// Capture request fields. The agent needs enough to enqueue a job without
|
|
// a round trip, and deliberately never receives the credentials.
|
|
StreamID int64 `json:"stream_id,omitempty"`
|
|
StreamName string `json:"stream_name,omitempty"`
|
|
App string `json:"app,omitempty"`
|
|
Channel string `json:"channel,omitempty"`
|
|
Reason string `json:"reason,omitempty"`
|
|
}
|
|
|
|
func NewHub(store *db.Store, lg *slog.Logger, allowedOrigins []string) *Hub {
|
|
if lg == nil {
|
|
lg = slog.Default()
|
|
}
|
|
h := &Hub{
|
|
Store: store,
|
|
Log: lg,
|
|
AllowedOrigins: allowedOrigins,
|
|
agents: map[string]*agentConn{},
|
|
uis: map[*websocket.Conn]struct{}{},
|
|
lastCapture: map[int64]time.Time{},
|
|
}
|
|
// A WebSocket handshake is not subject to the same-origin policy, so
|
|
// without this check any page on the internet could open /ws/ui against a
|
|
// logged-in operator's browser and read the event stream.
|
|
h.upgrader = websocket.Upgrader{CheckOrigin: h.checkOrigin}
|
|
return h
|
|
}
|
|
|
|
func (h *Hub) checkOrigin(r *http.Request) bool {
|
|
origin := strings.TrimSpace(r.Header.Get("Origin"))
|
|
if origin == "" {
|
|
// Non-browser clients (the agent) send no Origin. They are
|
|
// authenticated by bearer token instead.
|
|
return true
|
|
}
|
|
host := strings.ToLower(hostOnly(origin))
|
|
if host != "" && host == strings.ToLower(hostOnly("//"+r.Host)) {
|
|
return true
|
|
}
|
|
for _, allowed := range h.AllowedOrigins {
|
|
allowed = strings.TrimRight(strings.TrimSpace(allowed), "/")
|
|
if allowed == "" {
|
|
continue
|
|
}
|
|
if allowed == "*" || strings.EqualFold(allowed, strings.TrimRight(origin, "/")) {
|
|
return true
|
|
}
|
|
}
|
|
h.Log.Warn("ws: rejected cross-origin handshake", "origin", origin, "host", r.Host)
|
|
return false
|
|
}
|
|
|
|
// hostOnly extracts host[:port] from an origin or //host form.
|
|
func hostOnly(u string) string {
|
|
if i := strings.Index(u, "://"); i >= 0 {
|
|
u = u[i+3:]
|
|
} else {
|
|
u = strings.TrimPrefix(u, "//")
|
|
}
|
|
if i := strings.IndexAny(u, "/?#"); i >= 0 {
|
|
u = u[:i]
|
|
}
|
|
return u
|
|
}
|
|
|
|
func (h *Hub) Mount(mux *http.ServeMux) {
|
|
mux.HandleFunc("/ws/agent", h.handleAgent)
|
|
mux.HandleFunc("/ws/ui", h.handleUI)
|
|
mux.HandleFunc("/api/agents", h.handleAgentsAPI)
|
|
}
|
|
|
|
// RunExpireLoop periodically drops expired claims and dead agent sessions.
|
|
func (h *Hub) RunExpireLoop(stop <-chan struct{}) {
|
|
t := time.NewTicker(10 * time.Second)
|
|
defer t.Stop()
|
|
for {
|
|
select {
|
|
case <-stop:
|
|
return
|
|
case <-t.C:
|
|
h.tick()
|
|
}
|
|
}
|
|
}
|
|
|
|
func (h *Hub) tick() {
|
|
n, err := h.Store.ExpireClaims()
|
|
if err != nil {
|
|
h.Log.Error("ws: expire claims", "err", err)
|
|
} else if n > 0 {
|
|
h.Log.Info("ws: expired stale claims", "count", n)
|
|
h.broadcastUI(outbound{Type: "claims_changed", Message: "expired"})
|
|
}
|
|
|
|
now := time.Now().UTC()
|
|
var stale []string
|
|
h.mu.Lock()
|
|
for id, a := range h.agents {
|
|
if now.Sub(a.lastSeen) > agentStaleAfter {
|
|
stale = append(stale, id)
|
|
}
|
|
}
|
|
h.mu.Unlock()
|
|
for _, id := range stale {
|
|
h.Log.Warn("ws: agent heartbeat stale — releasing claims", "agent", id)
|
|
h.dropAgent(id, true)
|
|
}
|
|
}
|
|
|
|
func (h *Hub) handleAgentsAPI(w http.ResponseWriter, r *http.Request) {
|
|
if r.Method != http.MethodGet {
|
|
http.Error(w, `{"error":"method not allowed"}`, http.StatusMethodNotAllowed)
|
|
return
|
|
}
|
|
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
|
|
return
|
|
}
|
|
writeJSON(w, map[string]any{"agents": h.snapshotAgents()})
|
|
}
|
|
|
|
// handleUI serves the dashboard's event stream. It now requires a principal:
|
|
// it previously had no authentication at all.
|
|
func (h *Hub) handleUI(w http.ResponseWriter, r *http.Request) {
|
|
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
|
|
return
|
|
}
|
|
conn, err := h.upgrader.Upgrade(w, r, nil)
|
|
if err != nil {
|
|
return
|
|
}
|
|
h.mu.Lock()
|
|
h.uis[conn] = struct{}{}
|
|
h.mu.Unlock()
|
|
defer func() {
|
|
h.mu.Lock()
|
|
delete(h.uis, conn)
|
|
h.mu.Unlock()
|
|
_ = conn.Close()
|
|
}()
|
|
|
|
_ = conn.SetReadDeadline(time.Now().Add(pongWait))
|
|
conn.SetPongHandler(func(string) error {
|
|
_ = conn.SetReadDeadline(time.Now().Add(pongWait))
|
|
return nil
|
|
})
|
|
// Push initial agent list.
|
|
h.sendJSON(conn, outbound{Type: "agents", Agents: h.snapshotAgents()})
|
|
|
|
// Keep the socket alive from this side too, so an idle dashboard behind a
|
|
// proxy with an idle timeout is not disconnected every minute.
|
|
stop := make(chan struct{})
|
|
defer close(stop)
|
|
go func() {
|
|
t := time.NewTicker(agentHeartbeatEvery)
|
|
defer t.Stop()
|
|
for {
|
|
select {
|
|
case <-stop:
|
|
return
|
|
case <-t.C:
|
|
_ = conn.SetWriteDeadline(time.Now().Add(writeWait))
|
|
if err := conn.WriteControl(websocket.PingMessage, nil, time.Now().Add(writeWait)); err != nil {
|
|
return
|
|
}
|
|
}
|
|
}
|
|
}()
|
|
|
|
for {
|
|
if _, _, err := conn.ReadMessage(); err != nil {
|
|
return
|
|
}
|
|
_ = conn.SetReadDeadline(time.Now().Add(pongWait))
|
|
}
|
|
}
|
|
|
|
func (h *Hub) handleAgent(w http.ResponseWriter, r *http.Request) {
|
|
// Agents authenticate with a bearer API key. The ?token= query form is
|
|
// gone: it leaked the secret into proxy logs.
|
|
p, ok := auth.Guard(w, r, auth.RoleOperator)
|
|
if !ok {
|
|
return
|
|
}
|
|
agentID := strings.TrimSpace(r.URL.Query().Get("agent_id"))
|
|
if agentID == "" {
|
|
agentID = p.AgentID
|
|
}
|
|
if agentID == "" {
|
|
http.Error(w, `{"error":"agent_id required"}`, http.StatusBadRequest)
|
|
return
|
|
}
|
|
conn, err := h.upgrader.Upgrade(w, r, nil)
|
|
if err != nil {
|
|
return
|
|
}
|
|
ac := &agentConn{
|
|
conn: conn,
|
|
agentID: agentID,
|
|
lastSeen: time.Now().UTC(),
|
|
send: make(chan []byte, 16),
|
|
}
|
|
h.mu.Lock()
|
|
if old, ok := h.agents[agentID]; ok {
|
|
close(old.send)
|
|
_ = old.conn.Close()
|
|
}
|
|
h.agents[agentID] = ac
|
|
h.mu.Unlock()
|
|
h.Log.Info("ws: agent connected", "agent", agentID, "key", p.Name)
|
|
h.broadcastUI(outbound{Type: "agent_online", AgentID: agentID, Agents: h.snapshotAgents()})
|
|
|
|
go h.agentWriter(ac)
|
|
|
|
defer h.dropAgent(agentID, true)
|
|
|
|
_ = conn.SetReadDeadline(time.Now().Add(pongWait))
|
|
conn.SetPongHandler(func(string) error {
|
|
_ = conn.SetReadDeadline(time.Now().Add(pongWait))
|
|
return nil
|
|
})
|
|
|
|
// Greeting + first renew.
|
|
h.renew(agentID)
|
|
h.queue(ac, outbound{Type: "hello", AgentID: agentID, OK: true})
|
|
|
|
for {
|
|
_, data, err := conn.ReadMessage()
|
|
if err != nil {
|
|
return
|
|
}
|
|
_ = conn.SetReadDeadline(time.Now().Add(pongWait))
|
|
var msg inbound
|
|
if err := json.Unmarshal(data, &msg); err != nil {
|
|
continue
|
|
}
|
|
switch strings.ToLower(msg.Type) {
|
|
case "heartbeat", "ping", "hello":
|
|
h.mu.Lock()
|
|
if cur, ok := h.agents[agentID]; ok {
|
|
cur.lastSeen = time.Now().UTC()
|
|
}
|
|
h.mu.Unlock()
|
|
n, err := h.renew(agentID)
|
|
if err != nil {
|
|
h.queue(ac, outbound{Type: "heartbeat_ack", OK: false, Error: err.Error()})
|
|
continue
|
|
}
|
|
h.queue(ac, outbound{Type: "heartbeat_ack", OK: true, Message: "renewed", AgentID: agentID})
|
|
if n > 0 {
|
|
h.broadcastUI(outbound{Type: "claims_changed", AgentID: agentID, Message: "renewed"})
|
|
}
|
|
case "release_all":
|
|
_, _ = h.Store.ReleaseAgentClaims(agentID)
|
|
h.broadcastUI(outbound{Type: "claims_changed", AgentID: agentID, Message: "released"})
|
|
h.queue(ac, outbound{Type: "release_ack", OK: true})
|
|
}
|
|
}
|
|
}
|
|
|
|
func (h *Hub) renew(agentID string) (int64, error) {
|
|
return h.Store.RenewAgentClaims(agentID, claimRenewTTL)
|
|
}
|
|
|
|
func (h *Hub) dropAgent(agentID string, releaseClaims bool) {
|
|
h.mu.Lock()
|
|
ac, ok := h.agents[agentID]
|
|
if ok {
|
|
delete(h.agents, agentID)
|
|
}
|
|
h.mu.Unlock()
|
|
if !ok {
|
|
return
|
|
}
|
|
close(ac.send)
|
|
_ = ac.conn.Close()
|
|
if releaseClaims {
|
|
n, err := h.Store.ReleaseAgentClaims(agentID)
|
|
if err != nil {
|
|
h.Log.Error("ws: release claims", "agent", agentID, "err", err)
|
|
} else if n > 0 {
|
|
h.Log.Info("ws: released claims for disconnected agent", "agent", agentID, "count", n)
|
|
}
|
|
}
|
|
h.Log.Info("ws: agent disconnected", "agent", agentID)
|
|
h.broadcastUI(outbound{Type: "agent_offline", AgentID: agentID, Agents: h.snapshotAgents()})
|
|
}
|
|
|
|
func (h *Hub) agentWriter(ac *agentConn) {
|
|
ticker := time.NewTicker(agentHeartbeatEvery)
|
|
defer ticker.Stop()
|
|
for {
|
|
select {
|
|
case msg, ok := <-ac.send:
|
|
if !ok {
|
|
return
|
|
}
|
|
_ = ac.conn.SetWriteDeadline(time.Now().Add(writeWait))
|
|
if err := ac.conn.WriteMessage(websocket.TextMessage, msg); err != nil {
|
|
return
|
|
}
|
|
case <-ticker.C:
|
|
_ = ac.conn.SetWriteDeadline(time.Now().Add(writeWait))
|
|
if err := ac.conn.WriteControl(websocket.PingMessage, []byte("ping"), time.Now().Add(writeWait)); err != nil {
|
|
return
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
func (h *Hub) queue(ac *agentConn, msg outbound) {
|
|
b, err := json.Marshal(msg)
|
|
if err != nil {
|
|
return
|
|
}
|
|
// Never block the caller on a wedged agent: dropping a heartbeat ack is
|
|
// harmless, and a capture request will be retried on the next poll.
|
|
select {
|
|
case ac.send <- b:
|
|
default:
|
|
}
|
|
}
|
|
|
|
// RequestCapture asks every connected agent to refresh this stream's
|
|
// credentials now. Returns how many agents were notified.
|
|
//
|
|
// This is what makes an on-demand wake and a scheduled pre-roll responsive:
|
|
// without it the agent would not notice until its next poll, up to 30s later,
|
|
// with a viewer already waiting.
|
|
func (h *Hub) RequestCapture(st db.Stream, reason string) int {
|
|
h.mu.Lock()
|
|
if last, ok := h.lastCapture[st.ID]; ok && time.Since(last) < captureDebounce {
|
|
h.mu.Unlock()
|
|
return 0
|
|
}
|
|
h.lastCapture[st.ID] = time.Now()
|
|
// Keep the debounce map from growing with deleted streams.
|
|
if len(h.lastCapture) > 1000 {
|
|
for id, t := range h.lastCapture {
|
|
if time.Since(t) > 10*time.Minute {
|
|
delete(h.lastCapture, id)
|
|
}
|
|
}
|
|
}
|
|
conns := make([]*agentConn, 0, len(h.agents))
|
|
for _, a := range h.agents {
|
|
conns = append(conns, a)
|
|
}
|
|
h.mu.Unlock()
|
|
|
|
if len(conns) == 0 {
|
|
return 0
|
|
}
|
|
msg := outbound{
|
|
Type: "capture_requested",
|
|
StreamID: st.ID,
|
|
StreamName: st.Name,
|
|
App: st.App,
|
|
Channel: st.Channel,
|
|
Reason: reason,
|
|
}
|
|
for _, ac := range conns {
|
|
h.queue(ac, msg)
|
|
}
|
|
h.Log.Info("ws: capture requested", "stream", st.Name, "reason", reason, "agents", len(conns))
|
|
return len(conns)
|
|
}
|
|
|
|
// NotifyStreamChanged tells the dashboard to refresh, and nudges agents to
|
|
// re-poll rather than wait out their interval.
|
|
func (h *Hub) NotifyStreamChanged(name, reason string) {
|
|
h.broadcastUI(outbound{Type: "streams_changed", StreamName: name, Reason: reason})
|
|
h.mu.Lock()
|
|
conns := make([]*agentConn, 0, len(h.agents))
|
|
for _, a := range h.agents {
|
|
conns = append(conns, a)
|
|
}
|
|
h.mu.Unlock()
|
|
for _, ac := range conns {
|
|
h.queue(ac, outbound{Type: "stream_changed", StreamName: name, Reason: reason})
|
|
}
|
|
}
|
|
|
|
// NotifyRuntime pushes a live health delta to the dashboard, so it does not
|
|
// have to poll the whole stream list on a timer.
|
|
func (h *Hub) NotifyRuntime(name, health string) {
|
|
h.broadcastUI(outbound{Type: "runtime", StreamName: name, Message: health})
|
|
}
|
|
|
|
func (h *Hub) sendJSON(conn *websocket.Conn, msg outbound) {
|
|
b, _ := json.Marshal(msg)
|
|
_ = conn.SetWriteDeadline(time.Now().Add(writeWait))
|
|
_ = conn.WriteMessage(websocket.TextMessage, b)
|
|
}
|
|
|
|
func (h *Hub) broadcastUI(msg outbound) {
|
|
b, err := json.Marshal(msg)
|
|
if err != nil {
|
|
return
|
|
}
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
for conn := range h.uis {
|
|
_ = conn.SetWriteDeadline(time.Now().Add(writeWait))
|
|
if err := conn.WriteMessage(websocket.TextMessage, b); err != nil {
|
|
_ = conn.Close()
|
|
delete(h.uis, conn)
|
|
}
|
|
}
|
|
}
|
|
|
|
func (h *Hub) snapshotAgents() []any {
|
|
h.mu.Lock()
|
|
defer h.mu.Unlock()
|
|
out := make([]any, 0, len(h.agents))
|
|
now := time.Now().UTC()
|
|
for id, a := range h.agents {
|
|
out = append(out, map[string]any{
|
|
"agent_id": id,
|
|
"last_seen_s": now.Sub(a.lastSeen).Seconds(),
|
|
"connected": true,
|
|
})
|
|
}
|
|
return out
|
|
}
|
|
|
|
func writeJSON(w http.ResponseWriter, v any) {
|
|
w.Header().Set("Content-Type", "application/json")
|
|
enc := json.NewEncoder(w)
|
|
enc.SetIndent("", " ")
|
|
_ = enc.Encode(v)
|
|
}
|