Slice 5: releases, sentry-cli and sourcemaps

145dcb0 · gmorell · 2026-12-02 02:17

14 files +255 -15

Files changed

modified ROADMAP.md
+9 −1
@@ -314,7 +314,7 @@ libraries to the images.
314 314 - Email goes to members who can see the project minus opt-outs. Webhook payloads are ported from GlitchTip (Slack-compatible, Discord, Google Chat, ntfy, Teams, Zulip), with "and N more" past 3 issues.
315 315 - `Vigil.Outbound` refuses private, loopback, link-local, CGNAT and reserved addresses, v4 and v6 (mapped, NAT64, 6to4), and hosts that don't resolve; such deliveries fail without retrying. DNS rebinding is a known limitation.
316 316
317 −### 5. Releases, sentry-cli and sourcemaps · large
317 +### 5. Releases, sentry-cli and sourcemaps · large · **done**
318 318 The `/api/0` API:
319 319 - `GET /api/0/` returns user and token info.
320 320 - **Releases:**
@@ -340,6 +340,14 @@ The `/api/0` API:
340 340 - File storage behind a small behaviour, with local disk and S3 (Req's `aws_sigv4`, as cartosnap does).
341 341 - **UI:** releases list and detail (new, resolved and regressed issues, deploys, artifacts). Issues gain "resolve in next release".
342 342 - **Exit:** `sentry-cli releases new/finalize/deploys`, `sourcemaps upload --wait` and a minified-JS error together give a readable stacktrace.
343 +- **As built:**
344 + - Release create is idempotent on both paths: 201 when new or newly linked, otherwise 208, as 2019 Sentry answers. `archive`/`restore` arrive as an org-path POST with `status`. Commits and refs from PUT are kept in `data`. Lists use Sentry's cursor Link headers. A token sees only releases of projects it can see.
345 + - Chunk upload advertises `release_files`, `artifact_bundles` and `artifact_bundles_v2`. sentry-cli 2.58 only chunks source maps at all when `release_files` is offered. With no project named it uses the release-bound `releases/{v}/assemble/`, which assembles into the release's projects.
346 + - Chunks are gzip-capped, SHA-1-checked and kept per org in `Vigil.Storage` (local disk or S3). The assemble job checks the whole SHA-1, reads the bundle with the `vigil_sourcemap` NIF (capped while inflating; sentry-cli's `SYSB` header is handled) and extracts files with their debug ids. An `error` is reported once, so a re-upload retries. Blobs and statuses are dropped after a day.
347 + - Symbolication runs before grouping, so hashes, title and culprit use the mapped frames. It looks up by debug id, then release + dist + url (`~/`, `app:///`, `webpack://`), then the `sourcemap` header, `sourceMappingURL` or `<url>.map`. `raw_stacktrace` is kept, and it can never drop an event.
348 + - Regressions follow Sentry's GroupResolution. Resolved in X: X or newer reopens it. Resolved in the next release: only newer than the latest reopens it. Events without a release don't reopen. Release order is creation order, from UUIDv7 ids.
349 + - The release page's "regressed" list is approximate ("earlier issues seen in this release"), since no regression history is kept yet.
350 + - Tested end to end with the real sentry-cli 2.58.2: releases, deploys, set-commits, and `sourcemaps upload --wait` to a symbolicated event.
343 351
344 352 ### 6. Performance · large
345 353 - **Storage:**
modified lib/vigil/artifacts.ex
+20 −12
@@ -54,7 +54,10 @@ defmodule Vigil.Artifacts do
54 54 concurrency: 4,
55 55 hashAlgorithm: "sha1",
56 56 compression: ["gzip"],
57 − accept: ["artifact_bundles", "artifact_bundles_v2"]
57 + # sentry-cli only chunks source maps at all when release_files is
58 + # offered; with projects named it then sends artifact bundles, and
59 + # without, the release-bound assemble (`assemble_for_release/3`).
60 + accept: ["release_files", "artifact_bundles", "artifact_bundles_v2"]
58 61 }
59 62 end
60 63
@@ -170,6 +173,22 @@ defmodule Vigil.Artifacts do
170 173 end
171 174 end
172 175
176 + @doc """
177 + The legacy, release-bound assemble (`POST /organizations/{org}/releases/
178 + {version}/assemble/`), which sentry-cli uses when no project is named:
179 + the same bundle, for the release's projects the caller can see.
180 + """
181 + def assemble_for_release(%Scope{} = scope, version, params) do
182 + case Releases.get_release(scope, version) do
183 + nil ->
184 + {:error, 404, "Release not found"}
185 +
186 + release ->
187 + projects = Enum.map(release.projects, & &1.slug)
188 + assemble(scope, Map.merge(params, %{"projects" => projects, "version" => version}))
189 + end
190 + end
191 +
173 192 defp valid_request(checksum, chunks) do
174 193 if Regex.match?(@sha1, checksum) and Enum.all?(chunks, &Regex.match?(@sha1, &1)),
175 194 do: :ok,
@@ -430,17 +449,6 @@ defmodule Vigil.Artifacts do
430 449 )
431 450 end
432 451
433 − @doc "The artifact bundles of a release in a project, newest first."
434 − def list_bundles(project_id, version) do
435 − Repo.all(
436 − from b in ArtifactBundle,
437 − join: bp in "artifact_bundle_projects",
438 − on: bp.artifact_bundle_id == b.id,
439 − where: bp.project_id == type(^project_id, :binary_id) and b.release == ^version,
440 − order_by: [desc: b.id]
441 − )
442 − end
443 −
444 452 @doc """
445 453 Drops chunk blobs and assemble statuses older than `max_age_seconds`
446 454 (a day): blobs only matter until their bundle is assembled.
modified lib/vigil_web/api/v0/artifact_controller.ex
+12 −0
@@ -44,6 +44,18 @@ defmodule VigilWeb.Api.V0.ArtifactController do
44 44 end
45 45 end
46 46
47 + def assemble_release(conn, %{"org" => slug, "version" => version} = params) do
48 + with {:ok, conn} <- Auth.put_org(conn, slug),
49 + {:ok, conn} <- require_upload(conn) do
50 + case Artifacts.assemble_for_release(conn.assigns.current_scope, version, params) do
51 + {:ok, response} -> json(conn, response)
52 + {:error, status, detail} -> Auth.json_error(conn, status, detail)
53 + end
54 + else
55 + {:error, conn} -> conn
56 + end
57 + end
58 +
47 59 defp require_upload(conn) do
48 60 scope = conn.assigns.current_scope
49 61
modified lib/vigil_web/router.ex
+1 −0
@@ -60,6 +60,7 @@ defmodule VigilWeb.Router do
60 60 get "/organizations/:org/chunk-upload", ArtifactController, :chunk_options
61 61 post "/organizations/:org/chunk-upload", ArtifactController, :upload_chunks
62 62 post "/organizations/:org/artifactbundle/assemble", ArtifactController, :assemble
63 + post "/organizations/:org/releases/:version/assemble", ArtifactController, :assemble_release
63 64
64 65 # Anything else: GlitchTip's JSON 404, which sentry-cli reads as
65 66 # "not supported here".
modified test/vigil_web/api/artifact_upload_test.exs
+35 −2
@@ -138,6 +138,39 @@ defmodule VigilWeb.ArtifactUploadTest do
138 138 assert [_] = all_enqueued(worker: AssembleWorker)
139 139 end
140 140
141 + test "the release-bound assemble uses the release's projects", ctx do
142 + Vigil.Releases.ensure_release(ctx.org.id, ctx.project.id, "web@3.0")
143 + data = "bundle"
144 + checksum = sha1(data)
145 + :ok = Artifacts.store_chunks(scope(ctx), [write_gz(data)])
146 +
147 + assert %{"state" => "created"} =
148 + ctx.conn
149 + |> bearer(ctx.token)
150 + |> put_req_header("content-type", "application/json")
151 + |> post(
152 + "/api/0/organizations/#{ctx.org.slug}/releases/web%403.0/assemble/",
153 + Jason.encode!(%{checksum: checksum, chunks: [checksum]})
154 + )
155 + |> json_response(200)
156 +
157 + project_id = ctx.project.id
158 +
159 + assert_enqueued(
160 + worker: AssembleWorker,
161 + args: %{checksum: checksum, version: "web@3.0", project_ids: [project_id]}
162 + )
163 +
164 + assert build_conn()
165 + |> bearer(ctx.token)
166 + |> put_req_header("content-type", "application/json")
167 + |> post(
168 + "/api/0/organizations/#{ctx.org.slug}/releases/nope/assemble/",
169 + Jason.encode!(%{checksum: checksum, chunks: [checksum]})
170 + )
171 + |> json_response(404)
172 + end
173 +
141 174 test "a project the token can't see is a 404", ctx do
142 175 checksum = sha1("x")
143 176
@@ -200,8 +233,8 @@ defmodule VigilWeb.ArtifactUploadTest do
200 233 assert map.debug_id == minified.debug_id
201 234 assert {:ok, "function a(){}"} = Vigil.Storage.get(minified.storage_key)
202 235
203 − assert Vigil.Releases.ensure_release(ctx.org.id, ctx.project.id, "web@1.2.0")
204 − assert [%ArtifactBundle{}] = Artifacts.list_bundles(ctx.project.id, "web@1.2.0")
236 + release = Vigil.Releases.ensure_release(ctx.org.id, ctx.project.id, "web@1.2.0")
237 + assert [%ArtifactBundle{}] = Vigil.Releases.list_artifact_bundles(release, ctx.project)
205 238 assert Repo.aggregate(ArtifactFile, :count) == 2
206 239 end
207 240
added test/vigil_web/sentry_cli_sourcemaps_test.exs
+178 −0
@@ -0,0 +1,178 @@
1 +defmodule VigilWeb.SentryCliSourcemapsTest do
2 + @moduledoc """
3 + Slice 5's exit: the real sentry-cli (on PATH, or `SENTRY_CLI`) creates
4 + and finalizes a release, uploads source maps with `--wait` (chunk
5 + upload, assemble, `ok`), and a minified-JS error then reads as the
6 + TypeScript it came from. Skipped when there is no binary.
7 + """
8 + use VigilWeb.ConnCase, async: false
9 +
10 + import Vigil.AccountsFixtures
11 + import Vigil.OrganizationsFixtures
12 +
13 + alias Vigil.{ApiTokens, Ingest, Issues, Repo}
14 + alias Vigil.Artifacts.ArtifactBundle
15 + alias Vigil.Ingest.{Drain, Envelope}
16 +
17 + @cli System.get_env("SENTRY_CLI") || System.find_executable("sentry-cli")
18 + @abs_path "https://example.com/static/js/app.min.js"
19 + @release "web@2.0.0"
20 +
21 + setup do
22 + owner = user_fixture()
23 + org = organization_fixture(owner)
24 + scope = org_scope(owner, org)
25 + project = project_fixture(scope, %{"name" => "web"})
26 +
27 + {:ok, token} =
28 + ApiTokens.create_token(owner, %{
29 + label: "cli",
30 + scopes: ["project:releases", "project:read", "org:read"]
31 + })
32 +
33 + server = start_supervised!({Bandit, plug: VigilWeb.Endpoint, port: 0, ip: :loopback})
34 + {:ok, {_ip, port}} = ThousandIsland.listener_info(server)
35 +
36 + env = [
37 + {"SENTRY_URL", "http://127.0.0.1:#{port}"},
38 + {"SENTRY_AUTH_TOKEN", token.token},
39 + {"SENTRY_ORG", org.slug},
40 + {"SENTRY_PROJECT", project.slug},
41 + {"SENTRY_LOG_LEVEL", "warn"},
42 + {"SENTRY_DISABLE_UPDATE_CHECK", "true"},
43 + {"SENTRY_LOAD_DOTENV", "0"}
44 + ]
45 +
46 + %{env: env, org: org, project: project}
47 + end
48 +
49 + defp ok!(env, args) do
50 + {out, status} =
51 + System.cmd(@cli, args, env: env, stderr_to_stdout: true, cd: System.tmp_dir!())
52 +
53 + assert status == 0, "sentry-cli #{Enum.join(args, " ")} failed:\n#{out}"
54 + out
55 + end
56 +
57 + # Oban runs jobs only when asked in tests: run the assemble jobs while
58 + # sentry-cli polls for them.
59 + defp run_jobs_meanwhile do
60 + parent = self()
61 +
62 + task =
63 + Task.async(fn ->
64 + Ecto.Adapters.SQL.Sandbox.allow(Repo, parent, self())
65 +
66 + Stream.repeatedly(fn -> Oban.drain_queue(queue: :processing) end)
67 + |> Enum.reduce_while(nil, fn _, _ ->
68 + receive do
69 + :stop -> {:halt, :ok}
70 + after
71 + 100 -> {:cont, nil}
72 + end
73 + end)
74 + end)
75 +
76 + fn ->
77 + send(task.pid, :stop)
78 + Task.await(task)
79 + end
80 + end
81 +
82 + @tag :sdk
83 + @tag :tmp_dir
84 + test "release, sourcemaps upload --wait, and a readable stacktrace", ctx do
85 + if @cli do
86 + %{env: env, project: project, org: org} = ctx
87 +
88 + dir = Path.join(ctx.tmp_dir, "static/js")
89 + File.mkdir_p!(dir)
90 + File.cp_r!("test/support/fixtures/sourcemaps/injected", dir)
91 +
92 + ok!(env, ["releases", "new", @release])
93 +
94 + stop = run_jobs_meanwhile()
95 +
96 + out =
97 + ok!(env, [
98 + "sourcemaps",
99 + "upload",
100 + "--release",
101 + @release,
102 + "--url-prefix",
103 + "~/static/js",
104 + "--wait",
105 + dir
106 + ])
107 +
108 + stop.()
109 + assert out =~ "File processing complete"
110 +
111 + assert [%ArtifactBundle{release: @release, artifact_count: 2}] =
112 + Vigil.Releases.list_artifact_bundles(
113 + Vigil.Releases.ensure_release(org.id, project.id, @release),
114 + project
115 + )
116 +
117 + ok!(env, ["releases", "finalize", @release])
118 +
119 + target = %Ingest.Target{
120 + project_id: project.id,
121 + dsn_id: project.dsn_id,
122 + organization_id: org.id,
123 + key_id: Ecto.UUID.generate()
124 + }
125 +
126 + item = %Envelope.Item{
127 + type: "event",
128 + headers: %{"type" => "event"},
129 + payload: Jason.encode!(minified_error())
130 + }
131 +
132 + Ingest.accept(target, %{headers: %{}, items: [item]}, %{client_ip: nil, user_agent: nil})
133 + Drain.drain(project.id)
134 +
135 + [issue] = Repo.all(Vigil.Issues.Issue)
136 + event = Issues.latest_event(issue)
137 + [exception] = event.data["exception"]["values"]
138 + frames = exception["stacktrace"]["frames"]
139 +
140 + assert Enum.any?(frames, &(&1["filename"] =~ "app.ts" and &1["function"] == "startApp"))
141 + assert Enum.all?(frames, &get_in(&1, ["data", "symbolicated"]))
142 + assert exception["raw_stacktrace"]["frames"] |> hd() |> Map.get("lineno") == 3
143 + else
144 + IO.puts("skipping sentry-cli sourcemaps: no sentry-cli on PATH")
145 + end
146 + end
147 +
148 + # What @sentry/browser sends for startApp("{}") on the injected bundle,
149 + # matched by url (and release), as no debug_meta is sent.
150 + defp minified_error do
151 + frames =
152 + for {function, col} <- [{"o", 217}, {"n", 182}, {"t", 77}] do
153 + %{
154 + "function" => function,
155 + "abs_path" => @abs_path,
156 + "filename" => @abs_path,
157 + "lineno" => 3,
158 + "colno" => col,
159 + "in_app" => true
160 + }
161 + end
162 +
163 + %{
164 + "event_id" => Vigil.Schema.uuid7() |> String.replace("-", ""),
165 + "platform" => "javascript",
166 + "release" => @release,
167 + "exception" => %{
168 + "values" => [
169 + %{
170 + "type" => "Error",
171 + "value" => "retries must be a number",
172 + "stacktrace" => %{"frames" => frames}
173 + }
174 + ]
175 + }
176 + }
177 + end
178 +end

Parents: 970bb0d