import Foundation import Observation import RastrilloApple import RastrilloNative struct DocsOfflineMetadata: Codable { var detail: DocumentDetail var pendingTitle: String? var draftToken: String? } /// All windows for an account share the same outbox and send reservation. @MainActor @Observable final class DocsOfflineAccount { private static var accounts: [String: DocsOfflineAccount] = [:] let store: BlobStore let outbox: Outbox let connectivity: NativeConnectivity let replicaCache: DocsReplicaCache private var supplier: @MainActor () -> NativeTransport? private(set) var drainer: OutboxDrainer! static func account(_ id: String, origin: URL, fallback: NativeTransport, transport: (@MainActor () -> NativeTransport?)?) -> DocsOfflineAccount { if let existing = accounts[id] { if let transport { existing.supplier = transport; existing.drainer.sessionRestored() }; return existing } let root = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] .appendingPathComponent(Bundle.main.bundleIdentifier ?? "works.oficina.docs") .appendingPathComponent("accounts").appendingPathComponent(id) let store = NativeSealedStore(root: root, accountID: id, keys: KeychainKeyProvider(accountID: id, origin: origin)) let account = DocsOfflineAccount(store: store, accountID: id, connectivity: .shared, transport: transport ?? { fallback }) accounts[id] = account; return account } init(store: BlobStore, accountID: String, connectivity: NativeConnectivity, transport: @escaping @MainActor () -> NativeTransport?) { self.store = store; outbox = Outbox(store: store, account: accountID) replicaCache = DocsReplicaCache(store: store) self.connectivity = connectivity; supplier = transport drainer = OutboxDrainer(outbox: outbox, transport: { [weak self] in self?.supplier() }, connectivity: connectivity, maxBatchBytes: 512 * 1024) { [weak self] lane, entries, transport in guard let self else { throw CancellationError() } return try await self.send(lane, entries: entries, transport: transport) } } func metadata(_ key: String) throws -> DocsOfflineMetadata? { guard let bytes = try store.read("cache/docs/\(key)/meta") else { return nil } return try JSONDecoder().decode(DocsOfflineMetadata.self, from: bytes) } private func index() throws -> [String: String] { try store.read("cache/docs/index").map { try JSONDecoder().decode([String: String].self, from: $0) } ?? [:] } func saveMetadata(_ metadata: DocsOfflineMetadata, key: String) throws { // Register the immutable key first. A crash may leave an empty slot, // never undiscoverable metadata or a rename that Home cannot replay. var index = try index() if index[key] == nil { index[key] = key try store.write(JSONEncoder().encode(index), to: "cache/docs/index") } try store.write(JSONEncoder().encode(metadata), to: "cache/docs/\(key)/meta") if metadata.draftToken == nil, index[metadata.detail.sqid] != key { index[metadata.detail.sqid] = key try store.write(JSONEncoder().encode(index), to: "cache/docs/index") } } func key(for sqid: String) throws -> String { let index = try index() if let key = index[sqid] { return key } // The alias is derived state. Attachment metadata is committed first, // so scanning registered keys heals a kill before the alias write. for key in Set(index.values).sorted() { if let metadata = try metadata(key), metadata.detail.sqid == sqid { try saveMetadata(metadata, key: key) return key } } return sqid } func ensureMetadataEntry(_ key: String) async throws { let generation = replicaCache.generation(key) guard let metadata = try metadata(key), metadata.pendingTitle != nil || metadata.draftToken != nil else { return } let entries = await outbox.entries(lane: "doc:" + key, excludingInFlight: true) guard replicaCache.generation(key) == generation, !entries.contains(where: { $0.kind == "metadata" }) else { return } try await outbox.enqueue(lane: "doc:" + key, kind: "metadata", payload: Data()) } func activate() async throws { try await outbox.load() // Older K3 records can also be discovered from their durable lane. let lanes = await outbox.summary.lanes.keys let keys = Set(try index().values).union(lanes.filter { $0.hasPrefix("doc:") }.map { String($0.dropFirst(4)) }) for key in keys.sorted() { try await ensureMetadataEntry(key) } drainer.start(); drainer.kick() } private static func form(_ values: [String: String]) -> Data { var form = URLComponents(); form.queryItems = values.map { URLQueryItem(name: $0.key, value: $0.value) } return Data((form.percentEncodedQuery ?? "").replacingOccurrences(of: "+", with: "%2B").utf8) } private func send(_ lane: String, entries: [OutboxEntry], transport: NativeTransport) async throws -> [UUID: OutboxDrainer.Disposition] { let key = String(lane.dropFirst(4)), generation = replicaCache.generation(String(lane.dropFirst(4))) let saved: DocsOfflineMetadata? do { saved = try metadata(key) } catch BlobStoreError.corrupt { saved = nil } catch is DecodingError { saved = nil } // A missing/corrupt destination cannot be retried into existence. Keep // its lane for resolution, without mistaking a locked store for loss. guard lane.hasPrefix("doc:"), var metadata = saved else { return Dictionary(uniqueKeysWithValues: entries.map { ($0.id, .hold(Hold(.rejected("metadata")))) }) } if let token = metadata.draftToken { let reply = try await transport.responseDetails("/documents", method: "POST", body: Self.form(["title": metadata.detail.title, "creation_token": token]), contentType: "application/x-www-form-urlencoded") try reply.requireSuccess() let item = try JSONDecoder().decode(DocumentSummary.self, from: reply.data) let attached: DocumentDetail = try await transport.request("/d/\(item.sqid)") guard replicaCache.generation(key) == generation, let latest = try self.metadata(key) else { throw CancellationError() } metadata = latest metadata.detail = DocumentDetail(sqid: attached.sqid, title: latest.pendingTitle ?? attached.title, guid: attached.guid, can_write: attached.can_write, can_share: attached.can_share) metadata.draftToken = nil // Commit identity before publishing it or attempting text sends. try saveMetadata(metadata, key: key) } while let title = metadata.pendingTitle { let reply = try await transport.responseDetails("/d/\(metadata.detail.sqid)/title", method: "POST", body: Self.form(["title": title]), contentType: "application/x-www-form-urlencoded") try reply.requireSuccess() guard replicaCache.generation(key) == generation, var latest = try self.metadata(key) else { throw CancellationError() } if latest.pendingTitle == title { latest.pendingTitle = nil; try saveMetadata(latest, key: key) } metadata = latest // A rename during this POST must also be sent. } let updates = entries.filter { $0.kind == "update" } var dispositions = Dictionary(uniqueKeysWithValues: entries.filter { $0.kind == "metadata" }.map { ($0.id, OutboxDrainer.Disposition.sent) }) guard !updates.isEmpty else { return dispositions } let merger = CRDTReplica(guid: metadata.detail.guid) let update: Data var sending = updates do { _ = try await merger.open(update: Data()) do { update = try await merger.mergeUpdates(updates.map(\.payload)) } catch { sending = Array(updates.prefix(1)); update = sending[0].payload } await merger.close() } catch { await merger.close(); throw error } let reply = try await transport.responseDetails("/d/\(metadata.detail.sqid)/updates", method: "POST", body: update, contentType: "application/octet-stream") try reply.requireSuccess() var state = update, sequence: Int64 = 0 if try store.read("cache/docs/\(key)/replica") == nil { let initial = try await transport.responseDetails("/d/\(metadata.detail.sqid)/updates", maxBytes: 8 * 1024 * 1024) try initial.requireSuccess() guard let cursor = Int64(initial.header("Docs-Seq") ?? "") else { throw NativeClientError.invalidResponse } state = initial.data; sequence = cursor } // Keep sent bytes locally before ack can remove their lane files. try await replicaCache.commit(PersistedReplica(format: 1, sequence: sequence, guid: metadata.detail.guid, savedAt: Date(), state: state), key: key, generation: generation) for entry in sending { dispositions[entry.id] = .sent } return dispositions } } /// Used only by previews and callers that have no NativeAccount (unit tests). /// The application always supplies its per-account sealed store. final class EphemeralDocsStore: BlobStore, @unchecked Sendable { private let lock = NSLock() private var files: [String: Data] = [:] func read(_ path: String) throws -> Data? { lock.withLock { files[path] } } func write(_ data: Data, to path: String) throws { lock.withLock { files[path] = data } } func remove(_ path: String) throws { lock.withLock { files = files.filter { $0.key != path && !$0.key.hasPrefix(path + "/") } } } func list(_ directory: String) throws -> [String] { lock.withLock { files.keys.filter { $0.hasPrefix(directory + "/") }.map { String($0.dropFirst(directory.count + 1)) }.filter { !$0.contains("/") }.sorted() } } }