Slice 5: vigil_sourcemap NIF and JS symbolication

1619312 · gmorell · 2026-12-02 02:14

40 files +2877 -2
Message
{commit_body(@commit)}

Files changed

added lib/vigil/artifacts/lookup.ex
+440 −0
@@ -0,0 +1,440 @@
1 +defmodule Vigil.Artifacts.Lookup do
2 + @moduledoc """
3 + Finds the minified source and source map for a JavaScript frame among a
4 + project's uploaded artifact bundles (ROADMAP.md, slice 5), for
5 + `Vigil.Symbolication.JS`. One lookup serves one event: files and answers
6 + are cached in the struct, since many frames share a file.
7 +
8 + 1. **By debug id.** `debug_meta.images` entries of type `sourcemap`
9 + carry a `debug_id` and the `code_file` (the frame's `abs_path`) it is
10 + for. The newest `source_map` with that debug id, in a bundle linked
11 + to the project, and the `minified_source` with the same id.
12 + 2. **By release, dist and url.** The newest bundles of the event's
13 + release and dist (no dist matches only no dist) linked to the
14 + project. The frame's `abs_path` is matched against manifest urls as
15 + Sentry does (`candidates/1`): the url as is, without its query, and
16 + as `~/path` (scheme and host dropped, so `app:///`, `webpack://`
17 + and `https://host/` all reach `~/`). The minified file then names
18 + its map: its debug id, its `Sourcemap` header, its
19 + `sourceMappingURL` comment (a `data:` url is decoded in place), or
20 + else `<url>.map`; relative references are resolved against the
21 + minified file's url (`join_url/2`).
22 +
23 + Files over #{50} MiB are not loaded.
24 + """
25 +
26 + import Ecto.Query
27 +
28 + alias Vigil.Artifacts.{ArtifactBundle, ArtifactFile}
29 + alias Vigil.{Repo, Sourcemap, Storage}
30 +
31 + @max_file_size 50 * 1024 * 1024
32 + @max_bundles 50
33 +
34 + defstruct [
35 + :organization_id,
36 + :project_id,
37 + :release,
38 + :dist,
39 + images: %{},
40 + release_bundles: nil,
41 + found: %{},
42 + contents: %{}
43 + ]
44 +
45 + @type t :: %__MODULE__{}
46 +
47 + @typedoc """
48 + What a frame's `abs_path` resolved to: the map's bytes, its url in the
49 + frame's terms (where the map's `sources` are relative to), and the
50 + minified source when there is one.
51 + """
52 + @type source :: %{map: binary(), map_url: String.t(), minified: binary() | nil}
53 +
54 + @doc "A lookup for one event of the project."
55 + @spec new(map(), %{organization_id: Ecto.UUID.t(), project_id: Ecto.UUID.t()}) :: t()
56 + def new(event, %{organization_id: org_id, project_id: project_id}) do
57 + images =
58 + for %{"type" => "sourcemap", "code_file" => file, "debug_id" => id} <-
59 + List.wrap(get_in(event, ["debug_meta", "images"])),
60 + is_binary(file),
61 + {:ok, id} <- [cast_debug_id(id)],
62 + into: %{},
63 + do: {file, id}
64 +
65 + %__MODULE__{
66 + organization_id: org_id,
67 + project_id: project_id,
68 + release: string(event["release"]),
69 + dist: string(event["dist"]),
70 + images: images
71 + }
72 + end
73 +
74 + @doc "Whether the event named a debug id for `abs_path`."
75 + @spec debug_id?(t(), String.t()) :: boolean()
76 + def debug_id?(%__MODULE__{images: images}, abs_path), do: Map.has_key?(images, abs_path)
77 +
78 + @doc "The map (and minified source) for a frame's `abs_path`, or `nil`."
79 + @spec source_for(t(), String.t()) :: {source() | nil, t()}
80 + def source_for(%__MODULE__{found: found} = lookup, abs_path) when is_binary(abs_path) do
81 + case found do
82 + %{^abs_path => source} ->
83 + {source, lookup}
84 +
85 + _ ->
86 + {source, lookup} = find(lookup, abs_path)
87 + {source, %{lookup | found: Map.put(lookup.found, abs_path, source)}}
88 + end
89 + end
90 +
91 + defp find(lookup, abs_path) do
92 + case by_debug_id(lookup, abs_path) do
93 + {nil, lookup} -> by_release(lookup, abs_path)
94 + found -> found
95 + end
96 + end
97 +
98 + ## By debug id
99 +
100 + defp by_debug_id(%{images: images} = lookup, abs_path) do
101 + case images do
102 + %{^abs_path => debug_id} ->
103 + files =
104 + from(f in project_files(lookup),
105 + where: f.debug_id == ^debug_id and f.kind in ["source_map", "minified_source"]
106 + )
107 + |> Repo.all()
108 +
109 + map = Enum.find(files, &(&1.kind == "source_map"))
110 + minified = Enum.find(files, &(&1.kind == "minified_source"))
111 + source(lookup, abs_path, map, minified)
112 +
113 + _ ->
114 + {nil, lookup}
115 + end
116 + end
117 +
118 + ## By release and url
119 +
120 + defp by_release(%{release: nil} = lookup, _abs_path), do: {nil, lookup}
121 +
122 + defp by_release(lookup, abs_path) do
123 + {bundle_ids, lookup} = release_bundles(lookup)
124 + candidates = candidates(abs_path)
125 +
126 + if bundle_ids == [] do
127 + {nil, lookup}
128 + else
129 + files =
130 + from(f in ArtifactFile,
131 + where: f.artifact_bundle_id in ^bundle_ids and f.url in ^candidates
132 + )
133 + |> Repo.all()
134 +
135 + case best(files, bundle_ids, candidates, &(&1.kind != "source_map")) do
136 + nil ->
137 + # No minified file uploaded, but maybe its map: `<url>.map`.
138 + map = map_by_url(files_at(bundle_ids, abs_path <> ".map"), bundle_ids, abs_path)
139 + source(lookup, abs_path, map, nil)
140 +
141 + minified ->
142 + {contents, lookup} = load(lookup, minified)
143 + map = map_for(lookup, minified, contents, bundle_ids)
144 +
145 + case map do
146 + {:inline, map_binary} ->
147 + source = %{map: map_binary, map_url: abs_path, minified: contents}
148 + {source, lookup}
149 +
150 + map ->
151 + source(lookup, abs_path, map, minified)
152 + end
153 + end
154 + end
155 + end
156 +
157 + defp release_bundles(%{release_bundles: ids} = lookup) when is_list(ids), do: {ids, lookup}
158 +
159 + defp release_bundles(lookup) do
160 + query =
161 + from b in ArtifactBundle,
162 + join: bp in "artifact_bundle_projects",
163 + on: bp.artifact_bundle_id == b.id,
164 + where:
165 + b.organization_id == ^lookup.organization_id and
166 + bp.project_id == type(^lookup.project_id, :binary_id) and
167 + b.release == ^lookup.release,
168 + order_by: [desc: b.inserted_at, desc: b.id],
169 + limit: @max_bundles,
170 + select: b.id
171 +
172 + query =
173 + if lookup.dist,
174 + do: where(query, [b], b.dist == ^lookup.dist),
175 + else: where(query, [b], is_nil(b.dist))
176 +
177 + ids = Repo.all(query)
178 + {ids, %{lookup | release_bundles: ids}}
179 + end
180 +
181 + # The minified file's map: same debug id, else its reference, in the
182 + # bundles at hand (its own first).
183 + defp map_for(lookup, minified, contents, bundle_ids) do
184 + bundle_ids = [
185 + minified.artifact_bundle_id | List.delete(bundle_ids, minified.artifact_bundle_id)
186 + ]
187 +
188 + by_id =
189 + minified.debug_id &&
190 + Repo.one(
191 + from(f in project_files(lookup),
192 + where: f.debug_id == ^minified.debug_id and f.kind == "source_map",
193 + limit: 1
194 + )
195 + )
196 +
197 + by_id || map_by_reference(minified, contents, bundle_ids)
198 + end
199 +
200 + defp map_by_reference(minified, contents, bundle_ids) do
201 + reference =
202 + minified.sourcemap || header(minified.headers, "sourcemap") ||
203 + header(minified.headers, "x-sourcemap") ||
204 + (contents && Sourcemap.sourcemap_url(contents))
205 +
206 + case reference do
207 + "data:" <> _ = data ->
208 + case decode_data_url(data) do
209 + nil -> nil
210 + map -> {:inline, map}
211 + end
212 +
213 + nil ->
214 + map_by_url(
215 + files_at(bundle_ids, minified.url <> ".map"),
216 + bundle_ids,
217 + minified.url <> ".map"
218 + )
219 +
220 + ref ->
221 + url = join_url(minified.url, ref)
222 + map_by_url(files_at(bundle_ids, url), bundle_ids, url)
223 + end
224 + end
225 +
226 + defp files_at(bundle_ids, url) do
227 + candidates = candidates(url)
228 +
229 + from(f in ArtifactFile, where: f.artifact_bundle_id in ^bundle_ids and f.url in ^candidates)
230 + |> Repo.all()
231 + end
232 +
233 + defp map_by_url(files, bundle_ids, url),
234 + do: best(files, bundle_ids, candidates(url), &(&1.kind in ["source_map", "other"]))
235 +
236 + # The file that best matches: earliest candidate url, then newest bundle.
237 + defp best(files, bundle_ids, candidates, keep?) do
238 + rank = bundle_ids |> Enum.with_index() |> Map.new()
239 + url_rank = candidates |> Enum.with_index() |> Map.new()
240 +
241 + files
242 + |> Enum.filter(keep?)
243 + |> Enum.min_by(
244 + &{Map.get(url_rank, &1.url, 999), Map.get(rank, &1.artifact_bundle_id, 999)},
245 + fn -> nil end
246 + )
247 + end
248 +
249 + ## Loading
250 +
251 + defp source(lookup, _abs_path, nil, _minified), do: {nil, lookup}
252 +
253 + defp source(lookup, abs_path, %ArtifactFile{} = map, minified) do
254 + {map_binary, lookup} = load(lookup, map)
255 + {minified_binary, lookup} = if minified, do: load(lookup, minified), else: {nil, lookup}
256 +
257 + case map_binary do
258 + nil ->
259 + {nil, lookup}
260 +
261 + map_binary ->
262 + map_url = frame_map_url(abs_path, map, minified)
263 + {%{map: map_binary, map_url: map_url, minified: minified_binary}, lookup}
264 + end
265 + end
266 +
267 + # The map's url as the frame sees it: its map sits where the minified
268 + # file does (the usual case) unless the manifest says otherwise.
269 + defp frame_map_url(abs_path, map, minified) do
270 + same_dir? = is_nil(minified) or dirname(minified.url) == dirname(map.url)
271 +
272 + if same_dir?,
273 + do: join_url(abs_path, basename(map.url)),
274 + else: map.url
275 + end
276 +
277 + defp load(%{contents: contents} = lookup, %ArtifactFile{id: id} = file) do
278 + case contents do
279 + %{^id => binary} ->
280 + {binary, lookup}
281 +
282 + _ ->
283 + binary =
284 + with true <- (file.size || 0) <= @max_file_size,
285 + {:ok, binary} when byte_size(binary) <= @max_file_size <-
286 + Storage.get(file.storage_key) do
287 + binary
288 + else
289 + _ -> nil
290 + end
291 +
292 + {binary, %{lookup | contents: Map.put(contents, id, binary)}}
293 + end
294 + end
295 +
296 + defp project_files(lookup) do
297 + from f in ArtifactFile,
298 + join: bp in "artifact_bundle_projects",
299 + on: bp.artifact_bundle_id == f.artifact_bundle_id,
300 + where:
301 + f.organization_id == ^lookup.organization_id and
302 + bp.project_id == type(^lookup.project_id, :binary_id),
303 + order_by: [desc: f.inserted_at, desc: f.id]
304 + end
305 +
306 + ## Urls
307 +
308 + @doc """
309 + The manifest urls a frame's `abs_path` may have been uploaded under, in
310 + order of preference: as is, without its query, then `~/path` with and
311 + without the query.
312 +
313 + iex> Vigil.Artifacts.Lookup.candidates("https://example.com/static/app.js?v=1")
314 + ["https://example.com/static/app.js?v=1", "https://example.com/static/app.js",
315 + "~/static/app.js?v=1", "~/static/app.js"]
316 + iex> Vigil.Artifacts.Lookup.candidates("app:///index.js")
317 + ["app:///index.js", "~/index.js"]
318 + """
319 + @spec candidates(String.t()) :: [String.t()]
320 + def candidates(url) do
321 + bare = url |> String.split("#", parts: 2) |> hd() |> String.split("?", parts: 2) |> hd()
322 +
323 + tilde =
324 + cond do
325 + String.starts_with?(url, "~/") ->
326 + []
327 +
328 + String.starts_with?(url, "/") ->
329 + ["~" <> url, "~" <> bare]
330 +
331 + true ->
332 + case URI.new(url) do
333 + {:ok, %URI{scheme: scheme, path: "/" <> _ = path, query: query}}
334 + when is_binary(scheme) ->
335 + path = String.replace(path, "/./", "/")
336 + if query, do: ["~#{path}?#{query}", "~" <> path], else: ["~" <> path]
337 +
338 + _ ->
339 + []
340 + end
341 + end
342 +
343 + Enum.uniq([url, bare | tilde])
344 + end
345 +
346 + @doc """
347 + `ref` resolved against `base`, as a browser would, with `~/` urls kept
348 + as such and references with a scheme (`webpack://…`) left alone.
349 +
350 + iex> Vigil.Artifacts.Lookup.join_url("~/static/js/app.js", "app.js.map")
351 + "~/static/js/app.js.map"
352 + iex> Vigil.Artifacts.Lookup.join_url("https://x.io/js/app.js.map", "../src/a.ts")
353 + "https://x.io/src/a.ts"
354 + iex> Vigil.Artifacts.Lookup.join_url("https://x.io/js/app.js.map", "webpack:///./src/a.ts")
355 + "webpack:///./src/a.ts"
356 + """
357 + @spec join_url(String.t(), String.t()) :: String.t()
358 + def join_url(base, ref) do
359 + cond do
360 + Regex.match?(~r/^[a-zA-Z][a-zA-Z0-9+.\-]*:/, ref) or String.starts_with?(ref, "~/") ->
361 + ref
362 +
363 + String.starts_with?(base, "~/") ->
364 + "http://~/"
365 + |> Kernel.<>(String.trim_leading(base, "~/"))
366 + |> merge(ref)
367 + |> String.replace_prefix("http://~/", "~/")
368 +
369 + Regex.match?(~r/^[a-zA-Z][a-zA-Z0-9+.\-]*:/, base) ->
370 + merge(base, ref)
371 +
372 + true ->
373 + base |> Path.dirname() |> Path.join(ref) |> normalize_path()
374 + end
375 + end
376 +
377 + defp merge(base, ref) do
378 + base |> URI.merge(ref) |> URI.to_string()
379 + rescue
380 + _ -> ref
381 + end
382 +
383 + defp normalize_path(path) do
384 + absolute? = String.starts_with?(path, "/")
385 +
386 + path
387 + |> String.split("/", trim: true)
388 + |> Enum.reduce([], fn
389 + ".", acc -> acc
390 + "..", [_ | rest] -> rest
391 + "..", [] -> []
392 + part, acc -> [part | acc]
393 + end)
394 + |> Enum.reverse()
395 + |> Enum.join("/")
396 + |> then(&if(absolute?, do: "/" <> &1, else: &1))
397 + end
398 +
399 + defp dirname(url), do: url |> String.split("/") |> Enum.drop(-1) |> Enum.join("/")
400 + defp basename(url), do: url |> String.split("/") |> List.last()
401 +
402 + defp decode_data_url(data) do
403 + case String.split(data, ",", parts: 2) do
404 + [meta, payload] ->
405 + if String.ends_with?(meta, ";base64"),
406 + do: Base.decode64(payload, ignore: :whitespace) |> ok_or_nil(),
407 + else: URI.decode(payload)
408 +
409 + _ ->
410 + nil
411 + end
412 + end
413 +
414 + defp ok_or_nil({:ok, value}), do: value
415 + defp ok_or_nil(_), do: nil
416 +
417 + defp header(headers, name) when is_map(headers) do
418 + Enum.find_value(headers, fn {k, v} ->
419 + if is_binary(v) and String.downcase(k) == name, do: v
420 + end)
421 + end
422 +
423 + defp header(_headers, _name), do: nil
424 +
425 + defp cast_debug_id(id) when is_binary(id) do
426 + # Debug ids may carry an age appendix (`<uuid>-<age>`); JS ones don't.
427 + case String.downcase(id) do
428 + <<a::binary-8, b::binary-4, c::binary-4, d::binary-4, e::binary-12>> ->
429 + Ecto.UUID.cast(Enum.join([a, b, c, d, e], "-"))
430 +
431 + long ->
432 + long |> String.slice(0, 36) |> Ecto.UUID.cast()
433 + end
434 + end
435 +
436 + defp cast_debug_id(_), do: :error
437 +
438 + defp string(value) when is_binary(value) and value != "", do: value
439 + defp string(_), do: nil
440 +end
modified lib/vigil/events/processor.ex
+14 −2
@@ -8,8 +8,10 @@ defmodule Vigil.Events.Processor do
8 8 the project or organization says.
9 9 2. A repeat of an `event_id` already stored for the project in the last
10 10 #{2} days is dropped: SDKs retry.
11 − 3. Stack traces normalised for grouping, title, culprit and metadata
12 − worked out (`Vigil.Grouping`, `Vigil.Events.Metadata`), then hashed
11 + 3. JavaScript frames mapped through uploaded source maps
12 + (`Vigil.Symbolication.JS`). Stack traces normalised for grouping,
13 + title, culprit and metadata worked out (`Vigil.Grouping`,
14 + `Vigil.Events.Metadata`), then hashed
13 15 under the project's grouping strategy, and its previous one too while
14 16 a switch is under way.
15 17 4. The issue any of those hashes points at, or a new one (`PROJ-n` from
@@ -105,6 +107,7 @@ defmodule Vigil.Events.Processor do
105 107
106 108 defp store(project, item, event) do
107 109 config = project.grouping_config
110 + event = symbolicate(project, event)
108 111 event = Grouping.normalize_stacktraces(event, config)
109 112 meta = Metadata.compute(event)
110 113 hashes = hashes(project, event)
@@ -131,6 +134,15 @@ defmodule Vigil.Events.Processor do
131 134 :ok
132 135 end
133 136
137 + # JS frames mapped through uploaded source maps, before anything reads
138 + # them (grouping, title, culprit).
139 + defp symbolicate(project, event) do
140 + Vigil.Symbolication.JS.symbolicate(event, %{
141 + organization_id: project.organization_id,
142 + project_id: project.id
143 + })
144 + end
145 +
134 146 ## Grouping
135 147
136 148 # [{config, hash}], the project's strategy first, then (while switching)
added lib/vigil/sourcemap.ex
+130 −0
@@ -0,0 +1,130 @@
1 +defmodule Vigil.Sourcemap do
2 + @moduledoc """
3 + JavaScript source maps and artifact bundles (ROADMAP.md, slice 5), over
4 + the `vigil_sourcemap` NIF (`Vigil.Sourcemap.Native`).
5 +
6 + * `read_bundle/2`: a sentry-cli artifact bundle zip, its manifest
7 + parsed, every file inflated under a size and count cap;
8 + * `lookup/3`: many minified positions resolved against one map;
9 + * `discover_debug_id/1`, `sourcemap_url/1`: what a minified file says
10 + about itself in its trailing comments.
11 +
12 + ## Artifact bundles
13 +
14 + sentry-cli 2.x writes them with symbolic's `SourceBundleWriter`: an
15 + 8-byte `SYSB` header, then a zip of `files/<scheme>/<host>/<path>`
16 + entries (`~/` urls under `files/_/_/`) and a `manifest.json`:
17 +
18 + {"files": {"files/_/_/static/js/app.min.js": {
19 + "type": "minified_source", "url": "~/static/js/app.min.js",
20 + "headers": {"debug-id": "ce611417-…", "sourcemap": "app.min.js.map"}},
21 + "files/_/_/static/js/app.min.js.map": {
22 + "type": "source_map", "url": "~/static/js/app.min.js.map",
23 + "headers": {"debug-id": "ce611417-…"}}},
24 + "debug_id": "<bundle id>", "org": "o", "project": "p",
25 + "release": "web@1.0.0", "dist": "d1"}
26 +
27 + `project`, `release`, `dist` and `note` are present only when given;
28 + header names are lowercased.
29 + """
30 +
31 + alias Vigil.Sourcemap.Native
32 +
33 + @mib 1024 * 1024
34 +
35 + @type bundle :: %{manifest: map(), files: %{String.t() => binary()}}
36 + @type context :: %{pre: [String.t()], line: String.t(), post: [String.t()]}
37 + @type mapped :: %{
38 + src: String.t() | nil,
39 + line: non_neg_integer(),
40 + col: non_neg_integer(),
41 + name: String.t() | nil,
42 + function: String.t() | nil,
43 + context: context() | nil
44 + }
45 +
46 + @doc """
47 + Unpacks an artifact bundle zip.
48 +
49 + Options: `max_total`, the uncompressed bytes allowed in all (default
50 + 200 MiB), enforced while inflating; `max_files` (default 10 000).
51 +
52 + Errors: `:invalid_zip`, `:no_manifest`, `:invalid_manifest` (not a JSON
53 + object), `:too_large`, `:too_many_files`.
54 + """
55 + @spec read_bundle(binary(), keyword()) ::
56 + {:ok, bundle()}
57 + | {:error,
58 + :invalid_zip | :no_manifest | :invalid_manifest | :too_large | :too_many_files}
59 + def read_bundle(zip, opts \\ []) when is_binary(zip) do
60 + max_total = Keyword.get(opts, :max_total, 200 * @mib)
61 + max_files = Keyword.get(opts, :max_files, 10_000)
62 +
63 + with {:ok, {manifest, files}} <- Native.read_bundle(zip, max_total, max_files) do
64 + case Jason.decode(manifest) do
65 + {:ok, %{} = manifest} -> {:ok, %{manifest: manifest, files: Map.new(files)}}
66 + _ -> {:error, :invalid_manifest}
67 + end
68 + end
69 + end
70 +
71 + @doc """
72 + Resolves minified positions against the source map `map`.
73 +
74 + Each position is `{line, col}` or `{line, col, minified_function_name}`,
75 + all 0-based (Sentry frames are 1-based: subtract one from both). Answers
76 + one entry per position, `nil` where nothing maps: `src`, `line`, `col`
77 + (0-based, original), the token's `name`, `function` (the original name
78 + of the enclosing function, guessed from the minified source and the
79 + frame's minified function name, when `minified_source:` is given), and
80 + `context` (5 lines either side, from `sourcesContent`) or `nil`.
81 +
82 + Index (sectioned) maps are flattened; their sections must be embedded.
83 + """
84 + @spec lookup(binary(), [{non_neg_integer(), non_neg_integer()} | tuple()], keyword()) ::
85 + {:ok, [mapped() | nil]} | {:error, :invalid_map}
86 + def lookup(map, positions, opts \\ []) when is_binary(map) and is_list(positions) do
87 + positions =
88 + Enum.map(positions, fn
89 + {line, col} -> {line, col, nil}
90 + {line, col, name} when is_binary(name) or is_nil(name) -> {line, col, name}
91 + end)
92 +
93 + Native.lookup(map, Keyword.get(opts, :minified_source), positions)
94 + end
95 +
96 + @debug_id ~r"//# debugId=([0-9a-fA-F]{8}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{4}-?[0-9a-fA-F]{12})"
97 + @sourcemap_url ~r{//[#@] sourceMappingURL=(\S+)}
98 +
99 + @doc """
100 + The debug id sentry-cli's `sourcemaps inject` left in a minified file's
101 + trailing `//# debugId=` comment, lowercased and hyphenated; or `nil`.
102 + """
103 + @spec discover_debug_id(binary()) :: String.t() | nil
104 + def discover_debug_id(source) when is_binary(source) do
105 + case Regex.run(@debug_id, tail(source), capture: :all_but_first) do
106 + [id] -> id |> String.downcase() |> hyphenate()
107 + nil -> nil
108 + end
109 + end
110 +
111 + @doc "The url in a minified file's last `//# sourceMappingURL=` comment, or `nil`."
112 + @spec sourcemap_url(binary()) :: String.t() | nil
113 + def sourcemap_url(source) when is_binary(source) do
114 + case Regex.scan(@sourcemap_url, source, capture: :all_but_first) do
115 + [] -> nil
116 + matches -> matches |> List.last() |> hd()
117 + end
118 + end
119 +
120 + # The trailing comments live in the last few lines.
121 + defp tail(source) when byte_size(source) > 4096,
122 + do: binary_part(source, byte_size(source) - 4096, 4096)
123 +
124 + defp tail(source), do: source
125 +
126 + defp hyphenate(<<a::binary-8, b::binary-4, c::binary-4, d::binary-4, e::binary-12>>),
127 + do: Enum.join([a, b, c, d, e], "-")
128 +
129 + defp hyphenate(id), do: id
130 +end
added lib/vigil/sourcemap/native.ex
+27 −0
@@ -0,0 +1,27 @@
1 +defmodule Vigil.Sourcemap.Native do
2 + @moduledoc """
3 + The `native/vigil_sourcemap` Rustler NIF: artifact-bundle zips and source
4 + map lookups, on getsentry's `sourcemap` crate. Use `Vigil.Sourcemap`.
5 + """
6 +
7 + use Rustler, otp_app: :vigil, crate: "vigil_sourcemap"
8 +
9 + @doc """
10 + Unpacks a bundle zip, inflating at most `max_total` bytes in all and
11 + accepting at most `max_files` files besides `manifest.json`:
12 + `{:ok, {manifest_bytes, [{zip_path, bytes}]}}` or `{:error, reason}`.
13 + """
14 + @spec read_bundle(binary(), non_neg_integer(), non_neg_integer()) ::
15 + {:ok, {binary(), [{String.t(), binary()}]}}
16 + | {:error, :invalid_zip | :no_manifest | :too_large | :too_many_files}
17 + def read_bundle(_zip, _max_total, _max_files), do: :erlang.nif_error(:nif_not_loaded)
18 +
19 + @doc """
20 + Parses `map` once and resolves each `{line, col, minified_function_name}`
21 + (0-based), with `minified_source` for the original function name guess.
22 + """
23 + @spec lookup(binary(), binary() | nil, [
24 + {non_neg_integer(), non_neg_integer(), String.t() | nil}
25 + ]) :: {:ok, [map() | nil]} | {:error, :invalid_map}
26 + def lookup(_map, _minified_source, _positions), do: :erlang.nif_error(:nif_not_loaded)
27 +end
added lib/vigil/symbolication/js.ex
+299 −0
@@ -0,0 +1,299 @@
1 +defmodule Vigil.Symbolication.JS do
2 + @moduledoc """
3 + JavaScript symbolication (ROADMAP.md, slice 5): minified frames mapped
4 + back to original source through the project's uploaded source maps
5 + (`Vigil.Artifacts.Lookup`, `Vigil.Sourcemap`), as Sentry's JavaScript
6 + processor does. Runs in `Vigil.Events.Processor` before grouping, so
7 + hashes, title and culprit see the original frames.
8 +
9 + For `javascript` and `node` events, or frames that look like JavaScript
10 + (a `.js`, `.mjs` or `.cjs` `abs_path`), every stack trace in
11 + `exception.values`, `threads.values` and the top-level `stacktrace` is
12 + rewritten. An exception or thread keeps its original as
13 + `raw_stacktrace`. A mapped frame gets:
14 +
15 + * `abs_path`: the token's source resolved against the map's url;
16 + `filename` that without `webpack:///`, `webpack://<ns>/`, `app:///`
17 + and leading `./` and `../` (webpack's `/~/` becomes `~/`);
18 + * `lineno`, `colno`: 1-based, from the 0-based token;
19 + * `function`: the enclosing function's original name, guessed from the
20 + minified source; else the name of the token at the caller's frame
21 + (what was called), as Sentry falls back to; else as it was;
22 + * `pre_context`, `context_line`, `post_context` from `sourcesContent`;
23 + * `data`: `sourcemap` (the map's url) and `symbolicated: true`;
24 + * `in_app`: false under `node_modules/` or webpack's `~/` externals and
25 + bootstrap, otherwise the SDK's value, or true.
26 +
27 + Frames that don't map stay as they were. A frame whose debug id found
28 + nothing, or a map that won't parse, is noted in the event's `errors`
29 + (`js_no_source`, `js_invalid_source`).
30 + """
31 +
32 + require Logger
33 +
34 + alias Vigil.Artifacts.Lookup
35 + alias Vigil.Sourcemap
36 +
37 + @js_platforms ~w(javascript node)
38 + @js_extension ~r/\.(js|mjs|cjs|jsx|jsbundle|bundle)([?#].*)?$/
39 +
40 + @doc """
41 + The event with its JavaScript frames mapped; unchanged when nothing maps
42 + (or anything goes wrong: symbolication never costs an event).
43 + """
44 + @spec symbolicate(map(), %{organization_id: Ecto.UUID.t(), project_id: Ecto.UUID.t()}) ::
45 + map()
46 + def symbolicate(event, scope) when is_map(event) do
47 + js? = event["platform"] in @js_platforms
48 +
49 + frames =
50 + event |> stacktraces() |> Enum.flat_map(&frames/1) |> Enum.filter(&mappable?(&1, js?))
51 +
52 + if frames == [] do
53 + event
54 + else
55 + do_symbolicate(event, frames, scope)
56 + end
57 + rescue
58 + e ->
59 + Logger.warning("JS symbolication failed: " <> Exception.message(e))
60 + event
61 + end
62 +
63 + defp do_symbolicate(event, frames, scope) do
64 + lookup = Lookup.new(event, scope)
65 +
66 + {resolved, errors, _lookup} =
67 + frames
68 + |> Enum.group_by(& &1["abs_path"], &position/1)
69 + |> Enum.reduce({%{}, [], lookup}, fn {abs_path, positions}, {resolved, errors, lookup} ->
70 + {source, lookup} = Lookup.source_for(lookup, abs_path)
71 + {found, error} = resolve(source, abs_path, Enum.uniq(positions), lookup)
72 + {Map.merge(resolved, found), List.wrap(error) ++ errors, lookup}
73 + end)
74 +
75 + if resolved == %{} and errors == [] do
76 + event
77 + else
78 + event
79 + |> rewrite(resolved)
80 + |> add_errors(errors)
81 + end
82 + end
83 +
84 + # {abs_path, lineno, colno, function} => {mapped, map_url}
85 + defp resolve(nil, abs_path, _positions, lookup) do
86 + error =
87 + if Lookup.debug_id?(lookup, abs_path),
88 + do: %{"type" => "js_no_source", "url" => abs_path}
89 +
90 + {%{}, error}
91 + end
92 +
93 + defp resolve(source, abs_path, positions, _lookup) do
94 + queries = for {_path, line, col, function} <- positions, do: {line - 1, col - 1, function}
95 +
96 + case Sourcemap.lookup(source.map, queries, minified_source: source.minified) do
97 + {:ok, results} ->
98 + found =
99 + for {position, %{} = mapped} <- Enum.zip(positions, results),
100 + into: %{},
101 + do: {position, {mapped, source.map_url}}
102 +
103 + {found, nil}
104 +
105 + {:error, :invalid_map} ->
106 + {%{}, %{"type" => "js_invalid_source", "url" => source.map_url || abs_path}}
107 + end
108 + end
109 +
110 + ## Which frames
111 +
112 + defp mappable?(%{"abs_path" => path, "lineno" => line, "colno" => col}, js?)
113 + when is_binary(path) and is_integer(line) and line > 0 and is_integer(col) and col > 0 do
114 + not String.starts_with?(path, ["node:", "internal/", "<", "native"]) and
115 + (js? or Regex.match?(@js_extension, path))
116 + end
117 +
118 + defp mappable?(_frame, _js?), do: false
119 +
120 + defp position(frame) do
121 + function = if is_binary(frame["function"]), do: frame["function"]
122 + {frame["abs_path"], frame["lineno"], frame["colno"], function}
123 + end
124 +
125 + ## Stack traces
126 +
127 + defp stacktraces(event) do
128 + containers =
129 + for key <- ["exception", "threads"],
130 + %{} = item <- List.wrap(get_in(event, [key, "values"])),
131 + is_nil(item["raw_stacktrace"]),
132 + do: item["stacktrace"]
133 +
134 + [event["stacktrace"] | containers] |> Enum.filter(&is_map/1)
135 + end
136 +
137 + defp frames(%{"frames" => frames}) when is_list(frames), do: Enum.filter(frames, &is_map/1)
138 + defp frames(_), do: []
139 +
140 + defp rewrite(event, resolved) do
141 + event
142 + |> update_values("exception", resolved)
143 + |> update_values("threads", resolved)
144 + |> then(fn event ->
145 + case event["stacktrace"] do
146 + %{} = st -> Map.put(event, "stacktrace", elem(map_stacktrace(st, resolved), 0))
147 + _ -> event
148 + end
149 + end)
150 + end
151 +
152 + defp update_values(event, key, resolved) do
153 + case event[key] do
154 + %{"values" => values} = container when is_list(values) ->
155 + values = Enum.map(values, &update_container(&1, resolved))
156 + Map.put(event, key, %{container | "values" => values})
157 +
158 + _ ->
159 + event
160 + end
161 + end
162 +
163 + defp update_container(%{"stacktrace" => %{} = st} = item, resolved) do
164 + if Map.has_key?(item, "raw_stacktrace") do
165 + item
166 + else
167 + case map_stacktrace(st, resolved) do
168 + {_st, false} -> item
169 + {mapped, true} -> item |> Map.put("stacktrace", mapped) |> Map.put("raw_stacktrace", st)
170 + end
171 + end
172 + end
173 +
174 + defp update_container(item, _resolved), do: item
175 +
176 + # Frames are oldest first: the frame before a frame is its caller, and
177 + # the caller's token names what it called.
178 + defp map_stacktrace(%{"frames" => frames} = st, resolved) when is_list(frames) do
179 + {frames, {_caller, changed?}} =
180 + Enum.map_reduce(frames, {nil, false}, fn frame, {caller, changed?} ->
181 + case is_map(frame) && Map.get(resolved, position(frame)) do
182 + {mapped, map_url} ->
183 + {map_frame(frame, mapped, map_url, caller), {mapped, true}}
184 +
185 + _ ->
186 + {frame, {nil, changed?}}
187 + end
188 + end)
189 +
190 + {%{st | "frames" => frames}, changed?}
191 + end
192 +
193 + defp map_stacktrace(st, _resolved), do: {st, false}
194 +
195 + defp map_frame(frame, mapped, map_url, caller) do
196 + src = mapped.src || frame["abs_path"]
197 + abs_path = if map_url, do: Lookup.join_url(map_url, src), else: src
198 + filename = clean_filename(src)
199 +
200 + function =
201 + mapped.function || (caller && caller.name) || frame["function"]
202 +
203 + frame
204 + |> Map.drop(["pre_context", "context_line", "post_context"])
205 + |> Map.merge(%{
206 + "abs_path" => abs_path,
207 + "filename" => filename,
208 + "lineno" => mapped.line + 1,
209 + "colno" => mapped.col + 1,
210 + "in_app" => in_app(filename, abs_path, frame["in_app"]),
211 + "data" => Map.merge(data(frame), %{"sourcemap" => map_url, "symbolicated" => true})
212 + })
213 + |> put_present("function", function)
214 + |> put_context(mapped.context)
215 + end
216 +
217 + defp data(%{"data" => %{} = data}), do: data
218 + defp data(_frame), do: %{}
219 +
220 + defp put_context(frame, %{pre: pre, line: line, post: post}) do
221 + Map.merge(frame, %{"pre_context" => pre, "context_line" => line, "post_context" => post})
222 + end
223 +
224 + defp put_context(frame, _), do: frame
225 +
226 + defp put_present(map, _key, nil), do: map
227 + defp put_present(map, key, value), do: Map.put(map, key, value)
228 +
229 + @doc """
230 + A mapped source path as a frame shows it: no `webpack:///`,
231 + `webpack://<namespace>/` or `app:///` prefix, no leading `./` or `../`,
232 + webpack's `/~/` (resolver root, i.e. node_modules) as `~/`, and only the
233 + path of an http(s) url.
234 +
235 + iex> Vigil.Symbolication.JS.clean_filename("webpack://my-app/./src/index.ts")
236 + "src/index.ts"
237 + iex> Vigil.Symbolication.JS.clean_filename("../../src/config.ts")
238 + "src/config.ts"
239 + """
240 + @spec clean_filename(String.t()) :: String.t()
241 + def clean_filename(path) do
242 + path =
243 + cond do
244 + String.contains?(path, "/~/") ->
245 + "~/" <> (path |> String.split("/~/", parts: 2) |> List.last())
246 +
247 + String.starts_with?(path, "webpack:///") ->
248 + String.replace_prefix(path, "webpack:///", "")
249 +
250 + String.starts_with?(path, "webpack://") ->
251 + path |> String.replace_prefix("webpack://", "") |> drop_segment()
252 +
253 + String.starts_with?(path, "app:///") ->
254 + String.replace_prefix(path, "app:///", "")
255 +
256 + String.starts_with?(path, ["http://", "https://"]) ->
257 + case URI.new(path) do
258 + {:ok, %URI{path: "/" <> rest}} -> rest
259 + _ -> path
260 + end
261 +
262 + true ->
263 + path
264 + end
265 +
266 + strip_relative(path)
267 + end
268 +
269 + defp drop_segment(path) do
270 + case String.split(path, "/", parts: 2) do
271 + [_namespace, rest] -> rest
272 + [only] -> only
273 + end
274 + end
275 +
276 + defp strip_relative("./" <> rest), do: strip_relative(rest)
277 + defp strip_relative("../" <> rest), do: strip_relative(rest)
278 + defp strip_relative(path), do: path
279 +
280 + defp in_app(filename, abs_path, sdk_value) do
281 + vendored? =
282 + String.contains?(filename, "node_modules/") or String.contains?(abs_path, "node_modules/") or
283 + String.starts_with?(filename, ["~/", "webpack/bootstrap", "(webpack)", "external "]) or
284 + String.contains?(abs_path, "/~/")
285 +
286 + cond do
287 + vendored? -> false
288 + is_boolean(sdk_value) -> sdk_value
289 + true -> true
290 + end
291 + end
292 +
293 + defp add_errors(event, []), do: event
294 +
295 + defp add_errors(event, errors) do
296 + existing = if is_list(event["errors"]), do: event["errors"], else: []
297 + Map.put(event, "errors", Enum.uniq(existing ++ Enum.reverse(errors)))
298 + end
299 +end
added native/vigil_sourcemap/Cargo.lock
+798 −0

Click to load diff…

added native/vigil_sourcemap/Cargo.toml
+30 −0

Click to load diff…

added native/vigil_sourcemap/src/lib.rs
+272 −0

Click to load diff…

added test/support/fixtures/sourcemap_fixtures.ex
+107 −0

Click to load diff…

modified ?
+0 −0

Click to load diff…

added test/support/fixtures/sourcemaps/dist/app.min.js
+2 −0

Click to load diff…

added test/support/fixtures/sourcemaps/dist/app.min.js.map
+7 −0

Click to load diff…

added test/support/fixtures/sourcemaps/injected/app.min.js
+6 −0

Click to load diff…

added test/support/fixtures/sourcemaps/injected/app.min.js.map
+1 −0

Click to load diff…

added test/support/fixtures/sourcemaps/src/app.ts
+14 −0

Click to load diff…

added test/support/fixtures/sourcemaps/src/config.ts
+13 −0

Click to load diff…

added test/vigil/artifacts/lookup_test.exs
+190 −0

Click to load diff…

added test/vigil/events/processor_symbolication_test.exs
+121 −0

Click to load diff…

added test/vigil/sourcemap_test.exs
+177 −0

Click to load diff…

added test/vigil/symbolication/js_test.exs
+229 −0

Click to load diff…

Parents: 657cace