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.

Ask the App Store no faster than Apple's lookup allows

Țugui Dragoș7a0b9322c71a
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index 9940d292..ad4f14f2 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -337,7 +337,8 @@ macOS asks the user to approve it once. It talks to the app over XPC.
Homebrew no longer reports is forgotten then, and Peel reads Homebrew again once it has checked since. From the App
Store it reads the listing of the installed bundle (`AppStoreListing`): the Mac's, which Apple gives for the desktop,
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. An app that came with macOS or from Setapp gets no feed (`UpdateFeed.detect`, `InstalledApp.isFromSetapp`):
+ 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
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 939753d1..e8f661fb 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -73,6 +73,8 @@ its changes the way [Keep a Changelog](https://keepachangelog.com/) suggests.
#### Applications
+- Applications and `peel updates` ask the App Store about at most 20 apps a minute, the pace Apple documents for its
+ lookup, so a Mac with many apps from the App Store is checked within it rather than all at once.
- Rescan asks about every app's updates again at once, whatever each one's schedule says.
- Peel reads Homebrew again once Homebrew has checked for new versions since Peel last read it, as after `brew update`
in Terminal.
diff --git a/Packages/PeelCore/Sources/PeelCore/Updates/RequestWindow.swift b/Packages/PeelCore/Sources/PeelCore/Updates/RequestWindow.swift
new file mode 100644
index 00000000..3323759d
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCore/Updates/RequestWindow.swift
@@ -0,0 +1,35 @@
+import Foundation
+
+/// The pace of requests to one server: at most `limit` of them in any `window`, each waiting its turn. Apple says its
+/// lookup "is limited to approximately 20 calls per minute", so a process asks the App Store no faster (`appStore`).
+actor RequestWindow {
+ /// The App Store's, which every check in the process shares.
+ static let appStore = forTheAppStore()
+
+ /// A window at the pace Apple gives for its lookup.
+ static func forTheAppStore() -> RequestWindow {
+ RequestWindow(limit: 20, window: .seconds(60))
+ }
+
+ private let limit: Int
+ private let window: Duration
+ private var sent: [ContinuousClock.Instant] = []
+
+ init(limit: Int, window: Duration) {
+ self.limit = limit
+ self.window = window
+ }
+
+ /// Waits until a request may go, and counts it. A canceled wait throws, so nothing goes and nothing is counted.
+ func turn() async throws {
+ while true {
+ let now = ContinuousClock.now
+ sent.removeAll { now - $0 >= window }
+ if sent.count < limit {
+ sent.append(now)
+ return
+ }
+ try await Task.sleep(until: sent[0] + window, clock: .continuous)
+ }
+ }
+}
diff --git a/Packages/PeelCore/Sources/PeelCore/Updates/UpdateChecker.swift b/Packages/PeelCore/Sources/PeelCore/Updates/UpdateChecker.swift
index d7c76d01..4b85764d 100644
--- a/Packages/PeelCore/Sources/PeelCore/Updates/UpdateChecker.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Updates/UpdateChecker.swift
@@ -27,6 +27,8 @@ public struct UpdateChecker: Sendable {
}
private let session: URLSession
+ /// The pace of requests to the App Store, which the process shares.
+ private let appStoreWindow: RequestWindow
private let country: String
private let systemVersion: String
private let isAppleSilicon = HostArchitecture.isAppleSilicon
@@ -35,8 +37,16 @@ public struct UpdateChecker: Sendable {
public init(
session: URLSession? = nil, locale: Locale = .current, clock: @escaping @Sendable () -> Date = { .now }
+ ) {
+ self.init(session: session, locale: locale, clock: clock, appStoreWindow: .appStore)
+ }
+
+ init(
+ session: URLSession? = nil, locale: Locale = .current, clock: @escaping @Sendable () -> Date = { .now },
+ appStoreWindow: RequestWindow
) {
self.session = session ?? URLSession(configuration: Self.configuration)
+ self.appStoreWindow = appStoreWindow
self.clock = clock
country = Self.storefront(of: locale)
let version = ProcessInfo.processInfo.operatingSystemVersion
@@ -240,10 +250,12 @@ public struct UpdateChecker: Sendable {
}
}
+ /// Asks the App Store once the process's window of requests to it lets: a check that is canceled meanwhile asks
+ /// nothing.
private func lookup(_ identifier: String, in country: String, for listing: AppStoreListing) async -> Reply {
- guard let url = AppStoreLookup.url(bundleIdentifier: identifier, country: country, for: listing) else {
- return Reply()
- }
+ guard let url = AppStoreLookup.url(bundleIdentifier: identifier, country: country, for: listing),
+ (try? await appStoreWindow.turn()) != nil
+ else { return Reply() }
return await fetchReply(url)
}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/UpdateCheckerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/UpdateCheckerTests.swift
index 8d55f325..856275ea 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/UpdateCheckerTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/UpdateCheckerTests.swift
@@ -14,6 +14,7 @@ private final class CannedProtocol: URLProtocol, @unchecked Sendable {
static let replies = Mutex<[String: Reply]>([:])
static let asked = Mutex<[String]>([])
static let addresses = Mutex<[String]>([])
+ static let times = Mutex<[ContinuousClock.Instant]>([])
override class func canInit(with request: URLRequest) -> Bool { true }
override class func canonicalRequest(for request: URLRequest) -> URLRequest { request }
@@ -22,6 +23,7 @@ private final class CannedProtocol: URLProtocol, @unchecked Sendable {
override func startLoading() {
let host = request.url?.host() ?? ""
Self.asked.withLock { $0.append(host) }
+ Self.times.withLock { $0.append(.now) }
Self.addresses.withLock { $0.append(request.url?.absoluteString ?? "") }
guard let reply = Self.replies.withLock({ $0[host] }), let url = request.url,
let response = HTTPURLResponse(
@@ -42,7 +44,7 @@ private final class CannedProtocol: URLProtocol, @unchecked Sendable {
private var checker: UpdateChecker {
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [CannedProtocol.self]
- return UpdateChecker(session: URLSession(configuration: configuration))
+ return UpdateChecker(session: URLSession(configuration: configuration), appStoreWindow: .forTheAppStore())
}
/// Apple's lookup answers HTTP 400 for a region with no store, such as `150` (Europe), `001` (the world), or
@@ -59,7 +61,10 @@ private final class CannedProtocol: URLProtocol, @unchecked Sendable {
@Test func aRefusedStoreIsAskedOnceMoreAsTheUnitedStates() async {
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [CannedProtocol.self]
- let antarctic = UpdateChecker(session: URLSession(configuration: configuration), locale: Locale(identifier: "en_AQ"))
+ let antarctic = UpdateChecker(
+ session: URLSession(configuration: configuration), locale: Locale(identifier: "en_AQ"),
+ appStoreWindow: .forTheAppStore()
+ )
let sold = InstalledApp(
url: URL(filePath: "/Applications/Notes Pro.app"),
bundleIdentifier: "com.example.notes",
@@ -128,6 +133,35 @@ private final class CannedProtocol: URLProtocol, @unchecked Sendable {
#expect(CannedProtocol.asked.withLock { $0 } == ["feed.example.com"])
}
+ @Test func asksTheAppStoreNoFasterThanItsWindowLets() async {
+ CannedProtocol.replies.withLock {
+ $0 = ["itunes.apple.com": .init(body: Data(#"{"resultCount":0,"results":[]}"#.utf8))]
+ }
+ CannedProtocol.times.withLock { $0 = [] }
+ let configuration = URLSessionConfiguration.ephemeral
+ configuration.protocolClasses = [CannedProtocol.self]
+ let checker = UpdateChecker(
+ session: URLSession(configuration: configuration),
+ appStoreWindow: RequestWindow(limit: 2, window: .milliseconds(600))
+ )
+ let apps = (1...3).map { index in
+ InstalledApp(
+ url: URL(filePath: "/Applications/Store \(index).app"), bundleIdentifier: "org.example.store\(index)",
+ name: "Store \(index)", version: "1.0", isFromAppStore: true, updateFeed: .appStore(.mac)
+ )
+ }
+
+ await withTaskGroup(of: Void.self) { group in
+ for app in apps {
+ group.addTask { _ = await checker.status(for: app, preference: .appStore) }
+ }
+ }
+
+ let times = CannedProtocol.times.withLock { $0 }.sorted()
+ #expect(times.count == 3)
+ #expect(times.count == 3 && times[2] - times[0] >= .milliseconds(400), "\(times)")
+ }
+
/// Only a 200 is an answer, and what is not an appcast is a failed check.
@Test func readsOnlyAProperAnswer() async {
reply("feed.example.com", status: 404, appcast("<item><sparkle:version>999</sparkle:version></item>"))
@@ -159,7 +193,9 @@ private final class CannedProtocol: URLProtocol, @unchecked Sendable {
private func checking(at now: Date) -> UpdateChecker {
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [CannedProtocol.self]
- return UpdateChecker(session: URLSession(configuration: configuration), clock: { now })
+ return UpdateChecker(
+ session: URLSession(configuration: configuration), clock: { now }, appStoreWindow: .forTheAppStore()
+ )
}
private var feedlessApp: InstalledApp {
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/UpdatePrivacyTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/UpdatePrivacyTests.swift
index 36f6aa27..0a70fbd9 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/UpdatePrivacyTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/UpdatePrivacyTests.swift
@@ -102,7 +102,7 @@ private final class OneRequestServer: Sendable {
private var checker: UpdateChecker {
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [RecordingProtocol.self]
- return UpdateChecker(session: URLSession(configuration: configuration))
+ return UpdateChecker(session: URLSession(configuration: configuration), appStoreWindow: .forTheAppStore())
}
@Test func asksAppleOnlyAboutAnAppItSold() async {