diff --git a/connection_manager.go b/connection_manager.go index 59f9faf2..5fda76be 100644 --- a/connection_manager.go +++ b/connection_manager.go @@ -451,28 +451,31 @@ type connectionPlanParams struct { } func getConnectionPlanInitial(params connectionPlanParams) ([]connectionAttemptParams, error) { - var regionsToTry []*livekit.RegionInfo - // The caller's own region goes first. buildConnectionPlan removes the same - // region from the discovered list. - if p := params.incomingRequestParams.preferredRegion; p != nil { - regionsToTry = append(regionsToTry, p) - } + var discovered []*livekit.RegionInfo if !params.incomingRequestParams.disableRegionDiscovery { cloudHostname, _ := parseCloudURL(params.incomingRequestParams.url) if cloudHostname != "" { start := time.Now() - settings, err := params.regionURLProvider.RegionSettings(cloudHostname, params.token) + settings, err := params.regionURLProvider.RegionSettings(cloudHostname, params.token, params.incomingRequestParams.preferredRegion.GetRegion()) if err != nil { // Discovery is best effort. Fall back to the original URL, but make // the cost visible: a timeout here adds 2s to the join. params.log.Warnw("region discovery failed, using original url", err, "cloudHostname", cloudHostname, "duration", time.Since(start)) } else { - regionsToTry = append(regionsToTry, settings.GetRegions()...) + discovered = settings.GetRegions() } } } + var regionsToTry []*livekit.RegionInfo + // The caller's own region goes first. buildConnectionPlan removes the same + // region from the discovered list. + if p := usablePreferredRegion(params.log, params.incomingRequestParams.preferredRegion, discovered); p != nil { + regionsToTry = append(regionsToTry, p) + } + regionsToTry = append(regionsToTry, discovered...) + // add the incoming request URL (i. e. original URL) just in case the region specific options did not work regionsToTry = append(regionsToTry, &livekit.RegionInfo{ Region: cOriginalRegion, @@ -529,29 +532,31 @@ func getConnectionPlanReconnecting(params connectionPlanParams) ([]connectionAtt } } - // The server-sent list and the connected region stay first. The caller's - // own region comes before the discovered regions. - if p := params.incomingRequestParams.preferredRegion; p != nil { - regionsToTry = append(regionsToTry, p) - } - // layer on region provider regions if enabled + var discovered []*livekit.RegionInfo if !params.incomingRequestParams.disableRegionDiscovery { cloudHostname, _ := parseCloudURL(params.incomingRequestParams.url) if cloudHostname != "" { start := time.Now() - settings, err := params.regionURLProvider.RegionSettings(cloudHostname, params.token) + settings, err := params.regionURLProvider.RegionSettings(cloudHostname, params.token, params.incomingRequestParams.preferredRegion.GetRegion()) if err != nil { // Discovery is best effort. Fall back to the regions already // collected, but make a slow or failed fetch visible. params.log.Warnw("region discovery failed, using known regions", err, "cloudHostname", cloudHostname, "duration", time.Since(start)) } else { - regionsToTry = append(regionsToTry, settings.GetRegions()...) + discovered = settings.GetRegions() } } } + // The server-sent list and the connected region stay first. The caller's + // own region comes before the discovered regions. + if p := usablePreferredRegion(params.log, params.incomingRequestParams.preferredRegion, discovered); p != nil { + regionsToTry = append(regionsToTry, p) + } + regionsToTry = append(regionsToTry, discovered...) + // add the incoming request URL (i. e. original URL) just in case the region specific options did not work regionsToTry = append(regionsToTry, &livekit.RegionInfo{ Region: cOriginalRegion, @@ -562,6 +567,27 @@ func getConnectionPlanReconnecting(params connectionPlanParams) ([]connectionAtt return buildConnectionPlan(context.Background(), regionsToTry, params.token, params.incomingRequestParams.preferredRegion) } +// usablePreferredRegion returns preferred, or nil if discovery returned regions +// and preferred is not one of them. Discovery lists only the regions that the +// project can use, so this skips a region that the server would refuse, for +// example for a project pinned to other regions. Discovery ranks the regions +// near preferred, so the list has preferred if the project can use it. +func usablePreferredRegion(log protoLogger.Logger, preferred *livekit.RegionInfo, discovered []*livekit.RegionInfo) *livekit.RegionInfo { + if preferred == nil || len(discovered) == 0 { + return preferred + } + names := make([]string, 0, len(discovered)) + for _, r := range discovered { + if r.GetRegion() == preferred.GetRegion() { + return preferred + } + names = append(names, r.GetRegion()) + } + log.Debugw("skipping preferred region, not in discovered regions", + "preferredRegion", preferred.GetRegion(), "discoveredRegions", names) + return nil +} + // buildConnectionPlan removes duplicate regions by name. An entry with the // name of preferred but a different host is kept, so a wrong preferred URL // does not hide the discovered URL for that region. diff --git a/connection_manager_test.go b/connection_manager_test.go index dce49b08..53bcc9c6 100644 --- a/connection_manager_test.go +++ b/connection_manager_test.go @@ -16,6 +16,7 @@ package lksdk import ( "context" + "net/http" "testing" "time" @@ -199,7 +200,8 @@ func TestConnectionManager_GetConnectionPlanInitial_WithDiscovery(t *testing.T) // TestConnectionManager_PreferredRegion: the preferred region is first on a // join, and after the server list and connected region on a full reconnect. -// A discovered entry with its name but another host stays in the plan. +// A discovered entry with its name but another host stays in the plan. If +// discovery returns regions without the preferred region, the plan skips it. func TestConnectionManager_PreferredRegion(t *testing.T) { const orig = "wss://test.livekit.cloud" usEast := &livekit.RegionInfo{Region: "us-east", Url: "wss://us-east.livekit.cloud"} @@ -219,6 +221,11 @@ func TestConnectionManager_PreferredRegion(t *testing.T) { want: []string{usWest.Url, usEast.Url, orig}}, {name: "join, no discovery", preferred: usWest, noDiscovery: true, want: []string{usWest.Url, orig}}, + // Discovery lists only the regions that the project can use. + {name: "join, not discovered", preferred: usWest, discovered: []*livekit.RegionInfo{usEast}, + want: []string{usEast.Url, orig}}, + {name: "join, empty discovery", preferred: usWest, discovered: []*livekit.RegionInfo{}, + want: []string{usWest.Url, orig}}, {name: "join, other host", preferred: oldWest, discovered: []*livekit.RegionInfo{usWest, usEast}, want: []string{oldWest.Url, usWest.Url, usEast.Url, orig}}, {name: "join, same host", preferred: upperWest, discovered: []*livekit.RegionInfo{usWest}, @@ -227,12 +234,14 @@ func TestConnectionManager_PreferredRegion(t *testing.T) { want: []string{usEast.Url, usWest.Url, orig}}, {name: "reconnect, other host", preferred: oldWest, discovered: []*livekit.RegionInfo{usWest}, reconnect: true, want: []string{usEast.Url, oldWest.Url, usWest.Url, orig}}, + {name: "reconnect, not discovered", preferred: usWest, discovered: []*livekit.RegionInfo{usEast}, reconnect: true, + want: []string{usEast.Url, orig}}, } { t.Run(c.name, func(t *testing.T) { cm := newConnectionManager(newRegionURLProvider()) cm.setIncomingRequestParams(context.Background(), orig, "test-token", &signalling.ConnectParams{}, c.noDiscovery, c.preferred) if c.discovered != nil { - cm.regionProvider.cache.set("test.livekit.cloud", &livekit.RegionSettings{Regions: c.discovered}, time.Minute) + cm.regionProvider.cache.set(regionCacheKey("test.livekit.cloud", c.preferred.GetRegion()), &livekit.RegionSettings{Regions: c.discovered}, time.Minute) } if c.reconnect { cm.setConnected(usEast) @@ -584,3 +593,41 @@ func TestConnectionManager_BuildConnectionPlan_Backoff(t *testing.T) { require.Equal(t, w, plan[i].backoffWait, "idx %d", i) } } + +// TestPrepareConnection_PreferredRegion: PrepareConnection with the same +// WithPreferredRegion as the join fills the region list that the join reads, +// so the join does not wait for another discovery request. +func TestPrepareConnection_PreferredRegion(t *testing.T) { + usWest := &livekit.RegionInfo{Region: "us-west", Url: "wss://us-west.example.com"} + rs := newRegionSettingsServer(t, &livekit.RegionSettings{Regions: []*livekit.RegionInfo{usWest}}) + p := newTestProvider(rs) + // The cloud URL must end in .livekit.cloud, so send its requests to the test server. + p.cache.client.Transport = toHostTransport{host: rs.hostname, next: p.cache.client.Transport} + const cloudURL = "wss://test.livekit.cloud" + + room := NewRoom(nil) + room.regionURLProvider = p + require.NoError(t, room.PrepareConnection(cloudURL, "test-token", WithPreferredRegion(usWest))) + + cm := newConnectionManager(p) + cm.setIncomingRequestParams(context.Background(), cloudURL, "test-token", &signalling.ConnectParams{}, false, usWest) + _, err := cm.getConnectionPlan() + require.NoError(t, err) + + rs.mu.Lock() + defer rs.mu.Unlock() + require.Equal(t, []string{"us-west"}, rs.nears) // one request, from PrepareConnection +} + +// toHostTransport sends every request to host. +type toHostTransport struct { + host string + next http.RoundTripper +} + +func (t toHostTransport) RoundTrip(req *http.Request) (*http.Response, error) { + req = req.Clone(req.Context()) + req.URL.Host = t.host + req.Host = t.host + return t.next.RoundTrip(req) +} diff --git a/regionurlprovider.go b/regionurlprovider.go index 6be7e7b3..dbf10044 100644 --- a/regionurlprovider.go +++ b/regionurlprovider.go @@ -39,17 +39,25 @@ func newRegionURLProvider() *regionURLProvider { return ®ionURLProvider{cache: newRegionCache()} } -func (r *regionURLProvider) RefreshRegionSettings(cloudHostname, token string) error { - _, err := r.RegionSettings(cloudHostname, token) +func (r *regionURLProvider) RefreshRegionSettings(cloudHostname, token, near string) error { + _, err := r.RegionSettings(cloudHostname, token, near) return err } // RegionSettings returns the cached region list for a hostname, refreshing it if // stale. The returned list is owned by the cache and must not be mutated; the // caller is responsible for tracking its own per-failover attempt state. -func (r *regionURLProvider) RegionSettings(cloudHostname, token string) (*livekit.RegionSettings, error) { +// +// If near is set, the server ranks the regions by distance from that region, +// not from the GeoIP location of the client. The list still holds only the +// regions that the project can use. +func (r *regionURLProvider) RegionSettings(cloudHostname, token, near string) (*livekit.RegionSettings, error) { headers := http.Header{"Authorization": []string{"Bearer " + token}} - settings, err := r.cache.get(cloudHostname, regionSettingsURL(cloudHostname), headers, regionHostnameProviderSettingsCacheTime) + discoveryURL := regionSettingsURL(cloudHostname) + if near != "" { + discoveryURL += "?near=" + url.QueryEscape(near) + } + settings, err := r.cache.get(regionCacheKey(cloudHostname, near), discoveryURL, headers, regionHostnameProviderSettingsCacheTime) if err != nil { return nil, err } @@ -62,6 +70,15 @@ func (r *regionURLProvider) RegionSettings(cloudHostname, token string) (*liveki return settings, nil } +// regionCacheKey keeps a separate list for each near region, because the +// server ranks the regions by distance from it. +func regionCacheKey(cloudHostname, near string) string { + if near == "" { + return cloudHostname + } + return cloudHostname + "?near=" + near +} + // regionCache fetches and caches the LiveKit Cloud region list per host. It is // shared by the API failover path (which honors the request scheme and forwards // the caller's headers) and the RTC signaling path (which fetches over https diff --git a/regionurlprovider_test.go b/regionurlprovider_test.go index 1de604c9..b69ff577 100644 --- a/regionurlprovider_test.go +++ b/regionurlprovider_test.go @@ -39,6 +39,7 @@ type regionSettingsServer struct { mu sync.Mutex regions *livekit.RegionSettings status int + nears []string // the near parameter of each request } func newRegionSettingsServer(t *testing.T, regions *livekit.RegionSettings) *regionSettingsServer { @@ -54,6 +55,7 @@ func newRegionSettingsServer(t *testing.T, regions *livekit.RegionSettings) *reg rs.mu.Lock() status, regions := rs.status, rs.regions + rs.nears = append(rs.nears, r.URL.Query().Get("near")) rs.mu.Unlock() if status != http.StatusOK { @@ -102,7 +104,7 @@ func TestRegionURLProvider_RegionSettingsOrder(t *testing.T) { // RegionSettings returns the list in server order and does not mutate it, so // repeated calls return the same list and only fetch once. for n := 0; n < 2; n++ { - settings, err := p.RegionSettings(rs.hostname, "test-token") + settings, err := p.RegionSettings(rs.hostname, "test-token", "") require.NoError(t, err) var got []string for _, region := range settings.GetRegions() { @@ -119,8 +121,8 @@ func TestRegionURLProvider_CacheAvoidsRefetch(t *testing.T) { }) p := newTestProvider(rs) - require.NoError(t, p.RefreshRegionSettings(rs.hostname, "test-token")) - require.NoError(t, p.RefreshRegionSettings(rs.hostname, "test-token")) + require.NoError(t, p.RefreshRegionSettings(rs.hostname, "test-token", "")) + require.NoError(t, p.RefreshRegionSettings(rs.hostname, "test-token", "")) require.EqualValues(t, 1, rs.hits.Load(), "second refresh within cache TTL must not refetch") } @@ -134,7 +136,7 @@ func TestRegionURLProvider_RefreshRepopulates(t *testing.T) { }) p := newTestProvider(rs) - settings, err := p.RegionSettings(rs.hostname, "test-token") + settings, err := p.RegionSettings(rs.hostname, "test-token", "") require.NoError(t, err) require.Equal(t, "wss://a.example.com", settings.GetRegions()[0].Url) @@ -146,7 +148,7 @@ func TestRegionURLProvider_RefreshRepopulates(t *testing.T) { Regions: []*livekit.RegionInfo{{Region: "b", Url: "wss://b.example.com"}}, }) - settings, err = p.RegionSettings(rs.hostname, "test-token") + settings, err = p.RegionSettings(rs.hostname, "test-token", "") require.NoError(t, err) require.EqualValues(t, 2, rs.hits.Load(), "refresh past TTL must refetch") require.Equal(t, "wss://b.example.com", settings.GetRegions()[0].Url) @@ -159,7 +161,7 @@ func TestRegionURLProvider_FetchError(t *testing.T) { rs.mu.Unlock() p := newTestProvider(rs) - _, err := p.RegionSettings(rs.hostname, "test-token") + _, err := p.RegionSettings(rs.hostname, "test-token", "") require.Error(t, err, "no regions cached after a failed fetch") } @@ -178,3 +180,18 @@ func TestParseRegionSettingsMaxAge(t *testing.T) { require.Equal(t, want, parseRegionSettingsMaxAge(in), "input %q", in) } } + +// TestRegionURLProvider_Near: the near region goes to the server, and each near +// region has its own cached list. +func TestRegionURLProvider_Near(t *testing.T) { + rs := newRegionSettingsServer(t, &livekit.RegionSettings{ + Regions: []*livekit.RegionInfo{{Region: "us-east", Url: "wss://us-east.example.com"}}, + }) + p := newTestProvider(rs) + + for _, near := range []string{"us-west", "", "us-west"} { + _, err := p.RegionSettings(rs.hostname, "test-token", near) + require.NoError(t, err) + } + require.Equal(t, []string{"us-west", ""}, rs.nears) // the second "us-west" is cached +} diff --git a/room.go b/room.go index 9bbfa14b..976776f6 100644 --- a/room.go +++ b/room.go @@ -218,9 +218,13 @@ func WithDisableRegionDiscovery() ConnectOption { } } -// WithPreferredRegion tries region first, before the regions from region -// discovery. Use it when the caller knows its own region. If that attempt -// fails, the SDK tries the discovered regions, then the original URL. +// WithPreferredRegion tries region first, then the regions from region +// discovery, then the original URL. Use it when the caller knows its own region. +// +// Discovery ranks the regions by distance from region. If the list does not +// include region, the project cannot use it, and the SDK skips it. A server +// that does not support this ranking can leave out region even when the +// project can use it. func WithPreferredRegion(region *livekit.RegionInfo) ConnectOption { return func(p *connParams) { if region == nil || region.Region == "" || region.Url == "" { @@ -456,14 +460,20 @@ func (r *Room) SID() string { return r.sid } -// PrepareConnection - with LiveKit Cloud, determine the best edge data center for the current client to connect to -func (r *Room) PrepareConnection(url, token string) error { +// PrepareConnection - with LiveKit Cloud, determine the best edge data center for the current client to connect to. +// Pass the same WithPreferredRegion option as to the join: the join reads a +// separate region list for each preferred region. +func (r *Room) PrepareConnection(url, token string, opts ...ConnectOption) error { cloudHostname, _ := parseCloudURL(url) if cloudHostname == "" { return nil } + params := &connParams{ConnectParams: &signalling.ConnectParams{}} + for _, opt := range opts { + opt(params) + } - return r.regionURLProvider.RefreshRegionSettings(cloudHostname, token) + return r.regionURLProvider.RefreshRegionSettings(cloudHostname, token, params.preferredRegion.GetRegion()) } // Join - joins the room with default permissions