Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 71 additions & 11 deletions ArkServer/Features/Updates/AppUpdater.swift
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,8 @@ final class AppUpdater: ObservableObject {
static let skippedKey = "updates.skippedVersion"
static let lastCheckKey = "updates.lastCheck"
static let latestURL = URL(string: "https://api.github.com/repos/HR0101/ArkServer/releases/latest")!
/// 進捗をこの幅(1%)以上進んだときだけ画面に反映し,再描画の回数を抑える
static let progressReportStep = 0.01

enum State: Equatable {
case idle, checking, available(AppRelease), upToDate, noRelease
Expand All @@ -116,12 +118,15 @@ final class AppUpdater: ObservableObject {
private var window: NSWindow?
private var manualRequested = false
private let presentsWindows: Bool
private let downloadsDirectory: URL?

init(defaults: UserDefaults = .standard, session: URLSession = .shared,
version: String? = nil, build: String? = nil, presentsWindows: Bool = true) {
version: String? = nil, build: String? = nil, presentsWindows: Bool = true,
downloadsDirectory: URL? = nil) {
self.defaults = defaults
self.session = session
self.presentsWindows = presentsWindows
self.downloadsDirectory = downloadsDirectory
currentVersion = version ?? Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0.0.0"
currentBuild = build ?? Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "0"
automaticallyChecks = defaults.object(forKey: Self.automaticKey) as? Bool ?? true
Expand Down Expand Up @@ -209,20 +214,26 @@ final class AppUpdater: ObservableObject {
let delegate = UpdateDownloadProgress { [weak self] value in
Task { @MainActor in
guard self?.downloadID == id, case .downloading = self?.state else { return }
self?.progress = value
self?.applyProgress(value)
}
}
defer { delegate.invalidate() }
let (temporary, response) = try await session.download(for: URLRequest(url: url, timeoutInterval: 300), delegate: delegate)
defer { try? FileManager.default.removeItem(at: temporary) }
try Task.checkCancellation()
guard let http = response as? HTTPURLResponse else { throw AppUpdateError.response }
try Self.validateHTTP(http)
let directory = try FileManager.default.url(for: .downloadsDirectory, in: .userDomainMask, appropriateFor: nil, create: true)
let directory = try downloadsDirectory ?? FileManager.default.url(
for: .downloadsDirectory, in: .userDomainMask, appropriateFor: nil, create: true
)
try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
let destination = directory.appendingPathComponent("ArkServer-\(UUID().uuidString).dmg")
try FileManager.default.moveItem(at: temporary, to: destination)
downloadID = nil
state = .downloaded(destination)
NSWorkspace.shared.activateFileViewerSelecting([destination])
if presentsWindows {
NSWorkspace.shared.activateFileViewerSelecting([destination])
}
} catch {
guard !Task.isCancelled else { return }
downloadID = nil
Expand All @@ -231,6 +242,18 @@ final class AppUpdater: ObservableObject {
}
}

/// 通知の順序は保証されないため,進捗は増える方向にだけ更新する
private func applyProgress(_ value: Double?) {
// nil(サイズ不明)は開始時に設定済みなので,ここでは確定値だけを扱う.
// 確定値の後に nil へ戻すとバーがスピナーに戻ってしまうため無視する
guard let value else { return }
if let current = progress {
guard value > current else { return }
guard value >= 1 || value - current >= Self.progressReportStep else { return }
}
progress = value
}

func cancelDownload() {
guard case .downloading(let release) = state else { return }
operation?.cancel()
Expand Down Expand Up @@ -259,12 +282,49 @@ final class AppUpdater: ObservableObject {
}
}

private final class UpdateDownloadProgress: NSObject, URLSessionDownloadDelegate, @unchecked Sendable {
nonisolated let report: @Sendable (Double?) -> Void
nonisolated init(report: @escaping @Sendable (Double?) -> Void) { self.report = report }
nonisolated func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {}
nonisolated func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
report(totalBytesExpectedToWrite > 0 ? min(1, Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)) : nil)
/// Observes download progress from the created `URLSessionTask`.
///
/// Async `URLSession.download(for:delegate:)` only forwards `URLSessionTaskDelegate`
/// callbacks and skips `URLSessionDownloadDelegate.didWriteData`, so we observe `task.progress`.
private nonisolated final class UpdateDownloadProgress: NSObject, URLSessionTaskDelegate, @unchecked Sendable {
private let lock = NSLock()
private var observation: NSKeyValueObservation?
private let report: @Sendable (Double?) -> Void

init(report: @escaping @Sendable (Double?) -> Void) {
self.report = report
}

deinit {
invalidate()
}

func urlSession(_ session: URLSession, didCreateTask task: URLSessionTask) {
let report = self.report
let next = task.progress.observe(\.fractionCompleted, options: [.initial, .new]) { [weak task] progress, _ in
// 旧実装の totalBytesExpectedToWrite > 0 と同じく,応答の予定サイズで「サイズ不明」を判定する
let expectedBytes = task?.countOfBytesExpectedToReceive ?? 0
let fraction: Double? = expectedBytes > 0
? min(1, max(0, progress.fractionCompleted))
: nil
report(fraction)
}
let previous = lock.withLock { () -> NSKeyValueObservation? in
defer { observation = next }
return observation
}
previous?.invalidate()
}

func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
invalidate()
}

func invalidate() {
let current = lock.withLock { () -> NSKeyValueObservation? in
defer { observation = nil }
return observation
}
current?.invalidate()
}
}
76 changes: 70 additions & 6 deletions ArkServerTests/AppUpdaterTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -108,13 +108,59 @@ struct AppUpdaterTests {
#expect(AppRelease.trustedURL(URL(string: "https://github.com/HR0101/ArkServer/releases/download/v2/ArkServer.dmg")!, download: true))
}

private func fixture() throws -> (AppUpdater, UserDefaults, URLSession, String) {
@Test func downloadReportsProgressAndSavesDMG() async throws {
let directory = FileManager.default.temporaryDirectory.appendingPathComponent("UpdaterDownloadTests-\(UUID().uuidString)")
defer { try? FileManager.default.removeItem(at: directory) }
let (updater, defaults, session, suite) = try fixture(downloadsDirectory: directory)
defer { defaults.removePersistentDomain(forName: suite); session.invalidateAndCancel() }

let payload = Data(repeating: 0x5A, count: 64 * 1024)
UpdateMockProtocol.response = (200, payload, nil)
UpdateMockProtocol.chunkDelay = 0.03
defer { UpdateMockProtocol.chunkDelay = 0 }

let release = try JSONDecoder().decode(AppRelease.self, from: releaseJSON())
updater.download(release)

var observedProgress: [Double] = []
for _ in 0..<500 {
if let value = updater.progress {
observedProgress.append(value)
}
if !updater.isBusy { break }
try? await Task.sleep(for: .milliseconds(5))
}

guard case .downloaded(let savedURL) = updater.state else {
Issue.record("Expected downloaded state, got \(updater.state)")
return
}
#expect(savedURL.deletingLastPathComponent().resolvingSymlinksInPath() == directory.resolvingSymlinksInPath())
#expect(savedURL.lastPathComponent.hasPrefix("ArkServer-") && savedURL.pathExtension == "dmg")
#expect(try Data(contentsOf: savedURL) == payload)
#expect(!observedProgress.isEmpty)
#expect((observedProgress.last ?? 0) > 0)
}

private func fixture(downloadsDirectory: URL? = nil) throws -> (AppUpdater, UserDefaults, URLSession, String) {
let suite = "UpdaterTests-\(UUID().uuidString)"
let defaults = try #require(UserDefaults(suiteName: suite))
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [UpdateMockProtocol.self]
let session = URLSession(configuration: configuration)
return (AppUpdater(defaults: defaults, session: session, version: "1.0", build: "1", presentsWindows: false), defaults, session, suite)
return (
AppUpdater(
defaults: defaults,
session: session,
version: "1.0",
build: "1",
presentsWindows: false,
downloadsDirectory: downloadsDirectory
),
defaults,
session,
suite
)
}

private func finish(_ updater: AppUpdater) async {
Expand All @@ -136,15 +182,33 @@ struct AppUpdaterTests {

private final class UpdateMockProtocol: URLProtocol, @unchecked Sendable {
nonisolated(unsafe) static var response: (Int, Data, Error?) = (200, Data(), nil)
nonisolated(unsafe) static var chunkDelay: TimeInterval = 0
private let lock = NSLock()
private var isStopped = false

override class func canInit(with request: URLRequest) -> Bool { true }
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
override func startLoading() {
let (status, data, error) = Self.response
let delay = Self.chunkDelay
if let error { client?.urlProtocol(self, didFailWithError: error); return }
let response = HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: nil)!
let headers = delay > 0 && !data.isEmpty ? ["Content-Length": "\(data.count)"] : nil
let response = HTTPURLResponse(url: request.url!, statusCode: status, httpVersion: nil, headerFields: headers)!
client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
client?.urlProtocol(self, didLoad: data)
client?.urlProtocolDidFinishLoading(self)
guard delay > 0, data.count > 1 else {
client?.urlProtocol(self, didLoad: data)
client?.urlProtocolDidFinishLoading(self)
return
}
let split = data.count / 2
client?.urlProtocol(self, didLoad: data.prefix(split))
DispatchQueue.global().asyncAfter(deadline: .now() + delay) { [weak self] in
guard let self, self.lock.withLock({ !self.isStopped }) else { return }
self.client?.urlProtocol(self, didLoad: data.suffix(from: split))
self.client?.urlProtocolDidFinishLoading(self)
}
}
override func stopLoading() {
lock.withLock { isStopped = true }
}
override func stopLoading() {}
}
Loading