SPB Git

Repository Public

StreamingAndOfflineTests.swift 14.2 KB 228 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Tests/CoreTests/StreamingAndOfflineTests.swift3// Description: Tests: streaming, offline changes, conflicts, revoked session, connectivity loss and return.4import XCTest5import AVFoundation6@testable import SPMusicCore78final class StreamingTests: ClusterTestCase {9    func testStreamingStartsBeforeTheFileIsThereSeeksByRangeAndLeavesAVerifiedCopy() async throws {10        let s = try await makeSession()11        try await s.sync.sync()12        let t = try some(await s.store.tracks().first { $0.title == "Long bruit rose" })13        proxy.resetCounters()14        proxy.bytesPerSecond = 1_500_000                       // a slow link: the file needs about 13 s to arrive15        let r = try await s.resolve(t, normalize: false)16        XCTAssertEqual(r.kind, .stream)17        let engine = OfflinePlayer.engine()18        let started = Date()19        engine.load(token: UUID(), source: r.source, typeHint: r.typeHint, autoplay: true)20        let first = OfflinePlayer.render(engine, seconds: 2)21        XCTAssertGreaterThan(Signal.rms(first[22050...]), 0.01, "sound comes out")22        XCTAssertLessThan(Date().timeIntervalSince(started), 4, "long before the whole file could have arrived")23        XCTAssertLessThan(r.source.bufferedFraction, 0.6, "the file is still on its way while it plays")2425        // Jump far ahead: the engine asks the cluster for the bytes at that place instead of waiting for them.26        engine.seek(to: 95)27        let after = OfflinePlayer.render(engine, seconds: 1.5)28        XCTAssertGreaterThan(Signal.rms(after[22050...]), 0.01, "sound resumes at the new position")29        XCTAssertEqual(engine.status().position, 96.5, accuracy: 0.6)30        let ranges = proxy.requests.filter { $0.contains("/stream/\(t.id)") }.compactMap { $0.components(separatedBy: "bytes=").last?.split(separator: "-").first.flatMap { Int64($0) } }31        XCTAssertEqual(ranges.first, 0)32        XCTAssertTrue(ranges.contains { $0 > t.sizeBytes / 2 }, "a range request deep in the file: \(ranges)")3334        // Left alone, the source fills its holes and ends with a complete copy that matches the cluster's checksum.35        proxy.bytesPerSecond = nil36        let source = try XCTUnwrap(r.source as? ProgressiveHTTPSource)37        await waitUntil(40, "cache complete") { source.isComplete }38        let cached = try XCTUnwrap(StreamCache.completeFile(s.storage.streamCacheDirectory, trackID: t.id, assetID: t.assetID!))39        XCTAssertEqual(try StorageManager.sha256(of: cached), t.sha256)40        XCTAssertLessThan(Int64(proxy.bytesFromServer), t.sizeBytes + 800_000, "holes were filled without fetching anything twice")41        engine.stop()4243        // Played again: from the cache, no request. Downloaded afterwards: the cached bytes are reused, no request either.44        proxy.resetCounters()45        let again = try await s.resolve(t, normalize: false)46        XCTAssertEqual(again.kind, .cache)47        XCTAssertTrue(s.isAvailableOffline(t))48        await s.downloads.start()49        await s.downloads.enqueue([t.id])50        await waitUntil(20, "installed from the cache") { await s.store.track(t.id)?.isDownloaded == true }51        XCTAssertFalse(proxy.requests.contains { $0.contains("/stream/") }, "nothing was fetched again: \(proxy.requests)")52    }5354    func testAStreamSurvivesAShortNetworkCut() async throws {55        let s = try await makeSession()56        try await s.sync.sync()57        let t = try some(await s.store.tracks().first { $0.title == "Bruit blanc" })58        proxy.bytesPerSecond = 2_000_00059        let r = try await s.resolve(t, normalize: false)60        let engine = OfflinePlayer.engine()61        engine.load(token: UUID(), source: r.source, typeHint: r.typeHint, autoplay: true)62        _ = OfflinePlayer.render(engine, seconds: 1)63        proxy.down = true64        try await Task.sleep(nanoseconds: 1_200_000_000)65        XCTAssertFalse(s.connectivity.isOnline, "the app noticed the cut")66        proxy.down = false; proxy.bytesPerSecond = nil67        // Playback goes on through the whole file once bytes flow again; nothing had to be restarted by hand.68        let x = OfflinePlayer.render(engine, seconds: 58, patience: 20)69        XCTAssertGreaterThan(Signal.rms(x[(44100 * 50)...]), 0.01)70        engine.stop()71    }7273    func testEveryFormatOfTheLibraryStreams() async throws {74        let s = try await makeSession()75        try await s.sync.sync()76        for (title, hz) in [("Été compressé", 330.0), ("Sans perte Apple", 550.0), ("Haute résolution", 660.0)] {77            let t = try some(await s.store.tracks().first { $0.title == title })78            let r = try await s.resolve(t, normalize: false)79            let engine = OfflinePlayer.engine()80            engine.load(token: UUID(), source: r.source, typeHint: r.typeHint, autoplay: true)81            let x = OfflinePlayer.render(engine, seconds: 3)82            XCTAssertEqual(Signal.frequency(x[44100..<(44100 * 3)], rate: 44100), hz, accuracy: 4, "\(title) (\(t.codec))")83            engine.stop()84        }85    }86}8788final class OfflineChangesTests: ClusterTestCase {89    func testChangesMadeOfflineAreSentWhenTheClusterComesBack() async throws {90        let s = try await makeSession()91        try await s.sync.sync()92        let tracks = await s.store.albumTracks(try some(await s.store.albums().first { $0.title == "Fréquences pures" }).id)93        let name = "Faite hors ligne \(UUID().uuidString.prefix(5))"9495        s.connectivity.forcedOffline = true96        proxy.resetCounters()97        let local = try await s.store.createPlaylist(name: name, trackIDs: [tracks[0].id, tracks[1].id])98        try await s.store.addToPlaylist(local, trackIDs: [tracks[2].id])99        try await s.store.renamePlaylist(local, name: name + " ✓")100        try await s.store.setFavorite(kind: "track", id: tracks[3].id, on: true)101        try await s.store.setFavorite(kind: "album", id: tracks[0].albumID, on: true)102        do { try await s.sync.sync(); XCTFail("offline") } catch { XCTAssertEqual(error as? APIError, .offline) }103        XCTAssertEqual(proxy.connections, 0, "forced offline mode makes no request at all")104        // Offline, the listener already sees everything they did.105        let mine = try some(await s.store.playlists().first { $0.id == local })106        XCTAssertEqual(mine.name, name + " ✓"); XCTAssertEqual(mine.trackCount, 3); XCTAssertTrue(mine.pendingCreation)107        let favs = await s.store.favoriteTracks()108        XCTAssertEqual(favs.map(\.id), [tracks[3].id])109        let waiting = await s.store.pendingOpCount()110        XCTAssertGreaterThan(waiting, 0)111112        s.connectivity.forcedOffline = false113        let r = try await s.sync.sync()114        XCTAssertEqual(r.operationsWaiting, 0); XCTAssertEqual(r.conflicts, 0)115        let id = psql("SELECT id FROM playlists WHERE name = '\(name) ✓'")116        XCTAssertEqual(id.count, 36, "the playlist exists on the cluster")117        XCTAssertEqual(psql("SELECT string_agg(t.title, ',' ORDER BY pt.position) FROM playlist_tracks pt JOIN tracks t ON t.id = pt.track_id WHERE pt.playlist_id = '\(id)'"), "Onde 1,Onde 2,Onde 3")118        XCTAssertEqual(psql("SELECT count(*) FROM favorites WHERE track_id = '\(tracks[3].id)'"), "1")119        XCTAssertEqual(psql("SELECT count(*) FROM favorite_albums WHERE album_id = '\(tracks[0].albumID)'"), "1")120        let synced = try some(await s.store.playlists().first { $0.id == id })121        XCTAssertFalse(synced.pendingCreation)122        // Clean up through the app.123        try await s.store.setFavorite(kind: "track", id: tracks[3].id, on: false); try await s.store.setFavorite(kind: "album", id: tracks[0].albumID, on: false)124        try await s.store.deletePlaylist(id); try await s.sync.sync()125        XCTAssertEqual(psql("SELECT count(*) FROM playlists WHERE id = '\(id)'"), "0"); XCTAssertEqual(psql("SELECT count(*) FROM favorites WHERE track_id = '\(tracks[3].id)'"), "0")126    }127128    func testAPlaylistChangedHereAndElsewhereKeepsBothVersions() async throws {129        let s = try await makeSession()130        try await s.sync.sync()131        let tracks = await s.store.albumTracks(try some(await s.store.albums().first { $0.title == "Fréquences pures" }).id)132        let name = "Conflit \(UUID().uuidString.prefix(5))"133        _ = try await s.store.createPlaylist(name: name, trackIDs: tracks.map(\.id))134        try await s.sync.sync()135        let pl = try some(await s.store.playlists().first { $0.name == name })136137        // Offline on this Mac: keep tracks 4 and 1 only, in that order.138        s.connectivity.forcedOffline = true139        let entries = await s.store.playlistEntries(pl.id)140        try await s.store.setPlaylistEntries(pl.id, entryIDs: [entries[3].id, entries[0].id])141        // Meanwhile, on another device: the first track is removed.142        psql("DELETE FROM playlist_tracks WHERE playlist_id = '\(pl.id)' AND track_id = '\(tracks[0].id)'; UPDATE playlists SET updated_at = now() + interval '1 second' WHERE id = '\(pl.id)'")143        s.connectivity.forcedOffline = false144        let r = try await s.sync.sync()145        XCTAssertEqual(r.conflicts, 1)146        // The other device's version is intact under the original name…147        XCTAssertEqual(psql("SELECT string_agg(t.title, ',' ORDER BY pt.position) FROM playlist_tracks pt JOIN tracks t ON t.id = pt.track_id WHERE pt.playlist_id = '\(pl.id)'"), "Onde 2,Onde 3,Onde 4")148        // …and this Mac's version was saved beside it, not thrown away.149        let copy = psql("SELECT id FROM playlists WHERE name = '\(name) (copie de ce Mac)'")150        XCTAssertEqual(psql("SELECT string_agg(t.title, ',' ORDER BY pt.position) FROM playlist_tracks pt JOIN tracks t ON t.id = pt.track_id WHERE pt.playlist_id = '\(copy)'"), "Onde 4,Onde 1")151        let names = await s.store.playlists().map(\.name)152        XCTAssertTrue(names.contains(name) && names.contains(name + " (copie de ce Mac)"))153        let notices = await s.store.takeNotices()154        XCTAssertEqual(notices.count, 1); XCTAssertTrue(notices[0].contains("Les deux versions ont été conservées"))155        psql("DELETE FROM playlists WHERE id IN ('\(pl.id)', '\(copy)')")156    }157158    func testAnOrderChangedOfflineIsAppliedWhenNobodyElseTouchedThePlaylist() async throws {159        let s = try await makeSession()160        try await s.sync.sync()161        let tracks = await s.store.albumTracks(try some(await s.store.albums().first { $0.title == "Fréquences pures" }).id)162        let name = "Ordre \(UUID().uuidString.prefix(5))"163        _ = try await s.store.createPlaylist(name: name, trackIDs: [tracks[0].id, tracks[1].id, tracks[2].id])164        try await s.sync.sync()165        let pl = try some(await s.store.playlists().first { $0.name == name })166        s.connectivity.forcedOffline = true167        try await s.store.addToPlaylist(pl.id, trackIDs: [tracks[3].id])168        let e = await s.store.playlistEntries(pl.id)169        try await s.store.setPlaylistEntries(pl.id, entryIDs: [e[3].id, e[2].id, e[0].id])      // 4, 3, 1 — track 2 removed170        s.connectivity.forcedOffline = false171        let r = try await s.sync.sync()172        XCTAssertEqual(r.conflicts, 0)173        XCTAssertEqual(psql("SELECT string_agg(t.title, ',' ORDER BY pt.position) FROM playlist_tracks pt JOIN tracks t ON t.id = pt.track_id WHERE pt.playlist_id = '\(pl.id)'"), "Onde 4,Onde 3,Onde 1")174        let after = await s.store.playlistEntries(pl.id).map(\.track.title)175        XCTAssertEqual(after, ["Onde 4", "Onde 3", "Onde 1"])176        psql("DELETE FROM playlists WHERE id = '\(pl.id)'")177    }178179    func testWhenTheSessionIsRevokedTheLibraryOnThisMacStillPlays() async throws {180        let own = try await deviceLink()181        let s = try await makeSession(credential: own)182        try await s.sync.sync()183        await s.downloads.start()184        let t = try some(await s.store.tracks().first { $0.title == "Onde 1" })185        await s.downloads.enqueue([t.id])186        await waitUntil(20, "downloaded") { await s.store.track(t.id)?.isDownloaded == true }187        let other = try some(await s.store.tracks().first { $0.title == "Onde 2" })188        // The account closes this device's session from the web.189        psql("UPDATE sessions SET revoked_at = now() WHERE id = (SELECT id FROM sessions WHERE method = 'device' AND revoked_at IS NULL ORDER BY created_at DESC LIMIT 1)")190        let flagged = expectation(description: "the app learns its session ended"); flagged.assertForOverFulfill = false191        s.api.setUnauthenticatedHandler { flagged.fulfill() }192        do { try await s.sync.sync(); XCTFail() } catch { XCTAssertEqual(error as? APIError, .unauthenticated) }193        await fulfillment(of: [flagged], timeout: 2)194        // Nothing local was deleted, and what was downloaded plays.195        let kept = try some(await s.store.track(t.id))196        XCTAssertTrue(kept.isDownloaded)197        let r = try await s.resolve(kept, normalize: false)198        XCTAssertEqual(r.kind, .local); XCTAssertTrue(AudioDecoder.canDecode(r.source, typeHint: r.typeHint))199        // A queued download waits for the next sign-in instead of failing.200        await s.downloads.enqueue([other.id])201        try await Task.sleep(nanoseconds: 600_000_000)202        let waiting = await s.store.download(other.id)203        XCTAssertEqual(waiting?.state, .queued)204        // Signing out forgets the session, not the music.205        await s.auth.signOut()206        XCTAssertNil(s.api.currentCredential)207        XCTAssertNotNil(s.storage.localFile(for: kept))208    }209210    func testTheAppNoticesTheClusterGoingAwayAndComingBack() async throws {211        let s = try await makeSession()212        try await s.sync.sync()213        s.connectivity.start(probe: { [api = s.api] in await api.probe() }, interval: 0.3)214        var seen: [Bool] = []215        let watcher = Task { () -> [Bool] in var out: [Bool] = []; for await v in s.connectivity.states() { out.append(v); if out.count == 3 { break } }; return out }216        try await Task.sleep(nanoseconds: 100_000_000)217        proxy.down = true218        do { try await s.sync.sync(); XCTFail() } catch { XCTAssertEqual(error as? APIError, .offline) }219        XCTAssertFalse(s.connectivity.isOnline)220        proxy.down = false221        await waitUntil(5, "back online by itself") { s.connectivity.isOnline }222        seen = await watcher.value223        XCTAssertEqual(seen, [true, false, true])224        let r = try await s.sync.sync()225        XCTAssertFalse(r.full)226    }227}228
Files main
Menu

Theme