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
10 changes: 8 additions & 2 deletions core/common/mixins.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
INCLUDE_PARENT_CONCEPTS, INCLUDE_CHILD_CONCEPTS, INCLUDE_PARENT_CONCEPT_URLS, INCLUDE_CHILD_CONCEPT_URLS,
INCLUDE_HIERARCHY_PATH, INCLUDE_SUMMARY)
MAX_UNPAGINATED_RESULTS = 1000 # `Compress` lists; above this, users.list_unpaginated (ocl_online#230)
FACETS_CACHE_SUFFIX = '#for-anyone' # a facetsOnly answer's cache key ends with it


class CustomPaginator:
Expand Down Expand Up @@ -185,6 +186,9 @@ def __get_cached_data_if_any(self, request):
if query_string:
key_body += '?' + query_string
key_headers += '?' + query_string
if self.only_facets(): # get_facets(for_requester=False)'s, not the answers cached before as one requester's
key_body += FACETS_CACHE_SUFFIX
key_headers += FACETS_CACHE_SUFFIX

return key_body, cache.get(key_body) or None, key_headers, cache.get(key_headers) or None

Expand Down Expand Up @@ -235,6 +239,8 @@ def _list(self, request): # pylint:disable=too-many-locals,too-many-branches,to
cache_key_body, data, cache_key_headers, headers = self.__get_cached_data_if_any(request)
if self.request.query_params.get('_force_cache_clear') in TRUTHY:
data = None
if data and self.only_facets(): # cached as anyone sees them, so as this requester sees them
return Response({'facets': {'fields': self.get_requester_facets(data['facets']['fields'])}})
Comment on lines +242 to +243

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Entries cached before this deploys (they live for a day) were stored by the old get_facets(), so they have no _collection_names. On a hit, keep_collection_facets_viewable gets collections == [] and finds no URLs. It then sets collection, collection_version and expansion to [] for every requester who isn't staff, until the entry expires or the repo's cache is cleared. So for up to a day after release, every source version's cached facets would show no collections.

_collection_names is always in the new entries (the faceted response has a key for every facet, even an empty one), so an entry without it is from before the change. Treating it as a miss recomputes the entry and caches it in the new shape:

Suggested change
if data and self.only_facets(): # cached as anyone sees them, so as this requester sees them
return Response({'facets': {'fields': self.get_requester_facets(data['facets']['fields'])}})
if data and self.only_facets(): # cached as anyone sees them, so as this requester sees them
if '_collection_names' in get(data, 'facets.fields', {}):
return Response({'facets': {'fields': self.get_requester_facets(data['facets']['fields'])}})
data = None # cached before collection facets were recounted

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. 0290592 handles it with a separate key rather than a shape check: shared entries are stored under a key ending #for-anyone (FACETS_CACHE_SUFFIX), so entries from before the change sit under the old key and are never read. Non-staff get a fresh computation on the first hit, which is then cached in the new shape. It also covers a rollback (Codex pass 2, F2.1): old code never reads the new entries, which hold _collection_names. test_repo_version_concepts_facets_ignore_answers_cached_before checks that an answer under the old key isn't read.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The #for-anyone key works better than my shape check: it also covers a rollback, and clear_cache still clears it because delete_pattern matches by prefix. Resolved.


if not data:
search_string = query_params.get('type', None)
Expand All @@ -245,12 +251,12 @@ def _list(self, request): # pylint:disable=too-many-locals,too-many-branches,to
return self.get_csv(request)

if self.only_facets():
data = {'facets': {'fields': self.get_facets()}}
data = {'facets': {'fields': self.get_facets(for_requester=False)}} # the same for everyone
if cache_key_body is not None:
timeout = 60 * 60 * 24 # 1 day
cache.set(cache_key_body, data, timeout=timeout)
cache.set(cache_key_headers, headers, timeout=timeout)
return Response(data)
return Response({'facets': {'fields': self.get_requester_facets(data['facets']['fields'])}})
if self.only_search_stats() and search_term:
return Response(
self.get_search_stats(
Expand Down
5 changes: 4 additions & 1 deletion core/common/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,11 @@ def get_visible_repo_criteria(user):


class CustomESFacetedSearch(FacetedSearch):
def __init__(self, query=None, filters=None, sort=(), _search=None): # pylint: disable=dangerous-default-value
def __init__(self, query=None, filters=None, sort=(), _search=None, extra_facets=None): # pylint: disable=dangerous-default-value
"""extra_facets: facets to compute alongside the class's, by name."""
self._search = _search
if extra_facets:
self.facets = {**self.facets, **extra_facets}
super().__init__(query=query, filters=filters or {}, sort=sort)

@staticmethod
Expand Down
91 changes: 83 additions & 8 deletions core/common/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from elasticsearch import RequestError, TransportError
from elasticsearch_dsl import Q
from elasticsearch_dsl import Q, TermsFacet
from pydash import get, compact
from rest_framework import response, generics, status
from rest_framework.generics import ListAPIView, RetrieveUpdateDestroyAPIView
Expand All @@ -27,7 +27,7 @@
LIMIT_PARAM, NOT_FOUND, MUST_SPECIFY_EXTRA_PARAM_IN_BODY, INCLUDE_RETIRED_PARAM, VERBOSE_PARAM, HEAD, LATEST, \
BRIEF_PARAM, ES_REQUEST_TIMEOUT, INCLUDE_INACTIVE, FHIR_LIMIT_PARAM, RAW_PARAM, SEARCH_MAP_CODES_PARAM, \
INCLUDE_SEARCH_META_PARAM, EXCLUDE_FUZZY_SEARCH_PARAM, EXCLUDE_WILDCARD_SEARCH_PARAM, UPDATED_BY_USERNAME_PARAM, \
CANONICAL_URL_REQUEST_PARAM, CHECKSUMS_PARAM, ACCESS_TYPE_NONE, HTTP_COMPRESS_HEADER
CANONICAL_URL_REQUEST_PARAM, CHECKSUMS_PARAM, ACCESS_TYPE_NONE, HTTP_COMPRESS_HEADER, FACET_SIZE
from core.common.exceptions import Http400
from core.common.mixins import PathWalkerMixin
from core.common.permissions import CanViewConceptDictionary
Expand Down Expand Up @@ -68,6 +68,10 @@ class BaseAPIView(generics.GenericAPIView, PathWalkerMixin):
collection_facets = ('collection', 'collection_url', 'collection_owner_url')
max_viewable_collection_urls = 1000
_viewable_collection_urls = None # get_viewable_collection_urls's, read once per request and facet value
max_collection_facet_names = 3 * FACET_SIZE # keep_collection_facets_viewable's
# the facets that name collection versions or expansions, with the index field holding the URLs they come from
collection_url_facets = {'collection': 'collection_url', 'collection_version': 'collection_url',
'expansion': 'expansion_url'}
Comment on lines +73 to +74

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The recount makes the collection_version and expansion facets count only versions the requester can view, but their filters still read the raw index. They aren't in collection_facets, so get_faceted_filters turns ?collectionVersion= and ?expansion= into a plain term query, and get_collection_facet_criterion never sees them. In a source scope:

  • An outsider sees v1: 1, clicks it, and gets the members of every collection's v1, private ones included. That's more rows than the count, and it shows which concepts are in a version they can't view.
  • A name left out of the facet still lists its members when typed in. In the new test, ?collectionVersion=hidden… works for an outsider.

So the description's "a bucket's count is what clicking it finds" holds for collection only.

Fix options:

  • In this PR: route these two filters through the same viewable criterion. collection_version=<name> becomes terms collection_url over the viewable versions with that name, and expansion=<name> becomes terms expansion_url over the viewable expansions.
  • Or open a follow-up ticket and narrow the description's claim to collection.

Either way, a check like listed(f'{url}?collectionVersion=v1', self.outsider, 'concepts') next to the facet assertions in test_collection_version_and_expansion_facets_name_only_versions_the_requester_can_view would pin it.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks. I checked this on b73149a before changing anything: collection_version and expansion aren't query-string filters. Neither is in Concept.es_fields or Mapping.es_fields, so get_faceted_fields never picks them up. In a source scope, an outsider's and a member's ?collectionVersion=v1, ?collectionVersion=hidden…, ?expansion=hidden… and ?collectionVersion=nope all list exactly the unfiltered scope, on both the DB path and the search path (with q). So clicking a bucket doesn't narrow anything and can't show a version's members.

I pinned it as you suggested, next to the facet assertions in that test (b73149a): each of those queries lists what the unfiltered scope lists for an outsider. The description now claims "count = what clicking finds" for collection only, and says the other two aren't filters. If they're ever made filterable, they should go through get_collection_facet_criterion like collection.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed, my mistake. get_faceted_fields builds the filter list from es_fields, and neither Concept.es_fields nor Mapping.es_fields has collection_version or expansion. So ?collectionVersion= and ?expansion= never reach the query, and nothing leaks. The new assertions in b73149a pin that, and the description now scopes its claim to collection. Resolved.


def get_throttles(self):
return ThrottleUtil.get_throttles_by_user_plan(self.request.user)
Expand Down Expand Up @@ -714,23 +718,30 @@ def exclude_hidden_latest_releases(self, results, latest_attr):
criterion = criteria if criterion is None else criterion | criteria
return results if criterion is None else results.exclude(criterion)

def get_facets(self): # pylint: disable=too-many-branches
def get_facets(self, for_requester=True): # pylint: disable=too-many-branches
"""
The search's facets. Without for_requester, before get_requester_facets: the same for everyone who can run
the search, so they can be cached.
"""
facets = {}
parent_repo = None
params = {}

if self.facet_class:
if self.is_user_document():
return facets

params = {
'query': self.get_search_string(lower=False),
'_search': self.__get_search_results(
ignore_retired_filter=True, sort=False, highlight=False, force=True)
'_search': self.get_facets_search()
}
if 'source' in self.kwargs and self.is_concept_document():
parent_repo = params['parent'] = get(self, 'parent_resource')
if self.map_codes_release:
params['release'] = self.map_codes_release
if self.is_source_child_document_model(): # see keep_collection_facets_viewable
params['extra_facets'] = {
'_collection_names': TermsFacet(field='collection', size=self.max_collection_facet_names)}

faceted_search = self.facet_class(**params) # pylint: disable=not-callable
faceted_search.params(request_timeout=ES_REQUEST_TIMEOUT)
Expand All @@ -739,8 +750,6 @@ def get_facets(self): # pylint: disable=too-many-branches
facets = s.facets.to_dict()
except TransportError as ex: # pragma: no cover
raise Http400(detail=get(ex, 'info') or get(ex, 'error') or str(ex)) from ex
if not get(self.request.user, 'is_authenticated'):
facets.pop('updatedBy', None)
if self.should_search_latest_repo() and self.is_source_child_document_model() and 'source_version' in facets:
facets['source_version'] = [facet for facet in facets['source_version'] if facet[0] != 'HEAD']
is_global_scope = ('org' not in self.kwargs and 'user' not in self.kwargs and not self.user_is_self)
Expand Down Expand Up @@ -769,10 +778,76 @@ def get_facets(self): # pylint: disable=too-many-branches
facets.pop('is_latest_version', None)

if parent_repo and self.is_concept_document():
return parent_repo.get_ordered_concept_facets_by_filter_order(facets)
facets = parent_repo.get_ordered_concept_facets_by_filter_order(facets)

return self.get_requester_facets(facets, get(params, '_search')) if for_requester else facets

def get_facets_search(self):
return self.__get_search_results(ignore_retired_filter=True, sort=False, highlight=False, force=True)

def get_requester_facets(self, facets, search=None):
"""get_facets(for_requester=False)'s facets as this requester sees them; `search`: get_facets_search's."""
if not get(self.request.user, 'is_authenticated'):
facets.pop('updatedBy', None)
self.keep_collection_facets_viewable(facets, search)
return facets

def keep_collection_facets_viewable(self, facets, search=None):
"""
The collection, collection_version and expansion facets name the collection versions and expansions a match
is in as the index lists them: those the requester can't view, and those since deleted, too. Here each name
counts only the matches in the ones they can view, as the collection filter matches them
(get_collection_facet_criterion), in one more request; a name with none is left out. Staff see them as they
are. The collections counted are those _collection_names lists: the top max_collection_facet_names among the
matches. One past them isn't counted, so its names can be missing, never wrong.
"""
from core.collections.models import Collection
collections = [name for name, _, _ in facets.pop('_collection_names', [])]
present = {facet: {name for name, _, _ in facets[facet]} for facet in self.collection_url_facets
if facets.get(facet)}
viewable = Collection.get_viewable_versions_criteria(self.request.user)
if not present or viewable is None:
return
urls = self.get_viewable_collection_facet_urls(present, collections, viewable)
counts = {}
if urls:
search = (search or self.get_facets_search()).extra(size=0).params(request_timeout=ES_REQUEST_TIMEOUT)
search.aggs.bucket('viewable', 'filters', filters={
str(i): Q('terms', **{self.collection_url_facets[facet]: sorted(values)})
for i, ((facet, _), values) in enumerate(urls.items())})
try:
buckets = search.execute().aggregations.viewable.buckets
except TransportError as ex: # pragma: no cover
raise Http400(detail=get(ex, 'info') or get(ex, 'error') or str(ex)) from ex
counts = {key: buckets[str(i)].doc_count for i, key in enumerate(urls)}
for facet in present:
facets[facet] = sorted(
[(name, count, False) for (_facet, name), count in counts.items() if _facet == facet and count],
key=lambda bucket: (-bucket[1], bucket[0]))[:FACET_SIZE]

@staticmethod
def get_viewable_collection_facet_urls(facets, collections, viewable):
"""
{(facet, name): urls} for these collection facets ({facet: the names it lists}), from these collections'
versions the requester can view (`viewable`): their URLs by collection and version name, as the collection
filter matches them, and their expansions' URLs by expansion name. A version or expansion name counts only if
its facet lists it, so the request stays the facets' size. Names read as the documents read them from their
expansions' URIs (to_parent_kwargs_from_uri).
"""
from core.collections.models import Collection, Expansion
versions = Collection.objects.filter(viewable, mnemonic__in=collections)
urls = {}
for uri in versions.values_list('uri', flat=True):
parts = uri.strip('/').split('/')
for facet, name in [('collection', parts[3]), ('collection_version', parts[4] if len(parts) > 4 else HEAD)]:
if facet in facets and (facet == 'collection' or name in facets[facet]):
urls.setdefault((facet, name), set()).add(uri)
if 'expansion' in facets:
for uri, name in Expansion.objects.filter(
collection_version__in=versions, mnemonic__in=facets['expansion']).values_list('uri', 'mnemonic'):
urls.setdefault(('expansion', name), set()).add(uri)
return urls

def get_extras_searchable_fields_from_query_params(self):
query_params = self.request.query_params.dict()
result = {}
Expand Down
Loading
Loading