javascript_event_processor.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201
  1. import copy
  2. import itertools
  3. import re
  4. from os.path import splitext
  5. from typing import TYPE_CHECKING
  6. from urllib.parse import urlsplit
  7. from symbolic import SourceMapView, SourceView
  8. from apps.files.models import File
  9. from sentry.utils.safe import get_path
  10. if TYPE_CHECKING:
  11. from .schema import IssueEventSchema, StackTrace, StackTraceFrame
  12. UNKNOWN_MODULE = "<unknown module>"
  13. CLEAN_MODULE_RE = re.compile(
  14. r"""^
  15. (?:/| # Leading slashes
  16. (?:
  17. (?:java)?scripts?|js|build|static|node_modules|bower_components|[_\.~].*?| # common folder prefixes
  18. v?(?:\d+\.)*\d+| # version numbers, v1, 1.0.0
  19. [a-f0-9]{7,8}| # short sha
  20. [a-f0-9]{32}| # md5
  21. [a-f0-9]{40} # sha1
  22. )/)+|
  23. (?:[-\.][a-f0-9]{7,}$) # Ending in a commitish
  24. """,
  25. re.X | re.I,
  26. )
  27. VERSION_RE = re.compile(r"^[a-f0-9]{32}|[a-f0-9]{40}$", re.I)
  28. NODE_MODULES_RE = re.compile(r"\bnode_modules/")
  29. def generate_module(src):
  30. """
  31. Converts a url into a made-up module name by doing the following:
  32. * Extract just the path name ignoring querystrings
  33. * Trimming off the initial /
  34. * Trimming off the file extension
  35. * Removes off useless folder prefixes
  36. e.g. http://google.com/js/v1.0/foo/bar/baz.js -> foo/bar/baz
  37. """
  38. if not src:
  39. return UNKNOWN_MODULE
  40. filename, _ = splitext(urlsplit(src).path)
  41. if filename.endswith(".min"):
  42. filename = filename[:-4]
  43. tokens = filename.split("/")
  44. for idx, token in enumerate(tokens):
  45. # a SHA
  46. if VERSION_RE.match(token):
  47. return "/".join(tokens[idx + 1 :])
  48. return CLEAN_MODULE_RE.sub("", filename) or UNKNOWN_MODULE
  49. class JavascriptEventProcessor:
  50. """
  51. Based partially on sentry/lang/javascript/processor.py
  52. """
  53. def __init__(self, release_id: int, data: "IssueEventSchema"):
  54. self.release_id = release_id
  55. self.data = data
  56. def get_stacktraces(self) -> list["StackTrace"]:
  57. data = self.data
  58. if data.exception and not isinstance(data.exception, list):
  59. return [e.stacktrace for e in data.exception.values if e.stacktrace]
  60. return []
  61. def get_valid_frames(self, stacktraces) -> list["StackTraceFrame"]:
  62. frames = [stacktrace.frames for stacktrace in stacktraces]
  63. merged = list(itertools.chain(*frames))
  64. return [f for f in merged if f is not None and f.lineno is not None]
  65. def process_frame(self, frame, map_file, minified_source):
  66. # Required to determine source
  67. if not frame.abs_path or not frame.lineno:
  68. return
  69. minified_source.blob.blob.seek(0)
  70. map_file.blob.blob.seek(0)
  71. sourcemap_view = SourceMapView.from_json_bytes(map_file.blob.blob.read())
  72. minified_source_view = SourceView.from_bytes(minified_source.blob.blob.read())
  73. token = sourcemap_view.lookup(
  74. frame.lineno - 1,
  75. frame.colno - 1,
  76. frame.function,
  77. minified_source_view,
  78. )
  79. if not token:
  80. return
  81. frame.lineno = token.src_line + 1
  82. frame.colno = token.src_col + 1
  83. if token.function_name:
  84. frame.function = token.function_name
  85. filename = token.src
  86. abs_path = frame.abs_path
  87. in_app = None
  88. # special case webpack support
  89. # abs_path will always be the full path with webpack:/// prefix.
  90. # filename will be relative to that
  91. if abs_path.startswith("webpack:"):
  92. filename = abs_path
  93. # webpack seems to use ~ to imply "relative to resolver root"
  94. # which is generally seen for third party deps
  95. # (i.e. node_modules)
  96. if "/~/" in filename:
  97. filename = "~/" + abs_path.split("/~/", 1)[-1]
  98. else:
  99. filename = filename.split("webpack:///", 1)[-1]
  100. # As noted above:
  101. # * [js/node] '~/' means they're coming from node_modules, so these are not app dependencies
  102. # * [node] sames goes for `./node_modules/` and '../node_modules/', which is used when bundling node apps
  103. # * [node] and webpack, which includes it's own code to bootstrap all modules and its internals
  104. # eg. webpack:///webpack/bootstrap, webpack:///external
  105. if (
  106. filename.startswith("~/")
  107. or "/node_modules/" in filename
  108. or not filename.startswith("./")
  109. ):
  110. in_app = False
  111. # And conversely, local dependencies start with './'
  112. elif filename.startswith("./"):
  113. in_app = True
  114. # We want to explicitly generate a webpack module name
  115. frame["module"] = generate_module(filename)
  116. elif "/node_modules/" in abs_path:
  117. in_app = False
  118. if abs_path.startswith("app:"):
  119. if filename and NODE_MODULES_RE.search(filename):
  120. in_app = False
  121. else:
  122. in_app = True
  123. frame.filename = filename
  124. if not frame.module and abs_path.startswith(
  125. ("http:", "https:", "webpack:", "app:")
  126. ):
  127. frame.module = generate_module(abs_path)
  128. if in_app is not None:
  129. frame.in_app = in_app
  130. # Extract frame context
  131. source_result = next(
  132. (x for x in sourcemap_view.iter_sources() if x[1] == token.src), None
  133. )
  134. if source_result is not None:
  135. sourceview = sourcemap_view.get_sourceview(source_result[0])
  136. source = sourceview.get_source().splitlines()
  137. pre_lines = max(0, token.src_line - 5)
  138. past_lines = min(len(source), token.src_line + 5)
  139. frame.context_line = source[token.src_line]
  140. frame.pre_context = source[pre_lines : token.src_line]
  141. frame.post_context = source[token.src_line + 1 : past_lines]
  142. def transform(self):
  143. stacktraces = self.get_stacktraces()
  144. frames = self.get_valid_frames(stacktraces)
  145. filenames = {frame.filename.split("/")[-1] for frame in frames}
  146. # Make a guess at which files are relevant, match then better after
  147. source_files = File.objects.filter(
  148. releasefile__release_id=self.release_id,
  149. name__in={filename + ".map" for filename in filenames} | filenames,
  150. )
  151. if not source_files:
  152. return
  153. # Copy original stacktrace before modifying them
  154. for exception in get_path(
  155. self.data, "exception", "values", filter=True, default=()
  156. ):
  157. exception["raw_stacktrace"] = copy.deepcopy(exception["stacktrace"])
  158. frames_with_source = []
  159. for frame in frames:
  160. minified_filename = frame.abs_path.split("/")[-1] if frame.abs_path else ""
  161. map_filename = minified_filename + ".map"
  162. minified_file = None
  163. map_file = None
  164. for source_file in source_files:
  165. if source_file.name == minified_filename:
  166. minified_file = source_file
  167. if source_file.name == map_filename:
  168. map_file = source_file
  169. if map_file:
  170. frames_with_source.append((frame, map_file, minified_file))
  171. for frame_with_source in frames_with_source:
  172. self.process_frame(*frame_with_source)