Skip to content

Commit bc4e386

Browse files
fix(api): apply a timeout to every API request
TwirpClient.request forwarded its `timeout` argument to session.post even when it was None. aiohttp reads an explicit `timeout=None` as "no timeout at all" — only a *missing* argument selects the session timeout — so every call that did not pass its own timeout ran unbounded and the session's 10s default never applied. A host that accepts the connection and never answers therefore blocked the call forever, and region failover never started, because failover only begins once an attempt fails. The same function already read `self._session.timeout.total` to size the failover budget, so it assumed the session timeout governed the request while the post call discarded it. Resolve the timeout once, per call override -> client default -> session, and pass the result explicitly, so both uses agree. Also make `LiveKitAPI(timeout=...)` mean something when the caller supplies a session. It was read only on the path where the SDK built the session, so `LiveKitAPI(session=..., timeout=...)` silently ignored the timeout even though it is documented as the request timeout. The value now reaches TwirpClient through Service, letting a caller give API calls a deadline without changing the timeout of other traffic on a shared session. A supplied session with no explicit timeout keeps its own, as before. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
1 parent 407502d commit bc4e386

11 files changed

Lines changed: 253 additions & 21 deletions

‎.changeset/api-request-timeout.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"livekit-api": patch
3+
---
4+
5+
Apply a timeout to every API request. Requests previously ignored the session timeout and waited indefinitely, so a host that accepted the connection but never answered blocked the call and prevented region failover. `LiveKitAPI(timeout=...)` now also applies when a session is supplied by the caller, giving API calls a deadline without changing the timeout of other traffic sharing that session.

‎livekit-api/livekit/api/_service.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,9 @@ def __init__(
2424
api_key: str,
2525
api_secret: str,
2626
failover: bool = True,
27+
timeout: aiohttp.ClientTimeout | None = None,
2728
):
28-
self._client = TwirpClient(session, host, "livekit", failover=failover)
29+
self._client = TwirpClient(session, host, "livekit", failover=failover, timeout=timeout)
2930
self.api_key = api_key
3031
self.api_secret = api_secret
3132
# A pre-signed token set by LiveKitAPI for token auth; sent verbatim,

‎livekit-api/livekit/api/agent_dispatch_service.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,9 @@ def __init__(
3333
api_key: str,
3434
api_secret: str,
3535
failover: bool = True,
36+
timeout: Optional[aiohttp.ClientTimeout] = None,
3637
):
37-
super().__init__(session, url, api_key, api_secret, failover=failover)
38+
super().__init__(session, url, api_key, api_secret, failover=failover, timeout=timeout)
3839

3940
async def create_dispatch(self, req: CreateAgentDispatchRequest) -> AgentDispatch:
4041
"""Create an explicit dispatch for an agent to join a room.

‎livekit-api/livekit/api/connector_service.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,9 @@ def __init__(
4444
api_key: str,
4545
api_secret: str,
4646
failover: bool = True,
47+
timeout: Optional[aiohttp.ClientTimeout] = None,
4748
):
48-
super().__init__(session, url, api_key, api_secret, failover=failover)
49+
super().__init__(session, url, api_key, api_secret, failover=failover, timeout=timeout)
4950

5051
async def dial_whatsapp_call(
5152
self, request: DialWhatsAppCallRequest

‎livekit-api/livekit/api/egress_service.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
)
1616
from ._service import Service
1717
from .access_token import VideoGrants
18+
from typing import Optional
1819

1920
SVC = "Egress"
2021
"""@private"""
@@ -41,8 +42,9 @@ def __init__(
4142
api_key: str,
4243
api_secret: str,
4344
failover: bool = True,
45+
timeout: Optional[aiohttp.ClientTimeout] = None,
4446
):
45-
super().__init__(session, url, api_key, api_secret, failover=failover)
47+
super().__init__(session, url, api_key, api_secret, failover=failover, timeout=timeout)
4648

4749
async def start_room_composite_egress(self, start: RoomCompositeEgressRequest) -> EgressInfo:
4850
"""Starts a composite recording of a room."""

‎livekit-api/livekit/api/ingress_service.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
)
1010
from ._service import Service
1111
from .access_token import VideoGrants
12+
from typing import Optional
1213

1314
SVC = "Ingress"
1415
"""@private"""
@@ -35,8 +36,9 @@ def __init__(
3536
api_key: str,
3637
api_secret: str,
3738
failover: bool = True,
39+
timeout: Optional[aiohttp.ClientTimeout] = None,
3840
):
39-
super().__init__(session, url, api_key, api_secret, failover=failover)
41+
super().__init__(session, url, api_key, api_secret, failover=failover, timeout=timeout)
4042

4143
async def create_ingress(self, create: CreateIngressRequest) -> IngressInfo:
4244
return await self._client.request(

‎livekit-api/livekit/api/livekit_api.py‎

Lines changed: 21 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,11 @@ def __init__(
4949
token: Pre-signed access token (read from `LIVEKIT_TOKEN` environment variable if not provided)
5050
token_provider: Async callable that returns a token for the grants of each call,
5151
in place of signing one with api_key and api_secret
52-
timeout: Request timeout (default: 10 seconds)
52+
timeout: Per-request timeout, applied to every API call. Defaults to
53+
10 seconds when this instance creates its own session. When a
54+
`session` is supplied, it defaults to that session's timeout;
55+
pass this to give API calls a deadline of their own without
56+
changing the timeout of other traffic sharing the session.
5357
session: aiohttp.ClientSession instance to use for requests, if not provided, a new one will be created
5458
"""
5559
url = url or os.getenv("LIVEKIT_URL")
@@ -84,12 +88,17 @@ def __init__(
8488
# the token, injected into each service below.
8589
key = api_key or ""
8690
secret = api_secret or ""
87-
self._room = RoomService(self._session, url, key, secret, failover)
88-
self._ingress = IngressService(self._session, url, key, secret, failover)
89-
self._egress = EgressService(self._session, url, key, secret, failover)
90-
self._sip = SipService(self._session, url, key, secret, failover)
91-
self._agent_dispatch = AgentDispatchService(self._session, url, key, secret, failover)
92-
self._connector = ConnectorService(self._session, url, key, secret, failover)
91+
# Passed to every service so that `timeout` applies to API calls even
92+
# when the session belongs to the caller, whose timeout is typically
93+
# tuned for other traffic sharing that session.
94+
self._room = RoomService(self._session, url, key, secret, failover, timeout)
95+
self._ingress = IngressService(self._session, url, key, secret, failover, timeout)
96+
self._egress = EgressService(self._session, url, key, secret, failover, timeout)
97+
self._sip = SipService(self._session, url, key, secret, failover, timeout)
98+
self._agent_dispatch = AgentDispatchService(
99+
self._session, url, key, secret, failover, timeout
100+
)
101+
self._connector = ConnectorService(self._session, url, key, secret, failover, timeout)
93102

94103
if token or token_provider:
95104
for svc in (
@@ -122,7 +131,11 @@ def with_token(
122131
Args:
123132
token: Pre-signed access token
124133
url: LiveKit server URL (read from `LIVEKIT_URL` if not provided)
125-
timeout: Request timeout (default: 10 seconds)
134+
timeout: Per-request timeout, applied to every API call. Defaults to
135+
10 seconds when this instance creates its own session. When a
136+
`session` is supplied, it defaults to that session's timeout;
137+
pass this to give API calls a deadline of their own without
138+
changing the timeout of other traffic sharing the session.
126139
session: aiohttp.ClientSession to use; a new one is created if omitted
127140
"""
128141
return cls(url, token=token, timeout=timeout, session=session, failover=failover)

‎livekit-api/livekit/api/room_service.py‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
from livekit.protocol.models import Room, ParticipantInfo
2727
from ._service import Service
2828
from .access_token import VideoGrants
29+
from typing import Optional
2930

3031
SVC = "RoomService"
3132
"""@private"""
@@ -52,8 +53,9 @@ def __init__(
5253
api_key: str,
5354
api_secret: str,
5455
failover: bool = True,
56+
timeout: Optional[aiohttp.ClientTimeout] = None,
5557
):
56-
super().__init__(session, url, api_key, api_secret, failover=failover)
58+
super().__init__(session, url, api_key, api_secret, failover=failover, timeout=timeout)
5759

5860
async def create_room(
5961
self,

‎livekit-api/livekit/api/sip_service.py‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,8 +76,9 @@ def __init__(
7676
api_key: str,
7777
api_secret: str,
7878
failover: bool = True,
79+
timeout: Optional[aiohttp.ClientTimeout] = None,
7980
):
80-
super().__init__(session, url, api_key, api_secret, failover=failover)
81+
super().__init__(session, url, api_key, api_secret, failover=failover, timeout=timeout)
8182

8283
async def create_inbound_trunk(
8384
self, create: CreateSIPInboundTrunkRequest

‎livekit-api/livekit/api/twirp_client.py‎

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,7 @@ def __init__(
195195
prefix: str = DEFAULT_PREFIX,
196196
failover: bool = True,
197197
*,
198+
timeout: Optional[aiohttp.ClientTimeout] = None,
198199
_failover_force: bool = False,
199200
_failover_backoff: float = FAILOVER_BACKOFF_BASE,
200201
) -> None:
@@ -208,6 +209,10 @@ def __init__(
208209
self.pkg = pkg
209210
self.prefix = prefix
210211
self._session = session
212+
# Applies to every request this client issues, unless a call passes its
213+
# own. Lets a caller who supplies a shared session still give the API a
214+
# deadline of its own, without touching the session's.
215+
self._timeout = timeout
211216
# _failover_force / _failover_backoff are internal test-only knobs.
212217
self._failover = failover
213218
self._failover_force = _failover_force
@@ -237,11 +242,18 @@ async def request(
237242
headers[REQUEST_ID_HEADER] = str(uuid.uuid4())
238243
serialized_data = data.SerializeToString()
239244

240-
# The effective per-attempt timeout is the per-call override, or the
241-
# session default; used to gate failover for short requests.
242-
effective_timeout = timeout.total if timeout else None
243-
if effective_timeout is None and self._session.timeout is not None:
244-
effective_timeout = self._session.timeout.total
245+
# The per-attempt timeout is the per-call override, then this client's
246+
# default, then the session default. aiohttp treats an explicit
247+
# ``timeout=None`` as "no timeout at all" rather than "use the session
248+
# default" — only a *missing* argument selects the session timeout — so
249+
# resolve the fallback here and pass the result explicitly.
250+
request_timeout = timeout
251+
if request_timeout is None:
252+
request_timeout = self._timeout
253+
if request_timeout is None:
254+
request_timeout = self._session.timeout
255+
# Used to gate failover for short requests.
256+
effective_timeout = request_timeout.total if request_timeout is not None else None
245257
host = urlparse(self._origin).hostname
246258
max_attempts = failover_attempts(
247259
self._failover, host, self._failover_force, effective_timeout
@@ -263,7 +275,7 @@ async def request(
263275
error_data: Dict = {}
264276
try:
265277
async with self._session.post(
266-
url, headers=headers, data=serialized_data, timeout=timeout
278+
url, headers=headers, data=serialized_data, timeout=request_timeout
267279
) as resp:
268280
if resp.status == 200:
269281
return response_class.FromString(await resp.read())

0 commit comments

Comments
 (0)