vomebook
Make Reader CI contracts resilient and reduce redundant checks
dead914
Raw History Blame Contribute Delete
6.23 kB
"""Application startup ordering and cancellation-owned resource shutdown."""
import asyncio
from collections import OrderedDict
from collections.abc import AsyncGenerator, Awaitable, Callable, Coroutine
from contextlib import asynccontextmanager
from dataclasses import dataclass
from typing import Any, Literal, Protocol
import aiohttp
from backend.reader.document.application.ranges import RangeFlightState
from backend.reader_range_cache import RangeCacheState
from backend.search_execution import SearchExecutor
class LifecycleState(RangeCacheState, RangeFlightState, Protocol):
search_executor: SearchExecutor
http_session: aiohttp.ClientSession
upstream_semaphore: asyncio.Semaphore
reader_index_build_task: asyncio.Task[None] | None
reader_index_warm_task: asyncio.Task[None] | None
reader_assets_lock: asyncio.Lock
reader_assets_task: asyncio.Task[None] | None
download_warm_enabled: bool
download_warm_task: asyncio.Task[None] | None
download_warm_at: float
@dataclass(frozen=True)
class LifecycleDependencies:
# Hooks resolve the composition root's current implementations when called.
load_data: Callable[[], None]
create_executor: Callable[[], SearchExecutor]
create_http_session: Callable[[], aiohttp.ClientSession]
initialize_bucket: Callable[[], None]
initialize_archive: Callable[[], None]
mark_user_activity: Callable[[], None]
warm_reader_indexes: Callable[[], Coroutine[Any, Any, None]]
shutdown_bucket: Callable[[], Awaitable[None]]
shutdown_archive: Callable[[], Awaitable[None]]
shutdown_ranges: Callable[[], Awaitable[None]]
TaskName = Literal["reader_index_warm_task", "reader_index_build_task",
"reader_assets_task", "download_warm_task"]
@asynccontextmanager
async def lifespan(state: Callable[[], LifecycleState],
deps: LifecycleDependencies) -> AsyncGenerator[None, None]:
deps.load_data()
state().search_executor = deps.create_executor()
state().reader_index_build_task = None
state().reader_index_warm_task = None
state().http_session = deps.create_http_session()
state().upstream_semaphore = asyncio.Semaphore(8)
state().download_warm_enabled = True
state().download_warm_task = None
state().download_warm_at = float("-inf")
state().reader_assets_lock = asyncio.Lock()
state().reader_assets_task = None
deps.initialize_bucket()
deps.initialize_archive()
state().reader_range_cache = OrderedDict()
state().reader_range_cache_bytes = 0
state().reader_range_flights = {}
state().reader_range_flight_owners = set()
deps.mark_user_activity()
state().reader_index_warm_task = asyncio.create_task(deps.warm_reader_indexes())
# Preserve the startup boundary: only a fully started lifespan owns cleanup.
body_error: BaseException | None = None
try:
yield
except BaseException as exc:
body_error = exc
finally:
errors: list[BaseException] = []
async def attempt(action: Callable[[], Awaitable[None]]) -> bool:
try:
await action()
return True
except BaseException as exc:
errors.append(exc)
return False
async def stop_task(name: TaskName) -> None:
task: asyncio.Task[None] | None = getattr(state(), name)
if task is not None:
task.cancel()
result = (await asyncio.gather(task, return_exceptions=True))[0]
setattr(state(), name, None)
if isinstance(result, BaseException) and not isinstance(result, asyncio.CancelledError):
errors.append(result)
async def cleanup_resources() -> None:
state().download_warm_enabled = False
warm_stopped = await attempt(lambda: stop_task("reader_index_warm_task"))
build_stopped = await attempt(lambda: stop_task("reader_index_build_task"))
executor_closed = await attempt(state().search_executor.close)
if executor_closed:
del state().search_executor
assets_stopped = await attempt(lambda: stop_task("reader_assets_task"))
download_stopped = await attempt(lambda: stop_task("download_warm_task"))
# Failure to drain a producer is not proof that its resources are free.
if not all((warm_stopped, build_stopped, executor_closed, assets_stopped, download_stopped)):
return
bucket_closed = await attempt(deps.shutdown_bucket)
archive_closed = await attempt(deps.shutdown_archive)
ranges_closed = await attempt(deps.shutdown_ranges)
if bucket_closed and archive_closed and ranges_closed:
state().reader_range_cache.clear()
state().reader_range_cache_bytes = 0
await attempt(state().http_session.close)
# Own the entire sequence, including later Reader/session awaits.
cleanup = asyncio.create_task(cleanup_resources())
cancelled: asyncio.CancelledError | None = None
while not cleanup.done():
try:
await asyncio.shield(cleanup)
except asyncio.CancelledError as exc:
if cancelled is None:
cancelled = exc
except BaseException:
break
try:
cleanup.result()
except BaseException as exc:
errors.append(exc)
failure = (errors[0] if len(errors) == 1 else
BaseExceptionGroup("Lifespan cleanup errors", errors) if errors else None)
if body_error is not None or cancelled is not None:
if failure is not None:
asyncio.get_running_loop().call_exception_handler({
"message": "Lifespan resource close failed while handling an exception",
"exception": failure,
"task": cleanup,
})
if body_error is not None:
raise body_error
if cancelled is not None:
raise cancelled
if failure is not None:
raise failure