Skip to content
Closed
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
5 changes: 3 additions & 2 deletions src/livepeer_gateway/discovery.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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:
Expand Down
8 changes: 2 additions & 6 deletions src/livepeer_gateway/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
74 changes: 49 additions & 25 deletions src/livepeer_gateway/live_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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)
Comment on lines +985 to +987
Comment on lines +985 to +987
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,
Expand Down Expand Up @@ -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,
*,
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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 ""
32 changes: 8 additions & 24 deletions src/livepeer_gateway/selection.py
Original file line number Diff line number Diff line change
@@ -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 (
Expand All @@ -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
Expand Down Expand Up @@ -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(
Expand All @@ -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")
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 ""
34 changes: 23 additions & 11 deletions tests/test_live_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
*,
Expand All @@ -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[
Expand Down Expand Up @@ -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",
}
)

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 = {
Expand Down
Loading