Skip to content
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
90e782e
perf(playback): cut direct-play, remux, and transcode stream startup …
Quick104 Dec 4, 2026
b01738b
Merge remote-tracking branch 'origin/main' into perf/stream-start-spe…
Quick104 Dec 5, 2026
9a81ee1
fix(playback): keep shared capability fetches and start replays correct
Quick104 Dec 6, 2026
d523ab0
fix(playback): keep fresh transcodes at full quality and probe packet…
Quick104 Dec 6, 2026
472b697
fix(nodes): cache a capability snapshot only for the configuration it…
Quick104 Dec 6, 2026
1f42f40
fix(playback): negotiate gzip playlists as other responses do
Quick104 Dec 6, 2026
c508a69
refactor(tonemap): drop the unused vaapiFilter
Quick104 Dec 6, 2026
954bbb1
fix(web): settle codec detection and seed capabilities under the play…
Quick104 Dec 6, 2026
4273991
fix(web): reconcile markers on the first player connect again
Quick104 Dec 6, 2026
6310659
fix(web): keep the transport when Play reopens the title already loaded
Quick104 Dec 6, 2026
d775864
perf(web): prefetch watch detail on Play intent and probe the decoder…
Quick104 Dec 6, 2026
9e8d751
fix(nodes): rebuild an unsettled capability snapshot within a minute
Quick104 Dec 6, 2026
58bcb02
fix(playback): return a failed attempt lookup without waiting for the…
Quick104 Dec 6, 2026
69a918e
refactor(playback): spell out the remux fragment duration
Quick104 Dec 6, 2026
e96c17c
test(web): mock the idle scheduler in the signed-in boot test
Quick104 Dec 6, 2026
711d962
fix(playback): keep a two-segment lead for fresh CPU encodes
Quick104 Dec 6, 2026
28a7167
fix(playback): leave an abandoned deny lookup out of the cache
Quick104 Dec 6, 2026
5a52322
fix(playback): reuse a capability answer that lands just before a sha…
Quick104 Dec 6, 2026
8675e3f
fix(playback): stop the speculative start reads when a start returns …
Quick104 Dec 6, 2026
cb3496f
fix(nodes): never serve a discarded capability build, and rebuild whe…
Quick104 Dec 6, 2026
bcb8510
fix(nodes): back off a repeating unsettled snapshot and count a faile…
Quick104 Dec 6, 2026
71b0916
fix(playback): stop the speculative direct-state read on an early sta…
Quick104 Dec 6, 2026
1a48766
refactor(playback): reuse the hardware backend check and fold the ton…
Quick104 Dec 6, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions docs/architecture/worker-http-protocol.md
Original file line number Diff line number Diff line change
Expand Up @@ -628,6 +628,18 @@ the node with GET; it rewrites a playlist it re-tokenizes and recomputes its
`Content-Length`. Segment routes take GET only, and remux HEAD is still
forwarded as HEAD.

Playlists of 1 KiB or more are gzipped when the request's `Accept-Encoding`
admits gzip (negotiated as the API's response compressor negotiates), with
`Content-Encoding: gzip`, `Vary: Accept-Encoding`, and a `Content-Length` that
counts the encoded bytes; otherwise they go out as identity with their exact
length. Every writer (the API manifest route, the API relay's rewrite, and the
node) holds the whole playlist, so a playlist never goes out chunked. Relays
pass the viewer's preference upstream (`gzip` or `identity`) instead of letting
Go's transport add its own, because a transport that adds `gzip` itself also
decodes the answer and drops its length. The rewrite asks the node for
identity, since it reads the body. A proxy or API relay older than its node
still lets Go's transport add `gzip`, so upgrade relays before nodes.

The proxy `/stream/v3` family remains a separate header-authenticated protocol.
Each request requires an access JWT, a live login session and a stored grant owned
by the same account, plus the committed egress and endpoint family. API keys,
Expand Down
20 changes: 19 additions & 1 deletion internal/access/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ import "context"

type contextKey string

const scopeKey contextKey = "access_scope"
const (
scopeKey contextKey = "access_scope"
resolvedPolicyKey contextKey = "access_resolved_user_policy"
)

// SetScope stores a resolved access scope in context.
func SetScope(ctx context.Context, scope Scope) context.Context {
Expand All @@ -16,3 +19,18 @@ func GetScope(ctx context.Context) (Scope, bool) {
scope, ok := ctx.Value(scopeKey).(Scope)
return scope, ok
}

// SetResolvedUserPolicy stores the request's resolved account policy in context.
func SetResolvedUserPolicy(ctx context.Context, policy ResolvedUserPolicy) context.Context {
return context.WithValue(ctx, resolvedPolicyKey, policy)
}

// GetResolvedUserPolicy retrieves the request's resolved account policy for
// userID if viewer access resolution already loaded it on this request.
func GetResolvedUserPolicy(ctx context.Context, userID int) (EffectiveUserPolicy, bool) {
resolved, ok := ctx.Value(resolvedPolicyKey).(ResolvedUserPolicy)
if !ok || !resolved.Resolved || resolved.UserID != userID {
return EffectiveUserPolicy{}, false
}
return resolved.Policy, true
}
93 changes: 76 additions & 17 deletions internal/access/resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"sort"
"sync"

"github.com/Silo-Server/silo-server/internal/models"
"github.com/Silo-Server/silo-server/internal/settingsresolve"
Expand Down Expand Up @@ -76,15 +77,79 @@ func NewResolver(users UserRepository, storeFactory userstore.UserStoreProvider,

// Resolve computes the effective viewer scope for the request.
func (r *Resolver) Resolve(ctx context.Context, input ResolveInput) (Scope, error) {
user, err := r.users.GetByID(ctx, input.UserID)
if err != nil {
return Scope{}, fmt.Errorf("loading user %d: %w", input.UserID, err)
// Overlap independent account/policy reads with user-store/profile/preference
// reads while preserving exact error precedence.
var (
user *models.User
userErr error
effective EffectiveUserPolicy
effectiveErr error
allowUnrated bool
store userstore.UserStore
storeErr error
preferences ViewerPreferences
profile *userstore.Profile
profileErr error
outer sync.WaitGroup
)
outer.Add(1)
go func() {
defer outer.Done()
user, userErr = r.users.GetByID(ctx, input.UserID)
if userErr != nil {
return
}
effective, effectiveErr = EffectivePolicyForUser(ctx, user, r.groups)
}()
if r.unrated != nil {
outer.Add(1)
go func() {
defer outer.Done()
allowUnrated = r.unrated.AllowUnratedContent(ctx)
}()
}
if r.storeFactory != nil {
outer.Add(1)
go func() {
defer outer.Done()
store, storeErr = r.storeFactory.ForUser(ctx, input.UserID)
if storeErr != nil || store == nil {
return
}
var inner sync.WaitGroup
if !input.SkipViewerPreferences {
inner.Add(1)
go func() {
defer inner.Done()
preferences = ResolveViewerPreferences(ctx, store, r.defaults, input.ProfileID)
}()
}
if input.ProfileID != "" {
inner.Add(1)
go func() {
defer inner.Done()
profile, profileErr = store.GetProfile(ctx, input.ProfileID)
}()
}
inner.Wait()
}()
}
effective, err := EffectivePolicyForUser(ctx, user, r.groups)
if err != nil {
return Scope{}, fmt.Errorf("loading access group policy for user %d: %w", input.UserID, err)
outer.Wait()

if userErr != nil {
return Scope{}, fmt.Errorf("loading user %d: %w", input.UserID, userErr)
}
if effectiveErr != nil {
return Scope{}, fmt.Errorf("loading access group policy for user %d: %w", input.UserID, effectiveErr)
}

if input.EffectivePolicyOut != nil {
*input.EffectivePolicyOut = ResolvedUserPolicy{
UserID: user.ID,
Policy: effective,
Resolved: true,
}
}
scope := Scope{
UserID: user.ID,
ProfileID: input.ProfileID,
Expand All @@ -95,22 +160,16 @@ func (r *Resolver) Resolve(ctx context.Context, input ResolveInput) (Scope, erro
MaxLocalStreamBitrateKbps: effective.MaxLocalStreamBitrateKbps,
PolicyRevision: user.AccessPolicyRevision,
ProfileVerified: input.ProfileID == "",
}
if r.unrated != nil {
scope.AllowUnratedContent = r.unrated.AllowUnratedContent(ctx)
AllowUnratedContent: allowUnrated,
}

store, err := r.storeFactory.ForUser(ctx, input.UserID)
if err != nil {
return Scope{}, fmt.Errorf("opening user store for %d: %w", input.UserID, err)
if storeErr != nil {
return Scope{}, fmt.Errorf("opening user store for %d: %w", input.UserID, storeErr)
}

preferences := ResolveViewerPreferences(ctx, store, r.defaults, input.ProfileID)
var profile *userstore.Profile
if input.ProfileID != "" {
profile, err = store.GetProfile(ctx, input.ProfileID)
if err != nil {
return Scope{}, fmt.Errorf("loading profile %s: %w", input.ProfileID, err)
if profileErr != nil {
return Scope{}, fmt.Errorf("loading profile %s: %w", input.ProfileID, profileErr)
}
if profile == nil {
return Scope{}, ErrProfileNotFound
Expand Down
16 changes: 16 additions & 0 deletions internal/access/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,6 +164,22 @@ type ResolveInput struct {
// Reading another profile's shared personal collection uses it: the
// owner's browsing preference does not limit what the collection shows.
ContentAccessOnly bool
// SkipViewerPreferences omits browsing-only viewer preferences (Next Up,
// card availability, metadata language, disabled library filters) on
// routes that only serve bytes for an already-authorized playback session.
SkipViewerPreferences bool
// EffectivePolicyOut, when non-nil, receives the resolved EffectiveUserPolicy
// so downstream request handlers (e.g. playback admission limits) can reuse
// it without repeating the user and access-group DB queries.
EffectivePolicyOut *ResolvedUserPolicy
}

// ResolvedUserPolicy carries the account-level EffectiveUserPolicy computed
// during viewer access resolution for reuse within the same request.
type ResolvedUserPolicy struct {
UserID int
Policy EffectiveUserPolicy
Resolved bool
}

// ProfileTokenClaims are the claims embedded in a verified profile token.
Expand Down
35 changes: 17 additions & 18 deletions internal/api/handlers/playback.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import (

"github.com/go-chi/chi/v5"
"github.com/google/uuid"
"golang.org/x/sync/singleflight"

apimw "github.com/Silo-Server/silo-server/internal/api/middleware"
"github.com/Silo-Server/silo-server/internal/catalog"
Expand Down Expand Up @@ -325,6 +326,7 @@ type PlaybackHandler struct {
v3RouteNodeProbe func(context.Context, string) bool // nil: probeRouteNodeV3
v3NodeCapabilitiesMu sync.Mutex
v3NodeCapabilities map[v3NodeCapabilityKey]v3NodeCapabilityCache
v3NodeCapFlight singleflight.Group
// v3NodeProbeBudgets holds what each node last said a capability read of it
// costs, guarded by v3NodeCapabilitiesMu. It is kept apart from the
// inventory above because the two are invalidated for different reasons: an
Expand Down Expand Up @@ -2441,20 +2443,7 @@ func (h *PlaybackHandler) HandleGetTranscodeManifest(w http.ResponseWriter, r *h
return
}
playback.WarnIfPlaylistOversized(r.Context(), "api", sessionID, manifest)

w.Header().Set("Content-Type", "application/vnd.apple.mpegurl")
// no-transform keeps proxies and CDNs from re-encoding the playlist,
// which drops the Content-Length below (Cloudflare does).
w.Header().Set("Cache-Control", "no-store, no-transform, max-age=0")
w.Header().Set("Pragma", "no-cache")
// The playlist is complete in memory, so state its length. Without it a
// playlist past net/http's small write buffer goes out chunked, and a
// player that opens HLS sources with a ranged byte reader (AetherEngine
// on Apple platforms) takes the length-less 200 for a non-seekable stream
// and misreads the playlist as media.
w.Header().Set("Content-Length", strconv.Itoa(len(manifest)))
w.WriteHeader(http.StatusOK)
_, _ = w.Write(manifest)
playback.WriteHLSManifest(w, r, manifest)
}

func writePlaybackToneMapExecutionError(w http.ResponseWriter, err error) bool {
Expand Down Expand Up @@ -2720,6 +2709,15 @@ func (h *PlaybackHandler) relayToTranscodeNode(w http.ResponseWriter, r *http.Re
slog.WarnContext(r.Context(), "stream token not forwarded to transcode node", "component", "api", "error", verifyErr, "playback_session_id", sessionID)
}
}
if strings.HasSuffix(path, ".m3u8") {
if validToken != "" {
// Need plain text here so token re-injection can rewrite segment URIs
// before WriteHLSManifest compresses the client-facing response.
req.Header.Set("Accept-Encoding", "identity")
} else {
req.Header.Set("Accept-Encoding", playback.ManifestRelayAcceptEncoding(r))
}
}

resp, err := transcodeproxy.DoNode(transcodeproxy.NodeClient(), req, transcodeNodeURL, "stream")
if err != nil {
Expand Down Expand Up @@ -2772,16 +2770,16 @@ func (h *PlaybackHandler) relayToTranscodeNode(w http.ResponseWriter, r *http.Re
}
playback.WarnIfPlaylistOversized(r.Context(), "api", sessionID, rewritten)
for k, vv := range resp.Header {
if http.CanonicalHeaderKey(k) == "Content-Length" {
canonical := http.CanonicalHeaderKey(k)
if canonical == "Content-Length" || canonical == "Content-Encoding" || canonical == "Content-Type" ||
canonical == "Cache-Control" || canonical == "Pragma" || canonical == "Vary" {
continue
}
for _, v := range vv {
w.Header().Add(k, v)
}
}
w.Header().Set("Content-Length", strconv.Itoa(len(rewritten)))
w.WriteHeader(resp.StatusCode)
_, _ = w.Write(rewritten)
playback.WriteHLSManifest(w, r, rewritten)
return nil
}

Expand All @@ -2804,6 +2802,7 @@ func (h *PlaybackHandler) relayToTranscodeNode(w http.ResponseWriter, r *http.Re
fullSize := transcodeproxy.FullRepresentationSize(resp)
if isMediaSegment && generation != "" && r.Method == http.MethodGet &&
sw.CompletedFullResponse(fullSize) {
_ = http.NewResponseController(w).Flush()
if ackErr := transcodeproxy.Acknowledge(r.Context(), transcodeproxy.NodeClient(), transcodeNodeURL, path, h.NodeKeys, generation); ackErr != nil {
slog.WarnContext(r.Context(), "acknowledge transcode segment completion", "component", "api", "error", ackErr, "playback_session_id", sessionID)
}
Expand Down
37 changes: 32 additions & 5 deletions internal/api/handlers/playback_connection.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,19 +68,30 @@ func (h *PlaybackHandler) currentReadings(probe *connectionstore.Probe, sample *
// purpose: the sender's reading is not the receiver's link. Nothing is
// recorded. key is the connection the reading is read under; empty applies none.
func (h *PlaybackHandler) applyConnectionReading(r *http.Request, req *playback.StartRequestV3, key string) error {
_, _, err := h.applyConnectionReadingRow(r, req, key)
return err
}

// applyConnectionReadingRow is applyConnectionReading returning the fetched
// connection row (and whether a lookup ran) so applyLearnedLimitWithRow can
// reuse its learned limit without a second playback_connections query.
func (h *PlaybackHandler) applyConnectionReadingRow(r *http.Request, req *playback.StartRequestV3, key string) (*connectionstore.AdminConnection, bool, error) {
if !playback.HasFeatureV3(req.ClientFeatures, playback.FeatureBufferingQualityV1) ||
req.QualityPreference != playback.QualityAutoV3 || req.BandwidthEstimateKbps != nil || req.LearnedLimit == playback.LearnedLimitIgnoreV3 {
return nil
return nil, false, nil
}
device, _ := r.Context().Value(playbackConnectionDeviceContextKey{}).(string)
c, err := h.Connections.Connection(r.Context(), apimw.GetUserID(r.Context()), connectionDeviceV3(device), key)
if err != nil || c == nil {
return err
if err != nil {
return nil, false, err
}
if c == nil {
return nil, true, nil
}
if kbps := connectionstore.Reading(h.currentReadings(c.Probe, c.PlaybackSample)); kbps > 0 {
req.BandwidthEstimateKbps, req.BandwidthEstimateSource = &kbps, playback.BandwidthEstimateProbeV3
}
return nil
return c, true, nil
}

// clearKeysV3 is the connections a clear removes the limit of: record first,
Expand Down Expand Up @@ -114,6 +125,10 @@ func clearKeysV3(record string, clearAlso ...string) []string {
// removes the limit of clearAlso, the connection the plan may be served over
// instead. An empty key or record applies or writes nothing.
func (h *PlaybackHandler) applyLearnedLimit(r *http.Request, req *playback.StartRequestV3, clientSent bool, key, record string, outputBound func() bool, clearAlso ...string) (*playback.BandwidthLimitV3, error) {
return h.applyLearnedLimitWithRow(r, req, clientSent, key, record, outputBound, nil, false, clearAlso...)
}

func (h *PlaybackHandler) applyLearnedLimitWithRow(r *http.Request, req *playback.StartRequestV3, clientSent bool, key, record string, outputBound func() bool, prefetched *connectionstore.AdminConnection, hasPrefetched bool, clearAlso ...string) (*playback.BandwidthLimitV3, error) {
if !playback.HasFeatureV3(req.ClientFeatures, playback.FeatureBufferingQualityV1) {
return nil, nil
}
Expand All @@ -139,6 +154,7 @@ func (h *PlaybackHandler) applyLearnedLimit(r *http.Request, req *playback.Start
if req.LearnedLimit == playback.LearnedLimitIgnoreV3 {
return nil, nil
}
wrote := false
if clientSent && req.BandwidthEstimateSource == playback.BandwidthEstimateObservedRebufferV3 && req.BandwidthEstimateKbps != nil && req.QualityPreference == playback.QualityAutoV3 {
switch {
case device == "" || record == "":
Expand All @@ -151,12 +167,23 @@ func (h *PlaybackHandler) applyLearnedLimit(r *http.Request, req *playback.Start
if err := h.Connections.Observe(r.Context(), user, device, record, *req.BandwidthEstimateKbps); err != nil {
return nil, err
}
wrote = true
}
}
if req.QualityPreference != playback.QualityAutoV3 {
return nil, nil
}
limit, err := h.Connections.Get(r.Context(), user, device, key)
var (
limit *connectionstore.Limit
err error
)
if hasPrefetched && !wrote {
if prefetched != nil {
limit = prefetched.LearnedLimit
}
} else {
limit, err = h.Connections.Get(r.Context(), user, device, key)
}
if err != nil || limit == nil {
return nil, err
}
Expand Down
4 changes: 2 additions & 2 deletions internal/api/handlers/playback_desired_tracks_v3.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ func (h *PlaybackHandler) desiredSubtitleFromFileV3(ctx context.Context, file *m
if h.SubtitleRepo == nil {
return nil, nil
}
downloaded, err := h.SubtitleRepo.ListDownloadedSubtitles(ctx, file.ID)
downloaded, err := h.listDownloadedSubtitlesRawV3(ctx, file.ID)
if err != nil {
return nil, fmt.Errorf("load downloaded subtitles: %w", wrapSubtitleStoreErrorV3(err))
}
Expand Down Expand Up @@ -70,7 +70,7 @@ func (h *PlaybackHandler) resolveDesiredSubtitleV3(ctx context.Context, want pla
var downloaded []subtitles.DownloadedSubtitle
if want.Source == playback.SubtitleSourceDownloadedV3 && h.SubtitleRepo != nil {
var err error
downloaded, err = h.SubtitleRepo.ListDownloadedSubtitles(ctx, target.ID)
downloaded, err = h.listDownloadedSubtitlesRawV3(ctx, target.ID)
if err != nil {
// A failed lookup says nothing about whether the track exists;
// dropping the selection over it would turn subtitles off.
Expand Down
6 changes: 4 additions & 2 deletions internal/api/handlers/playback_session_recipe.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ type sessionRecipeStoreV3 interface {
// Best effort, like the node recipe: a failed write only costs this session its
// restart recovery, and the plan binding keeps the card it failed to replace
// from rebuilding the superseded transport.
func (h *PlaybackHandler) recordSessionRecipeV3(ctx context.Context, planID string, transport *preparedTransportV3) {
func (h *PlaybackHandler) recordSessionRecipeV3(ctx context.Context, planID string, transport *preparedTransportV3, isReplan bool) {
if h == nil || transport == nil || transport.sessionRecipe == nil || planID == "" ||
h.SessionRecipeStore == nil || !h.SessionRecipeStore.Enabled() {
return
Expand All @@ -54,7 +54,9 @@ func (h *PlaybackHandler) recordSessionRecipeV3(ctx context.Context, planID stri
return
}
if current.RoutingEgress == string(noderouting.EgressProxy) {
h.deleteSessionRecipeV3(ctx, card.SessionID)
if isReplan {
h.deleteSessionRecipeV3(ctx, card.SessionID)
}
return
}
card.PlanID = planID
Expand Down
Loading
Loading