"""Resolve published source IDs against the awaited Reader asset snapshot.""" import asyncio from collections.abc import Callable, Coroutine, Sequence from typing import Protocol, cast JsonObject = dict[str, object] class ResolutionAccess(Protocol): def valid_id(self, source_id: str) -> bool: ... def indexes_ready(self) -> bool: ... def ensure_indexes(self) -> Coroutine[object, object, None]: ... def assets(self) -> Coroutine[object, object, JsonObject]: ... def cold_dependencies(self) -> Coroutine[object, object, JsonObject]: ... def source_indices(self, source_id: str) -> Sequence[int]: ... def record(self, index: int) -> JsonObject: ... def asset_key(self, record: JsonObject) -> str: ... def resolved_record(self) -> Callable[[JsonObject, JsonObject], JsonObject]: ... def canonical_source(self, url: str) -> str: ... async def cold_dependencies(access: ResolutionAccess) -> JsonObject: # These are request-local waiters. The existing index/asset owners retain # shielding and publication; collect both waiters on failure/cancellation. index_task = asyncio.create_task(access.ensure_indexes()) asset_task = asyncio.create_task(access.assets()) try: await asyncio.gather(index_task, asset_task) finally: for task in (index_task, asset_task): if not task.done(): task.cancel() await asyncio.gather(index_task, asset_task, return_exceptions=True) return asset_task.result() async def resolve_source(source_id: str, access: ResolutionAccess) -> tuple[list[JsonObject], JsonObject]: # Read published IDs and records only after both cold dependencies settle. # Retain the returned asset snapshot even if a later refresh is published. if access.indexes_ready(): assets = await access.assets() else: assets = await access.cold_dependencies() matches: list[JsonObject] = [] for index in access.source_indices(source_id): record = access.record(index) matches.append(access.resolved_record()( record, cast(dict[str, JsonObject], assets.get("f", {})).get(access.asset_key(record), {}), )) return matches, assets