// 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 }`).importCottonKitimportFoundationimport os/// What this phone keeps of one book (`books.here`), and how it moves.enumBookHere: String, Sendable, Equatable {case absent, keeping, keptenumEvent: 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`).structBookHereStore: Sendable {let core: any CottonCallingprivatestructWire: Decodable { let state: String? }func read(_ key: String) asyncthrows -> BookHere {let wire = tryawait 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) asyncthrows {let value: RecordValue = state == .absent ? .null : .text(state.rawValue)let request: [String: RecordValue] = ["key": .text(key), "state": value] _ = tryawait 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) asyncthrows {let request: [String: RecordValue] = ["key": .text(key), "state": .text(BookHere.kept.rawValue), "from": .text(file.path)] _ = tryawait core.callJSON(CottonMethod.booksHereWrite, request) }/// Remove download: this phone's copy goes and the entry is forgotten.func remove(_ key: String) asyncthrows {let request: [String: RecordValue] = ["key": .text(key)] _ = tryawait 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.@MainActorprotocolKeptDownloading: AnyObject {var ended: ((_ key: String, _ result: Result<URL, Error>) -> 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)}@MainActorfinalclassBookKeeper {staticlet shared = BookKeeper(downloads: KeptDownloads.books)privatestaticlet log = Logger(subsystem: "com.cottondb.books", category: "keep")privatelet downloads: any KeptDownloadingprivatevar core: (any CottonCalling)?privatevar say: ((String) -> Void)?/// The books coming down now, by file key.privatevar fetching: Set<String> = []/// The readers waiting on a book coming down.privatevar waiting: [String: [CheckedContinuation<URL, Error>]] = [:]/// Downloads that ended before a core was here (a launch iOS made to/// hand the session's events over): handled once it is.privatevar early: [(key: String, result: Result<URL, Error>)] = []init(downloads: any KeptDownloading) {self.downloads = downloads downloads.ended = { [weakself] key, result inself?.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 = coreself.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) asyncthrows -> URL {guardlet core else { throwCocoaError(.fileReadUnknown) }iflet here = tryawait kept(key, core: core) { return here }returntryawait withCheckedThrowingContinuation { reader in waiting[key, default: []].append(reader)if fetching.insert(key).inserted { Task { awaitself.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 {guardlet core, let file = awaitSelf.file(table: table, id: id, core: core) else { returnfalse }do {iftryawait kept(file, core: core) != nil { returntrue } } catch { say?((error as? CottonCallError)?.message ?? ShellLines.line("cards", "book.could_not_keep"))returnfalse }guard fetching.insert(file).inserted else { returntrue }returnawait 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 {guardlet core, let file = awaitSelf.file(table: table, id: id, core: core) else { returnfalse } downloads.cancel(file) resume(file, with: .failure(CancellationError()))do {tryawaitBookHereStore(core: core).remove(file)returntrue } catch { say?((error as? CottonCallError)?.message ?? ShellLines.line("cards", "book.could_not_remove"))returnfalse } }/// Every book being read is kept here, whichever phone set it reading.func sweep() async {guardlet core else { return }structPage: 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)]), ]guardlet page = try? await core.call(CottonMethod.recordsList, request, as: Page.self) else { return }for wire in page.records {let record = wire.recordguardlet 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).privatefunc kept(_ key: String, core: any CottonCalling) asyncthrows -> URL? {guardtryawaitBookHereStore(core: core).read(key) == .kept else { returnnil }returnawaitCoreAttachmentStore(core: core).localURL(for: key) }/// The object signs the book's one key and the download starts. @discardableResultprivatefunc fetch(_ key: String, core: any CottonCalling) async -> Bool {let store = BookHereStore(core: core)do {tryawait store.write(key, BookHere.absent.after(.keep).state)let address = tryawaitBookStreamGrant.mint(key, core: core)Self.log.notice("book \(key.suffix(12), privacy: .public) comes down through its signed stream") downloads.start(address, key: key)returntrue } 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))returnfalse } }/// A download ended: what landed is kept through the core, and every/// reader waiting on it opens.privatefunc ended(_ key: String, _ result: Result<URL, Error>) {guardlet 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.guardtryawait store.read(key) == .keeping else {try? FileManager.default.removeItem(at: file)return }tryawait store.adopt(key, from: file)guardlet here = awaitCoreAttachmentStore(core: core).localURL(for: key) else { throwCocoaError(.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)) } } }privatefunc resume(_ key: String, with result: Result<URL, Error>) { 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).privateenumColumns {staticlet table = "book"staticlet file = "file"staticlet status = "status"staticlet reading = "reading" }/// A book's file key, from its record; nil for one with no file.privatestaticfunc file(table: String, id: String, core: any CottonCalling) async -> String? {structRead: Decodable { let data: [String: RecordValue] }guardlet read = try? await core.call(CottonMethod.recordsGet, ["table": RecordValue.text(table), "id": .text(id)], as: Read.self)else { returnnil }return read.data[Columns.file]?.text }}/// The object's signed address for a book's one key (`media.stream`).structBookStreamGrant: Decodable, Sendable {let url: Stringstaticfunc mint(_ key: String, core: any CottonCalling) asyncthrows -> URL {let grant = tryawait core.call(CottonMethod.mediaStream, ["key": RecordValue.text(key)], as: BookStreamGrant.self)guardlet url = URL(string: grant.url) else {throwCottonCallError(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.@MainActorfinalclassKeptDownloads: KeptDownloading {staticlet books = KeptDownloads(identifier: "cotton.books.keep", folder: "books-coming")staticlet songs = KeptDownloads(identifier: "cotton.music.keep", folder: "songs-coming")staticlet films = KeptDownloads(identifier: "cotton.films.whole", folder: "films-coming")/// Each one, by its session's name, for iOS's background wake.staticlet 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 = trueinit(identifier: String, folder: String) {self.identifier = identifierself.folder = folder }var ended: ((_ key: String, _ result: Result<URL, Error>) -> Void)? { didSet {let heard = unheard unheard = []for (key, result) in heard { finish(key, result) } } }privatevar session: URLSession?/// Ends that came before anyone listened (a launch iOS made for them).privatevar unheard: [(key: String, result: Result<URL, Error>)] = []privatelet delegate = KeptDownloadsDelegate()privatevar tasks: [String: URLSessionDownloadTask] = [:]privatevar 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)?) {iflet events { wakes.append(events) }guard session == nilelse { return } delegate.downloads = self delegate.folder = folderlet configuration = URLSessionConfiguration.background(withIdentifier: identifier) configuration.sessionSendsLaunchEvents = truelet session = URLSession(configuration: configuration, delegate: delegate, delegateQueue: .main)self.session = session session.getAllTasks { found inlet carried = found.compactMap { $0 as? URLSessionDownloadTask }Task { @MainActor [weakself] infor task in carried { iflet key = task.taskDescription { self?.tasks[key] = task } } } } }func start(_ address: URL, key: String) { wake(nil)guardlet session, tasks[key] == nilelse { return }var request = URLRequest(url: address) request.allowsCellularAccess = cellularlet task = session.downloadTask(with: request) task.taskDescription = key tasks[key] = task task.resume() }func cancel(_ key: String) { tasks.removeValue(forKey: key)?.cancel() }fileprivatefunc finish(_ key: String, _ result: Result<URL, Error>) { tasks[key] = nilguardlet ended else { return unheard.append((key, result)) } ended(key, result) }fileprivatefunc eventsDone() {let done = wakes wakes = []for events in done { events() } }/// Where a landed file waits for the core: the app's own caches. nonisolated staticfunc holding(in named: String) throws -> URL {let folder = tryFileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) .appendingPathComponent(named, isDirectory: true)tryFileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)return folder.appendingPathComponent(UUID().uuidString) }}privatefinalclassKeptDownloadsDelegate: NSObject, URLSessionDownloadDelegate, @unchecked Sendable {weakvar downloads: KeptDownloads?/// The folder a landed file waits in (`KeptDownloads.folder`).var folder = ""func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {guardlet key = downloadTask.taskDescription else { return }// A server's refusal lands as a file too: only a whole answer is kept.let result: Result<URL, Error>iflet http = downloadTask.response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) { result = .failure(URLError(.badServerResponse)) } else { result = Result { let held = tryKeptDownloads.holding(in: folder); tryFileManager.default.moveItem(at: location, to: held); return held } }MainActor.assumeIsolated { downloads?.finish(key, result) } }func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {guardlet error, let key = task.taskDescription else { return }MainActor.assumeIsolated { downloads?.finish(key, .failure(error)) } }func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {MainActor.assumeIsolated { downloads?.eventsDone() } }}