Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Prepare connection / region pinning #450

Open
wants to merge 20 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 36 additions & 6 deletions Sources/LiveKit/Core/Room+Engine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -264,7 +264,7 @@ extension Room {
throw LiveKitError(.invalidState)
}

guard let url = _state.url, let token = _state.token else {
guard let url = _state.providedUrl, let token = _state.token else {
log("[Connect] Url or token is nil", .error)
throw LiveKitError(.invalidState)
}
Expand Down Expand Up @@ -332,16 +332,46 @@ extension Room {
$0.connectionState = .reconnecting
}

await cleanUp(isFullReconnect: true)
let (providedUrl, connectedUrl, token) = _state.read { ($0.providedUrl, $0.connectedUrl, $0.token) }

guard let url = _state.url,
let token = _state.token
else {
guard let providedUrl, let connectedUrl, let token else {
log("[Connect] Url or token is nil")
throw LiveKitError(.invalidState)
}

try await fullConnectSequence(url, token)
var nextUrl = connectedUrl
var nextRegion: RegionInfo?

while true {
do {
// Prepare for next connect attempt.
await cleanUp(isFullReconnect: true)

try await fullConnectSequence(nextUrl, token)
_state.mutate { $0.connectedUrl = nextUrl }
// Exit loop on successful connection
break
} catch {
// Re-throw if is cancel.
if error is CancellationError {
throw error
}

if let region = nextRegion {
nextRegion = nil
log("Connect failed with region: \(region)")
regionManager(addFailedRegion: region)
}

try Task.checkCancellation()

if providedUrl.isCloud {
let region = try await regionManagerResolveBest()
nextUrl = region.url
nextRegion = region
}
}
}
}

do {
Expand Down
150 changes: 150 additions & 0 deletions Sources/LiveKit/Core/Room+Region.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
/*
* Copyright 2024 LiveKit
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import Foundation

// MARK: - Room+Region

extension Room {
static let regionManagerCacheInterval: TimeInterval = 3000

// MARK: - Public

// prepareConnection should be called as soon as the page is loaded, in order
// to speed up the connection attempt.
//
// With LiveKit Cloud, it will also determine the best edge data center for
// the current client to connect to if a token is provided.
public func prepareConnection(url providedUrlString: String, token: String) {
// Must be in disconnected state.
guard _state.connectionState == .disconnected else {
log("Room is not in disconnected state", .info)
return
}

guard let providedUrl = URL(string: providedUrlString), providedUrl.isValidForConnect else {
log("URL parse failed", .error)
return
}

guard providedUrl.isCloud else {
log("Provided url is not a livekit cloud url", .warning)
return
}

_state.mutate {
$0.providedUrl = providedUrl
$0.token = token
}

regionManagerPrepareRegionSettings()
}

// MARK: - Internal

func regionManagerResolveBest() async throws -> RegionInfo {
try await regionManagerRequestSettings()

guard let selectedRegion = _regionState.remaining.first else {
throw LiveKitError(.regionUrlProvider, message: "No more remaining regions.")
}

log("[Region] Resolved region: \(String(describing: selectedRegion))")

return selectedRegion
}

func regionManager(addFailedRegion region: RegionInfo) {
_regionState.mutate {
$0.remaining.removeAll { $0 == region }
}
}

func regionManagerPrepareRegionSettings() {
Task.detached {
try await self.regionManagerRequestSettings()
}
}

func regionManager(shouldRequestSettingsForUrl providedUrl: URL) -> Bool {
guard providedUrl.isCloud else { return false }
return _regionState.read {
guard providedUrl == $0.url, let regionSettingsUpdated = $0.lastRequested else { return true }
let interval = Date().timeIntervalSince(regionSettingsUpdated)
return interval > Self.regionManagerCacheInterval
}
}

// MARK: - Private

private func regionManagerRequestSettings() async throws {
let (providedUrl, token) = _state.read { ($0.providedUrl, $0.token) }

guard let providedUrl, let token else {
throw LiveKitError(.invalidState)
}

// Ensure url is for cloud.
guard providedUrl.isCloud else {
throw LiveKitError(.onlyForCloud)
}

guard regionManager(shouldRequestSettingsForUrl: providedUrl) else {
return
}

// Make a request which ignores cache.
var request = URLRequest(url: providedUrl.regionSettingsUrl(),
cachePolicy: .reloadIgnoringLocalAndRemoteCacheData)

request.addValue("Bearer \(token)", forHTTPHeaderField: "authorization")

log("[Region] Requesting region settings...")

let (data, response) = try await URLSession.shared.data(for: request)
// Response must be a HTTPURLResponse.
guard let httpResponse = response as? HTTPURLResponse else {
throw LiveKitError(.regionUrlProvider, message: "Failed to fetch region settings")
}

// Check the status code.
guard httpResponse.isStatusCodeOK else {
log("[Region] Failed to fetch region settings, error: \(String(describing: httpResponse))", .error)
throw LiveKitError(.regionUrlProvider, message: "Failed to fetch region settings with status code: \(httpResponse.statusCode)")
}

do {
// Try to parse the JSON data.
let regionSettings = try Livekit_RegionSettings(jsonUTF8Data: data)
let allRegions = regionSettings.regions.compactMap { $0.toLKType() }

if allRegions.isEmpty {
throw LiveKitError(.regionUrlProvider, message: "Fetched region data is empty.")
}

log("[Region] all regions: \(String(describing: allRegions))")

_regionState.mutate {
$0.url = providedUrl
$0.all = allRegions
$0.remaining = allRegions
$0.lastRequested = Date()
}
} catch {
throw LiveKitError(.regionUrlProvider, message: "Failed to parse region settings with error: \(error)")
}
}
}
90 changes: 71 additions & 19 deletions Sources/LiveKit/Core/Room.swift
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ public class Room: NSObject, ObservableObject, Loggable {

// expose engine's vars
@objc
public var url: String? { _state.url?.absoluteString }
public var url: String? { _state.providedUrl?.absoluteString }

@objc
public var token: String? { _state.token }
Expand Down Expand Up @@ -134,8 +134,10 @@ public class Room: NSObject, ObservableObject, Loggable {
var serverInfo: Livekit_ServerInfo?

// Engine
var url: URL?
var providedUrl: URL?
var connectedUrl: URL?
var token: String?

// preferred reconnect mode which will be used only for next attempt
var nextReconnectMode: ReconnectMode?
var isReconnectingWithMode: ReconnectMode?
Expand Down Expand Up @@ -168,7 +170,16 @@ public class Room: NSObject, ObservableObject, Loggable {
}
}

struct RegionState {
// Region
var url: URL?
var lastRequested: Date?
var all: [RegionInfo] = []
var remaining: [RegionInfo] = []
}

let _state: StateSync<State>
let _regionState = StateSync(RegionState())

private let _sidCompleter = AsyncCompleter<Sid>(label: "sid", defaultTimeout: .resolveSid)

Expand Down Expand Up @@ -278,12 +289,12 @@ public class Room: NSObject, ObservableObject, Loggable {
}

@objc
public func connect(url: String,
public func connect(url urlString: String,
token: String,
connectOptions: ConnectOptions? = nil,
roomOptions: RoomOptions? = nil) async throws
{
guard let url = URL(string: url), url.isValidForConnect else {
guard let providedUrl = URL(string: urlString), providedUrl.isValidForConnect else {
log("URL parse failed", .error)
throw LiveKitError(.failedToParseUrl)
}
Expand Down Expand Up @@ -315,28 +326,68 @@ public class Room: NSObject, ObservableObject, Loggable {

try Task.checkCancellation()

_state.mutate { $0.connectionState = .connecting }
_state.mutate {
$0.providedUrl = providedUrl
$0.token = token
$0.connectionState = .connecting
}

var nextUrl = providedUrl
var nextRegion: RegionInfo?

if providedUrl.isCloud {
if regionManager(shouldRequestSettingsForUrl: providedUrl) {
regionManagerPrepareRegionSettings()
} else {
// If region info already available, use it instead of provided url.
let region = try await regionManagerResolveBest()
nextUrl = region.url
nextRegion = region
}
}

do {
try await fullConnectSequence(url, token)
while true {
do {
try await fullConnectSequence(nextUrl, token)
// Connect sequence successful
log("Connect sequence completed")
// Final check if cancelled, don't fire connected events
try Task.checkCancellation()

_state.mutate {
$0.connectedUrl = nextUrl
$0.connectionState = .connected
}
// Exit loop on successful connection
break
} catch {
// Re-throw if is cancel.
if error is CancellationError {
throw error
}

// Connect sequence successful
log("Connect sequence completed")
if let region = nextRegion {
nextRegion = nil
log("Connect failed with region: \(region)")
regionManager(addFailedRegion: region)
}

// Final check if cancelled, don't fire connected events
try Task.checkCancellation()
try Task.checkCancellation()
// Prepare for next connect attempt.
await cleanUp(isFullReconnect: true)

// update internal vars (only if connect succeeded)
_state.mutate {
$0.url = url
$0.token = token
$0.connectionState = .connected
if providedUrl.isCloud {
let region = try await regionManagerResolveBest()
nextUrl = region.url
nextRegion = region
}
}
}

} catch {
log("Failed to resolve a region or connect: \(error)")
await cleanUp(withError: error)
// Re-throw error
throw error
throw error // Re-throw the original error
}

log("Connected to \(String(describing: self))", .info)
Expand Down Expand Up @@ -386,7 +437,8 @@ extension Room {
$0 = isFullReconnect ? State(
connectOptions: $0.connectOptions,
roomOptions: $0.roomOptions,
url: $0.url,
providedUrl: $0.providedUrl,
connectedUrl: $0.connectedUrl,
token: $0.token,
nextReconnectMode: $0.nextReconnectMode,
isReconnectingWithMode: $0.isReconnectingWithMode,
Expand Down
4 changes: 4 additions & 0 deletions Sources/LiveKit/Errors.swift
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,10 @@ public enum LiveKitErrorType: Int, Sendable {
case unableToResolveFPSRange = 703
case capturerDimensionsNotResolved = 704
case deviceAccessDenied = 705

// LiveKit Cloud
case onlyForCloud = 901
case regionUrlProvider = 902
}

extension LiveKitErrorType: CustomStringConvertible {
Expand Down
Loading
Loading