Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use router path as resource name #28

Closed
Closed
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: 18 additions & 1 deletion src/ddtrace_asgi/middleware.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import typing

from ddtrace import Tracer, tracer as global_tracer
from ddtrace import Span, Tracer, tracer as global_tracer
from ddtrace.constants import ANALYTICS_SAMPLE_RATE_KEY
from ddtrace.ext import http as http_tags
from ddtrace.http import store_request_headers, store_response_headers
from ddtrace.propagation.http import HTTPPropagator
from ddtrace.settings import config
from starlette.datastructures import CommaSeparatedStrings, Headers
from starlette.requests import Request
from starlette.routing import Match
from starlette.types import ASGIApp, Message, Receive, Scope, Send


Expand Down Expand Up @@ -106,8 +107,24 @@ async def send_with_tracing(message: Message) -> None:
span.set_traceback()
raise exc from None
finally:
self.__enrich_span(span, scope, method)
span.finish()

def __enrich_span(self, span: Span, scope: Scope, method: str) -> None:
if "router" in scope:
path = None
routes = getattr(scope["router"], "routes", [])
for route in routes:
match, _ = route.matches(scope)
if match == Match.FULL:
path = route.path
break
elif match == Match.PARTIAL and path is None:
path = route.path

if path is not None:
span.resource = f"{method} {path}"


def parse_tags(value: str) -> typing.Dict[str, str]:
tags = {}
Expand Down
5 changes: 5 additions & 0 deletions tests/applications/fastapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,8 @@ async def child(request: Request) -> str:
@application.get("/exception")
async def exception() -> typing.NoReturn:
raise RuntimeError("Oops")


@application.get("/path-parameters/{parameter}", response_class=PlainTextResponse)
async def path_parameters(parameter: str) -> str:
return f"Hello, {parameter}!"
29 changes: 29 additions & 0 deletions tests/applications/raw.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import re

from ddtrace import Tracer
from starlette.types import Receive, Scope, Send

Expand Down Expand Up @@ -42,10 +44,37 @@ async def exception(scope: Scope, receive: Receive, send: Send) -> None:
raise exc


async def path_parameters(scope: Scope, receive: Receive, send: Send) -> None:
assert scope["type"] == "http"
parameter = scope["path"].split("/")[2]
if scope["method"] == "GET":
await send(
{
"type": "http.response.start",
"status": 200,
"headers": [[b"content-type", b"text/plain"]],
}
)
await send(
{"type": "http.response.body", "body": f"Hello, {parameter}!".encode()}
)
else:
await send(
{
"type": "http.response.start",
"status": 405,
"headers": [[b"content-type", b"text/plain"]],
}
)
await send({"type": "http.response.body", "body": b"Method No Allowed"})


async def application(scope: Scope, receive: Receive, send: Send) -> None:
if scope["path"] == "/child":
await child(scope, receive, send)
elif scope["path"] == "/exception":
await exception(scope, receive, send)
elif re.match(r"/path-parameters/[^/]+", scope["path"]):
await path_parameters(scope, receive, send)
else:
await hello_world(scope, receive, send)
6 changes: 6 additions & 0 deletions tests/applications/starlette.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,9 @@ async def child(request: Request) -> Response:
@application.route("/exception")
async def exception(request: Request) -> typing.NoReturn:
raise RuntimeError("Oops")


@application.route("/path-parameters/{parameter}", methods=["GET"])
async def path_parameters(request: Request) -> Response:
parameter = request.path_params["parameter"]
return PlainTextResponse(f"Hello, {parameter}!")
69 changes: 69 additions & 0 deletions tests/test_trace_middleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,75 @@ async def test_child(client: httpx.AsyncClient, tracer: Tracer) -> None:
assert child_span.error == 0


@pytest.mark.asyncio
async def test_path_parameters_full_match(
application: ASGIApp, client: httpx.AsyncClient, tracer: Tracer
) -> None:
is_raw = application.__module__ == "tests.applications.raw"
resource = (
"GET /path-parameters/some-path-parameter"
if is_raw
else "GET /path-parameters/{parameter}"
)

start = time.time()
r = await client.get("/path-parameters/some-path-parameter")
end = time.time()
assert r.status_code == 200
assert r.text == "Hello, some-path-parameter!"

traces = tracer.writer.pop_traces()
assert len(traces) == 1
spans: typing.List[Span] = traces[0]
assert len(spans) == 1
spans_by_name = {s.name: s for s in spans}

span = spans_by_name["asgi.request"]
assert span.span_id
assert span.trace_id
assert span.parent_id is None
assert span.service == "test.asgi.service"
assert span.resource == resource
assert span.get_tag("hello") is None
assert span.start >= start
assert span.duration <= end - start
assert span.error == 0


@pytest.mark.asyncio
async def test_path_parameters_partial_match(
application: ASGIApp, client: httpx.AsyncClient, tracer: Tracer
) -> None:
is_raw = application.__module__ == "tests.applications.raw"
resource = (
"POST /path-parameters/some-path-parameter"
if is_raw
else "POST /path-parameters/{parameter}"
)

start = time.time()
r = await client.post("/path-parameters/some-path-parameter")
end = time.time()
assert r.status_code == 405

traces = tracer.writer.pop_traces()
assert len(traces) == 1
spans: typing.List[Span] = traces[0]
assert len(spans) == 1
spans_by_name = {s.name: s for s in spans}

span = spans_by_name["asgi.request"]
assert span.span_id
assert span.trace_id
assert span.parent_id is None
assert span.service == "test.asgi.service"
assert span.resource == resource
assert span.get_tag("hello") is None
assert span.start >= start
assert span.duration <= end - start
assert span.error == 0


@pytest.mark.asyncio
async def test_not_http_no_traces(tracer: Tracer) -> None:
async def app(scope: Scope, receive: Receive, send: Send) -> None:
Expand Down