Skip to content

Commit 87897e0

Browse files
committed
Merge main into claude/funny-ramanujan-ehkqn7
The path and full_path render arguments from #2987 are now passed by render_with_output_renderer(), replacing the three call sites that conflicted. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016BvfqCn4No2Nib8F28Zt5J
2 parents 49d9988 + e9d45fe commit 87897e0

18 files changed

Lines changed: 297 additions & 17 deletions

‎datasette/facets.py‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import json
2+
import time
23
import urllib
34

45
from datasette import hookimpl
@@ -12,6 +13,26 @@
1213
sqlite3,
1314
)
1415

16+
# Suggesting facets for a page can take at most this many multiples of
17+
# the facet_suggest_time_limit_ms setting in total, see #862
18+
SUGGEST_TOTAL_TIME_LIMIT_MULTIPLE = 10
19+
20+
21+
def start_suggest_deadline(ds, facet_instances):
22+
"""
23+
Start the clock on the total time allowed for suggesting facets for a
24+
page, sharing a single deadline across all of the facet instances.
25+
"""
26+
time_limit_ms = ds.setting("facet_suggest_time_limit_ms")
27+
if not time_limit_ms:
28+
# 0 means no per-query suggestion limit, so no total limit either
29+
return
30+
deadline = (
31+
time.monotonic() + SUGGEST_TOTAL_TIME_LIMIT_MULTIPLE * time_limit_ms / 1000
32+
)
33+
for facet in facet_instances:
34+
facet.suggest_deadline = deadline
35+
1536

1637
def load_facet_configs(request, table_config):
1738
# Given a request and the configuration for a table, return
@@ -86,6 +107,10 @@ class Facet:
86107
type = None
87108
# How many rows to consider when suggesting facets:
88109
suggest_consider = 1000
110+
# time.monotonic() value after which suggest() should stop considering
111+
# further columns, or None for no deadline. Shared by every facet
112+
# instance on a page, see start_suggest_deadline()
113+
suggest_deadline = None
89114

90115
def __init__(
91116
self,
@@ -152,6 +177,17 @@ def get_facet_size(self):
152177
async def suggest(self):
153178
return []
154179

180+
def suggest_time_exceeded(self):
181+
"""
182+
True if the page has used up its total time budget for suggesting
183+
facets. suggest() implementations should check this before running
184+
the query for each column and stop if it returns True.
185+
"""
186+
return (
187+
self.suggest_deadline is not None
188+
and time.monotonic() >= self.suggest_deadline
189+
)
190+
155191
async def facet_results(self):
156192
# returns ([results], [timed_out])
157193
# TODO: Include "hideable" with each one somehow, which indicates if it was
@@ -177,6 +213,8 @@ async def suggest(self):
177213
suggested_facets = []
178214
already_enabled = [c["config"]["simple"] for c in self.get_configs()]
179215
for column in columns:
216+
if self.suggest_time_exceeded():
217+
break
180218
if column in already_enabled:
181219
continue
182220
suggested_facet_sql = f"""
@@ -334,6 +372,8 @@ async def suggest(self):
334372
suggested_facets = []
335373
already_enabled = [c["config"]["simple"] for c in self.get_configs()]
336374
for column in columns:
375+
if self.suggest_time_exceeded():
376+
break
337377
if column in already_enabled:
338378
continue
339379
# Is every value in this column either null or a JSON array?
@@ -492,6 +532,8 @@ async def suggest(self):
492532
already_enabled = [c["config"]["simple"] for c in self.get_configs()]
493533
suggested_facets = []
494534
for column in columns:
535+
if self.suggest_time_exceeded():
536+
break
495537
if column in already_enabled:
496538
continue
497539
# Does this column contain any dates in the first 100 rows?

‎datasette/templates/_homepage_results.html‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
<section class="homepage-queries" aria-labelledby="homepage-queries-heading">
2121
<div class="homepage-section-header">
2222
<h2 id="homepage-queries-heading">{% if q %}Matching queries{% else %}Queries{% endif %}</h2>
23-
<a class="homepage-section-link" href="{{ all_queries_url }}{% if q %}?{{ {"q": q}|urlencode }}{% endif %}">{% if q %}All {{ "{:,}".format(catalog.queries_total) }} matching{% else %}All {{ "{:,}".format(catalog.queries_total) }} quer{% if catalog.queries_total != 1 %}ies{% else %}y{% endif %}{% endif %} →</a>
23+
<a class="homepage-section-link" href="{{ all_queries_url }}{% if q %}?{{ {"q": q}|urlencode }}{% endif %}">{{ "{:,}".format(catalog.queries_total) }}{% if q %} matching{% endif %} quer{% if catalog.queries_total != 1 %}ies{% else %}y{% endif %} →</a>
2424
</div>
2525
<ul class="query-list">
2626
{% for query in queries %}

‎datasette/templates/database.html‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ <h3>Custom SQL query</h3>
7171
<section class="homepage-queries" aria-labelledby="queries">
7272
<div class="homepage-section-header">
7373
<h2 id="queries">Queries</h2>
74-
<a class="homepage-section-link" href="{{ urls.database(database) }}/-/queries">All {{ "{:,}".format(queries_count) }} quer{% if queries_count != 1 %}ies{% else %}y{% endif %} →</a>
74+
<a class="homepage-section-link" href="{{ urls.database(database) }}/-/queries">{{ "{:,}".format(queries_count) }} quer{% if queries_count != 1 %}ies{% else %}y{% endif %} →</a>
7575
</div>
7676
<ul class="query-list">
7777
{% for query in queries %}

‎datasette/utils/__init__.py‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1068,12 +1068,12 @@ def path_with_format(
10681068
qs = extra_qs or {}
10691069
if path is None and request:
10701070
path = request.path
1071+
if replace_format is None and request:
1072+
# Drop the extension the current request used, e.g. .json
1073+
replace_format = request.url_vars.get("format")
10711074
if replace_format and path.endswith(f".{replace_format}"):
10721075
path = path[: -(1 + len(replace_format))]
1073-
if "." in path:
1074-
qs["_format"] = format
1075-
else:
1076-
path = f"{path}.{format}"
1076+
path = f"{path}.{format}"
10771077
if qs:
10781078
extra = urllib.parse.urlencode(sorted(qs.items()))
10791079
if request and request.query_string:
@@ -1085,6 +1085,17 @@ def path_with_format(
10851085
return path
10861086

10871087

1088+
def path_without_format(request, *, include_query_string=False):
1089+
"Path for this request with any ``.format`` removed, e.g. ``/db/table.json`` -> ``/db/table``"
1090+
path = request.path
1091+
format = request.url_vars.get("format")
1092+
if format and path.endswith(f".{format}"):
1093+
path = path[: -(1 + len(format))]
1094+
if include_query_string and request.query_string:
1095+
path = f"{path}?{request.query_string}"
1096+
return path
1097+
1098+
10881099
class CustomRow(OrderedDict):
10891100
# Loose imitation of sqlite3.Row which offers
10901101
# both index-based AND key-based lookups

‎datasette/views/base.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
add_cors_headers,
77
call_with_supported_arguments,
88
path_with_format,
9+
path_without_format,
910
)
1011
from datasette.utils.asgi import (
1112
BadRequest,
@@ -279,6 +280,8 @@ async def render_with_output_renderer(
279280
database=database,
280281
table=table,
281282
request=request,
283+
path=path_without_format(request),
284+
full_path=path_without_format(request, include_query_string=True),
282285
view_name=view_name,
283286
truncated=truncated,
284287
error=error,

‎datasette/views/database.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
path_with_added_args,
2727
path_with_format,
2828
path_with_removed_args,
29+
path_without_format,
2930
request_route_path,
3031
sqlite3,
3132
tilde_decode,
@@ -985,6 +986,8 @@ async def query_metadata():
985986
database=database,
986987
table=data.get("table"),
987988
request=request,
989+
path=path_without_format(request),
990+
full_path=path_without_format(request, include_query_string=True),
988991
view_name="database",
989992
)
990993
it_can_render = await await_me_maybe(it_can_render)

‎datasette/views/row.py‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
path_from_row_pks,
2828
path_with_format,
2929
path_with_removed_args,
30+
path_without_format,
3031
sqlite3,
3132
tilde_decode,
3233
to_css_class,
@@ -290,6 +291,8 @@ async def html(self, request, data, extra_template_data, templates):
290291
database=data.get("database"),
291292
table=data.get("table"),
292293
request=request,
294+
path=path_without_format(request),
295+
full_path=path_without_format(request, include_query_string=True),
293296
view_name=self.name,
294297
)
295298
it_can_render = await await_me_maybe(it_can_render)

‎datasette/views/table_extras.py‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
from datasette.column_types import SQLiteType
66
from datasette.database import QueryInterrupted
77
from datasette.extras import Extra, ExtraExample, ExtraRegistry, ExtraScope, Provider
8+
from datasette.facets import start_suggest_deadline
89
from datasette.plugins import pm
910
from datasette.resources import DatabaseResource, TableResource
1011
from datasette.utils import (
@@ -13,6 +14,7 @@
1314
path_with_added_args,
1415
path_with_format,
1516
path_with_removed_args,
17+
path_without_format,
1618
request_route_path,
1719
to_css_class,
1820
)
@@ -292,10 +294,11 @@ async def resolve(self, context, facet_instances):
292294
and not context.nofacet
293295
and not context.nosuggest
294296
):
295-
facet_suggest_awaitables = [facet.suggest() for facet in facet_instances]
296-
for suggest_result in await context.run_sequential(
297-
*facet_suggest_awaitables
298-
):
297+
start_suggest_deadline(context.datasette, facet_instances)
298+
for facet in facet_instances:
299+
if facet.suggest_time_exceeded():
300+
break
301+
(suggest_result,) = await context.run_sequential(facet.suggest())
299302
suggested_facets.extend(suggest_result)
300303
return suggested_facets
301304

@@ -1132,6 +1135,10 @@ async def resolve(self, context, expandable_columns, query):
11321135
database=context.database_name,
11331136
table=table_name,
11341137
request=context.request,
1138+
path=path_without_format(context.request),
1139+
full_path=path_without_format(
1140+
context.request, include_query_string=True
1141+
),
11351142
view_name=view_name,
11361143
)
11371144
it_can_render = await await_me_maybe(it_can_render)

‎docs/changelog.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ Unreleased
1818
- New ``?_extra=expanded_columns`` extra for table JSON, listing the foreign key columns that were expanded using ``?_labels=on``.
1919
- ``csv`` and ``tsv`` are now included in the ``?_extra=renderers`` extra.
2020
- Output renderers registered with :ref:`plugin_register_output_renderer` can now list the :ref:`extras <json_api_extra>` they need, such as ``count`` or ``human_description_en``, using a new ``"extras"`` key. Datasette calculates those and passes them to the ``render`` function in a new ``page`` argument, a dictionary which also includes ``next`` and ``next_url`` on table pages. (:issue:`2770`, :issue:`2186`)
21+
- The total time spent calculating suggested facets for a page is now capped at ten times the :ref:`setting_facet_suggest_time_limit_ms` setting, so tables with a large number of columns can no longer spend several seconds suggesting facets. (:issue:`862`)
2122
- The default :ref:`setting_max_post_body_bytes` limit has been increased from 2MB to 10MB (``10485760`` bytes), allowing larger JSON API requests.
2223
- Fixed a bug where a database, table or saved query with a name such as ``count``, ``wrapper`` or ``tag`` could break the layout of its pages, because the class added to the ``<body>`` element for that name matched a class used by Datasette's own CSS and JavaScript.
2324

‎docs/json_api.rst‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -757,9 +757,9 @@ The available table extras are listed below.
757757
.. code-block:: json
758758
759759
{
760-
"json": "/fixtures/facetable.json?_extra=renderers&_format=json&_labels=on",
761-
"tsv": "/fixtures/facetable.json?_extra=renderers&_format=tsv&_labels=on",
762-
"csv": "/fixtures/facetable.json?_extra=renderers&_format=csv&_labels=on"
760+
"json": "/fixtures/facetable.json?_extra=renderers&_labels=on",
761+
"tsv": "/fixtures/facetable.tsv?_extra=renderers&_labels=on",
762+
"csv": "/fixtures/facetable.csv?_extra=renderers&_labels=on"
763763
}
764764
765765
``custom_table_templates``

0 commit comments

Comments
 (0)