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
|
|
@ -3,6 +3,7 @@ package client
|
|||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
|
|
@ -10,35 +11,84 @@ import (
|
|||
"time"
|
||||
)
|
||||
|
||||
// Version is reported in the User-Agent so streamd's audit log can tell
|
||||
// agent builds apart.
|
||||
const Version = "2.0"
|
||||
|
||||
type Client struct {
|
||||
BaseURL string
|
||||
Token string
|
||||
HTTP *http.Client
|
||||
UserAgent string
|
||||
BaseURL string
|
||||
Token string
|
||||
HTTP *http.Client
|
||||
UserAgent string
|
||||
// AgentID is sent as X-Agent-ID so streamd can attribute audit rows to
|
||||
// this agent rather than just to the API key it shares.
|
||||
AgentID string
|
||||
}
|
||||
|
||||
// ErrUnauthorized is returned when streamd rejects this agent's credential.
|
||||
// It is checked by the worker so a bad key does not burn job attempts.
|
||||
var ErrUnauthorized = errors.New("unauthorized")
|
||||
|
||||
func New(baseURL, token string) *Client {
|
||||
return &Client{
|
||||
BaseURL: strings.TrimRight(baseURL, "/"),
|
||||
Token: token,
|
||||
HTTP: &http.Client{Timeout: 30 * time.Second},
|
||||
UserAgent: "drm-agent/1.0",
|
||||
BaseURL: strings.TrimRight(baseURL, "/"),
|
||||
Token: token,
|
||||
HTTP: &http.Client{Timeout: 30 * time.Second},
|
||||
UserAgent: "drm-agent/" + Version,
|
||||
}
|
||||
}
|
||||
|
||||
// Stream is one row of GET /api/streams.
|
||||
//
|
||||
// Note there is no Key field. streamd redacts credentials from this response,
|
||||
// and the agent only ever writes keys, never reads them. Decisions that used
|
||||
// to be made here by inspecting the key are now made server-side and arrive
|
||||
// as NeedsCapture / KeyValid / DRMRequired.
|
||||
type Stream struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Title string `json:"title"`
|
||||
App string `json:"app"`
|
||||
Channel string `json:"channel"`
|
||||
Tags string `json:"tags"`
|
||||
MPD string `json:"mpd"`
|
||||
Key string `json:"key"`
|
||||
Enabled bool `json:"enabled"`
|
||||
Health string `json:"health"`
|
||||
LastError string `json:"last_error"`
|
||||
PlaylistAgeS float64 `json:"playlist_age_s"`
|
||||
ClaimedBy string `json:"claimed_by"`
|
||||
|
||||
// Credential state, without the credentials.
|
||||
HasKey bool `json:"has_key"`
|
||||
KeyValid bool `json:"key_valid"`
|
||||
DRMRequired bool `json:"drm_required"`
|
||||
// NeedsCapture is streamd's verdict on whether to refresh credentials.
|
||||
// This is the field the poller acts on.
|
||||
NeedsCapture bool `json:"needs_capture"`
|
||||
|
||||
OnDemand bool `json:"on_demand"`
|
||||
Public bool `json:"public"`
|
||||
|
||||
Outputs []Output `json:"outputs"`
|
||||
}
|
||||
|
||||
// Output is one configured publish format, shown by `agent status`.
|
||||
type Output struct {
|
||||
ID string `json:"id"`
|
||||
Label string `json:"label"`
|
||||
Format string `json:"format"`
|
||||
Enabled bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// EnabledOutputs is a short label list for display, e.g. "HLS, DASH".
|
||||
func (s Stream) EnabledOutputs() string {
|
||||
var on []string
|
||||
for _, o := range s.Outputs {
|
||||
if o.Enabled {
|
||||
on = append(on, o.Label)
|
||||
}
|
||||
}
|
||||
return strings.Join(on, ",")
|
||||
}
|
||||
|
||||
type Credentials struct {
|
||||
|
|
@ -49,11 +99,34 @@ type Credentials struct {
|
|||
PID string `json:"pid,omitempty"`
|
||||
}
|
||||
|
||||
// Identity is the answer from GET /api/me.
|
||||
type Identity struct {
|
||||
Name string `json:"name"`
|
||||
Role string `json:"role"`
|
||||
ActorKind string `json:"actor_kind"`
|
||||
AgentID string `json:"agent_id,omitempty"`
|
||||
}
|
||||
|
||||
func (c *Client) Health() error {
|
||||
_, err := c.do(http.MethodGet, "/api/health", nil)
|
||||
return err
|
||||
}
|
||||
|
||||
// Me verifies this agent's credential and reports the role it was granted.
|
||||
// Called at startup so a missing, wrong or revoked key fails loudly instead
|
||||
// of silently failing every poll.
|
||||
func (c *Client) Me() (Identity, error) {
|
||||
body, err := c.do(http.MethodGet, "/api/me", nil)
|
||||
if err != nil {
|
||||
return Identity{}, err
|
||||
}
|
||||
var id Identity
|
||||
if err := json.Unmarshal(body, &id); err != nil {
|
||||
return Identity{}, err
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
|
||||
func (c *Client) ListStreams() ([]Stream, error) {
|
||||
body, err := c.do(http.MethodGet, "/api/streams", nil)
|
||||
if err != nil {
|
||||
|
|
@ -85,6 +158,26 @@ func (c *Client) PostCredentials(id int64, cred Credentials) error {
|
|||
return err
|
||||
}
|
||||
|
||||
// Capture event kinds reported back to streamd, so a failing phone capture
|
||||
// shows up on the stream's timeline in the dashboard instead of only in this
|
||||
// agent's console.
|
||||
const (
|
||||
EventCaptureStarted = "capture_started"
|
||||
EventCaptureOK = "capture_ok"
|
||||
EventCaptureFailed = "capture_failed"
|
||||
)
|
||||
|
||||
// PostEvent records an agent-authored event against a stream. Failures are
|
||||
// the caller's to ignore: losing a timeline entry must never fail a capture.
|
||||
func (c *Client) PostEvent(streamID int64, kind, message string, detail map[string]any) error {
|
||||
payload := map[string]any{"kind": kind, "message": message}
|
||||
if len(detail) > 0 {
|
||||
payload["detail"] = detail
|
||||
}
|
||||
_, err := c.do(http.MethodPost, fmt.Sprintf("/api/streams/%d/events", streamID), payload)
|
||||
return err
|
||||
}
|
||||
|
||||
// ModuleInfo is one modules/<name>/ entry from GET /api/modules.
|
||||
type ModuleInfo struct {
|
||||
Name string `json:"name"`
|
||||
|
|
@ -113,22 +206,33 @@ func (c *Client) PutModuleYAML(name string, yamlBytes []byte) error {
|
|||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "text/yaml")
|
||||
req.Header.Set("User-Agent", c.UserAgent)
|
||||
if c.Token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+c.Token)
|
||||
}
|
||||
c.setHeaders(req)
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 1<<20))
|
||||
if resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("PUT /api/modules/%s: %s — %s", name, resp.Status, strings.TrimSpace(string(body)))
|
||||
return c.statusError(http.MethodPut, "/api/modules/"+name, resp, body)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) setHeaders(req *http.Request) {
|
||||
ua := c.UserAgent
|
||||
if ua == "" {
|
||||
ua = "drm-agent/" + Version
|
||||
}
|
||||
req.Header.Set("User-Agent", ua)
|
||||
if c.Token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+c.Token)
|
||||
}
|
||||
if c.AgentID != "" {
|
||||
req.Header.Set("X-Agent-ID", c.AgentID)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) do(method, path string, payload any) ([]byte, error) {
|
||||
var rdr io.Reader
|
||||
if payload != nil {
|
||||
|
|
@ -145,18 +249,53 @@ func (c *Client) do(method, path string, payload any) ([]byte, error) {
|
|||
if payload != nil {
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
req.Header.Set("User-Agent", c.UserAgent)
|
||||
if c.Token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+c.Token)
|
||||
}
|
||||
c.setHeaders(req)
|
||||
resp, err := c.HTTP.Do(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
body, _ := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
|
||||
if resp.StatusCode >= 300 {
|
||||
return nil, fmt.Errorf("%s %s: %s — %s", method, path, resp.Status, strings.TrimSpace(string(body)))
|
||||
return nil, c.statusError(method, path, resp, body)
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// statusError turns an HTTP failure into something actionable. A 401 or 403
|
||||
// used to surface as a bare status line, which left an operator guessing why
|
||||
// a working agent had gone quiet.
|
||||
func (c *Client) statusError(method, path string, resp *http.Response, body []byte) error {
|
||||
msg := strings.TrimSpace(string(body))
|
||||
if parsed := errorField(body); parsed != "" {
|
||||
msg = parsed
|
||||
}
|
||||
switch resp.StatusCode {
|
||||
case http.StatusUnauthorized:
|
||||
hint := "streamd rejected this agent's credential"
|
||||
if c.Token == "" {
|
||||
hint = "streamd requires a credential and none is configured"
|
||||
}
|
||||
return fmt.Errorf("%w: %s %s — %s. Set `token:` (or `api_key:`) in apps/agent/agent.yaml, "+
|
||||
"or STREAMD_TOKEN, to an API key created in the streamd dashboard under "+
|
||||
"Settings -> API keys (role: operator). Server said: %s",
|
||||
ErrUnauthorized, method, path, hint, msg)
|
||||
case http.StatusForbidden:
|
||||
return fmt.Errorf("%w: %s %s — this agent's API key lacks the needed role; "+
|
||||
"it must be at least `operator`. Server said: %s", ErrUnauthorized, method, path, msg)
|
||||
case http.StatusTooManyRequests:
|
||||
return fmt.Errorf("%s %s: rate limited by streamd (retry-after %s) — %s",
|
||||
method, path, resp.Header.Get("Retry-After"), msg)
|
||||
}
|
||||
return fmt.Errorf("%s %s: %s — %s", method, path, resp.Status, msg)
|
||||
}
|
||||
|
||||
func errorField(body []byte) string {
|
||||
var wrap struct {
|
||||
Error string `json:"error"`
|
||||
}
|
||||
if json.Unmarshal(body, &wrap) == nil {
|
||||
return strings.TrimSpace(wrap.Error)
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
|
|
|||
|
|
@ -11,8 +11,12 @@ import (
|
|||
)
|
||||
|
||||
type Config struct {
|
||||
StreamdURL string `yaml:"streamd_url"`
|
||||
StreamdURL string `yaml:"streamd_url"`
|
||||
// Token is this agent's streamd credential. It is now an API key created
|
||||
// in the dashboard (Settings -> API keys, role operator) rather than the
|
||||
// one shared secret; `api_key` is a clearer alias for the same field.
|
||||
Token string `yaml:"token"`
|
||||
APIKey string `yaml:"api_key"`
|
||||
PollIntervalSec int `yaml:"poll_interval_sec"`
|
||||
DataDir string `yaml:"data_dir"`
|
||||
Workers int `yaml:"workers"`
|
||||
|
|
@ -24,9 +28,19 @@ type Config struct {
|
|||
UserAgent string `yaml:"user_agent"`
|
||||
AgentID string `yaml:"agent_id"`
|
||||
// SyncModules pushes local modules/<name>/module.yaml to streamd when missing/stale.
|
||||
SyncModules bool `yaml:"sync_modules"`
|
||||
ModulesDir string `yaml:"modules_dir"` // empty = repo modules/
|
||||
ModulesSyncIntervalSec int `yaml:"modules_sync_interval_sec"`
|
||||
SyncModules bool `yaml:"sync_modules"`
|
||||
ModulesDir string `yaml:"modules_dir"` // empty = repo modules/
|
||||
ModulesSyncIntervalSec int `yaml:"modules_sync_interval_sec"`
|
||||
// OnDemandPriority lets a capture that streamd pushed — a viewer waking
|
||||
// an on-demand stream, or a scheduled event about to start — jump ahead
|
||||
// of routine refreshes in the queue.
|
||||
OnDemandPriority *bool `yaml:"ondemand_priority"`
|
||||
}
|
||||
|
||||
// PushedCapturesArePriority reports whether pushed captures jump the queue.
|
||||
// Defaults to true: somebody is waiting on them.
|
||||
func (c Config) PushedCapturesArePriority() bool {
|
||||
return c.OnDemandPriority == nil || *c.OnDemandPriority
|
||||
}
|
||||
|
||||
func (c Config) PollInterval() time.Duration {
|
||||
|
|
@ -72,9 +86,15 @@ func applyDefaults(cfg Config, root string) Config {
|
|||
if cfg.StreamdURL == "" {
|
||||
cfg.StreamdURL = "http://127.0.0.1:8083"
|
||||
}
|
||||
if cfg.Token == "" {
|
||||
cfg.Token = cfg.APIKey
|
||||
}
|
||||
if cfg.Token == "" {
|
||||
cfg.Token = os.Getenv("STREAMD_TOKEN")
|
||||
}
|
||||
if cfg.Token == "" {
|
||||
cfg.Token = os.Getenv("STREAMD_API_KEY")
|
||||
}
|
||||
if cfg.PollIntervalSec <= 0 {
|
||||
cfg.PollIntervalSec = 30
|
||||
}
|
||||
|
|
|
|||
|
|
@ -9,10 +9,10 @@ import (
|
|||
|
||||
// Pool tracks free/busy ADB devices. Never installs apps.
|
||||
type Pool struct {
|
||||
mu sync.Mutex
|
||||
adbBin string
|
||||
allow map[string]bool // empty allow = all serials
|
||||
busy map[string]string // serial → job label
|
||||
mu sync.Mutex
|
||||
adbBin string
|
||||
allow map[string]bool // empty allow = all serials
|
||||
busy map[string]string // serial → job label
|
||||
}
|
||||
|
||||
func New(adbBin string, allowlist []string) *Pool {
|
||||
|
|
|
|||
|
|
@ -51,6 +51,27 @@ func (p *Poller) Once() error {
|
|||
return nil
|
||||
}
|
||||
|
||||
// EnqueueNow is the entry point for a capture streamd has pushed over the
|
||||
// websocket, for a viewer waking an on-demand stream or a scheduled event
|
||||
// about to start. It jumps ahead of routine refreshes because somebody is
|
||||
// waiting on it.
|
||||
func (p *Poller) EnqueueNow(streamID int64, name, app, channel, reason string) {
|
||||
if reason == "" {
|
||||
reason = "requested"
|
||||
}
|
||||
j, added, err := p.Queue.EnqueueIfIdlePriority(
|
||||
streamID, name, app, channel, reason, p.MaxAttempts, queue.PriorityInteractive)
|
||||
switch {
|
||||
case err != nil:
|
||||
p.logf("push capture for stream %s failed: %v", name, err)
|
||||
case added:
|
||||
p.logf("enqueued job=%d stream=%s reason=%s (pushed by streamd, priority)", j.ID, name, reason)
|
||||
default:
|
||||
// Already queued or running: EnqueueIfIdlePriority promoted it.
|
||||
p.logf("push capture for stream %s: a job is already pending (promoted)", name)
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Poller) Loop(stop <-chan struct{}) {
|
||||
t := time.NewTicker(p.Interval)
|
||||
defer t.Stop()
|
||||
|
|
@ -67,11 +88,24 @@ func (p *Poller) Loop(stop <-chan struct{}) {
|
|||
}
|
||||
}
|
||||
|
||||
// needsRefresh decides whether a stream wants fresh credentials.
|
||||
//
|
||||
// The verdict comes from streamd, not from inspecting the key: credentials are
|
||||
// redacted out of the stream list, so a local "is the key empty?" test would
|
||||
// see every stream as broken and queue a capture for all of them forever.
|
||||
// streamd also knows things this agent does not — whether the stream is clear
|
||||
// rather than encrypted, whether it is an idle on-demand stream, and whether
|
||||
// it is still inside its start-up window.
|
||||
func needsRefresh(st client.Stream) string {
|
||||
if strings.TrimSpace(st.MPD) == "" || strings.TrimSpace(st.Key) == "" {
|
||||
return "missing_credentials"
|
||||
if !st.NeedsCapture {
|
||||
return ""
|
||||
}
|
||||
if !validKeyPair(st.Key) {
|
||||
switch {
|
||||
case strings.TrimSpace(st.MPD) == "":
|
||||
return "missing_credentials"
|
||||
case st.DRMRequired && !st.HasKey:
|
||||
return "missing_credentials"
|
||||
case st.DRMRequired && !st.KeyValid:
|
||||
return "invalid_credentials"
|
||||
}
|
||||
h := strings.ToLower(strings.TrimSpace(st.Health))
|
||||
|
|
@ -79,27 +113,44 @@ func needsRefresh(st client.Stream) string {
|
|||
case "down", "error", "failed":
|
||||
return "down"
|
||||
}
|
||||
return ""
|
||||
return "stale"
|
||||
}
|
||||
|
||||
// validKeyPair accepts KID:KEY as 32-hex:32-hex (colons/dashes in KID ignored).
|
||||
func validKeyPair(key string) bool {
|
||||
parts := strings.SplitN(strings.TrimSpace(key), ":", 2)
|
||||
if len(parts) != 2 {
|
||||
return false
|
||||
}
|
||||
hexOnly := func(s string) string {
|
||||
var b strings.Builder
|
||||
for _, r := range s {
|
||||
switch {
|
||||
case r >= '0' && r <= '9', r >= 'a' && r <= 'f', r >= 'A' && r <= 'F':
|
||||
b.WriteRune(r)
|
||||
}
|
||||
// ValidKeyPair accepts KID:KEY as 32-hex:32-hex (colons/dashes in KID
|
||||
// ignored). The authoritative check lives in streamd; this copy exists only
|
||||
// to sanity-check what a worker is about to POST.
|
||||
func ValidKeyPair(key string) bool {
|
||||
for _, line := range splitKeyLines(key) {
|
||||
kid, k, ok := strings.Cut(line, ":")
|
||||
if !ok || len(hexOnly(kid)) != 32 || len(hexOnly(k)) != 32 {
|
||||
return false
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
kid, k := hexOnly(parts[0]), hexOnly(parts[1])
|
||||
return len(kid) == 32 && len(k) == 32
|
||||
return len(splitKeyLines(key)) > 0
|
||||
}
|
||||
|
||||
// splitKeyLines mirrors how streamd and the packager split a key field, so a
|
||||
// multi-KID capture is not mistaken for a malformed one.
|
||||
func splitKeyLines(raw string) []string {
|
||||
raw = strings.NewReplacer(",", "\n", ";", "\n").Replace(raw)
|
||||
var out []string
|
||||
for _, line := range strings.Split(raw, "\n") {
|
||||
if line = strings.TrimSpace(line); line != "" {
|
||||
out = append(out, line)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func hexOnly(s string) string {
|
||||
var b strings.Builder
|
||||
for _, r := range s {
|
||||
switch {
|
||||
case r >= '0' && r <= '9', r >= 'a' && r <= 'f', r >= 'A' && r <= 'F':
|
||||
b.WriteRune(r)
|
||||
}
|
||||
}
|
||||
return b.String()
|
||||
}
|
||||
|
||||
func (p *Poller) logf(format string, args ...any) {
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ package queue
|
|||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
|
@ -100,24 +101,56 @@ func parseTime(s string) time.Time {
|
|||
return t
|
||||
}
|
||||
|
||||
// EnqueueIfIdle inserts a job unless one is already queued/running for the stream.
|
||||
// Job priorities. ClaimNext orders by priority ascending, so a lower number
|
||||
// runs sooner.
|
||||
const (
|
||||
// PriorityInteractive is for a capture a viewer or a schedule is actively
|
||||
// waiting on, pushed by streamd over the agent websocket.
|
||||
PriorityInteractive = 10
|
||||
// PriorityRoutine is a background refresh found by polling.
|
||||
PriorityRoutine = 100
|
||||
)
|
||||
|
||||
// EnqueueIfIdle inserts a routine job unless one is already queued/running
|
||||
// for the stream.
|
||||
func (s *Store) EnqueueIfIdle(streamID int64, name, app, channel, reason string, maxAttempts int) (Job, bool, error) {
|
||||
var existing int
|
||||
return s.EnqueueIfIdlePriority(streamID, name, app, channel, reason, maxAttempts, PriorityRoutine)
|
||||
}
|
||||
|
||||
// EnqueueIfIdlePriority is EnqueueIfIdle with an explicit priority. A job that
|
||||
// someone is waiting on is enqueued ahead of routine refreshes; if a routine
|
||||
// job for the same stream is already queued, its priority is raised instead of
|
||||
// adding a duplicate.
|
||||
func (s *Store) EnqueueIfIdlePriority(streamID int64, name, app, channel, reason string, maxAttempts, priority int) (Job, bool, error) {
|
||||
var existingID int64
|
||||
var existingPriority int
|
||||
err := s.DB.QueryRow(`
|
||||
SELECT COUNT(1) FROM jobs WHERE stream_id=? AND status IN ('queued','running')`, streamID).Scan(&existing)
|
||||
if err != nil {
|
||||
return Job{}, false, err
|
||||
}
|
||||
if existing > 0 {
|
||||
SELECT id, priority FROM jobs
|
||||
WHERE stream_id=? AND status IN ('queued','running')
|
||||
ORDER BY id LIMIT 1`, streamID).Scan(&existingID, &existingPriority)
|
||||
switch {
|
||||
case err == nil:
|
||||
// Already pending. Promote it when this request is more urgent, and
|
||||
// clear any backoff so it runs now rather than after the delay.
|
||||
if priority < existingPriority {
|
||||
_, _ = s.DB.Exec(
|
||||
`UPDATE jobs SET priority=?, reason=?, not_before='' WHERE id=? AND status='queued'`,
|
||||
priority, reason, existingID)
|
||||
}
|
||||
return Job{}, false, nil
|
||||
case !errors.Is(err, sql.ErrNoRows):
|
||||
return Job{}, false, err
|
||||
}
|
||||
if maxAttempts <= 0 {
|
||||
maxAttempts = 5
|
||||
}
|
||||
if priority <= 0 {
|
||||
priority = PriorityRoutine
|
||||
}
|
||||
res, err := s.DB.Exec(`
|
||||
INSERT INTO jobs(stream_id,stream_name,app,channel,reason,status,priority,attempts,max_attempts,created_at,not_before)
|
||||
VALUES(?,?,?,?,?,'queued',100,0,?,?,?)`,
|
||||
streamID, name, app, channel, reason, maxAttempts, now(), now())
|
||||
VALUES(?,?,?,?,?,'queued',?,0,?,?,?)`,
|
||||
streamID, name, app, channel, reason, priority, maxAttempts, now(), now())
|
||||
if err != nil {
|
||||
return Job{}, false, err
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
package worker
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
|
|
@ -12,6 +13,7 @@ import (
|
|||
|
||||
"drmdecryption/apps/agent/internal/client"
|
||||
"drmdecryption/apps/agent/internal/device"
|
||||
"drmdecryption/apps/agent/internal/poller"
|
||||
"drmdecryption/apps/agent/internal/queue"
|
||||
)
|
||||
|
||||
|
|
@ -69,6 +71,8 @@ func (w *Worker) tick() {
|
|||
return
|
||||
}
|
||||
w.logf("job=%d failed: %v", job.ID, err)
|
||||
w.event(job, client.EventCaptureFailed, err.Error(),
|
||||
map[string]any{"attempts": job.Attempts + 1, "max_attempts": job.MaxAttempts})
|
||||
_ = w.Queue.MarkFailed(job.ID, err.Error(), false)
|
||||
return
|
||||
}
|
||||
|
|
@ -80,6 +84,11 @@ func isAuthErr(err error) bool {
|
|||
if err == nil {
|
||||
return false
|
||||
}
|
||||
// The client now returns a typed error with an actionable message; the
|
||||
// substring check stays as a fallback for errors raised elsewhere.
|
||||
if errors.Is(err, client.ErrUnauthorized) {
|
||||
return true
|
||||
}
|
||||
s := strings.ToLower(err.Error())
|
||||
return strings.Contains(s, "401") || strings.Contains(s, "unauthorized")
|
||||
}
|
||||
|
|
@ -98,6 +107,10 @@ func (w *Worker) runJob(job queue.Job) error {
|
|||
return err
|
||||
}
|
||||
label := fmt.Sprintf("job-%d:%s", job.ID, job.StreamName)
|
||||
// Tell streamd a capture is under way, so the stream's timeline in the
|
||||
// dashboard shows it rather than just an unexplained "down".
|
||||
w.event(job, client.EventCaptureStarted,
|
||||
fmt.Sprintf("capture started on %s (%s)", w.AgentID, job.Reason), nil)
|
||||
c, serial, err := w.Pool.Acquire(a.Package(), label)
|
||||
if err != nil {
|
||||
return err
|
||||
|
|
@ -137,9 +150,31 @@ func (w *Worker) runJob(job queue.Job) error {
|
|||
if err := w.API.PostCredentials(job.StreamID, cred); err != nil {
|
||||
return fmt.Errorf("post credentials: %w", err)
|
||||
}
|
||||
// Report what was captured, never the key itself.
|
||||
w.event(job, client.EventCaptureOK, "credentials captured and posted", map[string]any{
|
||||
"device": serial,
|
||||
"has_key": strings.TrimSpace(res.Key) != "",
|
||||
"key_valid": poller.ValidKeyPair(res.Key),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
// event posts a stream event to streamd. A timeline entry is never worth
|
||||
// failing a capture over, so errors are logged and dropped.
|
||||
func (w *Worker) event(job queue.Job, kind, message string, detail map[string]any) {
|
||||
if w.API == nil || job.StreamID == 0 {
|
||||
return
|
||||
}
|
||||
if detail == nil {
|
||||
detail = map[string]any{}
|
||||
}
|
||||
detail["agent_id"] = w.AgentID
|
||||
detail["job_id"] = job.ID
|
||||
if err := w.API.PostEvent(job.StreamID, kind, message, detail); err != nil {
|
||||
w.logf("job=%d: could not report %s to streamd: %v", job.ID, kind, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (w *Worker) logf(format string, args ...any) {
|
||||
prefix := fmt.Sprintf("worker/%d: ", w.ID)
|
||||
if w.Log != nil {
|
||||
|
|
|
|||
|
|
@ -10,16 +10,39 @@ import (
|
|||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
|
||||
"drmdecryption/apps/agent/internal/client"
|
||||
)
|
||||
|
||||
// Message is one push from streamd.
|
||||
type Message struct {
|
||||
Type string `json:"type"`
|
||||
OK bool `json:"ok"`
|
||||
Error string `json:"error"`
|
||||
Message string `json:"message"`
|
||||
StreamID int64 `json:"stream_id"`
|
||||
StreamName string `json:"stream_name"`
|
||||
App string `json:"app"`
|
||||
Channel string `json:"channel"`
|
||||
Reason string `json:"reason"`
|
||||
}
|
||||
|
||||
// Client keeps a streamd /ws/agent connection alive and sends heartbeats
|
||||
// so claims auto-renew; on disconnect streamd releases this agent's claims.
|
||||
// It also carries pushes from streamd: a capture a viewer or a schedule is
|
||||
// waiting on, which would otherwise not be noticed until the next poll.
|
||||
type Client struct {
|
||||
BaseURL string
|
||||
Token string
|
||||
AgentID string
|
||||
Log *log.Logger
|
||||
|
||||
// OnCapture is called when streamd asks for credentials now.
|
||||
OnCapture func(streamID int64, name, app, channel, reason string)
|
||||
// OnStreamChanged is called when a stream was edited, so the agent can
|
||||
// re-poll instead of waiting out its interval.
|
||||
OnStreamChanged func(name, reason string)
|
||||
|
||||
stop chan struct{}
|
||||
}
|
||||
|
||||
|
|
@ -47,7 +70,8 @@ func (c *Client) Loop() {
|
|||
return
|
||||
default:
|
||||
}
|
||||
if err := c.session(); err != nil {
|
||||
err := c.session()
|
||||
if err != nil {
|
||||
c.Log.Printf("ws: session ended: %v — retry in %s", err, backoff)
|
||||
}
|
||||
select {
|
||||
|
|
@ -75,18 +99,29 @@ func (c *Client) session() error {
|
|||
u.Path = "/ws/agent"
|
||||
q := u.Query()
|
||||
q.Set("agent_id", c.AgentID)
|
||||
if c.Token != "" {
|
||||
q.Set("token", c.Token)
|
||||
}
|
||||
// The token is deliberately NOT put in the query string. It used to be,
|
||||
// which wrote the shared secret into every reverse proxy access log.
|
||||
// streamd authenticates the handshake from the Authorization header below.
|
||||
u.RawQuery = q.Encode()
|
||||
|
||||
hdr := http.Header{}
|
||||
if c.Token != "" {
|
||||
hdr.Set("Authorization", "Bearer "+c.Token)
|
||||
}
|
||||
if c.AgentID != "" {
|
||||
hdr.Set("X-Agent-ID", c.AgentID)
|
||||
}
|
||||
hdr.Set("User-Agent", "drm-agent/"+client.Version)
|
||||
dialer := websocket.Dialer{HandshakeTimeout: 10 * time.Second}
|
||||
conn, _, err := dialer.Dial(u.String(), hdr)
|
||||
conn, resp, err := dialer.Dial(u.String(), hdr)
|
||||
if err != nil {
|
||||
if resp != nil {
|
||||
switch resp.StatusCode {
|
||||
case http.StatusUnauthorized, http.StatusForbidden:
|
||||
return fmt.Errorf("dial: %w (streamd rejected this agent's API key for /ws/agent; "+
|
||||
"it needs at least the operator role)", err)
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("dial: %w", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
|
@ -107,14 +142,11 @@ func (c *Client) session() error {
|
|||
return
|
||||
}
|
||||
_ = conn.SetReadDeadline(time.Now().Add(60 * time.Second))
|
||||
var msg map[string]any
|
||||
if json.Unmarshal(data, &msg) == nil {
|
||||
if t, _ := msg["type"].(string); t == "heartbeat_ack" {
|
||||
if ok, _ := msg["ok"].(bool); !ok {
|
||||
c.Log.Printf("ws: heartbeat nack: %v", msg["error"])
|
||||
}
|
||||
}
|
||||
var msg Message
|
||||
if json.Unmarshal(data, &msg) != nil {
|
||||
continue
|
||||
}
|
||||
c.handle(msg)
|
||||
}
|
||||
}()
|
||||
|
||||
|
|
@ -139,6 +171,28 @@ func (c *Client) session() error {
|
|||
}
|
||||
}
|
||||
|
||||
func (c *Client) handle(msg Message) {
|
||||
switch strings.ToLower(msg.Type) {
|
||||
case "heartbeat_ack":
|
||||
if !msg.OK {
|
||||
c.Log.Printf("ws: heartbeat nack: %s", msg.Error)
|
||||
}
|
||||
case "capture_requested":
|
||||
if msg.StreamID == 0 {
|
||||
return
|
||||
}
|
||||
c.Log.Printf("ws: streamd requested a capture for stream=%s reason=%s",
|
||||
msg.StreamName, msg.Reason)
|
||||
if c.OnCapture != nil {
|
||||
c.OnCapture(msg.StreamID, msg.StreamName, msg.App, msg.Channel, msg.Reason)
|
||||
}
|
||||
case "stream_changed":
|
||||
if c.OnStreamChanged != nil {
|
||||
c.OnStreamChanged(msg.StreamName, msg.Reason)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) writeHeartbeat(conn *websocket.Conn) error {
|
||||
_ = conn.SetWriteDeadline(time.Now().Add(10 * time.Second))
|
||||
return conn.WriteJSON(map[string]string{
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue