Repository Public License
1// SyncEngine — the transport-independent core: change records, deterministic merge.2import CryptoKit3import Foundation4import NavigatorCore56public struct SyncKey: Hashable, Sendable, Codable, Comparable, CustomStringConvertible {7 public var entity: SyncRecord.Entity8 public var entityID: String910 public init(_ entity: SyncRecord.Entity, _ entityID: String) { self.entity = entity; self.entityID = entityID }11 public init(_ record: SyncRecord) { entity = record.entity; entityID = record.entityID }1213 public var description: String { "\(entity.rawValue):\(entityID)" }14 public static func < (lhs: SyncKey, rhs: SyncKey) -> Bool { (lhs.entity.rawValue, lhs.entityID) < (rhs.entity.rawValue, rhs.entityID) }15}1617/// A sync record as it travels: the same fields as `SyncRecord` minus the local row id, with dates as seconds18/// since 1970 (the exact value the database stores, so every device compares identical numbers).19public struct SyncStamp: Hashable, Sendable, Codable {20 public var entity: SyncRecord.Entity21 public var entityID: String22 public var version: Int6423 public var deviceID: String24 public var modifiedAt: Double25 public var deletedAt: Double?26 public var payloadHash: String?2728 public init(_ record: SyncRecord) {29 entity = record.entity; entityID = record.entityID; version = record.version; deviceID = record.deviceID30 modifiedAt = record.modifiedAt.timeIntervalSince1970; deletedAt = record.deletedAt?.timeIntervalSince197031 payloadHash = record.payloadHash32 }3334 public init(entity: SyncRecord.Entity, entityID: String, version: Int64, deviceID: String, modifiedAt: Double, deletedAt: Double? = nil,35 payloadHash: String? = nil) {36 self.entity = entity; self.entityID = entityID; self.version = version; self.deviceID = deviceID37 self.modifiedAt = modifiedAt; self.deletedAt = deletedAt; self.payloadHash = payloadHash38 }3940 public var key: SyncKey { SyncKey(entity, entityID) }41 public var isTombstone: Bool { deletedAt != nil }4243 public var record: SyncRecord {44 SyncRecord(entity: entity, entityID: entityID, version: version, deviceID: deviceID, modifiedAt: Date(timeIntervalSince1970: modifiedAt),45 deletedAt: deletedAt.map(Date.init(timeIntervalSince1970:)), payloadHash: payloadHash)46 }47}4849/// One change: the stamp, and for a live entity its canonical JSON.50public struct SyncChange: Hashable, Sendable, Codable {51 public var stamp: SyncStamp52 /// Canonical JSON of the entity; `nil` for a deletion.53 public var payload: Data?54 /// The profile the entity belonged to on the device that wrote it (bookmarks and spaces). Profiles are not55 /// synchronised: the receiver uses it only if it has that very profile.56 public var profileHint: String?5758 public init(stamp: SyncStamp, payload: Data?, profileHint: String? = nil) {59 self.stamp = stamp; self.payload = payload; self.profileHint = profileHint60 }6162 public var key: SyncKey { stamp.key }6364 /// A live change must carry exactly the bytes its stamp announces; a deletion carries none.65 public var isWellFormed: Bool {66 if stamp.isTombstone { return payload == nil }67 guard let payload, let hash = stamp.payloadHash else { return false }68 return SyncMerge.hash(payload) == hash69 }70}7172/// The merge rule of the whole sync system, as pure functions.73///74/// Every key (entity, id) holds one stamp. Stamps of a key are totally ordered by75/// `(version, modifiedAt, deviceID, isTombstone, payloadHash)`, compared left to right; merging keeps the76/// greatest. Keeping a maximum is commutative, associative and idempotent, so devices that have seen the same77/// set of changes hold the same stamps whatever the order, grouping or repetition in which they arrived.78///79/// - `version` is a Lamport counter: a device that has seen a change always writes a higher one, so an edit made80/// with knowledge of another edit wins over it.81/// - `modifiedAt`, then `deviceID`, break ties between edits made without knowledge of each other.82/// - On a tie of all three (same device, same version, same time) a deletion wins over a live record.83public enum SyncMerge {84 public static func hash(_ payload: Data) -> String { SHA256.hash(data: payload).map { String(format: "%02x", $0) }.joined() }8586 /// Strict order: `true` when `lhs` loses against `rhs`.87 public static func precedes(_ lhs: SyncStamp, _ rhs: SyncStamp) -> Bool {88 if lhs.version != rhs.version { return lhs.version < rhs.version }89 if lhs.modifiedAt != rhs.modifiedAt { return lhs.modifiedAt < rhs.modifiedAt }90 if lhs.deviceID != rhs.deviceID { return lhs.deviceID < rhs.deviceID }91 if lhs.isTombstone != rhs.isTombstone { return rhs.isTombstone }92 return (lhs.payloadHash ?? "") < (rhs.payloadHash ?? "")93 }9495 /// Whether an incoming stamp replaces the one held (`nil` = nothing held).96 public static func wins(_ incoming: SyncStamp, over held: SyncStamp?) -> Bool {97 guard let held else { return true }98 return precedes(held, incoming)99 }100101 /// Merges changes into a state and returns the keys whose value changed.102 @discardableResult103 public static func merge(_ changes: some Sequence<SyncChange>, into state: inout [SyncKey: SyncChange]) -> [SyncKey] {104 var changed: [SyncKey] = []105 for change in changes where change.isWellFormed && wins(change.stamp, over: state[change.key]?.stamp) {106 state[change.key] = change107 changed.append(change.key)108 }109 return changed110 }111112 /// From a peer's list of stamps: the live changes worth asking for and the deletions to apply directly.113 public static func plan(remote: some Sequence<SyncStamp>, local: [SyncKey: SyncStamp]) -> (request: [SyncKey], tombstones: [SyncStamp]) {114 var request: [SyncKey] = [], tombstones: [SyncStamp] = []115 for stamp in remote where wins(stamp, over: local[stamp.key]) {116 if stamp.isTombstone { tombstones.append(stamp) } else { request.append(stamp.key) }117 }118 return (request.sorted(), tombstones.sorted { $0.key < $1.key })119 }120}121