SPB Git

Repository Public

OperationJournal.swift 14.8 KB 232 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sync/OperationJournal.swift3// Description: Persistent journal of the changes decided on this device (create folder, rename, move, trash, restore, favourite, copy): applied at once to the local mirror, replayed in order against the server when it is reachable, kept as history. Survives restarts; nothing is lost offline.4import Foundation5import SPDriveCore67public enum OpKind: String, Codable, Sendable { case createFolder, rename, move, trash, restore, star, copy }8public struct OpPayload: Codable, Sendable, Equatable {9    public var ids: [String] = []        // items concerned (identifiers may be local ones, see `localPrefix`)10    public var kinds: [String] = []      // "file"/"folder", parallel to ids11    public var parent: String?           // destination folder, or parent of a new folder12    public var name: String?13    public var flag: Bool?14    public var localID: String?          // identifier given to a folder created offline15    public init() {}16}17public struct JournalOp: Sendable, Identifiable, Equatable {18    public var id: String; public var kind: OpKind; public var payload: OpPayload19    /// pending, done, failed20    public var state: String21    public var attempts: Int; public var error: String?; public var source: String; public var createdAt: Date; public var updatedAt: Date22    public var summary: String {23        let n = payload.ids.count24        switch kind {25        case .createFolder: return "Créer le dossier « \(payload.name ?? "") »"26        case .rename: return "Renommer en « \(payload.name ?? "") »"27        case .move: return "Déplacer \(n) élément\(n > 1 ? "s" : "")"28        case .trash: return "Mettre \(n) élément\(n > 1 ? "s" : "") à la corbeille"29        case .restore: return "Restaurer \(n) élément\(n > 1 ? "s" : "")"30        case .star: return payload.flag == true ? "Ajouter aux favoris" : "Retirer des favoris"31        case .copy: return "Dupliquer \(n) élément\(n > 1 ? "s" : "")"32        }33    }34}3536public final class OperationJournal: Sendable {37    public static let localPrefix = "local-"38    public let api: APIClient39    public let store: MetadataStore40    public init(api: APIClient, store: MetadataStore) { self.api = api; self.store = store }41    public static func isLocal(_ id: String) -> Bool { id.hasPrefix(localPrefix) }4243    // MARK: Recording (optimistic)44    private func append(_ kind: OpKind, _ payload: OpPayload, source: String) throws -> String {45        let id = UUID().uuidString, now = Date().timeIntervalSince197046        let ord = (try store.db.scalar("SELECT COALESCE(MAX(ord), 0) + 1 FROM ops").int) ?? 147        try store.db.run("INSERT INTO ops (id, kind, payload, state, source, created_at, updated_at, ord) VALUES (?,?,?,?,?,?,?,?)",48                         [.text(id), .text(kind.rawValue), .text(String(data: try JSONEncoder().encode(payload), encoding: .utf8) ?? "{}"), .text("pending"), .text(source), .double(now), .double(now), .int(ord)])49        return id50    }51    private func selection(_ items: [DriveItem]) -> OpPayload { var p = OpPayload(); p.ids = items.map(\.id); p.kinds = items.map(\.kind.rawValue); return p }52    private func local(_ sql: String, _ v: [SQLValue], ids: [String]) throws { try store.db.run(sql, v); try store.touch(ids) }5354    /// Creates a folder locally at once; the server learns of it when reachable. Returns the local item.55    @discardableResult public func createFolder(parent: String, name: String, source: String = "app") throws -> DriveItem {56        try store.db.transaction {57            let taken = Set(try store.children(of: parent).map { NameRules.key($0.name) })58            let free = NameRules.nextFree(NameRules.sanitize(name, fallback: "Nouveau dossier")) { taken.contains($0) }59            var p = OpPayload(); p.parent = parent; p.name = free; p.localID = OperationJournal.localPrefix + UUID().uuidString.lowercased()60            let item = DriveItem(id: p.localID!, kind: .folder, name: free, parentID: parent, rev: 0)61            try store.upsert([item]); _ = try append(.createFolder, p, source: source)62            return item63        }64    }65    public func rename(_ item: DriveItem, to name: String, source: String = "app") throws {66        let clean = NameRules.sanitize(name)67        guard clean != item.name else { return }68        try store.db.transaction {69            if let parent = item.parentID, let other = try store.child(of: parent, named: clean), other.id != item.id { throw DriveError.server(status: 409, code: "name_conflict", message: "", extra: [:]) }70            var p = selection([item]); p.name = clean71            try local("UPDATE items SET name = ?, name_key = ?, ext = ? WHERE id = ?", [.text(clean), .text(NameRules.searchKey(clean)), .text(item.isFolder ? "" : NameRules.fileExtension(clean)), .text(item.id)], ids: [item.id])72            _ = try append(.rename, p, source: source)73        }74    }75    public func move(_ items: [DriveItem], to destination: String, source: String = "app") throws {76        let moving = items.filter { $0.parentID != destination && !$0.isRoot }77        guard !moving.isEmpty else { return }78        try store.db.transaction {79            for f in moving where f.isFolder { if try store.subtreeIDs(of: f.id).contains(destination) { throw DriveError.server(status: 409, code: "move_into_self", message: "", extra: [:]) } }80            var p = selection(moving); p.parent = destination81            for i in moving { try local("UPDATE items SET parent_id = ? WHERE id = ?", [.text(destination), .text(i.id)], ids: [i.id]) }82            _ = try append(.move, p, source: source)83        }84    }85    public func trash(_ items: [DriveItem], source: String = "app") throws {86        let live = items.filter { !$0.isRoot && !$0.isTrashed }87        guard !live.isEmpty else { return }88        try store.db.transaction {89            let now = Date().timeIntervalSince197090            for i in live {91                let ids = i.isFolder ? try store.subtreeIDs(of: i.id) : [i.id]92                for id in ids { try store.db.run("UPDATE items SET trashed_at = ?, trash_root = ? WHERE id = ? AND trashed_at IS NULL", [.double(now), .int(id == i.id ? 1 : 0), .text(id)]) }93                try store.touch(ids)94            }95            _ = try append(.trash, selection(live), source: source)96        }97    }98    public func restore(_ items: [DriveItem], source: String = "app") throws {99        let roots = items.filter(\.trashRoot)100        guard !roots.isEmpty else { return }101        try store.db.transaction {102            for i in roots {103                let ids = i.isFolder ? try store.subtreeIDs(of: i.id, includeTrashed: true) : [i.id]104                for id in ids { try store.db.run("UPDATE items SET trashed_at = NULL, trash_root = 0 WHERE id = ?", [.text(id)]) }105                try store.touch(ids)106            }107            _ = try append(.restore, selection(roots), source: source)108        }109    }110    public func setStarred(_ item: DriveItem, _ on: Bool, source: String = "app") throws {111        try store.db.transaction {112            var p = selection([item]); p.flag = on113            try local("UPDATE items SET starred = ? WHERE id = ?", [.int(on ? 1 : 0), .text(item.id)], ids: [item.id])114            _ = try append(.star, p, source: source)115        }116    }117    /// Duplicates items into a folder. The copies appear when the server has made them (their content is shared there, not re-sent).118    public func copy(_ items: [DriveItem], to destination: String, source: String = "app") throws {119        guard !items.isEmpty else { return }120        var p = selection(items); p.parent = destination121        _ = try append(.copy, p, source: source)122    }123124    // MARK: Reading125    private static func op(_ r: SQLRow) -> JournalOp? {126        guard let kind = OpKind(rawValue: r["kind"]?.text ?? ""), let payload = try? JSONDecoder().decode(OpPayload.self, from: Data((r["payload"]?.text ?? "{}").utf8)) else { return nil }127        return JournalOp(id: r["id"]?.text ?? "", kind: kind, payload: payload, state: r["state"]?.text ?? "", attempts: Int(r["attempts"]?.int ?? 0), error: r["error"]?.text, source: r["source"]?.text ?? "app",128                         createdAt: Date(timeIntervalSince1970: r["created_at"]?.double ?? 0), updatedAt: Date(timeIntervalSince1970: r["updated_at"]?.double ?? 0))129    }130    public func pending() throws -> [JournalOp] { try store.db.query("SELECT * FROM ops WHERE state = 'pending' ORDER BY ord").compactMap(OperationJournal.op) }131    public func pendingCount() throws -> Int { Int(try store.db.scalar("SELECT COUNT(*) FROM ops WHERE state = 'pending'").int ?? 0) }132    public func history(limit: Int = 200) throws -> [JournalOp] { try store.db.query("SELECT * FROM ops ORDER BY ord DESC LIMIT ?", [.int(Int64(limit))]).compactMap(OperationJournal.op) }133    /// Server identifier of an item created offline, once known.134    public func resolve(_ id: String) -> String { OperationJournal.isLocal(id) ? ((try? store.meta("idmap:" + id)) ?? id) ?? id : id }135    public func prune(olderThan days: Int = 30) throws {136        try store.db.run("DELETE FROM ops WHERE state <> 'pending' AND updated_at < ?", [.double(Date().timeIntervalSince1970 - Double(days) * 86400)])137    }138139    // MARK: Replay140    public struct RunResult: Sendable, Equatable { public var done = 0; public var failed = 0; public var blocked = false }141    /// Replays pending operations in the order they were decided. A network failure stops the run (order matters and142    /// nothing is skipped); an operation the server refuses for good is marked failed, the mirror is put back in line143    /// with the server for the items it touched, and the run continues.144    @discardableResult public func run() async -> RunResult {145        var result = RunResult()146        guard let ops = try? pending() else { return result }147        for op in ops {148            do {149                try Task.checkCancellation()150                try await execute(op)151                try finish(op, state: "done", error: nil); result.done += 1152            } catch {153                let e = DriveError.wrap(error)154                if e.isTransient || e == .cancelled || e == .unauthenticated {155                    _ = try? store.db.run("UPDATE ops SET attempts = attempts + 1, error = ?, updated_at = ? WHERE id = ?", [.text(e.errorDescription ?? e.code), .double(Date().timeIntervalSince1970), .text(op.id)])156                    result.blocked = true; return result157                }158                // an item already gone, or already in the wanted state, is not a failure of the person's intent159                let harmless = e.isNotFound && [.trash, .star].contains(op.kind)160                _ = try? finish(op, state: harmless ? "done" : "failed", error: harmless ? nil : (e.errorDescription ?? e.code))161                if harmless { result.done += 1 } else { result.failed += 1 }162                await realign(op)163            }164        }165        return result166    }167    private func finish(_ op: JournalOp, state: String, error: String?) throws {168        try store.db.run("UPDATE ops SET state = ?, error = ?, attempts = attempts + 1, updated_at = ? WHERE id = ?", [.text(state), error.map(SQLValue.text) ?? .null, .double(Date().timeIntervalSince1970), .text(op.id)])169    }170    private func selection(_ p: OpPayload) throws -> Selection {171        var s = Selection()172        for (i, raw) in p.ids.enumerated() {173            let id = resolve(raw)174            if OperationJournal.isLocal(id) { throw DriveError.local("l’élément créé hors ligne n’a pas pu être créé sur le serveur") }175            if i < p.kinds.count, p.kinds[i] == "folder" { s.folderIds.append(id) } else { s.fileIds.append(id) }176        }177        return s178    }179    private func execute(_ op: JournalOp) async throws {180        let p = op.payload181        func parent() throws -> String {182            let id = resolve(p.parent ?? "root")183            if OperationJournal.isLocal(id) { throw DriveError.local("le dossier de destination n’a pas pu être créé sur le serveur") }184            return id185        }186        switch op.kind {187        case .createFolder:188            let created = try await api.createFolder(parent: try parent(), name: p.name ?? "Nouveau dossier", onConflict: .rename)189            if let localID = p.localID {190                // swap the placeholder for the real folder and re-home what was put inside it meanwhile191                try store.db.transaction {192                    try store.setMeta("idmap:" + localID, created.id)193                    try store.upsert([created])194                    let kids = try store.db.query("SELECT id FROM items WHERE parent_id = ?", [.text(localID)]).compactMap { $0["id"]?.text }195                    try store.db.run("UPDATE items SET parent_id = ? WHERE parent_id = ?", [.text(created.id), .text(localID)])196                    try store.db.run("UPDATE transfers SET parent_id = ? WHERE parent_id = ?", [.text(created.id), .text(localID)])197                    if try store.isPinnedItself(localID) { try store.setPinned(created.id, true) }198                    try store.touch(kids); try store.remove([localID])199                }200            } else { try store.upsert([created]) }201        case .rename:202            let s = try selection(p)203            let updated = s.folderIds.first != nil ? try await api.updateFolder(s.folderIds[0], name: p.name) : try await api.updateFile(s.fileIds[0], name: p.name)204            try store.upsert([updated])205        case .move: try await api.move(try selection(p), to: try parent(), onConflict: .rename)206        case .trash: try await api.trash(try selection(p))207        case .restore: try await api.restore(try selection(p))208        case .star:209            let s = try selection(p)210            let updated = s.folderIds.first != nil ? try await api.updateFolder(s.folderIds[0], starred: p.flag) : try await api.updateFile(s.fileIds[0], starred: p.flag)211            try store.upsert([updated])212        case .copy: try await api.copy(try selection(p), to: try parent())213        }214    }215    /// After a refused operation: make the mirror say what the server says for the items involved.216    private func realign(_ op: JournalOp) async {217        var s = Selection()218        for (i, raw) in op.payload.ids.enumerated() {219            let id = resolve(raw); if OperationJournal.isLocal(id) { continue }220            if i < op.payload.kinds.count, op.payload.kinds[i] == "folder" { s.folderIds.append(id) } else { s.fileIds.append(id) }221        }222        if let localID = op.payload.localID { try? store.remove([localID]) }223        guard !s.isEmpty, let fresh = try? await api.items(s) else { return }224        try? store.db.transaction {225            let known = Set(fresh.all.map(\.id))226            for id in s.fileIds + s.folderIds where !known.contains(id) { try store.remove([id]) }227            for i in fresh.all { try store.db.run("UPDATE items SET rev = -1 WHERE id = ?", [.text(i.id)]) } // force the server's state over the optimistic one228            try store.upsert(fresh.all)229        }230    }231}232
Files main
Menu

Theme