import Foundation import HydraulophoneCore import XCTest @testable import Hydraulophone @MainActor final class PlaybackRecoveryTests: XCTestCase { func testPauseCancelsPendingReconnectDelayWithoutStartingAnotherRequest() async { let service = FailingMusicService() let sleeper = ControlledRetrySleeper() let controller = PlaybackController( service: service, retrySleeper: { seconds in try await sleeper.sleep(seconds: seconds) } ) controller.play(Self.song("retry")) let delay = await sleeper.waitForRequest() XCTAssertEqual(delay, 1) let requestsBeforePause = await service.requestedIDs() XCTAssertEqual(requestsBeforePause, ["retry"]) controller.pause() await sleeper.waitForCancellation() let requestsAfterPause = await service.requestedIDs() XCTAssertEqual(requestsAfterPause, ["retry"]) XCTAssertEqual(controller.currentSong?.id, "retry") XCTAssertEqual(controller.state, .paused) controller.stop() } func testCurrentItemCompletionStartsTheNextQueuedOccurrence() async { let service = PendingMusicService() let controller = PlaybackController(service: service) controller.setQueue([Self.song("first"), Self.song("second")]) let firstRequest = await service.waitForRequestCount(1) XCTAssertEqual(firstRequest, ["first"]) controller.simulateCurrentItemEnd() let requests = await service.waitForRequestCount(2) XCTAssertEqual(requests, ["first", "second"]) XCTAssertEqual(controller.currentSong?.id, "second") controller.stop() } private static func song(_ id: String) -> Song { Song(id: id, title: id, artist: "Fixture Artist") } } private enum PlaybackRecoveryFixtureError: Error { case rejected } private actor FailingMusicService: MusicService { private var ids: [String] = [] func requestedIDs() -> [String] { ids } func search(query: String) async throws -> [SearchResult] { [] } func playlists() async throws -> [Playlist] { [] } func tracks(in playlist: Playlist) async throws -> [Song] { [] } func stream(for song: Song) async throws -> URL { ids.append(song.id) throw PlaybackRecoveryFixtureError.rejected } } private actor PendingMusicService: MusicService { private var ids: [String] = [] private var pending: [String: CheckedContinuation] = [:] private var requestWaiters: [( count: Int, continuation: CheckedContinuation<[String], Never> )] = [] func search(query: String) async throws -> [SearchResult] { [] } func playlists() async throws -> [Playlist] { [] } func tracks(in playlist: Playlist) async throws -> [Song] { [] } func stream(for song: Song) async throws -> URL { ids.append(song.id) resumeRequestWaiters() return try await withTaskCancellationHandler( operation: { try await withCheckedThrowingContinuation { continuation in pending[song.id] = continuation } }, onCancel: { Task { await self.cancelRequest(for: song.id) } } ) } func waitForRequestCount(_ count: Int) async -> [String] { if ids.count >= count { return ids } return await withCheckedContinuation { continuation in requestWaiters.append((count, continuation)) } } private func resumeRequestWaiters() { let ready = requestWaiters.filter { ids.count >= $0.count } requestWaiters.removeAll { ids.count >= $0.count } for waiter in ready { waiter.continuation.resume(returning: ids) } } private func cancelRequest(for id: String) { pending.removeValue(forKey: id)?.resume(throwing: CancellationError()) } } private actor ControlledRetrySleeper { private var requestedDelay: Int? private var delayWaiter: CheckedContinuation? private var pending: CheckedContinuation? private var cancelled = false private var cancellationWaiters: [CheckedContinuation] = [] func sleep(seconds: Int) async throws { try await withTaskCancellationHandler( operation: { try await withCheckedThrowingContinuation { continuation in requestedDelay = seconds pending = continuation delayWaiter?.resume(returning: seconds) delayWaiter = nil } }, onCancel: { Task { await self.cancel() } } ) } func waitForRequest() async -> Int { if let requestedDelay { return requestedDelay } return await withCheckedContinuation { delayWaiter = $0 } } func waitForCancellation() async { if cancelled { return } await withCheckedContinuation { cancellationWaiters.append($0) } } private func cancel() { cancelled = true pending?.resume(throwing: CancellationError()) pending = nil for waiter in cancellationWaiters { waiter.resume() } cancellationWaiters.removeAll() } }