Skip to content
Draft
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
2 changes: 2 additions & 0 deletions src/livepeer_gateway/channel_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,7 @@ def __init__(
consumption starts immediately. If no loop is running, call
start_callback() later from async code or use async with the reader.
"""
self._subscriber: TrickleSubscriber | None = None
self._init_callback(
events_url,
start_seq=start_seq,
Expand Down Expand Up @@ -291,6 +292,7 @@ async def _iter() -> AsyncIterator[dict[str, Any]]:
max_retries=max_retries,
max_bytes=max_event_bytes,
) as subscriber:
self._subscriber = subscriber
while (segment := await subscriber.next()) is not None:
payload = await _read_all(segment)
if not payload.strip():
Expand Down
13 changes: 12 additions & 1 deletion src/livepeer_gateway/live_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -324,6 +324,7 @@ def __init__(
self._closed = False
self._task: asyncio.Task[None] | None = None
self._o2r_task: asyncio.Task[None] | None = None
self._retired_o2r_tasks: set[asyncio.Task[None]] = set()

async def start(self) -> LiveRunnerRegistration:
await self._send_heartbeat()
Expand Down Expand Up @@ -559,7 +560,7 @@ async def _post_heartbeat(self, auth: str) -> dict[str, Any]:
)

def _start_o2r(self, value: object) -> None:
if self._closed or self._o2r_reader is not None:
if self._closed:
return
if not _is_trickle_channel_response(value):
if value is not None:
Expand All @@ -570,6 +571,14 @@ def _start_o2r(self, value: object) -> None:
if not url:
return
self.o2r_channel = channel
if (old_reader := self._o2r_reader) and (old_task := self._o2r_task) and not old_task.done():
if (sub := old_reader._subscriber) is None or not sub._closing:
ended = sub and (sub._errored or sub._pending_get and "Lp-Trickle-Closed" in sub._pending_get.headers)
if not ended and old_reader.events_url.rstrip("/") == url.rstrip("/"):
return
old_task.cancel()
self._retired_o2r_tasks.add(old_task)
old_task.add_done_callback(self._retired_o2r_tasks.discard)
reader = ChannelReader(url, start_seq=0, on_event=self._handle_o2r_message)
self._o2r_reader = reader
self._o2r_task = reader.callback_task()
Expand Down Expand Up @@ -613,6 +622,8 @@ async def _handle_o2r_message(self, message: dict[str, Any]) -> None:
await result
except Exception:
_LOG.exception("Live runner %s callback failed for session %s", typed_event, session_id)
if asyncio.current_task() in self._retired_o2r_tasks:
raise asyncio.CancelledError

def _release_session_id(self, session_id: str) -> None:
if self._active_sessions.pop(session_id, None) is None:
Expand Down
1 change: 1 addition & 0 deletions tests/test_channel_reader.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ async def test_async_event_callback_is_awaited(self) -> None:
order: list[str] = []

async def _on_event(_event: dict[str, object]) -> None:
assert reader._subscriber is _FakeSubscriber.instances[0]
order.append("start")
await asyncio.sleep(0)
order.append("done")
Expand Down
41 changes: 34 additions & 7 deletions tests/test_live_runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -832,6 +832,7 @@ def _json_data(data: dict[str, object]) -> tuple[bytes, str]:

class _FakeO2RReader:
instances: list[_FakeO2RReader] = []
_subscriber: SimpleNamespace | None = None

def __init__(
self,
Expand Down Expand Up @@ -1365,7 +1366,9 @@ async def test_initial_heartbeat_requires_heartbeat_secret(self) -> None:
auto_detect_gpu=False,
)

async def test_heartbeat_resets_auth_after_invalid_authorization(self) -> None:
@pytest.mark.parametrize(("new_channel", "state"), [("old/", "live"), ("new", "live"), ("old", "closing"), ("old", "errored"), ("old", "eos")])
async def test_heartbeat_resets_auth_after_invalid_authorization(self, new_channel: str, state: str) -> None:
_FakeO2RReader.instances = []
calls: list[tuple[str, dict[str, object], dict[str, str]]] = []
auth_refreshed = asyncio.Event()

Expand All @@ -1375,21 +1378,33 @@ def _post_json(
*,
headers: dict[str, str],
timeout: float,
) -> dict[str, str]:
) -> dict[str, object]:
calls.append((url, payload, headers))
if headers["Authorization"] == "heartbeat-token":
pending = SimpleNamespace(headers={"Lp-Trickle-Closed": ""} if state == "eos" else {})
_FakeO2RReader.instances[0]._subscriber = SimpleNamespace(_closing=state == "closing", _errored=state == "errored", _pending_get=pending)
raise LivepeerHTTPError(401, url, "any body")
if len(calls) >= 3:
channel = {1: "old", 3: new_channel}.get(len(calls), "ignored")
if len(calls) >= 4:
auth_refreshed.set()
return {
"runner_id": "runner-1",
"heartbeat_interval": "1h",
"heartbeat_secret": (
"heartbeat-token" if len(calls) == 1 else "fresh-heartbeat-token"
),
"o2r": {
"name": "o2r",
"channel_name": "updated" if len(calls) >= 3 else "initial",
"url": f"https://service.example.com/trickle/{channel}",
"mime_type": "application/json",
},
}

with mock.patch.object(live_runner, "post_json", side_effect=_post_json):
with (
mock.patch.object(live_runner, "post_json", side_effect=_post_json),
mock.patch.object(live_runner, "ChannelReader", _FakeO2RReader),
):
reg = await register_runner(
"http://localhost:8935",
secret="secret-token",
Expand All @@ -1400,13 +1415,25 @@ def _post_json(
heartbeat_interval_s=0.01,
unregister_on_close=False,
)
await asyncio.wait_for(auth_refreshed.wait(), timeout=1.0)
await reg.close()
try:
await asyncio.wait_for(auth_refreshed.wait(), timeout=1.0)
assert len(_FakeO2RReader.instances) == (1 if new_channel == "old/" else 2)
reader = _FakeO2RReader.instances[-1]
assert reader.events_url.endswith(f"/{new_channel.rstrip('/')}")
assert reg.o2r_channel["channel_name"] == "updated"
assert _FakeO2RReader.instances[0].callback_task().cancelling() == (new_channel == "new" or state in {"errored", "eos"})
await reader.on_event({"event": "reserved", "session": "fresh"})
assert reg.active_session_ids == ("fresh",)
finally:
await reg.close()
if state == "closing":
await _FakeO2RReader.instances[0].close()

assert [headers for _, _, headers in calls[:3]] == [
assert [headers for _, _, headers in calls[:4]] == [
{"Authorization": "secret-token"},
{"Authorization": "heartbeat-token"},
{"Authorization": "secret-token"},
{"Authorization": "fresh-heartbeat-token"},
]
assert calls[2][1]["runner_id"] == "runner-1"

Expand Down