tracer.trace_child_tasks() for asyncio.gather tracing

Also added documentation for datasette.tracer module.

Closes #1576
This commit is contained in:
Simon Willison 2022-02-04 21:19:49 -08:00
commit da53e0360d
4 changed files with 111 additions and 7 deletions

View file

@ -1,5 +1,7 @@
import asyncio
from datasette import hookimpl
from datasette.facets import Facet
from datasette import tracer
from datasette.utils import path_with_added_args
from datasette.utils.asgi import asgi_send_json, Response
import base64
@ -270,6 +272,15 @@ def register_routes():
def asgi_scope(scope):
return Response.json(scope, default=repr)
async def parallel_queries(datasette):
db = datasette.get_database()
with tracer.trace_child_tasks():
one, two = await asyncio.gather(
db.execute("select coalesce(sleep(0.1), 1)"),
db.execute("select coalesce(sleep(0.1), 2)"),
)
return Response.json({"one": one.single_value(), "two": two.single_value()})
return [
(r"/one/$", one),
(r"/two/(?P<name>.*)$", two),
@ -281,6 +292,7 @@ def register_routes():
(r"/add-message/$", add_message),
(r"/render-message/$", render_message),
(r"/asgi-scope$", asgi_scope),
(r"/parallel-queries$", parallel_queries),
]

View file

@ -51,3 +51,18 @@ def test_trace(trace_debug):
execute_manys = [trace for trace in traces if trace.get("executemany")]
assert execute_manys
assert all(isinstance(trace["count"], int) for trace in execute_manys)
def test_trace_parallel_queries():
with make_app_client(settings={"trace_debug": True}) as client:
response = client.get("/parallel-queries?_trace=1")
assert response.status == 200
data = response.json
assert data["one"] == 1
assert data["two"] == 2
trace_info = data["_trace"]
traces = [trace for trace in trace_info["traces"] if "sql" in trace]
one, two = traces
# "two" should have started before "one" ended
assert two["start"] < one["end"]