| 1 | import Foundation |
| 2 | import RastrilloNative |
| 3 | |
| 4 | /// A document's stored replica: a base (`replica`, the whole state when it |
| 5 | /// was last compacted) plus segments in `replica-log/`, each an update |
| 6 | /// appended since with the server sequence it brings the state to. The |
| 7 | /// replica is their union; a CRDT applies them in any order, more than once. |
| 8 | /// |
| 9 | /// Editor captures and headless sends both write here. Appending never |
| 10 | /// rewrites what another writer stored, and a compaction removes only the |
| 11 | /// segments it merged, so neither writer can erase an acknowledged batch. |
| 12 | @MainActor final class DocsReplicaCache { |
| 13 | let store: BlobStore |
| 14 | private var generations: [String: Int] = [:] |
| 15 | /// Compact once this many segments are waiting, or one large one is. |
| 16 | static let compactionSegments = 32 |
| 17 | static let compactionBytes = 256 * 1024 |
| 18 | init(store: BlobStore) { self.store = store } |
| 19 | func generation(_ key: String) -> Int { generations[key, default: 0] } |
| 20 | func invalidate(_ key: String) { generations[key, default: 0] += 1 } |
| 21 | static func basePath(_ key: String) -> String { "cache/docs/\(key)/replica" } |
| 22 | static func logPath(_ key: String) -> String { "cache/docs/\(key)/replica-log" } |
| 23 | |
| 24 | /// One appended update. Segments are numbered without gaps from the |
| 25 | /// base's `segmentsFrom`; the number is in the name and, sealed, in the |
| 26 | /// bytes, so a missing or substituted segment is seen on load. |
| 27 | struct Segment: Sendable { |
| 28 | let name: String |
| 29 | let index: Int64 |
| 30 | let sequence: Int64 |
| 31 | let update: Data |
| 32 | private static let magic = Data("DRL2".utf8) |
| 33 | var encoded: Data { |
| 34 | var data = Self.magic |
| 35 | withUnsafeBytes(of: index.bigEndian) { data.append(contentsOf: $0) } |
| 36 | withUnsafeBytes(of: sequence.bigEndian) { data.append(contentsOf: $0) } |
| 37 | data.append(update) |
| 38 | return data |
| 39 | } |
| 40 | static func name(_ index: Int64) -> String { String(format: "%016llx-%08x-", index, UInt32.random(in: 0...UInt32.max)) + UUID().uuidString } |
| 41 | static func index(of name: String) -> Int64? { Int64(name.prefix(16), radix: 16) } |
| 42 | init(index: Int64, sequence: Int64, update: Data) { self.name = Self.name(index); self.index = index; self.sequence = sequence; self.update = update } |
| 43 | init?(name: String, encoded data: Data) { |
| 44 | guard data.count >= 20, data.prefix(4) == Self.magic else { return nil } |
| 45 | func number(_ at: Int) -> Int64 { data.dropFirst(at).prefix(8).reduce(Int64(0)) { ($0 << 8) | Int64($1) } } |
| 46 | guard number(4) == Self.index(of: name) else { return nil } |
| 47 | self.name = name; index = number(4); sequence = number(12); update = Data(data.dropFirst(20)) |
| 48 | } |
| 49 | } |
| 50 | struct Stored: Sendable { |
| 51 | let replica: PersistedReplica |
| 52 | let segments: [Segment] |
| 53 | var sequence: Int64 { segments.reduce(replica.sequence) { max($0, $1.sequence) } } |
| 54 | } |
| 55 | /// Whether a base is stored, without reading (and unsealing) it. |
| 56 | func hasBase(_ key: String) throws -> Bool { |
| 57 | try store.list("cache/docs/\(key)").contains("replica") |
| 58 | } |
| 59 | /// The stored replica. A segment that fails to unseal, or a gap in the |
| 60 | /// numbering (a segment removed after a failed read, or lost), makes the |
| 61 | /// whole replica untrustworthy: a later segment's sequence would claim |
| 62 | /// updates it no longer holds. So all of it is removed, as a corrupt base |
| 63 | /// is, and the next open starts again from the server and the outbox. |
| 64 | /// Segments numbered below the base's `segmentsFrom` are already in it |
| 65 | /// (a compaction stopped before removing them) and are skipped. |
| 66 | func load(_ key: String) throws -> Stored? { |
| 67 | guard let data = try store.read(Self.basePath(key)) else { return nil } |
| 68 | let replica = try JSONDecoder().decode(PersistedReplica.self, from: data) |
| 69 | let first = replica.segmentsFrom ?? 0 |
| 70 | var segments: [Segment] = [] |
| 71 | do { |
| 72 | for name in try segmentNames(key) { |
| 73 | let path = Self.logPath(key) + "/" + name |
| 74 | guard let index = Segment.index(of: name), index >= first else { continue } |
| 75 | guard let data = try store.read(path), let segment = Segment(name: name, encoded: data) else { throw BlobStoreError.corrupt(path) } |
| 76 | segments.append(segment) |
| 77 | } |
| 78 | segments.sort { $0.index < $1.index } |
| 79 | for (offset, segment) in segments.enumerated() where segment.index != first + Int64(offset) { |
| 80 | throw BlobStoreError.corrupt(Self.logPath(key) + "/" + segment.name) |
| 81 | } |
| 82 | } catch BlobStoreError.corrupt(let path) { |
| 83 | try remove(key) |
| 84 | throw BlobStoreError.corrupt(path) |
| 85 | } |
| 86 | nextIndex[key] = first + Int64(segments.count) |
| 87 | return Stored(replica: replica, segments: segments) |
| 88 | } |
| 89 | /// Segments first: an interrupted removal leaves the base alone (an |
| 90 | /// older state the outbox and server complete), never segments without it. |
| 91 | func remove(_ key: String) throws { |
| 92 | try store.remove(Self.logPath(key)) |
| 93 | try store.remove(Self.basePath(key)) |
| 94 | } |
| 95 | /// Only names this cache writes: anything else in the directory (a |
| 96 | /// file system's temporary file) is not a segment. |
| 97 | private func segmentNames(_ key: String) throws -> [String] { |
| 98 | try store.list(Self.logPath(key)).filter { name in |
| 99 | let parts = name.split(separator: "-", maxSplits: 2) |
| 100 | return parts.count == 3 && parts[0].count == 16 && parts[1].count == 8 && UUID(uuidString: String(parts[2])) != nil |
| 101 | } |
| 102 | } |
| 103 | /// The next segment number per document, once known in this process. |
| 104 | private var nextIndex: [String: Int64] = [:] |
| 105 | /// The number the next segment takes: one past the highest stored, or |
| 106 | /// the base's `segmentsFrom` when none is. |
| 107 | private func nextSegment(_ key: String) throws -> Int64 { |
| 108 | if let highest = try segmentNames(key).compactMap(Segment.index(of:)).max() { return highest + 1 } |
| 109 | if let known = nextIndex[key] { return known } |
| 110 | guard let data = try store.read(Self.basePath(key)) else { return 0 } |
| 111 | return try JSONDecoder().decode(PersistedReplica.self, from: data).segmentsFrom ?? 0 |
| 112 | } |
| 113 | /// Store `update` as a new segment. Refuses (false) when there is no base |
| 114 | /// to append to, or when `valid` no longer holds; a discarded document |
| 115 | /// (a newer generation) throws. |
| 116 | @discardableResult func append(_ update: Data, sequence: Int64, key: String, generation: Int, valid: () -> Bool = { true }) throws -> Bool { |
| 117 | guard self.generation(key) == generation else { throw CancellationError() } |
| 118 | guard try hasBase(key), valid() else { return false } |
| 119 | let segment = Segment(index: try nextSegment(key), sequence: sequence, update: update) |
| 120 | try store.write(segment.encoded, to: Self.logPath(key) + "/" + segment.name) |
| 121 | nextIndex[key] = segment.index + 1 |
| 122 | return true |
| 123 | } |
| 124 | /// Store a whole state. With a base already stored it is appended like |
| 125 | /// any update; otherwise it becomes the base, merged with any base a |
| 126 | /// concurrent writer stores first. |
| 127 | @discardableResult func commit(_ candidate: PersistedReplica, key: String, generation: Int, valid: () -> Bool = { true }) async throws -> Bool { |
| 128 | let path = Self.basePath(key) |
| 129 | while self.generation(key) == generation { |
| 130 | if try hasBase(key) { |
| 131 | guard valid() else { return false } |
| 132 | if try append(candidate.state, sequence: candidate.sequence, key: key, generation: generation) { return true } |
| 133 | continue |
| 134 | } |
| 135 | let before = try store.read(path) |
| 136 | let previous = try before.map { try JSONDecoder().decode(PersistedReplica.self, from: $0) } |
| 137 | let merger = CRDTReplica(guid: candidate.guid) |
| 138 | do { |
| 139 | try await merger.open(update: previous?.state ?? Data()) |
| 140 | try await merger.apply(candidate.state) |
| 141 | let state = try await merger.persistentState().state |
| 142 | await merger.close() |
| 143 | guard self.generation(key) == generation else { throw CancellationError() } |
| 144 | // No suspension between the compare and write. A concurrent |
| 145 | // editor or headless writer forces a fresh merge, never a loss. |
| 146 | guard try store.read(path) == before else { continue } |
| 147 | let merged = PersistedReplica(format: 1, sequence: max(previous?.sequence ?? 0, candidate.sequence), guid: candidate.guid, savedAt: Date(), state: state, |
| 148 | parked: candidate.parked ?? previous?.parked, segmentsFrom: previous?.segmentsFrom) |
| 149 | guard valid() else { return false } |
| 150 | // Segments without a base are left by an interrupted removal: |
| 151 | // they belong to discarded state and must never be read again. |
| 152 | if previous == nil { try store.remove(Self.logPath(key)); nextIndex[key] = 0 } |
| 153 | try store.write(JSONEncoder().encode(merged), to: path) |
| 154 | return true |
| 155 | } catch { |
| 156 | await merger.close() |
| 157 | throw error |
| 158 | } |
| 159 | } |
| 160 | throw CancellationError() |
| 161 | } |
| 162 | /// Fold the segments into the base once enough of them are waiting. |
| 163 | func compactIfNeeded(_ key: String, generation: Int, appended bytes: Int = 0) async throws { |
| 164 | guard try bytes >= Self.compactionBytes || segmentNames(key).count >= Self.compactionSegments else { return } |
| 165 | try await compact(key, generation: generation) |
| 166 | } |
| 167 | /// Write base ∪ segments as the new base, then remove exactly the |
| 168 | /// segments merged. A crash between the two only leaves segments the base |
| 169 | /// already contains. Segments appended meanwhile stay. The base keeps the |
| 170 | /// parking it had accepted (#147). |
| 171 | func compact(_ key: String, generation: Int) async throws { |
| 172 | _ = try await fold(key, generation: generation, adding: nil) |
| 173 | } |
| 174 | /// Store `candidate` as the base itself, folding the stored base and |
| 175 | /// segments in, with the candidate's accepted parking: after a replica |
| 176 | /// settles (#147), what the old base accepted no longer holds, and a |
| 177 | /// segment cannot carry that. Refuses (false) when `valid` no longer |
| 178 | /// holds; a discarded document throws. |
| 179 | @discardableResult func replace(with candidate: PersistedReplica, key: String, generation: Int, valid: () -> Bool = { true }) async throws -> Bool { |
| 180 | while self.generation(key) == generation { |
| 181 | guard try hasBase(key) else { return try await commit(candidate, key: key, generation: generation, valid: valid) } |
| 182 | switch try await fold(key, generation: generation, adding: candidate, valid: valid) { |
| 183 | case .stored: return true |
| 184 | case .refused: return false |
| 185 | case .raced: continue |
| 186 | } |
| 187 | } |
| 188 | throw CancellationError() |
| 189 | } |
| 190 | private enum Folded { case stored, refused, raced } |
| 191 | private func fold(_ key: String, generation: Int, adding candidate: PersistedReplica?, valid: () -> Bool = { true }) async throws -> Folded { |
| 192 | let path = Self.basePath(key) |
| 193 | guard let before = try store.read(path), let stored = try load(key) else { return .raced } |
| 194 | guard candidate != nil || !stored.segments.isEmpty else { return .stored } |
| 195 | let merger = CRDTReplica(guid: stored.replica.guid) |
| 196 | let state: Data |
| 197 | do { |
| 198 | try await merger.open(update: stored.replica.state) |
| 199 | for segment in stored.segments { try await merger.apply(segment.update) } |
| 200 | if let candidate { try await merger.apply(candidate.state) } |
| 201 | state = try await merger.persistentState().state |
| 202 | await merger.close() |
| 203 | } catch { await merger.close(); throw error } |
| 204 | guard self.generation(key) == generation else { throw CancellationError() } |
| 205 | // Another writer replaced the base meanwhile: leave the segments for it. |
| 206 | guard try store.read(path) == before else { return .raced } |
| 207 | let next = stored.segments.last.map { $0.index + 1 } ?? (stored.replica.segmentsFrom ?? 0) |
| 208 | let merged = PersistedReplica(format: 1, sequence: max(stored.sequence, candidate?.sequence ?? 0), guid: stored.replica.guid, savedAt: Date(), state: state, |
| 209 | parked: candidate?.parked ?? stored.replica.parked, segmentsFrom: next) |
| 210 | // No suspension between this check and the write. |
| 211 | guard valid() else { return .refused } |
| 212 | try store.write(JSONEncoder().encode(merged), to: path) |
| 213 | nextIndex[key] = next |
| 214 | // Remove what the new base holds: the merged segments, and any left |
| 215 | // below the old base's start by an earlier interrupted compaction. |
| 216 | for name in try segmentNames(key) where (Segment.index(of: name) ?? next) < next { try store.remove(Self.logPath(key) + "/" + name) } |
| 217 | return .stored |
| 218 | } |
| 219 | } |
| 220 | |