SPB Git

Repository Public

ResumableUpload.swift 8.7 KB 152 lines swift

1// SP Lecture Studio — LectureSync2// File: Packages/LectureSync/Sources/ResumableUpload.swift3// Description: Explicit, resumable upload of a file to a user-configured endpoint using the open tus 1.0 protocol (creation + core).4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation89public enum UploadError: Error, Equatable, CustomStringConvertible {10    case notConfigured, insecureEndpoint, cancelled, server(Int, String), protocolError(String), network(String), fileChanged11    public var description: String {12        switch self {13        case .notConfigured: "no upload endpoint is configured"14        case .insecureEndpoint: "the endpoint must use https"15        case .cancelled: "cancelled"16        case .server(let c, let m): "server answered \(c) \(m)"17        case .protocolError(let m): "unexpected server behaviour: \(m)"18        case .network(let m): m19        case .fileChanged: "the file changed since the upload started"20        }21    }22}2324public struct UploadEndpoint: Sendable, Hashable, Codable {25    /// tus creation URL, e.g. https://host.example/files/26    public var url: String27    public init(url: String = "") { self.url = url }28    public var parsed: URL? { URL(string: url.trimmingCharacters(in: .whitespaces)) }29    public var isConfigured: Bool { parsed != nil && !url.trimmingCharacters(in: .whitespaces).isEmpty }30    public var isSecure: Bool {31        guard let u = parsed, let scheme = u.scheme?.lowercased(), let host = u.host else { return false }32        return scheme == "https" || (scheme == "http" && ["localhost", "127.0.0.1", "::1"].contains(host))33    }34}3536/// Progress of one upload, persisted so that an interrupted transfer continues where it stopped (even after a relaunch).37public struct UploadState: Sendable, Hashable, Codable {38    public var filePath: String39    public var fileSize: Int6440    public var fileModified: Date41    public var uploadURL: String?42    public var offset: Int6443    public var completed: Bool44    public init(file: URL) throws {45        let attrs = try FileManager.default.attributesOfItem(atPath: file.path)46        filePath = file.path; fileSize = (attrs[.size] as? NSNumber)?.int64Value ?? 0; fileModified = attrs[.modificationDate] as? Date ?? Date()47        uploadURL = nil; offset = 0; completed = false48    }49}5051public final class ResumableUploader: @unchecked Sendable {52    public let endpoint: UploadEndpoint53    private let token: String?54    private let session: URLSession55    public var chunkSize = 8 << 2056    public var maxRetriesPerChunk = 45758    public init(endpoint: UploadEndpoint, token: String?, session: URLSession = .shared) {59        self.endpoint = endpoint; self.token = token; self.session = session60    }6162    private func request(_ url: URL, _ method: String) -> URLRequest {63        var r = URLRequest(url: url); r.httpMethod = method; r.timeoutInterval = 12064        r.setValue("1.0.0", forHTTPHeaderField: "Tus-Resumable")65        if let token, !token.isEmpty { r.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") }66        return r67    }6869    private func send(_ r: URLRequest, body: Data? = nil) async throws -> (Data, HTTPURLResponse) {70        do {71            let (data, response): (Data, URLResponse)72            if let body { (data, response) = try await session.upload(for: r, from: body) } else { (data, response) = try await session.data(for: r) }73            guard let http = response as? HTTPURLResponse else { throw UploadError.protocolError("not HTTP") }74            return (data, http)75        } catch let e as UploadError { throw e }76        catch is CancellationError { throw UploadError.cancelled }77        catch { throw UploadError.network(error.localizedDescription) }78    }7980    /// Uploads (or resumes) `state`. `onState` is called after every acknowledged chunk so the caller can persist it.81    public func upload(_ initial: UploadState, metadata: [String: String] = [:], onState: @escaping @Sendable (UploadState) -> Void = { _ in },82                       isCancelled: @escaping @Sendable () -> Bool = { false }) async throws -> UploadState {83        guard endpoint.isConfigured, let base = endpoint.parsed else { throw UploadError.notConfigured }84        guard endpoint.isSecure else { throw UploadError.insecureEndpoint }85        var state = initial86        let file = URL(fileURLWithPath: state.filePath)87        let current = try UploadState(file: file)88        guard current.fileSize == state.fileSize, abs(current.fileModified.timeIntervalSince(state.fileModified)) < 1 else { throw UploadError.fileChanged }8990        // 1. Create the upload, or ask the server how much it already has.91        if let existing = state.uploadURL.flatMap(URL.init(string:)) {92            let (_, http) = try await send(request(existing, "HEAD"))93            if http.statusCode == 404 || http.statusCode == 410 { state.uploadURL = nil; state.offset = 0 }       // the server forgot it: start over94            else if (200..<300).contains(http.statusCode), let s = http.value(forHTTPHeaderField: "Upload-Offset"), let off = Int64(s) { state.offset = off }95            else { throw UploadError.server(http.statusCode, "HEAD") }96        }97        if state.uploadURL == nil {98            var r = request(base, "POST")99            r.setValue(String(state.fileSize), forHTTPHeaderField: "Upload-Length")100            var meta = metadata; meta["filename"] = meta["filename"] ?? file.lastPathComponent101            r.setValue(meta.sorted { $0.key < $1.key }.map { "\($0.key) \(Data($0.value.utf8).base64EncodedString())" }.joined(separator: ","), forHTTPHeaderField: "Upload-Metadata")102            let (data, http) = try await send(r)103            guard http.statusCode == 201, let location = http.value(forHTTPHeaderField: "Location"), let url = URL(string: location, relativeTo: base)?.absoluteURL else {104                throw UploadError.server(http.statusCode, String(decoding: data.prefix(200), as: UTF8.self))105            }106            guard UploadEndpoint(url: url.absoluteString).isSecure else { throw UploadError.insecureEndpoint }107            state.uploadURL = url.absoluteString; state.offset = 0108            onState(state)109        }110        guard let uploadURL = state.uploadURL.flatMap(URL.init(string:)) else { throw UploadError.protocolError("no upload URL") }111112        // 2. Send the remaining bytes chunk by chunk.113        let handle = try FileHandle(forReadingFrom: file)114        defer { try? handle.close() }115        var failures = 0116        while state.offset < state.fileSize {117            if isCancelled() { throw UploadError.cancelled }118            try handle.seek(toOffset: UInt64(state.offset))119            let chunk = try handle.read(upToCount: chunkSize) ?? Data()120            guard !chunk.isEmpty else { throw UploadError.fileChanged }121            var r = request(uploadURL, "PATCH")122            r.setValue("application/offset+octet-stream", forHTTPHeaderField: "Content-Type")123            r.setValue(String(state.offset), forHTTPHeaderField: "Upload-Offset")124            do {125                let (data, http) = try await send(r, body: chunk)126                if http.statusCode == 204, let s = http.value(forHTTPHeaderField: "Upload-Offset"), let off = Int64(s) {127                    guard off > state.offset, off <= state.fileSize else { throw UploadError.protocolError("offset \(off)") }128                    state.offset = off; failures = 0; onState(state)129                } else if http.statusCode == 409 {130                    // Offset mismatch: resynchronize with the server and continue.131                    let (_, head) = try await send(request(uploadURL, "HEAD"))132                    guard let s = head.value(forHTTPHeaderField: "Upload-Offset"), let off = Int64(s) else { throw UploadError.protocolError("409 without offset") }133                    state.offset = off; onState(state)134                } else if (500..<600).contains(http.statusCode) {135                    throw UploadError.network("server error \(http.statusCode)")136                } else {137                    throw UploadError.server(http.statusCode, String(decoding: data.prefix(200), as: UTF8.self))138                }139            } catch UploadError.network(let message) {140                failures += 1141                if failures > maxRetriesPerChunk { throw UploadError.network(message) }142                try? await Task.sleep(nanoseconds: UInt64(min(8, pow(2, Double(failures - 1))) * 0.25 * 1e9))143                // Ask the server where it stands before retrying (part of the chunk may have arrived).144                if let (_, head) = try? await send(request(uploadURL, "HEAD")), let s = head.value(forHTTPHeaderField: "Upload-Offset"), let off = Int64(s) { state.offset = off }145            }146        }147        state.completed = true148        onState(state)149        return state150    }151}152
Files main
Menu

Theme