// A book's file on this phone: kept, coming down, or not here. // // The bytes live once, in the phone's content-addressed media store, however // they arrived (shared on this phone, or fetched from the object). What this // phone keeps of each book is `books.here` in the core (`phone::books`), // never synced, keyed by the book's file key; `kept` pins the bytes against // the store's budget, and Remove download (`books.remove`) lets this copy go // — never the last one, which the object's bucket holds. // // Opening a book keeps it, and a book set to reading is kept without asking // (`sweep`). The bytes come down from the address the object signs for the // book's one key (`media.stream`), in a background session iOS carries while // the app is gone (`KeptDownloads.books`); what lands is handed to the core, which // moves it into the store and keeps it (`books.here.write { from }`). import CottonKit import Foundation import os /// What this phone keeps of one book (`books.here`), and how it moves. enum BookHere: String, Sendable, Equatable { case absent, keeping, kept enum Event: Sendable, Equatable { /// Keep on phone, or the book opened. case keep /// The bytes are here. case landed /// The fetch failed or was refused. case failed /// Remove download. case remove } /// The state an event leaves, and whether the bytes must be fetched. func after(_ event: Event) -> (state: BookHere, fetch: Bool) { switch (self, event) { case (.absent, .keep): (.keeping, true) case (.keeping, .keep), (.kept, .keep): (self, false) case (.keeping, .landed): (.kept, false) case (.keeping, .failed): (.absent, false) // A fetch that lands or fails after Remove download changes nothing. case (_, .landed), (_, .failed): (self, false) case (_, .remove): (.absent, false) } } } /// The core's device-local store of books (`phone::books`). struct BookHereStore: Sendable { let core: any CottonCalling private struct Wire: Decodable { let state: String? } func read(_ key: String) async throws -> BookHere { let wire = try await core.call(CottonMethod.booksHereRead, ["key": RecordValue.text(key)], as: Wire.self) return wire.state.flatMap(BookHere.init(rawValue:)) ?? .absent } func write(_ key: String, _ state: BookHere) async throws { let value: RecordValue = state == .absent ? .null : .text(state.rawValue) let request: [String: RecordValue] = ["key": .text(key), "state": value] _ = try await core.callJSON(CottonMethod.booksHereWrite, request) } /// A download landed at `file`: the core moves it into the store and keeps it. func adopt(_ key: String, from file: URL) async throws { let request: [String: RecordValue] = ["key": .text(key), "state": .text(BookHere.kept.rawValue), "from": .text(file.path)] _ = try await core.callJSON(CottonMethod.booksHereWrite, request) } /// Remove download: this phone's copy goes and the entry is forgotten. func remove(_ key: String) async throws { let request: [String: RecordValue] = ["key": .text(key)] _ = try await core.callJSON(CottonMethod.booksRemove, request) } } /// Where a book's bytes come down from: a download of the object's signed /// address, ending with the file it left (moved out of the session's reach) /// or the reason it did not. @MainActor protocol KeptDownloading: AnyObject { var ended: ((_ key: String, _ result: Result) -> Void)? { get set } /// The session made again, so what iOS carried while the app was gone lands. func wake() func start(_ address: URL, key: String) func cancel(_ key: String) } @MainActor final class BookKeeper { static let shared = BookKeeper(downloads: KeptDownloads.books) private static let log = Logger(subsystem: "com.cottondb.books", category: "keep") private let downloads: any KeptDownloading private var core: (any CottonCalling)? private var say: ((String) -> Void)? /// The books coming down now, by file key. private var fetching: Set = [] /// The readers waiting on a book coming down. private var waiting: [String: [CheckedContinuation]] = [:] /// Downloads that ended before a core was here (a launch iOS made to /// hand the session's events over): handled once it is. private var early: [(key: String, result: Result)] = [] init(downloads: any KeptDownloading) { self.downloads = downloads downloads.ended = { [weak self] key, result in self?.ended(key, result) } } /// The core and the toasts, from the root once a core is open. func attach(core: any CottonCalling, say: @escaping (String) -> Void) { self.core = core self.say = say downloads.wake() let waiting = early early = [] for (key, result) in waiting { ended(key, result) } Task { await sweep() } } /// The book's file for the reader: kept on this phone by being opened. /// A book's file by its key (`shell.reader`'s `file`): here, or once it has come down. func file(for key: String) async throws -> URL { guard let core else { throw CocoaError(.fileReadUnknown) } if let here = try await kept(key, core: core) { return here } return try await withCheckedThrowingContinuation { reader in waiting[key, default: []].append(reader) if fetching.insert(key).inserted { Task { await self.fetch(key, core: core) } } } } /// Keep on phone (`keepBook`, the root's flow): the download starts and /// carries on in the background. func keep(table: String, id: String) async -> Bool { guard let core, let file = await Self.file(table: table, id: id, core: core) else { return false } do { if try await kept(file, core: core) != nil { return true } } catch { say?((error as? CottonCallError)?.message ?? ShellLines.line("cards", "book.could_not_keep")) return false } guard fetching.insert(file).inserted else { return true } return await fetch(file, core: core) } /// Remove download (`removeBookDownload`): what is coming down stops and /// this phone's copy goes. func remove(table: String, id: String) async -> Bool { guard let core, let file = await Self.file(table: table, id: id, core: core) else { return false } downloads.cancel(file) resume(file, with: .failure(CancellationError())) do { try await BookHereStore(core: core).remove(file) return true } catch { say?((error as? CottonCallError)?.message ?? ShellLines.line("cards", "book.could_not_remove")) return false } } /// Every book being read is kept here, whichever phone set it reading. func sweep() async { guard let core else { return } struct Page: Decodable { let records: [CoreRecords.WireRecord] } let request: [String: RecordValue] = [ "table": .text(Columns.table), "where": .object([Columns.status: .text(Columns.reading), "on_phone": .text(BookHere.absent.rawValue)]), ] guard let page = try? await core.call(CottonMethod.recordsList, request, as: Page.self) else { return } for wire in page.records { let record = wire.record guard let file = record.values[Columns.file]?.text, fetching.insert(file).inserted else { continue } await fetch(file, core: core) } } /// The bytes when this phone keeps them; nil when they must come down /// (absent, or a download the app was killed in). private func kept(_ key: String, core: any CottonCalling) async throws -> URL? { guard try await BookHereStore(core: core).read(key) == .kept else { return nil } return await CoreAttachmentStore(core: core).localURL(for: key) } /// The object signs the book's one key and the download starts. @discardableResult private func fetch(_ key: String, core: any CottonCalling) async -> Bool { let store = BookHereStore(core: core) do { try await store.write(key, BookHere.absent.after(.keep).state) let address = try await BookStreamGrant.mint(key, core: core) Self.log.notice("book \(key.suffix(12), privacy: .public) comes down through its signed stream") downloads.start(address, key: key) return true } catch { try? await store.write(key, BookHere.keeping.after(.failed).state) say?((error as? CottonCallError)?.message ?? ShellLines.line("cards", "book.could_not_keep")) resume(key, with: .failure(error)) return false } } /// A download ended: what landed is kept through the core, and every /// reader waiting on it opens. private func ended(_ key: String, _ result: Result) { guard let core else { return early.append((key, result)) } Task { let store = BookHereStore(core: core) switch result { case .success(let file): do { // Remove download came first: nothing is kept. guard try await store.read(key) == .keeping else { try? FileManager.default.removeItem(at: file) return } try await store.adopt(key, from: file) guard let here = await CoreAttachmentStore(core: core).localURL(for: key) else { throw CocoaError(.fileNoSuchFile) } Self.log.notice("book \(key.suffix(12), privacy: .public) kept") resume(key, with: .success(here)) } catch { try? FileManager.default.removeItem(at: file) try? await store.write(key, BookHere.keeping.after(.failed).state) say?((error as? CottonCallError)?.message ?? ShellLines.line("cards", "book.could_not_keep")) resume(key, with: .failure(error)) } case .failure(let error): // Cancelled is Remove download's own doing. guard (error as NSError).code != NSURLErrorCancelled else { return } try? await store.write(key, BookHere.keeping.after(.failed).state) say?(ShellLines.line("cards", "book.could_not_keep")) resume(key, with: .failure(error)) } } } private func resume(_ key: String, with result: Result) { fetching.remove(key) for reader in waiting.removeValue(forKey: key) ?? [] { reader.resume(with: result) } } /// The `book` columns the keeper reads (agreed with the books kit). private enum Columns { static let table = "book" static let file = "file" static let status = "status" static let reading = "reading" } /// A book's file key, from its record; nil for one with no file. private static func file(table: String, id: String, core: any CottonCalling) async -> String? { struct Read: Decodable { let data: [String: RecordValue] } guard let read = try? await core.call(CottonMethod.recordsGet, ["table": RecordValue.text(table), "id": .text(id)], as: Read.self) else { return nil } return read.data[Columns.file]?.text } } /// The object's signed address for a book's one key (`media.stream`). struct BookStreamGrant: Decodable, Sendable { let url: String static func mint(_ key: String, core: any CottonCalling) async throws -> URL { let grant = try await core.call(CottonMethod.mediaStream, ["key": RecordValue.text(key)], as: BookStreamGrant.self) guard let url = URL(string: grant.url) else { throw CottonCallError(code: "unreadable", message: ShellLines.line("cards", "book.could_not_keep")) } return url } } /// A background session kept files come down on (books, songs, whole films): the file is /// moved out of the session's folder at once (it is deleted when the delegate /// returns), then handed to its keeper. @MainActor final class KeptDownloads: KeptDownloading { static let books = KeptDownloads(identifier: "cotton.books.keep", folder: "books-coming") static let songs = KeptDownloads(identifier: "cotton.music.keep", folder: "songs-coming") static let films = KeptDownloads(identifier: "cotton.films.whole", folder: "films-coming") /// Each one, by its session's name, for iOS's background wake. static let all = [books, songs, films] let identifier: String /// The caches folder a landed file waits in for the core. nonisolated let folder: String /// Whether the next download may use mobile data: a film's follows this /// phone's word (`films.keeping`), Wi-Fi only unless it said so. var cellular = true init(identifier: String, folder: String) { self.identifier = identifier self.folder = folder } var ended: ((_ key: String, _ result: Result) -> Void)? { didSet { let heard = unheard unheard = [] for (key, result) in heard { finish(key, result) } } } private var session: URLSession? /// Ends that came before anyone listened (a launch iOS made for them). private var unheard: [(key: String, result: Result)] = [] private let delegate = KeptDownloadsDelegate() private var tasks: [String: URLSessionDownloadTask] = [:] private var wakes: [() -> Void] = [] func wake() { wake(nil) } /// iOS finished a file while the app was gone and woke it to say so. func wake(_ events: (() -> Void)?) { if let events { wakes.append(events) } guard session == nil else { return } delegate.downloads = self delegate.folder = folder let configuration = URLSessionConfiguration.background(withIdentifier: identifier) configuration.sessionSendsLaunchEvents = true let session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: .main) self.session = session session.getAllTasks { found in let carried = found.compactMap { $0 as? URLSessionDownloadTask } Task { @MainActor [weak self] in for task in carried { if let key = task.taskDescription { self?.tasks[key] = task } } } } } func start(_ address: URL, key: String) { wake(nil) guard let session, tasks[key] == nil else { return } var request = URLRequest(url: address) request.allowsCellularAccess = cellular let task = session.downloadTask(with: request) task.taskDescription = key tasks[key] = task task.resume() } func cancel(_ key: String) { tasks.removeValue(forKey: key)?.cancel() } fileprivate func finish(_ key: String, _ result: Result) { tasks[key] = nil guard let ended else { return unheard.append((key, result)) } ended(key, result) } fileprivate func eventsDone() { let done = wakes wakes = [] for events in done { events() } } /// Where a landed file waits for the core: the app's own caches. nonisolated static func holding(in named: String) throws -> URL { let folder = try FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent(named, isDirectory: true) try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) return folder.appendingPathComponent(UUID().uuidString) } } private final class KeptDownloadsDelegate: NSObject, URLSessionDownloadDelegate, @unchecked Sendable { weak var downloads: KeptDownloads? /// The folder a landed file waits in (`KeptDownloads.folder`). var folder = "" func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) { guard let key = downloadTask.taskDescription else { return } // A server's refusal lands as a file too: only a whole answer is kept. let result: Result if let http = downloadTask.response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) { result = .failure(URLError(.badServerResponse)) } else { result = Result { let held = try KeptDownloads.holding(in: folder); try FileManager.default.moveItem(at: location, to: held); return held } } MainActor.assumeIsolated { downloads?.finish(key, result) } } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { guard let error, let key = task.taskDescription else { return } MainActor.assumeIsolated { downloads?.finish(key, .failure(error)) } } func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) { MainActor.assumeIsolated { downloads?.eventsDone() } } }