Slice 5: sentry-cli release API, deploys, commits, and releases UI

10e07e4 · gmorell · 2026-12-02 02:15

35 files +2696 -7
Message
{commit_body(@commit)}

Files changed

modified lib/vigil/releases.ex
+470 −5
@@ -1,16 +1,40 @@
1 1 defmodule Vigil.Releases do
2 2 @moduledoc """
3 − Releases and environments, as far as events need them: made when first
4 − seen (`ensure_release/3`, `ensure_environment/3`), and linked to the
5 − project the event came from. Both are idempotent and race-safe
6 − (`ON CONFLICT`).
3 + Releases, their deploys and commits, and environments.
4 +
5 + Events make releases and environments when first seen
6 + (`ensure_release/3`, `ensure_environment/3`), linked to the project the
7 + event came from; both are idempotent and race-safe (`ON CONFLICT`).
8 +
9 + sentry-cli manages them through the scope-first functions below (the
10 + `/api/0` release API, `VigilWeb.Api.V0.ReleaseController`). A caller sees
11 + a release when it is linked to a project they can see
12 + (`Vigil.Projects.list_visible/1`), as Sentry's `has_release_permission`;
13 + reading needs one of `project:read`/`project:releases`/`project:write`/
14 + `project:admin`, changing one of the last three (Sentry's
15 + `ReleasePermission`; GlitchTip asks for `project:releases`).
16 +
17 + Unlike GlitchTip: creating is idempotent on both paths, `dateReleased`
18 + stays nil until finalized, and the `commits` and `refs` sentry-cli sends
19 + are kept (in `data`), as are archive/restore (`status`).
7 20 """
8 21
9 22 import Ecto.Query
10 23
11 − alias Vigil.Releases.Release
24 + alias Vigil.Accounts.Scope
25 + alias Vigil.Artifacts.ArtifactBundle
26 + alias Vigil.Issues.Issue
27 + alias Vigil.Projects
28 + alias Vigil.Projects.Project
29 + alias Vigil.Releases.{Deploy, Release}
12 30 alias Vigil.Repo
13 31
32 + @read_scopes ~w(project:read project:releases project:write project:admin)
33 + @write_scopes ~w(project:releases project:write project:admin)
34 +
35 + # Commits kept per release; commit_count still counts them all.
36 + @max_commits 1000
37 +
14 38 @doc "The release `version` of an organization, made if new, and linked to the project."
15 39 def ensure_release(_org_id, _project_id, version) when version in [nil, ""], do: nil
16 40
@@ -95,4 +119,445 @@ defmodule Vigil.Releases do
95 119 select: e.name
96 120 )
97 121 end
122 +
123 + ## The release API
124 +
125 + @doc "Whether the caller may read releases here."
126 + def can_read?(scope), do: Enum.any?(@read_scopes, &Scope.can?(scope, &1))
127 +
128 + @doc "Whether the caller may create, change and delete releases here."
129 + def can_write?(scope), do: Enum.any?(@write_scopes, &Scope.can?(scope, &1))
130 +
131 + defp authorize_write(scope), do: if(can_write?(scope), do: :ok, else: {:error, :forbidden})
132 +
133 + @doc """
134 + A release's short name, as Sentry shows it: a package prefix
135 + (`pkg@1.2.3`) dropped, and a full 40-hex commit SHA cut to 12.
136 + """
137 + def short_version(version) when is_binary(version) do
138 + rest =
139 + case String.split(version, "@", parts: 2) do
140 + [pkg, v] when pkg != "" and v != "" -> v
141 + _ -> version
142 + end
143 +
144 + if rest =~ ~r/\A[0-9a-fA-F]{40}\z/, do: String.slice(rest, 0, 12), else: rest
145 + end
146 +
147 + @doc """
148 + The releases the caller sees, newest (finalized, else created) first.
149 +
150 + Options: `:project` (only that project's, which the caller must see),
151 + `:query` (a version substring, case-insensitive), `:status` (`:open`,
152 + the default, `:archived` or `:any`), `:limit` and `:offset`.
153 + Each comes with its visible `projects` preloaded.
154 + """
155 + def list_releases(%Scope{} = scope, opts \\ []) do
156 + visible = visible_project_ids(scope)
157 +
158 + scope
159 + |> releases_query(visible, opts[:project])
160 + |> filter_query(opts[:query])
161 + |> filter_status(Keyword.get(opts, :status, :open))
162 + |> order_by([r], desc: coalesce(r.date_released, r.inserted_at), desc: r.id)
163 + |> limit(^Keyword.get(opts, :limit, 100))
164 + |> offset(^Keyword.get(opts, :offset, 0))
165 + |> preload_projects(visible)
166 + |> Repo.all()
167 + end
168 +
169 + @doc "A release by version, if the caller sees it (in `opts[:project]` when given)."
170 + def get_release(%Scope{} = scope, version, opts \\ []) when is_binary(version) do
171 + visible = visible_project_ids(scope)
172 +
173 + scope
174 + |> releases_query(visible, opts[:project])
175 + |> where([r], r.version == ^version)
176 + |> preload_projects(visible)
177 + |> Repo.one()
178 + end
179 +
180 + defp visible_project_ids(scope), do: scope |> Projects.list_visible() |> Enum.map(& &1.id)
181 +
182 + defp releases_query(scope, visible, project) do
183 + ids =
184 + case project do
185 + nil -> visible
186 + %Project{id: id} -> Enum.filter(visible, &(&1 == id))
187 + end
188 +
189 + from r in Release,
190 + where:
191 + r.organization_id == ^scope.organization.id and
192 + r.id in subquery(
193 + from rp in "release_projects",
194 + where: rp.project_id in type(^ids, {:array, Ecto.UUID}),
195 + select: rp.release_id
196 + )
197 + end
198 +
199 + defp filter_query(query, q) when is_binary(q) and q != "" do
200 + pattern = "%" <> String.replace(q, ~w(\\ % _), &("\\" <> &1)) <> "%"
201 + where(query, [r], ilike(r.version, ^pattern))
202 + end
203 +
204 + defp filter_query(query, _), do: query
205 +
206 + defp filter_status(query, :any), do: query
207 + defp filter_status(query, status), do: where(query, [r], r.status == ^status)
208 +
209 + defp preload_projects(query, visible) do
210 + projects =
211 + from p in Project, where: p.id in ^visible and is_nil(p.deleted_at), order_by: p.slug
212 +
213 + preload(query, projects: ^projects)
214 + end
215 +
216 + @doc """
217 + Creates release `attrs["version"]`, or finds it: creating is idempotent
218 + (Sentry's is; GlitchTip's organization path answers 500). The projects
219 + are linked: `opts[:project]` on the project path, else the slugs in
220 + `attrs["projects"]`, each of which the caller must see. A new release
221 + needs one. `ref`, `url`, `date_released` (only when given: no default),
222 + `status`, `commits` and `refs` are applied as `update_release/3` does,
223 + on an existing release too (`releases archive` POSTs its status).
224 +
225 + Returns `{:ok, release, :created | :linked | :existing}`: `:linked` when
226 + it existed but gained a project (Sentry answers 201 for both of those,
227 + 208 for the last).
228 + """
229 + def create_release(%Scope{} = scope, attrs, opts \\ []) do
230 + with :ok <- authorize_write(scope),
231 + {:ok, projects} <- projects_for(scope, attrs, opts[:project]) do
232 + scope
233 + |> find_or_create(projects, attrs)
234 + |> case do
235 + # Made meanwhile (by an event, say): it exists after all.
236 + {:error, %Ecto.Changeset{errors: [{:organization_id, _} | _]}} ->
237 + find_or_create(scope, projects, attrs)
238 +
239 + other ->
240 + other
241 + end
242 + |> case do
243 + {:ok, {release, how}} -> {:ok, get_release(scope, release.version), how}
244 + {:error, _} = error -> error
245 + end
246 + end
247 + end
248 +
249 + defp find_or_create(scope, projects, attrs) do
250 + version = attrs["version"]
251 +
252 + Repo.transact(fn ->
253 + existing =
254 + is_binary(version) &&
255 + Repo.get_by(Release, organization_id: scope.organization.id, version: version)
256 +
257 + case existing do
258 + %Release{} = release -> existing_release(scope, release, projects, attrs)
259 + _ -> new_release(scope, projects, attrs)
260 + end
261 + end)
262 + end
263 +
264 + defp projects_for(_scope, _attrs, %Project{} = project), do: {:ok, [project]}
265 +
266 + defp projects_for(scope, attrs, nil) do
267 + slugs = attrs["projects"] || []
268 + by_slug = scope |> Projects.list_visible() |> Map.new(&{&1.slug, &1})
269 +
270 + if is_list(slugs) and Enum.all?(slugs, &Map.has_key?(by_slug, &1)),
271 + do: {:ok, slugs |> Enum.uniq() |> Enum.map(&by_slug[&1])},
272 + else: {:error, :invalid_projects}
273 + end
274 +
275 + defp new_release(_scope, [], _attrs), do: {:error, :invalid_projects}
276 +
277 + defp new_release(scope, projects, attrs) do
278 + %Release{organization_id: scope.organization.id}
279 + |> Release.create_changeset(attrs)
280 + |> Repo.insert()
281 + |> case do
282 + {:ok, release} ->
283 + link_projects(release, projects)
284 +
285 + with {:ok, release} <- apply_data(release, attrs),
286 + do: {:ok, {release, :created}}
287 +
288 + {:error, %Ecto.Changeset{} = cs} ->
289 + {:error, cs}
290 + end
291 + end
292 +
293 + defp existing_release(scope, release, projects, attrs) do
294 + linked = link_projects(release, projects)
295 +
296 + if linked == 0 and not visible?(scope, release) do
297 + {:error, :not_found}
298 + else
299 + with {:ok, release} <- do_update(release, Map.delete(attrs, "version")) do
300 + {:ok, {release, if(linked > 0, do: :linked, else: :existing)}}
301 + end
302 + end
303 + end
304 +
305 + defp visible?(scope, release) do
306 + ids = visible_project_ids(scope)
307 +
308 + Repo.exists?(
309 + from rp in "release_projects",
310 + where:
311 + rp.release_id == type(^release.id, Ecto.UUID) and
312 + rp.project_id in type(^ids, {:array, Ecto.UUID})
313 + )
314 + end
315 +
316 + defp link_projects(release, projects) do
317 + rows =
318 + Enum.map(
319 + projects,
320 + &%{release_id: Ecto.UUID.dump!(release.id), project_id: Ecto.UUID.dump!(&1.id)}
321 + )
322 +
323 + {n, _} = Repo.insert_all("release_projects", rows, on_conflict: :nothing)
324 + n
325 + end
326 +
327 + @doc """
328 + Updates a release from sentry-cli's PUT: `ref`, `url`, `date_released`
329 + (finalize), `status` (`"open"`/`"archived"`), and `commits` and `refs`,
330 + kept in `data` (commits up to #{@max_commits}, all counted).
331 + """
332 + def update_release(%Scope{} = scope, %Release{} = release, attrs) do
333 + with :ok <- authorize_write(scope),
334 + {:ok, updated} <- do_update(release, attrs) do
335 + {:ok, %{updated | projects: release.projects}}
336 + end
337 + end
338 +
339 + defp do_update(release, attrs) do
340 + changes = Map.take(attrs, ~w(ref url date_released status))
341 +
342 + with {:ok, release} <- release |> Release.update_changeset(changes) |> Repo.update() do
343 + apply_data(release, attrs)
344 + end
345 + end
346 +
347 + defp apply_data(release, attrs) do
348 + data = release.data || %{}
349 +
350 + {data, count} =
351 + case attrs["commits"] do
352 + commits when is_list(commits) ->
353 + commits = commits |> Enum.map(&normalize_commit/1) |> Enum.reject(&is_nil/1)
354 + {Map.put(data, "commits", Enum.take(commits, @max_commits)), length(commits)}
355 +
356 + _ ->
357 + {data, release.commit_count}
358 + end
359 +
360 + data =
361 + case attrs["refs"] do
362 + refs when is_list(refs) ->
363 + Map.put(data, "refs", refs |> Enum.map(&normalize_ref/1) |> Enum.reject(&is_nil/1))
364 +
365 + _ ->
366 + data
367 + end
368 +
369 + if data == release.data and count == release.commit_count,
370 + do: {:ok, release},
371 + else: release |> Ecto.Changeset.change(data: data, commit_count: count) |> Repo.update()
372 + end
373 +
374 + defp normalize_commit(%{"id" => id} = c) when is_binary(id) and id != "" do
375 + %{
376 + "id" => String.slice(id, 0, 64),
377 + "repository" => str(c["repository"]),
378 + "message" => str(c["message"], 10_000),
379 + "author_name" => str(c["author_name"] || c["authorName"]),
380 + "author_email" => str(c["author_email"] || c["authorEmail"]),
381 + "timestamp" => str(c["timestamp"] || c["dateCreated"]),
382 + "patch_set" =>
383 + for %{"path" => path} = p <- List.wrap(c["patch_set"]), is_binary(path) do
384 + %{"path" => String.slice(path, 0, 1000), "type" => str(p["type"])}
385 + end
386 + }
387 + end
388 +
389 + defp normalize_commit(_), do: nil
390 +
391 + defp normalize_ref(%{"commit" => commit} = r) when is_binary(commit) do
392 + %{
393 + "repository" => str(r["repository"]),
394 + "commit" => String.slice(commit, 0, 128),
395 + "previousCommit" => str(r["previousCommit"])
396 + }
397 + end
398 +
399 + defp normalize_ref(_), do: nil
400 +
401 + defp str(v, max \\ 255)
402 + defp str(v, max) when is_binary(v), do: String.slice(v, 0, max)
403 + defp str(_, _), do: nil
404 +
405 + @doc "A release's commits, newest first, as kept from sentry-cli."
406 + def list_commits(%Release{data: data}), do: (data || %{})["commits"] || []
407 +
408 + @doc "A release's commit authors, by email, as Sentry's `authors`."
409 + def authors(%Release{} = release) do
410 + release
411 + |> list_commits()
412 + |> Enum.filter(&is_binary(&1["author_email"]))
413 + |> Enum.uniq_by(&String.downcase(&1["author_email"]))
414 + |> Enum.map(&%{name: &1["author_name"], email: &1["author_email"]})
415 + end
416 +
417 + @doc "Deletes a release (its deploys go with it; issues keep theirs, unset)."
418 + def delete_release(%Scope{} = scope, %Release{} = release) do
419 + with :ok <- authorize_write(scope), do: Repo.delete(release)
420 + end
421 +
422 + ## Deploys
423 +
424 + @doc """
425 + Records a deploy of `release` (`environment` required; `date_finished`
426 + defaults to now), counts it, and gives the release's projects (or those
427 + of them in `attrs["projects"]`) the environment.
428 + """
429 + def create_deploy(%Scope{} = scope, %Release{} = release, attrs) do
430 + with :ok <- authorize_write(scope) do
431 + Repo.transact(fn ->
432 + with {:ok, deploy} <-
433 + %Deploy{release_id: release.id} |> Deploy.changeset(attrs) |> Repo.insert() do
434 + Repo.update_all(from(r in Release, where: r.id == ^release.id), inc: [deploy_count: 1])
435 +
436 + release
437 + |> deploy_projects(attrs["projects"])
438 + |> Enum.each(&ensure_environment(release.organization_id, &1.id, deploy.environment))
439 +
440 + {:ok, deploy}
441 + end
442 + end)
443 + end
444 + end
445 +
446 + defp deploy_projects(release, slugs) do
447 + projects = Repo.all(Ecto.assoc(release, :projects))
448 +
449 + case slugs do
450 + [_ | _] -> Enum.filter(projects, &(&1.slug in slugs))
451 + _ -> projects
452 + end
453 + end
454 +
455 + @doc "A release's deploys, latest first."
456 + def list_deploys(%Scope{}, %Release{id: id}) do
457 + Repo.all(
458 + from d in Deploy,
459 + where: d.release_id == ^id,
460 + order_by: [desc: d.date_finished, desc: d.id]
461 + )
462 + end
463 +
464 + ## Stats and pages
465 +
466 + @doc """
467 + What events and deploys say about `releases`, by release id, counting
468 + issues in the releases' (preloaded, visible) projects only:
469 + `new_groups` (issues first seen in it), `new_groups_by_project`,
470 + `first_event` (the earliest of those), `last_event` (the latest event
471 + of the issues last seen in it), and `last_deploy`.
472 + """
473 + def release_stats([]), do: %{}
474 +
475 + def release_stats(releases) do
476 + ids = Enum.map(releases, & &1.id)
477 + project_ids = releases |> Enum.flat_map(& &1.projects) |> Enum.map(& &1.id) |> Enum.uniq()
478 +
479 + new =
480 + Repo.all(
481 + from i in Issue,
482 + where:
483 + i.first_release_id in ^ids and i.project_id in ^project_ids and is_nil(i.deleted_at),
484 + group_by: [i.first_release_id, i.project_id],
485 + select: {i.first_release_id, i.project_id, count(i.id), min(i.first_seen)}
486 + )
487 +
488 + last =
489 + Repo.all(
490 + from i in Issue,
491 + where:
492 + i.last_release_id in ^ids and i.project_id in ^project_ids and is_nil(i.deleted_at),
493 + group_by: i.last_release_id,
494 + select: {i.last_release_id, max(i.last_seen)}
495 + )
496 + |> Map.new()
497 +
498 + deploys =
499 + Repo.all(
500 + from d in Deploy,
501 + where: d.release_id in ^ids,
502 + distinct: d.release_id,
503 + order_by: [asc: d.release_id, desc: d.date_finished, desc: d.id]
504 + )
505 + |> Map.new(&{&1.release_id, &1})
506 +
507 + new_by_release = Enum.group_by(new, &elem(&1, 0))
508 +
509 + Map.new(ids, fn id ->
510 + rows = Map.get(new_by_release, id, [])
511 +
512 + {id,
513 + %{
514 + new_groups: rows |> Enum.map(&elem(&1, 2)) |> Enum.sum(),
515 + new_groups_by_project: Map.new(rows, fn {_, pid, n, _} -> {pid, n} end),
516 + first_event: rows |> Enum.map(&elem(&1, 3)) |> Enum.min(DateTime, fn -> nil end),
517 + last_event: last[id],
518 + last_deploy: deploys[id]
519 + }}
520 + end)
521 + end
522 +
523 + @doc """
524 + For a release's page, a project's issues: `new` (first seen in it),
525 + `resolved` (resolved in it), and `seen_again` (first seen in an earlier
526 + release, or none, and last seen in this one: carried over or regressed).
527 + At most `limit` each, latest first.
528 + """
529 + def release_issues(%Release{id: rid}, %Project{id: pid}, limit \\ 50) do
530 + base =
531 + from i in Issue,
532 + where: i.project_id == ^pid and is_nil(i.deleted_at),
533 + order_by: [desc: i.last_seen],
534 + limit: ^limit
535 +
536 + %{
537 + new: Repo.all(where(base, [i], i.first_release_id == ^rid)),
538 + resolved: Repo.all(where(base, [i], i.resolved_in_release_id == ^rid)),
539 + seen_again:
540 + Repo.all(
541 + where(
542 + base,
543 + [i],
544 + i.last_release_id == ^rid and
545 + (is_nil(i.first_release_id) or i.first_release_id != ^rid)
546 + )
547 + )
548 + }
549 + end
550 +
551 + @doc "The artifact bundles uploaded for a release, for one project, newest first."
552 + def list_artifact_bundles(%Release{} = release, %Project{id: pid}) do
553 + Repo.all(
554 + from b in ArtifactBundle,
555 + join: bp in "artifact_bundle_projects",
556 + on: bp.artifact_bundle_id == b.id,
557 + where:
558 + b.organization_id == ^release.organization_id and b.release == ^release.version and
559 + bp.project_id == type(^pid, Ecto.UUID),
560 + order_by: [desc: b.inserted_at]
561 + )
562 + end
98 563 end
modified lib/vigil/releases/deploy.ex
+18 −0
@@ -2,6 +2,8 @@ defmodule Vigil.Releases.Deploy do
2 2 @moduledoc "A release going out to an environment (`sentry-cli releases deploys new`)."
3 3 use Vigil.Schema
4 4
5 + import Ecto.Changeset
6 +
5 7 schema "deploys" do
6 8 field :environment, :string
7 9 field :name, :string
@@ -13,4 +15,20 @@ defmodule Vigil.Releases.Deploy do
13 15
14 16 timestamps(type: :utc_datetime, updated_at: false)
15 17 end
18 +
19 + @doc "A new deploy; `date_finished` defaults to now, as Sentry's."
20 + def changeset(deploy, attrs) do
21 + deploy
22 + |> cast(attrs, [:environment, :name, :url, :date_started, :date_finished])
23 + |> validate_required([:environment])
24 + |> validate_length(:environment, max: 64)
25 + |> validate_format(:environment, ~r/^[^\/\n\r\t\f]+$/, message: "is not a valid environment")
26 + |> validate_length(:name, max: 64)
27 + |> validate_length(:url, max: 255)
28 + |> then(fn cs ->
29 + if get_field(cs, :date_finished),
30 + do: cs,
31 + else: put_change(cs, :date_finished, DateTime.utc_now(:second))
32 + end)
33 + end
16 34 end
modified lib/vigil/releases/release.ex
+45 −2
@@ -1,11 +1,15 @@
1 1 defmodule Vigil.Releases.Release do
2 2 @moduledoc """
3 3 A version of an organization's code (`version`, unique per organization),
4 − made when an event first names it, or by sentry-cli (slice 5).
5 − `date_released` stays nil until it is finalized.
4 + made when an event first names it, or by sentry-cli (`Vigil.Releases`).
5 + `date_released` stays nil until it is finalized. `data` holds what
6 + sentry-cli sends that has no column: `"commits"` and `"refs"`.
7 + `status` is `:archived` after `sentry-cli releases archive`.
6 8 """
7 9 use Vigil.Schema
8 10
11 + import Ecto.Changeset
12 +
9 13 schema "releases" do
10 14 field :organization_id, Ecto.UUID
11 15 field :version, :string
@@ -15,9 +19,48 @@ defmodule Vigil.Releases.Release do
15 19 field :data, :map, default: %{}
16 20 field :commit_count, :integer, default: 0
17 21 field :deploy_count, :integer, default: 0
22 + field :status, Ecto.Enum, values: [:open, :archived], default: :open
18 23
19 24 many_to_many :projects, Vigil.Projects.Project, join_through: "release_projects"
25 + has_many :deploys, Vigil.Releases.Deploy
20 26
21 27 timestamps(type: :utc_datetime)
22 28 end
29 +
30 + # Sentry's Release.is_valid_version, but for "/": sentry-cli can't send
31 + # one (it turns it into U+FFFD), yet an SDK's event can name one.
32 + @bad_chars ["\n", "\r", "\t", "\f"]
33 +
34 + @doc "A new release from the API."
35 + def create_changeset(release, attrs) do
36 + release
37 + |> cast(attrs, [:version, :ref, :url, :date_released, :status])
38 + |> validate_required([:version])
39 + |> validate_length(:version, max: 250)
40 + |> validate_change(:version, fn :version, v ->
41 + if valid_version?(v), do: [], else: [version: "is not a valid release version"]
42 + end)
43 + |> common()
44 + |> unique_constraint([:organization_id, :version])
45 + end
46 +
47 + @doc "Changes to a release's ref, url, finalize date and status."
48 + def update_changeset(release, attrs) do
49 + release
50 + |> cast(attrs, [:ref, :url, :date_released, :status])
51 + |> common()
52 + end
53 +
54 + defp common(changeset) do
55 + changeset
56 + |> validate_length(:ref, max: 250)
57 + |> validate_length(:url, max: 255)
58 + end
59 +
60 + def valid_version?(v) when is_binary(v),
61 + do:
62 + String.trim(v) != "" and v not in [".", ".."] and String.downcase(v) != "latest" and
63 + not String.contains?(v, @bad_chars)
64 +
65 + def valid_version?(_), do: false
23 66 end
added lib/vigil_web/api/v0/deploy_controller.ex
+53 −0
@@ -0,0 +1,53 @@
1 +defmodule VigilWeb.Api.V0.DeployController do
2 + @moduledoc """
3 + `GET`/`POST /api/0/organizations/{org}/releases/{version}/deploys/`
4 + (`sentry-cli deploys list/new`), in Sentry's deploy shape. `environment`
5 + is required, `dateFinished` defaults to now, and the release's projects
6 + (or those named in `projects`) gain the environment. 2019 Sentry's
7 + `release_deploys.py`; GlitchTip's `create_deploy` (MIT).
8 + """
9 + use VigilWeb, :controller
10 +
11 + import VigilWeb.Api.V0.ReleaseController,
12 + only: [fetch_release: 3, done: 1, error: 2]
13 +
14 + alias Vigil.Releases
15 + alias VigilWeb.Api.V0.ReleaseJSON
16 +
17 + @fields [
18 + {"environment", "environment"},
19 + {"name", "name"},
20 + {"url", "url"},
21 + {"dateStarted", "date_started"},
22 + {"dateFinished", "date_finished"},
23 + {"projects", "projects"}
24 + ]
25 +
26 + def index(conn, params) do
27 + with {:ok, conn, release} <- fetch_release(conn, params, :read) do
28 + deploys = Releases.list_deploys(conn.assigns.current_scope, release)
29 + json(conn, Enum.map(deploys, &ReleaseJSON.deploy/1))
30 + end
31 + |> done()
32 + end
33 +
34 + def create(conn, params) do
35 + with {:ok, conn, release} <- fetch_release(conn, params, :write) do
36 + body = if is_map(conn.body_params), do: conn.body_params, else: %{}
37 +
38 + attrs =
39 + Enum.reduce(@fields, %{}, fn {from, to}, acc ->
40 + case Map.get(body, from) do
41 + nil -> acc
42 + value -> Map.put(acc, to, value)
43 + end
44 + end)
45 +
46 + case Releases.create_deploy(conn.assigns.current_scope, release, attrs) do
47 + {:ok, deploy} -> conn |> put_status(201) |> json(ReleaseJSON.deploy(deploy))
48 + {:error, reason} -> error(conn, reason)
49 + end
50 + end
51 + |> done()
52 + end
53 +end
added lib/vigil_web/api/v0/release_controller.ex
+262 −0
@@ -0,0 +1,262 @@
1 +defmodule VigilWeb.Api.V0.ReleaseController do
2 + @moduledoc """
3 + sentry-cli's release API (`Vigil.Releases`), on both the organization
4 + and the (older, project-bound) project paths, as sentry-cli 2.x calls
5 + them (`src/api/mod.rs`):
6 +
7 + * `POST /organizations/{org}/releases/` (`projects` in the body) and
8 + `POST /projects/{org}/{project}/releases/`: idempotent; 201 when the
9 + release is new or gained a project, else Sentry's 208.
10 + * `GET`, `PUT`, `DELETE .../releases/{version}/`: 404 when missing.
11 + PUT takes `ref`, `url`, `dateReleased` (finalize), `status`
12 + (archive/restore), `commits` and `refs`.
13 + * `GET .../releases/`: Sentry's Link-header cursors (`per_page`,
14 + `cursor`), `query` (a version substring) and `status`
15 + (`open`, the default, `archived` or `any`).
16 + * `GET .../releases/{version}/commits/`: what `set-commits` sent.
17 + * `GET /organizations/{org}/repos/`: always `[]` (no repository
18 + integrations), so `set-commits --auto` falls back to local git.
19 + * `GET .../releases/{version}/previous-with-commits/`: 404, which
20 + sentry-cli reads as "no previous release".
21 + * Deploys: `VigilWeb.Api.V0.DeployController`.
22 +
23 + A token sees only the releases of projects it can see; others are 404.
24 + Shapes ported from GlitchTip's `apps/releases` (MIT) and 2019 Sentry's
25 + `organization_releases.py`/`organization_release_details.py` (BSD-3).
26 + """
27 + use VigilWeb, :controller
28 +
29 + alias Vigil.Releases
30 + alias VigilWeb.Api.Auth
31 + alias VigilWeb.Api.V0.ReleaseJSON
32 +
33 + @per_page 100
34 +
35 + @release_fields [
36 + {"version", "version"},
37 + {"projects", "projects"},
38 + {"ref", "ref"},
39 + {"url", "url"},
40 + {"dateReleased", "date_released"},
41 + {"status", "status"},
42 + {"commits", "commits"},
43 + {"refs", "refs"}
44 + ]
45 +
46 + def index(conn, params) do
47 + with {:ok, conn, project} <- resolve(conn, params, :read) do
48 + scope = conn.assigns.current_scope
49 + offset = cursor_offset(params["cursor"])
50 + per_page = per_page(params["per_page"])
51 +
52 + releases =
53 + Releases.list_releases(scope,
54 + project: project,
55 + query: params["query"],
56 + status: status_filter(params["status"]),
57 + limit: per_page + 1,
58 + offset: offset
59 + )
60 +
61 + {page, more?} = {Enum.take(releases, per_page), length(releases) > per_page}
62 + stats = Releases.release_stats(page)
63 +
64 + conn
65 + |> put_resp_header("link", link_header(conn, offset, per_page, more?))
66 + |> json(Enum.map(page, &ReleaseJSON.release(&1, stats[&1.id])))
67 + end
68 + |> done()
69 + end
70 +
71 + def create(conn, params) do
72 + with {:ok, conn, project} <- resolve(conn, params, :write) do
73 + attrs = release_attrs(conn.body_params)
74 +
75 + case Releases.create_release(conn.assigns.current_scope, attrs, project: project) do
76 + {:ok, release, how} ->
77 + conn
78 + |> put_status(if(how == :existing, do: 208, else: 201))
79 + |> render_release(release)
80 +
81 + {:error, reason} ->
82 + error(conn, reason)
83 + end
84 + end
85 + |> done()
86 + end
87 +
88 + def show(conn, params) do
89 + with {:ok, conn, release} <- fetch_release(conn, params, :read) do
90 + render_release(conn, release)
91 + end
92 + |> done()
93 + end
94 +
95 + def update(conn, params) do
96 + with {:ok, conn, release} <- fetch_release(conn, params, :write) do
97 + attrs = conn.body_params |> release_attrs() |> Map.drop(["version", "projects"])
98 +
99 + case Releases.update_release(conn.assigns.current_scope, release, attrs) do
100 + {:ok, release} -> render_release(conn, release)
101 + {:error, reason} -> error(conn, reason)
102 + end
103 + end
104 + |> done()
105 + end
106 +
107 + def delete(conn, params) do
108 + with {:ok, conn, release} <- fetch_release(conn, params, :write) do
109 + case Releases.delete_release(conn.assigns.current_scope, release) do
110 + {:ok, _} -> send_resp(conn, 204, "")
111 + {:error, reason} -> error(conn, reason)
112 + end
113 + end
114 + |> done()
115 + end
116 +
117 + def commits(conn, params) do
118 + with {:ok, conn, release} <- fetch_release(conn, params, :read) do
119 + json(conn, release |> Releases.list_commits() |> Enum.map(&ReleaseJSON.commit/1))
120 + end
121 + |> done()
122 + end
123 +
124 + def repos(conn, %{"org" => org}) do
125 + with {:ok, conn} <- Auth.put_org(conn, org),
126 + {:ok, conn} <- authorize(conn, :read) do
127 + json(conn, [])
128 + end
129 + |> done()
130 + end
131 +
132 + ## Helpers, shared with DeployController
133 +
134 + @doc false
135 + # The organization (and project, on a project path) of the request, or
136 + # the request ended: 404 for what the token can't see, 403 without the
137 + # scopes `access` (:read or :write) needs.
138 + def resolve(conn, params, access) do
139 + with {:ok, conn} <- Auth.put_org(conn, params["org"]),
140 + {:ok, conn} <- authorize(conn, access) do
141 + case params["project"] do
142 + nil ->
143 + {:ok, conn, nil}
144 +
145 + slug ->
146 + case Vigil.Projects.get_visible(conn.assigns.current_scope, slug) do
147 + nil -> {:error, Auth.not_found(conn)}
148 + project -> {:ok, conn, project}
149 + end
150 + end
151 + end
152 + end
153 +
154 + @doc false
155 + def fetch_release(conn, params, access) do
156 + with {:ok, conn, project} <- resolve(conn, params, access) do
157 + case Releases.get_release(conn.assigns.current_scope, params["version"], project: project) do
158 + nil -> {:error, Auth.not_found(conn)}
159 + release -> {:ok, conn, release}
160 + end
161 + end
162 + end
163 +
164 + defp authorize(conn, :read), do: allow(conn, Releases.can_read?(conn.assigns.current_scope))
165 + defp authorize(conn, :write), do: allow(conn, Releases.can_write?(conn.assigns.current_scope))
166 +
167 + defp allow(conn, true), do: {:ok, conn}
168 +
169 + defp allow(conn, false),
170 + do: {:error, Auth.json_error(conn, 403, "You do not have permission to perform this action.")}
171 +
172 + @doc false
173 + def done({:error, conn}), do: conn
174 + def done(%Plug.Conn{} = conn), do: conn
175 +
176 + @doc false
177 + def error(conn, :not_found), do: Auth.not_found(conn)
178 +
179 + def error(conn, :forbidden),
180 + do: Auth.json_error(conn, 403, "You do not have permission to perform this action.")
181 +
182 + def error(conn, :invalid_projects),
183 + do: conn |> put_status(400) |> json(%{projects: ["Invalid project slugs"]})
184 +
185 + def error(conn, %Ecto.Changeset{} = cs) do
186 + errors =
187 + Ecto.Changeset.traverse_errors(cs, fn {msg, opts} ->
188 + Regex.replace(~r"%{(\w+)}", msg, fn _, key ->
189 + opts |> Keyword.get(String.to_existing_atom(key), key) |> to_string()
190 + end)
191 + end)
192 +
193 + conn |> put_status(400) |> json(camelize(errors))
194 + end
195 +
196 + defp camelize(errors) do
197 + Map.new(errors, fn {k, v} ->
198 + [first | rest] = k |> to_string() |> String.split("_")
199 + {first <> Enum.map_join(rest, &String.capitalize/1), v}
200 + end)
201 + end
202 +
203 + defp render_release(conn, release) do
204 + stats = Releases.release_stats([release])
205 + json(conn, ReleaseJSON.release(release, stats[release.id]))
206 + end
207 +
208 + defp release_attrs(body) when is_map(body) do
209 + Enum.reduce(@release_fields, %{}, fn {from, to}, acc ->
210 + case Map.get(body, from) do
211 + nil -> acc
212 + value -> Map.put(acc, to, value)
213 + end
214 + end)
215 + end
216 +
217 + defp release_attrs(_), do: %{}
218 +
219 + defp status_filter("archived"), do: :archived
220 + defp status_filter("any"), do: :any
221 + defp status_filter(_), do: :open
222 +
223 + ## Pagination: Sentry's cursors, "<value>:<offset>:<is_prev>"
224 +
225 + defp per_page(value) do
226 + case value && Integer.parse(value) do
227 + {n, ""} when n in 1..@per_page -> n
228 + _ -> @per_page
229 + end
230 + end
231 +
232 + defp cursor_offset(cursor) when is_binary(cursor) do
233 + case String.split(cursor, ":") do
234 + [_value, offset | _] ->
235 + case Integer.parse(offset) do
236 + {n, ""} when n >= 0 -> n
237 + _ -> 0
238 + end
239 +
240 + _ ->
241 + 0
242 + end
243 + end
244 +
245 + defp cursor_offset(_), do: 0
246 +
247 + defp link_header(conn, offset, per_page, more?) do
248 + prev = max(offset - per_page, 0)
249 +
250 + [
251 + link(conn, "previous", "0:#{prev}:1", offset > 0),
252 + link(conn, "next", "0:#{offset + per_page}:0", more?)
253 + ]
254 + |> Enum.join(", ")
255 + end
256 +
257 + defp link(conn, rel, cursor, results?) do
258 + query = conn.query_params |> Map.put("cursor", cursor) |> URI.encode_query()
259 + url = conn |> request_url() |> String.split("?") |> hd()
260 + ~s(<#{url}?#{query}>; rel="#{rel}"; results="#{results?}"; cursor="#{cursor}")
261 + end
262 +end
added lib/vigil_web/api/v0/release_json.ex
+82 −0

Click to load diff…

modified lib/vigil_web/live/issue_live/index.ex
+9 −0

Click to load diff…

added lib/vigil_web/live/release_live/index.ex
+220 −0

Click to load diff…

added lib/vigil_web/live/release_live/show.ex
+442 −0

Click to load diff…

modified lib/vigil_web/router.ex
+25 −0

Click to load diff…

added priv/repo/migrations/20261202020556_add_release_status.exs
+16 −0

Click to load diff…

added test/support/fixtures/releases_fixtures.ex
+63 −0

Click to load diff…

added test/vigil/releases_test.exs
+159 −0

Click to load diff…

added test/vigil_web/api/release_api_test.exs
+506 −0

Click to load diff…

added test/vigil_web/live/release_live_test.exs
+157 −0

Click to load diff…

added test/vigil_web/sentry_cli_releases_test.exs
+169 −0

Click to load diff…

Parents: 657cace