diff --git a/CHANGELOG.md b/CHANGELOG.md index e1added..e766c2b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/). ## [Unreleased] +### Fixed + +- Reject malformed or mismatched Node session replies, attempt to stop rejected onchain sessions when the challenge ID is known, and try the next runner. + ### Added - `LiveRunnerRegistration.stop_session()` to stop reserved sessions diff --git a/src/livepeer_gateway/discovery.py b/src/livepeer_gateway/discovery.py index 06da4b5..19b4ab0 100644 --- a/src/livepeer_gateway/discovery.py +++ b/src/livepeer_gateway/discovery.py @@ -3,7 +3,7 @@ import asyncio import logging from typing import Any -from collections.abc import Sequence +from collections.abc import Callable, Sequence from urllib.parse import parse_qsl, quote, urlencode, urlparse, urlunparse from .errors import LivepeerGatewayError @@ -189,6 +189,7 @@ async def discover_orchestrator_runners( app: FilterValue | None = None, gpu: FilterValue | None = None, batch_size: int = _RUNNER_DISCOVERY_BATCH_SIZE, + _has_runners: Callable[[list[dict[str, Any]]], bool] = bool, ) -> list[dict[str, Any]]: first_error: Exception | None = None urls = orchestrator_discovery_urls(orchestrators) @@ -204,7 +205,7 @@ async def discover_orchestrator_runners( first_error = result _LOG.debug("discover_orchestrator_runners failed: %s (%s)", discovery_url, result) continue - if result: + if _has_runners(result): return result if first_error is not None: diff --git a/src/livepeer_gateway/http.py b/src/livepeer_gateway/http.py index 9c15c74..31a3b12 100644 --- a/src/livepeer_gateway/http.py +++ b/src/livepeer_gateway/http.py @@ -323,14 +323,10 @@ async def _post_empty( *, headers: dict[str, str] | None = None, timeout: float = 5.0, + allow_redirects: bool = True, ) -> None: """POST an empty body to ``url`` and discard the response.""" - await _request_body( - url, - method="POST", - headers=headers, - timeout=timeout, - ) + await _request_body(url, method="POST", headers=headers, timeout=timeout, allow_redirects=allow_redirects) def _parse_http_url(url: str, *, context: str = "URL") -> ParseResult: diff --git a/src/livepeer_gateway/live_runner.py b/src/livepeer_gateway/live_runner.py index 6e2afd0..3d88ef3 100644 --- a/src/livepeer_gateway/live_runner.py +++ b/src/livepeer_gateway/live_runner.py @@ -21,14 +21,14 @@ overload, ) from collections.abc import AsyncIterator, Awaitable, Callable, Mapping -from urllib.parse import quote, urlparse, urlunparse +from urllib.parse import quote, urlparse, urlsplit, urlunparse import aiohttp from aiohttp.helpers import parse_mimetype from .channel_reader import ChannelReader from .errors import LivepeerGatewayError, LivepeerHTTPError, SignerRefreshRequired -from .http import _close_response, _post_empty, _request_body, open_stream, post_json, request_json +from .http import _close_response, _parse_http_url, _post_empty, _request_body, open_stream, post_json, request_json from .remote_signer import ( LivePaymentChallenge, LivePaymentSession, @@ -850,6 +850,7 @@ async def call_runner( state = _stream_state(payload) owned = state is not None and not isinstance(payload, _StreamState) payload = state if state is not None else payload + method = method or ("POST" if payload is not None else "GET") try: runner_url = runner_url.strip() or (runner.url.strip() if runner is not None else "") if not runner_url: @@ -969,27 +970,32 @@ async def call_runner( await _stop_funding(pay_task) # Non-JSON bodies (an image, ndjson) are handed back unparsed in `content`. is_json = _is_json_content_type(response_content_type) - data: dict[str, Any] = {} - if is_json: - try: - data = json.loads(body) - except (UnicodeDecodeError, json.JSONDecodeError) as e: - raise LivepeerGatewayError( - f"HTTP JSON error: endpoint did not return valid JSON: {e} " - f"(url={runner_url}, content_type={response_content_type})" - ) from e + is_session = method.upper() == "POST" and _is_session_endpoint(runner_url, runner) + try: + data = json.loads(body) if is_json else {} if not isinstance(data, dict): - raise LivepeerGatewayError( - f"Live runner call expected JSON object, got {type(data).__name__}" - ) + raise LivepeerGatewayError(f"Live runner call expected JSON object, got {type(data).__name__}") + if is_session: + if missing := next((key for key in ("session_id", "app_url", "control_url") if not _string_value(data.get(key))), None): + raise LivepeerGatewayError(f"runner session response missing {missing}") + if session_id and not (session_id == data["session_id"] == data["session_id"].strip()): + raise LivepeerGatewayError("runner session response session_id does not match payment manifest") + _join_endpoint(data["control_url"], "stop") + except (LivepeerGatewayError, ValueError, RecursionError) as error: + if is_session and re.fullmatch(r"[\w-]{1,128}", session_id, re.ASCII): + with contextlib.suppress(Exception): + await _post_empty(_join_endpoint(runner_url, f"{session_id}/stop"), allow_redirects=False) + if isinstance(error, LivepeerGatewayError): + raise + raise LivepeerGatewayError( + f"HTTP JSON error: endpoint did not return valid JSON: {error} " + f"(url={runner_url}, content_type={response_content_type})" + ) from error return LiveRunnerCallResult( data, runner_url=runner_url, runner=runner, - session_id=( - session_id - or (data["session_id"].strip() if isinstance(data.get("session_id"), str) else "") - ), + session_id=session_id or _string_value(data.get("session_id")), payment_session=None if payment_type == "fixed" else payment_session, content=None if is_json else body, content_type=response_content_type, @@ -1122,6 +1128,20 @@ def _live_runner_price_info_from_json(value: object) -> LiveRunnerPriceInfo | No ) +def _is_session_endpoint(url: str, runner: LiveRunnerInstance | None) -> bool: + with contextlib.suppress(ValueError): + address = runner.orchestrator_url if runner else "" + base, target = urlsplit(address if "://" in address else f"https://{address}"), urlsplit(url) + default_port = 443 if target.scheme == "https" else 80 + origin = target.scheme, target.hostname, target.port if target.port is not None else default_port + single_shot = urlsplit(runner.url) if runner is not None and runner.mode == "single-shot" else None + same_orchestrator = not address or origin == (base.scheme, base.hostname, base.port if base.port is not None else default_port) + same_single_shot = single_shot and target.path.rstrip("/") == single_shot.path.rstrip("/") and origin == (single_shot.scheme, single_shot.hostname, single_shot.port if single_shot.port is not None else default_port) + has_http_origin = target.scheme in ("http", "https") and target.hostname is not None and target.port != 0 + return has_http_origin and same_orchestrator and not same_single_shot and re.fullmatch(re.escape(base.path.rstrip("/")) + r"/apps/[\w-]+/session/?", target.path, re.ASCII) is not None + return False + + async def stop_runner_session( session: LiveRunnerSession | LiveRunnerSessionRequest, *, @@ -1167,13 +1187,13 @@ def detect_process_gpu() -> LiveRunnerGPU | None: def _normalize_http_base(url: str) -> str: - url = url.strip() - normalized = url if "://" in url else f"https://{url}" - parsed = urlparse(normalized) - if parsed.scheme not in ("http", "https") or not parsed.netloc: - raise LivepeerGatewayError(f"Invalid orchestrator URL: {url!r}") - path = parsed.path.rstrip("/") - return urlunparse((parsed.scheme, parsed.netloc, path, "", parsed.query, "")) + try: + parsed = _parse_http_url(url) + if not parsed.hostname or parsed.port == 0: + raise ValueError("invalid hostname or port") + except ValueError as error: + raise LivepeerGatewayError(f"Invalid orchestrator URL: {url.strip()!r}") from error + return parsed._replace(path=parsed.path.rstrip("/"), params="", fragment="").geturl() def _join_endpoint(base_url: str, suffix: str) -> str: @@ -1472,3 +1492,7 @@ def _decode_maybe_bytes(value: object) -> str: if isinstance(value, bytes): return value.decode("utf-8", errors="replace") return str(value or "") + + +def _string_value(value: object) -> str: + return value.strip() if isinstance(value, str) else "" diff --git a/src/livepeer_gateway/selection.py b/src/livepeer_gateway/selection.py index 0118198..0e0a278 100644 --- a/src/livepeer_gateway/selection.py +++ b/src/livepeer_gateway/selection.py @@ -1,7 +1,7 @@ from __future__ import annotations import logging -from collections.abc import Sequence +from collections.abc import Callable, Sequence from typing import Any from .discovery import ( @@ -18,7 +18,9 @@ LiveRunnerCallResult, LiveRunnerInstance, LiveRunnerSession, + _is_session_endpoint, _live_runner_price_info_from_json, + _string_value, call_runner, ) from .runner_payload import RunnerPayload, _ReplayUnavailableError, _StreamState, _stream_state @@ -151,12 +153,14 @@ async def runner_selector( app: FilterValue | None = None, gpu: FilterValue | None = None, timeout: float = 5.0, + _matches: Callable[[LiveRunnerInstance], bool] = bool, ) -> RunnerSelectionCursor: if orchestrators is not None: entries = await discover_orchestrator_runners( orchestrators, app=app, gpu=gpu, + _has_runners=lambda entries: any(_matches(runner) for runner in _runner_candidates_from_discovery(entries)), ) else: entries = await discover_runners( @@ -168,7 +172,7 @@ async def runner_selector( gpu=gpu, ) - candidates = _runner_candidates_from_discovery(entries) + candidates = [runner for runner in _runner_candidates_from_discovery(entries) if _matches(runner)] if not candidates: _LOG.debug("select_runner failed: empty runner list") @@ -205,26 +209,10 @@ async def reserve_session( app=app, gpu=gpu, timeout=timeout, + _matches=lambda runner: _is_session_endpoint(runner.url, runner), ) result = await cursor.next() - session_id = result.data.get("session_id") - app_url = result.data.get("app_url") - control_url = _string_value(result.data.get("control_url")) - if not isinstance(session_id, str) or not session_id.strip(): - raise LivepeerGatewayError("runner session response missing session_id") - if not isinstance(app_url, str) or not app_url.strip(): - raise LivepeerGatewayError("runner session response missing app_url") - if not control_url: - raise LivepeerGatewayError("runner session response missing control_url") - session = LiveRunnerSession( - session_id=session_id.strip(), - app_url=app_url.strip(), - runner_url=result.runner_url, - control_url=control_url, - runner=result.runner, - ) - - # No payment session means fixed price or offchain: nothing to fund. + session = LiveRunnerSession(result.session_id, result.data["app_url"].strip(), result.runner_url, result.data["control_url"], result.runner) if result.payment_session is not None: session._start_payments(result.payment_session) return session @@ -257,7 +245,3 @@ def _runner_candidates_from_discovery(entries: Sequence[dict[str, Any]]) -> list ) ) return candidates - - -def _string_value(value: object) -> str: - return value.strip() if isinstance(value, str) else "" diff --git a/tests/test_live_runner.py b/tests/test_live_runner.py index 32a58d6..1c714f8 100644 --- a/tests/test_live_runner.py +++ b/tests/test_live_runner.py @@ -247,16 +247,30 @@ async def test_stop_runner_session_request_requires_control_header(self) -> None with pytest.raises(LivepeerGatewayError): await stop_runner_session(request) - async def test_call_runner_can_attach_runner_instance(self) -> None: + @pytest.mark.parametrize( + "mode,override", + [ + ("persistent", ""), + ("single-shot", ""), + ("single-shot", "https://SERVICE.example.com:443/apps/runner-1/session/?format=json"), + ], + ) + async def test_call_runner_can_attach_runner_instance(self, mode: str, override: str) -> None: runner = LiveRunnerInstance( url="https://service.example.com/apps/runner-1/session", app="livepeer-sample/echo", runner_id="runner-1", - mode="persistent", + mode=mode, orchestrator_url="https://service.example.com", raw={"app": "livepeer-sample/echo"}, ) + data = { + "session_id": "session-1", + "app_url": "https://service.example.com/app", + "control_url": "https://service.example.com/control", + } if mode == "persistent" else {"ok": True} + def _request_body( url: str, *, @@ -267,17 +281,13 @@ def _request_body( ) -> tuple[bytes, str]: del method, payload, timeout assert headers == {"Accept": "*/*"} - return _json_data( - { - "session_id": "session-1", - "app_url": "https://service.example.com/app", - } - ) + return _json_data(data) with mock.patch.object(live_runner, "_request_body", side_effect=_request_body): - result = await call_runner(runner=runner) + result = await call_runner(override, runner=runner) assert result.runner is runner + assert result.data == data async def test_paid_call_retries_with_payment_headers(self) -> None: calls: list[ @@ -432,6 +442,7 @@ def _request_body( { "session_id": "fixed-manifest", "app_url": "https://service.example.com/app", + "control_url": "https://service.example.com/control", } ) @@ -503,8 +514,9 @@ def _request_body( if headers and "Livepeer-Payment" in headers: return _json_data( { - "session_id": "session-2", + "session_id": "manifest-2", "app_url": "https://service.example.com/app", + "control_url": "https://service.example.com/control", } ) unpaid_count += 1 @@ -532,7 +544,7 @@ def _request_body( signer_url="https://signer.example.com", ) - assert result.data["session_id"] == "session-2" + assert result.data["session_id"] == "manifest-2" assert result.session_id == "manifest-2" assert result.payment_session is payment_sessions[1] challenge_headers = { diff --git a/tests/test_live_runner_payments.py b/tests/test_live_runner_payments.py index c6fab96..f16370b 100644 --- a/tests/test_live_runner_payments.py +++ b/tests/test_live_runner_payments.py @@ -220,83 +220,18 @@ async def test_already_released_session_only_stops_local_funding(self) -> None: post_empty.assert_not_awaited() -class _Cursor: - def __init__(self, *results: LiveRunnerCallResult) -> None: - self.results = list(results) - self.rejections = [] - - async def next(self) -> LiveRunnerCallResult: - if self.results: - return self.results.pop(0) - raise AssertionError("unexpected extra runner selection") - - -def _reservation( - name: str, - *, - control_url: str | None, - payment_session: object | None = None, -) -> LiveRunnerCallResult: - data = { - "session_id": f"session-{name}", - "app_url": f"https://orch.example.com/session-{name}/app", - } - if control_url is not None: - data["control_url"] = control_url - return LiveRunnerCallResult( - data, - runner_url=f"https://orch.example.com/runner-{name}/session", +async def test_onchain_reservation_starts_scoped_funding() -> None: + payment_session = _FundingSession() + expected = _session() + result = LiveRunnerCallResult( + {"app_url": expected.app_url, "control_url": expected.control_url}, + runner_url=expected.runner_url, + session_id=expected.session_id, payment_session=payment_session, # type: ignore[arg-type] ) + cursor = mock.Mock(next=mock.AsyncMock(return_value=result)) + with mock.patch.object(selection, "runner_selector", return_value=cursor): + session = await selection.reserve_session() - -class TestReservationSelection: - async def test_paid_reservation_starts_scoped_funding(self) -> None: - payment_session = _FundingSession() - cursor = _Cursor( - _reservation( - "1", - control_url=_CONTROL_URL, - payment_session=payment_session, - ) - ) - - with mock.patch.object( - selection, "runner_selector", new=mock.AsyncMock(return_value=cursor) - ): - session = await selection.reserve_session() - - await asyncio.wait_for(payment_session.started.wait(), timeout=1.0) - await session.stop_payments() - - @pytest.mark.parametrize( - "bad_control_url", - [None, "ftp://orch.example.com/session/bad"], - ) - async def test_invalid_control_url_fails_immediately( - self, bad_control_url: str | None - ) -> None: - cursor = _Cursor( - _reservation("bad", control_url=bad_control_url), - _reservation("good", control_url=_CONTROL_URL), - ) - - with mock.patch.object( - selection, - "runner_selector", - new=mock.AsyncMock(return_value=cursor), - ): - with pytest.raises(LivepeerGatewayError): - await selection.reserve_session() - - assert len(cursor.results) == 1 - - async def test_missing_control_url_is_contract_error(self) -> None: - cursor = _Cursor(_reservation("bad", control_url=None)) - with mock.patch.object( - selection, - "runner_selector", - new=mock.AsyncMock(return_value=cursor), - ): - with pytest.raises(LivepeerGatewayError, match="missing control_url"): - await selection.reserve_session() + await asyncio.wait_for(payment_session.started.wait(), timeout=1.0) + await session.stop_payments() diff --git a/tests/test_reservation_cleanup.py b/tests/test_reservation_cleanup.py new file mode 100644 index 0000000..4788ce8 --- /dev/null +++ b/tests/test_reservation_cleanup.py @@ -0,0 +1,127 @@ +from __future__ import annotations + +from types import SimpleNamespace +from unittest import mock +from urllib.parse import urljoin + +import pytest +from aiohttp import web +from aiohttp.test_utils import TestServer + +from livepeer_gateway import live_runner, selection +from livepeer_gateway.errors import LivepeerGatewayError, NoRunnerAvailableError + +_SESSION_URLS = {"app_url": "https://orch.test/app", "control_url": "https://orch.test/control"} +_ID_MISMATCH = "does not match payment manifest" + + +@pytest.mark.parametrize( + "manifest_id,body,error,expected_stops", + [ + ("onchain-id", b"{", "did not return valid JSON", ["onchain-id"]), + ("onchain-id", [], "expected JSON object", ["onchain-id"]), + ("onchain-id", b'{"huge":' + b"1" * 5000 + b"}", "did not return valid JSON", ["onchain-id"]), + ("onchain-id", {}, "missing session_id", ["onchain-id"]), + ("onchain-id", {}, None, ["onchain-id"]), + ("onchain-id", {**_SESSION_URLS, "session_id": "onchain-id", "control_url": "https://orch.test:bad/s1"}, None, ["onchain-id"]), + ("onchain-id", {**_SESSION_URLS, "session_id": "wrong-id"}, _ID_MISMATCH, ["onchain-id"]), + ("onchain-id", {**_SESSION_URLS, "session_id": " onchain-id "}, _ID_MISMATCH, ["onchain-id"]), + (" onchain-id ", {**_SESSION_URLS, "session_id": " onchain-id "}, _ID_MISMATCH, []), + ("", {"session_id": "offchain-id"}, "missing app_url", []), + ("", b"{", "did not return valid JSON", []), + ], +) +async def test_malformed_reservation_cleanup(manifest_id, body, error, expected_stops): + stops = [] + + async def reserve(request: web.Request) -> web.Response: + if manifest_id and not request.headers.get("Livepeer-Payment"): + return web.json_response( + {"manifest_id": manifest_id, "payment_params": "test", "payment_url": f"{base}/onchain-id/payment"}, + status=402, + ) + if isinstance(body, bytes): + return web.Response(body=body, content_type="application/json") + return web.json_response(body) + + async def stop(request: web.Request) -> web.Response: + stops.append(request.match_info["session_id"]) + return web.Response(status=503) + + async def reserve_next(request: web.Request) -> web.Response: + assert stops == expected_stops + return web.json_response({**_SESSION_URLS, "session_id": "next-id"}) + + app = web.Application() + app.router.add_post("/apps/a/session", reserve) + app.router.add_post("/apps/a/session/{session_id}/stop", stop) + app.router.add_post("/apps/next/session", reserve_next) + async with TestServer(app) as server: + base = str(server.make_url("/apps/a/session")) + entries = [{"runners": [{"url": base, "app": "a", "price_info": {"price": "1", "unit": "fixed"}}]}] + if error is None: + entries[0]["runners"].append({"url": str(server.make_url("/apps/next/session")), "app": "a"}) + signer_url = "https://signer.test" if manifest_id else None + with ( + mock.patch.object(selection, "discover_runners", return_value=entries), + mock.patch.object(live_runner, "get_signer_info", return_value=SimpleNamespace(address="payer")), + mock.patch.object( + live_runner.LivePaymentSession, "get_payment", + return_value=SimpleNamespace(payment="payment", seg_creds="segment"), + ), + ): + if error is None: + session = await selection.reserve_session(signer_url=signer_url) + assert session.session_id == "next-id" + else: + with pytest.raises(NoRunnerAvailableError) as raised: + await selection.reserve_session(signer_url=signer_url) + assert len(raised.value.rejections) == 1 + assert error in raised.value.rejections[0].reason + assert stops == expected_stops + + +@pytest.mark.parametrize( + "prefix,path,is_session", + [ + ("", "/apps/a/app/apps/b/session", False), + ("/mount", "/apps/a/session", False), + ("", "/apps/a/session;other", False), + ("", "https://proxy.test/apps/a/session", False), + ("", "https://ORCH.test:443/apps/a/session", True), + ("/mount", "/mount/apps/a/session", True), + ("/mount;v=2", "/mount/apps/a/session", False), + ("/mount;v=2", "/mount;v=2/apps/a/session", True), + ], +) +def test_session_endpoint_matches_the_discovery_mount(prefix, path, is_session): + runner = SimpleNamespace(mode="persistent", orchestrator_url="https://orch.test" + prefix) + assert live_runner._is_session_endpoint(urljoin("https://orch.test", path), runner) is is_session + + +def test_session_endpoint_requires_http_origin(): + for url in ("/apps/a/session", "ftp://orch.test/apps/a/session", "https://orch.test:0/apps/a/session"): + assert not live_runner._is_session_endpoint(url, None) + + +@pytest.mark.parametrize( + "body,error", + [ + (b"{}", "missing session_id"), + (b'{"session_id":"s1","app_url":"https://orch.test/app","control_url":"https://orch.test:bad/s1"}', "Invalid orchestrator URL"), + ], +) +async def test_call_runner_validates_session_with_implicit_post(body, error): + runner = live_runner.LiveRunnerInstance( + url="https://orch.test/apps/proxy/session", + app="proxy", + runner_id="proxy", + mode="single-shot", + orchestrator_url="https://orch.test", + raw={}, + ) + with mock.patch.object(live_runner, "_request_body", return_value=(body, "application/json")) as request: + with pytest.raises(LivepeerGatewayError, match=error): + await live_runner.call_runner("https://orch.test/apps/a/session", runner=runner, method="", payload={}) + + assert request.call_args.kwargs["method"] == "POST" diff --git a/tests/test_selection.py b/tests/test_selection.py index 863bfd3..cab1554 100644 --- a/tests/test_selection.py +++ b/tests/test_selection.py @@ -1,11 +1,12 @@ from __future__ import annotations import asyncio +import json from unittest import mock import pytest -from livepeer_gateway import selection +from livepeer_gateway import discovery, live_runner, selection from livepeer_gateway.errors import LivepeerGatewayError, NoRunnerAvailableError from livepeer_gateway.live_runner import LiveRunnerCallResult, LiveRunnerInstance @@ -331,73 +332,41 @@ async def test_runner_selector_rejects_invalid_orchestrator_url(self) -> None: with pytest.raises(LivepeerGatewayError): await selection.runner_selector(orchestrators="ftp://orch.example.com") - async def test_reserve_session_returns_session_from_call_result(self) -> None: - async def _call_runner( - *, - runner: LiveRunnerInstance, - payload: dict[str, object], - method: str, - timeout: float, - ) -> LiveRunnerCallResult: - del payload, method, timeout - return LiveRunnerCallResult( - { - "session_id": "session-1", - "app_url": "https://orch-a/apps/a/app", - "control_url": "https://orch-a/apps/a/session/session-1", - }, - runner_url=runner.url, - runner=runner, - session_id="session-1", - ) - + @pytest.mark.parametrize( + "first_address,first_mode,first_url", + [ + ("https://orch-a", "single-shot", "https://orch-a/apps/report/session"), + ("https:///mount", "persistent", "https://orch-a/mount/apps/report/session"), + ("https://orch-a:0", "persistent", "https://orch-a/apps/report/session"), + ], + ) + async def test_reserve_session_uses_first_eligible_orchestrator( + self, first_address: str, first_mode: str, first_url: str, + ) -> None: + second = "https://orch-b/mount/apps/a/session" + body = {"session_id": " s1 ", "app_url": second + "/s1/app", "control_url": second + "/s1"} with ( mock.patch.object( - selection, + discovery, "discover_runners", - return_value=[ - _entry([{"url": "https://orch-a/apps/a/session", "app": "app-a"}]) + side_effect=[ + [_entry([{"url": first_url, "app": "app-a", "mode": first_mode}], address=first_address)], + [_entry([{"url": second, "app": "app-a", "mode": "persistent"}], address="orch-b:443/mount")], ], ), - mock.patch.object(selection, "call_runner", side_effect=_call_runner), - ): - session = await selection.reserve_session( - discovery_url="https://example.com/discovery", app="app-a" - ) - - assert session.session_id == "session-1" - assert session.app_url == "https://orch-a/apps/a/app" - assert session.runner_url == "https://orch-a/apps/a/session" - assert session.runner is not None - assert session.runner.app == "app-a" - - async def test_reserve_session_rejects_non_session_json(self) -> None: - async def _call_runner( - *, - runner: LiveRunnerInstance, - payload: dict[str, object], - method: str, - timeout: float, - ) -> LiveRunnerCallResult: - del runner, payload, method, timeout - return LiveRunnerCallResult( - {"ok": True}, runner_url="https://orch-a/apps/a/app" - ) - - with ( mock.patch.object( - selection, - "discover_runners", - return_value=[ - _entry([{"url": "https://orch-a/apps/a/app", "app": "app-a"}]) - ], - ), - mock.patch.object(selection, "call_runner", side_effect=_call_runner), + live_runner, "_request_body", return_value=(json.dumps(body).encode(), "application/json") + ) as request, ): - with pytest.raises(LivepeerGatewayError): - await selection.reserve_session( - discovery_url="https://example.com/discovery", app="app-a" - ) + session = await selection.reserve_session(orchestrators=["https://orch-a", "https://orch-b"]) + + assert session.session_id == "s1" + assert session.app_url == body["app_url"] + assert session.control_url == body["control_url"] + assert session.runner_url == second + assert session.runner is not None and session.runner.app == "app-a" + request.assert_awaited_once() + assert request.call_args.args[0] == second async def test_runner_selector_supports_single_shot_url(self) -> None: async def _call_runner(