import CottonKit import XCTest @testable import CottonUI /// How a book's file comes down: the object signs its one key /// (`media.stream`), a background download fetches that address, and the /// core keeps what landed (`books.here.write { from }`). Nothing asks /// `media.ensure` for a book. @MainActor final class BookKeeperTests: XCTestCase { private let key = "11111111-1111-4111-8111-111111111111/books/\(String(repeating: "a", count: 64)).epub" /// RULE: a book not on this phone is fetched from the address the object signs for its key, once however many readers wait, and opens from the store once the core keeps the download. func testABookComesDownThroughItsSignedStream() async throws { let core = KeepingCore() let downloads = HeldDownloads() let keeper = BookKeeper(downloads: downloads) keeper.attach(core: core) { _ in } let key = self.key async let first = keeper.file(for: key) async let second = keeper.file(for: key) for _ in 0..<10_000 where downloads.started.isEmpty { await Task.yield() } let started = try XCTUnwrap(downloads.started.first) XCTAssertEqual(started.key, key) XCTAssertEqual(started.address.absoluteString, "https://object.test/v1/stream/tok/\(key)") XCTAssertEqual(core.state(key), "keeping") let landed = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) try Data("synthetic".utf8).write(to: landed) downloads.ended?(key, .success(landed)) let (one, two) = try await (first, second) XCTAssertEqual(one.path, KeepingCore.store) XCTAssertEqual(two.path, KeepingCore.store) XCTAssertEqual(downloads.started.count, 1, "one download for the book however many wait") XCTAssertEqual(core.asked.filter { $0 == CottonMethod.mediaStream }.count, 1) XCTAssertFalse(core.asked.contains(CottonMethod.mediaEnsure), "a book never comes through media.ensure") XCTAssertEqual(core.adopted, [landed.path], "the core keeps the file the download left") XCTAssertEqual(core.state(key), "kept") } /// RULE: a download that fails leaves the book absent and the reader told, so the next open fetches it again. func testAFailedDownloadLeavesTheBookAbsent() async throws { let core = KeepingCore() let downloads = HeldDownloads() let keeper = BookKeeper(downloads: downloads) keeper.attach(core: core) { _ in } let key = self.key async let opened = keeper.file(for: key) for _ in 0..<10_000 where downloads.started.isEmpty { await Task.yield() } downloads.ended?(key, .failure(URLError(.networkConnectionLost))) do { _ = try await opened XCTFail("a failed download opens nothing") } catch {} XCTAssertNil(core.state(key)) XCTAssertTrue(core.adopted.isEmpty) } } /// A download that ends when the test says so. @MainActor private final class HeldDownloads: KeptDownloading { var ended: ((_ key: String, _ result: Result) -> Void)? var started: [(address: URL, key: String)] = [] func wake() {} func start(_ address: URL, key: String) { started.append((address, key)) } func cancel(_ key: String) {} } /// The core's side of keeping a book: what this phone keeps, the signed /// address, and the store's path once a download is kept. private final class KeepingCore: CottonCalling, @unchecked Sendable { static let store = "/media/store/book.epub" private let lock = NSLock() private var states: [String: String] = [:] private var methods: [String] = [] private var froms: [String] = [] var asked: [String] { lock.withLock { methods } } var adopted: [String] { lock.withLock { froms } } func state(_ key: String) -> String? { lock.withLock { states[key] } } func callRaw(_ method: String, requestJSON: String) async throws -> String { let request = (try? JSONSerialization.jsonObject(with: Data(requestJSON.utf8))) as? [String: Any] ?? [:] let key = (request["key"] as? String) ?? ((request["args"] as? [String: Any])?["key"] as? String) ?? "" return lock.withLock { methods.append(method) switch method { case CottonMethod.booksHereRead: return answer(["key": key, "state": states[key] ?? NSNull()]) case CottonMethod.booksHereWrite: if let from = request["from"] as? String { froms.append(from) } states[key] = request["state"] as? String return answer(["key": key, "state": states[key] ?? NSNull()]) case CottonMethod.mediaStream: return answer(["url": "https://object.test/v1/stream/tok/\(key)", "expires_at": "2026-11-04T12:00:00.000Z"]) case CottonMethod.readMediaPath: return answer(states[key] == "kept" ? ["present": true, "path": Self.store] : ["present": false]) default: return #"{"ok":false,"error":{"code":"unknown_method","message":"not here"}}"# } } } func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) async {} func close() async {} private func answer(_ data: [String: Any]) -> String { let body = (try? JSONSerialization.data(withJSONObject: ["ok": true, "data": data])) ?? Data() return String(decoding: body, as: UTF8.self) } }