Files
uptimesebi/internal/api/limits.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

419 lines
12 KiB
Go

package api
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
"git.zb-server.de/ZB-Server/uptimesebi/internal/tenant"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
// Platform admins limit what organizations and accounts may create. The
// platform defaults apply to every organization without an override of its
// own, also after they change. 0 means unlimited.
const settingLimits = "limits"
// Limits are the limits in effect for an organization, or the platform
// defaults.
type Limits struct {
Monitors int `json:"monitors"`
StatusPages int `json:"status_pages"`
RegionsPerMonitor int `json:"regions_per_monitor"`
// OwnRegionsCount makes the organization's own checker regions count
// towards RegionsPerMonitor; otherwise only platform regions do.
OwnRegionsCount bool `json:"own_regions_count"`
// OrgsPerAccount limits the organizations an account owns.
OrgsPerAccount int `json:"orgs_per_account"`
}
func (s *Server) defaultLimits() Limits {
if s.cloud() {
return Limits{OrgsPerAccount: 3}
}
return Limits{}
}
// platformLimits returns the platform defaults.
func (s *Server) platformLimits(ctx context.Context) Limits {
l, err := s.limits.get(ctx, s.rdb, func(ctx context.Context) (Limits, error) {
l := s.defaultLimits()
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
raw, err := q.GetPlatformSetting(ctx, settingLimits)
if errors.Is(err, pgx.ErrNoRows) {
return nil
}
if err != nil {
return err
}
return json.Unmarshal(raw, &l)
})
return l, err
})
if err != nil {
s.log.WarnContext(ctx, "loading limits failed", "error", err)
return s.defaultLimits()
}
return l
}
// orgLimits applies org's overrides to the platform defaults.
func (s *Server) orgLimits(ctx context.Context, org store.Org) Limits {
l := s.platformLimits(ctx)
override := func(dst *int, v *int32) {
if v != nil {
*dst = int(*v)
}
}
override(&l.Monitors, org.LimitMonitors)
override(&l.StatusPages, org.LimitStatusPages)
override(&l.RegionsPerMonitor, org.LimitRegionsPerMonitor)
if org.LimitOwnRegionsCount != nil {
l.OwnRegionsCount = *org.LimitOwnRegionsCount
}
return l
}
// limitError reports a reached limit from inside a transaction.
type limitError struct {
code string
max int
}
func (e limitError) Error() string { return fmt.Sprintf("api: %s (%d)", e.code, e.max) }
// failLimit answers err if it is a limitError and reports whether it was.
func failLimit(c *gin.Context, err error) bool {
var le limitError
if errors.As(err, &le) {
fail(c, http.StatusUnprocessableEntity, le.code, "Max", le.max)
return true
}
return false
}
// reserve locks org's usage and fails if count, from countFn, has reached
// max.
func reserve(ctx context.Context, q *store.Queries, org uuid.UUID, max int, code string, countFn func(context.Context, uuid.UUID) (int64, error)) error {
if max == 0 {
return nil
}
if err := q.LockOrgUsage(ctx, org); err != nil {
return err
}
n, err := countFn(ctx, org)
if err != nil {
return err
}
if n >= int64(max) {
return limitError{code, max}
}
return nil
}
// countedRegions counts the regions that count towards the limit.
func countedRegions(l Limits, regions []uuid.UUID, platform map[uuid.UUID]bool) int {
n := 0
for _, r := range regions {
if l.OwnRegionsCount || platform[r] {
n++
}
}
return n
}
// checkRegions fails if a monitor would use more counted regions than
// allowed. A monitor already beyond a lowered limit may keep its regions
// but not add any.
func checkRegions(l Limits, regions, previous []uuid.UUID, platform map[uuid.UUID]bool) error {
n := countedRegions(l, regions, platform)
if l.RegionsPerMonitor == 0 || n <= l.RegionsPerMonitor || n <= countedRegions(l, previous, platform) {
return nil
}
if l.OwnRegionsCount {
return limitError{"region_limit", l.RegionsPerMonitor}
}
return limitError{"platform_region_limit", l.RegionsPerMonitor}
}
type usageView struct {
Limits Limits `json:"limits"`
Usage struct {
Monitors int `json:"monitors"`
StatusPages int `json:"status_pages"`
} `json:"usage"`
}
func (s *Server) orgUsage(ctx context.Context, p *principal) (usageView, error) {
v := usageView{Limits: s.orgLimits(ctx, p.Org)}
v.Limits.OrgsPerAccount = 0
err := s.db.Tx(ctx, p.scope(), func(q *store.Queries) error {
m, err := q.CountMonitors(ctx, p.Org.ID)
if err != nil {
return err
}
pg, err := q.CountStatusPages(ctx, p.Org.ID)
v.Usage.Monitors, v.Usage.StatusPages = int(m), int(pg)
return err
})
return v, err
}
func (s *Server) getOrgLimits(c *gin.Context) {
v, err := s.orgUsage(c.Request.Context(), current(c))
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, v)
}
func (s *Server) adminGetLimits(c *gin.Context) {
c.JSON(http.StatusOK, s.platformLimits(c.Request.Context()))
}
type limitsRequest struct {
Monitors int `json:"monitors" binding:"min=0,max=1000000"`
StatusPages int `json:"status_pages" binding:"min=0,max=1000000"`
RegionsPerMonitor int `json:"regions_per_monitor" binding:"min=0,max=1000"`
OwnRegionsCount bool `json:"own_regions_count"`
OrgsPerAccount int `json:"orgs_per_account" binding:"min=0,max=100000"`
}
func (s *Server) adminSetLimits(c *gin.Context) {
var req limitsRequest
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
raw, _ := json.Marshal(Limits(req))
auditDetail(c, "limits", Limits(req))
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
return q.SetPlatformSetting(ctx, store.SetPlatformSettingParams{Key: settingLimits, Value: raw})
})
if err != nil {
internalError(c, err)
return
}
if err := s.limits.bump(ctx, s.rdb); err != nil {
s.log.ErrorContext(ctx, "announcing limit change failed", "error", err)
}
c.Status(http.StatusNoContent)
}
// optBool is a JSON boolean that may be null, and also accepts "true",
// "false" and "" from forms.
type optBool struct{ v *bool }
// UnmarshalJSON implements json.Unmarshaler.
func (o *optBool) UnmarshalJSON(b []byte) error {
switch strings.Trim(string(b), `"`) {
case "null", "":
o.v = nil
case "true":
t := true
o.v = &t
case "false":
f := false
o.v = &f
default:
return errors.New("not a boolean")
}
return nil
}
// MarshalJSON implements json.Marshaler.
func (o optBool) MarshalJSON() ([]byte, error) { return json.Marshal(o.v) }
// orgLimitsRequest overrides limits for one organization; null follows the
// platform default.
type orgLimitsRequest struct {
Monitors *int32 `json:"monitors" binding:"omitempty,min=0,max=1000000"`
StatusPages *int32 `json:"status_pages" binding:"omitempty,min=0,max=1000000"`
RegionsPerMonitor *int32 `json:"regions_per_monitor" binding:"omitempty,min=0,max=1000"`
OwnRegionsCount optBool `json:"own_regions_count"`
}
func (s *Server) adminSetOrgLimits(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
var req orgLimitsRequest
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
auditDetail(c, "limits", req)
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
row, err := q.SetOrgLimits(ctx, store.SetOrgLimitsParams{
ID: id, Monitors: req.Monitors, StatusPages: req.StatusPages,
RegionsPerMonitor: req.RegionsPerMonitor, OwnRegionsCount: req.OwnRegionsCount.v,
})
auditDetail(c, "slug", row.Slug)
return err
})
if moderated(c, err) {
c.Status(http.StatusNoContent)
}
}
type userLimitsRequest struct {
// Orgs limits the organizations the account owns; null follows the
// platform default.
Orgs *int32 `json:"orgs" binding:"omitempty,min=0,max=100000"`
}
func (s *Server) adminSetUserLimits(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
fail(c, http.StatusNotFound, "not_found")
return
}
var req userLimitsRequest
if !bind(c, &req) {
return
}
ctx := c.Request.Context()
auditDetail(c, "orgs", req.Orgs)
err = s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
row, err := q.SetUserOrgLimit(ctx, store.SetUserOrgLimitParams{ID: id, Orgs: req.Orgs})
auditDetail(c, "email", row.Email)
return err
})
if moderated(c, err) {
c.Status(http.StatusNoContent)
}
}
// adminOrg is an organization in the admin list.
type adminOrg struct {
moderatedOrg
Created string `json:"created_at"`
Overrides orgLimitsView `json:"overrides"`
Limits Limits `json:"limits"`
Usage struct {
Monitors int `json:"monitors"`
StatusPages int `json:"status_pages"`
} `json:"usage"`
Owner *adminOwner `json:"owner"`
}
type orgLimitsView struct {
Monitors *int32 `json:"monitors"`
StatusPages *int32 `json:"status_pages"`
RegionsPerMonitor *int32 `json:"regions_per_monitor"`
OwnRegionsCount *bool `json:"own_regions_count"`
}
type adminOwner struct {
moderatedUser
// OrgLimit overrides the organizations the account may own.
OrgLimit *int32 `json:"org_limit"`
Orgs int `json:"orgs"`
}
func (s *Server) adminOrgs(ctx context.Context, search string, pg pageReq) ([]adminOrg, pageInfo, error) {
var rows []store.AdminListOrgsRow
err := s.db.Tx(ctx, tenant.System(), func(q *store.Queries) error {
var err error
rows, err = q.AdminListOrgs(ctx, store.AdminListOrgsParams{
Search: truncate(strings.TrimSpace(search), 200), MaxRows: pg.fetch(),
AfterT: pg.afterT(), AfterID: pg.afterID(), BeforeT: pg.beforeT(), BeforeID: pg.beforeID(),
})
return err
})
rows, info := paginate(pg, rows, func(r store.AdminListOrgsRow) cursor { return cursor{T: r.CreatedAt, ID: r.ID} })
defaults := s.platformLimits(ctx)
out := make([]adminOrg, len(rows))
for i, r := range rows {
o := &out[i]
o.moderatedOrg = moderatedOrg{r.ID, r.Slug, r.Name, r.SuspendedAt, r.SuspendedReason}
o.Created = r.CreatedAt.Format("2006-01-02")
o.Overrides = orgLimitsView{r.LimitMonitors, r.LimitStatusPages, r.LimitRegionsPerMonitor, r.LimitOwnRegionsCount}
o.Limits = s.orgLimits(ctx, store.Org{LimitMonitors: r.LimitMonitors, LimitStatusPages: r.LimitStatusPages,
LimitRegionsPerMonitor: r.LimitRegionsPerMonitor, LimitOwnRegionsCount: r.LimitOwnRegionsCount})
o.Limits.OrgsPerAccount = defaults.OrgsPerAccount
o.Usage.Monitors, o.Usage.StatusPages = int(r.Monitors), int(r.StatusPages)
if r.OwnerID != uuid.Nil {
o.Owner = &adminOwner{
moderatedUser: moderatedUser{r.OwnerID, r.OwnerEmail, r.OwnerDisabledAt, r.OwnerDisabledReason, r.OwnerIsAdmin},
OrgLimit: r.OwnerLimitOrgs, Orgs: int(r.OwnerOrgs),
}
if r.OwnerLimitOrgs != nil {
o.Limits.OrgsPerAccount = int(*r.OwnerLimitOrgs)
}
}
}
return out, info, err
}
func (s *Server) adminListOrgs(c *gin.Context) {
pg, ok := parsePage(c, apiPageSize)
if !ok {
return
}
orgs, info, err := s.adminOrgs(c.Request.Context(), c.Query("q"), pg)
if err != nil {
internalError(c, err)
return
}
c.JSON(http.StatusOK, gin.H{"orgs": orgs, "next_cursor": info.Next, "prev_cursor": info.Prev})
}
func webLimits(l Limits) web.LimitsView { return web.LimitsView(l) }
func optInt(v *int32) string {
if v == nil {
return ""
}
return strconv.Itoa(int(*v))
}
func (s *Server) orgsView(c *gin.Context, pg pageReq) (web.OrgsView, error) {
ctx := c.Request.Context()
orgs, info, err := s.adminOrgs(ctx, c.Query("q"), pg)
v := web.OrgsView{
Search: strings.TrimSpace(c.Query("q")), Pager: pager(c, info), Next: c.Request.URL.RequestURI(),
Defaults: webLimits(s.platformLimits(ctx)),
}
state := func(at *time.Time, reason string) string {
switch {
case at == nil:
return ""
case reason == "":
return "-"
}
return reason
}
for _, o := range orgs {
row := web.OrgRow{
ID: o.ID.String(), Name: o.Name, Slug: o.Slug, Created: o.Created, Suspended: state(o.SuspendedAt, o.Reason),
Monitors: o.Usage.Monitors, StatusPages: o.Usage.StatusPages, Limits: webLimits(o.Limits),
MonitorsOverride: optInt(o.Overrides.Monitors), StatusPagesOverride: optInt(o.Overrides.StatusPages),
RegionsOverride: optInt(o.Overrides.RegionsPerMonitor),
}
if o.Overrides.OwnRegionsCount != nil {
row.OwnRegionsOverride = strconv.FormatBool(*o.Overrides.OwnRegionsCount)
}
if o.Owner != nil {
row.Owner = &web.ModeratedTarget{ID: o.Owner.ID.String(), Name: o.Owner.Email, Suspended: state(o.Owner.SuspendedAt, o.Owner.Reason), Admin: o.Owner.Admin}
row.OwnerOrgs, row.OwnerOrgLimit = o.Owner.Orgs, optInt(o.Owner.OrgLimit)
}
v.Orgs = append(v.Orgs, row)
}
return v, err
}