@@ -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