Files
uptimesebi/internal/api/channels.go
Sebastian UnterschützandClaude Opus 5.5 d7c5cd711e
ci / image (pull_request) Successful in 3m18s
ci / build (pull_request) Successful in 8m38s
ci / test (pull_request) Successful in 12m6s
ci / lint (pull_request) Successful in 15m0s
feat: page long and truncated lists
Lists that were cut off by a fixed LIMIT, or could grow without bound,
are paged by keyset: the cursor holds the sort key and an ID, so pages
neither skip nor repeat items as others are added. The audit logs had a
timestamp-only cursor that could skip entries with equal times.

The API returns at most 100 items per list (limit takes up to 500) with
next_cursor and prev_cursor, passed back as after and before. The
console shows Newer/Older (or Previous/Next) links and To the start,
without JavaScript.

Paged: incidents (optionally of one monitor), a monitor's results and
evidence, a checker's results, the audit logs, members, maintenance
windows, firing Alertmanager alerts, the monitors API and the admin
lists of status pages and organizations, which move to their own admin
pages. A monitor's page shows its latest incidents and results and links
to all of them. The dashboard caps every group at 50 of its own monitors
with a link to a paged view of the group, and gains a search by name or
target. Lists filtered by permission after reading may show fewer items
on a page.

Closes #116

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
2026-11-22 21:40:25 +01:00

344 lines
9.7 KiB
Go

package api
import (
"context"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"net/http"
"net/mail"
"net/url"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/notify"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
)
type channelRequest struct {
Name string `json:"name" binding:"required,max=100"`
Type string `json:"type" binding:"required,max=32"`
URL string `json:"url" binding:"max=2000"`
To []string `json:"to" binding:"max=20,dive,max=320"`
Locale string `json:"locale" binding:"max=10"`
Enabled *bool `json:"enabled"`
// Settings configure the other channel types, as listed by
// notify.Providers; secret settings left empty keep their value.
Settings map[string]string `json:"settings" binding:"max=20"`
}
type channelView struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Type string `json:"type"`
Enabled bool `json:"enabled"`
URL string `json:"url,omitempty"`
To []string `json:"to,omitempty"`
Locale string `json:"locale,omitempty"`
// Settings and SecretsSet describe other channel types; secret values
// are never returned.
Settings map[string]string `json:"settings,omitempty"`
SecretsSet []string `json:"secrets_set,omitempty"`
}
func viewChannel(ch store.NotificationChannel) channelView {
v := channelView{ID: ch.ID, Name: ch.Name, Type: ch.Type, Enabled: ch.Enabled}
switch ch.Type {
case "webhook":
var c webhookConfig
_ = json.Unmarshal(ch.Config, &c)
v.URL = c.URL
case "email":
var c emailConfig
_ = json.Unmarshal(ch.Config, &c)
v.To, v.Locale = c.To, c.Locale
default:
v.Settings, v.SecretsSet, v.Locale = providerView(ch.Config)
}
return v
}
// channelConfig validates req and builds the stored config. For webhooks a
// new signing secret is created unless previous holds one for the same URL;
// the plain secret is returned only when it is new.
func (s *Server) channelConfig(req *channelRequest, previous []byte) (config []byte, newSecret, code string) {
req.Name = strings.TrimSpace(req.Name)
if req.Name == "" {
return nil, "", "invalid_input"
}
switch req.Type {
case "webhook":
u, err := url.Parse(strings.TrimSpace(req.URL))
if err != nil || u.Host == "" || u.User != nil || (u.Scheme != "https" && (s.cloud() || u.Scheme != "http")) {
return nil, "", "invalid_webhook_url"
}
req.URL = u.String()
var secret []byte
if previous != nil {
var old webhookConfig
if json.Unmarshal(previous, &old) == nil {
if sealedOld, err := base64.StdEncoding.DecodeString(old.Secret); err == nil {
secret, _ = s.keys.Open(sealedOld, []byte(old.URL))
}
}
}
if secret == nil {
b := make([]byte, 32)
_, _ = rand.Read(b)
secret = []byte(hex.EncodeToString(b))
newSecret = string(secret)
}
// The secret is bound to the URL so a copied config row cannot be
// pointed at another receiver with the same secret.
sealedSecret := s.keys.Seal(secret, []byte(req.URL))
config, _ = json.Marshal(webhookConfig{URL: req.URL, Secret: base64.StdEncoding.EncodeToString(sealedSecret)})
return config, newSecret, ""
case "email":
if s.smtp == nil {
return nil, "", "email_not_configured"
}
if len(req.To) == 0 {
return nil, "", "invalid_email"
}
for i, to := range req.To {
to = normalizeEmail(to)
if a, err := mail.ParseAddress(to); err != nil || a.Address != to {
return nil, "", "invalid_email"
}
req.To[i] = to
}
if req.Locale == "" || !s.catalog.IsSupported(req.Locale) {
req.Locale = "en"
}
config, _ = json.Marshal(emailConfig{To: req.To, Locale: req.Locale})
return config, "", ""
}
if p, ok := notify.Lookup(req.Type); ok {
config, code = s.providerSettings(p, req, previous)
return config, "", code
}
return nil, "", "invalid_input"
}
func (s *Server) listChannels(c *gin.Context) {
p := current(c)
ctx := c.Request.Context()
var rows []store.NotificationChannel
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
rows, err = q.ListChannels(ctx)
return err
})
if err != nil {
internalError(c, err)
return
}
out := make([]channelView, len(rows))
for i, r := range rows {
out[i] = viewChannel(r)
}
c.JSON(http.StatusOK, gin.H{"channels": out, "email_available": s.smtp != nil})
}
func (s *Server) createChannel(c *gin.Context) {
var req channelRequest
if !bind(c, &req) {
return
}
config, secret, code := s.channelConfig(&req, nil)
if code != "" {
fail(c, http.StatusUnprocessableEntity, code)
return
}
p := current(c)
ctx := c.Request.Context()
var row store.NotificationChannel
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
row, err = q.CreateChannel(ctx, store.CreateChannelParams{
OrgID: p.Org.ID, Name: req.Name, Type: req.Type, Config: config, Enabled: req.Enabled == nil || *req.Enabled,
})
return err
})
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusCreated, gin.H{"channel": viewChannel(row), "signing_secret": secret})
}
func (s *Server) updateChannel(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
var req channelRequest
if !bind(c, &req) {
return
}
p := current(c)
ctx := c.Request.Context()
var (
row store.NotificationChannel
secret string
code string
)
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
old, err := q.GetChannel(ctx, id)
if err != nil {
return err
}
if old.Type != req.Type {
code = "channel_type_immutable"
return nil
}
var config []byte
config, secret, code = s.channelConfig(&req, old.Config)
if code != "" {
return nil
}
row, err = q.UpdateChannel(ctx, store.UpdateChannelParams{ID: id, Name: req.Name, Config: config, Enabled: req.Enabled == nil || *req.Enabled})
return err
})
switch {
case errors.Is(err, pgx.ErrNoRows):
fail(c, http.StatusNotFound, "not_found")
case err != nil:
internalError(c, err)
case code != "":
fail(c, http.StatusUnprocessableEntity, code)
default:
c.JSON(http.StatusOK, gin.H{"channel": viewChannel(row), "signing_secret": secret})
}
}
func (s *Server) deleteChannel(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
p := current(c)
ctx := c.Request.Context()
var n int64
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
n, err = q.DeleteChannel(ctx, id)
return err
})
if err != nil {
internalError(c, err)
return
}
if n == 0 {
fail(c, http.StatusNotFound, "not_found")
return
}
c.Status(http.StatusNoContent)
}
// testChannel sends a sample event right away so users can verify their
// receiver; the error is returned to the user.
func (s *Server) testChannel(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
p := current(c)
ctx := c.Request.Context()
if !s.limit(c, "channel_test:"+id.String(), 10, time.Minute) {
return
}
var ch store.NotificationChannel
err = s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
ch, err = q.GetChannel(ctx, id)
return err
})
if errors.Is(err, pgx.ErrNoRows) {
fail(c, http.StatusNotFound, "not_found")
return
}
if err != nil {
internalError(c, err)
return
}
ev := notify.Event{
Kind: notify.Test, IncidentID: uuid.Nil, StartedAt: time.Now(),
Monitor: notify.Monitor{Name: "Example monitor", Type: "http", Target: "https://example.com"},
}
if err := s.send(ctx, ch.Type, ch.Config, ev); err != nil {
c.AbortWithStatusJSON(http.StatusBadGateway, gin.H{
"error": "channel_test_failed", "message": truncateValid(err.Error(), 300),
})
return
}
c.Status(http.StatusNoContent)
}
type incidentView struct {
ID uuid.UUID `json:"id"`
MonitorID uuid.UUID `json:"monitor_id"`
MonitorName string `json:"monitor_name"`
StartedAt time.Time `json:"started_at"`
ResolvedAt *time.Time `json:"resolved_at"`
Cause map[string]string `json:"cause"`
}
// incidentPage reads a page of incidents, newest first, of one monitor
// if monitor is set.
func (s *Server) incidentPage(ctx context.Context, p *principal, pg pageReq, monitor *uuid.UUID) ([]store.ListIncidentsRow, pageInfo, error) {
var rows []store.ListIncidentsRow
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
var err error
rows, err = q.ListIncidents(ctx, store.ListIncidentsParams{
MonitorID: monitor, AfterT: pg.afterT(), AfterID: pg.afterID(), BeforeT: pg.beforeT(), BeforeID: pg.beforeID(), MaxRows: pg.fetch(),
})
return err
})
rows, info := paginate(pg, rows, func(r store.ListIncidentsRow) cursor { return cursor{T: r.StartedAt, ID: r.ID} })
return rows, info, err
}
// monitorFilter reads the optional monitor query parameter.
func monitorFilter(c *gin.Context, name string) (*uuid.UUID, bool) {
raw := c.Query(name)
if raw == "" {
return nil, true
}
id, err := uuid.Parse(raw)
if err != nil {
fail(c, http.StatusUnprocessableEntity, "invalid_input")
return nil, false
}
return &id, true
}
func (s *Server) listIncidents(c *gin.Context) {
pg, ok := parsePage(c, apiPageSize)
if !ok {
return
}
monitor, ok := monitorFilter(c, "monitor_id")
if !ok {
return
}
rows, info, err := s.incidentPage(c.Request.Context(), current(c), pg, monitor)
if err != nil {
internalError(c, err)
return
}
out := make([]incidentView, len(rows))
for i, r := range rows {
out[i] = incidentView{ID: r.ID, MonitorID: r.MonitorID, MonitorName: r.MonitorName, StartedAt: r.StartedAt, ResolvedAt: r.ResolvedAt}
_ = json.Unmarshal(r.Cause, &out[i].Cause)
}
c.JSON(http.StatusOK, gin.H{"incidents": out, "next_cursor": info.Next, "prev_cursor": info.Prev})
}