Skip to content

Commit d1fe6e5

Browse files
committed
livekit-api: unreadable successes are malformed ServerErrors, empty ids fail early, 499/502 mapped
1 parent c410dc2 commit d1fe6e5

2 files changed

Lines changed: 75 additions & 18 deletions

File tree

‎livekit-api/livekit/api/public_api_client.py‎

Lines changed: 44 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,10 @@
1414

1515
from __future__ import annotations
1616

17+
import inspect
1718
import json
1819
from collections.abc import Awaitable
19-
from typing import Any, Callable, Dict, Optional, Type, TypeVar
20+
from typing import Any, Callable, Dict, Optional, Tuple, Type, TypeVar
2021
from urllib.parse import urlparse
2122

2223
import aiohttp
@@ -41,7 +42,9 @@
4142
404: ServerErrorCode.NOT_FOUND,
4243
409: ServerErrorCode.ALREADY_EXISTS,
4344
429: ServerErrorCode.RESOURCE_EXHAUSTED,
45+
499: ServerErrorCode.CANCELED,
4446
501: ServerErrorCode.UNIMPLEMENTED,
47+
502: ServerErrorCode.UNAVAILABLE,
4548
503: ServerErrorCode.UNAVAILABLE,
4649
504: ServerErrorCode.DEADLINE_EXCEEDED,
4750
}
@@ -97,8 +100,8 @@ async def request(
97100
) -> M:
98101
"""Calls a generated operation and parses its JSON (or its `field`) into `response_class`.
99102
A parameter at its protobuf default (`""`, `0`) is left unset."""
100-
data = await self._call(operation=operation, headers=headers, params=params)
101-
return _parse(data.get(field) if field else data, response_class)
103+
data, status = await self._call(operation=operation, headers=headers, params=params)
104+
return _parse(data.get(field) if field else data, response_class, status)
102105

103106
async def list(
104107
self,
@@ -113,36 +116,64 @@ async def list(
113116
) -> M:
114117
"""Calls a generated list operation for one page: its `items` and `pageInfo` become the
115118
protocol response's `items` field and `next_page_token`."""
116-
data = await self._call(
119+
data, status = await self._call(
117120
operation=operation,
118121
headers=headers,
119122
# A limit of zero or below leaves the page size to the server.
120123
params={"page_cursor": page_token, "page_page_size": max(limit, 0), **params},
121124
)
122125
next_page = (data.get("pageInfo") or {}).get("nextCursor", "")
123-
return _parse({items: data.get("items"), "nextPageToken": next_page}, response_class)
126+
page = {items: data.get("items"), "nextPageToken": next_page}
127+
return _parse(page, response_class, status)
124128

125129
async def _call(
126130
self,
127131
*,
128132
operation: Callable[..., Awaitable[aiohttp.ClientResponse]],
129133
headers: Dict[str, str],
130134
params: Dict[str, Any],
131-
) -> Dict[str, Any]:
132-
set_params = {k: v for k, v in params.items() if v not in (None, "", 0)}
135+
) -> Tuple[Dict[str, Any], int]:
136+
"""The JSON object of a successful response and its status. Required parameters (the
137+
operation's own, without a default) must be set; optional ones at their protobuf
138+
default are left unset."""
139+
required = {
140+
name
141+
for name, p in inspect.signature(operation).parameters.items()
142+
if p.default is p.empty and p.kind in (p.POSITIONAL_OR_KEYWORD, p.KEYWORD_ONLY)
143+
}
144+
for name in required & params.keys():
145+
if params[name] in (None, ""):
146+
raise ValueError(f"{name} must not be empty")
147+
set_params = {k: v for k, v in params.items() if k in required or v not in (None, "", 0)}
133148
resp = await operation(
134149
project_id=PROJECT, _headers=headers, _request_timeout=self.timeout, **set_params
135150
)
136-
body = await resp.read()
151+
try:
152+
body = await resp.read()
153+
finally:
154+
resp.release()
137155
if not 200 <= resp.status < 300:
138156
raise _server_error(body, resp.status)
139-
data = json.loads(body) if body else {}
140-
return data if isinstance(data, dict) else {}
157+
try:
158+
data = json.loads(body) if body else {}
159+
except ValueError:
160+
data = None
161+
if not isinstance(data, dict):
162+
raise _malformed("response is not a JSON object", body, resp.status)
163+
return data, resp.status
141164

142165

143-
def _parse(data: Any, response_class: Type[M]) -> M:
166+
def _parse(data: Any, response_class: Type[M], status: int) -> M:
144167
# Fields this SDK doesn't know yet are ignored.
145-
return json_format.ParseDict(data or {}, response_class(), ignore_unknown_fields=True)
168+
try:
169+
return json_format.ParseDict(data or {}, response_class(), ignore_unknown_fields=True)
170+
except json_format.ParseError as e:
171+
raise ServerError(ServerErrorCode.MALFORMED, f"malformed response: {e}", status=status)
172+
173+
174+
def _malformed(reason: str, body: bytes, status: int) -> ServerError:
175+
snippet = body[:200].decode("utf-8", errors="replace")
176+
return ServerError(ServerErrorCode.MALFORMED, f"{reason}: {snippet}", status=status)
146177

147178

148179
def _server_error(body: bytes, status: int) -> ServerError:
@@ -162,7 +193,7 @@ def _server_error(body: bytes, status: int) -> ServerError:
162193
code = _STATUS_CODES.get(status) or (
163194
ServerErrorCode.INTERNAL if status >= 500 else ServerErrorCode.UNKNOWN
164195
)
165-
return ServerError(code, msg or text, status=status)
196+
return ServerError(code, msg or text or f"HTTP {status}", status=status)
166197

167198

168199
def to_json(msg: Message) -> Dict[str, Any]:

‎tests/api/test_public_api.py‎

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,9 @@ def run(
5757
reply: Reply = (200, {}),
5858
*,
5959
token: Optional[str] = None,
60-
) -> Tuple[Any, Recorded]:
60+
) -> Tuple[Any, Any]:
6161
"""Runs `call` against a server answering every request with `reply`, and
62-
returns its result with the one request the server received."""
62+
returns its result with the one request the server received (None when none was sent)."""
6363
requests: List[Recorded] = []
6464

6565
async def handle(request: web.Request) -> web.Response:
@@ -82,8 +82,8 @@ async def main() -> Any:
8282
return await call(lkapi)
8383

8484
result = asyncio.run(main())
85-
assert len(requests) == 1
86-
return result, requests[0]
85+
assert len(requests) <= 1
86+
return result, requests[0] if requests else None
8787

8888

8989
def test_public_api_url_from_project_url():
@@ -292,7 +292,8 @@ def test_database_operations():
292292
((404, {"code": 5, "message": "thread not found"}), "not_found", "thread not found"),
293293
((409, {"code": "aborted", "message": "busy"}), "aborted", "busy"),
294294
((503, "upstream down"), "unavailable", "upstream down"),
295-
((502, {}), "internal", "{}"),
295+
((502, {}), "unavailable", "{}"),
296+
((499, ""), "canceled", "HTTP 499"),
296297
((418, {}), "unknown", "{}"),
297298
],
298299
)
@@ -306,6 +307,31 @@ async def call(lk: LiveKitAPI) -> ServerError:
306307
assert (err.code, err.message, err.status) == (code, message, reply[0])
307308

308309

310+
@pytest.mark.parametrize(
311+
"reply",
312+
[(200, "<html>gateway</html>"), (200, [1, 2]), (200, {"thread": {"attributes": "x"}})],
313+
)
314+
def test_a_success_the_sdk_cannot_read_is_malformed(reply: Reply):
315+
async def call(lk: LiveKitAPI) -> ServerError:
316+
with pytest.raises(ServerError) as err:
317+
await lk.threads.get_thread(thread_id="AT_1")
318+
return err.value
319+
320+
err, _ = run(call, reply)
321+
assert (err.code, err.status) == ("malformed", 200)
322+
323+
324+
def test_an_empty_id_fails_before_any_request():
325+
async def call(lk: LiveKitAPI) -> str:
326+
with pytest.raises(ValueError) as err:
327+
await lk.threads.get_thread(thread_id="")
328+
return str(err.value)
329+
330+
message, rec = run(call)
331+
assert message == "thread_id must not be empty"
332+
assert rec is None
333+
334+
309335
def test_services_share_the_session_and_timeout():
310336
async def main() -> Dict[str, Any]:
311337
async with aiohttp.ClientSession() as session:

0 commit comments

Comments
 (0)