"""Endpoint for managing queries (dialogue/questions) in a study."""
from __future__ import annotations
import builtins
from collections.abc import AsyncIterator, Callable, Iterator, Sequence
from typing import Any
from imednet.core.endpoint.dispatch import execute_list
from imednet.core.endpoint.edc_mixin import EdcAsyncListEndpoint, EdcSyncListEndpoint
from imednet.core.endpoint.operations.list import ListOperation
from imednet.core.paginator import AsyncPaginator, Paginator, _parse_int_param
from imednet.core.protocols import AsyncRequesterProtocol, RequesterProtocol
from imednet.models.queries import Query
from imednet.utils.filters import (
QUERY_STATUS_ATTRIBUTES,
matches_query_status_bounds,
split_query_status_filters,
)
from imednet.utils.typing import FilterValue
class _BoundedQueryIterator(Iterator[Query]):
"""Synchronous iterator applying client-side QueryStatus predicates before limit."""
def __init__(
self,
source: Iterator[Query],
local_predicates: Sequence[tuple[str, Any]],
limit: int | None = None,
) -> None:
self._source = iter(source)
self._local_predicates = local_predicates
self._remaining = limit
def __iter__(self) -> _BoundedQueryIterator:
return self
def __next__(self) -> Query:
if self._remaining is not None and self._remaining <= 0:
raise StopIteration
while True:
item = next(self._source)
if matches_query_status_bounds(item, self._local_predicates):
if self._remaining is not None:
self._remaining -= 1
return item
class _AsyncBoundedQueryIterator(AsyncIterator[Query]):
"""Asynchronous iterator applying client-side QueryStatus predicates before limit."""
def __init__(
self,
source: AsyncIterator[Query],
local_predicates: Sequence[tuple[str, Any]],
limit: int | None = None,
) -> None:
self._source = source.__aiter__()
self._local_predicates = local_predicates
self._remaining = limit
def __aiter__(self) -> _AsyncBoundedQueryIterator:
return self
async def __anext__(self) -> Query:
if self._remaining is not None and self._remaining <= 0:
raise StopAsyncIteration
while True:
item = await self._source.__anext__()
if matches_query_status_bounds(item, self._local_predicates):
if self._remaining is not None:
self._remaining -= 1
return item
class _BoundedQueryListOperation(ListOperation[Query]):
"""List operation pushing upstream filters and evaluating QueryStatus locally."""
def __init__(
self,
path: str,
params: dict[str, Any],
page_size: int,
parse_func: Callable[[Any], Query],
*,
local_predicates: Sequence[tuple[str, Any]],
local_limit: int | None = None,
) -> None:
super().__init__(path=path, params=params, page_size=page_size, parse_func=parse_func)
self._local_predicates = tuple(local_predicates)
self._local_limit = local_limit
def execute_sync(
self,
client: RequesterProtocol,
paginator_cls: type[Paginator],
) -> Iterator[Query]:
base_iter = super().execute_sync(client, paginator_cls)
return _BoundedQueryIterator(base_iter, self._local_predicates, self._local_limit)
def execute_async(
self,
client: AsyncRequesterProtocol,
paginator_cls: type[AsyncPaginator],
) -> AsyncIterator[Query]:
base_aiter = super().execute_async(client, paginator_cls)
return _AsyncBoundedQueryIterator(base_aiter, self._local_predicates, self._local_limit)
[docs]class QueriesOperationDef:
"""Definition for Query operations."""
PATH = "queries"
MODEL = Query
PAGE_SIZE = 500
LOCAL_FILTER_ATTRIBUTES = QUERY_STATUS_ATTRIBUTES
FILTER_ATTRIBUTES = frozenset(
{
"annotationId",
"subjectId",
"subjectOid",
"annotationType",
"type",
"description",
"recordId",
"variable",
"subjectKey",
"dateCreated",
"dateModified",
"lastUpdated",
}
)
def _build_query_list_operation(
self,
study_key: str | None,
raw_filters: dict[str, Any],
) -> ListOperation[Query]:
"""Build a standard or locally status-filtered query list operation."""
upstream_filters, local_predicates = split_query_status_filters(raw_filters)
if not local_predicates:
state = self._prepare_list_request(study_key, None, upstream_filters) # type: ignore[attr-defined]
return ListOperation[Query](
path=state.path,
params=state.params,
page_size=self.PAGE_SIZE,
parse_func=self._resolve_parse_func(), # type: ignore[attr-defined]
)
local_limit: int | None = None
raw_limit = upstream_filters.pop("limit", None)
if raw_limit is not None:
parsed_limit = _parse_int_param("limit", raw_limit)
if parsed_limit < 1:
raise ValueError(f"Pagination 'limit' must be >= 1, got {parsed_limit}.")
local_limit = parsed_limit
state = self._prepare_list_request(study_key, None, upstream_filters) # type: ignore[attr-defined]
return _BoundedQueryListOperation(
path=state.path,
params=state.params,
page_size=self.PAGE_SIZE,
parse_func=self._resolve_parse_func(), # type: ignore[attr-defined]
local_predicates=local_predicates,
local_limit=local_limit,
)
[docs] @execute_list # type: ignore[arg-type]
def list(
self,
study_key: str | None = None,
**filters: FilterValue,
) -> ListOperation[Query]:
"""List queries matching upstream filters while evaluating status locally."""
return self._build_query_list_operation(study_key, dict(filters))
def _list_sync(self, *a: Any, **k: Any) -> builtins.list[Query]:
study_key = k.pop("study_key", None)
op = self._build_query_list_operation(study_key, k)
return builtins.list(
op.execute_sync(
self._require_sync_client(), # type: ignore[attr-defined]
self.PAGINATOR_CLS, # type: ignore[attr-defined]
)
)
async def _list_async(self, *a: Any, **k: Any) -> builtins.list[Query]:
study_key = k.pop("study_key", None)
op = self._build_query_list_operation(study_key, k)
return [
item
async for item in op.execute_async(
self._require_async_client(), # type: ignore[attr-defined]
self.ASYNC_PAGINATOR_CLS, # type: ignore[attr-defined]
)
]
[docs]class QueriesEndpoint(QueriesOperationDef, EdcSyncListEndpoint[Query]): # type: ignore[misc]
"""Synchronous endpoint for managing Queries."""
[docs]class AsyncQueriesEndpoint(QueriesOperationDef, EdcAsyncListEndpoint[Query]): # type: ignore[misc]
"""Asynchronous endpoint for managing Queries."""