Skip to content

Commit 66bd743

Browse files
authored
Simplify error type (#282)
1 parent 5bd432c commit 66bd743

27 files changed

+243
-391
lines changed

Sources/LiveKit/Core/DataChannelPairActor.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ actor DataChannelPairActor: NSObject, Loggable {
7676

7777
public func send(userPacket: Livekit_UserPacket, reliability: Reliability) throws {
7878
guard isOpen else {
79-
throw InternalError.state(message: "Data channel is not open")
79+
throw LiveKitError(.invalidState, message: "Data channel is not open")
8080
}
8181

8282
let packet = Livekit_DataPacket.with {
@@ -89,7 +89,7 @@ actor DataChannelPairActor: NSObject, Loggable {
8989

9090
let channel = (reliability == .reliable) ? _reliableChannel : _lossyChannel
9191
guard let sendDataResult = channel?.sendData(rtcData), sendDataResult else {
92-
throw InternalError.state(message: "sendData failed")
92+
throw LiveKitError(.invalidState, message: "sendData failed")
9393
}
9494
}
9595

Sources/LiveKit/Core/Engine+SignalClientDelegate.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,9 +23,9 @@ extension Engine: SignalClientDelegate {
2323
// connectionState did update
2424
if state.connectionState != oldState.connectionState,
2525
// did disconnect
26-
case let .disconnected(reason) = state.connectionState,
26+
case .disconnected = state.connectionState,
2727
// only attempt re-connect if disconnected(reason: network)
28-
case .networkError = reason,
28+
case .network = state.disconnectError?.type,
2929
// engine is currently connected state
3030
case .connected = _state.connectionState
3131
{

Sources/LiveKit/Core/Engine+TransportDelegate.swift

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ extension Engine: TransportDelegate {
3232
publisherTransportConnectedCompleter.resume(returning: ())
3333
}
3434

35-
if _state.connectionState.isConnected {
35+
if _state.connectionState == .connected {
3636
// Attempt re-connect if primary or publisher transport failed
3737
if transport.isPrimary || (_state.hasPublished && transport.target == .publisher), [.disconnected, .failed].contains(pcState) {
3838
log("[reconnect] starting, reason: transport disconnected or failed")
@@ -56,7 +56,7 @@ extension Engine: TransportDelegate {
5656
// execute block when connected
5757
execute(when: { state, _ in state.connectionState == .connected },
5858
// always remove this block when disconnected
59-
removeWhen: { state, _ in state.connectionState == .disconnected() })
59+
removeWhen: { state, _ in state.connectionState == .disconnected })
6060
{ [weak self] in
6161
guard let self else { return }
6262
self.notify { $0.engine(self, didAddTrack: track, rtpReceiver: rtpReceiver, streams: streams) }

Sources/LiveKit/Core/Engine.swift

Lines changed: 22 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,8 @@ class Engine: MulticastDelegate<EngineDelegate> {
3434
// preferred reconnect mode which will be used only for next attempt
3535
var nextPreferredReconnectMode: ReconnectMode?
3636
var reconnectMode: ReconnectMode?
37-
var connectionState: ConnectionState = .disconnected()
37+
var connectionState: ConnectionState = .disconnected
38+
var disconnectError: LiveKitError?
3839
var connectStopwatch = Stopwatch(label: "connect")
3940
var hasPublished: Bool = false
4041
}
@@ -159,20 +160,22 @@ class Engine: MulticastDelegate<EngineDelegate> {
159160
$0.connectionState = .connected
160161
}
161162

162-
} catch is CancellationError {
163-
// Cancelled by .user
164-
try await cleanUp(reason: .user)
165163
} catch {
166-
try await cleanUp(reason: .networkError(error))
164+
try await cleanUp(withError: error)
165+
// Re-throw error
166+
throw error
167167
}
168168
}
169169

170170
// cleanUp (reset) both Room & Engine's state
171-
func cleanUp(reason: DisconnectReason? = nil, isFullReconnect: Bool = false) async throws {
171+
func cleanUp(withError disconnectError: Error? = nil,
172+
isFullReconnect: Bool = false) async throws
173+
{
172174
// This should never happen since Engine is owned by Room
173175
let room = try requireRoom()
174176
// Call Room's cleanUp
175-
await room.cleanUp(reason: reason, isFullReconnect: isFullReconnect)
177+
await room.cleanUp(withError: disconnectError,
178+
isFullReconnect: isFullReconnect)
176179
}
177180

178181
// Resets state of transports
@@ -362,18 +365,18 @@ extension Engine {
362365

363366
func startReconnect() async throws {
364367
guard case .connected = _state.connectionState else {
365-
log("[reconnect] must be called with connected state", .warning)
366-
throw EngineError.state(message: "Must be called with connected state")
368+
log("[Reconnect] Must be called with connected state", .error)
369+
throw LiveKitError(.invalidState)
367370
}
368371

369372
guard let url = _state.url, let token = _state.token else {
370-
log("[reconnect] url or token is nil", .warning)
371-
throw EngineError.state(message: "url or token is nil")
373+
log("[Reconnect] Url or token is nil", .error)
374+
throw LiveKitError(.invalidState)
372375
}
373376

374377
guard subscriber != nil, publisher != nil else {
375-
log("[reconnect] publisher or subscriber is nil", .warning)
376-
throw EngineError.state(message: "Publisher or Subscriber is nil")
378+
log("[Reconnect] Publisher or subscriber is nil", .error)
379+
throw LiveKitError(.invalidState)
377380
}
378381

379382
// quick connect sequence, does not update connection state
@@ -420,7 +423,8 @@ extension Engine {
420423
guard let url = _state.url,
421424
let token = _state.token
422425
else {
423-
throw EngineError.state(message: "url or token is nil")
426+
log("[Reconnect] Url or token is nil")
427+
throw LiveKitError(.invalidState)
424428
}
425429

426430
try await fullConnectSequence(url, token)
@@ -461,12 +465,12 @@ extension Engine {
461465
do {
462466
try await retryingTask.value
463467
// Re-connect sequence successful
464-
log("[reconnect] sequence completed")
468+
log("[reconnect] Sequence completed")
465469
_state.mutate { $0.connectionState = .connected }
466470
} catch {
467471
log("[Reconnect] Sequence failed with error: \(error)")
468472
// Finally disconnect if all attempts fail
469-
try await cleanUp(reason: .networkError(error))
473+
try await cleanUp(withError: error)
470474
}
471475
}
472476
}
@@ -517,12 +521,12 @@ extension Engine {
517521

518522
extension Engine {
519523
func requireRoom() throws -> Room {
520-
guard let room = _room else { throw EngineError.state(message: "Room is nil") }
524+
guard let room = _room else { throw LiveKitError(.invalidState, message: "Room is nil") }
521525
return room
522526
}
523527

524528
func requirePublisher() throws -> Transport {
525-
guard let publisher else { throw EngineError.state(message: "Publisher is nil") }
529+
guard let publisher else { throw LiveKitError(.invalidState, message: "Publisher is nil") }
526530
return publisher
527531
}
528532
}

Sources/LiveKit/Core/Room+EngineDelegate.swift

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -40,29 +40,23 @@ extension Room: EngineDelegate {
4040
}
4141

4242
delegates.notify(label: { "room.didUpdate connectionState: \(state.connectionState) oldValue: \(oldState.connectionState)" }) {
43-
// Objective-C support
44-
$0.room?(self, didUpdate: state.connectionState.toObjCType(), oldValue: oldState.connectionState.toObjCType())
45-
// Swift only
46-
if let delegateSwift = $0 as? RoomDelegate {
47-
delegateSwift.room(self, didUpdate: state.connectionState, oldValue: oldState.connectionState)
48-
}
43+
$0.room?(self, didUpdate: state.connectionState, oldValue: oldState.connectionState)
4944
}
5045

5146
// Legacy connection delegates
5247
if case .connected = state.connectionState {
5348
let didReconnect = oldState.connectionState == .reconnecting
5449
delegates.notify { $0.room?(self, didConnect: didReconnect) }
55-
} else if case let .disconnected(reason) = state.connectionState {
50+
} else if case .disconnected = state.connectionState {
5651
if case .connecting = oldState.connectionState {
57-
let error = reason?.networkError ?? NetworkError.disconnected(message: "Did fail to connect", rawError: nil)
58-
delegates.notify { $0.room?(self, didFailToConnect: error) }
52+
delegates.notify { $0.room?(self, didFailToConnect: oldState.disconnectError) }
5953
} else {
60-
delegates.notify { $0.room?(self, didDisconnect: reason?.networkError) }
54+
delegates.notify { $0.room?(self, didDisconnect: state.disconnectError) }
6155
}
6256
}
6357
}
6458

65-
if state.connectionState.isReconnecting, state.reconnectMode == .full, oldState.reconnectMode != .full {
59+
if state.connectionState == .reconnecting, state.reconnectMode == .full, oldState.reconnectMode != .full {
6660
Task {
6761
// Started full reconnect
6862
await cleanUpParticipants(notify: true)

Sources/LiveKit/Core/Room+MulticastDelegate.swift

Lines changed: 2 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,12 @@
1717
import Foundation
1818

1919
extension Room: MulticastDelegateProtocol {
20+
@objc(addDelegate:)
2021
public func add(delegate: RoomDelegate) {
2122
delegates.add(delegate: delegate)
2223
}
2324

25+
@objc(removeDelegate:)
2426
public func remove(delegate: RoomDelegate) {
2527
delegates.remove(delegate: delegate)
2628
}
@@ -29,18 +31,4 @@ extension Room: MulticastDelegateProtocol {
2931
public func removeAllDelegates() {
3032
delegates.removeAllDelegates()
3133
}
32-
33-
/// Only for Objective-C.
34-
@objc(addDelegate:)
35-
@available(swift, obsoleted: 1.0)
36-
public func addObjC(delegate: RoomDelegateObjC) {
37-
delegates.add(delegate: delegate)
38-
}
39-
40-
/// Only for Objective-C.
41-
@objc(removeDelegate:)
42-
@available(swift, obsoleted: 1.0)
43-
public func removeObjC(delegate: RoomDelegateObjC) {
44-
delegates.remove(delegate: delegate)
45-
}
4634
}

Sources/LiveKit/Core/Room+SignalClientDelegate.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ extension Room: SignalClientDelegate {
2828
} else {
2929
Task {
3030
// Server indicates it's not recoverable
31-
await cleanUp(reason: reason.toLKType())
31+
await cleanUp(withError: LiveKitError.from(reason: reason))
3232
}
3333
}
3434
}

Sources/LiveKit/Core/Room.swift

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import Foundation
2424
public class Room: NSObject, ObservableObject, Loggable {
2525
// MARK: - MulticastDelegate
2626

27-
public let delegates = MulticastDelegate<RoomDelegateObjC>()
27+
public let delegates = MulticastDelegate<RoomDelegate>()
2828

2929
// MARK: - Public
3030

@@ -76,12 +76,11 @@ public class Room: NSObject, ObservableObject, Loggable {
7676
public var token: String? { engine._state.token }
7777

7878
/// Current ``ConnectionState`` of the ``Room``.
79+
@objc
7980
public var connectionState: ConnectionState { engine._state.connectionState }
8081

81-
/// Only for Objective-C.
82-
@objc(connectionState)
83-
@available(swift, obsoleted: 1.0)
84-
public var connectionStateObjC: ConnectionStateObjC { engine._state.connectionState.toObjCType() }
82+
@objc
83+
public var disconnectError: LiveKitError? { engine._state.disconnectError }
8584

8685
public var connectStopwatch: Stopwatch { engine._state.connectStopwatch }
8786

@@ -141,7 +140,7 @@ public class Room: NSObject, ObservableObject, Loggable {
141140
}
142141

143142
@objc
144-
public init(delegate: RoomDelegateObjC? = nil,
143+
public init(delegate: RoomDelegate? = nil,
145144
connectOptions: ConnectOptions? = nil,
146145
roomOptions: RoomOptions? = nil)
147146
{
@@ -252,18 +251,18 @@ public class Room: NSObject, ObservableObject, Loggable {
252251
log("Failed to send leave with error: \(error)")
253252
}
254253

255-
await cleanUp(reason: .user)
254+
await cleanUp()
256255
}
257256
}
258257

259258
// MARK: - Internal
260259

261260
extension Room {
262261
// Resets state of Room
263-
func cleanUp(reason: DisconnectReason? = nil,
262+
func cleanUp(withError disconnectError: Error? = nil,
264263
isFullReconnect: Bool = false) async
265264
{
266-
log("Reason: \(String(describing: reason))")
265+
log("withError: \(String(describing: disconnectError))")
267266

268267
// Start Engine cleanUp sequence
269268

@@ -281,11 +280,12 @@ extension Room {
281280
connectionState: $0.connectionState
282281
) : Engine.State(
283282
connectOptions: $0.connectOptions,
284-
connectionState: .disconnected(reason: reason)
283+
connectionState: .disconnected,
284+
disconnectError: LiveKitError.from(error: disconnectError)
285285
)
286286
}
287287

288-
await engine.signalClient.cleanUp(reason: reason)
288+
await engine.signalClient.cleanUp(withError: disconnectError)
289289
await engine.cleanUpRTC()
290290
await cleanUpParticipants()
291291
// Reset state
@@ -315,7 +315,7 @@ extension Room {
315315

316316
func _onParticipantDidDisconnect(identity: Identity) async throws {
317317
guard let participant = _state.mutate({ $0.remoteParticipants.removeValue(forKey: identity) }) else {
318-
throw EngineError.state(message: "Participant not found for \(identity)")
318+
throw LiveKitError(.invalidState, message: "Participant not found for \(identity)")
319319
}
320320

321321
await participant.cleanUp(notify: true)

0 commit comments

Comments
 (0)