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.

Tell a feed that drops the connection from a Mac that isn't online

Țugui Dragoș681d0b750640
diff --git a/Packages/PeelCore/Sources/PeelCore/Updates/NetworkPath.swift b/Packages/PeelCore/Sources/PeelCore/Updates/NetworkPath.swift
new file mode 100644
index 00000000..12340abe
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCore/Updates/NetworkPath.swift
@@ -0,0 +1,27 @@
+import Foundation
+import Network
+import Synchronization
+
+enum NetworkPath {
+ /// The first path the framework reports, or true when none comes within a second, so a check never waits on it.
+ @concurrent
+ static func isOnline() async -> Bool {
+ let monitor = NWPathMonitor()
+ let queue = DispatchQueue(label: "Peel.NetworkPath", qos: .userInitiated)
+ let isOnline = await withCheckedContinuation { (continuation: CheckedContinuation<Bool, Never>) in
+ let answered = Mutex(false)
+ let answer = { @Sendable (isOnline: Bool) in
+ guard answered.withLock({ wasAnswered in
+ defer { wasAnswered = true }
+ return !wasAnswered
+ }) else { return }
+ continuation.resume(returning: isOnline)
+ }
+ monitor.pathUpdateHandler = { answer($0.status == .satisfied) }
+ monitor.start(queue: queue)
+ queue.asyncAfter(deadline: .now() + 1) { answer(true) }
+ }
+ monitor.cancel()
+ return isOnline
+ }
+}
diff --git a/Packages/PeelCore/Sources/PeelCore/Updates/UpdateChecker.swift b/Packages/PeelCore/Sources/PeelCore/Updates/UpdateChecker.swift
index c252dae3..949efbb7 100644
--- a/Packages/PeelCore/Sources/PeelCore/Updates/UpdateChecker.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Updates/UpdateChecker.swift
@@ -36,6 +36,7 @@ public struct UpdateChecker: Sendable {
private let isAppleSilicon = HostArchitecture.isAppleSilicon
/// The time a check is made at, which decides whether what Homebrew says is recent enough to count.
private let clock: @Sendable () -> Date
+ private let isOnline: @Sendable () async -> Bool
public init(
session: URLSession? = nil, locale: Locale = .current, clock: @escaping @Sendable () -> Date = { .now }
@@ -45,11 +46,12 @@ public struct UpdateChecker: Sendable {
init(
session: URLSession? = nil, locale: Locale = .current, clock: @escaping @Sendable () -> Date = { .now },
- appStoreWindow: RequestWindow
+ appStoreWindow: RequestWindow, isOnline: @escaping @Sendable () async -> Bool = NetworkPath.isOnline
) {
self.session = session ?? URLSession(configuration: Self.configuration)
self.appStoreWindow = appStoreWindow
self.clock = clock
+ self.isOnline = isOnline
country = Self.storefront(of: locale)
let version = ProcessInfo.processInfo.operatingSystemVersion
systemVersion = "\(version.majorVersion).\(version.minorVersion).\(version.patchVersion)"
@@ -332,11 +334,11 @@ public struct UpdateChecker: Sendable {
}
- /// The errors that mean this Mac isn't online rather than that the server failed.
+ /// The errors only a Mac that isn't online gets. Any other, such as a connection lost, which a server that closes
+ /// it without answering gives too, means so only while this Mac has no network path.
static func meansOffline(_ error: any Error) -> Bool {
guard let error = error as? URLError else { return false }
- return [.notConnectedToInternet, .networkConnectionLost, .dataNotAllowed, .internationalRoamingOff]
- .contains(error.code)
+ return [.notConnectedToInternet, .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
@@ -430,7 +432,8 @@ public struct UpdateChecker: Sendable {
do {
(stream, response) = try await session.bytes(for: request, delegate: delegate)
} catch {
- return Reply(wasOffline: delegate.waitedForConnectivity || Self.meansOffline(error))
+ let isOffline = delegate.waitedForConnectivity || Self.meansOffline(error)
+ return Reply(wasOffline: isOffline ? true : !(await isOnline()))
}
let status = (response as? HTTPURLResponse)?.statusCode
var answer = Reply(status: status, mimeType: response.mimeType, textEncodingName: response.textEncodingName)
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/UpdateCheckerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/UpdateCheckerTests.swift
index b783e4bb..6cd42713 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/UpdateCheckerTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/UpdateCheckerTests.swift
@@ -50,6 +50,17 @@ private final class OfflineProtocol: URLProtocol, @unchecked Sendable {
}
}
+/// Fails every request as a server that closes the connection without answering does.
+private final class DroppedProtocol: 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(.networkConnectionLost))
+ }
+}
+
/// The part of the update check that talks to the network, against replies written here.
@Suite(.serialized) struct UpdateCheckerTests {
private var checker: UpdateChecker {
@@ -58,6 +69,36 @@ private final class OfflineProtocol: URLProtocol, @unchecked Sendable {
return UpdateChecker(session: URLSession(configuration: configuration), appStoreWindow: .forTheAppStore())
}
+ @Test func aServerThatDropsTheConnectionIsNoMacOffline() async {
+ let configuration = URLSessionConfiguration.ephemeral
+ configuration.protocolClasses = [DroppedProtocol.self]
+ let checker = { (isOnline: Bool) in
+ UpdateChecker(
+ session: URLSession(configuration: configuration), appStoreWindow: .forTheAppStore(),
+ isOnline: { isOnline }
+ )
+ }
+ 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 dropped = await checker(true).answer(for: app)
+ let lost = await checker(false).answer(for: app)
+
+ #expect(dropped.status == .failed && !dropped.wasOffline)
+ #expect(lost.status == .failed && lost.wasOffline)
+ }
+
+ @Test func knowsWhetherThisMacHasANetworkWithinASecond() async {
+ let clock = ContinuousClock()
+ let started = clock.now
+
+ _ = await NetworkPath.isOnline()
+
+ #expect(clock.now - started < .seconds(2))
+ }
+
@Test func aCheckFromAMacThatIsntOnlineLearnsNothing() async {
let configuration = URLSessionConfiguration.ephemeral
configuration.protocolClasses = [OfflineProtocol.self]