oficina / sheets Public

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

Plain git — no account needed to clone.

Download

Download this file

1import Foundation
2import RastrilloApple
3#if os(iOS)
4import UIKit
5#endif
6
7/// A value edit the server has not acknowledged yet.
8///
9/// Edits are optimistic (Paul, 2026-11-26: "the cell goes grey for a second
10/// to wait for the server … unnecessary"). Committing a cell records it here
11/// and returns at once; the cell paints this value normally while one send
12/// per document carries it, and any edits made meanwhile wait behind that send
13/// and go together in the next one.
14///
15/// The display rule, which `SheetModel.displayCell` implements:
16/// - queued or sending: the local value wins. A peer update for the same cell
17/// lands underneath in `cells` and does not flicker the local value back
18/// and forth.
19/// - acknowledged: the entry is removed and the cell shows the server's value,
20/// which is the newest by version (ours, or a peer's that came after it).
21/// - failed: the local value stays on screen, marked as not saved, until
22/// Retry sends it again or Revert drops it and shows the server's value.
23/// An unsaved value nobody can see is one nobody can decide to keep.
24struct PendingEdit: Sendable, Equatable {
25 enum State: Sendable, Equatable { case queued, sending, failed }
26 var write: CellWrite
27 var state: State
28 /// Each new edit to a cell gets a higher generation, so an answer for an
29 /// older send never resolves a newer edit made while it was in flight.
30 var generation: UInt64
31}
32
33@MainActor extension SheetModel {
34 /// Records value edits and starts sending them. Returns false only when the
35 /// edit cannot be accepted at all (no write access, or over the size limit);
36 /// the answer from the server arrives later and never blocks editing.
37 @discardableResult func write(_ writes: [CellWrite]) -> Bool {
38 guard mayWrite else { return false }
39 hurried = false
40 // Mid-switch, an edit could only be sent to the sheet being left.
41 guard !opening else { return false }
42 guard writes.allSatisfy({ $0.raw.utf8.count <= 8192 }) else {
43 error = "A cell exceeds the input size limit. Nothing was changed."
44 return false
45 }
46 if writes.isEmpty { return true }
47 var next = pending
48 for write in writes {
49 editGeneration += 1
50 next[Coordinate(r: write.r, c: write.c)] = PendingEdit(
51 write: write, state: .queued, generation: editGeneration)
52 }
53 pending = next
54 startSending()
55 return true
56 }
57
58 var hasFailedEdits: Bool { pending.values.contains { $0.state == .failed } }
59 var isSending: Bool { pending.values.contains { $0.state != .failed } }
60 /// The status bar's words: an edit being typed, edits on their way, edits
61 /// not saved, or the last outcome. "Saved" only once nothing is left to
62 /// send and nothing failed.
63 var saveStatus: String {
64 if dirty { return "Unsaved cell edit" }
65 if isSending { return sheetsMacString("Saving…") }
66 if hasFailedEdits { return sheetsMacString("Not saved") }
67 return notice
68 }
69
70 static func keepAlive() -> (@MainActor () -> Void) {
71 #if os(iOS)
72 final class Holder { var id = UIBackgroundTaskIdentifier.invalid }
73 let app = UIApplication.shared
74 let task = Holder()
75 task.id = app.beginBackgroundTask(withName: "Saving cell edits") {
76 MainActor.assumeIsolated {
77 app.endBackgroundTask(task.id)
78 task.id = .invalid
79 }
80 }
81 return {
82 if task.id != .invalid { app.endBackgroundTask(task.id); task.id = .invalid }
83 }
84 #else
85 ProcessInfo.processInfo.disableSuddenTermination()
86 return { ProcessInfo.processInfo.enableSuddenTermination() }
87 #endif
88 }
89
90 /// The cell as it should look: a pending local value wins over the server's.
91 func displayCell(_ point: Coordinate) -> Cell? {
92 guard let edit = pending[point] else { return cells[point] }
93 let raw = edit.write.raw
94 var cell = cells[point] ?? Cell(r: point.r, c: point.c, raw: "", display: "")
95 cell.raw = raw
96 cell.display = raw
97 cell.n = Double(raw.trimmingCharacters(in: .whitespaces)) != nil
98 return cell
99 }
100 /// The input a cell holds, including an edit that is still on its way.
101 func rawAt(_ point: Coordinate) -> String { pending[point]?.write.raw ?? cells[point]?.raw ?? "" }
102 func editState(_ point: Coordinate) -> PendingEdit.State? { pending[point]?.state }
103
104 func retryWrites(_ points: [Coordinate]? = nil) {
105 hurried = false
106 var next = pending
107 for (point, edit) in pending where edit.state == .failed && (points?.contains(point) ?? true) {
108 next[point]?.state = .queued
109 }
110 pending = next
111 error = ""
112 startSending()
113 }
114 /// Drops failed edits and shows the server's value again. An edit whose
115 /// answer was lost may have landed after all, so the cells are read back
116 /// from the server rather than trusted from before the edit. Edits still
117 /// being sent are not touched: they may land yet.
118 func revertWrites(_ points: [Coordinate]? = nil) {
119 pending = pending.filter { point, edit in
120 edit.state != .failed || !(points?.contains(point) ?? true)
121 }
122 if !hasFailedEdits { error = "" }
123 if !dirty { discard() }
124 Task { await refresh() }
125 }
126
127 /// A failed edit the server turns out to hold (its answer was lost, then
128 /// the live stream or a refetch brought the cell back) is saved after all.
129 func reconcileFailedEdits() {
130 // A cleared cell is absent from the server's cells, not an empty one.
131 let landed = pending.filter { point, edit in
132 edit.state == .failed && (cells[point]?.raw ?? "") == edit.write.raw
133 }
134 guard !landed.isEmpty else { return }
135 pending = pending.filter { landed[$0.key] == nil }
136 }
137
138 /// Waits until nothing is queued or in flight. Failed edits stay failed.
139 /// `hurry`: Close or Quit is waiting, so an ended session's edits are
140 /// marked as not saved now rather than after the renewal hold (about a
141 /// minute), and the window can ask about them straight away.
142 func settle(hurry: Bool = false) async {
143 if hurry {
144 hurried = true
145 sessionWait?.cancel()
146 }
147 while let sender { await sender.value }
148 }
149
150 func startSending() {
151 guard sender == nil, pending.values.contains(where: { $0.state == .queued }) else { return }
152 let release = keepAliveWhileSending()
153 sender = Task { [weak self] in
154 await self?.sendQueued()
155 release()
156 self?.sender = nil
157 // An edit queued while the last answer was being applied.
158 self?.startSending()
159 }
160 }
161
162 /// One send per document at a time. Everything queued when a send starts
163 /// goes in it; edits made meanwhile wait and go together in the next.
164 private func sendQueued() async {
165 var sessionWaits = 0
166 while !Task.isCancelled {
167 let batch = pending.values.filter { $0.state == .queued }.sorted { $0.generation < $1.generation }
168 guard !batch.isEmpty else { return }
169 var next = pending
170 for edit in batch { next[edit.write.coordinate]?.state = .sending }
171 pending = next
172 let source = grid
173 let writes = batch.map(\.write)
174 var offset = 0
175 do {
176 while offset < writes.count {
177 let chunk = try await wire.encode(writes, startingAt: offset)
178 let (bytes, status) = try await client.response(
179 source + "/cells/batch", method: "POST", body: chunk.data, maxBytes: 64 << 20)
180 // 401, or the 303 to sign-in (the Oficina ID transport also reports
181 // the guards' "Sign in first." 403 as 401): the session ended and is
182 // being renewed. That refuses nothing about the edit.
183 if status == 401 || status == 303 { throw NativeClientError.unauthorized }
184 guard (200..<300).contains(status) else {
185 throw NativeClientError.message(sheetsMacString("Not saved"))
186 }
187 let response = try await wire.decode(bytes)
188 guard grid == source else { return abandon(batch) }
189 await accept(response)
190 resolve(batch[offset..<(offset + chunk.count)], failed: false)
191 offset += chunk.count
192 }
193 sessionWaits = 0
194 error = ""
195 if !isSending { notice = "Saved" }
196 if showTable { await loadTable() }
197 } catch NativeClientError.unauthorized where sessionWaits < sessionRetryDelays.count && !hurried {
198 guard grid == source else { return abandon(batch) }
199 // Hold the queue while the session is renewed, then send again: the
200 // edits stay pending (Saving…), and edits made meanwhile join them.
201 requeue(batch[offset...])
202 let delay = sessionRetryDelays[sessionWaits]
203 sessionWaits += 1
204 let wait = Task { _ = try? await Task.sleep(for: delay) }
205 sessionWait = wait
206 await wait.value
207 sessionWait = nil
208 if hurried {
209 // Close or Quit cut the hold short: what is queued is not saved.
210 var next = pending
211 for (point, edit) in pending where edit.state == .queued { next[point]?.state = .failed }
212 pending = next
213 return
214 }
215 } catch {
216 guard grid == source else { return abandon(batch) }
217 // The cells say so themselves, with Retry and Revert; editing goes on.
218 resolve(batch[offset...], failed: true)
219 }
220 }
221 }
222
223 private func requeue(_ sent: ArraySlice<PendingEdit>) {
224 var next = pending
225 for edit in sent where next[edit.write.coordinate]?.generation == edit.generation {
226 next[edit.write.coordinate]?.state = .queued
227 }
228 pending = next
229 }
230
231 /// The sheet changed under a send: its edits were for the old sheet, and
232 /// must neither paint on the new one nor stay "sending" for ever.
233 private func abandon(_ batch: [PendingEdit]) {
234 var next = pending
235 for edit in batch where next[edit.write.coordinate]?.generation == edit.generation {
236 next[edit.write.coordinate] = nil
237 }
238 pending = next
239 }
240
241 /// Settles the edits a send carried, unless the person edited the cell again
242 /// while it was in flight: that newer edit is still queued and stays.
243 private func resolve(_ sent: ArraySlice<PendingEdit>, failed: Bool) {
244 var next = pending
245 for edit in sent where next[edit.write.coordinate]?.generation == edit.generation {
246 if failed { next[edit.write.coordinate]?.state = .failed }
247 else { next[edit.write.coordinate] = nil }
248 }
249 pending = next
250 refreshDraftIfClean()
251 }
252}
253
254extension CellWrite {
255 var coordinate: Coordinate { Coordinate(r: r, c: c) }
256}
257