oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1import Foundation
2import Observation
3import RastrilloApple
4import RastrilloNative
5
6struct DocsOfflineMetadata: Codable {
7 var detail: DocumentDetail
8 var pendingTitle: String?
9 var draftToken: String?
10}
11
12/// All windows for an account share the same outbox and send reservation.
13@MainActor @Observable final class DocsOfflineAccount {
14 private static var accounts: [String: DocsOfflineAccount] = [:]
15 let store: BlobStore
16 let outbox: Outbox
17 let connectivity: NativeConnectivity
18 let replicaCache: DocsReplicaCache
19 private var supplier: @MainActor () -> NativeTransport?
20 private(set) var drainer: OutboxDrainer!
21 static func account(_ id: String, origin: URL, fallback: NativeTransport, transport: (@MainActor () -> NativeTransport?)?) -> DocsOfflineAccount {
22 if let existing = accounts[id] { if let transport { existing.supplier = transport; existing.drainer.sessionRestored() }; return existing }
23 let root = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0]
24 .appendingPathComponent(Bundle.main.bundleIdentifier ?? "works.oficina.docs")
25 .appendingPathComponent("accounts").appendingPathComponent(id)
26 let store = NativeSealedStore(root: root, accountID: id, keys: KeychainKeyProvider(accountID: id, origin: origin))
27 let account = DocsOfflineAccount(store: store, accountID: id, connectivity: .shared, transport: transport ?? { fallback })
28 accounts[id] = account; return account
29 }
30 init(store: BlobStore, accountID: String, connectivity: NativeConnectivity, transport: @escaping @MainActor () -> NativeTransport?) {
31 self.store = store; outbox = Outbox(store: store, account: accountID)
32 replicaCache = DocsReplicaCache(store: store)
33 self.connectivity = connectivity; supplier = transport
34 drainer = OutboxDrainer(outbox: outbox, transport: { [weak self] in self?.supplier() }, connectivity: connectivity, maxBatchBytes: 512 * 1024) { [weak self] lane, entries, transport in
35 guard let self else { throw CancellationError() }
36 return try await self.send(lane, entries: entries, transport: transport)
37 }
38 }
39 func metadata(_ key: String) throws -> DocsOfflineMetadata? {
40 guard let bytes = try store.read("cache/docs/\(key)/meta") else { return nil }
41 return try JSONDecoder().decode(DocsOfflineMetadata.self, from: bytes)
42 }
43 private func index() throws -> [String: String] {
44 try store.read("cache/docs/index").map { try JSONDecoder().decode([String: String].self, from: $0) } ?? [:]
45 }
46 func saveMetadata(_ metadata: DocsOfflineMetadata, key: String) throws {
47 // Register the immutable key first. A crash may leave an empty slot,
48 // never undiscoverable metadata or a rename that Home cannot replay.
49 var index = try index()
50 if index[key] == nil {
51 index[key] = key
52 try store.write(JSONEncoder().encode(index), to: "cache/docs/index")
53 }
54 try store.write(JSONEncoder().encode(metadata), to: "cache/docs/\(key)/meta")
55 if metadata.draftToken == nil, index[metadata.detail.sqid] != key {
56 index[metadata.detail.sqid] = key
57 try store.write(JSONEncoder().encode(index), to: "cache/docs/index")
58 }
59 }
60 func key(for sqid: String) throws -> String {
61 let index = try index()
62 if let key = index[sqid] { return key }
63 // The alias is derived state. Attachment metadata is committed first,
64 // so scanning registered keys heals a kill before the alias write.
65 for key in Set(index.values).sorted() {
66 if let metadata = try metadata(key), metadata.detail.sqid == sqid {
67 try saveMetadata(metadata, key: key)
68 return key
69 }
70 }
71 return sqid
72 }
73 func ensureMetadataEntry(_ key: String) async throws {
74 let generation = replicaCache.generation(key)
75 guard let metadata = try metadata(key), metadata.pendingTitle != nil || metadata.draftToken != nil else { return }
76 let entries = await outbox.entries(lane: "doc:" + key, excludingInFlight: true)
77 guard replicaCache.generation(key) == generation, !entries.contains(where: { $0.kind == "metadata" }) else { return }
78 try await outbox.enqueue(lane: "doc:" + key, kind: "metadata", payload: Data())
79 }
80 func activate() async throws {
81 try await outbox.load()
82 // Older K3 records can also be discovered from their durable lane.
83 let lanes = await outbox.summary.lanes.keys
84 let keys = Set(try index().values).union(lanes.filter { $0.hasPrefix("doc:") }.map { String($0.dropFirst(4)) })
85 for key in keys.sorted() { try await ensureMetadataEntry(key) }
86 drainer.start(); drainer.kick()
87 }
88 private static func form(_ values: [String: String]) -> Data {
89 var form = URLComponents(); form.queryItems = values.map { URLQueryItem(name: $0.key, value: $0.value) }
90 return Data((form.percentEncodedQuery ?? "").replacingOccurrences(of: "+", with: "%2B").utf8)
91 }
92 private func send(_ lane: String, entries: [OutboxEntry], transport: NativeTransport) async throws -> [UUID: OutboxDrainer.Disposition] {
93 let key = String(lane.dropFirst(4)), generation = replicaCache.generation(String(lane.dropFirst(4)))
94 let saved: DocsOfflineMetadata?
95 do { saved = try metadata(key) }
96 catch BlobStoreError.corrupt { saved = nil }
97 catch is DecodingError { saved = nil }
98 // A missing/corrupt destination cannot be retried into existence. Keep
99 // its lane for resolution, without mistaking a locked store for loss.
100 guard lane.hasPrefix("doc:"), var metadata = saved else {
101 return Dictionary(uniqueKeysWithValues: entries.map { ($0.id, .hold(Hold(.rejected("metadata")))) })
102 }
103 if let token = metadata.draftToken {
104 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")
105 try reply.requireSuccess()
106 let item = try JSONDecoder().decode(DocumentSummary.self, from: reply.data)
107 let attached: DocumentDetail = try await transport.request("/d/\(item.sqid)")
108 guard replicaCache.generation(key) == generation, let latest = try self.metadata(key) else { throw CancellationError() }
109 metadata = latest
110 metadata.detail = DocumentDetail(sqid: attached.sqid, title: latest.pendingTitle ?? attached.title, guid: attached.guid, can_write: attached.can_write, can_share: attached.can_share)
111 metadata.draftToken = nil
112 // Commit identity before publishing it or attempting text sends.
113 try saveMetadata(metadata, key: key)
114 }
115 while let title = metadata.pendingTitle {
116 let reply = try await transport.responseDetails("/d/\(metadata.detail.sqid)/title", method: "POST", body: Self.form(["title": title]), contentType: "application/x-www-form-urlencoded")
117 try reply.requireSuccess()
118 guard replicaCache.generation(key) == generation, var latest = try self.metadata(key) else { throw CancellationError() }
119 if latest.pendingTitle == title { latest.pendingTitle = nil; try saveMetadata(latest, key: key) }
120 metadata = latest // A rename during this POST must also be sent.
121 }
122 let updates = entries.filter { $0.kind == "update" }
123 var dispositions = Dictionary(uniqueKeysWithValues: entries.filter { $0.kind == "metadata" }.map { ($0.id, OutboxDrainer.Disposition.sent) })
124 guard !updates.isEmpty else { return dispositions }
125 let merger = CRDTReplica(guid: metadata.detail.guid)
126 let update: Data
127 var sending = updates
128 do {
129 _ = try await merger.open(update: Data())
130 do { update = try await merger.mergeUpdates(updates.map(\.payload)) }
131 catch { sending = Array(updates.prefix(1)); update = sending[0].payload }
132 await merger.close()
133 } catch { await merger.close(); throw error }
134 let reply = try await transport.responseDetails("/d/\(metadata.detail.sqid)/updates", method: "POST", body: update, contentType: "application/octet-stream")
135 try reply.requireSuccess()
136 var state = update, sequence: Int64 = 0
137 if try store.read("cache/docs/\(key)/replica") == nil {
138 let initial = try await transport.responseDetails("/d/\(metadata.detail.sqid)/updates", maxBytes: 8 * 1024 * 1024)
139 try initial.requireSuccess()
140 guard let cursor = Int64(initial.header("Docs-Seq") ?? "") else { throw NativeClientError.invalidResponse }
141 state = initial.data; sequence = cursor
142 }
143 // Keep sent bytes locally before ack can remove their lane files.
144 try await replicaCache.commit(PersistedReplica(format: 1, sequence: sequence, guid: metadata.detail.guid, savedAt: Date(), state: state), key: key, generation: generation)
145 for entry in sending { dispositions[entry.id] = .sent }
146 return dispositions
147 }
148
149}
150
151/// Used only by previews and callers that have no NativeAccount (unit tests).
152/// The application always supplies its per-account sealed store.
153final class EphemeralDocsStore: BlobStore, @unchecked Sendable {
154 private let lock = NSLock()
155 private var files: [String: Data] = [:]
156 func read(_ path: String) throws -> Data? { lock.withLock { files[path] } }
157 func write(_ data: Data, to path: String) throws { lock.withLock { files[path] = data } }
158 func remove(_ path: String) throws { lock.withLock { files = files.filter { $0.key != path && !$0.key.hasPrefix(path + "/") } } }
159 func list(_ directory: String) throws -> [String] { lock.withLock {
160 files.keys.filter { $0.hasPrefix(directory + "/") }.map { String($0.dropFirst(directory.count + 1)) }.filter { !$0.contains("/") }.sorted()
161 } }
162}
163