Null-DRM-Official/apps/agent/internal/worker/worker.go
404errordeveloper a091922efa
All checks were successful
release / build-and-upload (push) Successful in 7m2s
streamd v0.2.2: session uptimes, egress DNS, Support, agent/Widevine
Dashboard Live uptimes + Recent runs from stream_sessions; overview.recent_sessions.
WireGuard netns resolv.conf + missing-deps WARN. Support donations card.
Agent start/stop/update, job_backoff default off, wvkey ensure/venv, phonecap retries,
modhost YAML enrich, DRM SetCredentials requires keys.
2026-10-10 19:26:39 +02:00

216 lines
6 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package worker
import (
"errors"
"fmt"
"log"
"strings"
"time"
"streamd/modhost"
"streamd/phonecap"
"streamd/repo"
"streamd/apps/agent/internal/client"
"streamd/apps/agent/internal/device"
"streamd/apps/agent/internal/poller"
"streamd/apps/agent/internal/queue"
)
type Worker struct {
ID int
API *client.Client
Queue *queue.Store
Pool *device.Pool
AgentID string
CaptureWait time.Duration
Python string
WVD string
UserAgent string
// JobBackoff enables exponential delays between failed capture attempts.
// When false (default), failed jobs are re-queued immediately.
JobBackoff bool
Log *log.Logger
lastDelayLog time.Time
}
func (w *Worker) Loop(stop <-chan struct{}) {
t := time.NewTicker(2 * time.Second)
defer t.Stop()
for {
select {
case <-stop:
return
case <-t.C:
w.tick()
}
}
}
func (w *Worker) tick() {
job, ok, err := w.Queue.ClaimNext()
if err != nil {
w.logf("claim next: %v", err)
return
}
if !ok {
if j, until, found, err := w.Queue.NextDelayed(); err == nil && found {
if time.Since(w.lastDelayLog) > 30*time.Second {
w.lastDelayLog = time.Now()
w.logf("no runnable jobs; next is job=%d stream=%s in %s (backoff)",
j.ID, j.StreamName, until.Round(time.Second))
}
}
return
}
w.logf("job=%d running stream=%s app=%s channel=%s reason=%s",
job.ID, job.StreamName, job.App, job.Channel, job.Reason)
if err := w.runJob(job); err != nil {
if device.IsWait(err) || isAuthErr(err) || isUnknownAppErr(err) {
// Config/environment issues — do not burn attempts or multi-minute backoff.
w.logf("job=%d waiting: %v", job.ID, err)
_ = w.Queue.MarkFailed(job.ID, err.Error(), true, 0)
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})
backoff := time.Duration(0)
if w.JobBackoff {
backoff = queue.ExponentialBackoff(job.Attempts + 1)
w.logf("job=%d re-queue in %s (job_backoff=true)", job.ID, backoff)
}
_ = w.Queue.MarkFailed(job.ID, err.Error(), false, backoff)
return
}
_ = w.Queue.MarkOK(job.ID)
w.logf("job=%d ok stream=%s", job.ID, job.StreamName)
}
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")
}
func isUnknownAppErr(err error) bool {
if err == nil {
return false
}
s := strings.ToLower(err.Error())
return strings.Contains(s, "unknown app") || strings.Contains(s, "unknown module") || strings.Contains(s, "no modules found")
}
func (w *Worker) runJob(job queue.Job) error {
a, err := modhost.Open(repo.Root(), job.App)
if err != nil {
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
}
defer w.Pool.Release(serial)
_ = w.Queue.SetDevice(job.ID, serial)
w.logf("job=%d device=%s package=%s", job.ID, serial, a.Package())
// Long enough for DRM capture retries (3×90s wait + launch). Heartbeats renew.
if err := w.API.Claim(job.StreamID, w.AgentID, 360); err != nil {
return fmt.Errorf("streamd claim: %w", err)
}
defer func() { _ = w.API.ReleaseClaim(job.StreamID, w.AgentID) }()
res, err := phonecap.Run(phonecap.Options{
App: a,
Channel: job.Channel,
Client: c,
Python: w.Python,
WVD: w.WVD,
UserAgent: w.UserAgent,
Wait: w.CaptureWait,
CloseApp: true,
ClearProxy: true,
})
if err != nil {
return err
}
needsKeys := true
if km := strings.ToLower(strings.TrimSpace(a.KeyMode())); km == "none" || km == "clear" {
needsKeys = false
}
hasKey := poller.ValidKeyPair(res.Key)
if needsKeys && !hasKey {
return fmt.Errorf("refusing to post credentials without valid Widevine key (got mpd=%q key_empty=%v)",
trimURL(res.MPD), strings.TrimSpace(res.Key) == "")
}
if strings.TrimSpace(res.MPD) == "" {
return fmt.Errorf("refusing to post credentials without mpd")
}
cred := client.Credentials{
MPD: res.MPD,
Key: res.Key,
PSSH: res.Session.PSSH,
Auth: res.Session.Auth,
PID: res.Session.PID,
}
if err := w.API.PostCredentials(job.StreamID, cred); err != nil {
return fmt.Errorf("post credentials: %w", err)
}
w.logf("job=%d posted credentials to streamd has_key=%v key_valid=%v mpd=%s",
job.ID, strings.TrimSpace(res.Key) != "", hasKey, trimURL(res.MPD))
// 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": hasKey,
})
return nil
}
func trimURL(s string) string {
s = strings.TrimSpace(s)
if len(s) <= 96 {
return s
}
return s[:96] + "…"
}
// 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 {
w.Log.Printf(prefix+format, args...)
return
}
log.Printf(prefix+format, args...)
}