Skip to content

Commit

Permalink
Hide certain implementation specific classes/variables (#1684)
Browse files Browse the repository at this point in the history
  • Loading branch information
lzchen authored Mar 10, 2021
1 parent 0cd037f commit c81fd5e
Show file tree
Hide file tree
Showing 17 changed files with 64 additions and 56 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
([#1674](https://github.com/open-telemetry/opentelemetry-python/pull/1674))
- Remove time_ns from API and add a warning for older versions of Python
([#1602](https://github.com/open-telemetry/opentelemetry-python/pull/1602))
- Hide implementation classes/variables in api/sdk
([#1684](https://github.com/open-telemetry/opentelemetry-python/pull/1684))

### Removed
- Removed unused `get_hexadecimal_trace_id` and `get_hexadecimal_span_id` methods.
Expand Down
1 change: 1 addition & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@
# Even if wrapt is added to intersphinx_mapping, sphinx keeps failing
# with "class reference target not found: ObjectProxy".
("py:class", "ObjectProxy"),
("py:class", "opentelemetry.trace._LinkBase",),
# TODO: Understand why sphinx is not able to find this local class
("py:class", "opentelemetry.propagators.textmap.TextMapPropagator",),
("py:class", "opentelemetry.propagators.textmap.DictGetter",),
Expand Down
2 changes: 1 addition & 1 deletion opentelemetry-api/setup.cfg
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ where = src
opentelemetry_context =
contextvars_context = opentelemetry.context.contextvars_context:ContextVarsRuntimeContext
opentelemetry_tracer_provider =
default_tracer_provider = opentelemetry.trace:DefaultTracerProvider
default_tracer_provider = opentelemetry.trace:_DefaultTracerProvider
opentelemetry_propagator =
tracecontext = opentelemetry.trace.propagation.tracecontext:TraceContextTextMapPropagator
baggage = opentelemetry.baggage.propagation:W3CBaggagePropagator
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,9 @@
class W3CBaggagePropagator(textmap.TextMapPropagator):
"""Extracts and injects Baggage which is used to annotate telemetry."""

MAX_HEADER_LENGTH = 8192
MAX_PAIR_LENGTH = 4096
MAX_PAIRS = 180
_MAX_HEADER_LENGTH = 8192
_MAX_PAIR_LENGTH = 4096
_MAX_PAIRS = 180
_BAGGAGE_HEADER_NAME = "baggage"

def extract(
Expand All @@ -48,16 +48,16 @@ def extract(
getter.get(carrier, self._BAGGAGE_HEADER_NAME)
)

if not header or len(header) > self.MAX_HEADER_LENGTH:
if not header or len(header) > self._MAX_HEADER_LENGTH:
return context

baggage_entries = header.split(",")
total_baggage_entries = self.MAX_PAIRS
total_baggage_entries = self._MAX_PAIRS
for entry in baggage_entries:
if total_baggage_entries <= 0:
return context
total_baggage_entries -= 1
if len(entry) > self.MAX_PAIR_LENGTH:
if len(entry) > self._MAX_PAIR_LENGTH:
continue
try:
name, value = entry.split("=", 1)
Expand Down
4 changes: 2 additions & 2 deletions opentelemetry-api/src/opentelemetry/context/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,11 @@

from pkg_resources import iter_entry_points

from opentelemetry.context.context import Context, RuntimeContext
from opentelemetry.context.context import Context, _RuntimeContext
from opentelemetry.environment_variables import OTEL_PYTHON_CONTEXT

logger = logging.getLogger(__name__)
_RUNTIME_CONTEXT = None # type: typing.Optional[RuntimeContext]
_RUNTIME_CONTEXT = None # type: typing.Optional[_RuntimeContext]
_RUNTIME_CONTEXT_LOCK = threading.Lock()

_F = typing.TypeVar("_F", bound=typing.Callable[..., typing.Any])
Expand Down
6 changes: 3 additions & 3 deletions opentelemetry-api/src/opentelemetry/context/context.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ def __setitem__(self, key: str, value: object) -> None:
raise ValueError


class RuntimeContext(ABC):
class _RuntimeContext(ABC):
"""The RuntimeContext interface provides a wrapper for the different
mechanisms that are used to propagate context in Python.
Implementations can be made available via entry_points and
Expand All @@ -39,7 +39,7 @@ def attach(self, context: Context) -> object:

@abstractmethod
def get_current(self) -> Context:
""" Returns the current `Context` object. """
"""Returns the current `Context` object. """

@abstractmethod
def detach(self, token: object) -> None:
Expand All @@ -50,4 +50,4 @@ def detach(self, token: object) -> None:
"""


__all__ = ["Context", "RuntimeContext"]
__all__ = ["Context"]
19 changes: 14 additions & 5 deletions opentelemetry-api/src/opentelemetry/context/contextvars_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
from contextvars import ContextVar
from sys import version_info

from opentelemetry.context.context import Context, RuntimeContext
from opentelemetry.context.context import Context, _RuntimeContext

if (3, 5, 3) <= version_info < (3, 7):
import aiocontextvars # type: ignore # pylint:disable=unused-import,import-error
Expand All @@ -23,7 +23,7 @@
import opentelemetry.context.aiocontextvarsfix # pylint:disable=unused-import


class ContextVarsRuntimeContext(RuntimeContext):
class ContextVarsRuntimeContext(_RuntimeContext):
"""An implementation of the RuntimeContext interface which wraps ContextVar under
the hood. This is the prefered implementation for usage with Python 3.5+
"""
Expand All @@ -36,15 +36,24 @@ def __init__(self) -> None:
)

def attach(self, context: Context) -> object:
"""See `opentelemetry.context.RuntimeContext.attach`."""
"""Sets the current `Context` object. Returns a
token that can be used to reset to the previous `Context`.
Args:
context: The Context to set.
"""
return self._current_context.set(context)

def get_current(self) -> Context:
"""See `opentelemetry.context.RuntimeContext.get_current`."""
"""Returns the current `Context` object. """
return self._current_context.get()

def detach(self, token: object) -> None:
"""See `opentelemetry.context.RuntimeContext.detach`."""
"""Resets Context to a previous value
Args:
token: A reference to a previous Context.
"""
self._current_context.reset(token) # type: ignore


Expand Down
17 changes: 5 additions & 12 deletions opentelemetry-api/src/opentelemetry/trace/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@
logger = getLogger(__name__)


class LinkBase(ABC):
class _LinkBase(ABC):
def __init__(self, context: "SpanContext") -> None:
self._context = context

Expand All @@ -124,7 +124,7 @@ def attributes(self) -> types.Attributes:
pass


class Link(LinkBase):
class Link(_LinkBase):
"""A link to a `Span`.
Args:
Expand Down Expand Up @@ -205,7 +205,7 @@ def get_tracer(
"""


class DefaultTracerProvider(TracerProvider):
class _DefaultTracerProvider(TracerProvider):
"""The default TracerProvider, used when no implementation is available.
All operations are no-op.
Expand All @@ -217,7 +217,7 @@ def get_tracer(
instrumenting_library_version: str = "",
) -> "Tracer":
# pylint:disable=no-self-use,unused-argument
return DefaultTracer()
return _DefaultTracer()


class Tracer(ABC):
Expand All @@ -227,10 +227,6 @@ class Tracer(ABC):
and controlling spans' lifecycles.
"""

# Constant used to represent the current span being used as a parent.
# This is the default behavior when creating spans.
CURRENT_SPAN = NonRecordingSpan(INVALID_SPAN_CONTEXT)

@abstractmethod
def start_span(
self,
Expand Down Expand Up @@ -353,7 +349,7 @@ def start_as_current_span(
"""


class DefaultTracer(Tracer):
class _DefaultTracer(Tracer):
"""The default Tracer, used when no Tracer implementation is available.
All operations are no-op.
Expand Down Expand Up @@ -496,10 +492,7 @@ def use_span(
"INVALID_SPAN_ID",
"INVALID_TRACE_ID",
"NonRecordingSpan",
"DefaultTracer",
"DefaultTracerProvider",
"Link",
"LinkBase",
"Span",
"SpanContext",
"SpanKind",
Expand Down
8 changes: 4 additions & 4 deletions opentelemetry-api/tests/baggage/test_baggage_propagation.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def test_invalid_header(self):
self.assertEqual(self._extract(header), expected)

def test_header_too_long(self):
long_value = "s" * (W3CBaggagePropagator.MAX_HEADER_LENGTH + 1)
long_value = "s" * (W3CBaggagePropagator._MAX_HEADER_LENGTH + 1)
header = "key1={}".format(long_value)
expected = {}
self.assertEqual(self._extract(header), expected)
Expand All @@ -96,15 +96,15 @@ def test_header_contains_too_many_entries(self):
header = ",".join(
[
"key{}=val".format(k)
for k in range(W3CBaggagePropagator.MAX_PAIRS + 1)
for k in range(W3CBaggagePropagator._MAX_PAIRS + 1)
]
)
self.assertEqual(
len(self._extract(header)), W3CBaggagePropagator.MAX_PAIRS
len(self._extract(header)), W3CBaggagePropagator._MAX_PAIRS
)

def test_header_contains_pair_too_long(self):
long_value = "s" * (W3CBaggagePropagator.MAX_PAIR_LENGTH + 1)
long_value = "s" * (W3CBaggagePropagator._MAX_PAIR_LENGTH + 1)
header = "key1=value1,key2={},key3=value3".format(long_value)
expected = {"key1": "value1", "key3": "value3"}
self.assertEqual(self._extract(header), expected)
Expand Down
3 changes: 2 additions & 1 deletion opentelemetry-api/tests/test_implementation.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ def test_tracer(self):
trace.TracerProvider() # type:ignore

def test_default_tracer(self):
tracer_provider = trace.DefaultTracerProvider()
# pylint: disable=protected-access
tracer_provider = trace._DefaultTracerProvider()
tracer = tracer_provider.get_tracer(__name__)
with tracer.start_span("test") as span:
self.assertEqual(
Expand Down
5 changes: 3 additions & 2 deletions opentelemetry-api/tests/trace/test_globals.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,11 @@ def test_get_tracer(self):

class TestTracer(unittest.TestCase):
def setUp(self):
self.tracer = trace.DefaultTracer()
# pylint: disable=protected-access
self.tracer = trace._DefaultTracer()

def test_get_current_span(self):
"""DefaultTracer's start_span will also
"""_DefaultTracer's start_span will also
be retrievable via get_current_span
"""
self.assertEqual(trace.get_current_span(), trace.INVALID_SPAN)
Expand Down
3 changes: 2 additions & 1 deletion opentelemetry-api/tests/trace/test_tracer.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@

class TestTracer(unittest.TestCase):
def setUp(self):
self.tracer = trace.DefaultTracer()
# pylint: disable=protected-access
self.tracer = trace._DefaultTracer()

def test_start_span(self):
with self.tracer.start_span("") as span:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ def _handle(self, error: Exception, *args, **kwargs):
"""


class DefaultErrorHandler(ErrorHandler):
class _DefaultErrorHandler(ErrorHandler):
"""
Default error handler
Expand Down Expand Up @@ -144,6 +144,6 @@ def __exit__(self, exc_type, exc_value, traceback):

if not plugin_handled:

DefaultErrorHandler()._handle(exc_value)
_DefaultErrorHandler()._handle(exc_value)

return True
4 changes: 2 additions & 2 deletions opentelemetry-sdk/src/opentelemetry/sdk/resources/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,7 @@
TELEMETRY_SDK_LANGUAGE = "telemetry.sdk.language"


OPENTELEMETRY_SDK_VERSION = pkg_resources.get_distribution(
_OPENTELEMETRY_SDK_VERSION = pkg_resources.get_distribution(
"opentelemetry-sdk"
).version

Expand Down Expand Up @@ -225,7 +225,7 @@ def __hash__(self):
{
TELEMETRY_SDK_LANGUAGE: "python",
TELEMETRY_SDK_NAME: "opentelemetry",
TELEMETRY_SDK_VERSION: OPENTELEMETRY_SDK_VERSION,
TELEMETRY_SDK_VERSION: _OPENTELEMETRY_SDK_VERSION,
}
)

Expand Down
24 changes: 12 additions & 12 deletions opentelemetry-sdk/src/opentelemetry/sdk/trace/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,11 @@
environ.get(OTEL_SPAN_ATTRIBUTE_COUNT_LIMIT, 128)
)

SPAN_EVENT_COUNT_LIMIT = int(environ.get(OTEL_SPAN_EVENT_COUNT_LIMIT, 128))
SPAN_LINK_COUNT_LIMIT = int(environ.get(OTEL_SPAN_LINK_COUNT_LIMIT, 128))
VALID_ATTR_VALUE_TYPES = (bool, str, int, float)
_SPAN_EVENT_COUNT_LIMIT = int(environ.get(OTEL_SPAN_EVENT_COUNT_LIMIT, 128))
_SPAN_LINK_COUNT_LIMIT = int(environ.get(OTEL_SPAN_LINK_COUNT_LIMIT, 128))
_VALID_ATTR_VALUE_TYPES = (bool, str, int, float)
# pylint: disable=protected-access
TRACE_SAMPLER = sampling._get_from_env_or_default()
_TRACE_SAMPLER = sampling._get_from_env_or_default()


class SpanProcessor:
Expand Down Expand Up @@ -333,14 +333,14 @@ def _is_valid_attribute_value(value: types.AttributeValue) -> bool:
if element is None:
continue
element_type = type(element)
if element_type not in VALID_ATTR_VALUE_TYPES:
if element_type not in _VALID_ATTR_VALUE_TYPES:
logger.warning(
"Invalid type %s in attribute value sequence. Expected one of "
"%s or None",
element_type.__name__,
[
valid_type.__name__
for valid_type in VALID_ATTR_VALUE_TYPES
for valid_type in _VALID_ATTR_VALUE_TYPES
],
)
return False
Expand All @@ -356,12 +356,12 @@ def _is_valid_attribute_value(value: types.AttributeValue) -> bool:
)
return False

elif not isinstance(value, VALID_ATTR_VALUE_TYPES):
elif not isinstance(value, _VALID_ATTR_VALUE_TYPES):
logger.warning(
"Invalid type %s for attribute value. Expected one of %s or a "
"sequence of those types",
type(value).__name__,
[valid_type.__name__ for valid_type in VALID_ATTR_VALUE_TYPES],
[valid_type.__name__ for valid_type in _VALID_ATTR_VALUE_TYPES],
)
return False
return True
Expand Down Expand Up @@ -640,7 +640,7 @@ def __init__(
if links is None:
self._links = self._new_links()
else:
self._links = BoundedList.from_seq(SPAN_LINK_COUNT_LIMIT, links)
self._links = BoundedList.from_seq(_SPAN_LINK_COUNT_LIMIT, links)

def __repr__(self):
return '{}(name="{}", context={})'.format(
Expand All @@ -653,11 +653,11 @@ def _new_attributes():

@staticmethod
def _new_events():
return BoundedList(SPAN_EVENT_COUNT_LIMIT)
return BoundedList(_SPAN_EVENT_COUNT_LIMIT)

@staticmethod
def _new_links():
return BoundedList(SPAN_LINK_COUNT_LIMIT)
return BoundedList(_SPAN_LINK_COUNT_LIMIT)

def get_span_context(self):
return self._context
Expand Down Expand Up @@ -962,7 +962,7 @@ class TracerProvider(trace_api.TracerProvider):

def __init__(
self,
sampler: sampling.Sampler = TRACE_SAMPLER,
sampler: sampling.Sampler = _TRACE_SAMPLER,
resource: Resource = Resource.create({}),
shutdown_on_exit: bool = True,
active_span_processor: Union[
Expand Down
Loading

0 comments on commit c81fd5e

Please sign in to comment.