Skip to content

Replace a live session's request headers without a rebuild (rotating bearer tokens), and type a mid-session 401 #792

Open

Description

@dlev02

What should the engine do?

Let a host replace the request headers of a live session, so the next request the source reader makes carries them, without a teardown. And when a credential has lapsed mid-session, say so: a 401/403 that outlasts the reader's ladder should reach the host as sourceRefused with the status, not as vodSourceFailed / "Source read failed".

Motivating use case

A media server that requires a bearer token on every media request, where access tokens live one hour (the server admin can shorten that). The host holds a refresh token and can mint a new access token in the background at any time, with no user interaction. A two-hour film therefore crosses at least one expiry, and nothing about the film, the session or the byte stream changes at that moment except the value of one header.

Reading main at 210728a, the host has two ways to get a new token onto the wire today, and both rebuild the session:

The reason nothing cheaper exists is that the headers are fixed per reader:

  • AVIOReader.extraHeaders is a let (AVIOReader.swift:44). Every request the reader builds goes through headers(for:) (:1177), so the per-request path is already centralised. Only the value is frozen.
  • HLSVideoEngine.sourceHTTPHeaders is a let too (HLSVideoEngine.swift:44). The producer's fresh-demuxer reopens (:1261, and the live reopen in HLSVideoEngine+LiveReopen.swift:1072) replay the load-time value even after a host correction, unless that correction went through a rebuild.

What happens today when the token lapses mid-session

Again from reading 210728a, for a progressive HTTP source (MKV/MP4) on the software/loopback path:

  1. The next range request gets a 401. persistentReceivedResponse notes only 429/503/509 with OriginRequestBudget (AVIOReader.swift:3673), so the refusal is never stamped as one.
  2. The ended-connection ladder treats it as an unproductive reconnect: backoff 1, 2, 4, 8, 8 … s, up to reconnectMaxUnproductive = 12 (:675, :2698), each attempt sending the same expired header. Phase is .stalled(reconnecting: true) throughout. That is roughly 80 s with nothing a host can read to learn that the cause is the credential.
  3. The give-up returns -1, handleVODReadErrorExit finds no metering stamp, and spends readErrorReviveGate's two revives on fresh demuxers. Both reopen with the same headers and are refused again.
  4. The session ends with surfaceVODSourceFailure(code, "Source read failed"), kind vodSourceFailed. The 401 never reaches PlaybackErrorInfo, although sourceRefused exists for exactly this at open time (A refused source (HTTP 403 on every GET) reaches the host as "Invalid data found when processing input" and disables the tail prefetch for the origin #378).

On the revision we ship (7.36.0, c6365cc) the observed behaviour is a stall that holds .stalled(reconnecting: true) for as long as we let it before reloading. So the host works around it: it renews the token before load when less than 30 minutes remain, and if the reader stalls over an expired token, it reloads in place with the new header.

Proposed API

1. Replace the header set for subsequent requests on a live session.

/// Replaces the HTTP headers the session's source requests carry from the next request on, without a
/// rebuild. Also installed into `loadedOptions.httpHeaders`, so every later reopen (an audio switch,
/// a background return, a revive, `reloadAtCurrentPosition()`) replays it too.
@discardableResult
public func updateRequestHeaders(_ headers: [String: String]) -> RequestHeaderUpdateOutcome

public enum RequestHeaderUpdateOutcome: Sendable, Equatable {
    /// The session's readers will send these headers on their next request. A reconnect that is
    /// already backing off picks them up on its next attempt, so a stall over a lapsed credential
    /// heals without a teardown.
    case appliedToLiveRequests
    /// The session's requests are owned by something that fixes its headers at load (an
    /// AVFoundation-hosted remote HLS item, a custom `IOReader`). The headers are installed for the
    /// next rebuild. Call `reloadAtCurrentPosition()` if they are needed now.
    case installedForNextRebuild
    /// There is no session to update.
    case noActiveSession
}

Implementation sketch (I am preparing a PR along these lines):

  • A small lock-protected reference box (RequestHeaderStore) that the session creates at load from options.httpHeaders.
  • AVIOReader reads its headers from the box when it was given one, so headers(for:), and with it every request path, the held connection and the redirect policy, sees the current value. The box is passed through DemuxerOpenProfile, so Demuxer.open's signature doesn't change.
  • HLSVideoEngine reads sourceHTTPHeaders from the same box, so its reopens use the current value.
  • RedirectHeaderPolicy scoping is unchanged. The credential still stays off a cross-origin redirect target, because the box only supplies the value that the policy then scopes.
  • Delegates that capture headers for redirect replay keep capturing per request. A request already in flight finishes with the headers it was sent with.

This is deliberately narrower than #460. It changes one field, doesn't touch routing or the session's identity, and costs nothing. A host could call it every few minutes or on a timer derived from the token's exp, and a viewer would never see it.

2. Make a lapsed credential observable and typed.

Any one of these would let a host stop guessing from .stalled(reconnecting: true). I'm listing them in the order I think they're worth it:

  • Stamp 401/403 mid-session the way 429 is stamped, and have the revive arm surface sourceRefused with underlyingCode = status once its budget is spent, rather than vodSourceFailed. That keeps the existing kind's meaning ("the origin answered with a status instead of media") for the mid-session case.
  • Give 401 a short ladder of its own. Retrying an identical request with an identical expired credential twelve times can't succeed. Two attempts, then give up, would surface the typed failure in seconds instead of minutes. With (1) in place, a host that renews on the first 401 heals inside those two attempts.
  • Optionally, a host-readable event on the first mid-session 401/403 (for example sourceAuthorizationRefused: AnyPublisher<Int, Never>), so a host can renew immediately instead of waiting for a phase.

I've left part 2 out of the PR because it changes how the revive arm classifies failures, which is your call to shape. I'm happy to follow up with it in whichever form you prefer.

Area

Public API surface

Host app / integration context

A closed-source iOS/tvOS/macOS media client that plays from self-hosted media servers through AetherEngine (pinned by SHA, currently 7.36.0).

Would you be willing to open a PR?

Yes, for part 1; I will link it here.

Activity

  1. superuser404notfound commented on Oct 15, 2026

    @superuser404notfound
    Owner

    Thanks for the thorough write-up, every reference checks out against current main (b3edb6b): extraHeaders is a private let (AVIOReader.swift:44) with headers(for:) as the single funnel, persistentReceivedResponse only notes the rate-limit statuses, so a 401 walks the full unproductive ladder with the same header, then spends both readErrorReviveGate revives and ends as vodSourceFailed.

    Part 1: yes, please open the PR. The scope is right: one field, no routing or identity change, RedirectHeaderPolicy still scoping whatever the box supplies. Three places in review I'll look at specifically, because they hold or compare a copy today and would otherwise keep sending the old token:

    • The warm-connection adoption check, warm.requestHeaders == extraHeaders (AVIOReader.swift:2935). It has to compare against the current value, or a warm connection opened with the old token gets adopted (or a valid one gets discarded for the wrong reason).
    • The scrub-still path, which captures sourceHTTPHeaders once (HLSVideoEngine.swift:2846).
    • The I-frame reader construction (HLSVideoEngine.swift:4414).

    A test that rotates the header mid-session and asserts the next range request, a fresh-demuxer reopen and a scrub-still fetch all carry the new value would cover the lot.

    Part 2: I'll take it, after part 1 lands, since it builds on the box. Shape I have in mind, roughly your first two bullets plus one addition:

    1. A mid-session 401/403 is stamped the way 429 is, and once the budget is spent the session surfaces sourceRefused with the status as underlyingCode, not vodSourceFailed.
    2. 401/403 get a short ladder of their own (two attempts), not twelve.
    3. The header box carries a revision. A refusal records the revision it was sent with, and the revive arm only spends a revive on a credential refusal when the revision has moved since. Reviving with the identical expired header can't succeed; reviving after the host renewed is exactly the heal you want, without a teardown.
    4. The sourceAuthorizationRefused event as well. It's cheap, and a proactive exp timer doesn't cover a token revoked early by an admin, where the host otherwise only sees .stalled.

    I'll link the PR here when it's up.

  2. dlev02 commented on Oct 15, 2026

    @dlev02
    ContributorAuthor

    Part 1 is up as #793. In a loopback test, the 401 stall this issue describes measured 83 s of reconnect ladder before the read failed. With the PR, the same reader heals on its next attempt once the store holds the renewed token.

  3. superuser404notfound commented on Oct 15, 2026

    @superuser404notfound
    Owner

    Part 1 merged: #793 (4768000), plus 83aefbf so the session's still extractor follows the store too. Not released yet. Part 2 (typed sourceRefused for a mid-session 401/403, the short ladder, the revision-gated revive and the sourceAuthorizationRefused event) is next, in the shape described above.

  4. superuser404notfound commented on Oct 15, 2026

    @superuser404notfound
    Owner

    Released in 7.37.0 (a3db0d7): part 1 (#793 plus the still-extractor follow-up) and part 2 (4f245b88). A mid-session 401/403 now gets its own ladder of about 3 s instead of about 80 s, the first refusal of a header set is published on sourceAuthorizationRefused with the status, a renewal through updateRequestHeaders(_:) mid-ladder gives the reader a fresh one, and once the reader has given up the loopback session waits up to 10 s for new headers and rebuilds at the playhead if they come. Otherwise the session ends with sourceRefused and the status as underlyingCode; the software path reports the same kind. Details under Rotating a credential without a rebuild.

  5. added a commit that references this issue on Nov 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions