Files
silo-server/internal/nodesessions/tracker.go
T
7958f0bbf0 feat(nodepool): node groups, per-node caps, and local transcode fallback control (#126)
* feat(nodepool): node groups, per-node caps, and local transcode fallback control

Group co-located transcode and proxy nodes so transcoded streams are
served by a proxy on the same host/LAN instead of bouncing across the
internal network (fixes #93):

- New nodepool.Planner is the single selection entry point: it picks the
  transcode node and its group's proxy together (round-robin within the
  group), replacing the independent ProxyPool.Pick/TranscodePool.Acquire
  calls scattered across the native and jellycompat handlers, and absorbs
  the duplicated soft-affinity pick logic.
- A group is only eligible while all of its enabled members are healthy;
  ungrouped nodes keep the historical behavior.
- New per-node max_jobs cap (transcodes for transcode nodes, streams for
  proxies; NULL = unlimited), enforced via health-reported job counts
  plus short-lived reservations that expire once fresher health data
  arrives. Proxy health now reports real stream counts, including HLS
  sessions via idle-expiry tracking.
- New playback.local_transcode_fallback setting (default on) lets admins
  refuse API-server transcoding when no eligible node exists.
- Health checks now publish updated node copies under the pool lock
  instead of mutating shared structs in place, fixing a data race.
- Admin UI: group + cap fields on the node form, group/cap columns, and
  the new fallback toggle in playback settings.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* feat(nodepool): proxy bandwidth measurement and egress caps

Proxy nodes now measure their stream egress (rolling 60s average over
everything under /stream) and report it via the health endpoint. A new
per-proxy max_bandwidth_kbps cap lets the planner route new streams away
from saturated proxies:

- Admission combines the measured egress with the estimated bitrate of
  the new stream (transcode target bitrate, or source bitrate for direct
  play/remux) so a stream is only admitted where it fits.
- Recently admitted streams are bridged as bandwidth reservations for the
  meter window, since the rolling average only converges on a new
  stream's rate gradually.
- A group whose proxies lack bandwidth headroom is treated as full: its
  transcode nodes are skipped, same as the job cap.
- Admin UI: per-proxy "Max Egress Bandwidth (Mbps)" field and a live
  egress column; manual health checks return the measured rate.

Active streams are never interrupted - the cap only gates new admissions.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* perf(playback): trim node-mode time-to-stream-start

Distributed playback paid several avoidable costs before the first frame
that integrated mode doesn't have. This trims the safe ones:

- Web player preconnects to the stream origin (the proxy node) as soon as
  /playback/start returns, overlapping DNS/TCP/TLS handshakes with the
  transcode dispatch instead of paying them at the first manifest fetch.
- The transcode node no longer blocks its 202 on monitoring work: the
  Redis session-track write moves off the request path, and a replaced
  session's segment directory is renamed aside and deleted in the
  background instead of synchronously (RemoveAll of a long session can
  take seconds on slow disks during quality switches).
- The proxy's node-facing HTTP client gets a tuned transport: a larger
  idle-connection pool (Go's default of 2 per host causes connection
  churn and TLS re-handshakes when many viewers stream through one
  proxy->node pair) and a response-header timeout so a hung transcode
  node can no longer hang client requests indefinitely.
- jellycompat's remote transcode dispatch gains the same 10s timeout the
  native path has had; an unreachable node previously hung the compat
  manifest request until the OS gave up.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-10 17:18:18 -04:00

249 lines
6.2 KiB
Go

package nodesessions
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"log/slog"
"sync"
"time"
"github.com/redis/go-redis/v9"
)
const (
keyPrefix = "silo:sessions:"
sessionTTL = 60 * time.Second
refreshInt = 30 * time.Second
)
// SessionInfo represents an active streaming session stored in Redis.
type SessionInfo struct {
SessionID string `json:"session_id"`
NodeURL string `json:"node_url"`
NodeName string `json:"node_name"`
UserID string `json:"user_id,omitempty"`
MediaItemID string `json:"media_item_id,omitempty"`
MediaTitle string `json:"media_title,omitempty"`
Type string `json:"type"` // "direct_play", "remux", "transcode"
CodecVideo string `json:"codec_video,omitempty"`
CodecAudio string `json:"codec_audio,omitempty"`
Resolution string `json:"resolution,omitempty"`
HWAccel string `json:"hw_accel,omitempty"`
StartedAt string `json:"started_at"`
}
// Tracker manages session lifecycle in Redis for a single node.
type Tracker struct {
rdb *redis.Client
nodeURL string
nodeName string
nodeType string
nodeHash string // first 8 chars of SHA-256 of nodeURL
mu sync.Mutex
sessions map[string]struct{} // set of active session IDs
touched map[string]time.Time // ephemeral sessions by last-activity time
}
// NewTracker creates a session tracker for the given node.
// rdb may be nil, in which case all operations are no-ops.
func NewTracker(rdb *redis.Client, nodeURL, nodeName, nodeType string) *Tracker {
h := sha256.Sum256([]byte(nodeURL))
return &Tracker{
rdb: rdb,
nodeURL: nodeURL,
nodeName: nodeName,
nodeType: nodeType,
nodeHash: hex.EncodeToString(h[:4]), // 8 hex chars
sessions: make(map[string]struct{}),
touched: make(map[string]time.Time),
}
}
// redisKey returns the full Redis key for a session.
func (tr *Tracker) redisKey(sessionID string) string {
return keyPrefix + tr.nodeHash + ":" + sessionID
}
// NodeHash returns the node's hash prefix used in Redis keys.
func (tr *Tracker) NodeHash() string {
return tr.nodeHash
}
// NodeURL returns the node's URL.
func (tr *Tracker) NodeURL() string {
return tr.nodeURL
}
// NodeName returns the node's display name.
func (tr *Tracker) NodeName() string {
return tr.nodeName
}
// ActiveCount returns the number of active sessions tracked by this node,
// including ephemeral sessions touched within the session TTL.
func (tr *Tracker) ActiveCount() int {
tr.mu.Lock()
defer tr.mu.Unlock()
now := time.Now()
count := len(tr.sessions)
for id, last := range tr.touched {
if _, dup := tr.sessions[id]; dup {
continue
}
if now.Sub(last) <= sessionTTL {
count++
}
}
return count
}
// Track registers an active session in Redis with a TTL.
func (tr *Tracker) Track(ctx context.Context, info SessionInfo) {
if tr.rdb == nil {
return
}
data, err := json.Marshal(info)
if err != nil {
slog.Debug("session track marshal failed", "error", err)
return
}
key := tr.redisKey(info.SessionID)
if err := tr.rdb.Set(ctx, key, data, sessionTTL).Err(); err != nil {
slog.Debug("session track set failed", "error", err, "session", info.SessionID)
return
}
tr.mu.Lock()
tr.sessions[info.SessionID] = struct{}{}
tr.mu.Unlock()
}
// Touch registers or refreshes an ephemeral session that has no explicit end,
// such as HLS manifest/segment fetches flowing through a proxy. The session is
// written to Redis on first touch and drops out of the active count after
// sessionTTL without further touches (pruned by the refresh loop).
func (tr *Tracker) Touch(ctx context.Context, info SessionInfo) {
if tr.rdb == nil {
return
}
tr.mu.Lock()
_, known := tr.touched[info.SessionID]
tr.touched[info.SessionID] = time.Now()
tr.mu.Unlock()
if known {
return
}
data, err := json.Marshal(info)
if err != nil {
slog.Debug("session touch marshal failed", "error", err)
return
}
if err := tr.rdb.Set(ctx, tr.redisKey(info.SessionID), data, sessionTTL).Err(); err != nil {
slog.Debug("session touch set failed", "error", err, "session", info.SessionID)
}
}
// Remove deletes a session from Redis and the in-memory set.
func (tr *Tracker) Remove(ctx context.Context, sessionID string) {
if tr.rdb == nil {
return
}
tr.mu.Lock()
delete(tr.sessions, sessionID)
delete(tr.touched, sessionID)
tr.mu.Unlock()
if err := tr.rdb.Del(ctx, tr.redisKey(sessionID)).Err(); err != nil {
slog.Debug("session remove failed", "error", err, "session", sessionID)
}
}
// Cleanup deletes all session keys for this node. Called on graceful shutdown.
func (tr *Tracker) Cleanup(ctx context.Context) {
if tr.rdb == nil {
return
}
tr.mu.Lock()
ids := make([]string, 0, len(tr.sessions)+len(tr.touched))
for id := range tr.sessions {
ids = append(ids, id)
}
for id := range tr.touched {
if _, dup := tr.sessions[id]; !dup {
ids = append(ids, id)
}
}
tr.sessions = make(map[string]struct{})
tr.touched = make(map[string]time.Time)
tr.mu.Unlock()
if len(ids) == 0 {
return
}
pipe := tr.rdb.Pipeline()
for _, id := range ids {
pipe.Del(ctx, tr.redisKey(id))
}
if _, err := pipe.Exec(ctx); err != nil {
slog.Debug("session cleanup pipeline failed", "error", err)
}
}
// StartRefresh starts a background goroutine that refreshes TTLs for all
// active sessions every 30 seconds. Stops when ctx is cancelled.
func (tr *Tracker) StartRefresh(ctx context.Context) {
if tr.rdb == nil {
return
}
go func() {
ticker := time.NewTicker(refreshInt)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
tr.refreshAll(ctx)
}
}
}()
}
func (tr *Tracker) refreshAll(ctx context.Context) {
now := time.Now()
tr.mu.Lock()
ids := make([]string, 0, len(tr.sessions)+len(tr.touched))
for id := range tr.sessions {
ids = append(ids, id)
}
for id, last := range tr.touched {
if now.Sub(last) > sessionTTL {
// Idle ephemeral session: stop refreshing and let the Redis
// key expire on its own.
delete(tr.touched, id)
continue
}
if _, dup := tr.sessions[id]; !dup {
ids = append(ids, id)
}
}
tr.mu.Unlock()
if len(ids) == 0 {
return
}
pipe := tr.rdb.Pipeline()
for _, id := range ids {
pipe.Expire(ctx, tr.redisKey(id), sessionTTL)
}
if _, err := pipe.Exec(ctx); err != nil {
slog.Debug("session refresh pipeline failed", "error", err)
}
}