streamd: preview quality picker, dashboard polish, C4 wrap keys
- 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
This commit is contained in:
parent
b3955bd81e
commit
066e018749
113 changed files with 19002 additions and 1541 deletions
|
|
@ -2,7 +2,7 @@ package ws
|
|||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
|
|
@ -10,6 +10,7 @@ import (
|
|||
|
||||
"github.com/gorilla/websocket"
|
||||
|
||||
"drmdecryption/apps/streamd/internal/auth"
|
||||
"drmdecryption/apps/streamd/internal/db"
|
||||
)
|
||||
|
||||
|
|
@ -19,21 +20,26 @@ const (
|
|||
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
|
||||
)
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
CheckOrigin: func(r *http.Request) bool { return true },
|
||||
}
|
||||
|
||||
// Hub tracks agent WebSocket sessions and UI listeners.
|
||||
type Hub struct {
|
||||
Store *db.Store
|
||||
Token string
|
||||
Log *log.Logger
|
||||
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 {
|
||||
|
|
@ -55,19 +61,70 @@ type outbound struct {
|
|||
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, token string, lg *log.Logger) *Hub {
|
||||
func NewHub(store *db.Store, lg *slog.Logger, allowedOrigins []string) *Hub {
|
||||
if lg == nil {
|
||||
lg = log.Default()
|
||||
lg = slog.Default()
|
||||
}
|
||||
return &Hub{
|
||||
Store: store,
|
||||
Token: token,
|
||||
Log: lg,
|
||||
agents: map[string]*agentConn{},
|
||||
uis: map[*websocket.Conn]struct{}{},
|
||||
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) {
|
||||
|
|
@ -93,9 +150,9 @@ func (h *Hub) RunExpireLoop(stop <-chan struct{}) {
|
|||
func (h *Hub) tick() {
|
||||
n, err := h.Store.ExpireClaims()
|
||||
if err != nil {
|
||||
h.Log.Printf("ws: expire claims: %v", err)
|
||||
h.Log.Error("ws: expire claims", "err", err)
|
||||
} else if n > 0 {
|
||||
h.Log.Printf("ws: expired %d stale claim(s)", n)
|
||||
h.Log.Info("ws: expired stale claims", "count", n)
|
||||
h.broadcastUI(outbound{Type: "claims_changed", Message: "expired"})
|
||||
}
|
||||
|
||||
|
|
@ -109,36 +166,29 @@ func (h *Hub) tick() {
|
|||
}
|
||||
h.mu.Unlock()
|
||||
for _, id := range stale {
|
||||
h.Log.Printf("ws: agent %s heartbeat stale — releasing claims", id)
|
||||
h.Log.Warn("ws: agent heartbeat stale — releasing claims", "agent", id)
|
||||
h.dropAgent(id, true)
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Hub) authToken(r *http.Request) bool {
|
||||
if h.Token == "" {
|
||||
return true
|
||||
}
|
||||
tok := r.URL.Query().Get("token")
|
||||
if tok == "" {
|
||||
auth := r.Header.Get("Authorization")
|
||||
tok = strings.TrimPrefix(auth, "Bearer ")
|
||||
}
|
||||
if tok == "" {
|
||||
tok = r.Header.Get("X-Streamd-Token")
|
||||
}
|
||||
return tok == h.Token
|
||||
}
|
||||
|
||||
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) {
|
||||
conn, err := upgrader.Upgrade(w, r, nil)
|
||||
if _, ok := auth.Guard(w, r, auth.RoleViewer); !ok {
|
||||
return
|
||||
}
|
||||
conn, err := h.upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
|
@ -159,24 +209,51 @@ func (h *Hub) handleUI(w http.ResponseWriter, r *http.Request) {
|
|||
})
|
||||
// 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) {
|
||||
if !h.authToken(r) {
|
||||
http.Error(w, `{"error":"unauthorized"}`, http.StatusUnauthorized)
|
||||
// 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 := upgrader.Upgrade(w, r, nil)
|
||||
conn, err := h.upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
|
@ -184,7 +261,7 @@ func (h *Hub) handleAgent(w http.ResponseWriter, r *http.Request) {
|
|||
conn: conn,
|
||||
agentID: agentID,
|
||||
lastSeen: time.Now().UTC(),
|
||||
send: make(chan []byte, 8),
|
||||
send: make(chan []byte, 16),
|
||||
}
|
||||
h.mu.Lock()
|
||||
if old, ok := h.agents[agentID]; ok {
|
||||
|
|
@ -193,7 +270,7 @@ func (h *Hub) handleAgent(w http.ResponseWriter, r *http.Request) {
|
|||
}
|
||||
h.agents[agentID] = ac
|
||||
h.mu.Unlock()
|
||||
h.Log.Printf("ws: agent connected id=%s", agentID)
|
||||
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)
|
||||
|
|
@ -263,12 +340,12 @@ func (h *Hub) dropAgent(agentID string, releaseClaims bool) {
|
|||
if releaseClaims {
|
||||
n, err := h.Store.ReleaseAgentClaims(agentID)
|
||||
if err != nil {
|
||||
h.Log.Printf("ws: release claims for %s: %v", agentID, err)
|
||||
h.Log.Error("ws: release claims", "agent", agentID, "err", err)
|
||||
} else if n > 0 {
|
||||
h.Log.Printf("ws: released %d claim(s) for disconnected agent %s", n, agentID)
|
||||
h.Log.Info("ws: released claims for disconnected agent", "agent", agentID, "count", n)
|
||||
}
|
||||
}
|
||||
h.Log.Printf("ws: agent disconnected id=%s", agentID)
|
||||
h.Log.Info("ws: agent disconnected", "agent", agentID)
|
||||
h.broadcastUI(outbound{Type: "agent_offline", AgentID: agentID, Agents: h.snapshotAgents()})
|
||||
}
|
||||
|
||||
|
|
@ -299,12 +376,80 @@ func (h *Hub) queue(ac *agentConn, msg outbound) {
|
|||
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))
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue