| index a2bce5c..386e77a 100644 |
| --- a/native/apple/Sources/DocsKit/CRDTReplica.swift |
| +++ b/native/apple/Sources/DocsKit/CRDTReplica.swift |
| @@ -22,13 +22,12 @@ actor CRDTReplica { |
| } |
| /// A replica's state as bytes without encoding it: a base update and the |
| /// updates applied since, in order. Their concatenation is one input for |
| - /// the 255 envelope, which applies each update in turn. |
| + /// the 255 envelope, which applies each update in turn (see `fresh(state:)`). |
| struct State: Sendable { |
| private(set) var base = Data() |
| private(set) var tail: [Data] = [] |
| private(set) var tailBytes = 0 |
| init(base: Data = Data()) { self.base = base } |
| - var data: Data { tail.isEmpty ? base : tail.reduce(into: base) { $0.append($1) } } |
| mutating func append(_ update: Data) { tail.append(update); tailBytes += update.count } |
| /// Re-encode as one snapshot once the tail costs more to replay or |
| /// keep than a snapshot does to take. |
| @@ -59,6 +58,9 @@ actor CRDTReplica { |
| /// Updates applied to the authority since the replica was last persisted. |
| private var unpersisted: [Data] = [] |
| private var unpersistedBytes = 0 |
| + /// The position of `unpersisted[0]` among every update recorded in this |
| + /// epoch, so a capture marks exactly what it covered as stored. |
| + private var unpersistedStart = 0 |
| /// Moves when `unpersisted` stops being a record of every change (it |
| /// grew past `unpersistedLimit` while nothing could be stored, or the |
| /// replica reopened): only a whole state can be stored after that. |
| @@ -68,9 +70,12 @@ actor CRDTReplica { |
| private func recordUnpersisted(_ update: Data) { |
| unpersisted.append(update); unpersistedBytes += update.count |
| if unpersistedBytes > unpersistedLimit { |
| - unpersisted.removeAll(); unpersistedBytes = 0; unpersistedEpoch &+= 1; needsWhole = true |
| + resetUnpersisted(); needsWhole = true |
| } |
| } |
| + private func resetUnpersisted() { |
| + unpersisted.removeAll(); unpersistedBytes = 0; unpersistedStart = 0; unpersistedEpoch &+= 1 |
| + } |
| private let guid: String |
| enum Failure: Error { case unavailable, rejected, invalidProjection, generationLimit } |
| init(guid: String, unpersistedLimit: Int = 4 * 1024 * 1024) { self.guid = guid; self.unpersistedLimit = unpersistedLimit } |
| @@ -98,6 +103,8 @@ actor CRDTReplica { |
| /// The parking accepted as the server's own when this was taken. |
| let parked: String |
| let epoch: UInt64 |
| + /// The position after the last update captured. |
| + let end: Int |
| } |
| /// What changed since the replica was last persisted, so a writer can |
| /// append it instead of rewriting the whole state; and the whole state |
| @@ -109,43 +116,57 @@ actor CRDTReplica { |
| if !lastGood.tail.isEmpty { try compact(authority) } |
| whole = lastGood.base |
| } |
| - return PersistentChanges(updates: unpersisted, whole: whole, sequence: durableSequence, commandsApplied: commandsApplied, guid: guid, parked: acceptedParking, epoch: unpersistedEpoch) |
| + return PersistentChanges(updates: unpersisted, whole: whole, sequence: durableSequence, commandsApplied: commandsApplied, guid: guid, |
| + parked: acceptedParking, epoch: unpersistedEpoch, end: unpersistedStart + unpersisted.count) |
| } |
| - /// The first `count` updates of the last `persistentChanges` are stored. |
| - /// `changes` (or, with `count`, that many first updates) are stored. |
| + /// Everything `changes` captured is stored. By position, not count: a |
| + /// capture that overlaps one already marked (or arrives after a later |
| + /// one) marks nothing twice and never an update it did not cover. |
| func persisted(_ changes: PersistentChanges) { |
| guard changes.epoch == unpersistedEpoch else { return } |
| - let count = min(changes.updates.count, unpersisted.count) |
| + let count = min(max(0, changes.end - unpersistedStart), unpersisted.count) |
| unpersistedBytes -= unpersisted.prefix(count).reduce(0) { $0 + $1.count } |
| - unpersisted.removeFirst(count) |
| + unpersisted.removeFirst(count); unpersistedStart += count |
| if changes.whole != nil { needsWhole = false } |
| } |
| /// Everything applied so far is already stored elsewhere (on reopen). |
| - func persistedAll() { unpersisted.removeAll(); unpersistedBytes = 0; unpersistedEpoch &+= 1; needsWhole = false } |
| + func persistedAll() { resetUnpersisted(); needsWhole = false } |
| func currentSequence() -> Int64 { durableSequence } |
| func setSequence(_ sequence: Int64) { durableSequence = max(durableSequence, sequence) } |
| func close() { |
| opened = false; authority = nil; merger = nil; presented = nil |
| sources.removeAll(); sourceStates.removeAll(); sourceVersions.removeAll() |
| - lastGood = State(); unpersisted.removeAll(); unpersistedBytes = 0; unpersistedEpoch &+= 1 |
| + lastGood = State(); resetUnpersisted() |
| + } |
| + /// A sandbox from a state, imported as its base and then its tail in |
| + /// envelopes of their own, so a base near the bridge's 8 MiB limit still |
| + /// imports with a tail behind it. |
| + private func fresh(state: State) throws -> (UInt64, Sandbox) { |
| + try fresh(update: state.base, then: state.tail) |
| } |
| - private func fresh(update: Data) throws -> (UInt64, Sandbox) { |
| + private func fresh(update: Data, then tail: [Data] = []) throws -> (UInt64, Sandbox) { |
| let sandbox = try Sandbox() |
| var client = UInt64(UInt32.random(in: 1...UInt32.max)) |
| while reserved.contains(client) { client = UInt64(UInt32.random(in: 1...UInt32.max)) } |
| reserved.insert(client) |
| _ = try sandbox.invoke(["op": .string("open"), "guid": .string(guid), "client": .number(Double(client))]) |
| if !update.isEmpty { _ = try sandbox.invoke(Data([255]) + update) } |
| + var chunk = Data([255]) |
| + for part in tail { |
| + if chunk.count > 1, chunk.count + part.count > 4 * 1024 * 1024 { _ = try sandbox.invoke(chunk); chunk = Data([255]) } |
| + chunk.append(part) |
| + } |
| + if chunk.count > 1 { _ = try sandbox.invoke(chunk) } |
| let used = try JSONDecoder().decode([UInt64].self, from: sandbox.invoke(["op": .string("clients")])) |
| reserved.formUnion(used) |
| // Imported state may already contain the proposed ID. Never write it. |
| - if used.contains(client) { return try fresh(update: update) } |
| + if used.contains(client) { return try fresh(update: update, then: tail) } |
| return (client, sandbox) |
| } |
| func open(update: Data) throws { |
| sources.removeAll(); sourceStates.removeAll(); sourceVersions.removeAll() |
| commandsApplied = 0; durableSequence = 0; presented = nil; acceptedParking = "" |
| - unpersisted.removeAll(); unpersistedBytes = 0; unpersistedEpoch &+= 1; needsWhole = false |
| + resetUnpersisted(); needsWhole = false |
| authority = try fresh(update: update).1 |
| opened = true |
| lastGood = State(base: try authority!.invoke(["op": .string("snapshot")])) |
| @@ -153,7 +174,7 @@ actor CRDTReplica { |
| } |
| private func currentAuthority() throws -> Sandbox { |
| guard opened else { throw Failure.unavailable } |
| - if authority == nil { presented = nil; authority = try fresh(update: lastGood.data).1 } |
| + if authority == nil { presented = nil; authority = try fresh(state: lastGood).1 } |
| guard let authority else { throw Failure.unavailable } |
| return authority |
| } |
| @@ -269,7 +290,7 @@ actor CRDTReplica { |
| let start = try endpoint(selection.location), end = try endpoint(NSMaxRange(selection)) |
| resolved = NSRange(location: min(start, end), length: abs(end - start)) |
| } catch { |
| - if let state = sourceStates[generation] { sources[generation] = try? fresh(update: state.data).1 } |
| + if let state = sourceStates[generation] { sources[generation] = try? fresh(state: state).1 } |
| else { sources.removeValue(forKey: generation) } |
| recover() |
| throw error |
| @@ -277,7 +298,7 @@ actor CRDTReplica { |
| } |
| if reuse { return (generation, try authorityProjection(authority), resolved) } |
| if lastGood.tail.count > 8 { try compact(authority) } |
| - let (_, source) = try fresh(update: lastGood.data) |
| + let (_, source) = try fresh(state: lastGood) |
| let generation = nextGeneration; nextGeneration += 1 |
| sources[generation] = source; sourceStates[generation] = lastGood; sourceVersions[generation] = version |
| return (generation, try authorityProjection(authority), resolved) |
| @@ -291,7 +312,7 @@ actor CRDTReplica { |
| // No invalid interpreter is reused. A new authority ID cannot reuse |
| // clocks from a partially executed command. UI reports undo loss. |
| presented = nil |
| - authority = try? fresh(update: lastGood.data).1 |
| + authority = try? fresh(state: lastGood).1 |
| } |
| func mergeUpdates(_ updates: [Data]) throws -> Data { |
| guard let first = updates.first else { throw Failure.rejected } |
| @@ -319,13 +340,15 @@ actor CRDTReplica { |
| let generation: UInt64? = if case .number(let value) = command["generation"] { UInt64(exactly: value) } else { nil } |
| let op: String? = if case .string(let value) = command["op"] { value } else { nil } |
| // Projections go through `projection()` only: it owns the delta base. |
| - if op == "project" || op == "project_delta" || op == "open" { throw Failure.rejected } |
| + // So do imports: an `apply` here would bypass lastGood, the sources' |
| + // states and the record of unstored changes. |
| + if op == "project" || op == "project_delta" || op == "open" || op == "apply" { throw Failure.rejected } |
| let isHistory = op == "undo" || op == "redo" |
| let writer: Sandbox |
| if isHistory || generation == nil { writer = authority } |
| else { |
| let generation = generation! |
| - if sources[generation] == nil, let state = sourceStates[generation] { sources[generation] = try fresh(update: state.data).1 } |
| + if sources[generation] == nil, let state = sourceStates[generation] { sources[generation] = try fresh(state: state).1 } |
| guard let source = sources[generation] else { throw Failure.unavailable } |
| writer = source |
| } |
| @@ -350,7 +373,7 @@ actor CRDTReplica { |
| compactIfWanted(authority) |
| return update |
| } catch { |
| - if writer !== authority, let generation { sources[generation] = try? fresh(update: (sourceStates[generation] ?? lastGood).data).1 } |
| + if writer !== authority, let generation { sources[generation] = try? fresh(state: sourceStates[generation] ?? lastGood).1 } |
| if authorityTouched { recover() } |
| throw error |
| } |