mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-29 12:35:13 +00:00
fix(api): stop serve cleanly with jobs, streams and remote sessions open
This commit is contained in:
@@ -88,10 +88,14 @@ def wait_for_health(url: str, secret_key: str, timeout: float = 60.0) -> bool:
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def isolated_job_history(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Redirect job history writes to tmp_path so tests don't append to the server's api_history.jsonl."""
|
||||
"""Redirect job history writes to tmp_path and give each test its own download manager.
|
||||
|
||||
An app teardown shuts the global manager down, and a shut-down manager refuses new jobs.
|
||||
"""
|
||||
from unshackle.core.api import download_manager
|
||||
|
||||
monkeypatch.setattr(download_manager, "history_path", lambda: tmp_path / "api_history.jsonl")
|
||||
monkeypatch.setattr(download_manager, "download_manager", None)
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
|
||||
@@ -175,6 +175,30 @@ async def test_events_burst_mode(aiohttp_client, dashboard_cfg) -> None:
|
||||
assert [e["data"]["action"] for e in body["events"] if e["event"] == "session"] == ["create", "delete"]
|
||||
|
||||
|
||||
def test_bus_close_ends_a_full_subscriber_queue() -> None:
|
||||
local = EventBus()
|
||||
queue: asyncio.Queue = asyncio.Queue(maxsize=1)
|
||||
local._subs.append(queue)
|
||||
local.publish("session", {"action": "create"})
|
||||
local.close()
|
||||
assert queue.get_nowait() is None
|
||||
|
||||
|
||||
async def test_the_event_stream_ends_at_serve_shutdown(aiohttp_client, dashboard_cfg) -> None:
|
||||
from unshackle.core.api.download_manager import shutdown_download_manager
|
||||
from unshackle.core.api.events import close_event_streams
|
||||
|
||||
app = make_app()
|
||||
assert {close_event_streams, shutdown_download_manager} <= set(app.on_shutdown)
|
||||
client = await aiohttp_client(app)
|
||||
resp = await client.get("/api/dashboard/events", headers={"X-Secret-Key": "dash-secret"})
|
||||
assert resp.status == 200
|
||||
await asyncio.wait_for(resp.content.readuntil(b"\n\n"), timeout=10)
|
||||
await close_event_streams(app)
|
||||
await asyncio.wait_for(resp.content.read(), timeout=10)
|
||||
assert resp.content.at_eof()
|
||||
|
||||
|
||||
async def test_session_action_log() -> None:
|
||||
store = SessionStore()
|
||||
entry = await store.create("EXAMPLE", object(), owner_key="k")
|
||||
|
||||
@@ -6,6 +6,9 @@ cleanup/serialize); they do not exercise the actual subprocess download path.
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
from collections.abc import Callable
|
||||
from contextlib import suppress
|
||||
from datetime import datetime, timedelta
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
@@ -764,3 +767,91 @@ def test_a_download_error_keeps_the_code_its_raiser_named(
|
||||
download_manager.perform_download("job-1", "EXAMPLE1", "t1", {})
|
||||
|
||||
assert exc.value.error_code == (APIErrorCode.WORKER_ERROR if carrier == "none" else APIErrorCode.DRM_ERROR)
|
||||
|
||||
|
||||
async def _until(condition: Callable[[], bool], timeout: float = 10.0) -> None:
|
||||
"""Wait for ``condition`` with a deadline."""
|
||||
loop = asyncio.get_running_loop()
|
||||
deadline = loop.time() + timeout
|
||||
while not condition():
|
||||
assert loop.time() < deadline, "condition not met before the deadline"
|
||||
await asyncio.sleep(0.01)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def downloading(monkeypatch: pytest.MonkeyPatch, manager: DownloadQueueManager) -> Any:
|
||||
"""A manager whose jobs download until cancelled, with no history file written."""
|
||||
from unshackle.core.api import download_manager
|
||||
|
||||
started = asyncio.Event()
|
||||
|
||||
async def block(job: DownloadJob) -> None:
|
||||
started.set()
|
||||
await asyncio.Event().wait()
|
||||
|
||||
monkeypatch.setattr(manager, "execute_download", block)
|
||||
monkeypatch.setattr(download_manager, "record_job_history", lambda job: None)
|
||||
return started
|
||||
|
||||
|
||||
async def test_a_cancel_of_the_worker_task_ends_it_while_a_job_downloads(
|
||||
manager: DownloadQueueManager, downloading: Any
|
||||
) -> None:
|
||||
worker = asyncio.create_task(manager.download_worker("w"))
|
||||
job = manager.create_job("EXAMPLE", "t")
|
||||
await asyncio.wait_for(downloading.wait(), timeout=10)
|
||||
|
||||
worker.cancel()
|
||||
with pytest.raises(asyncio.CancelledError):
|
||||
await asyncio.wait_for(worker, timeout=10)
|
||||
assert job.status is JobStatus.CANCELLED
|
||||
assert job.completed_time is not None
|
||||
|
||||
|
||||
async def test_a_cancel_of_the_job_download_keeps_the_worker_running(
|
||||
manager: DownloadQueueManager, downloading: Any
|
||||
) -> None:
|
||||
worker = asyncio.create_task(manager.download_worker("w"))
|
||||
try:
|
||||
job = manager.create_job("EXAMPLE", "t")
|
||||
await asyncio.wait_for(downloading.wait(), timeout=10)
|
||||
manager._active_downloads[job.job_id].cancel()
|
||||
await _until(lambda: job.completed_time is not None)
|
||||
assert job.status is JobStatus.CANCELLED
|
||||
assert not worker.done()
|
||||
finally:
|
||||
worker.cancel()
|
||||
with suppress(asyncio.CancelledError):
|
||||
await worker
|
||||
|
||||
|
||||
async def test_shutdown_cancels_every_job_and_ends_each_stream_on_its_terminal_event(
|
||||
manager: DownloadQueueManager, downloading: Any
|
||||
) -> None:
|
||||
from unshackle.core.api.errors import APIError
|
||||
|
||||
worker = asyncio.create_task(manager.download_worker("w"))
|
||||
running = manager.create_job("EXAMPLE", "t")
|
||||
await asyncio.wait_for(downloading.wait(), timeout=10)
|
||||
queued = manager.create_job("EXAMPLE", "u")
|
||||
streams = {job.job_id: manager.subscribe(job.job_id) for job in (running, queued)}
|
||||
|
||||
await manager.shutdown()
|
||||
await asyncio.wait_for(worker, timeout=10)
|
||||
for job in (running, queued):
|
||||
assert job.status is JobStatus.CANCELLED
|
||||
assert job.completed_time is not None
|
||||
events = []
|
||||
while (item := await asyncio.wait_for(streams[job.job_id].get(), timeout=10)) is not None:
|
||||
events.append(item["event"])
|
||||
assert events[-1] == "cancelled"
|
||||
with pytest.raises(APIError):
|
||||
manager.create_job("EXAMPLE", "v")
|
||||
|
||||
|
||||
async def test_the_shutdown_hook_makes_no_manager(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
from unshackle.core.api import download_manager
|
||||
|
||||
monkeypatch.setattr(download_manager, "download_manager", None)
|
||||
await download_manager.shutdown_download_manager(object())
|
||||
assert download_manager.download_manager is None
|
||||
|
||||
@@ -134,6 +134,19 @@ async def test_cancel_all_bridges(store: SessionStore) -> None:
|
||||
entry.input_bridge.ensure_active()
|
||||
|
||||
|
||||
async def test_cancel_all_bridges_removes_the_session_cache_dirs(
|
||||
store: SessionStore, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
removed: list = []
|
||||
monkeypatch.setattr(SessionStore, "cleanup_cache_dir", staticmethod(removed.append))
|
||||
entry = await store.create("EXAMPLE", _FakeService(), cache_tag="_sessions/k/s/EXAMPLE")
|
||||
await store.create("OTHER", _FakeService())
|
||||
|
||||
await store.cancel_all_bridges()
|
||||
assert removed == [entry.cache_tag, None]
|
||||
assert store.session_count == 0
|
||||
|
||||
|
||||
async def test_get_session_store_returns_singleton() -> None:
|
||||
a = get_session_store()
|
||||
b = get_session_store()
|
||||
|
||||
Reference in New Issue
Block a user