utils.py 66 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164
  1. import base64
  2. import contextvars
  3. import json
  4. import linecache
  5. import logging
  6. import math
  7. import os
  8. import copy
  9. import random
  10. import re
  11. import subprocess
  12. import sys
  13. import threading
  14. import time
  15. from collections import namedtuple
  16. from contextlib import contextmanager
  17. from datetime import datetime, timezone
  18. from decimal import Decimal
  19. from functools import partial, partialmethod, wraps
  20. from numbers import Real
  21. from urllib.parse import parse_qs, unquote, urlencode, urlsplit, urlunsplit
  22. try:
  23. # Python 3.11
  24. from builtins import BaseExceptionGroup
  25. except ImportError:
  26. # Python 3.10 and below
  27. BaseExceptionGroup = None # type: ignore
  28. from typing import TYPE_CHECKING
  29. import sentry_sdk
  30. from sentry_sdk._compat import PY37
  31. from sentry_sdk._types import SENSITIVE_DATA_SUBSTITUTE, Annotated, AnnotatedValue
  32. from sentry_sdk.consts import (
  33. DEFAULT_ADD_FULL_STACK,
  34. DEFAULT_MAX_STACK_FRAMES,
  35. DEFAULT_MAX_VALUE_LENGTH,
  36. EndpointType,
  37. )
  38. if TYPE_CHECKING:
  39. from types import FrameType, TracebackType
  40. from typing import (
  41. Any,
  42. Callable,
  43. ContextManager,
  44. Dict,
  45. Generator,
  46. Iterator,
  47. List,
  48. NoReturn,
  49. Optional,
  50. ParamSpec,
  51. Set,
  52. Tuple,
  53. Type,
  54. TypeVar,
  55. Union,
  56. cast,
  57. overload,
  58. )
  59. from gevent.hub import Hub
  60. from sentry_sdk._types import (
  61. AttributeValue,
  62. SerializedAttributeValue,
  63. Event,
  64. ExcInfo,
  65. Hint,
  66. Log,
  67. Metric,
  68. )
  69. P = ParamSpec("P")
  70. R = TypeVar("R")
  71. epoch = datetime(1970, 1, 1)
  72. # The logger is created here but initialized in the debug support module
  73. logger = logging.getLogger("sentry_sdk.errors")
  74. _installed_modules = None
  75. _is_sentry_internal_task = contextvars.ContextVar(
  76. "is_sentry_internal_task", default=False
  77. )
  78. def is_internal_task() -> bool:
  79. return _is_sentry_internal_task.get()
  80. @contextmanager
  81. def mark_sentry_task_internal() -> "Generator[None, None, None]":
  82. """Context manager to mark a task as Sentry internal."""
  83. token = _is_sentry_internal_task.set(True)
  84. try:
  85. yield
  86. finally:
  87. _is_sentry_internal_task.reset(token)
  88. BASE64_ALPHABET = re.compile(r"^[a-zA-Z0-9/+=]*$")
  89. FALSY_ENV_VALUES = frozenset(("false", "f", "n", "no", "off", "0"))
  90. TRUTHY_ENV_VALUES = frozenset(("true", "t", "y", "yes", "on", "1"))
  91. MAX_STACK_FRAMES = 2000
  92. """Maximum number of stack frames to send to Sentry.
  93. If we have more than this number of stack frames, we will stop processing
  94. the stacktrace to avoid getting stuck in a long-lasting loop. This value
  95. exceeds the default sys.getrecursionlimit() of 1000, so users will only
  96. be affected by this limit if they have a custom recursion limit.
  97. """
  98. def env_to_bool(value: "Any", *, strict: "Optional[bool]" = False) -> "bool | None":
  99. """Casts an ENV variable value to boolean using the constants defined above.
  100. In strict mode, it may return None if the value doesn't match any of the predefined values.
  101. """
  102. normalized = str(value).lower() if value is not None else None
  103. if normalized in FALSY_ENV_VALUES:
  104. return False
  105. if normalized in TRUTHY_ENV_VALUES:
  106. return True
  107. return None if strict else bool(value)
  108. def json_dumps(data: "Any") -> bytes:
  109. """Serialize data into a compact JSON representation encoded as UTF-8."""
  110. return json.dumps(data, allow_nan=False, separators=(",", ":")).encode("utf-8")
  111. def get_git_revision() -> "Optional[str]":
  112. try:
  113. with open(os.path.devnull, "w+") as null:
  114. # prevent command prompt windows from popping up on windows
  115. startupinfo = None
  116. if sys.platform == "win32" or sys.platform == "cygwin":
  117. startupinfo = subprocess.STARTUPINFO()
  118. startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW
  119. revision = (
  120. subprocess.Popen(
  121. ["git", "rev-parse", "HEAD"],
  122. startupinfo=startupinfo,
  123. stdout=subprocess.PIPE,
  124. stderr=null,
  125. stdin=null,
  126. )
  127. .communicate()[0]
  128. .strip()
  129. .decode("utf-8")
  130. )
  131. except (OSError, IOError, FileNotFoundError):
  132. return None
  133. return revision
  134. def get_default_release() -> "Optional[str]":
  135. """Try to guess a default release."""
  136. release = os.environ.get("SENTRY_RELEASE")
  137. if release:
  138. return release
  139. release = get_git_revision()
  140. if release:
  141. return release
  142. for var in (
  143. "HEROKU_BUILD_COMMIT",
  144. "HEROKU_SLUG_COMMIT", # deprecated by Heroku, kept for backward compatibility
  145. "SOURCE_VERSION",
  146. "CODEBUILD_RESOLVED_SOURCE_VERSION",
  147. "CIRCLE_SHA1",
  148. "GAE_DEPLOYMENT_ID",
  149. "K_REVISION",
  150. ):
  151. release = os.environ.get(var)
  152. if release:
  153. return release
  154. return None
  155. def get_sdk_name(installed_integrations: "List[str]") -> str:
  156. """Return the SDK name including the name of the used web framework."""
  157. # Note: I can not use for example sentry_sdk.integrations.django.DjangoIntegration.identifier
  158. # here because if django is not installed the integration is not accessible.
  159. framework_integrations = [
  160. "django",
  161. "flask",
  162. "fastapi",
  163. "bottle",
  164. "falcon",
  165. "quart",
  166. "sanic",
  167. "starlette",
  168. "litestar",
  169. "starlite",
  170. "chalice",
  171. "serverless",
  172. "pyramid",
  173. "tornado",
  174. "aiohttp",
  175. "aws_lambda",
  176. "gcp",
  177. "beam",
  178. "asgi",
  179. "wsgi",
  180. ]
  181. for integration in framework_integrations:
  182. if integration in installed_integrations:
  183. return "sentry.python.{}".format(integration)
  184. return "sentry.python"
  185. class CaptureInternalException:
  186. __slots__ = ()
  187. def __enter__(self) -> "ContextManager[Any]":
  188. return self
  189. def __exit__(
  190. self,
  191. ty: "Optional[Type[BaseException]]",
  192. value: "Optional[BaseException]",
  193. tb: "Optional[TracebackType]",
  194. ) -> bool:
  195. if ty is not None and value is not None:
  196. capture_internal_exception((ty, value, tb))
  197. return True
  198. _CAPTURE_INTERNAL_EXCEPTION = CaptureInternalException()
  199. def capture_internal_exceptions() -> "ContextManager[Any]":
  200. return _CAPTURE_INTERNAL_EXCEPTION
  201. def capture_internal_exception(exc_info: "ExcInfo") -> None:
  202. """
  203. Capture an exception that is likely caused by a bug in the SDK
  204. itself.
  205. These exceptions do not end up in Sentry and are just logged instead.
  206. """
  207. if sentry_sdk.get_client().is_active():
  208. logger.error("Internal error in sentry_sdk", exc_info=exc_info)
  209. def to_timestamp(value: "datetime") -> float:
  210. return (value - epoch).total_seconds()
  211. def format_timestamp(value: "datetime") -> str:
  212. """Formats a timestamp in RFC 3339 format.
  213. Any datetime objects with a non-UTC timezone are converted to UTC, so that all timestamps are formatted in UTC.
  214. """
  215. utctime = value.astimezone(timezone.utc)
  216. # We use this custom formatting rather than isoformat for backwards compatibility (we have used this format for
  217. # several years now), and isoformat is slightly different.
  218. return utctime.strftime("%Y-%m-%dT%H:%M:%S.%fZ")
  219. ISO_TZ_SEPARATORS = frozenset(("+", "-"))
  220. def datetime_from_isoformat(value: str) -> "datetime":
  221. try:
  222. result = datetime.fromisoformat(value)
  223. except (AttributeError, ValueError):
  224. # py 3.6
  225. timestamp_format = (
  226. "%Y-%m-%dT%H:%M:%S.%f" if "." in value else "%Y-%m-%dT%H:%M:%S"
  227. )
  228. if value.endswith("Z"):
  229. value = value[:-1] + "+0000"
  230. if value[-6] in ISO_TZ_SEPARATORS:
  231. timestamp_format += "%z"
  232. value = value[:-3] + value[-2:]
  233. elif value[-5] in ISO_TZ_SEPARATORS:
  234. timestamp_format += "%z"
  235. result = datetime.strptime(value, timestamp_format)
  236. return result.astimezone(timezone.utc)
  237. def event_hint_with_exc_info(
  238. exc_info: "Optional[ExcInfo]" = None,
  239. ) -> "Dict[str, Optional[ExcInfo]]":
  240. """Creates a hint with the exc info filled in."""
  241. if exc_info is None:
  242. exc_info = sys.exc_info()
  243. else:
  244. exc_info = exc_info_from_error(exc_info)
  245. if exc_info[0] is None:
  246. exc_info = None
  247. return {"exc_info": exc_info}
  248. class BadDsn(ValueError):
  249. """Raised on invalid DSNs."""
  250. class Dsn:
  251. """Represents a DSN."""
  252. ORG_ID_REGEX = re.compile(r"^o(\d+)\.")
  253. def __init__(
  254. self, value: "Union[Dsn, str]", org_id: "Optional[str]" = None
  255. ) -> None:
  256. if isinstance(value, Dsn):
  257. self.__dict__ = dict(value.__dict__)
  258. return
  259. parts = urlsplit(str(value))
  260. if parts.scheme not in ("http", "https"):
  261. raise BadDsn("Unsupported scheme %r" % parts.scheme)
  262. self.scheme = parts.scheme
  263. if parts.hostname is None:
  264. raise BadDsn("Missing hostname")
  265. self.host = parts.hostname
  266. if org_id is not None:
  267. self.org_id: "Optional[str]" = org_id
  268. else:
  269. org_id_match = Dsn.ORG_ID_REGEX.match(self.host)
  270. self.org_id = org_id_match.group(1) if org_id_match else None
  271. if parts.port is None:
  272. self.port: int = self.scheme == "https" and 443 or 80
  273. else:
  274. self.port = parts.port
  275. if not parts.username:
  276. raise BadDsn("Missing public key")
  277. self.public_key = parts.username
  278. self.secret_key = parts.password
  279. path = parts.path.rsplit("/", 1)
  280. try:
  281. self.project_id = str(int(path.pop()))
  282. except (ValueError, TypeError):
  283. raise BadDsn("Invalid project in DSN (%r)" % (parts.path or "")[1:])
  284. self.path = "/".join(path) + "/"
  285. @property
  286. def netloc(self) -> str:
  287. """The netloc part of a DSN."""
  288. rv = self.host
  289. if (self.scheme, self.port) not in (("http", 80), ("https", 443)):
  290. rv = "%s:%s" % (rv, self.port)
  291. return rv
  292. def to_auth(self, client: "Optional[Any]" = None) -> "Auth":
  293. """Returns the auth info object for this dsn."""
  294. return Auth(
  295. scheme=self.scheme,
  296. host=self.netloc,
  297. path=self.path,
  298. project_id=self.project_id,
  299. public_key=self.public_key,
  300. secret_key=self.secret_key,
  301. client=client,
  302. )
  303. def __str__(self) -> str:
  304. return "%s://%s%s@%s%s%s" % (
  305. self.scheme,
  306. self.public_key,
  307. self.secret_key and "@" + self.secret_key or "",
  308. self.netloc,
  309. self.path,
  310. self.project_id,
  311. )
  312. class Auth:
  313. """Helper object that represents the auth info."""
  314. def __init__(
  315. self,
  316. scheme: str,
  317. host: str,
  318. project_id: str,
  319. public_key: str,
  320. secret_key: "Optional[str]" = None,
  321. version: int = 7,
  322. client: "Optional[Any]" = None,
  323. path: str = "/",
  324. ) -> None:
  325. self.scheme = scheme
  326. self.host = host
  327. self.path = path
  328. self.project_id = project_id
  329. self.public_key = public_key
  330. self.secret_key = secret_key
  331. self.version = version
  332. self.client = client
  333. def get_api_url(
  334. self,
  335. type: "EndpointType" = EndpointType.ENVELOPE,
  336. ) -> str:
  337. """Returns the API url for storing events."""
  338. return "%s://%s%sapi/%s/%s/" % (
  339. self.scheme,
  340. self.host,
  341. self.path,
  342. self.project_id,
  343. type.value,
  344. )
  345. def to_header(self) -> str:
  346. """Returns the auth header a string."""
  347. rv = [("sentry_key", self.public_key), ("sentry_version", self.version)]
  348. if self.client is not None:
  349. rv.append(("sentry_client", self.client))
  350. if self.secret_key is not None:
  351. rv.append(("sentry_secret", self.secret_key))
  352. return "Sentry " + ", ".join("%s=%s" % (key, value) for key, value in rv)
  353. def get_type_name(cls: "Optional[type]") -> "Optional[str]":
  354. return getattr(cls, "__qualname__", None) or getattr(cls, "__name__", None)
  355. def get_type_module(cls: "Optional[type]") -> "Optional[str]":
  356. mod = getattr(cls, "__module__", None)
  357. if mod not in (None, "builtins", "__builtins__"):
  358. return mod
  359. return None
  360. def should_hide_frame(frame: "FrameType") -> bool:
  361. try:
  362. mod = frame.f_globals["__name__"]
  363. if mod.startswith("sentry_sdk."):
  364. return True
  365. except (AttributeError, KeyError):
  366. pass
  367. for flag_name in "__traceback_hide__", "__tracebackhide__":
  368. try:
  369. if frame.f_locals[flag_name]:
  370. return True
  371. except Exception:
  372. pass
  373. return False
  374. def iter_stacks(tb: "Optional[TracebackType]") -> "Iterator[TracebackType]":
  375. tb_: "Optional[TracebackType]" = tb
  376. while tb_ is not None:
  377. if not should_hide_frame(tb_.tb_frame):
  378. yield tb_
  379. tb_ = tb_.tb_next
  380. def get_lines_from_file(
  381. filename: str,
  382. lineno: int,
  383. max_length: "Optional[int]" = None,
  384. loader: "Optional[Any]" = None,
  385. module: "Optional[str]" = None,
  386. ) -> "Tuple[List[Annotated[str]], Optional[Annotated[str]], List[Annotated[str]]]":
  387. context_lines = 5
  388. source = None
  389. if loader is not None and hasattr(loader, "get_source"):
  390. try:
  391. source_str: "Optional[str]" = loader.get_source(module)
  392. except (ImportError, IOError):
  393. source_str = None
  394. if source_str is not None:
  395. source = source_str.splitlines()
  396. if source is None:
  397. try:
  398. source = linecache.getlines(filename)
  399. except (OSError, IOError):
  400. return [], None, []
  401. if not source:
  402. return [], None, []
  403. lower_bound = max(0, lineno - context_lines)
  404. upper_bound = min(lineno + 1 + context_lines, len(source))
  405. try:
  406. pre_context = [
  407. strip_string(line.strip("\r\n"), max_length=max_length)
  408. for line in source[lower_bound:lineno]
  409. ]
  410. context_line = strip_string(source[lineno].strip("\r\n"), max_length=max_length)
  411. post_context = [
  412. strip_string(line.strip("\r\n"), max_length=max_length)
  413. for line in source[(lineno + 1) : upper_bound]
  414. ]
  415. return pre_context, context_line, post_context
  416. except IndexError:
  417. # the file may have changed since it was loaded into memory
  418. return [], None, []
  419. def get_source_context(
  420. frame: "FrameType",
  421. tb_lineno: "Optional[int]",
  422. max_value_length: "Optional[int]" = None,
  423. ) -> "Tuple[List[Annotated[str]], Optional[Annotated[str]], List[Annotated[str]]]":
  424. try:
  425. abs_path: "Optional[str]" = frame.f_code.co_filename
  426. except Exception:
  427. abs_path = None
  428. try:
  429. module = frame.f_globals["__name__"]
  430. except Exception:
  431. return [], None, []
  432. try:
  433. loader = frame.f_globals["__loader__"]
  434. except Exception:
  435. loader = None
  436. if tb_lineno is not None and abs_path:
  437. lineno = tb_lineno - 1
  438. return get_lines_from_file(
  439. abs_path, lineno, max_value_length, loader=loader, module=module
  440. )
  441. return [], None, []
  442. def safe_str(value: "Any") -> str:
  443. try:
  444. return str(value)
  445. except Exception:
  446. return safe_repr(value)
  447. def safe_repr(value: "Any") -> str:
  448. try:
  449. return repr(value)
  450. except Exception:
  451. return "<broken repr>"
  452. def filename_for_module(
  453. module: "Optional[str]", abs_path: "Optional[str]"
  454. ) -> "Optional[str]":
  455. if not abs_path or not module:
  456. return abs_path
  457. try:
  458. if abs_path.endswith(".pyc"):
  459. abs_path = abs_path[:-1]
  460. base_module = module.split(".", 1)[0]
  461. if base_module == module:
  462. return os.path.basename(abs_path)
  463. base_module_path = sys.modules[base_module].__file__
  464. if not base_module_path:
  465. return abs_path
  466. return abs_path.split(base_module_path.rsplit(os.sep, 2)[0], 1)[-1].lstrip(
  467. os.sep
  468. )
  469. except Exception:
  470. return abs_path
  471. def serialize_frame(
  472. frame: "FrameType",
  473. tb_lineno: "Optional[int]" = None,
  474. include_local_variables: bool = True,
  475. include_source_context: bool = True,
  476. max_value_length: "Optional[int]" = None,
  477. custom_repr: "Optional[Callable[..., Optional[str]]]" = None,
  478. ) -> "Dict[str, Any]":
  479. f_code = getattr(frame, "f_code", None)
  480. if not f_code:
  481. abs_path = None
  482. function = None
  483. else:
  484. abs_path = frame.f_code.co_filename
  485. function = frame.f_code.co_name
  486. try:
  487. module = frame.f_globals["__name__"]
  488. except Exception:
  489. module = None
  490. if tb_lineno is None:
  491. tb_lineno = frame.f_lineno
  492. try:
  493. os_abs_path = os.path.abspath(abs_path) if abs_path else None
  494. except Exception:
  495. os_abs_path = None
  496. rv: "Dict[str, Any]" = {
  497. "filename": filename_for_module(module, abs_path) or None,
  498. "abs_path": os_abs_path,
  499. "function": function or "<unknown>",
  500. "module": module,
  501. "lineno": tb_lineno,
  502. }
  503. if include_source_context:
  504. rv["pre_context"], rv["context_line"], rv["post_context"] = get_source_context(
  505. frame, tb_lineno, max_value_length
  506. )
  507. if include_local_variables:
  508. from sentry_sdk.serializer import serialize
  509. rv["vars"] = serialize(
  510. dict(frame.f_locals), is_vars=True, custom_repr=custom_repr
  511. )
  512. return rv
  513. def current_stacktrace(
  514. include_local_variables: bool = True,
  515. include_source_context: bool = True,
  516. max_value_length: "Optional[int]" = None,
  517. ) -> "Dict[str, Any]":
  518. __tracebackhide__ = True
  519. frames = []
  520. f: "Optional[FrameType]" = sys._getframe()
  521. while f is not None:
  522. if not should_hide_frame(f):
  523. frames.append(
  524. serialize_frame(
  525. f,
  526. include_local_variables=include_local_variables,
  527. include_source_context=include_source_context,
  528. max_value_length=max_value_length,
  529. )
  530. )
  531. f = f.f_back
  532. frames.reverse()
  533. return {"frames": frames}
  534. def get_errno(exc_value: BaseException) -> "Optional[Any]":
  535. return getattr(exc_value, "errno", None)
  536. def get_error_message(exc_value: "Optional[BaseException]") -> str:
  537. message: str = safe_str(
  538. getattr(exc_value, "message", "")
  539. or getattr(exc_value, "detail", "")
  540. or safe_str(exc_value)
  541. )
  542. # __notes__ should be a list of strings when notes are added
  543. # via add_note, but can be anything else if __notes__ is set
  544. # directly. We only support strings in __notes__, since that
  545. # is the correct use.
  546. notes: object = getattr(exc_value, "__notes__", None)
  547. if isinstance(notes, list) and len(notes) > 0:
  548. message += "\n" + "\n".join(note for note in notes if isinstance(note, str))
  549. return message
  550. def single_exception_from_error_tuple(
  551. exc_type: "Optional[type]",
  552. exc_value: "Optional[BaseException]",
  553. tb: "Optional[TracebackType]",
  554. client_options: "Optional[Dict[str, Any]]" = None,
  555. mechanism: "Optional[Dict[str, Any]]" = None,
  556. exception_id: "Optional[int]" = None,
  557. parent_id: "Optional[int]" = None,
  558. source: "Optional[str]" = None,
  559. full_stack: "Optional[list[dict[str, Any]]]" = None,
  560. ) -> "Dict[str, Any]":
  561. """
  562. Creates a dict that goes into the events `exception.values` list and is ingestible by Sentry.
  563. See the Exception Interface documentation for more details:
  564. https://develop.sentry.dev/sdk/event-payloads/exception/
  565. """
  566. exception_value: "Dict[str, Any]" = {}
  567. exception_value["mechanism"] = (
  568. mechanism.copy() if mechanism else {"type": "generic", "handled": True}
  569. )
  570. if exception_id is not None:
  571. exception_value["mechanism"]["exception_id"] = exception_id
  572. if exc_value is not None:
  573. errno = get_errno(exc_value)
  574. else:
  575. errno = None
  576. if errno is not None:
  577. exception_value["mechanism"].setdefault("meta", {}).setdefault(
  578. "errno", {}
  579. ).setdefault("number", errno)
  580. if source is not None:
  581. exception_value["mechanism"]["source"] = source
  582. is_root_exception = exception_id == 0
  583. if not is_root_exception and parent_id is not None:
  584. exception_value["mechanism"]["parent_id"] = parent_id
  585. exception_value["mechanism"]["type"] = "chained"
  586. if is_root_exception and "type" not in exception_value["mechanism"]:
  587. exception_value["mechanism"]["type"] = "generic"
  588. is_exception_group = BaseExceptionGroup is not None and isinstance(
  589. exc_value, BaseExceptionGroup
  590. )
  591. if is_exception_group:
  592. exception_value["mechanism"]["is_exception_group"] = True
  593. exception_value["module"] = get_type_module(exc_type)
  594. exception_value["type"] = get_type_name(exc_type)
  595. exception_value["value"] = get_error_message(exc_value)
  596. if client_options is None:
  597. include_local_variables = True
  598. include_source_context = True
  599. max_value_length = DEFAULT_MAX_VALUE_LENGTH # fallback
  600. custom_repr = None
  601. else:
  602. include_local_variables = client_options["include_local_variables"]
  603. include_source_context = client_options["include_source_context"]
  604. max_value_length = client_options["max_value_length"]
  605. custom_repr = client_options.get("custom_repr")
  606. frames: "List[Dict[str, Any]]" = [
  607. serialize_frame(
  608. tb.tb_frame,
  609. tb_lineno=tb.tb_lineno,
  610. include_local_variables=include_local_variables,
  611. include_source_context=include_source_context,
  612. max_value_length=max_value_length,
  613. custom_repr=custom_repr,
  614. )
  615. # Process at most MAX_STACK_FRAMES + 1 frames, to avoid hanging on
  616. # processing a super-long stacktrace.
  617. for tb, _ in zip(iter_stacks(tb), range(MAX_STACK_FRAMES + 1))
  618. ]
  619. if len(frames) > MAX_STACK_FRAMES:
  620. # If we have more frames than the limit, we remove the stacktrace completely.
  621. # We don't trim the stacktrace here because we have not processed the whole
  622. # thing (see above, we stop at MAX_STACK_FRAMES + 1). Normally, Relay would
  623. # intelligently trim by removing frames in the middle of the stacktrace, but
  624. # since we don't have the whole stacktrace, we can't do that. Instead, we
  625. # drop the entire stacktrace.
  626. exception_value["stacktrace"] = AnnotatedValue.removed_because_over_size_limit(
  627. value=None
  628. )
  629. elif frames:
  630. if not full_stack:
  631. new_frames = frames
  632. else:
  633. new_frames = merge_stack_frames(frames, full_stack, client_options)
  634. exception_value["stacktrace"] = {"frames": new_frames}
  635. return exception_value
  636. HAS_CHAINED_EXCEPTIONS = hasattr(Exception, "__suppress_context__")
  637. if HAS_CHAINED_EXCEPTIONS:
  638. def walk_exception_chain(exc_info: "ExcInfo") -> "Iterator[ExcInfo]":
  639. exc_type, exc_value, tb = exc_info
  640. seen_exceptions = []
  641. seen_exception_ids: "Set[int]" = set()
  642. while (
  643. exc_type is not None
  644. and exc_value is not None
  645. and id(exc_value) not in seen_exception_ids
  646. ):
  647. yield exc_type, exc_value, tb
  648. # Avoid hashing random types we don't know anything
  649. # about. Use the list to keep a ref so that the `id` is
  650. # not used for another object.
  651. seen_exceptions.append(exc_value)
  652. seen_exception_ids.add(id(exc_value))
  653. if exc_value.__suppress_context__:
  654. cause = exc_value.__cause__
  655. else:
  656. cause = exc_value.__context__
  657. if cause is None:
  658. break
  659. exc_type = type(cause)
  660. exc_value = cause
  661. tb = getattr(cause, "__traceback__", None)
  662. else:
  663. def walk_exception_chain(exc_info: "ExcInfo") -> "Iterator[ExcInfo]":
  664. yield exc_info
  665. def exceptions_from_error(
  666. exc_type: "Optional[type]",
  667. exc_value: "Optional[BaseException]",
  668. tb: "Optional[TracebackType]",
  669. client_options: "Optional[Dict[str, Any]]" = None,
  670. mechanism: "Optional[Dict[str, Any]]" = None,
  671. exception_id: int = 0,
  672. parent_id: int = 0,
  673. source: "Optional[str]" = None,
  674. full_stack: "Optional[list[dict[str, Any]]]" = None,
  675. seen_exceptions: "Optional[list[BaseException]]" = None,
  676. seen_exception_ids: "Optional[Set[int]]" = None,
  677. ) -> "Tuple[int, List[Dict[str, Any]]]":
  678. """
  679. Creates the list of exceptions.
  680. This can include chained exceptions and exceptions from an ExceptionGroup.
  681. See the Exception Interface documentation for more details:
  682. https://develop.sentry.dev/sdk/event-payloads/exception/
  683. Args:
  684. exception_id (int):
  685. Sequential counter for assigning ``mechanism.exception_id``
  686. to each processed exception. Is NOT the result of calling `id()` on the exception itself.
  687. parent_id (int):
  688. The ``mechanism.exception_id`` of the parent exception.
  689. Written into ``mechanism.parent_id`` in the event payload so Sentry can
  690. reconstruct the exception tree.
  691. Not to be confused with ``seen_exception_ids``, which tracks Python ``id()``
  692. values for cycle detection.
  693. """
  694. if seen_exception_ids is None:
  695. seen_exception_ids = set()
  696. if seen_exceptions is None:
  697. seen_exceptions = []
  698. if exc_value is not None and id(exc_value) in seen_exception_ids:
  699. return (exception_id, [])
  700. if exc_value is not None:
  701. seen_exceptions.append(exc_value)
  702. seen_exception_ids.add(id(exc_value))
  703. parent = single_exception_from_error_tuple(
  704. exc_type=exc_type,
  705. exc_value=exc_value,
  706. tb=tb,
  707. client_options=client_options,
  708. mechanism=mechanism,
  709. exception_id=exception_id,
  710. parent_id=parent_id,
  711. source=source,
  712. full_stack=full_stack,
  713. )
  714. exceptions = [parent]
  715. parent_id = exception_id
  716. exception_id += 1
  717. should_supress_context = (
  718. hasattr(exc_value, "__suppress_context__") and exc_value.__suppress_context__ # type: ignore
  719. )
  720. if should_supress_context:
  721. # Add direct cause.
  722. # The field `__cause__` is set when raised with the exception (using the `from` keyword).
  723. exception_has_cause = (
  724. exc_value
  725. and hasattr(exc_value, "__cause__")
  726. and exc_value.__cause__ is not None
  727. )
  728. if exception_has_cause:
  729. cause = exc_value.__cause__ # type: ignore
  730. (exception_id, child_exceptions) = exceptions_from_error(
  731. exc_type=type(cause),
  732. exc_value=cause,
  733. tb=getattr(cause, "__traceback__", None),
  734. client_options=client_options,
  735. mechanism=mechanism,
  736. exception_id=exception_id,
  737. source="__cause__",
  738. full_stack=full_stack,
  739. seen_exceptions=seen_exceptions,
  740. seen_exception_ids=seen_exception_ids,
  741. )
  742. exceptions.extend(child_exceptions)
  743. else:
  744. # Add indirect cause.
  745. # The field `__context__` is assigned if another exception occurs while handling the exception.
  746. exception_has_content = (
  747. exc_value
  748. and hasattr(exc_value, "__context__")
  749. and exc_value.__context__ is not None
  750. )
  751. if exception_has_content:
  752. context = exc_value.__context__ # type: ignore
  753. (exception_id, child_exceptions) = exceptions_from_error(
  754. exc_type=type(context),
  755. exc_value=context,
  756. tb=getattr(context, "__traceback__", None),
  757. client_options=client_options,
  758. mechanism=mechanism,
  759. exception_id=exception_id,
  760. source="__context__",
  761. full_stack=full_stack,
  762. seen_exceptions=seen_exceptions,
  763. seen_exception_ids=seen_exception_ids,
  764. )
  765. exceptions.extend(child_exceptions)
  766. # Add exceptions from an ExceptionGroup.
  767. is_exception_group = exc_value and hasattr(exc_value, "exceptions")
  768. if is_exception_group:
  769. for idx, e in enumerate(exc_value.exceptions): # type: ignore
  770. (exception_id, child_exceptions) = exceptions_from_error(
  771. exc_type=type(e),
  772. exc_value=e,
  773. tb=getattr(e, "__traceback__", None),
  774. client_options=client_options,
  775. mechanism=mechanism,
  776. exception_id=exception_id,
  777. parent_id=parent_id,
  778. source="exceptions[%s]" % idx,
  779. full_stack=full_stack,
  780. seen_exceptions=seen_exceptions,
  781. seen_exception_ids=seen_exception_ids,
  782. )
  783. exceptions.extend(child_exceptions)
  784. return (exception_id, exceptions)
  785. def exceptions_from_error_tuple(
  786. exc_info: "ExcInfo",
  787. client_options: "Optional[Dict[str, Any]]" = None,
  788. mechanism: "Optional[Dict[str, Any]]" = None,
  789. full_stack: "Optional[list[dict[str, Any]]]" = None,
  790. ) -> "List[Dict[str, Any]]":
  791. exc_type, exc_value, tb = exc_info
  792. is_exception_group = BaseExceptionGroup is not None and isinstance(
  793. exc_value, BaseExceptionGroup
  794. )
  795. if is_exception_group:
  796. (_, exceptions) = exceptions_from_error(
  797. exc_type=exc_type,
  798. exc_value=exc_value,
  799. tb=tb,
  800. client_options=client_options,
  801. mechanism=mechanism,
  802. exception_id=0,
  803. parent_id=0,
  804. full_stack=full_stack,
  805. )
  806. else:
  807. exceptions = []
  808. for exc_type, exc_value, tb in walk_exception_chain(exc_info):
  809. exceptions.append(
  810. single_exception_from_error_tuple(
  811. exc_type=exc_type,
  812. exc_value=exc_value,
  813. tb=tb,
  814. client_options=client_options,
  815. mechanism=mechanism,
  816. full_stack=full_stack,
  817. )
  818. )
  819. exceptions.reverse()
  820. return exceptions
  821. def to_string(value: str) -> str:
  822. try:
  823. return str(value)
  824. except UnicodeDecodeError:
  825. return repr(value)[1:-1]
  826. def iter_event_stacktraces(event: "Event") -> "Iterator[Annotated[Dict[str, Any]]]":
  827. if "stacktrace" in event:
  828. yield event["stacktrace"]
  829. if "threads" in event:
  830. for thread in event["threads"].get("values") or ():
  831. if "stacktrace" in thread:
  832. yield thread["stacktrace"]
  833. if "exception" in event:
  834. for exception in event["exception"].get("values") or ():
  835. if isinstance(exception, dict) and "stacktrace" in exception:
  836. yield exception["stacktrace"]
  837. def iter_event_frames(event: "Event") -> "Iterator[Dict[str, Any]]":
  838. for stacktrace in iter_event_stacktraces(event):
  839. if isinstance(stacktrace, AnnotatedValue):
  840. stacktrace = stacktrace.value or {}
  841. for frame in stacktrace.get("frames") or ():
  842. yield frame
  843. def handle_in_app(
  844. event: "Event",
  845. in_app_exclude: "Optional[List[str]]" = None,
  846. in_app_include: "Optional[List[str]]" = None,
  847. project_root: "Optional[str]" = None,
  848. ) -> "Event":
  849. for stacktrace in iter_event_stacktraces(event):
  850. if isinstance(stacktrace, AnnotatedValue):
  851. stacktrace = stacktrace.value or {}
  852. set_in_app_in_frames(
  853. stacktrace.get("frames"),
  854. in_app_exclude=in_app_exclude,
  855. in_app_include=in_app_include,
  856. project_root=project_root,
  857. )
  858. return event
  859. def set_in_app_in_frames(
  860. frames: "Any",
  861. in_app_exclude: "Optional[List[str]]",
  862. in_app_include: "Optional[List[str]]",
  863. project_root: "Optional[str]" = None,
  864. ) -> "Optional[Any]":
  865. if not frames:
  866. return None
  867. for frame in frames:
  868. # if frame has already been marked as in_app, skip it
  869. current_in_app = frame.get("in_app")
  870. if current_in_app is not None:
  871. continue
  872. module = frame.get("module")
  873. # check if module in frame is in the list of modules to include
  874. if _module_in_list(module, in_app_include):
  875. frame["in_app"] = True
  876. continue
  877. # check if module in frame is in the list of modules to exclude
  878. if _module_in_list(module, in_app_exclude):
  879. frame["in_app"] = False
  880. continue
  881. # if frame has no abs_path, skip further checks
  882. abs_path = frame.get("abs_path")
  883. if abs_path is None:
  884. continue
  885. if _is_external_source(abs_path):
  886. frame["in_app"] = False
  887. continue
  888. if _is_in_project_root(abs_path, project_root):
  889. frame["in_app"] = True
  890. continue
  891. return frames
  892. def exc_info_from_error(error: "Union[BaseException, ExcInfo]") -> "ExcInfo":
  893. if isinstance(error, tuple) and len(error) == 3:
  894. exc_type, exc_value, tb = error
  895. elif isinstance(error, BaseException):
  896. tb = getattr(error, "__traceback__", None)
  897. if tb is not None:
  898. exc_type = type(error)
  899. exc_value = error
  900. else:
  901. exc_type, exc_value, tb = sys.exc_info()
  902. if exc_value is not error:
  903. tb = None
  904. exc_value = error
  905. exc_type = type(error)
  906. else:
  907. raise ValueError("Expected Exception object to report, got %s!" % type(error))
  908. exc_info = (exc_type, exc_value, tb)
  909. if TYPE_CHECKING:
  910. # This cast is safe because exc_type and exc_value are either both
  911. # None or both not None.
  912. exc_info = cast(ExcInfo, exc_info)
  913. return exc_info
  914. def merge_stack_frames(
  915. frames: "List[Dict[str, Any]]",
  916. full_stack: "List[Dict[str, Any]]",
  917. client_options: "Optional[Dict[str, Any]]",
  918. ) -> "List[Dict[str, Any]]":
  919. """
  920. Add the missing frames from full_stack to frames and return the merged list.
  921. """
  922. frame_ids = {
  923. (
  924. frame["abs_path"],
  925. frame["context_line"],
  926. frame["lineno"],
  927. frame["function"],
  928. )
  929. for frame in frames
  930. }
  931. new_frames = [
  932. stackframe
  933. for stackframe in full_stack
  934. if (
  935. stackframe["abs_path"],
  936. stackframe["context_line"],
  937. stackframe["lineno"],
  938. stackframe["function"],
  939. )
  940. not in frame_ids
  941. ]
  942. new_frames.extend(frames)
  943. # Limit the number of frames
  944. max_stack_frames = (
  945. client_options.get("max_stack_frames", DEFAULT_MAX_STACK_FRAMES)
  946. if client_options
  947. else None
  948. )
  949. if max_stack_frames is not None:
  950. new_frames = new_frames[len(new_frames) - max_stack_frames :]
  951. return new_frames
  952. def event_from_exception(
  953. exc_info: "Union[BaseException, ExcInfo]",
  954. client_options: "Optional[Dict[str, Any]]" = None,
  955. mechanism: "Optional[Dict[str, Any]]" = None,
  956. ) -> "Tuple[Event, Dict[str, Any]]":
  957. exc_info = exc_info_from_error(exc_info)
  958. hint = event_hint_with_exc_info(exc_info)
  959. if client_options and client_options.get("add_full_stack", DEFAULT_ADD_FULL_STACK):
  960. full_stack = current_stacktrace(
  961. include_local_variables=client_options["include_local_variables"],
  962. max_value_length=client_options["max_value_length"],
  963. )["frames"]
  964. else:
  965. full_stack = None
  966. return (
  967. {
  968. "level": "error",
  969. "exception": {
  970. "values": exceptions_from_error_tuple(
  971. exc_info, client_options, mechanism, full_stack
  972. )
  973. },
  974. },
  975. hint,
  976. )
  977. def _module_in_list(name: "Optional[str]", items: "Optional[List[str]]") -> bool:
  978. if name is None:
  979. return False
  980. if not items:
  981. return False
  982. for item in items:
  983. if item == name or name.startswith(item + "."):
  984. return True
  985. return False
  986. def _is_external_source(abs_path: "Optional[str]") -> bool:
  987. # check if frame is in 'site-packages' or 'dist-packages'
  988. if abs_path is None:
  989. return False
  990. external_source = (
  991. re.search(r"[\\/](?:dist|site)-packages[\\/]", abs_path) is not None
  992. )
  993. return external_source
  994. def _is_in_project_root(
  995. abs_path: "Optional[str]", project_root: "Optional[str]"
  996. ) -> bool:
  997. if abs_path is None or project_root is None:
  998. return False
  999. # check if path is in the project root
  1000. if abs_path.startswith(project_root):
  1001. return True
  1002. return False
  1003. def _truncate_by_bytes(string: str, max_bytes: int) -> str:
  1004. """
  1005. Truncate a UTF-8-encodable string to the last full codepoint so that it fits in max_bytes.
  1006. """
  1007. truncated = string.encode("utf-8")[: max_bytes - 3].decode("utf-8", errors="ignore")
  1008. return truncated + "..."
  1009. def _get_size_in_bytes(value: str) -> "Optional[int]":
  1010. try:
  1011. return len(value.encode("utf-8"))
  1012. except (UnicodeEncodeError, UnicodeDecodeError):
  1013. return None
  1014. def strip_string(
  1015. value: str, max_length: "Optional[int]" = None
  1016. ) -> "Union[AnnotatedValue, str]":
  1017. if not value:
  1018. return value
  1019. if max_length is None:
  1020. max_length = DEFAULT_MAX_VALUE_LENGTH
  1021. byte_size = _get_size_in_bytes(value)
  1022. text_size = len(value)
  1023. if byte_size is not None and byte_size > max_length:
  1024. # truncate to max_length bytes, preserving code points
  1025. truncated_value = _truncate_by_bytes(value, max_length)
  1026. elif text_size is not None and text_size > max_length:
  1027. # fallback to truncating by string length
  1028. truncated_value = value[: max_length - 3] + "..."
  1029. else:
  1030. return value
  1031. return AnnotatedValue(
  1032. value=truncated_value,
  1033. metadata={
  1034. "len": byte_size or text_size,
  1035. "rem": [["!limit", "x", max_length - 3, max_length]],
  1036. },
  1037. )
  1038. def parse_version(version: str) -> "Optional[Tuple[int, ...]]":
  1039. """
  1040. Parses a version string into a tuple of integers.
  1041. This uses the parsing loging from PEP 440:
  1042. https://peps.python.org/pep-0440/#appendix-b-parsing-version-strings-with-regular-expressions
  1043. """
  1044. VERSION_PATTERN = r""" # noqa: N806
  1045. v?
  1046. (?:
  1047. (?:(?P<epoch>[0-9]+)!)? # epoch
  1048. (?P<release>[0-9]+(?:\.[0-9]+)*) # release segment
  1049. (?P<pre> # pre-release
  1050. [-_\.]?
  1051. (?P<pre_l>(a|b|c|rc|alpha|beta|pre|preview))
  1052. [-_\.]?
  1053. (?P<pre_n>[0-9]+)?
  1054. )?
  1055. (?P<post> # post release
  1056. (?:-(?P<post_n1>[0-9]+))
  1057. |
  1058. (?:
  1059. [-_\.]?
  1060. (?P<post_l>post|rev|r)
  1061. [-_\.]?
  1062. (?P<post_n2>[0-9]+)?
  1063. )
  1064. )?
  1065. (?P<dev> # dev release
  1066. [-_\.]?
  1067. (?P<dev_l>dev)
  1068. [-_\.]?
  1069. (?P<dev_n>[0-9]+)?
  1070. )?
  1071. )
  1072. (?:\+(?P<local>[a-z0-9]+(?:[-_\.][a-z0-9]+)*))? # local version
  1073. """
  1074. pattern = re.compile(
  1075. r"^\s*" + VERSION_PATTERN + r"\s*$",
  1076. re.VERBOSE | re.IGNORECASE,
  1077. )
  1078. try:
  1079. release = pattern.match(version).groupdict()["release"] # type: ignore
  1080. release_tuple: "Tuple[int, ...]" = tuple(map(int, release.split(".")[:3]))
  1081. except (TypeError, ValueError, AttributeError):
  1082. return None
  1083. return release_tuple
  1084. def _is_contextvars_broken() -> bool:
  1085. """
  1086. Returns whether gevent/eventlet have patched the stdlib in a way where thread locals are now more "correct" than contextvars.
  1087. """
  1088. try:
  1089. import gevent
  1090. from gevent.monkey import is_object_patched
  1091. # Get the MAJOR and MINOR version numbers of Gevent
  1092. version_tuple = tuple(
  1093. [int(part) for part in re.split(r"a|b|rc|\.", gevent.__version__)[:2]]
  1094. )
  1095. if is_object_patched("threading", "local"):
  1096. # Gevent 20.9.0 depends on Greenlet 0.4.17 which natively handles switching
  1097. # context vars when greenlets are switched, so, Gevent 20.9.0+ is all fine.
  1098. # Ref: https://github.com/gevent/gevent/blob/83c9e2ae5b0834b8f84233760aabe82c3ba065b4/src/gevent/monkey.py#L604-L609
  1099. # Gevent 20.5, that doesn't depend on Greenlet 0.4.17 with native support
  1100. # for contextvars, is able to patch both thread locals and contextvars, in
  1101. # that case, check if contextvars are effectively patched.
  1102. if (
  1103. # Gevent 20.9.0+
  1104. (sys.version_info >= (3, 7) and version_tuple >= (20, 9))
  1105. # Gevent 20.5.0+ or Python < 3.7
  1106. or (is_object_patched("contextvars", "ContextVar"))
  1107. ):
  1108. return False
  1109. return True
  1110. except ImportError:
  1111. pass
  1112. try:
  1113. import greenlet
  1114. from eventlet.patcher import is_monkey_patched # type: ignore
  1115. greenlet_version = parse_version(greenlet.__version__)
  1116. if greenlet_version is None:
  1117. logger.error(
  1118. "Internal error in Sentry SDK: Could not parse Greenlet version from greenlet.__version__."
  1119. )
  1120. return False
  1121. if is_monkey_patched("thread") and greenlet_version < (0, 5):
  1122. return True
  1123. except ImportError:
  1124. pass
  1125. return False
  1126. def _make_threadlocal_contextvars(local: type) -> type:
  1127. class ContextVar:
  1128. # Super-limited impl of ContextVar
  1129. def __init__(self, name: str, default: "Any" = None) -> None:
  1130. self._name = name
  1131. self._default = default
  1132. self._local = local()
  1133. self._original_local = local()
  1134. def get(self, default: "Any" = None) -> "Any":
  1135. return getattr(self._local, "value", default or self._default)
  1136. def set(self, value: "Any") -> "Any":
  1137. token = str(random.getrandbits(64))
  1138. original_value = self.get()
  1139. setattr(self._original_local, token, original_value)
  1140. self._local.value = value
  1141. return token
  1142. def reset(self, token: "Any") -> None:
  1143. self._local.value = getattr(self._original_local, token)
  1144. # delete the original value (this way it works in Python 3.6+)
  1145. del self._original_local.__dict__[token]
  1146. return ContextVar
  1147. def _get_contextvars() -> "Tuple[bool, type]":
  1148. """
  1149. Figure out the "right" contextvars installation to use. Returns a
  1150. `contextvars.ContextVar`-like class with a limited API.
  1151. See https://docs.sentry.io/platforms/python/contextvars/ for more information.
  1152. """
  1153. if not _is_contextvars_broken():
  1154. # aiocontextvars is a PyPI package that ensures that the contextvars
  1155. # backport (also a PyPI package) works with asyncio under Python 3.6
  1156. #
  1157. # Import it if available.
  1158. if sys.version_info < (3, 7):
  1159. # `aiocontextvars` is absolutely required for functional
  1160. # contextvars on Python 3.6.
  1161. try:
  1162. from aiocontextvars import ContextVar
  1163. return True, ContextVar
  1164. except ImportError:
  1165. pass
  1166. else:
  1167. # On Python 3.7 contextvars are functional.
  1168. try:
  1169. from contextvars import ContextVar
  1170. return True, ContextVar
  1171. except ImportError:
  1172. pass
  1173. # Fall back to basic thread-local usage.
  1174. from threading import local
  1175. return False, _make_threadlocal_contextvars(local)
  1176. HAS_REAL_CONTEXTVARS, ContextVar = _get_contextvars()
  1177. CONTEXTVARS_ERROR_MESSAGE = """
  1178. With asyncio/ASGI applications, the Sentry SDK requires a functional
  1179. installation of `contextvars` to avoid leaking scope/context data across
  1180. requests.
  1181. Please refer to https://docs.sentry.io/platforms/python/contextvars/ for more information.
  1182. """
  1183. def qualname_from_function(func: "Callable[..., Any]") -> "Optional[str]":
  1184. """Return the qualified name of func. Works with regular function, lambda, partial and partialmethod."""
  1185. func_qualname: "Optional[str]" = None
  1186. # Python 2
  1187. try:
  1188. return "%s.%s.%s" % (
  1189. func.im_class.__module__, # type: ignore
  1190. func.im_class.__name__, # type: ignore
  1191. func.__name__,
  1192. )
  1193. except Exception:
  1194. pass
  1195. prefix, suffix = "", ""
  1196. if isinstance(func, partial) and hasattr(func.func, "__name__"):
  1197. prefix, suffix = "partial(<function ", ">)"
  1198. func = func.func
  1199. else:
  1200. # The _partialmethod attribute of methods wrapped with partialmethod() was renamed to __partialmethod__ in CPython 3.13:
  1201. # https://github.com/python/cpython/pull/16600
  1202. partial_method = getattr(func, "_partialmethod", None) or getattr(
  1203. func, "__partialmethod__", None
  1204. )
  1205. if isinstance(partial_method, partialmethod):
  1206. prefix, suffix = "partialmethod(<function ", ">)"
  1207. func = partial_method.func
  1208. if hasattr(func, "__qualname__"):
  1209. func_qualname = func.__qualname__
  1210. elif hasattr(func, "__name__"): # Python 2.7 has no __qualname__
  1211. func_qualname = func.__name__
  1212. # Python 3: methods, functions, classes
  1213. if func_qualname is not None:
  1214. if hasattr(func, "__module__") and isinstance(func.__module__, str):
  1215. func_qualname = func.__module__ + "." + func_qualname
  1216. func_qualname = prefix + func_qualname + suffix
  1217. return func_qualname
  1218. def transaction_from_function(func: "Callable[..., Any]") -> "Optional[str]":
  1219. return qualname_from_function(func)
  1220. disable_capture_event = ContextVar("disable_capture_event")
  1221. class ServerlessTimeoutWarning(Exception): # noqa: N818
  1222. """Raised when a serverless method is about to reach its timeout."""
  1223. pass
  1224. class TimeoutThread(threading.Thread):
  1225. """Creates a Thread which runs (sleeps) for a time duration equal to
  1226. waiting_time and raises a custom ServerlessTimeout exception.
  1227. """
  1228. def __init__(
  1229. self,
  1230. waiting_time: float,
  1231. configured_timeout: int,
  1232. isolation_scope: "Optional[sentry_sdk.Scope]" = None,
  1233. current_scope: "Optional[sentry_sdk.Scope]" = None,
  1234. ) -> None:
  1235. threading.Thread.__init__(self)
  1236. self.waiting_time = waiting_time
  1237. self.configured_timeout = configured_timeout
  1238. self.isolation_scope = isolation_scope
  1239. self.current_scope = current_scope
  1240. self._stop_event = threading.Event()
  1241. def stop(self) -> None:
  1242. self._stop_event.set()
  1243. def _capture_exception(self) -> "ExcInfo":
  1244. exc_info = sys.exc_info()
  1245. client = sentry_sdk.get_client()
  1246. event, hint = event_from_exception(
  1247. exc_info,
  1248. client_options=client.options,
  1249. mechanism={"type": "threading", "handled": False},
  1250. )
  1251. sentry_sdk.capture_event(event, hint=hint)
  1252. return exc_info
  1253. def run(self) -> None:
  1254. self._stop_event.wait(self.waiting_time)
  1255. if self._stop_event.is_set():
  1256. return
  1257. integer_configured_timeout = int(self.configured_timeout)
  1258. # Setting up the exact integer value of configured time(in seconds)
  1259. if integer_configured_timeout < self.configured_timeout:
  1260. integer_configured_timeout = integer_configured_timeout + 1
  1261. # Raising Exception after timeout duration is reached
  1262. if self.isolation_scope is not None and self.current_scope is not None:
  1263. with sentry_sdk.scope.use_isolation_scope(self.isolation_scope):
  1264. with sentry_sdk.scope.use_scope(self.current_scope):
  1265. try:
  1266. raise ServerlessTimeoutWarning(
  1267. "WARNING : Function is expected to get timed out. Configured timeout duration = {} seconds.".format(
  1268. integer_configured_timeout
  1269. )
  1270. )
  1271. except Exception:
  1272. reraise(*self._capture_exception())
  1273. raise ServerlessTimeoutWarning(
  1274. "WARNING : Function is expected to get timed out. Configured timeout duration = {} seconds.".format(
  1275. integer_configured_timeout
  1276. )
  1277. )
  1278. def to_base64(original: str) -> "Optional[str]":
  1279. """
  1280. Convert a string to base64, via UTF-8. Returns None on invalid input.
  1281. """
  1282. base64_string = None
  1283. try:
  1284. utf8_bytes = original.encode("UTF-8")
  1285. base64_bytes = base64.b64encode(utf8_bytes)
  1286. base64_string = base64_bytes.decode("UTF-8")
  1287. except Exception as err:
  1288. logger.warning("Unable to encode {orig} to base64:".format(orig=original), err)
  1289. return base64_string
  1290. def from_base64(base64_string: str) -> "Optional[str]":
  1291. """
  1292. Convert a string from base64, via UTF-8. Returns None on invalid input.
  1293. """
  1294. utf8_string = None
  1295. try:
  1296. only_valid_chars = BASE64_ALPHABET.match(base64_string)
  1297. assert only_valid_chars
  1298. base64_bytes = base64_string.encode("UTF-8")
  1299. utf8_bytes = base64.b64decode(base64_bytes)
  1300. utf8_string = utf8_bytes.decode("UTF-8")
  1301. except Exception as err:
  1302. logger.warning(
  1303. "Unable to decode {b64} from base64:".format(b64=base64_string), err
  1304. )
  1305. return utf8_string
  1306. Components = namedtuple("Components", ["scheme", "netloc", "path", "query", "fragment"])
  1307. def sanitize_url(
  1308. url: str,
  1309. remove_authority: bool = True,
  1310. remove_query_values: bool = True,
  1311. split: bool = False,
  1312. ) -> "Union[str, Components]":
  1313. """
  1314. Removes the authority and query parameter values from a given URL.
  1315. """
  1316. parsed_url = urlsplit(url)
  1317. query_params = parse_qs(parsed_url.query, keep_blank_values=True)
  1318. # strip username:password (netloc can be usr:pwd@example.com)
  1319. if remove_authority:
  1320. netloc_parts = parsed_url.netloc.split("@")
  1321. if len(netloc_parts) > 1:
  1322. netloc = "%s:%s@%s" % (
  1323. SENSITIVE_DATA_SUBSTITUTE,
  1324. SENSITIVE_DATA_SUBSTITUTE,
  1325. netloc_parts[-1],
  1326. )
  1327. else:
  1328. netloc = parsed_url.netloc
  1329. else:
  1330. netloc = parsed_url.netloc
  1331. # strip values from query string
  1332. if remove_query_values:
  1333. query_string = unquote(
  1334. urlencode({key: SENSITIVE_DATA_SUBSTITUTE for key in query_params})
  1335. )
  1336. else:
  1337. query_string = parsed_url.query
  1338. components = Components(
  1339. scheme=parsed_url.scheme,
  1340. netloc=netloc,
  1341. query=query_string,
  1342. path=parsed_url.path,
  1343. fragment=parsed_url.fragment,
  1344. )
  1345. if split:
  1346. return components
  1347. else:
  1348. return urlunsplit(components)
  1349. ParsedUrl = namedtuple("ParsedUrl", ["url", "query", "fragment"])
  1350. def parse_url(url: str, sanitize: bool = True) -> "ParsedUrl":
  1351. """
  1352. Splits a URL into a url (including path), query and fragment. If sanitize is True, the query
  1353. parameters will be sanitized to remove sensitive data. The autority (username and password)
  1354. in the URL will always be removed.
  1355. """
  1356. parsed_url = sanitize_url(
  1357. url, remove_authority=True, remove_query_values=sanitize, split=True
  1358. )
  1359. base_url = urlunsplit(
  1360. Components(
  1361. scheme=parsed_url.scheme, # type: ignore
  1362. netloc=parsed_url.netloc, # type: ignore
  1363. query="",
  1364. path=parsed_url.path, # type: ignore
  1365. fragment="",
  1366. )
  1367. )
  1368. return ParsedUrl(
  1369. url=base_url,
  1370. query=parsed_url.query, # type: ignore
  1371. fragment=parsed_url.fragment, # type: ignore
  1372. )
  1373. def is_valid_sample_rate(rate: "Any", source: str) -> bool:
  1374. """
  1375. Checks the given sample rate to make sure it is valid type and value (a
  1376. boolean or a number between 0 and 1, inclusive).
  1377. """
  1378. # both booleans and NaN are instances of Real, so a) checking for Real
  1379. # checks for the possibility of a boolean also, and b) we have to check
  1380. # separately for NaN and Decimal does not derive from Real so need to check that too
  1381. if not isinstance(rate, (Real, Decimal)) or math.isnan(rate):
  1382. logger.warning(
  1383. "{source} Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got {rate} of type {type}.".format(
  1384. source=source, rate=rate, type=type(rate)
  1385. )
  1386. )
  1387. return False
  1388. # in case rate is a boolean, it will get cast to 1 if it's True and 0 if it's False
  1389. rate = float(rate)
  1390. if rate < 0 or rate > 1:
  1391. logger.warning(
  1392. "{source} Given sample rate is invalid. Sample rate must be between 0 and 1. Got {rate}.".format(
  1393. source=source, rate=rate
  1394. )
  1395. )
  1396. return False
  1397. return True
  1398. def match_regex_list(
  1399. item: str,
  1400. regex_list: "Optional[List[str]]" = None,
  1401. substring_matching: bool = False,
  1402. ) -> bool:
  1403. if regex_list is None:
  1404. return False
  1405. for item_matcher in regex_list:
  1406. if not substring_matching and item_matcher[-1] != "$":
  1407. item_matcher += "$"
  1408. matched = re.search(item_matcher, item)
  1409. if matched:
  1410. return True
  1411. return False
  1412. def is_sentry_url(client: "sentry_sdk.client.BaseClient", url: str) -> bool:
  1413. """
  1414. Determines whether the given URL matches the Sentry DSN.
  1415. """
  1416. return (
  1417. client is not None
  1418. and client.transport is not None
  1419. and client.transport.parsed_dsn is not None
  1420. and client.transport.parsed_dsn.netloc in url
  1421. )
  1422. def _generate_installed_modules() -> "Iterator[Tuple[str, str]]":
  1423. try:
  1424. from importlib import metadata
  1425. yielded = set()
  1426. for dist in metadata.distributions():
  1427. name = dist.metadata.get("Name", None) # type: ignore[attr-defined]
  1428. # `metadata` values may be `None`, see:
  1429. # https://github.com/python/cpython/issues/91216
  1430. # and
  1431. # https://github.com/python/importlib_metadata/issues/371
  1432. if name is not None:
  1433. normalized_name = _normalize_module_name(name)
  1434. if dist.version is not None and normalized_name not in yielded:
  1435. yield normalized_name, dist.version
  1436. yielded.add(normalized_name)
  1437. except ImportError:
  1438. # < py3.8
  1439. try:
  1440. import pkg_resources
  1441. except ImportError:
  1442. return
  1443. for info in pkg_resources.working_set:
  1444. yield _normalize_module_name(info.key), info.version
  1445. def _normalize_module_name(name: str) -> str:
  1446. return name.lower()
  1447. def _replace_hyphens_dots_and_underscores_with_dashes(name: str) -> str:
  1448. # https://peps.python.org/pep-0503/#normalized-names
  1449. return re.sub(r"[-_.]+", "-", name)
  1450. def _get_installed_modules() -> "Dict[str, str]":
  1451. global _installed_modules
  1452. if _installed_modules is None:
  1453. _installed_modules = dict(_generate_installed_modules())
  1454. return _installed_modules
  1455. def package_version(package: str) -> "Optional[Tuple[int, ...]]":
  1456. normalized_package = _normalize_module_name(
  1457. _replace_hyphens_dots_and_underscores_with_dashes(package)
  1458. )
  1459. installed_packages = {
  1460. _replace_hyphens_dots_and_underscores_with_dashes(module): v
  1461. for module, v in _get_installed_modules().items()
  1462. }
  1463. version = installed_packages.get(normalized_package)
  1464. if version is None:
  1465. return None
  1466. return parse_version(version)
  1467. def reraise(
  1468. tp: "Optional[Type[BaseException]]",
  1469. value: "Optional[BaseException]",
  1470. tb: "Optional[Any]" = None,
  1471. ) -> "NoReturn":
  1472. assert value is not None
  1473. if value.__traceback__ is not tb:
  1474. raise value.with_traceback(tb)
  1475. raise value
  1476. def _no_op(*_a: "Any", **_k: "Any") -> None:
  1477. """No-op function for ensure_integration_enabled."""
  1478. pass
  1479. if TYPE_CHECKING:
  1480. @overload
  1481. def ensure_integration_enabled(
  1482. integration: "type[sentry_sdk.integrations.Integration]",
  1483. original_function: "Callable[P, R]",
  1484. ) -> "Callable[[Callable[P, R]], Callable[P, R]]": ...
  1485. @overload
  1486. def ensure_integration_enabled(
  1487. integration: "type[sentry_sdk.integrations.Integration]",
  1488. ) -> "Callable[[Callable[P, None]], Callable[P, None]]": ...
  1489. def ensure_integration_enabled(
  1490. integration: "type[sentry_sdk.integrations.Integration]",
  1491. original_function: "Union[Callable[P, R], Callable[P, None]]" = _no_op,
  1492. ) -> "Callable[[Callable[P, R]], Callable[P, R]]":
  1493. """
  1494. Ensures a given integration is enabled prior to calling a Sentry-patched function.
  1495. The function takes as its parameters the integration that must be enabled and the original
  1496. function that the SDK is patching. The function returns a function that takes the
  1497. decorated (Sentry-patched) function as its parameter, and returns a function that, when
  1498. called, checks whether the given integration is enabled. If the integration is enabled, the
  1499. function calls the decorated, Sentry-patched function. If the integration is not enabled,
  1500. the original function is called.
  1501. The function also takes care of preserving the original function's signature and docstring.
  1502. Example usage:
  1503. ```python
  1504. @ensure_integration_enabled(MyIntegration, my_function)
  1505. def patch_my_function():
  1506. with sentry_sdk.start_transaction(...):
  1507. return my_function()
  1508. ```
  1509. """
  1510. if TYPE_CHECKING:
  1511. # Type hint to ensure the default function has the right typing. The overloads
  1512. # ensure the default _no_op function is only used when R is None.
  1513. original_function = cast(Callable[P, R], original_function)
  1514. def patcher(sentry_patched_function: "Callable[P, R]") -> "Callable[P, R]":
  1515. def runner(*args: "P.args", **kwargs: "P.kwargs") -> "R":
  1516. if sentry_sdk.get_client().get_integration(integration) is None:
  1517. return original_function(*args, **kwargs)
  1518. return sentry_patched_function(*args, **kwargs)
  1519. if original_function is _no_op:
  1520. return wraps(sentry_patched_function)(runner)
  1521. return wraps(original_function)(runner)
  1522. return patcher
  1523. if PY37:
  1524. def nanosecond_time() -> int:
  1525. return time.perf_counter_ns()
  1526. else:
  1527. def nanosecond_time() -> int:
  1528. return int(time.perf_counter() * 1e9)
  1529. def now() -> float:
  1530. return time.perf_counter()
  1531. try:
  1532. from gevent import get_hub as get_gevent_hub
  1533. from gevent.monkey import is_module_patched
  1534. except ImportError:
  1535. # it's not great that the signatures are different, get_hub can't return None
  1536. # consider adding an if TYPE_CHECKING to change the signature to Optional[Hub]
  1537. def get_gevent_hub() -> "Optional[Hub]": # type: ignore[misc]
  1538. return None
  1539. def is_module_patched(mod_name: str) -> bool:
  1540. # unable to import from gevent means no modules have been patched
  1541. return False
  1542. def is_gevent() -> bool:
  1543. return is_module_patched("threading") or is_module_patched("_thread")
  1544. def get_current_thread_meta(
  1545. thread: "Optional[threading.Thread]" = None,
  1546. ) -> "Tuple[Optional[int], Optional[str]]":
  1547. """
  1548. Try to get the id of the current thread, with various fall backs.
  1549. """
  1550. # if a thread is specified, that takes priority
  1551. if thread is not None:
  1552. try:
  1553. thread_id = thread.ident
  1554. thread_name = thread.name
  1555. if thread_id is not None:
  1556. return thread_id, thread_name
  1557. except AttributeError:
  1558. pass
  1559. # if the app is using gevent, we should look at the gevent hub first
  1560. # as the id there differs from what the threading module reports
  1561. if is_gevent():
  1562. gevent_hub = get_gevent_hub()
  1563. if gevent_hub is not None:
  1564. try:
  1565. # this is undocumented, so wrap it in try except to be safe
  1566. return gevent_hub.thread_ident, None
  1567. except AttributeError:
  1568. pass
  1569. # use the current thread's id if possible
  1570. try:
  1571. thread = threading.current_thread()
  1572. thread_id = thread.ident
  1573. thread_name = thread.name
  1574. if thread_id is not None:
  1575. return thread_id, thread_name
  1576. except AttributeError:
  1577. pass
  1578. # if we can't get the current thread id, fall back to the main thread id
  1579. try:
  1580. thread = threading.main_thread()
  1581. thread_id = thread.ident
  1582. thread_name = thread.name
  1583. if thread_id is not None:
  1584. return thread_id, thread_name
  1585. except AttributeError:
  1586. pass
  1587. # we've tried everything, time to give up
  1588. return None, None
  1589. def should_be_treated_as_error(ty: "Any", value: "Any") -> bool:
  1590. if ty == SystemExit and hasattr(value, "code") and value.code in (0, None):
  1591. # https://docs.python.org/3/library/exceptions.html#SystemExit
  1592. return False
  1593. return True
  1594. if TYPE_CHECKING:
  1595. T = TypeVar("T")
  1596. def try_convert(convert_func: "Callable[[Any], T]", value: "Any") -> "Optional[T]":
  1597. """
  1598. Attempt to convert from an unknown type to a specific type, using the
  1599. given function. Return None if the conversion fails, i.e. if the function
  1600. raises an exception.
  1601. """
  1602. try:
  1603. if isinstance(value, convert_func): # type: ignore
  1604. return value
  1605. except TypeError:
  1606. pass
  1607. try:
  1608. return convert_func(value)
  1609. except Exception:
  1610. return None
  1611. def safe_serialize(data: "Any") -> str:
  1612. """Safely serialize to a readable string."""
  1613. def serialize_item(
  1614. item: "Any",
  1615. ) -> "Union[str, dict[Any, Any], list[Any], tuple[Any, ...]]":
  1616. if callable(item):
  1617. try:
  1618. module = getattr(item, "__module__", None)
  1619. qualname = getattr(item, "__qualname__", None)
  1620. name = getattr(item, "__name__", "anonymous")
  1621. if module and qualname:
  1622. full_path = f"{module}.{qualname}"
  1623. elif module and name:
  1624. full_path = f"{module}.{name}"
  1625. else:
  1626. full_path = name
  1627. return f"<function {full_path}>"
  1628. except Exception:
  1629. return f"<callable {type(item).__name__}>"
  1630. elif isinstance(item, dict):
  1631. return {k: serialize_item(v) for k, v in item.items()}
  1632. elif isinstance(item, (list, tuple)):
  1633. return [serialize_item(x) for x in item]
  1634. elif hasattr(item, "__dict__"):
  1635. try:
  1636. attrs = {
  1637. k: serialize_item(v)
  1638. for k, v in vars(item).items()
  1639. if not k.startswith("_")
  1640. }
  1641. return f"<{type(item).__name__} {attrs}>"
  1642. except Exception:
  1643. return repr(item)
  1644. else:
  1645. return item
  1646. try:
  1647. serialized = serialize_item(data)
  1648. return (
  1649. json.dumps(serialized, default=str)
  1650. if not isinstance(serialized, str)
  1651. else serialized
  1652. )
  1653. except Exception:
  1654. return str(data)
  1655. def has_logs_enabled(options: "Optional[dict[str, Any]]") -> bool:
  1656. if options is None:
  1657. return False
  1658. return bool(
  1659. options.get("enable_logs", False)
  1660. or options["_experiments"].get("enable_logs", False)
  1661. )
  1662. def get_before_send_log(
  1663. options: "Optional[dict[str, Any]]",
  1664. ) -> "Optional[Callable[[Log, Hint], Optional[Log]]]":
  1665. if options is None:
  1666. return None
  1667. return options.get("before_send_log") or options["_experiments"].get(
  1668. "before_send_log"
  1669. )
  1670. def has_metrics_enabled(options: "Optional[dict[str, Any]]") -> bool:
  1671. if options is None:
  1672. return False
  1673. return bool(options.get("enable_metrics", True))
  1674. def get_before_send_metric(
  1675. options: "Optional[dict[str, Any]]",
  1676. ) -> "Optional[Callable[[Metric, Hint], Optional[Metric]]]":
  1677. if options is None:
  1678. return None
  1679. return options.get("before_send_metric") or options["_experiments"].get(
  1680. "before_send_metric"
  1681. )
  1682. def format_attribute(val: "Any") -> "AttributeValue":
  1683. """
  1684. Turn unsupported attribute value types into an AttributeValue.
  1685. We do this as soon as a user-provided attribute is set, to prevent spans,
  1686. logs, metrics and similar from having live references to various objects.
  1687. Note: This is not the final attribute value format. Before they're sent,
  1688. they're serialized further into the actual format the protocol expects:
  1689. https://develop.sentry.dev/sdk/telemetry/attributes/
  1690. """
  1691. if isinstance(val, (bool, int, float, str)):
  1692. return val
  1693. if isinstance(val, (list, tuple)) and not val:
  1694. return []
  1695. elif isinstance(val, list):
  1696. ty = type(val[0])
  1697. if ty in (str, int, float, bool) and all(type(v) is ty for v in val):
  1698. return copy.deepcopy(val)
  1699. elif isinstance(val, tuple):
  1700. ty = type(val[0])
  1701. if ty in (str, int, float, bool) and all(type(v) is ty for v in val):
  1702. return list(val)
  1703. return safe_repr(val)
  1704. def serialize_attribute(val: "AttributeValue") -> "SerializedAttributeValue":
  1705. """Serialize attribute value to the transport format."""
  1706. if isinstance(val, bool):
  1707. return {"value": val, "type": "boolean"}
  1708. if isinstance(val, int):
  1709. return {"value": val, "type": "integer"}
  1710. if isinstance(val, float):
  1711. return {"value": val, "type": "double"}
  1712. if isinstance(val, str):
  1713. return {"value": val, "type": "string"}
  1714. if isinstance(val, list):
  1715. if not val:
  1716. return {"value": [], "type": "array"}
  1717. # Only lists of elements of a single type are supported
  1718. ty = type(val[0])
  1719. if ty in (int, str, bool, float) and all(type(v) is ty for v in val):
  1720. return {"value": val, "type": "array"}
  1721. # Coerce to string if we don't know what to do with the value. This should
  1722. # never happen as we pre-format early in format_attribute, but let's be safe.
  1723. return {"value": safe_repr(val), "type": "string"}