neiam
/vigil
public · Issues · Pulls · Labels · Forks · Compare · Actions success · Badges · Packages
Log in to mark this repository.
Slice 4: alerts and notifications
0ac4ba6 · gmorell · 2026-12-01 23:06
Message
{commit_body(@commit)}
Files changed
modified
ROADMAP.md
+6
−1
| 299 | 299 | - Keyboard shortcuts on the list (j/k/o/x/r/i, /) and on the detail page (r/i/u, j/k events, c). Neither has been tried in a browser yet. |
| 300 | 300 | - **Permissions:** GlitchTip gives every role `event:admin`, so deleting issues and moderating comments need `project:admin` (admins and up) instead. |
| 301 | 301 | |
| 302 | −### 4. Alerts and notifications · medium | |
| 302 | +### 4. Alerts and notifications · medium · **done** | |
| 303 | 303 | - **Rules:** per project, "N events in M minutes", "new issue" and "regression". Recipients are email, a generic webhook (Slack-compatible), Discord, ntfy, Teams, Google Chat and Zulip, with GlitchTip's payload shapes. |
| 304 | 304 | - **Evaluation:** |
| 305 | 305 | - Processors record touched issues in an `alert_candidates` table (instead of a Valkey set). |
| 308 | 308 | - **Dedupe:** once per issue per rule, until a regression. A "snooze for X" option re-notifies after time passes, which GlitchTip can't. |
| 309 | 309 | - **Who gets email:** per-user project subscriptions with a subscribe-by-default setting; email goes through Swoosh. |
| 310 | 310 | - **Exit:** new and regressed issues reach email and a webhook exactly once. |
| 311 | +- **As built:** | |
| 312 | + - Rules are frequency, new issue and regression, with an optional re-notify window; dedupe is per (rule, issue) and a regression clears it. | |
| 313 | + - Evaluation is a minutely Oban cron job over `alert_candidates`, and delivery is an Oban job per recipient (5 attempts) with a visible delivery log. | |
| 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 | + - `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. | |
| 311 | 316 | |
| 312 | 317 | ### 5. Releases, sentry-cli and sourcemaps · large |
| 313 | 318 | The `/api/0` API: |
modified
config/config.exs
+3
−1
| 49 | 49 | {Oban.Plugins.Cron, |
| 50 | 50 | crontab: [ |
| 51 | 51 | # Partitions ahead of time for the partitioned tables (Vigil.Partitions). |
| 52 | − {"17 3 * * *", Vigil.Partitions.MaintainWorker} | |
| 52 | + {"17 3 * * *", Vigil.Partitions.MaintainWorker}, | |
| 53 | + # Alert rules against the issues events touched (Vigil.Alerts). | |
| 54 | + {"* * * * *", Vigil.Alerts.EvaluateWorker} | |
| 53 | 55 | ]} |
| 54 | 56 | ] |
| 55 | 57 |
modified
config/test.exs
+6
−0
| 3 | 3 | # Jobs are inserted but not run; tests assert_enqueued / perform_job. |
| 4 | 4 | config :vigil, Oban, testing: :manual |
| 5 | 5 | |
| 6 | +# Alert webhooks go to Req.Test stubs, and webhook hosts "resolve" to a | |
| 7 | +# public address, so tests make no network calls (Vigil.Alerts.webhook_opts/0). | |
| 8 | +config :vigil, :webhook_opts, | |
| 9 | + req_options: [plug: {Req.Test, Vigil.Alerts.Webhooks}], | |
| 10 | + resolver: &Vigil.TestResolver.public/1 | |
| 11 | + | |
| 6 | 12 | # Tests make the partitions they need (Vigil.PartitionsTest). |
| 7 | 13 | config :vigil, :maintain_partitions_on_boot, false |
| 8 | 14 |
added
lib/vigil/alerts.ex
+437
−0
| 1 | +defmodule Vigil.Alerts do | |
| 2 | + @moduledoc """ | |
| 3 | + Telling people about issues (ROADMAP.md, slice 4), as GlitchTip does, | |
| 4 | + without its Valkey set and with its gaps closed. | |
| 5 | + | |
| 6 | + * The event processor records each issue an event touched as a | |
| 7 | + *candidate* (`record/2`): `:new`, `:regression`, or plain `:event`, | |
| 8 | + at most one waiting row per issue and kind (`alert_candidates`, in | |
| 9 | + place of GlitchTip's `alert_issue_ids` set). | |
| 10 | + * Every minute `Vigil.Alerts.EvaluateWorker` takes the candidates | |
| 11 | + (`evaluate/1`) and checks them against each enabled rule of their | |
| 12 | + project (`Vigil.Alerts.Rule`): new issues, regressions, or "N events | |
| 13 | + in M minutes". Ignored and resolved issues are left out. | |
| 14 | + * An issue is told about once per rule (`alert_issue_states`), until it | |
| 15 | + regresses (`forget/1`), or again after the rule's `renotify_minutes`. | |
| 16 | + * A firing is a `Vigil.Alerts.Notification`, sent to each recipient by | |
| 17 | + its own Oban job (`Vigil.Alerts.DeliverWorker`), retried with backoff, | |
| 18 | + its outcome kept as a `Vigil.Alerts.Delivery`. A rule with no | |
| 19 | + recipients emails, as GlitchTip falls back to email. | |
| 20 | + | |
| 21 | + Email goes to the project's members who can see it and haven't turned | |
| 22 | + its alerts off (`set_subscription/3`). | |
| 23 | + """ | |
| 24 | + | |
| 25 | + import Ecto.Query | |
| 26 | + | |
| 27 | + alias Vigil.Accounts.{Scope, User} | |
| 28 | + alias Vigil.Alerts.{Delivery, DeliverWorker, Notification, Recipient, Rule} | |
| 29 | + alias Vigil.Issues.{Issue, IssueEvent} | |
| 30 | + alias Vigil.Organizations | |
| 31 | + alias Vigil.Organizations.Member | |
| 32 | + alias Vigil.Projects.Project | |
| 33 | + alias Vigil.Repo | |
| 34 | + | |
| 35 | + ## Rules and recipients | |
| 36 | + | |
| 37 | + def list_rules(%Project{id: project_id}) do | |
| 38 | + Repo.all( | |
| 39 | + from r in Rule, | |
| 40 | + where: r.project_id == ^project_id, | |
| 41 | + order_by: r.id, | |
| 42 | + preload: [recipients: ^from(x in Recipient, order_by: x.id)] | |
| 43 | + ) | |
| 44 | + end | |
| 45 | + | |
| 46 | + def get_rule!(%Project{id: project_id}, id), | |
| 47 | + do: Repo.get_by!(Rule, id: id, project_id: project_id) |> Repo.preload(:recipients) | |
| 48 | + | |
| 49 | + def change_rule(%Rule{} = rule, attrs \\ %{}), do: Rule.changeset(rule, attrs) | |
| 50 | + def change_recipient(%Recipient{} = r, attrs \\ %{}), do: Recipient.changeset(r, attrs) | |
| 51 | + | |
| 52 | + @doc "Needs `project:write`." | |
| 53 | + def create_rule(%Scope{} = scope, %Project{} = project, attrs) do | |
| 54 | + with :ok <- Organizations.authorize(scope, "project:write") do | |
| 55 | + %Rule{project_id: project.id} |> Rule.changeset(attrs) |> Repo.insert() | |
| 56 | + end | |
| 57 | + end | |
| 58 | + | |
| 59 | + @doc "Needs `project:write`." | |
| 60 | + def update_rule(%Scope{} = scope, %Rule{} = rule, attrs) do | |
| 61 | + with :ok <- Organizations.authorize(scope, "project:write"), | |
| 62 | + do: rule |> Rule.changeset(attrs) |> Repo.update() | |
| 63 | + end | |
| 64 | + | |
| 65 | + @doc "Needs `project:write`." | |
| 66 | + def delete_rule(%Scope{} = scope, %Rule{} = rule) do | |
| 67 | + with :ok <- Organizations.authorize(scope, "project:write"), do: Repo.delete(rule) | |
| 68 | + end | |
| 69 | + | |
| 70 | + @doc "Needs `project:write`." | |
| 71 | + def add_recipient(%Scope{} = scope, %Rule{} = rule, attrs) do | |
| 72 | + with :ok <- Organizations.authorize(scope, "project:write") do | |
| 73 | + %Recipient{alert_rule_id: rule.id} |> Recipient.changeset(attrs) |> Repo.insert() | |
| 74 | + end | |
| 75 | + end | |
| 76 | + | |
| 77 | + @doc "Needs `project:write`." | |
| 78 | + def delete_recipient(%Scope{} = scope, %Rule{} = rule, recipient_id) do | |
| 79 | + with :ok <- Organizations.authorize(scope, "project:write"), | |
| 80 | + {:ok, id} <- Ecto.UUID.cast(recipient_id), | |
| 81 | + %Recipient{} = r <- Repo.get_by(Recipient, id: id, alert_rule_id: rule.id) do | |
| 82 | + Repo.delete(r) | |
| 83 | + else | |
| 84 | + {:error, _} = error -> error | |
| 85 | + _ -> {:error, :not_found} | |
| 86 | + end | |
| 87 | + end | |
| 88 | + | |
| 89 | + ## Email subscriptions | |
| 90 | + | |
| 91 | + @doc "Whether `user` gets email alerts for `project` (on unless turned off)." | |
| 92 | + def subscribed?(%User{id: user_id}, %Project{id: project_id}) do | |
| 93 | + Repo.one( | |
| 94 | + from s in "user_project_alerts", | |
| 95 | + where: | |
| 96 | + s.user_id == type(^user_id, :binary_id) and | |
| 97 | + s.project_id == type(^project_id, :binary_id), | |
| 98 | + select: s.enabled | |
| 99 | + ) != false | |
| 100 | + end | |
| 101 | + | |
| 102 | + def set_subscription(%User{id: user_id}, %Project{id: project_id}, enabled?) | |
| 103 | + when is_boolean(enabled?) do | |
| 104 | + Repo.insert_all( | |
| 105 | + "user_project_alerts", | |
| 106 | + [ | |
| 107 | + %{ | |
| 108 | + user_id: Ecto.UUID.dump!(user_id), | |
| 109 | + project_id: Ecto.UUID.dump!(project_id), | |
| 110 | + enabled: enabled? | |
| 111 | + } | |
| 112 | + ], | |
| 113 | + on_conflict: [set: [enabled: enabled?]], | |
| 114 | + conflict_target: [:user_id, :project_id] | |
| 115 | + ) | |
| 116 | + | |
| 117 | + :ok | |
| 118 | + end | |
| 119 | + | |
| 120 | + @doc """ | |
| 121 | + The users email alerts for a project go to: members who can see it (all | |
| 122 | + of a manager's or owner's projects, a team's, every one with open | |
| 123 | + membership), less those who turned its alerts off. | |
| 124 | + """ | |
| 125 | + def email_recipients(%Project{} = project) do | |
| 126 | + project = Repo.preload(project, :organization) | |
| 127 | + | |
| 128 | + team_member_ids = | |
| 129 | + from(tm in "team_members", | |
| 130 | + join: tp in "team_projects", | |
| 131 | + on: tp.team_id == tm.team_id, | |
| 132 | + where: tp.project_id == type(^project.id, :binary_id), | |
| 133 | + select: tm.member_id | |
| 134 | + ) | |
| 135 | + | |
| 136 | + opted_out = | |
| 137 | + from(s in "user_project_alerts", | |
| 138 | + where: s.project_id == type(^project.id, :binary_id) and not s.enabled, | |
| 139 | + select: s.user_id | |
| 140 | + ) | |
| 141 | + | |
| 142 | + from(u in User, | |
| 143 | + join: m in Member, | |
| 144 | + on: m.user_id == u.id, | |
| 145 | + where: m.organization_id == ^project.organization_id, | |
| 146 | + where: u.id not in subquery(opted_out), | |
| 147 | + order_by: u.email, | |
| 148 | + distinct: true | |
| 149 | + ) | |
| 150 | + |> then(fn q -> | |
| 151 | + if project.organization.open_membership, | |
| 152 | + do: q, | |
| 153 | + else: where(q, [_u, m], m.role in [:manager, :owner] or m.id in subquery(team_member_ids)) | |
| 154 | + end) | |
| 155 | + |> Repo.all() | |
| 156 | + end | |
| 157 | + | |
| 158 | + ## Candidates | |
| 159 | + | |
| 160 | + @doc """ | |
| 161 | + Notes that an event touched `issue`: `:new` (first event), `:regression` | |
| 162 | + (reopened), or `:event`. One waiting row per issue and kind. | |
| 163 | + """ | |
| 164 | + def record(%Issue{} = issue, kind) when kind in [:event, :new, :regression] do | |
| 165 | + Repo.insert_all( | |
| 166 | + "alert_candidates", | |
| 167 | + [ | |
| 168 | + %{ | |
| 169 | + id: Ecto.UUID.dump!(Vigil.Schema.uuid7()), | |
| 170 | + project_id: Ecto.UUID.dump!(issue.project_id), | |
| 171 | + issue_id: Ecto.UUID.dump!(issue.id), | |
| 172 | + kind: Atom.to_string(kind), | |
| 173 | + inserted_at: DateTime.utc_now(:second) | |
| 174 | + } | |
| 175 | + ], | |
| 176 | + on_conflict: :nothing, | |
| 177 | + conflict_target: [:issue_id, :kind] | |
| 178 | + ) | |
| 179 | + | |
| 180 | + :ok | |
| 181 | + end | |
| 182 | + | |
| 183 | + @doc "A regressed issue may be told about again by every rule." | |
| 184 | + def forget(%Issue{id: issue_id}) do | |
| 185 | + Repo.delete_all( | |
| 186 | + from s in "alert_issue_states", where: s.issue_id == type(^issue_id, :binary_id) | |
| 187 | + ) | |
| 188 | + | |
| 189 | + :ok | |
| 190 | + end | |
| 191 | + | |
| 192 | + ## Evaluation | |
| 193 | + | |
| 194 | + @doc """ | |
| 195 | + Takes the waiting candidates and fires the rules they meet. Returns the | |
| 196 | + notifications made (their deliveries are queued). | |
| 197 | + """ | |
| 198 | + def evaluate(now \\ DateTime.utc_now()) do | |
| 199 | + candidates = take_candidates() | |
| 200 | + | |
| 201 | + candidates | |
| 202 | + |> Enum.group_by(& &1.project_id) | |
| 203 | + |> Enum.flat_map(fn {project_id, cands} -> evaluate_project(project_id, cands, now) end) | |
| 204 | + end | |
| 205 | + | |
| 206 | + defp take_candidates do | |
| 207 | + %{rows: rows} = | |
| 208 | + Repo.query!("DELETE FROM alert_candidates RETURNING project_id, issue_id, kind") | |
| 209 | + | |
| 210 | + Enum.map(rows, fn [p, i, k] -> | |
| 211 | + %{project_id: Ecto.UUID.load!(p), issue_id: Ecto.UUID.load!(i), kind: k} | |
| 212 | + end) | |
| 213 | + end | |
| 214 | + | |
| 215 | + defp evaluate_project(project_id, candidates, now) do | |
| 216 | + rules = | |
| 217 | + Repo.all( | |
| 218 | + from r in Rule, | |
| 219 | + where: r.project_id == ^project_id and r.enabled, | |
| 220 | + preload: :recipients | |
| 221 | + ) | |
| 222 | + | |
| 223 | + Enum.flat_map(rules, fn rule -> | |
| 224 | + issue_ids = | |
| 225 | + rule | |
| 226 | + |> matching(candidates, now) | |
| 227 | + |> open_issues() | |
| 228 | + |> due(rule, now) | |
| 229 | + | |
| 230 | + if issue_ids == [], do: [], else: [fire(rule, issue_ids, now)] | |
| 231 | + end) | |
| 232 | + end | |
| 233 | + | |
| 234 | + defp matching(%Rule{kind: :new_issue}, cands, _now), do: ids_of(cands, "new") | |
| 235 | + defp matching(%Rule{kind: :regression}, cands, _now), do: ids_of(cands, "regression") | |
| 236 | + | |
| 237 | + defp matching(%Rule{kind: :frequency} = rule, cands, now) do | |
| 238 | + ids = cands |> Enum.map(& &1.issue_id) |> Enum.uniq() | |
| 239 | + since = Vigil.Partitions.uuid7_floor(DateTime.add(now, -rule.timespan_minutes, :minute)) | |
| 240 | + | |
| 241 | + from(e in IssueEvent, | |
| 242 | + where: e.issue_id in ^ids and e.id >= ^since, | |
| 243 | + group_by: e.issue_id, | |
| 244 | + having: count(e.id) >= ^rule.quantity, | |
| 245 | + select: e.issue_id | |
| 246 | + ) | |
| 247 | + |> Repo.all() | |
| 248 | + end | |
| 249 | + | |
| 250 | + defp ids_of(cands, kind), do: for(c <- cands, c.kind == kind, uniq: true, do: c.issue_id) | |
| 251 | + | |
| 252 | + defp open_issues([]), do: [] | |
| 253 | + | |
| 254 | + defp open_issues(ids) do | |
| 255 | + Repo.all( | |
| 256 | + from i in Issue, | |
| 257 | + where: i.id in ^ids and i.status == :unresolved and is_nil(i.deleted_at), | |
| 258 | + select: i.id | |
| 259 | + ) | |
| 260 | + end | |
| 261 | + | |
| 262 | + # Not told about yet by this rule, or told longer ago than renotify. | |
| 263 | + defp due([], _rule, _now), do: [] | |
| 264 | + | |
| 265 | + defp due(ids, rule, now) do | |
| 266 | + told = | |
| 267 | + from(s in "alert_issue_states", | |
| 268 | + where: | |
| 269 | + s.alert_rule_id == type(^rule.id, :binary_id) and | |
| 270 | + s.issue_id in type(^ids, {:array, :binary_id}), | |
| 271 | + select: {type(s.issue_id, :binary_id), s.last_notified_at} | |
| 272 | + ) | |
| 273 | + |> Repo.all() | |
| 274 | + |> Map.new() | |
| 275 | + | |
| 276 | + Enum.filter(ids, fn id -> | |
| 277 | + case told[id] do | |
| 278 | + nil -> | |
| 279 | + true | |
| 280 | + | |
| 281 | + last when is_integer(rule.renotify_minutes) -> | |
| 282 | + NaiveDateTime.diff(DateTime.to_naive(now), last, :minute) >= rule.renotify_minutes | |
| 283 | + | |
| 284 | + _ -> | |
| 285 | + false | |
| 286 | + end | |
| 287 | + end) | |
| 288 | + end | |
| 289 | + | |
| 290 | + defp fire(rule, issue_ids, now) do | |
| 291 | + {:ok, notification} = | |
| 292 | + Repo.transact(fn -> | |
| 293 | + notification = | |
| 294 | + Repo.insert!(%Notification{ | |
| 295 | + alert_rule_id: rule.id, | |
| 296 | + project_id: rule.project_id, | |
| 297 | + issue_ids: issue_ids | |
| 298 | + }) | |
| 299 | + | |
| 300 | + at = DateTime.truncate(now, :second) | |
| 301 | + | |
| 302 | + Repo.insert_all( | |
| 303 | + "alert_issue_states", | |
| 304 | + for id <- issue_ids do | |
| 305 | + %{ | |
| 306 | + alert_rule_id: Ecto.UUID.dump!(rule.id), | |
| 307 | + issue_id: Ecto.UUID.dump!(id), | |
| 308 | + last_notified_at: at | |
| 309 | + } | |
| 310 | + end, | |
| 311 | + on_conflict: [set: [last_notified_at: at]], | |
| 312 | + conflict_target: [:alert_rule_id, :issue_id] | |
| 313 | + ) | |
| 314 | + | |
| 315 | + recipients = | |
| 316 | + if rule.recipients == [], do: [%Recipient{type: :email}], else: rule.recipients | |
| 317 | + | |
| 318 | + for recipient <- recipients do | |
| 319 | + delivery = | |
| 320 | + Repo.insert!(%Delivery{ | |
| 321 | + notification_id: notification.id, | |
| 322 | + recipient_id: recipient.id, | |
| 323 | + project_id: rule.project_id, | |
| 324 | + type: Atom.to_string(recipient.type), | |
| 325 | + target: recipient.url | |
| 326 | + }) | |
| 327 | + | |
| 328 | + {:ok, _} = DeliverWorker.enqueue(delivery) | |
| 329 | + end | |
| 330 | + | |
| 331 | + {:ok, notification} | |
| 332 | + end) | |
| 333 | + | |
| 334 | + notification | |
| 335 | + end | |
| 336 | + | |
| 337 | + ## Deliveries | |
| 338 | + | |
| 339 | + @doc "A project's latest deliveries, newest first, with their rule." | |
| 340 | + def list_deliveries(%Project{id: project_id}, limit \\ 50) do | |
| 341 | + Repo.all( | |
| 342 | + from d in Delivery, | |
| 343 | + where: d.project_id == ^project_id, | |
| 344 | + order_by: [desc: d.id], | |
| 345 | + limit: ^limit, | |
| 346 | + preload: [notification: :alert_rule] | |
| 347 | + ) | |
| 348 | + end | |
| 349 | + | |
| 350 | + @doc """ | |
| 351 | + What a notification says: the shape `Vigil.Alerts.Webhooks.deliver/3` | |
| 352 | + and the alert email take. Issues newest activity first, with the tags | |
| 353 | + alerts show (environment, release, server name, and the recipient's | |
| 354 | + `tags_to_add`). | |
| 355 | + """ | |
| 356 | + def alert_for(%Notification{} = notification, extra_tags \\ []) do | |
| 357 | + rule = Repo.get!(Rule, notification.alert_rule_id) | |
| 358 | + project = Repo.get!(Project, notification.project_id) |> Repo.preload(:organization) | |
| 359 | + org = project.organization | |
| 360 | + base = VigilWeb.base_url() | |
| 361 | + project_url = "#{base}/orgs/#{org.slug}/projects/#{project.slug}" | |
| 362 | + | |
| 363 | + issues = | |
| 364 | + from(i in Issue, where: i.id in ^notification.issue_ids, order_by: [desc: i.last_seen]) | |
| 365 | + |> Repo.all() | |
| 366 | + |> Enum.map(fn i -> | |
| 367 | + %{ | |
| 368 | + title: i.title, | |
| 369 | + culprit: i.culprit, | |
| 370 | + short_id: "#{String.upcase(project.slug)}-#{i.short_id}", | |
| 371 | + url: "#{project_url}/issues/#{i.short_id}", | |
| 372 | + level: i.level, | |
| 373 | + count: i.count, | |
| 374 | + first_seen: i.first_seen, | |
| 375 | + last_seen: i.last_seen, | |
| 376 | + status: i.status, | |
| 377 | + tags: alert_tags(i, ["environment", "release", "server_name" | extra_tags]) | |
| 378 | + } | |
| 379 | + end) | |
| 380 | + | |
| 381 | + %{ | |
| 382 | + title: | |
| 383 | + "Vigil Alert (#{length(issues)} #{if length(issues) == 1, do: "issue", else: "issues"})", | |
| 384 | + rule: rule.name, | |
| 385 | + project: %{name: project.name, slug: project.slug}, | |
| 386 | + organization: %{name: org.name, slug: org.slug}, | |
| 387 | + url: project_url, | |
| 388 | + issues: issues | |
| 389 | + } | |
| 390 | + end | |
| 391 | + | |
| 392 | + # The most common value of each key over the issue's stored days. | |
| 393 | + defp alert_tags(issue, keys) do | |
| 394 | + from(t in "issue_tags", | |
| 395 | + where: t.issue_id == type(^issue.id, :binary_id) and t.key in ^keys, | |
| 396 | + group_by: [t.key, t.value], | |
| 397 | + select: {t.key, t.value, type(sum(t.count), :integer)} | |
| 398 | + ) | |
| 399 | + |> Repo.all() | |
| 400 | + |> Enum.group_by(&elem(&1, 0)) | |
| 401 | + |> Map.new(fn {k, rows} -> {k, rows |> Enum.max_by(&elem(&1, 2)) |> elem(1)} end) | |
| 402 | + end | |
| 403 | + | |
| 404 | + @doc """ | |
| 405 | + Sends a test message to one recipient now (the alerts page's "Send | |
| 406 | + test"). Email goes to the asking user only. | |
| 407 | + """ | |
| 408 | + def send_test(%Scope{} = scope, %Recipient{type: :email}, project) do | |
| 409 | + with :ok <- Organizations.authorize(scope, "project:write") do | |
| 410 | + scope.user |> Vigil.Alerts.Email.test(project) |> Vigil.Mailer.deliver() |> then(&ok_or/1) | |
| 411 | + end | |
| 412 | + end | |
| 413 | + | |
| 414 | + def send_test(%Scope{} = scope, %Recipient{} = recipient, project) do | |
| 415 | + with :ok <- Organizations.authorize(scope, "project:write") do | |
| 416 | + Vigil.Alerts.Webhooks.deliver_message( | |
| 417 | + webhook_recipient(recipient), | |
| 418 | + Vigil.Alerts.Webhooks.test_message(%{name: project.name}), | |
| 419 | + webhook_opts() | |
| 420 | + ) | |
| 421 | + end | |
| 422 | + end | |
| 423 | + | |
| 424 | + @doc """ | |
| 425 | + Options for `Vigil.Alerts.Webhooks` calls, from `config :vigil, | |
| 426 | + :webhook_opts` (tests stub HTTP and DNS there: `:req_options`, | |
| 427 | + `:resolver`). | |
| 428 | + """ | |
| 429 | + def webhook_opts, do: Application.get_env(:vigil, :webhook_opts, []) | |
| 430 | + | |
| 431 | + @doc false | |
| 432 | + def webhook_recipient(%Recipient{} = r), | |
| 433 | + do: %{type: Atom.to_string(r.type), url: r.url, config: r.config || %{}} | |
| 434 | + | |
| 435 | + defp ok_or({:ok, _}), do: :ok | |
| 436 | + defp ok_or({:error, reason}), do: {:error, reason} | |
| 437 | +end |
added
lib/vigil/alerts/deliver_worker.ex
+88
−0
| 1 | +defmodule Vigil.Alerts.DeliverWorker do | |
| 2 | + @moduledoc """ | |
| 3 | + Sends one `Vigil.Alerts.Delivery`: an email to each of the project's | |
| 4 | + subscribed members, or one webhook (`Vigil.Alerts.Webhooks`). Retried by | |
| 5 | + Oban with backoff (#{5} attempts; GlitchTip tries once and swallows the | |
| 6 | + error); the delivery row records each outcome for the alerts page. | |
| 7 | + """ | |
| 8 | + use Oban.Worker, queue: :notify, max_attempts: 5 | |
| 9 | + | |
| 10 | + require Logger | |
| 11 | + | |
| 12 | + alias Vigil.Alerts | |
| 13 | + alias Vigil.Alerts.{Delivery, Recipient} | |
| 14 | + alias Vigil.Projects.Project | |
| 15 | + alias Vigil.Repo | |
| 16 | + | |
| 17 | + def enqueue(%Delivery{id: id}), do: %{delivery_id: id} |> new() |> Oban.insert() | |
| 18 | + | |
| 19 | + @impl Oban.Worker | |
| 20 | + def perform(%Oban.Job{args: %{"delivery_id" => id}, attempt: attempt, max_attempts: max}) do | |
| 21 | + case Repo.get(Delivery, id) |> Repo.preload([:notification, :recipient]) do | |
| 22 | + nil -> | |
| 23 | + :ok | |
| 24 | + | |
| 25 | + %Delivery{state: :sent} -> | |
| 26 | + :ok | |
| 27 | + | |
| 28 | + delivery -> | |
| 29 | + result = send_it(delivery) | |
| 30 | + | |
| 31 | + case result do | |
| 32 | + # A URL the outbound guard refuses won't become safe on retry. | |
| 33 | + {:error, {:unsafe_url, _}} = error -> | |
| 34 | + record(delivery, error, max, max) | |
| 35 | + {:cancel, elem(error, 1)} | |
| 36 | + | |
| 37 | + _ -> | |
| 38 | + record(delivery, result, attempt, max) | |
| 39 | + result | |
| 40 | + end | |
| 41 | + end | |
| 42 | + end | |
| 43 | + | |
| 44 | + defp send_it(%Delivery{type: "email"} = d) do | |
| 45 | + alert = Alerts.alert_for(d.notification) | |
| 46 | + project = Repo.get!(Project, d.notification.project_id) | |
| 47 | + | |
| 48 | + project | |
| 49 | + |> Alerts.email_recipients() | |
| 50 | + |> Enum.reduce_while(:ok, fn user, :ok -> | |
| 51 | + case user |> Vigil.Alerts.Email.issue_alert(alert) |> Vigil.Mailer.deliver() do | |
| 52 | + {:ok, _} -> {:cont, :ok} | |
| 53 | + {:error, reason} -> {:halt, {:error, {:mail, reason}}} | |
| 54 | + end | |
| 55 | + end) | |
| 56 | + end | |
| 57 | + | |
| 58 | + defp send_it(%Delivery{recipient: %Recipient{} = r} = d) do | |
| 59 | + alert = Alerts.alert_for(d.notification, r.tags_to_add || []) | |
| 60 | + Vigil.Alerts.Webhooks.deliver(Alerts.webhook_recipient(r), alert, Alerts.webhook_opts()) | |
| 61 | + end | |
| 62 | + | |
| 63 | + # The recipient was deleted since: nothing to send to. | |
| 64 | + defp send_it(%Delivery{recipient: nil}), do: :ok | |
| 65 | + | |
| 66 | + defp record(delivery, :ok, attempt, _max) do | |
| 67 | + delivery | |
| 68 | + |> Ecto.Changeset.change( | |
| 69 | + state: :sent, | |
| 70 | + attempts: attempt, | |
| 71 | + error: nil, | |
| 72 | + delivered_at: DateTime.utc_now(:second) | |
| 73 | + ) | |
| 74 | + |> Repo.update!() | |
| 75 | + end | |
| 76 | + | |
| 77 | + defp record(delivery, {:error, reason}, attempt, max) do | |
| 78 | + Logger.warning("alert delivery #{delivery.id} (#{delivery.type}) failed: #{inspect(reason)}") | |
| 79 | + | |
| 80 | + delivery | |
| 81 | + |> Ecto.Changeset.change( | |
| 82 | + state: if(attempt >= max, do: :failed, else: :pending), | |
| 83 | + attempts: attempt, | |
| 84 | + error: reason |> inspect() |> String.slice(0, 2000) | |
| 85 | + ) | |
| 86 | + |> Repo.update!() | |
| 87 | + end | |
| 88 | +end |
added
lib/vigil/alerts/delivery.ex
+24
−0
Click to load diff…
added
lib/vigil/alerts/email.ex
+90
−0
Click to load diff…
added
lib/vigil/alerts/evaluate_worker.ex
+10
−0
Click to load diff…
added
lib/vigil/alerts/notification.ex
+14
−0
Click to load diff…
added
lib/vigil/alerts/recipient.ex
+49
−0
Click to load diff…
added
lib/vigil/alerts/rule.ex
+50
−0
Click to load diff…
modified
lib/vigil/events/processor.ex
+16
−3
Click to load diff…
modified
lib/vigil_web/live/issue_live/index.ex
+9
−0
Click to load diff…
added
lib/vigil_web/live/project_live/alerts.ex
+467
−0
Click to load diff…
modified
lib/vigil_web/router.ex
+1
−0
Click to load diff…
added
priv/repo/migrations/20261201230109_create_alerts.exs
+117
−0
Click to load diff…
added
test/support/test_resolver.ex
+4
−0
Click to load diff…
added
test/vigil/alerts_test.exs
+228
−0
Click to load diff…
added
test/vigil_web/live/project_live/alerts_test.exs
+137
−0
Click to load diff…
Parents: 0f3693e