Merged
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
100 changes: 13 additions & 87 deletions sentry_sdk/hub.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,13 +7,11 @@
from sentry_sdk.consts import INSTRUMENTER
from sentry_sdk.scope import Scope
from sentry_sdk.client import Client
from sentry_sdk.profiler import Profile
from sentry_sdk.tracing import (
NoOpSpan,
Span,
Transaction,
)
from sentry_sdk.tracing_utils import normalize_incoming_data

from sentry_sdk.utils import (
logger,
Expand DownExpand Up@@ -430,54 +428,12 @@ def start_span(self, span=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs):

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Span`.
"""
configuration_instrumenter = self.client and self.client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

# THIS BLOCK IS DEPRECATED
# TODO: consider removing this in a future release.
# This is for backwards compatibility with releases before
# start_transaction existed, to allow for a smoother transition.
if isinstance(span, Transaction) or "transaction" in kwargs:
deprecation_msg = (
"Deprecated: use start_transaction to start transactions and "
"Transaction.start_child to start spans."
)

if isinstance(span, Transaction):
logger.warning(deprecation_msg)
return self.start_transaction(span)

if "transaction" in kwargs:
logger.warning(deprecation_msg)
name = kwargs.pop("transaction")
return self.start_transaction(name=name, **kwargs)

# THIS BLOCK IS DEPRECATED
# We do not pass a span into start_span in our code base, so I deprecate this.
if span is not None:
deprecation_msg = "Deprecated: passing a span into `start_span` is deprecated and will be removed in the future."
logger.warning(deprecation_msg)
return span

kwargs.setdefault("hub", self)

active_span = self.scope.span
if active_span is not None:
new_child_span = active_span.start_child(**kwargs)
return new_child_span
client, scope = self._stack[-1]

# If there is already a trace_id in the propagation context, use it.
# This does not need to be done for `start_child` above because it takes
# the trace_id from the parent span.
if "trace_id" not in kwargs:
traceparent = self.get_traceparent()
trace_id = traceparent.split("-")[0] if traceparent else None
if trace_id is not None:
kwargs["trace_id"] = trace_id
kwargs["hub"] = self
kwargs["client"] = client

return Span(**kwargs)
return scope.start_span(span=span, instrumenter=instrumenter, **kwargs)

def start_transaction(
self, transaction=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs
Expand DownExpand Up@@ -507,55 +463,25 @@ def start_transaction(

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Transaction`.
"""
configuration_instrumenter = self.client and self.client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

custom_sampling_context = kwargs.pop("custom_sampling_context", {})

# if we haven't been given a transaction, make one
if transaction is None:
kwargs.setdefault("hub", self)
transaction = Transaction(**kwargs)

# use traces_sample_rate, traces_sampler, and/or inheritance to make a
# sampling decision
sampling_context = {
"transaction_context": transaction.to_json(),
"parent_sampled": transaction.parent_sampled,
}
sampling_context.update(custom_sampling_context)
transaction._set_initial_sampling_decision(sampling_context=sampling_context)

profile = Profile(transaction, hub=self)
profile._set_initial_sampling_decision(sampling_context=sampling_context)
client, scope = self._stack[-1]

# we don't bother to keep spans if we already know we're not going to
# send the transaction
if transaction.sampled:
max_spans = (
self.client and self.client.options["_experiments"].get("max_spans")
) or 1000
transaction.init_span_recorder(maxlen=max_spans)
kwargs["hub"] = self
kwargs["client"] = client

return transaction
return scope.start_transaction(
transaction=transaction, instrumenter=instrumenter, **kwargs
)

def continue_trace(self, environ_or_headers, op=None, name=None, source=None):
# type: (Dict[str, Any], Optional[str], Optional[str], Optional[str]) -> Transaction
"""
Sets the propagation context from environment or headers and returns a transaction.
"""
with self.configure_scope() as scope:
scope.generate_propagation_context(environ_or_headers)
scope = self._stack[-1][1]

transaction = Transaction.continue_from_headers(
normalize_incoming_data(environ_or_headers),
op=op,
name=name,
source=source,
return scope.continue_trace(
environ_or_headers=environ_or_headers, op=op, name=name, source=source
)
return transaction

@overload
def push_scope(
Expand Down
158 changes: 154 additions & 4 deletions sentry_sdk/scope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,8 +6,9 @@

from sentry_sdk.attachments import Attachment
from sentry_sdk._compat import datetime_utcnow
from sentry_sdk.consts import FALSE_VALUES
from sentry_sdk.consts import FALSE_VALUES, INSTRUMENTER
from sentry_sdk._functools import wraps
from sentry_sdk.profiler import Profile
from sentry_sdk.session import Session
from sentry_sdk.tracing_utils import (
Baggage,
Expand All@@ -18,6 +19,8 @@
from sentry_sdk.tracing import (
BAGGAGE_HEADER_NAME,
SENTRY_TRACE_HEADER_NAME,
NoOpSpan,
Span,
Transaction,
)
from sentry_sdk._types import TYPE_CHECKING
Expand All@@ -34,6 +37,7 @@
from typing import Optional
from typing import Tuple
from typing import TypeVar
from typing import Union

from sentry_sdk._types import (
Breadcrumb,
Expand All@@ -46,9 +50,6 @@
Type,
)

from sentry_sdk.profiler import Profile
from sentry_sdk.tracing import Span

F = TypeVar("F", bound=Callable[..., Any])
T = TypeVar("T")

Expand DownExpand Up@@ -636,6 +637,155 @@ def add_breadcrumb(self, crumb=None, hint=None, **kwargs):
while len(self._breadcrumbs) > max_breadcrumbs:
self._breadcrumbs.popleft()

def start_transaction(
self, transaction=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs
):
# type: (Optional[Transaction], str, Any) -> Union[Transaction, NoOpSpan]
"""
Start and return a transaction.

Start an existing transaction if given, otherwise create and start a new
transaction with kwargs.

This is the entry point to manual tracing instrumentation.

A tree structure can be built by adding child spans to the transaction,
and child spans to other spans. To start a new child span within the
transaction or any span, call the respective `.start_child()` method.

Every child span must be finished before the transaction is finished,
otherwise the unfinished spans are discarded.

When used as context managers, spans and transactions are automatically
finished at the end of the `with` block. If not using context managers,
call the `.finish()` method.

When the transaction is finished, it will be sent to Sentry with all its
finished child spans.

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Transaction`.
"""
hub = kwargs.pop("hub", None)
client = kwargs.pop("client", None)

configuration_instrumenter = client and client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

custom_sampling_context = kwargs.pop("custom_sampling_context", {})

# if we haven't been given a transaction, make one
if transaction is None:
kwargs.setdefault("hub", hub)
Comment thread
antonpirker marked this conversation as resolved.
transaction = Transaction(**kwargs)

# use traces_sample_rate, traces_sampler, and/or inheritance to make a
# sampling decision
sampling_context = {
"transaction_context": transaction.to_json(),
"parent_sampled": transaction.parent_sampled,
}
sampling_context.update(custom_sampling_context)
transaction._set_initial_sampling_decision(sampling_context=sampling_context)

profile = Profile(transaction, hub=hub)
profile._set_initial_sampling_decision(sampling_context=sampling_context)

# we don't bother to keep spans if we already know we're not going to
# send the transaction
if transaction.sampled:
max_spans = (
client and client.options["_experiments"].get("max_spans")
) or 1000
transaction.init_span_recorder(maxlen=max_spans)

return transaction

def start_span(self, span=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs):
# type: (Optional[Span], str, Any) -> Span
"""
Start a span whose parent is the currently active span or transaction, if any.

The return value is a :py:class:`sentry_sdk.tracing.Span` instance,
typically used as a context manager to start and stop timing in a `with`
block.

Only spans contained in a transaction are sent to Sentry. Most
integrations start a transaction at the appropriate time, for example
for every incoming HTTP request. Use
:py:meth:`sentry_sdk.start_transaction` to start a new transaction when
one is not already in progress.

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Span`.
"""
client = kwargs.get("client", None)

configuration_instrumenter = client and client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

# THIS BLOCK IS DEPRECATED
# TODO: consider removing this in a future release.
# This is for backwards compatibility with releases before
# start_transaction existed, to allow for a smoother transition.
if isinstance(span, Transaction) or "transaction" in kwargs:
deprecation_msg = (
Comment thread
antonpirker marked this conversation as resolved.
"Deprecated: use start_transaction to start transactions and "
"Transaction.start_child to start spans."
)

if isinstance(span, Transaction):
logger.warning(deprecation_msg)
return self.start_transaction(span, **kwargs)

if "transaction" in kwargs:
logger.warning(deprecation_msg)
name = kwargs.pop("transaction")
return self.start_transaction(name=name, **kwargs)

# THIS BLOCK IS DEPRECATED
# We do not pass a span into start_span in our code base, so I deprecate this.
if span is not None:
deprecation_msg = "Deprecated: passing a span into `start_span` is deprecated and will be removed in the future."
logger.warning(deprecation_msg)
return span

kwargs.pop("client")

active_span = self.span
if active_span is not None:
new_child_span = active_span.start_child(**kwargs)
return new_child_span

# If there is already a trace_id in the propagation context, use it.
# This does not need to be done for `start_child` above because it takes
# the trace_id from the parent span.
if "trace_id" not in kwargs:
traceparent = self.get_traceparent()
trace_id = traceparent.split("-")[0] if traceparent else None
if trace_id is not None:
kwargs["trace_id"] = trace_id

return Span(**kwargs)

def continue_trace(self, environ_or_headers, op=None, name=None, source=None):
# type: (Dict[str, Any], Optional[str], Optional[str], Optional[str]) -> Transaction
"""
Sets the propagation context from environment or headers and returns a transaction.
"""
self.generate_propagation_context(environ_or_headers)

transaction = Transaction.continue_from_headers(
normalize_incoming_data(environ_or_headers),
op=op,
name=name,
source=source,
)

return transaction

def start_session(self, *args, **kwargs):
# type: (*Any, **Any) -> None
"""Starts a new session."""
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Add copy buttons to all
 blocks\n(function() {\n function addCopyButtons() {\n document.querySelectorAll('pre code').forEach(function(codeBlock) {\n if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;\n codeBlock.parentElement.setAttribute('data-copy-added', 'true');\n \n var btn = document.createElement('button');\n btn.textContent = 'Copy';\n btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';\n btn.onmouseover = function() { this.style.opacity = '1'; };\n btn.onmouseout = function() { this.style.opacity = '0.7'; };\n btn.onclick = function() {\n navigator.clipboard.writeText(codeBlock.textContent).then(function() {\n btn.textContent = 'Copied!';\n setTimeout(function() { btn.textContent = 'Copy'; }, 1500);\n });\n };\n codeBlock.parentElement.style.position = 'relative';\n codeBlock.parentElement.appendChild(btn);\n });\n }\n \n addCopyButtons();\n \n // Re-run on dynamic content\n var observer = new MutationObserver(addCopyButtons);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Add Copy Buttons to Code Blocks");
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
Skip to content
Merged
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
100 changes: 13 additions & 87 deletions sentry_sdk/hub.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,13 +7,11 @@
from sentry_sdk.consts import INSTRUMENTER
from sentry_sdk.scope import Scope
from sentry_sdk.client import Client
from sentry_sdk.profiler import Profile
from sentry_sdk.tracing import (
NoOpSpan,
Span,
Transaction,
)
from sentry_sdk.tracing_utils import normalize_incoming_data

from sentry_sdk.utils import (
logger,
Expand DownExpand Up@@ -430,54 +428,12 @@ def start_span(self, span=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs):

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Span`.
"""
configuration_instrumenter = self.client and self.client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

# THIS BLOCK IS DEPRECATED
# TODO: consider removing this in a future release.
# This is for backwards compatibility with releases before
# start_transaction existed, to allow for a smoother transition.
if isinstance(span, Transaction) or "transaction" in kwargs:
deprecation_msg = (
"Deprecated: use start_transaction to start transactions and "
"Transaction.start_child to start spans."
)

if isinstance(span, Transaction):
logger.warning(deprecation_msg)
return self.start_transaction(span)

if "transaction" in kwargs:
logger.warning(deprecation_msg)
name = kwargs.pop("transaction")
return self.start_transaction(name=name, **kwargs)

# THIS BLOCK IS DEPRECATED
# We do not pass a span into start_span in our code base, so I deprecate this.
if span is not None:
deprecation_msg = "Deprecated: passing a span into `start_span` is deprecated and will be removed in the future."
logger.warning(deprecation_msg)
return span

kwargs.setdefault("hub", self)

active_span = self.scope.span
if active_span is not None:
new_child_span = active_span.start_child(**kwargs)
return new_child_span
client, scope = self._stack[-1]

# If there is already a trace_id in the propagation context, use it.
# This does not need to be done for `start_child` above because it takes
# the trace_id from the parent span.
if "trace_id" not in kwargs:
traceparent = self.get_traceparent()
trace_id = traceparent.split("-")[0] if traceparent else None
if trace_id is not None:
kwargs["trace_id"] = trace_id
kwargs["hub"] = self
kwargs["client"] = client

return Span(**kwargs)
return scope.start_span(span=span, instrumenter=instrumenter, **kwargs)

def start_transaction(
self, transaction=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs
Expand DownExpand Up@@ -507,55 +463,25 @@ def start_transaction(

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Transaction`.
"""
configuration_instrumenter = self.client and self.client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

custom_sampling_context = kwargs.pop("custom_sampling_context", {})

# if we haven't been given a transaction, make one
if transaction is None:
kwargs.setdefault("hub", self)
transaction = Transaction(**kwargs)

# use traces_sample_rate, traces_sampler, and/or inheritance to make a
# sampling decision
sampling_context = {
"transaction_context": transaction.to_json(),
"parent_sampled": transaction.parent_sampled,
}
sampling_context.update(custom_sampling_context)
transaction._set_initial_sampling_decision(sampling_context=sampling_context)

profile = Profile(transaction, hub=self)
profile._set_initial_sampling_decision(sampling_context=sampling_context)
client, scope = self._stack[-1]

# we don't bother to keep spans if we already know we're not going to
# send the transaction
if transaction.sampled:
max_spans = (
self.client and self.client.options["_experiments"].get("max_spans")
) or 1000
transaction.init_span_recorder(maxlen=max_spans)
kwargs["hub"] = self
kwargs["client"] = client

return transaction
return scope.start_transaction(
transaction=transaction, instrumenter=instrumenter, **kwargs
)

def continue_trace(self, environ_or_headers, op=None, name=None, source=None):
# type: (Dict[str, Any], Optional[str], Optional[str], Optional[str]) -> Transaction
"""
Sets the propagation context from environment or headers and returns a transaction.
"""
with self.configure_scope() as scope:
scope.generate_propagation_context(environ_or_headers)
scope = self._stack[-1][1]

transaction = Transaction.continue_from_headers(
normalize_incoming_data(environ_or_headers),
op=op,
name=name,
source=source,
return scope.continue_trace(
environ_or_headers=environ_or_headers, op=op, name=name, source=source
)
return transaction

@overload
def push_scope(
Expand Down
158 changes: 154 additions & 4 deletions sentry_sdk/scope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,8 +6,9 @@

from sentry_sdk.attachments import Attachment
from sentry_sdk._compat import datetime_utcnow
from sentry_sdk.consts import FALSE_VALUES
from sentry_sdk.consts import FALSE_VALUES, INSTRUMENTER
from sentry_sdk._functools import wraps
from sentry_sdk.profiler import Profile
from sentry_sdk.session import Session
from sentry_sdk.tracing_utils import (
Baggage,
Expand All@@ -18,6 +19,8 @@
from sentry_sdk.tracing import (
BAGGAGE_HEADER_NAME,
SENTRY_TRACE_HEADER_NAME,
NoOpSpan,
Span,
Transaction,
)
from sentry_sdk._types import TYPE_CHECKING
Expand All@@ -34,6 +37,7 @@
from typing import Optional
from typing import Tuple
from typing import TypeVar
from typing import Union

from sentry_sdk._types import (
Breadcrumb,
Expand All@@ -46,9 +50,6 @@
Type,
)

from sentry_sdk.profiler import Profile
from sentry_sdk.tracing import Span

F = TypeVar("F", bound=Callable[..., Any])
T = TypeVar("T")

Expand DownExpand Up@@ -636,6 +637,155 @@ def add_breadcrumb(self, crumb=None, hint=None, **kwargs):
while len(self._breadcrumbs) > max_breadcrumbs:
self._breadcrumbs.popleft()

def start_transaction(
self, transaction=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs
):
# type: (Optional[Transaction], str, Any) -> Union[Transaction, NoOpSpan]
"""
Start and return a transaction.

Start an existing transaction if given, otherwise create and start a new
transaction with kwargs.

This is the entry point to manual tracing instrumentation.

A tree structure can be built by adding child spans to the transaction,
and child spans to other spans. To start a new child span within the
transaction or any span, call the respective `.start_child()` method.

Every child span must be finished before the transaction is finished,
otherwise the unfinished spans are discarded.

When used as context managers, spans and transactions are automatically
finished at the end of the `with` block. If not using context managers,
call the `.finish()` method.

When the transaction is finished, it will be sent to Sentry with all its
finished child spans.

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Transaction`.
"""
hub = kwargs.pop("hub", None)
client = kwargs.pop("client", None)

configuration_instrumenter = client and client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

custom_sampling_context = kwargs.pop("custom_sampling_context", {})

# if we haven't been given a transaction, make one
if transaction is None:
kwargs.setdefault("hub", hub)
Comment thread
antonpirker marked this conversation as resolved.
transaction = Transaction(**kwargs)

# use traces_sample_rate, traces_sampler, and/or inheritance to make a
# sampling decision
sampling_context = {
"transaction_context": transaction.to_json(),
"parent_sampled": transaction.parent_sampled,
}
sampling_context.update(custom_sampling_context)
transaction._set_initial_sampling_decision(sampling_context=sampling_context)

profile = Profile(transaction, hub=hub)
profile._set_initial_sampling_decision(sampling_context=sampling_context)

# we don't bother to keep spans if we already know we're not going to
# send the transaction
if transaction.sampled:
max_spans = (
client and client.options["_experiments"].get("max_spans")
) or 1000
transaction.init_span_recorder(maxlen=max_spans)

return transaction

def start_span(self, span=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs):
# type: (Optional[Span], str, Any) -> Span
"""
Start a span whose parent is the currently active span or transaction, if any.

The return value is a :py:class:`sentry_sdk.tracing.Span` instance,
typically used as a context manager to start and stop timing in a `with`
block.

Only spans contained in a transaction are sent to Sentry. Most
integrations start a transaction at the appropriate time, for example
for every incoming HTTP request. Use
:py:meth:`sentry_sdk.start_transaction` to start a new transaction when
one is not already in progress.

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Span`.
"""
client = kwargs.get("client", None)

configuration_instrumenter = client and client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

# THIS BLOCK IS DEPRECATED
# TODO: consider removing this in a future release.
# This is for backwards compatibility with releases before
# start_transaction existed, to allow for a smoother transition.
if isinstance(span, Transaction) or "transaction" in kwargs:
deprecation_msg = (
Comment thread
antonpirker marked this conversation as resolved.
"Deprecated: use start_transaction to start transactions and "
"Transaction.start_child to start spans."
)

if isinstance(span, Transaction):
logger.warning(deprecation_msg)
return self.start_transaction(span, **kwargs)

if "transaction" in kwargs:
logger.warning(deprecation_msg)
name = kwargs.pop("transaction")
return self.start_transaction(name=name, **kwargs)

# THIS BLOCK IS DEPRECATED
# We do not pass a span into start_span in our code base, so I deprecate this.
if span is not None:
deprecation_msg = "Deprecated: passing a span into `start_span` is deprecated and will be removed in the future."
logger.warning(deprecation_msg)
return span

kwargs.pop("client")

active_span = self.span
if active_span is not None:
new_child_span = active_span.start_child(**kwargs)
return new_child_span

# If there is already a trace_id in the propagation context, use it.
# This does not need to be done for `start_child` above because it takes
# the trace_id from the parent span.
if "trace_id" not in kwargs:
traceparent = self.get_traceparent()
trace_id = traceparent.split("-")[0] if traceparent else None
if trace_id is not None:
kwargs["trace_id"] = trace_id

return Span(**kwargs)

def continue_trace(self, environ_or_headers, op=None, name=None, source=None):
# type: (Dict[str, Any], Optional[str], Optional[str], Optional[str]) -> Transaction
"""
Sets the propagation context from environment or headers and returns a transaction.
"""
self.generate_propagation_context(environ_or_headers)

transaction = Transaction.continue_from_headers(
normalize_incoming_data(environ_or_headers),
op=op,
name=name,
source=source,
)

return transaction

def start_session(self, *args, **kwargs):
# type: (*Any, **Any) -> None
"""Starts a new session."""
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Force GitHub README to respect dark mode\n(function() {\n var style = document.createElement('style');\n style.textContent = '\n .markdown-body {\n color-scheme: dark light;\n }\n .markdown-body pre { background: #161b22 !important; }\n .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; }\n .markdown-body table th, .markdown-body table td { border-color: #30363d !important; }\n .markdown-body img { background: #0d1117; }\n .markdown-body blockquote { border-left-color: #8b949e; }\n .markdown-body hr { border-color: #30363d; }\n ';\n document.head.appendChild(style);\n})();", "GitHub Dark Mode README Fix"); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
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
100 changes: 13 additions & 87 deletions sentry_sdk/hub.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,13 +7,11 @@
from sentry_sdk.consts import INSTRUMENTER
from sentry_sdk.scope import Scope
from sentry_sdk.client import Client
from sentry_sdk.profiler import Profile
from sentry_sdk.tracing import (
NoOpSpan,
Span,
Transaction,
)
from sentry_sdk.tracing_utils import normalize_incoming_data

from sentry_sdk.utils import (
logger,
Expand DownExpand Up@@ -430,54 +428,12 @@ def start_span(self, span=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs):

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Span`.
"""
configuration_instrumenter = self.client and self.client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

# THIS BLOCK IS DEPRECATED
# TODO: consider removing this in a future release.
# This is for backwards compatibility with releases before
# start_transaction existed, to allow for a smoother transition.
if isinstance(span, Transaction) or "transaction" in kwargs:
deprecation_msg = (
"Deprecated: use start_transaction to start transactions and "
"Transaction.start_child to start spans."
)

if isinstance(span, Transaction):
logger.warning(deprecation_msg)
return self.start_transaction(span)

if "transaction" in kwargs:
logger.warning(deprecation_msg)
name = kwargs.pop("transaction")
return self.start_transaction(name=name, **kwargs)

# THIS BLOCK IS DEPRECATED
# We do not pass a span into start_span in our code base, so I deprecate this.
if span is not None:
deprecation_msg = "Deprecated: passing a span into `start_span` is deprecated and will be removed in the future."
logger.warning(deprecation_msg)
return span

kwargs.setdefault("hub", self)

active_span = self.scope.span
if active_span is not None:
new_child_span = active_span.start_child(**kwargs)
return new_child_span
client, scope = self._stack[-1]

# If there is already a trace_id in the propagation context, use it.
# This does not need to be done for `start_child` above because it takes
# the trace_id from the parent span.
if "trace_id" not in kwargs:
traceparent = self.get_traceparent()
trace_id = traceparent.split("-")[0] if traceparent else None
if trace_id is not None:
kwargs["trace_id"] = trace_id
kwargs["hub"] = self
kwargs["client"] = client

return Span(**kwargs)
return scope.start_span(span=span, instrumenter=instrumenter, **kwargs)

def start_transaction(
self, transaction=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs
Expand DownExpand Up@@ -507,55 +463,25 @@ def start_transaction(

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Transaction`.
"""
configuration_instrumenter = self.client and self.client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

custom_sampling_context = kwargs.pop("custom_sampling_context", {})

# if we haven't been given a transaction, make one
if transaction is None:
kwargs.setdefault("hub", self)
transaction = Transaction(**kwargs)

# use traces_sample_rate, traces_sampler, and/or inheritance to make a
# sampling decision
sampling_context = {
"transaction_context": transaction.to_json(),
"parent_sampled": transaction.parent_sampled,
}
sampling_context.update(custom_sampling_context)
transaction._set_initial_sampling_decision(sampling_context=sampling_context)

profile = Profile(transaction, hub=self)
profile._set_initial_sampling_decision(sampling_context=sampling_context)
client, scope = self._stack[-1]

# we don't bother to keep spans if we already know we're not going to
# send the transaction
if transaction.sampled:
max_spans = (
self.client and self.client.options["_experiments"].get("max_spans")
) or 1000
transaction.init_span_recorder(maxlen=max_spans)
kwargs["hub"] = self
kwargs["client"] = client

return transaction
return scope.start_transaction(
transaction=transaction, instrumenter=instrumenter, **kwargs
)

def continue_trace(self, environ_or_headers, op=None, name=None, source=None):
# type: (Dict[str, Any], Optional[str], Optional[str], Optional[str]) -> Transaction
"""
Sets the propagation context from environment or headers and returns a transaction.
"""
with self.configure_scope() as scope:
scope.generate_propagation_context(environ_or_headers)
scope = self._stack[-1][1]

transaction = Transaction.continue_from_headers(
normalize_incoming_data(environ_or_headers),
op=op,
name=name,
source=source,
return scope.continue_trace(
environ_or_headers=environ_or_headers, op=op, name=name, source=source
)
return transaction

@overload
def push_scope(
Expand Down
158 changes: 154 additions & 4 deletions sentry_sdk/scope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,8 +6,9 @@

from sentry_sdk.attachments import Attachment
from sentry_sdk._compat import datetime_utcnow
from sentry_sdk.consts import FALSE_VALUES
from sentry_sdk.consts import FALSE_VALUES, INSTRUMENTER
from sentry_sdk._functools import wraps
from sentry_sdk.profiler import Profile
from sentry_sdk.session import Session
from sentry_sdk.tracing_utils import (
Baggage,
Expand All@@ -18,6 +19,8 @@
from sentry_sdk.tracing import (
BAGGAGE_HEADER_NAME,
SENTRY_TRACE_HEADER_NAME,
NoOpSpan,
Span,
Transaction,
)
from sentry_sdk._types import TYPE_CHECKING
Expand All@@ -34,6 +37,7 @@
from typing import Optional
from typing import Tuple
from typing import TypeVar
from typing import Union

from sentry_sdk._types import (
Breadcrumb,
Expand All@@ -46,9 +50,6 @@
Type,
)

from sentry_sdk.profiler import Profile
from sentry_sdk.tracing import Span

F = TypeVar("F", bound=Callable[..., Any])
T = TypeVar("T")

Expand DownExpand Up@@ -636,6 +637,155 @@ def add_breadcrumb(self, crumb=None, hint=None, **kwargs):
while len(self._breadcrumbs) > max_breadcrumbs:
self._breadcrumbs.popleft()

def start_transaction(
self, transaction=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs
):
# type: (Optional[Transaction], str, Any) -> Union[Transaction, NoOpSpan]
"""
Start and return a transaction.

Start an existing transaction if given, otherwise create and start a new
transaction with kwargs.

This is the entry point to manual tracing instrumentation.

A tree structure can be built by adding child spans to the transaction,
and child spans to other spans. To start a new child span within the
transaction or any span, call the respective `.start_child()` method.

Every child span must be finished before the transaction is finished,
otherwise the unfinished spans are discarded.

When used as context managers, spans and transactions are automatically
finished at the end of the `with` block. If not using context managers,
call the `.finish()` method.

When the transaction is finished, it will be sent to Sentry with all its
finished child spans.

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Transaction`.
"""
hub = kwargs.pop("hub", None)
client = kwargs.pop("client", None)

configuration_instrumenter = client and client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

custom_sampling_context = kwargs.pop("custom_sampling_context", {})

# if we haven't been given a transaction, make one
if transaction is None:
kwargs.setdefault("hub", hub)
Comment thread
antonpirker marked this conversation as resolved.
transaction = Transaction(**kwargs)

# use traces_sample_rate, traces_sampler, and/or inheritance to make a
# sampling decision
sampling_context = {
"transaction_context": transaction.to_json(),
"parent_sampled": transaction.parent_sampled,
}
sampling_context.update(custom_sampling_context)
transaction._set_initial_sampling_decision(sampling_context=sampling_context)

profile = Profile(transaction, hub=hub)
profile._set_initial_sampling_decision(sampling_context=sampling_context)

# we don't bother to keep spans if we already know we're not going to
# send the transaction
if transaction.sampled:
max_spans = (
client and client.options["_experiments"].get("max_spans")
) or 1000
transaction.init_span_recorder(maxlen=max_spans)

return transaction

def start_span(self, span=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs):
# type: (Optional[Span], str, Any) -> Span
"""
Start a span whose parent is the currently active span or transaction, if any.

The return value is a :py:class:`sentry_sdk.tracing.Span` instance,
typically used as a context manager to start and stop timing in a `with`
block.

Only spans contained in a transaction are sent to Sentry. Most
integrations start a transaction at the appropriate time, for example
for every incoming HTTP request. Use
:py:meth:`sentry_sdk.start_transaction` to start a new transaction when
one is not already in progress.

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Span`.
"""
client = kwargs.get("client", None)

configuration_instrumenter = client and client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

# THIS BLOCK IS DEPRECATED
# TODO: consider removing this in a future release.
# This is for backwards compatibility with releases before
# start_transaction existed, to allow for a smoother transition.
if isinstance(span, Transaction) or "transaction" in kwargs:
deprecation_msg = (
Comment thread
antonpirker marked this conversation as resolved.
"Deprecated: use start_transaction to start transactions and "
"Transaction.start_child to start spans."
)

if isinstance(span, Transaction):
logger.warning(deprecation_msg)
return self.start_transaction(span, **kwargs)

if "transaction" in kwargs:
logger.warning(deprecation_msg)
name = kwargs.pop("transaction")
return self.start_transaction(name=name, **kwargs)

# THIS BLOCK IS DEPRECATED
# We do not pass a span into start_span in our code base, so I deprecate this.
if span is not None:
deprecation_msg = "Deprecated: passing a span into `start_span` is deprecated and will be removed in the future."
logger.warning(deprecation_msg)
return span

kwargs.pop("client")

active_span = self.span
if active_span is not None:
new_child_span = active_span.start_child(**kwargs)
return new_child_span

# If there is already a trace_id in the propagation context, use it.
# This does not need to be done for `start_child` above because it takes
# the trace_id from the parent span.
if "trace_id" not in kwargs:
traceparent = self.get_traceparent()
trace_id = traceparent.split("-")[0] if traceparent else None
if trace_id is not None:
kwargs["trace_id"] = trace_id

return Span(**kwargs)

def continue_trace(self, environ_or_headers, op=None, name=None, source=None):
# type: (Dict[str, Any], Optional[str], Optional[str], Optional[str]) -> Transaction
"""
Sets the propagation context from environment or headers and returns a transaction.
"""
self.generate_propagation_context(environ_or_headers)

transaction = Transaction.continue_from_headers(
normalize_incoming_data(environ_or_headers),
op=op,
name=name,
source=source,
)

return transaction

def start_session(self, *args, **kwargs):
# type: (*Any, **Any) -> None
"""Starts a new session."""
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Highlight search terms from Google/DuckDuckGo/Bing referrer\n(function() {\n var ref = document.referrer;\n var terms = [];\n \n if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) {\n var url = new URL(ref);\n var q = url.searchParams.get('q') || url.searchParams.get('p');\n if (q) {\n terms = q.split(/\\s+/).filter(function(t) { return t.length > 2; });\n }\n }\n \n if (terms.length === 0) return;\n \n var style = document.createElement('style');\n style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }';\n document.head.appendChild(style);\n \n function highlight(node) {\n if (node.nodeType === 3) { // text node\n var text = node.textContent;\n var found = false;\n terms.forEach(function(term) {\n var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\') + ')', 'gi');\n if (regex.test(text)) {\n found = true;\n var frag = document.createDocumentFragment();\n var parts = text.split(regex);\n parts.forEach(function(part, i) {\n if (i % 2 === 0) {\n frag.appendChild(document.createTextNode(part));\n } else {\n var span = document.createElement('span');\n span.className = 'userscript-highlight';\n span.textContent = part;\n frag.appendChild(span);\n }\n });\n node.parentNode.replaceChild(frag, node);\n }\n });\n } else if (node.nodeType === 1 && node.childNodes) { // element\n var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT'];\n if (!skipTags.includes(node.tagName)) {\n Array.from(node.childNodes).forEach(highlight);\n }\n }\n }\n \n highlight(document.body);\n \n // Re-highlight on dynamic content\n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1 || node.nodeType === 3) highlight(node);\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Highlight Search Terms"); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
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
100 changes: 13 additions & 87 deletions sentry_sdk/hub.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,13 +7,11 @@
from sentry_sdk.consts import INSTRUMENTER
from sentry_sdk.scope import Scope
from sentry_sdk.client import Client
from sentry_sdk.profiler import Profile
from sentry_sdk.tracing import (
NoOpSpan,
Span,
Transaction,
)
from sentry_sdk.tracing_utils import normalize_incoming_data

from sentry_sdk.utils import (
logger,
Expand DownExpand Up@@ -430,54 +428,12 @@ def start_span(self, span=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs):

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Span`.
"""
configuration_instrumenter = self.client and self.client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

# THIS BLOCK IS DEPRECATED
# TODO: consider removing this in a future release.
# This is for backwards compatibility with releases before
# start_transaction existed, to allow for a smoother transition.
if isinstance(span, Transaction) or "transaction" in kwargs:
deprecation_msg = (
"Deprecated: use start_transaction to start transactions and "
"Transaction.start_child to start spans."
)

if isinstance(span, Transaction):
logger.warning(deprecation_msg)
return self.start_transaction(span)

if "transaction" in kwargs:
logger.warning(deprecation_msg)
name = kwargs.pop("transaction")
return self.start_transaction(name=name, **kwargs)

# THIS BLOCK IS DEPRECATED
# We do not pass a span into start_span in our code base, so I deprecate this.
if span is not None:
deprecation_msg = "Deprecated: passing a span into `start_span` is deprecated and will be removed in the future."
logger.warning(deprecation_msg)
return span

kwargs.setdefault("hub", self)

active_span = self.scope.span
if active_span is not None:
new_child_span = active_span.start_child(**kwargs)
return new_child_span
client, scope = self._stack[-1]

# If there is already a trace_id in the propagation context, use it.
# This does not need to be done for `start_child` above because it takes
# the trace_id from the parent span.
if "trace_id" not in kwargs:
traceparent = self.get_traceparent()
trace_id = traceparent.split("-")[0] if traceparent else None
if trace_id is not None:
kwargs["trace_id"] = trace_id
kwargs["hub"] = self
kwargs["client"] = client

return Span(**kwargs)
return scope.start_span(span=span, instrumenter=instrumenter, **kwargs)

def start_transaction(
self, transaction=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs
Expand DownExpand Up@@ -507,55 +463,25 @@ def start_transaction(

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Transaction`.
"""
configuration_instrumenter = self.client and self.client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

custom_sampling_context = kwargs.pop("custom_sampling_context", {})

# if we haven't been given a transaction, make one
if transaction is None:
kwargs.setdefault("hub", self)
transaction = Transaction(**kwargs)

# use traces_sample_rate, traces_sampler, and/or inheritance to make a
# sampling decision
sampling_context = {
"transaction_context": transaction.to_json(),
"parent_sampled": transaction.parent_sampled,
}
sampling_context.update(custom_sampling_context)
transaction._set_initial_sampling_decision(sampling_context=sampling_context)

profile = Profile(transaction, hub=self)
profile._set_initial_sampling_decision(sampling_context=sampling_context)
client, scope = self._stack[-1]

# we don't bother to keep spans if we already know we're not going to
# send the transaction
if transaction.sampled:
max_spans = (
self.client and self.client.options["_experiments"].get("max_spans")
) or 1000
transaction.init_span_recorder(maxlen=max_spans)
kwargs["hub"] = self
kwargs["client"] = client

return transaction
return scope.start_transaction(
transaction=transaction, instrumenter=instrumenter, **kwargs
)

def continue_trace(self, environ_or_headers, op=None, name=None, source=None):
# type: (Dict[str, Any], Optional[str], Optional[str], Optional[str]) -> Transaction
"""
Sets the propagation context from environment or headers and returns a transaction.
"""
with self.configure_scope() as scope:
scope.generate_propagation_context(environ_or_headers)
scope = self._stack[-1][1]

transaction = Transaction.continue_from_headers(
normalize_incoming_data(environ_or_headers),
op=op,
name=name,
source=source,
return scope.continue_trace(
environ_or_headers=environ_or_headers, op=op, name=name, source=source
)
return transaction

@overload
def push_scope(
Expand Down
158 changes: 154 additions & 4 deletions sentry_sdk/scope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,8 +6,9 @@

from sentry_sdk.attachments import Attachment
from sentry_sdk._compat import datetime_utcnow
from sentry_sdk.consts import FALSE_VALUES
from sentry_sdk.consts import FALSE_VALUES, INSTRUMENTER
from sentry_sdk._functools import wraps
from sentry_sdk.profiler import Profile
from sentry_sdk.session import Session
from sentry_sdk.tracing_utils import (
Baggage,
Expand All@@ -18,6 +19,8 @@
from sentry_sdk.tracing import (
BAGGAGE_HEADER_NAME,
SENTRY_TRACE_HEADER_NAME,
NoOpSpan,
Span,
Transaction,
)
from sentry_sdk._types import TYPE_CHECKING
Expand All@@ -34,6 +37,7 @@
from typing import Optional
from typing import Tuple
from typing import TypeVar
from typing import Union

from sentry_sdk._types import (
Breadcrumb,
Expand All@@ -46,9 +50,6 @@
Type,
)

from sentry_sdk.profiler import Profile
from sentry_sdk.tracing import Span

F = TypeVar("F", bound=Callable[..., Any])
T = TypeVar("T")

Expand DownExpand Up@@ -636,6 +637,155 @@ def add_breadcrumb(self, crumb=None, hint=None, **kwargs):
while len(self._breadcrumbs) > max_breadcrumbs:
self._breadcrumbs.popleft()

def start_transaction(
self, transaction=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs
):
# type: (Optional[Transaction], str, Any) -> Union[Transaction, NoOpSpan]
"""
Start and return a transaction.

Start an existing transaction if given, otherwise create and start a new
transaction with kwargs.

This is the entry point to manual tracing instrumentation.

A tree structure can be built by adding child spans to the transaction,
and child spans to other spans. To start a new child span within the
transaction or any span, call the respective `.start_child()` method.

Every child span must be finished before the transaction is finished,
otherwise the unfinished spans are discarded.

When used as context managers, spans and transactions are automatically
finished at the end of the `with` block. If not using context managers,
call the `.finish()` method.

When the transaction is finished, it will be sent to Sentry with all its
finished child spans.

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Transaction`.
"""
hub = kwargs.pop("hub", None)
client = kwargs.pop("client", None)

configuration_instrumenter = client and client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

custom_sampling_context = kwargs.pop("custom_sampling_context", {})

# if we haven't been given a transaction, make one
if transaction is None:
kwargs.setdefault("hub", hub)
Comment thread
antonpirker marked this conversation as resolved.
transaction = Transaction(**kwargs)

# use traces_sample_rate, traces_sampler, and/or inheritance to make a
# sampling decision
sampling_context = {
"transaction_context": transaction.to_json(),
"parent_sampled": transaction.parent_sampled,
}
sampling_context.update(custom_sampling_context)
transaction._set_initial_sampling_decision(sampling_context=sampling_context)

profile = Profile(transaction, hub=hub)
profile._set_initial_sampling_decision(sampling_context=sampling_context)

# we don't bother to keep spans if we already know we're not going to
# send the transaction
if transaction.sampled:
max_spans = (
client and client.options["_experiments"].get("max_spans")
) or 1000
transaction.init_span_recorder(maxlen=max_spans)

return transaction

def start_span(self, span=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs):
# type: (Optional[Span], str, Any) -> Span
"""
Start a span whose parent is the currently active span or transaction, if any.

The return value is a :py:class:`sentry_sdk.tracing.Span` instance,
typically used as a context manager to start and stop timing in a `with`
block.

Only spans contained in a transaction are sent to Sentry. Most
integrations start a transaction at the appropriate time, for example
for every incoming HTTP request. Use
:py:meth:`sentry_sdk.start_transaction` to start a new transaction when
one is not already in progress.

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Span`.
"""
client = kwargs.get("client", None)

configuration_instrumenter = client and client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

# THIS BLOCK IS DEPRECATED
# TODO: consider removing this in a future release.
# This is for backwards compatibility with releases before
# start_transaction existed, to allow for a smoother transition.
if isinstance(span, Transaction) or "transaction" in kwargs:
deprecation_msg = (
Comment thread
antonpirker marked this conversation as resolved.
"Deprecated: use start_transaction to start transactions and "
"Transaction.start_child to start spans."
)

if isinstance(span, Transaction):
logger.warning(deprecation_msg)
return self.start_transaction(span, **kwargs)

if "transaction" in kwargs:
logger.warning(deprecation_msg)
name = kwargs.pop("transaction")
return self.start_transaction(name=name, **kwargs)

# THIS BLOCK IS DEPRECATED
# We do not pass a span into start_span in our code base, so I deprecate this.
if span is not None:
deprecation_msg = "Deprecated: passing a span into `start_span` is deprecated and will be removed in the future."
logger.warning(deprecation_msg)
return span

kwargs.pop("client")

active_span = self.span
if active_span is not None:
new_child_span = active_span.start_child(**kwargs)
return new_child_span

# If there is already a trace_id in the propagation context, use it.
# This does not need to be done for `start_child` above because it takes
# the trace_id from the parent span.
if "trace_id" not in kwargs:
traceparent = self.get_traceparent()
trace_id = traceparent.split("-")[0] if traceparent else None
if trace_id is not None:
kwargs["trace_id"] = trace_id

return Span(**kwargs)

def continue_trace(self, environ_or_headers, op=None, name=None, source=None):
# type: (Dict[str, Any], Optional[str], Optional[str], Optional[str]) -> Transaction
"""
Sets the propagation context from environment or headers and returns a transaction.
"""
self.generate_propagation_context(environ_or_headers)

transaction = Transaction.continue_from_headers(
normalize_incoming_data(environ_or_headers),
op=op,
name=name,
source=source,
)

return transaction

def start_session(self, *args, **kwargs):
# type: (*Any, **Any) -> None
"""Starts a new session."""
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Strip utm_, fbclid, gclid, etc. from all links on page\n(function() {\n var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content',\n 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid',\n 'ref', 'ref_src', 'source', 'medium', 'campaign'];\n \n function cleanUrl(url) {\n try {\n var u = new URL(url, window.location.origin);\n var changed = false;\n trackingParams.forEach(function(p) {\n if (u.searchParams.has(p)) {\n u.searchParams.delete(p);\n changed = true;\n }\n });\n return changed ? u.toString() : url;\n } catch (e) {\n return url;\n }\n }\n \n function cleanLinks() {\n document.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n \n cleanLinks();\n \n var observer = new MutationObserver(function(mutations) {\n mutations.forEach(function(m) {\n m.addedNodes.forEach(function(node) {\n if (node.nodeType === 1) {\n if (node.tagName === 'A') cleanLinks();\n node.querySelectorAll('a[href]').forEach(function(a) {\n var clean = cleanUrl(a.href);\n if (clean !== a.href) a.href = clean;\n });\n }\n });\n });\n });\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "Remove Tracking Parameters from Links"); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + '
Skip to content
Merged
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
100 changes: 13 additions & 87 deletions sentry_sdk/hub.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,13 +7,11 @@
from sentry_sdk.consts import INSTRUMENTER
from sentry_sdk.scope import Scope
from sentry_sdk.client import Client
from sentry_sdk.profiler import Profile
from sentry_sdk.tracing import (
NoOpSpan,
Span,
Transaction,
)
from sentry_sdk.tracing_utils import normalize_incoming_data

from sentry_sdk.utils import (
logger,
Expand DownExpand Up@@ -430,54 +428,12 @@ def start_span(self, span=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs):

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Span`.
"""
configuration_instrumenter = self.client and self.client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

# THIS BLOCK IS DEPRECATED
# TODO: consider removing this in a future release.
# This is for backwards compatibility with releases before
# start_transaction existed, to allow for a smoother transition.
if isinstance(span, Transaction) or "transaction" in kwargs:
deprecation_msg = (
"Deprecated: use start_transaction to start transactions and "
"Transaction.start_child to start spans."
)

if isinstance(span, Transaction):
logger.warning(deprecation_msg)
return self.start_transaction(span)

if "transaction" in kwargs:
logger.warning(deprecation_msg)
name = kwargs.pop("transaction")
return self.start_transaction(name=name, **kwargs)

# THIS BLOCK IS DEPRECATED
# We do not pass a span into start_span in our code base, so I deprecate this.
if span is not None:
deprecation_msg = "Deprecated: passing a span into `start_span` is deprecated and will be removed in the future."
logger.warning(deprecation_msg)
return span

kwargs.setdefault("hub", self)

active_span = self.scope.span
if active_span is not None:
new_child_span = active_span.start_child(**kwargs)
return new_child_span
client, scope = self._stack[-1]

# If there is already a trace_id in the propagation context, use it.
# This does not need to be done for `start_child` above because it takes
# the trace_id from the parent span.
if "trace_id" not in kwargs:
traceparent = self.get_traceparent()
trace_id = traceparent.split("-")[0] if traceparent else None
if trace_id is not None:
kwargs["trace_id"] = trace_id
kwargs["hub"] = self
kwargs["client"] = client

return Span(**kwargs)
return scope.start_span(span=span, instrumenter=instrumenter, **kwargs)

def start_transaction(
self, transaction=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs
Expand DownExpand Up@@ -507,55 +463,25 @@ def start_transaction(

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Transaction`.
"""
configuration_instrumenter = self.client and self.client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

custom_sampling_context = kwargs.pop("custom_sampling_context", {})

# if we haven't been given a transaction, make one
if transaction is None:
kwargs.setdefault("hub", self)
transaction = Transaction(**kwargs)

# use traces_sample_rate, traces_sampler, and/or inheritance to make a
# sampling decision
sampling_context = {
"transaction_context": transaction.to_json(),
"parent_sampled": transaction.parent_sampled,
}
sampling_context.update(custom_sampling_context)
transaction._set_initial_sampling_decision(sampling_context=sampling_context)

profile = Profile(transaction, hub=self)
profile._set_initial_sampling_decision(sampling_context=sampling_context)
client, scope = self._stack[-1]

# we don't bother to keep spans if we already know we're not going to
# send the transaction
if transaction.sampled:
max_spans = (
self.client and self.client.options["_experiments"].get("max_spans")
) or 1000
transaction.init_span_recorder(maxlen=max_spans)
kwargs["hub"] = self
kwargs["client"] = client

return transaction
return scope.start_transaction(
transaction=transaction, instrumenter=instrumenter, **kwargs
)

def continue_trace(self, environ_or_headers, op=None, name=None, source=None):
# type: (Dict[str, Any], Optional[str], Optional[str], Optional[str]) -> Transaction
"""
Sets the propagation context from environment or headers and returns a transaction.
"""
with self.configure_scope() as scope:
scope.generate_propagation_context(environ_or_headers)
scope = self._stack[-1][1]

transaction = Transaction.continue_from_headers(
normalize_incoming_data(environ_or_headers),
op=op,
name=name,
source=source,
return scope.continue_trace(
environ_or_headers=environ_or_headers, op=op, name=name, source=source
)
return transaction

@overload
def push_scope(
Expand Down
158 changes: 154 additions & 4 deletions sentry_sdk/scope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,8 +6,9 @@

from sentry_sdk.attachments import Attachment
from sentry_sdk._compat import datetime_utcnow
from sentry_sdk.consts import FALSE_VALUES
from sentry_sdk.consts import FALSE_VALUES, INSTRUMENTER
from sentry_sdk._functools import wraps
from sentry_sdk.profiler import Profile
from sentry_sdk.session import Session
from sentry_sdk.tracing_utils import (
Baggage,
Expand All@@ -18,6 +19,8 @@
from sentry_sdk.tracing import (
BAGGAGE_HEADER_NAME,
SENTRY_TRACE_HEADER_NAME,
NoOpSpan,
Span,
Transaction,
)
from sentry_sdk._types import TYPE_CHECKING
Expand All@@ -34,6 +37,7 @@
from typing import Optional
from typing import Tuple
from typing import TypeVar
from typing import Union

from sentry_sdk._types import (
Breadcrumb,
Expand All@@ -46,9 +50,6 @@
Type,
)

from sentry_sdk.profiler import Profile
from sentry_sdk.tracing import Span

F = TypeVar("F", bound=Callable[..., Any])
T = TypeVar("T")

Expand DownExpand Up@@ -636,6 +637,155 @@ def add_breadcrumb(self, crumb=None, hint=None, **kwargs):
while len(self._breadcrumbs) > max_breadcrumbs:
self._breadcrumbs.popleft()

def start_transaction(
self, transaction=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs
):
# type: (Optional[Transaction], str, Any) -> Union[Transaction, NoOpSpan]
"""
Start and return a transaction.

Start an existing transaction if given, otherwise create and start a new
transaction with kwargs.

This is the entry point to manual tracing instrumentation.

A tree structure can be built by adding child spans to the transaction,
and child spans to other spans. To start a new child span within the
transaction or any span, call the respective `.start_child()` method.

Every child span must be finished before the transaction is finished,
otherwise the unfinished spans are discarded.

When used as context managers, spans and transactions are automatically
finished at the end of the `with` block. If not using context managers,
call the `.finish()` method.

When the transaction is finished, it will be sent to Sentry with all its
finished child spans.

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Transaction`.
"""
hub = kwargs.pop("hub", None)
client = kwargs.pop("client", None)

configuration_instrumenter = client and client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

custom_sampling_context = kwargs.pop("custom_sampling_context", {})

# if we haven't been given a transaction, make one
if transaction is None:
kwargs.setdefault("hub", hub)
Comment thread
antonpirker marked this conversation as resolved.
transaction = Transaction(**kwargs)

# use traces_sample_rate, traces_sampler, and/or inheritance to make a
# sampling decision
sampling_context = {
"transaction_context": transaction.to_json(),
"parent_sampled": transaction.parent_sampled,
}
sampling_context.update(custom_sampling_context)
transaction._set_initial_sampling_decision(sampling_context=sampling_context)

profile = Profile(transaction, hub=hub)
profile._set_initial_sampling_decision(sampling_context=sampling_context)

# we don't bother to keep spans if we already know we're not going to
# send the transaction
if transaction.sampled:
max_spans = (
client and client.options["_experiments"].get("max_spans")
) or 1000
transaction.init_span_recorder(maxlen=max_spans)

return transaction

def start_span(self, span=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs):
# type: (Optional[Span], str, Any) -> Span
"""
Start a span whose parent is the currently active span or transaction, if any.

The return value is a :py:class:`sentry_sdk.tracing.Span` instance,
typically used as a context manager to start and stop timing in a `with`
block.

Only spans contained in a transaction are sent to Sentry. Most
integrations start a transaction at the appropriate time, for example
for every incoming HTTP request. Use
:py:meth:`sentry_sdk.start_transaction` to start a new transaction when
one is not already in progress.

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Span`.
"""
client = kwargs.get("client", None)

configuration_instrumenter = client and client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

# THIS BLOCK IS DEPRECATED
# TODO: consider removing this in a future release.
# This is for backwards compatibility with releases before
# start_transaction existed, to allow for a smoother transition.
if isinstance(span, Transaction) or "transaction" in kwargs:
deprecation_msg = (
Comment thread
antonpirker marked this conversation as resolved.
"Deprecated: use start_transaction to start transactions and "
"Transaction.start_child to start spans."
)

if isinstance(span, Transaction):
logger.warning(deprecation_msg)
return self.start_transaction(span, **kwargs)

if "transaction" in kwargs:
logger.warning(deprecation_msg)
name = kwargs.pop("transaction")
return self.start_transaction(name=name, **kwargs)

# THIS BLOCK IS DEPRECATED
# We do not pass a span into start_span in our code base, so I deprecate this.
if span is not None:
deprecation_msg = "Deprecated: passing a span into `start_span` is deprecated and will be removed in the future."
logger.warning(deprecation_msg)
return span

kwargs.pop("client")

active_span = self.span
if active_span is not None:
new_child_span = active_span.start_child(**kwargs)
return new_child_span

# If there is already a trace_id in the propagation context, use it.
# This does not need to be done for `start_child` above because it takes
# the trace_id from the parent span.
if "trace_id" not in kwargs:
traceparent = self.get_traceparent()
trace_id = traceparent.split("-")[0] if traceparent else None
if trace_id is not None:
kwargs["trace_id"] = trace_id

return Span(**kwargs)

def continue_trace(self, environ_or_headers, op=None, name=None, source=None):
# type: (Dict[str, Any], Optional[str], Optional[str], Optional[str]) -> Transaction
"""
Sets the propagation context from environment or headers and returns a transaction.
"""
self.generate_propagation_context(environ_or_headers)

transaction = Transaction.continue_from_headers(
normalize_incoming_data(environ_or_headers),
op=op,
name=name,
source=source,
)

return transaction

def start_session(self, *args, **kwargs):
# type: (*Any, **Any) -> None
"""Starts a new session."""
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Auto-enable theater mode on YouTube\n(function() {\n function tryTheater() {\n var btn = document.querySelector('button[aria-label=\"Theater mode\"], ytd-player #player button[title=\"Theater mode\"]');\n if (btn && !btn.classList.contains('activated')) {\n btn.click();\n }\n }\n \n // Try immediately\n tryTheater();\n \n // Try after navigation (SPA)\n var lastUrl = location.href;\n setInterval(function() {\n if (location.href !== lastUrl) {\n lastUrl = location.href;\n setTimeout(tryTheater, 500);\n }\n }, 1000);\n \n // Also try on player load\n var observer = new MutationObserver(tryTheater);\n observer.observe(document.body, { childList: true, subtree: true });\n})();", "YouTube Theater Mode Default"); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
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
100 changes: 13 additions & 87 deletions sentry_sdk/hub.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,13 +7,11 @@
from sentry_sdk.consts import INSTRUMENTER
from sentry_sdk.scope import Scope
from sentry_sdk.client import Client
from sentry_sdk.profiler import Profile
from sentry_sdk.tracing import (
NoOpSpan,
Span,
Transaction,
)
from sentry_sdk.tracing_utils import normalize_incoming_data

from sentry_sdk.utils import (
logger,
Expand DownExpand Up@@ -430,54 +428,12 @@ def start_span(self, span=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs):

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Span`.
"""
configuration_instrumenter = self.client and self.client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

# THIS BLOCK IS DEPRECATED
# TODO: consider removing this in a future release.
# This is for backwards compatibility with releases before
# start_transaction existed, to allow for a smoother transition.
if isinstance(span, Transaction) or "transaction" in kwargs:
deprecation_msg = (
"Deprecated: use start_transaction to start transactions and "
"Transaction.start_child to start spans."
)

if isinstance(span, Transaction):
logger.warning(deprecation_msg)
return self.start_transaction(span)

if "transaction" in kwargs:
logger.warning(deprecation_msg)
name = kwargs.pop("transaction")
return self.start_transaction(name=name, **kwargs)

# THIS BLOCK IS DEPRECATED
# We do not pass a span into start_span in our code base, so I deprecate this.
if span is not None:
deprecation_msg = "Deprecated: passing a span into `start_span` is deprecated and will be removed in the future."
logger.warning(deprecation_msg)
return span

kwargs.setdefault("hub", self)

active_span = self.scope.span
if active_span is not None:
new_child_span = active_span.start_child(**kwargs)
return new_child_span
client, scope = self._stack[-1]

# If there is already a trace_id in the propagation context, use it.
# This does not need to be done for `start_child` above because it takes
# the trace_id from the parent span.
if "trace_id" not in kwargs:
traceparent = self.get_traceparent()
trace_id = traceparent.split("-")[0] if traceparent else None
if trace_id is not None:
kwargs["trace_id"] = trace_id
kwargs["hub"] = self
kwargs["client"] = client

return Span(**kwargs)
return scope.start_span(span=span, instrumenter=instrumenter, **kwargs)

def start_transaction(
self, transaction=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs
Expand DownExpand Up@@ -507,55 +463,25 @@ def start_transaction(

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Transaction`.
"""
configuration_instrumenter = self.client and self.client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

custom_sampling_context = kwargs.pop("custom_sampling_context", {})

# if we haven't been given a transaction, make one
if transaction is None:
kwargs.setdefault("hub", self)
transaction = Transaction(**kwargs)

# use traces_sample_rate, traces_sampler, and/or inheritance to make a
# sampling decision
sampling_context = {
"transaction_context": transaction.to_json(),
"parent_sampled": transaction.parent_sampled,
}
sampling_context.update(custom_sampling_context)
transaction._set_initial_sampling_decision(sampling_context=sampling_context)

profile = Profile(transaction, hub=self)
profile._set_initial_sampling_decision(sampling_context=sampling_context)
client, scope = self._stack[-1]

# we don't bother to keep spans if we already know we're not going to
# send the transaction
if transaction.sampled:
max_spans = (
self.client and self.client.options["_experiments"].get("max_spans")
) or 1000
transaction.init_span_recorder(maxlen=max_spans)
kwargs["hub"] = self
kwargs["client"] = client

return transaction
return scope.start_transaction(
transaction=transaction, instrumenter=instrumenter, **kwargs
)

def continue_trace(self, environ_or_headers, op=None, name=None, source=None):
# type: (Dict[str, Any], Optional[str], Optional[str], Optional[str]) -> Transaction
"""
Sets the propagation context from environment or headers and returns a transaction.
"""
with self.configure_scope() as scope:
scope.generate_propagation_context(environ_or_headers)
scope = self._stack[-1][1]

transaction = Transaction.continue_from_headers(
normalize_incoming_data(environ_or_headers),
op=op,
name=name,
source=source,
return scope.continue_trace(
environ_or_headers=environ_or_headers, op=op, name=name, source=source
)
return transaction

@overload
def push_scope(
Expand Down
158 changes: 154 additions & 4 deletions sentry_sdk/scope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,8 +6,9 @@

from sentry_sdk.attachments import Attachment
from sentry_sdk._compat import datetime_utcnow
from sentry_sdk.consts import FALSE_VALUES
from sentry_sdk.consts import FALSE_VALUES, INSTRUMENTER
from sentry_sdk._functools import wraps
from sentry_sdk.profiler import Profile
from sentry_sdk.session import Session
from sentry_sdk.tracing_utils import (
Baggage,
Expand All@@ -18,6 +19,8 @@
from sentry_sdk.tracing import (
BAGGAGE_HEADER_NAME,
SENTRY_TRACE_HEADER_NAME,
NoOpSpan,
Span,
Transaction,
)
from sentry_sdk._types import TYPE_CHECKING
Expand All@@ -34,6 +37,7 @@
from typing import Optional
from typing import Tuple
from typing import TypeVar
from typing import Union

from sentry_sdk._types import (
Breadcrumb,
Expand All@@ -46,9 +50,6 @@
Type,
)

from sentry_sdk.profiler import Profile
from sentry_sdk.tracing import Span

F = TypeVar("F", bound=Callable[..., Any])
T = TypeVar("T")

Expand DownExpand Up@@ -636,6 +637,155 @@ def add_breadcrumb(self, crumb=None, hint=None, **kwargs):
while len(self._breadcrumbs) > max_breadcrumbs:
self._breadcrumbs.popleft()

def start_transaction(
self, transaction=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs
):
# type: (Optional[Transaction], str, Any) -> Union[Transaction, NoOpSpan]
"""
Start and return a transaction.

Start an existing transaction if given, otherwise create and start a new
transaction with kwargs.

This is the entry point to manual tracing instrumentation.

A tree structure can be built by adding child spans to the transaction,
and child spans to other spans. To start a new child span within the
transaction or any span, call the respective `.start_child()` method.

Every child span must be finished before the transaction is finished,
otherwise the unfinished spans are discarded.

When used as context managers, spans and transactions are automatically
finished at the end of the `with` block. If not using context managers,
call the `.finish()` method.

When the transaction is finished, it will be sent to Sentry with all its
finished child spans.

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Transaction`.
"""
hub = kwargs.pop("hub", None)
client = kwargs.pop("client", None)

configuration_instrumenter = client and client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

custom_sampling_context = kwargs.pop("custom_sampling_context", {})

# if we haven't been given a transaction, make one
if transaction is None:
kwargs.setdefault("hub", hub)
Comment thread
antonpirker marked this conversation as resolved.
transaction = Transaction(**kwargs)

# use traces_sample_rate, traces_sampler, and/or inheritance to make a
# sampling decision
sampling_context = {
"transaction_context": transaction.to_json(),
"parent_sampled": transaction.parent_sampled,
}
sampling_context.update(custom_sampling_context)
transaction._set_initial_sampling_decision(sampling_context=sampling_context)

profile = Profile(transaction, hub=hub)
profile._set_initial_sampling_decision(sampling_context=sampling_context)

# we don't bother to keep spans if we already know we're not going to
# send the transaction
if transaction.sampled:
max_spans = (
client and client.options["_experiments"].get("max_spans")
) or 1000
transaction.init_span_recorder(maxlen=max_spans)

return transaction

def start_span(self, span=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs):
# type: (Optional[Span], str, Any) -> Span
"""
Start a span whose parent is the currently active span or transaction, if any.

The return value is a :py:class:`sentry_sdk.tracing.Span` instance,
typically used as a context manager to start and stop timing in a `with`
block.

Only spans contained in a transaction are sent to Sentry. Most
integrations start a transaction at the appropriate time, for example
for every incoming HTTP request. Use
:py:meth:`sentry_sdk.start_transaction` to start a new transaction when
one is not already in progress.

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Span`.
"""
client = kwargs.get("client", None)

configuration_instrumenter = client and client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

# THIS BLOCK IS DEPRECATED
# TODO: consider removing this in a future release.
# This is for backwards compatibility with releases before
# start_transaction existed, to allow for a smoother transition.
if isinstance(span, Transaction) or "transaction" in kwargs:
deprecation_msg = (
Comment thread
antonpirker marked this conversation as resolved.
"Deprecated: use start_transaction to start transactions and "
"Transaction.start_child to start spans."
)

if isinstance(span, Transaction):
logger.warning(deprecation_msg)
return self.start_transaction(span, **kwargs)

if "transaction" in kwargs:
logger.warning(deprecation_msg)
name = kwargs.pop("transaction")
return self.start_transaction(name=name, **kwargs)

# THIS BLOCK IS DEPRECATED
# We do not pass a span into start_span in our code base, so I deprecate this.
if span is not None:
deprecation_msg = "Deprecated: passing a span into `start_span` is deprecated and will be removed in the future."
logger.warning(deprecation_msg)
return span

kwargs.pop("client")

active_span = self.span
if active_span is not None:
new_child_span = active_span.start_child(**kwargs)
return new_child_span

# If there is already a trace_id in the propagation context, use it.
# This does not need to be done for `start_child` above because it takes
# the trace_id from the parent span.
if "trace_id" not in kwargs:
traceparent = self.get_traceparent()
trace_id = traceparent.split("-")[0] if traceparent else None
if trace_id is not None:
kwargs["trace_id"] = trace_id

return Span(**kwargs)

def continue_trace(self, environ_or_headers, op=None, name=None, source=None):
# type: (Dict[str, Any], Optional[str], Optional[str], Optional[str]) -> Transaction
"""
Sets the propagation context from environment or headers and returns a transaction.
"""
self.generate_propagation_context(environ_or_headers)

transaction = Transaction.continue_from_headers(
normalize_incoming_data(environ_or_headers),
op=op,
name=name,
source=source,
)

return transaction

def start_session(self, *args, **kwargs):
# type: (*Any, **Any) -> None
"""Starts a new session."""
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Remove or un-stick sticky/fixed headers that block content\n(function() {\n function unstick() {\n document.querySelectorAll('header, nav, [role=\"banner\"], .header, .navbar, .sticky, .fixed-top, [style*=\"position: fixed\"], [style*=\"position:sticky\"]').forEach(function(el) {\n if (el.style.position === 'fixed' || el.style.position === 'sticky' || \n getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') {\n el.style.position = 'static';\n el.style.top = 'auto';\n el.style.zIndex = 'auto';\n }\n });\n }\n \n unstick();\n \n var observer = new MutationObserver(unstick);\n observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] });\n})();", "Kill Sticky Headers"); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + '
Skip to content
Merged
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
100 changes: 13 additions & 87 deletions sentry_sdk/hub.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,13 +7,11 @@
from sentry_sdk.consts import INSTRUMENTER
from sentry_sdk.scope import Scope
from sentry_sdk.client import Client
from sentry_sdk.profiler import Profile
from sentry_sdk.tracing import (
NoOpSpan,
Span,
Transaction,
)
from sentry_sdk.tracing_utils import normalize_incoming_data

from sentry_sdk.utils import (
logger,
Expand DownExpand Up@@ -430,54 +428,12 @@ def start_span(self, span=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs):

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Span`.
"""
configuration_instrumenter = self.client and self.client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

# THIS BLOCK IS DEPRECATED
# TODO: consider removing this in a future release.
# This is for backwards compatibility with releases before
# start_transaction existed, to allow for a smoother transition.
if isinstance(span, Transaction) or "transaction" in kwargs:
deprecation_msg = (
"Deprecated: use start_transaction to start transactions and "
"Transaction.start_child to start spans."
)

if isinstance(span, Transaction):
logger.warning(deprecation_msg)
return self.start_transaction(span)

if "transaction" in kwargs:
logger.warning(deprecation_msg)
name = kwargs.pop("transaction")
return self.start_transaction(name=name, **kwargs)

# THIS BLOCK IS DEPRECATED
# We do not pass a span into start_span in our code base, so I deprecate this.
if span is not None:
deprecation_msg = "Deprecated: passing a span into `start_span` is deprecated and will be removed in the future."
logger.warning(deprecation_msg)
return span

kwargs.setdefault("hub", self)

active_span = self.scope.span
if active_span is not None:
new_child_span = active_span.start_child(**kwargs)
return new_child_span
client, scope = self._stack[-1]

# If there is already a trace_id in the propagation context, use it.
# This does not need to be done for `start_child` above because it takes
# the trace_id from the parent span.
if "trace_id" not in kwargs:
traceparent = self.get_traceparent()
trace_id = traceparent.split("-")[0] if traceparent else None
if trace_id is not None:
kwargs["trace_id"] = trace_id
kwargs["hub"] = self
kwargs["client"] = client

return Span(**kwargs)
return scope.start_span(span=span, instrumenter=instrumenter, **kwargs)

def start_transaction(
self, transaction=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs
Expand DownExpand Up@@ -507,55 +463,25 @@ def start_transaction(

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Transaction`.
"""
configuration_instrumenter = self.client and self.client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

custom_sampling_context = kwargs.pop("custom_sampling_context", {})

# if we haven't been given a transaction, make one
if transaction is None:
kwargs.setdefault("hub", self)
transaction = Transaction(**kwargs)

# use traces_sample_rate, traces_sampler, and/or inheritance to make a
# sampling decision
sampling_context = {
"transaction_context": transaction.to_json(),
"parent_sampled": transaction.parent_sampled,
}
sampling_context.update(custom_sampling_context)
transaction._set_initial_sampling_decision(sampling_context=sampling_context)

profile = Profile(transaction, hub=self)
profile._set_initial_sampling_decision(sampling_context=sampling_context)
client, scope = self._stack[-1]

# we don't bother to keep spans if we already know we're not going to
# send the transaction
if transaction.sampled:
max_spans = (
self.client and self.client.options["_experiments"].get("max_spans")
) or 1000
transaction.init_span_recorder(maxlen=max_spans)
kwargs["hub"] = self
kwargs["client"] = client

return transaction
return scope.start_transaction(
transaction=transaction, instrumenter=instrumenter, **kwargs
)

def continue_trace(self, environ_or_headers, op=None, name=None, source=None):
# type: (Dict[str, Any], Optional[str], Optional[str], Optional[str]) -> Transaction
"""
Sets the propagation context from environment or headers and returns a transaction.
"""
with self.configure_scope() as scope:
scope.generate_propagation_context(environ_or_headers)
scope = self._stack[-1][1]

transaction = Transaction.continue_from_headers(
normalize_incoming_data(environ_or_headers),
op=op,
name=name,
source=source,
return scope.continue_trace(
environ_or_headers=environ_or_headers, op=op, name=name, source=source
)
return transaction

@overload
def push_scope(
Expand Down
158 changes: 154 additions & 4 deletions sentry_sdk/scope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,8 +6,9 @@

from sentry_sdk.attachments import Attachment
from sentry_sdk._compat import datetime_utcnow
from sentry_sdk.consts import FALSE_VALUES
from sentry_sdk.consts import FALSE_VALUES, INSTRUMENTER
from sentry_sdk._functools import wraps
from sentry_sdk.profiler import Profile
from sentry_sdk.session import Session
from sentry_sdk.tracing_utils import (
Baggage,
Expand All@@ -18,6 +19,8 @@
from sentry_sdk.tracing import (
BAGGAGE_HEADER_NAME,
SENTRY_TRACE_HEADER_NAME,
NoOpSpan,
Span,
Transaction,
)
from sentry_sdk._types import TYPE_CHECKING
Expand All@@ -34,6 +37,7 @@
from typing import Optional
from typing import Tuple
from typing import TypeVar
from typing import Union

from sentry_sdk._types import (
Breadcrumb,
Expand All@@ -46,9 +50,6 @@
Type,
)

from sentry_sdk.profiler import Profile
from sentry_sdk.tracing import Span

F = TypeVar("F", bound=Callable[..., Any])
T = TypeVar("T")

Expand DownExpand Up@@ -636,6 +637,155 @@ def add_breadcrumb(self, crumb=None, hint=None, **kwargs):
while len(self._breadcrumbs) > max_breadcrumbs:
self._breadcrumbs.popleft()

def start_transaction(
self, transaction=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs
):
# type: (Optional[Transaction], str, Any) -> Union[Transaction, NoOpSpan]
"""
Start and return a transaction.

Start an existing transaction if given, otherwise create and start a new
transaction with kwargs.

This is the entry point to manual tracing instrumentation.

A tree structure can be built by adding child spans to the transaction,
and child spans to other spans. To start a new child span within the
transaction or any span, call the respective `.start_child()` method.

Every child span must be finished before the transaction is finished,
otherwise the unfinished spans are discarded.

When used as context managers, spans and transactions are automatically
finished at the end of the `with` block. If not using context managers,
call the `.finish()` method.

When the transaction is finished, it will be sent to Sentry with all its
finished child spans.

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Transaction`.
"""
hub = kwargs.pop("hub", None)
client = kwargs.pop("client", None)

configuration_instrumenter = client and client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

custom_sampling_context = kwargs.pop("custom_sampling_context", {})

# if we haven't been given a transaction, make one
if transaction is None:
kwargs.setdefault("hub", hub)
Comment thread
antonpirker marked this conversation as resolved.
transaction = Transaction(**kwargs)

# use traces_sample_rate, traces_sampler, and/or inheritance to make a
# sampling decision
sampling_context = {
"transaction_context": transaction.to_json(),
"parent_sampled": transaction.parent_sampled,
}
sampling_context.update(custom_sampling_context)
transaction._set_initial_sampling_decision(sampling_context=sampling_context)

profile = Profile(transaction, hub=hub)
profile._set_initial_sampling_decision(sampling_context=sampling_context)

# we don't bother to keep spans if we already know we're not going to
# send the transaction
if transaction.sampled:
max_spans = (
client and client.options["_experiments"].get("max_spans")
) or 1000
transaction.init_span_recorder(maxlen=max_spans)

return transaction

def start_span(self, span=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs):
# type: (Optional[Span], str, Any) -> Span
"""
Start a span whose parent is the currently active span or transaction, if any.

The return value is a :py:class:`sentry_sdk.tracing.Span` instance,
typically used as a context manager to start and stop timing in a `with`
block.

Only spans contained in a transaction are sent to Sentry. Most
integrations start a transaction at the appropriate time, for example
for every incoming HTTP request. Use
:py:meth:`sentry_sdk.start_transaction` to start a new transaction when
one is not already in progress.

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Span`.
"""
client = kwargs.get("client", None)

configuration_instrumenter = client and client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

# THIS BLOCK IS DEPRECATED
# TODO: consider removing this in a future release.
# This is for backwards compatibility with releases before
# start_transaction existed, to allow for a smoother transition.
if isinstance(span, Transaction) or "transaction" in kwargs:
deprecation_msg = (
Comment thread
antonpirker marked this conversation as resolved.
"Deprecated: use start_transaction to start transactions and "
"Transaction.start_child to start spans."
)

if isinstance(span, Transaction):
logger.warning(deprecation_msg)
return self.start_transaction(span, **kwargs)

if "transaction" in kwargs:
logger.warning(deprecation_msg)
name = kwargs.pop("transaction")
return self.start_transaction(name=name, **kwargs)

# THIS BLOCK IS DEPRECATED
# We do not pass a span into start_span in our code base, so I deprecate this.
if span is not None:
deprecation_msg = "Deprecated: passing a span into `start_span` is deprecated and will be removed in the future."
logger.warning(deprecation_msg)
return span

kwargs.pop("client")

active_span = self.span
if active_span is not None:
new_child_span = active_span.start_child(**kwargs)
return new_child_span

# If there is already a trace_id in the propagation context, use it.
# This does not need to be done for `start_child` above because it takes
# the trace_id from the parent span.
if "trace_id" not in kwargs:
traceparent = self.get_traceparent()
trace_id = traceparent.split("-")[0] if traceparent else None
if trace_id is not None:
kwargs["trace_id"] = trace_id

return Span(**kwargs)

def continue_trace(self, environ_or_headers, op=None, name=None, source=None):
# type: (Dict[str, Any], Optional[str], Optional[str], Optional[str]) -> Transaction
"""
Sets the propagation context from environment or headers and returns a transaction.
"""
self.generate_propagation_context(environ_or_headers)

transaction = Transaction.continue_from_headers(
normalize_incoming_data(environ_or_headers),
op=op,
name=name,
source=source,
)

return transaction

def start_session(self, *args, **kwargs):
# type: (*Any, **Any) -> None
"""Starts a new session."""
Expand Down
, 'i'); if (__m === '*' || __re.test(location.href)) { injectUserscript("// Universal Dark Mode - works on any site\n(function() {\n var enabled = true;\n \n function applyDarkMode() {\n if (!enabled) return;\n \n // Create style element if it doesn't exist\n var style = document.getElementById('universal-dark-mode-style');\n if (!style) {\n style = document.createElement('style');\n style.id = 'universal-dark-mode-style';\n document.head.appendChild(style);\n }\n \n // Dark mode CSS - inverts colors but preserves images/video\n style.textContent = '\n /* Invert everything except media */\n html {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #1a1a2e !important;\n }\n \n /* Restore images, videos, iframes, canvas */\n img, video, iframe, canvas, svg, picture, [style*=\"background-image\"] {\n filter: invert(1) hue-rotate(180deg) !important;\n }\n \n /* Preserve specific elements that should not be inverted */\n .no-dark-mode, .no-dark-mode *,\n [data-theme=\"light\"], [data-theme=\"light\"],\n .ace_editor, .ace_editor *,\n .CodeMirror, .CodeMirror *,\n .monaco-editor, .monaco-editor *,\n .markdown-body pre, .markdown-body pre *,\n .highlight, .highlight *,\n pre code, pre code * {\n filter: none !important;\n }\n \n /* Fix common UI elements */\n .modal, .popup, .dropdown-menu, .tooltip, .popover {\n filter: invert(1) hue-rotate(180deg) !important;\n background: #2d2d44 !important;\n border-color: #444 !important;\n }\n \n /* Scrollbars */\n ::-webkit-scrollbar { background: #1a1a2e !important; }\n ::-webkit-scrollbar-thumb { background: #444 !important; }\n ::-webkit-scrollbar-thumb:hover { background: #555 !important; }\n \n /* Selection */\n ::selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ::-moz-selection { background: #4ecdc4 !important; color: #1a1a2e !important; }\n ';\n }\n \n function removeDarkMode() {\n var style = document.getElementById('universal-dark-mode-style');\n if (style) style.remove();\n }\n \n // Toggle with Alt+Shift+D\n document.addEventListener('keydown', function(e) {\n if (e.altKey && e.shiftKey && e.key === 'D') {\n e.preventDefault();\n enabled = !enabled;\n if (enabled) {\n applyDarkMode();\n console.log('[Universal Dark Mode] Enabled');\n } else {\n removeDarkMode();\n console.log('[Universal Dark Mode] Disabled');\n }\n }\n });\n \n // Apply on load\n applyDarkMode();\n \n // Re-apply on dynamic content\n var observer = new MutationObserver(function(mutations) {\n if (enabled && !document.getElementById('universal-dark-mode-style')) {\n applyDarkMode();\n }\n });\n observer.observe(document.head, { childList: true });\n \n console.log('[Universal Dark Mode] Loaded - Press Alt+Shift+D to toggle');\n})();", "Universal Dark Mode"); } } catch(__e) { console.warn('[Userscript:Universal Dark Mode]', __e); } })(); })();
Skip to content
Merged
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
100 changes: 13 additions & 87 deletions sentry_sdk/hub.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -7,13 +7,11 @@
from sentry_sdk.consts import INSTRUMENTER
from sentry_sdk.scope import Scope
from sentry_sdk.client import Client
from sentry_sdk.profiler import Profile
from sentry_sdk.tracing import (
NoOpSpan,
Span,
Transaction,
)
from sentry_sdk.tracing_utils import normalize_incoming_data

from sentry_sdk.utils import (
logger,
Expand DownExpand Up@@ -430,54 +428,12 @@ def start_span(self, span=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs):

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Span`.
"""
configuration_instrumenter = self.client and self.client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

# THIS BLOCK IS DEPRECATED
# TODO: consider removing this in a future release.
# This is for backwards compatibility with releases before
# start_transaction existed, to allow for a smoother transition.
if isinstance(span, Transaction) or "transaction" in kwargs:
deprecation_msg = (
"Deprecated: use start_transaction to start transactions and "
"Transaction.start_child to start spans."
)

if isinstance(span, Transaction):
logger.warning(deprecation_msg)
return self.start_transaction(span)

if "transaction" in kwargs:
logger.warning(deprecation_msg)
name = kwargs.pop("transaction")
return self.start_transaction(name=name, **kwargs)

# THIS BLOCK IS DEPRECATED
# We do not pass a span into start_span in our code base, so I deprecate this.
if span is not None:
deprecation_msg = "Deprecated: passing a span into `start_span` is deprecated and will be removed in the future."
logger.warning(deprecation_msg)
return span

kwargs.setdefault("hub", self)

active_span = self.scope.span
if active_span is not None:
new_child_span = active_span.start_child(**kwargs)
return new_child_span
client, scope = self._stack[-1]

# If there is already a trace_id in the propagation context, use it.
# This does not need to be done for `start_child` above because it takes
# the trace_id from the parent span.
if "trace_id" not in kwargs:
traceparent = self.get_traceparent()
trace_id = traceparent.split("-")[0] if traceparent else None
if trace_id is not None:
kwargs["trace_id"] = trace_id
kwargs["hub"] = self
kwargs["client"] = client

return Span(**kwargs)
return scope.start_span(span=span, instrumenter=instrumenter, **kwargs)

def start_transaction(
self, transaction=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs
Expand DownExpand Up@@ -507,55 +463,25 @@ def start_transaction(

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Transaction`.
"""
configuration_instrumenter = self.client and self.client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

custom_sampling_context = kwargs.pop("custom_sampling_context", {})

# if we haven't been given a transaction, make one
if transaction is None:
kwargs.setdefault("hub", self)
transaction = Transaction(**kwargs)

# use traces_sample_rate, traces_sampler, and/or inheritance to make a
# sampling decision
sampling_context = {
"transaction_context": transaction.to_json(),
"parent_sampled": transaction.parent_sampled,
}
sampling_context.update(custom_sampling_context)
transaction._set_initial_sampling_decision(sampling_context=sampling_context)

profile = Profile(transaction, hub=self)
profile._set_initial_sampling_decision(sampling_context=sampling_context)
client, scope = self._stack[-1]

# we don't bother to keep spans if we already know we're not going to
# send the transaction
if transaction.sampled:
max_spans = (
self.client and self.client.options["_experiments"].get("max_spans")
) or 1000
transaction.init_span_recorder(maxlen=max_spans)
kwargs["hub"] = self
kwargs["client"] = client

return transaction
return scope.start_transaction(
transaction=transaction, instrumenter=instrumenter, **kwargs
)

def continue_trace(self, environ_or_headers, op=None, name=None, source=None):
# type: (Dict[str, Any], Optional[str], Optional[str], Optional[str]) -> Transaction
"""
Sets the propagation context from environment or headers and returns a transaction.
"""
with self.configure_scope() as scope:
scope.generate_propagation_context(environ_or_headers)
scope = self._stack[-1][1]

transaction = Transaction.continue_from_headers(
normalize_incoming_data(environ_or_headers),
op=op,
name=name,
source=source,
return scope.continue_trace(
environ_or_headers=environ_or_headers, op=op, name=name, source=source
)
return transaction

@overload
def push_scope(
Expand Down
158 changes: 154 additions & 4 deletions sentry_sdk/scope.py
Original file line numberDiff line numberDiff line change
Expand Up@@ -6,8 +6,9 @@

from sentry_sdk.attachments import Attachment
from sentry_sdk._compat import datetime_utcnow
from sentry_sdk.consts import FALSE_VALUES
from sentry_sdk.consts import FALSE_VALUES, INSTRUMENTER
from sentry_sdk._functools import wraps
from sentry_sdk.profiler import Profile
from sentry_sdk.session import Session
from sentry_sdk.tracing_utils import (
Baggage,
Expand All@@ -18,6 +19,8 @@
from sentry_sdk.tracing import (
BAGGAGE_HEADER_NAME,
SENTRY_TRACE_HEADER_NAME,
NoOpSpan,
Span,
Transaction,
)
from sentry_sdk._types import TYPE_CHECKING
Expand All@@ -34,6 +37,7 @@
from typing import Optional
from typing import Tuple
from typing import TypeVar
from typing import Union

from sentry_sdk._types import (
Breadcrumb,
Expand All@@ -46,9 +50,6 @@
Type,
)

from sentry_sdk.profiler import Profile
from sentry_sdk.tracing import Span

F = TypeVar("F", bound=Callable[..., Any])
T = TypeVar("T")

Expand DownExpand Up@@ -636,6 +637,155 @@ def add_breadcrumb(self, crumb=None, hint=None, **kwargs):
while len(self._breadcrumbs) > max_breadcrumbs:
self._breadcrumbs.popleft()

def start_transaction(
self, transaction=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs
):
# type: (Optional[Transaction], str, Any) -> Union[Transaction, NoOpSpan]
"""
Start and return a transaction.

Start an existing transaction if given, otherwise create and start a new
transaction with kwargs.

This is the entry point to manual tracing instrumentation.

A tree structure can be built by adding child spans to the transaction,
and child spans to other spans. To start a new child span within the
transaction or any span, call the respective `.start_child()` method.

Every child span must be finished before the transaction is finished,
otherwise the unfinished spans are discarded.

When used as context managers, spans and transactions are automatically
finished at the end of the `with` block. If not using context managers,
call the `.finish()` method.

When the transaction is finished, it will be sent to Sentry with all its
finished child spans.

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Transaction`.
"""
hub = kwargs.pop("hub", None)
client = kwargs.pop("client", None)

configuration_instrumenter = client and client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

custom_sampling_context = kwargs.pop("custom_sampling_context", {})

# if we haven't been given a transaction, make one
if transaction is None:
kwargs.setdefault("hub", hub)
Comment thread
antonpirker marked this conversation as resolved.
transaction = Transaction(**kwargs)

# use traces_sample_rate, traces_sampler, and/or inheritance to make a
# sampling decision
sampling_context = {
"transaction_context": transaction.to_json(),
"parent_sampled": transaction.parent_sampled,
}
sampling_context.update(custom_sampling_context)
transaction._set_initial_sampling_decision(sampling_context=sampling_context)

profile = Profile(transaction, hub=hub)
profile._set_initial_sampling_decision(sampling_context=sampling_context)

# we don't bother to keep spans if we already know we're not going to
# send the transaction
if transaction.sampled:
max_spans = (
client and client.options["_experiments"].get("max_spans")
) or 1000
transaction.init_span_recorder(maxlen=max_spans)

return transaction

def start_span(self, span=None, instrumenter=INSTRUMENTER.SENTRY, **kwargs):
# type: (Optional[Span], str, Any) -> Span
"""
Start a span whose parent is the currently active span or transaction, if any.

The return value is a :py:class:`sentry_sdk.tracing.Span` instance,
typically used as a context manager to start and stop timing in a `with`
block.

Only spans contained in a transaction are sent to Sentry. Most
integrations start a transaction at the appropriate time, for example
for every incoming HTTP request. Use
:py:meth:`sentry_sdk.start_transaction` to start a new transaction when
one is not already in progress.

For supported `**kwargs` see :py:class:`sentry_sdk.tracing.Span`.
"""
client = kwargs.get("client", None)

configuration_instrumenter = client and client.options["instrumenter"]

if instrumenter != configuration_instrumenter:
return NoOpSpan()

# THIS BLOCK IS DEPRECATED
# TODO: consider removing this in a future release.
# This is for backwards compatibility with releases before
# start_transaction existed, to allow for a smoother transition.
if isinstance(span, Transaction) or "transaction" in kwargs:
deprecation_msg = (
Comment thread
antonpirker marked this conversation as resolved.
"Deprecated: use start_transaction to start transactions and "
"Transaction.start_child to start spans."
)

if isinstance(span, Transaction):
logger.warning(deprecation_msg)
return self.start_transaction(span, **kwargs)

if "transaction" in kwargs:
logger.warning(deprecation_msg)
name = kwargs.pop("transaction")
return self.start_transaction(name=name, **kwargs)

# THIS BLOCK IS DEPRECATED
# We do not pass a span into start_span in our code base, so I deprecate this.
if span is not None:
deprecation_msg = "Deprecated: passing a span into `start_span` is deprecated and will be removed in the future."
logger.warning(deprecation_msg)
return span

kwargs.pop("client")

active_span = self.span
if active_span is not None:
new_child_span = active_span.start_child(**kwargs)
return new_child_span

# If there is already a trace_id in the propagation context, use it.
# This does not need to be done for `start_child` above because it takes
# the trace_id from the parent span.
if "trace_id" not in kwargs:
traceparent = self.get_traceparent()
trace_id = traceparent.split("-")[0] if traceparent else None
if trace_id is not None:
kwargs["trace_id"] = trace_id

return Span(**kwargs)

def continue_trace(self, environ_or_headers, op=None, name=None, source=None):
# type: (Dict[str, Any], Optional[str], Optional[str], Optional[str]) -> Transaction
"""
Sets the propagation context from environment or headers and returns a transaction.
"""
self.generate_propagation_context(environ_or_headers)

transaction = Transaction.continue_from_headers(
normalize_incoming_data(environ_or_headers),
op=op,
name=name,
source=source,
)

return transaction

def start_session(self, *args, **kwargs):
# type: (*Any, **Any) -> None
"""Starts a new session."""
Expand Down