A storm of alerts used to mean opening every incident to acknowledge it. The queue now has a checkbox per row and a bar to acknowledge, snooze or assign everything ticked, with an Undo on the confirmation. On the server this is one POST per action under /api/incidents (acknowledge, unacknowledge, snooze, unsnooze, assign), each taking up to 100 ids and answering per id: ok, noop, conflict (resolved) or not_found (missing, or not in the caller's teams, which look the same on purpose). Partial success rather than all-or-nothing, since one resolved incident in a selection should not block the other nine. Each incident runs in its own transaction, row-locked, so the update, the escalation stop and the timeline event land together and carry the same actor as the single-incident endpoints. Those are unchanged; only the snooze time parsing moved into a helper both now use. Resolve is left out of bulk deliberately: it is terminal, and a mis-ticked row is hard to take back. Undoing a bulk assign restores the previous assignee but cannot unassign, as no endpoint does that. The snooze and assign sheets moved to js/pickers.js so the incident page and the queue share them.
287 lines
8.4 KiB
Go
287 lines
8.4 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"net/http"
|
|
"time"
|
|
|
|
"git.ryuvia.com/niklas/terdut-server/internal/models"
|
|
)
|
|
|
|
// maxBulkIncidents caps how many incidents one bulk request may name. It keeps a
|
|
// request to one short burst of small transactions.
|
|
const maxBulkIncidents = 100
|
|
|
|
// Per-incident outcomes of a bulk action.
|
|
const (
|
|
bulkOK = "ok" // the action changed the incident
|
|
bulkNoop = "noop" // the incident was already in the wanted state
|
|
bulkNotFound = "not_found" // no such incident, or not one of the caller's teams
|
|
bulkConflict = "conflict" // the incident is resolved, which is terminal
|
|
)
|
|
|
|
type bulkResult struct {
|
|
ID int64 `json:"id"`
|
|
Status string `json:"status"`
|
|
Incident *models.Incident `json:"incident,omitempty"`
|
|
}
|
|
|
|
type bulkResponse struct {
|
|
Results []bulkResult `json:"results"`
|
|
Summary map[string]int `json:"summary"`
|
|
}
|
|
|
|
// bulkAction applies one change to one open incident inside the caller's
|
|
// transaction and reports bulkOK or bulkNoop.
|
|
type bulkAction func(ctx context.Context, tx querier, id int64) (string, error)
|
|
|
|
// bulkIDs reads and validates the {"ids": [...]} part of a request, dropping
|
|
// duplicates but keeping the caller's order. It answers 400 itself.
|
|
func bulkIDs(w http.ResponseWriter, ids []int64) ([]int64, bool) {
|
|
if len(ids) == 0 {
|
|
respond(w, http.StatusBadRequest, errResp("ids is required"))
|
|
return nil, false
|
|
}
|
|
if len(ids) > maxBulkIncidents {
|
|
respond(w, http.StatusBadRequest, errResp("too many ids (max 100)"))
|
|
return nil, false
|
|
}
|
|
seen := make(map[int64]bool, len(ids))
|
|
out := make([]int64, 0, len(ids))
|
|
for _, id := range ids {
|
|
if id <= 0 {
|
|
respond(w, http.StatusBadRequest, errResp("invalid incident id"))
|
|
return nil, false
|
|
}
|
|
if !seen[id] {
|
|
seen[id] = true
|
|
out = append(out, id)
|
|
}
|
|
}
|
|
return out, true
|
|
}
|
|
|
|
// runBulk applies act to every id. Each incident gets its own transaction, so
|
|
// the change, the escalation stop and the timeline event land together, while
|
|
// one incident that cannot take the action does not hold up the others.
|
|
//
|
|
// The scoping is the same as incidentIDParam's: an incident outside the caller's
|
|
// teams is reported exactly like a missing one.
|
|
func runBulk(w http.ResponseWriter, r *http.Request, db *sql.DB, ids []int64, act bulkAction) {
|
|
ctx := r.Context()
|
|
teams := callerTeamIDs(ctx)
|
|
resp := bulkResponse{
|
|
Results: make([]bulkResult, 0, len(ids)),
|
|
Summary: map[string]int{bulkOK: 0, bulkNoop: 0, bulkNotFound: 0, bulkConflict: 0},
|
|
}
|
|
for _, id := range ids {
|
|
status, err := bulkOne(ctx, db, teams, id, act)
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
res := bulkResult{ID: id, Status: status}
|
|
if status == bulkOK || status == bulkNoop {
|
|
inc, err := fetchIncident(ctx, db, id)
|
|
if err != nil {
|
|
serverError(w, r, err)
|
|
return
|
|
}
|
|
res.Incident = &inc
|
|
}
|
|
resp.Results = append(resp.Results, res)
|
|
resp.Summary[status]++
|
|
}
|
|
respond(w, http.StatusOK, resp)
|
|
}
|
|
|
|
func bulkOne(ctx context.Context, db *sql.DB, teams []int64, id int64, act bulkAction) (string, error) {
|
|
tx, err := db.BeginTx(ctx, nil)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
defer tx.Rollback() //nolint:errcheck
|
|
|
|
// FOR UPDATE so a concurrent resolve cannot slip between this check and the
|
|
// change.
|
|
var resolved bool
|
|
err = tx.QueryRowContext(ctx,
|
|
"SELECT resolved_at IS NOT NULL FROM incidents WHERE id = $1 AND team_id = ANY($2) FOR UPDATE",
|
|
id, teams).Scan(&resolved)
|
|
if err == sql.ErrNoRows {
|
|
return bulkNotFound, nil
|
|
}
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
if resolved {
|
|
return bulkConflict, nil
|
|
}
|
|
status, err := act(ctx, tx, id)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return status, tx.Commit()
|
|
}
|
|
|
|
// execBulk runs a guarded UPDATE: no rows matched means the guard (already in
|
|
// the wanted state) held, which is a no-op rather than a failure.
|
|
func execBulk(ctx context.Context, tx querier, query string, args ...any) (bool, error) {
|
|
res, err := tx.ExecContext(ctx, query, args...)
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
n, _ := res.RowsAffected()
|
|
return n > 0, nil
|
|
}
|
|
|
|
func bulkStatus(changed bool) string {
|
|
if changed {
|
|
return bulkOK
|
|
}
|
|
return bulkNoop
|
|
}
|
|
|
|
func handleBulkAcknowledge(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
IDs []int64 `json:"ids"`
|
|
}
|
|
if err := decodeJSON(r, &req); err != nil {
|
|
respond(w, http.StatusBadRequest, errResp("invalid request body"))
|
|
return
|
|
}
|
|
ids, ok := bulkIDs(w, req.IDs)
|
|
if !ok {
|
|
return
|
|
}
|
|
userID, saID := callerActorIDs(r.Context())
|
|
runBulk(w, r, db, ids, func(ctx context.Context, tx querier, id int64) (string, error) {
|
|
changed, err := acknowledgeIncidentAs(ctx, tx, id, userID, saID)
|
|
return bulkStatus(changed), err
|
|
})
|
|
}
|
|
}
|
|
|
|
func handleBulkUnacknowledge(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
IDs []int64 `json:"ids"`
|
|
}
|
|
if err := decodeJSON(r, &req); err != nil {
|
|
respond(w, http.StatusBadRequest, errResp("invalid request body"))
|
|
return
|
|
}
|
|
ids, ok := bulkIDs(w, req.IDs)
|
|
if !ok {
|
|
return
|
|
}
|
|
userID, saID := callerActorIDs(r.Context())
|
|
runBulk(w, r, db, ids, func(ctx context.Context, tx querier, id int64) (string, error) {
|
|
changed, err := execBulk(ctx, tx,
|
|
`UPDATE incidents SET status = 'triggered', acknowledged_by = NULL,
|
|
acknowledged_by_service_account_id = NULL, acknowledged_at = NULL
|
|
WHERE id = $1 AND resolved_at IS NULL AND status = 'acknowledged'`, id)
|
|
if err != nil || !changed {
|
|
return bulkNoop, err
|
|
}
|
|
return bulkOK, logEvent(ctx, tx, id, evUnacknowledged, userID, saID, nil, nil)
|
|
})
|
|
}
|
|
}
|
|
|
|
func handleBulkSnooze(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
IDs []int64 `json:"ids"`
|
|
Until string `json:"until"`
|
|
Duration string `json:"duration"`
|
|
}
|
|
if err := decodeJSON(r, &req); err != nil {
|
|
respond(w, http.StatusBadRequest, errResp("invalid request body"))
|
|
return
|
|
}
|
|
ids, ok := bulkIDs(w, req.IDs)
|
|
if !ok {
|
|
return
|
|
}
|
|
until, msg := parseSnoozeUntil(req.Until, req.Duration)
|
|
if msg != "" {
|
|
respond(w, http.StatusBadRequest, errResp(msg))
|
|
return
|
|
}
|
|
userID, saID := callerActorIDs(r.Context())
|
|
detail := until.UTC().Format(time.RFC3339)
|
|
runBulk(w, r, db, ids, func(ctx context.Context, tx querier, id int64) (string, error) {
|
|
if _, err := tx.ExecContext(ctx,
|
|
"UPDATE incidents SET snoozed_until = $1 WHERE id = $2", until.Unix(), id); err != nil {
|
|
return "", err
|
|
}
|
|
return bulkOK, logEvent(ctx, tx, id, evSnoozed, userID, saID, nil, &detail)
|
|
})
|
|
}
|
|
}
|
|
|
|
func handleBulkUnsnooze(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
IDs []int64 `json:"ids"`
|
|
}
|
|
if err := decodeJSON(r, &req); err != nil {
|
|
respond(w, http.StatusBadRequest, errResp("invalid request body"))
|
|
return
|
|
}
|
|
ids, ok := bulkIDs(w, req.IDs)
|
|
if !ok {
|
|
return
|
|
}
|
|
userID, saID := callerActorIDs(r.Context())
|
|
runBulk(w, r, db, ids, func(ctx context.Context, tx querier, id int64) (string, error) {
|
|
changed, err := execBulk(ctx, tx,
|
|
"UPDATE incidents SET snoozed_until = NULL WHERE id = $1 AND snoozed_until IS NOT NULL", id)
|
|
if err != nil || !changed {
|
|
return bulkNoop, err
|
|
}
|
|
return bulkOK, logEvent(ctx, tx, id, evUnsnoozed, userID, saID, nil, nil)
|
|
})
|
|
}
|
|
}
|
|
|
|
func handleBulkAssign(db *sql.DB) http.HandlerFunc {
|
|
return func(w http.ResponseWriter, r *http.Request) {
|
|
var req struct {
|
|
IDs []int64 `json:"ids"`
|
|
UserID int64 `json:"user_id"`
|
|
}
|
|
if err := decodeJSON(r, &req); err != nil {
|
|
respond(w, http.StatusBadRequest, errResp("invalid request body"))
|
|
return
|
|
}
|
|
ids, ok := bulkIDs(w, req.IDs)
|
|
if !ok {
|
|
return
|
|
}
|
|
if req.UserID == 0 {
|
|
respond(w, http.StatusBadRequest, errResp("user_id is required"))
|
|
return
|
|
}
|
|
var exists int
|
|
if err := db.QueryRowContext(r.Context(),
|
|
"SELECT 1 FROM users WHERE id = $1", req.UserID).Scan(&exists); err != nil {
|
|
respond(w, http.StatusNotFound, errResp("user not found"))
|
|
return
|
|
}
|
|
actorUserID, actorSAID := callerActorIDs(r.Context())
|
|
runBulk(w, r, db, ids, func(ctx context.Context, tx querier, id int64) (string, error) {
|
|
changed, err := execBulk(ctx, tx,
|
|
"UPDATE incidents SET assigned_to = $1 WHERE id = $2 AND assigned_to IS DISTINCT FROM $1",
|
|
req.UserID, id)
|
|
if err != nil || !changed {
|
|
return bulkNoop, err
|
|
}
|
|
return bulkOK, logAssignedEvent(ctx, tx, id, req.UserID, actorUserID, actorSAID)
|
|
})
|
|
}
|
|
}
|