Skip to content
New issue

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

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

Already on GitHub? Sign in to your account

[ATO-2105] Implement functionality to create custom spans #1075

Merged
merged 4 commits into from
Feb 14, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
5 changes: 4 additions & 1 deletion rasa_sdk/tracing/instrumentation/instrumentation.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from rasa_sdk.executor import ActionExecutor
from rasa_sdk.forms import ValidationAction
from rasa_sdk.tracing.instrumentation import attribute_extractors
from rasa_sdk.tracing.trace_provider import TraceProvider

# The `TypeVar` representing the return type for a function to be wrapped.
S = TypeVar("S")
Expand Down Expand Up @@ -132,13 +133,15 @@ def instrument(
if action_executor_class is not None and not class_is_instrumented(
action_executor_class
):
tracer = tracer_provider.get_tracer(action_executor_class.__module__)
_instrument_method(
tracer_provider.get_tracer(action_executor_class.__module__),
tracer,
action_executor_class,
"run",
attribute_extractors.extract_attrs_for_action_executor,
)
mark_class_as_instrumented(action_executor_class)
TraceProvider().register_tracer(tracer)

if validation_action_class is not None and not class_is_instrumented(
validation_action_class
Expand Down
23 changes: 23 additions & 0 deletions rasa_sdk/tracing/trace_provider.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from typing import Optional
from rasa_sdk.utils import Singleton
from opentelemetry.trace import Tracer


class TraceProvider(metaclass=Singleton):
Tawakalt marked this conversation as resolved.
Show resolved Hide resolved
"""Represents a provider for tracer."""

tracer: Optional[Tracer] = None
Tawakalt marked this conversation as resolved.
Show resolved Hide resolved

def register_tracer(self, tracer: Tracer) -> None:
"""Register a tracer.
Args:
trace: The tracer to register.
"""
self.tracer = tracer

def get_tracer(self) -> Optional[Tracer]:
"""Get the tracer.
Returns:
The tracer.
"""
return self.tracer
22 changes: 22 additions & 0 deletions rasa_sdk/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,28 @@ class Button(dict):
pass


class Singleton(type):
"""Singleton metaclass."""

_instances: Dict[Any, Any] = {}

def __call__(cls, *args: Any, **kwargs: Any) -> Any:
"""Call the class.

Args:
*args: Arguments.
**kwargs: Keyword arguments.
"""
if cls not in cls._instances:
cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)

return cls._instances[cls]

def clear(cls) -> None:
"""Clear the class."""
cls._instances = {}


def all_subclasses(cls: Any) -> List[Any]:
"""Returns all known (imported) subclasses of a class."""
return cls.__subclasses__() + [
Expand Down
35 changes: 33 additions & 2 deletions tests/tracing/instrumentation/test_action_executor.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
from typing import Any, Dict, Sequence, Text, Optional

import pytest

from typing import Any, Dict, Sequence, Text, Optional
from unittest.mock import Mock
from pytest import MonkeyPatch
from opentelemetry.sdk.trace import ReadableSpan, TracerProvider
from opentelemetry.sdk.trace.export.in_memory_span_exporter import InMemorySpanExporter
from opentelemetry import trace

from rasa_sdk.tracing.instrumentation import instrumentation
from tests.tracing.instrumentation.conftest import MockActionExecutor
from rasa_sdk.types import ActionCall
from rasa_sdk import Tracker
from rasa_sdk.tracing.trace_provider import TraceProvider


@pytest.mark.parametrize(
Expand Down Expand Up @@ -56,3 +60,30 @@ async def test_tracing_action_executor_run(
assert captured_span.name == "MockActionExecutor.run"

assert captured_span.attributes == expected


@pytest.mark.asyncio
async def test_instrument_action_executor_run_registers_tracer(
tracer_provider: TracerProvider, monkeypatch: MonkeyPatch
ancalita marked this conversation as resolved.
Show resolved Hide resolved
) -> None:
component_class = MockActionExecutor

mock_tracer = trace.get_tracer(__name__)

register_tracer_mock = Mock()
get_tracer_mock = Mock(return_value=mock_tracer)

monkeypatch.setattr(TraceProvider, "register_tracer", register_tracer_mock())
monkeypatch.setattr(TraceProvider, "get_tracer", get_tracer_mock)

instrumentation.instrument(
tracer_provider,
action_executor_class=component_class,
)
register_tracer_mock.assert_called_once()

provider = TraceProvider()
tracer = provider.get_tracer()

assert tracer is not None
assert tracer == mock_tracer
19 changes: 19 additions & 0 deletions tests/tracing/test_trace_provider.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
from rasa_sdk.tracing.trace_provider import TraceProvider
from opentelemetry import trace


def test_anonymization_pipeline_provider_is_singleton() -> None:
Tawakalt marked this conversation as resolved.
Show resolved Hide resolved
trace_provider_1 = TraceProvider()
trace_provider_2 = TraceProvider()

assert trace_provider_1 is trace_provider_2
assert trace_provider_1.tracer is trace_provider_2.tracer


def test_trace_provider() -> None:
trace_provider = TraceProvider()
Tawakalt marked this conversation as resolved.
Show resolved Hide resolved
tracer = trace.get_tracer(__name__)
trace_provider.register_tracer(tracer)

assert trace_provider.tracer == tracer
assert trace_provider.get_tracer() == tracer
Loading