Repository Public
1// SP Drive iOS2// File: Sync/BackgroundSession.swift3// Description: URLSession background plumbing: transfers keep running while the app is suspended, and their results are4// delivered again after a relaunch. iOS decides when background tasks run; nothing here promises continuity.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import Synchronization1011/// What the system reports about one background task. `tag` is the caller's identifier (stored in `taskDescription`,12/// so it survives a relaunch of the app).13public enum BackgroundEvent: Sendable {14 case progress(tag: String, done: Int64, total: Int64)15 case finished(tag: String, result: BackgroundResult)16}1718public struct BackgroundResult: Sendable {19 public var status: Int?20 public var headers: [String: String]21 /// Response body of an upload (small JSON), capped.22 public var body: Data23 /// Downloaded bytes, already moved out of the system's temporary location.24 public var file: URL?25 public var error: URLError?26 public var resumeData: Data?27 public var isSuccess: Bool { error == nil && (status.map { (200..<300).contains($0) } ?? false) }28}2930public final class BackgroundSession: NSObject, URLSessionDownloadDelegate, URLSessionDataDelegate, Sendable {31 public typealias Handler = @Sendable (BackgroundEvent) -> Void32 private struct State {33 var bodies: [Int: Data] = [:]34 var files: [Int: URL] = [:]35 var systemCompletion: (@Sendable () -> Void)?36 var handler: Handler?37 var backlog: [BackgroundEvent] = []38 }39 private let state = Mutex(State())40 private let staging: URL41 private let identifier: String42 private let sessionBox = Mutex<URLSession?>(nil)4344 /// - Parameters:45 /// - identifier: stable across launches; the system uses it to hand results back.46 /// - staging: where finished downloads are parked until the owner of the transfer verifies and files them.47 public init(identifier: String, staging: URL) {48 self.identifier = identifier49 self.staging = staging50 super.init()51 try? FileManager.default.createDirectory(at: staging, withIntermediateDirectories: true)52 }5354 private var session: URLSession {55 sessionBox.withLock { s in56 if let s { return s }57 let c = URLSessionConfiguration.background(withIdentifier: identifier)58 c.sessionSendsLaunchEvents = true59 c.isDiscretionary = false60 c.httpCookieStorage = nil61 c.httpShouldSetCookies = false62 c.urlCache = nil63 c.waitsForConnectivity = true64 c.timeoutIntervalForResource = 7 * 24 * 360065 c.httpMaximumConnectionsPerHost = 466 let made = URLSession(configuration: c, delegate: self, delegateQueue: nil)67 s = made68 return made69 }70 }7172 /// Connects the session to its consumer. Events that arrived before (relaunch in the background) are replayed in order.73 public func start(handler: @escaping Handler) {74 let backlog = state.withLock { st -> [BackgroundEvent] in st.handler = handler; defer { st.backlog = [] }; return st.backlog }75 backlog.forEach(handler)76 _ = session77 }7879 /// Called from `application(_:handleEventsForBackgroundURLSession:completionHandler:)`.80 public func setSystemCompletion(_ completion: @escaping @Sendable () -> Void) {81 state.withLock { $0.systemCompletion = completion }82 _ = session83 }8485 public func download(_ request: URLRequest, tag: String, resumeData: Data? = nil, expectedBytes: Int64 = 0) {86 let task = resumeData.map { session.downloadTask(withResumeData: $0) } ?? session.downloadTask(with: request)87 task.taskDescription = tag88 if expectedBytes > 0 { task.countOfBytesClientExpectsToReceive = expectedBytes }89 task.resume()90 }9192 /// Background uploads must read their body from a file.93 public func upload(_ request: URLRequest, fromFile file: URL, tag: String) {94 let task = session.uploadTask(with: request, fromFile: file)95 task.taskDescription = tag96 task.countOfBytesClientExpectsToSend = (try? file.resourceValues(forKeys: [.fileSizeKey]).fileSize).map(Int64.init) ?? NSURLSessionTransferSizeUnknown97 task.resume()98 }99100 /// Tags of the tasks the system still holds (running or waiting), to reconcile with the persistent queue after a launch.101 public func activeTags() async -> Set<String> {102 Set(await session.allTasks.filter { $0.state == .running || $0.state == .suspended }.compactMap(\.taskDescription))103 }104105 public func cancel(tag: String) async {106 for t in await session.allTasks where t.taskDescription == tag { t.cancel() }107 }108109 public func cancelAll() async {110 for t in await session.allTasks { t.cancel() }111 }112113 private func emit(_ e: BackgroundEvent) {114 let h = state.withLock { st -> Handler? in115 if st.handler == nil { if case .finished = e { st.backlog.append(e) } }116 return st.handler117 }118 h?(e)119 }120121 // MARK: URLSession delegate122123 public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {124 guard let tag = downloadTask.taskDescription else { return }125 emit(.progress(tag: tag, done: totalBytesWritten, total: totalBytesExpectedToWrite))126 }127128 public func urlSession(_ session: URLSession, task: URLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {129 guard let tag = task.taskDescription else { return }130 emit(.progress(tag: tag, done: totalBytesSent, total: totalBytesExpectedToSend))131 }132133 public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {134 // The temporary file disappears when this method returns: park it now.135 let dest = staging.appendingPathComponent(UUID().uuidString)136 do {137 try FileManager.default.moveItem(at: location, to: dest)138 state.withLock { $0.files[downloadTask.taskIdentifier] = dest }139 } catch {140 Log.transfer.error("could not park a finished download: \(error.localizedDescription, privacy: .public)")141 }142 }143144 public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {145 state.withLock { st in146 var d = st.bodies[dataTask.taskIdentifier] ?? Data()147 if d.count < 256 * 1024 { d.append(data) }148 st.bodies[dataTask.taskIdentifier] = d149 }150 }151152 public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {153 guard let tag = task.taskDescription else { return }154 let (body, file) = state.withLock { st in (st.bodies.removeValue(forKey: task.taskIdentifier) ?? Data(), st.files.removeValue(forKey: task.taskIdentifier)) }155 let http = task.response as? HTTPURLResponse156 var headers: [String: String] = [:]157 for (k, v) in http?.allHeaderFields ?? [:] { if let k = k as? String, let v = v as? String { headers[k.lowercased()] = v } }158 let urlError = error as? URLError159 let resume = (error as NSError?)?.userInfo[NSURLSessionDownloadTaskResumeData] as? Data160 var result = BackgroundResult(status: http?.statusCode, headers: headers, body: body, file: file, error: urlError, resumeData: resume)161 if error != nil, urlError == nil { result.error = URLError(.unknown) }162 // A download that the server refused (4xx/5xx) still produces a file: it holds the error body, not the document.163 if let f = file, let s = http?.statusCode, !(200..<300).contains(s) {164 result.body = (try? Data(contentsOf: f, options: .mappedIfSafe).prefix(64 * 1024)).map { Data($0) } ?? Data()165 try? FileManager.default.removeItem(at: f)166 result.file = nil167 }168 emit(.finished(tag: tag, result: result))169 }170171 public func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {172 let done = state.withLock { st -> (@Sendable () -> Void)? in defer { st.systemCompletion = nil }; return st.systemCompletion }173 if let done { DispatchQueue.main.async { done() } }174 }175}176