react-native-audio-browser 0.2.0-next.81 → 0.2.0-next.83

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.
@@ -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,103 +35,165 @@ public enum PlaybackErrorContext {
41
35
  }
42
36
  }
43
37
 
44
- /// Retries failed loads with exponential backoff until a budget runs out, then reports the error
45
- /// as terminal; the iOS counterpart of Android's RetryLoadErrorHandlingPolicy.
46
- ///
47
- /// Two duration budgets apply, chosen by whether the current Load has produced audio (`hasPlayed`,
48
- /// docs/adr/0004): a short first-connect budget for a stream that never played (usually dead, with
49
- /// the listener waiting for a verdict), counted only while online, and the full recovery budget for
50
- /// one that played and dropped. While offline, a
51
- /// scheduled retry fires as soon as connectivity returns.
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
- enum Policy {
57
- case disabled
58
- case infinite
59
- case limited(maxRetries: Int)
60
- }
61
-
62
- private static let defaultMaxRetryDurationMs: Double = 120_000
63
- private static let defaultFirstConnectMaxRetryDurationMs: Double = 12_000
64
-
65
- // Bounds everything, offline waits included, so playback does not resume by surprise after a
66
- // long time offline.
67
- private var maxRetryDuration: TimeInterval = defaultMaxRetryDurationMs / 1000
68
- private var firstConnectMaxRetryDuration: TimeInterval = defaultFirstConnectMaxRetryDurationMs / 1000
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 retries gave up, or the failure cannot be retried. Not called when the retry
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 backoff while the state stays
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
- /// 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.
87
+ /// How long a connect or a stall may go without new data before it counts as a failure. Longer
88
+ /// than AVPlayer takes to fail a stalled item itself, so its error, which says more, is usually
89
+ /// the one retried; a connect's request can outlast it.
98
90
  var stallTimeout: Duration = .seconds(30)
99
- /// The end of the loaded range; the stall watch reads progress off it.
91
+ /// The end of the current connection's loaded range; the stall watch reads progress off it.
100
92
  var bufferedPosition: () -> Double = { 0 }
101
93
  private(set) var stallTask: Task<Void, Never>?
102
94
 
103
- private var policy: Policy = .disabled
104
- private var firstRetryTime: Date?
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
95
+ private let clock: any RetryClock
96
+ private let sleep: @Sendable (Int) async throws -> Void
110
97
 
98
+ /// - Parameters:
99
+ /// - online: Connectivity when the loop is made; `onlineChanged` reports each change after.
100
+ /// - sleep: The wait before a reconnect, in milliseconds; the clock's sleep by default.
111
101
  init(
112
- networkMonitor: (any NetworkStatusProviding)? = nil,
113
- sleep: @escaping @Sendable (TimeInterval) async throws -> Void = { try await Task.sleep(for: .seconds($0)) },
102
+ online: Bool = true,
103
+ clock: any RetryClock = ContinuousRetryClock(),
104
+ sleep: (@Sendable (Int) async throws -> Void)? = nil,
114
105
  ) {
115
- self.networkMonitor = networkMonitor
116
- self.sleep = sleep
106
+ budget = SilenceBudget(online: online)
107
+ pacer = ReconnectPacer(online: online)
108
+ self.clock = clock
109
+ self.sleep = sleep ?? { try await clock.sleep(ms: $0) }
117
110
  }
118
111
 
119
- var isEnabled: Bool {
120
- if case .disabled = policy { return false }
121
- return true
122
- }
112
+ /// Whether the current Load has produced audio (docs/adr/0004).
113
+ var hasPlayed: Bool { budget.hasPlayed }
123
114
 
124
115
  // MARK: - Configuration
125
116
 
126
117
  func updatePolicy(from config: Variant_Bool_RetryConfig?) {
127
- maxRetryDuration = Self.defaultMaxRetryDurationMs / 1000
128
- firstConnectMaxRetryDuration = Self.defaultFirstConnectMaxRetryDurationMs / 1000
118
+ budget.recoveryMs = 120_000
119
+ budget.firstConnectMs = 12_000
120
+ pacer.maxRetries = nil
129
121
  switch config {
130
122
  case nil:
131
- policy = .disabled
123
+ isEnabled = false
132
124
  case let .first(enabled):
133
- policy = enabled ? .infinite : .disabled
125
+ isEnabled = enabled
134
126
  case let .second(retryConfig):
135
- maxRetryDuration = (retryConfig.maxRetryDurationMs ?? Self.defaultMaxRetryDurationMs) / 1000
136
- firstConnectMaxRetryDuration =
137
- (retryConfig.firstConnectMaxRetryDurationMs ?? Self.defaultFirstConnectMaxRetryDurationMs) / 1000
138
- policy = retryConfig.maxRetries.map { .limited(maxRetries: Int($0)) } ?? .infinite
127
+ isEnabled = true
128
+ retryConfig.maxRetryDurationMs.map { budget.recoveryMs = Int($0) }
129
+ retryConfig.firstConnectMaxRetryDurationMs.map { budget.firstConnectMs = Int($0) }
130
+ pacer.maxRetries = retryConfig.maxRetries.map { Int($0) }
131
+ }
132
+ logger.debug("Retry enabled: \(self.isEnabled), max retries \(String(describing: self.pacer.maxRetries))")
133
+ armDeadline()
134
+ }
135
+
136
+ // MARK: - Inputs
137
+
138
+ /// A new Load: a track change, or a restart from the terminal error. Drops the retry in flight.
139
+ func loadStarted() {
140
+ cancel()
141
+ lastFailure = nil
142
+ replacedConnectionCounts = false
143
+ budget.loadStarted(atMs: clock.nowMs)
144
+ pacer.reset()
145
+ }
146
+
147
+ /// A connect going out: the Load's first, a reconnect, or a reload by the Player, which ends the
148
+ /// connection it replaces. A replaced connection counts only if it delivered audio: one cut off
149
+ /// while connecting says nothing about the source. With the play intent up, the stall watch runs
150
+ /// from the start, so a connect that opens and sends nothing is replaced (docs/adr/0014, rule 9).
151
+ func connectionStarted() {
152
+ let now = clock.nowMs
153
+ if let startedAtMs = connectionStartedAtMs, replacedConnectionCounts, connectionDeliveredAudio, !connectionEndReported {
154
+ pacer.connectionEnded(deliveredAudio: true, startedAtMs: startedAtMs, atMs: now)
155
+ }
156
+ connectionStartedAtMs = now
157
+ replacedConnectionCounts = true
158
+ connectionDeliveredAudio = false
159
+ connectionEndReported = false
160
+ deadlineArmed = true
161
+ armDeadline()
162
+ if playIntent { startStallWatch() }
163
+ }
164
+
165
+ func playIntentChanged(_ up: Bool) {
166
+ guard up != playIntent else { return }
167
+ playIntent = up
168
+ if up {
169
+ lastFailure = nil
170
+ // The pacer starts over: a reload now does not count the connection it replaces.
171
+ replacedConnectionCounts = false
139
172
  }
140
- logger.debug("Retry policy: \(String(describing: self.policy)), max duration \(self.maxRetryDuration)s")
173
+ budget.playIntentChanged(up, atMs: clock.nowMs)
174
+ pacer.playIntentChanged(up)
175
+ armDeadline()
176
+ }
177
+
178
+ func onlineChanged(_ online: Bool) {
179
+ budget.onlineChanged(online)
180
+ pacer.onlineChanged(online)
181
+ armDeadline()
182
+ }
183
+
184
+ /// Audio clears the failure the deadline would report: a silence after it that ends with no
185
+ /// failure is a stall.
186
+ func playbackBecameAudible() {
187
+ stopStallWatch()
188
+ connectionDeliveredAudio = true
189
+ lastFailure = nil
190
+ budget.audioStarted(atMs: clock.nowMs)
191
+ armDeadline()
192
+ }
193
+
194
+ func playbackStoppedBeingAudible() {
195
+ budget.audioStopped(atMs: clock.nowMs)
196
+ armDeadline()
141
197
  }
142
198
 
143
199
  // MARK: - Failures
@@ -157,61 +213,113 @@ final class RetryLoop {
157
213
  }
158
214
 
159
215
  /// 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) {
216
+ /// and reported as the context's fallback error.
217
+ func handleFailure(_ context: PlaybackErrorContext) {
162
218
  logger.error("[\(String(describing: context))] failure")
163
- handle(.init(error: context.fallbackError, retryable: true), context: context, immediately: immediately)
219
+ handle(.init(error: context.fallbackError, retryable: true), context: context)
164
220
  }
165
221
 
166
- private func handle(
167
- _ failure: PlaybackFailure.Classification, context: PlaybackErrorContext, immediately: Bool = false,
168
- ) {
222
+ private func handle(_ failure: PlaybackFailure.Classification, context: PlaybackErrorContext) {
169
223
  stopStallWatch()
170
224
  guard isEnabled, failure.retryable else {
171
225
  let reason = isEnabled ? "Error not retryable" : "Retry disabled"
172
226
  logger.warning("\(reason), surfacing \(String(describing: failure.error))")
173
- onError?(failure.error)
174
- return
227
+ return giveUp(failure.error)
175
228
  }
176
- guard shouldRetry() else {
229
+ guard playIntent else {
177
230
  logger.info("No play intent: \(String(describing: failure.error)) is left to the next play")
178
231
  onFailedWithoutIntent?()
179
232
  return
180
233
  }
234
+ lastFailure = failure.error
235
+ let now = clock.nowMs
236
+ if !connectionEndReported {
237
+ connectionEndReported = true
238
+ // The Player can stay .playing on a failure, on buffered audio that is about to run out.
239
+ budget.audioStopped(atMs: now)
240
+ budget.connectionEnded(atMs: now)
241
+ pacer.connectionEnded(deliveredAudio: connectionDeliveredAudio, startedAtMs: connectionStartedAtMs ?? now, atMs: now)
242
+ }
181
243
  onRetryingError?(failure.error)
244
+ armDeadline()
182
245
  pendingTask?.cancel()
183
246
  pendingTask = Task { [weak self] in
184
- guard let self else { return }
185
- let retried = await attemptRetry(startFromCurrentTime: context.startFromCurrentTime, immediately: immediately)
247
+ await self?.reconnect(startFromCurrentTime: context.startFromCurrentTime)
248
+ }
249
+ }
250
+
251
+ /// Asks the pacer again every half second at most, so a change in connectivity or a passed
252
+ /// deadline is seen without waiting out the whole wait.
253
+ private func reconnect(startFromCurrentTime: Bool) async {
254
+ while !Task.isCancelled {
255
+ if let deadline = budget.deadlineMs, deadline <= clock.nowMs {
256
+ return giveUp(lastFailure ?? .playbackStalled)
257
+ }
258
+ let waitMs: Int
259
+ switch pacer.wait(atMs: clock.nowMs) {
260
+ case .giveUp:
261
+ logger.info("Max retries (\(self.pacer.maxRetries ?? 0)) exceeded, giving up")
262
+ return giveUp(lastFailure ?? .playbackStalled)
263
+ case .untilOnline:
264
+ waitMs = 500
265
+ case let .after(ms):
266
+ waitMs = min(ms, 500)
267
+ }
268
+ if waitMs == 0 { break }
186
269
  // Cancelled by a track change or stop: stay silent, or the new track or the stop would
187
270
  // flip to .error. The canceller owns `pendingTask`.
188
- if Task.isCancelled { return }
189
- if !retried { onError?(failure.error) }
190
- pendingTask = nil
271
+ guard await (try? sleep(waitMs)) != nil else { return }
191
272
  }
273
+ if Task.isCancelled { return }
274
+ pendingTask = nil
275
+ logger.info("Reconnecting")
276
+ onRetry?(startFromCurrentTime)
192
277
  }
193
278
 
194
- /// Drops the retry in flight and the stall watch without touching the budgets.
279
+ private func giveUp(_ error: TrackPlayerError.PlaybackError) {
280
+ cancel()
281
+ onError?(error)
282
+ }
283
+
284
+ /// Drops the retry in flight, the stall watch and the deadline until the next connection starts.
195
285
  func cancel() {
196
286
  pendingTask?.cancel()
197
287
  pendingTask = nil
198
288
  stopStallWatch()
289
+ deadlineTask?.cancel()
290
+ deadlineTask = nil
291
+ deadlineArmed = false
292
+ }
293
+
294
+ // MARK: - Deadline
295
+
296
+ private func armDeadline() {
297
+ deadlineTask?.cancel()
298
+ deadlineTask = nil
299
+ guard isEnabled, deadlineArmed, let deadline = budget.deadlineMs else { return }
300
+ deadlineTask = Task { [weak self, clock] in
301
+ let remaining = deadline - clock.nowMs
302
+ if remaining > 0 { guard await (try? clock.sleep(ms: remaining)) != nil else { return } }
303
+ guard let self, !Task.isCancelled else { return }
304
+ logger.info("Silent past the deadline, giving up")
305
+ giveUp(lastFailure ?? .playbackStalled)
306
+ }
199
307
  }
200
308
 
201
309
  // MARK: - Stalls
202
310
 
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.
311
+ /// Starts the stall watch, over a connect or a stall: a `stallTimeout` in which `bufferedPosition`
312
+ /// does not advance makes it a `.stall` failure, provided the play intent holds and no retry is
313
+ /// pending; one in which it advances starts another. Any failure ends it.
206
314
  func startStallWatch() {
207
315
  stallTask?.cancel()
208
316
  let buffered = bufferedPosition()
209
- stallTask = Task { [weak self, stallTimeout] in
210
- try? await Task.sleep(for: stallTimeout)
317
+ stallTask = Task { [weak self, clock, stallTimeout] in
318
+ guard await (try? clock.sleep(ms: Int(stallTimeout / .milliseconds(1)))) != nil else { return }
211
319
  guard let self, !Task.isCancelled else { return }
212
320
  stallTask = nil
213
321
  if bufferedPosition() > buffered { return startStallWatch() }
214
- guard pendingTask == nil, shouldRetry() else { return }
322
+ guard pendingTask == nil, playIntent else { return }
215
323
  handleFailure(.stall)
216
324
  }
217
325
  }
@@ -220,115 +328,4 @@ final class RetryLoop {
220
328
  stallTask?.cancel()
221
329
  stallTask = nil
222
330
  }
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
331
  }
@@ -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 avPlayerWaiting_alwaysTransitionsToBuffering() {
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 avPlayerPlaying_alwaysTransitionsToPlaying() {
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 audioFrameDecoded_alwaysTransitionsToPlaying() {
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