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.

The helper counts a connection from the moment it arrives

Țugui Dragoș968da7fad46c
diff --git a/PeelHelper/HelperLifetime.swift b/Packages/PeelCore/Sources/PeelPrivileged/HelperLifetime.swift
similarity index 53%
rename from PeelHelper/HelperLifetime.swift
rename to Packages/PeelCore/Sources/PeelPrivileged/HelperLifetime.swift
index ff9697cf..c2a3053a 100644
--- a/PeelHelper/HelperLifetime.swift
+++ b/Packages/PeelCore/Sources/PeelPrivileged/HelperLifetime.swift
@@ -3,33 +3,61 @@ import Synchronization
/// Exits the helper after `idleTimeout` seconds with no open connection and no running request.
/// launchd starts it again on the next request.
-final class HelperLifetime: Sendable {
- private static let idleTimeout: TimeInterval = 30
-
+public final class HelperLifetime: Sendable {
+ private let idleTimeout: TimeInterval
+ private let schedule: @Sendable (TimeInterval, @escaping @Sendable () -> Void) -> Void
+ private let exit: @Sendable () -> Void
private let state = Mutex((activeConnections: 0, requestsInFlight: 0, generation: 0))
- func start() {
+ public convenience init() {
+ self.init(
+ idleTimeout: 30,
+ schedule: { delay, work in DispatchQueue.global().asyncAfter(deadline: .now() + delay, execute: work) },
+ // `_exit`, not `exit`: `exit` would first run `atexit` handlers, while the helper's other threads keep
+ // running.
+ exit: { _exit(EXIT_SUCCESS) }
+ )
+ }
+
+ init(
+ idleTimeout: TimeInterval,
+ schedule: @escaping @Sendable (TimeInterval, @escaping @Sendable () -> Void) -> Void,
+ exit: @escaping @Sendable () -> Void
+ ) {
+ self.idleTimeout = idleTimeout
+ self.schedule = schedule
+ self.exit = exit
+ }
+
+ public func start() {
scheduleExitIfIdle(generation: 0)
}
- func connectionOpened() {
+ /// Accepts a connection when `isAllowed` answers yes, and counts it until `connectionClosed()`. It is counted
+ /// before `isAllowed` is asked, since that can take a while and the helper must not exit meanwhile.
+ public func accept(_ isAllowed: () -> Bool) -> Bool {
state.withLock { state in
state.activeConnections += 1
state.generation += 1
}
+ guard isAllowed() else {
+ connectionClosed()
+ return false
+ }
+ return true
}
/// Counts a request as running until `requestFinished()`. The connection count alone is not enough: a
/// client that goes away in the middle of a batch drops it to zero while the work is still running, and
/// a single `launchctl bootout` can take half a minute.
- func requestStarted() {
+ public func requestStarted() {
state.withLock { state in
state.requestsInFlight += 1
state.generation += 1
}
}
- func requestFinished() {
+ public func requestFinished() {
let generation = state.withLock { state in
state.requestsInFlight -= 1
state.generation += 1
@@ -38,7 +66,7 @@ final class HelperLifetime: Sendable {
scheduleExitIfIdle(generation: generation)
}
- func connectionClosed() {
+ public func connectionClosed() {
let generation = state.withLock { state in
state.activeConnections -= 1
state.generation += 1
@@ -51,12 +79,10 @@ final class HelperLifetime: Sendable {
/// has changed since `generation`. The check and the exit happen under one lock, so no connection can open
/// between them and have its work cut off.
private func scheduleExitIfIdle(generation: Int) {
- DispatchQueue.global().asyncAfter(deadline: .now() + Self.idleTimeout) {
- self.state.withLock { state in
+ schedule(idleTimeout) { [self] in
+ state.withLock { state in
if state.activeConnections == 0, state.requestsInFlight == 0, state.generation == generation {
- // `_exit`, not `exit`: `exit` would first run `atexit` handlers, while the helper's other
- // threads keep running.
- _exit(EXIT_SUCCESS)
+ exit()
}
}
}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/HelperLifetimeTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/HelperLifetimeTests.swift
new file mode 100644
index 00000000..aeb72533
--- /dev/null
+++ b/Packages/PeelCore/Tests/PeelCoreTests/HelperLifetimeTests.swift
@@ -0,0 +1,83 @@
+import Foundation
+@testable import PeelPrivileged
+import Synchronization
+import Testing
+
+struct HelperLifetimeTests {
+ /// Holds each scheduled idle check until the test runs it, so the order is the test's and never the clock's.
+ private final class Clock: Sendable {
+ private let pending = Mutex<[@Sendable () -> Void]>([])
+ let exits = Mutex(0)
+
+ func lifetime() -> HelperLifetime {
+ HelperLifetime(
+ idleTimeout: 30,
+ schedule: { [self] _, work in pending.withLock { $0.append(work) } },
+ exit: { [self] in exits.withLock { $0 += 1 } }
+ )
+ }
+
+ func runChecks() {
+ let due = pending.withLock { pending in
+ defer { pending = [] }
+ return pending
+ }
+ due.forEach { $0() }
+ }
+
+ var exitCount: Int { exits.withLock { $0 } }
+ }
+
+ @Test func exitsWhenNothingHappensAfterItStarts() {
+ let clock = Clock()
+ clock.lifetime().start()
+ clock.runChecks()
+ #expect(clock.exitCount == 1)
+ }
+
+ @Test func staysWhileARequestRunsAndExitsAfterIt() {
+ let clock = Clock()
+ let lifetime = clock.lifetime()
+ lifetime.start()
+ lifetime.requestStarted()
+ clock.runChecks()
+ #expect(clock.exitCount == 0)
+
+ lifetime.requestFinished()
+ clock.runChecks()
+ #expect(clock.exitCount == 1)
+ }
+
+ @Test func staysWhileAConnectionIsBeingAccepted() {
+ let clock = Clock()
+ let lifetime = clock.lifetime()
+ lifetime.start()
+
+ let accepted = lifetime.accept {
+ clock.runChecks()
+ return true
+ }
+
+ #expect(accepted)
+ #expect(clock.exitCount == 0, "the helper exited while it was accepting a connection")
+ lifetime.connectionClosed()
+ clock.runChecks()
+ #expect(clock.exitCount == 1)
+ }
+
+ @Test func aRefusedConnectionLeavesTheHelperFreeToExit() {
+ let clock = Clock()
+ let lifetime = clock.lifetime()
+ lifetime.start()
+
+ let accepted = lifetime.accept {
+ clock.runChecks()
+ return false
+ }
+
+ #expect(!accepted)
+ #expect(clock.exitCount == 0, "the helper exited while it was asking about a connection")
+ clock.runChecks()
+ #expect(clock.exitCount == 1, "a refused connection kept the helper running")
+ }
+}
diff --git a/PeelHelper/HelperListenerDelegate.swift b/PeelHelper/HelperListenerDelegate.swift
index 814dc8f1..7772a7d2 100644
--- a/PeelHelper/HelperListenerDelegate.swift
+++ b/PeelHelper/HelperListenerDelegate.swift
@@ -9,11 +9,11 @@ final class HelperListenerDelegate: NSObject, NSXPCListenerDelegate {
}
func listener(_ listener: NSXPCListener, shouldAcceptNewConnection connection: NSXPCConnection) -> Bool {
- guard UserAuthorization.isAdministrator(connection.effectiveUserIdentifier) else { return false }
+ let isAdministrator = { UserAuthorization.isAdministrator(connection.effectiveUserIdentifier) }
+ guard lifetime.accept(isAdministrator) else { return false }
connection.exportedInterface = Self.interface()
connection.exportedObject = HelperService(lifetime: lifetime)
- lifetime.connectionOpened()
connection.invalidationHandler = { [lifetime] in
lifetime.connectionClosed()
}