SPB Git

Repository Public

FakeServer.swift 11.5 KB 185 lines swift

1// SP Music iOS2// File: Core/Tests/SPMusicCoreTests/FakeServer.swift3// Description: In-memory stand-in for the API (URLProtocol) and the test rig.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai78import CryptoKit9import Foundation10import Synchronization11@testable import SPMusicCore1213/// In-memory stand-in for the Music SP API, plugged under URLSession through URLProtocol. It speaks the real wire14/// format (the JSON below is what the server sends), enforces the session cookie and the CSRF header, and can be15/// taken offline, so the client's behaviour is tested without a network.16final class FakeServer: Sendable {17    struct TrackSeed { var id: String; var title: String; var artist: String; var album: String; var no: Int; var data: Data }18    struct State {19        var token = "tok-1"20        var csrf = "csrf-1"21        var offline = false22        var rev: Int64 = 023        var artists: [String: (name: String, rev: Int64)] = [:]24        var albums: [String: (title: String, artistId: String, rev: Int64)] = [:]25        var tracks: [String: (title: String, artistId: String, albumId: String, no: Int, rev: Int64, data: Data)] = [:]26        var tombstones: [(kind: String, id: String, rev: Int64)] = []27        var favorites: [String] = []28        var playlists: [(id: String, name: String, entries: [(entryId: String, trackId: String)])] = []29        var history: [[String: Any]] = []30        var requests: [String] = []31        var corruptStream: Set<String> = []32        var csrfRejectionsLeft = 033        var streamStatus = 20034    }35    let state = Mutex(State())36    static let current = Mutex<FakeServer?>(nil)3738    static func uuid(_ n: Int) -> String { String(format: "00000000-0000-4000-8000-%012d", n) }39    static func sha(_ d: Data) -> String { SHA256.hash(data: d).map { String(format: "%02x", $0) }.joined() }4041    func install() { Self.current.withLock { $0 = self } }4243    func addTrack(_ n: Int, title: String, artist: Int, album: Int, no: Int, bytes: Int = 4096) {44        state.withLock { s in45            let aid = Self.uuid(1000 + artist), alid = Self.uuid(2000 + album)46            if s.artists[aid] == nil { s.rev += 1; s.artists[aid] = ("Artiste \(artist)", s.rev) }47            if s.albums[alid] == nil { s.rev += 1; s.albums[alid] = ("Album \(album)", aid, s.rev) }48            s.rev += 149            var data = Data(count: bytes); for i in 0..<bytes { data[i] = UInt8((i &* 31 &+ n) & 0xff) }50            s.tracks[Self.uuid(n)] = (title, aid, alid, no, s.rev, data)51        }52    }53    func deleteTrack(_ n: Int) { state.withLock { s in s.tracks[Self.uuid(n)] = nil; s.rev += 1; s.tombstones.append(("track", Self.uuid(n), s.rev)) } }54    func rename(_ n: Int, _ title: String) { state.withLock { s in s.rev += 1; s.tracks[Self.uuid(n)]?.title = title; s.tracks[Self.uuid(n)]?.rev = s.rev } }5556    private func json(_ o: Any, _ status: Int = 200, headers: [String: String] = [:]) -> (Int, [String: String], Data) {57        (status, ["Content-Type": "application/json"].merging(headers) { $1 }, try! JSONSerialization.data(withJSONObject: o))58    }59    private func err(_ status: Int, _ code: String) -> (Int, [String: String], Data) { json(["error": ["code": code, "message": code]], status) }6061    /// nil = the request fails at the network level.62    func respond(_ req: URLRequest, body: Data) -> (Int, [String: String], Data)? {63        let path = req.url!.path, method = req.httpMethod ?? "GET"64        let query = URLComponents(url: req.url!, resolvingAgainstBaseURL: false)?.queryItems ?? []65        return state.withLock { s -> (Int, [String: String], Data)? in66            if s.offline { return nil }67            s.requests.append("\(method) \(path)")68            let authed = req.value(forHTTPHeaderField: "Cookie") == "spmusic_session=\(s.token)"69            if path == "/api/v1/auth/session" {70                return authed ? json(["authenticated": true, "csrfToken": s.csrf, "user": ["id": Self.uuid(1), "email": "o@example.test", "displayName": "Test", "role": "admin", "isOwner": true, "locale": "fr", "accent": "ember"]])71                              : json(["authenticated": false])72            }73            if path == "/api/v1/auth/recovery" {74                let code = (try? JSONSerialization.jsonObject(with: body) as? [String: Any])?["code"] as? String75                guard code == "aaaa-bbbb-cccc" else { return err(401, "login_failed") }76                s.token = "tok-2"; s.csrf = "csrf-2"77                return json(["ok": true], headers: ["Set-Cookie": "spmusic_session=tok-2; Path=/; HttpOnly; Secure; SameSite=lax"])78            }79            guard authed else { return err(401, "unauthenticated") }80            if method != "GET" {81                if req.value(forHTTPHeaderField: "Origin") != nil { return err(403, "bad_origin") }82                if s.csrfRejectionsLeft > 0 { s.csrfRejectionsLeft -= 1; s.csrf = "csrf-rotated"; return err(403, "csrf") }83                if req.value(forHTTPHeaderField: "X-CSRF-Token") != s.csrf { return err(403, "csrf") }84            }85            if path == "/api/v1/library/sync" {86                let since = Int64(query.first { $0.name == "since" }?.value ?? "0") ?? 087                let tracks: [[String: Any]] = s.tracks.filter { $0.value.rev > since }.map { id, t in88                    ["id": id, "title": t.title, "trackNo": t.no, "discNo": 1, "durationMs": 180_000, "year": 2024, "codec": "flac", "container": "flac", "sampleRate": 44100, "bitDepth": 16,89                     "channels": 2, "bitrate": 900_000, "webPlayable": "yes", "compatState": "none", "artistId": t.artistId, "albumId": t.albumId, "genre": "Test", "lyricsState": NSNull(),90                     "createdAt": "2026-11-17T12:00:00.000Z", "file": ["assetId": Self.uuid(9000), "sha256": Self.sha(t.data), "sizeBytes": t.data.count, "mime": "audio/flac"], "compat": NSNull(), "rev": t.rev]91                }92                return json(["since": since, "rev": s.rev, "more": false,93                             "artists": s.artists.filter { $0.value.rev > since }.map { ["id": $0.key, "name": $0.value.name, "rev": $0.value.rev] as [String: Any] },94                             "albums": s.albums.filter { $0.value.rev > since }.map { ["id": $0.key, "title": $0.value.title, "year": 2024, "artworkId": NSNull(), "artistId": $0.value.artistId, "genre": NSNull(), "createdAt": "2026-11-17T12:00:00.000Z", "rev": $0.value.rev] as [String: Any] },95                             "tracks": tracks, "deleted": s.tombstones.filter { $0.rev > since }.map { ["kind": $0.kind, "id": $0.id, "rev": $0.rev] as [String: Any] },96                             "counts": ["artists": s.artists.count, "albums": s.albums.count, "tracks": s.tracks.count]])97            }98            if path == "/api/v1/library/sync/me" {99                return json(["playlists": s.playlists.map { p in ["id": p.id, "name": p.name, "createdAt": "2026-11-17T12:00:00.000Z", "updatedAt": "2026-11-17T12:00:00.000Z",100                                                                  "entries": p.entries.enumerated().map { ["entryId": $0.element.entryId, "trackId": $0.element.trackId, "position": $0.offset, "addedAt": "2026-11-17T12:00:00.000Z"] as [String: Any] }] as [String: Any] },101                             "favoriteTracks": s.favorites.map { ["id": $0, "createdAt": "2026-11-17T12:00:00.000Z"] }, "favoriteAlbums": [], "playback": NSNull()])102            }103            if path == "/api/v1/library/history" {104                if method == "POST", let events = (try? JSONSerialization.jsonObject(with: body) as? [String: Any])?["events"] as? [[String: Any]] {105                    for e in events where !s.history.contains(where: { $0["id"] as? String == e["id"] as? String }) { s.history.append(e) }106                    return json(["stored": events.count, "skipped": 0])107                }108                return json(["items": s.history, "total": s.history.count, "limit": 200, "offset": 0])109            }110            if path.hasPrefix("/api/v1/library/favorites/track/") {111                let id = String(path.split(separator: "/").last!)112                guard s.tracks[id] != nil else { return err(404, "not_found") }113                s.favorites.removeAll { $0 == id }114                if method == "PUT" { s.favorites.insert(id, at: 0) }115                return json(["favorite": method == "PUT"])116            }117            if path.hasPrefix("/api/v1/stream/") {118                let id = String(path.split(separator: "/").last!)119                if s.streamStatus != 200 { return err(s.streamStatus, "refused") }120                guard var data = s.tracks[id]?.data else { return err(404, "not_found") }121                if s.corruptStream.contains(id) { data[10] ^= 0xff }122                return (200, ["Content-Type": "audio/flac", "Content-Length": String(data.count), "Accept-Ranges": "bytes", "ETag": "\"x\""], data)123            }124            return err(404, "not_found")125        }126    }127}128129final class StubProtocol: URLProtocol, @unchecked Sendable {130    override class func canInit(with request: URLRequest) -> Bool { true }131    override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }132    override func startLoading() {133        var body = request.httpBody ?? Data()134        if let stream = request.httpBodyStream {135            stream.open(); defer { stream.close() }136            var buf = [UInt8](repeating: 0, count: 4096)137            while stream.hasBytesAvailable { let n = stream.read(&buf, maxLength: buf.count); if n <= 0 { break }; body.append(buf, count: n) }138        }139        guard let server = FakeServer.current.withLock({ $0 }), let (status, headers, data) = server.respond(request, body: body) else {140            client?.urlProtocol(self, didFailWithError: URLError(.notConnectedToInternet)); return141        }142        let resp = HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: "HTTP/1.1", headerFields: headers)!143        client?.urlProtocol(self, didReceive: resp, cacheStoragePolicy: .notAllowed)144        client?.urlProtocol(self, didLoad: data)145        client?.urlProtocolDidFinishLoading(self)146    }147    override func stopLoading() {}148}149150/// Everything the engines need, wired to the fake server and to a temporary folder.151final class Rig: Sendable {152    let server = FakeServer()153    let tokens = InMemoryTokenStore("tok-1")154    let api: APIClient155    let db: Database156    let files: OfflineFiles157    let downloads: DownloadManager158    let sync: SyncEngine159    let dir: URL160161    init() async throws {162        server.install()163        dir = FileManager.default.temporaryDirectory.appendingPathComponent("spmusic-tests-\(UUID().uuidString)")164        files = OfflineFiles(root: dir.appendingPathComponent("support"), caches: dir.appendingPathComponent("caches"))165        api = APIClient(baseURL: URL(string: "https://music.test")!, tokens: tokens, protocolClasses: [StubProtocol.self])166        db = try Database(url: nil)167        let c = URLSessionConfiguration.ephemeral168        c.protocolClasses = [StubProtocol.self]169        downloads = DownloadManager(db: db, api: api, files: files, configuration: c, settings: { TransferSettings() }, network: { .wifi })170        sync = SyncEngine(db: db, api: api)171        await downloads.start()172    }173174    /// Waits until every download has left the transient states.175    func settle(timeout: TimeInterval = 10) async throws {176        let deadline = Date().addingTimeInterval(timeout)177        while Date() < deadline {178            if await db.downloads(states: [.queued, .running]).isEmpty { return }179            try await Task.sleep(for: .milliseconds(20))180        }181        throw APIError(status: 0, code: "timeout", message: "downloads did not settle")182    }183    func cleanup() { try? FileManager.default.removeItem(at: dir) }184}185
Files main
Menu

Theme