Skip to content

Commit d67913c

Browse files
authored
skip counting results for mvt tiles (#288)
* skip counting results for mvt tiles * pr feedback * switch to flag * fix tests
1 parent ec53872 commit d67913c

7 files changed

Lines changed: 269 additions & 21 deletions

File tree

‎arches_search/utils/search/compiler.py‎

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -156,23 +156,23 @@ def __init__(
156156
for graph_payload in search_payload.advanced_search_queries or []
157157
}
158158

159-
def compile(self) -> SearchResult:
159+
def compile(self, return_counts: bool = True) -> SearchResult:
160160
"""
161161
The matches in the graphs graph_slugs names, how many there are, and how
162162
many of them each of those graphs holds.
163+
164+
With return_counts=False the counts are left as None and their grouped
165+
COUNT is never run.
163166
"""
164-
requested_slugs = set(self.search_payload.graph_slugs or [])
165-
requested_graphs = [
166-
graph for graph in self._named_graphs if graph.slug in requested_slugs
167-
]
167+
requested_graphs = self._requested_graphs()
168168
if not requested_graphs:
169-
return SearchResult(
170-
results=self._base_resources().none(),
171-
scoped_count=0,
172-
resource_type_counts=[],
173-
)
169+
matches = self._base_resources().none()
170+
else:
171+
matches = self._permitted_matches(requested_graphs)
172+
173+
if not return_counts:
174+
return SearchResult(results=matches)
174175

175-
matches = self._permitted_matches(requested_graphs)
176176
# One grouped count gives both the per-graph counts and the total, so a
177177
# paginator can skip its own COUNT(*).
178178
counts_by_graph_id = _counts_by_graph_id(matches)
@@ -184,6 +184,10 @@ def compile(self) -> SearchResult:
184184
),
185185
)
186186

187+
def _requested_graphs(self) -> List[SearchableGraph]:
188+
requested_slugs = set(self.search_payload.graph_slugs or [])
189+
return [graph for graph in self._named_graphs if graph.slug in requested_slugs]
190+
187191
@cached_property
188192
def _named_graphs(self) -> List[SearchableGraph]:
189193
"""

‎arches_search/utils/search/types.py‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,12 +40,12 @@ class SearchResult:
4040
What the compiler found in the graphs graph_slugs names, before any
4141
projection or paging. scoped_count is how many resources `results` holds,
4242
and what pagination is measured against; resource_type_counts splits it by
43-
graph.
43+
graph. Both are None when the compiler was asked not to count.
4444
"""
4545

4646
results: QuerySet
47-
scoped_count: int
48-
resource_type_counts: List[Dict[str, Any]]
47+
scoped_count: Optional[int] = None
48+
resource_type_counts: Optional[List[Dict[str, Any]]] = None
4949

5050

5151
@dataclass(frozen=True)

‎arches_search/views/api/search_export.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,11 @@ def post(self, request):
3030
search_payload = SearchPayload.from_body(body)
3131
try:
3232
validate_search_payload(search_payload)
33-
queryset = SearchCompiler(search_payload, request.user).compile().results
33+
queryset = (
34+
SearchCompiler(search_payload, request.user)
35+
.compile(return_counts=False)
36+
.results
37+
)
3438
except ValidationError as error:
3539
return JSONResponse({"error": str(error)}, status=400)
3640

‎arches_search/views/api/search_mvt.py‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,9 @@ def post(self, request):
8383
try:
8484
search_payload = SearchPayload.from_body(body)
8585
validate_search_payload(search_payload)
86-
SearchCompiler(search_payload, request.user).compile()
86+
SearchCompiler(search_payload, request.user).compile(
87+
return_counts=False
88+
).results
8789
except ValidationError as error:
8890
return JSONResponse({"error": str(error)}, status=400)
8991

@@ -111,15 +113,17 @@ def get(self, request, context_id, zoom, x, y):
111113
return _tile_response(request, cached_tile)
112114

113115
try:
114-
search_result = SearchCompiler(
115-
SearchPayload.from_body(body), request.user
116-
).compile()
116+
matches = (
117+
SearchCompiler(SearchPayload.from_body(body), request.user)
118+
.compile(return_counts=False)
119+
.results
120+
)
117121
except ValidationError:
118122
# The context was checked as the user who created it. Another user
119123
# may not be able to read a node it names, and gets nothing drawn.
120124
return HttpResponse(b"", content_type="application/x-protobuf")
121125

122-
search_results_queryset = search_result.results.values("resourceinstanceid")
126+
search_results_queryset = matches.values("resourceinstanceid")
123127
mvt_tile = self._generate_tile(search_results_queryset, zoom, x, y)
124128

125129
gzipped_tile = (

‎arches_search/views/api/search_results_export.py‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,11 @@ def post(self, request):
5858

5959
try:
6060
validate_search_payload(search_payload)
61-
queryset = SearchCompiler(search_payload, request.user).compile().results
61+
queryset = (
62+
SearchCompiler(search_payload, request.user)
63+
.compile(return_counts=False)
64+
.results
65+
)
6266
except ValidationError as error:
6367
return JSONResponse({"error": str(error)}, status=400)
6468

‎tests/integration/utils/search/test_search_compiler.py‎

Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,10 @@
1414
from django.db import connection
1515
from django.test import TestCase, override_settings
1616
from django.test.utils import CaptureQueriesContext
17+
from django.contrib.auth.models import Group
1718
from django.urls import reverse
1819

20+
from arches.app.utils.permission_backend import assign_perm
1921
from arches.app.models.models import (
2022
GraphModel,
2123
ResourceInstance,
@@ -209,6 +211,91 @@ def _search_models_payloads(self, search_models, operator, operands):
209211
for graph in (self.graph_a, self.graph_b)
210212
]
211213

214+
def _compile_skipping_counts_ids(self, **kwargs):
215+
slugs = kwargs.pop("graph_slugs", [self.graph_a.slug, self.graph_b.slug])
216+
payload = SearchPayload(
217+
graph_slugs=slugs,
218+
term_search=kwargs.get("term_search"),
219+
advanced_search_queries=kwargs.get("advanced_search_queries"),
220+
)
221+
compiler = SearchCompiler(payload, self.user)
222+
return set(
223+
compiler.compile(return_counts=False).results.values_list(
224+
"resourceinstanceid", flat=True
225+
)
226+
), self._result_ids(SearchCompiler(payload, self.user).compile())
227+
228+
def test_compile_skipping_counts_matches_compile_with_no_requested_graphs(self):
229+
results_ids, compile_ids = self._compile_skipping_counts_ids(graph_slugs=[])
230+
self.assertEqual(results_ids, set())
231+
self.assertEqual(results_ids, compile_ids)
232+
233+
def test_compile_skipping_counts_matches_compile_for_a_term_search(self):
234+
results_ids, compile_ids = self._compile_skipping_counts_ids(
235+
term_search={"terms": ["amber"], "max_hops": 0}
236+
)
237+
self.assertTrue(results_ids)
238+
self.assertEqual(results_ids, compile_ids)
239+
240+
def test_compile_skipping_counts_matches_compile_for_an_advanced_search(self):
241+
results_ids, compile_ids = self._compile_skipping_counts_ids(
242+
advanced_search_queries=self._search_models_payloads(
243+
["DateSearch", "DateRangeSearch"],
244+
"BETWEEN",
245+
[
246+
{"type": "LITERAL", "value": "1890-01-01"},
247+
{"type": "LITERAL", "value": "1910-01-01"},
248+
],
249+
)
250+
)
251+
self.assertEqual(results_ids, {self.amber_mineral.resourceinstanceid})
252+
self.assertEqual(results_ids, compile_ids)
253+
254+
def test_compile_skipping_counts_refuses_a_payload_naming_an_unsearched_graph(self):
255+
payload = SearchPayload(
256+
graph_slugs=[self.graph_a.slug],
257+
term_search=None,
258+
advanced_search_queries=[
259+
{
260+
"graph_slug": self.graph_a.slug + "-typo",
261+
"scope": "RESOURCE",
262+
"logic": "AND",
263+
"clauses": [],
264+
"groups": [],
265+
"aggregations": [],
266+
"relationship": None,
267+
}
268+
],
269+
)
270+
with self.assertRaises(ValidationError):
271+
SearchCompiler(payload, self.user).compile(return_counts=False).results
272+
273+
def test_compile_skipping_counts_leaves_the_counts_unset(self):
274+
payload = SearchPayload(
275+
graph_slugs=[self.graph_a.slug],
276+
term_search=None,
277+
advanced_search_queries=None,
278+
)
279+
result = SearchCompiler(payload, self.user).compile(return_counts=False)
280+
self.assertIsNone(result.scoped_count)
281+
self.assertIsNone(result.resource_type_counts)
282+
283+
def test_compile_skipping_counts_issues_no_count_query(self):
284+
payload = SearchPayload(
285+
graph_slugs=[self.graph_a.slug, self.graph_b.slug],
286+
term_search={"terms": ["amber"], "max_hops": 0},
287+
advanced_search_queries=None,
288+
)
289+
with CaptureQueriesContext(connection) as queries:
290+
list(
291+
SearchCompiler(payload, self.user)
292+
.compile(return_counts=False)
293+
.results.values("resourceinstanceid")
294+
)
295+
self.assertTrue(queries.captured_queries)
296+
for query in queries.captured_queries:
297+
self.assertNotIn("COUNT(", query["sql"].upper())
298+
212299
def test_text_match_direct_only_max_hops_zero(self):
213300
result = self._search(term_search={"terms": ["amber"], "max_hops": 0})
214301
self.assertEqual(
@@ -798,3 +885,46 @@ def test_pre_filter_narrows_addressed_and_unaddressed_graphs_alike(self):
798885
self.assertEqual(ids & self.DOG_IDS, {DOG_B_ID})
799886
with self.subTest("the unaddressed graph is narrowed to it"):
800887
self.assertEqual(ids & self.PERSON_IDS, {PERSON_A_ID, PERSON_B_ID})
888+
889+
890+
class CompileResultsPermissionTests(TestCase):
891+
@classmethod
892+
def setUpTestData(cls):
893+
cls.member = get_user_model().objects.create_user(
894+
username="compile-results-member", password="password"
895+
)
896+
cls.group = Group.objects.create(name="compile_skipping_counts_group")
897+
cls.member.groups.add(cls.group)
898+
cls.graph = GraphModel.objects.create(
899+
graphid=uuid.uuid4(),
900+
name="Permissioned",
901+
slug="compile-results-permissioned",
902+
isresource=True,
903+
is_active=True,
904+
)
905+
cls.granted = ResourceInstance.objects.create(
906+
resourceinstanceid=uuid.uuid4(), graph=cls.graph
907+
)
908+
cls.hidden = ResourceInstance.objects.create(
909+
resourceinstanceid=uuid.uuid4(), graph=cls.graph
910+
)
911+
assign_perm("view_resourceinstance", cls.group, cls.granted)
912+
913+
def test_compile_skipping_counts_applies_the_permission_filter(self):
914+
payload = SearchPayload(
915+
graph_slugs=[self.graph.slug],
916+
term_search=None,
917+
advanced_search_queries=None,
918+
)
919+
results_ids = set(
920+
SearchCompiler(payload, self.member)
921+
.compile(return_counts=False)
922+
.results.values_list("resourceinstanceid", flat=True)
923+
)
924+
compile_ids = set(
925+
SearchCompiler(payload, self.member)
926+
.compile()
927+
.results.values_list("resourceinstanceid", flat=True)
928+
)
929+
self.assertEqual(results_ids, {self.granted.resourceinstanceid})
930+
self.assertEqual(results_ids, compile_ids)
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
import json
2+
import uuid
3+
from unittest.mock import patch
4+
5+
from django.contrib.auth import get_user_model
6+
from django.db.models import QuerySet
7+
from django.test import TestCase, override_settings
8+
from django.urls import reverse
9+
10+
from arches.app.models.models import GraphModel
11+
12+
from arches_search.views.api.search_mvt import SearchMVTAPI
13+
14+
# python manage.py test tests.test_search_mvt_context_api --settings="tests.test_settings"
15+
16+
TILE_BYTES = b"fixed-tile"
17+
SEARCHRESULTS_CACHES = {
18+
"default": {"BACKEND": "django.core.cache.backends.dummy.DummyCache"},
19+
"searchresults": {
20+
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
21+
"LOCATION": "mvt-context-test",
22+
},
23+
}
24+
25+
26+
@override_settings(CACHES=SEARCHRESULTS_CACHES)
27+
class SearchMVTSkipsCountTest(TestCase):
28+
@classmethod
29+
def setUpTestData(cls):
30+
cls.user = get_user_model().objects.create_superuser(
31+
username="mvt-context-admin",
32+
email="mvt-context@example.com",
33+
password="password",
34+
)
35+
cls.graph = GraphModel.objects.create(
36+
graphid=uuid.uuid4(),
37+
name="MVT",
38+
slug="mvt-context-graph",
39+
isresource=True,
40+
is_active=True,
41+
)
42+
43+
def setUp(self):
44+
self.client.force_login(self.user)
45+
compile_patcher = patch(
46+
"arches_search.utils.search.compiler._counts_by_graph_id",
47+
side_effect=AssertionError("the counts should not be computed"),
48+
)
49+
compile_patcher.start()
50+
self.addCleanup(compile_patcher.stop)
51+
52+
def _post_context(self, body):
53+
return self.client.post(
54+
reverse("search_mvt_context"),
55+
json.dumps(body),
56+
content_type="application/json",
57+
)
58+
59+
def test_a_valid_context_is_created_without_counting(self):
60+
response = self._post_context({"graph_slugs": [self.graph.slug]})
61+
62+
self.assertEqual(response.status_code, 200)
63+
self.assertIn("context_id", response.json())
64+
65+
def test_an_invalid_payload_is_still_a_400(self):
66+
response = self._post_context(
67+
{
68+
"graph_slugs": [self.graph.slug],
69+
"advanced_search_queries": [
70+
{
71+
"graph_slug": self.graph.slug + "-typo",
72+
"scope": "RESOURCE",
73+
"logic": "AND",
74+
"clauses": [],
75+
"groups": [],
76+
"aggregations": [],
77+
"relationship": None,
78+
}
79+
],
80+
}
81+
)
82+
83+
self.assertEqual(response.status_code, 400)
84+
85+
def test_a_tile_is_generated_from_the_matches_without_counting(self):
86+
context_id = self._post_context({"graph_slugs": [self.graph.slug]}).json()[
87+
"context_id"
88+
]
89+
90+
with patch.object(
91+
SearchMVTAPI, "_generate_tile", return_value=TILE_BYTES
92+
) as generate_tile:
93+
response = self.client.get(
94+
reverse(
95+
"search_mvt",
96+
kwargs={"context_id": context_id, "zoom": 6, "x": 9, "y": 24},
97+
)
98+
)
99+
100+
self.assertEqual(response.status_code, 200)
101+
self.assertEqual(response.content, TILE_BYTES)
102+
self.assertIsInstance(generate_tile.call_args.args[0], QuerySet)

0 commit comments

Comments
 (0)