Skip to content
Merged
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
19 changes: 8 additions & 11 deletions isic/core/api/image.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@

from isic.auth import IsAuthenticated, IsStaff
from isic.core.models import Image
from isic.core.pagination import CursorPagination, paginate, qs_with_hardcoded_count
from isic.core.pagination import CursorPagination, paginate
from isic.core.permissions import get_visible_objects
from isic.core.search import build_elasticsearch_query, facets, get_elasticsearch_client
from isic.core.serializers import SearchQuerySerializer, StrictSerializer
Expand Down Expand Up @@ -170,10 +170,7 @@ def _get_position_from_instance(self, instance, ordering):

@override
def paginate_queryset(self, queryset, request, *, pin_sort: bool = False, **kwargs):
# ordering clones the queryset, which would drop a hardcoded count, so a queryset that
# the view already ordered (see _ordering) is left alone.
if not queryset.query.order_by:
queryset = queryset.order_by(*_ordering(request, pin_sort=pin_sort))
queryset = queryset.order_by(*_ordering(request, pin_sort=pin_sort))
return super().paginate_queryset(queryset, request, **kwargs)


Expand All @@ -188,15 +185,15 @@ def _ordering(request, *, pin_sort: bool = False) -> tuple[str, ...]:
def image_list(request):
qs = get_visible_objects(request.user, "core.view_image", default_qs)

count = None
if settings.ISIC_USE_ELASTICSEARCH_COUNTS:
es_query = build_elasticsearch_query({}, request.user, None)
es_count = get_elasticsearch_client().count(
count = get_elasticsearch_client().count(
index=settings.ISIC_ELASTICSEARCH_IMAGES_INDEX,
body={"query": es_query},
)["count"]
qs = qs_with_hardcoded_count(qs, _ordering(request), es_count)

return paginate(request, qs, ImageSerializer, PinnedFirstPagination())
return paginate(request, qs, ImageSerializer, PinnedFirstPagination(), count=count)


@api_view(["GET"])
Expand All @@ -206,15 +203,15 @@ def image_search(request):
search.is_valid(raise_exception=True)
qs: QuerySet[Image] = search.to_queryset(user=request.user, qs=default_qs)

count = None
if settings.ISIC_USE_ELASTICSEARCH_COUNTS:
es_query = search.to_es_query(request.user)
es_count = get_elasticsearch_client().count(
count = get_elasticsearch_client().count(
index=settings.ISIC_ELASTICSEARCH_IMAGES_INDEX,
body={"query": es_query},
)["count"]
qs = qs_with_hardcoded_count(qs, _ordering(request), es_count)

return paginate(request, qs, ImageSerializer, PinnedFirstPagination())
return paginate(request, qs, ImageSerializer, PinnedFirstPagination(), count=count)


@api_view(["GET"])
Expand Down
58 changes: 25 additions & 33 deletions isic/core/pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,25 +13,6 @@
_OFFSET_CUTOFF = 100


def qs_with_hardcoded_count(qs: QuerySet, ordering: Sequence, count: int) -> QuerySet:
"""
Modify a queryset to return a hardcoded count rather than querying the database.

This is useful when the count can be obtained with a cheaper method instead of
the default queryset.count() method, e.g. elasticsearch, a separate query with
fewer joins, etc.
"""
# This is an unfortunate bit of hackery to get around the fact that the CursorPagination class
# adds an order by which clones the queryset, overriding our hardcoded count. We have to repeat
# the logic here to make sure the paginator doesn't modify our queryset.
if not qs.query.order_by:
qs = qs.order_by(*ordering)

qs.count = lambda: count

return qs


@dataclass
class Cursor:
offset: int = 0
Expand Down Expand Up @@ -73,26 +54,35 @@ def __init__(self, ordering: Sequence = default_ordering) -> None:
self.ordering = ordering

def paginate_queryset(
self, queryset: QuerySet, request: HttpRequest, *, limit: int | None, cursor: Cursor
self,
queryset: QuerySet,
request: HttpRequest,
*,
limit: int | None,
cursor: Cursor,
count: int | None = None,
) -> dict:
"""
Paginate a queryset.

count is the total number of results, for callers that can get it cheaper than
queryset.count(), e.g. from elasticsearch or a materialized view. It's returned on every
page, whereas queryset.count() only runs on the first page since it's slow for large
queries.
"""
limit = _clamp(limit or self.max_page_size, 0, self.max_page_size)

if not queryset.query.order_by:
queryset = queryset.order_by(*self.ordering)

order: tuple[str, ...] = queryset.query.order_by

total_count = (
# let the queryset define a custom_count attribute in the event that computing
# the count can be done cheaper than the default queryset.count() method.
queryset.custom_count
if hasattr(queryset, "custom_count")
else queryset.count()
# only count the total number of results if a position is absent, usually indicating
# that we're on the first page. this improves performance for larger queries.
if cursor.position is None
else None
)
if count is not None:
total_count = count
elif cursor.position is None:
total_count = queryset.count()
else:
total_count = None

base_url = request.build_absolute_uri()

Expand Down Expand Up @@ -346,9 +336,11 @@ def validate_cursor(self, encoded_cursor: str | None) -> Cursor:
return Cursor(offset=offset, reverse=reverse, position=position)


def paginate(request, queryset: QuerySet, serializer_class, paginator=None) -> Response:
def paginate(
request, queryset: QuerySet, serializer_class, paginator=None, *, count: int | None = None
) -> Response:
paginator = paginator if paginator is not None else CursorPagination()
params = CursorPaginationSerializer(data=request.query_params)
params.is_valid(raise_exception=True)
page = paginator.paginate_queryset(queryset, request, **params.validated_data)
page = paginator.paginate_queryset(queryset, request, count=count, **params.validated_data)
return Response({**page, "results": serializer_class(page["results"], many=True).data})
11 changes: 3 additions & 8 deletions isic/core/views/collections.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,7 @@

from isic.core.forms.collection import CollectionForm
from isic.core.models import Collection
from isic.core.pagination import (
CursorPagination,
CursorPaginationSerializer,
qs_with_hardcoded_count,
)
from isic.core.pagination import CursorPagination, CursorPaginationSerializer
from isic.core.permissions import get_visible_objects, needs_object_permission
from isic.core.services import image_metadata_csv
from isic.core.services.collection import create_collection, update_collection
Expand Down Expand Up @@ -132,16 +128,15 @@ def collection_detail(request, pk):
)

# prevent the paginator from doing a slow count.
if hasattr(collection, "cached_counts"):
images = qs_with_hardcoded_count(images, ("created",), collection.cached_counts.image_count)
count = collection.cached_counts.image_count if hasattr(collection, "cached_counts") else None

paginator = CursorPagination(ordering=("created",))
try:
params = CursorPaginationSerializer(
data={"limit": request.GET.get("limit", 30), "cursor": request.GET.get("cursor")}
)
params.is_valid(raise_exception=True)
page = paginator.paginate_queryset(images, request, **params.validated_data)
page = paginator.paginate_queryset(images, request, count=count, **params.validated_data)
except DrfValidationError as e:
raise BadRequest("Invalid pagination parameters.") from e

Expand Down
15 changes: 9 additions & 6 deletions isic/core/views/images.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
from isic.core.api.image import PinnedFirstPagination
from isic.core.forms.search import ImageSearchForm
from isic.core.models import Collection, Image
from isic.core.pagination import CursorPaginationSerializer, qs_with_hardcoded_count
from isic.core.pagination import CursorPaginationSerializer
from isic.core.permissions import get_visible_objects, needs_object_permission
from isic.core.search import get_elasticsearch_client
from isic.core.tasks import generate_staff_image_list_metadata_csv_task
Expand Down Expand Up @@ -161,26 +161,29 @@ def image_browser(request):
collections=collections,
)
qs: QuerySet[Image] = Image.objects.none()
order_by = ("-pinned", "created")
total_images = 0

if search_form.is_valid():
qs = search_form.results

if settings.ISIC_USE_ELASTICSEARCH_COUNTS:
es_query = search_form.serializer.to_es_query(request.user)
es_count = get_elasticsearch_client().count(
total_images = get_elasticsearch_client().count(
index=settings.ISIC_ELASTICSEARCH_IMAGES_INDEX,
body={"query": es_query},
)["count"]
qs = qs_with_hardcoded_count(qs, order_by, es_count)
else:
total_images = qs.count()

paginator = PinnedFirstPagination()
try:
params = CursorPaginationSerializer(
data={"limit": request.GET.get("limit", 30), "cursor": request.GET.get("cursor")}
)
params.is_valid(raise_exception=True)
page = paginator.paginate_queryset(qs, request, pin_sort=True, **params.validated_data)
page = paginator.paginate_queryset(
qs, request, pin_sort=True, count=total_images, **params.validated_data
)
except DrfValidationError as e:
raise BadRequest("Invalid pagination parameters.") from e

Expand All @@ -195,7 +198,7 @@ def image_browser(request):
request,
"core/image_browser.html",
{
"total_images": qs.count(),
"total_images": total_images,
"images": page["results"],
"page": page,
# This gets POSTed to the populate endpoint if called
Expand Down
3 changes: 1 addition & 2 deletions isic/ingest/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,8 +77,7 @@ def lesion_list(request):
.order_by("id"),
)
# the count can be done much more efficiently than the full query
qs.custom_count = get_lesion_count_for_user(request.user)
return paginate(request, qs, LesionSerializer)
return paginate(request, qs, LesionSerializer, count=get_lesion_count_for_user(request.user))


class AccessionCreateSerializer(StrictSerializer):
Expand Down