SPB Git

Repository Public

DirectTransfer.swift 4.1 KB 73 lines swift

1// SP Drive iOS2// File: Sync/DirectTransfer.swift3// Description: Straight-through upload and download for the extensions (File Provider, share sheet): block by block, verified, resumable4//              when the system runs the same request again after an interruption.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation910public enum DirectTransfer {11    static let chunkSize: Int64 = 8 * 1024 * 10241213    /// Sends a file through the resumable protocol. `resumeKey` names this piece of work: when the same key comes back (the system retried14    /// after the extension was stopped), the upload continues from the offset the server holds instead of starting again.15    public static func upload(file: URL, remote: DriveRemote, store: DriveStore?, resumeKey: String?, scratch: URL, progress: (@Sendable (Int64, Int64) -> Void)? = nil,16                              create: @Sendable (_ size: Int64) async throws -> RemoteUpload) async throws -> DriveItem {17        let size = IntegrityVerifier.size(of: file)18        let sha = try IntegrityVerifier.sha256(of: file)19        let key = resumeKey.map { "upload:\($0):\(sha)" }20        var upload: RemoteUpload?21        if let key, let saved = store?.meta(key), let status = try? await remote.uploadStatus(id: saved), status.status == "active", status.size == size { upload = status }22        if upload == nil {23            upload = try await create(size)24            if let key { store?.setMeta(key, upload!.id) }25        }26        var current = upload!27        defer { try? FileManager.default.removeItem(at: scratch) }28        var mismatches = 029        while current.received < size {30            try Task.checkCancellation()31            let length = min(chunkSize, size - current.received)32            let chunkSHA = try IntegrityVerifier.slice(file, offset: current.received, length: length, to: scratch)33            do {34                current = try await remote.sendChunk(uploadID: current.id, offset: current.received, sha256: chunkSHA, fileURL: scratch)35            } catch RemoteError.offsetMismatch(let received) {36                mismatches += 137                guard mismatches < 5 else { throw RemoteError.checksumMismatch }38                current.received = received39            } catch RemoteError.checksumMismatch {40                mismatches += 141                guard mismatches < 5 else { throw RemoteError.checksumMismatch }42            }43            progress?(current.received, size)44        }45        do {46            let item = try await remote.completeUpload(id: current.id, sha256: sha)47            if let key { store?.setMeta(key, nil) }48            return item49        } catch let e as RemoteError where !e.isTransient {50            // refused for good (conflict, quota…): the caller decides; the saved session stays valid for a conflict copy51            throw UploadRefused(error: e, uploadID: current.id, sha256: sha, resumeKey: key)52        }53    }5455    public struct UploadRefused: Error, Sendable { public let error: RemoteError; public let uploadID: String; public let sha256: String; public let resumeKey: String? }5657    /// Fetches a file's content into `destination` and verifies it against the announced hash. A partial file left by an earlier attempt is completed.58    public static func download(item: DriveItem, api: DriveAPI, to destination: URL, progress: (@Sendable (Int64) -> Void)? = nil) async throws {59        var offset = IntegrityVerifier.size(of: destination)60        if offset > item.size { try? FileManager.default.removeItem(at: destination); offset = 0 }61        if item.size == 0 { FileManager.default.createFile(atPath: destination.path, contents: nil) }62        if offset < item.size {63            let request = try await api.contentRequest(fileID: item.id, versionID: nil, offset: offset, etag: item.sha256)64            let base = offset65            _ = try await api.download(request, to: destination, append: offset > 0) { progress?(base + $0) }66        }67        guard IntegrityVerifier.verify(destination, sha256: item.sha256) else {68            try? FileManager.default.removeItem(at: destination)69            throw RemoteError.checksumMismatch70        }71    }72}73
Files main
Menu

Theme