react-native-audio-browser 0.2.0-next.76 → 0.2.0-next.77

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/android/src/main/java/com/audiobrowser/AudioBrowser.kt +1 -1
  2. package/android/src/main/java/com/audiobrowser/player/EnginePlayback.kt +9 -5
  3. package/android/src/main/java/com/audiobrowser/player/InterceptingPlayer.kt +71 -39
  4. package/android/src/main/java/com/audiobrowser/player/LiveStreamExtractor.kt +65 -0
  5. package/android/src/main/java/com/audiobrowser/player/MediaFactory.kt +12 -3
  6. package/android/src/main/java/com/audiobrowser/player/NowPlayingUpdater.kt +5 -0
  7. package/android/src/main/java/com/audiobrowser/player/Player.kt +78 -36
  8. package/android/src/main/java/com/audiobrowser/player/PlayerListener.kt +6 -0
  9. package/android/src/main/java/com/audiobrowser/player/RetryLoadErrorHandlingPolicy.kt +1 -1
  10. package/android/src/main/java/com/audiobrowser/remote/RemoteSwitchingPlayer.kt +21 -0
  11. package/android/src/test/java/androidx/media3/session/SessionViews.kt +10 -0
  12. package/android/src/test/java/com/audiobrowser/player/LiveStreamEndTest.kt +372 -0
  13. package/android/src/test/java/com/audiobrowser/player/PlayerSetupEndedTest.kt +221 -0
  14. package/android/src/test/java/com/audiobrowser/player/PlayerSetupTest.kt +17 -7
  15. package/android/src/test/java/com/audiobrowser/player/PlayerSuppressionTest.kt +183 -7
  16. package/android/src/test/java/com/audiobrowser/player/PlayerTrackChangeTest.kt +48 -0
  17. package/android/src/test/java/com/audiobrowser/player/SessionPlayTest.kt +236 -0
  18. package/android/src/test/java/com/audiobrowser/player/SessionViewRulesTest.kt +62 -0
  19. package/android/src/test/java/com/audiobrowser/player/SessionViewTest.kt +188 -0
  20. package/android/src/test/java/com/audiobrowser/remote/FakeRemote.kt +11 -0
  21. package/android/src/test/java/com/audiobrowser/remote/RemoteSwitchingPlayerTest.kt +58 -0
  22. package/ios/AVPlayerEngine.swift +5 -1
  23. package/ios/Browser/BrowserManager.swift +2 -2
  24. package/ios/Browser/PageResolver.swift +14 -19
  25. package/ios/Browser/RequestPipeline.swift +6 -4
  26. package/ios/CarPlay/CarPlayNowPlayingManager.swift +1 -1
  27. package/ios/CarPlay/CarPlaySession+PageLoader.swift +1 -0
  28. package/ios/CarPlay/CarPlaySession+TabBar.swift +2 -0
  29. package/ios/Extension/Promise+AwaitCallback.swift +33 -0
  30. package/ios/HybridAudioBrowser+Player.swift +1 -1
  31. package/ios/HybridAudioBrowser.swift +1 -1
  32. package/ios/Player/MediaLoader.swift +1 -1
  33. package/ios/Player/PlaybackFailure.swift +3 -3
  34. package/ios/Player/Player.swift +67 -49
  35. package/ios/Player/PlayerEngine.swift +2 -0
  36. package/ios/Player/RetryLoop.swift +72 -12
  37. package/ios/Tests/AwaitCallbackTests.swift +210 -0
  38. package/ios/Tests/GenerationMemoTests.swift +57 -0
  39. package/ios/Tests/PlaybackFailureTests.swift +7 -0
  40. package/ios/Tests/PlayerPolicyTests.swift +346 -6
  41. package/ios/Tests/PlayerTests.swift +79 -1
  42. package/ios/Tests/RetryLoopTests.swift +30 -5
  43. package/ios/Tests/Support/TestTypes.swift +15 -7
  44. package/ios/Tests/Support/TimeLimit.swift +43 -0
  45. package/ios/Util/AwaitCallback.swift +80 -0
  46. package/ios/Util/GenerationMemo.swift +11 -4
  47. package/package.json +1 -1
  48. package/android/src/test/java/com/audiobrowser/player/SessionErrorMaskTest.kt +0 -63
  49. package/ios/Player/EndOfTrackJudgement.swift +0 -25
  50. package/ios/Tests/EndOfTrackJudgementTests.swift +0 -30
@@ -123,6 +123,11 @@ final class Player {
123
123
  deferredSeek.target ?? (enginePositionIsCurrent ? engine.resumePosition : nil)
124
124
  }
125
125
 
126
+ /// Where a reload resumes: nowhere after the end, or after a stop whose rewind may not have landed.
127
+ private var reloadPosition: TimeInterval? {
128
+ state == .ended || state == .stopped ? nil : resumePosition
129
+ }
130
+
126
131
  // MARK: - Track State (for active track changed events)
127
132
 
128
133
  private var lastIndex: Int = -1
@@ -183,18 +188,14 @@ final class Player {
183
188
  if newValue, resumes || state == .stopped || state == .ended {
184
189
  reloadResolving(startFromCurrentTime: resumes)
185
190
  }
186
- if state != .loading {
187
- if newValue { engine.play() } else { engine.pause() }
188
- }
191
+ // While loading, the engine may still hold the previous track's item: a play waits for the new one.
192
+ if !newValue { engine.pause() } else if state != .loading { engine.play() }
189
193
 
190
194
  guard changed else { return }
195
+ // A resume can find the state still .buffering (a pause near the end leaves it), with no watch.
196
+ if newValue, state == .buffering { retry.startStallWatch() }
191
197
  // Left to run, the retry would give up on the dropped intent and surface .error.
192
- if !newValue, retry.pendingTask != nil {
193
- retry.reset()
194
- if let position = resumePosition { deferredSeek.capture(position) }
195
- load?.reloadOnPlay = true
196
- transition(.retryCancelled)
197
- }
198
+ if !newValue, retry.pendingTask != nil { parkForReloadOnPlay() }
198
199
  // A pause during the sleep fade ends the timer early, restoring the pre-fade volume.
199
200
  if !newValue, sleepTimerManager.isFading { sleepTimerManager.clear() }
200
201
  publish()
@@ -252,9 +253,11 @@ final class Player {
252
253
 
253
254
  retry.onError = { [weak self] in self?.transition(.errorOccurred($0)) }
254
255
  retry.onRetryingError = { [weak self] in self?.reportRetryingError($0) }
256
+ retry.onFailedWithoutIntent = { [weak self] in self?.parkForReloadOnPlay() }
255
257
  retry.onRetry = { [weak self] in self?.reloadResolving(startFromCurrentTime: $0) }
256
258
  retry.shouldRetry = { [weak self] in self?.playWhenReady ?? false }
257
259
  retry.hasPlayed = { [weak self] in self?.load?.hasPlayed ?? false }
260
+ retry.bufferedPosition = { [weak self] in self?.engine.bufferedPosition ?? 0 }
258
261
  }
259
262
 
260
263
  /// Shows a failure the retry loop is still working on over the current state: not a
@@ -345,6 +348,11 @@ final class Player {
345
348
  } else if old == .playing {
346
349
  retry.playbackStoppedBeingAudible()
347
350
  }
351
+ if new == .buffering, playWhenReady {
352
+ retry.startStallWatch()
353
+ } else if old == .buffering {
354
+ retry.stopStallWatch()
355
+ }
348
356
 
349
357
  switch new {
350
358
  case .ready:
@@ -355,6 +363,10 @@ final class Player {
355
363
  case .ended:
356
364
  // A natural end exhausts the play intent; the setter also requests the session release.
357
365
  setPlayWhenReady(false)
366
+ case .error:
367
+ // A stall or a lost connection can fail an item that is still alive: data arriving later
368
+ // must not play it under the error.
369
+ engine.pause()
358
370
  default: break
359
371
  }
360
372
 
@@ -717,19 +729,34 @@ final class Player {
717
729
  transition(.errorOccurred(.invalidSourceUrl("nil")))
718
730
  return
719
731
  }
720
- prepareForReload(resumingAt: startFromCurrentTime ? resumePosition : nil)
732
+ prepareForReload(resumingAt: startFromCurrentTime ? reloadPosition : nil)
721
733
  engine.resolveAndLoad(src: src, track: track)
722
734
  }
723
735
 
736
+ /// The caller's retry: reloads now, resuming where it was, in place of any retry pending.
737
+ func retryNow() {
738
+ retry.cancel()
739
+ reloadResolving(startFromCurrentTime: true)
740
+ }
741
+
742
+ private func parkForReloadOnPlay() {
743
+ retry.reset()
744
+ if let position = reloadPosition { deferredSeek.capture(position) }
745
+ load?.reloadOnPlay = true
746
+ transition(.retryCancelled)
747
+ }
748
+
724
749
  /// A restart from a terminal error begins a new Load on a new AVPlayer; automatic retries
725
- /// never get here in .error, since the retry loop keeps the state non-terminal. `time`, else the
726
- /// pending target, is held as the deferred seek before the loading transition saves the snapshot.
750
+ /// never get here in .error, since the retry loop keeps the state non-terminal, but get a new
751
+ /// AVPlayer in the same Load when the AVPlayer itself failed. `time`, else the pending target,
752
+ /// is held as the deferred seek before the loading transition saves the snapshot.
727
753
  private func prepareForReload(resumingAt time: TimeInterval?) {
728
754
  load?.reloadOnPlay = false
729
755
  let target = time ?? deferredSeek.target
730
756
  deferredSeek.reset()
731
- if state == .error {
732
- beginLoad()
757
+ let restart = state == .error
758
+ if restart { beginLoad() }
759
+ if restart || engine.playerFailed {
733
760
  engine.clearItem()
734
761
  engine.recreate()
735
762
  } else {
@@ -749,11 +776,13 @@ final class Player {
749
776
  /// Recovers from a media-services reset: every AVPlayer and session handle is invalid, so a
750
777
  /// new player reloads the current track, keeping the play intent, so a live stream reconnects
751
778
  /// instead of going silent. An on-demand track resumes where it was, unless it ended, or was
752
- /// stopped and its rewind may not have landed. No-op when nothing is loaded.
779
+ /// stopped and its rewind may not have landed. Replaces any retry pending. No-op when nothing is
780
+ /// loaded.
753
781
  func mediaServicesWereReset() {
754
782
  guard let track = currentTrack else { return }
755
783
  logger.info("Media services were reset — recreating player and reloading current track")
756
- if track.live != true, state != .ended, state != .stopped, let position = resumePosition {
784
+ retry.cancel()
785
+ if track.live != true, let position = reloadPosition {
757
786
  deferredSeek.capture(position)
758
787
  }
759
788
  engine.clearItem()
@@ -792,8 +821,8 @@ final class Player {
792
821
  case .playedToEnd:
793
822
  itemDidPlayToEnd()
794
823
  case .stalled:
795
- // Nudge, don't reconnect: a genuine drop is recovered by the retry and network paths.
796
- recoverFromStall(reconnectIfLive: false)
824
+ // A nudge only: this also arrives while audio plays, so the stall watch keys on .buffering.
825
+ if playWhenReady, state != .error { engine.play() }
797
826
  case let .timedMetadata(metadata):
798
827
  callbacks?.playerDidReceiveTimedMetadata(metadata)
799
828
  engine.applyTimedMetadata(metadata)
@@ -833,43 +862,32 @@ final class Player {
833
862
  engine.primeNowPlaying()
834
863
  }
835
864
 
836
- /// A genuine end advances the queue; a dropped live stream or an underrun reported as an end
837
- /// is recovered instead (see `EndOfTrackJudgement`).
865
+ /// An on-demand item's end is the end, whatever its duration estimate said: a truncated file
866
+ /// stalls instead, which is the stall watch's. A live stream's is a dropped connection, a
867
+ /// failure for the retry loop, since AVPlayer will not play on from an item it has ended.
838
868
  private func itemDidPlayToEnd() {
839
- let judgement = EndOfTrackJudgement(
840
- isLive: currentTrack?.live == true,
841
- currentTime: engine.currentTime,
842
- duration: engine.duration,
843
- )
844
- switch judgement.outcome {
845
- case .ended: trackDidPlayToEnd()
846
- case .stalled: recoverFromStall(reconnectIfLive: true)
847
- }
848
- }
849
-
850
- /// Recovers from a stall while the play intent holds: a live stream that ran out of data
851
- /// (`reconnectIfLive`) rejoins the edge; otherwise play() un-parks AVPlayer from waiting.
852
- private func recoverFromStall(reconnectIfLive: Bool) {
853
- guard playWhenReady else { return }
854
- if reconnectIfLive, currentTrack?.live == true {
855
- seekToLiveEdge()
856
- } else {
857
- engine.play()
858
- }
869
+ guard currentTrack?.live == true else { return trackDidPlayToEnd() }
870
+ // The engine stops observing the item it replaces: an end delivered during the load is stale.
871
+ guard state != .loading else { return }
872
+ // AVPlayer pauses an ended item, which the play intent hides: the state would read playing.
873
+ if playWhenReady, retry.isEnabled { transition(.avPlayerWaiting) }
874
+ retry.handleFailure(.liveEnd)
859
875
  }
860
876
 
861
877
  private var previousTimeControlStatus: PlayerTimeControlStatus?
862
878
  private var previousWaitingForNoItem = false
863
879
 
864
880
  /// AVPlayer can strand itself in .paused after a `.noItemToPlay` wait over AirPlay while the
865
- /// intent is to play: play() is re-issued on exactly that transition.
881
+ /// intent is to play: play() is re-issued on exactly that transition. Outside the retry loop:
882
+ /// nothing failed, and play() is the whole recovery; an item that is dead fails, and that
883
+ /// failure goes through the loop.
866
884
  private func recoverIfAirPlayStalled(transitioningTo current: PlayerTimeControlStatus, waitingForNoItem: Bool) {
867
885
  let stalled = AirPlayStallJudgement(
868
886
  previous: previousTimeControlStatus,
869
887
  current: current,
870
888
  previousWaitingReasonWasNoItemToPlay: previousWaitingForNoItem,
871
889
  isAirPlay: engine.isAirPlayRoute,
872
- playWhenReady: playWhenReady,
890
+ playWhenReady: playWhenReady && state != .error,
873
891
  ).shouldNudge
874
892
  previousTimeControlStatus = current
875
893
  previousWaitingForNoItem = current == .waitingToPlayAtSpecifiedRate && waitingForNoItem
@@ -882,15 +900,15 @@ final class Player {
882
900
  // MARK: - Connectivity
883
901
 
884
902
  /// Re-renders the now-playing lines, whose stall line tells offline from buffering, and when
885
- /// connectivity returns re-establishes a stalled stream. AVPlayer doesn't reliably report a
886
- /// live stream's mid-stream drop as a failure: it waits with no error, so the retry loop never
887
- /// engages. Only while stalled (.buffering) with play intent, so a pause or a retry that gave up
888
- /// isn't resumed; and not while a retry is pending, which owns that reload.
903
+ /// connectivity returns retries a stalled stream at once, spending an attempt, rather than wait
904
+ /// for AVPlayer to fail it. Only while stalled (.buffering) with play intent, so a pause or a
905
+ /// retry that gave up isn't resumed; not while a retry is pending, whose wait watches connectivity
906
+ /// itself; and not with retry off, which leaves the stall to AVPlayer.
889
907
  func networkStatusDidChange(isOnline: Bool) {
890
908
  engine.renderNowPlaying()
891
- guard isOnline, playWhenReady, state == .buffering, retry.pendingTask == nil else { return }
892
- logger.info("Connectivity restored while stalled — re-resolving to reconnect")
893
- reloadResolving(startFromCurrentTime: true)
909
+ guard isOnline, playWhenReady, state == .buffering, retry.isEnabled, retry.pendingTask == nil else { return }
910
+ logger.info("Connectivity restored while stalled — retrying now")
911
+ retry.handleFailure(.stall, immediately: true)
894
912
  }
895
913
 
896
914
  /// Time playback must have progressed before a buffer dip counts as a stall, so the initial
@@ -62,6 +62,8 @@ enum EngineEvent {
62
62
  /// Drops the asset and removes the item.
63
63
  func clearItem()
64
64
  func stopObservingItem()
65
+ /// Whether the AVPlayer itself has failed, not only its item: it plays nothing until recreated.
66
+ var playerFailed: Bool { get }
65
67
  /// Replaces the AVPlayer: every handle to the old one is invalid.
66
68
  func recreate()
67
69
 
@@ -18,11 +18,17 @@ public enum PlaybackErrorContext {
18
18
  case playback
19
19
  /// A MediaLoader key-value load failure: retries start from the beginning.
20
20
  case mediaLoad
21
+ /// Playback that stopped receiving data without AVFoundation failing it: retries resume from
22
+ /// the current time.
23
+ case stall
24
+ /// A live stream that reported played-to-end, as a cleanly closed connection does: retries
25
+ /// reconnect, since AVPlayer will not play on from an item it has ended.
26
+ case liveEnd
21
27
 
22
28
  var startFromCurrentTime: Bool {
23
29
  switch self {
24
- case .playback: true
25
- case .mediaLoad: false
30
+ case .playback, .stall: true
31
+ case .mediaLoad, .liveEnd: false
26
32
  }
27
33
  }
28
34
 
@@ -30,6 +36,7 @@ public enum PlaybackErrorContext {
30
36
  switch self {
31
37
  case .playback: .playbackFailed
32
38
  case .mediaLoad: .failedToLoadKeyValue
39
+ case .stall, .liveEnd: .playbackStalled
33
40
  }
34
41
  }
35
42
  }
@@ -73,6 +80,8 @@ final class RetryLoop {
73
80
  /// A failure a retry is now scheduled for, reported before the backoff while the state stays
74
81
  /// non-terminal.
75
82
  var onRetryingError: ((TrackPlayerError.PlaybackError) -> Void)?
83
+ /// A retryable failure with no play intent: nothing retries it and nothing reports it.
84
+ var onFailedWithoutIntent: (() -> Void)?
76
85
 
77
86
  weak var networkMonitor: (any NetworkStatusProviding)?
78
87
 
@@ -84,6 +93,13 @@ final class RetryLoop {
84
93
  var healthyPlaybackDuration: Duration = .seconds(20)
85
94
  private(set) var healthyPlaybackTask: Task<Void, Never>?
86
95
 
96
+ /// How long a stall may go without new data before it counts as a failure; longer than AVPlayer
97
+ /// takes to fail a stalled item itself, so its error, which says more, is the one usually retried.
98
+ var stallTimeout: Duration = .seconds(30)
99
+ /// The end of the loaded range; the stall watch reads progress off it.
100
+ var bufferedPosition: () -> Double = { 0 }
101
+ private(set) var stallTask: Task<Void, Never>?
102
+
87
103
  private var policy: Policy = .disabled
88
104
  private var firstRetryTime: Date?
89
105
  // The first-connect budget's clock: never set while offline and wiped by any offline
@@ -126,9 +142,9 @@ final class RetryLoop {
126
142
 
127
143
  // MARK: - Failures
128
144
 
129
- /// Reports a non-retryable failure through `onError` at once; otherwise reports it through
130
- /// `onRetryingError`, replaces any retry in flight, and calls `onError` only if that retry gives
131
- /// up.
145
+ /// Reports a non-retryable failure through `onError` at once, and one with no play intent
146
+ /// through `onFailedWithoutIntent`; otherwise reports it through `onRetryingError`, replaces any
147
+ /// retry in flight, and calls `onError` only if that retry gives up.
132
148
  func handleError(_ error: Error?, context: PlaybackErrorContext, httpStatusCode: Int? = nil) {
133
149
  if let error {
134
150
  let nsError = error as NSError
@@ -137,17 +153,36 @@ final class RetryLoop {
137
153
  logger.error("[\(String(describing: context))] failure with nil error")
138
154
  }
139
155
 
140
- let failure = PlaybackFailure.classify(error, httpStatusCode: httpStatusCode, fallback: context.fallbackError)
156
+ handle(PlaybackFailure.classify(error, httpStatusCode: httpStatusCode, fallback: context.fallbackError), context: context)
157
+ }
158
+
159
+ /// A failure the Player judges from what playback did, with no error to classify: retryable,
160
+ /// and reported as the context's fallback error. `immediately` skips the backoff, not the budgets.
161
+ func handleFailure(_ context: PlaybackErrorContext, immediately: Bool = false) {
162
+ logger.error("[\(String(describing: context))] failure")
163
+ handle(.init(error: context.fallbackError, retryable: true), context: context, immediately: immediately)
164
+ }
165
+
166
+ private func handle(
167
+ _ failure: PlaybackFailure.Classification, context: PlaybackErrorContext, immediately: Bool = false,
168
+ ) {
169
+ stopStallWatch()
141
170
  guard isEnabled, failure.retryable else {
142
- logger.warning("Error not retryable, surfacing \(String(describing: failure.error))")
171
+ let reason = isEnabled ? "Error not retryable" : "Retry disabled"
172
+ logger.warning("\(reason), surfacing \(String(describing: failure.error))")
143
173
  onError?(failure.error)
144
174
  return
145
175
  }
176
+ guard shouldRetry() else {
177
+ logger.info("No play intent: \(String(describing: failure.error)) is left to the next play")
178
+ onFailedWithoutIntent?()
179
+ return
180
+ }
146
181
  onRetryingError?(failure.error)
147
182
  pendingTask?.cancel()
148
183
  pendingTask = Task { [weak self] in
149
184
  guard let self else { return }
150
- let retried = await attemptRetry(startFromCurrentTime: context.startFromCurrentTime)
185
+ let retried = await attemptRetry(startFromCurrentTime: context.startFromCurrentTime, immediately: immediately)
151
186
  // Cancelled by a track change or stop: stay silent, or the new track or the stop would
152
187
  // flip to .error. The canceller owns `pendingTask`.
153
188
  if Task.isCancelled { return }
@@ -156,10 +191,34 @@ final class RetryLoop {
156
191
  }
157
192
  }
158
193
 
159
- /// Drops the retry in flight without touching the budgets.
194
+ /// Drops the retry in flight and the stall watch without touching the budgets.
160
195
  func cancel() {
161
196
  pendingTask?.cancel()
162
197
  pendingTask = nil
198
+ stopStallWatch()
199
+ }
200
+
201
+ // MARK: - Stalls
202
+
203
+ /// Starts the stall watch: a `stallTimeout` in which `bufferedPosition` does not advance makes
204
+ /// the stall a `.stall` failure, provided the play intent holds and no retry is pending; one in
205
+ /// which it advances starts another. Any failure ends it.
206
+ func startStallWatch() {
207
+ stallTask?.cancel()
208
+ let buffered = bufferedPosition()
209
+ stallTask = Task { [weak self, stallTimeout] in
210
+ try? await Task.sleep(for: stallTimeout)
211
+ guard let self, !Task.isCancelled else { return }
212
+ stallTask = nil
213
+ if bufferedPosition() > buffered { return startStallWatch() }
214
+ guard pendingTask == nil, shouldRetry() else { return }
215
+ handleFailure(.stall)
216
+ }
217
+ }
218
+
219
+ func stopStallWatch() {
220
+ stallTask?.cancel()
221
+ stallTask = nil
163
222
  }
164
223
 
165
224
  /// Drops the retry in flight and refills the budgets.
@@ -212,7 +271,7 @@ final class RetryLoop {
212
271
 
213
272
  /// Waits out the backoff, or connectivity's return, then calls `onRetry`. False when the policy,
214
273
  /// the play intent or a budget says stop, or the wait was cancelled.
215
- func attemptRetry(startFromCurrentTime: Bool) async -> Bool {
274
+ func attemptRetry(startFromCurrentTime: Bool, immediately: Bool = false) async -> Bool {
216
275
  guard isEnabled, shouldRetry() else { return false }
217
276
  if case let .limited(maxRetries) = policy, attempts >= maxRetries {
218
277
  logger.info("Max retries (\(maxRetries)) exceeded, giving up")
@@ -230,8 +289,9 @@ final class RetryLoop {
230
289
  return false
231
290
  }
232
291
 
233
- logger.info("Scheduling retry after \(self.backoff)s")
234
- guard await waitForDelayOrNetworkRestored(delaySeconds: backoff), !Task.isCancelled, shouldRetry() else {
292
+ let delay = immediately ? 0 : backoff
293
+ logger.info("Scheduling retry after \(delay)s")
294
+ guard await waitForDelayOrNetworkRestored(delaySeconds: delay), !Task.isCancelled, shouldRetry() else {
235
295
  return false
236
296
  }
237
297
  // The wait for connectivity may have been long.
@@ -0,0 +1,210 @@
1
+ import Foundation
2
+ import Testing
3
+
4
+ @testable import AudioBrowserTestable
5
+
6
+ @Suite("awaitCallback")
7
+ struct AwaitCallbackTests {
8
+ struct Rejected: Error, Equatable {}
9
+
10
+ /// A JS callback's pending answer: records the subscriber's `deliver`, which the test calls
11
+ /// as JS would, on any thread and as often as it likes.
12
+ final class FakeCallback: @unchecked Sendable {
13
+ private let lock = NSLock()
14
+ private var delivers: [@Sendable (Result<Int, Error>) -> Void] = []
15
+
16
+ var subscribe: CallbackSubscription<Int> {
17
+ { deliver in self.lock.withLock { self.delivers.append(deliver) } }
18
+ }
19
+
20
+ var isSubscribed: Bool {
21
+ lock.withLock { !delivers.isEmpty }
22
+ }
23
+
24
+ func settle(_ result: Result<Int, Error>) {
25
+ for deliver in lock.withLock({ delivers }) {
26
+ deliver(result)
27
+ }
28
+ }
29
+
30
+ func waitForSubscriber() async {
31
+ while !isSubscribed {
32
+ await Task.yield()
33
+ }
34
+ }
35
+ }
36
+
37
+ static let raceRuns = 500
38
+
39
+ // MARK: - Without a timeout
40
+
41
+ @Test func anAnswerResumesWithIt() async throws {
42
+ let callback = FakeCallback()
43
+ let result = try await withinTimeLimit {
44
+ try await awaitCallback { deliver in
45
+ callback.subscribe(deliver)
46
+ callback.settle(.success(7))
47
+ }
48
+ }
49
+ #expect(result == 7)
50
+ }
51
+
52
+ @Test func aRejectionThrowsIt() async throws {
53
+ let callback = FakeCallback()
54
+ await #expect(throws: Rejected.self) {
55
+ try await withinTimeLimit {
56
+ try await awaitCallback { deliver in
57
+ callback.subscribe(deliver)
58
+ callback.settle(.failure(Rejected()))
59
+ }
60
+ }
61
+ }
62
+ }
63
+
64
+ @Test func aCancelledCallerEndsWhileJSIsSilent() async throws {
65
+ let callback = FakeCallback()
66
+ let waiting = Task { try await awaitCallback(callback.subscribe) }
67
+ await callback.waitForSubscriber()
68
+ waiting.cancel()
69
+ await #expect(throws: CancellationError.self) {
70
+ try await withinTimeLimit { try await waiting.value }
71
+ }
72
+ callback.settle(.success(1))
73
+ }
74
+
75
+ @Test func aCallerCancelledBeforeTheAwaitEndsAtOnce() async throws {
76
+ let callback = FakeCallback()
77
+ await #expect(throws: CancellationError.self) {
78
+ try await withinTimeLimit {
79
+ withUnsafeCurrentTask { $0?.cancel() }
80
+ return try await awaitCallback(callback.subscribe)
81
+ }
82
+ }
83
+ }
84
+
85
+ @Test func anAnswerAndACancelTogetherResumeOnce() async throws {
86
+ var answered = 0
87
+ var cancelled = 0
88
+ for _ in 0 ..< Self.raceRuns {
89
+ let callback = FakeCallback()
90
+ let waiting = Task { try await awaitCallback(callback.subscribe) }
91
+ await callback.waitForSubscriber()
92
+ let go = Flag()
93
+ let answer = Task.detached {
94
+ while !go.isSet {}
95
+ callback.settle(.success(3))
96
+ }
97
+ let cancel = Task.detached {
98
+ while !go.isSet {}
99
+ waiting.cancel()
100
+ }
101
+ go.set()
102
+ await answer.value
103
+ await cancel.value
104
+ let outcome = try await withinTimeLimit { await waiting.result }
105
+ switch outcome {
106
+ case let .success(value):
107
+ #expect(value == 3)
108
+ answered += 1
109
+ case let .failure(error):
110
+ #expect(error is CancellationError)
111
+ cancelled += 1
112
+ }
113
+ }
114
+ #expect(answered > 0 && cancelled > 0, "answered \(answered), cancelled \(cancelled)")
115
+ }
116
+
117
+ @Test func aRejectAfterACancelIsIgnored() async throws {
118
+ for _ in 0 ..< Self.raceRuns {
119
+ let callback = FakeCallback()
120
+ let waiting = Task { try await awaitCallback(callback.subscribe) }
121
+ await callback.waitForSubscriber()
122
+ waiting.cancel()
123
+ await Task.detached { callback.settle(.failure(Rejected())) }.value
124
+ await #expect(throws: CancellationError.self) {
125
+ try await withinTimeLimit { try await waiting.value }
126
+ }
127
+ }
128
+ }
129
+
130
+ // MARK: - With a timeout
131
+
132
+ @Test func silentJSTimesOutAndNotBefore() async throws {
133
+ let callback = FakeCallback()
134
+ let waiting = Task { try await awaitCallback(timeout: .milliseconds(600), callback.subscribe) }
135
+ let finished = Flag()
136
+ Task {
137
+ _ = await waiting.result
138
+ finished.set()
139
+ }
140
+ try await Task.sleep(for: .milliseconds(200))
141
+ #expect(!finished.isSet)
142
+ await #expect(throws: CallbackTimeoutError.self) {
143
+ try await withinTimeLimit { try await waiting.value }
144
+ }
145
+ }
146
+
147
+ @Test func anAnswerInsideTheTimeoutIsKept() async throws {
148
+ let callback = FakeCallback()
149
+ let waiting = Task { try await awaitCallback(timeout: .seconds(5), callback.subscribe) }
150
+ await callback.waitForSubscriber()
151
+ callback.settle(.success(4))
152
+ #expect(try await withinTimeLimit { try await waiting.value } == 4)
153
+ }
154
+
155
+ @Test func aCancelledCallerWithATimeoutPendingEndsWithItsCancellation() async throws {
156
+ let callback = FakeCallback()
157
+ let waiting = Task { try await awaitCallback(timeout: .seconds(5), callback.subscribe) }
158
+ await callback.waitForSubscriber()
159
+ waiting.cancel()
160
+ await #expect(throws: CancellationError.self) {
161
+ try await withinTimeLimit { try await waiting.value }
162
+ }
163
+ }
164
+
165
+ /// Spreads each run's settle from before the timeout to after it.
166
+ static func delay(_ run: Int) -> Duration {
167
+ .microseconds(run * 10000 / raceRuns)
168
+ }
169
+
170
+ @Test func anAnswerAroundTheTimeoutResumesOnce() async throws {
171
+ var answered = 0
172
+ var timedOut = 0
173
+ for run in 0 ..< Self.raceRuns {
174
+ let callback = FakeCallback()
175
+ let waiting = Task { try await awaitCallback(timeout: .milliseconds(5), callback.subscribe) }
176
+ await callback.waitForSubscriber()
177
+ try await Task.sleep(for: Self.delay(run))
178
+ await Task.detached { callback.settle(.success(5)) }.value
179
+ let outcome = try await withinTimeLimit { await waiting.result }
180
+ switch outcome {
181
+ case let .success(value):
182
+ #expect(value == 5)
183
+ answered += 1
184
+ case let .failure(error):
185
+ #expect(error is CallbackTimeoutError)
186
+ timedOut += 1
187
+ }
188
+ }
189
+ #expect(answered > 0 && timedOut > 0, "answered \(answered), timed out \(timedOut)")
190
+ }
191
+
192
+ @Test func aCancelAroundTheTimeoutResumesOnce() async throws {
193
+ var cancelled = 0
194
+ var timedOut = 0
195
+ for run in 0 ..< Self.raceRuns {
196
+ let callback = FakeCallback()
197
+ let waiting = Task { try await awaitCallback(timeout: .milliseconds(5), callback.subscribe) }
198
+ await callback.waitForSubscriber()
199
+ try await Task.sleep(for: Self.delay(run))
200
+ waiting.cancel()
201
+ let outcome = try await withinTimeLimit { await waiting.result }
202
+ switch outcome {
203
+ case .failure(is CancellationError): cancelled += 1
204
+ case .failure(is CallbackTimeoutError): timedOut += 1
205
+ default: Issue.record("resumed with \(outcome)")
206
+ }
207
+ }
208
+ #expect(cancelled > 0 && timedOut > 0, "cancelled \(cancelled), timed out \(timedOut)")
209
+ }
210
+ }
@@ -118,4 +118,61 @@ struct GenerationMemoTests {
118
118
  await #expect(throws: CancellationError.self) { try await result.value }
119
119
  #expect(gate.runs == 1)
120
120
  }
121
+
122
+ @Test func aCancelledCallerLeavesWhileTheComputationRunsOn() async throws {
123
+ let memo = GenerationMemo<Int>()
124
+ let gate = Gate()
125
+ gate.input = 5
126
+ let cancelled = Task { try await memo.value { await gate.run() } }
127
+ let other = Task { try await memo.value { await gate.run() } }
128
+ await gate.waitForRuns(1)
129
+ cancelled.cancel()
130
+ await #expect(throws: CancellationError.self) {
131
+ try await withinTimeLimit { try await cancelled.value }
132
+ }
133
+ gate.release()
134
+ #expect(try await withinTimeLimit { try await other.value } == 5)
135
+ #expect(gate.runs == 1)
136
+ }
137
+
138
+ @Test func aCallerAfterACancelledOneJoinsTheRunningComputation() async throws {
139
+ let memo = GenerationMemo<Int>()
140
+ let gate = Gate()
141
+ gate.input = 6
142
+ let cancelled = Task { try await memo.value { await gate.run() } }
143
+ await gate.waitForRuns(1)
144
+ cancelled.cancel()
145
+ _ = try await withinTimeLimit { await cancelled.result }
146
+ let later = Task { try await memo.value { await gate.run() } }
147
+ for _ in 0 ..< 100 {
148
+ await Task.yield()
149
+ }
150
+ gate.release()
151
+ #expect(try await withinTimeLimit { try await later.value } == 6)
152
+ #expect(gate.runs == 1)
153
+ }
154
+
155
+ @Test func aFailureAfterEveryCallerLeftIsNotKept() async throws {
156
+ let memo = GenerationMemo<Int>()
157
+ let gate = Gate()
158
+ let cancelled = Task {
159
+ try await memo.value {
160
+ let input = await gate.run()
161
+ if input == 0 { throw Failure() }
162
+ return input
163
+ }
164
+ }
165
+ await gate.waitForRuns(1)
166
+ cancelled.cancel()
167
+ _ = try await withinTimeLimit { await cancelled.result }
168
+ gate.release()
169
+ for _ in 0 ..< 100 {
170
+ await Task.yield()
171
+ }
172
+ gate.input = 7
173
+ let later = Task { try await memo.value { await gate.run() } }
174
+ await gate.waitForRuns(2)
175
+ gate.release()
176
+ #expect(try await withinTimeLimit { try await later.value } == 7)
177
+ }
121
178
  }
@@ -90,6 +90,13 @@ struct PlaybackFailureRetryTests {
90
90
  #expect(!retryable(URLError(.timedOut), status: status))
91
91
  }
92
92
 
93
+ /// A live stream's error log keeps the 200 of the connection that played.
94
+ @Test func aSuccessStatusLeavesItToTheErrorChain() {
95
+ #expect(retryable(URLError(.networkConnectionLost), status: 200))
96
+ #expect(retryable(NSError(domain: "CoreMediaErrorDomain", code: -16830), status: 206))
97
+ #expect(!retryable(URLError(.badURL), status: 200))
98
+ }
99
+
93
100
  @Test func aTransientURLErrorRetries() {
94
101
  #expect(retryable(URLError(.networkConnectionLost)))
95
102
  }