dc39e3a5d3
First step of #1, and it goes first for one reason: #4 adds a team_id to nearly every table, and doing that twice -- once for SQLite, once for Postgres -- is work nobody gets paid for. The teams migrations now only have to be written against one database. The ten SQLite migrations are replaced by a single Postgres baseline rather than ported one by one. They were incremental in a way that has no value on a fresh install: 004 adds columns 008 drops again, and 008's backfill rewrites data a Postgres database never had. The history stays in git; the schema they add up to is now 001_baseline.sql. Timestamps stay BIGINT unix seconds and are NOT converted to timestamptz. Everything in Go already speaks epochs, so converting would have been a second, larger change riding along inside this one. It is worth doing on its own. The JSON columns did move to jsonb, because #4 will want to filter and index on labels. Most of the port is mechanical -- 170 placeholders from ? to $1 -- but four things needed more than a search and replace: * Dynamically built WHERE clauses cannot keep their numbering straight by hand, so they hand out placeholders through sqlArgs instead. A filter can now be added or reordered without renumbering anything. * SUM(resolved_at IS NULL) was SQLite counting a boolean as 0 or 1. Postgres has no sum(boolean), and this was breaking every dead man's switch -- silently, since the sweeper only logs. Now COUNT(*) FILTER. * unixepoch() became FLOOR(EXTRACT(EPOCH FROM now()))::bigint. The FLOOR is load-bearing: a bare cast rounds half up, so a row written at .6 of a second claimed a timestamp a second in the future and disagreed with the time.Now().Unix() the Go side stamps. * The unique-violation check matched SQLite's error text. It matches SQLSTATE 23505 now, so a renamed constraint cannot turn a 409 back into a 500. Tests need a real Postgres, because there is no in-memory Postgres the way there was an in-memory SQLite. Each test gets its own schema on a shared server -- cheaper than a database each, and still isolated. TERDUT_TEST_DSN says where it is; `make test-db` starts one locally and ci.yaml runs one as a service container. An unset DSN fails the suite rather than skipping it: a run that quietly tests nothing is worse than one that does not run. TestMigration_BackfillCarriesAckAndComments is deleted along with the migrations it replayed. What it protected -- an upgrade not losing acknowledgements and comments -- now belongs to scripts/sqlite-to-postgres.go, which is build-tagged so the SQLite driver stays out of the server binary. Both are meant to be deleted once this install has migrated. The chart loses the PVC, the data volume and the python backup sidecar, and requires database.dsnSecret.name: it provisions no database and cannot guess where the credentials live, so a render without it is meant to fail. Backups move to where Postgres actually runs. The other half of that -- the postgresql CR, the k8up pg_dump annotation and the network policy -- is a change to the wrapper chart in Ryuvia/charts and is not in here. Verified rather than assumed: the gate is green with -race against Postgres 17, govulncheck and gitleaks are clean, and the migration script was run end to end against a SQLite database built at the old schema and seeded in every table. Ids survive, so incidents keep their numbers and every foreign key still points where it did; the identity sequences are moved past the copied ids, and a webhook after the migration opened incident 12 rather than colliding at 1.
158 lines
4.5 KiB
Go
158 lines
4.5 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.ryuvia.com/niklas/terdut-server/internal/models"
|
|
"github.com/go-chi/chi/v5"
|
|
)
|
|
|
|
// alertSelectFrom is the shared SELECT … FROM … clause used by all alert queries.
|
|
// The subquery resolves the alert's most recent incident: membership is kept in
|
|
// incident_alerts rather than as a column here, because one alert row is reused
|
|
// across occurrences and belongs to a different incident each time.
|
|
const alertSelectFrom = `
|
|
SELECT a.id, a.fingerprint, a.name, a.status,
|
|
a.labels, a.annotations,
|
|
a.starts_at, a.ends_at, a.generator_url, a.received_at,
|
|
(SELECT ia.incident_id
|
|
FROM incident_alerts ia
|
|
JOIN incidents i ON i.id = ia.incident_id
|
|
WHERE ia.alert_id = a.id
|
|
ORDER BY i.triggered_at DESC, i.id DESC
|
|
LIMIT 1),
|
|
a.resolution_source, a.archived_at
|
|
FROM alerts a`
|
|
|
|
func handleListAlerts(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
q := r.URL.Query()
|
|
|
|
where := []string{}
|
|
args := &sqlArgs{}
|
|
|
|
if status := q.Get("status"); status != "" {
|
|
where = append(where, "a.status = "+args.add(status))
|
|
}
|
|
if name := q.Get("name"); name != "" {
|
|
where = append(where, "a.name = "+args.add(name))
|
|
}
|
|
if archived := q.Get("archived"); archived == "true" {
|
|
where = append(where, "a.archived_at IS NOT NULL")
|
|
} else {
|
|
where = append(where, "a.archived_at IS NULL")
|
|
}
|
|
if incidentID := q.Get("incident_id"); incidentID != "" {
|
|
if n, err := strconv.ParseInt(incidentID, 10, 64); err == nil {
|
|
where = append(where, "a.id IN (SELECT alert_id FROM incident_alerts WHERE incident_id = "+args.add(n)+")")
|
|
}
|
|
}
|
|
|
|
if from := q.Get("from"); from != "" {
|
|
if t, err := time.Parse("2006-01-02", from); err == nil {
|
|
where = append(where, "a.received_at >= "+args.add(t.UTC().Unix()))
|
|
}
|
|
}
|
|
if to := q.Get("to"); to != "" {
|
|
if t, err := time.Parse("2006-01-02", to); err == nil {
|
|
where = append(where, "a.received_at < "+args.add(t.UTC().AddDate(0, 0, 1).Unix()))
|
|
}
|
|
}
|
|
|
|
limit := 50
|
|
if l := q.Get("limit"); l != "" {
|
|
if n, err := strconv.Atoi(l); err == nil && n > 0 && n <= 500 {
|
|
limit = n
|
|
}
|
|
}
|
|
|
|
clause := "1=1"
|
|
if len(where) > 0 {
|
|
clause = strings.Join(where, " AND ")
|
|
}
|
|
|
|
rows, err := db.QueryContext(r.Context(),
|
|
fmt.Sprintf("%s WHERE %s ORDER BY a.received_at DESC LIMIT %s", alertSelectFrom, clause, args.add(limit)),
|
|
args.all()...)
|
|
if err != nil {
|
|
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
|
return
|
|
}
|
|
defer rows.Close()
|
|
|
|
alerts := []models.Alert{}
|
|
for rows.Next() {
|
|
a, err := scanAlert(rows)
|
|
if err != nil {
|
|
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
|
return
|
|
}
|
|
alerts = append(alerts, a)
|
|
}
|
|
respond(w, http.StatusOK, alerts)
|
|
}
|
|
}
|
|
|
|
func handleGetAlert(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
|
|
if err != nil {
|
|
respond(w, http.StatusBadRequest, errResp("invalid alert id"))
|
|
return
|
|
}
|
|
a, err := fetchAlert(r.Context(), db, id)
|
|
if err == sql.ErrNoRows {
|
|
respond(w, http.StatusNotFound, errResp("alert not found"))
|
|
return
|
|
}
|
|
if err != nil {
|
|
respond(w, http.StatusInternalServerError, errResp("internal error"))
|
|
return
|
|
}
|
|
respond(w, http.StatusOK, a)
|
|
}
|
|
}
|
|
|
|
// fetchAlert loads a single alert by ID using the shared query.
|
|
func fetchAlert(ctx context.Context, db *sql.DB, id int64) (models.Alert, error) {
|
|
return scanAlert(db.QueryRowContext(ctx, alertSelectFrom+" WHERE a.id = $1", id))
|
|
}
|
|
|
|
// scanner is satisfied by both *sql.Row and *sql.Rows.
|
|
type scanner interface {
|
|
Scan(dest ...any) error
|
|
}
|
|
|
|
func scanAlert(s scanner) (models.Alert, error) {
|
|
var a models.Alert
|
|
var labelsJSON, annotationsJSON string
|
|
var startsAtUnix, receivedAtUnix int64
|
|
var endsAtUnix, archivedAtUnix *int64
|
|
|
|
if err := s.Scan(
|
|
&a.ID, &a.Fingerprint, &a.Name, &a.Status,
|
|
&labelsJSON, &annotationsJSON,
|
|
&startsAtUnix, &endsAtUnix,
|
|
&a.GeneratorURL, &receivedAtUnix,
|
|
&a.IncidentID,
|
|
&a.ResolutionSource, &archivedAtUnix,
|
|
); err != nil {
|
|
return a, err
|
|
}
|
|
|
|
json.Unmarshal([]byte(labelsJSON), &a.Labels) //nolint:errcheck
|
|
json.Unmarshal([]byte(annotationsJSON), &a.Annotations) //nolint:errcheck
|
|
a.StartsAt = time.Unix(startsAtUnix, 0).UTC()
|
|
a.ReceivedAt = time.Unix(receivedAtUnix, 0).UTC()
|
|
a.EndsAt = unixPtr(endsAtUnix)
|
|
a.ArchivedAt = unixPtr(archivedAtUnix)
|
|
return a, nil
|
|
}
|