Skip to content

feat(nodepool): node groups, per-node caps, and local transcode fallback control - #126

Merged
Quick104 merged 3 commits into
mainfrom
feat/node-groups-and-caps
Jun 10, 2026
Merged

Quick104 merged 3 commits into
mainfrom
feat/node-groups-and-caps

Conversation

@Quick104

@Quick104 Quick104 commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Closes #93. In distributed deployments, the proxy serving a transcoded stream is picked round-robin with no relationship to the transcode node producing it. Every HLS segment then travels transcode node → proxy → client, and when those nodes sit on different hosts/LAN segments, internal egress is effectively doubled.

What changed

Node grouping. Stream nodes get an optional free-form group label (admin UI + API). Nodes sharing a group are treated as co-located: when a transcode node from group G is selected, the stream is always served by a proxy from G (round-robin when G has several), so transcoded bytes stay on that LAN. A group is only eligible while all of its enabled members are healthy — a sick proxy sidelines the group's transcode nodes rather than letting pinned streams dangle. Ungrouped nodes keep the historical behavior exactly (least-connections transcode pick, global round-robin proxy, soft session affinity).

Unified selection. A new nodepool.Planner (PlanSession) is now the single place transcode/proxy pairs are chosen. It replaces the independent ProxyPool.Pick() / TranscodePool.Acquire() calls at five call sites (native start, audio change, transcode start, jellycompat stream + manifest) and deletes the duplicated soft-affinity pickTranscodeNode copy in jellycompat.

Per-node capacity caps (also from #93). New nullable max_jobs per node — max concurrent transcodes for transcode nodes, max concurrent streams for proxies; empty = unlimited. Admission control combines health-reported job counts with short-lived per-session reservations that stop counting as soon as a fresher health report arrives (or after 90s), bridging the 30s health-check window without any session-teardown bookkeeping. Proxy nodes previously reported no load at all; their health endpoint now returns real stream counts, with HLS sessions tracked via a new idle-expiry Touch mechanism in the session tracker.

Proxy bandwidth caps. Proxy nodes now measure their stream egress — a rolling 60-second average over everything under /stream, counted by a metering middleware — and report it through the health endpoint (visible live in the admin UI). A new nullable max_bandwidth_kbps per proxy ("Max Egress Bandwidth (Mbps)" in the UI) gates admission: a new stream is only routed to a proxy where its expected bitrate (transcode target bitrate, or source bitrate for direct play/remux) fits within the cap. Recently admitted streams are bridged as weighted 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, same as the job cap. Active streams are never interrupted — the cap only gates new admissions.

Local fallback control. New playback.local_transcode_fallback setting (Admin → Settings → Playback, default on = historical behavior). When off, transcode requests fail with 503 instead of falling back to ffmpeg on the API server when no eligible node exists — for admins who never want the API host transcoding. Enforced on both native and Jellyfin-compat paths.

Data race fix. The health checker used to mutate shared *Node structs in place while request paths read them. Health results are now published as immutable node copies swapped in under the pool lock (verified with go test -race).

Notes for review

  • Migration 20260610130619_node_groups_and_caps.sql adds four nullable/defaulted columns; existing deployments are unaffected (NULL group = ungrouped, NULL caps = unlimited). Not yet applied to the shared dev DB.
  • Clearing semantics: empty-string group and caps <= 0 reset to NULL — avoids the "cap 0 = never selected" foot-gun and keeps the update API simple.
  • Bandwidth admission is deliberately conservative during the 60s bridge window (measured egress + full reservation can briefly double-count a ramping stream); the safe direction for an admission control.
  • The egress meter wraps /stream response writers, which bypasses the sendfile fast path for direct play through a proxy — a deliberate trade for accurate measurement.
  • Stream URLs, token claims, and client-facing API shapes are unchanged — no Android/Apple client follow-up needed; only the admin web UI changed.
  • A group whose proxies are all at cap (jobs or bandwidth) is treated as full: its transcode nodes are skipped (a group's capacity is bounded by its proxies).
  • Known pre-existing issue left out of scope: remux sessions start on /stream/transcode/ but switch to /stream/remux/ after an audio change; tracked separately.
  • Verified: go build ./..., full go test ./... (-race on changed packages; 19 planner tests + egress meter tests), golangci-lint clean for changed lines, pnpm run build, ESLint/Prettier, make verify-local-paths.

AI-use disclosure

Implemented with Claude Code (architecture explored, designed, and reviewed via multi-agent passes).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Node grouping and per-node concurrency/bandwidth caps plus an intelligent session planner for proxy/transcode placement.
  • Improvements

    • Admin UI: view/edit group, max streams and bandwidth; health now reports egress bandwidth; active stream tracking improved.
    • Player warms connections to stream origins.
    • New setting: Local Transcode Fallback toggle.
  • Behavior

    • Streams may be routed via remote nodes; transcode-required requests can return 503 when remote transcode is disallowed.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@coderabbitai

coderabbitai Bot commented Jun 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: d55425a9-6fa4-46c7-9350-fdef61bdf1da

📥 Commits

Reviewing files that changed from the base of the PR and between e7de2bb64ed2f65541a7802befddbadbd62e1617 and a2a66c3.

📒 Files selected for processing (26)
  • cmd/silo/main.go
  • internal/api/handlers/nodes.go
  • internal/api/handlers/playback.go
  • internal/api/handlers/playback_test.go
  • internal/api/router.go
  • internal/jellycompat/handlers_playback.go
  • internal/jellycompat/router.go
  • internal/jellycompat/server.go
  • internal/jellycompat/streams.go
  • internal/nodepool/health.go
  • internal/nodepool/planner.go
  • internal/nodepool/planner_test.go
  • internal/nodepool/proxy_pool.go
  • internal/nodepool/repository.go
  • internal/nodepool/transcode_pool.go
  • internal/nodesessions/tracker.go
  • internal/proxy/egress.go
  • internal/proxy/egress_test.go
  • internal/proxy/server.go
  • internal/transcodenode/server.go
  • migrations/sql/20260610130619_node_groups_and_caps.sql
  • web/src/api/types.ts
  • web/src/pages/AdminNodes.tsx
  • web/src/pages/admin-settings/PlaybackSettings.tsx
  • web/src/player/components/VideoPlayer.tsx
  • web/src/player/stream-url.ts
🚧 Files skipped from review as they are similar to previous changes (24)
  • internal/jellycompat/server.go
  • web/src/pages/admin-settings/PlaybackSettings.tsx
  • web/src/player/stream-url.ts
  • web/src/player/components/VideoPlayer.tsx
  • internal/proxy/egress_test.go
  • internal/api/handlers/playback_test.go
  • migrations/sql/20260610130619_node_groups_and_caps.sql
  • internal/nodepool/proxy_pool.go
  • internal/nodepool/transcode_pool.go
  • internal/proxy/egress.go
  • cmd/silo/main.go
  • web/src/api/types.ts
  • internal/jellycompat/router.go
  • internal/nodesessions/tracker.go
  • internal/nodepool/health.go
  • internal/api/router.go
  • internal/api/handlers/nodes.go
  • internal/proxy/server.go
  • internal/jellycompat/handlers_playback.go
  • web/src/pages/AdminNodes.tsx
  • internal/nodepool/planner.go
  • internal/jellycompat/streams.go
  • internal/nodepool/planner_test.go
  • internal/api/handlers/playback.go

📝 Walkthrough

Walkthrough

This PR introduces distributed transcode node planning with group-aware resource allocation and per-node capacity limits. A new Planner assigns proxy and transcode nodes to playback sessions based on group affinity, job load, and soft-affinity re-planning. Node configuration now supports optional grouping and max-jobs limits, health checks use atomic callbacks, and the admin UI exposes group and capacity management.

Changes

Distributed Transcode Planning System

Layer / File(s) Summary
Node Model & Persistence with Grouping and Capacity
internal/nodepool/repository.go, migrations/sql/20260610130619_node_groups_and_caps.sql, web/src/api/types.ts
Node struct gains optional Group and MaxJobs fields; repository Create and Update now persist these via node_group and max_jobs columns with SQL NULL for unset values; web DTO types (StreamNode, CreateNodeRequest, UpdateNodeRequest) reflect the new fields.
Pool Health Updates with Atomic Callbacks
internal/nodepool/proxy_pool.go, internal/nodepool/transcode_pool.go, internal/nodepool/health.go
ProxyPool.ApplyHealth and TranscodePool.ApplyHealth methods update node health under write locks; health checker refactored to publish check results via these callbacks instead of direct mutation, ensuring safe concurrent updates.
Session Planner Core Implementation
internal/nodepool/planner.go, internal/nodepool/planner_test.go
New Planner implements session-aware node assignment with group affinity (co-locating transcode/proxy within groups), capacity awareness (tracking active jobs + reservations per node), soft-affinity re-planning (keeping current transcode unless better candidate is ≥2 jobs lighter), and automatic reservation expiry. Comprehensive test suite covers 15 scenarios including group degradation, capacity gating, and fallback behavior.
API Playback Handler Integration
internal/api/handlers/playback.go, internal/api/router.go, internal/api/handlers/playback_test.go
PlaybackHandler now uses NodePlanner instead of direct pool access; removed exported ProxyPicker/TranscodeAcquirer interfaces and PickTranscodeNode method; all playback paths (StartPlayback, ChangeAudioTrack, StartTranscode) now call PlanSession; added 503 response when distributed mode active but local fallback disabled; router wires deps.NodePlanner to handler.
JellyCompat Handler & Stream Integration
internal/jellycompat/server.go, internal/jellycompat/router.go, internal/jellycompat/handlers_playback.go, internal/jellycompat/streams.go
JellyCompat PlaybackHandler refactored to use NodePlanner instead of ProxyPool/TranscodePool; HandleVideoStream and HandleMasterManifest now plan sessions and route through planned proxy/transcode nodes; added local-fallback policy check returning 503 when disabled; buildProxyRedirectURL accepts explicit proxyNode parameter.
Ephemeral Session Tracking & Health Metrics
internal/nodesessions/tracker.go, internal/proxy/server.go
Tracker adds ephemeral session map (touched) tracking last-activity time for transcode HLS streams; Touch method records/refreshes ephemeral activity and on-first-touch writes to Redis; health endpoint now returns active_jobs from tracker.ActiveCount(); transcode manifest/segment handlers call touchTranscodeSession to keep HLS activity in active stream count.
Application Startup & Planner Initialization
cmd/silo/main.go
NodePlanner created from proxy/transcode pools during integrated/API startup and wired into both API and Jellyfin-compat server dependencies, replacing prior direct pool-based configuration.
Admin UI for Node Groups and Capacity Configuration
web/src/pages/AdminNodes.tsx, web/src/pages/admin-settings/PlaybackSettings.tsx, web/src/api/types.ts
AdminNodes table adds "Group" column with per-node badges and changes jobs cell to show active_jobs plus optional max_jobs limit. NodeForm adds optional group text input and maxJobs numeric input (labels vary by node type). Update mutations now send full fields object including group/max_jobs. Proxy section enables job display. PlaybackSettings adds "Local Transcode Fallback" toggle for playback.local_transcode_fallback policy setting.

🎯 4 (Complex) | ⏱️ ~60 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 26.32% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'feat(nodepool): node groups, per-node caps, and local transcode fallback control' accurately and concisely summarizes the main changes: node grouping (co-location), per-node capacity caps, and a new local transcode fallback setting.
Linked Issues check ✅ Passed All objectives from issue #93 are addressed: node grouping enables co-located transcode/proxy selection, per-node max_jobs caps implement load-aware admission control, proxy bandwidth caps with max_bandwidth_kbps prevent saturation, and machines can now act as both transcode and proxy nodes.
Out of Scope Changes check ✅ Passed All changes directly support the linked objectives: node grouping, per-node caps, bandwidth metering, planner logic, health tracking, session tracking improvements, and UI additions are all in scope. Stream-start latency optimizations (preconnect, async session tracking, transport tuning) align with stated goals and lack concerning scope creep.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/node-groups-and-caps

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
internal/jellycompat/streams.go (1)

198-245: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Validate the distributed route before creating sessions or remote jobs.

This block creates side effects before it proves the distributed plan is usable. If PlanSession yields no remote node and local fallback is disabled, ensureUpstreamPlayback has already created an upstream transcode session that you return 503 from without cleaning up. If PlanSession yields a transcode node but no proxy node, startRemoteTranscode can succeed and the later redirect signing fails with 500, orphaning the remote job. Check that the plan is fully usable before starting work, or explicitly roll back these failure paths.

🧹 Nitpick comments (1)
internal/proxy/server.go (1)

171-183: 💤 Low value

Consider adding a nil check for defensive consistency.

handleHealth() defensively checks s.tracker != nil before calling methods, but touchTranscodeSession() does not. While the existing handlers (handleDirectPlay, handleRemux) also assume tracker is non-nil (so this isn't a regression), adding a guard here would be consistent with handleHealth() and protect against future nil-tracker scenarios.

🛡️ Optional defensive guard
 func (s *Server) touchTranscodeSession(r *http.Request, claims *streamtoken.Claims) {
+	if s.tracker == nil {
+		return
+	}
 	s.tracker.Touch(r.Context(), nodesessions.SessionInfo{
 		SessionID: claims.SessionID,
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/proxy/server.go` around lines 171 - 183, Add a defensive nil check
in touchTranscodeSession so it mirrors handleHealth: if s.tracker is nil, return
early and do not call s.tracker.Touch; otherwise continue to call
s.tracker.Touch with the nodesessions.SessionInfo (SessionID from
claims.SessionID, NodeURL/NodeName from
s.tracker.NodeURL()/s.tracker.NodeName(), Type "transcode" and StartedAt
time.Now().UTC().Format(time.RFC3339)). This ensures null-safety for the tracker
before invoking Touch.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@internal/jellycompat/streams.go`:
- Around line 100-103: The planner is being keyed with the transient
UpstreamSessionID, causing stale reservations; change the PlanSession call to
use the stable compat session ID by passing playSession.ID (i.e., call
h.NodePlanner.PlanSession(playSession.ID, ...)) instead of
playSession.UpstreamSessionID, and make the same replacement for the other
occurrence referenced (the second PlanSession call at the other location).
Ensure the rest of the parameters (empty string, false) remain unchanged and
that buildProxyRedirectURL still receives playSession.UpstreamSessionID where
appropriate.

---

Nitpick comments:
In `@internal/proxy/server.go`:
- Around line 171-183: Add a defensive nil check in touchTranscodeSession so it
mirrors handleHealth: if s.tracker is nil, return early and do not call
s.tracker.Touch; otherwise continue to call s.tracker.Touch with the
nodesessions.SessionInfo (SessionID from claims.SessionID, NodeURL/NodeName from
s.tracker.NodeURL()/s.tracker.NodeName(), Type "transcode" and StartedAt
time.Now().UTC().Format(time.RFC3339)). This ensures null-safety for the tracker
before invoking Touch.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro Plus

Run ID: a384b800-c1fe-4db8-90c6-0ceeb73721db

📥 Commits

Reviewing files that changed from the base of the PR and between 56d7f63 and 8585daa5baf4eabb0d148ffaca932d9a2d6502c8.

📒 Files selected for processing (20)
  • cmd/silo/main.go
  • internal/api/handlers/playback.go
  • internal/api/handlers/playback_test.go
  • internal/api/router.go
  • internal/jellycompat/handlers_playback.go
  • internal/jellycompat/router.go
  • internal/jellycompat/server.go
  • internal/jellycompat/streams.go
  • internal/nodepool/health.go
  • internal/nodepool/planner.go
  • internal/nodepool/planner_test.go
  • internal/nodepool/proxy_pool.go
  • internal/nodepool/repository.go
  • internal/nodepool/transcode_pool.go
  • internal/nodesessions/tracker.go
  • internal/proxy/server.go
  • migrations/sql/20260610130619_node_groups_and_caps.sql
  • web/src/api/types.ts
  • web/src/pages/AdminNodes.tsx
  • web/src/pages/admin-settings/PlaybackSettings.tsx

Comment on lines +100 to +103
if h.NodePlanner != nil && h.JWTSecret != "" {
plan := h.NodePlanner.PlanSession(playSession.UpstreamSessionID, "", false)
if redirectURL, redirectErr := h.buildProxyRedirectURL(playSession.ID, playSession.UpstreamSessionID, method, file, *source, "", seekSeconds, plan.ProxyNode); redirectErr == nil {
http.Redirect(w, r, redirectURL, http.StatusTemporaryRedirect)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Use the compat play-session ID as the planner key.

PlanSession only replaces reservations when the same session ID is reused, but playSession.UpstreamSessionID is regenerated whenever ensureUpstreamPlayback switches methods. That leaves the old reservation behind until expiry, so direct→transcode transitions can double-count proxy/transcode capacity and incorrectly reject later sessions. Pass the stable compat session ID (playSession.ID) here instead.

Also applies to: 206-206

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@internal/jellycompat/streams.go` around lines 100 - 103, The planner is being
keyed with the transient UpstreamSessionID, causing stale reservations; change
the PlanSession call to use the stable compat session ID by passing
playSession.ID (i.e., call h.NodePlanner.PlanSession(playSession.ID, ...))
instead of playSession.UpstreamSessionID, and make the same replacement for the
other occurrence referenced (the second PlanSession call at the other location).
Ensure the rest of the parameters (empty string, false) remain unchanged and
that buildProxyRedirectURL still receives playSession.UpstreamSessionID where
appropriate.

@Quick104

Copy link
Copy Markdown
Contributor Author

Added: node-mode stream-start latency improvements (e7de2bb6)

Traced the distributed startup waterfall (client → API → transcode node → proxy) and trimmed the safe overhead that integrated mode doesn't pay:

  • Player preconnect — the web player now warms DNS/TCP/TLS to the proxy origin the moment /playback/start returns, overlapping the handshakes with the transcode dispatch instead of paying them at the first manifest fetch (easily 200–600ms on a WAN proxy).
  • Faster 202 from the transcode node — 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. The synchronous os.RemoveAll could add seconds to quality switches on slow disks while the client sat waiting.
  • Proxy→node transport tuning — larger idle-connection pool (the Go default of 2 idle conns per host caused churn/re-handshakes with many viewers on one proxy→node pair) and a 60s response-header timeout, so a hung transcode node can no longer hang client requests indefinitely.
  • jellycompat dispatch timeout — startRemoteTranscode now has the same 10s bound as the native path; an unreachable node previously hung the compat manifest request until the OS gave up.

Deliberately not done here: making the API→node /transcode/start dispatch asynchronous (it would remove a full round trip + ffmpeg fork from the client's critical path, but changes failure semantics — a down node would surface as manifest errors instead of a clean 502 at start). Worth its own design discussion.

🤖 Generated with Claude Code

Quick104 and others added 3 commits June 10, 2026 15:00
…ack 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 <[email protected]>
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 <[email protected]>
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 <[email protected]>
@Quick104
Quick104 force-pushed the feat/node-groups-and-caps branch from e7de2bb to a2a66c3 Compare June 10, 2026 19:03
@Quick104
Quick104 merged commit 762ca23 into main Jun 10, 2026
1 check passed
@Quick104
Quick104 deleted the feat/node-groups-and-caps branch June 10, 2026 21:18
Quick104 added a commit that referenced this pull request Jun 11, 2026
…ack 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Quick104 added a commit that referenced this pull request Jun 17, 2026
…ack 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 <[email protected]>

* 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 <[email protected]>

* 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 <[email protected]>

---------

Co-authored-by: Claude Fable 5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat(distributed): Enable egress from transcode workers

1 participant