| 1 | import Foundation |
| 2 | import Observation |
| 3 | import RastrilloApple |
| 4 | import RastrilloNative |
| 5 | |
| 6 | struct DocsOfflineMetadata: Codable { |
| 7 | var detail: DocumentDetail |
| 8 | var pendingTitle: String? |
| 9 | var draftToken: String? |
| 10 | } |
| 11 | |
| 12 | /// What one POST of a document's updates came back with: the sequence the |
| 13 | /// server gave it (nil if it failed or carried none) and the outbox entries |
| 14 | /// whose bytes it carried. |
| 15 | struct DocsSentUpdates: Sendable { |
| 16 | let key: String |
| 17 | let sequence: Int64? |
| 18 | let entries: Set<UUID> |
| 19 | } |
| 20 | |
| 21 | /// All windows for an account share the same outbox and send reservation. |
| 22 | @MainActor @Observable final class DocsOfflineAccount { |
| 23 | static var accounts: [String: DocsOfflineAccount] = [:] |
| 24 | let store: BlobStore |
| 25 | let outbox: Outbox |
| 26 | let connectivity: NativeConnectivity |
| 27 | let replicaCache: DocsReplicaCache |
| 28 | /// Never observed: a view reads the drainer's state, not which closure |
| 29 | /// supplies its transport. |
| 30 | @ObservationIgnored private var supplier: @MainActor () -> NativeTransport? |
| 31 | private(set) var drainer: OutboxDrainer! |
| 32 | /// The least time between two update POSTs for one document, as the web |
| 33 | /// editor's 250 ms save throttle. The first send after a pause goes at |
| 34 | /// once. While typing continues, a send that leaves more of its lane |
| 35 | /// waiting holds the drainer until the next POST is allowed, so the |
| 36 | /// keystrokes typed meanwhile are reserved into that POST rather than |
| 37 | /// the one after it. Each keystroke still reaches the outbox on disk |
| 38 | /// first, so this only delays the network, never durability. |
| 39 | @ObservationIgnored var sendInterval: Duration = .milliseconds(250) |
| 40 | @ObservationIgnored private var lastUpdatePost: [String: ContinuousClock.Instant] = [:] |
| 41 | /// Until then nothing waits for the throttle (`sendNow`). |
| 42 | @ObservationIgnored private var hurriedUntil: ContinuousClock.Instant? |
| 43 | @ObservationIgnored private var pacing: (id: UUID, wake: CheckedContinuation<Void, Never>)? |
| 44 | /// Documents whose update POST is on the wire now. |
| 45 | @ObservationIgnored private(set) var postingUpdates: Set<String> = [] |
| 46 | @ObservationIgnored private var sendObservers: [UUID: @MainActor (DocsSentUpdates) -> Void] = [:] |
| 47 | /// Bumped by every metadata write this account makes, so an open |
| 48 | /// document re-reads (and decrypts) its metadata only when it changed. |
| 49 | @ObservationIgnored private(set) var metadataRevisions: [String: Int] = [:] |
| 50 | /// The account's shared store, outbox and drainer, made on first use. |
| 51 | /// Called from a view's initialiser, which runs inside its window's body |
| 52 | /// on every pass: anything observed it reads joins that body's |
| 53 | /// dependencies, and anything observed it mutates (the drainer's |
| 54 | /// backoff, its session, this supplier) invalidates them. Docs |
| 55 | /// 0.1.7/0.1.8 did both here, so the body re-ran for ever and the main |
| 56 | /// thread spun at launch. So: a lookup, nothing else. A workspace calls |
| 57 | /// `resume(transport:)` from its `.task` instead. |
| 58 | static func account(_ id: String, origin: URL, fallback: NativeTransport, transport: (@MainActor () -> NativeTransport?)?) -> DocsOfflineAccount { |
| 59 | if let existing = accounts[id] { return existing } |
| 60 | let root = accountsRoot.appendingPathComponent(id) |
| 61 | let store = NativeSealedStore(root: root, accountID: id, keys: keys(accountID: id, origin: origin)) |
| 62 | let account = DocsOfflineAccount(store: store, accountID: id, connectivity: .shared, transport: transport ?? { fallback }) |
| 63 | accounts[id] = account; return account |
| 64 | } |
| 65 | static var accountsRoot: URL { |
| 66 | FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] |
| 67 | .appendingPathComponent(Bundle.main.bundleIdentifier ?? "works.oficina.docs") |
| 68 | .appendingPathComponent("accounts") |
| 69 | } |
| 70 | |
| 71 | /// What every Oficina ID team's store key is filed under, whatever its |
| 72 | /// origin. A team's origin can change (a label moved, a rename, a team |
| 73 | /// self-hosting by DNS) while its account, keyed by (identity, team), |
| 74 | /// does not; keyed by origin, the store would find no key and delete |
| 75 | /// itself, unsent outbox and all. Server accounts keep their origin: an |
| 76 | /// account there is a host. |
| 77 | nonisolated static let oficinaKeyOrigin = URL(string: "https://oficina-id.invalid")! |
| 78 | |
| 79 | nonisolated static func keys(accountID: String, origin: URL) -> KeychainKeyProvider { |
| 80 | KeychainKeyProvider(accountID: accountID, origin: DocsOficinaSession.isOficinaAccount(accountID) ? oficinaKeyOrigin : origin) |
| 81 | } |
| 82 | |
| 83 | /// Whether any of `identity`'s teams has changes on this device not yet |
| 84 | /// sent: the outboxes open in this run, and any left on disk by an |
| 85 | /// earlier one (a crash, a quit with a lane held) that nothing has |
| 86 | /// opened since. Signing out must not strand them. |
| 87 | static func hasUnsent(identity: String, root: URL? = nil, |
| 88 | keys: (String) -> KeyProvider = { keys(accountID: $0, origin: oficinaKeyOrigin) }) async -> Bool { |
| 89 | for (id, account) in accounts where DocsOficinaSession.account(id, belongsTo: identity) { |
| 90 | if await !account.outbox.summary.isEmpty { return true } |
| 91 | } |
| 92 | let root = root ?? accountsRoot |
| 93 | let names = (try? FileManager.default.contentsOfDirectory(atPath: root.path)) ?? [] |
| 94 | for name in names.sorted() where DocsOficinaSession.account(name, belongsTo: identity) && accounts[name] == nil { |
| 95 | let outbox = Outbox(store: NativeSealedStore(root: root.appendingPathComponent(name), accountID: name, keys: keys(name)), account: name) |
| 96 | // An outbox that can't be read (its key unavailable, the device |
| 97 | // locked) is skipped on purpose: it is not deleted, its store stays |
| 98 | // on disk, and it resumes sending when the same identity signs in |
| 99 | // again. Refusing sign-out over it would lock the person in. |
| 100 | guard (try? await outbox.load()) != nil else { continue } |
| 101 | if await !outbox.summary.isEmpty { return true } |
| 102 | } |
| 103 | return false |
| 104 | } |
| 105 | |
| 106 | /// The account's session was replaced (Oficina ID re-minted it): an |
| 107 | /// outbox that stopped on the old one's 401 sends again. |
| 108 | static func sessionRestored(_ id: String) { accounts[id]?.drainer.sessionRestored() } |
| 109 | |
| 110 | /// A request on the account's old session was refused after the session |
| 111 | /// had been replaced. If it was the outbox's, its "signed out" stops the |
| 112 | /// drainer, possibly after the replacement restarted it: so a drain in |
| 113 | /// flight is let finish (joining it starts nothing new), and the outbox |
| 114 | /// is restarted on the session it now has. |
| 115 | static func sessionReplaced(_ id: String) async { |
| 116 | guard let drainer = accounts[id]?.drainer else { return } |
| 117 | if drainer.phase == .sending { await drainer.drain() } |
| 118 | drainer.sessionRestored() |
| 119 | } |
| 120 | |
| 121 | /// A workspace for this account appeared with a session (a sign-in made |
| 122 | /// a new one): its outbox sends through it, and sends again if it had |
| 123 | /// stopped on the old session's 401. |
| 124 | func resume(transport: @escaping @MainActor () -> NativeTransport?) { |
| 125 | supplier = transport |
| 126 | drainer.sessionRestored() |
| 127 | } |
| 128 | init(store: BlobStore, accountID: String, connectivity: NativeConnectivity, transport: @escaping @MainActor () -> NativeTransport?) { |
| 129 | self.store = store; outbox = Outbox(store: store, account: accountID) |
| 130 | replicaCache = DocsReplicaCache(store: store) |
| 131 | self.connectivity = connectivity; supplier = transport |
| 132 | drainer = OutboxDrainer(outbox: outbox, transport: { [weak self] in self?.supplier() }, connectivity: connectivity, maxBatchBytes: 512 * 1024) { [weak self] lane, entries, transport in |
| 133 | guard let self else { throw CancellationError() } |
| 134 | return try await self.send(lane, entries: entries, transport: transport) |
| 135 | } |
| 136 | } |
| 137 | func metadata(_ key: String) throws -> DocsOfflineMetadata? { |
| 138 | guard let bytes = try store.read("cache/docs/\(key)/meta") else { return nil } |
| 139 | return try JSONDecoder().decode(DocsOfflineMetadata.self, from: bytes) |
| 140 | } |
| 141 | private func index() throws -> [String: String] { |
| 142 | try store.read("cache/docs/index").map { try JSONDecoder().decode([String: String].self, from: $0) } ?? [:] |
| 143 | } |
| 144 | func saveMetadata(_ metadata: DocsOfflineMetadata, key: String) throws { |
| 145 | defer { metadataRevisions[key, default: 0] += 1 } |
| 146 | // Register the immutable key first. A crash may leave an empty slot, |
| 147 | // never undiscoverable metadata or a rename that Home cannot replay. |
| 148 | var index = try index() |
| 149 | if index[key] == nil { |
| 150 | index[key] = key |
| 151 | try store.write(JSONEncoder().encode(index), to: "cache/docs/index") |
| 152 | } |
| 153 | try store.write(JSONEncoder().encode(metadata), to: "cache/docs/\(key)/meta") |
| 154 | if metadata.draftToken == nil, index[metadata.detail.sqid] != key { |
| 155 | index[metadata.detail.sqid] = key |
| 156 | try store.write(JSONEncoder().encode(index), to: "cache/docs/index") |
| 157 | } |
| 158 | } |
| 159 | func removeMetadata(_ key: String) throws { |
| 160 | defer { metadataRevisions[key, default: 0] += 1 } |
| 161 | try store.remove("cache/docs/\(key)/meta") |
| 162 | } |
| 163 | /// An open document hears every update POST's answer, to skip fetching |
| 164 | /// its own change back (see `DocsModel.sent`). |
| 165 | func observeSends(_ observer: @escaping @MainActor (DocsSentUpdates) -> Void) -> UUID { |
| 166 | let id = UUID(); sendObservers[id] = observer; return id |
| 167 | } |
| 168 | func stopObservingSends(_ id: UUID) { sendObservers[id] = nil } |
| 169 | /// Send what is waiting now, without the typing throttle: Save, closing |
| 170 | /// a document, the app going to the background. |
| 171 | func sendNow() { |
| 172 | lastUpdatePost.removeAll() |
| 173 | hurriedUntil = ContinuousClock.now.advanced(by: .seconds(1)) |
| 174 | if let pacing { self.pacing = nil; pacing.wake.resume() } |
| 175 | drainer.kick() |
| 176 | } |
| 177 | private func pace(_ key: String) async { |
| 178 | if let hurriedUntil, hurriedUntil > .now { return } |
| 179 | guard let last = lastUpdatePost[key] else { return } |
| 180 | let due = last.advanced(by: sendInterval) |
| 181 | guard due > .now else { return } |
| 182 | let id = UUID() |
| 183 | await withCheckedContinuation { (wake: CheckedContinuation<Void, Never>) in |
| 184 | pacing = (id, wake) |
| 185 | Task { [weak self] in |
| 186 | try? await Task.sleep(until: due) |
| 187 | guard let self, let pacing = self.pacing, pacing.id == id else { return } |
| 188 | self.pacing = nil; pacing.wake.resume() |
| 189 | } |
| 190 | } |
| 191 | } |
| 192 | private func posted(_ result: DocsSentUpdates) { |
| 193 | postingUpdates.remove(result.key) |
| 194 | for observer in sendObservers.values { observer(result) } |
| 195 | } |
| 196 | func key(for sqid: String) throws -> String { |
| 197 | let index = try index() |
| 198 | if let key = index[sqid] { return key } |
| 199 | // The alias is derived state. Attachment metadata is committed first, |
| 200 | // so scanning registered keys heals a kill before the alias write. |
| 201 | for key in Set(index.values).sorted() { |
| 202 | if let metadata = try metadata(key), metadata.detail.sqid == sqid { |
| 203 | try saveMetadata(metadata, key: key) |
| 204 | return key |
| 205 | } |
| 206 | } |
| 207 | return sqid |
| 208 | } |
| 209 | func ensureMetadataEntry(_ key: String) async throws { |
| 210 | let generation = replicaCache.generation(key) |
| 211 | guard let metadata = try metadata(key), metadata.pendingTitle != nil || metadata.draftToken != nil else { return } |
| 212 | let entries = await outbox.entries(lane: "doc:" + key, excludingInFlight: true) |
| 213 | guard replicaCache.generation(key) == generation, !entries.contains(where: { $0.kind == "metadata" }) else { return } |
| 214 | try await outbox.enqueue(lane: "doc:" + key, kind: "metadata", payload: Data()) |
| 215 | } |
| 216 | func activate() async throws { |
| 217 | try await outbox.load() |
| 218 | // Older K3 records can also be discovered from their durable lane. |
| 219 | let lanes = await outbox.summary.lanes.keys |
| 220 | let keys = Set(try index().values).union(lanes.filter { $0.hasPrefix("doc:") }.map { String($0.dropFirst(4)) }) |
| 221 | for key in keys.sorted() { try await ensureMetadataEntry(key) } |
| 222 | drainer.start(); drainer.kick() |
| 223 | } |
| 224 | private static func form(_ values: [String: String]) -> Data { |
| 225 | var form = URLComponents(); form.queryItems = values.map { URLQueryItem(name: $0.key, value: $0.value) } |
| 226 | return Data((form.percentEncodedQuery ?? "").replacingOccurrences(of: "+", with: "%2B").utf8) |
| 227 | } |
| 228 | private func send(_ lane: String, entries: [OutboxEntry], transport: NativeTransport) async throws -> [UUID: OutboxDrainer.Disposition] { |
| 229 | let key = String(lane.dropFirst(4)), generation = replicaCache.generation(String(lane.dropFirst(4))) |
| 230 | let saved: DocsOfflineMetadata? |
| 231 | do { saved = try metadata(key) } |
| 232 | catch BlobStoreError.corrupt { saved = nil } |
| 233 | catch is DecodingError { saved = nil } |
| 234 | // A missing/corrupt destination cannot be retried into existence. Keep |
| 235 | // its lane for resolution, without mistaking a locked store for loss. |
| 236 | guard lane.hasPrefix("doc:"), var metadata = saved else { |
| 237 | return Dictionary(uniqueKeysWithValues: entries.map { ($0.id, .hold(Hold(.rejected("metadata")))) }) |
| 238 | } |
| 239 | if let token = metadata.draftToken { |
| 240 | 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") |
| 241 | try reply.requireSuccess() |
| 242 | let item = try JSONDecoder().decode(DocumentSummary.self, from: reply.data) |
| 243 | let attached: DocumentDetail = try await transport.request("/d/\(item.sqid)") |
| 244 | guard replicaCache.generation(key) == generation, let latest = try self.metadata(key) else { throw CancellationError() } |
| 245 | metadata = latest |
| 246 | metadata.detail = DocumentDetail(sqid: attached.sqid, title: latest.pendingTitle ?? attached.title, guid: attached.guid, can_write: attached.can_write, can_share: attached.can_share) |
| 247 | metadata.draftToken = nil |
| 248 | // Commit identity before publishing it or attempting text sends. |
| 249 | try saveMetadata(metadata, key: key) |
| 250 | } |
| 251 | while let title = metadata.pendingTitle { |
| 252 | let reply = try await transport.responseDetails("/d/\(metadata.detail.sqid)/title", method: "POST", body: Self.form(["title": title]), contentType: "application/x-www-form-urlencoded") |
| 253 | try reply.requireSuccess() |
| 254 | guard replicaCache.generation(key) == generation, var latest = try self.metadata(key) else { throw CancellationError() } |
| 255 | if latest.pendingTitle == title { latest.pendingTitle = nil; try saveMetadata(latest, key: key) } |
| 256 | metadata = latest // A rename during this POST must also be sent. |
| 257 | } |
| 258 | let updates = entries.filter { $0.kind == "update" } |
| 259 | var dispositions = Dictionary(uniqueKeysWithValues: entries.filter { $0.kind == "metadata" }.map { ($0.id, OutboxDrainer.Disposition.sent) }) |
| 260 | guard !updates.isEmpty else { return dispositions } |
| 261 | let merger = CRDTReplica(guid: metadata.detail.guid) |
| 262 | let update: Data |
| 263 | var sending = updates |
| 264 | do { |
| 265 | try await merger.open(update: Data()) |
| 266 | do { update = try await merger.mergeUpdates(updates.map(\.payload)) } |
| 267 | catch { sending = Array(updates.prefix(1)); update = sending[0].payload } |
| 268 | await merger.close() |
| 269 | } catch { await merger.close(); throw error } |
| 270 | await pace(key) |
| 271 | // A discard during the wait must not be sent. |
| 272 | guard replicaCache.generation(key) == generation else { throw CancellationError() } |
| 273 | lastUpdatePost[key] = .now |
| 274 | postingUpdates.insert(key) |
| 275 | let reply: NativeResponse |
| 276 | do { reply = try await transport.responseDetails("/d/\(metadata.detail.sqid)/updates", method: "POST", body: update, contentType: "application/octet-stream") } |
| 277 | catch { posted(DocsSentUpdates(key: key, sequence: nil, entries: [])); throw error } |
| 278 | let assigned = (200..<300).contains(reply.status) ? Int64(reply.header("Docs-Seq") ?? "") : nil |
| 279 | posted(DocsSentUpdates(key: key, sequence: assigned, entries: Set(sending.map(\.id)))) |
| 280 | try reply.requireSuccess() |
| 281 | // Keep sent bytes locally before ack can remove their lane files. |
| 282 | if try replicaCache.hasBase(key), try replicaCache.append(update, sequence: 0, key: key, generation: generation) { |
| 283 | try? await replicaCache.compactIfNeeded(key, generation: generation, appended: update.count) |
| 284 | } else { |
| 285 | var state = update, sequence: Int64 = 0, parked: String? = nil |
| 286 | if try !replicaCache.hasBase(key) { |
| 287 | let initial = try await transport.responseDetails("/d/\(metadata.detail.sqid)/updates", maxBytes: 8 * 1024 * 1024) |
| 288 | try initial.requireSuccess() |
| 289 | guard let cursor = Int64(initial.header("Docs-Seq") ?? "") else { throw NativeClientError.invalidResponse } |
| 290 | state = initial.data; sequence = cursor |
| 291 | // The server's whole state: what it parks is the server's own, and |
| 292 | // the first record accepts it, as a first open does (#147). |
| 293 | let reader = CRDTReplica(guid: metadata.detail.guid) |
| 294 | do { try await reader.open(update: state); parked = try await reader.parked(); await reader.close() } |
| 295 | catch { await reader.close(); throw error } |
| 296 | } |
| 297 | try await replicaCache.commit(PersistedReplica(format: 1, sequence: sequence, guid: metadata.detail.guid, savedAt: Date(), state: state, parked: parked), key: key, generation: generation) |
| 298 | } |
| 299 | // More of this lane is waiting (typed during this POST): hold the |
| 300 | // drainer until the next POST is allowed, then let it reserve |
| 301 | // everything typed by then in one batch. |
| 302 | if await !outbox.sendable(lane: lane).isEmpty { await pace(key) } |
| 303 | for entry in sending { dispositions[entry.id] = .sent } |
| 304 | return dispositions |
| 305 | } |
| 306 | |
| 307 | } |
| 308 | |
| 309 | /// Used only by previews and callers that have no NativeAccount (unit tests). |
| 310 | /// The application always supplies its per-account sealed store. |
| 311 | final class EphemeralDocsStore: BlobStore, @unchecked Sendable { |
| 312 | private let lock = NSLock() |
| 313 | private var files: [String: Data] = [:] |
| 314 | func read(_ path: String) throws -> Data? { lock.withLock { files[path] } } |
| 315 | func write(_ data: Data, to path: String) throws { lock.withLock { files[path] = data } } |
| 316 | func remove(_ path: String) throws { lock.withLock { files = files.filter { $0.key != path && !$0.key.hasPrefix(path + "/") } } } |
| 317 | func list(_ directory: String) throws -> [String] { lock.withLock { |
| 318 | files.keys.filter { $0.hasPrefix(directory + "/") }.map { String($0.dropFirst(directory.count + 1)) }.filter { !$0.contains("/") }.sorted() |
| 319 | } } |
| 320 | } |
| 321 | |