| index c4a1c40..cae2909 100644 |
| --- a/native/apple/Sources/DocsKit/DocsReplicaCache.swift |
| +++ b/native/apple/Sources/DocsKit/DocsReplicaCache.swift |
| @@ -21,22 +21,30 @@ import RastrilloNative |
| static func basePath(_ key: String) -> String { "cache/docs/\(key)/replica" } |
| static func logPath(_ key: String) -> String { "cache/docs/\(key)/replica-log" } |
| |
| + /// One appended update. Segments are numbered without gaps from the |
| + /// base's `segmentsFrom`; the number is in the name and, sealed, in the |
| + /// bytes, so a missing or substituted segment is seen on load. |
| struct Segment: Sendable { |
| let name: String |
| + let index: Int64 |
| let sequence: Int64 |
| let update: Data |
| - private static let magic = Data("DRL1".utf8) |
| + private static let magic = Data("DRL2".utf8) |
| var encoded: Data { |
| var data = Self.magic |
| + withUnsafeBytes(of: index.bigEndian) { data.append(contentsOf: $0) } |
| withUnsafeBytes(of: sequence.bigEndian) { data.append(contentsOf: $0) } |
| data.append(update) |
| return data |
| } |
| - init(name: String, sequence: Int64, update: Data) { self.name = name; self.sequence = sequence; self.update = update } |
| + static func name(_ index: Int64) -> String { String(format: "%016llx-%08x-", index, UInt32.random(in: 0...UInt32.max)) + UUID().uuidString } |
| + static func index(of name: String) -> Int64? { Int64(name.prefix(16), radix: 16) } |
| + init(index: Int64, sequence: Int64, update: Data) { self.name = Self.name(index); self.index = index; self.sequence = sequence; self.update = update } |
| init?(name: String, encoded data: Data) { |
| - guard data.count >= 12, data.prefix(4) == Self.magic else { return nil } |
| - let sequence = data.dropFirst(4).prefix(8).reduce(Int64(0)) { ($0 << 8) | Int64($1) } |
| - self.init(name: name, sequence: sequence, update: Data(data.dropFirst(12))) |
| + guard data.count >= 20, data.prefix(4) == Self.magic else { return nil } |
| + func number(_ at: Int) -> Int64 { data.dropFirst(at).prefix(8).reduce(Int64(0)) { ($0 << 8) | Int64($1) } } |
| + guard number(4) == Self.index(of: name) else { return nil } |
| + self.name = name; index = number(4); sequence = number(12); update = Data(data.dropFirst(20)) |
| } |
| } |
| struct Stored: Sendable { |
| @@ -48,24 +56,34 @@ import RastrilloNative |
| func hasBase(_ key: String) throws -> Bool { |
| try store.list("cache/docs/\(key)").contains("replica") |
| } |
| - /// The stored replica. A segment that fails to unseal makes the whole |
| - /// replica untrustworthy (a later segment's sequence would claim updates |
| - /// it no longer holds), so all of it is removed, as a corrupt base is, |
| - /// and the next open starts again from the server and the outbox. |
| + /// The stored replica. A segment that fails to unseal, or a gap in the |
| + /// numbering (a segment removed after a failed read, or lost), makes the |
| + /// whole replica untrustworthy: a later segment's sequence would claim |
| + /// updates it no longer holds. So all of it is removed, as a corrupt base |
| + /// is, and the next open starts again from the server and the outbox. |
| + /// Segments numbered below the base's `segmentsFrom` are already in it |
| + /// (a compaction stopped before removing them) and are skipped. |
| func load(_ key: String) throws -> Stored? { |
| guard let data = try store.read(Self.basePath(key)) else { return nil } |
| let replica = try JSONDecoder().decode(PersistedReplica.self, from: data) |
| + let first = replica.segmentsFrom ?? 0 |
| var segments: [Segment] = [] |
| do { |
| for name in try segmentNames(key) { |
| - guard let data = try store.read(Self.logPath(key) + "/" + name) else { continue } |
| - guard let segment = Segment(name: name, encoded: data) else { throw BlobStoreError.corrupt(Self.logPath(key) + "/" + name) } |
| + let path = Self.logPath(key) + "/" + name |
| + guard let index = Segment.index(of: name), index >= first else { continue } |
| + guard let data = try store.read(path), let segment = Segment(name: name, encoded: data) else { throw BlobStoreError.corrupt(path) } |
| segments.append(segment) |
| } |
| + segments.sort { $0.index < $1.index } |
| + for (offset, segment) in segments.enumerated() where segment.index != first + Int64(offset) { |
| + throw BlobStoreError.corrupt(Self.logPath(key) + "/" + segment.name) |
| + } |
| } catch BlobStoreError.corrupt(let path) { |
| try remove(key) |
| throw BlobStoreError.corrupt(path) |
| } |
| + nextIndex[key] = first + Int64(segments.count) |
| return Stored(replica: replica, segments: segments) |
| } |
| /// Segments first: an interrupted removal leaves the base alone (an |
| @@ -82,10 +100,15 @@ import RastrilloNative |
| return parts.count == 3 && parts[0].count == 16 && parts[1].count == 8 && UUID(uuidString: String(parts[2])) != nil |
| } |
| } |
| - private var counter: UInt64 = 0 |
| - private func segmentName() -> String { |
| - counter &+= 1 |
| - return String(format: "%016llx-%08llx-", UInt64(Date().timeIntervalSince1970 * 1_000_000), counter) + UUID().uuidString |
| + /// The next segment number per document, once known in this process. |
| + private var nextIndex: [String: Int64] = [:] |
| + /// The number the next segment takes: one past the highest stored, or |
| + /// the base's `segmentsFrom` when none is. |
| + private func nextSegment(_ key: String) throws -> Int64 { |
| + if let highest = try segmentNames(key).compactMap(Segment.index(of:)).max() { return highest + 1 } |
| + if let known = nextIndex[key] { return known } |
| + guard let data = try store.read(Self.basePath(key)) else { return 0 } |
| + return try JSONDecoder().decode(PersistedReplica.self, from: data).segmentsFrom ?? 0 |
| } |
| /// Store `update` as a new segment. Refuses (false) when there is no base |
| /// to append to, or when `valid` no longer holds; a discarded document |
| @@ -93,8 +116,9 @@ import RastrilloNative |
| @discardableResult func append(_ update: Data, sequence: Int64, key: String, generation: Int, valid: () -> Bool = { true }) throws -> Bool { |
| guard self.generation(key) == generation else { throw CancellationError() } |
| guard try hasBase(key), valid() else { return false } |
| - let segment = Segment(name: segmentName(), sequence: sequence, update: update) |
| + let segment = Segment(index: try nextSegment(key), sequence: sequence, update: update) |
| try store.write(segment.encoded, to: Self.logPath(key) + "/" + segment.name) |
| + nextIndex[key] = segment.index + 1 |
| return true |
| } |
| /// Store a whole state. With a base already stored it is appended like |
| @@ -121,11 +145,11 @@ import RastrilloNative |
| // editor or headless writer forces a fresh merge, never a loss. |
| guard try store.read(path) == before else { continue } |
| let merged = PersistedReplica(format: 1, sequence: max(previous?.sequence ?? 0, candidate.sequence), guid: candidate.guid, savedAt: Date(), state: state, |
| - parked: candidate.parked ?? previous?.parked) |
| + parked: candidate.parked ?? previous?.parked, segmentsFrom: previous?.segmentsFrom) |
| guard valid() else { return false } |
| // Segments without a base are left by an interrupted removal: |
| // they belong to discarded state and must never be read again. |
| - if previous == nil { try store.remove(Self.logPath(key)) } |
| + if previous == nil { try store.remove(Self.logPath(key)); nextIndex[key] = 0 } |
| try store.write(JSONEncoder().encode(merged), to: path) |
| return true |
| } catch { |
| @@ -157,8 +181,11 @@ import RastrilloNative |
| guard self.generation(key) == generation else { throw CancellationError() } |
| // Another writer replaced the base meanwhile: leave the segments for it. |
| guard try store.read(path) == before else { return } |
| - let merged = PersistedReplica(format: 1, sequence: stored.sequence, guid: stored.replica.guid, savedAt: Date(), state: state) |
| + let next = (stored.segments.last?.index ?? 0) + 1 |
| + let merged = PersistedReplica(format: 1, sequence: stored.sequence, guid: stored.replica.guid, savedAt: Date(), state: state, segmentsFrom: next) |
| try store.write(JSONEncoder().encode(merged), to: path) |
| - for segment in stored.segments { try store.remove(Self.logPath(key) + "/" + segment.name) } |
| + // Remove what the new base holds: the merged segments, and any left |
| + // below the old base's start by an earlier interrupted compaction. |
| + for name in try segmentNames(key) where (Segment.index(of: name) ?? next) < next { try store.remove(Self.logPath(key) + "/" + name) } |
| } |
| } |