forked from mtusi2026/mtusi2026lab2
feat(app) lab2 prepared for mr
This commit is contained in:
@@ -4,6 +4,7 @@ import (
|
||||
"errors"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/gofiber/fiber/v3/middleware/requestid"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -80,6 +81,16 @@ func Internal() *AppError {
|
||||
return NewAppError(fiber.StatusInternalServerError, ErrorCodeInternal, "Internal server error")
|
||||
}
|
||||
|
||||
func Unavailable(message string) *AppError {
|
||||
return NewAppError(fiber.StatusServiceUnavailable, ErrorCodeUnavailable, message)
|
||||
}
|
||||
|
||||
// IsCode reports whether err is an AppError with the given contract code.
|
||||
func IsCode(err error, code string) bool {
|
||||
var appErr *AppError
|
||||
return errors.As(err, &appErr) && appErr.Code == code
|
||||
}
|
||||
|
||||
func ErrorCodeFromStatus(status int) string {
|
||||
switch status {
|
||||
case fiber.StatusBadRequest:
|
||||
@@ -104,7 +115,10 @@ func ErrorCodeFromStatus(status int) string {
|
||||
}
|
||||
|
||||
func getRequestID(c fiber.Ctx) string {
|
||||
return string(c.Response().Header.Peek("X-Request-Id"))
|
||||
if id := string(c.Response().Header.Peek("X-Request-Id")); id != "" {
|
||||
return id
|
||||
}
|
||||
return requestid.FromContext(c)
|
||||
}
|
||||
|
||||
func SendError(c fiber.Ctx, status int, code, message string) error {
|
||||
@@ -120,3 +134,10 @@ func SendAppError(c fiber.Ctx, err error) error {
|
||||
return SendError(c, fiber.StatusInternalServerError,
|
||||
ErrorCodeInternal, "Internal server error")
|
||||
}
|
||||
|
||||
// SendChallenge emits a 401 with the WWW-Authenticate value required by the
|
||||
// contract: Basic for login, Bearer for every protected endpoint.
|
||||
func SendChallenge(c fiber.Ctx, challenge, message string) error {
|
||||
c.Set(fiber.HeaderWWWAuthenticate, challenge)
|
||||
return SendError(c, fiber.StatusUnauthorized, ErrorCodeUnauthorized, message)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestCursorRoundTrip(t *testing.T) {
|
||||
want := CursorKeyCtx{
|
||||
Time: time.Date(2026, 10, 20, 12, 30, 45, 123456789, time.UTC),
|
||||
ID: uuid.MustParse("11111111-1111-4111-8111-111111111111"),
|
||||
ContextID: uuid.MustParse("22222222-2222-4222-8222-222222222222"),
|
||||
}
|
||||
|
||||
encoded := EncodeCursor(want)
|
||||
got, ok := DecodeCursor(encoded)
|
||||
if !ok {
|
||||
t.Fatal("cursor did not decode")
|
||||
}
|
||||
if !got.Time.Equal(want.Time) || got.ID != want.ID || got.ContextID != want.ContextID {
|
||||
t.Fatalf("cursor round trip changed the key: %+v", got)
|
||||
}
|
||||
|
||||
for _, invalid := range []string{"not-base64!", "", "aGVsbG8"} {
|
||||
if _, ok := DecodeCursor(invalid); ok {
|
||||
t.Fatalf("invalid cursor %q was accepted", invalid)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatePasswordRange(t *testing.T) {
|
||||
cases := []struct {
|
||||
password string
|
||||
valid bool
|
||||
}{
|
||||
{"short", false},
|
||||
{"12345678901", false},
|
||||
{"123456789012", true},
|
||||
{"пароль-из-двенадцати", true},
|
||||
{"😀", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := ValidatePassword(tc.password) == ""; got != tc.valid {
|
||||
t.Fatalf("ValidatePassword(%q) valid=%v, want %v", tc.password, got, tc.valid)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -34,7 +34,7 @@ func BindJSON(c fiber.Ctx, req any) error {
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := decoder.Decode(req); err != nil {
|
||||
return BadRequest(err.Error())
|
||||
return BadRequest("invalid JSON body")
|
||||
}
|
||||
|
||||
var extra json.RawMessage
|
||||
@@ -43,7 +43,7 @@ func BindJSON(c fiber.Ctx, req any) error {
|
||||
}
|
||||
|
||||
if err := validate.Struct(req); err != nil {
|
||||
return BadRequest("field validation failed: " + err.Error())
|
||||
return BadRequest("field validation failed")
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -74,6 +74,17 @@ func ValidateCreateUser(username, displayName string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// ValidatePassword enforces the contract range in Unicode code points. The
|
||||
// upper bound matters: bcrypt would silently truncate, which is why this
|
||||
// project uses Argon2id instead.
|
||||
func ValidatePassword(password string) string {
|
||||
if !strLenBetween(password, 12, 128) {
|
||||
return "password must be between 12 and 128 Unicode code points"
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
func ValidateChatTitle(title string) string {
|
||||
if blank(title) {
|
||||
return "title must not be empty or only whitespace"
|
||||
|
||||
Reference in New Issue
Block a user