Skip to content
Merged
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
8 changes: 6 additions & 2 deletions livekit-api/livekit/api/twirp_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ def __init__(
if scheme.startswith("ws"):
scheme = scheme.replace("ws", "http")

host = f"{scheme}://{parse_res.netloc}/{parse_res.path}"
host = f"{scheme}://{parse_res.netloc}{parse_res.path}"
self.host = host.rstrip("/")
self.pkg = pkg
self.prefix = prefix
Expand Down Expand Up @@ -248,10 +248,13 @@ async def request(
attempted = {host_key(self._origin)}
region_origins: Optional[List[str]] = None
current_origin = self._origin
# The configured host may carry a base path (e.g. behind a reverse
# proxy); fallback regions are bare origins.
current_base = self.host

for attempt in range(max_attempts):
is_last = attempt + 1 >= max_attempts
url = f"{current_origin}/{path}"
url = f"{current_base}/{path}"

transport_exc: Optional[BaseException] = None
retryable_status: Optional[int] = None
Expand Down Expand Up @@ -298,6 +301,7 @@ async def request(
await asyncio.sleep(self._failover_backoff * (2**attempt))
attempted.add(host_key(next_origin))
current_origin = next_origin
current_base = next_origin

raise RuntimeError("failover loop exited without returning") # unreachable

Expand Down
69 changes: 69 additions & 0 deletions tests/api/test_twirp_client.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
# Copyright 2026 LiveKit, Inc.
#
# 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 asyncio
from typing import List

import pytest

from livekit.api.twirp_client import TwirpClient
from livekit.protocol.room import ListRoomsRequest, ListRoomsResponse


class _Response:
status = 200

async def read(self) -> bytes:
return ListRoomsResponse().SerializeToString()


class _Post:
async def __aenter__(self) -> _Response:
return _Response()

async def __aexit__(self, *exc) -> None:
return None


class _RecordingSession:
timeout = None

def __init__(self) -> None:
self.urls: List[str] = []

def post(self, url: str, **kwargs) -> _Post:
self.urls.append(url)
return _Post()


def _requested_url(host: str) -> str:
session = _RecordingSession()
client = TwirpClient(session, host, "livekit") # type: ignore[arg-type]
asyncio.run(
client.request("RoomService", "ListRooms", ListRoomsRequest(), {}, ListRoomsResponse)
)
return session.urls[0]


@pytest.mark.parametrize(
("host", "expected"),
[
("wss://example.livekit.cloud", "https://example.livekit.cloud"),
("http://localhost:7880/", "http://localhost:7880"),
("https://proxy.example.com/livekit", "https://proxy.example.com/livekit"),
("wss://proxy.example.com/livekit/", "https://proxy.example.com/livekit"),
],
)
def test_request_url_keeps_the_base_path(host: str, expected: str) -> None:
assert _requested_url(host) == f"{expected}/twirp/livekit.RoomService/ListRooms"
Loading