|
| 1 | +import Foundation |
| 2 | + |
| 3 | +struct UpdateHTTPResponse: Sendable { |
| 4 | + let statusCode: Int |
| 5 | + let headers: [String: String] |
| 6 | + let body: Data |
| 7 | + |
| 8 | + func header(named name: String) -> String? { |
| 9 | + headers.first { $0.key.caseInsensitiveCompare(name) == .orderedSame }?.value |
| 10 | + } |
| 11 | +} |
| 12 | + |
| 13 | +protocol UpdateNetworkTransport: Sendable { |
| 14 | + func fetch(_ request: URLRequest) async throws -> UpdateHTTPResponse |
| 15 | + /// Returns a temporary file whose ownership transfers to the caller. |
| 16 | + func download( |
| 17 | + _ request: URLRequest, |
| 18 | + progress: @escaping @Sendable (UpdateDownloadProgress) async -> Void |
| 19 | + ) async throws -> URL |
| 20 | +} |
| 21 | + |
| 22 | +enum UpdateTransportError: Error { |
| 23 | + case invalidResponse |
| 24 | +} |
| 25 | + |
| 26 | +final class MacUpdateNetworkTransport: UpdateNetworkTransport, @unchecked Sendable { |
| 27 | + private let session: URLSession |
| 28 | + private let fileManager: FileManager |
| 29 | + |
| 30 | + init(session: URLSession = .shared, fileManager: FileManager = .default) { |
| 31 | + self.session = session |
| 32 | + self.fileManager = fileManager |
| 33 | + } |
| 34 | + |
| 35 | + func fetch(_ request: URLRequest) async throws -> UpdateHTTPResponse { |
| 36 | + let (data, response) = try await session.data(for: request) |
| 37 | + guard let response = response as? HTTPURLResponse else { |
| 38 | + throw UpdateTransportError.invalidResponse |
| 39 | + } |
| 40 | + return UpdateHTTPResponse( |
| 41 | + statusCode: response.statusCode, |
| 42 | + headers: response.allHeaderFields.reduce(into: [:]) { headers, entry in |
| 43 | + headers[String(describing: entry.key)] = String(describing: entry.value) |
| 44 | + }, |
| 45 | + body: data |
| 46 | + ) |
| 47 | + } |
| 48 | + |
| 49 | + func download( |
| 50 | + _ request: URLRequest, |
| 51 | + progress: @escaping @Sendable (UpdateDownloadProgress) async -> Void |
| 52 | + ) async throws -> URL { |
| 53 | + let (bytes, response) = try await session.bytes(for: request) |
| 54 | + guard let httpResponse = response as? HTTPURLResponse else { |
| 55 | + throw UpdateTransportError.invalidResponse |
| 56 | + } |
| 57 | + guard (200..<300).contains(httpResponse.statusCode) else { |
| 58 | + throw UpdateCheckError.httpStatus(httpResponse.statusCode) |
| 59 | + } |
| 60 | + |
| 61 | + let totalBytes = response.expectedContentLength > 0 |
| 62 | + ? response.expectedContentLength |
| 63 | + : nil |
| 64 | + let destination = fileManager.temporaryDirectory |
| 65 | + .appendingPathComponent("lithe-update-\(UUID().uuidString).dmg") |
| 66 | + guard fileManager.createFile(atPath: destination.path, contents: nil) else { |
| 67 | + throw UpdateCheckError.downloadFailed |
| 68 | + } |
| 69 | + |
| 70 | + do { |
| 71 | + let handle = try FileHandle(forWritingTo: destination) |
| 72 | + defer { try? handle.close() } |
| 73 | + |
| 74 | + var buffer = Data() |
| 75 | + buffer.reserveCapacity(64 * 1024) |
| 76 | + var downloadedBytes: Int64 = 0 |
| 77 | + var lastProgressUpdate = Date.distantPast |
| 78 | + |
| 79 | + for try await byte in bytes { |
| 80 | + buffer.append(byte) |
| 81 | + downloadedBytes += 1 |
| 82 | + |
| 83 | + if buffer.count >= 64 * 1024 { |
| 84 | + try handle.write(contentsOf: buffer) |
| 85 | + buffer.removeAll(keepingCapacity: true) |
| 86 | + let now = Date() |
| 87 | + if now.timeIntervalSince(lastProgressUpdate) >= 0.05 { |
| 88 | + lastProgressUpdate = now |
| 89 | + await progress(UpdateDownloadProgress( |
| 90 | + downloadedBytes: downloadedBytes, |
| 91 | + totalBytes: totalBytes |
| 92 | + )) |
| 93 | + } |
| 94 | + } |
| 95 | + } |
| 96 | + |
| 97 | + if !buffer.isEmpty { |
| 98 | + try handle.write(contentsOf: buffer) |
| 99 | + } |
| 100 | + await progress(UpdateDownloadProgress( |
| 101 | + downloadedBytes: downloadedBytes, |
| 102 | + totalBytes: totalBytes |
| 103 | + )) |
| 104 | + return destination |
| 105 | + } catch { |
| 106 | + try? fileManager.removeItem(at: destination) |
| 107 | + throw error |
| 108 | + } |
| 109 | + } |
| 110 | +} |
0 commit comments