Перенесите реализацию ЛР 4 на стенд ЛР 5
This commit is contained in:
@@ -0,0 +1,63 @@
|
||||
// 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
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package pagination_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"messenger/internal/platform/ident"
|
||||
"messenger/internal/platform/pagination"
|
||||
)
|
||||
|
||||
func TestCursorRoundTrip(t *testing.T) {
|
||||
scope, last := ident.New(), ident.New()
|
||||
encoded := pagination.EncodeCursor(scope, last)
|
||||
if encoded == "" || strings.ContainsAny(encoded, "+/=") {
|
||||
t.Fatalf("cursor must be non-empty URL-safe base64 without padding, got %q", encoded)
|
||||
}
|
||||
got, err := pagination.DecodeCursor(encoded, scope)
|
||||
if err != nil {
|
||||
t.Fatalf("DecodeCursor error: %v", err)
|
||||
}
|
||||
if got != last {
|
||||
t.Fatalf("decoded %s, want %s", got, last)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeCursorRejectsForeignScope(t *testing.T) {
|
||||
encoded := pagination.EncodeCursor(ident.New(), ident.New())
|
||||
_, err := pagination.DecodeCursor(encoded, ident.New())
|
||||
if !errors.Is(err, pagination.ErrInvalidCursor) {
|
||||
t.Fatalf("err = %v, want ErrInvalidCursor", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeCursorRejectsGarbage(t *testing.T) {
|
||||
scope := ident.New()
|
||||
valid := pagination.EncodeCursor(scope, ident.New())
|
||||
for _, raw := range []string{"", "***", "abc", valid[:len(valid)-2], valid + "AA", strings.ToUpper(valid)} {
|
||||
if _, err := pagination.DecodeCursor(raw, scope); !errors.Is(err, pagination.ErrInvalidCursor) {
|
||||
t.Errorf("DecodeCursor(%q) err = %v, want ErrInvalidCursor", raw, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseLimit(t *testing.T) {
|
||||
cases := []struct {
|
||||
raw string
|
||||
want int
|
||||
ok bool
|
||||
}{
|
||||
{"", 50, true},
|
||||
{"1", 1, true},
|
||||
{"100", 100, true},
|
||||
{"0", 0, false},
|
||||
{"101", 0, false},
|
||||
{"-1", 0, false},
|
||||
{"+5", 0, false},
|
||||
{"5.0", 0, false},
|
||||
{"abc", 0, false},
|
||||
{" 5", 0, false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
got, err := pagination.ParseLimit(tc.raw)
|
||||
if tc.ok && (err != nil || got != tc.want) {
|
||||
t.Errorf("ParseLimit(%q) = %d, %v; want %d", tc.raw, got, err, tc.want)
|
||||
}
|
||||
if !tc.ok && !errors.Is(err, pagination.ErrInvalidLimit) {
|
||||
t.Errorf("ParseLimit(%q) err = %v, want ErrInvalidLimit", tc.raw, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package pagination
|
||||
|
||||
import "github.com/google/uuid"
|
||||
|
||||
// Page is the service-level page: the items and the id to continue from,
|
||||
// nil when the listing is exhausted. It carries the raw keyset id so that any
|
||||
// transport can encode the continuation its own way.
|
||||
type Page[T any] struct {
|
||||
Items []T
|
||||
Next *uuid.UUID
|
||||
}
|
||||
|
||||
// PageResponse is the wire form of a page with the continuation already
|
||||
// encoded as an opaque cursor.
|
||||
type PageResponse[T any] struct {
|
||||
Items []T `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
// Cut turns a slice over-fetched by one item into a page of at most limit
|
||||
// items; the extra item only proves that a next page exists.
|
||||
func Cut[T any](items []T, limit int, id func(T) uuid.UUID) Page[T] {
|
||||
if len(items) <= limit {
|
||||
return Page[T]{Items: items}
|
||||
}
|
||||
items = items[:limit]
|
||||
next := id(items[limit-1])
|
||||
return Page[T]{Items: items, Next: &next}
|
||||
}
|
||||
|
||||
func ToResponse[D, R any](p Page[D], scope uuid.UUID, convert func(D) R) PageResponse[R] {
|
||||
out := PageResponse[R]{Items: make([]R, 0, len(p.Items))}
|
||||
for _, item := range p.Items {
|
||||
out.Items = append(out.Items, convert(item))
|
||||
}
|
||||
if p.Next != nil {
|
||||
cursor := EncodeCursor(scope, *p.Next)
|
||||
out.NextCursor = &cursor
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package pagination_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/platform/ident"
|
||||
"messenger/internal/platform/pagination"
|
||||
)
|
||||
|
||||
func self(id uuid.UUID) uuid.UUID { return id }
|
||||
|
||||
func TestCutTrimsOverfetchAndDerivesNext(t *testing.T) {
|
||||
ids := []uuid.UUID{ident.New(), ident.New(), ident.New()}
|
||||
|
||||
fewer := pagination.Cut(ids[:2], 5, self)
|
||||
if len(fewer.Items) != 2 || fewer.Next != nil {
|
||||
t.Fatalf("fewer than limit: %+v", fewer)
|
||||
}
|
||||
exact := pagination.Cut(ids[:2], 2, self)
|
||||
if len(exact.Items) != 2 || exact.Next != nil {
|
||||
t.Fatalf("exactly limit must not continue: %+v", exact)
|
||||
}
|
||||
over := pagination.Cut(ids, 2, self)
|
||||
if len(over.Items) != 2 || over.Next == nil || *over.Next != ids[1] {
|
||||
t.Fatalf("over-fetched page must trim and continue from the last kept id: %+v", over)
|
||||
}
|
||||
if over.Items[0] != ids[0] || over.Items[1] != ids[1] {
|
||||
t.Fatalf("order changed: %v", over.Items)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToResponseEncodesCursorWithinScope(t *testing.T) {
|
||||
scope, last := ident.New(), ident.New()
|
||||
page := pagination.Page[uuid.UUID]{Items: []uuid.UUID{last}, Next: &last}
|
||||
res := pagination.ToResponse(page, scope, func(id uuid.UUID) string { return id.String() })
|
||||
if len(res.Items) != 1 || res.Items[0] != last.String() {
|
||||
t.Fatalf("items = %v", res.Items)
|
||||
}
|
||||
if res.NextCursor == nil {
|
||||
t.Fatal("next cursor missing")
|
||||
}
|
||||
got, err := pagination.DecodeCursor(*res.NextCursor, scope)
|
||||
if err != nil || got != last {
|
||||
t.Fatalf("cursor decodes to %s, %v; want %s", got, err, last)
|
||||
}
|
||||
}
|
||||
|
||||
func TestToResponseSerializesEmptyPageAsContractRequires(t *testing.T) {
|
||||
res := pagination.ToResponse(pagination.Page[uuid.UUID]{}, ident.New(), func(id uuid.UUID) string { return id.String() })
|
||||
raw, err := json.Marshal(res)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(raw) != `{"items":[],"next_cursor":null}` {
|
||||
t.Fatalf("empty page = %s", raw)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user