Skip to content

Commit 4c3f868

Browse files
Quick104claude
andcommitted
refactor(hls): simplify relay authorization plumbing
Behavior-preserving cleanups from review: - fetchPlaylist and fetchData share one dispatch bridge, fetchWhole. - authorize returns static headers before registering a wait when the relay has no provider, so the TLS-only relay skips an unused wait. - A 401 challenge has one failure exit: retry only with a changed credential. - UpstreamPump shares its over-limit transition, and transfer binds the response URL once. - loadRemoteHLS drops an unreachable guard: prepareRemoteHLSStandIn already throws when a required authorization relay cannot start. - changedFields names its three comparison modes in one switch. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1 parent ed94179 commit 4c3f868

3 files changed

Lines changed: 53 additions & 71 deletions

File tree

‎Sources/AetherEngine/AetherEngine+Loading.swift‎

Lines changed: 4 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -496,17 +496,10 @@ extension AetherEngine {
496496
//
497497
// AE#495: a host that answered the trust evaluator needs the media on a session the engine
498498
// owns, and the same stand-in does that. With sidecars it mounts a relay behind the
499-
// rewritten master, without them the relay stands alone.
500-
let standInURL = try await prepareRemoteHLSStandIn(
501-
originURL: url, options: options, expectedGeneration: bypassGeneration)
502-
let playbackURL: URL
503-
if let standInURL { playbackURL = standInURL }
504-
else {
505-
guard options.httpRequestAuthorization == nil else {
506-
throw RemoteHLSSubtitleProxy.Refusal.serverUnavailable("required authorization relay is unavailable")
507-
}
508-
playbackURL = url
509-
}
499+
// rewritten master, without them the relay stands alone. A required authorization relay
500+
// that cannot start throws rather than returning nil.
501+
let playbackURL = try await prepareRemoteHLSStandIn(
502+
originURL: url, options: options, expectedGeneration: bypassGeneration) ?? url
510503
// With a relay in front, the item AVPlayer fails is a loopback 502 and the refused handshake
511504
// happened out of its sight, so the classification has to be able to ask the side that made it.
512505
if let relay = remoteHLSSubtitleProxy?.server.relay {

‎Sources/AetherEngine/AetherEngine+ReloadWithOptions.swift‎

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -368,20 +368,18 @@ enum SessionOptionCorrection {
368368
for (lhs, rhs) in zip(Mirror(reflecting: current).children,
369369
Mirror(reflecting: proposed).children) {
370370
guard let label = lhs.label else { continue }
371-
// Providers compare by identity; their text descriptions only name the type.
372-
if label == "httpRequestAuthorization" {
373-
if current.httpRequestAuthorization != proposed.httpRequestAuthorization {
374-
changed.append(label)
375-
}
376-
continue
371+
let differs: Bool
372+
switch label {
373+
// Authorization providers compare by identity, which reflection erases: a description
374+
// names only the type, so two scopes, alone or inside tracks, describe identically.
375+
case "httpRequestAuthorization":
376+
differs = current.httpRequestAuthorization != proposed.httpRequestAuthorization
377+
case "externalSubtitles":
378+
differs = current.externalSubtitles != proposed.externalSubtitles
379+
default:
380+
differs = describe(lhs.value) != describe(rhs.value)
377381
}
378-
// The track array also contains identity-based providers; reflection erases those
379-
// identities and can describe different subtitle authorization scopes identically.
380-
if label == "externalSubtitles" {
381-
if current.externalSubtitles != proposed.externalSubtitles { changed.append(label) }
382-
continue
383-
}
384-
if describe(lhs.value) != describe(rhs.value) { changed.append(label) }
382+
if differs { changed.append(label) }
385383
}
386384
return changed
387385
}

‎Sources/AetherEngine/Network/HLSOriginRelay.swift‎

Lines changed: 38 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -437,13 +437,8 @@ final class HLSOriginRelay: @unchecked Sendable {
437437
case .challenge(let response, let sentHeaders):
438438
challenged = true
439439
let respondingURL = response.url ?? url
440-
let fresh: [String: String]
441-
do { fresh = try authorize(respondingURL, rejectedHeaders: sentHeaders, fallback: [:]) }
442-
catch {
443-
reportRequestFailure()
444-
return .held(Fetched(url: respondingURL, status: 401, body: Data(), contentType: nil, contentRange: nil))
445-
}
446-
guard Self.authorizationValue(fresh) != Self.authorizationValue(sentHeaders) else {
440+
guard let fresh = try? authorize(respondingURL, rejectedHeaders: sentHeaders, fallback: [:]),
441+
Self.authorizationValue(fresh) != Self.authorizationValue(sentHeaders) else {
447442
reportRequestFailure()
448443
return .held(Fetched(url: respondingURL, status: 401, body: Data(), contentType: nil, contentRange: nil))
449444
}
@@ -470,63 +465,59 @@ final class HLSOriginRelay: @unchecked Sendable {
470465
fallback: [String: String]) throws -> [String: String] {
471466
let timeout = remainingBudget(upTo: authorizationTimeout)
472467
guard timeout > 0 else { throw URLError(.timedOut) }
473-
let wait = HTTPAuthorizationWait()
474-
let id = UUID()
475468
stateLock.lock()
476469
guard !stopped else { stateLock.unlock(); throw CancellationError() }
470+
guard let authorization else { stateLock.unlock(); return fallback }
471+
let wait = HTTPAuthorizationWait()
472+
let id = UUID()
477473
authorizationWaits[id] = wait
478474
stateLock.unlock()
479475
defer {
480476
stateLock.lock()
481477
authorizationWaits.removeValue(forKey: id)
482478
stateLock.unlock()
483479
}
484-
guard let authorization else { return fallback }
485480
return try wait.resolve(authorization, url: url, rejectedHeaders: rejectedHeaders,
486481
timeout: timeout)
487482
}
488483

489484
/// Playlist preflight shares exactly the relay's redirect, challenge and authorization contract.
490-
/// Dispatching the synchronous pump keeps the caller's actor and cooperative executor free.
491485
func fetchPlaylist(_ url: URL, headers: [String: String]) async throws -> (String, URL) {
492-
try await withTaskCancellationHandler {
493-
try Task.checkCancellation()
494-
return try await withCheckedThrowingContinuation { continuation in
495-
DispatchQueue.global(qos: .userInitiated).async { [self] in
496-
let sink = Sink(head: { _, _, _, _ in false }, body: { _ in false })
497-
switch fetch(origin: url, headers: headers, range: nil, sink: sink, forceHold: true) {
498-
case .held(let fetched) where (200..<300).contains(fetched.status):
499-
if let body = String(data: fetched.body, encoding: .utf8) {
500-
continuation.resume(returning: (body, fetched.url))
501-
} else { continuation.resume(throwing: URLError(.cannotDecodeContentData)) }
502-
default: continuation.resume(throwing: URLError(.badServerResponse))
503-
}
504-
}
505-
}
506-
} onCancel: { self.stop() }
486+
let fetched = try await fetchWhole(url, headers: headers)
487+
guard let body = String(data: fetched.body, encoding: .utf8) else {
488+
throw URLError(.cannotDecodeContentData)
489+
}
490+
return (body, fetched.url)
507491
}
508492

509493
/// Raw resources share the relay transport but never enter playlist rewriting. The pump
510494
/// enforces the cap before accumulating bytes, including unknown or misleading lengths.
511495
func fetchData(_ url: URL, maximumBytes: Int) async throws -> Data {
512496
guard Self.originKey(for: url) != nil else { throw URLError(.unsupportedURL) }
513497
guard maximumBytes >= 0 else { throw URLError(.dataLengthExceedsMaximum) }
514-
let body: Data = try await withTaskCancellationHandler {
498+
let body = try await fetchWhole(url, headers: [:], maximumBytes: maximumBytes).body
499+
try Task.checkCancellation()
500+
return body
501+
}
502+
503+
/// One successful body, read whole. Dispatching the synchronous pump keeps the caller's actor
504+
/// and cooperative executor free; cancellation stops the relay, which wakes the pump.
505+
private func fetchWhole(_ url: URL, headers: [String: String],
506+
maximumBytes: Int? = nil) async throws -> Fetched {
507+
try await withTaskCancellationHandler {
515508
try Task.checkCancellation()
516509
return try await withCheckedThrowingContinuation { continuation in
517510
DispatchQueue.global(qos: .userInitiated).async { [self] in
518511
let sink = Sink(head: { _, _, _, _ in false }, body: { _ in false })
519-
switch fetch(origin: url, headers: [:], range: nil, sink: sink,
512+
switch fetch(origin: url, headers: headers, range: nil, sink: sink,
520513
forceHold: true, maximumBytes: maximumBytes) {
521514
case .held(let fetched) where (200..<300).contains(fetched.status):
522-
continuation.resume(returning: fetched.body)
515+
continuation.resume(returning: fetched)
523516
default: continuation.resume(throwing: URLError(.badServerResponse))
524517
}
525518
}
526519
}
527520
} onCancel: { self.stop() }
528-
try Task.checkCancellation()
529-
return body
530521
}
531522

532523
private enum Transfer {
@@ -567,9 +558,10 @@ final class HLSOriginRelay: @unchecked Sendable {
567558
note(failure: pump.awaitFailure(), origin: origin)
568559
return .complete(.failed)
569560
}
561+
let responseURL = http.url ?? origin
570562
if [301, 302, 303, 307, 308].contains(http.statusCode),
571563
let location = http.value(forHTTPHeaderField: "Location"),
572-
let destination = URL(string: location, relativeTo: http.url ?? origin)?.absoluteURL {
564+
let destination = URL(string: location, relativeTo: responseURL)?.absoluteURL {
573565
return .redirect(destination)
574566
}
575567
if interceptChallenge && http.statusCode == 401 {
@@ -579,28 +571,28 @@ final class HLSOriginRelay: @unchecked Sendable {
579571
}
580572
if Self.refusalStatuses.contains(http.statusCode) {
581573
OriginRequestBudget.shared.noteRefusal(
582-
for: http.url ?? origin, status: http.statusCode,
574+
for: responseURL, status: http.statusCode,
583575
retryAfter: http.value(forHTTPHeaderField: "Retry-After").flatMap(TimeInterval.init))
584576
}
585577
// Raw sidecars and bounded resources need successful bytes only, never an error page.
586578
// In particular, a terminal 401/403 must not wait for an unbounded or stalled error body.
587579
if (rawResources || maximumBytes != nil) && !(200..<300).contains(http.statusCode) {
588-
return .complete(.held(Fetched(url: http.url ?? origin, status: http.statusCode,
580+
return .complete(.held(Fetched(url: responseURL, status: http.statusCode,
589581
body: Data(), contentType: nil, contentRange: nil)))
590582
}
591583
let contentType = http.value(forHTTPHeaderField: "Content-Type")
592584
let contentRange = http.value(forHTTPHeaderField: "Content-Range")
593585
let declaredLength = http.expectedContentLength
594586
let mustHold = forceHold || !(200..<300).contains(http.statusCode)
595587
|| (!rawResources && (declaredLength < 0
596-
|| Self.looksLikePlaylist(url: http.url ?? origin, contentType: contentType)))
588+
|| Self.looksLikePlaylist(url: responseURL, contentType: contentType)))
597589
if mustHold {
598590
let body = pump.awaitWholeBody()
599591
if let error = pump.awaitFailure() {
600592
note(failure: error, origin: origin)
601593
return .complete(.failed)
602594
}
603-
return .complete(.held(Fetched(url: http.url ?? origin, status: http.statusCode,
595+
return .complete(.held(Fetched(url: responseURL, status: http.statusCode,
604596
body: body, contentType: contentType, contentRange: contentRange)))
605597
}
606598
guard sink.head(http.statusCode, contentType ?? "application/octet-stream", contentRange,
@@ -800,11 +792,7 @@ private final class UpstreamPump: NSObject, URLSessionDataDelegate, @unchecked S
800792
condition.lock()
801793
head = http
802794
let tooLarge = maximumBytes.map { http.expectedContentLength > Int64($0) } ?? false
803-
if tooLarge {
804-
failure = URLError(.dataLengthExceedsMaximum)
805-
finished = true
806-
consumerGaveUp = true
807-
}
795+
if tooLarge { failOverLimit() }
808796
condition.broadcast()
809797
condition.unlock()
810798
completionHandler(tooLarge ? .cancel : .allow)
@@ -813,12 +801,7 @@ private final class UpstreamPump: NSObject, URLSessionDataDelegate, @unchecked S
813801
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
814802
condition.lock()
815803
while pending.count >= Self.highWaterBytes && !consumerGaveUp { condition.wait() }
816-
if let maximumBytes, data.count > maximumBytes - receivedBytes {
817-
failure = URLError(.dataLengthExceedsMaximum)
818-
finished = true
819-
consumerGaveUp = true
820-
condition.broadcast()
821-
}
804+
if let maximumBytes, data.count > maximumBytes - receivedBytes { failOverLimit() }
822805
let abandoned = consumerGaveUp
823806
if !abandoned {
824807
if maximumBytes != nil { receivedBytes += data.count }
@@ -829,6 +812,14 @@ private final class UpstreamPump: NSObject, URLSessionDataDelegate, @unchecked S
829812
if abandoned { dataTask.cancel() }
830813
}
831814

815+
/// The body passed `maximumBytes`: fail it and stop accepting bytes. Caller holds `condition`.
816+
private func failOverLimit() {
817+
failure = URLError(.dataLengthExceedsMaximum)
818+
finished = true
819+
consumerGaveUp = true
820+
condition.broadcast()
821+
}
822+
832823
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
833824
condition.lock()
834825
if failure == nil { failure = error }

0 commit comments

Comments
 (0)