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
|
|
@ -14,12 +14,28 @@ import (
|
|||
|
||||
type Store struct {
|
||||
DB *sql.DB
|
||||
// hist buffers event and metric writes; see events.go.
|
||||
hist history
|
||||
}
|
||||
|
||||
// DRM mode values for Stream.DRMMode. "auto" infers from whether the stream
|
||||
// currently holds a key, so a clear channel is not treated as broken for
|
||||
// having none.
|
||||
const (
|
||||
DRMAuto = "auto"
|
||||
DRMYes = "yes"
|
||||
DRMNo = "no"
|
||||
)
|
||||
|
||||
// DefaultIdleTimeoutS is how long an on-demand stream runs with no viewers.
|
||||
const DefaultIdleTimeoutS = 300
|
||||
|
||||
type Stream struct {
|
||||
ID int64 `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Tags string `json:"tags"`
|
||||
App string `json:"app"`
|
||||
Channel string `json:"channel"`
|
||||
MPD string `json:"mpd"`
|
||||
|
|
@ -31,6 +47,12 @@ type Stream struct {
|
|||
Enabled bool `json:"enabled"`
|
||||
Rewriter string `json:"rewriter"`
|
||||
VariantsJSON string `json:"variants_json"` // FHD/HD/SD ladder config
|
||||
OutputsJSON string `json:"outputs_json"` // HLS/CMAF/DASH/TS output config
|
||||
SettingsJSON string `json:"settings_json"` // per-stream packager knobs
|
||||
DRMMode string `json:"drm_mode"` // auto | yes | no
|
||||
OnDemand bool `json:"on_demand"`
|
||||
IdleTimeoutS int `json:"idle_timeout_s"`
|
||||
Public bool `json:"public"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
|
||||
|
|
@ -45,42 +67,80 @@ type Stream struct {
|
|||
|
||||
// Variants is filled for API responses (play paths + optional live health).
|
||||
Variants []VariantStatus `json:"variants,omitempty"`
|
||||
// Outputs is the resolved output format list for API responses.
|
||||
Outputs []OutputStatus `json:"outputs,omitempty"`
|
||||
// Links is every playable endpoint (variant x output, plus the ABR
|
||||
// master), filled by the API layer which can see the files on disk.
|
||||
Links []PublishLink `json:"links,omitempty"`
|
||||
|
||||
ClaimedBy string `json:"claimed_by,omitempty"`
|
||||
ClaimExp string `json:"claim_expires_at,omitempty"`
|
||||
|
||||
// Derived, never stored. These exist so clients — above all the capture
|
||||
// agent — can reason about credentials without being handed the secrets.
|
||||
HasKey bool `json:"has_key"`
|
||||
HasHeaders bool `json:"has_headers"`
|
||||
HasProxy bool `json:"has_proxy"`
|
||||
KeyValid bool `json:"key_valid"`
|
||||
// DRMRequired is DRMMode resolved: whether this stream needs keys at all.
|
||||
DRMRequired bool `json:"drm_required"`
|
||||
// NeedsCapture is the server's verdict on whether the agent should fetch
|
||||
// fresh credentials. The agent must use this rather than inspecting keys,
|
||||
// which are redacted out of API responses.
|
||||
NeedsCapture bool `json:"needs_capture"`
|
||||
// Viewers is the live client count, filled by the HLS gate.
|
||||
Viewers int `json:"viewers,omitempty"`
|
||||
}
|
||||
|
||||
type CreateStream struct {
|
||||
Name string `json:"name"`
|
||||
Title string `json:"title"`
|
||||
App string `json:"app"`
|
||||
Channel string `json:"channel"`
|
||||
MPD string `json:"mpd"`
|
||||
Key string `json:"key"`
|
||||
HeadersJSON string `json:"headers_json"`
|
||||
Proxy string `json:"proxy"`
|
||||
VideoSelect string `json:"video_select"`
|
||||
AudioSelect string `json:"audio_select"`
|
||||
Rewriter string `json:"rewriter"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
VariantsJSON string `json:"variants_json"`
|
||||
Variants []VariantSpec `json:"variants"`
|
||||
Name string `json:"name"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Tags string `json:"tags"`
|
||||
App string `json:"app"`
|
||||
Channel string `json:"channel"`
|
||||
MPD string `json:"mpd"`
|
||||
Key string `json:"key"`
|
||||
HeadersJSON string `json:"headers_json"`
|
||||
Proxy string `json:"proxy"`
|
||||
VideoSelect string `json:"video_select"`
|
||||
AudioSelect string `json:"audio_select"`
|
||||
Rewriter string `json:"rewriter"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
VariantsJSON string `json:"variants_json"`
|
||||
Variants []VariantSpec `json:"variants"`
|
||||
OutputsJSON string `json:"outputs_json"`
|
||||
Outputs []OutputSpec `json:"outputs"`
|
||||
SettingsJSON string `json:"settings_json"`
|
||||
DRMMode string `json:"drm_mode"`
|
||||
OnDemand *bool `json:"on_demand"`
|
||||
IdleTimeoutS *int `json:"idle_timeout_s"`
|
||||
Public *bool `json:"public"`
|
||||
}
|
||||
|
||||
type PatchStream struct {
|
||||
Title *string `json:"title"`
|
||||
App *string `json:"app"`
|
||||
Channel *string `json:"channel"`
|
||||
MPD *string `json:"mpd"`
|
||||
Key *string `json:"key"`
|
||||
HeadersJSON *string `json:"headers_json"`
|
||||
Proxy *string `json:"proxy"`
|
||||
VideoSelect *string `json:"video_select"`
|
||||
AudioSelect *string `json:"audio_select"`
|
||||
Rewriter *string `json:"rewriter"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
VariantsJSON *string `json:"variants_json"`
|
||||
Variants []VariantSpec `json:"variants"`
|
||||
Title *string `json:"title"`
|
||||
Description *string `json:"description"`
|
||||
Tags *string `json:"tags"`
|
||||
App *string `json:"app"`
|
||||
Channel *string `json:"channel"`
|
||||
MPD *string `json:"mpd"`
|
||||
Key *string `json:"key"`
|
||||
HeadersJSON *string `json:"headers_json"`
|
||||
Proxy *string `json:"proxy"`
|
||||
VideoSelect *string `json:"video_select"`
|
||||
AudioSelect *string `json:"audio_select"`
|
||||
Rewriter *string `json:"rewriter"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
VariantsJSON *string `json:"variants_json"`
|
||||
Variants []VariantSpec `json:"variants"`
|
||||
OutputsJSON *string `json:"outputs_json"`
|
||||
Outputs []OutputSpec `json:"outputs"`
|
||||
SettingsJSON *string `json:"settings_json"`
|
||||
DRMMode *string `json:"drm_mode"`
|
||||
OnDemand *bool `json:"on_demand"`
|
||||
IdleTimeoutS *int `json:"idle_timeout_s"`
|
||||
Public *bool `json:"public"`
|
||||
}
|
||||
|
||||
type Credentials struct {
|
||||
|
|
@ -156,10 +216,30 @@ CREATE TABLE IF NOT EXISTS agent_claims (
|
|||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Older DBs created before proxy / variants existed.
|
||||
_, _ = s.DB.Exec(`ALTER TABLE streams ADD COLUMN proxy TEXT NOT NULL DEFAULT ''`)
|
||||
_, _ = s.DB.Exec(`ALTER TABLE streams ADD COLUMN variants_json TEXT NOT NULL DEFAULT ''`)
|
||||
return nil
|
||||
// Columns added after the original schema. SQLite has no "ADD COLUMN IF
|
||||
// NOT EXISTS", so these are best-effort and fail harmlessly when the
|
||||
// column is already there.
|
||||
for _, stmt := range []string{
|
||||
`ALTER TABLE streams ADD COLUMN proxy TEXT NOT NULL DEFAULT ''`,
|
||||
`ALTER TABLE streams ADD COLUMN variants_json TEXT NOT NULL DEFAULT ''`,
|
||||
`ALTER TABLE streams ADD COLUMN description TEXT NOT NULL DEFAULT ''`,
|
||||
`ALTER TABLE streams ADD COLUMN tags TEXT NOT NULL DEFAULT ''`,
|
||||
`ALTER TABLE streams ADD COLUMN outputs_json TEXT NOT NULL DEFAULT ''`,
|
||||
`ALTER TABLE streams ADD COLUMN settings_json TEXT NOT NULL DEFAULT ''`,
|
||||
`ALTER TABLE streams ADD COLUMN drm_mode TEXT NOT NULL DEFAULT 'auto'`,
|
||||
`ALTER TABLE streams ADD COLUMN on_demand INTEGER NOT NULL DEFAULT 0`,
|
||||
`ALTER TABLE streams ADD COLUMN idle_timeout_s INTEGER NOT NULL DEFAULT 300`,
|
||||
`ALTER TABLE streams ADD COLUMN public INTEGER NOT NULL DEFAULT 1`,
|
||||
} {
|
||||
_, _ = s.DB.Exec(stmt)
|
||||
}
|
||||
if err := s.migrateHistory(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := s.migrateSettings(); err != nil {
|
||||
return err
|
||||
}
|
||||
return s.migrateSchedules()
|
||||
}
|
||||
|
||||
func now() string {
|
||||
|
|
@ -185,9 +265,13 @@ func slug(name string) string {
|
|||
}
|
||||
|
||||
const streamSelect = `
|
||||
SELECT s.id, s.name, s.title, s.app, s.channel, s.mpd, s.key_kid_key, s.headers_json,
|
||||
SELECT s.id, s.name, s.title, COALESCE(s.description,''), COALESCE(s.tags,''),
|
||||
s.app, s.channel, s.mpd, s.key_kid_key, s.headers_json,
|
||||
COALESCE(s.proxy,''), s.video_select, s.audio_select, s.enabled, s.rewriter,
|
||||
COALESCE(s.variants_json,''), s.created_at, s.updated_at,
|
||||
COALESCE(s.variants_json,''), COALESCE(s.outputs_json,''), COALESCE(s.settings_json,''),
|
||||
COALESCE(s.drm_mode,'auto'), COALESCE(s.on_demand,0),
|
||||
COALESCE(s.idle_timeout_s,300), COALESCE(s.public,1),
|
||||
s.created_at, s.updated_at,
|
||||
COALESCE(r.health,''), COALESCE(r.pid,0), COALESCE(r.play_path,''),
|
||||
COALESCE(r.uptime_s,0), COALESCE(r.bitrate_mbps,0), COALESCE(r.playlist_age_s,0),
|
||||
COALESCE(r.last_error,''), COALESCE(r.updated_at,''),
|
||||
|
|
@ -218,16 +302,25 @@ func (s *Store) GetStream(id int64) (Stream, error) {
|
|||
return scanStream(row)
|
||||
}
|
||||
|
||||
// GetStreamByName resolves a stream by its slug name, used by the HLS gate.
|
||||
func (s *Store) GetStreamByName(name string) (Stream, error) {
|
||||
row := s.DB.QueryRow(streamSelect+` WHERE s.name = ?`, name)
|
||||
return scanStream(row)
|
||||
}
|
||||
|
||||
type rowScanner interface {
|
||||
Scan(dest ...any) error
|
||||
}
|
||||
|
||||
func scanStream(row rowScanner) (Stream, error) {
|
||||
var st Stream
|
||||
var enabled int
|
||||
var enabled, onDemand, public int
|
||||
err := row.Scan(
|
||||
&st.ID, &st.Name, &st.Title, &st.App, &st.Channel, &st.MPD, &st.Key, &st.HeadersJSON,
|
||||
&st.Proxy, &st.VideoSelect, &st.AudioSelect, &enabled, &st.Rewriter, &st.VariantsJSON,
|
||||
&st.ID, &st.Name, &st.Title, &st.Description, &st.Tags,
|
||||
&st.App, &st.Channel, &st.MPD, &st.Key, &st.HeadersJSON,
|
||||
&st.Proxy, &st.VideoSelect, &st.AudioSelect, &enabled, &st.Rewriter,
|
||||
&st.VariantsJSON, &st.OutputsJSON, &st.SettingsJSON,
|
||||
&st.DRMMode, &onDemand, &st.IdleTimeoutS, &public,
|
||||
&st.CreatedAt, &st.UpdatedAt,
|
||||
&st.Health, &st.PID, &st.PlayPath, &st.UptimeS, &st.BitrateMbps, &st.PlaylistAgeS,
|
||||
&st.LastError, &st.RuntimeAt, &st.ClaimedBy, &st.ClaimExp,
|
||||
|
|
@ -236,6 +329,11 @@ func scanStream(row rowScanner) (Stream, error) {
|
|||
return st, err
|
||||
}
|
||||
st.Enabled = enabled != 0
|
||||
st.OnDemand = onDemand != 0
|
||||
st.Public = public != 0
|
||||
if st.IdleTimeoutS <= 0 {
|
||||
st.IdleTimeoutS = DefaultIdleTimeoutS
|
||||
}
|
||||
if st.Health == "" {
|
||||
st.Health = "stopped"
|
||||
}
|
||||
|
|
@ -243,6 +341,7 @@ func scanStream(row rowScanner) (Stream, error) {
|
|||
st.PlayPath = "/hls/" + st.Name + "/index.m3u8"
|
||||
}
|
||||
st.Variants = AttachVariantStatuses(st.Name, st.VariantsJSON, st.Health, st.PlaylistAgeS)
|
||||
st.Outputs = AttachOutputStatuses(st.Name, st.OutputsJSON)
|
||||
// Hide expired claims in API responses (ExpireClaims cleans them shortly after).
|
||||
if st.ClaimExp != "" {
|
||||
if exp, e := time.Parse(time.RFC3339, st.ClaimExp); e == nil && !exp.After(time.Now().UTC()) {
|
||||
|
|
@ -250,9 +349,127 @@ func scanStream(row rowScanner) (Stream, error) {
|
|||
st.ClaimExp = ""
|
||||
}
|
||||
}
|
||||
st.fillDerived()
|
||||
return st, nil
|
||||
}
|
||||
|
||||
// fillDerived computes the non-secret flags clients use in place of the
|
||||
// credentials themselves.
|
||||
func (st *Stream) fillDerived() {
|
||||
st.HasKey = strings.TrimSpace(st.Key) != ""
|
||||
st.KeyValid = ValidKeyPairs(st.Key)
|
||||
hdr := strings.TrimSpace(st.HeadersJSON)
|
||||
st.HasHeaders = hdr != "" && hdr != "{}" && hdr != "null"
|
||||
st.HasProxy = strings.TrimSpace(st.Proxy) != ""
|
||||
switch strings.ToLower(strings.TrimSpace(st.DRMMode)) {
|
||||
case DRMYes:
|
||||
st.DRMRequired = true
|
||||
case DRMNo:
|
||||
st.DRMRequired = false
|
||||
default:
|
||||
// auto: a stream that holds a key is encrypted; one that never had a
|
||||
// key is assumed clear, matching streamd's support for clear content.
|
||||
st.DRMMode = DRMAuto
|
||||
st.DRMRequired = st.HasKey
|
||||
}
|
||||
st.NeedsCapture = st.computeNeedsCapture()
|
||||
}
|
||||
|
||||
// Redact removes credentials from a Stream destined for an API response.
|
||||
// The derived flags survive, so a caller can still tell that a key exists and
|
||||
// whether it parses, without being handed the key itself.
|
||||
func (st *Stream) Redact() {
|
||||
st.Key = ""
|
||||
st.HeadersJSON = ""
|
||||
st.Proxy = ""
|
||||
}
|
||||
|
||||
// Redacted returns a copy with credentials stripped.
|
||||
func (st Stream) Redacted() Stream {
|
||||
st.Redact()
|
||||
return st
|
||||
}
|
||||
|
||||
// bootstrapGraceS is how long a stream may sit in "starting" before we treat
|
||||
// it as needing fresh credentials. It matches the supervisor's own bootstrap
|
||||
// deadline: capturing sooner would restart a stream that is still coming up,
|
||||
// which is a slow restart loop.
|
||||
const bootstrapGraceS = 180
|
||||
|
||||
// computeNeedsCapture reports whether an enabled stream looks down or is
|
||||
// missing the credentials it needs.
|
||||
func (st Stream) computeNeedsCapture() bool {
|
||||
if !st.Enabled {
|
||||
return false
|
||||
}
|
||||
// No manifest at all: only a capture can supply one.
|
||||
if strings.TrimSpace(st.MPD) == "" {
|
||||
return true
|
||||
}
|
||||
// Encrypted streams need usable keys. Clear streams do not, which is why
|
||||
// this is gated on DRMRequired rather than on the key being empty.
|
||||
if st.DRMRequired && !st.KeyValid {
|
||||
return true
|
||||
}
|
||||
// An on-demand stream that is deliberately idle is not broken. Its
|
||||
// credentials are refreshed when a viewer wakes it.
|
||||
if st.OnDemand && (st.Health == "stopped" || st.Health == "") {
|
||||
return false
|
||||
}
|
||||
switch st.Health {
|
||||
case "down", "stopped", "":
|
||||
return true
|
||||
case "starting":
|
||||
// Give the supervisor its bootstrap window before interfering.
|
||||
return st.UptimeS > bootstrapGraceS
|
||||
}
|
||||
return st.PlaylistAgeS > 30
|
||||
}
|
||||
|
||||
// ValidKeyPairs reports whether raw holds at least one KID:KEY pair and every
|
||||
// pair present is a 32-hex:32-hex pair. Separators may be newlines, commas or
|
||||
// semicolons, matching what the supervisor writes to NRE's key file — a
|
||||
// multi-KID stream is valid, which a single-pair check would wrongly reject.
|
||||
func ValidKeyPairs(raw string) bool {
|
||||
lines := SplitKeyLines(raw)
|
||||
if len(lines) == 0 {
|
||||
return false
|
||||
}
|
||||
for _, line := range lines {
|
||||
kid, key, ok := strings.Cut(line, ":")
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
if len(hexOnly(kid)) != 32 || len(hexOnly(key)) != 32 {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// SplitKeyLines normalises a key field into one KID:KEY entry per line.
|
||||
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()
|
||||
}
|
||||
|
||||
// AttachVariantStatuses builds the variants array for API responses.
|
||||
// Source (FHD) inherits the stream health; scaled variants stay "configured"
|
||||
// until the supervisor refreshes them via EnrichVariantHealth.
|
||||
|
|
@ -266,7 +483,7 @@ func AttachVariantStatuses(streamName, variantsJSON, streamHealth string, playli
|
|||
}
|
||||
if !v.Enabled {
|
||||
vs.Health = "off"
|
||||
} else if v.Height <= 0 {
|
||||
} else if v.Height <= 0 && !v.AudioOnly {
|
||||
vs.Health = streamHealth
|
||||
vs.PlaylistAgeS = playlistAge
|
||||
} else {
|
||||
|
|
@ -277,6 +494,17 @@ func AttachVariantStatuses(streamName, variantsJSON, streamHealth string, playli
|
|||
return out
|
||||
}
|
||||
|
||||
func normalizeDRMMode(s string) string {
|
||||
switch strings.ToLower(strings.TrimSpace(s)) {
|
||||
case DRMYes:
|
||||
return DRMYes
|
||||
case DRMNo:
|
||||
return DRMNo
|
||||
default:
|
||||
return DRMAuto
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Store) CreateStream(in CreateStream) (Stream, error) {
|
||||
name := slug(in.Name)
|
||||
if name == "" {
|
||||
|
|
@ -288,38 +516,55 @@ func (s *Store) CreateStream(in CreateStream) (Stream, error) {
|
|||
if !json.Valid([]byte(in.HeadersJSON)) {
|
||||
return Stream{}, fmt.Errorf("headers_json must be valid JSON")
|
||||
}
|
||||
// Installation-wide defaults for on_demand / idle / outputs when the
|
||||
// caller left those fields unset. Explicit body values still win.
|
||||
s.ApplyCreateDefaults(&in)
|
||||
// video_select / audio_select / rewriter are left empty on purpose: the
|
||||
// supervisor resolves them from the stream's app module at start time, so no
|
||||
// provider's preferences are baked into the schema.
|
||||
if in.Title == "" {
|
||||
in.Title = name
|
||||
}
|
||||
variantsJSON := strings.TrimSpace(in.VariantsJSON)
|
||||
if len(in.Variants) > 0 {
|
||||
encoded, err := EncodeVariantsJSON(in.Variants)
|
||||
if err != nil {
|
||||
return Stream{}, err
|
||||
}
|
||||
variantsJSON = encoded
|
||||
} else if variantsJSON == "" {
|
||||
variantsJSON, _ = EncodeVariantsJSON(DefaultVariants())
|
||||
} else {
|
||||
encoded, err := EncodeVariantsJSON(ParseVariantsJSON(variantsJSON))
|
||||
if err != nil {
|
||||
return Stream{}, err
|
||||
}
|
||||
variantsJSON = encoded
|
||||
variantsJSON, err := resolveVariantsJSON(in.VariantsJSON, in.Variants, true)
|
||||
if err != nil {
|
||||
return Stream{}, err
|
||||
}
|
||||
outputsJSON, err := resolveOutputsJSON(in.OutputsJSON, in.Outputs, true)
|
||||
if err != nil {
|
||||
return Stream{}, err
|
||||
}
|
||||
settingsJSON := strings.TrimSpace(in.SettingsJSON)
|
||||
if settingsJSON != "" && !json.Valid([]byte(settingsJSON)) {
|
||||
return Stream{}, fmt.Errorf("settings_json must be valid JSON")
|
||||
}
|
||||
enabled := 0
|
||||
if in.Enabled != nil && *in.Enabled {
|
||||
enabled = 1
|
||||
}
|
||||
onDemand := 0
|
||||
if in.OnDemand != nil && *in.OnDemand {
|
||||
onDemand = 1
|
||||
}
|
||||
// Public by default: that is today's behaviour, and an on-demand stream
|
||||
// that nobody may fetch could never be woken.
|
||||
public := 1
|
||||
if in.Public != nil && !*in.Public {
|
||||
public = 0
|
||||
}
|
||||
idle := DefaultIdleTimeoutS
|
||||
if in.IdleTimeoutS != nil && *in.IdleTimeoutS > 0 {
|
||||
idle = *in.IdleTimeoutS
|
||||
}
|
||||
ts := now()
|
||||
res, err := s.DB.Exec(`
|
||||
INSERT INTO streams(name,title,app,channel,mpd,key_kid_key,headers_json,proxy,video_select,audio_select,enabled,rewriter,variants_json,created_at,updated_at)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
||||
name, in.Title, in.App, in.Channel, in.MPD, in.Key, in.HeadersJSON, strings.TrimSpace(in.Proxy),
|
||||
in.VideoSelect, in.AudioSelect, enabled, in.Rewriter, variantsJSON, ts, ts)
|
||||
INSERT INTO streams(name,title,description,tags,app,channel,mpd,key_kid_key,headers_json,proxy,
|
||||
video_select,audio_select,enabled,rewriter,variants_json,outputs_json,
|
||||
settings_json,drm_mode,on_demand,idle_timeout_s,public,created_at,updated_at)
|
||||
VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
||||
name, in.Title, strings.TrimSpace(in.Description), normalizeTags(in.Tags),
|
||||
in.App, in.Channel, in.MPD, in.Key, in.HeadersJSON, strings.TrimSpace(in.Proxy),
|
||||
in.VideoSelect, in.AudioSelect, enabled, in.Rewriter, variantsJSON, outputsJSON,
|
||||
settingsJSON, normalizeDRMMode(in.DRMMode), onDemand, idle, public, ts, ts)
|
||||
if err != nil {
|
||||
return Stream{}, err
|
||||
}
|
||||
|
|
@ -329,6 +574,51 @@ VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`,
|
|||
return s.GetStream(id)
|
||||
}
|
||||
|
||||
// resolveVariantsJSON normalises the ladder from either the typed list or the
|
||||
// raw JSON field. onCreate fills the default ladder when both are empty.
|
||||
func resolveVariantsJSON(raw string, list []VariantSpec, onCreate bool) (string, error) {
|
||||
if len(list) > 0 {
|
||||
return EncodeVariantsJSON(list)
|
||||
}
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
if onCreate {
|
||||
return EncodeVariantsJSON(DefaultVariants())
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
return EncodeVariantsJSON(ParseVariantsJSON(raw))
|
||||
}
|
||||
|
||||
func resolveOutputsJSON(raw string, list []OutputSpec, onCreate bool) (string, error) {
|
||||
if len(list) > 0 {
|
||||
return EncodeOutputsJSON(list)
|
||||
}
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
if onCreate {
|
||||
return EncodeOutputsJSON(DefaultOutputs())
|
||||
}
|
||||
return "", nil
|
||||
}
|
||||
return EncodeOutputsJSON(ParseOutputsJSON(raw))
|
||||
}
|
||||
|
||||
// normalizeTags lowercases and de-duplicates a comma-separated tag list.
|
||||
func normalizeTags(raw string) string {
|
||||
seen := map[string]bool{}
|
||||
var out []string
|
||||
for _, t := range strings.Split(raw, ",") {
|
||||
t = slug(t)
|
||||
if t == "" || seen[t] {
|
||||
continue
|
||||
}
|
||||
seen[t] = true
|
||||
out = append(out, t)
|
||||
}
|
||||
return strings.Join(out, ",")
|
||||
}
|
||||
|
||||
func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) {
|
||||
cur, err := s.GetStream(id)
|
||||
if err != nil {
|
||||
|
|
@ -337,6 +627,12 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) {
|
|||
if in.Title != nil {
|
||||
cur.Title = *in.Title
|
||||
}
|
||||
if in.Description != nil {
|
||||
cur.Description = strings.TrimSpace(*in.Description)
|
||||
}
|
||||
if in.Tags != nil {
|
||||
cur.Tags = normalizeTags(*in.Tags)
|
||||
}
|
||||
if in.App != nil {
|
||||
cur.App = *in.App
|
||||
}
|
||||
|
|
@ -367,18 +663,50 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) {
|
|||
if in.Rewriter != nil {
|
||||
cur.Rewriter = *in.Rewriter
|
||||
}
|
||||
if len(in.Variants) > 0 {
|
||||
encoded, err := EncodeVariantsJSON(in.Variants)
|
||||
if in.DRMMode != nil {
|
||||
cur.DRMMode = normalizeDRMMode(*in.DRMMode)
|
||||
}
|
||||
if in.OnDemand != nil {
|
||||
cur.OnDemand = *in.OnDemand
|
||||
}
|
||||
if in.Public != nil {
|
||||
cur.Public = *in.Public
|
||||
}
|
||||
if in.IdleTimeoutS != nil && *in.IdleTimeoutS > 0 {
|
||||
cur.IdleTimeoutS = *in.IdleTimeoutS
|
||||
}
|
||||
if in.SettingsJSON != nil {
|
||||
v := strings.TrimSpace(*in.SettingsJSON)
|
||||
if v != "" && !json.Valid([]byte(v)) {
|
||||
return Stream{}, fmt.Errorf("settings_json must be valid JSON")
|
||||
}
|
||||
cur.SettingsJSON = v
|
||||
}
|
||||
if len(in.Variants) > 0 || in.VariantsJSON != nil {
|
||||
raw := ""
|
||||
if in.VariantsJSON != nil {
|
||||
raw = *in.VariantsJSON
|
||||
}
|
||||
encoded, err := resolveVariantsJSON(raw, in.Variants, false)
|
||||
if err != nil {
|
||||
return Stream{}, err
|
||||
}
|
||||
cur.VariantsJSON = encoded
|
||||
} else if in.VariantsJSON != nil {
|
||||
encoded, err := EncodeVariantsJSON(ParseVariantsJSON(*in.VariantsJSON))
|
||||
if encoded != "" {
|
||||
cur.VariantsJSON = encoded
|
||||
}
|
||||
}
|
||||
if len(in.Outputs) > 0 || in.OutputsJSON != nil {
|
||||
raw := ""
|
||||
if in.OutputsJSON != nil {
|
||||
raw = *in.OutputsJSON
|
||||
}
|
||||
encoded, err := resolveOutputsJSON(raw, in.Outputs, false)
|
||||
if err != nil {
|
||||
return Stream{}, err
|
||||
}
|
||||
cur.VariantsJSON = encoded
|
||||
if encoded != "" {
|
||||
cur.OutputsJSON = encoded
|
||||
}
|
||||
}
|
||||
enabled := 0
|
||||
if cur.Enabled {
|
||||
|
|
@ -391,12 +719,24 @@ func (s *Store) PatchStream(id int64, in PatchStream) (Stream, error) {
|
|||
enabled = 0
|
||||
}
|
||||
}
|
||||
onDemand := 0
|
||||
if cur.OnDemand {
|
||||
onDemand = 1
|
||||
}
|
||||
public := 0
|
||||
if cur.Public {
|
||||
public = 1
|
||||
}
|
||||
ts := now()
|
||||
_, err = s.DB.Exec(`
|
||||
UPDATE streams SET title=?, app=?, channel=?, mpd=?, key_kid_key=?, headers_json=?, proxy=?,
|
||||
video_select=?, audio_select=?, enabled=?, rewriter=?, variants_json=?, updated_at=? WHERE id=?`,
|
||||
cur.Title, cur.App, cur.Channel, cur.MPD, cur.Key, cur.HeadersJSON, cur.Proxy,
|
||||
cur.VideoSelect, cur.AudioSelect, enabled, cur.Rewriter, cur.VariantsJSON, ts, id)
|
||||
UPDATE streams SET title=?, description=?, tags=?, app=?, channel=?, mpd=?, key_kid_key=?,
|
||||
headers_json=?, proxy=?, video_select=?, audio_select=?, enabled=?, rewriter=?,
|
||||
variants_json=?, outputs_json=?, settings_json=?, drm_mode=?, on_demand=?,
|
||||
idle_timeout_s=?, public=?, updated_at=? WHERE id=?`,
|
||||
cur.Title, cur.Description, cur.Tags, cur.App, cur.Channel, cur.MPD, cur.Key,
|
||||
cur.HeadersJSON, cur.Proxy, cur.VideoSelect, cur.AudioSelect, enabled, cur.Rewriter,
|
||||
cur.VariantsJSON, cur.OutputsJSON, cur.SettingsJSON, cur.DRMMode, onDemand,
|
||||
cur.IdleTimeoutS, public, ts, id)
|
||||
if err != nil {
|
||||
return Stream{}, err
|
||||
}
|
||||
|
|
@ -554,21 +894,3 @@ ON CONFLICT(stream_id) DO UPDATE SET
|
|||
id, p.Health, p.PID, play, p.UptimeS, p.BitrateMbps, p.PlaylistAgeS, p.LastError, now())
|
||||
return err
|
||||
}
|
||||
|
||||
// NeedsCapture reports whether an enabled stream looks down / missing creds.
|
||||
func (st Stream) NeedsCapture() bool {
|
||||
if !st.Enabled {
|
||||
return false
|
||||
}
|
||||
if strings.TrimSpace(st.MPD) == "" || strings.TrimSpace(st.Key) == "" {
|
||||
return true
|
||||
}
|
||||
switch st.Health {
|
||||
case "down", "stopped", "starting", "":
|
||||
return true
|
||||
}
|
||||
if st.PlaylistAgeS > 30 {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
|
|
|||
438
apps/streamd/internal/db/events.go
Normal file
438
apps/streamd/internal/db/events.go
Normal file
|
|
@ -0,0 +1,438 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Event kinds recorded against a stream. Together they are the stream's
|
||||
// timeline: who or what acted, and what the supervisor saw happen.
|
||||
const (
|
||||
EventCreated = "created"
|
||||
EventUpdated = "updated"
|
||||
EventDeleted = "deleted"
|
||||
EventStarted = "started"
|
||||
EventStopped = "stopped"
|
||||
EventRestarted = "restarted"
|
||||
EventCrashed = "crashed"
|
||||
EventFFRestart = "ff_restart"
|
||||
EventVariantUp = "variant_up"
|
||||
EventVariantDown = "variant_down"
|
||||
EventOnDemandWake = "ondemand_wake"
|
||||
EventIdleStop = "idle_stop"
|
||||
EventScheduledStart = "scheduled_start"
|
||||
EventScheduledStop = "scheduled_stop"
|
||||
EventCredsSet = "creds_set"
|
||||
EventClaimed = "claimed"
|
||||
EventReleased = "released"
|
||||
EventProbe = "probe"
|
||||
EventCaptureStarted = "capture_started"
|
||||
EventCaptureOK = "capture_ok"
|
||||
EventCaptureFailed = "capture_failed"
|
||||
)
|
||||
|
||||
// Severities.
|
||||
const (
|
||||
SevInfo = "info"
|
||||
SevWarn = "warn"
|
||||
SevError = "error"
|
||||
)
|
||||
|
||||
// ActorSystem is the actor for anything streamd did by itself.
|
||||
const ActorSystem = "system"
|
||||
|
||||
// StreamEvent is one entry on a stream's timeline.
|
||||
type StreamEvent struct {
|
||||
ID int64 `json:"id"`
|
||||
StreamID int64 `json:"stream_id"`
|
||||
StreamName string `json:"stream_name,omitempty"`
|
||||
At string `json:"at"`
|
||||
Kind string `json:"kind"`
|
||||
Severity string `json:"severity"`
|
||||
Actor string `json:"actor"`
|
||||
Message string `json:"message"`
|
||||
// Detail is raw JSON, passed through to the client as-is.
|
||||
Detail json.RawMessage `json:"detail,omitempty"`
|
||||
}
|
||||
|
||||
// MetricPoint is one health sample for a stream.
|
||||
type MetricPoint struct {
|
||||
At string `json:"at"`
|
||||
Health string `json:"health"`
|
||||
BitrateMbps float64 `json:"bitrate_mbps"`
|
||||
PlaylistAgeS float64 `json:"playlist_age_s"`
|
||||
Viewers int `json:"viewers"`
|
||||
// Bucket is 0 for a raw sample and the rollup width in seconds for an
|
||||
// aggregate (60 for the one-minute rollups kept beyond the raw window).
|
||||
Bucket int `json:"bucket,omitempty"`
|
||||
}
|
||||
|
||||
// Retention windows.
|
||||
const (
|
||||
// RawMetricWindow is how long per-tick samples are kept before being
|
||||
// rolled up into one-minute averages.
|
||||
RawMetricWindow = time.Hour
|
||||
// RollupRetention is how long the one-minute rollups are kept.
|
||||
RollupRetention = 7 * 24 * time.Hour
|
||||
// EventRetention is how long a stream's timeline is kept.
|
||||
EventRetention = 90 * 24 * time.Hour
|
||||
rollupBucketS = 60
|
||||
)
|
||||
|
||||
// history holds the buffered event and metric writes. The store runs on a
|
||||
// single database connection shared with every stream write, so neither a
|
||||
// 5-second metric tick nor a crash loop may write per occurrence.
|
||||
type history struct {
|
||||
mu sync.Mutex
|
||||
events []StreamEvent
|
||||
metrics []bufferedMetric
|
||||
}
|
||||
|
||||
type bufferedMetric struct {
|
||||
streamID int64
|
||||
point MetricPoint
|
||||
}
|
||||
|
||||
const maxHistoryBuffer = 20_000
|
||||
|
||||
func (s *Store) migrateHistory() error {
|
||||
_, err := s.DB.Exec(`
|
||||
CREATE TABLE IF NOT EXISTS stream_events (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
stream_id INTEGER NOT NULL REFERENCES streams(id) ON DELETE CASCADE,
|
||||
at TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
severity TEXT NOT NULL DEFAULT 'info',
|
||||
actor TEXT NOT NULL DEFAULT '',
|
||||
message TEXT NOT NULL DEFAULT '',
|
||||
detail_json TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_events_stream_at ON stream_events(stream_id, id DESC);
|
||||
CREATE INDEX IF NOT EXISTS idx_events_at ON stream_events(at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS stream_metrics (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
stream_id INTEGER NOT NULL REFERENCES streams(id) ON DELETE CASCADE,
|
||||
at TEXT NOT NULL,
|
||||
health TEXT NOT NULL DEFAULT '',
|
||||
bitrate_mbps REAL NOT NULL DEFAULT 0,
|
||||
playlist_age_s REAL NOT NULL DEFAULT 0,
|
||||
viewers INTEGER NOT NULL DEFAULT 0,
|
||||
bucket INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_metrics_stream_at ON stream_metrics(stream_id, at);
|
||||
`)
|
||||
return err
|
||||
}
|
||||
|
||||
// AddEvent buffers one timeline entry.
|
||||
func (s *Store) AddEvent(e StreamEvent) {
|
||||
if e.StreamID == 0 || e.Kind == "" {
|
||||
return
|
||||
}
|
||||
if e.At == "" {
|
||||
e.At = now()
|
||||
}
|
||||
if e.Severity == "" {
|
||||
e.Severity = SevInfo
|
||||
}
|
||||
if e.Actor == "" {
|
||||
e.Actor = ActorSystem
|
||||
}
|
||||
e.Message = truncateStr(e.Message, 2000)
|
||||
s.hist.mu.Lock()
|
||||
defer s.hist.mu.Unlock()
|
||||
if len(s.hist.events) >= maxHistoryBuffer {
|
||||
s.hist.events = s.hist.events[1:]
|
||||
}
|
||||
s.hist.events = append(s.hist.events, e)
|
||||
}
|
||||
|
||||
// Eventf is the common case: a system event with a formatted message.
|
||||
func (s *Store) Eventf(streamID int64, kind, severity, format string, args ...any) {
|
||||
s.AddEvent(StreamEvent{
|
||||
StreamID: streamID,
|
||||
Kind: kind,
|
||||
Severity: severity,
|
||||
Actor: ActorSystem,
|
||||
Message: fmt.Sprintf(format, args...),
|
||||
})
|
||||
}
|
||||
|
||||
// AddMetric buffers one health sample.
|
||||
func (s *Store) AddMetric(streamID int64, p MetricPoint) {
|
||||
if streamID == 0 {
|
||||
return
|
||||
}
|
||||
if p.At == "" {
|
||||
p.At = now()
|
||||
}
|
||||
s.hist.mu.Lock()
|
||||
defer s.hist.mu.Unlock()
|
||||
if len(s.hist.metrics) >= maxHistoryBuffer {
|
||||
s.hist.metrics = s.hist.metrics[1:]
|
||||
}
|
||||
s.hist.metrics = append(s.hist.metrics, bufferedMetric{streamID: streamID, point: p})
|
||||
}
|
||||
|
||||
// FlushHistory writes buffered events and metrics in one transaction.
|
||||
func (s *Store) FlushHistory() error {
|
||||
s.hist.mu.Lock()
|
||||
events := s.hist.events
|
||||
metrics := s.hist.metrics
|
||||
s.hist.events = nil
|
||||
s.hist.metrics = nil
|
||||
s.hist.mu.Unlock()
|
||||
|
||||
if len(events) == 0 && len(metrics) == 0 {
|
||||
return nil
|
||||
}
|
||||
requeue := func() {
|
||||
s.hist.mu.Lock()
|
||||
s.hist.events = append(events, s.hist.events...)
|
||||
s.hist.metrics = append(metrics, s.hist.metrics...)
|
||||
if len(s.hist.events) > maxHistoryBuffer {
|
||||
s.hist.events = s.hist.events[len(s.hist.events)-maxHistoryBuffer:]
|
||||
}
|
||||
if len(s.hist.metrics) > maxHistoryBuffer {
|
||||
s.hist.metrics = s.hist.metrics[len(s.hist.metrics)-maxHistoryBuffer:]
|
||||
}
|
||||
s.hist.mu.Unlock()
|
||||
}
|
||||
|
||||
tx, err := s.DB.Begin()
|
||||
if err != nil {
|
||||
requeue()
|
||||
return err
|
||||
}
|
||||
if len(events) > 0 {
|
||||
stmt, err := tx.Prepare(`
|
||||
INSERT INTO stream_events(stream_id,at,kind,severity,actor,message,detail_json)
|
||||
VALUES(?,?,?,?,?,?,?)`)
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
requeue()
|
||||
return err
|
||||
}
|
||||
for _, e := range events {
|
||||
// A stream deleted between buffering and flushing takes its
|
||||
// events with it; the foreign key makes that insert fail, which
|
||||
// must not abort the whole batch.
|
||||
_, _ = stmt.Exec(e.StreamID, e.At, e.Kind, e.Severity, e.Actor, e.Message, string(e.Detail))
|
||||
}
|
||||
_ = stmt.Close()
|
||||
}
|
||||
if len(metrics) > 0 {
|
||||
stmt, err := tx.Prepare(`
|
||||
INSERT INTO stream_metrics(stream_id,at,health,bitrate_mbps,playlist_age_s,viewers,bucket)
|
||||
VALUES(?,?,?,?,?,?,?)`)
|
||||
if err != nil {
|
||||
_ = tx.Rollback()
|
||||
requeue()
|
||||
return err
|
||||
}
|
||||
for _, m := range metrics {
|
||||
_, _ = stmt.Exec(m.streamID, m.point.At, m.point.Health,
|
||||
m.point.BitrateMbps, m.point.PlaylistAgeS, m.point.Viewers, m.point.Bucket)
|
||||
}
|
||||
_ = stmt.Close()
|
||||
}
|
||||
if err := tx.Commit(); err != nil {
|
||||
requeue()
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListEvents returns a stream's timeline, newest first.
|
||||
func (s *Store) ListEvents(streamID int64, limit int, kind, since string) ([]StreamEvent, error) {
|
||||
if limit <= 0 || limit > 1000 {
|
||||
limit = 200
|
||||
}
|
||||
q := `SELECT id,stream_id,at,kind,severity,actor,message,detail_json
|
||||
FROM stream_events WHERE stream_id = ?`
|
||||
args := []any{streamID}
|
||||
if k := strings.TrimSpace(kind); k != "" {
|
||||
// Accept a comma-separated kind filter.
|
||||
kinds := strings.Split(k, ",")
|
||||
ph := make([]string, 0, len(kinds))
|
||||
for _, one := range kinds {
|
||||
if one = strings.TrimSpace(one); one != "" {
|
||||
ph = append(ph, "?")
|
||||
args = append(args, one)
|
||||
}
|
||||
}
|
||||
if len(ph) > 0 {
|
||||
q += ` AND kind IN (` + strings.Join(ph, ",") + `)`
|
||||
}
|
||||
}
|
||||
if sv := strings.TrimSpace(since); sv != "" {
|
||||
q += ` AND at >= ?`
|
||||
args = append(args, sv)
|
||||
}
|
||||
q += ` ORDER BY id DESC LIMIT ?`
|
||||
args = append(args, limit)
|
||||
return s.queryEvents(q, args...)
|
||||
}
|
||||
|
||||
// RecentEvents returns the newest events across every stream, for the
|
||||
// dashboard's activity feed.
|
||||
func (s *Store) RecentEvents(limit int) ([]StreamEvent, error) {
|
||||
if limit <= 0 || limit > 500 {
|
||||
limit = 50
|
||||
}
|
||||
return s.queryEvents(`
|
||||
SELECT e.id, e.stream_id, e.at, e.kind, e.severity, e.actor, e.message, e.detail_json, s.name
|
||||
FROM stream_events e LEFT JOIN streams s ON s.id = e.stream_id
|
||||
ORDER BY e.id DESC LIMIT ?`, limit)
|
||||
}
|
||||
|
||||
func (s *Store) queryEvents(q string, args ...any) ([]StreamEvent, error) {
|
||||
rows, err := s.DB.Query(q, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
cols, err := rows.Columns()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
withName := len(cols) > 8
|
||||
out := []StreamEvent{}
|
||||
for rows.Next() {
|
||||
var e StreamEvent
|
||||
var detail string
|
||||
var name *string
|
||||
dest := []any{&e.ID, &e.StreamID, &e.At, &e.Kind, &e.Severity, &e.Actor, &e.Message, &detail}
|
||||
if withName {
|
||||
dest = append(dest, &name)
|
||||
}
|
||||
if err := rows.Scan(dest...); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if detail != "" && json.Valid([]byte(detail)) {
|
||||
e.Detail = json.RawMessage(detail)
|
||||
}
|
||||
if name != nil {
|
||||
e.StreamName = *name
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// ListMetrics returns samples for a stream within the window, oldest first.
|
||||
func (s *Store) ListMetrics(streamID int64, window time.Duration) ([]MetricPoint, error) {
|
||||
if window <= 0 {
|
||||
window = time.Hour
|
||||
}
|
||||
cutoff := time.Now().UTC().Add(-window).Format(time.RFC3339)
|
||||
rows, err := s.DB.Query(`
|
||||
SELECT at,health,bitrate_mbps,playlist_age_s,viewers,bucket
|
||||
FROM stream_metrics WHERE stream_id = ? AND at >= ?
|
||||
ORDER BY at ASC`, streamID, cutoff)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []MetricPoint{}
|
||||
for rows.Next() {
|
||||
var p MetricPoint
|
||||
if err := rows.Scan(&p.At, &p.Health, &p.BitrateMbps, &p.PlaylistAgeS, &p.Viewers, &p.Bucket); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// UptimeRatio is the fraction of samples in the window where the stream was
|
||||
// healthy. Returns -1 when there is nothing to judge from.
|
||||
func (s *Store) UptimeRatio(streamID int64, window time.Duration) (float64, error) {
|
||||
if window <= 0 {
|
||||
window = 24 * time.Hour
|
||||
}
|
||||
cutoff := time.Now().UTC().Add(-window).Format(time.RFC3339)
|
||||
var total, ok int
|
||||
err := s.DB.QueryRow(`
|
||||
SELECT COUNT(*), COALESCE(SUM(CASE WHEN health = 'ok' THEN 1 ELSE 0 END),0)
|
||||
FROM stream_metrics WHERE stream_id = ? AND at >= ?`, streamID, cutoff).Scan(&total, &ok)
|
||||
if err != nil {
|
||||
return -1, err
|
||||
}
|
||||
if total == 0 {
|
||||
return -1, nil
|
||||
}
|
||||
return float64(ok) / float64(total), nil
|
||||
}
|
||||
|
||||
// RollupMetrics collapses raw samples older than RawMetricWindow into
|
||||
// one-minute averages, then drops rollups and events past their retention.
|
||||
// Keeping every 5-second sample for a week would be millions of rows per
|
||||
// stream for no benefit at that zoom level.
|
||||
func (s *Store) RollupMetrics() error {
|
||||
rawCutoff := time.Now().UTC().Add(-RawMetricWindow).Format(time.RFC3339)
|
||||
tx, err := s.DB.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// SQLite has no date_trunc, but the timestamps are fixed-width RFC3339
|
||||
// (…THH:MM:SSZ), so truncating to the minute is a substring.
|
||||
if _, err := tx.Exec(`
|
||||
INSERT INTO stream_metrics(stream_id,at,health,bitrate_mbps,playlist_age_s,viewers,bucket)
|
||||
SELECT stream_id,
|
||||
substr(at, 1, 17) || '00Z',
|
||||
-- the worst health in the minute, so an outage is never averaged away
|
||||
CASE WHEN SUM(CASE WHEN health <> 'ok' THEN 1 ELSE 0 END) > 0 THEN 'degraded' ELSE 'ok' END,
|
||||
AVG(bitrate_mbps), AVG(playlist_age_s), MAX(viewers), ?
|
||||
FROM stream_metrics
|
||||
WHERE bucket = 0 AND at < ?
|
||||
GROUP BY stream_id, substr(at, 1, 17)`, rollupBucketS, rawCutoff); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(`DELETE FROM stream_metrics WHERE bucket = 0 AND at < ?`, rawCutoff); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
rollupCutoff := time.Now().UTC().Add(-RollupRetention).Format(time.RFC3339)
|
||||
if _, err := tx.Exec(`DELETE FROM stream_metrics WHERE at < ?`, rollupCutoff); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
eventCutoff := time.Now().UTC().Add(-EventRetention).Format(time.RFC3339)
|
||||
if _, err := tx.Exec(`DELETE FROM stream_events WHERE at < ?`, eventCutoff); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// RunHistoryMaintenance flushes buffered history and prunes on a schedule.
|
||||
func (s *Store) RunHistoryMaintenance(stop <-chan struct{}) {
|
||||
flush := time.NewTicker(5 * time.Second)
|
||||
defer flush.Stop()
|
||||
prune := time.NewTicker(15 * time.Minute)
|
||||
defer prune.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-stop:
|
||||
_ = s.FlushHistory()
|
||||
return
|
||||
case <-flush.C:
|
||||
_ = s.FlushHistory()
|
||||
case <-prune.C:
|
||||
_ = s.RollupMetrics()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func truncateStr(s string, n int) string {
|
||||
if len(s) <= n {
|
||||
return s
|
||||
}
|
||||
return s[:n]
|
||||
}
|
||||
285
apps/streamd/internal/db/outputs.go
Normal file
285
apps/streamd/internal/db/outputs.go
Normal file
|
|
@ -0,0 +1,285 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Output formats. These are the muxers the packager can be asked to emit for
|
||||
// each enabled variant. They are orthogonal to the resolution ladder: the set
|
||||
// actually published is variants x outputs.
|
||||
const (
|
||||
// FormatHLS is mpegts HLS — the original and only output, kept as the
|
||||
// default so an upgraded install publishes exactly what it did before.
|
||||
FormatHLS = "hls"
|
||||
// FormatCMAF is fMP4/CMAF HLS: init.mp4 plus .m4s segments.
|
||||
FormatCMAF = "hls_fmp4"
|
||||
// FormatDASH is MPEG-DASH.
|
||||
FormatDASH = "dash"
|
||||
// FormatTS is a progressive, endless MPEG-TS stream served from a shared
|
||||
// ring buffer rather than from disk.
|
||||
FormatTS = "mpegts"
|
||||
)
|
||||
|
||||
// OutputSpec is one configured output format for a stream.
|
||||
type OutputSpec struct {
|
||||
ID string `json:"id"`
|
||||
Label string `json:"label"`
|
||||
Format string `json:"format"`
|
||||
Enabled bool `json:"enabled"`
|
||||
// SegmentDuration and ListSize override the stream's packager settings for
|
||||
// this output only. Zero means "inherit".
|
||||
SegmentDuration int `json:"segment_duration,omitempty"`
|
||||
ListSize int `json:"list_size,omitempty"`
|
||||
}
|
||||
|
||||
// OutputStatus is an OutputSpec as reported by the API.
|
||||
type OutputStatus struct {
|
||||
OutputSpec
|
||||
}
|
||||
|
||||
// PublishLink is one playable endpoint: a variant crossed with an output
|
||||
// format, or the ABR master playlist. The dashboard renders one row per link.
|
||||
type PublishLink struct {
|
||||
VariantID string `json:"variant_id"`
|
||||
VariantLabel string `json:"variant_label"`
|
||||
OutputID string `json:"output_id"`
|
||||
OutputLabel string `json:"output_label"`
|
||||
Format string `json:"format"`
|
||||
PlayPath string `json:"play_path"`
|
||||
Health string `json:"health,omitempty"`
|
||||
PlaylistAgeS float64 `json:"playlist_age_s,omitempty"`
|
||||
// Master marks the ABR master playlist, which spans every variant.
|
||||
Master bool `json:"master,omitempty"`
|
||||
}
|
||||
|
||||
// DefaultOutputs is the output set for a new stream: mpegts HLS only. The
|
||||
// other formats exist but stay off, so turning one on is always a deliberate
|
||||
// act and an upgraded install does not silently start transcoding more.
|
||||
func DefaultOutputs() []OutputSpec {
|
||||
return []OutputSpec{
|
||||
{ID: "hls", Label: "HLS", Format: FormatHLS, Enabled: true},
|
||||
{ID: "cmaf", Label: "CMAF", Format: FormatCMAF, Enabled: false},
|
||||
{ID: "dash", Label: "DASH", Format: FormatDASH, Enabled: false},
|
||||
{ID: "ts", Label: "TS", Format: FormatTS, Enabled: false},
|
||||
}
|
||||
}
|
||||
|
||||
// knownFormats maps a format to its default id and label.
|
||||
var knownFormats = map[string]struct{ id, label, container string }{
|
||||
FormatHLS: {"hls", "HLS", "mpegts"},
|
||||
FormatCMAF: {"cmaf", "CMAF", "fmp4"},
|
||||
FormatDASH: {"dash", "DASH", "fmp4"},
|
||||
FormatTS: {"ts", "TS", "mpegts"},
|
||||
}
|
||||
|
||||
// normalizeFormat maps user input onto a known format, tolerating the shorter
|
||||
// aliases the UI and API are likely to send.
|
||||
func normalizeFormat(f string) string {
|
||||
switch strings.ToLower(strings.TrimSpace(f)) {
|
||||
case FormatHLS, "m3u8", "hls_mpegts", "hls-ts":
|
||||
return FormatHLS
|
||||
case FormatCMAF, "cmaf", "fmp4", "hls-fmp4":
|
||||
return FormatCMAF
|
||||
case FormatDASH, "mpd":
|
||||
return FormatDASH
|
||||
case FormatTS, "ts", "progressive":
|
||||
return FormatTS
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// ParseOutputsJSON reads outputs_json. Empty or unparseable falls back to the
|
||||
// defaults, matching how the variant ladder behaves.
|
||||
func ParseOutputsJSON(raw string) []OutputSpec {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" || raw == "[]" || raw == "null" {
|
||||
return DefaultOutputs()
|
||||
}
|
||||
var list []OutputSpec
|
||||
if err := json.Unmarshal([]byte(raw), &list); err != nil || len(list) == 0 {
|
||||
return DefaultOutputs()
|
||||
}
|
||||
return NormalizeOutputs(list)
|
||||
}
|
||||
|
||||
// NormalizeOutputs fills ids and labels, drops unknown formats, de-duplicates
|
||||
// by format, and guarantees every known format has an entry so a client can
|
||||
// toggle one without having to know the full list.
|
||||
func NormalizeOutputs(in []OutputSpec) []OutputSpec {
|
||||
byFormat := map[string]OutputSpec{}
|
||||
for _, o := range in {
|
||||
f := normalizeFormat(o.Format)
|
||||
if f == "" {
|
||||
// Allow a client to identify an output by id alone.
|
||||
f = normalizeFormat(o.ID)
|
||||
}
|
||||
if f == "" {
|
||||
continue
|
||||
}
|
||||
meta := knownFormats[f]
|
||||
o.Format = f
|
||||
if o.ID = slug(o.ID); o.ID == "" {
|
||||
o.ID = meta.id
|
||||
}
|
||||
if strings.TrimSpace(o.Label) == "" {
|
||||
o.Label = meta.label
|
||||
}
|
||||
if o.SegmentDuration < 0 {
|
||||
o.SegmentDuration = 0
|
||||
}
|
||||
if o.ListSize < 0 {
|
||||
o.ListSize = 0
|
||||
}
|
||||
// A later entry for the same format wins, so a partial patch applies
|
||||
// cleanly over the defaults.
|
||||
byFormat[f] = o
|
||||
}
|
||||
out := make([]OutputSpec, 0, len(knownFormats))
|
||||
for _, def := range DefaultOutputs() {
|
||||
if got, ok := byFormat[def.Format]; ok {
|
||||
out = append(out, got)
|
||||
continue
|
||||
}
|
||||
out = append(out, def)
|
||||
}
|
||||
// An output set with nothing enabled would publish nothing at all and
|
||||
// leave the stream unreachable; fall back to HLS.
|
||||
anyOn := false
|
||||
for _, o := range out {
|
||||
if o.Enabled {
|
||||
anyOn = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !anyOn {
|
||||
for i := range out {
|
||||
if out[i].Format == FormatHLS {
|
||||
out[i].Enabled = true
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func EncodeOutputsJSON(list []OutputSpec) (string, error) {
|
||||
list = NormalizeOutputs(list)
|
||||
b, err := json.Marshal(list)
|
||||
if err != nil {
|
||||
return "[]", err
|
||||
}
|
||||
return string(b), nil
|
||||
}
|
||||
|
||||
// EnabledOutputs returns the outputs that should be muxed.
|
||||
func EnabledOutputs(list []OutputSpec) []OutputSpec {
|
||||
var out []OutputSpec
|
||||
for _, o := range list {
|
||||
if o.Enabled {
|
||||
out = append(out, o)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// AttachOutputStatuses builds the outputs array for API responses.
|
||||
func AttachOutputStatuses(streamName, outputsJSON string) []OutputStatus {
|
||||
specs := ParseOutputsJSON(outputsJSON)
|
||||
out := make([]OutputStatus, 0, len(specs))
|
||||
for _, o := range specs {
|
||||
out = append(out, OutputStatus{OutputSpec: o})
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// VariantDir is the www subdirectory for one variant: the stream name for the
|
||||
// source rung, and "<name>-<id>" for every other rung. This is the single
|
||||
// definition of that layout; the HLS gate parses it back.
|
||||
func VariantDir(streamName, variantID string, height int, audioOnly bool) string {
|
||||
variantID = slug(variantID)
|
||||
if !audioOnly && (height <= 0 || variantID == "" || variantID == SourceVariantID) {
|
||||
return streamName
|
||||
}
|
||||
return streamName + "-" + variantID
|
||||
}
|
||||
|
||||
// OutputSubPath is the path of an output's playlist relative to its variant
|
||||
// directory. The mpegts HLS playlist stays at the root of the directory so
|
||||
// existing /hls/<name>/index.m3u8 URLs never move.
|
||||
func OutputSubPath(format string) string {
|
||||
switch normalizeFormat(format) {
|
||||
case FormatHLS:
|
||||
return "index.m3u8"
|
||||
case FormatCMAF:
|
||||
return "cmaf/index.m3u8"
|
||||
case FormatDASH:
|
||||
return "dash/index.mpd"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// OutputPlayPath is the URL for one variant x output pair. Progressive TS is
|
||||
// served from /live/ because it is a live pipe, not a file on disk.
|
||||
func OutputPlayPath(streamName, variantID string, height int, audioOnly bool, format string) string {
|
||||
dir := VariantDir(streamName, variantID, height, audioOnly)
|
||||
if normalizeFormat(format) == FormatTS {
|
||||
return "/live/" + dir + ".ts"
|
||||
}
|
||||
sub := OutputSubPath(format)
|
||||
if sub == "" {
|
||||
return ""
|
||||
}
|
||||
return "/hls/" + dir + "/" + sub
|
||||
}
|
||||
|
||||
// MasterPlayPath is the ABR master playlist spanning every enabled variant.
|
||||
func MasterPlayPath(streamName string) string {
|
||||
return "/hls/" + streamName + "/master.m3u8"
|
||||
}
|
||||
|
||||
// BuildPublishLinks is the cross product of enabled variants and enabled
|
||||
// outputs, with the ABR master first when there is more than one rung to
|
||||
// choose between. Health is left empty here and filled by the API layer, which
|
||||
// is the part that can see the files on disk.
|
||||
func BuildPublishLinks(streamName, variantsJSON, outputsJSON string) []PublishLink {
|
||||
variants := EnabledVariants(ParseVariantsJSON(variantsJSON))
|
||||
outputs := EnabledOutputs(ParseOutputsJSON(outputsJSON))
|
||||
links := make([]PublishLink, 0, len(variants)*len(outputs)+1)
|
||||
|
||||
// The master is only meaningful when HLS is on and there is a real choice.
|
||||
hlsOn := false
|
||||
for _, o := range outputs {
|
||||
if o.Format == FormatHLS || o.Format == FormatCMAF {
|
||||
hlsOn = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if hlsOn && len(variants) > 1 {
|
||||
links = append(links, PublishLink{
|
||||
VariantID: "all",
|
||||
VariantLabel: "ABR",
|
||||
OutputID: "master",
|
||||
OutputLabel: "Master",
|
||||
Format: FormatHLS,
|
||||
PlayPath: MasterPlayPath(streamName),
|
||||
Master: true,
|
||||
})
|
||||
}
|
||||
for _, v := range variants {
|
||||
for _, o := range outputs {
|
||||
p := OutputPlayPath(streamName, v.ID, v.Height, v.AudioOnly, o.Format)
|
||||
if p == "" {
|
||||
continue
|
||||
}
|
||||
links = append(links, PublishLink{
|
||||
VariantID: v.ID,
|
||||
VariantLabel: v.Label,
|
||||
OutputID: o.ID,
|
||||
OutputLabel: o.Label,
|
||||
Format: o.Format,
|
||||
PlayPath: p,
|
||||
})
|
||||
}
|
||||
}
|
||||
return links
|
||||
}
|
||||
459
apps/streamd/internal/db/schedules.go
Normal file
459
apps/streamd/internal/db/schedules.go
Normal file
|
|
@ -0,0 +1,459 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Schedule actions and kinds.
|
||||
const (
|
||||
ActionStart = "start"
|
||||
ActionStop = "stop"
|
||||
|
||||
KindOnce = "once"
|
||||
KindWeekly = "weekly"
|
||||
)
|
||||
|
||||
// Schedule is one timed action on a stream: a council meeting at 19:00 every
|
||||
// Tuesday, or a one-off match on Saturday.
|
||||
type Schedule struct {
|
||||
ID int64 `json:"id"`
|
||||
StreamID int64 `json:"stream_id"`
|
||||
StreamName string `json:"stream_name,omitempty"`
|
||||
Action string `json:"action"`
|
||||
Kind string `json:"kind"`
|
||||
// AtUTC is the moment a "once" schedule fires, RFC3339.
|
||||
AtUTC string `json:"at_utc,omitempty"`
|
||||
// DaysMask is a bitmask of weekdays for a "weekly" schedule, with
|
||||
// Sunday as bit 0 through Saturday as bit 6.
|
||||
DaysMask int `json:"days_mask,omitempty"`
|
||||
// TimeOfDay is "HH:MM" in TZ, for a "weekly" schedule.
|
||||
TimeOfDay string `json:"time_of_day,omitempty"`
|
||||
// TZ is an IANA zone name. Local wall-clock time is what an operator
|
||||
// means by "19:00", so the zone is stored rather than a UTC offset: an
|
||||
// offset would drift by an hour across a DST boundary.
|
||||
TZ string `json:"tz,omitempty"`
|
||||
Enabled bool `json:"enabled"`
|
||||
LastFiredAt string `json:"last_fired_at,omitempty"`
|
||||
NextFireAt string `json:"next_fire_at,omitempty"`
|
||||
CreatedBy string `json:"created_by,omitempty"`
|
||||
CreatedAt string `json:"created_at,omitempty"`
|
||||
// PrerollFiredFor records the NextFireAt a pre-roll capture was already
|
||||
// requested for, so it happens once per occurrence.
|
||||
PrerollFiredFor string `json:"-"`
|
||||
}
|
||||
|
||||
func (s *Store) migrateSchedules() error {
|
||||
_, err := s.DB.Exec(`
|
||||
CREATE TABLE IF NOT EXISTS schedules (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
stream_id INTEGER NOT NULL REFERENCES streams(id) ON DELETE CASCADE,
|
||||
action TEXT NOT NULL,
|
||||
kind TEXT NOT NULL,
|
||||
at_utc TEXT NOT NULL DEFAULT '',
|
||||
days_mask INTEGER NOT NULL DEFAULT 0,
|
||||
time_of_day TEXT NOT NULL DEFAULT '',
|
||||
tz TEXT NOT NULL DEFAULT 'UTC',
|
||||
enabled INTEGER NOT NULL DEFAULT 1,
|
||||
last_fired_at TEXT NOT NULL DEFAULT '',
|
||||
next_fire_at TEXT NOT NULL DEFAULT '',
|
||||
preroll_fired_for TEXT NOT NULL DEFAULT '',
|
||||
created_by TEXT NOT NULL DEFAULT '',
|
||||
created_at TEXT NOT NULL DEFAULT ''
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_schedules_next ON schedules(enabled, next_fire_at);
|
||||
CREATE INDEX IF NOT EXISTS idx_schedules_stream ON schedules(stream_id);
|
||||
`)
|
||||
return err
|
||||
}
|
||||
|
||||
// Validate checks a schedule and normalises its fields.
|
||||
func (sc *Schedule) Validate() error {
|
||||
sc.Action = strings.ToLower(strings.TrimSpace(sc.Action))
|
||||
switch sc.Action {
|
||||
case ActionStart, ActionStop:
|
||||
default:
|
||||
return fmt.Errorf("action must be %q or %q", ActionStart, ActionStop)
|
||||
}
|
||||
sc.Kind = strings.ToLower(strings.TrimSpace(sc.Kind))
|
||||
if sc.TZ = strings.TrimSpace(sc.TZ); sc.TZ == "" {
|
||||
sc.TZ = "UTC"
|
||||
}
|
||||
if _, err := time.LoadLocation(sc.TZ); err != nil {
|
||||
return fmt.Errorf("unknown timezone %q", sc.TZ)
|
||||
}
|
||||
switch sc.Kind {
|
||||
case KindOnce:
|
||||
t, err := ParseScheduleTime(sc.AtUTC, sc.TZ)
|
||||
if err != nil {
|
||||
return fmt.Errorf("at_utc: %w", err)
|
||||
}
|
||||
sc.AtUTC = t.UTC().Format(time.RFC3339)
|
||||
case KindWeekly:
|
||||
if _, _, err := parseHHMM(sc.TimeOfDay); err != nil {
|
||||
return fmt.Errorf("time_of_day: %w", err)
|
||||
}
|
||||
if sc.DaysMask&0x7F == 0 {
|
||||
return errors.New("days_mask must select at least one weekday")
|
||||
}
|
||||
sc.DaysMask &= 0x7F
|
||||
default:
|
||||
return fmt.Errorf("kind must be %q or %q", KindOnce, KindWeekly)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ParseScheduleTime accepts an RFC3339 instant, or a local "YYYY-MM-DD HH:MM"
|
||||
// interpreted in tz — which is how a person types a meeting time.
|
||||
func ParseScheduleTime(s, tz string) (time.Time, error) {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return time.Time{}, errors.New("a time is required")
|
||||
}
|
||||
if t, err := time.Parse(time.RFC3339, s); err == nil {
|
||||
return t, nil
|
||||
}
|
||||
loc, err := time.LoadLocation(tz)
|
||||
if err != nil {
|
||||
loc = time.UTC
|
||||
}
|
||||
for _, layout := range []string{"2006-01-02 15:04", "2006-01-02T15:04", "2006-01-02 15:04:05"} {
|
||||
if t, err := time.ParseInLocation(layout, s, loc); err == nil {
|
||||
return t, nil
|
||||
}
|
||||
}
|
||||
return time.Time{}, fmt.Errorf("could not parse %q as a time", s)
|
||||
}
|
||||
|
||||
func parseHHMM(s string) (hour, minute int, err error) {
|
||||
s = strings.TrimSpace(s)
|
||||
t, err := time.Parse("15:04", s)
|
||||
if err != nil {
|
||||
return 0, 0, fmt.Errorf("want HH:MM, got %q", s)
|
||||
}
|
||||
return t.Hour(), t.Minute(), nil
|
||||
}
|
||||
|
||||
// NextFire computes the next time this schedule should fire, strictly after
|
||||
// the given moment. The zero time means "never again".
|
||||
func (sc Schedule) NextFire(after time.Time) time.Time {
|
||||
if !sc.Enabled {
|
||||
return time.Time{}
|
||||
}
|
||||
switch sc.Kind {
|
||||
case KindOnce:
|
||||
t, err := time.Parse(time.RFC3339, sc.AtUTC)
|
||||
if err != nil || !t.After(after) {
|
||||
return time.Time{}
|
||||
}
|
||||
return t.UTC()
|
||||
case KindWeekly:
|
||||
hour, minute, err := parseHHMM(sc.TimeOfDay)
|
||||
if err != nil {
|
||||
return time.Time{}
|
||||
}
|
||||
loc, err := time.LoadLocation(sc.TZ)
|
||||
if err != nil {
|
||||
loc = time.UTC
|
||||
}
|
||||
// Walk forward day by day in the target zone. Constructing the time
|
||||
// per local day is what makes this correct across a DST change: the
|
||||
// event stays at 19:00 wall clock rather than drifting an hour.
|
||||
local := after.In(loc)
|
||||
for i := 0; i <= 8; i++ {
|
||||
day := local.AddDate(0, 0, i)
|
||||
if sc.DaysMask&(1<<uint(day.Weekday())) == 0 {
|
||||
continue
|
||||
}
|
||||
cand := time.Date(day.Year(), day.Month(), day.Day(), hour, minute, 0, 0, loc)
|
||||
if cand.After(after) {
|
||||
return cand.UTC()
|
||||
}
|
||||
}
|
||||
}
|
||||
return time.Time{}
|
||||
}
|
||||
|
||||
const scheduleSelect = `
|
||||
SELECT sc.id, sc.stream_id, sc.action, sc.kind, sc.at_utc, sc.days_mask,
|
||||
sc.time_of_day, sc.tz, sc.enabled, sc.last_fired_at, sc.next_fire_at,
|
||||
sc.preroll_fired_for, sc.created_by, sc.created_at, COALESCE(s.name,'')
|
||||
FROM schedules sc LEFT JOIN streams s ON s.id = sc.stream_id`
|
||||
|
||||
func scanSchedule(row rowScanner) (Schedule, error) {
|
||||
var sc Schedule
|
||||
var enabled int
|
||||
err := row.Scan(&sc.ID, &sc.StreamID, &sc.Action, &sc.Kind, &sc.AtUTC, &sc.DaysMask,
|
||||
&sc.TimeOfDay, &sc.TZ, &enabled, &sc.LastFiredAt, &sc.NextFireAt,
|
||||
&sc.PrerollFiredFor, &sc.CreatedBy, &sc.CreatedAt, &sc.StreamName)
|
||||
if err != nil {
|
||||
return sc, err
|
||||
}
|
||||
sc.Enabled = enabled != 0
|
||||
return sc, nil
|
||||
}
|
||||
|
||||
func (s *Store) CreateSchedule(sc Schedule) (Schedule, error) {
|
||||
if err := sc.Validate(); err != nil {
|
||||
return Schedule{}, err
|
||||
}
|
||||
if _, err := s.GetStream(sc.StreamID); err != nil {
|
||||
return Schedule{}, fmt.Errorf("stream %d not found", sc.StreamID)
|
||||
}
|
||||
sc.Enabled = true
|
||||
next := sc.NextFire(time.Now().UTC())
|
||||
nextStr := ""
|
||||
if !next.IsZero() {
|
||||
nextStr = next.Format(time.RFC3339)
|
||||
}
|
||||
res, err := s.DB.Exec(`
|
||||
INSERT INTO schedules(stream_id,action,kind,at_utc,days_mask,time_of_day,tz,enabled,
|
||||
next_fire_at,created_by,created_at)
|
||||
VALUES(?,?,?,?,?,?,?,1,?,?,?)`,
|
||||
sc.StreamID, sc.Action, sc.Kind, sc.AtUTC, sc.DaysMask, sc.TimeOfDay, sc.TZ,
|
||||
nextStr, sc.CreatedBy, now())
|
||||
if err != nil {
|
||||
return Schedule{}, err
|
||||
}
|
||||
id, _ := res.LastInsertId()
|
||||
return s.GetSchedule(id)
|
||||
}
|
||||
|
||||
func (s *Store) GetSchedule(id int64) (Schedule, error) {
|
||||
sc, err := scanSchedule(s.DB.QueryRow(scheduleSelect+` WHERE sc.id = ?`, id))
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return sc, errors.New("schedule not found")
|
||||
}
|
||||
return sc, err
|
||||
}
|
||||
|
||||
func (s *Store) ListSchedules(streamID int64) ([]Schedule, error) {
|
||||
q := scheduleSelect
|
||||
var args []any
|
||||
if streamID > 0 {
|
||||
q += ` WHERE sc.stream_id = ?`
|
||||
args = append(args, streamID)
|
||||
}
|
||||
q += ` ORDER BY sc.next_fire_at = '', sc.next_fire_at, sc.id`
|
||||
rows, err := s.DB.Query(q, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []Schedule{}
|
||||
for rows.Next() {
|
||||
sc, err := scanSchedule(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, sc)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// UpcomingSchedules lists the soonest pending occurrences across all streams.
|
||||
func (s *Store) UpcomingSchedules(limit int) ([]Schedule, error) {
|
||||
if limit <= 0 || limit > 200 {
|
||||
limit = 20
|
||||
}
|
||||
rows, err := s.DB.Query(scheduleSelect+`
|
||||
WHERE sc.enabled = 1 AND sc.next_fire_at <> '' AND sc.next_fire_at >= ?
|
||||
ORDER BY sc.next_fire_at LIMIT ?`, now(), limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []Schedule{}
|
||||
for rows.Next() {
|
||||
sc, err := scanSchedule(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, sc)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// DueSchedules returns enabled schedules whose moment has arrived.
|
||||
func (s *Store) DueSchedules(at time.Time) ([]Schedule, error) {
|
||||
rows, err := s.DB.Query(scheduleSelect+`
|
||||
WHERE sc.enabled = 1 AND sc.next_fire_at <> '' AND sc.next_fire_at <= ?
|
||||
ORDER BY sc.next_fire_at`, at.UTC().Format(time.RFC3339))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []Schedule{}
|
||||
for rows.Next() {
|
||||
sc, err := scanSchedule(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, sc)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// PendingPreroll returns start schedules firing within the lead time, whose
|
||||
// pre-roll has not been requested yet.
|
||||
func (s *Store) PendingPreroll(at time.Time, lead time.Duration) ([]Schedule, error) {
|
||||
until := at.Add(lead).UTC().Format(time.RFC3339)
|
||||
rows, err := s.DB.Query(scheduleSelect+`
|
||||
WHERE sc.enabled = 1 AND sc.action = 'start' AND sc.next_fire_at <> ''
|
||||
AND sc.next_fire_at <= ? AND sc.next_fire_at > ?
|
||||
AND sc.preroll_fired_for <> sc.next_fire_at
|
||||
ORDER BY sc.next_fire_at`, until, at.UTC().Format(time.RFC3339))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := []Schedule{}
|
||||
for rows.Next() {
|
||||
sc, err := scanSchedule(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, sc)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// MarkPrerolled records that a pre-roll was requested for this occurrence.
|
||||
func (s *Store) MarkPrerolled(id int64, forTime string) error {
|
||||
_, err := s.DB.Exec(`UPDATE schedules SET preroll_fired_for=? WHERE id=?`, forTime, id)
|
||||
return err
|
||||
}
|
||||
|
||||
// MarkFired advances a schedule after it has run. A "once" schedule is
|
||||
// disabled, since its moment has passed.
|
||||
func (s *Store) MarkFired(sc Schedule, at time.Time) error {
|
||||
next := sc.NextFire(at.Add(time.Second))
|
||||
nextStr := ""
|
||||
if !next.IsZero() {
|
||||
nextStr = next.Format(time.RFC3339)
|
||||
}
|
||||
enabled := 1
|
||||
if sc.Kind == KindOnce || nextStr == "" {
|
||||
enabled = 0
|
||||
}
|
||||
_, err := s.DB.Exec(`
|
||||
UPDATE schedules SET last_fired_at=?, next_fire_at=?, enabled=? WHERE id=?`,
|
||||
at.UTC().Format(time.RFC3339), nextStr, enabled, sc.ID)
|
||||
return err
|
||||
}
|
||||
|
||||
// PatchSchedule updates a schedule and recomputes when it next fires.
|
||||
func (s *Store) PatchSchedule(id int64, in Schedule, setEnabled *bool) (Schedule, error) {
|
||||
cur, err := s.GetSchedule(id)
|
||||
if err != nil {
|
||||
return Schedule{}, err
|
||||
}
|
||||
if in.Action != "" {
|
||||
cur.Action = in.Action
|
||||
}
|
||||
if in.Kind != "" {
|
||||
cur.Kind = in.Kind
|
||||
}
|
||||
if in.AtUTC != "" {
|
||||
cur.AtUTC = in.AtUTC
|
||||
}
|
||||
if in.TimeOfDay != "" {
|
||||
cur.TimeOfDay = in.TimeOfDay
|
||||
}
|
||||
if in.TZ != "" {
|
||||
cur.TZ = in.TZ
|
||||
}
|
||||
if in.DaysMask != 0 {
|
||||
cur.DaysMask = in.DaysMask
|
||||
}
|
||||
if setEnabled != nil {
|
||||
cur.Enabled = *setEnabled
|
||||
}
|
||||
if err := cur.Validate(); err != nil {
|
||||
return Schedule{}, err
|
||||
}
|
||||
next := cur.NextFire(time.Now().UTC())
|
||||
nextStr := ""
|
||||
if !next.IsZero() {
|
||||
nextStr = next.Format(time.RFC3339)
|
||||
}
|
||||
en := 0
|
||||
if cur.Enabled {
|
||||
en = 1
|
||||
}
|
||||
_, err = s.DB.Exec(`
|
||||
UPDATE schedules SET action=?, kind=?, at_utc=?, days_mask=?, time_of_day=?, tz=?,
|
||||
enabled=?, next_fire_at=?, preroll_fired_for='' WHERE id=?`,
|
||||
cur.Action, cur.Kind, cur.AtUTC, cur.DaysMask, cur.TimeOfDay, cur.TZ,
|
||||
en, nextStr, id)
|
||||
if err != nil {
|
||||
return Schedule{}, err
|
||||
}
|
||||
return s.GetSchedule(id)
|
||||
}
|
||||
|
||||
func (s *Store) DeleteSchedule(id int64) error {
|
||||
res, err := s.DB.Exec(`DELETE FROM schedules WHERE id=?`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if n, _ := res.RowsAffected(); n == 0 {
|
||||
return errors.New("schedule not found")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RecomputeNextFire refreshes next_fire_at for every enabled schedule, called
|
||||
// at startup so a server that was down over an occurrence does not fire a
|
||||
// stale one and then sit with a past timestamp.
|
||||
func (s *Store) RecomputeNextFire() error {
|
||||
list, err := s.ListSchedules(0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
nowT := time.Now().UTC()
|
||||
for _, sc := range list {
|
||||
if !sc.Enabled {
|
||||
continue
|
||||
}
|
||||
next := sc.NextFire(nowT)
|
||||
nextStr := ""
|
||||
if !next.IsZero() {
|
||||
nextStr = next.Format(time.RFC3339)
|
||||
}
|
||||
enabled := 1
|
||||
if nextStr == "" {
|
||||
// A "once" schedule whose moment has passed is spent.
|
||||
enabled = 0
|
||||
}
|
||||
_, _ = s.DB.Exec(`UPDATE schedules SET next_fire_at=?, enabled=? WHERE id=?`,
|
||||
nextStr, enabled, sc.ID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// WeekdayMask builds a days_mask from weekday numbers (0 = Sunday).
|
||||
func WeekdayMask(days ...int) int {
|
||||
m := 0
|
||||
for _, d := range days {
|
||||
if d >= 0 && d <= 6 {
|
||||
m |= 1 << uint(d)
|
||||
}
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
||||
// DaysLabel renders a mask as "Mon,Tue".
|
||||
func DaysLabel(mask int) string {
|
||||
names := []string{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}
|
||||
var out []string
|
||||
for i := range names {
|
||||
if mask&(1<<uint(i)) != 0 {
|
||||
out = append(out, names[i])
|
||||
}
|
||||
}
|
||||
return strings.Join(out, ",")
|
||||
}
|
||||
370
apps/streamd/internal/db/schedules_test.go
Normal file
370
apps/streamd/internal/db/schedules_test.go
Normal file
|
|
@ -0,0 +1,370 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
_ "time/tzdata"
|
||||
)
|
||||
|
||||
func newStore(t *testing.T) *Store {
|
||||
t.Helper()
|
||||
s, err := Open(filepath.Join(t.TempDir(), "d"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
return s
|
||||
}
|
||||
|
||||
func TestScheduleValidate(t *testing.T) {
|
||||
bad := []Schedule{
|
||||
{Action: "burn", Kind: KindOnce, AtUTC: "2026-01-01T10:00:00Z"},
|
||||
{Action: ActionStart, Kind: "hourly"},
|
||||
{Action: ActionStart, Kind: KindOnce, AtUTC: "not a time"},
|
||||
{Action: ActionStart, Kind: KindWeekly, TimeOfDay: "25:00", DaysMask: 2},
|
||||
{Action: ActionStart, Kind: KindWeekly, TimeOfDay: "19:00", DaysMask: 0},
|
||||
{Action: ActionStart, Kind: KindWeekly, TimeOfDay: "19:00", DaysMask: 2, TZ: "Mars/Olympus"},
|
||||
}
|
||||
for _, sc := range bad {
|
||||
if err := sc.Validate(); err == nil {
|
||||
t.Errorf("expected %+v to be rejected", sc)
|
||||
}
|
||||
}
|
||||
good := Schedule{Action: " START ", Kind: KindWeekly, TimeOfDay: "19:00",
|
||||
DaysMask: WeekdayMask(2), TZ: "Europe/Dublin"}
|
||||
if err := good.Validate(); err != nil {
|
||||
t.Fatalf("valid schedule rejected: %v", err)
|
||||
}
|
||||
if good.Action != ActionStart {
|
||||
t.Errorf("action should be normalised, got %q", good.Action)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseScheduleTimeAcceptsLocalWallClock(t *testing.T) {
|
||||
// A person types a local time; it must be read in the stream's zone, not
|
||||
// as UTC, or the event fires at the wrong hour.
|
||||
got, err := ParseScheduleTime("2026-07-01 19:00", "Europe/Dublin")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Dublin is UTC+1 in July.
|
||||
if got.UTC().Hour() != 18 {
|
||||
t.Errorf("19:00 Dublin in July should be 18:00 UTC, got %s", got.UTC())
|
||||
}
|
||||
if _, err := ParseScheduleTime("", "UTC"); err == nil {
|
||||
t.Error("an empty time should error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNextFireOnce(t *testing.T) {
|
||||
at := time.Date(2026, 3, 10, 19, 0, 0, 0, time.UTC)
|
||||
sc := Schedule{Action: ActionStart, Kind: KindOnce,
|
||||
AtUTC: at.Format(time.RFC3339), Enabled: true}
|
||||
|
||||
before := at.Add(-time.Hour)
|
||||
if got := sc.NextFire(before); !got.Equal(at) {
|
||||
t.Errorf("NextFire = %s, want %s", got, at)
|
||||
}
|
||||
// Once the moment has passed there is no next occurrence.
|
||||
if got := sc.NextFire(at.Add(time.Second)); !got.IsZero() {
|
||||
t.Errorf("a spent once-schedule should not fire again, got %s", got)
|
||||
}
|
||||
// A disabled schedule never fires.
|
||||
sc.Enabled = false
|
||||
if got := sc.NextFire(before); !got.IsZero() {
|
||||
t.Errorf("a disabled schedule should not fire, got %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNextFireWeekly(t *testing.T) {
|
||||
// Tuesdays at 19:00 UTC.
|
||||
sc := Schedule{
|
||||
Action: ActionStart, Kind: KindWeekly, TimeOfDay: "19:00",
|
||||
DaysMask: WeekdayMask(int(time.Tuesday)), TZ: "UTC", Enabled: true,
|
||||
}
|
||||
// A Monday.
|
||||
mon := time.Date(2026, 3, 9, 12, 0, 0, 0, time.UTC)
|
||||
got := sc.NextFire(mon)
|
||||
if got.Weekday() != time.Tuesday || got.Hour() != 19 {
|
||||
t.Errorf("next fire = %s, want Tuesday 19:00", got)
|
||||
}
|
||||
if d := got.Sub(mon); d < 0 || d > 48*time.Hour {
|
||||
t.Errorf("next fire %s is not within two days of %s", got, mon)
|
||||
}
|
||||
// From Tuesday 19:00:01 it must roll to the following week, not fire
|
||||
// again the same evening.
|
||||
justAfter := time.Date(2026, 3, 10, 19, 0, 1, 0, time.UTC)
|
||||
next := sc.NextFire(justAfter)
|
||||
if next.Weekday() != time.Tuesday {
|
||||
t.Errorf("next = %s, want the following Tuesday", next)
|
||||
}
|
||||
if next.Sub(justAfter) < 6*24*time.Hour {
|
||||
t.Errorf("next = %s, should be about a week after %s", next, justAfter)
|
||||
}
|
||||
}
|
||||
|
||||
// A weekly event is a wall-clock commitment: a 19:00 meeting stays at 19:00
|
||||
// local across a DST change. Storing a fixed UTC offset would drift an hour.
|
||||
func TestNextFireWeeklyAcrossDST(t *testing.T) {
|
||||
const zone = "Europe/Dublin"
|
||||
loc, err := time.LoadLocation(zone)
|
||||
if err != nil {
|
||||
t.Skipf("zone data unavailable: %v", err)
|
||||
}
|
||||
sc := Schedule{
|
||||
Action: ActionStart, Kind: KindWeekly, TimeOfDay: "19:00",
|
||||
DaysMask: WeekdayMask(int(time.Sunday)), TZ: zone, Enabled: true,
|
||||
}
|
||||
// Ireland springs forward at 01:00 on Sunday 29 March 2026. Starting on
|
||||
// the 21st puts the first occurrence on 22 March (still GMT) and the
|
||||
// second on 29 March (already IST), so the pair straddles the change.
|
||||
beforeChange := time.Date(2026, 3, 21, 12, 0, 0, 0, loc)
|
||||
first := sc.NextFire(beforeChange)
|
||||
afterChange := sc.NextFire(first.Add(time.Second))
|
||||
if first.In(loc).Day() != 22 || afterChange.In(loc).Day() != 29 {
|
||||
t.Fatalf("test set-up is wrong: occurrences are %s and %s, want 22 and 29 March",
|
||||
first.In(loc), afterChange.In(loc))
|
||||
}
|
||||
|
||||
// Both occurrences must read 19:00 in local time...
|
||||
for _, got := range []time.Time{first, afterChange} {
|
||||
local := got.In(loc)
|
||||
if local.Hour() != 19 || local.Minute() != 0 {
|
||||
t.Errorf("occurrence %s is %02d:%02d local, want 19:00", got, local.Hour(), local.Minute())
|
||||
}
|
||||
}
|
||||
// ...which means their UTC hours differ across the change. That
|
||||
// difference is the proof the zone is being honoured.
|
||||
if first.UTC().Hour() == afterChange.UTC().Hour() {
|
||||
t.Errorf("UTC hour did not shift across the DST boundary (%s vs %s) — "+
|
||||
"the schedule is drifting rather than tracking local time",
|
||||
first.UTC(), afterChange.UTC())
|
||||
}
|
||||
}
|
||||
|
||||
func TestNextFireWeeklyMultipleDays(t *testing.T) {
|
||||
sc := Schedule{
|
||||
Action: ActionStart, Kind: KindWeekly, TimeOfDay: "08:30",
|
||||
DaysMask: WeekdayMask(int(time.Monday), int(time.Wednesday), int(time.Friday)),
|
||||
TZ: "UTC", Enabled: true,
|
||||
}
|
||||
// From Monday 09:00, the next is Wednesday.
|
||||
from := time.Date(2026, 3, 9, 9, 0, 0, 0, time.UTC)
|
||||
got := sc.NextFire(from)
|
||||
if got.Weekday() != time.Wednesday || got.Hour() != 8 || got.Minute() != 30 {
|
||||
t.Errorf("got %s, want Wednesday 08:30", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScheduleCRUDAndFiring(t *testing.T) {
|
||||
store := newStore(t)
|
||||
st, err := store.CreateStream(CreateStream{Name: "council", MPD: "https://x/a.mpd"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// A one-off two minutes out.
|
||||
at := time.Now().UTC().Add(2 * time.Minute).Truncate(time.Second)
|
||||
sc, err := store.CreateSchedule(Schedule{
|
||||
StreamID: st.ID, Action: ActionStart, Kind: KindOnce,
|
||||
AtUTC: at.Format(time.RFC3339), CreatedBy: "tester",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if sc.NextFireAt == "" {
|
||||
t.Error("a new schedule should have a next_fire_at")
|
||||
}
|
||||
if sc.StreamName != "council" {
|
||||
t.Errorf("stream name = %q", sc.StreamName)
|
||||
}
|
||||
|
||||
// Not due yet.
|
||||
if due, err := store.DueSchedules(time.Now().UTC()); err != nil || len(due) != 0 {
|
||||
t.Fatalf("should not be due yet: %v %d", err, len(due))
|
||||
}
|
||||
// Due once its moment arrives.
|
||||
due, err := store.DueSchedules(at.Add(time.Second))
|
||||
if err != nil || len(due) != 1 {
|
||||
t.Fatalf("want 1 due, got %d (%v)", len(due), err)
|
||||
}
|
||||
|
||||
// Firing a once-schedule spends it.
|
||||
if err := store.MarkFired(due[0], at); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, err := store.GetSchedule(sc.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if after.Enabled {
|
||||
t.Error("a fired once-schedule should be disabled")
|
||||
}
|
||||
if after.LastFiredAt == "" {
|
||||
t.Error("last_fired_at should be set")
|
||||
}
|
||||
if later, _ := store.DueSchedules(at.Add(time.Hour)); len(later) != 0 {
|
||||
t.Error("a spent schedule must not fire twice")
|
||||
}
|
||||
|
||||
// A weekly schedule keeps going.
|
||||
weekly, err := store.CreateSchedule(Schedule{
|
||||
StreamID: st.ID, Action: ActionStart, Kind: KindWeekly,
|
||||
TimeOfDay: "19:00", DaysMask: WeekdayMask(0, 1, 2, 3, 4, 5, 6), TZ: "UTC",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
firstNext := weekly.NextFireAt
|
||||
firedAt, err := time.Parse(time.RFC3339, firstNext)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.MarkFired(weekly, firedAt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
again, _ := store.GetSchedule(weekly.ID)
|
||||
if !again.Enabled {
|
||||
t.Error("a weekly schedule should stay enabled after firing")
|
||||
}
|
||||
if again.NextFireAt == "" || again.NextFireAt == firstNext {
|
||||
t.Errorf("weekly next_fire_at should have advanced, was %q now %q", firstNext, again.NextFireAt)
|
||||
}
|
||||
|
||||
// Listing and deleting.
|
||||
list, err := store.ListSchedules(st.ID)
|
||||
if err != nil || len(list) != 2 {
|
||||
t.Fatalf("want 2 schedules, got %d (%v)", len(list), err)
|
||||
}
|
||||
if err := store.DeleteSchedule(weekly.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.DeleteSchedule(weekly.ID); err == nil {
|
||||
t.Error("deleting twice should report not found")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSchedulePrerollOnlyOncePerOccurrence(t *testing.T) {
|
||||
store := newStore(t)
|
||||
st, _ := store.CreateStream(CreateStream{Name: "match", MPD: "https://x/a.mpd"})
|
||||
at := time.Now().UTC().Add(2 * time.Minute)
|
||||
sc, err := store.CreateSchedule(Schedule{
|
||||
StreamID: st.ID, Action: ActionStart, Kind: KindOnce,
|
||||
AtUTC: at.Format(time.RFC3339),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
nowT := time.Now().UTC()
|
||||
pending, err := store.PendingPreroll(nowT, 5*time.Minute)
|
||||
if err != nil || len(pending) != 1 {
|
||||
t.Fatalf("want 1 pre-roll pending, got %d (%v)", len(pending), err)
|
||||
}
|
||||
if err := store.MarkPrerolled(sc.ID, pending[0].NextFireAt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Already requested: must not ask again every tick.
|
||||
pending, err = store.PendingPreroll(nowT, 5*time.Minute)
|
||||
if err != nil || len(pending) != 0 {
|
||||
t.Fatalf("pre-roll should not repeat, got %d (%v)", len(pending), err)
|
||||
}
|
||||
|
||||
// A stop schedule never pre-rolls: there is nothing to prepare.
|
||||
_, err = store.CreateSchedule(Schedule{
|
||||
StreamID: st.ID, Action: ActionStop, Kind: KindOnce,
|
||||
AtUTC: at.Format(time.RFC3339),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pending, _ = store.PendingPreroll(nowT, 5*time.Minute)
|
||||
for _, p := range pending {
|
||||
if p.Action == ActionStop {
|
||||
t.Error("a stop schedule should not be pre-rolled")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A server that was down over an occurrence must not fire it late.
|
||||
func TestRecomputeNextFireDropsMissedOnce(t *testing.T) {
|
||||
store := newStore(t)
|
||||
st, _ := store.CreateStream(CreateStream{Name: "gone", MPD: "https://x/a.mpd"})
|
||||
past := time.Now().UTC().Add(-2 * time.Hour)
|
||||
sc, err := store.CreateSchedule(Schedule{
|
||||
StreamID: st.ID, Action: ActionStart, Kind: KindOnce,
|
||||
AtUTC: past.Add(time.Hour).Format(time.RFC3339),
|
||||
})
|
||||
if err != nil {
|
||||
// CreateSchedule accepts a past time; NextFire just yields nothing.
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.RecomputeNextFire(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, _ := store.GetSchedule(sc.ID)
|
||||
if got.Enabled {
|
||||
t.Error("a missed once-schedule should be disabled, not fired late")
|
||||
}
|
||||
if due, _ := store.DueSchedules(time.Now().UTC()); len(due) != 0 {
|
||||
t.Error("a missed schedule must not be due")
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpcomingSchedulesOrdering(t *testing.T) {
|
||||
store := newStore(t)
|
||||
st, _ := store.CreateStream(CreateStream{Name: "events", MPD: "https://x/a.mpd"})
|
||||
far := time.Now().UTC().Add(3 * time.Hour)
|
||||
near := time.Now().UTC().Add(10 * time.Minute)
|
||||
if _, err := store.CreateSchedule(Schedule{StreamID: st.ID, Action: ActionStart,
|
||||
Kind: KindOnce, AtUTC: far.Format(time.RFC3339)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := store.CreateSchedule(Schedule{StreamID: st.ID, Action: ActionStart,
|
||||
Kind: KindOnce, AtUTC: near.Format(time.RFC3339)}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
up, err := store.UpcomingSchedules(10)
|
||||
if err != nil || len(up) != 2 {
|
||||
t.Fatalf("want 2 upcoming, got %d (%v)", len(up), err)
|
||||
}
|
||||
if up[0].NextFireAt > up[1].NextFireAt {
|
||||
t.Errorf("upcoming should be soonest first, got %q then %q", up[0].NextFireAt, up[1].NextFireAt)
|
||||
}
|
||||
}
|
||||
|
||||
// Deleting a stream must take its schedules with it, or the scheduler would
|
||||
// keep trying to start something that no longer exists.
|
||||
func TestSchedulesCascadeOnStreamDelete(t *testing.T) {
|
||||
store := newStore(t)
|
||||
st, _ := store.CreateStream(CreateStream{Name: "temp", MPD: "https://x/a.mpd"})
|
||||
if _, err := store.CreateSchedule(Schedule{
|
||||
StreamID: st.ID, Action: ActionStart, Kind: KindWeekly,
|
||||
TimeOfDay: "19:00", DaysMask: WeekdayMask(1), TZ: "UTC",
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.DeleteStream(st.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
list, err := store.ListSchedules(st.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(list) != 0 {
|
||||
t.Errorf("schedules outlived their stream: %+v", list)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDaysLabel(t *testing.T) {
|
||||
if got := DaysLabel(WeekdayMask(1, 3, 5)); got != "Mon,Wed,Fri" {
|
||||
t.Errorf("got %q", got)
|
||||
}
|
||||
if got := DaysLabel(0); got != "" {
|
||||
t.Errorf("empty mask = %q", got)
|
||||
}
|
||||
if got := DaysLabel(WeekdayMask(0, 6)); got != "Sun,Sat" {
|
||||
t.Errorf("got %q", got)
|
||||
}
|
||||
}
|
||||
179
apps/streamd/internal/db/settings.go
Normal file
179
apps/streamd/internal/db/settings.go
Normal file
|
|
@ -0,0 +1,179 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Setting keys. These are the installation-wide defaults that sit at the
|
||||
// bottom of the resolution chain: stream row -> app module -> these -> the
|
||||
// compiled-in defaults.
|
||||
const (
|
||||
SettingHLSTime = "hls_time"
|
||||
SettingHLSListSize = "hls_list_size"
|
||||
SettingLiveWait = "live_wait"
|
||||
SettingTSReadyBytes = "ts_ready_bytes"
|
||||
SettingIdleTimeoutS = "idle_timeout_s"
|
||||
SettingDefaultOutputs = "default_outputs"
|
||||
SettingOnDemand = "default_on_demand"
|
||||
)
|
||||
|
||||
func (s *Store) migrateSettings() error {
|
||||
_, err := s.DB.Exec(`
|
||||
CREATE TABLE IF NOT EXISTS settings (
|
||||
key TEXT PRIMARY KEY,
|
||||
value TEXT NOT NULL DEFAULT '',
|
||||
updated_at TEXT NOT NULL DEFAULT ''
|
||||
);`)
|
||||
return err
|
||||
}
|
||||
|
||||
// GetSettings returns every stored setting.
|
||||
func (s *Store) GetSettings() (map[string]string, error) {
|
||||
rows, err := s.DB.Query(`SELECT key, value FROM settings`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
out := map[string]string{}
|
||||
for rows.Next() {
|
||||
var k, v string
|
||||
if err := rows.Scan(&k, &v); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[k] = v
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// SetSettings upserts the given keys in one transaction. A key with an empty
|
||||
// value is deleted, which returns it to the built-in default.
|
||||
func (s *Store) SetSettings(in map[string]string) error {
|
||||
tx, err := s.DB.Begin()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for k, v := range in {
|
||||
k = strings.TrimSpace(k)
|
||||
if k == "" {
|
||||
continue
|
||||
}
|
||||
if strings.TrimSpace(v) == "" {
|
||||
if _, err := tx.Exec(`DELETE FROM settings WHERE key=?`, k); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
continue
|
||||
}
|
||||
if _, err := tx.Exec(`
|
||||
INSERT INTO settings(key,value,updated_at) VALUES(?,?,?)
|
||||
ON CONFLICT(key) DO UPDATE SET value=excluded.value, updated_at=excluded.updated_at`,
|
||||
k, v, now()); err != nil {
|
||||
_ = tx.Rollback()
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit()
|
||||
}
|
||||
|
||||
// PackagerSettings are the knobs that shape the ffmpeg command line. A zero
|
||||
// field means "not set at this level", so the next level down applies.
|
||||
type PackagerSettings struct {
|
||||
HLSTime int `json:"hls_time,omitempty"`
|
||||
HLSListSize int `json:"hls_list_size,omitempty"`
|
||||
LiveWait int `json:"live_wait,omitempty"`
|
||||
TSReadyBytes int `json:"ts_ready_bytes,omitempty"`
|
||||
}
|
||||
|
||||
// ParsePackagerSettings reads a stream's settings_json. Unparseable JSON
|
||||
// yields the zero value, which simply defers to the levels below.
|
||||
func ParsePackagerSettings(raw string) PackagerSettings {
|
||||
var p PackagerSettings
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" || raw == "null" {
|
||||
return p
|
||||
}
|
||||
_ = json.Unmarshal([]byte(raw), &p)
|
||||
return p.sane()
|
||||
}
|
||||
|
||||
// sane drops nonsense values rather than passing them to ffmpeg, where a
|
||||
// zero segment duration would produce an unplayable stream.
|
||||
func (p PackagerSettings) sane() PackagerSettings {
|
||||
if p.HLSTime < 1 || p.HLSTime > 30 {
|
||||
p.HLSTime = 0
|
||||
}
|
||||
if p.HLSListSize < 1 || p.HLSListSize > 500 {
|
||||
p.HLSListSize = 0
|
||||
}
|
||||
if p.LiveWait < 0 || p.LiveWait > 120 {
|
||||
p.LiveWait = 0
|
||||
}
|
||||
if p.TSReadyBytes < 0 || p.TSReadyBytes > (256<<20) {
|
||||
p.TSReadyBytes = 0
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
// GlobalPackagerSettings reads the installation-wide packager defaults.
|
||||
func (s *Store) GlobalPackagerSettings() PackagerSettings {
|
||||
vals, err := s.GetSettings()
|
||||
if err != nil {
|
||||
return PackagerSettings{}
|
||||
}
|
||||
atoi := func(k string) int {
|
||||
n, err := strconv.Atoi(strings.TrimSpace(vals[k]))
|
||||
if err != nil {
|
||||
return 0
|
||||
}
|
||||
return n
|
||||
}
|
||||
return PackagerSettings{
|
||||
HLSTime: atoi(SettingHLSTime),
|
||||
HLSListSize: atoi(SettingHLSListSize),
|
||||
LiveWait: atoi(SettingLiveWait),
|
||||
TSReadyBytes: atoi(SettingTSReadyBytes),
|
||||
}.sane()
|
||||
}
|
||||
|
||||
// settingTruthy accepts the spellings operators realistically type into the
|
||||
// settings form for boolean defaults.
|
||||
func settingTruthy(v string) bool {
|
||||
switch strings.ToLower(strings.TrimSpace(v)) {
|
||||
case "1", "true", "yes", "on":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// ApplyCreateDefaults fills CreateStream fields that the caller left unset
|
||||
// from the installation-wide settings table. Explicit request fields win.
|
||||
// Packager knobs (hls_time etc.) are resolved at start time, not at create.
|
||||
func (s *Store) ApplyCreateDefaults(in *CreateStream) {
|
||||
if in == nil {
|
||||
return
|
||||
}
|
||||
vals, err := s.GetSettings()
|
||||
if err != nil || len(vals) == 0 {
|
||||
return
|
||||
}
|
||||
if in.OnDemand == nil {
|
||||
if v, ok := vals[SettingOnDemand]; ok && strings.TrimSpace(v) != "" {
|
||||
b := settingTruthy(v)
|
||||
in.OnDemand = &b
|
||||
}
|
||||
}
|
||||
if in.IdleTimeoutS == nil {
|
||||
if v := strings.TrimSpace(vals[SettingIdleTimeoutS]); v != "" {
|
||||
if n, err := strconv.Atoi(v); err == nil && n > 0 {
|
||||
in.IdleTimeoutS = &n
|
||||
}
|
||||
}
|
||||
}
|
||||
if len(in.Outputs) == 0 && strings.TrimSpace(in.OutputsJSON) == "" {
|
||||
if v := strings.TrimSpace(vals[SettingDefaultOutputs]); v != "" {
|
||||
in.OutputsJSON = v
|
||||
}
|
||||
}
|
||||
}
|
||||
57
apps/streamd/internal/db/settings_test.go
Normal file
57
apps/streamd/internal/db/settings_test.go
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
package db
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestApplyCreateDefaultsFillsUnsetFields(t *testing.T) {
|
||||
s, err := Open(filepath.Join(t.TempDir(), "d"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
|
||||
if err := s.SetSettings(map[string]string{
|
||||
SettingOnDemand: "true",
|
||||
SettingIdleTimeoutS: "120",
|
||||
SettingDefaultOutputs: `[{"id":"hls","label":"HLS","format":"hls","enabled":true}]`,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
in := CreateStream{Name: "news"}
|
||||
s.ApplyCreateDefaults(&in)
|
||||
if in.OnDemand == nil || !*in.OnDemand {
|
||||
t.Fatalf("expected on_demand=true from settings, got %+v", in.OnDemand)
|
||||
}
|
||||
if in.IdleTimeoutS == nil || *in.IdleTimeoutS != 120 {
|
||||
t.Fatalf("expected idle_timeout_s=120, got %+v", in.IdleTimeoutS)
|
||||
}
|
||||
if in.OutputsJSON == "" {
|
||||
t.Fatal("expected default_outputs JSON to be copied")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyCreateDefaultsDoesNotOverrideExplicit(t *testing.T) {
|
||||
s, err := Open(filepath.Join(t.TempDir(), "d"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = s.Close() })
|
||||
|
||||
_ = s.SetSettings(map[string]string{
|
||||
SettingOnDemand: "true",
|
||||
SettingIdleTimeoutS: "120",
|
||||
})
|
||||
off := false
|
||||
idle := 600
|
||||
in := CreateStream{Name: "news", OnDemand: &off, IdleTimeoutS: &idle}
|
||||
s.ApplyCreateDefaults(&in)
|
||||
if in.OnDemand == nil || *in.OnDemand {
|
||||
t.Fatal("explicit on_demand=false must win over settings")
|
||||
}
|
||||
if in.IdleTimeoutS == nil || *in.IdleTimeoutS != 600 {
|
||||
t.Fatal("explicit idle_timeout_s must win over settings")
|
||||
}
|
||||
}
|
||||
170
apps/streamd/internal/db/stream_test.go
Normal file
170
apps/streamd/internal/db/stream_test.go
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
package db
|
||||
|
||||
import "testing"
|
||||
|
||||
const (
|
||||
testKID = "0123456789abcdef0123456789abcdef"
|
||||
testKey = "fedcba9876543210fedcba9876543210"
|
||||
)
|
||||
|
||||
var goodKey = testKID + ":" + testKey
|
||||
|
||||
// withDerived runs the same derivation scanStream does, so these tests
|
||||
// exercise exactly what the API serialises.
|
||||
func withDerived(st Stream) Stream {
|
||||
st.fillDerived()
|
||||
return st
|
||||
}
|
||||
|
||||
func TestNeedsCaptureDisabledStreamNever(t *testing.T) {
|
||||
st := withDerived(Stream{Enabled: false, MPD: "", Health: "down"})
|
||||
if st.NeedsCapture {
|
||||
t.Error("a disabled stream must never be queued for capture")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeedsCaptureMissingManifest(t *testing.T) {
|
||||
st := withDerived(Stream{Enabled: true, MPD: "", Health: "ok"})
|
||||
if !st.NeedsCapture {
|
||||
t.Error("a stream with no manifest needs a capture")
|
||||
}
|
||||
}
|
||||
|
||||
// The regression the key redaction would otherwise cause: a healthy encrypted
|
||||
// stream must not look like it needs a capture just because the API response
|
||||
// no longer carries the key. The server decides, using the derived flags.
|
||||
func TestNeedsCaptureHealthyDRMStream(t *testing.T) {
|
||||
st := withDerived(Stream{
|
||||
Enabled: true, MPD: "https://x/manifest.mpd", Key: goodKey,
|
||||
Health: "ok", PlaylistAgeS: 2,
|
||||
})
|
||||
if !st.DRMRequired {
|
||||
t.Error("a stream holding a key should resolve to DRM required")
|
||||
}
|
||||
if !st.KeyValid {
|
||||
t.Error("a well-formed key should be valid")
|
||||
}
|
||||
if st.NeedsCapture {
|
||||
t.Error("a healthy DRM stream must not be queued for capture")
|
||||
}
|
||||
// And after redaction the verdict is unchanged and the key is gone.
|
||||
red := st.Redacted()
|
||||
if red.Key != "" || red.HeadersJSON != "" || red.Proxy != "" {
|
||||
t.Errorf("Redacted left secrets behind: %+v", red)
|
||||
}
|
||||
if red.NeedsCapture != st.NeedsCapture || red.HasKey != true || red.KeyValid != true {
|
||||
t.Error("redaction must preserve the derived flags")
|
||||
}
|
||||
}
|
||||
|
||||
// A clear stream legitimately has no keys. streamd supports clear content, so
|
||||
// this must not spin the capture queue forever — the bug the old
|
||||
// "key == empty means capture" rule caused.
|
||||
func TestNeedsCaptureClearStreamWithNoKey(t *testing.T) {
|
||||
st := withDerived(Stream{
|
||||
Enabled: true, MPD: "https://x/manifest.mpd", Key: "",
|
||||
DRMMode: DRMNo, Health: "ok", PlaylistAgeS: 2,
|
||||
})
|
||||
if st.DRMRequired {
|
||||
t.Error("drm_mode=no must resolve to DRM not required")
|
||||
}
|
||||
if st.NeedsCapture {
|
||||
t.Error("a healthy clear stream must not be queued for capture")
|
||||
}
|
||||
}
|
||||
|
||||
// In auto mode a stream that has never held a key is assumed clear.
|
||||
func TestNeedsCaptureAutoModeInfersFromKey(t *testing.T) {
|
||||
clear := withDerived(Stream{Enabled: true, MPD: "https://x/a.mpd", Health: "ok"})
|
||||
if clear.DRMRequired {
|
||||
t.Error("auto with no key should infer clear")
|
||||
}
|
||||
if clear.DRMMode != DRMAuto {
|
||||
t.Errorf("auto should be normalised to %q, got %q", DRMAuto, clear.DRMMode)
|
||||
}
|
||||
encrypted := withDerived(Stream{Enabled: true, MPD: "https://x/a.mpd", Key: goodKey, Health: "ok"})
|
||||
if !encrypted.DRMRequired {
|
||||
t.Error("auto with a key should infer DRM")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeedsCaptureInvalidKey(t *testing.T) {
|
||||
st := withDerived(Stream{
|
||||
Enabled: true, MPD: "https://x/a.mpd", Key: "garbage",
|
||||
DRMMode: DRMYes, Health: "ok",
|
||||
})
|
||||
if st.KeyValid {
|
||||
t.Error("garbage should not be a valid key")
|
||||
}
|
||||
if !st.NeedsCapture {
|
||||
t.Error("a DRM stream with an unusable key needs a capture")
|
||||
}
|
||||
}
|
||||
|
||||
// An on-demand stream sitting idle is doing its job, not failing. Treating
|
||||
// "stopped" as broken would queue a capture for every idle channel.
|
||||
func TestNeedsCaptureOnDemandIdleIsNotBroken(t *testing.T) {
|
||||
st := withDerived(Stream{
|
||||
Enabled: true, MPD: "https://x/a.mpd", Key: goodKey,
|
||||
OnDemand: true, Health: "stopped",
|
||||
})
|
||||
if st.NeedsCapture {
|
||||
t.Error("an idle on-demand stream must not be queued for capture")
|
||||
}
|
||||
// The same stream that is not on-demand is genuinely down.
|
||||
always := withDerived(Stream{
|
||||
Enabled: true, MPD: "https://x/a.mpd", Key: goodKey,
|
||||
OnDemand: false, Health: "stopped",
|
||||
})
|
||||
if !always.NeedsCapture {
|
||||
t.Error("an always-on stream that is stopped should be refreshed")
|
||||
}
|
||||
}
|
||||
|
||||
// A stream still inside its bootstrap window must be left alone: capturing
|
||||
// would POST credentials and restart it, which is a slow restart loop.
|
||||
func TestNeedsCaptureStartingRespectsBootstrapGrace(t *testing.T) {
|
||||
young := withDerived(Stream{
|
||||
Enabled: true, MPD: "https://x/a.mpd", Key: goodKey,
|
||||
Health: "starting", UptimeS: 10,
|
||||
})
|
||||
if young.NeedsCapture {
|
||||
t.Error("a stream still starting up must not be restarted by a capture")
|
||||
}
|
||||
stuck := withDerived(Stream{
|
||||
Enabled: true, MPD: "https://x/a.mpd", Key: goodKey,
|
||||
Health: "starting", UptimeS: bootstrapGraceS + 1,
|
||||
})
|
||||
if !stuck.NeedsCapture {
|
||||
t.Error("a stream stuck in starting past the grace window needs help")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNeedsCaptureStalePlaylist(t *testing.T) {
|
||||
st := withDerived(Stream{
|
||||
Enabled: true, MPD: "https://x/a.mpd", Key: goodKey,
|
||||
Health: "ok", PlaylistAgeS: 120,
|
||||
})
|
||||
if !st.NeedsCapture {
|
||||
t.Error("a stale playlist should trigger a refresh")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDerivedHeaderAndProxyFlags(t *testing.T) {
|
||||
for _, c := range []struct {
|
||||
headers string
|
||||
want bool
|
||||
}{
|
||||
{"", false}, {"{}", false}, {"null", false},
|
||||
{`{"Cookie":"x"}`, true},
|
||||
} {
|
||||
st := withDerived(Stream{HeadersJSON: c.headers})
|
||||
if st.HasHeaders != c.want {
|
||||
t.Errorf("HasHeaders(%q) = %v want %v", c.headers, st.HasHeaders, c.want)
|
||||
}
|
||||
}
|
||||
st := withDerived(Stream{Proxy: "socks5://127.0.0.1:1080"})
|
||||
if !st.HasProxy {
|
||||
t.Error("a configured proxy should set HasProxy")
|
||||
}
|
||||
}
|
||||
|
|
@ -6,9 +6,14 @@ import (
|
|||
"strings"
|
||||
)
|
||||
|
||||
// SourceVariantID is the id of the pass-through rung: the source copy
|
||||
// published at /hls/<name>/index.m3u8.
|
||||
const SourceVariantID = "fhd"
|
||||
|
||||
// VariantSpec is one configured output ladder rung for a stream.
|
||||
// Height 0 (or id "fhd") is the source copy published at /hls/<name>/index.m3u8.
|
||||
// Other heights are ffmpeg-scaled sibling playlists at /hls/<name>-<id>/index.m3u8.
|
||||
// An AudioOnly rung is also height 0 but is a separate, re-encoded rung.
|
||||
type VariantSpec struct {
|
||||
ID string `json:"id"`
|
||||
Label string `json:"label"`
|
||||
|
|
@ -16,6 +21,10 @@ type VariantSpec struct {
|
|||
Height int `json:"height"`
|
||||
VideoBitrate string `json:"video_bitrate,omitempty"`
|
||||
AudioBitrate string `json:"audio_bitrate,omitempty"`
|
||||
// AudioOnly drops video entirely. It is checked before the height-zero
|
||||
// source-rung rule, because an audio rung is height zero too and would
|
||||
// otherwise be rewritten into the source copy.
|
||||
AudioOnly bool `json:"audio_only,omitempty"`
|
||||
}
|
||||
|
||||
// VariantStatus is VariantSpec plus live play path / health for the API/UI.
|
||||
|
|
@ -26,12 +35,19 @@ type VariantStatus struct {
|
|||
PlaylistAgeS float64 `json:"playlist_age_s,omitempty"`
|
||||
}
|
||||
|
||||
// DefaultVariants returns the FHD + optional HD/SD ladder with only FHD enabled.
|
||||
// IsSource reports whether this rung is the pass-through copy of the input.
|
||||
func (v VariantSpec) IsSource() bool {
|
||||
return !v.AudioOnly && v.Height <= 0
|
||||
}
|
||||
|
||||
// DefaultVariants returns the FHD + optional HD/SD/audio ladder with only FHD
|
||||
// enabled.
|
||||
func DefaultVariants() []VariantSpec {
|
||||
return []VariantSpec{
|
||||
{ID: "fhd", Label: "FHD", Enabled: true, Height: 0},
|
||||
{ID: SourceVariantID, Label: "FHD", Enabled: true, Height: 0},
|
||||
{ID: "hd", Label: "HD", Enabled: false, Height: 720, VideoBitrate: "2800k", AudioBitrate: "128k"},
|
||||
{ID: "sd", Label: "SD", Enabled: false, Height: 480, VideoBitrate: "1200k", AudioBitrate: "96k"},
|
||||
{ID: "audio", Label: "Audio", Enabled: false, AudioOnly: true, AudioBitrate: "96k"},
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -48,16 +64,37 @@ func ParseVariantsJSON(raw string) []VariantSpec {
|
|||
return NormalizeVariants(list)
|
||||
}
|
||||
|
||||
// NormalizeVariants fills ids/labels/bitrates and ensures an FHD/source entry exists.
|
||||
// NormalizeVariants fills ids/labels/bitrates and ensures a source entry exists.
|
||||
func NormalizeVariants(in []VariantSpec) []VariantSpec {
|
||||
out := make([]VariantSpec, 0, len(in))
|
||||
seen := map[string]bool{}
|
||||
hasSource := false
|
||||
for _, v := range in {
|
||||
v.ID = slug(v.ID)
|
||||
// An audio rung is resolved first: it is height zero like the source
|
||||
// copy, and the source rule below would otherwise swallow it.
|
||||
if v.AudioOnly {
|
||||
v.Height = 0
|
||||
if v.ID == "" || v.ID == SourceVariantID {
|
||||
v.ID = "audio"
|
||||
}
|
||||
if v.Label == "" {
|
||||
v.Label = "Audio"
|
||||
}
|
||||
if v.AudioBitrate == "" {
|
||||
v.AudioBitrate = "96k"
|
||||
}
|
||||
v.VideoBitrate = ""
|
||||
if seen[v.ID] {
|
||||
continue
|
||||
}
|
||||
seen[v.ID] = true
|
||||
out = append(out, v)
|
||||
continue
|
||||
}
|
||||
if v.ID == "" {
|
||||
if v.Height <= 0 {
|
||||
v.ID = "fhd"
|
||||
v.ID = SourceVariantID
|
||||
} else {
|
||||
v.ID = fmt.Sprintf("%dp", v.Height)
|
||||
}
|
||||
|
|
@ -74,8 +111,8 @@ func NormalizeVariants(in []VariantSpec) []VariantSpec {
|
|||
}
|
||||
if v.Height == 0 {
|
||||
hasSource = true
|
||||
v.ID = "fhd"
|
||||
if v.Label == "" || strings.EqualFold(v.Label, "fhd") {
|
||||
v.ID = SourceVariantID
|
||||
if v.Label == "" || strings.EqualFold(v.Label, SourceVariantID) {
|
||||
v.Label = "FHD"
|
||||
}
|
||||
v.Enabled = true // source copy always published when the stream runs
|
||||
|
|
@ -103,7 +140,7 @@ func NormalizeVariants(in []VariantSpec) []VariantSpec {
|
|||
out = append(out, v)
|
||||
}
|
||||
if !hasSource {
|
||||
out = append([]VariantSpec{{ID: "fhd", Label: "FHD", Enabled: true, Height: 0}}, out...)
|
||||
out = append([]VariantSpec{{ID: SourceVariantID, Label: "FHD", Enabled: true, Height: 0}}, out...)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
|
@ -121,19 +158,71 @@ func EncodeVariantsJSON(list []VariantSpec) (string, error) {
|
|||
// VariantPlayPath is the HLS URL path for one variant of stream name.
|
||||
func VariantPlayPath(streamName, variantID string, height int) string {
|
||||
variantID = slug(variantID)
|
||||
if height <= 0 || variantID == "" || variantID == "fhd" {
|
||||
if height <= 0 || variantID == "" || variantID == SourceVariantID {
|
||||
return "/hls/" + streamName + "/index.m3u8"
|
||||
}
|
||||
return "/hls/" + streamName + "-" + variantID + "/index.m3u8"
|
||||
}
|
||||
|
||||
// ScaledVariants returns enabled non-source (transcode) variants.
|
||||
// ScaledVariants returns enabled rungs that need their own encoder: every
|
||||
// non-source rung, including audio-only.
|
||||
func ScaledVariants(list []VariantSpec) []VariantSpec {
|
||||
var out []VariantSpec
|
||||
for _, v := range list {
|
||||
if v.Enabled && v.Height > 0 {
|
||||
if v.Enabled && !v.IsSource() {
|
||||
out = append(out, v)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// EnabledVariants returns every enabled rung, source included.
|
||||
func EnabledVariants(list []VariantSpec) []VariantSpec {
|
||||
var out []VariantSpec
|
||||
for _, v := range list {
|
||||
if v.Enabled {
|
||||
out = append(out, v)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// VariantWidth estimates a rung's pixel width for the ABR master playlist.
|
||||
// The packager scales with scale=-2:<height>, so width follows the source
|
||||
// aspect; 16:9 is the right assumption for broadcast content and the only
|
||||
// thing available before the stream has been probed.
|
||||
func VariantWidth(height int) int {
|
||||
if height <= 0 {
|
||||
return 0
|
||||
}
|
||||
w := height * 16 / 9
|
||||
// H.264 needs even dimensions, which is what -2 in the scale filter gives.
|
||||
if w%2 == 1 {
|
||||
w++
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
// BitrateBps parses an ffmpeg bitrate string such as "2800k" into bits per
|
||||
// second, for the BANDWIDTH attribute in the master playlist.
|
||||
func BitrateBps(s string) int {
|
||||
s = strings.TrimSpace(strings.ToLower(s))
|
||||
if s == "" {
|
||||
return 0
|
||||
}
|
||||
mult := 1
|
||||
switch {
|
||||
case strings.HasSuffix(s, "k"):
|
||||
mult, s = 1000, strings.TrimSuffix(s, "k")
|
||||
case strings.HasSuffix(s, "m"):
|
||||
mult, s = 1000000, strings.TrimSuffix(s, "m")
|
||||
}
|
||||
n := 0
|
||||
for _, r := range s {
|
||||
if r < '0' || r > '9' {
|
||||
return 0
|
||||
}
|
||||
n = n*10 + int(r-'0')
|
||||
}
|
||||
return n * mult
|
||||
}
|
||||
|
|
|
|||
|
|
@ -22,11 +22,296 @@ func TestNormalizeVariantsEnsuresFHD(t *testing.T) {
|
|||
|
||||
func TestParseVariantsJSONDefault(t *testing.T) {
|
||||
got := ParseVariantsJSON("")
|
||||
if len(got) != 3 {
|
||||
t.Fatalf("default len=%d", len(got))
|
||||
// The default ladder offers the rungs but turns none of the encoding ones
|
||||
// on, so a new stream costs exactly one pass-through copy.
|
||||
if len(got) != len(DefaultVariants()) {
|
||||
t.Fatalf("default len=%d want %d", len(got), len(DefaultVariants()))
|
||||
}
|
||||
scaled := ScaledVariants(got)
|
||||
if len(scaled) != 0 {
|
||||
t.Fatalf("default scaled=%v", scaled)
|
||||
if scaled := ScaledVariants(got); len(scaled) != 0 {
|
||||
t.Fatalf("default should encode nothing, got %v", scaled)
|
||||
}
|
||||
enabled := EnabledVariants(got)
|
||||
if len(enabled) != 1 || !enabled[0].IsSource() {
|
||||
t.Fatalf("default should enable only the source rung, got %+v", enabled)
|
||||
}
|
||||
}
|
||||
|
||||
// An audio-only rung is height 0, exactly like the source copy. The source
|
||||
// rule must not swallow it, or enabling audio would silently overwrite the
|
||||
// pass-through rung.
|
||||
func TestAudioOnlyRungSurvivesNormalize(t *testing.T) {
|
||||
got := NormalizeVariants([]VariantSpec{
|
||||
{ID: SourceVariantID, Label: "FHD", Enabled: true, Height: 0},
|
||||
{ID: "audio", Label: "Audio", Enabled: true, AudioOnly: true},
|
||||
})
|
||||
var source, audio *VariantSpec
|
||||
for i := range got {
|
||||
switch {
|
||||
case got[i].AudioOnly:
|
||||
audio = &got[i]
|
||||
case got[i].IsSource():
|
||||
source = &got[i]
|
||||
}
|
||||
}
|
||||
if source == nil {
|
||||
t.Fatal("source rung disappeared")
|
||||
}
|
||||
if audio == nil {
|
||||
t.Fatal("audio rung was absorbed into the source rung")
|
||||
}
|
||||
if audio.ID == SourceVariantID {
|
||||
t.Errorf("audio rung must not take the source id, got %q", audio.ID)
|
||||
}
|
||||
if audio.VideoBitrate != "" {
|
||||
t.Errorf("audio rung should carry no video bitrate, got %q", audio.VideoBitrate)
|
||||
}
|
||||
if audio.AudioBitrate == "" {
|
||||
t.Error("audio rung should get a default audio bitrate")
|
||||
}
|
||||
// It needs its own encoder, so it must count as scaled.
|
||||
scaled := ScaledVariants(got)
|
||||
foundAudio := false
|
||||
for _, v := range scaled {
|
||||
if v.AudioOnly {
|
||||
foundAudio = true
|
||||
}
|
||||
}
|
||||
if !foundAudio {
|
||||
t.Error("audio rung should be in ScaledVariants (it needs an encoder)")
|
||||
}
|
||||
}
|
||||
|
||||
// An audio rung sent without an explicit id must not claim the source id.
|
||||
func TestAudioOnlyWithoutIDGetsOwnID(t *testing.T) {
|
||||
got := NormalizeVariants([]VariantSpec{{Enabled: true, AudioOnly: true}})
|
||||
var audio, source int
|
||||
for _, v := range got {
|
||||
if v.AudioOnly {
|
||||
audio++
|
||||
if v.ID != "audio" {
|
||||
t.Errorf("want id audio, got %q", v.ID)
|
||||
}
|
||||
}
|
||||
if v.IsSource() {
|
||||
source++
|
||||
}
|
||||
}
|
||||
if audio != 1 || source != 1 {
|
||||
t.Fatalf("want one audio and one source rung, got audio=%d source=%d (%+v)", audio, source, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVariantDirAndOutputPaths(t *testing.T) {
|
||||
cases := []struct {
|
||||
name, id string
|
||||
height int
|
||||
audio bool
|
||||
format string
|
||||
want string
|
||||
}{
|
||||
// The original mpegts HLS URL must never move.
|
||||
{"rte-one", "fhd", 0, false, FormatHLS, "/hls/rte-one/index.m3u8"},
|
||||
{"rte-one", "hd", 720, false, FormatHLS, "/hls/rte-one-hd/index.m3u8"},
|
||||
{"rte-one", "fhd", 0, false, FormatCMAF, "/hls/rte-one/cmaf/index.m3u8"},
|
||||
{"rte-one", "hd", 720, false, FormatCMAF, "/hls/rte-one-hd/cmaf/index.m3u8"},
|
||||
{"rte-one", "fhd", 0, false, FormatDASH, "/hls/rte-one/dash/index.mpd"},
|
||||
{"rte-one", "fhd", 0, false, FormatTS, "/live/rte-one.ts"},
|
||||
{"rte-one", "hd", 720, false, FormatTS, "/live/rte-one-hd.ts"},
|
||||
{"rte-one", "audio", 0, true, FormatHLS, "/hls/rte-one-audio/index.m3u8"},
|
||||
}
|
||||
for _, c := range cases {
|
||||
if got := OutputPlayPath(c.name, c.id, c.height, c.audio, c.format); got != c.want {
|
||||
t.Errorf("OutputPlayPath(%s,%s,%d,%v,%s) = %q want %q",
|
||||
c.name, c.id, c.height, c.audio, c.format, got, c.want)
|
||||
}
|
||||
}
|
||||
// A stream name containing a dash must keep its own directory.
|
||||
if got := VariantDir("city-news", "fhd", 0, false); got != "city-news" {
|
||||
t.Errorf("source dir = %q", got)
|
||||
}
|
||||
if got := VariantDir("city-news", "hd", 720, false); got != "city-news-hd" {
|
||||
t.Errorf("variant dir = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaultOutputsOnlyHLS(t *testing.T) {
|
||||
got := ParseOutputsJSON("")
|
||||
on := EnabledOutputs(got)
|
||||
if len(on) != 1 || on[0].Format != FormatHLS {
|
||||
t.Fatalf("default outputs should be mpegts HLS only, got %+v", on)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeOutputsKeepsFullSetAndAliases(t *testing.T) {
|
||||
// A client toggling DASH on by id alone should get the whole set back
|
||||
// with DASH enabled and HLS still present.
|
||||
got := NormalizeOutputs([]OutputSpec{
|
||||
{ID: "hls", Format: FormatHLS, Enabled: true},
|
||||
{ID: "dash", Format: "mpd", Enabled: true},
|
||||
{ID: "bogus", Format: "quicktime", Enabled: true},
|
||||
})
|
||||
if len(got) != len(DefaultOutputs()) {
|
||||
t.Fatalf("want the full output set, got %d: %+v", len(got), got)
|
||||
}
|
||||
byFormat := map[string]OutputSpec{}
|
||||
for _, o := range got {
|
||||
byFormat[o.Format] = o
|
||||
}
|
||||
if !byFormat[FormatDASH].Enabled {
|
||||
t.Error("mpd alias should have enabled DASH")
|
||||
}
|
||||
if !byFormat[FormatHLS].Enabled {
|
||||
t.Error("HLS should still be enabled")
|
||||
}
|
||||
if byFormat[FormatCMAF].Enabled {
|
||||
t.Error("CMAF should have stayed off")
|
||||
}
|
||||
for _, o := range got {
|
||||
if o.Label == "" || o.ID == "" {
|
||||
t.Errorf("output missing id/label: %+v", o)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Publishing nothing would make the stream unreachable, so an all-off set
|
||||
// falls back to HLS rather than going dark.
|
||||
func TestNormalizeOutputsNeverPublishesNothing(t *testing.T) {
|
||||
got := NormalizeOutputs([]OutputSpec{
|
||||
{ID: "hls", Format: FormatHLS, Enabled: false},
|
||||
{ID: "dash", Format: FormatDASH, Enabled: false},
|
||||
})
|
||||
if len(EnabledOutputs(got)) == 0 {
|
||||
t.Fatal("an all-off output set should fall back to HLS")
|
||||
}
|
||||
for _, o := range EnabledOutputs(got) {
|
||||
if o.Format != FormatHLS {
|
||||
t.Errorf("fallback should be HLS, got %q", o.Format)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildPublishLinks(t *testing.T) {
|
||||
variants, err := EncodeVariantsJSON([]VariantSpec{
|
||||
{ID: SourceVariantID, Enabled: true, Height: 0},
|
||||
{ID: "hd", Enabled: true, Height: 720},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
outputs, err := EncodeOutputsJSON([]OutputSpec{
|
||||
{ID: "hls", Format: FormatHLS, Enabled: true},
|
||||
{ID: "ts", Format: FormatTS, Enabled: true},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
links := BuildPublishLinks("city-news", variants, outputs)
|
||||
// master + 2 variants x 2 outputs
|
||||
if len(links) != 5 {
|
||||
t.Fatalf("want 5 links, got %d: %+v", len(links), links)
|
||||
}
|
||||
if !links[0].Master || links[0].PlayPath != "/hls/city-news/master.m3u8" {
|
||||
t.Errorf("first link should be the ABR master, got %+v", links[0])
|
||||
}
|
||||
seen := map[string]bool{}
|
||||
for _, l := range links {
|
||||
if l.PlayPath == "" {
|
||||
t.Errorf("link with no path: %+v", l)
|
||||
}
|
||||
if seen[l.PlayPath] {
|
||||
t.Errorf("duplicate link path %q", l.PlayPath)
|
||||
}
|
||||
seen[l.PlayPath] = true
|
||||
}
|
||||
for _, want := range []string{
|
||||
"/hls/city-news/index.m3u8",
|
||||
"/hls/city-news-hd/index.m3u8",
|
||||
"/live/city-news.ts",
|
||||
"/live/city-news-hd.ts",
|
||||
} {
|
||||
if !seen[want] {
|
||||
t.Errorf("missing expected link %q", want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// With a single rung there is nothing to switch between, so no master.
|
||||
func TestBuildPublishLinksNoMasterForSingleRung(t *testing.T) {
|
||||
variants, _ := EncodeVariantsJSON([]VariantSpec{{ID: SourceVariantID, Enabled: true}})
|
||||
outputs, _ := EncodeOutputsJSON(DefaultOutputs())
|
||||
for _, l := range BuildPublishLinks("solo", variants, outputs) {
|
||||
if l.Master {
|
||||
t.Error("a single-rung stream should not advertise an ABR master")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestVariantWidthAndBitrate(t *testing.T) {
|
||||
if got := VariantWidth(720); got != 1280 {
|
||||
t.Errorf("720p width = %d want 1280", got)
|
||||
}
|
||||
if got := VariantWidth(1080); got != 1920 {
|
||||
t.Errorf("1080p width = %d want 1920", got)
|
||||
}
|
||||
if got := VariantWidth(0); got != 0 {
|
||||
t.Errorf("source height should give width 0, got %d", got)
|
||||
}
|
||||
if got := VariantWidth(480); got%2 != 0 {
|
||||
t.Errorf("width must be even for H.264, got %d", got)
|
||||
}
|
||||
for in, want := range map[string]int{
|
||||
"2800k": 2800000, "1200K": 1200000, "5M": 5000000,
|
||||
"": 0, "fast": 0, "900": 900,
|
||||
} {
|
||||
if got := BitrateBps(in); got != want {
|
||||
t.Errorf("BitrateBps(%q) = %d want %d", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidKeyPairs(t *testing.T) {
|
||||
const kid = "0123456789abcdef0123456789abcdef"
|
||||
const key = "fedcba9876543210fedcba9876543210"
|
||||
good := []string{
|
||||
kid + ":" + key,
|
||||
kid + ":" + key + "\n" + kid + ":" + key,
|
||||
// Multi-KID separated by commas and semicolons, as the supervisor
|
||||
// accepts. A single-pair check would reject these, which is why the
|
||||
// agent used to re-capture multi-KID streams forever.
|
||||
kid + ":" + key + "," + kid + ":" + key,
|
||||
kid + ":" + key + ";" + kid + ":" + key,
|
||||
" " + kid + ":" + key + " \n\n",
|
||||
}
|
||||
for _, g := range good {
|
||||
if !ValidKeyPairs(g) {
|
||||
t.Errorf("ValidKeyPairs(%q) = false, want true", g)
|
||||
}
|
||||
}
|
||||
bad := []string{
|
||||
"", " ", "notakey", kid, kid + ":", ":" + key,
|
||||
kid + ":deadbeef",
|
||||
kid + ":" + key + "\nbroken",
|
||||
"zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz:" + key,
|
||||
}
|
||||
for _, b := range bad {
|
||||
if ValidKeyPairs(b) {
|
||||
t.Errorf("ValidKeyPairs(%q) = true, want false", b)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeTags(t *testing.T) {
|
||||
for in, want := range map[string]string{
|
||||
"Council, Sports": "council,sports",
|
||||
"council,council": "council",
|
||||
" Live Events ": "live-events",
|
||||
"": "",
|
||||
",,,": "",
|
||||
"A,b,C": "a,b,c",
|
||||
"Town Hall,town hall": "town-hall",
|
||||
} {
|
||||
if got := normalizeTags(in); got != want {
|
||||
t.Errorf("normalizeTags(%q) = %q want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue