-
Notifications
You must be signed in to change notification settings - Fork 462
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
asyncio integration #1671
Merged
Merged
asyncio integration #1671
Changes from 21 commits
Commits
Show all changes
25 commits
Select commit
Hold shift + click to select a range
a93565b
First version of asyncio integration
antonpirker 18a02c5
Create a hub and span for each corotine run.
antonpirker 82f0329
Fixed some typing
antonpirker 00678e0
Fixed some typing
antonpirker e570c85
Merge branch 'antonpirker/asyncio-integration' of github.com:getsentr…
antonpirker 5ed18da
Fixed linting
antonpirker d5800d9
Merge branch 'master' into antonpirker/asyncio-integration
antonpirker 192b578
Merge branch 'master' into antonpirker/asyncio-integration
antonpirker 64d8e1a
Added tests
antonpirker 8f74a50
Moved fixtured into test because it uses modules that are not always …
antonpirker 3fb9d11
Using constant
antonpirker 3597375
Using the 'function' op.
antonpirker 402b192
Wrap import with try except
antonpirker d37cfb1
Make sure to use custom task factory if there is one
antonpirker 9b7e111
Merge branch 'master' into antonpirker/asyncio-integration
antonpirker 7c60637
Update sentry_sdk/integrations/asyncio.py
antonpirker 4b4fbdb
Merge branch 'master' into antonpirker/asyncio-integration
antonpirker 2de0b43
Error handling
antonpirker ff17782
Merge branch 'master' into antonpirker/asyncio-integration
antonpirker e0a51c0
Merge branch 'master' into antonpirker/asyncio-integration
antonpirker 380ca42
Merge branch 'master' into antonpirker/asyncio-integration
antonpirker 26f7c80
Merge branch 'master' into antonpirker/asyncio-integration
antonpirker e7e5ebb
Update sentry_sdk/integrations/asyncio.py
antonpirker 01a9fe6
Ignoring typing
antonpirker d138ba7
Merge branch 'master' into antonpirker/asyncio-integration
antonpirker File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
from __future__ import absolute_import | ||
|
||
from sentry_sdk.consts import OP | ||
from sentry_sdk.hub import Hub | ||
from sentry_sdk.integrations import Integration, DidNotEnable | ||
from sentry_sdk._types import MYPY | ||
|
||
try: | ||
import asyncio | ||
from asyncio.tasks import Task | ||
except ImportError: | ||
raise DidNotEnable("asyncio not available") | ||
|
||
|
||
if MYPY: | ||
from typing import Any | ||
|
||
|
||
def _sentry_task_factory(loop, coro): | ||
# type: (Any, Any) -> Task[None] | ||
|
||
async def _coro_creating_hub_and_span(): | ||
# type: () -> None | ||
hub = Hub(Hub.current) | ||
with hub: | ||
with hub.start_span(op=OP.FUNCTION, description=coro.__qualname__): | ||
await coro | ||
|
||
# Trying to use user set task factory (if there is one) | ||
orig_factory = loop.get_task_factory() | ||
if orig_factory: | ||
return orig_factory(loop, _coro_creating_hub_and_span) | ||
|
||
# The default task factory in `asyncio` does not have its own function | ||
# but is just a couple of lines in `asyncio.base_events.create_task()` | ||
# Those lines are copied here. | ||
|
||
# WARNING: | ||
# If the default behavior of the task creation in asyncio changes, | ||
# this will break! | ||
task = Task(_coro_creating_hub_and_span(), loop=loop) | ||
if task._source_traceback: # type: ignore | ||
del task._source_traceback[-1] # type: ignore | ||
|
||
return task | ||
|
||
|
||
def patch_asyncio(): | ||
# type: () -> None | ||
try: | ||
loop = asyncio.get_running_loop() | ||
loop.set_task_factory(_sentry_task_factory) | ||
except RuntimeError: | ||
# When there is no running loop, we have nothing to patch. | ||
pass | ||
|
||
|
||
class AsyncioIntegration(Integration): | ||
identifier = "asyncio" | ||
|
||
@staticmethod | ||
def setup_once(): | ||
# type: () -> None | ||
patch_asyncio() |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,118 @@ | ||
import asyncio | ||
import sys | ||
|
||
import pytest | ||
import pytest_asyncio | ||
|
||
import sentry_sdk | ||
from sentry_sdk.consts import OP | ||
from sentry_sdk.integrations.asyncio import AsyncioIntegration | ||
|
||
|
||
minimum_python_36 = pytest.mark.skipif( | ||
sys.version_info < (3, 6), reason="ASGI is only supported in Python >= 3.6" | ||
) | ||
|
||
|
||
async def foo(): | ||
await asyncio.sleep(0.01) | ||
|
||
|
||
async def bar(): | ||
await asyncio.sleep(0.01) | ||
|
||
|
||
@pytest_asyncio.fixture(scope="session") | ||
def event_loop(request): | ||
"""Create an instance of the default event loop for each test case.""" | ||
loop = asyncio.get_event_loop_policy().new_event_loop() | ||
yield loop | ||
loop.close() | ||
|
||
|
||
@minimum_python_36 | ||
@pytest.mark.asyncio | ||
async def test_create_task( | ||
sentry_init, | ||
capture_events, | ||
event_loop, | ||
): | ||
sentry_init( | ||
traces_sample_rate=1.0, | ||
send_default_pii=True, | ||
debug=True, | ||
integrations=[ | ||
AsyncioIntegration(), | ||
], | ||
) | ||
|
||
events = capture_events() | ||
|
||
with sentry_sdk.start_transaction(name="test_transaction_for_create_task"): | ||
with sentry_sdk.start_span(op="root", description="not so important"): | ||
tasks = [event_loop.create_task(foo()), event_loop.create_task(bar())] | ||
await asyncio.wait(tasks, return_when=asyncio.FIRST_EXCEPTION) | ||
|
||
sentry_sdk.flush() | ||
|
||
(transaction_event,) = events | ||
|
||
assert transaction_event["spans"][0]["op"] == "root" | ||
assert transaction_event["spans"][0]["description"] == "not so important" | ||
|
||
assert transaction_event["spans"][1]["op"] == OP.FUNCTION | ||
assert transaction_event["spans"][1]["description"] == "foo" | ||
assert ( | ||
transaction_event["spans"][1]["parent_span_id"] | ||
== transaction_event["spans"][0]["span_id"] | ||
) | ||
|
||
assert transaction_event["spans"][2]["op"] == OP.FUNCTION | ||
assert transaction_event["spans"][2]["description"] == "bar" | ||
assert ( | ||
transaction_event["spans"][2]["parent_span_id"] | ||
== transaction_event["spans"][0]["span_id"] | ||
) | ||
|
||
|
||
@minimum_python_36 | ||
@pytest.mark.asyncio | ||
async def test_gather( | ||
sentry_init, | ||
capture_events, | ||
): | ||
sentry_init( | ||
traces_sample_rate=1.0, | ||
send_default_pii=True, | ||
debug=True, | ||
integrations=[ | ||
AsyncioIntegration(), | ||
], | ||
) | ||
|
||
events = capture_events() | ||
|
||
with sentry_sdk.start_transaction(name="test_transaction_for_gather"): | ||
with sentry_sdk.start_span(op="root", description="not so important"): | ||
await asyncio.gather(foo(), bar(), return_exceptions=True) | ||
|
||
sentry_sdk.flush() | ||
|
||
(transaction_event,) = events | ||
|
||
assert transaction_event["spans"][0]["op"] == "root" | ||
assert transaction_event["spans"][0]["description"] == "not so important" | ||
|
||
assert transaction_event["spans"][1]["op"] == OP.FUNCTION | ||
assert transaction_event["spans"][1]["description"] == "foo" | ||
assert ( | ||
transaction_event["spans"][1]["parent_span_id"] | ||
== transaction_event["spans"][0]["span_id"] | ||
) | ||
|
||
assert transaction_event["spans"][2]["op"] == OP.FUNCTION | ||
assert transaction_event["spans"][2]["description"] == "bar" | ||
assert ( | ||
transaction_event["spans"][2]["parent_span_id"] | ||
== transaction_event["spans"][0]["span_id"] | ||
) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
shouldn't this be
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Done.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
but how did it work before lol
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
How does it work now, actually 😄 The correct version is the first one.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I'm not sure, please test all cases @antonpirker
this is what cpython does
https://github.com/python/cpython/blob/main/Lib/asyncio/base_events.py#L436-L444
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ok, will test.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Really good catch @vmarkovtsev!
This lead to this fix: #1689