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.
@@ -0,0 +1,148 @@
1
+ import Testing
2
+
3
+ @testable import AudioBrowserTestable
4
+
5
+ @MainActor
6
+ @Suite("SupersedingTask")
7
+ struct SupersedingTaskTests {
8
+ /// Work that never answers unless cancelled, recording how each run ended.
9
+ @MainActor
10
+ final class SilentWork {
11
+ var started = 0
12
+ var cancelled = 0
13
+
14
+ func run() async throws -> Int? {
15
+ started += 1
16
+ do {
17
+ return try await awaitCallback { (_: @escaping @Sendable (Result<Int?, Error>) -> Void) in }
18
+ } catch {
19
+ if error is CancellationError { cancelled += 1 }
20
+ throw error
21
+ }
22
+ }
23
+ }
24
+
25
+ private func yieldUntil(_ condition: () -> Bool, sourceLocation: SourceLocation = #_sourceLocation) async {
26
+ for _ in 0 ..< 1000 where !condition() {
27
+ await Task.yield()
28
+ }
29
+ #expect(condition(), sourceLocation: sourceLocation)
30
+ }
31
+
32
+ @Test func aNewRunCancelsTheSilentOneBefore() async {
33
+ let task = SupersedingTask<String, Int>()
34
+ let work = SilentWork()
35
+ var delivered: [Result<Int?, Error>] = []
36
+ task.run(key: nil) { try await work.run() } deliver: { delivered.append($0) }
37
+ await yieldUntil { work.started == 1 }
38
+ task.run(key: nil) { try await work.run() } deliver: { delivered.append($0) }
39
+ await yieldUntil { work.cancelled == 1 }
40
+ #expect(work.started == 2)
41
+ #expect(delivered.isEmpty)
42
+ task.cancel()
43
+ await yieldUntil { work.cancelled == 2 }
44
+ }
45
+
46
+ @Test func cancelEndsTheRunWithoutDelivering() async {
47
+ let task = SupersedingTask<String, Int>()
48
+ let work = SilentWork()
49
+ var delivered = 0
50
+ task.run(key: nil) { try await work.run() } deliver: { _ in delivered += 1 }
51
+ await yieldUntil { work.started == 1 }
52
+ task.cancel()
53
+ await yieldUntil { work.cancelled == 1 }
54
+ for _ in 0 ..< 10 {
55
+ await Task.yield()
56
+ }
57
+ #expect(delivered == 0)
58
+ }
59
+
60
+ @Test func deliversOnlyTheLatestResult() async {
61
+ let task = SupersedingTask<String, Int>()
62
+ var resumeFirst: CheckedContinuation<Void, Never>?
63
+ var delivered: [Int?] = []
64
+ task.run(key: nil) {
65
+ // Ignores cancellation, so its answer arrives after it was superseded.
66
+ await withCheckedContinuation { resumeFirst = $0 }
67
+ return 1
68
+ } deliver: { delivered.append(try! $0.get()) }
69
+ await yieldUntil { resumeFirst != nil }
70
+ task.run(key: nil) { 2 } deliver: { delivered.append(try! $0.get()) }
71
+ await yieldUntil { delivered == [2] }
72
+ resumeFirst?.resume()
73
+ for _ in 0 ..< 10 {
74
+ await Task.yield()
75
+ }
76
+ #expect(delivered == [2])
77
+ }
78
+
79
+ @Test func aRunForTheLatestKeyIsSkipped() async {
80
+ let task = SupersedingTask<String, Int>()
81
+ let work = SilentWork()
82
+ task.run(key: "a") { try await work.run() } deliver: { _ in }
83
+ task.run(key: "a") { try await work.run() } deliver: { _ in }
84
+ await yieldUntil { work.started == 1 }
85
+ task.run(key: "b") { try await work.run() } deliver: { _ in }
86
+ await yieldUntil { work.started == 2 }
87
+ #expect(work.cancelled == 1)
88
+ task.cancel()
89
+ }
90
+
91
+ @Test func aDeliveredKeyIsSkippedUntilCancel() async {
92
+ let task = SupersedingTask<String, Int>()
93
+ var runs = 0
94
+ var delivered: [Int?] = []
95
+ task.run(key: "a") { runs += 1; return 1 } deliver: { delivered.append(try! $0.get()) }
96
+ await yieldUntil { delivered == [1] }
97
+ task.run(key: "a") { runs += 1; return 2 } deliver: { delivered.append(try! $0.get()) }
98
+ for _ in 0 ..< 10 {
99
+ await Task.yield()
100
+ }
101
+ #expect(runs == 1)
102
+ task.cancel()
103
+ task.run(key: "a") { runs += 1; return 3 } deliver: { delivered.append(try! $0.get()) }
104
+ await yieldUntil { delivered == [1, 3] }
105
+ #expect(runs == 2)
106
+ }
107
+
108
+ @Test func aFailedKeyRunsAgain() async {
109
+ struct Failure: Error {}
110
+ let task = SupersedingTask<String, Int>()
111
+ var runs = 0
112
+ var failed = false
113
+ task.run(key: "a") { runs += 1; throw Failure() } deliver: { _ in failed = true }
114
+ await yieldUntil { failed }
115
+ task.run(key: "a") { runs += 1; return 1 } deliver: { _ in }
116
+ await yieldUntil { runs == 2 }
117
+ }
118
+
119
+ @Test func aNilAnswerRunsAgain() async {
120
+ let task = SupersedingTask<String, Int>()
121
+ var runs = 0
122
+ var answered = false
123
+ task.run(key: "a") { runs += 1; return nil } deliver: { _ in answered = true }
124
+ await yieldUntil { answered }
125
+ task.run(key: "a") { runs += 1; return 1 } deliver: { _ in }
126
+ await yieldUntil { runs == 2 }
127
+ }
128
+
129
+ @Test func aNilKeyAlwaysRuns() async {
130
+ let task = SupersedingTask<String, Int>()
131
+ let work = SilentWork()
132
+ task.run(key: nil) { try await work.run() } deliver: { _ in }
133
+ await yieldUntil { work.started == 1 }
134
+ task.run(key: nil) { try await work.run() } deliver: { _ in }
135
+ await yieldUntil { work.started == 2 }
136
+ task.cancel()
137
+ }
138
+
139
+ @Test func deliversAFailure() async {
140
+ struct Failure: Error {}
141
+ let task = SupersedingTask<String, Int>()
142
+ var failed = false
143
+ task.run(key: nil) { throw Failure() } deliver: { result in
144
+ if case .failure(is Failure) = result { failed = true }
145
+ }
146
+ await yieldUntil { failed }
147
+ }
148
+ }
@@ -55,10 +55,15 @@ final class MockPlayerEngine: PlayerEngine {
55
55
 
56
56
  func resolveAndLoad(src: String, track _: Track) { resolveAndLoadCalls.append(src) }
57
57
  func cancelLoading() { cancelLoadingCount += 1 }
58
- func dropAsset() { dropAssetCount += 1 }
58
+ func dropAsset() {
59
+ dropAssetCount += 1
60
+ hasLoadedAsset = false
61
+ }
62
+
59
63
  func clearItem() {
60
64
  clearItemCount += 1
61
65
  hasItem = false
66
+ hasLoadedAsset = false
62
67
  resumePosition = nil
63
68
  }
64
69
 
@@ -163,7 +168,6 @@ final class MockPlayerEngine: PlayerEngine {
163
168
  func makePlayer(
164
169
  engine: MockPlayerEngine = MockPlayerEngine(),
165
170
  retry: RetryLoop = makeRetryLoop(),
166
- retries: Bool? = true,
167
171
  sleepTimerScheduler: any SleepTimerScheduling = ManualSleepTimerScheduler(),
168
172
  saveInterval: Duration = .seconds(5),
169
173
  ) -> Player {
@@ -171,8 +175,8 @@ func makePlayer(
171
175
  engine: engine, retry: retry, sleepTimerScheduler: sleepTimerScheduler,
172
176
  persistenceDefaults: UserDefaults(suiteName: "PlayerTests")!, persistenceSaveInterval: saveInterval,
173
177
  )
174
- // Player's init installs its own `shouldRetry`; replace it afterwards.
175
- if let retries { retry.shouldRetry = { retries } }
178
+ // The Player reports its play intent to the loop from here on, starting from none.
179
+ retry.playIntentChanged(false)
176
180
  return player
177
181
  }
178
182
 
@@ -258,16 +262,103 @@ final class MockPlayerCallbacks: PlayerCallbacks {
258
262
 
259
263
  // MARK: - RetryLoop
260
264
 
261
- /// An enabled RetryLoop with play intent that backs off for `delay` seconds and reloads, or gives
262
- /// up on the first retry when `givesUp`.
265
+ /// An enabled RetryLoop with play intent that waits `delay` seconds before each reconnect, or gives
266
+ /// up on the first connection that delivers nothing when `givesUp`.
263
267
  @MainActor
264
268
  func makeRetryLoop(givesUp: Bool = false, delay: TimeInterval = 0) -> RetryLoop {
265
- let loop = RetryLoop(sleep: { _ in
269
+ let clock = SkippingClock()
270
+ let loop = RetryLoop(clock: clock, sleep: { ms in
266
271
  if delay > 0 { try await Task.sleep(for: .seconds(delay)) }
272
+ clock.skip(ms)
267
273
  })
268
274
  loop.updatePolicy(from: givesUp ? .second(RetryConfig(
269
275
  maxRetries: 0, maxRetryDurationMs: nil, firstConnectMaxRetryDurationMs: nil,
270
276
  )) : .first(true))
271
- loop.shouldRetry = { true }
277
+ loop.playIntentChanged(true)
272
278
  return loop
273
279
  }
280
+
281
+ /// Real time, plus every wait skipped so far: a test need not sit out the waits between connects.
282
+ final class SkippingClock: RetryClock, @unchecked Sendable {
283
+ private let real = ContinuousRetryClock()
284
+ private let lock = NSLock()
285
+ private var skippedMs = 0
286
+
287
+ var nowMs: Int { real.nowMs + lock.withLock { skippedMs } }
288
+ func sleep(ms: Int) async throws { try await real.sleep(ms: ms) }
289
+ func skip(_ ms: Int) { lock.withLock { skippedMs += ms } }
290
+ }
291
+
292
+ /// A `RetryClock` that moves only when `run(until:)` moves it, firing what falls due in time order.
293
+ final class VirtualClock: RetryClock, @unchecked Sendable {
294
+ private struct Timer {
295
+ let atMs: Int
296
+ let order: Int
297
+ var action: (@MainActor () -> Void)?
298
+ var sleeper: CheckedContinuation<Void, Error>?
299
+ }
300
+
301
+ private let lock = NSLock()
302
+ private var _nowMs = 0
303
+ private var timers: [Int: Timer] = [:]
304
+ private var nextOrder = 0
305
+
306
+ var nowMs: Int { lock.withLock { _nowMs } }
307
+
308
+ private func allocate() -> Int {
309
+ lock.withLock {
310
+ defer { nextOrder += 1 }
311
+ return nextOrder
312
+ }
313
+ }
314
+
315
+ /// Runs `action` at `atMs` on this clock.
316
+ func at(_ atMs: Int, _ action: @escaping @MainActor () -> Void) {
317
+ let id = allocate()
318
+ lock.withLock { timers[id] = Timer(atMs: atMs, order: id, action: action) }
319
+ }
320
+
321
+ func sleep(ms: Int) async throws {
322
+ let id = allocate()
323
+ try await withTaskCancellationHandler {
324
+ try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in
325
+ let cancelled = lock.withLock {
326
+ guard !Task.isCancelled else { return true }
327
+ timers[id] = Timer(atMs: _nowMs + ms, order: id, sleeper: continuation)
328
+ return false
329
+ }
330
+ if cancelled { continuation.resume(throwing: CancellationError()) }
331
+ }
332
+ } onCancel: {
333
+ // Whichever of the cancel and `run` removes the timer resumes it.
334
+ lock.withLock { timers.removeValue(forKey: id) }?.sleeper?.resume(throwing: CancellationError())
335
+ }
336
+ }
337
+
338
+ /// Fires every timer due up to `endMs` in time order, letting the tasks each wakes run first.
339
+ @MainActor
340
+ func run(until endMs: Int) async {
341
+ while true {
342
+ await settle()
343
+ let next = lock.withLock { () -> Timer? in
344
+ guard let next = timers.values.min(by: { ($0.atMs, $0.order) < ($1.atMs, $1.order) }),
345
+ next.atMs <= endMs
346
+ else { return nil }
347
+ timers.removeValue(forKey: next.order)
348
+ _nowMs = max(_nowMs, next.atMs)
349
+ return next
350
+ }
351
+ guard let next else { break }
352
+ next.action?()
353
+ next.sleeper?.resume()
354
+ }
355
+ lock.withLock { _nowMs = max(_nowMs, endMs) }
356
+ }
357
+
358
+ @MainActor
359
+ private func settle() async {
360
+ for _ in 0 ..< 20 {
361
+ await Task.yield()
362
+ }
363
+ }
364
+ }
@@ -0,0 +1,12 @@
1
+ import Network
2
+
3
+ /// Connectivity; a fake stands in for `NetworkMonitor` in tests.
4
+ protocol NetworkStatusProviding: AnyObject, Sendable {
5
+ var isOnline: Bool { get }
6
+ }
7
+
8
+ extension NWPath.Status {
9
+ /// Offline only when no route exists: a path that requires a connection (a VPN on demand, some
10
+ /// cellular paths) comes up when one is made, so the retry loop must not wait for it.
11
+ var isOnline: Bool { self != .unsatisfied }
12
+ }
@@ -0,0 +1,38 @@
1
+ /// `work`'s result, or nil once `timeout` passes, when `work` is cancelled first: the answer comes on
2
+ /// time even when `work` ignores cancellation, and work that resumes after a nil answer sees
3
+ /// `Task.isCancelled`. `work` gets the deadline, to bound its own waits by what is left. Cancelling
4
+ /// the caller does not reach `work`.
5
+ @MainActor
6
+ func withDeadline<T: Sendable>(
7
+ _ timeout: Duration,
8
+ _ work: @escaping @MainActor (_ deadline: ContinuousClock.Instant) async -> T,
9
+ ) async -> T? {
10
+ let deadline = ContinuousClock.now + timeout
11
+ return await withCheckedContinuation { continuation in
12
+ let answer = DeadlineAnswer(continuation)
13
+ let task = Task { await answer.settle(work(deadline)) }
14
+ answer.timer = Task {
15
+ try? await Task.sleep(until: deadline, clock: .continuous)
16
+ guard !Task.isCancelled else { return }
17
+ task.cancel()
18
+ answer.settle(nil)
19
+ }
20
+ }
21
+ }
22
+
23
+ /// Settles on the main actor, so the work's last step and the timer cannot interleave.
24
+ @MainActor
25
+ private final class DeadlineAnswer<T: Sendable> {
26
+ private var continuation: CheckedContinuation<T?, Never>?
27
+ var timer: Task<Void, Never>?
28
+
29
+ init(_ continuation: CheckedContinuation<T?, Never>) {
30
+ self.continuation = continuation
31
+ }
32
+
33
+ func settle(_ value: T?) {
34
+ timer?.cancel()
35
+ continuation?.resume(returning: value)
36
+ continuation = nil
37
+ }
38
+ }
@@ -44,12 +44,12 @@ final class NetworkMonitor: @unchecked Sendable {
44
44
 
45
45
  // Seeded before `start`: written after it, a `currentPath` the monitor hasn't finished
46
46
  // evaluating could clobber the handler's real update. The handler stays the last writer.
47
- let initialStatus = monitor.currentPath.status == .satisfied
47
+ let initialStatus = monitor.currentPath.status.isOnline
48
48
  logger.notice("NetworkMonitor initialized, initial isOnline=\(initialStatus)")
49
49
  _isOnline = initialStatus
50
50
 
51
51
  monitor.pathUpdateHandler = { [weak self] path in
52
- self?.apply(path.status == .satisfied)
52
+ self?.apply(path.status.isOnline)
53
53
  }
54
54
 
55
55
  monitor.start(queue: queue)
@@ -0,0 +1,45 @@
1
+ /// At most one task in flight: `run` and `cancel` cancel the one before, and a result is
2
+ /// delivered only while its task is the latest, so a cancelled or superseded task delivers nothing.
3
+ /// A `run` with the latest run's non-nil key is skipped until `cancel`: that run, in flight or
4
+ /// done, already answers it through its own `deliver`. Only a non-nil answer keeps the key: after a
5
+ /// nil answer or a failure, the next run asks again.
6
+ @MainActor
7
+ final class SupersedingTask<Key: Equatable, Value: Sendable> {
8
+ private var generation: UInt = 0
9
+ private var task: Task<Void, Never>?
10
+ private var key: Key?
11
+
12
+ func run(
13
+ key: Key?,
14
+ _ work: @escaping @MainActor () async throws -> Value?,
15
+ deliver: @escaping @MainActor (Result<Value?, Error>) -> Void,
16
+ ) {
17
+ if key != nil, key == self.key { return }
18
+ cancel()
19
+ self.key = key
20
+ let generation = generation
21
+ task = Task { [weak self] in
22
+ let result: Result<Value?, Error>
23
+ do {
24
+ result = try await .success(work())
25
+ } catch {
26
+ result = .failure(error)
27
+ }
28
+ guard let self, self.generation == generation else { return }
29
+ self.task = nil
30
+ if (try? result.get()) == nil { self.key = nil }
31
+ deliver(result)
32
+ }
33
+ }
34
+
35
+ deinit {
36
+ task?.cancel()
37
+ }
38
+
39
+ func cancel() {
40
+ generation &+= 1
41
+ task?.cancel()
42
+ task = nil
43
+ key = nil
44
+ }
45
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-audio-browser",
3
- "version": "0.2.0-next.81",
3
+ "version": "0.2.0-next.83",
4
4
  "description": "react-native-audio-browser is a react native package built with Nitro",
5
5
  "keywords": [
6
6
  "react-native",