Skip to content

Free fork of NotProton: Windows Steam games in Mac Steam, on CodeWeavers' Wine and Apple's Game Porting Toolkit

fix(installer): download to a file with progress instead of reading the response byte by byte

raymondchins72a78ca1c3d2
diff --git a/app/Sources/BridgeplayInstallerCore/InstallerComponents.swift b/app/Sources/BridgeplayInstallerCore/InstallerComponents.swift
index ab0e18a..82e5b4e 100644
--- a/app/Sources/BridgeplayInstallerCore/InstallerComponents.swift
+++ b/app/Sources/BridgeplayInstallerCore/InstallerComponents.swift
@@ -71,11 +71,10 @@ public struct InstallerComponents: Sendable, Equatable {
/// Download to a file in `directory` and verify it. Throws without leaving the file on failure.
public func download(to directory: URL, session: URLSession = .shared,
progress: @escaping @Sendable (InstallerDownloadProgress) -> Void = { _ in }) async throws -> URL {
- let delegate = ProgressDelegate(total: length, progress: progress)
var request = URLRequest(url: archiveURL)
request.timeoutInterval = 60
let temporary: URL, response: URLResponse
- do { (temporary, response) = try await session.download(for: request, delegate: delegate) }
+ do { (temporary, response) = try await InstallerFileDownload.run(request, total: length, progress: progress) }
catch is CancellationError { throw CancellationError() }
catch { throw InstallerError.networkFailure(error.localizedDescription) }
let archive = directory.appending(path: "Bridgeplay-Installer.zip")
@@ -155,16 +154,58 @@ public struct InstallerComponents: Sendable, Equatable {
}
}
-private final class ProgressDelegate: NSObject, URLSessionDownloadDelegate, @unchecked Sendable {
- let total: Int64
- let progress: @Sendable (InstallerDownloadProgress) -> Void
- init(total: Int64, progress: @escaping @Sendable (InstallerDownloadProgress) -> Void) {
+/// Downloads to a file with progress. A task delegate passed to `URLSession.download(for:delegate:)`
+/// gets no progress callbacks, so each download gets its own session with this delegate.
+/// The file is moved out of URLSession's temporary location before the callback returns.
+final class InstallerFileDownload: NSObject, URLSessionDownloadDelegate, @unchecked Sendable {
+ private let total: Int64
+ private let progress: @Sendable (InstallerDownloadProgress) -> Void
+ private let lock = NSLock()
+ private var continuation: CheckedContinuation<(URL, URLResponse), Error>?
+ private var saved: URL?
+
+ private init(total: Int64, progress: @escaping @Sendable (InstallerDownloadProgress) -> Void) {
self.total = total
self.progress = progress
}
+
+ static func run(_ request: URLRequest, total: Int64,
+ progress: @escaping @Sendable (InstallerDownloadProgress) -> Void) async throws -> (URL, URLResponse) {
+ let delegate = InstallerFileDownload(total: total, progress: progress)
+ let session = URLSession(configuration: .ephemeral, delegate: delegate, delegateQueue: nil)
+ defer { session.finishTasksAndInvalidate() }
+ let task = session.downloadTask(with: request)
+ return try await withTaskCancellationHandler {
+ try await withCheckedThrowingContinuation { continuation in
+ delegate.lock.withLock { delegate.continuation = continuation }
+ task.resume()
+ }
+ } onCancel: { task.cancel() }
+ }
+
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64,
totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
progress(InstallerDownloadProgress(received: totalBytesWritten, total: total))
}
- func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {}
+
+ func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
+ let keep = FileManager.default.temporaryDirectory.appending(path: "bridgeplay-download-\(UUID().uuidString)")
+ try? FileManager.default.moveItem(at: location, to: keep)
+ lock.withLock { saved = keep }
+ }
+
+ func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
+ let (continuation, file) = lock.withLock { () -> (CheckedContinuation<(URL, URLResponse), Error>?, URL?) in
+ defer { self.continuation = nil }
+ return (self.continuation, saved)
+ }
+ if let error {
+ if let file { try? FileManager.default.removeItem(at: file) }
+ continuation?.resume(throwing: (error as? URLError)?.code == .cancelled ? CancellationError() : error)
+ } else if let file, let response = task.response {
+ continuation?.resume(returning: (file, response))
+ } else {
+ continuation?.resume(throwing: URLError(.cannotCreateFile))
+ }
+ }
}
diff --git a/app/Sources/BridgeplayInstallerCore/InstallerRelease.swift b/app/Sources/BridgeplayInstallerCore/InstallerRelease.swift
index 4d38adf..a92b132 100644
--- a/app/Sources/BridgeplayInstallerCore/InstallerRelease.swift
+++ b/app/Sources/BridgeplayInstallerCore/InstallerRelease.swift
@@ -128,68 +128,47 @@ public struct InstallerRelease: Sendable, Equatable {
return try parse(appcast: data)
}
- /// Stream the signed archive to temporary memory, verify it, then write it to disk.
- /// The destination is created only after the complete archive passes its EdDSA check.
+ /// Download the signed archive to a temporary file, verify it, then move it into place.
+ /// The destination archive exists only after the complete file passes its EdDSA check.
+ /// (Reading the response byte by byte held a fast connection to about 0.5 MB/s.)
public func download(
to destination: URL,
session: URLSession = .shared,
- progress: @Sendable (InstallerDownloadProgress) -> Void = { _ in }
+ progress: @escaping @Sendable (InstallerDownloadProgress) -> Void = { _ in }
) async throws -> URL {
guard destination.isFileURL else { throw InstallerError.invalidDestination }
let archiveURL = destination.appending(path: "Bridgeplay.zip")
var request = URLRequest(url: self.archiveURL)
request.timeoutInterval = 60
- let bytes: URLSession.AsyncBytes
+ let temporary: URL
let response: URLResponse
do {
- (bytes, response) = try await session.bytes(for: request)
+ (temporary, response) = try await InstallerFileDownload.run(request, total: archiveLength, progress: progress)
} catch is CancellationError {
throw CancellationError()
} catch {
throw InstallerError.networkFailure(error.localizedDescription)
}
+ defer { try? FileManager.default.removeItem(at: temporary) }
guard let http = response as? HTTPURLResponse, http.statusCode == 200,
let finalURL = http.url, Self.isArchiveResponseURL(finalURL) else {
throw InstallerError.invalidRelease
}
- let expected = response.expectedContentLength > 0 ? response.expectedContentLength : nil
- if let expected, expected > Self.maximumArchiveLength {
- throw InstallerError.archiveTooLarge
- }
-
- var archive = Data()
- archive.reserveCapacity(Int(min(expected ?? archiveLength, Self.maximumArchiveLength)))
- var received: Int64 = 0
- for try await byte in bytes {
- try Task.checkCancellation()
- received += 1
- guard received <= Self.maximumArchiveLength,
- received <= archiveLength,
- expected.map({ received <= $0 }) ?? true else {
- throw InstallerError.invalidArchiveLength
- }
- archive.append(byte)
- if received.isMultiple(of: 256 * 1024) {
- progress(InstallerDownloadProgress(received: received, total: expected ?? archiveLength))
- }
- }
-
- guard received == archiveLength, expected.map({ $0 == received }) ?? true else {
- throw InstallerError.invalidArchiveLength
- }
- try Self.verify(archive, signature: signature, publicKey: verificationKey)
+ if response.expectedContentLength > Self.maximumArchiveLength { throw InstallerError.archiveTooLarge }
+ try verifyArchive(at: temporary)
try Task.checkCancellation()
do {
try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true)
- try archive.write(to: archiveURL, options: .atomic)
+ try? FileManager.default.removeItem(at: archiveURL)
+ try FileManager.default.moveItem(at: temporary, to: archiveURL)
} catch {
try? FileManager.default.removeItem(at: archiveURL)
throw InstallerError.writeFailure(error.localizedDescription)
}
- progress(InstallerDownloadProgress(received: received, total: expected ?? archiveLength))
+ progress(InstallerDownloadProgress(received: archiveLength, total: archiveLength))
return archiveURL
}
diff --git a/app/Tests/BridgeplayInstallerCoreTests/InstallerLiveDownloadTests.swift b/app/Tests/BridgeplayInstallerCoreTests/InstallerLiveDownloadTests.swift
new file mode 100644
index 0000000..2868d20
--- /dev/null
+++ b/app/Tests/BridgeplayInstallerCoreTests/InstallerLiveDownloadTests.swift
@@ -0,0 +1,29 @@
+import Foundation
+import Testing
+@testable import BridgeplayInstallerCore
+
+// Downloads the Latest release over the network, so it runs only with BRIDGEPLAY_LIVE_DOWNLOAD=1.
+@Suite("Installer live download", .enabled(if: ProcessInfo.processInfo.environment["BRIDGEPLAY_LIVE_DOWNLOAD"] == "1"))
+struct InstallerLiveDownloadTests {
+ final class Seen: @unchecked Sendable {
+ let lock = NSLock()
+ var calls = 0, last: Int64 = 0
+ }
+
+ @Test("The Latest app downloads with progress and passes its signature check")
+ func latestApp() async throws {
+ let release = try await InstallerRelease.latest()
+ let seen = Seen()
+ let dir = FileManager.default.temporaryDirectory.appending(path: "live-\(UUID().uuidString)")
+ defer { try? FileManager.default.removeItem(at: dir) }
+ let start = Date()
+ let archive = try await release.download(to: dir) { value in
+ seen.lock.withLock { seen.calls += 1; seen.last = value.received }
+ }
+ let seconds = Date().timeIntervalSince(start)
+ print("live download: \(release.archiveLength) bytes in \(String(format: "%.1f", seconds))s, "
+ + "\(String(format: "%.1f", Double(release.archiveLength) / seconds / 1e6)) MB/s, \(seen.calls) progress calls")
+ #expect(FileManager.default.fileExists(atPath: archive.path))
+ #expect(seen.calls > 10 && seen.last == release.archiveLength)
+ }
+}