forked from mtusi2026/mtusi2026lab2
feat(app) lab2 prepared for mr
This commit is contained in:
@@ -2,7 +2,7 @@ package common
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -10,189 +10,99 @@ import (
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// CursorKeyCtx is the opaque keyset position: (created_at, id) plus the
|
||||
// resource/user the cursor belongs to. ContextID stops a cursor from one chat
|
||||
// or user list being replayed against another.
|
||||
type CursorKeyCtx struct {
|
||||
Time time.Time
|
||||
ID uuid.UUID
|
||||
ContextID uuid.UUID
|
||||
}
|
||||
|
||||
type cursorKey struct {
|
||||
time time.Time
|
||||
id uuid.UUID
|
||||
}
|
||||
|
||||
type CreatedAtIDable interface {
|
||||
GetCreatedAt() time.Time
|
||||
GetID() uuid.UUID
|
||||
}
|
||||
|
||||
type PaginatedResponse[T any] struct {
|
||||
type Page[T any] struct {
|
||||
Items []T `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func ParseLimit(c fiber.Ctx, defaultLimit int) (int, error) {
|
||||
limitStr, exists := c.Queries()["limit"]
|
||||
|
||||
if limitStr == "" {
|
||||
if !exists {
|
||||
return defaultLimit, nil
|
||||
}
|
||||
|
||||
if !exists {
|
||||
return defaultLimit, nil
|
||||
}
|
||||
if strings.TrimSpace(limitStr) == "" {
|
||||
return 0, BadRequest("limit param declared but empty")
|
||||
}
|
||||
|
||||
limit, ok := validateLimitStr(limitStr)
|
||||
if !ok {
|
||||
limit, err := strconv.Atoi(limitStr)
|
||||
if err != nil || limit < 1 || limit > 100 {
|
||||
return 0, BadRequest("limit must be an integer between 1 and 100")
|
||||
}
|
||||
|
||||
return limit, nil
|
||||
}
|
||||
|
||||
func ParseCursor(c fiber.Ctx) (*CursorKeyCtx, error) {
|
||||
cursorStr, exists := c.Queries()["cursor"]
|
||||
|
||||
if cursorStr == "" {
|
||||
if !exists {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
if !exists {
|
||||
return nil, nil
|
||||
}
|
||||
if strings.TrimSpace(cursorStr) == "" {
|
||||
return nil, BadRequest("cursor param declared but empty")
|
||||
}
|
||||
|
||||
cursor := DecodeCursor(cursorStr)
|
||||
if cursor == nil {
|
||||
cursor, ok := DecodeCursor(cursorStr)
|
||||
if !ok {
|
||||
return nil, BadRequest("invalid cursor format")
|
||||
}
|
||||
|
||||
return cursor, nil
|
||||
}
|
||||
|
||||
func Paginate[T CreatedAtIDable](
|
||||
items []T,
|
||||
limit int,
|
||||
cursor *CursorKeyCtx,
|
||||
contextID uuid.UUID,
|
||||
) (*PaginatedResponse[T], error) {
|
||||
enforceOrder(items)
|
||||
|
||||
start := 0
|
||||
|
||||
if cursor != nil {
|
||||
key := cursorKey{time: cursor.Time, id: cursor.ID}
|
||||
position, found := findAfter(items, key)
|
||||
|
||||
if !found {
|
||||
return nil, BadRequest("cursor invalid")
|
||||
}
|
||||
|
||||
if position == -1 {
|
||||
position = len(items)
|
||||
}
|
||||
|
||||
start = position
|
||||
}
|
||||
|
||||
end := start + limit
|
||||
if end > len(items) {
|
||||
end = len(items)
|
||||
}
|
||||
|
||||
page := items[start:end]
|
||||
if page == nil {
|
||||
page = []T{}
|
||||
}
|
||||
|
||||
var nextCursor *string
|
||||
if end < len(items) {
|
||||
last := items[end-1]
|
||||
encoded := encodeCursor(CursorKeyCtx{
|
||||
Time: last.GetCreatedAt(),
|
||||
ID: last.GetID(),
|
||||
ContextID: contextID,
|
||||
})
|
||||
nextCursor = &encoded
|
||||
}
|
||||
|
||||
return &PaginatedResponse[T]{
|
||||
Items: page,
|
||||
NextCursor: nextCursor,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func encodeCursor(key CursorKeyCtx) string {
|
||||
timeStr := key.Time.UTC().Format(time.RFC3339Nano)
|
||||
raw := timeStr + "|" + key.ID.String() + "|" + key.ContextID.String()
|
||||
func EncodeCursor(key CursorKeyCtx) string {
|
||||
raw := key.Time.UTC().Format(time.RFC3339Nano) + "|" + key.ID.String() + "|" + key.ContextID.String()
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
func DecodeCursor(cursor string) *CursorKeyCtx {
|
||||
func DecodeCursor(cursor string) (*CursorKeyCtx, bool) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return nil
|
||||
return nil, false
|
||||
}
|
||||
|
||||
parts := strings.SplitN(string(data), "|", 3)
|
||||
if len(parts) != 3 {
|
||||
return nil
|
||||
return nil, false
|
||||
}
|
||||
|
||||
parsedTime, err := time.Parse(time.RFC3339Nano, parts[0])
|
||||
if err != nil {
|
||||
return nil
|
||||
return nil, false
|
||||
}
|
||||
|
||||
parsedID, err := uuid.Parse(parts[1])
|
||||
if err != nil {
|
||||
return nil
|
||||
return nil, false
|
||||
}
|
||||
|
||||
parsedContextID, err := uuid.Parse(parts[2])
|
||||
parsedContext, err := uuid.Parse(parts[2])
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
return &CursorKeyCtx{Time: parsedTime, ID: parsedID, ContextID: parsedContext}, true
|
||||
}
|
||||
|
||||
// NextCursor returns a cursor pointing at the last item of a page when more
|
||||
// rows exist. limit+1 rows are fetched by the store, so a non-nil cursor means
|
||||
// the next page is known to be non-empty at read time.
|
||||
func NextCursor[T interface {
|
||||
GetID() uuid.UUID
|
||||
GetCreatedAt() time.Time
|
||||
}](items []T, hasMore bool, contextID uuid.UUID) *string {
|
||||
if !hasMore || len(items) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
return &CursorKeyCtx{
|
||||
Time: parsedTime,
|
||||
ID: parsedID,
|
||||
ContextID: parsedContextID,
|
||||
}
|
||||
}
|
||||
|
||||
func findAfter[T CreatedAtIDable](items []T, key cursorKey) (position int, keyFound bool) {
|
||||
for i, item := range items {
|
||||
itemKey := keyOf(item)
|
||||
|
||||
if itemKey == key {
|
||||
keyFound = true
|
||||
}
|
||||
|
||||
if after(itemKey, key) {
|
||||
return i, true
|
||||
}
|
||||
}
|
||||
|
||||
return -1, keyFound
|
||||
}
|
||||
|
||||
func keyOf(item CreatedAtIDable) cursorKey {
|
||||
return cursorKey{
|
||||
time: item.GetCreatedAt(),
|
||||
id: item.GetID(),
|
||||
}
|
||||
}
|
||||
|
||||
func after(a, b cursorKey) bool {
|
||||
if !a.time.Equal(b.time) {
|
||||
return a.time.After(b.time)
|
||||
}
|
||||
|
||||
return a.id.String() > b.id.String()
|
||||
}
|
||||
|
||||
func enforceOrder[T CreatedAtIDable](items []T) {
|
||||
sort.Slice(items, func(i, j int) bool {
|
||||
return after(keyOf(items[j]), keyOf(items[i]))
|
||||
last := items[len(items)-1]
|
||||
encoded := EncodeCursor(CursorKeyCtx{
|
||||
Time: last.GetCreatedAt(),
|
||||
ID: last.GetID(),
|
||||
ContextID: contextID,
|
||||
})
|
||||
return &encoded
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user