feat: page long and truncated lists
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

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
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-22 21:40:25 +01:00
1 parent 98fb5d3a82
commit d7c5cd711e
63 files changed
+5427 -3041

No files matched your search

+218
View File
@@ -0,0 +1,218 @@
package api
import (
"encoding/base64"
"encoding/json"
"net/http"
"slices"
"strconv"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"git.zb-server.de/ZB-Server/uptimesebi/internal/web"
)
// Lists are paged by keyset: a cursor holds the sort key of an item and
// its ID, so pages neither skip nor repeat items when others are added.
// after pages forward in the list's order, before backward.
const (
apiPageSize = 100
maxPageSize = 500
consolePageSize = 50
)
// cursor is the position of an item: a time or string sort key and a
// tie-breaking ID.
type cursor struct {
T time.Time `json:"t,omitzero"`
S string `json:"s,omitempty"`
ID uuid.UUID `json:"i,omitzero"`
}
func (c cursor) encode() string {
b, _ := json.Marshal(c)
return base64.RawURLEncoding.EncodeToString(b)
}
func decodeCursor(s string) (*cursor, bool) {
if s == "" {
return nil, true
}
b, err := base64.RawURLEncoding.DecodeString(s)
var c cursor
if err != nil || json.Unmarshal(b, &c) != nil {
return nil, false
}
return &c, true
}
// pageReq is a requested page.
type pageReq struct {
after, before *cursor
limit int
}
// backward reports whether the page is read against the list's order.
func (p pageReq) backward() bool { return p.before != nil }
// fetch is how many rows to read: one more tells whether more follow.
func (p pageReq) fetch() int32 { return int32(p.limit + 1) }
// at is the cursor to read from, in reading direction.
func (p pageReq) at() *cursor {
if p.before != nil {
return p.before
}
return p.after
}
// Keys of the cursor for queries; nil when not paging from a position.
func (p pageReq) afterT() *time.Time { return timeOf(p.after) }
func (p pageReq) beforeT() *time.Time { return timeOf(p.before) }
func (p pageReq) afterS() *string { return strOf(p.after) }
func (p pageReq) beforeS() *string { return strOf(p.before) }
func (p pageReq) afterID() *uuid.UUID { return idOf(p.after) }
func (p pageReq) beforeID() *uuid.UUID { return idOf(p.before) }
func timeOf(c *cursor) *time.Time {
if c == nil {
return nil
}
return &c.T
}
func strOf(c *cursor) *string {
if c == nil {
return nil
}
return &c.S
}
func idOf(c *cursor) *uuid.UUID {
if c == nil {
return nil
}
return &c.ID
}
// parsePage reads after, before and limit, answering 422 when invalid.
func parsePage(c *gin.Context, def int) (pageReq, bool) {
p := pageReq{limit: def}
if l := c.Query("limit"); l != "" {
n, err := strconv.Atoi(l)
if err != nil || n < 1 || n > maxPageSize {
fail(c, http.StatusUnprocessableEntity, "invalid_limit", "Max", maxPageSize)
return p, false
}
p.limit = n
}
var okA, okB bool
p.after, okA = decodeCursor(c.Query("after"))
p.before, okB = decodeCursor(c.Query("before"))
if !okA || !okB || p.after != nil && p.before != nil {
fail(c, http.StatusUnprocessableEntity, "invalid_cursor")
return p, false
}
return p, true
}
// pageInfo holds the cursors of the neighbouring pages, empty at either
// end of the list.
type pageInfo struct {
Next string `json:"next_cursor,omitempty"`
Prev string `json:"prev_cursor,omitempty"`
}
// paginate trims rows read for p to one page in the list's order and
// works out the neighbouring pages.
func paginate[T any](p pageReq, rows []T, key func(T) cursor) ([]T, pageInfo) {
var info pageInfo
more := len(rows) > p.limit
if more {
rows = rows[:p.limit]
}
if p.backward() {
slices.Reverse(rows)
}
if len(rows) == 0 {
return rows, info
}
first, last := key(rows[0]).encode(), key(rows[len(rows)-1]).encode()
switch {
case p.backward():
info.Next = last
if more {
info.Prev = first
}
default:
if more {
info.Next = last
}
if p.after != nil {
info.Prev = first
}
}
return rows, info
}
// pager builds the console's page links from info, keeping the request's
// other query parameters.
func pager(c *gin.Context, info pageInfo) web.Pager {
link := func(key, cur string) string {
q := c.Request.URL.Query()
q.Del("after")
q.Del("before")
if key != "" {
q.Set(key, cur)
}
if len(q) == 0 {
return c.Request.URL.Path
}
return c.Request.URL.Path + "?" + q.Encode()
}
var pg web.Pager
if info.Next != "" {
pg.Next = link("after", info.Next)
}
if info.Prev != "" {
pg.Prev = link("before", info.Prev)
pg.First = link("", "")
}
return pg
}
// pageSlice pages through items held in memory the way the queries page
// through tables. items must be sorted ascending by key.
func pageSlice[T any](items []T, pg pageReq, key func(T) cursor) ([]T, pageInfo) {
cmp := func(a, b cursor) int {
if c := strings.Compare(a.S, b.S); c != 0 {
return c
}
if c := a.T.Compare(b.T); c != 0 {
return c
}
return strings.Compare(a.ID.String(), b.ID.String())
}
var read []T
if pg.backward() {
for i := len(items) - 1; i >= 0 && len(read) < int(pg.fetch()); i-- {
if cmp(key(items[i]), *pg.before) < 0 {
read = append(read, items[i])
}
}
} else {
for _, it := range items {
if len(read) == int(pg.fetch()) {
break
}
if pg.after == nil || cmp(key(it), *pg.after) > 0 {
read = append(read, it)
}
}
}
return paginate(pg, read, key)
}