| 1 | import DocsCRDT |
| 2 | import Foundation |
| 3 | |
| 4 | /// Handles never leave the actor. Every untrusted decode executes in bounded WASM. |
| 5 | actor CRDTReplica { |
| 6 | private final class Sandbox { |
| 7 | let host: UnsafeMutableRawPointer |
| 8 | init() throws { guard let host = docs_host_new() else { throw Failure.unavailable }; self.host = host } |
| 9 | deinit { docs_host_free(host) } |
| 10 | func invoke(_ data: Data) throws -> Data { |
| 11 | let maximum = 8 * 1024 * 1024 + 1 |
| 12 | guard !data.isEmpty, data.count <= maximum else { throw Failure.unavailable } |
| 13 | var output = Data(count: maximum) |
| 14 | let count = output.withUnsafeMutableBytes { target in data.withUnsafeBytes { source in |
| 15 | docs_host_call(host, source.bindMemory(to: UInt8.self).baseAddress!, data.count, |
| 16 | target.bindMemory(to: UInt8.self).baseAddress!, maximum) |
| 17 | } } |
| 18 | guard count >= 0, count <= maximum else { throw Failure.rejected } |
| 19 | output.count = Int(count); return output |
| 20 | } |
| 21 | func invoke(_ command: [String: JSONValue]) throws -> Data { try invoke(JSONEncoder().encode(command)) } |
| 22 | } |
| 23 | /// A replica's state as bytes without encoding it: a base update and the |
| 24 | /// updates applied since, in order. Their concatenation is one input for |
| 25 | /// the 255 envelope, which applies each update in turn (see `fresh(state:)`). |
| 26 | struct State: Sendable { |
| 27 | private(set) var base = Data() |
| 28 | private(set) var tail: [Data] = [] |
| 29 | private(set) var tailBytes = 0 |
| 30 | init(base: Data = Data()) { self.base = base } |
| 31 | mutating func append(_ update: Data) { tail.append(update); tailBytes += update.count } |
| 32 | /// Re-encode as one snapshot once the tail costs more to replay or |
| 33 | /// keep than a snapshot does to take. |
| 34 | var wantsCompaction: Bool { tail.count > 128 || tailBytes > 256 * 1024 || (tailBytes > 16 * 1024 && tailBytes > base.count / 2) } |
| 35 | } |
| 36 | private var authority: Sandbox? |
| 37 | private var merger: Sandbox? |
| 38 | private var opened = false |
| 39 | /// The authority's last projection, which is also the base its deltas |
| 40 | /// are reported against. nil whenever the authority is replaced. |
| 41 | private var presented: CRDTProjection? |
| 42 | /// Moves every time a projection becomes `presented`, whoever asked for |
| 43 | /// it (spec 2026-11-22 §7 Design 1). A text view that has drawn revision |
| 44 | /// r can ask what changed since r (`presentation(…, since:)`). Clearing |
| 45 | /// `presented` moves nothing: the next projection is then a whole one, |
| 46 | /// which the log records as unknown. |
| 47 | private(set) var presentedRevision: UInt64 = 0 |
| 48 | /// For each recent revision, the top-level block ids its delta inserted |
| 49 | /// or removed (an edit in place is a remove and an insert of the same |
| 50 | /// id), or nil when it was a whole projection: then anything may have |
| 51 | /// changed. The last `dirtyLogLimit` revisions, oldest first. |
| 52 | private var dirtyLog: [(revision: UInt64, ids: Set<String>?)] = [] |
| 53 | let dirtyLogLimit: Int |
| 54 | private func logPresented(_ ids: Set<String>?) { |
| 55 | presentedRevision &+= 1 |
| 56 | dirtyLog.append((presentedRevision, ids)) |
| 57 | // Drop the oldest half at once, so trimming is amortised O(1). |
| 58 | if dirtyLog.count > 2 * dirtyLogLimit { dirtyLog.removeFirst(dirtyLog.count - dirtyLogLimit) } |
| 59 | } |
| 60 | /// The blocks that changed over exactly the revisions (since, through]: |
| 61 | /// nil when that span reaches back past the log, or holds a whole |
| 62 | /// projection (open, a fresh source, recovery, a reset, a delta that |
| 63 | /// would not apply). Then only a full comparison can say. |
| 64 | func dirty(since: UInt64, through: UInt64) -> Set<String>? { |
| 65 | guard since < through else { return [] } |
| 66 | let kept = dirtyLog.suffix(dirtyLogLimit) |
| 67 | guard let oldest = kept.first?.revision, oldest <= since + 1 else { return nil } |
| 68 | var ids = Set<String>() |
| 69 | for entry in kept where entry.revision > since && entry.revision <= through { |
| 70 | guard let touched = entry.ids else { return nil } |
| 71 | ids.formUnion(touched) |
| 72 | } |
| 73 | return ids |
| 74 | } |
| 75 | private var sources: [UInt64: Sandbox] = [:] |
| 76 | /// Each source's state, to recreate it after it is retired or traps. |
| 77 | private var sourceStates: [UInt64: State] = [:] |
| 78 | /// The authority version each source is known to equal: it was made |
| 79 | /// from the authority's state then, and every change since went to both. |
| 80 | private var sourceVersions: [UInt64: UInt64] = [:] |
| 81 | private var nextGeneration: UInt64 = 1 |
| 82 | // IDs remain reserved for this session even when a source is retired or traps. |
| 83 | private var reserved: Set<UInt64> = [] |
| 84 | private var lastGood = State() |
| 85 | /// Moves on every change to the authority's state. |
| 86 | private var version: UInt64 = 0 |
| 87 | private var commandsApplied = 0 |
| 88 | private var durableSequence: Int64 = 0 |
| 89 | /// Parking this replica has accepted as the server's own (#147). |
| 90 | private var acceptedParking = "" |
| 91 | /// Settling (#147) rebuilt the state or changed what is accepted: the |
| 92 | /// stored base must be replaced, which appending a segment cannot do. |
| 93 | /// Counts settlements, so a capture only clears the one it stored. |
| 94 | private var settlements = 0, storedSettlements = 0 |
| 95 | /// Updates applied to the authority since the replica was last persisted. |
| 96 | private var unpersisted: [Data] = [] |
| 97 | private var unpersistedBytes = 0 |
| 98 | /// The position of `unpersisted[0]` among every update recorded in this |
| 99 | /// epoch, so a capture marks exactly what it covered as stored. |
| 100 | private var unpersistedStart = 0 |
| 101 | /// Moves when `unpersisted` stops being a record of every change (it |
| 102 | /// grew past `unpersistedLimit` while nothing could be stored, or the |
| 103 | /// replica reopened): only a whole state can be stored after that. |
| 104 | private var unpersistedEpoch: UInt64 = 0 |
| 105 | private var needsWhole = false |
| 106 | let unpersistedLimit: Int |
| 107 | private func recordUnpersisted(_ update: Data) { |
| 108 | unpersisted.append(update); unpersistedBytes += update.count |
| 109 | if unpersistedBytes > unpersistedLimit { |
| 110 | resetUnpersisted(); needsWhole = true |
| 111 | } |
| 112 | } |
| 113 | private func resetUnpersisted() { |
| 114 | unpersisted.removeAll(); unpersistedBytes = 0; unpersistedStart = 0; unpersistedEpoch &+= 1 |
| 115 | } |
| 116 | private let guid: String |
| 117 | enum Failure: Error { case unavailable, rejected, invalidProjection, generationLimit } |
| 118 | init(guid: String, unpersistedLimit: Int = 4 * 1024 * 1024, dirtyLogLimit: Int = 512) { |
| 119 | self.guid = guid; self.unpersistedLimit = unpersistedLimit; self.dirtyLogLimit = max(1, dirtyLogLimit) |
| 120 | } |
| 121 | struct PersistentState: Sendable { |
| 122 | let state: Data |
| 123 | let sequence: Int64 |
| 124 | let commandsApplied: Int |
| 125 | let guid: String |
| 126 | let parked: String |
| 127 | } |
| 128 | /// The whole state as one snapshot. |
| 129 | func persistentState() throws -> PersistentState { |
| 130 | let authority = try currentAuthority() |
| 131 | if !lastGood.tail.isEmpty { try compact(authority) } |
| 132 | return PersistentState(state: lastGood.base, sequence: durableSequence, commandsApplied: commandsApplied, guid: guid, parked: acceptedParking) |
| 133 | } |
| 134 | struct PersistentChanges: Sendable { |
| 135 | /// Every update applied since the last `persisted`, in order. |
| 136 | let updates: [Data] |
| 137 | /// The whole state, when asked for: taken at the same moment. |
| 138 | let whole: Data? |
| 139 | let sequence: Int64 |
| 140 | let commandsApplied: Int |
| 141 | let guid: String |
| 142 | /// The parking accepted as the server's own when this was taken. |
| 143 | let parked: String |
| 144 | /// Set when the replica settled since last stored: the settlement |
| 145 | /// count `whole` reflects, and the base must be replaced with it. |
| 146 | let replace: Int? |
| 147 | let epoch: UInt64 |
| 148 | /// The position after the last update captured. |
| 149 | let end: Int |
| 150 | } |
| 151 | /// What changed since the replica was last persisted, so a writer can |
| 152 | /// append it instead of rewriting the whole state; and the whole state |
| 153 | /// too when those changes exceed `wholeAbove` bytes (-1: always). |
| 154 | /// And the whole state when the replica has settled since it was last |
| 155 | /// stored (#147): `replace` then says the stored base must be replaced. |
| 156 | func persistentChanges(wholeAbove limit: Int) throws -> PersistentChanges { |
| 157 | let authority = try currentAuthority() |
| 158 | var whole: Data? |
| 159 | let replace = settlements != storedSettlements |
| 160 | if limit < 0 || unpersistedBytes > limit || needsWhole || replace { |
| 161 | if !lastGood.tail.isEmpty { try compact(authority) } |
| 162 | whole = lastGood.base |
| 163 | } |
| 164 | return PersistentChanges(updates: unpersisted, whole: whole, sequence: durableSequence, commandsApplied: commandsApplied, guid: guid, |
| 165 | parked: acceptedParking, replace: replace ? settlements : nil, epoch: unpersistedEpoch, end: unpersistedStart + unpersisted.count) |
| 166 | } |
| 167 | /// Everything `changes` captured is stored. By position, not count: a |
| 168 | /// capture that overlaps one already marked (or arrives after a later |
| 169 | /// one) marks nothing twice and never an update it did not cover. |
| 170 | func persisted(_ changes: PersistentChanges) { |
| 171 | if let settled = changes.replace { storedSettlements = max(storedSettlements, settled) } |
| 172 | guard changes.epoch == unpersistedEpoch else { return } |
| 173 | let count = min(max(0, changes.end - unpersistedStart), unpersisted.count) |
| 174 | unpersistedBytes -= unpersisted.prefix(count).reduce(0) { $0 + $1.count } |
| 175 | unpersisted.removeFirst(count); unpersistedStart += count |
| 176 | if changes.whole != nil { needsWhole = false } |
| 177 | } |
| 178 | /// Everything applied so far is already stored elsewhere (on reopen). |
| 179 | func persistedAll() { resetUnpersisted(); needsWhole = false } |
| 180 | func currentSequence() -> Int64 { durableSequence } |
| 181 | func setSequence(_ sequence: Int64) { durableSequence = max(durableSequence, sequence) } |
| 182 | func close() { |
| 183 | opened = false; authority = nil; merger = nil; presented = nil |
| 184 | sources.removeAll(); sourceStates.removeAll(); sourceVersions.removeAll() |
| 185 | lastGood = State(); resetUnpersisted() |
| 186 | } |
| 187 | /// A sandbox from a state, imported as its base and then its tail in |
| 188 | /// envelopes of their own, so a base near the bridge's 8 MiB limit still |
| 189 | /// imports with a tail behind it. |
| 190 | private func fresh(state: State) throws -> (UInt64, Sandbox) { |
| 191 | try fresh(update: state.base, then: state.tail) |
| 192 | } |
| 193 | private func fresh(update: Data, then tail: [Data] = []) throws -> (UInt64, Sandbox) { |
| 194 | let sandbox = try Sandbox() |
| 195 | var client = UInt64(UInt32.random(in: 1...UInt32.max)) |
| 196 | while reserved.contains(client) { client = UInt64(UInt32.random(in: 1...UInt32.max)) } |
| 197 | reserved.insert(client) |
| 198 | _ = try sandbox.invoke(["op": .string("open"), "guid": .string(guid), "client": .number(Double(client))]) |
| 199 | if !update.isEmpty { _ = try sandbox.invoke(Data([255]) + update) } |
| 200 | var chunk = Data([255]) |
| 201 | for part in tail { |
| 202 | if chunk.count > 1, chunk.count + part.count > 4 * 1024 * 1024 { _ = try sandbox.invoke(chunk); chunk = Data([255]) } |
| 203 | chunk.append(part) |
| 204 | } |
| 205 | if chunk.count > 1 { _ = try sandbox.invoke(chunk) } |
| 206 | let used = try JSONDecoder().decode([UInt64].self, from: sandbox.invoke(["op": .string("clients")])) |
| 207 | reserved.formUnion(used) |
| 208 | // Imported state may already contain the proposed ID. Never write it. |
| 209 | if used.contains(client) { return try fresh(update: update, then: tail) } |
| 210 | return (client, sandbox) |
| 211 | } |
| 212 | func open(update: Data) throws { |
| 213 | sources.removeAll(); sourceStates.removeAll(); sourceVersions.removeAll() |
| 214 | commandsApplied = 0; durableSequence = 0; presented = nil; acceptedParking = "" |
| 215 | resetUnpersisted(); needsWhole = false |
| 216 | authority = try fresh(update: update).1 |
| 217 | opened = true |
| 218 | lastGood = State(base: try authority!.invoke(["op": .string("snapshot")])) |
| 219 | version &+= 1 |
| 220 | } |
| 221 | private func currentAuthority() throws -> Sandbox { |
| 222 | guard opened else { throw Failure.unavailable } |
| 223 | if authority == nil { presented = nil; authority = try fresh(state: lastGood).1 } |
| 224 | guard let authority else { throw Failure.unavailable } |
| 225 | return authority |
| 226 | } |
| 227 | /// Snapshot the authority so its state is one update again. |
| 228 | private func compact(_ authority: Sandbox) throws { |
| 229 | do { lastGood = State(base: try authority.invoke(["op": .string("snapshot")])) } |
| 230 | catch { recover(); throw error } |
| 231 | } |
| 232 | private func compactIfWanted(_ authority: Sandbox) { |
| 233 | if lastGood.wantsCompaction { try? compact(authority) } |
| 234 | } |
| 235 | /// The authority's projection: the changed blocks patched into the last |
| 236 | /// one, or the whole document when there is no last one. |
| 237 | private func authorityProjection(_ authority: Sandbox) throws -> CRDTProjection { |
| 238 | do { |
| 239 | if let presented { |
| 240 | let delta = try JSONDecoder().decode(CRDTProjectionDelta.self, from: authority.invoke(["op": .string("project_delta")])) |
| 241 | if let next = delta.applied(to: presented) { |
| 242 | self.presented = next; logPresented(delta.touched(in: presented)) |
| 243 | return next |
| 244 | } |
| 245 | } |
| 246 | // The whole document: an unknown entry, whatever the reason. |
| 247 | let projected = try JSONDecoder().decode(CRDTProjection.self, from: authority.invoke(["op": .string("project")])) |
| 248 | presented = projected; logPresented(nil) |
| 249 | return projected |
| 250 | } catch { recover(); throw error } |
| 251 | } |
| 252 | /// False when the replica parks structs or deletions it cannot integrate |
| 253 | /// (their dependency never arrived): it shows less than it holds (#145). |
| 254 | func isWhole() throws -> Bool { |
| 255 | try JSONDecoder().decode(Bool.self, from: currentAuthority().invoke(["op": .string("whole")])) |
| 256 | } |
| 257 | /// What the replica parks, described canonically ("" when whole). |
| 258 | func parked() throws -> String { |
| 259 | try JSONDecoder().decode(String.self, from: currentAuthority().invoke(["op": .string("parked")])) |
| 260 | } |
| 261 | func acceptParking(_ parked: String) { acceptedParking = parked } |
| 262 | /// Accept whatever is parked now; call only once caught up from the start. |
| 263 | func acceptCurrentParking() throws { acceptedParking = try parked() } |
| 264 | /// True when the replica parks something it has not accepted: damage, or |
| 265 | /// something the server has that this replica lacks. |
| 266 | func hasUnacceptedParking() throws -> Bool { |
| 267 | !Self.parking(try parked(), within: acceptedParking) |
| 268 | } |
| 269 | /// Whether every parked struct and deletion `parked` describes is also in |
| 270 | /// `accepted` (the engine's `parked` format: "client a-b c-d;" per client, |
| 271 | /// structs, then "|" and deletions). Containment, not equality: when part |
| 272 | /// of an accepted set later integrates, the rest stays accepted (#147). |
| 273 | nonisolated static func parking(_ parked: String, within accepted: String) -> Bool { |
| 274 | func ranges(_ description: String) -> [String: [(UInt64, UInt64)]] { |
| 275 | var out: [String: [(UInt64, UInt64)]] = [:] |
| 276 | let halves = description.split(separator: "|", omittingEmptySubsequences: false) |
| 277 | for (index, half) in halves.enumerated() { |
| 278 | for client in half.split(separator: ";") { |
| 279 | let words = client.split(separator: " ") |
| 280 | guard let id = words.first else { continue } |
| 281 | let key = (index == 0 ? "s" : "d") + id |
| 282 | for word in words.dropFirst() { |
| 283 | let bounds = word.split(separator: "-").compactMap { UInt64($0) } |
| 284 | if bounds.count == 2 { out[key, default: []].append((bounds[0], bounds[1])) } |
| 285 | } |
| 286 | } |
| 287 | } |
| 288 | return out |
| 289 | } |
| 290 | let have = ranges(accepted) |
| 291 | for (key, wanted) in ranges(parked) { |
| 292 | let covering = (have[key] ?? []).sorted { $0.0 < $1.0 } |
| 293 | for (start, end) in wanted { |
| 294 | var reached = start |
| 295 | for (from, to) in covering where from <= reached && to > reached { reached = to } |
| 296 | if reached < end { return false } |
| 297 | } |
| 298 | } |
| 299 | return true |
| 300 | } |
| 301 | /// Once caught up from the start: rebuild the authority from its own |
| 302 | /// snapshot and accept what still parks. Applying the server's state does |
| 303 | /// not unpark a damaged duplicate (yrs checks a parked struct's |
| 304 | /// dependencies before noticing it is integrated); a snapshot merges |
| 305 | /// parked structs with integrated ones and drops it. What parks after |
| 306 | /// that is the server's own. Undo history goes, as in `recover`; every |
| 307 | /// source is out of date, and the state becomes that one snapshot. |
| 308 | func settleAfterCatchingUpFromStart() throws { |
| 309 | let authority = try currentAuthority() |
| 310 | if !(try parked()).isEmpty { |
| 311 | let snapshot = try authority.invoke(["op": .string("snapshot")]) |
| 312 | let rebuilt = try fresh(update: snapshot).1 |
| 313 | self.authority = rebuilt; presented = nil |
| 314 | lastGood = State(base: try rebuilt.invoke(["op": .string("snapshot")])) |
| 315 | version &+= 1 |
| 316 | } |
| 317 | acceptedParking = try parked() |
| 318 | settlements += 1 |
| 319 | } |
| 320 | /// The replica settled without a rebuild (a catch-up integrated what it |
| 321 | /// parked): store it as the base on the next persist. |
| 322 | func markSettled() { settlements += 1 } |
| 323 | #if DEBUG |
| 324 | /// Tests only: change what the replica believes it last presented, so |
| 325 | /// the engine's next delta no longer applies to it. |
| 326 | func replacePresentedForTesting(_ transform: (CRDTProjection) -> CRDTProjection) { presented = presented.map(transform) } |
| 327 | #endif |
| 328 | func projection() throws -> CRDTProjection { |
| 329 | try authorityProjection(try currentAuthority()) |
| 330 | } |
| 331 | /// A projection to publish, with what changed since the text view's |
| 332 | /// revision (spec §7 Design 2): `dirty` covers exactly |
| 333 | /// (`since`, `revision`], or is nil when only a full comparison can say. |
| 334 | /// Returned together, so the main actor never asks the replica anything |
| 335 | /// while it applies one. |
| 336 | struct Presentation: Sendable { |
| 337 | let generation: UInt64 |
| 338 | let projection: CRDTProjection |
| 339 | let selection: NSRange |
| 340 | let revision: UInt64 |
| 341 | let dirty: Set<String>? |
| 342 | } |
| 343 | /// Bound retained WASM memories. The caller defers publication until render |
| 344 | /// acknowledgement and queued-callback drainage allow old sources to retire. |
| 345 | func presentation(source generation: UInt64, selection: NSRange, allowReuse: Bool = false, since: UInt64 = 0) throws -> Presentation? { |
| 346 | let authority = try currentAuthority() |
| 347 | // Only the caller knows that this source has actually been rendered and |
| 348 | // has no pending candidate. An identical state is additionally required: |
| 349 | // peers, undo, and divergent queued edits must still publish a fresh source. |
| 350 | // Never reconstruct or transfer a client ID to enable this fast path. |
| 351 | let reuse = allowReuse && sources[generation] != nil && sourceVersions[generation] == version |
| 352 | guard reuse || sources.count < 3 else { return nil } |
| 353 | var resolved = selection |
| 354 | if let displayed = sources[generation] { |
| 355 | func endpoint(_ position: Int) throws -> Int { |
| 356 | let encoded = try displayed.invoke(["op": .string("anchor"), "at": .number(Double(position))]) |
| 357 | let anchor = try JSONDecoder().decode(JSONValue.self, from: encoded) |
| 358 | return try JSONDecoder().decode(Int.self, from: authority.invoke(["op": .string("resolve"), "anchor": anchor])) |
| 359 | } |
| 360 | do { |
| 361 | let start = try endpoint(selection.location), end = try endpoint(NSMaxRange(selection)) |
| 362 | resolved = NSRange(location: min(start, end), length: abs(end - start)) |
| 363 | } catch { |
| 364 | if let state = sourceStates[generation] { sources[generation] = try? fresh(state: state).1 } |
| 365 | else { sources.removeValue(forKey: generation) } |
| 366 | recover() |
| 367 | throw error |
| 368 | } |
| 369 | } |
| 370 | func presented(_ generation: UInt64) throws -> Presentation { |
| 371 | let projection = try authorityProjection(authority) |
| 372 | return Presentation(generation: generation, projection: projection, selection: resolved, |
| 373 | revision: presentedRevision, dirty: dirty(since: since, through: presentedRevision)) |
| 374 | } |
| 375 | if reuse { return try presented(generation) } |
| 376 | if lastGood.tail.count > 8 { try compact(authority) } |
| 377 | let (_, source) = try fresh(state: lastGood) |
| 378 | let generation = nextGeneration; nextGeneration += 1 |
| 379 | sources[generation] = source; sourceStates[generation] = lastGood; sourceVersions[generation] = version |
| 380 | return try presented(generation) |
| 381 | } |
| 382 | func retainGenerations(_ ids: Set<UInt64>) { |
| 383 | sources = sources.filter { ids.contains($0.key) } |
| 384 | sourceStates = sourceStates.filter { ids.contains($0.key) } |
| 385 | sourceVersions = sourceVersions.filter { ids.contains($0.key) } |
| 386 | } |
| 387 | private func recover() { |
| 388 | // No invalid interpreter is reused. A new authority ID cannot reuse |
| 389 | // clocks from a partially executed command. UI reports undo loss. |
| 390 | presented = nil |
| 391 | authority = try? fresh(state: lastGood).1 |
| 392 | } |
| 393 | func mergeUpdates(_ updates: [Data]) throws -> Data { |
| 394 | guard let first = updates.first else { throw Failure.rejected } |
| 395 | if updates.count == 1 { return first } |
| 396 | guard opened else { throw Failure.unavailable } |
| 397 | if merger == nil { merger = try Sandbox() } |
| 398 | var envelope = Data([253]) |
| 399 | for update in updates { envelope.append(update) } |
| 400 | do { return try merger!.invoke(envelope) } |
| 401 | catch { merger = nil; throw error } |
| 402 | } |
| 403 | func apply(_ update: Data) throws { |
| 404 | let authority = try currentAuthority() |
| 405 | do { _ = try authority.invoke(Data([255]) + update) } |
| 406 | catch { recover(); throw error } |
| 407 | lastGood.append(update); version &+= 1; recordUnpersisted(update) |
| 408 | compactIfWanted(authority) |
| 409 | } |
| 410 | /// Reads that change nothing; any other command is an edit. |
| 411 | private static let reads: Set<String> = ["snapshot", "clients", "anchor", "resolve"] |
| 412 | /// Runs one command and returns the update it made: only what its own |
| 413 | /// transactions changed. No projection and no snapshot are taken. |
| 414 | func command(_ command: [String: JSONValue]) throws -> Data { |
| 415 | let authority = try currentAuthority() |
| 416 | let generation: UInt64? = if case .number(let value) = command["generation"] { UInt64(exactly: value) } else { nil } |
| 417 | let op: String? = if case .string(let value) = command["op"] { value } else { nil } |
| 418 | // Projections go through `projection()` only: it owns the delta base. |
| 419 | // So do imports: an `apply` here would bypass lastGood, the sources' |
| 420 | // states and the record of unstored changes. |
| 421 | if op == "project" || op == "project_delta" || op == "open" || op == "apply" { throw Failure.rejected } |
| 422 | let isHistory = op == "undo" || op == "redo" |
| 423 | let writer: Sandbox |
| 424 | if isHistory || generation == nil { writer = authority } |
| 425 | else { |
| 426 | let generation = generation! |
| 427 | if sources[generation] == nil, let state = sourceStates[generation] { sources[generation] = try fresh(state: state).1 } |
| 428 | guard let source = sources[generation] else { throw Failure.unavailable } |
| 429 | writer = source |
| 430 | } |
| 431 | if let op, Self.reads.contains(op) { return try writer.invoke(command) } |
| 432 | var authorityTouched = writer === authority |
| 433 | do { |
| 434 | let update = try writer.invoke(command) |
| 435 | if writer !== authority { authorityTouched = true; _ = try authority.invoke(Data([254]) + update) } |
| 436 | let wasInSync = generation.map { sourceVersions[$0] == version } ?? false |
| 437 | lastGood.append(update); version &+= 1; recordUnpersisted(update) |
| 438 | if writer !== authority, let generation { |
| 439 | if wasInSync { sourceStates[generation] = lastGood; sourceVersions[generation] = version } |
| 440 | else { |
| 441 | sourceVersions.removeValue(forKey: generation) |
| 442 | sourceStates[generation]?.append(update) |
| 443 | if sourceStates[generation]?.wantsCompaction == true, let state = try? writer.invoke(["op": .string("snapshot")]) { |
| 444 | sourceStates[generation] = State(base: state) |
| 445 | } |
| 446 | } |
| 447 | } |
| 448 | commandsApplied += 1 |
| 449 | compactIfWanted(authority) |
| 450 | return update |
| 451 | } catch { |
| 452 | if writer !== authority, let generation { sources[generation] = try? fresh(state: sourceStates[generation] ?? lastGood).1 } |
| 453 | if authorityTouched { recover() } |
| 454 | throw error |
| 455 | } |
| 456 | } |
| 457 | } |
| 458 | |