|
| 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, TypedDict |
| 28 | +from urllib.parse import urlparse |
| 29 | + |
| 30 | +import aiohttp |
| 31 | + |
| 32 | +_DEFAULT_MAX_ATTEMPTS = 3 |
| 33 | +_DEFAULT_BACKOFF_BASE = 0.2 |
| 34 | + |
| 35 | + |
| 36 | +class FailoverConfig(TypedDict, total=False): |
| 37 | + """Region-failover tuning, passed as the ``failover`` argument. Use it as a |
| 38 | + plain dict, e.g. ``failover={"max_attempts": 5}``. All keys are optional. |
| 39 | +
|
| 40 | + Keys: |
| 41 | + max_attempts: total number of attempts including the initial request — |
| 42 | + the original host plus up to ``max_attempts - 1`` fallback regions. |
| 43 | + Defaults to 3. Set to 1 to disable failover (a single attempt). |
| 44 | + backoff_base: seconds before the first retry; each subsequent retry |
| 45 | + doubles it. Defaults to 0.2. |
| 46 | + """ |
| 47 | + |
| 48 | + max_attempts: int |
| 49 | + backoff_base: float |
| 50 | + |
| 51 | + |
| 52 | +def failover_attempts(failover: Optional[FailoverConfig], host: Optional[str]) -> int: |
| 53 | + """Total request attempts including the initial one; 1 means no failover. |
| 54 | +
|
| 55 | + With no config (``None``) failover is enabled only for LiveKit Cloud hosts. |
| 56 | + An explicit config enables it for any host; ``max_attempts=1`` disables it. |
| 57 | + """ |
| 58 | + if failover is None: |
| 59 | + return _DEFAULT_MAX_ATTEMPTS if (bool(host) and is_cloud(host)) else 1 # type: ignore[arg-type] |
| 60 | + return max(1, failover.get("max_attempts", _DEFAULT_MAX_ATTEMPTS)) |
| 61 | + |
| 62 | + |
| 63 | +def failover_backoff_base(failover: Optional[FailoverConfig]) -> float: |
| 64 | + return (failover or {}).get("backoff_base", _DEFAULT_BACKOFF_BASE) |
| 65 | + |
| 66 | + |
| 67 | +def is_cloud(host: str) -> bool: |
| 68 | + # Auto mode only enables failover for LiveKit Cloud project domains. |
| 69 | + return host.endswith(".livekit.cloud") |
| 70 | + |
| 71 | + |
| 72 | +def to_http(url: str) -> str: |
| 73 | + """Normalizes a region URL to an http(s) scheme (ws -> http, wss -> https).""" |
| 74 | + if url.startswith("ws"): |
| 75 | + return "http" + url[2:] |
| 76 | + return url |
| 77 | + |
| 78 | + |
| 79 | +def origin_of(url: str) -> str: |
| 80 | + """Returns the scheme://host[:port] origin of a URL, dropping any path.""" |
| 81 | + parsed = urlparse(url) |
| 82 | + return f"{parsed.scheme}://{parsed.netloc}" |
| 83 | + |
| 84 | + |
| 85 | +def host_key(url: str) -> str: |
| 86 | + """A stable key identifying a host (including port) for dedup across attempts.""" |
| 87 | + return urlparse(url).netloc.lower() |
| 88 | + |
| 89 | + |
| 90 | +def pick_next(region_origins: List[str], attempted: set[str]) -> Optional[str]: |
| 91 | + """Returns the first region origin whose host has not yet been attempted.""" |
| 92 | + for origin in region_origins: |
| 93 | + if host_key(origin) not in attempted: |
| 94 | + return origin |
| 95 | + return None |
| 96 | + |
| 97 | + |
| 98 | +@dataclass |
| 99 | +class _CacheEntry: |
| 100 | + origins: List[str] |
| 101 | + fetched_at: float |
| 102 | + ttl: float |
| 103 | + |
| 104 | + |
| 105 | +class RegionCache: |
| 106 | + """Process-wide cache of the LiveKit Cloud region list, keyed by host.""" |
| 107 | + |
| 108 | + def __init__(self) -> None: |
| 109 | + self._entries: Dict[str, _CacheEntry] = {} |
| 110 | + |
| 111 | + async def region_origins( |
| 112 | + self, |
| 113 | + session: aiohttp.ClientSession, |
| 114 | + origin: str, |
| 115 | + headers: Dict[str, str], |
| 116 | + ) -> List[str]: |
| 117 | + """Returns alternative region origins for ``origin``, fetching |
| 118 | + ``/settings/regions`` if the cache is stale. Best-effort: on a fetch |
| 119 | + failure it serves a stale cached list when available, otherwise an empty |
| 120 | + list. Forwards ``headers`` so a valid token — and any test directives — |
| 121 | + reach the discovery endpoint.""" |
| 122 | + key = host_key(origin) |
| 123 | + entry = self._entries.get(key) |
| 124 | + if entry is not None and (time.monotonic() - entry.fetched_at) < entry.ttl: |
| 125 | + return entry.origins |
| 126 | + |
| 127 | + try: |
| 128 | + origins, ttl = await self._fetch(session, origin, headers) |
| 129 | + except Exception: |
| 130 | + return entry.origins if entry is not None else [] |
| 131 | + |
| 132 | + # A zero TTL (e.g. Cache-Control: max-age=0) means "do not cache". |
| 133 | + if ttl > 0: |
| 134 | + self._entries[key] = _CacheEntry(origins, time.monotonic(), ttl) |
| 135 | + return origins |
| 136 | + |
| 137 | + async def _fetch( |
| 138 | + self, |
| 139 | + session: aiohttp.ClientSession, |
| 140 | + origin: str, |
| 141 | + headers: Dict[str, str], |
| 142 | + ) -> tuple[List[str], float]: |
| 143 | + fetch_headers = { |
| 144 | + k: v for k, v in headers.items() if k.lower() not in ("content-type", "content-length") |
| 145 | + } |
| 146 | + async with session.get(f"{origin}/settings/regions", headers=fetch_headers) as resp: |
| 147 | + if resp.status != 200: |
| 148 | + raise RuntimeError(f"region discovery failed: {resp.status}") |
| 149 | + ttl = _parse_max_age(resp.headers.get("Cache-Control")) |
| 150 | + body = await resp.json() |
| 151 | + origins = [origin_of(to_http(r["url"])) for r in body.get("regions", []) if r.get("url")] |
| 152 | + return origins, ttl |
| 153 | + |
| 154 | + |
| 155 | +def _parse_max_age(cache_control: Optional[str]) -> float: |
| 156 | + if not cache_control: |
| 157 | + return 0.0 |
| 158 | + for directive in cache_control.split(","): |
| 159 | + directive = directive.strip().lower() |
| 160 | + if directive.startswith("max-age="): |
| 161 | + try: |
| 162 | + return float(int(directive[len("max-age=") :])) |
| 163 | + except ValueError: |
| 164 | + return 0.0 |
| 165 | + return 0.0 |
0 commit comments