SPB Git

Repository Public

ConflictResolver.swift 6.9 KB 101 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sync/ConflictResolver.swift3// Description: Conflicts between this device and the server: each one is recorded with the copy that preserved the local content, and resolved by an explicit choice — keep both, keep mine, keep the server's — none of which deletes anything for good.4import Foundation5import SPDriveCore67public struct SyncConflict: Sendable, Identifiable, Hashable {8    public var id: String9    /// The file that was changed on two devices.10    public var itemID: String11    public var itemName: String12    /// The copy holding this device's content.13    public var copyID: String?14    public var copyName: String15    /// "content" (edited on two devices), "edit_delete" (edited here, deleted elsewhere).16    public var kind: String17    public var detail: String18    public var detectedAt: Date19    public var resolvedAt: Date?20    public var resolution: String?21    public var isOpen: Bool { resolvedAt == nil }22}23public enum ConflictChoice: String, Sendable, CaseIterable {24    /// Both files stay, side by side.25    case keepBoth26    /// This device's content takes the original's place; the server's version goes to the trash.27    case keepMine28    /// The server's version stays; this device's copy goes to the trash.29    case keepServer30}3132public struct ConflictResolver: Sendable {33    public let api: APIClient34    public let store: MetadataStore35    public init(api: APIClient, store: MetadataStore) { self.api = api; self.store = store }3637    @discardableResult public func record(itemID: String, itemName: String, copy: DriveItem?, kind: String = "content", detail: String = "") throws -> SyncConflict {38        let c = SyncConflict(id: UUID().uuidString, itemID: itemID, itemName: itemName, copyID: copy?.id, copyName: copy?.name ?? "", kind: kind, detail: detail, detectedAt: Date(), resolvedAt: nil, resolution: nil)39        try store.db.run("INSERT INTO conflicts (id, item_id, item_name, copy_id, copy_name, kind, detail, detected_at) VALUES (?,?,?,?,?,?,?,?)",40                         [.text(c.id), .text(itemID), .text(itemName), copy.map { .text($0.id) } ?? .null, .text(c.copyName), .text(kind), .text(detail), .double(c.detectedAt.timeIntervalSince1970)])41        return c42    }43    private static func conflict(_ r: SQLRow) -> SyncConflict {44        SyncConflict(id: r["id"]?.text ?? "", itemID: r["item_id"]?.text ?? "", itemName: r["item_name"]?.text ?? "", copyID: r["copy_id"]?.text, copyName: r["copy_name"]?.text ?? "",45                     kind: r["kind"]?.text ?? "content", detail: r["detail"]?.text ?? "", detectedAt: Date(timeIntervalSince1970: r["detected_at"]?.double ?? 0),46                     resolvedAt: r["resolved_at"]?.double.map(Date.init(timeIntervalSince1970:)), resolution: r["resolution"]?.text)47    }48    public func conflicts(openOnly: Bool = false) throws -> [SyncConflict] {49        try store.db.query("SELECT * FROM conflicts \(openOnly ? "WHERE resolved_at IS NULL" : "") ORDER BY detected_at DESC LIMIT 500").map(ConflictResolver.conflict)50    }51    public func openCount() throws -> Int { Int(try store.db.scalar("SELECT COUNT(*) FROM conflicts WHERE resolved_at IS NULL").int ?? 0) }5253    /// Applies the person's choice. Whatever is set aside goes to the trash of SP Drive, from which it can be restored.54    public func resolve(_ c: SyncConflict, _ choice: ConflictChoice) async throws {55        switch choice {56        case .keepBoth: break57        case .keepServer:58            if let copy = c.copyID, try await api.item(copy, kind: .file)?.isTrashed == false { try await api.trash(Selection(fileIds: [copy])) }59        case .keepMine:60            guard let copy = c.copyID, let mine = try await api.item(copy, kind: .file), !mine.isTrashed else { throw DriveError.local("la copie de cet appareil n’existe plus") }61            if let original = try await api.item(c.itemID, kind: .file), !original.isTrashed {62                try await api.trash(Selection(fileIds: [original.id]))63                if original.parentID != mine.parentID, let p = original.parentID { try await api.move(Selection(fileIds: [copy]), to: p, onConflict: .rename) }64            }65            _ = try await api.updateFile(copy, name: c.itemName)66        }67        try store.db.run("UPDATE conflicts SET resolved_at = ?, resolution = ? WHERE id = ?", [.double(Date().timeIntervalSince1970), .text(choice.rawValue), .text(c.id)])68    }69    /// "Keep mine" without losing the file's history: this device's content becomes the **new current version** of the70    /// original file (the server's version stays in its version history, restorable), and the conflict copy goes to the71    /// trash. The upload names the version it replaces: if the file changed yet again meanwhile, nothing is overwritten72    /// and `version_conflict` is thrown so that the person looks again.73    @discardableResult public func resolveKeepingMineAsNewVersion(_ c: SyncConflict, workDirectory: URL, deviceName: String) async throws -> DriveItem {74        guard let copyID = c.copyID, let mine = try await api.item(copyID, kind: .file), !mine.isTrashed else { throw DriveError.local("la copie de cet appareil n’existe plus") }75        guard let original = try await api.item(c.itemID, kind: .file), !original.isTrashed else {76            // the original is gone: there is no history to extend; this device's copy simply takes the name77            try await resolve(c, .keepMine)78            return try await api.item(copyID, kind: .file) ?? mine79        }80        var result = original81        if mine.sha256 != original.sha256 {82            let dir = workDirectory.appendingPathComponent("conflicts/\(c.id)", isDirectory: true)83            defer { try? FileManager.default.removeItem(at: dir) }84            let local = try PathSafety.child(of: dir, named: "content")85            try await DownloadEngine(api: api).download(fileID: mine.id, versionID: mine.versionID, sha256: mine.sha256, size: mine.size, to: local, partial: dir.appendingPathComponent("content.part"))86            let outcome = try await UploadEngine(api: api, store: nil, deviceName: deviceName)87                .upload(file: local, to: .newVersion(fileID: original.id, folderID: original.parentID ?? "root", name: original.name, baseVersionID: original.versionID))88            guard case .stored(let updated) = outcome else {89                // changed again while we were deciding: the engine made a second copy of the same bytes — one is enough90                try? await api.trash(Selection(fileIds: [outcome.item.id]))91                throw DriveError.server(status: 409, code: "version_conflict", message: "", extra: [:])92            }93            result = updated94        }95        try await api.trash(Selection(fileIds: [copyID]))96        _ = try? store.upsert([result])97        try store.db.run("UPDATE conflicts SET resolved_at = ?, resolution = ? WHERE id = ?", [.double(Date().timeIntervalSince1970), .text("keepMineVersion"), .text(c.id)])98        return result99    }100}101
Files main
Menu

Theme