// Package pagination implements keyset paging. A cursor is opaque to the // client and bound to the resource it pages (the chat for history, the user // for the chat list), so a cursor from one resource is rejected on another. // Because ids are UUIDv7 and creation time derives from the id, the keyset // (created_at, id) collapses to the id of the last returned item. package pagination import ( "encoding/base64" "errors" "strconv" "github.com/google/uuid" ) const ( DefaultLimit = 50 MaxLimit = 100 ) var ( ErrInvalidCursor = errors.New("invalid cursor") ErrInvalidLimit = errors.New("limit must be an integer between 1 and 100") ) const cursorVersion = 1 func EncodeCursor(scope, last uuid.UUID) string { raw := make([]byte, 0, 1+16+16) raw = append(raw, cursorVersion) raw = append(raw, scope[:]...) raw = append(raw, last[:]...) return base64.RawURLEncoding.EncodeToString(raw) } func DecodeCursor(token string, scope uuid.UUID) (uuid.UUID, error) { raw, err := base64.RawURLEncoding.DecodeString(token) if err != nil || len(raw) != 1+16+16 || raw[0] != cursorVersion { return uuid.Nil, ErrInvalidCursor } if got, err := uuid.FromBytes(raw[1:17]); err != nil || got != scope { return uuid.Nil, ErrInvalidCursor } last, err := uuid.FromBytes(raw[17:]) if err != nil { return uuid.Nil, ErrInvalidCursor } return last, nil } // ParseLimit accepts an unsigned decimal between 1 and MaxLimit; an empty // value means DefaultLimit. ParseUint rejects signs, whitespace and // fractions and reports overflow, so no length guard is needed. func ParseLimit(raw string) (int, error) { if raw == "" { return DefaultLimit, nil } n, err := strconv.ParseUint(raw, 10, 32) if err != nil || n < 1 || n > MaxLimit { return 0, ErrInvalidLimit } return int(n), nil }