Skip to content

armgit / peel

Public Imported from GitHub
0

Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.

Don't count an update check made offline as a failed one

Țugui Dragoșc4ed467a1836
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 69c6b149..b3b086ab 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -352,11 +352,13 @@ macOS asks the user to approve it once. It talks to the app over XPC.
also for an app sold once for iPhone and Mac, or the iPhone and iPad one for an app of those devices installed on the
Mac, at most 20 lookups in any minute in a process, the pace Apple documents for its lookup (`RequestWindow`). An
app that came with macOS or from Setapp gets no feed (`UpdateFeed.detect`, `InstalledApp.isFromSetapp`):
- Software Update and Setapp keep them current, whatever feed the bundle carries. Every answer that changes nothing
- makes the next check of that app wait longer, up to a week (`UpdateSchedule`), and `UpdateMemory` keeps the last
- answer across launches, with the revision of the checker that gave it (`UpdateChecker.revision`): an answer an
- earlier revision gave about an app it couldn't check, or about one this revision asks nobody about, is dropped, so
- the app is asked again at the next round.
+ Software Update and Setapp keep them current, whatever feed the bundle carries. A check waits up to 30 seconds for
+ a Mac just awake to go online, and one made while it isn't online counts for nothing (`UpdateAnswer.wasOffline`):
+ what was known stays and the app is asked at the next round. Every answer that changes nothing makes the next check
+ of that app wait longer, up to a week (`UpdateSchedule`), and `UpdateMemory` keeps the last answer across launches,
+ with the revision of the checker that gave it (`UpdateChecker.revision`): an answer an earlier revision gave about
+ an app it couldn't check, or about one this revision asks nobody about, is dropped, so the app is asked again at
+ the next round.
- **Orphaned Files.** `OrphanScanner` lists what no installed app claims, under the app Peel saw go when it can
name it (`AppMemory`), and selects nothing for the person. An app macOS knows on another disk that claims something
is remembered too (`OrphanScan.appsOnOtherDisks`, `Disks`), so its files stay its own while that disk isn't
diff --git a/Packages/PeelCore/Sources/PeelCore/Updates/UpdateChecker.swift b/Packages/PeelCore/Sources/PeelCore/Updates/UpdateChecker.swift
index 23c3869c..7a5272d0 100644
--- a/Packages/PeelCore/Sources/PeelCore/Updates/UpdateChecker.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Updates/UpdateChecker.swift
@@ -1,4 +1,5 @@
public import Foundation
+import Synchronization
public struct UpdateChecker: Sendable {
/// Raised whenever the checker answers some apps differently: an app an earlier revision couldn't check is asked
@@ -17,6 +18,8 @@ public struct UpdateChecker: Sendable {
let configuration = URLSessionConfiguration.ephemeral
configuration.timeoutIntervalForRequest = 15
configuration.timeoutIntervalForResource = 30
+ // A Mac just awake from sleep has no network for a few seconds, and a check made then would fail at once.
+ configuration.waitsForConnectivity = true
configuration.httpCookieStorage = nil
configuration.httpShouldSetCookies = false
configuration.httpCookieAcceptPolicy = .never
@@ -88,6 +91,7 @@ public struct UpdateChecker: Sendable {
// checked through its own feed, or not at all.
let own = preference == .appStore && app.isFromAppStore
? await appStoreAnswer(for: app, earlier: earlier) : await feedAnswer(for: app, earlier: earlier)
+ guard !own.wasOffline else { return own }
// A feed can be down, and the App Store may not sell the app here: what Homebrew knows is used then.
if let homebrew, own.status == .unsupported || own.status == .failed {
return UpdateAnswer(status: homebrew, developer: own.developer, standsInFor: own.status)
@@ -177,7 +181,8 @@ public struct UpdateChecker: Sendable {
}
private func sparkleAnswer(for app: InstalledApp, installed: String, at url: URL) async -> UpdateAnswer {
- guard let data = await fetch(url) else { return UpdateAnswer(status: .failed) }
+ let reply = await fetchReply(url)
+ guard let data = reply.data else { return UpdateAnswer(status: .failed, wasOffline: reply.wasOffline) }
let item: AppcastItem
switch Appcast.read(data, systemVersion: systemVersion, isAppleSilicon: isAppleSilicon) {
case .unreadable: return UpdateAnswer(status: .failed)
@@ -199,7 +204,8 @@ public struct UpdateChecker: Sendable {
}
private func electronAnswer(installed: String, at url: URL) async -> UpdateAnswer {
- guard let data = await fetch(url) else { return UpdateAnswer(status: .failed) }
+ let reply = await fetchReply(url)
+ guard let data = reply.data else { return UpdateAnswer(status: .failed, wasOffline: reply.wasOffline) }
let feed = String(decoding: data, as: UTF8.self)
guard let latest = ElectronUpdater.version(fromFeed: feed) else { return UpdateAnswer(status: .failed) }
guard VersionComparison.isNewer(latest, than: installed) else { return UpdateAnswer(status: .upToDate) }
@@ -222,7 +228,7 @@ public struct UpdateChecker: Sendable {
if reply.status == 400, store != "us" {
reply = await lookup(identifier, in: "us", for: listing)
}
- guard let data = reply.data else { return UpdateAnswer(status: .failed) }
+ guard let data = reply.data else { return UpdateAnswer(status: .failed, wasOffline: reply.wasOffline) }
switch AppStoreLookup.answer(in: data, for: listing) {
case .unreadable:
return UpdateAnswer(status: .failed)
@@ -259,6 +265,13 @@ public struct UpdateChecker: Sendable {
await fetchReply(url).data
}
+ /// The errors that mean this Mac isn't online rather than that the server failed.
+ static func meansOffline(_ error: any Error) -> Bool {
+ guard let error = error as? URLError else { return false }
+ return [.notConnectedToInternet, .networkConnectionLost, .dataNotAllowed, .internationalRoamingOff]
+ .contains(error.code)
+ }
+
/// What is new in the update `answer` found, asked of the app's own addresses when the answer does not say: the
/// notes page its feed names, or, for an update Homebrew found, the app's own feed. Nothing else is asked: a
/// product page, a store page or a cask's homepage is a link to show, not notes to read.
@@ -326,12 +339,20 @@ public struct UpdateChecker: Sendable {
var status: Int?
var mimeType: String?
var textEncodingName: String?
+ /// True when this Mac wasn't online, so no server was asked.
+ var wasOffline = false
}
private func fetchReply(_ url: URL) async -> Reply {
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 15)
- let reply = try? await session.bytes(for: request, delegate: SecureRedirects())
- guard let (stream, response) = reply else { return Reply() }
+ let delegate = SecureRedirects()
+ let stream: URLSession.AsyncBytes
+ let response: URLResponse
+ do {
+ (stream, response) = try await session.bytes(for: request, delegate: delegate)
+ } catch {
+ return Reply(wasOffline: delegate.waitedForConnectivity || Self.meansOffline(error))
+ }
let status = (response as? HTTPURLResponse)?.statusCode
var answer = Reply(status: status, mimeType: response.mimeType, textEncodingName: response.textEncodingName)
guard status == 200, response.expectedContentLength <= Self.maximumFeedBytes else { return answer }
@@ -357,13 +378,22 @@ public struct UpdateChecker: Sendable {
/// Follows a redirect only to another https address. Every address an update check asks is https, while App
/// Transport Security still lets plain http reach this Mac and its local network, so a feed server could otherwise
/// send the check to a service there.
-private final class SecureRedirects: NSObject, URLSessionTaskDelegate {
+private final class SecureRedirects: NSObject, URLSessionTaskDelegate, Sendable {
+ private let waited = Mutex(false)
+
+ /// True once the request waited for this Mac to go online.
+ var waitedForConnectivity: Bool { waited.withLock { $0 } }
+
func urlSession(
_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest, completionHandler: @escaping @Sendable (URLRequest?) -> Void
) {
completionHandler(request.url?.scheme == "https" ? request : nil)
}
+
+ func urlSession(_ session: URLSession, taskIsWaitingForConnectivity task: URLSessionTask) {
+ waited.withLock { $0 = true }
+ }
}
/// The result of one update check. `developer` is set only when the App Store answered.
@@ -377,19 +407,23 @@ public struct UpdateAnswer: Sendable, Hashable {
/// What the app's own feed or the App Store answered, `.failed` or `.unsupported`, when `status` is Homebrew's
/// answer in its place.
public let standsInFor: UpdateStatus?
+ /// True when this Mac wasn't online, so the check learned nothing about the app.
+ public let wasOffline: Bool
public init(
status: UpdateStatus,
developer: String? = nil,
notes: ReleaseNotes? = nil,
notesPage: URL? = nil,
- standsInFor: UpdateStatus? = nil
+ standsInFor: UpdateStatus? = nil,
+ wasOffline: Bool = false
) {
self.status = status
self.developer = developer
self.notes = notes
self.notesPage = notesPage
self.standsInFor = standsInFor
+ self.wasOffline = wasOffline
}
/// The status to keep after `previous`: a check whose own source failed keeps an update that source found earlier,
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/UpdateCheckerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/UpdateCheckerTests.swift
index 856275ea..27161b7d 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/UpdateCheckerTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/UpdateCheckerTests.swift
@@ -39,6 +39,17 @@ private final class CannedProtocol: URLProtocol, @unchecked Sendable {
}
}
+/// Fails every request as macOS does when this Mac isn't online.
+private final class OfflineProtocol: URLProtocol, @unchecked Sendable {
+ override class func canInit(with request: URLRequest) -> Bool { true }
+ override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
+ override func stopLoading() {}
+
+ override func startLoading() {
+ client?.urlProtocol(self, didFailWithError: URLError(.notConnectedToInternet))
+ }
+}
+
/// The part of the update check that talks to the network, against replies written here.
@Suite(.serialized) struct UpdateCheckerTests {
private var checker: UpdateChecker {
@@ -47,6 +58,25 @@ private final class CannedProtocol: URLProtocol, @unchecked Sendable {
return UpdateChecker(session: URLSession(configuration: configuration), appStoreWindow: .forTheAppStore())
}
+ @Test func aCheckFromAMacThatIsntOnlineLearnsNothing() async {
+ let configuration = URLSessionConfiguration.ephemeral
+ configuration.protocolClasses = [OfflineProtocol.self]
+ let offline = UpdateChecker(
+ session: URLSession(configuration: configuration), appStoreWindow: .forTheAppStore()
+ )
+ let app = InstalledApp(
+ url: URL(filePath: "/Applications/Fed.app"), bundleIdentifier: "org.example.fed", name: "Fed",
+ version: "1.0", updateFeed: .sparkle(URL(string: "https://feed.example.com/appcast.xml")!)
+ )
+
+ let away = await offline.answer(for: app)
+ let down = await checker.answer(for: app)
+
+ #expect(away.status == .failed && away.wasOffline)
+ #expect(down.status == .failed && !down.wasOffline)
+ #expect(UpdateChecker.configuration.waitsForConnectivity)
+ }
+
/// Apple's lookup answers HTTP 400 for a region with no store, such as `150` (Europe), `001` (the world), or
/// `AQ`. A region that is not two letters, or no region at all, asks the US store.
@Test func asksAStoreThatExists() {
diff --git a/Peel/Model/AppLibrary.swift b/Peel/Model/AppLibrary.swift
index 2541985e..a3d07f08 100644
--- a/Peel/Model/AppLibrary.swift
+++ b/Peel/Model/AppLibrary.swift
@@ -580,8 +580,9 @@ final class AppLibrary {
}
}
// In a canceled round every pending request ends as a failure. Recording those would erase
- // what was known and put off the next check for hours.
- guard !Task.isCancelled else { continue }
+ // what was known and put off the next check for hours, and so would recording a check made while
+ // this Mac wasn't online, which leaves the app due at the next round.
+ guard !Task.isCancelled, !answer.wasOffline else { continue }
// The answer describes the build that was asked about, which may have been replaced since.
guard let app = asked[id], apps.contains(where: { $0.id == id && $0.isTheSameBuild(as: app) }) else {
continue
diff --git a/PeelTests/AppLibraryTests.swift b/PeelTests/AppLibraryTests.swift
index 30a00d78..c372a22d 100644
--- a/PeelTests/AppLibraryTests.swift
+++ b/PeelTests/AppLibraryTests.swift
@@ -42,6 +42,27 @@ private nonisolated final class HeldProtocol: URLProtocol, @unchecked Sendable {
}
}
+private nonisolated final class SometimesOfflineProtocol: URLProtocol, @unchecked Sendable {
+ static let isOffline = Mutex(false)
+ static let body = Mutex(Data())
+
+ override class func canInit(with request: URLRequest) -> Bool { true }
+ override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
+ override func stopLoading() {}
+
+ override func startLoading() {
+ guard !Self.isOffline.withLock({ $0 }), let url = request.url,
+ let response = HTTPURLResponse(url: url, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: nil)
+ else {
+ client?.urlProtocol(self, didFailWithError: URLError(.notConnectedToInternet))
+ return
+ }
+ client?.urlProtocol(self, didReceive: response, cacheStoragePolicy: .notAllowed)
+ client?.urlProtocol(self, didLoad: Self.body.withLock { $0 })
+ client?.urlProtocolDidFinishLoading(self)
+ }
+}
+
private nonisolated final class TestClock: Sendable {
private let moment: Mutex<Date>
@@ -405,6 +426,31 @@ private nonisolated final class TestClock: Sendable {
#expect(library.hasUpdate(last), "the eighth app was asked once the first seven left the list")
}
+ @Test func aRoundWhileThisMacIsntOnlineKeepsWhatWasKnown() async throws {
+ let folder = FileManager.default.temporaryDirectory.appending(path: "PeelTests-\(UUID().uuidString)")
+ let bundle = try caskApp("Fed", in: folder, feed: "https://feed.example.com/appcast.xml")
+ defer { try? FileManager.default.removeItem(at: folder) }
+ let made = try MadeUpDefaults()
+ defer { made.forget() }
+ SometimesOfflineProtocol.body.withLock {
+ $0 = Data(#"<rss xmlns:sparkle="http://www.andymatuschak.org/xml-namespaces/sparkle"><channel><item><enclosure url="https://feed.example.com/u.zip" sparkle:version="100" sparkle:shortVersionString="1.0" /></item></channel></rss>"#.utf8)
+ }
+ SometimesOfflineProtocol.isOffline.withLock { $0 = false }
+ defer { SometimesOfflineProtocol.isOffline.withLock { $0 = false } }
+ let library = library(with: made.defaults, notesIn: folder, answeredBy: SometimesOfflineProtocol.self)
+ #expect(await library.reveal([bundle]))
+ let app = try #require(library.apps.first { $0.bundleIdentifier == "org.example.fed" })
+ await library.checkForUpdates([app], force: true)
+ let known = made.defaults.data(forKey: SettingsKey.updateMemory)
+ #expect(library.shownUpdateStatus(of: app) == .upToDate)
+
+ SometimesOfflineProtocol.isOffline.withLock { $0 = true }
+ await library.checkForUpdates([app], force: true)
+
+ #expect(library.shownUpdateStatus(of: app) == .upToDate)
+ #expect(made.defaults.data(forKey: SettingsKey.updateMemory) == known, "nothing learned, nothing put off")
+ }
+
@Test func anAppPeelNeverChecksGetsNothingFromHomebrew() async throws {
let folder = FileManager.default.temporaryDirectory.appending(path: "PeelTests-\(UUID().uuidString)")
let bundle = try caskApp("Tool", in: folder)