Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sync/IntegrityVerifier.swift3// Description: Integrity checks of content on disk (size and SHA-256 read as a stream) and atomic placement of a verified file at its destination.4import CryptoKit5import Foundation6import SPDriveCore78public enum IntegrityVerifier {9 /// Throws `.integrity` unless the file has exactly this size and this SHA-256 (an empty `sha256` checks the size only).10 public static func verify(_ url: URL, sha256: String, size: Int64?) throws {11 let (sha, n) = try Hashing.sha256Hex(of: url)12 if let size, n != size { throw DriveError.integrity("taille \(n) au lieu de \(size)") }13 if !sha256.isEmpty, sha != sha256.lowercased() { throw DriveError.integrity("empreinte SHA-256 différente") }14 }15 /// Flushes `source` to disk and renames it over `destination` (same volume): a reader sees the old file or the new one, never a mix.16 public static func placeAtomically(_ source: URL, at destination: URL) throws {17 let fd = open(source.path, O_RDONLY)18 if fd >= 0 { _ = fcntl(fd, F_FULLFSYNC); close(fd) }19 try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true)20 guard rename(source.path, destination.path) == 0 else {21 // different volumes: copy next to the destination first, then rename22 let tmp = destination.deletingLastPathComponent().appendingPathComponent(".spdrive-\(UUID().uuidString).tmp")23 try FileManager.default.copyItem(at: source, to: tmp)24 guard rename(tmp.path, destination.path) == 0 else { try? FileManager.default.removeItem(at: tmp); throw DriveError.local("écriture impossible : \(String(cString: strerror(errno)))") }25 try? FileManager.default.removeItem(at: source)26 return27 }28 }29}3031/// Byte-rate limiter shared by the transfers of one direction (token bucket). A limit of 0 means unlimited.32public actor Throttle {33 private var limit: Int6434 private var allowance: Double35 private var last = ContinuousClock.now36 public init(bytesPerSecond: Int64 = 0) { limit = bytesPerSecond; allowance = Double(bytesPerSecond) }37 public func setLimit(_ bytesPerSecond: Int64) { limit = max(0, bytesPerSecond); allowance = min(allowance, Double(limit)) }38 public var bytesPerSecond: Int64 { limit }39 /// Largest block worth sending at once under the current limit (about one second of traffic).40 public func preferredBlock(_ wanted: Int) -> Int { limit > 0 ? max(16 * 1024, min(wanted, Int(limit))) : wanted }41 /// Waits until `bytes` may be sent or received.42 public func consume(_ bytes: Int) async throws {43 guard limit > 0 else { return }44 let now = ContinuousClock.now45 let elapsed = Double((now - last).components.seconds) + Double((now - last).components.attoseconds) / 1e1846 last = now47 allowance = min(Double(limit), allowance + elapsed * Double(limit)) - Double(bytes)48 if allowance < 0 { try await Task.sleep(nanoseconds: UInt64(-allowance / Double(limit) * 1e9)) }49 }50}51