Feat/operator alerts (#1635)

* feat(state): durable operator alerts owned by the State Store

Alerts dedup on org+kind+subject, resolve themselves when a condition
clears, and are raised, resolved, dismissed and listed through the state
contract. Task transitions raise needs-human and failed alerts in the same
transaction; the store checks service health and prunes closed alerts.
Each raise and resolve queues a webhook delivery whose attempts are kept.

* feat(notify): deliver operator alerts to the webhook; raise config and release alerts

notify.webhook now receives raised and resolved alerts above a severity
threshold with HMAC-signed payloads, bounded retry and every attempt recorded
on the alert. archied raises model alias, provider and credential-binding
alerts from the effective configuration, an update alert from the release
channel, and a credential-rejected alert from the egress resolver. The
dashboard API lists and dismisses the caller's org's alerts.

* feat(ui): alert bell in the top bar and webhook alert settings

The bell lists the org's open alerts by severity with dismiss and a link per
alert, and refreshes from the event stream. The task settings page gains the
webhook severity threshold and signing secret. ui/dist rebuilt.
This commit is contained in:
sam authored and GitHub committed 2026-10-12 03:30:46 +11:00
1 parent f34f60f9c7
commit 8a3ba32c5a
43 files changed
+4671 -465

No files matched your search

+328
View File
@@ -0,0 +1,328 @@
// Operator alerts: the Postgres implementation of internal/domain/alert.Store.
// Every write runs in a transaction that holds an advisory lock on the alert's
// key, so a raise and a resolve of one alert never interleave, and records the
// event and the delivery the change owes in the same commit.
package postgres
import (
"context"
"errors"
"fmt"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/samcharles93/archie-core/internal/domain/alert"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/events"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
)
var (
_ alert.Store = (*Store)(nil)
_ alert.Pruner = (*Store)(nil)
)
// deliveriesPerAlert bounds the delivery history one listed alert carries.
const deliveriesPerAlert = 10
func alertFromRow(r postgresdb.Alert) alert.Alert {
a := alert.Alert{
ID: r.ID,
Org: org.OrgID(r.OrgID), Kind: r.Kind, Subject: r.Subject,
Severity: alert.Severity(r.Severity), Title: r.Title, Body: r.Body, Link: r.Link,
Condition: r.IsCondition, State: alert.State(r.State),
FirstRaised: r.FirstRaised, LastSeen: r.LastSeen, Count: r.Count, ClosedBy: r.ClosedBy,
}
if r.ClosedAt.Valid {
a.ClosedAt = r.ClosedAt.Time
}
return a
}
func alertParams(a alert.Alert) postgresdb.UpsertAlertParams {
return postgresdb.UpsertAlertParams{
OrgID: string(a.Org), Kind: a.Kind, Subject: a.Subject, Severity: string(a.Severity),
Title: a.Title, Body: a.Body, Link: a.Link, IsCondition: a.Condition, State: string(a.State),
FirstRaised: a.FirstRaised, LastSeen: a.LastSeen, Count: a.Count, ClosedBy: a.ClosedBy,
ClosedAt: pgtype.Timestamptz{Time: a.ClosedAt, Valid: !a.ClosedAt.IsZero()},
}
}
func alertLockKey(k alert.Key) string { return string(k.Org) + "\x00" + k.Kind + "\x00" + k.Subject }
// lockedAlert takes the key's lock and returns the stored alert, nil when
// there is none.
func lockedAlert(ctx context.Context, q *postgresdb.Queries, key alert.Key) (*alert.Alert, error) {
if err := q.LockAlertKey(ctx, alertLockKey(key)); err != nil {
return nil, err
}
row, err := q.GetAlertByKey(ctx, postgresdb.GetAlertByKeyParams{OrgID: string(key.Org), Kind: key.Kind, Subject: key.Subject})
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
}
if err != nil {
return nil, err
}
a := alertFromRow(row)
return &a, nil
}
// alertChanged records an alert's change on the event stream, and the
// delivery it owes when delivery is not empty.
func alertChanged(ctx context.Context, q *postgresdb.Queries, a alert.Alert, delivery string) error {
if delivery != "" {
if err := q.InsertAlertDelivery(ctx, postgresdb.InsertAlertDeliveryParams{AlertID: a.ID, Event: delivery}); err != nil {
return err
}
}
_, err := insertEventQ(org.WithOrg(ctx, a.Org), q, events.Event{
Kind: events.KindAlert, Detail: a.Title,
Data: map[string]any{"id": a.ID, "kind": a.Kind, "state": string(a.State), "severity": string(a.Severity)},
})
return err
}
// raiseAlert stores in under q, which must be a transaction.
func raiseAlert(ctx context.Context, q *postgresdb.Queries, in alert.Input) (alert.Alert, error) {
if err := in.Validate(); err != nil {
return alert.Alert{}, err
}
prev, err := lockedAlert(ctx, q, in.Key)
if err != nil {
return alert.Alert{}, err
}
next, opened := alert.Apply(prev, in, time.Now().UTC())
row, err := q.UpsertAlert(ctx, alertParams(next))
if err != nil {
return alert.Alert{}, err
}
stored := alertFromRow(row)
if opened {
if err := alertChanged(ctx, q, stored, alert.EventRaised); err != nil {
return alert.Alert{}, err
}
}
return stored, nil
}
// resolveAlert clears the alert under key through q, which must be a
// transaction.
func resolveAlert(ctx context.Context, q *postgresdb.Queries, key alert.Key, by string) error {
prev, err := lockedAlert(ctx, q, key)
if err != nil || prev == nil {
return err
}
next, changed := alert.Resolve(*prev, by, time.Now().UTC())
if !changed {
return nil
}
row, err := q.UpsertAlert(ctx, alertParams(next))
if err != nil {
return err
}
return alertChanged(ctx, q, alertFromRow(row), alert.EventResolved)
}
func (s *Store) inTx(ctx context.Context, fn func(*postgresdb.Queries) error) error {
tx, err := s.pool.Begin(ctx)
if err != nil {
return err
}
defer func() { _ = tx.Rollback(ctx) }()
if err := fn(postgresdb.New(tx)); err != nil {
return err
}
return tx.Commit(ctx)
}
// Raise stores in idempotently.
func (s *Store) RaiseAlert(ctx context.Context, in alert.Input) (alert.Alert, error) {
var out alert.Alert
err := s.inTx(ctx, func(q *postgresdb.Queries) (err error) {
out, err = raiseAlert(ctx, q, in)
return err
})
return out, err
}
// Resolve clears the alert under key.
func (s *Store) ResolveAlert(ctx context.Context, key alert.Key, by string) error {
return s.inTx(ctx, func(q *postgresdb.Queries) error { return resolveAlert(ctx, q, key, by) })
}
// Dismiss dismisses an open alert of orgID. An alert of another org is
// indistinguishable from none.
func (s *Store) DismissAlert(ctx context.Context, orgID org.OrgID, id int64, by string) error {
return s.inTx(ctx, func(q *postgresdb.Queries) error {
row, err := q.GetOrgAlert(ctx, postgresdb.GetOrgAlertParams{OrgID: string(orgID), ID: id})
if errors.Is(err, pgx.ErrNoRows) {
return alert.ErrNotFound
}
if err != nil {
return err
}
prev, err := lockedAlert(ctx, q, alertFromRow(row).Key)
if err != nil || prev == nil {
return errors.Join(err, alert.ErrNotFound)
}
next, changed := alert.Dismiss(*prev, by, time.Now().UTC())
if !changed {
return nil
}
stored, err := q.UpsertAlert(ctx, alertParams(next))
if err != nil {
return err
}
return alertChanged(ctx, q, alertFromRow(stored), "")
})
}
// List returns an org's alerts with their deliveries.
func (s *Store) ListAlerts(ctx context.Context, orgID org.OrgID, filter alert.Filter) ([]alert.Alert, error) {
states := []string{string(alert.StateOpen)}
if len(filter.States) > 0 {
states = states[:0]
for _, st := range filter.States {
states = append(states, string(st))
}
}
limit := filter.Limit
if limit <= 0 || limit > 500 {
limit = 200
}
q := s.queries()
rows, err := q.ListAlerts(ctx, postgresdb.ListAlertsParams{OrgID: string(orgID), States: states, PageLimit: int32(limit)})
if err != nil {
return nil, err
}
out := make([]alert.Alert, len(rows))
ids := make([]int64, len(rows))
for i, r := range rows {
out[i], ids[i] = alertFromRow(r), r.ID
}
if len(ids) == 0 {
return nil, nil
}
deliveries, err := alertDeliveries(ctx, q, ids)
if err != nil {
return nil, err
}
for i := range out {
out[i].Deliveries = deliveries[out[i].ID]
}
return out, nil
}
// alertDeliveries returns each alert's newest deliveries with their attempts.
func alertDeliveries(ctx context.Context, q *postgresdb.Queries, alertIDs []int64) (map[int64][]alert.Delivery, error) {
rows, err := q.ListAlertDeliveries(ctx, alertIDs)
if err != nil {
return nil, err
}
byAlert := map[int64][]alert.Delivery{}
var deliveryIDs []int64
for _, r := range rows {
if len(byAlert[r.AlertID]) >= deliveriesPerAlert {
continue
}
byAlert[r.AlertID] = append(byAlert[r.AlertID], deliveryFromRow(r))
deliveryIDs = append(deliveryIDs, r.ID)
}
if len(deliveryIDs) == 0 {
return byAlert, nil
}
attempts, err := q.ListAlertAttempts(ctx, deliveryIDs)
if err != nil {
return nil, err
}
byDelivery := map[int64][]alert.Attempt{}
for _, a := range attempts {
byDelivery[a.DeliveryID] = append(byDelivery[a.DeliveryID], alert.Attempt{
N: a.Attempt, At: a.At, StatusCode: int(a.StatusCode), Error: a.Error,
})
}
for _, list := range byAlert {
for i := range list {
list[i].Attempts = byDelivery[list[i].ID]
}
}
return byAlert, nil
}
func deliveryFromRow(r postgresdb.AlertDelivery) alert.Delivery {
return alert.Delivery{
ID: r.ID, AlertID: r.AlertID, Event: r.Event, State: r.State,
CreatedAt: r.CreatedAt, NextAttemptAt: r.NextAttemptAt,
}
}
// Prune removes alerts closed before cutoff, with their deliveries.
func (s *Store) PruneAlerts(ctx context.Context, cutoff time.Time) (int64, error) {
return s.queries().PruneAlerts(ctx, pgtype.Timestamptz{Time: cutoff, Valid: true})
}
// ClaimDeliveries returns the due deliveries with their alerts.
func (s *Store) ClaimAlertDeliveries(ctx context.Context, limit int) ([]alert.Due, error) {
if limit <= 0 || limit > 100 {
limit = 20
}
var out []alert.Due
err := s.inTx(ctx, func(q *postgresdb.Queries) error {
rows, err := q.ClaimAlertDeliveries(ctx, int32(limit))
if err != nil {
return err
}
for _, r := range rows {
row, err := q.GetAlert(ctx, r.AlertID)
if err != nil {
return err
}
out = append(out, alert.Due{Delivery: deliveryFromRow(r), Alert: alertFromRow(row), Attempt: r.Attempts + 1})
}
return nil
})
return out, err
}
// RecordAttempt records one attempt and settles or reschedules the delivery.
func (s *Store) RecordAlertAttempt(ctx context.Context, o alert.Outcome) error {
return s.inTx(ctx, func(q *postgresdb.Queries) error {
d, err := q.LockAlertDelivery(ctx, o.DeliveryID)
if errors.Is(err, pgx.ErrNoRows) {
return alert.ErrNotFound
}
if err != nil {
return err
}
if d.State != alert.DeliveryPending {
return nil
}
now := time.Now().UTC()
params := postgresdb.SettleAlertDeliveryParams{ID: d.ID, State: alert.DeliveryPending, Attempts: d.Attempts, NextAttemptAt: d.NextAttemptAt}
switch {
case o.Skipped:
params.State = alert.DeliverySkipped
default:
params.Attempts++
if err := q.InsertAlertAttempt(ctx, postgresdb.InsertAlertAttemptParams{
DeliveryID: d.ID, Attempt: params.Attempts, StatusCode: int64(o.StatusCode), Error: o.Error,
}); err != nil {
return err
}
switch {
case o.OK():
params.State = alert.DeliveryDelivered
case params.Attempts >= alert.MaxDeliveryAttempts:
params.State = alert.DeliveryFailed
default:
params.NextAttemptAt = now.Add(alert.RetryDelay(params.Attempts))
}
}
if err := q.SettleAlertDelivery(ctx, params); err != nil {
return fmt.Errorf("settle alert delivery: %w", err)
}
return nil
})
}
@@ -0,0 +1,56 @@
-- Operator alerts: things that need a human, one row per (org, kind, subject).
-- Raising an open alert again bumps the row instead of adding one. A
-- condition-backed alert resolves when its condition clears; an event alert
-- stays until dismissed. Deliveries are the outbound notices (the notify
-- webhook) each raise or resolve owes, with every attempt kept.
-- +goose Up
CREATE TABLE alerts (
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
org_id text NOT NULL,
kind text NOT NULL,
subject text NOT NULL,
severity text NOT NULL CHECK (severity IN ('info', 'warning', 'action')),
title text NOT NULL,
body text NOT NULL DEFAULT '',
link text NOT NULL DEFAULT '',
is_condition boolean NOT NULL,
state text NOT NULL DEFAULT 'open' CHECK (state IN ('open', 'resolved', 'dismissed')),
first_raised timestamptz NOT NULL,
last_seen timestamptz NOT NULL,
count bigint NOT NULL DEFAULT 1,
closed_by text NOT NULL DEFAULT '',
closed_at timestamptz,
UNIQUE (org_id, kind, subject)
);
CREATE INDEX idx_alerts_org_state ON alerts (org_id, state, id);
CREATE INDEX idx_alerts_closed ON alerts (closed_at) WHERE state <> 'open';
CREATE TABLE alert_deliveries (
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
alert_id bigint NOT NULL REFERENCES alerts (id) ON DELETE CASCADE,
event text NOT NULL CHECK (event IN ('raised', 'resolved')),
state text NOT NULL DEFAULT 'pending' CHECK (state IN ('pending', 'delivered', 'failed', 'skipped')),
created_at timestamptz NOT NULL DEFAULT now(),
next_attempt_at timestamptz NOT NULL DEFAULT now(),
attempts bigint NOT NULL DEFAULT 0
);
CREATE INDEX idx_alert_deliveries_due ON alert_deliveries (next_attempt_at) WHERE state = 'pending';
CREATE INDEX idx_alert_deliveries_alert ON alert_deliveries (alert_id, id);
CREATE TABLE alert_delivery_attempts (
id bigint GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
delivery_id bigint NOT NULL REFERENCES alert_deliveries (id) ON DELETE CASCADE,
attempt bigint NOT NULL,
at timestamptz NOT NULL DEFAULT now(),
status_code bigint NOT NULL DEFAULT 0,
error text NOT NULL DEFAULT ''
);
CREATE INDEX idx_alert_delivery_attempts_delivery ON alert_delivery_attempts (delivery_id, id);
-- +goose Down
DROP TABLE alert_delivery_attempts;
DROP TABLE alert_deliveries;
DROP TABLE alerts;
@@ -0,0 +1,448 @@
// Code generated by sqlc. DO NOT EDIT.
// versions:
// sqlc v1.31.1
// source: alerts.sql
package postgresdb
import (
"context"
"time"
"github.com/jackc/pgx/v5/pgtype"
)
const claimAlertDeliveries = `-- name: ClaimAlertDeliveries :many
UPDATE alert_deliveries SET next_attempt_at = now() + interval '2 minutes'
WHERE id IN (
SELECT d.id FROM alert_deliveries d
WHERE d.state = 'pending' AND d.next_attempt_at <= now()
ORDER BY d.id LIMIT $1 FOR UPDATE SKIP LOCKED)
RETURNING id, alert_id, event, state, created_at, next_attempt_at, attempts
`
func (q *Queries) ClaimAlertDeliveries(ctx context.Context, pageLimit int32) ([]AlertDelivery, error) {
rows, err := q.db.Query(ctx, claimAlertDeliveries, pageLimit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []AlertDelivery
for rows.Next() {
var i AlertDelivery
if err := rows.Scan(
&i.ID,
&i.AlertID,
&i.Event,
&i.State,
&i.CreatedAt,
&i.NextAttemptAt,
&i.Attempts,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const getAlert = `-- name: GetAlert :one
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
FROM alerts WHERE id = $1
`
func (q *Queries) GetAlert(ctx context.Context, id int64) (Alert, error) {
row := q.db.QueryRow(ctx, getAlert, id)
var i Alert
err := row.Scan(
&i.ID,
&i.OrgID,
&i.Kind,
&i.Subject,
&i.Severity,
&i.Title,
&i.Body,
&i.Link,
&i.IsCondition,
&i.State,
&i.FirstRaised,
&i.LastSeen,
&i.Count,
&i.ClosedBy,
&i.ClosedAt,
)
return i, err
}
const getAlertByKey = `-- name: GetAlertByKey :one
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
FROM alerts WHERE org_id = $1 AND kind = $2 AND subject = $3
`
type GetAlertByKeyParams struct {
OrgID string
Kind string
Subject string
}
func (q *Queries) GetAlertByKey(ctx context.Context, arg GetAlertByKeyParams) (Alert, error) {
row := q.db.QueryRow(ctx, getAlertByKey, arg.OrgID, arg.Kind, arg.Subject)
var i Alert
err := row.Scan(
&i.ID,
&i.OrgID,
&i.Kind,
&i.Subject,
&i.Severity,
&i.Title,
&i.Body,
&i.Link,
&i.IsCondition,
&i.State,
&i.FirstRaised,
&i.LastSeen,
&i.Count,
&i.ClosedBy,
&i.ClosedAt,
)
return i, err
}
const getOrgAlert = `-- name: GetOrgAlert :one
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
FROM alerts WHERE org_id = $1 AND id = $2
`
type GetOrgAlertParams struct {
OrgID string
ID int64
}
func (q *Queries) GetOrgAlert(ctx context.Context, arg GetOrgAlertParams) (Alert, error) {
row := q.db.QueryRow(ctx, getOrgAlert, arg.OrgID, arg.ID)
var i Alert
err := row.Scan(
&i.ID,
&i.OrgID,
&i.Kind,
&i.Subject,
&i.Severity,
&i.Title,
&i.Body,
&i.Link,
&i.IsCondition,
&i.State,
&i.FirstRaised,
&i.LastSeen,
&i.Count,
&i.ClosedBy,
&i.ClosedAt,
)
return i, err
}
const insertAlertAttempt = `-- name: InsertAlertAttempt :exec
INSERT INTO alert_delivery_attempts (delivery_id, attempt, status_code, error) VALUES ($1, $2, $3, $4)
`
type InsertAlertAttemptParams struct {
DeliveryID int64
Attempt int64
StatusCode int64
Error string
}
func (q *Queries) InsertAlertAttempt(ctx context.Context, arg InsertAlertAttemptParams) error {
_, err := q.db.Exec(ctx, insertAlertAttempt,
arg.DeliveryID,
arg.Attempt,
arg.StatusCode,
arg.Error,
)
return err
}
const insertAlertDelivery = `-- name: InsertAlertDelivery :exec
INSERT INTO alert_deliveries (alert_id, event) VALUES ($1, $2)
`
type InsertAlertDeliveryParams struct {
AlertID int64
Event string
}
func (q *Queries) InsertAlertDelivery(ctx context.Context, arg InsertAlertDeliveryParams) error {
_, err := q.db.Exec(ctx, insertAlertDelivery, arg.AlertID, arg.Event)
return err
}
const listAlertAttempts = `-- name: ListAlertAttempts :many
SELECT id, delivery_id, attempt, at, status_code, error
FROM alert_delivery_attempts WHERE delivery_id = ANY($1::bigint[]) ORDER BY delivery_id, id
`
func (q *Queries) ListAlertAttempts(ctx context.Context, deliveryIds []int64) ([]AlertDeliveryAttempt, error) {
rows, err := q.db.Query(ctx, listAlertAttempts, deliveryIds)
if err != nil {
return nil, err
}
defer rows.Close()
var items []AlertDeliveryAttempt
for rows.Next() {
var i AlertDeliveryAttempt
if err := rows.Scan(
&i.ID,
&i.DeliveryID,
&i.Attempt,
&i.At,
&i.StatusCode,
&i.Error,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listAlertDeliveries = `-- name: ListAlertDeliveries :many
SELECT id, alert_id, event, state, created_at, next_attempt_at, attempts
FROM alert_deliveries WHERE alert_id = ANY($1::bigint[]) ORDER BY alert_id, id DESC
`
func (q *Queries) ListAlertDeliveries(ctx context.Context, alertIds []int64) ([]AlertDelivery, error) {
rows, err := q.db.Query(ctx, listAlertDeliveries, alertIds)
if err != nil {
return nil, err
}
defer rows.Close()
var items []AlertDelivery
for rows.Next() {
var i AlertDelivery
if err := rows.Scan(
&i.ID,
&i.AlertID,
&i.Event,
&i.State,
&i.CreatedAt,
&i.NextAttemptAt,
&i.Attempts,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const listAlerts = `-- name: ListAlerts :many
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
FROM alerts
WHERE org_id = $1 AND state = ANY($2::text[])
ORDER BY CASE severity WHEN 'action' THEN 3 WHEN 'warning' THEN 2 ELSE 1 END DESC, last_seen DESC, id DESC
LIMIT $3
`
type ListAlertsParams struct {
OrgID string
States []string
PageLimit int32
}
func (q *Queries) ListAlerts(ctx context.Context, arg ListAlertsParams) ([]Alert, error) {
rows, err := q.db.Query(ctx, listAlerts, arg.OrgID, arg.States, arg.PageLimit)
if err != nil {
return nil, err
}
defer rows.Close()
var items []Alert
for rows.Next() {
var i Alert
if err := rows.Scan(
&i.ID,
&i.OrgID,
&i.Kind,
&i.Subject,
&i.Severity,
&i.Title,
&i.Body,
&i.Link,
&i.IsCondition,
&i.State,
&i.FirstRaised,
&i.LastSeen,
&i.Count,
&i.ClosedBy,
&i.ClosedAt,
); err != nil {
return nil, err
}
items = append(items, i)
}
if err := rows.Err(); err != nil {
return nil, err
}
return items, nil
}
const lockAlertDelivery = `-- name: LockAlertDelivery :one
SELECT id, alert_id, event, state, created_at, next_attempt_at, attempts
FROM alert_deliveries WHERE id = $1 FOR UPDATE
`
func (q *Queries) LockAlertDelivery(ctx context.Context, id int64) (AlertDelivery, error) {
row := q.db.QueryRow(ctx, lockAlertDelivery, id)
var i AlertDelivery
err := row.Scan(
&i.ID,
&i.AlertID,
&i.Event,
&i.State,
&i.CreatedAt,
&i.NextAttemptAt,
&i.Attempts,
)
return i, err
}
const lockAlertKey = `-- name: LockAlertKey :exec
SELECT pg_advisory_xact_lock(hashtextextended($1::text, 0))
`
// Operator alerts and their outbound deliveries (internal/domain/alert).
// Serialises raisers of one alert, so two first raises cannot both insert.
func (q *Queries) LockAlertKey(ctx context.Context, lockKey string) error {
_, err := q.db.Exec(ctx, lockAlertKey, lockKey)
return err
}
const pruneAlerts = `-- name: PruneAlerts :execrows
DELETE FROM alerts WHERE state <> 'open' AND closed_at < $1
`
func (q *Queries) PruneAlerts(ctx context.Context, closedAt pgtype.Timestamptz) (int64, error) {
result, err := q.db.Exec(ctx, pruneAlerts, closedAt)
if err != nil {
return 0, err
}
return result.RowsAffected(), nil
}
const settleAlertDelivery = `-- name: SettleAlertDelivery :exec
UPDATE alert_deliveries SET state = $2, attempts = $3, next_attempt_at = $4 WHERE id = $1
`
type SettleAlertDeliveryParams struct {
ID int64
State string
Attempts int64
NextAttemptAt time.Time
}
func (q *Queries) SettleAlertDelivery(ctx context.Context, arg SettleAlertDeliveryParams) error {
_, err := q.db.Exec(ctx, settleAlertDelivery,
arg.ID,
arg.State,
arg.Attempts,
arg.NextAttemptAt,
)
return err
}
const taskAlertInfo = `-- name: TaskAlertInfo :one
SELECT org_id, title, workflow, park_class FROM tasks WHERE id = $1
`
type TaskAlertInfoRow struct {
OrgID string
Title string
Workflow string
ParkClass string
}
func (q *Queries) TaskAlertInfo(ctx context.Context, id int64) (TaskAlertInfoRow, error) {
row := q.db.QueryRow(ctx, taskAlertInfo, id)
var i TaskAlertInfoRow
err := row.Scan(
&i.OrgID,
&i.Title,
&i.Workflow,
&i.ParkClass,
)
return i, err
}
const upsertAlert = `-- name: UpsertAlert :one
INSERT INTO alerts (org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
ON CONFLICT (org_id, kind, subject) DO UPDATE SET
severity = excluded.severity, title = excluded.title, body = excluded.body, link = excluded.link,
is_condition = excluded.is_condition, state = excluded.state, first_raised = excluded.first_raised,
last_seen = excluded.last_seen, count = excluded.count, closed_by = excluded.closed_by, closed_at = excluded.closed_at
RETURNING id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
`
type UpsertAlertParams struct {
OrgID string
Kind string
Subject string
Severity string
Title string
Body string
Link string
IsCondition bool
State string
FirstRaised time.Time
LastSeen time.Time
Count int64
ClosedBy string
ClosedAt pgtype.Timestamptz
}
func (q *Queries) UpsertAlert(ctx context.Context, arg UpsertAlertParams) (Alert, error) {
row := q.db.QueryRow(ctx, upsertAlert,
arg.OrgID,
arg.Kind,
arg.Subject,
arg.Severity,
arg.Title,
arg.Body,
arg.Link,
arg.IsCondition,
arg.State,
arg.FirstRaised,
arg.LastSeen,
arg.Count,
arg.ClosedBy,
arg.ClosedAt,
)
var i Alert
err := row.Scan(
&i.ID,
&i.OrgID,
&i.Kind,
&i.Subject,
&i.Severity,
&i.Title,
&i.Body,
&i.Link,
&i.IsCondition,
&i.State,
&i.FirstRaised,
&i.LastSeen,
&i.Count,
&i.ClosedBy,
&i.ClosedAt,
)
return i, err
}
@@ -44,6 +44,43 @@ type AccessPolicyVersion struct {
UpdatedAt time.Time
}
type Alert struct {
ID int64
OrgID string
Kind string
Subject string
Severity string
Title string
Body string
Link string
IsCondition bool
State string
FirstRaised time.Time
LastSeen time.Time
Count int64
ClosedBy string
ClosedAt pgtype.Timestamptz
}
type AlertDelivery struct {
ID int64
AlertID int64
Event string
State string
CreatedAt time.Time
NextAttemptAt time.Time
Attempts int64
}
type AlertDeliveryAttempt struct {
ID int64
DeliveryID int64
Attempt int64
At time.Time
StatusCode int64
Error string
}
type ApplyStatus struct {
Process string
Kind string
@@ -0,0 +1,68 @@
-- Operator alerts and their outbound deliveries (internal/domain/alert).
-- name: LockAlertKey :exec
-- Serialises raisers of one alert, so two first raises cannot both insert.
SELECT pg_advisory_xact_lock(hashtextextended(sqlc.arg(lock_key)::text, 0));
-- name: GetAlertByKey :one
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
FROM alerts WHERE org_id = $1 AND kind = $2 AND subject = $3;
-- name: GetOrgAlert :one
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
FROM alerts WHERE org_id = $1 AND id = $2;
-- name: GetAlert :one
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
FROM alerts WHERE id = $1;
-- name: UpsertAlert :one
INSERT INTO alerts (org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)
ON CONFLICT (org_id, kind, subject) DO UPDATE SET
severity = excluded.severity, title = excluded.title, body = excluded.body, link = excluded.link,
is_condition = excluded.is_condition, state = excluded.state, first_raised = excluded.first_raised,
last_seen = excluded.last_seen, count = excluded.count, closed_by = excluded.closed_by, closed_at = excluded.closed_at
RETURNING id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at;
-- name: ListAlerts :many
SELECT id, org_id, kind, subject, severity, title, body, link, is_condition, state, first_raised, last_seen, count, closed_by, closed_at
FROM alerts
WHERE org_id = $1 AND state = ANY(sqlc.arg(states)::text[])
ORDER BY CASE severity WHEN 'action' THEN 3 WHEN 'warning' THEN 2 ELSE 1 END DESC, last_seen DESC, id DESC
LIMIT sqlc.arg(page_limit);
-- name: PruneAlerts :execrows
DELETE FROM alerts WHERE state <> 'open' AND closed_at < $1;
-- name: InsertAlertDelivery :exec
INSERT INTO alert_deliveries (alert_id, event) VALUES ($1, $2);
-- name: ClaimAlertDeliveries :many
UPDATE alert_deliveries SET next_attempt_at = now() + interval '2 minutes'
WHERE id IN (
SELECT d.id FROM alert_deliveries d
WHERE d.state = 'pending' AND d.next_attempt_at <= now()
ORDER BY d.id LIMIT sqlc.arg(page_limit) FOR UPDATE SKIP LOCKED)
RETURNING id, alert_id, event, state, created_at, next_attempt_at, attempts;
-- name: LockAlertDelivery :one
SELECT id, alert_id, event, state, created_at, next_attempt_at, attempts
FROM alert_deliveries WHERE id = $1 FOR UPDATE;
-- name: SettleAlertDelivery :exec
UPDATE alert_deliveries SET state = $2, attempts = $3, next_attempt_at = $4 WHERE id = $1;
-- name: InsertAlertAttempt :exec
INSERT INTO alert_delivery_attempts (delivery_id, attempt, status_code, error) VALUES ($1, $2, $3, $4);
-- name: ListAlertDeliveries :many
SELECT id, alert_id, event, state, created_at, next_attempt_at, attempts
FROM alert_deliveries WHERE alert_id = ANY(sqlc.arg(alert_ids)::bigint[]) ORDER BY alert_id, id DESC;
-- name: ListAlertAttempts :many
SELECT id, delivery_id, attempt, at, status_code, error
FROM alert_delivery_attempts WHERE delivery_id = ANY(sqlc.arg(delivery_ids)::bigint[]) ORDER BY delivery_id, id;
-- name: TaskAlertInfo :one
SELECT org_id, title, workflow, park_class FROM tasks WHERE id = $1;
+1 -1
View File
@@ -338,7 +338,7 @@ func (s *Store) CancelExecution(ctx context.Context, taskID int64, reason, to st
if n == 0 {
return nil, storecontract.ErrStaleTransition
}
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
TaskID: taskID, FromStatus: execution.Status, ToStatus: to, Detail: clip(reason, 4000),
}); err != nil {
return nil, err
+7 -7
View File
@@ -276,7 +276,7 @@ func (s *Store) Transition(ctx context.Context, taskID int64, from, to, detail s
if n == 0 {
return storecontract.ErrStaleTransition
}
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
TaskID: taskID, FromStatus: from, ToStatus: to, Detail: clip(detail, 4000),
}); err != nil {
return err
@@ -291,7 +291,7 @@ func (s *Store) Transition(ctx context.Context, taskID int64, from, to, detail s
return err
}
if promoted > 0 {
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
TaskID: taskID, FromStatus: workflow.StatusPROpen, ToStatus: workflow.StatusQueued,
Detail: "queued the next review",
}); err != nil {
@@ -327,7 +327,7 @@ func (s *Store) ParkTask(ctx context.Context, taskID int64, from, detail, class
if n == 0 {
return storecontract.ErrStaleTransition
}
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
TaskID: taskID, FromStatus: from, ToStatus: workflow.StatusParked, Detail: clip(detail, 4000),
}); err != nil {
return err
@@ -409,7 +409,7 @@ func (s *Store) BeginRemediation(ctx context.Context, taskID int64, payload stri
if n == 0 {
return storecontract.ErrStaleTransition
}
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
TaskID: taskID, FromStatus: workflow.StatusPROpen, ToStatus: workflow.StatusQueued,
Detail: "review reaction queued remediation",
}); err != nil {
@@ -589,7 +589,7 @@ func (s *Store) RespondReviewGate(ctx context.Context, taskID int64, fromStatus,
if rereview {
detail = "operator requested a re-review"
}
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
TaskID: taskID, FromStatus: fromStatus, ToStatus: workflow.StatusQueued, Detail: detail,
}); err != nil {
return err
@@ -619,7 +619,7 @@ func (s *Store) requeue(ctx context.Context, taskID int64, fromStatus, wf, detai
if n == 0 {
return storecontract.ErrStaleTransition
}
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
TaskID: taskID, FromStatus: fromStatus, ToStatus: workflow.StatusQueued, Detail: detail,
}); err != nil {
return err
@@ -684,7 +684,7 @@ func (s *Store) RecoverStale(ctx context.Context) (int64, error) {
return 0, err
}
}
if err := q.InsertTransition(ctx, postgresdb.InsertTransitionParams{
if err := recordTransition(ctx, q, postgresdb.InsertTransitionParams{
TaskID: execution.ID, FromStatus: workflow.StatusRunning, ToStatus: workflow.StatusQueued,
Detail: "re-queued after a crashed or replaced daemon",
}); err != nil {
@@ -0,0 +1,91 @@
package postgres
import (
"context"
"errors"
"fmt"
"github.com/jackc/pgx/v5"
"github.com/samcharles93/archie-core/internal/domain/alert"
"github.com/samcharles93/archie-core/internal/domain/org"
"github.com/samcharles93/archie-core/internal/domain/workflow"
"github.com/samcharles93/archie-core/internal/infrastructure/postgres/postgresdb"
"github.com/samcharles93/archie-core/internal/taskstate"
)
// systemResolver is recorded as the resolver of an alert the store clears
// itself because the task moved on.
const systemResolver = "system"
// recordTransition writes a transition's audit row and the alerts that
// transition raises or clears, in the same transaction. Every task status
// move goes through it, so the alerts follow the state without a poller.
func recordTransition(ctx context.Context, q *postgresdb.Queries, p postgresdb.InsertTransitionParams) error {
if err := q.InsertTransition(ctx, p); err != nil {
return err
}
return syncTaskAlerts(ctx, q, p)
}
// needsHuman reports whether a task in status, parked with class, is waiting
// on an operator's decision.
func needsHuman(status, class string) bool {
return status == workflow.StatusWaitingHuman || (status == workflow.StatusParked && class == taskstate.ParkNeedsHuman)
}
// failed reports whether a task in status, parked with class, will not
// succeed without an operator starting it over.
func failed(status, class string) bool {
return status == workflow.StatusDead || (status == workflow.StatusParked && class == taskstate.ParkTerminal)
}
func syncTaskAlerts(ctx context.Context, q *postgresdb.Queries, p postgresdb.InsertTransitionParams) error {
leaving := p.FromStatus == workflow.StatusWaitingHuman || p.FromStatus == workflow.StatusParked
if !leaving && p.ToStatus != workflow.StatusWaitingHuman && p.ToStatus != workflow.StatusParked && p.ToStatus != workflow.StatusDead {
return nil
}
info, err := q.TaskAlertInfo(ctx, p.TaskID)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return err
}
subject := fmt.Sprintf("task:%d", p.TaskID)
link := fmt.Sprintf("/tasks/%d", p.TaskID)
name := fmt.Sprintf("Task #%d", p.TaskID)
described := name
if info.Title != "" {
described = fmt.Sprintf("%s %q", name, info.Title)
}
key := func(kind string) alert.Key {
return alert.Key{Org: org.OrgID(info.OrgID), Kind: kind, Subject: subject}
}
if needsHuman(p.ToStatus, info.ParkClass) {
body := described + " is waiting for your approval or review."
if p.ToStatus == workflow.StatusParked {
body = described + " is parked and needs a decision."
}
_, err := raiseAlert(ctx, q, alert.Input{
Key: key(alert.KindTaskNeedsHuman), Severity: alert.SeverityAction, Condition: true,
Title: name + " needs you", Body: body, Link: link,
})
if err != nil {
return err
}
} else if leaving {
if err := resolveAlert(ctx, q, key(alert.KindTaskNeedsHuman), systemResolver); err != nil {
return err
}
}
if failed(p.ToStatus, info.ParkClass) {
_, err := raiseAlert(ctx, q, alert.Input{
Key: key(alert.KindTaskFailed), Severity: alert.SeverityWarning,
Title: name + " failed", Body: described + " failed and will not run again until you retry it.", Link: link,
})
return err
}
return nil
}