Modern Apps git

← xtool.git

HeartbeatHandler concurrency

Commit
74a532427a4aa1af343016ead03fce5c1586a42f
Author
Kabir Oberai <[email protected]>
When
2024-12-02 04:57 UTC (2 years ago)
Parents
5adf531

Diff

Sources/Supersign/Installation/Connection.swift
diff --git a/Sources/Supersign/Installation/Connection.swift b/Sources/Supersign/Installation/Connection.swiftindex 92d4199..4fa20c1 100644--- a/Sources/Supersign/Installation/Connection.swift+++ b/Sources/Supersign/Installation/Connection.swift@@ -102,7 +102,7 @@ public actor Connection {         client = try LockdownClient(device: device, label: Self.label, performHandshake: true)          progress(3/4)-        heartbeatHandler = HeartbeatHandler(device: device, client: client)+        heartbeatHandler = try await HeartbeatHandler(device: device, client: client)          progress(4/4)     }
Sources/Supersign/Installation/HeartbeatHandler.swift
diff --git a/Sources/Supersign/Installation/HeartbeatHandler.swift b/Sources/Supersign/Installation/HeartbeatHandler.swiftindex d4cd329..b0b71ff 100644--- a/Sources/Supersign/Installation/HeartbeatHandler.swift+++ b/Sources/Supersign/Installation/HeartbeatHandler.swift@@ -10,7 +10,7 @@ import Foundation import SwiftyMobileDevice import ConcurrencyExtras -public final class HeartbeatHandler: Sendable {+public actor HeartbeatHandler: Sendable {     private struct Error: Swift.Error {}      private struct ReceivedPacket: Decodable {@@ -46,24 +46,55 @@ public final class HeartbeatHandler: Sendable {     // the timeout when receiving subsequent heartbeat packets     private static let repeatedTimeout: TimeInterval = 5 -    // each handler should have its own heartbeat queue-    private let heartbeatQueue = DispatchQueue(-        label: "com.kabiroberai.Supersign.heartbeat-queue"-    )-    private let isStopped = LockIsolated(false)-     private let device: Device     private let client: LockdownClient-    public init(device: Device, client: LockdownClient) {+    private var task: Task<Void, Never>?++    public init(device: Device, client: LockdownClient) async throws {         self.device = device         self.client = client-        start()++        let initialClient = try await createHeartbeatClient()++        task = Task { [weak self] in+            var client = initialClient+            for iteration in 0... {+                // only retains `self` for this iteration. This way, if the reference to+                // the handler is dropped, the heartbeat stops+                guard let self = self, !Task.isCancelled else { break }++                do {+                    try await beat(client: client, iteration: iteration)+                } catch {+                    NSLog("%@", "Heartbeat failed: \(error)" as NSString)+                    do {+                        try await Task.sleep(seconds: Self.restartInterval)+                        client = try await createHeartbeatClient()+                    } catch {+                        return // cancelled+                    }+                }+            }+        }+    }++    private func createHeartbeatClient() async throws -> HeartbeatClient {+        while true {+            do {+                return try HeartbeatClient(+                    device: device,+                    service: .init(client: client, type: HeartbeatClient.self)+                )+            } catch {+                try await Task.sleep(seconds: Self.restartInterval)+            }+        }     }      // no need for a custom deinit because the `guard let self = self` in the loop stops it     // when the handler deinits -    private func beat(client: HeartbeatClient, iteration: Int) throws {+    private func beat(client: HeartbeatClient, iteration: Int) async throws {         // allow a 30 second timeout for the first heartbeat         let received = try client.receive(             ReceivedPacket.self,@@ -73,52 +104,10 @@ public final class HeartbeatHandler: Sendable {          try client.send(SentPacket(command: .polo)) -        Thread.sleep(forTimeInterval: .init(received.interval))-    }--    // TODO: Separate initial establishment phase (blocking) from loop-    // (non-blocking) and throw during initial phase if too many failed-    // attempts. Also maybe try to eliminate recursion to avoid relying-    // on TCO which is not deterministically applied.-    private func start() {-        let heartbeatClient: HeartbeatClient-        do {-            heartbeatClient = try HeartbeatClient(device: device, service: .init(client: client, type: HeartbeatClient.self))-        } catch {-            // we sleep instead of asyncAfter to allow the initial startHeartbeat-            // call to block until a connection is established-            Thread.sleep(forTimeInterval: Self.restartInterval)-            start()-            return-        }--        self.heartbeatQueue.async { [weak self] in-            for iteration in 0... {-                // only retains `self` for this iteration. This way, if the reference to-                // the handler is dropped, the heartbeat stops-                guard let self = self else { break }--                do {-                    guard !self.isStopped.value else { break }-                }--                do {-                    try self.beat(client: heartbeatClient, iteration: iteration)-                } catch {-                    "Heartbeat failed: \(error)".withCString {-                        NSLog("%s", $0)-                    }-                    // dispatching async should prevent stack overflows.-                    // We return to break out of the current loop.-                    return self.heartbeatQueue.asyncAfter(deadline: .now() + Self.restartInterval) {-                        self.start()-                    }-                }-            }-        }+        try? await Task.sleep(seconds: Double(received.interval))     } -    public func stop() {-        self.isStopped.setValue(true)+    nonisolated public func stop() {+        Task { await task?.cancel() }     } }
Sources/Supersign/Integration/SuperchargeInstaller.swift
diff --git a/Sources/Supersign/Integration/SuperchargeInstaller.swift b/Sources/Supersign/Integration/SuperchargeInstaller.swiftindex 0487e9a..22015c2 100644--- a/Sources/Supersign/Integration/SuperchargeInstaller.swift+++ b/Sources/Supersign/Integration/SuperchargeInstaller.swift@@ -189,7 +189,7 @@ public actor IntegratedInstaller {                 delegate?.setPresentedMessage(nextMessage)                 currMessage = nextMessage             }-            try await Task.sleep(nanoseconds: UInt64(repeatAfter * 1_000_000_000))+            try await Task.sleep(seconds: repeatAfter)         }     } 
Sources/Supersign/Utilities/Task+Utils.swift
diff --git a/Sources/Supersign/Utilities/Task+Utils.swift b/Sources/Supersign/Utilities/Task+Utils.swiftnew file mode 100644index 0000000..cf16124--- /dev/null+++ b/Sources/Supersign/Utilities/Task+Utils.swift@@ -0,0 +1,5 @@+extension Task<Never, Never> {+    public static func sleep(seconds: Double) async throws {+        try await sleep(nanoseconds: UInt64(seconds * 1_000_000_000))+    }+}