forked from github/CopilotForXcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathXPCController.swift
More file actions
68 lines (58 loc) · 1.85 KB
/
XPCController.swift
File metadata and controls
68 lines (58 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import Foundation
import Logger
import XPCShared
final class XPCController: XPCServiceDelegate {
let bridge: XPCCommunicationBridge
let xpcListener: NSXPCListener
let xpcServiceDelegate: ServiceDelegate
var pingTask: Task<Void, Error>?
init() {
let bridge = XPCCommunicationBridge(logger: .client)
let listener = NSXPCListener.anonymous()
let delegate = ServiceDelegate()
listener.delegate = delegate
listener.resume()
xpcListener = listener
xpcServiceDelegate = delegate
self.bridge = bridge
Task {
bridge.setDelegate(self)
createPingTask()
}
}
func quit() async {
bridge.setDelegate(nil)
pingTask?.cancel()
try? await bridge.quit()
}
deinit {
xpcListener.invalidate()
pingTask?.cancel()
}
func createPingTask() {
pingTask?.cancel()
pingTask = Task { [weak self] in
while !Task.isCancelled {
guard let self else { return }
do {
try await self.bridge.updateServiceEndpoint(self.xpcListener.endpoint)
try await Task.sleep(nanoseconds: 60_000_000_000)
} catch {
try await Task.sleep(nanoseconds: 1_000_000_000)
#if DEBUG
// No log, but you should run CommunicationBridge, too.
#else
Logger.service
.error("Failed to connect to bridge: \(error.localizedDescription)")
#endif
}
}
}
}
func connectionDidInvalidate() async {
// ignore
}
func connectionDidInterrupt() async {
createPingTask() // restart the ping task so that it can bring the bridge back immediately.
}
}