Skip to content

Commit

Permalink
Removed Opentelemetry dependancy
Browse files Browse the repository at this point in the history
  • Loading branch information
pboers1988 committed Mar 14, 2023
1 parent e7f9cb1 commit d6682e1
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 75 deletions.
2 changes: 1 addition & 1 deletion .bumpversion.cfg
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[bumpversion]
current_version = 1.2.4
current_version = 1.2.5
commit = False
tag = False
parse = (?P<major>\d+)\.(?P<minor>\d+)\.(?P<patch>\d+)(\-(?P<release>[a-z]+)(?P<build>\d+))?
Expand Down
2 changes: 1 addition & 1 deletion oauth2_lib/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,4 @@

"""This is the SURF Oauth2 module that interfaces with the oauth2 setup."""

__version__ = "1.2.4"
__version__ = "1.2.5"
89 changes: 18 additions & 71 deletions oauth2_lib/async_api_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,25 +10,15 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import contextlib
from asyncio import new_event_loop
from http import HTTPStatus
from typing import Any, Generator
from typing import Any

import structlog
import urllib3
from authlib.integrations.base_client import BaseOAuth
from opentelemetry import context
from opentelemetry.instrumentation.utils import http_status_to_status_code
from opentelemetry.instrumentation.version import __version__
from opentelemetry.propagate import inject
from opentelemetry.trace import Span, SpanKind, get_tracer
from opentelemetry.trace.status import Status

logger = structlog.get_logger(__name__)

_SUPPRESS_HTTP_INSTRUMENTATION_KEY = "suppress_http_instrumentation"


def is_api_exception(ex: Exception) -> bool:
"""Test for swagger-codegen ApiException.
Expand All @@ -47,27 +37,6 @@ def is_api_exception(ex: Exception) -> bool:
return ex.__class__.__name__ == "ApiException"


def _apply_response(span: Span, response: urllib3.response.HTTPResponse) -> None:
if not span.is_recording():
return
span.set_attribute("http.status_code", response.status)
span.set_attribute("http.status_text", response.reason)
span.set_status(Status(http_status_to_status_code(response.status)))


@contextlib.contextmanager
def _suppress_further_instrumentation() -> Generator:
token = context.attach(context.set_value(_SUPPRESS_HTTP_INSTRUMENTATION_KEY, True))
try:
yield
finally:
context.detach(token)


def _is_instrumentation_suppressed() -> bool:
return bool(context.get_value("suppress_instrumentation") or context.get_value(_SUPPRESS_HTTP_INSTRUMENTATION_KEY))


class AsyncAuthMixin:
"""Authorization mixin for swagger-codegen generated ApiClients.
Expand Down Expand Up @@ -160,44 +129,22 @@ def request( # type:ignore
):
headers = {} if headers is None else headers

span_attributes = {
"http.method": method,
"http.url": url,
}

with get_tracer(__name__, __version__).start_as_current_span(
f"External Api Call {self.__class__.__name__}", kind=SpanKind.CLIENT, attributes=span_attributes
) as span:
try:
try:
self.add_client_creds_token_header(headers)
return super().request( # type:ignore
method, url, query_params, headers, post_params, body, _preload_content, _request_timeout
)
except Exception as ex:
if is_api_exception(ex) and ex.status in (HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN): # type:ignore
logger.warning("Access Denied. Token expired? Retrying.", api_exception=str(ex))
loop = new_event_loop()
loop.run_until_complete(self.refresh_client_creds_token(force=True))
self.add_client_creds_token_header(headers)

if self._tracing_enabled and not _is_instrumentation_suppressed():
inject(type(headers).__setitem__, headers)

with _suppress_further_instrumentation():
response = super().request( # type:ignore
method, url, query_params, headers, post_params, body, _preload_content, _request_timeout
)
_apply_response(span, response)
return response
except Exception as ex:
if is_api_exception(ex) and ex.status in (HTTPStatus.UNAUTHORIZED, HTTPStatus.FORBIDDEN): # type:ignore
logger.warning("Access Denied. Token expired? Retrying.", api_exception=str(ex))
loop = new_event_loop()
loop.run_until_complete(self.refresh_client_creds_token(force=True))
self.add_client_creds_token_header(headers)

if self._tracing_enabled and not _is_instrumentation_suppressed():
inject(type(headers).__setitem__, headers)

with _suppress_further_instrumentation():
response = super().request( # type:ignore
method, url, query_params, headers, post_params, body, _preload_content, _request_timeout
)
_apply_response(span, response)
return response

else:
logger.exception("Could not call API.", client=self.__class__.__name__)
_apply_response(span, ex)
raise
return super().request( # type:ignore
method, url, query_params, headers, post_params, body, _preload_content, _request_timeout
)

else:
logger.exception("Could not call API.", client=self.__class__.__name__)
raise
3 changes: 1 addition & 2 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,10 @@ requires = [
"requests>=2.19.0",
"ruamel.yaml~=0.16.10",
"structlog>=20.2.0",
"fastapi>=0.65.1",
"fastapi>=0.90.1",
"httpx[http2]==0.23.0",
"authlib==1.0.1",
"pydantic>=1.8.0",
"opentelemetry-distro",
]
description-file = "README.md"
requires-python = ">3.8"
Expand Down

0 comments on commit d6682e1

Please sign in to comment.