Files
archie/internal/domain/audit/cursor.go
T

84 lines
2.4 KiB
Go

package audit
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/samcharles93/archie-core/internal/domain/storecontract"
)
// The cursor is a fixed-width sort key so a cursor string sorts like the row
// order it names: the at layout, the fixed origin rank, the zero-padded row
// id. The filter hash follows as an opaque suffix and binds the cursor to the
// filter that produced it.
const (
cursorSeparator = "|"
cursorRankWidth = 2
cursorIDWidth = 20
cursorParts = 4
)
// Cursor is a keyset resume point: the last entry a page returned. Only the
// fields are compared by the read model; the encoded string is opaque to
// every client.
type Cursor struct {
At time.Time
Rank int
ID int64
FilterHash string
}
// IsZero reports whether the cursor names no position, which means "newest".
func (c Cursor) IsZero() bool {
return c.At.IsZero() && c.Rank == 0 && c.ID == 0
}
// Encode returns the opaque cursor a response carries.
func (c Cursor) Encode() string {
return c.At.UTC().Format(storecontract.EventCursorLayout) + cursorSeparator +
fmt.Sprintf("%0*d", cursorRankWidth, c.Rank) + cursorSeparator +
fmt.Sprintf("%0*d", cursorIDWidth, c.ID) + cursorSeparator + c.FilterHash
}
// ParseCursor splits an opaque cursor. ok is false for a malformed cursor,
// which means "newest": a bad resume point is not worth failing a feed over.
func ParseCursor(raw string) (Cursor, bool) {
parts := strings.Split(raw, cursorSeparator)
if len(parts) != cursorParts || parts[3] == "" {
return Cursor{}, false
}
at, err := time.Parse(storecontract.EventCursorLayout, parts[0])
if err != nil {
return Cursor{}, false
}
rank, err := strconv.Atoi(parts[1])
if err != nil || rank < 0 {
return Cursor{}, false
}
id, err := strconv.ParseInt(parts[2], 10, 64)
if err != nil || id < 0 {
return Cursor{}, false
}
return Cursor{At: at, Rank: rank, ID: id, FilterHash: parts[3]}, true
}
// MatchesFilter reports whether the cursor was issued for f. A cursor reused
// with other filters is refused rather than silently resuming elsewhere.
func (c Cursor) MatchesFilter(f Filter) bool {
return c.FilterHash == f.Hash()
}
// After reports whether c is newer than other in the feed's descending order
// (at, rank, id), which is the order the cursor resumes.
func (c Cursor) After(other Cursor) bool {
if !c.At.Equal(other.At) {
return c.At.After(other.At)
}
if c.Rank != other.Rank {
return c.Rank > other.Rank
}
return c.ID > other.ID
}