|
| 1 | +# Copyright 2026 LiveKit, Inc. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Region failover for the Twirp API clients. |
| 16 | +
|
| 17 | +On a retryable failure (any transport error or HTTP 5xx) the client discovers |
| 18 | +alternative LiveKit Cloud regions via ``/settings/regions`` and replays the |
| 19 | +request against the next region, with exponential backoff. 4xx responses are |
| 20 | +returned immediately. |
| 21 | +""" |
| 22 | + |
| 23 | +from __future__ import annotations |
| 24 | + |
| 25 | +import time |
| 26 | +from dataclasses import dataclass |
| 27 | +from typing import Dict, List, Optional |
| 28 | +from urllib.parse import urlparse |
| 29 | + |
| 30 | +import aiohttp |
| 31 | + |
| 32 | +FAILOVER_MAX_ATTEMPTS = 3 |
| 33 | +FAILOVER_BACKOFF_BASE = 0.2 # seconds |
| 34 | + |
| 35 | + |
| 36 | +def failover_attempts(enabled: bool, host: Optional[str], force: bool = False) -> int: |
| 37 | + """Total request attempts for a host; 1 means no failover. Failover only |
| 38 | + engages when enabled and the host is a LiveKit Cloud domain. ``force`` |
| 39 | + bypasses the cloud-host check and is for internal testing only. |
| 40 | + """ |
| 41 | + if enabled and (force or (host is not None and is_cloud(host))): |
| 42 | + return FAILOVER_MAX_ATTEMPTS |
| 43 | + return 1 |
| 44 | + |
| 45 | + |
| 46 | +def is_cloud(host: str) -> bool: |
| 47 | + # Failover only engages for LiveKit Cloud project domains. |
| 48 | + return host.endswith(".livekit.cloud") |
| 49 | + |
| 50 | + |
| 51 | +def to_http(url: str) -> str: |
| 52 | + """Normalizes a region URL to an http(s) scheme (ws -> http, wss -> https).""" |
| 53 | + if url.startswith("ws"): |
| 54 | + return "http" + url[2:] |
| 55 | + return url |
| 56 | + |
| 57 | + |
| 58 | +def origin_of(url: str) -> str: |
| 59 | + """Returns the scheme://host[:port] origin of a URL, dropping any path.""" |
| 60 | + parsed = urlparse(url) |
| 61 | + return f"{parsed.scheme}://{parsed.netloc}" |
| 62 | + |
| 63 | + |
| 64 | +def host_key(url: str) -> str: |
| 65 | + """A stable key identifying a host (including port) for dedup across attempts.""" |
| 66 | + return urlparse(url).netloc.lower() |
| 67 | + |
| 68 | + |
| 69 | +def pick_next(region_origins: List[str], attempted: set[str]) -> Optional[str]: |
| 70 | + """Returns the first region origin whose host has not yet been attempted.""" |
| 71 | + for origin in region_origins: |
| 72 | + if host_key(origin) not in attempted: |
| 73 | + return origin |
| 74 | + return None |
| 75 | + |
| 76 | + |
| 77 | +@dataclass |
| 78 | +class _CacheEntry: |
| 79 | + origins: List[str] |
| 80 | + fetched_at: float |
| 81 | + ttl: float |
| 82 | + |
| 83 | + |
| 84 | +class RegionCache: |
| 85 | + """Process-wide cache of the LiveKit Cloud region list, keyed by host.""" |
| 86 | + |
| 87 | + def __init__(self) -> None: |
| 88 | + self._entries: Dict[str, _CacheEntry] = {} |
| 89 | + |
| 90 | + async def region_origins( |
| 91 | + self, |
| 92 | + session: aiohttp.ClientSession, |
| 93 | + origin: str, |
| 94 | + headers: Dict[str, str], |
| 95 | + ) -> List[str]: |
| 96 | + """Returns alternative region origins for ``origin``, fetching |
| 97 | + ``/settings/regions`` if the cache is stale. Best-effort: on a fetch |
| 98 | + failure it serves a stale cached list when available, otherwise an empty |
| 99 | + list. Forwards ``headers`` so a valid token — and any test directives — |
| 100 | + reach the discovery endpoint.""" |
| 101 | + key = host_key(origin) |
| 102 | + entry = self._entries.get(key) |
| 103 | + if entry is not None and (time.monotonic() - entry.fetched_at) < entry.ttl: |
| 104 | + return entry.origins |
| 105 | + |
| 106 | + try: |
| 107 | + origins, ttl = await self._fetch(session, origin, headers) |
| 108 | + except Exception: |
| 109 | + return entry.origins if entry is not None else [] |
| 110 | + |
| 111 | + # A zero TTL (e.g. Cache-Control: max-age=0) means "do not cache". |
| 112 | + if ttl > 0: |
| 113 | + self._entries[key] = _CacheEntry(origins, time.monotonic(), ttl) |
| 114 | + return origins |
| 115 | + |
| 116 | + async def _fetch( |
| 117 | + self, |
| 118 | + session: aiohttp.ClientSession, |
| 119 | + origin: str, |
| 120 | + headers: Dict[str, str], |
| 121 | + ) -> tuple[List[str], float]: |
| 122 | + fetch_headers = { |
| 123 | + k: v for k, v in headers.items() if k.lower() not in ("content-type", "content-length") |
| 124 | + } |
| 125 | + # Short timeout so a slow/unreachable discovery endpoint doesn't stall |
| 126 | + # the failover path. |
| 127 | + async with session.get( |
| 128 | + f"{origin}/settings/regions", |
| 129 | + headers=fetch_headers, |
| 130 | + timeout=aiohttp.ClientTimeout(total=2), |
| 131 | + ) as resp: |
| 132 | + if resp.status != 200: |
| 133 | + raise RuntimeError(f"region discovery failed: {resp.status}") |
| 134 | + ttl = _parse_max_age(resp.headers.get("Cache-Control")) |
| 135 | + body = await resp.json() |
| 136 | + origins = [origin_of(to_http(r["url"])) for r in body.get("regions", []) if r.get("url")] |
| 137 | + return origins, ttl |
| 138 | + |
| 139 | + |
| 140 | +def _parse_max_age(cache_control: Optional[str]) -> float: |
| 141 | + if not cache_control: |
| 142 | + return 0.0 |
| 143 | + for directive in cache_control.split(","): |
| 144 | + directive = directive.strip().lower() |
| 145 | + if directive.startswith("max-age="): |
| 146 | + try: |
| 147 | + return float(int(directive[len("max-age=") :])) |
| 148 | + except ValueError: |
| 149 | + return 0.0 |
| 150 | + return 0.0 |
0 commit comments