Skip to content

Commit a90267d

Browse files
committed
rewrite
1 parent 987d9dd commit a90267d

File tree

1 file changed

+27
-21
lines changed

1 file changed

+27
-21
lines changed

Coder Desktop/Coder Desktop/VPNService.swift

+27-21
Original file line numberDiff line numberDiff line change
@@ -158,41 +158,47 @@ final class CoderVPNService: NSObject, VPNService {
158158
}
159159

160160
extension CoderVPNService {
161+
// The number of NETunnelProviderSession states makes the excessive branching
162+
// necessary.
161163
// swiftlint:disable:next cyclomatic_complexity
162164
@objc private func vpnDidUpdate(_ notification: Notification) {
163165
guard let connection = notification.object as? NETunnelProviderSession else {
164166
return
165167
}
166-
switch connection.status {
167-
case .disconnected:
168+
switch (tunnelState, connection.status) {
169+
// Any -> Disconnected: Update UI w/ error if present
170+
case (_, .disconnected):
168171
connection.fetchLastDisconnectError { err in
169172
self.tunnelState = if let err {
170173
.failed(.internalError(err.localizedDescription))
171174
} else {
172175
.disabled
173176
}
174177
}
175-
case .connecting:
176-
// If transitioning to 'connecting' from any other state,
177-
// then the network extension is running, and we can connect over XPC
178-
if tunnelState != .connecting {
179-
xpc.connect()
180-
xpc.ping()
181-
tunnelState = .connecting
182-
}
183-
case .connected:
184-
// If transitioning to 'connected' from any other state, the tunnel has
185-
// finished starting, and we can learn the peer state
186-
if tunnelState != .connected {
187-
xpc.connect()
188-
xpc.getPeerState()
189-
tunnelState = .connected
190-
}
191-
case .reasserting:
178+
// Connecting -> Connecting: no-op
179+
case (.connecting, .connecting):
180+
break
181+
// Connected -> Connected: no-op
182+
case (.connected, .connected):
183+
break
184+
// Non-connecting -> Connecting: Establish XPC
185+
case (_, .connecting):
186+
xpc.connect()
187+
xpc.ping()
188+
tunnelState = .connecting
189+
// Non-connected -> Connected: Retrieve Peers
190+
case (_, .connected):
191+
xpc.connect()
192+
xpc.getPeerState()
193+
tunnelState = .connected
194+
// Any -> Reasserting
195+
case (_, .reasserting):
192196
tunnelState = .connecting
193-
case .disconnecting:
197+
// Any -> Disconnecting
198+
case (_, .disconnecting):
194199
tunnelState = .disconnecting
195-
case .invalid:
200+
// Any -> Invalid
201+
case (_, .invalid):
196202
tunnelState = .failed(.networkExtensionError(.unconfigured))
197203
@unknown default:
198204
tunnelState = .disabled

0 commit comments

Comments
 (0)