import Foundation import Testing @testable import HydraulophoneCore struct CachedMusicServiceTests { @Test func arraySurfaceCachesHitsExpiresSearchAndCreatesUnpaginatedPages() async throws { let service = ArrayCatalogFake( searchResults: [.song(Song(id: "one", title: "One", artist: "Artist"))], playlists: [Playlist(id: "playlist", title: "Playlist")] ) let clock = TestClock() let cached = CachedMusicService(base: service, clock: { clock.now() }) #expect( try await cached.search(query: "ambient") == [.song(Song(id: "one", title: "One", artist: "Artist"))]) await service.setSearchResults([ .song(Song(id: "two", title: "Two", artist: "Artist")) ]) #expect( try await cached.search(query: "ambient") == [.song(Song(id: "one", title: "One", artist: "Artist"))]) #expect(await service.searchCallCount == 1) clock.advance(by: 60) #expect( try await cached.search(query: "ambient") == [.song(Song(id: "two", title: "Two", artist: "Artist"))]) #expect(await service.searchCallCount == 2) let playlistPage = try await cached.playlistPage( continuation: nil, policy: .cacheFirst) #expect(playlistPage.items == [Playlist(id: "playlist", title: "Playlist")]) #expect(playlistPage.next == nil) } @Test func reloadReplacesTheAffectedPageAndDoesNotReloadOtherResources() async throws { let service = ArrayCatalogFake( searchResults: [.song(Song(id: "old", title: "Old", artist: "Artist"))], playlists: [Playlist(id: "playlist", title: "Playlist")] ) let cached = CachedMusicService(base: service) _ = try await cached.search(query: "ambient") await service.setSearchResults([ .song(Song(id: "new", title: "New", artist: "Artist")) ]) let reloaded = try await cached.searchPage( query: "ambient", continuation: nil, policy: .reload) #expect(reloaded.items == [.song(Song(id: "new", title: "New", artist: "Artist"))]) _ = try await cached.search(query: "ambient") #expect(await service.searchCallCount == 2) _ = try await cached.playlists() await service.setPlaylists([Playlist(id: "new-playlist", title: "New playlist")]) _ = try await cached.search(query: "ambient") #expect(await service.playlistsCallCount == 1) } @Test func cacheEvictsLeastRecentlyUsedEntryAtBound() async throws { let service = ArrayCatalogFake() let cached = CachedMusicService(base: service) for index in 0..<64 { _ = try await cached.search(query: "query-\(index)") } _ = try await cached.search(query: "query-0") _ = try await cached.search(query: "query-64") // Touching query-0 made query-1 the least recently used entry. _ = try await cached.search(query: "query-0") #expect(await service.searchCallCount(for: "query-0") == 1) _ = try await cached.search(query: "query-1") #expect(await service.searchCallCount(for: "query-1") == 2) } @Test func identicalRequestsCoalesceAndOneCancelledWaiterDoesNotCancelTheOther() async throws { let result: [SearchResult] = [ .song(Song(id: "shared", title: "Shared", artist: "Artist")) ] let service = CancellableCatalogFake() let cached = CachedMusicService(base: service) let first = Task { try await cached.search(query: "shared") } await waitUntil { await service.searchCallCount == 1 } let second = Task { try await cached.search(query: "shared") } first.cancel() await #expect(throws: CancellationError.self) { try await first.value } #expect(await service.searchCallCount == 1) #expect(await service.searchCancellationCount == 0) await service.releaseNextSearch(with: result) #expect(try await second.value == result) #expect(await service.searchCallCount == 1) #expect(await service.searchCancellationCount == 0) } @Test func soleCancellationCancelsTheRequestAndAllowsAFreshRetry() async throws { let service = CancellableCatalogFake() let cached = CachedMusicService(base: service) let first = Task { try await cached.search(query: "cancelled") } await waitUntil { await service.searchCallCount == 1 } first.cancel() await #expect(throws: CancellationError.self) { try await first.value } await waitUntil { await service.searchCancellationCount == 1 } let stale: [SearchResult] = [ .song(Song(id: "stale", title: "Stale", artist: "Artist")) ] await service.releaseNextSearch(with: stale) let fresh: [SearchResult] = [ .song(Song(id: "fresh", title: "Fresh", artist: "Artist")) ] await service.queueNextSearchResult(fresh) #expect(try await cached.search(query: "cancelled") == fresh) #expect(await service.searchCallCount == 2) } @Test func lateReloadCompletionCannotPublishOverTheReplacement() async throws { let service = ControlledCatalogFake() let cached = CachedMusicService(base: service) let old: [SearchResult] = [ .song(Song(id: "old", title: "Old", artist: "Artist")) ] let new: [SearchResult] = [ .song(Song(id: "new", title: "New", artist: "Artist")) ] let staleRequest = Task { try await cached.search(query: "race") } await waitUntil { await service.searchCallCount == 1 } let replacement = Task { try await cached.searchPage( query: "race", continuation: nil, policy: .reload ) } await waitUntil { await service.searchCallCount == 2 } await service.releaseNextSearch(with: old) await #expect(throws: CachedMusicServiceError.self) { try await staleRequest.value } await service.releaseNextSearch(with: new) #expect(try await replacement.value == Page(items: new)) _ = try await cached.search(query: "race") #expect(await service.searchCallCount == 2) } @Test func sessionTransitionClearsOldResultsAndRejectsRequestsDuringSignOut() async throws { let service = ControlledCatalogFake() let cached = CachedMusicService(base: service) let old: [SearchResult] = [ .song(Song(id: "account-a", title: "A", artist: "Artist")) ] let fresh: [SearchResult] = [ .song(Song(id: "anonymous", title: "Anonymous", artist: "Artist")) ] let accountA = UserSession(cookieHeader: "cookie-a") let oldRequest = Task { try await cached.search(query: "library") } await waitUntil { await service.searchCallCount == 1 } let signOut = Task { await cached.setSession(nil) } await waitUntil { await service.sessionCallCount == 1 } await #expect(throws: CachedMusicServiceError.self) { try await cached.search(query: "library") } await service.releaseNextSearch(with: old) await #expect(throws: CachedMusicServiceError.self) { try await oldRequest.value } await service.releaseNextSession() await signOut.value #expect(await service.sessionHistory == [nil]) await service.setSearchResult(fresh) #expect(try await cached.search(query: "library") == fresh) #expect(await service.searchCallCount == 2) // Replacing an account also invalidates the anonymous result, rather than // allowing a page from the previous generation to survive the transition. let replace = Task { await cached.setSession(accountA) } await waitUntil { await service.sessionCallCount == 2 } await service.releaseNextSession() await replace.value await service.setSearchResult(old) #expect(try await cached.search(query: "library") == old) #expect(await service.searchCallCount == 3) } @Test func overlappingSessionTransitionsStaySerialAndBlockCatalogUntilTheChainEnds() async throws { let service = ControlledCatalogFake() let cached = CachedMusicService(base: service) let sessionA = UserSession(cookieHeader: "cookie-a") let sessionB = UserSession(cookieHeader: "cookie-b") let sessionC = UserSession(cookieHeader: "cookie-c") let transitionA = Task { await cached.setSession(sessionA) } await waitUntil { await service.sessionCallCount == 1 } let transitionB = Task { await cached.setSession(sessionB) } let transitionC = Task { await cached.setSession(sessionC) } #expect(await service.sessionCallCount == 1) #expect(await service.maxSessionConcurrency == 1) await #expect(throws: CachedMusicServiceError.sessionTransitionInProgress) { try await cached.search(query: "blocked") } #expect(await service.searchCallCount == 0) await service.releaseNextSession() await waitUntil { await service.sessionCallCount == 2 } #expect(await service.maxSessionConcurrency == 1) await #expect(throws: CachedMusicServiceError.sessionTransitionInProgress) { try await cached.search(query: "blocked") } await service.releaseNextSession() await waitUntil { await service.sessionCallCount == 3 } #expect(await service.maxSessionConcurrency == 1) await #expect(throws: CachedMusicServiceError.sessionTransitionInProgress) { try await cached.search(query: "blocked") } await service.releaseNextSession() await transitionA.value await transitionB.value await transitionC.value #expect(await service.maxSessionConcurrency == 1) // B and C are submitted concurrently, so their actor-entry order is not // specified. Assert both run after A, exactly once, without assuming which // of the overlapping calls the actor receives first. let sessionHistory = await service.sessionHistory #expect(sessionHistory.count == 3) #expect(sessionHistory.first == sessionA) #expect(sessionHistory.dropFirst().filter { $0 == sessionB }.count == 1) #expect(sessionHistory.dropFirst().filter { $0 == sessionC }.count == 1) await service.releaseNextSearch(with: []) #expect(try await cached.search(query: "unblocked-after-transitions").isEmpty) } @Test func homeTTLIsSeparateAndUnsupportedCapabilitiesAreTyped() async throws { let service = PagedCatalogFake() let clock = TestClock() let cached = CachedMusicService(base: service, clock: { clock.now() }) let first = try await cached.homePage( audience: .anonymous, filter: nil, continuation: nil, policy: .cacheFirst) await service.setHome( HomePage(sections: [HomeSection(id: "new", title: "New", items: [])])) clock.advance(by: 119) #expect( try await cached.homePage( audience: .anonymous, filter: nil, continuation: nil, policy: .cacheFirst ) == first) clock.advance(by: 1) #expect( try await cached.homePage( audience: .anonymous, filter: nil, continuation: nil, policy: .cacheFirst ).sections.first?.id == "new") #expect(await service.homeCallCount == 2) let arrayOnly = CachedMusicService(base: ArrayCatalogFake()) await #expect(throws: CachedMusicServiceError.self) { try await arrayOnly.homePage( audience: .anonymous, filter: nil, continuation: nil, policy: .cacheFirst) } await #expect(throws: CachedMusicServiceError.self) { try await arrayOnly.albumTrackPage( in: Album(browseID: "album", title: "Album"), continuation: nil, policy: .cacheFirst ) } } } private final class TestClock: @unchecked Sendable { private let lock = NSLock() private var value = Date(timeIntervalSince1970: 0) func now() -> Date { lock.lock() defer { lock.unlock() } return value } func advance(by interval: TimeInterval) { lock.lock() value.addTimeInterval(interval) lock.unlock() } } private actor ArrayCatalogFake: MusicService { private var searchValues: [SearchResult] private var playlistValues: [Playlist] private(set) var searchCallCount = 0 private(set) var playlistsCallCount = 0 private var searchCallsByQuery: [String: Int] = [:] init( searchResults: [SearchResult] = [], playlists: [Playlist] = [] ) { searchValues = searchResults playlistValues = playlists } func search(query: String) async throws -> [SearchResult] { searchCallCount += 1 searchCallsByQuery[query, default: 0] += 1 return searchValues } func playlists() async throws -> [Playlist] { playlistsCallCount += 1 return playlistValues } func tracks(in playlist: Playlist) async throws -> [Song] { [] } func stream(for song: Song) async throws -> URL { URL(fileURLWithPath: "/tmp/\(song.id)") } func setSearchResults(_ values: [SearchResult]) { searchValues = values } func setPlaylists(_ values: [Playlist]) { playlistValues = values } func searchCallCount(for query: String) -> Int { searchCallsByQuery[query, default: 0] } } private actor ControlledCatalogFake: MusicService, SessionManagingMusicService { private var searchWaiters: [CheckedContinuation<[SearchResult], Never>] = [] private var availableSearchResults: [[SearchResult]] = [] private var sessionWaiters: [CheckedContinuation] = [] private(set) var searchCallCount = 0 private(set) var sessionCallCount = 0 private(set) var sessionHistory: [UserSession?] = [] private var activeSessionCount = 0 private(set) var maxSessionConcurrency = 0 func search(query: String) async throws -> [SearchResult] { searchCallCount += 1 if !availableSearchResults.isEmpty { return availableSearchResults.removeFirst() } return await withCheckedContinuation { continuation in searchWaiters.append(continuation) } } func playlists() async throws -> [Playlist] { [] } func tracks(in playlist: Playlist) async throws -> [Song] { [] } func stream(for song: Song) async throws -> URL { URL(fileURLWithPath: "/tmp/\(song.id)") } func setSession(_ session: UserSession?) async { sessionCallCount += 1 sessionHistory.append(session) activeSessionCount += 1 maxSessionConcurrency = max(maxSessionConcurrency, activeSessionCount) await withCheckedContinuation { continuation in sessionWaiters.append(continuation) } activeSessionCount -= 1 } func releaseNextSearch(with values: [SearchResult]) { if !searchWaiters.isEmpty { searchWaiters.removeFirst().resume(returning: values) } else { availableSearchResults.append(values) } } func releaseNextSession() { guard !sessionWaiters.isEmpty else { return } sessionWaiters.removeFirst().resume() } func setSearchResult(_ values: [SearchResult]) { availableSearchResults.append(values) } } private final class CancellableSearchWaiter: @unchecked Sendable { private let lock = NSLock() private var continuation: CheckedContinuation<[SearchResult], Error>? private var finished: Result<[SearchResult], Error>? func wait() async throws -> [SearchResult] { try await withCheckedThrowingContinuation { continuation in var result: Result<[SearchResult], Error>? lock.lock() if let finished { result = finished } else { self.continuation = continuation } lock.unlock() result.map { continuation.resume(with: $0) } } } func finish(_ result: Result<[SearchResult], Error>) { var continuation: CheckedContinuation<[SearchResult], Error>? lock.lock() guard finished == nil else { lock.unlock() return } finished = result continuation = self.continuation self.continuation = nil lock.unlock() continuation?.resume(with: result) } } private actor CancellableCatalogFake: MusicService { private var searchWaiters: [CancellableSearchWaiter] = [] private var queuedSearchResults: [[SearchResult]] = [] private var cancelledWaiters: Set = [] private(set) var searchCallCount = 0 private(set) var searchCancellationCount = 0 func search(query: String) async throws -> [SearchResult] { searchCallCount += 1 if !queuedSearchResults.isEmpty { return queuedSearchResults.removeFirst() } let waiter = CancellableSearchWaiter() searchWaiters.append(waiter) return try await withTaskCancellationHandler( operation: { try await waiter.wait() }, onCancel: { Task { await self.cancel(waiter) } } ) } func playlists() async throws -> [Playlist] { [] } func tracks(in playlist: Playlist) async throws -> [Song] { [] } func stream(for song: Song) async throws -> URL { URL(fileURLWithPath: "/tmp/\(song.id)") } func queueNextSearchResult(_ result: [SearchResult]) { queuedSearchResults.append(result) } func releaseNextSearch(with result: [SearchResult]) { guard !searchWaiters.isEmpty else { return } searchWaiters.removeFirst().finish(.success(result)) } private func cancel(_ waiter: CancellableSearchWaiter) { let waiterID = ObjectIdentifier(waiter) guard cancelledWaiters.insert(waiterID).inserted else { return } searchCancellationCount += 1 } } private actor PagedCatalogFake: MusicService, PaginatedCatalogMusicService { private var homeValue = HomePage(sections: [HomeSection(id: "old", title: "Old", items: [])]) private(set) var homeCallCount = 0 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 { URL(fileURLWithPath: "/tmp/\(song.id)") } func searchPage( query: String, continuation: PaginationToken?, policy: CatalogLoadPolicy ) async throws -> Page { Page(items: []) } func playlistPage( continuation: PaginationToken?, policy: CatalogLoadPolicy ) async throws -> Page { Page(items: []) } func trackPage( in playlist: Playlist, continuation: PaginationToken?, policy: CatalogLoadPolicy ) async throws -> Page { Page(items: []) } func albumTrackPage( in album: Album, continuation: PaginationToken?, policy: CatalogLoadPolicy ) async throws -> Page { Page(items: []) } func homePage( audience: HomeAudience, filter: HomeFilter?, continuation: PaginationToken?, policy: CatalogLoadPolicy ) async throws -> HomePage { homeCallCount += 1 return homeValue } func setHome(_ value: HomePage) { homeValue = value } } private func waitUntil( _ predicate: @escaping @Sendable () async -> Bool ) async { for _ in 0..<1_000 { if await predicate() { return } await Task.yield() } }