-
Notifications
You must be signed in to change notification settings - Fork 168
Expand file tree
/
Copy pathregionurlprovider.go
More file actions
211 lines (186 loc) · 6.42 KB
/
Copy pathregionurlprovider.go
File metadata and controls
211 lines (186 loc) · 6.42 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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
package lksdk
import (
"errors"
"fmt"
"io"
"net/http"
"net/url"
"strconv"
"strings"
"sync"
"time"
"google.golang.org/protobuf/encoding/protojson"
"github.com/livekit/protocol/livekit"
)
const (
regionHostnameProviderSettingsCacheTime = 3 * time.Second
// regionDiscoveryTimeout bounds a single /settings/regions fetch so a slow
// or unreachable endpoint doesn't stall the failover path.
regionDiscoveryTimeout = 2 * time.Second
)
// regionSettingsURL builds the LiveKit Cloud region-discovery URL for a hostname.
var regionSettingsURL = func(cloudHostname string) string {
return "https://" + cloudHostname + "/settings/regions"
}
// regionURLProvider supplies LiveKit Cloud region lists to the RTC signaling
// reconnect path. It is a thin token/https adapter over the shared regionCache,
// adding a default cache TTL and support for server-pushed region lists.
type regionURLProvider struct {
cache *regionCache
}
func newRegionURLProvider() *regionURLProvider {
return ®ionURLProvider{cache: newRegionCache()}
}
func (r *regionURLProvider) RefreshRegionSettings(cloudHostname, token string) error {
_, err := r.RegionSettings(cloudHostname, token)
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) {
headers := http.Header{"Authorization": []string{"Bearer " + token}}
settings, err := r.cache.get(cloudHostname, regionSettingsURL(cloudHostname), headers, regionHostnameProviderSettingsCacheTime)
if err != nil {
return nil, err
}
if settings == nil {
return nil, errors.New("no regions available")
}
if len(settings.Regions) == 0 {
logger.Warnw("no regions returned", nil, "cloudHostname", cloudHostname)
}
return settings, nil
}
// 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
// with a bearer token). The caller supplies the discovery URL so each path
// keeps its own URL scheme and test seams.
type regionCache struct {
mu sync.Mutex
client *http.Client
cache map[string]*regionCacheEntry
}
type regionCacheEntry struct {
settings *livekit.RegionSettings
fetchedAt time.Time
ttl time.Duration
}
func newRegionCache() *regionCache {
return ®ionCache{
client: &http.Client{Timeout: regionDiscoveryTimeout},
cache: make(map[string]*regionCacheEntry),
}
}
// get returns the cached region list for key, fetching discoveryURL if the
// cache is stale. The server's Cache-Control max-age sets the TTL; when absent,
// defaultTTL is used (0 means "do not cache"). Best-effort: on a fetch failure
// it serves a stale cached list when available, otherwise returns the error.
func (c *regionCache) get(key, discoveryURL string, headers http.Header, defaultTTL time.Duration) (*livekit.RegionSettings, error) {
key = strings.ToLower(key)
c.mu.Lock()
if entry := c.cache[key]; entry != nil && time.Since(entry.fetchedAt) < entry.ttl {
defer c.mu.Unlock()
return entry.settings, nil
}
c.mu.Unlock()
settings, ttl, err := c.fetch(discoveryURL, headers)
if err != nil {
c.mu.Lock()
defer c.mu.Unlock()
if entry := c.cache[key]; entry != nil {
return entry.settings, nil // serve stale on failure
}
return nil, err
}
if ttl <= 0 {
ttl = defaultTTL
}
if ttl > 0 {
c.mu.Lock()
c.cache[key] = ®ionCacheEntry{settings: settings, fetchedAt: time.Now(), ttl: ttl}
c.mu.Unlock()
}
return settings, nil
}
// set stores a region list pushed out-of-band (e.g. by the server on reconnect),
// overriding any cached list and keeping the existing TTL, or defaultTTL.
func (c *regionCache) set(key string, settings *livekit.RegionSettings, defaultTTL time.Duration) {
if settings == nil {
return
}
key = strings.ToLower(key)
c.mu.Lock()
defer c.mu.Unlock()
ttl := defaultTTL
if existing := c.cache[key]; existing != nil && existing.ttl > 0 {
ttl = existing.ttl
}
c.cache[key] = ®ionCacheEntry{settings: settings, fetchedAt: time.Now(), ttl: ttl}
}
func (c *regionCache) fetch(discoveryURL string, headers http.Header) (*livekit.RegionSettings, time.Duration, error) {
req, err := http.NewRequest(http.MethodGet, discoveryURL, nil)
if err != nil {
return nil, 0, err
}
// Forward the caller's headers (Authorization and any custom headers),
// minus body-specific ones, so a validly-signed token reaches the discovery
// endpoint and test directives propagate.
for k, vv := range headers {
switch http.CanonicalHeaderKey(k) {
case "Content-Type", "Content-Length":
continue
}
for _, v := range vv {
req.Header.Add(k, v)
}
}
resp, err := c.client.Do(req)
if err != nil {
return nil, 0, err
}
defer drainResponse(resp)
if resp.StatusCode != http.StatusOK {
return nil, 0, &RegionError{StatusCode: resp.StatusCode}
}
b, err := io.ReadAll(resp.Body)
if err != nil {
return nil, 0, err
}
settings := &livekit.RegionSettings{}
if err := protojson.Unmarshal(b, settings); err != nil {
return nil, 0, err
}
ttl := parseRegionSettingsMaxAge(resp.Header.Get("Cache-Control"))
return settings, ttl, nil
}
// parseRegionSettingsMaxAge extracts the max-age (seconds) from a Cache-Control
// header value, returning 0 when absent or unparseable. Directive names are
// case-insensitive per RFC 9111.
func parseRegionSettingsMaxAge(cacheControl string) time.Duration {
for _, directive := range strings.Split(cacheControl, ",") {
directive = strings.ToLower(strings.TrimSpace(directive))
if strings.HasPrefix(directive, "max-age=") {
if secs, err := strconv.Atoi(strings.TrimPrefix(directive, "max-age=")); err == nil && secs > 0 {
return time.Duration(secs) * time.Second
}
}
}
return 0
}
func parseCloudURL(serverURL string) (string, error) {
parsedURL, err := url.Parse(serverURL)
if err != nil {
return "", fmt.Errorf("invalid server url (%s): %v", serverURL, err)
}
if !isCloud(parsedURL.Hostname()) {
return "", errors.New("not a cloud url")
}
return parsedURL.Hostname(), nil
}
// isCloud reports whether the hostname belongs to a LiveKit Cloud project
// (a *.livekit.cloud subdomain).
var isCloud = func(hostname string) bool {
return strings.HasSuffix(hostname, ".livekit.cloud")
}