react-native-audio-browser 0.2.0-next.81 → 0.2.0-next.82
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.
- package/ios/Browser/BrowseGate.swift +14 -1
- package/ios/CarPlay/CarPlayNowPlayingManager.swift +23 -19
- package/ios/CarPlay/CarPlaySession+TabBar.swift +3 -5
- package/ios/CarPlay/MediaIntentHandler.swift +7 -2
- package/ios/CarPlay/MediaIntentPlayback.swift +23 -12
- package/ios/HybridAudioBrowser+Options.swift +1 -1
- package/ios/Model/NitroTypeStubs.swift +25 -0
- package/ios/Player/PlaybackStateMachine.swift +4 -3
- package/ios/Player/Player.swift +31 -18
- package/ios/Player/RetryLoop.swift +186 -193
- package/ios/Tests/BrowseGateTests.swift +50 -0
- package/ios/Tests/ConnectivityTests.swift +13 -0
- package/ios/Tests/MediaIntentDeadlineTests.swift +75 -0
- package/ios/Tests/PlaybackStateMachineTests.swift +6 -6
- package/ios/Tests/PlayerPolicyTests.swift +163 -50
- package/ios/Tests/PlayerTests.swift +11 -85
- package/ios/Tests/RetryLoopTests.swift +296 -120
- package/ios/Tests/SupersedingTaskTests.swift +148 -0
- package/ios/Tests/Support/TestTypes.swift +99 -8
- package/ios/Util/Connectivity.swift +12 -0
- package/ios/Util/Deadline.swift +38 -0
- package/ios/Util/NetworkMonitor.swift +2 -2
- package/ios/Util/SupersedingTask.swift +45 -0
- package/package.json +1 -1
|
@@ -5,12 +5,6 @@ import Foundation
|
|
|
5
5
|
#endif
|
|
6
6
|
import os.log
|
|
7
7
|
|
|
8
|
-
/// Connectivity as `RetryLoop` sees it; a fake stands in for `NetworkMonitor` in tests. Sendable
|
|
9
|
-
/// because the network-restore wait reads it from a task-group child.
|
|
10
|
-
protocol NetworkStatusProviding: AnyObject, Sendable {
|
|
11
|
-
var isOnline: Bool { get }
|
|
12
|
-
}
|
|
13
|
-
|
|
14
8
|
/// Where a failure came from, which decides where the retry resumes and the error reported when
|
|
15
9
|
/// the failure cannot be classified.
|
|
16
10
|
public enum PlaybackErrorContext {
|
|
@@ -41,57 +35,54 @@ public enum PlaybackErrorContext {
|
|
|
41
35
|
}
|
|
42
36
|
}
|
|
43
37
|
|
|
44
|
-
///
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
///
|
|
51
|
-
|
|
38
|
+
/// Milliseconds on a clock that does not jump, and sleeps on it.
|
|
39
|
+
protocol RetryClock: Sendable {
|
|
40
|
+
var nowMs: Int { get }
|
|
41
|
+
func sleep(ms: Int) async throws
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/// Counts while the device sleeps, so a silence spans it.
|
|
45
|
+
struct ContinuousRetryClock: RetryClock {
|
|
46
|
+
private let origin = ContinuousClock.now
|
|
47
|
+
var nowMs: Int { Int((ContinuousClock.now - origin) / .milliseconds(1)) }
|
|
48
|
+
func sleep(ms: Int) async throws { try await Task.sleep(for: .milliseconds(ms)) }
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/// Reconnects failed loads, paced by `ReconnectPacer`, and gives up when `SilenceBudget`'s
|
|
52
|
+
/// deadline passes (docs/adr/0014), reporting the last failure as terminal; the iOS counterpart
|
|
53
|
+
/// of Android's RetryLoadErrorHandlingPolicy. The play intent and connectivity go to both units.
|
|
52
54
|
@MainActor
|
|
53
55
|
final class RetryLoop {
|
|
54
56
|
private let logger = Logger(subsystem: "com.audiobrowser", category: "RetryLoop")
|
|
55
57
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
private
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
private var
|
|
68
|
-
private var
|
|
58
|
+
private(set) var isEnabled = false
|
|
59
|
+
private var playIntent = false
|
|
60
|
+
private var budget: SilenceBudget
|
|
61
|
+
private var pacer: ReconnectPacer
|
|
62
|
+
private var connectionStartedAtMs: Int?
|
|
63
|
+
private var connectionDeliveredAudio = false
|
|
64
|
+
/// AVFoundation can report one connection's failure more than once; the units hear its end once.
|
|
65
|
+
private var connectionEndReported = false
|
|
66
|
+
private var replacedConnectionCounts = false
|
|
67
|
+
/// True from a connection's start until a cancel or a terminal error, so a give-up reports one
|
|
68
|
+
/// error, and a stop, or a play with nothing loaded, leaves nothing to give up on.
|
|
69
|
+
private var deadlineArmed = false
|
|
70
|
+
private var lastFailure: TrackPlayerError.PlaybackError?
|
|
71
|
+
private var deadlineTask: Task<Void, Never>?
|
|
69
72
|
|
|
70
|
-
/// Whether the current Load has produced audio. Read from the Load, not kept here, because a
|
|
71
|
-
/// healthy-playback `reset()` must not clear it.
|
|
72
|
-
var hasPlayed: () -> Bool = { false }
|
|
73
|
-
/// The play intent; checked before and after the backoff.
|
|
74
|
-
var shouldRetry: () -> Bool = { true }
|
|
75
73
|
/// Reloads; the argument is true to resume from the current time, false to start over.
|
|
76
74
|
var onRetry: ((Bool) -> Void)?
|
|
77
|
-
/// Terminal: the
|
|
78
|
-
/// is cancelled.
|
|
75
|
+
/// Terminal: the deadline passed, `maxRetries` connections in a row delivered nothing, or the
|
|
76
|
+
/// failure cannot be retried. Not called when the retry is cancelled.
|
|
79
77
|
var onError: ((TrackPlayerError.PlaybackError) -> Void)?
|
|
80
|
-
/// A failure a retry is now scheduled for, reported before the
|
|
78
|
+
/// A failure a retry is now scheduled for, reported before the wait while the state stays
|
|
81
79
|
/// non-terminal.
|
|
82
80
|
var onRetryingError: ((TrackPlayerError.PlaybackError) -> Void)?
|
|
83
81
|
/// A retryable failure with no play intent: nothing retries it and nothing reports it.
|
|
84
82
|
var onFailedWithoutIntent: (() -> Void)?
|
|
85
83
|
|
|
86
|
-
weak var networkMonitor: (any NetworkStatusProviding)?
|
|
87
|
-
|
|
88
84
|
/// The retry in flight; session release waits while there is one.
|
|
89
85
|
private(set) var pendingTask: Task<Void, Never>?
|
|
90
|
-
private(set) var attempts = 0
|
|
91
|
-
|
|
92
|
-
/// Continuous audible playback after which the budgets refill (Android's HEALTHY_PLAYBACK_MS).
|
|
93
|
-
var healthyPlaybackDuration: Duration = .seconds(20)
|
|
94
|
-
private(set) var healthyPlaybackTask: Task<Void, Never>?
|
|
95
86
|
|
|
96
87
|
/// How long a stall may go without new data before it counts as a failure; longer than AVPlayer
|
|
97
88
|
/// takes to fail a stalled item itself, so its error, which says more, is the one usually retried.
|
|
@@ -100,44 +91,105 @@ final class RetryLoop {
|
|
|
100
91
|
var bufferedPosition: () -> Double = { 0 }
|
|
101
92
|
private(set) var stallTask: Task<Void, Never>?
|
|
102
93
|
|
|
103
|
-
private
|
|
104
|
-
private
|
|
105
|
-
// The first-connect budget's clock: never set while offline and wiped by any offline
|
|
106
|
-
// observation, so an offline stretch cannot burn the short budget.
|
|
107
|
-
private var firstOnlineRetryTime: Date?
|
|
108
|
-
|
|
109
|
-
private let sleep: @Sendable (TimeInterval) async throws -> Void
|
|
94
|
+
private let clock: any RetryClock
|
|
95
|
+
private let sleep: @Sendable (Int) async throws -> Void
|
|
110
96
|
|
|
97
|
+
/// - Parameters:
|
|
98
|
+
/// - online: Connectivity when the loop is made; `onlineChanged` reports each change after.
|
|
99
|
+
/// - sleep: The wait before a reconnect, in milliseconds; the clock's sleep by default.
|
|
111
100
|
init(
|
|
112
|
-
|
|
113
|
-
|
|
101
|
+
online: Bool = true,
|
|
102
|
+
clock: any RetryClock = ContinuousRetryClock(),
|
|
103
|
+
sleep: (@Sendable (Int) async throws -> Void)? = nil,
|
|
114
104
|
) {
|
|
115
|
-
|
|
116
|
-
|
|
105
|
+
budget = SilenceBudget(online: online)
|
|
106
|
+
pacer = ReconnectPacer(online: online)
|
|
107
|
+
self.clock = clock
|
|
108
|
+
self.sleep = sleep ?? { try await clock.sleep(ms: $0) }
|
|
117
109
|
}
|
|
118
110
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
return true
|
|
122
|
-
}
|
|
111
|
+
/// Whether the current Load has produced audio (docs/adr/0004).
|
|
112
|
+
var hasPlayed: Bool { budget.hasPlayed }
|
|
123
113
|
|
|
124
114
|
// MARK: - Configuration
|
|
125
115
|
|
|
126
116
|
func updatePolicy(from config: Variant_Bool_RetryConfig?) {
|
|
127
|
-
|
|
128
|
-
|
|
117
|
+
budget.recoveryMs = 120_000
|
|
118
|
+
budget.firstConnectMs = 12_000
|
|
119
|
+
pacer.maxRetries = nil
|
|
129
120
|
switch config {
|
|
130
121
|
case nil:
|
|
131
|
-
|
|
122
|
+
isEnabled = false
|
|
132
123
|
case let .first(enabled):
|
|
133
|
-
|
|
124
|
+
isEnabled = enabled
|
|
134
125
|
case let .second(retryConfig):
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
126
|
+
isEnabled = true
|
|
127
|
+
retryConfig.maxRetryDurationMs.map { budget.recoveryMs = Int($0) }
|
|
128
|
+
retryConfig.firstConnectMaxRetryDurationMs.map { budget.firstConnectMs = Int($0) }
|
|
129
|
+
pacer.maxRetries = retryConfig.maxRetries.map { Int($0) }
|
|
130
|
+
}
|
|
131
|
+
logger.debug("Retry enabled: \(self.isEnabled), max retries \(String(describing: self.pacer.maxRetries))")
|
|
132
|
+
armDeadline()
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// MARK: - Inputs
|
|
136
|
+
|
|
137
|
+
/// A new Load: a track change, or a restart from the terminal error. Drops the retry in flight.
|
|
138
|
+
func loadStarted() {
|
|
139
|
+
cancel()
|
|
140
|
+
lastFailure = nil
|
|
141
|
+
replacedConnectionCounts = false
|
|
142
|
+
budget.loadStarted(atMs: clock.nowMs)
|
|
143
|
+
pacer.reset()
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/// A connect going out: the Load's first, a reconnect, or a reload by the Player, which ends the
|
|
147
|
+
/// connection it replaces. A replaced connection counts only if it delivered audio: one cut off
|
|
148
|
+
/// while connecting says nothing about the source.
|
|
149
|
+
func connectionStarted() {
|
|
150
|
+
let now = clock.nowMs
|
|
151
|
+
if let startedAtMs = connectionStartedAtMs, replacedConnectionCounts, connectionDeliveredAudio, !connectionEndReported {
|
|
152
|
+
pacer.connectionEnded(deliveredAudio: true, startedAtMs: startedAtMs, atMs: now)
|
|
153
|
+
}
|
|
154
|
+
connectionStartedAtMs = now
|
|
155
|
+
replacedConnectionCounts = true
|
|
156
|
+
connectionDeliveredAudio = false
|
|
157
|
+
connectionEndReported = false
|
|
158
|
+
deadlineArmed = true
|
|
159
|
+
armDeadline()
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
func playIntentChanged(_ up: Bool) {
|
|
163
|
+
guard up != playIntent else { return }
|
|
164
|
+
playIntent = up
|
|
165
|
+
if up {
|
|
166
|
+
lastFailure = nil
|
|
167
|
+
// The pacer starts over: a reload now does not count the connection it replaces.
|
|
168
|
+
replacedConnectionCounts = false
|
|
139
169
|
}
|
|
140
|
-
|
|
170
|
+
budget.playIntentChanged(up, atMs: clock.nowMs)
|
|
171
|
+
pacer.playIntentChanged(up)
|
|
172
|
+
armDeadline()
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
func onlineChanged(_ online: Bool) {
|
|
176
|
+
budget.onlineChanged(online)
|
|
177
|
+
pacer.onlineChanged(online)
|
|
178
|
+
armDeadline()
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/// Audio clears the failure the deadline would report: a silence after it that ends with no
|
|
182
|
+
/// failure is a stall.
|
|
183
|
+
func playbackBecameAudible() {
|
|
184
|
+
connectionDeliveredAudio = true
|
|
185
|
+
lastFailure = nil
|
|
186
|
+
budget.audioStarted(atMs: clock.nowMs)
|
|
187
|
+
armDeadline()
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
func playbackStoppedBeingAudible() {
|
|
191
|
+
budget.audioStopped(atMs: clock.nowMs)
|
|
192
|
+
armDeadline()
|
|
141
193
|
}
|
|
142
194
|
|
|
143
195
|
// MARK: - Failures
|
|
@@ -157,45 +209,97 @@ final class RetryLoop {
|
|
|
157
209
|
}
|
|
158
210
|
|
|
159
211
|
/// A failure the Player judges from what playback did, with no error to classify: retryable,
|
|
160
|
-
/// and reported as the context's fallback error.
|
|
161
|
-
func handleFailure(_ context: PlaybackErrorContext
|
|
212
|
+
/// and reported as the context's fallback error.
|
|
213
|
+
func handleFailure(_ context: PlaybackErrorContext) {
|
|
162
214
|
logger.error("[\(String(describing: context))] failure")
|
|
163
|
-
handle(.init(error: context.fallbackError, retryable: true), context: context
|
|
215
|
+
handle(.init(error: context.fallbackError, retryable: true), context: context)
|
|
164
216
|
}
|
|
165
217
|
|
|
166
|
-
private func handle(
|
|
167
|
-
_ failure: PlaybackFailure.Classification, context: PlaybackErrorContext, immediately: Bool = false,
|
|
168
|
-
) {
|
|
218
|
+
private func handle(_ failure: PlaybackFailure.Classification, context: PlaybackErrorContext) {
|
|
169
219
|
stopStallWatch()
|
|
170
220
|
guard isEnabled, failure.retryable else {
|
|
171
221
|
let reason = isEnabled ? "Error not retryable" : "Retry disabled"
|
|
172
222
|
logger.warning("\(reason), surfacing \(String(describing: failure.error))")
|
|
173
|
-
|
|
174
|
-
return
|
|
223
|
+
return giveUp(failure.error)
|
|
175
224
|
}
|
|
176
|
-
guard
|
|
225
|
+
guard playIntent else {
|
|
177
226
|
logger.info("No play intent: \(String(describing: failure.error)) is left to the next play")
|
|
178
227
|
onFailedWithoutIntent?()
|
|
179
228
|
return
|
|
180
229
|
}
|
|
230
|
+
lastFailure = failure.error
|
|
231
|
+
let now = clock.nowMs
|
|
232
|
+
if !connectionEndReported {
|
|
233
|
+
connectionEndReported = true
|
|
234
|
+
// The Player can stay .playing on a failure, on buffered audio that is about to run out.
|
|
235
|
+
budget.audioStopped(atMs: now)
|
|
236
|
+
budget.connectionEnded(atMs: now)
|
|
237
|
+
pacer.connectionEnded(deliveredAudio: connectionDeliveredAudio, startedAtMs: connectionStartedAtMs ?? now, atMs: now)
|
|
238
|
+
}
|
|
181
239
|
onRetryingError?(failure.error)
|
|
240
|
+
armDeadline()
|
|
182
241
|
pendingTask?.cancel()
|
|
183
242
|
pendingTask = Task { [weak self] in
|
|
184
|
-
|
|
185
|
-
|
|
243
|
+
await self?.reconnect(startFromCurrentTime: context.startFromCurrentTime)
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/// Asks the pacer again every half second at most, so a change in connectivity or a passed
|
|
248
|
+
/// deadline is seen without waiting out the whole wait.
|
|
249
|
+
private func reconnect(startFromCurrentTime: Bool) async {
|
|
250
|
+
while !Task.isCancelled {
|
|
251
|
+
if let deadline = budget.deadlineMs, deadline <= clock.nowMs {
|
|
252
|
+
return giveUp(lastFailure ?? .playbackStalled)
|
|
253
|
+
}
|
|
254
|
+
let waitMs: Int
|
|
255
|
+
switch pacer.wait(atMs: clock.nowMs) {
|
|
256
|
+
case .giveUp:
|
|
257
|
+
logger.info("Max retries (\(self.pacer.maxRetries ?? 0)) exceeded, giving up")
|
|
258
|
+
return giveUp(lastFailure ?? .playbackStalled)
|
|
259
|
+
case .untilOnline:
|
|
260
|
+
waitMs = 500
|
|
261
|
+
case let .after(ms):
|
|
262
|
+
waitMs = min(ms, 500)
|
|
263
|
+
}
|
|
264
|
+
if waitMs == 0 { break }
|
|
186
265
|
// Cancelled by a track change or stop: stay silent, or the new track or the stop would
|
|
187
266
|
// flip to .error. The canceller owns `pendingTask`.
|
|
188
|
-
|
|
189
|
-
if !retried { onError?(failure.error) }
|
|
190
|
-
pendingTask = nil
|
|
267
|
+
guard await (try? sleep(waitMs)) != nil else { return }
|
|
191
268
|
}
|
|
269
|
+
if Task.isCancelled { return }
|
|
270
|
+
pendingTask = nil
|
|
271
|
+
logger.info("Reconnecting")
|
|
272
|
+
onRetry?(startFromCurrentTime)
|
|
192
273
|
}
|
|
193
274
|
|
|
194
|
-
|
|
275
|
+
private func giveUp(_ error: TrackPlayerError.PlaybackError) {
|
|
276
|
+
cancel()
|
|
277
|
+
onError?(error)
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
/// Drops the retry in flight, the stall watch and the deadline until the next connection starts.
|
|
195
281
|
func cancel() {
|
|
196
282
|
pendingTask?.cancel()
|
|
197
283
|
pendingTask = nil
|
|
198
284
|
stopStallWatch()
|
|
285
|
+
deadlineTask?.cancel()
|
|
286
|
+
deadlineTask = nil
|
|
287
|
+
deadlineArmed = false
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
// MARK: - Deadline
|
|
291
|
+
|
|
292
|
+
private func armDeadline() {
|
|
293
|
+
deadlineTask?.cancel()
|
|
294
|
+
deadlineTask = nil
|
|
295
|
+
guard isEnabled, deadlineArmed, let deadline = budget.deadlineMs else { return }
|
|
296
|
+
deadlineTask = Task { [weak self, clock] in
|
|
297
|
+
let remaining = deadline - clock.nowMs
|
|
298
|
+
if remaining > 0 { guard await (try? clock.sleep(ms: remaining)) != nil else { return } }
|
|
299
|
+
guard let self, !Task.isCancelled else { return }
|
|
300
|
+
logger.info("Silent past the deadline, giving up")
|
|
301
|
+
giveUp(lastFailure ?? .playbackStalled)
|
|
302
|
+
}
|
|
199
303
|
}
|
|
200
304
|
|
|
201
305
|
// MARK: - Stalls
|
|
@@ -211,7 +315,7 @@ final class RetryLoop {
|
|
|
211
315
|
guard let self, !Task.isCancelled else { return }
|
|
212
316
|
stallTask = nil
|
|
213
317
|
if bufferedPosition() > buffered { return startStallWatch() }
|
|
214
|
-
guard pendingTask == nil,
|
|
318
|
+
guard pendingTask == nil, playIntent else { return }
|
|
215
319
|
handleFailure(.stall)
|
|
216
320
|
}
|
|
217
321
|
}
|
|
@@ -220,115 +324,4 @@ final class RetryLoop {
|
|
|
220
324
|
stallTask?.cancel()
|
|
221
325
|
stallTask = nil
|
|
222
326
|
}
|
|
223
|
-
|
|
224
|
-
/// Drops the retry in flight and refills the budgets.
|
|
225
|
-
func reset() {
|
|
226
|
-
cancel()
|
|
227
|
-
attempts = 0
|
|
228
|
-
firstRetryTime = nil
|
|
229
|
-
firstOnlineRetryTime = nil
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
// MARK: - Healthy Playback
|
|
233
|
-
|
|
234
|
-
/// Starts the healthy-playback window; if it elapses with no retry pending, the budgets refill.
|
|
235
|
-
func playbackBecameAudible() {
|
|
236
|
-
healthyPlaybackTask?.cancel()
|
|
237
|
-
healthyPlaybackTask = Task { [weak self, healthyPlaybackDuration] in
|
|
238
|
-
try? await Task.sleep(for: healthyPlaybackDuration)
|
|
239
|
-
guard let self, !Task.isCancelled else { return }
|
|
240
|
-
// reset() would cancel the pending retry and silently kill an in-flight reconnect.
|
|
241
|
-
guard pendingTask == nil else { return }
|
|
242
|
-
reset()
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
func playbackStoppedBeingAudible() {
|
|
247
|
-
healthyPlaybackTask?.cancel()
|
|
248
|
-
healthyPlaybackTask = nil
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
// MARK: - Budgets
|
|
252
|
-
|
|
253
|
-
private var isOnline: Bool { networkMonitor?.isOnline ?? true }
|
|
254
|
-
|
|
255
|
-
private func exhaustedBudget() -> String? {
|
|
256
|
-
let now = Date()
|
|
257
|
-
if let start = firstRetryTime, now.timeIntervalSince(start) >= maxRetryDuration {
|
|
258
|
-
return "max retry duration (\(maxRetryDuration)s)"
|
|
259
|
-
}
|
|
260
|
-
if !hasPlayed(), isOnline, let start = firstOnlineRetryTime,
|
|
261
|
-
now.timeIntervalSince(start) >= firstConnectMaxRetryDuration
|
|
262
|
-
{
|
|
263
|
-
return "first-connect retry duration (\(firstConnectMaxRetryDuration)s)"
|
|
264
|
-
}
|
|
265
|
-
return nil
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
private var backoff: TimeInterval {
|
|
269
|
-
min(1.0 * pow(1.5, Double(attempts)), 5.0)
|
|
270
|
-
}
|
|
271
|
-
|
|
272
|
-
/// Waits out the backoff, or connectivity's return, then calls `onRetry`. False when the policy,
|
|
273
|
-
/// the play intent or a budget says stop, or the wait was cancelled.
|
|
274
|
-
func attemptRetry(startFromCurrentTime: Bool, immediately: Bool = false) async -> Bool {
|
|
275
|
-
guard isEnabled, shouldRetry() else { return false }
|
|
276
|
-
if case let .limited(maxRetries) = policy, attempts >= maxRetries {
|
|
277
|
-
logger.info("Max retries (\(maxRetries)) exceeded, giving up")
|
|
278
|
-
return false
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
if firstRetryTime == nil { firstRetryTime = Date() }
|
|
282
|
-
if isOnline {
|
|
283
|
-
if firstOnlineRetryTime == nil { firstOnlineRetryTime = Date() }
|
|
284
|
-
} else {
|
|
285
|
-
firstOnlineRetryTime = nil
|
|
286
|
-
}
|
|
287
|
-
if let budget = exhaustedBudget() {
|
|
288
|
-
logger.info("\(budget) exceeded, giving up")
|
|
289
|
-
return false
|
|
290
|
-
}
|
|
291
|
-
|
|
292
|
-
let delay = immediately ? 0 : backoff
|
|
293
|
-
logger.info("Scheduling retry after \(delay)s")
|
|
294
|
-
guard await waitForDelayOrNetworkRestored(delaySeconds: delay), !Task.isCancelled, shouldRetry() else {
|
|
295
|
-
return false
|
|
296
|
-
}
|
|
297
|
-
// The wait for connectivity may have been long.
|
|
298
|
-
if let budget = exhaustedBudget() {
|
|
299
|
-
logger.info("\(budget) exceeded after waiting, giving up")
|
|
300
|
-
return false
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
attempts += 1
|
|
304
|
-
logger.info("Executing retry #\(self.attempts)")
|
|
305
|
-
onRetry?(startFromCurrentTime)
|
|
306
|
-
return true
|
|
307
|
-
}
|
|
308
|
-
|
|
309
|
-
// MARK: - Network-Aware Waiting
|
|
310
|
-
|
|
311
|
-
/// True when it is time to retry, false when the wait was cancelled.
|
|
312
|
-
private func waitForDelayOrNetworkRestored(delaySeconds: TimeInterval) async -> Bool {
|
|
313
|
-
guard let monitor = networkMonitor, !monitor.isOnline else {
|
|
314
|
-
return await (try? sleep(delaySeconds)) != nil
|
|
315
|
-
}
|
|
316
|
-
logger.debug("Device is offline, will retry immediately when connectivity is restored")
|
|
317
|
-
let sleep = sleep
|
|
318
|
-
return await withTaskGroup(of: Bool.self, returning: Bool.self) { group in
|
|
319
|
-
group.addTask { await (try? sleep(delaySeconds)) != nil }
|
|
320
|
-
group.addTask { [weak self] in await self?.waitForNetworkRestored(monitor: monitor) ?? false }
|
|
321
|
-
let result = await group.next() ?? false
|
|
322
|
-
group.cancelAll()
|
|
323
|
-
return result
|
|
324
|
-
}
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
private func waitForNetworkRestored(monitor: any NetworkStatusProviding) async -> Bool {
|
|
328
|
-
while !monitor.isOnline {
|
|
329
|
-
guard await (try? sleep(0.5)) != nil else { return false }
|
|
330
|
-
}
|
|
331
|
-
logger.info("Network restored, accelerating retry")
|
|
332
|
-
return true
|
|
333
|
-
}
|
|
334
327
|
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import Testing
|
|
2
|
+
|
|
3
|
+
@testable import AudioBrowserTestable
|
|
4
|
+
|
|
5
|
+
@MainActor
|
|
6
|
+
@Suite("BrowseGate")
|
|
7
|
+
struct BrowseGateTests {
|
|
8
|
+
private let request = NativeGateRequest(reason: .search, path: nil, search: nil)
|
|
9
|
+
|
|
10
|
+
private func resolvedGate(_ resolve: @escaping @MainActor (NativeGateRequest) async throws -> GateDecision) -> BrowseGate {
|
|
11
|
+
let gate = BrowseGate()
|
|
12
|
+
gate.set(chrome: nil, hasResolver: true)
|
|
13
|
+
gate.resolve = resolve
|
|
14
|
+
return gate
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
@Test func reportsAGatedRequest() async {
|
|
18
|
+
let gate = resolvedGate { _ in GateDecision(gated: true, gate: nil) }
|
|
19
|
+
var reports: [GateReason] = []
|
|
20
|
+
let chrome = await gate.decide(request) { reports.append($0.reason) }
|
|
21
|
+
#expect(chrome?.title == BrowseGate.builtInChrome.title)
|
|
22
|
+
#expect(reports == [.search])
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
@Test func reportsNothingForAnAllowedRequest() async {
|
|
26
|
+
let gate = resolvedGate { _ in GateDecision(gated: false, gate: nil) }
|
|
27
|
+
var reports = 0
|
|
28
|
+
let chrome = await gate.decide(request) { _ in reports += 1 }
|
|
29
|
+
#expect(chrome == nil)
|
|
30
|
+
#expect(reports == 0)
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
@Test func aCancelledDecisionFailsClosedWithoutAReport() async {
|
|
34
|
+
var resolving = false
|
|
35
|
+
let gate = resolvedGate { _ in
|
|
36
|
+
resolving = true
|
|
37
|
+
return try await awaitCallback { (_: @escaping @Sendable (Result<GateDecision, Error>) -> Void) in }
|
|
38
|
+
}
|
|
39
|
+
var reports = 0
|
|
40
|
+
let decision = Task { await gate.decide(request) { _ in reports += 1 } }
|
|
41
|
+
for _ in 0 ..< 1000 where !resolving {
|
|
42
|
+
await Task.yield()
|
|
43
|
+
}
|
|
44
|
+
#expect(resolving)
|
|
45
|
+
decision.cancel()
|
|
46
|
+
let chrome = await decision.value
|
|
47
|
+
#expect(chrome?.title == BrowseGate.builtInChrome.title)
|
|
48
|
+
#expect(reports == 0)
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import Network
|
|
2
|
+
import Testing
|
|
3
|
+
|
|
4
|
+
@testable import AudioBrowserTestable
|
|
5
|
+
|
|
6
|
+
@Suite("Connectivity")
|
|
7
|
+
struct ConnectivityTests {
|
|
8
|
+
@Test func onlyAPathWithNoRouteIsOffline() {
|
|
9
|
+
#expect(NWPath.Status.satisfied.isOnline)
|
|
10
|
+
#expect(NWPath.Status.requiresConnection.isOnline)
|
|
11
|
+
#expect(!NWPath.Status.unsatisfied.isOnline)
|
|
12
|
+
}
|
|
13
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import Testing
|
|
2
|
+
|
|
3
|
+
@testable import AudioBrowserTestable
|
|
4
|
+
|
|
5
|
+
/// The Siri play-media intent's search under `withDeadline`, as `MediaIntentHandler` runs it. The
|
|
6
|
+
/// work's own cancellation guard stands in for `MediaIntentPlayback.livePlayer(of:)`, which needs
|
|
7
|
+
/// the bridge and is not compiled here. A search
|
|
8
|
+
/// answering in the same main-actor turn as the deadline is not covered: `withDeadline` settles both
|
|
9
|
+
/// on the main actor, cancelling before it answers nil.
|
|
10
|
+
@MainActor
|
|
11
|
+
@Suite("MediaIntentDeadline")
|
|
12
|
+
struct MediaIntentDeadlineTests {
|
|
13
|
+
private let deadline: Duration = .milliseconds(50)
|
|
14
|
+
private let found = [Track(src: "one.mp3", title: "One")]
|
|
15
|
+
|
|
16
|
+
@MainActor
|
|
17
|
+
final class Intent {
|
|
18
|
+
var played: [Track] = []
|
|
19
|
+
|
|
20
|
+
func answer(within timeout: Duration, search: @escaping @MainActor () async -> [Track]?) async -> Bool? {
|
|
21
|
+
await withDeadline(timeout) { _ in
|
|
22
|
+
guard let tracks = await search(), !Task.isCancelled else { return false }
|
|
23
|
+
self.played = tracks
|
|
24
|
+
return true
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
@Test func aSilentSearchFailsAtTheDeadlineAndPlaysNothing() async throws {
|
|
30
|
+
let intent = Intent()
|
|
31
|
+
let deadline = deadline
|
|
32
|
+
let answer = try await withinTimeLimit(.seconds(2)) {
|
|
33
|
+
await intent.answer(within: deadline) {
|
|
34
|
+
try? await awaitCallback { (_: @escaping @Sendable (Result<[Track]?, Error>) -> Void) in }
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
#expect(answer == nil)
|
|
38
|
+
try await Task.sleep(for: deadline * 2)
|
|
39
|
+
#expect(intent.played.isEmpty)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
@Test func aSearchAnsweringAfterTheDeadlinePlaysNothing() async throws {
|
|
43
|
+
let intent = Intent()
|
|
44
|
+
let found = found
|
|
45
|
+
let late = deadline * 2
|
|
46
|
+
let answer = await intent.answer(within: deadline) {
|
|
47
|
+
// Ignores cancellation, as a search whose result is already in hand does.
|
|
48
|
+
await withCheckedContinuation { continuation in
|
|
49
|
+
Task {
|
|
50
|
+
try? await Task.sleep(for: late)
|
|
51
|
+
continuation.resume()
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
return found
|
|
55
|
+
}
|
|
56
|
+
#expect(answer == nil)
|
|
57
|
+
try await Task.sleep(for: late * 2)
|
|
58
|
+
#expect(intent.played.isEmpty)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
@Test func aSearchAnsweringInTimePlays() async {
|
|
62
|
+
let intent = Intent()
|
|
63
|
+
let found = found
|
|
64
|
+
let answer = await intent.answer(within: .seconds(5)) { found }
|
|
65
|
+
#expect(answer == true)
|
|
66
|
+
#expect(intent.played == found)
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
@Test func theWorkIsGivenTheDeadline() async {
|
|
70
|
+
let before = ContinuousClock.now
|
|
71
|
+
let given = await withDeadline(.seconds(5)) { $0 }
|
|
72
|
+
#expect(given.map { before.duration(to: $0) >= .seconds(5) } == true)
|
|
73
|
+
#expect(given.map { ContinuousClock.now.duration(to: $0) <= .seconds(5) } == true)
|
|
74
|
+
}
|
|
75
|
+
}
|
|
@@ -39,21 +39,21 @@ struct UnconditionalEventTests {
|
|
|
39
39
|
}
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
-
@Test func
|
|
42
|
+
@Test func avPlayerWaiting_transitionsToBuffering_exceptFromError() {
|
|
43
43
|
for state in allStates {
|
|
44
|
-
#expect(nextPlaybackState(from: state, on: .avPlayerWaiting) == .buffering)
|
|
44
|
+
#expect(nextPlaybackState(from: state, on: .avPlayerWaiting) == (state == .error ? nil : .buffering))
|
|
45
45
|
}
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
-
@Test func
|
|
48
|
+
@Test func avPlayerPlaying_transitionsToPlaying_exceptFromError() {
|
|
49
49
|
for state in allStates {
|
|
50
|
-
#expect(nextPlaybackState(from: state, on: .avPlayerPlaying) == .playing)
|
|
50
|
+
#expect(nextPlaybackState(from: state, on: .avPlayerPlaying) == (state == .error ? nil : .playing))
|
|
51
51
|
}
|
|
52
52
|
}
|
|
53
53
|
|
|
54
|
-
@Test func
|
|
54
|
+
@Test func audioFrameDecoded_transitionsToPlaying_exceptFromError() {
|
|
55
55
|
for state in allStates {
|
|
56
|
-
#expect(nextPlaybackState(from: state, on: .audioFrameDecoded) == .playing)
|
|
56
|
+
#expect(nextPlaybackState(from: state, on: .audioFrameDecoded) == (state == .error ? nil : .playing))
|
|
57
57
|
}
|
|
58
58
|
}
|
|
59
59
|
|