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) }