| 1 | import Foundation |
| 2 | import RastrilloNative |
| 3 | |
| 4 | struct PersistedReplica: Codable, Sendable { |
| 5 | let format: Int |
| 6 | let sequence: Int64 |
| 7 | let guid: String |
| 8 | let savedAt: Date |
| 9 | let state: Data |
| 10 | /// What this state was known to park once caught up from the start (the |
| 11 | /// engine's `parked` description): the server's own parked updates, not |
| 12 | /// damage. Absent in records written before #147, and when nothing was. |
| 13 | var parked: String? = nil |
| 14 | /// The index of the first replica segment not folded into `state`; |
| 15 | /// segments must follow it without a gap (absent: 0). |
| 16 | var segmentsFrom: Int64? = nil |
| 17 | } |
| 18 | |
| 19 | /// One document's durability boundary. The writer and editor share this |
| 20 | /// watermark, but only a successful outbox write may advance it. |
| 21 | @MainActor final class DocsPersistence { |
| 22 | let store: BlobStore |
| 23 | let outbox: Outbox |
| 24 | let key: String |
| 25 | let replica: CRDTReplica |
| 26 | private(set) var commandsDurable = 0 |
| 27 | /// Outbox entries whose bytes this replica holds: replayed at reopen, |
| 28 | /// enqueued from it, or compacted from only such entries. Another window |
| 29 | /// of the same document writes entries this replica has not seen. |
| 30 | private(set) var held: Set<UUID> = [] |
| 31 | private var active = true |
| 32 | /// The stored replica parks something it has not accepted: possibly damage |
| 33 | /// from before the #145 fix, which its stored sequence would keep the server |
| 34 | /// from ever resending. DocsModel settles it (catching up, from the start if |
| 35 | /// need be) and adds no first paragraph to it meanwhile. |
| 36 | private(set) var unsettled = false |
| 37 | /// Whether this document has a stored base to append to, and the |
| 38 | /// sequence the stored replica has reached. |
| 39 | private var hasBase = false |
| 40 | private var storedSequence: Int64 = 0 |
| 41 | /// Changes larger than this are stored as a whole state instead. |
| 42 | static let appendLimit = 1024 * 1024 |
| 43 | let cache: DocsReplicaCache |
| 44 | private let generation: Int |
| 45 | var lane: String { "doc:" + key } |
| 46 | var path: String { "cache/docs/" + key + "/replica" } |
| 47 | init(store: BlobStore, outbox: Outbox, key: String, replica: CRDTReplica, cache: DocsReplicaCache? = nil) { |
| 48 | self.store = store; self.outbox = outbox; self.key = key; self.replica = replica |
| 49 | self.cache = cache ?? DocsReplicaCache(store: store) |
| 50 | generation = self.cache.generation(key) |
| 51 | } |
| 52 | func reopen(fallback: Data, sequence: Int64) async throws { |
| 53 | try await outbox.load() |
| 54 | let entries = await outbox.entries(lane: lane) |
| 55 | let saved = try cache.load(key) |
| 56 | if let saved, saved.replica.format != 1 { throw BlobStoreError.unavailable } |
| 57 | try await replica.open(update: saved?.replica.state ?? fallback) |
| 58 | for segment in saved?.segments ?? [] { try await replica.apply(segment.update) } |
| 59 | await replica.setSequence(saved?.sequence ?? sequence) |
| 60 | if let saved { |
| 61 | await replica.acceptParking(saved.replica.parked ?? "") |
| 62 | unsettled = try await replica.hasUnacceptedParking() |
| 63 | } else { |
| 64 | // The server's whole state: whatever it parks is the server's own. |
| 65 | try await replica.acceptCurrentParking() |
| 66 | unsettled = false |
| 67 | } |
| 68 | // Replay includes held entries: the editor must show everything kept |
| 69 | // here, even when it cannot currently send it. |
| 70 | for entry in entries where entry.kind == "update" { try await replica.apply(entry.payload); held.insert(entry.id) } |
| 71 | commandsDurable = 0 |
| 72 | hasBase = saved != nil |
| 73 | storedSequence = saved?.sequence ?? 0 |
| 74 | // Stored segments and replayed entries are already durable. |
| 75 | if saved != nil { await replica.persistedAll() } |
| 76 | } |
| 77 | /// Entries the server has taken are acknowledged and never sent again. |
| 78 | func forget(_ entries: Set<UUID>) { held.subtract(entries) } |
| 79 | func enqueue(_ update: Data) async throws { |
| 80 | let entry = try await outbox.enqueue(lane: lane, kind: "update", payload: update) |
| 81 | held.insert(entry.id) |
| 82 | commandsDurable += 1 |
| 83 | } |
| 84 | /// Store what changed since the last persist: appended as one segment |
| 85 | /// (a few bytes per keystroke), or, with no base yet or a large change, |
| 86 | /// as the whole state. |
| 87 | @discardableResult func persist() async throws -> Bool { |
| 88 | let changes = try await replica.persistentChanges(wholeAbove: hasBase ? Self.appendLimit : -1) |
| 89 | // No suspension between checking the watermark and the atomic write. |
| 90 | // A writer running between command and enqueue must defer its capture. |
| 91 | guard active, changes.commandsApplied == commandsDurable else { return false } |
| 92 | let valid = { self.active && changes.commandsApplied == self.commandsDurable } |
| 93 | if changes.whole == nil, changes.updates.isEmpty, changes.sequence <= storedSequence, hasBase { return true } |
| 94 | if let whole = changes.whole { |
| 95 | let saved = PersistedReplica(format: 1, sequence: changes.sequence, guid: changes.guid, savedAt: Date(), state: whole, parked: changes.parked) |
| 96 | if hasBase, changes.replace != nil { |
| 97 | // Settled (#147): the base itself must change, with its |
| 98 | // parking; folding the old base in drops a damaged duplicate. |
| 99 | guard try await cache.replace(with: saved, key: key, generation: generation, valid: valid) else { return false } |
| 100 | } else { |
| 101 | guard try await cache.commit(saved, key: key, generation: generation, valid: valid) else { return false } |
| 102 | } |
| 103 | } else { |
| 104 | let update = changes.updates.reduce(into: Data()) { $0.append($1) } |
| 105 | guard try cache.append(update, sequence: changes.sequence, key: key, generation: generation, valid: valid) else { |
| 106 | // The base is gone (or the capture is stale): store the whole state. |
| 107 | guard valid() else { return false } |
| 108 | hasBase = false |
| 109 | return try await persist() |
| 110 | } |
| 111 | } |
| 112 | hasBase = true |
| 113 | storedSequence = max(storedSequence, changes.sequence) |
| 114 | await replica.persisted(changes) |
| 115 | // Folding segments into the base is upkeep, not durability: they are |
| 116 | // already stored, so a failure here is retried on a later persist. |
| 117 | // A whole state stored as a segment counts too, so it is folded in. |
| 118 | let appended = changes.updates.reduce(changes.whole?.count ?? 0) { $0 + $1.count } |
| 119 | try? await cache.compactIfNeeded(key, generation: generation, appended: appended) |
| 120 | return true |
| 121 | } |
| 122 | func compact() async throws { |
| 123 | let entries = await outbox.sendable(lane: lane, maxBytes: nil) |
| 124 | guard entries.count > 256 || entries.reduce(0, { $0 + $1.payload.count }) > 1024 * 1024 else { return } |
| 125 | var batch: [OutboxEntry] = []; var bytes = 0 |
| 126 | for entry in entries { |
| 127 | if entry.kind != "update" { if batch.isEmpty { continue }; break } |
| 128 | if !batch.isEmpty && bytes + entry.payload.count > 512 * 1024 { break } |
| 129 | batch.append(entry); bytes += entry.payload.count |
| 130 | } |
| 131 | guard batch.count > 1 else { return } |
| 132 | let merged = try await replica.mergeUpdates(batch.map(\.payload)) |
| 133 | guard merged.count <= 512 * 1024 else { return } |
| 134 | // A send can reserve the batch while mergeUpdates suspends. Refusing |
| 135 | // that compaction is expected; it must never delete the reservation. |
| 136 | do { |
| 137 | let replaced = try await outbox.replace(batch.map(\.id), with: merged) |
| 138 | let wasHeld = batch.allSatisfy { held.contains($0.id) } |
| 139 | held.subtract(batch.map(\.id)) |
| 140 | if wasHeld { held.insert(replaced.id) } |
| 141 | } |
| 142 | catch OutboxError.inFlight { } |
| 143 | catch OutboxError.unknownEntry { } |
| 144 | } |
| 145 | func discard() async throws { |
| 146 | active = false |
| 147 | cache.invalidate(key) |
| 148 | // Remove the replica first: a crash may replay lane entries again, |
| 149 | // but can never leave local text whose lane has already been removed. |
| 150 | try cache.remove(key) |
| 151 | try await outbox.discard(lane: lane) |
| 152 | } |
| 153 | } |
| 154 | |