Skip to content

Commit

Permalink
weakref, not id()
Browse files Browse the repository at this point in the history
  • Loading branch information
matthewgrossman committed Mar 14, 2023
1 parent df2085d commit fe1bd89
Showing 1 changed file with 10 additions and 10 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -243,6 +243,7 @@ def response_hook(span: Span, status: str, response_headers: List):
from time import time_ns
from timeit import default_timer
from typing import Collection
import weakref

import flask

Expand All @@ -265,18 +266,17 @@ def response_hook(span: Span, status: str, response_headers: List):
_ENVIRON_STARTTIME_KEY = "opentelemetry-flask.starttime_key"
_ENVIRON_SPAN_KEY = "opentelemetry-flask.span_key"
_ENVIRON_ACTIVATION_KEY = "opentelemetry-flask.activation_key"
_ENVIRON_REQCTX_ID_KEY = "opentelemetry-flask.reqctx_id_key"
_ENVIRON_REQCTX_REF_KEY = "opentelemetry-flask.reqctx_ref_key"
_ENVIRON_TOKEN = "opentelemetry-flask.token"

_excluded_urls_from_env = get_excluded_urls("FLASK")

if package_version.parse(flask.__version__) >= package_version.parse("2.2.0"):
def _request_ctx_id() -> int:
# return id(flask.globals.request_ctx)
return id(flask.globals.request_ctx._get_current_object())
def _request_ctx_ref() -> weakref.ReferenceType:
return weakref.ref(flask.globals.request_ctx._get_current_object())
else:
def _request_ctx_id() -> int:
return id(flask._request_ctx_stack.top)
def _request_ctx_ref() -> int:
return weakref.ref(flask._request_ctx_stack.top)

def get_default_span_name():
try:
Expand Down Expand Up @@ -406,7 +406,7 @@ def _before_request():
activation = trace.use_span(span, end_on_exit=True)
activation.__enter__() # pylint: disable=E1101
flask_request_environ[_ENVIRON_ACTIVATION_KEY] = activation
flask_request_environ[_ENVIRON_REQCTX_ID_KEY] = _request_ctx_id()
flask_request_environ[_ENVIRON_REQCTX_REF_KEY] = _request_ctx_ref()
flask_request_environ[_ENVIRON_SPAN_KEY] = span
flask_request_environ[_ENVIRON_TOKEN] = token

Expand Down Expand Up @@ -447,9 +447,9 @@ def _teardown_request(exc):

activation = flask.request.environ.get(_ENVIRON_ACTIVATION_KEY)

original_reqctx_id = flask.request.environ.get(_ENVIRON_REQCTX_ID_KEY)
current_reqctx_id = _request_ctx_id()
if not activation or original_reqctx_id != current_reqctx_id:
original_reqctx_ref = flask.request.environ.get(_ENVIRON_REQCTX_REF_KEY)
current_reqctx_ref = _request_ctx_ref()
if not activation or original_reqctx_ref != current_reqctx_ref:
# This request didn't start a span, maybe because it was created in
# a way that doesn't run `before_request`, like when it is created
# with `app.test_request_context`.
Expand Down

0 comments on commit fe1bd89

Please sign in to comment.