Chunk upload, artifact-bundle assemble and blob cleanup

5dd02d6 · gmorell · 2026-12-02 02:06

19 files +881 -2

Files changed

modified config/config.exs
+3 −1
@@ -51,7 +51,9 @@ config :vigil, Oban,
51 51 # Partitions ahead of time for the partitioned tables (Vigil.Partitions).
52 52 {"17 3 * * *", Vigil.Partitions.MaintainWorker},
53 53 # Alert rules against the issues events touched (Vigil.Alerts).
54 − {"* * * * *", Vigil.Alerts.EvaluateWorker}
54 + {"* * * * *", Vigil.Alerts.EvaluateWorker},
55 + # Chunk blobs and assemble statuses past a day (Vigil.Artifacts).
56 + {"41 3 * * *", Vigil.Artifacts.CleanupWorker}
55 57 ]}
56 58 ]
57 59
added lib/vigil/artifacts.ex
+458 −0
@@ -0,0 +1,458 @@
1 +defmodule Vigil.Artifacts do
2 + @moduledoc """
3 + sentry-cli's chunked upload and artifact-bundle assemble
4 + (`sentry-cli sourcemaps upload`):
5 +
6 + 1. `GET /organizations/{org}/chunk-upload/`: `chunk_options/1`, what
7 + the server takes (chunk size, sha1, gzip, `artifact_bundles(_v2)`).
8 + 2. `POST /organizations/{org}/artifactbundle/assemble/` with the
9 + bundle's checksum and its chunks' (`assemble/2`): with
10 + `artifact_bundles_v2` sentry-cli asks first, and uploads only the
11 + chunks answered `not_found`.
12 + 3. `POST /organizations/{org}/chunk-upload/`: gzipped chunks named by
13 + their SHA-1 (`store_chunks/2`). Each is checked against its name,
14 + which GlitchTip doesn't do, and kept per organization.
15 + 4. `assemble/2` again: once every chunk is here an
16 + `Vigil.Artifacts.AssembleWorker` job joins them, checks the whole
17 + SHA-1, and extracts the bundle into `ArtifactFile`s. sentry-cli polls
18 + through `created` and `assembling` to `ok` or `error` (`--wait`);
19 + GlitchTip never answers `ok`.
20 +
21 + Blobs are only needed until a bundle is assembled; `CleanupWorker` drops
22 + them, and old assemble statuses, after a day.
23 + """
24 +
25 + import Ecto.Query
26 +
27 + alias Vigil.Accounts.Scope
28 + alias Vigil.Artifacts.{ArtifactBundle, ArtifactFile, AssembleStatus, AssembleWorker, FileBlob}
29 + alias Vigil.{Projects, Releases, Repo, Storage}
30 +
31 + require Logger
32 +
33 + @chunk_size 8 * 1024 * 1024
34 + @chunks_per_request 64
35 + @max_request_size 32 * 1024 * 1024
36 + # The assembled bundle is held in memory, so this is kept well short of
37 + # what sentry-cli would otherwise send.
38 + @max_file_size 256 * 1024 * 1024
39 + @max_bundle_contents 512 * 1024 * 1024
40 +
41 + @sha1 ~r/\A[0-9a-f]{40}\z/
42 +
43 + @doc "The chunk-upload options for an organization, as sentry-cli reads them."
44 + def chunk_options(org_slug) do
45 + %{
46 + # Relative: sentry-cli resolves it against its own SENTRY_URL, so a
47 + # proxy's host and scheme never matter.
48 + url: "/api/0/organizations/#{org_slug}/chunk-upload/",
49 + chunkSize: @chunk_size,
50 + chunksPerRequest: @chunks_per_request,
51 + maxRequestSize: @max_request_size,
52 + maxFileSize: @max_file_size,
53 + maxWait: 0,
54 + concurrency: 4,
55 + hashAlgorithm: "sha1",
56 + compression: ["gzip"],
57 + accept: ["artifact_bundles", "artifact_bundles_v2"]
58 + }
59 + end
60 +
61 + @doc "The most a chunk-upload request body may be (the multipart parser's cap)."
62 + def max_request_size, do: @max_request_size
63 +
64 + @doc """
65 + Stores uploaded chunks for the scope's organization: `uploads` are
66 + `{name, path}` pairs, `name` the SHA-1 sentry-cli names each by and
67 + `path` its gzipped bytes. Every chunk must inflate to at most the chunk
68 + size and hash to its name, or nothing more is stored and the error says
69 + which. Chunks already held are skipped.
70 + """
71 + def store_chunks(%Scope{organization: org}, uploads) do
72 + with :ok <- check_count(uploads) do
73 + Enum.reduce_while(uploads, :ok, fn {name, path}, :ok ->
74 + case store_chunk(org.id, String.downcase(name || ""), path) do
75 + :ok -> {:cont, :ok}
76 + {:error, _} = error -> {:halt, error}
77 + end
78 + end)
79 + end
80 + end
81 +
82 + defp check_count(uploads) when length(uploads) > @chunks_per_request,
83 + do: {:error, "Too many chunks"}
84 +
85 + defp check_count(_), do: :ok
86 +
87 + defp store_chunk(org_id, checksum, path) do
88 + with :ok <- valid_checksum(checksum),
89 + {:ok, gz} <- File.read(path),
90 + {:ok, data} <- inflate(gz),
91 + :ok <- matches(data, checksum) do
92 + if Repo.exists?(blob_query(org_id, [checksum])),
93 + do: :ok,
94 + else: put_blob(org_id, checksum, data)
95 + else
96 + {:error, reason} when is_binary(reason) -> {:error, reason}
97 + {:error, _} -> {:error, "Could not read chunk #{checksum}"}
98 + end
99 + end
100 +
101 + defp valid_checksum(checksum) do
102 + if Regex.match?(@sha1, checksum), do: :ok, else: {:error, "Invalid chunk name"}
103 + end
104 +
105 + defp inflate(gz) do
106 + case Vigil.Ingest.Codec.decode(gz, "gzip", @chunk_size) do
107 + {:ok, data} -> {:ok, data}
108 + {:error, :too_large} -> {:error, "Chunk size too large"}
109 + {:error, _} -> {:error, "Chunk is not valid gzip"}
110 + end
111 + end
112 +
113 + defp matches(data, checksum) do
114 + if sha1(data) == checksum, do: :ok, else: {:error, "Chunk checksum mismatch (#{checksum})"}
115 + end
116 +
117 + defp put_blob(org_id, checksum, data) do
118 + key = "blobs/#{org_id}/#{checksum}"
119 +
120 + with :ok <- Storage.put(key, data) do
121 + Repo.insert_all(
122 + FileBlob,
123 + [
124 + %{
125 + id: Vigil.Schema.uuid7(),
126 + organization_id: org_id,
127 + checksum: checksum,
128 + size: byte_size(data),
129 + storage_key: key,
130 + inserted_at: DateTime.utc_now(:second)
131 + }
132 + ],
133 + on_conflict: :nothing,
134 + conflict_target: [:organization_id, :checksum]
135 + )
136 +
137 + :ok
138 + end
139 + end
140 +
141 + defp blob_query(org_id, checksums),
142 + do: from(b in FileBlob, where: b.organization_id == ^org_id and b.checksum in ^checksums)
143 +
144 + @doc """
145 + An artifact-bundle assemble request, `params` as sentry-cli sends them
146 + (`checksum`, `chunks`, `projects` (slugs), `version`, `dist`). Answers
147 + `{:ok, %{state:, missingChunks:, detail:}}`, or `{:error, status,
148 + detail}` for a bad request or a project the caller can't see.
149 + """
150 + def assemble(%Scope{organization: org} = scope, params) do
151 + checksum = params |> Map.get("checksum", "") |> to_string() |> String.downcase()
152 +
153 + chunks =
154 + params |> Map.get("chunks", []) |> List.wrap() |> Enum.map(&String.downcase(to_string(&1)))
155 +
156 + with :ok <- valid_request(checksum, chunks),
157 + {:ok, projects} <- assemble_projects(scope, Map.get(params, "projects", [])) do
158 + case Repo.get_by(AssembleStatus, organization_id: org.id, checksum: checksum) do
159 + # An error is told once, then forgotten, so uploading again retries.
160 + %AssembleStatus{state: :error} = status ->
161 + Repo.delete(status)
162 + {:ok, response(:error, [], status.detail)}
163 +
164 + %AssembleStatus{} = status ->
165 + {:ok, response(status.state, [], status.detail)}
166 +
167 + nil ->
168 + start_assemble(org, checksum, chunks, projects, params)
169 + end
170 + end
171 + end
172 +
173 + defp valid_request(checksum, chunks) do
174 + if Regex.match?(@sha1, checksum) and Enum.all?(chunks, &Regex.match?(@sha1, &1)),
175 + do: :ok,
176 + else: {:error, 400, "Invalid checksum"}
177 + end
178 +
179 + defp assemble_projects(scope, slugs) when is_list(slugs) and slugs != [] do
180 + visible = scope |> Projects.list_visible() |> Map.new(&{&1.slug, &1})
181 +
182 + Enum.reduce_while(slugs, {:ok, []}, fn slug, {:ok, acc} ->
183 + case Map.fetch(visible, to_string(slug)) do
184 + {:ok, project} -> {:cont, {:ok, [project | acc]}}
185 + :error -> {:halt, {:error, 404, "Project not found: #{slug}"}}
186 + end
187 + end)
188 + end
189 +
190 + defp assemble_projects(_scope, _),
191 + do: {:error, 400, "projects: at least one project is required"}
192 +
193 + defp start_assemble(org, checksum, chunks, projects, params) do
194 + held =
195 + Repo.all(from b in blob_query(org.id, chunks), select: b.checksum) |> MapSet.new()
196 +
197 + case Enum.reject(Enum.uniq(chunks), &MapSet.member?(held, &1)) do
198 + [] when chunks != [] ->
199 + now = DateTime.utc_now(:second)
200 +
201 + Repo.insert_all(
202 + AssembleStatus,
203 + [
204 + %{
205 + id: Vigil.Schema.uuid7(),
206 + organization_id: org.id,
207 + checksum: checksum,
208 + state: :created,
209 + inserted_at: now,
210 + updated_at: now
211 + }
212 + ],
213 + on_conflict: :nothing,
214 + conflict_target: [:organization_id, :checksum]
215 + )
216 +
217 + %{
218 + organization_id: org.id,
219 + checksum: checksum,
220 + chunks: chunks,
221 + project_ids: Enum.map(projects, & &1.id),
222 + version: blank_to_nil(params["version"]),
223 + dist: blank_to_nil(params["dist"])
224 + }
225 + |> AssembleWorker.new()
226 + |> Oban.insert!()
227 +
228 + {:ok, response(:created, [], nil)}
229 +
230 + missing ->
231 + {:ok, response(:not_found, missing, nil)}
232 + end
233 + end
234 +
235 + defp response(state, missing, detail),
236 + do: %{state: to_string(state), missingChunks: missing, detail: detail}
237 +
238 + defp blank_to_nil(v) when v in [nil, ""], do: nil
239 + defp blank_to_nil(v), do: to_string(v)
240 +
241 + @doc """
242 + Assembles a bundle (the `AssembleWorker` job): joins its chunks, checks
243 + the whole SHA-1, and extracts it. Records `ok` or `error` on the
244 + assemble status either way.
245 + """
246 + def run_assemble(%{"organization_id" => org_id, "checksum" => checksum} = args) do
247 + set_status(org_id, checksum, :assembling, nil)
248 +
249 + case do_assemble(args) do
250 + {:ok, bundle} ->
251 + set_status(org_id, checksum, :ok, nil)
252 + {:ok, bundle}
253 +
254 + {:error, detail} ->
255 + Logger.warning("artifact bundle #{checksum} failed: #{detail}")
256 + set_status(org_id, checksum, :error, detail)
257 + {:error, detail}
258 + end
259 + end
260 +
261 + defp do_assemble(%{"organization_id" => org_id, "checksum" => checksum} = args) do
262 + case Repo.get_by(ArtifactBundle, organization_id: org_id, checksum: checksum) do
263 + %ArtifactBundle{} = bundle ->
264 + # Uploaded before (to other projects, say): link these too.
265 + link_projects(bundle, args["project_ids"])
266 + ensure_releases(org_id, args)
267 + {:ok, bundle}
268 +
269 + nil ->
270 + with {:ok, zip} <- join_chunks(org_id, args["chunks"]),
271 + :ok <- check_whole(zip, checksum),
272 + {:ok, %{manifest: manifest, files: files}} <- read_bundle(zip) do
273 + save_bundle(args, byte_size(zip), manifest, files)
274 + end
275 + end
276 + end
277 +
278 + defp join_chunks(org_id, chunks) do
279 + blobs = Repo.all(blob_query(org_id, chunks)) |> Map.new(&{&1.checksum, &1})
280 +
281 + Enum.reduce_while(chunks, {:ok, [], 0}, fn checksum, {:ok, acc, size} ->
282 + with %FileBlob{} = blob <- Map.get(blobs, checksum),
283 + true <- size + blob.size <= @max_file_size || :too_large,
284 + {:ok, data} <- Storage.get(blob.storage_key) do
285 + {:cont, {:ok, [acc, data], size + blob.size}}
286 + else
287 + :too_large -> {:halt, {:error, "Bundle is larger than #{@max_file_size} bytes"}}
288 + _ -> {:halt, {:error, "Chunk #{checksum} is missing"}}
289 + end
290 + end)
291 + |> case do
292 + {:ok, iodata, _size} -> {:ok, IO.iodata_to_binary(iodata)}
293 + error -> error
294 + end
295 + end
296 +
297 + defp check_whole(zip, checksum) do
298 + if sha1(zip) == checksum, do: :ok, else: {:error, "Bundle checksum mismatch"}
299 + end
300 +
301 + defp read_bundle(zip) do
302 + case Vigil.Sourcemap.read_bundle(zip, max_total: @max_bundle_contents) do
303 + {:ok, bundle} -> {:ok, bundle}
304 + {:error, :no_manifest} -> {:error, "Bundle has no manifest.json"}
305 + {:error, :too_large} -> {:error, "Bundle contents are too large"}
306 + {:error, :too_many_files} -> {:error, "Bundle has too many files"}
307 + {:error, _} -> {:error, "Bundle is not a valid zip"}
308 + end
309 + end
310 +
311 + defp save_bundle(args, size, manifest, files) do
312 + org_id = args["organization_id"]
313 + bundle_id = Vigil.Schema.uuid7()
314 + entries = manifest_entries(manifest, files)
315 + release = args["version"] || string(manifest["release"])
316 + dist = args["dist"] || string(manifest["dist"])
317 +
318 + # Files go to storage first; a failed transaction leaves only orphans
319 + # for the cleanup to find, never rows without their bytes.
320 + with {:ok, rows} <- store_files(org_id, bundle_id, entries),
321 + {:ok, bundle} <- insert_bundle(args, bundle_id, size, manifest, release, dist, rows) do
322 + ensure_releases(org_id, %{args | "version" => release})
323 + {:ok, bundle}
324 + end
325 + end
326 +
327 + defp store_files(org_id, bundle_id, entries) do
328 + Enum.reduce_while(entries, {:ok, []}, fn {path, info, data}, {:ok, acc} ->
329 + file_id = Vigil.Schema.uuid7()
330 + key = "artifacts/#{org_id}/#{bundle_id}/#{file_id}"
331 + headers = normalize_headers(info["headers"])
332 +
333 + case Storage.put(key, data) do
334 + :ok ->
335 + {:cont,
336 + {:ok, [file_row(org_id, bundle_id, file_id, key, path, info, headers, data) | acc]}}
337 +
338 + {:error, reason} ->
339 + {:halt, {:error, "Could not store #{path}: #{inspect(reason)}"}}
340 + end
341 + end)
342 + end
343 +
344 + defp file_row(org_id, bundle_id, file_id, key, path, info, headers, data) do
345 + %{
346 + id: file_id,
347 + artifact_bundle_id: bundle_id,
348 + organization_id: org_id,
349 + kind: string(info["type"]) || "other",
350 + url: string(info["url"]) || path,
351 + debug_id: debug_id(headers["debug-id"]),
352 + sourcemap: headers["sourcemap"] || headers["x-sourcemap"],
353 + headers: headers,
354 + size: byte_size(data),
355 + storage_key: key,
356 + inserted_at: DateTime.utc_now(:second)
357 + }
358 + end
359 +
360 + defp insert_bundle(args, bundle_id, size, manifest, release, dist, rows) do
361 + Repo.transaction(fn ->
362 + bundle =
363 + Repo.insert!(%ArtifactBundle{
364 + id: bundle_id,
365 + organization_id: args["organization_id"],
366 + checksum: args["checksum"],
367 + bundle_id: string(manifest["debug_id"] || manifest["bundle_id"]),
368 + release: release,
369 + dist: dist,
370 + artifact_count: length(rows),
371 + size: size
372 + })
373 +
374 + rows |> Enum.chunk_every(500) |> Enum.each(&Repo.insert_all(ArtifactFile, &1))
375 + link_projects(bundle, args["project_ids"])
376 + bundle
377 + end)
378 + end
379 +
380 + # The manifest's file entries paired with their bytes; entries whose file
381 + # isn't in the zip are skipped.
382 + defp manifest_entries(%{"files" => files_info}, files) when is_map(files_info) do
383 + for {path, info} <- files_info,
384 + is_map(info),
385 + data = Map.get(files, path),
386 + do: {path, info, data}
387 + end
388 +
389 + defp manifest_entries(_, _), do: []
390 +
391 + defp normalize_headers(headers) when is_map(headers),
392 + do: Map.new(headers, fn {k, v} -> {String.downcase(to_string(k)), to_string(v)} end)
393 +
394 + defp normalize_headers(_), do: %{}
395 +
396 + defp debug_id(nil), do: nil
397 +
398 + defp debug_id(raw) do
399 + # Debug ids may carry an appendix ("<uuid>-<age>" for native); the
400 + # first 36 characters are the UUID.
401 + case Ecto.UUID.cast(String.slice(String.downcase(raw), 0, 36)) do
402 + {:ok, uuid} -> uuid
403 + :error -> nil
404 + end
405 + end
406 +
407 + defp string(v) when is_binary(v) and v != "", do: v
408 + defp string(_), do: nil
409 +
410 + defp link_projects(bundle, project_ids) do
411 + Repo.insert_all(
412 + "artifact_bundle_projects",
413 + Enum.map(project_ids || [], fn pid ->
414 + %{artifact_bundle_id: Ecto.UUID.dump!(bundle.id), project_id: Ecto.UUID.dump!(pid)}
415 + end),
416 + on_conflict: :nothing
417 + )
418 + end
419 +
420 + defp ensure_releases(_org_id, %{"version" => nil}), do: :ok
421 +
422 + defp ensure_releases(org_id, %{"version" => version, "project_ids" => project_ids}) do
423 + Enum.each(project_ids || [], &Releases.ensure_release(org_id, &1, version))
424 + end
425 +
426 + defp set_status(org_id, checksum, state, detail) do
427 + Repo.update_all(
428 + from(s in AssembleStatus, where: s.organization_id == ^org_id and s.checksum == ^checksum),
429 + set: [state: state, detail: detail, updated_at: DateTime.utc_now(:second)]
430 + )
431 + end
432 +
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 + @doc """
445 + Drops chunk blobs and assemble statuses older than `max_age_seconds`
446 + (a day): blobs only matter until their bundle is assembled.
447 + """
448 + def cleanup(max_age_seconds \\ 86_400) do
449 + cutoff = DateTime.add(DateTime.utc_now(), -max_age_seconds)
450 + blobs = Repo.all(from b in FileBlob, where: b.inserted_at < ^cutoff)
451 + Enum.each(blobs, &Storage.delete(&1.storage_key))
452 + Repo.delete_all(from b in FileBlob, where: b.id in ^Enum.map(blobs, & &1.id))
453 + Repo.delete_all(from s in AssembleStatus, where: s.updated_at < ^cutoff)
454 + :ok
455 + end
456 +
457 + defp sha1(data), do: :crypto.hash(:sha, data) |> Base.encode16(case: :lower)
458 +end
added lib/vigil/artifacts/assemble_worker.ex
+20 −0
@@ -0,0 +1,20 @@
1 +defmodule Vigil.Artifacts.AssembleWorker do
2 + @moduledoc """
3 + Joins an uploaded artifact bundle's chunks and extracts it
4 + (`Vigil.Artifacts.run_assemble/1`). One job per (organization,
5 + checksum) at a time. A failure is recorded on the assemble status for
6 + sentry-cli to read, so the job doesn't retry it.
7 + """
8 + use Oban.Worker,
9 + queue: :processing,
10 + max_attempts: 1,
11 + unique: [keys: [:organization_id, :checksum], states: [:available, :scheduled, :executing]]
12 +
13 + @impl Oban.Worker
14 + def perform(%Oban.Job{args: args}) do
15 + case Vigil.Artifacts.run_assemble(args) do
16 + {:ok, _bundle} -> :ok
17 + {:error, detail} -> {:cancel, detail}
18 + end
19 + end
20 +end
added lib/vigil/artifacts/cleanup_worker.ex
+7 −0
@@ -0,0 +1,7 @@
1 +defmodule Vigil.Artifacts.CleanupWorker do
2 + @moduledoc "Daily: drops chunk blobs and assemble statuses over a day old (`Vigil.Artifacts.cleanup/1`)."
3 + use Oban.Worker, queue: :maintenance, max_attempts: 3
4 +
5 + @impl Oban.Worker
6 + def perform(_job), do: Vigil.Artifacts.cleanup()
7 +end
added lib/vigil_web/api/v0/artifact_controller.ex
+55 −0
@@ -0,0 +1,55 @@
1 +defmodule VigilWeb.Api.V0.ArtifactController do
2 + @moduledoc """
3 + sentry-cli's chunk upload and artifact-bundle assemble
4 + (`sentry-cli sourcemaps upload`); see `Vigil.Artifacts` for the flow.
5 + Uploading needs `project:releases` (or `project:write`), as in GlitchTip.
6 + """
7 + use VigilWeb, :controller
8 +
9 + alias Vigil.Accounts.Scope
10 + alias Vigil.Artifacts
11 + alias VigilWeb.Api.Auth
12 +
13 + def chunk_options(conn, %{"org" => slug}) do
14 + with {:ok, conn} <- Auth.put_org(conn, slug) do
15 + json(conn, Artifacts.chunk_options(conn.assigns.current_scope.organization.slug))
16 + else
17 + {:error, conn} -> conn
18 + end
19 + end
20 +
21 + def upload_chunks(conn, %{"org" => slug} = params) do
22 + with {:ok, conn} <- Auth.put_org(conn, slug),
23 + {:ok, conn} <- require_upload(conn) do
24 + uploads = for %Plug.Upload{} = u <- List.wrap(params["file_gzip"]), do: {u.filename, u.path}
25 +
26 + case Artifacts.store_chunks(conn.assigns.current_scope, uploads) do
27 + :ok -> send_resp(conn, 200, "")
28 + {:error, detail} -> Auth.json_error(conn, 400, detail)
29 + end
30 + else
31 + {:error, conn} -> conn
32 + end
33 + end
34 +
35 + def assemble(conn, %{"org" => slug} = params) do
36 + with {:ok, conn} <- Auth.put_org(conn, slug),
37 + {:ok, conn} <- require_upload(conn) do
38 + case Artifacts.assemble(conn.assigns.current_scope, params) do
39 + {:ok, response} -> json(conn, response)
40 + {:error, status, detail} -> Auth.json_error(conn, status, detail)
41 + end
42 + else
43 + {:error, conn} -> conn
44 + end
45 + end
46 +
47 + defp require_upload(conn) do
48 + scope = conn.assigns.current_scope
49 +
50 + if Scope.can?(scope, "project:releases") or Scope.can?(scope, "project:write"),
51 + do: {:ok, conn},
52 + else:
53 + {:error, Auth.json_error(conn, 403, "You do not have permission to perform this action.")}
54 + end
55 +end
added lib/vigil_web/chunk_multipart.ex
+44 −0
@@ -0,0 +1,44 @@
1 +defmodule VigilWeb.ChunkMultipart do
2 + @moduledoc """
3 + `Plug.Parsers.MULTIPART`, except for sentry-cli's chunk uploads
4 + (`POST /api/0/organizations/{org}/chunk-upload/`): those send many parts
5 + all named `file_gzip`, each with its SHA-1 as the filename, which Plug's
6 + default would collapse to the last one. There every part is kept, as
7 + `params["file_gzip"]`, a list of `Plug.Upload`s, and the body may be up
8 + to `Vigil.Artifacts.max_request_size/0`. Other requests parse as usual.
9 + """
10 +
11 + @multipart Plug.Parsers.MULTIPART
12 +
13 + def init(opts) do
14 + chunk_opts =
15 + opts
16 + |> Keyword.put(:length, Vigil.Artifacts.max_request_size() + 1024 * 1024)
17 + |> Keyword.put(:multipart_to_params, {__MODULE__, :all_parts, []})
18 +
19 + %{default: @multipart.init(opts), chunks: @multipart.init(chunk_opts)}
20 + end
21 +
22 + def parse(conn, "multipart", subtype, headers, %{default: default, chunks: chunks}) do
23 + opts = if chunk_upload?(conn), do: chunks, else: default
24 + @multipart.parse(conn, "multipart", subtype, headers, opts)
25 + end
26 +
27 + def parse(conn, _type, _subtype, _headers, _opts), do: {:next, conn}
28 +
29 + @doc false
30 + def all_parts(parts, conn) do
31 + uploads =
32 + for {"file_gzip", _headers, %Plug.Upload{} = upload} <- Enum.reverse(parts), do: upload
33 +
34 + {:ok, %{"file_gzip" => uploads}, conn}
35 + end
36 +
37 + defp chunk_upload?(%{
38 + method: "POST",
39 + path_info: ["api", "0", "organizations", _, "chunk-upload"]
40 + }),
41 + do: true
42 +
43 + defp chunk_upload?(_), do: false
44 +end
modified lib/vigil_web/endpoint.ex
+3 −1
@@ -48,7 +48,9 @@ defmodule VigilWeb.Endpoint do
48 48 plug VigilWeb.IngestPlug
49 49
50 50 plug Plug.Parsers,
51 − parsers: [:urlencoded, :multipart, :json],
51 + # VigilWeb.ChunkMultipart: Plug's multipart, but sentry-cli's chunk
52 + # uploads keep every same-named part, with their own size cap.
53 + parsers: [:urlencoded, VigilWeb.ChunkMultipart, :json],
52 54 pass: ["*/*"],
53 55 json_decoder: Phoenix.json_library()
54 56
modified lib/vigil_web/router.ex
+3 −0
@@ -34,6 +34,9 @@ defmodule VigilWeb.Router do
34 34 # Releases, deploys and commits (slice 5).
35 35
36 36 # Chunk upload and artifact-bundle assemble (slice 5).
37 + get "/organizations/:org/chunk-upload", ArtifactController, :chunk_options
38 + post "/organizations/:org/chunk-upload", ArtifactController, :upload_chunks
39 + post "/organizations/:org/artifactbundle/assemble", ArtifactController, :assemble
37 40
38 41 # Anything else: GlitchTip's JSON 404, which sentry-cli reads as
39 42 # "not supported here".
added test/vigil_web/api/artifact_upload_test.exs
+288 −0
@@ -0,0 +1,288 @@
1 +defmodule VigilWeb.ArtifactUploadTest do
2 + use VigilWeb.ConnCase, async: true
3 + use Oban.Testing, repo: Vigil.Repo
4 +
5 + import Vigil.AccountsFixtures
6 + import Vigil.OrganizationsFixtures
7 +
8 + alias Vigil.ApiTokens
9 + alias Vigil.Artifacts
10 + alias Vigil.Artifacts.{ArtifactBundle, ArtifactFile, AssembleStatus, AssembleWorker, FileBlob}
11 + alias Vigil.Repo
12 +
13 + setup do
14 + user = user_fixture()
15 + org = organization_fixture(user)
16 + project = project_fixture(org_scope(user, org), %{"name" => "web"})
17 +
18 + {:ok, token} =
19 + ApiTokens.create_token(user, %{label: "cli", scopes: ["project:releases", "org:read"]})
20 +
21 + %{user: user, org: org, project: project, token: token.token}
22 + end
23 +
24 + defp bearer(conn, token), do: put_req_header(conn, "authorization", "Bearer " <> token)
25 + defp sha1(data), do: :crypto.hash(:sha, data) |> Base.encode16(case: :lower)
26 +
27 + # A multipart body as sentry-cli's curl form sends it: one `file_gzip`
28 + # part per chunk, named by its SHA-1.
29 + defp upload(conn, token, org, parts) do
30 + boundary = "vigil-test-boundary"
31 +
32 + body =
33 + Enum.map(parts, fn {name, gz} ->
34 + [
35 + "--",
36 + boundary,
37 + "\r\n",
38 + ~s(Content-Disposition: form-data; name="file_gzip"; filename="#{name}"\r\n),
39 + "Content-Type: application/octet-stream\r\n\r\n",
40 + gz,
41 + "\r\n"
42 + ]
43 + end)
44 + |> then(&IO.iodata_to_binary([&1, "--", boundary, "--\r\n"]))
45 +
46 + conn
47 + |> bearer(token)
48 + |> put_req_header("content-type", "multipart/form-data; boundary=#{boundary}")
49 + |> post("/api/0/organizations/#{org.slug}/chunk-upload/", body)
50 + end
51 +
52 + defp assemble(conn, token, org, body) do
53 + conn
54 + |> bearer(token)
55 + |> put_req_header("content-type", "application/json")
56 + |> post("/api/0/organizations/#{org.slug}/artifactbundle/assemble/", Jason.encode!(body))
57 + end
58 +
59 + test "chunk-upload options advertise artifact bundles", %{conn: conn, org: org, token: token} do
60 + body =
61 + conn
62 + |> bearer(token)
63 + |> get("/api/0/organizations/#{org.slug}/chunk-upload/")
64 + |> json_response(200)
65 +
66 + assert body["url"] == "/api/0/organizations/#{org.slug}/chunk-upload/"
67 + assert body["hashAlgorithm"] == "sha1"
68 + assert "artifact_bundles_v2" in body["accept"]
69 + assert body["compression"] == ["gzip"]
70 + end
71 +
72 + test "chunks are stored per organization, every part kept, each checked", ctx do
73 + a = "chunk a " <> String.duplicate("x", 1000)
74 + b = "chunk b"
75 +
76 + conn =
77 + upload(ctx.conn, ctx.token, ctx.org, [{sha1(a), :zlib.gzip(a)}, {sha1(b), :zlib.gzip(b)}])
78 +
79 + assert response(conn, 200)
80 +
81 + assert Repo.aggregate(FileBlob, :count) == 2
82 + blob = Repo.get_by!(FileBlob, checksum: sha1(a))
83 + assert blob.organization_id == ctx.org.id
84 + assert {:ok, ^a} = Vigil.Storage.get(blob.storage_key)
85 +
86 + # Same again: nothing new.
87 + assert ctx.conn |> upload(ctx.token, ctx.org, [{sha1(a), :zlib.gzip(a)}]) |> response(200)
88 + assert Repo.aggregate(FileBlob, :count) == 2
89 + end
90 +
91 + test "a chunk whose bytes don't match its name is refused", ctx do
92 + conn = upload(ctx.conn, ctx.token, ctx.org, [{sha1("other"), :zlib.gzip("data")}])
93 + assert %{"detail" => "Chunk checksum mismatch" <> _} = json_response(conn, 400)
94 +
95 + conn = upload(build_conn(), ctx.token, ctx.org, [{sha1("data"), "not gzip"}])
96 + assert json_response(conn, 400)
97 + assert Repo.aggregate(FileBlob, :count) == 0
98 + end
99 +
100 + test "uploading needs project:releases or project:write", ctx do
101 + {:ok, t} = ApiTokens.create_token(ctx.user, %{label: "read", scopes: ["project:read"]})
102 +
103 + assert ctx.conn
104 + |> upload(t.token, ctx.org, [{sha1("a"), :zlib.gzip("a")}])
105 + |> json_response(403)
106 + end
107 +
108 + test "another organization's chunk-upload is a 404", ctx do
109 + other = organization_fixture()
110 +
111 + assert ctx.conn
112 + |> upload(ctx.token, other, [{sha1("a"), :zlib.gzip("a")}])
113 + |> json_response(404)
114 + end
115 +
116 + describe "assemble" do
117 + test "missing chunks first, then created and a job", ctx do
118 + data = "the whole bundle"
119 + checksum = sha1(data)
120 + req = %{checksum: checksum, chunks: [checksum], projects: ["web"], version: "1.0"}
121 +
122 + assert %{"state" => "not_found", "missingChunks" => [^checksum]} =
123 + ctx.conn |> assemble(ctx.token, ctx.org, req) |> json_response(200)
124 +
125 + assert build_conn()
126 + |> upload(ctx.token, ctx.org, [{checksum, :zlib.gzip(data)}])
127 + |> response(200)
128 +
129 + assert %{"state" => "created", "missingChunks" => []} =
130 + build_conn() |> assemble(ctx.token, ctx.org, req) |> json_response(200)
131 +
132 + assert_enqueued(worker: AssembleWorker, args: %{checksum: checksum, version: "1.0"})
133 +
134 + # Asking again while it's queued: still created, no second job.
135 + assert %{"state" => "created"} =
136 + build_conn() |> assemble(ctx.token, ctx.org, req) |> json_response(200)
137 +
138 + assert [_] = all_enqueued(worker: AssembleWorker)
139 + end
140 +
141 + test "a project the token can't see is a 404", ctx do
142 + checksum = sha1("x")
143 +
144 + assert ctx.conn
145 + |> assemble(ctx.token, ctx.org, %{checksum: checksum, chunks: [], projects: ["nope"]})
146 + |> json_response(404)
147 + end
148 +
149 + test "a bundle that isn't a zip ends in error, told once", ctx do
150 + data = "not a zip"
151 + checksum = sha1(data)
152 + :ok = Artifacts.store_chunks(scope(ctx), [write_gz(data)])
153 + req = %{checksum: checksum, chunks: [checksum], projects: ["web"]}
154 +
155 + assert %{"state" => "created"} =
156 + ctx.conn |> assemble(ctx.token, ctx.org, req) |> json_response(200)
157 +
158 + assert {:cancel, _} = perform_job(AssembleWorker, job_args(ctx, checksum, [checksum]))
159 +
160 + assert %{"state" => "error", "detail" => detail} =
161 + build_conn() |> assemble(ctx.token, ctx.org, req) |> json_response(200)
162 +
163 + assert detail =~ "zip"
164 + refute Repo.get_by(AssembleStatus, checksum: checksum)
165 + end
166 +
167 + test "a bundle from two chunks is joined, checked and extracted", ctx do
168 + zip = bundle_zip()
169 + checksum = sha1(zip)
170 + {first, second} = String.split_at(zip, div(byte_size(zip), 2))
171 + chunks = [sha1(first), sha1(second)]
172 + :ok = Artifacts.store_chunks(scope(ctx), [write_gz(first), write_gz(second)])
173 +
174 + req = %{checksum: checksum, chunks: chunks, projects: ["web"], version: "web@1.2.0"}
175 +
176 + assert %{"state" => "created"} =
177 + ctx.conn |> assemble(ctx.token, ctx.org, req) |> json_response(200)
178 +
179 + assert :ok =
180 + perform_job(
181 + AssembleWorker,
182 + job_args(ctx, checksum, chunks) |> Map.put("version", "web@1.2.0")
183 + )
184 +
185 + assert %{"state" => "ok"} =
186 + build_conn() |> assemble(ctx.token, ctx.org, req) |> json_response(200)
187 +
188 + bundle =
189 + Repo.get_by!(ArtifactBundle, checksum: checksum) |> Repo.preload([:files, :projects])
190 +
191 + assert bundle.release == "web@1.2.0"
192 + assert bundle.artifact_count == 2
193 + assert [%{slug: "web"}] = bundle.projects
194 +
195 + minified = Enum.find(bundle.files, &(&1.kind == "minified_source"))
196 + map = Enum.find(bundle.files, &(&1.kind == "source_map"))
197 + assert minified.url == "~/static/app.min.js"
198 + assert minified.sourcemap == "app.min.js.map"
199 + assert minified.debug_id == "6c2a7d7e-3c1f-4b0a-9d43-5a8f1e2b3c4d"
200 + assert map.debug_id == minified.debug_id
201 + assert {:ok, "function a(){}"} = Vigil.Storage.get(minified.storage_key)
202 +
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")
205 + assert Repo.aggregate(ArtifactFile, :count) == 2
206 + end
207 +
208 + test "a bundle whose whole checksum is wrong is an error", ctx do
209 + data = "abc"
210 + :ok = Artifacts.store_chunks(scope(ctx), [write_gz(data)])
211 + wrong = sha1("something else")
212 +
213 + req = %{checksum: wrong, chunks: [sha1(data)], projects: ["web"]}
214 +
215 + assert %{"state" => "created"} =
216 + ctx.conn |> assemble(ctx.token, ctx.org, req) |> json_response(200)
217 +
218 + assert {:cancel, "Bundle checksum mismatch"} =
219 + perform_job(AssembleWorker, job_args(ctx, wrong, [sha1(data)]))
220 + end
221 + end
222 +
223 + test "cleanup drops old blobs and statuses", ctx do
224 + :ok = Artifacts.store_chunks(scope(ctx), [write_gz("old")])
225 + blob = Repo.one!(FileBlob)
226 +
227 + Repo.update_all(FileBlob, set: [inserted_at: ~U[2020-01-01 00:00:00Z]])
228 + assert :ok = Artifacts.cleanup()
229 + refute Repo.one(FileBlob)
230 + assert {:error, :not_found} = Vigil.Storage.get(blob.storage_key)
231 + end
232 +
233 + defp scope(ctx), do: org_scope(ctx.user, ctx.org)
234 +
235 + defp write_gz(data) do
236 + path = Path.join(System.tmp_dir!(), "vigil-chunk-#{System.unique_integer([:positive])}")
237 + File.write!(path, :zlib.gzip(data))
238 + on_exit(fn -> File.rm(path) end)
239 + {sha1(data), path}
240 + end
241 +
242 + defp job_args(ctx, checksum, chunks) do
243 + %{
244 + "organization_id" => ctx.org.id,
245 + "checksum" => checksum,
246 + "chunks" => chunks,
247 + "project_ids" => [ctx.project.id],
248 + "version" => nil,
249 + "dist" => nil
250 + }
251 + end
252 +
253 + # The layout sentry-cli writes: manifest.json plus files/, the manifest
254 + # naming each file's url, type and headers.
255 + defp bundle_zip do
256 + debug_id = "6c2a7d7e-3c1f-4b0a-9d43-5a8f1e2b3c4d"
257 +
258 + manifest = %{
259 + "org" => "x",
260 + "release" => "web@1.2.0",
261 + "files" => %{
262 + "files/_/_/app.min.js" => %{
263 + "url" => "~/static/app.min.js",
264 + "type" => "minified_source",
265 + "headers" => %{"debug-id" => debug_id, "Sourcemap" => "app.min.js.map"}
266 + },
267 + "files/_/_/app.min.js.map" => %{
268 + "url" => "~/static/app.min.js.map",
269 + "type" => "source_map",
270 + "headers" => %{"debug-id" => debug_id}
271 + }
272 + }
273 + }
274 +
275 + {:ok, {_, zip}} =
276 + :zip.create(
277 + ~c"bundle.zip",
278 + [
279 + {~c"manifest.json", Jason.encode!(manifest)},
280 + {~c"files/_/_/app.min.js", "function a(){}"},
281 + {~c"files/_/_/app.min.js.map", ~s({"version":3,"sources":[],"mappings":""})}
282 + ],
283 + [:memory]
284 + )
285 +
286 + zip
287 + end
288 +end

Parents: 657cace