Перенести решение лабораторной 1 как основу для лабораторной 2
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
// Package apperr is the application's error vocabulary: every module reports
|
||||
// failures as a Kind plus a message that is safe to show to clients, and the
|
||||
// transport layer owns the only mapping from Kind to HTTP status. Causes are
|
||||
// kept for logs but never rendered.
|
||||
package apperr
|
||||
|
||||
import "errors"
|
||||
|
||||
type Kind int
|
||||
|
||||
const (
|
||||
KindInternal Kind = iota
|
||||
KindInvalid
|
||||
KindUnauthorized
|
||||
KindNotFound
|
||||
KindConflict
|
||||
KindPayloadTooLarge
|
||||
KindUnsupportedMedia
|
||||
KindUnavailable
|
||||
)
|
||||
|
||||
type Error struct {
|
||||
Kind Kind
|
||||
Message string
|
||||
Cause error
|
||||
}
|
||||
|
||||
func (e *Error) Error() string { return e.Message }
|
||||
|
||||
func (e *Error) Unwrap() error { return e.Cause }
|
||||
|
||||
func New(kind Kind, message string) *Error {
|
||||
return &Error{Kind: kind, Message: message}
|
||||
}
|
||||
|
||||
func Wrap(kind Kind, message string, cause error) *Error {
|
||||
return &Error{Kind: kind, Message: message, Cause: cause}
|
||||
}
|
||||
|
||||
// KindOf classifies any error; foreign errors are internal.
|
||||
func KindOf(err error) Kind {
|
||||
if e, ok := errors.AsType[*Error](err); ok {
|
||||
return e.Kind
|
||||
}
|
||||
return KindInternal
|
||||
}
|
||||
|
||||
func Invalid(message string) *Error { return New(KindInvalid, message) }
|
||||
func Unauthorized(message string) *Error { return New(KindUnauthorized, message) }
|
||||
func NotFound(message string) *Error { return New(KindNotFound, message) }
|
||||
func Conflict(message string) *Error { return New(KindConflict, message) }
|
||||
func PayloadTooLarge(message string) *Error { return New(KindPayloadTooLarge, message) }
|
||||
func UnsupportedMedia(message string) *Error { return New(KindUnsupportedMedia, message) }
|
||||
func Unavailable(message string) *Error { return New(KindUnavailable, message) }
|
||||
@@ -0,0 +1,49 @@
|
||||
package apperr_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
)
|
||||
|
||||
func TestKindOfReturnsKindForApplicationError(t *testing.T) {
|
||||
err := apperr.NotFound("chat not found")
|
||||
if got := apperr.KindOf(err); got != apperr.KindNotFound {
|
||||
t.Fatalf("KindOf = %v, want KindNotFound", got)
|
||||
}
|
||||
if err.Error() != "chat not found" {
|
||||
t.Fatalf("Error() = %q", err.Error())
|
||||
}
|
||||
}
|
||||
|
||||
func TestKindOfSeesThroughWrapping(t *testing.T) {
|
||||
err := fmt.Errorf("service: %w", apperr.Conflict("username taken"))
|
||||
if got := apperr.KindOf(err); got != apperr.KindConflict {
|
||||
t.Fatalf("KindOf = %v, want KindConflict", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestKindOfDefaultsToInternal(t *testing.T) {
|
||||
if got := apperr.KindOf(errors.New("boom")); got != apperr.KindInternal {
|
||||
t.Fatalf("KindOf = %v, want KindInternal", got)
|
||||
}
|
||||
if got := apperr.KindOf(nil); got != apperr.KindInternal {
|
||||
t.Fatalf("KindOf(nil) = %v, want KindInternal", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWrapKeepsCause(t *testing.T) {
|
||||
cause := errors.New("cause")
|
||||
err := apperr.Wrap(apperr.KindInvalid, "bad input", cause)
|
||||
if !errors.Is(err, cause) {
|
||||
t.Fatal("wrapped error must unwrap to cause")
|
||||
}
|
||||
if apperr.KindOf(err) != apperr.KindInvalid {
|
||||
t.Fatal("wrapped error must keep its kind")
|
||||
}
|
||||
if err.Error() != "bad input" {
|
||||
t.Fatalf("Error() = %q, want public message only", err.Error())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Package config reads the process configuration from the environment.
|
||||
// Every setting has a default suited to the lab stand; an invalid value stops
|
||||
// the process at start-up with a message naming the variable.
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Host string
|
||||
Port int
|
||||
Env string
|
||||
LogLevel slog.Level
|
||||
ShutdownTimeout time.Duration
|
||||
MaxBodyBytes int64
|
||||
}
|
||||
|
||||
// Lookup reads one variable, reporting whether it was set; os.LookupEnv
|
||||
// in production, a map in tests.
|
||||
type Lookup func(key string) (string, bool)
|
||||
|
||||
func Load(lookup Lookup) (Config, error) {
|
||||
cfg := Config{
|
||||
Host: "0.0.0.0",
|
||||
Port: 8080,
|
||||
Env: "lab",
|
||||
LogLevel: slog.LevelInfo,
|
||||
ShutdownTimeout: 8 * time.Second,
|
||||
MaxBodyBytes: 64 * 1024,
|
||||
}
|
||||
if v, ok := lookup("APP_HOST"); ok {
|
||||
if strings.TrimSpace(v) == "" {
|
||||
return Config{}, fmt.Errorf("APP_HOST must not be empty")
|
||||
}
|
||||
cfg.Host = v
|
||||
}
|
||||
if v, ok := lookup("APP_PORT"); ok {
|
||||
port, err := strconv.Atoi(v)
|
||||
if err != nil || port < 1 || port > 65535 {
|
||||
return Config{}, fmt.Errorf("APP_PORT must be an integer between 1 and 65535, got %q", v)
|
||||
}
|
||||
cfg.Port = port
|
||||
}
|
||||
if v, ok := lookup("APP_ENV"); ok && strings.TrimSpace(v) != "" {
|
||||
cfg.Env = v
|
||||
}
|
||||
if v, ok := lookup("APP_LOG_LEVEL"); ok {
|
||||
var level slog.Level
|
||||
if err := level.UnmarshalText([]byte(v)); err != nil {
|
||||
return Config{}, fmt.Errorf("APP_LOG_LEVEL must be debug, info, warn or error, got %q", v)
|
||||
}
|
||||
cfg.LogLevel = level
|
||||
}
|
||||
if v, ok := lookup("APP_SHUTDOWN_TIMEOUT"); ok {
|
||||
d, err := time.ParseDuration(v)
|
||||
if err != nil || d <= 0 {
|
||||
return Config{}, fmt.Errorf("APP_SHUTDOWN_TIMEOUT must be a positive duration such as 8s, got %q", v)
|
||||
}
|
||||
cfg.ShutdownTimeout = d
|
||||
}
|
||||
if v, ok := lookup("APP_MAX_BODY_BYTES"); ok {
|
||||
n, err := strconv.ParseInt(v, 10, 64)
|
||||
if err != nil || n <= 0 {
|
||||
return Config{}, fmt.Errorf("APP_MAX_BODY_BYTES must be a positive integer, got %q", v)
|
||||
}
|
||||
cfg.MaxBodyBytes = n
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (c Config) Addr() string {
|
||||
return net.JoinHostPort(c.Host, strconv.Itoa(c.Port))
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package config_test
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/internal/platform/config"
|
||||
)
|
||||
|
||||
func env(values map[string]string) func(string) (string, bool) {
|
||||
return func(key string) (string, bool) {
|
||||
v, ok := values[key]
|
||||
return v, ok
|
||||
}
|
||||
}
|
||||
|
||||
func TestDefaults(t *testing.T) {
|
||||
cfg, err := config.Load(env(nil))
|
||||
if err != nil {
|
||||
t.Fatalf("Load error: %v", err)
|
||||
}
|
||||
if cfg.Addr() != "0.0.0.0:8080" {
|
||||
t.Fatalf("Addr = %q", cfg.Addr())
|
||||
}
|
||||
if cfg.Env != "lab" || cfg.LogLevel != slog.LevelInfo {
|
||||
t.Fatalf("cfg = %+v", cfg)
|
||||
}
|
||||
if cfg.ShutdownTimeout != 8*time.Second || cfg.MaxBodyBytes != 65536 {
|
||||
t.Fatalf("cfg = %+v", cfg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestOverrides(t *testing.T) {
|
||||
cfg, err := config.Load(env(map[string]string{
|
||||
"APP_HOST": "127.0.0.1",
|
||||
"APP_PORT": "9090",
|
||||
"APP_ENV": "dev",
|
||||
"APP_LOG_LEVEL": "debug",
|
||||
"APP_SHUTDOWN_TIMEOUT": "3s",
|
||||
"APP_MAX_BODY_BYTES": "1024",
|
||||
}))
|
||||
if err != nil {
|
||||
t.Fatalf("Load error: %v", err)
|
||||
}
|
||||
if cfg.Addr() != "127.0.0.1:9090" || cfg.Env != "dev" || cfg.LogLevel != slog.LevelDebug {
|
||||
t.Fatalf("cfg = %+v", cfg)
|
||||
}
|
||||
if cfg.ShutdownTimeout != 3*time.Second || cfg.MaxBodyBytes != 1024 {
|
||||
t.Fatalf("cfg = %+v", cfg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidValuesAreReported(t *testing.T) {
|
||||
cases := map[string]map[string]string{
|
||||
"port text": {"APP_PORT": "abc"},
|
||||
"port zero": {"APP_PORT": "0"},
|
||||
"port too big": {"APP_PORT": "70000"},
|
||||
"level": {"APP_LOG_LEVEL": "loud"},
|
||||
"timeout": {"APP_SHUTDOWN_TIMEOUT": "soon"},
|
||||
"timeout negative": {"APP_SHUTDOWN_TIMEOUT": "-1s"},
|
||||
"body zero": {"APP_MAX_BODY_BYTES": "0"},
|
||||
"body text": {"APP_MAX_BODY_BYTES": "big"},
|
||||
"empty host": {"APP_HOST": ""},
|
||||
}
|
||||
for name, values := range cases {
|
||||
if _, err := config.Load(env(values)); err == nil {
|
||||
t.Errorf("%s: want error", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
)
|
||||
|
||||
// DecodeJSON reads exactly one JSON object into dst and enforces what gin's
|
||||
// binding does not: the media type must be application/json (415), invalid
|
||||
// UTF-8, unknown fields, wrong types, malformed syntax and trailing data are
|
||||
// 400, an oversized body is 413, and messages never expose Go type names.
|
||||
func DecodeJSON(c *gin.Context, dst any) error {
|
||||
mediaType, _, err := mime.ParseMediaType(c.GetHeader("Content-Type"))
|
||||
if err != nil || mediaType != "application/json" {
|
||||
return apperr.UnsupportedMedia("Content-Type must be application/json")
|
||||
}
|
||||
// The body is already capped by the bodyLimit middleware, so reading it
|
||||
// whole is bounded.
|
||||
body, err := io.ReadAll(c.Request.Body)
|
||||
if err != nil {
|
||||
return decodeError(err)
|
||||
}
|
||||
// encoding/json silently replaces invalid UTF-8 with U+FFFD; the contract
|
||||
// and RFC 8259 require UTF-8, so such a body is rejected, not repaired.
|
||||
if !utf8.Valid(body) {
|
||||
return apperr.Invalid("request body must be valid UTF-8")
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
return decodeError(err)
|
||||
}
|
||||
if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
|
||||
return apperr.Invalid("unexpected data after JSON body")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func decodeError(err error) error {
|
||||
if tooLarge, ok := errors.AsType[*http.MaxBytesError](err); ok {
|
||||
return apperr.Wrap(apperr.KindPayloadTooLarge, fmt.Sprintf("request body must be at most %d bytes", tooLarge.Limit), err)
|
||||
}
|
||||
if errors.Is(err, io.EOF) {
|
||||
return apperr.Wrap(apperr.KindInvalid, "request body is required", err)
|
||||
}
|
||||
if wrongType, ok := errors.AsType[*json.UnmarshalTypeError](err); ok {
|
||||
if wrongType.Field == "" {
|
||||
return apperr.Wrap(apperr.KindInvalid, "request body must be a JSON object", err)
|
||||
}
|
||||
return apperr.Wrap(apperr.KindInvalid, fmt.Sprintf("field %q has wrong type", wrongType.Field), err)
|
||||
}
|
||||
// encoding/json reports unknown fields as a plain error without a type.
|
||||
const unknownPrefix = "json: unknown field "
|
||||
if msg := err.Error(); strings.HasPrefix(msg, unknownPrefix) {
|
||||
field := strings.Trim(strings.TrimPrefix(msg, unknownPrefix), `"`)
|
||||
return apperr.Wrap(apperr.KindInvalid, fmt.Sprintf("unknown field %q", field), err)
|
||||
}
|
||||
return apperr.Wrap(apperr.KindInvalid, "malformed JSON body", err)
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// Package httpx is the transport layer over gin: request ids, access
|
||||
// logging, panic recovery, body limits, strict JSON decoding and the single
|
||||
// error format of the API contract. gin is used for routing and the
|
||||
// middleware chain; everything here exists because the contract demands a
|
||||
// specific behaviour that gin's own helpers do not provide.
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
)
|
||||
|
||||
const (
|
||||
keyRequestID = "messenger.request_id"
|
||||
keyLogger = "messenger.logger"
|
||||
)
|
||||
|
||||
// NewEngine builds an engine whose every response, including routing
|
||||
// failures and panics, carries X-Request-Id and the contract error body.
|
||||
func NewEngine(log *slog.Logger, maxBodyBytes int64) *gin.Engine {
|
||||
gin.SetMode(gin.ReleaseMode)
|
||||
e := gin.New()
|
||||
// Redirects would answer with text/plain and without a request id.
|
||||
e.RedirectTrailingSlash = false
|
||||
e.RedirectFixedPath = false
|
||||
e.HandleMethodNotAllowed = true
|
||||
|
||||
e.Use(requestID(log), accessLog(), recovery(), bodyLimit(maxBodyBytes))
|
||||
e.NoRoute(func(c *gin.Context) { Error(c, apperr.NotFound("route not found")) })
|
||||
e.NoMethod(func(c *gin.Context) { Fail(c, http.StatusMethodNotAllowed, "invalid_request", "method not allowed") })
|
||||
return e
|
||||
}
|
||||
|
||||
func RequestID(c *gin.Context) string {
|
||||
return c.GetString(keyRequestID)
|
||||
}
|
||||
|
||||
func logger(c *gin.Context) *slog.Logger {
|
||||
if l, ok := c.Get(keyLogger); ok {
|
||||
if log, ok := l.(*slog.Logger); ok {
|
||||
return log
|
||||
}
|
||||
}
|
||||
return slog.Default()
|
||||
}
|
||||
@@ -0,0 +1,309 @@
|
||||
package httpx_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/httpx"
|
||||
)
|
||||
|
||||
type errorBody struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
type payload struct {
|
||||
Text string `json:"text"`
|
||||
Count int `json:"count"`
|
||||
}
|
||||
|
||||
func newEngine(t *testing.T, logs *bytes.Buffer) *gin.Engine {
|
||||
t.Helper()
|
||||
return newEngineAt(t, logs, slog.LevelDebug)
|
||||
}
|
||||
|
||||
func newEngineAt(t *testing.T, logs *bytes.Buffer, level slog.Level) *gin.Engine {
|
||||
t.Helper()
|
||||
if logs == nil {
|
||||
logs = &bytes.Buffer{}
|
||||
}
|
||||
log := slog.New(slog.NewJSONHandler(logs, &slog.HandlerOptions{Level: level}))
|
||||
e := httpx.NewEngine(log, 64)
|
||||
e.GET("/ok", func(c *gin.Context) { httpx.JSON(c, http.StatusOK, gin.H{"text": "<a&b>"}) })
|
||||
e.GET("/panic", func(c *gin.Context) { panic("secret detail") })
|
||||
e.GET("/fail", func(c *gin.Context) { httpx.Error(c, errors.New("db password leaked")) })
|
||||
e.GET("/notfound", func(c *gin.Context) { httpx.Error(c, apperr.NotFound("chat not found")) })
|
||||
e.GET("/who", func(c *gin.Context) {
|
||||
httpx.SetUserID(c, uuid.MustParse("11111111-1111-4111-8111-111111111111"))
|
||||
id, ok := httpx.UserID(c)
|
||||
httpx.JSON(c, http.StatusOK, gin.H{"id": id.String(), "ok": ok})
|
||||
})
|
||||
e.POST("/decode", func(c *gin.Context) {
|
||||
var p payload
|
||||
if err := httpx.DecodeJSON(c, &p); err != nil {
|
||||
httpx.Error(c, err)
|
||||
return
|
||||
}
|
||||
httpx.JSON(c, http.StatusOK, p)
|
||||
})
|
||||
return e
|
||||
}
|
||||
|
||||
func do(t *testing.T, e *gin.Engine, method, path string, body string, headers map[string]string) (*httptest.ResponseRecorder, errorBody) {
|
||||
t.Helper()
|
||||
var reader io.Reader
|
||||
if body != "" {
|
||||
reader = strings.NewReader(body)
|
||||
}
|
||||
req := httptest.NewRequest(method, path, reader)
|
||||
for k, v := range headers {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
e.ServeHTTP(rec, req)
|
||||
var eb errorBody
|
||||
if rec.Code >= 400 {
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &eb); err != nil {
|
||||
t.Fatalf("%s %s: error body is not JSON: %v: %s", method, path, err, rec.Body.String())
|
||||
}
|
||||
}
|
||||
return rec, eb
|
||||
}
|
||||
|
||||
func assertError(t *testing.T, rec *httptest.ResponseRecorder, eb errorBody, status int, code string) {
|
||||
t.Helper()
|
||||
if rec.Code != status {
|
||||
t.Fatalf("status = %d, want %d (body %s)", rec.Code, status, rec.Body.String())
|
||||
}
|
||||
if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") {
|
||||
t.Fatalf("Content-Type = %q", ct)
|
||||
}
|
||||
rid := rec.Header().Get("X-Request-Id")
|
||||
if rid == "" {
|
||||
t.Fatal("missing X-Request-Id header")
|
||||
}
|
||||
if eb.Error.RequestID != rid {
|
||||
t.Fatalf("body request_id %q != header %q", eb.Error.RequestID, rid)
|
||||
}
|
||||
if eb.Error.Code != code || eb.Error.Message == "" {
|
||||
t.Fatalf("error = %+v, want code %q with a message", eb.Error, code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnknownRouteIsJSON404(t *testing.T) {
|
||||
rec, eb := do(t, newEngine(t, nil), http.MethodGet, "/nope", "", nil)
|
||||
assertError(t, rec, eb, http.StatusNotFound, "not_found")
|
||||
}
|
||||
|
||||
func TestTrailingSlashIsNotRedirected(t *testing.T) {
|
||||
rec, eb := do(t, newEngine(t, nil), http.MethodGet, "/ok/", "", nil)
|
||||
assertError(t, rec, eb, http.StatusNotFound, "not_found")
|
||||
}
|
||||
|
||||
func TestWrongMethodIsJSON405WithAllow(t *testing.T) {
|
||||
rec, eb := do(t, newEngine(t, nil), http.MethodDelete, "/ok", "", nil)
|
||||
assertError(t, rec, eb, http.StatusMethodNotAllowed, "invalid_request")
|
||||
if !strings.Contains(rec.Header().Get("Allow"), "GET") {
|
||||
t.Fatalf("Allow = %q, want GET", rec.Header().Get("Allow"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestPanicBecomesJSON500WithoutDetails(t *testing.T) {
|
||||
logs := &bytes.Buffer{}
|
||||
rec, eb := do(t, newEngine(t, logs), http.MethodGet, "/panic", "", nil)
|
||||
assertError(t, rec, eb, http.StatusInternalServerError, "internal_error")
|
||||
if strings.Contains(rec.Body.String(), "secret detail") {
|
||||
t.Fatal("panic value leaked to the client")
|
||||
}
|
||||
if !strings.Contains(logs.String(), "secret detail") {
|
||||
t.Fatal("panic must be logged for operators")
|
||||
}
|
||||
}
|
||||
|
||||
func TestForeignErrorBecomesJSON500WithoutDetails(t *testing.T) {
|
||||
logs := &bytes.Buffer{}
|
||||
rec, eb := do(t, newEngine(t, logs), http.MethodGet, "/fail", "", nil)
|
||||
assertError(t, rec, eb, http.StatusInternalServerError, "internal_error")
|
||||
if strings.Contains(rec.Body.String(), "password") {
|
||||
t.Fatal("internal error text leaked to the client")
|
||||
}
|
||||
if !strings.Contains(logs.String(), "db password leaked") {
|
||||
t.Fatal("cause must be logged for operators")
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplicationErrorMapping(t *testing.T) {
|
||||
rec, eb := do(t, newEngine(t, nil), http.MethodGet, "/notfound", "", nil)
|
||||
assertError(t, rec, eb, http.StatusNotFound, "not_found")
|
||||
if eb.Error.Message != "chat not found" {
|
||||
t.Fatalf("message = %q", eb.Error.Message)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuccessResponseHeadersAndEscaping(t *testing.T) {
|
||||
rec, _ := do(t, newEngine(t, nil), http.MethodGet, "/ok", "", nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("status = %d", rec.Code)
|
||||
}
|
||||
if ct := rec.Header().Get("Content-Type"); ct != "application/json; charset=utf-8" {
|
||||
t.Fatalf("Content-Type = %q", ct)
|
||||
}
|
||||
if rec.Header().Get("X-Request-Id") == "" {
|
||||
t.Fatal("missing X-Request-Id on success")
|
||||
}
|
||||
if !strings.Contains(rec.Body.String(), `"<a&b>"`) {
|
||||
t.Fatalf("HTML escaping must be off, body %s", rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRequestIDIsGeneratedNotEchoed(t *testing.T) {
|
||||
rec, _ := do(t, newEngine(t, nil), http.MethodGet, "/ok", "", map[string]string{"X-Request-Id": "client-chosen"})
|
||||
if got := rec.Header().Get("X-Request-Id"); got == "" || got == "client-chosen" {
|
||||
t.Fatalf("X-Request-Id = %q, want a server generated value", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeJSONHappyPath(t *testing.T) {
|
||||
rec, _ := do(t, newEngine(t, nil), http.MethodPost, "/decode", `{"text":"Привет","count":2}`, map[string]string{"Content-Type": "application/json; charset=utf-8"})
|
||||
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"Привет"`) {
|
||||
t.Fatalf("status %d body %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeJSONFailures(t *testing.T) {
|
||||
jsonCT := map[string]string{"Content-Type": "application/json"}
|
||||
cases := []struct {
|
||||
name string
|
||||
body string
|
||||
headers map[string]string
|
||||
status int
|
||||
code string
|
||||
contain string
|
||||
}{
|
||||
{"no content type", `{"text":"x"}`, nil, http.StatusUnsupportedMediaType, "unsupported_media_type", ""},
|
||||
{"wrong content type", `{"text":"x"}`, map[string]string{"Content-Type": "text/plain"}, http.StatusUnsupportedMediaType, "unsupported_media_type", ""},
|
||||
{"empty body", "", jsonCT, http.StatusBadRequest, "invalid_request", "body"},
|
||||
{"malformed", `{"text":`, jsonCT, http.StatusBadRequest, "invalid_request", "malformed"},
|
||||
{"invalid utf-8", "{\"text\":\"bad \xff byte\"}", jsonCT, http.StatusBadRequest, "invalid_request", "UTF-8"},
|
||||
{"unknown field", `{"text":"x","extra":1}`, jsonCT, http.StatusBadRequest, "invalid_request", "extra"},
|
||||
{"wrong type", `{"text":123}`, jsonCT, http.StatusBadRequest, "invalid_request", "text"},
|
||||
{"trailing data", `{"text":"x"} {"text":"y"}`, jsonCT, http.StatusBadRequest, "invalid_request", "after"},
|
||||
{"array instead of object", `[1,2]`, jsonCT, http.StatusBadRequest, "invalid_request", ""},
|
||||
{"too large", `{"text":"` + strings.Repeat("x", 100) + `"}`, jsonCT, http.StatusRequestEntityTooLarge, "payload_too_large", ""},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
rec, eb := do(t, newEngine(t, nil), http.MethodPost, "/decode", tc.body, tc.headers)
|
||||
assertError(t, rec, eb, tc.status, tc.code)
|
||||
if tc.contain != "" && !strings.Contains(eb.Error.Message, tc.contain) {
|
||||
t.Fatalf("message %q must mention %q", eb.Error.Message, tc.contain)
|
||||
}
|
||||
if strings.Contains(eb.Error.Message, "httpx_test") || strings.Contains(eb.Error.Message, "payload") {
|
||||
t.Fatalf("message must not leak Go type names: %q", eb.Error.Message)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccessLogHasRequestFieldsButNoBody(t *testing.T) {
|
||||
logs := &bytes.Buffer{}
|
||||
e := newEngine(t, logs)
|
||||
rec, _ := do(t, e, http.MethodPost, "/decode", `{"text":"confidential"}`, map[string]string{"Content-Type": "application/json"})
|
||||
var entry map[string]any
|
||||
line := lastLine(logs.String())
|
||||
if err := json.Unmarshal([]byte(line), &entry); err != nil {
|
||||
t.Fatalf("log line is not JSON: %v: %s", err, line)
|
||||
}
|
||||
for _, key := range []string{"request_id", "method", "path", "status", "duration_ms"} {
|
||||
if _, ok := entry[key]; !ok {
|
||||
t.Errorf("log entry missing %q: %s", key, line)
|
||||
}
|
||||
}
|
||||
if entry["request_id"] != rec.Header().Get("X-Request-Id") {
|
||||
t.Errorf("log request_id %v != header %q", entry["request_id"], rec.Header().Get("X-Request-Id"))
|
||||
}
|
||||
if strings.Contains(logs.String(), "confidential") {
|
||||
t.Fatal("request body must never be logged")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAccessLogLevelFollowsStatus(t *testing.T) {
|
||||
logs := &bytes.Buffer{}
|
||||
e := newEngineAt(t, logs, slog.LevelInfo)
|
||||
|
||||
do(t, e, http.MethodGet, "/ok", "", nil)
|
||||
if strings.Contains(logs.String(), `"msg":"request"`) {
|
||||
t.Fatalf("successful requests must be logged at debug level only, got %s", logs.String())
|
||||
}
|
||||
do(t, e, http.MethodGet, "/notfound", "", nil)
|
||||
if entry := logEntry(t, logs); entry["level"] != "INFO" || entry["status"] != float64(404) {
|
||||
t.Fatalf("client error must be logged at info level with its status, got %v", entry)
|
||||
}
|
||||
do(t, e, http.MethodGet, "/fail", "", nil)
|
||||
if entry := logEntry(t, logs); entry["level"] != "ERROR" || entry["status"] != float64(500) {
|
||||
t.Fatalf("server error must be logged at error level with its status, got %v", entry)
|
||||
}
|
||||
|
||||
verbose := &bytes.Buffer{}
|
||||
do(t, newEngineAt(t, verbose, slog.LevelDebug), http.MethodGet, "/ok", "", nil)
|
||||
if entry := logEntry(t, verbose); entry["level"] != "DEBUG" || entry["status"] != float64(200) {
|
||||
t.Fatalf("at debug level successful requests must be logged, got %v", entry)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserIDRoundTripAndAccessLogAttribution(t *testing.T) {
|
||||
logs := &bytes.Buffer{}
|
||||
rec, _ := do(t, newEngine(t, logs), http.MethodGet, "/who", "", nil)
|
||||
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"ok":true`) {
|
||||
t.Fatalf("UserID must return what SetUserID stored: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if entry := logEntry(t, logs); entry["user_id"] != "11111111-1111-4111-8111-111111111111" {
|
||||
t.Fatalf("access log must attribute the request to the user, got %v", entry)
|
||||
}
|
||||
anonymous := &bytes.Buffer{}
|
||||
do(t, newEngine(t, anonymous), http.MethodGet, "/ok", "", nil)
|
||||
if _, present := logEntry(t, anonymous)["user_id"]; present {
|
||||
t.Fatal("anonymous requests must not carry user_id")
|
||||
}
|
||||
}
|
||||
|
||||
func logEntry(t *testing.T, logs *bytes.Buffer) map[string]any {
|
||||
t.Helper()
|
||||
var entry map[string]any
|
||||
line := lastLine(logs.String())
|
||||
if err := json.Unmarshal([]byte(line), &entry); err != nil {
|
||||
t.Fatalf("log line is not JSON: %v: %s", err, line)
|
||||
}
|
||||
return entry
|
||||
}
|
||||
|
||||
func TestTimestampFormat(t *testing.T) {
|
||||
ts := time.Date(2026, 9, 1, 12, 0, 0, 0, time.FixedZone("MSK", 3*3600))
|
||||
if got := httpx.Timestamp(ts); got != "2026-09-01T09:00:00.000Z" {
|
||||
t.Fatalf("Timestamp = %q", got)
|
||||
}
|
||||
ts = time.Date(2026, 9, 1, 12, 0, 0, 7_000_000, time.UTC)
|
||||
if got := httpx.Timestamp(ts); got != "2026-09-01T12:00:00.007Z" {
|
||||
t.Fatalf("Timestamp = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func lastLine(s string) string {
|
||||
lines := strings.Split(strings.TrimSpace(s), "\n")
|
||||
return lines[len(lines)-1]
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const keyUserID = "messenger.user_id"
|
||||
|
||||
// SetUserID records the identified caller for the handlers behind the
|
||||
// identification middleware and for the access log. It lives here rather
|
||||
// than in the auth package because the access log needs it and auth already
|
||||
// depends on this package.
|
||||
func SetUserID(c *gin.Context, id uuid.UUID) {
|
||||
c.Set(keyUserID, id)
|
||||
}
|
||||
|
||||
func UserID(c *gin.Context) (uuid.UUID, bool) {
|
||||
v, ok := c.Get(keyUserID)
|
||||
if !ok {
|
||||
return uuid.Nil, false
|
||||
}
|
||||
id, ok := v.(uuid.UUID)
|
||||
return id, ok
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"runtime/debug"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// requestID assigns a fresh identifier to every request.
|
||||
//
|
||||
// An incoming X-Request-Id is deliberately not reused. This service is
|
||||
// client-facing: there is no trusted upstream that could have minted the
|
||||
// value, so honouring it would let any caller pick an arbitrary string that
|
||||
// ends up in logs (log injection, unbounded length) or collides with another
|
||||
// request and corrupts log correlation. Reusing the header is the right
|
||||
// choice only when the caller is a trusted proxy or a sibling service that
|
||||
// propagates one id across a chain of calls.
|
||||
func requestID(log *slog.Logger) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var raw [16]byte
|
||||
if _, err := rand.Read(raw[:]); err != nil {
|
||||
panic("httpx: random source unavailable: " + err.Error())
|
||||
}
|
||||
id := hex.EncodeToString(raw[:])
|
||||
c.Set(keyRequestID, id)
|
||||
c.Set(keyLogger, log)
|
||||
c.Writer.Header().Set("X-Request-Id", id)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// accessLog writes one line per request at a level that follows the
|
||||
// outcome (2xx debug, 4xx info, 5xx error), so the ordinary log level decides
|
||||
// how much traffic is recorded. Headers, query strings and bodies are never
|
||||
// recorded. time.Since uses the monotonic clock, so wall clock adjustments
|
||||
// cannot distort the duration.
|
||||
func accessLog() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
start := time.Now()
|
||||
c.Next()
|
||||
|
||||
status := c.Writer.Status()
|
||||
level := slog.LevelDebug
|
||||
switch {
|
||||
case status >= http.StatusInternalServerError:
|
||||
level = slog.LevelError
|
||||
case status >= http.StatusBadRequest:
|
||||
level = slog.LevelInfo
|
||||
}
|
||||
log := logger(c)
|
||||
ctx := c.Request.Context()
|
||||
if !log.Enabled(ctx, level) {
|
||||
return
|
||||
}
|
||||
attrs := []any{
|
||||
"request_id", RequestID(c),
|
||||
"method", c.Request.Method,
|
||||
"path", c.Request.URL.Path,
|
||||
"status", status,
|
||||
"duration_ms", float64(time.Since(start).Microseconds()) / 1000,
|
||||
"bytes", c.Writer.Size(),
|
||||
}
|
||||
if id, ok := UserID(c); ok {
|
||||
attrs = append(attrs, "user_id", id.String())
|
||||
}
|
||||
log.Log(ctx, level, "request", attrs...)
|
||||
}
|
||||
}
|
||||
|
||||
// recovery turns a panic into a contract 500; the stack goes to the log only.
|
||||
func recovery() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
defer func() {
|
||||
if r := recover(); r != nil {
|
||||
logger(c).Error("panic recovered",
|
||||
"request_id", RequestID(c),
|
||||
"panic", fmt.Sprint(r),
|
||||
"stack", string(debug.Stack()),
|
||||
)
|
||||
if !c.Writer.Written() {
|
||||
Fail(c, http.StatusInternalServerError, "internal_error", "internal error")
|
||||
}
|
||||
c.Abort()
|
||||
}
|
||||
}()
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// bodyLimit caps request bodies; exceeding it surfaces from the JSON
|
||||
// decoder as *http.MaxBytesError.
|
||||
func bodyLimit(maxBytes int64) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
if c.Request.Body != nil {
|
||||
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBytes)
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
)
|
||||
|
||||
type errorEnvelope struct {
|
||||
Error errorDetail `json:"error"`
|
||||
}
|
||||
|
||||
type errorDetail struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
type statusCode struct {
|
||||
status int
|
||||
code string
|
||||
}
|
||||
|
||||
var kinds = map[apperr.Kind]statusCode{
|
||||
apperr.KindInvalid: {http.StatusBadRequest, "invalid_request"},
|
||||
apperr.KindUnauthorized: {http.StatusUnauthorized, "unauthorized"},
|
||||
apperr.KindNotFound: {http.StatusNotFound, "not_found"},
|
||||
apperr.KindConflict: {http.StatusConflict, "conflict"},
|
||||
apperr.KindPayloadTooLarge: {http.StatusRequestEntityTooLarge, "payload_too_large"},
|
||||
apperr.KindUnsupportedMedia: {http.StatusUnsupportedMediaType, "unsupported_media_type"},
|
||||
apperr.KindUnavailable: {http.StatusServiceUnavailable, "unavailable"},
|
||||
}
|
||||
|
||||
// JSON is the single place that fixes the response media type; PureJSON
|
||||
// keeps non-ASCII and HTML characters verbatim.
|
||||
func JSON(c *gin.Context, status int, body any) {
|
||||
c.PureJSON(status, body)
|
||||
}
|
||||
|
||||
// Fail writes the contract error body and stops the handler chain.
|
||||
func Fail(c *gin.Context, status int, code, message string) {
|
||||
JSON(c, status, errorEnvelope{Error: errorDetail{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: RequestID(c),
|
||||
}})
|
||||
c.Abort()
|
||||
}
|
||||
|
||||
// Error maps an application error to its status. Anything that is not an
|
||||
// application error is logged with its text and reported as an opaque 500,
|
||||
// so internal details never reach the client.
|
||||
func Error(c *gin.Context, err error) {
|
||||
mapped, known := kinds[apperr.KindOf(err)]
|
||||
if !known {
|
||||
logger(c).Error("request failed", "request_id", RequestID(c), "error", err.Error())
|
||||
Fail(c, http.StatusInternalServerError, "internal_error", "internal error")
|
||||
return
|
||||
}
|
||||
Fail(c, mapped.status, mapped.code, err.Error())
|
||||
}
|
||||
|
||||
// Timestamp renders RFC 3339 UTC with a fixed millisecond width: Python 3.9
|
||||
// (the oldest version the public tests support) only parses 3 or 6 fractional
|
||||
// digits, and RFC3339Nano would trim trailing zeros to a variable width.
|
||||
func Timestamp(t time.Time) string {
|
||||
return t.UTC().Format("2006-01-02T15:04:05.000Z")
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// Package ident generates and parses entity identifiers.
|
||||
//
|
||||
// Identifiers are UUIDv7 (RFC 9562): the first 48 bits carry a Unix
|
||||
// millisecond timestamp and google/uuid keeps them strictly increasing within
|
||||
// one process even when the system clock steps backwards, so lexicographic
|
||||
// order of ids equals creation order.
|
||||
package ident
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var ErrInvalid = errors.New("invalid uuid")
|
||||
|
||||
// New panics only if the platform random source is unavailable, which is a
|
||||
// fatal environment fault rather than a request error.
|
||||
func New() uuid.UUID {
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
panic("ident: random source unavailable: " + err.Error())
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
// TimeOf extracts the creation time carried by a UUIDv7 as UTC with
|
||||
// millisecond precision.
|
||||
func TimeOf(id uuid.UUID) time.Time {
|
||||
sec, nsec := id.Time().UnixTime()
|
||||
return time.Unix(sec, nsec).UTC()
|
||||
}
|
||||
|
||||
// Parse accepts only the canonical 36-character form; uuid.Parse alone would
|
||||
// also take braces, urn prefixes and bare hex.
|
||||
func Parse(raw string) (uuid.UUID, error) {
|
||||
if len(raw) != 36 {
|
||||
return uuid.Nil, ErrInvalid
|
||||
}
|
||||
id, err := uuid.Parse(raw)
|
||||
if err != nil {
|
||||
return uuid.Nil, ErrInvalid
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package ident_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/internal/platform/ident"
|
||||
)
|
||||
|
||||
func TestNewProducesVersion7(t *testing.T) {
|
||||
id := ident.New()
|
||||
if got := id.Version(); got != 7 {
|
||||
t.Fatalf("version = %d, want 7", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewIsStrictlyIncreasingWithinProcess(t *testing.T) {
|
||||
prev := ident.New()
|
||||
for i := 0; i < 20000; i++ {
|
||||
next := ident.New()
|
||||
if bytes.Compare(next[:], prev[:]) <= 0 {
|
||||
t.Fatalf("id %s is not greater than previous %s at iteration %d", next, prev, i)
|
||||
}
|
||||
prev = next
|
||||
}
|
||||
}
|
||||
|
||||
func TestTimeOfMatchesWallClockAtMillisecondPrecision(t *testing.T) {
|
||||
before := time.Now().Truncate(time.Millisecond)
|
||||
id := ident.New()
|
||||
after := time.Now().Add(time.Millisecond)
|
||||
|
||||
got := ident.TimeOf(id)
|
||||
if got.Location() != time.UTC {
|
||||
t.Fatalf("TimeOf must return UTC, got %v", got.Location())
|
||||
}
|
||||
if got.Before(before) || got.After(after) {
|
||||
t.Fatalf("TimeOf = %v, want within [%v, %v]", got, before, after)
|
||||
}
|
||||
if got.Nanosecond()%int(time.Millisecond) != 0 {
|
||||
t.Fatalf("TimeOf must be truncated to milliseconds, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseAcceptsCanonicalForm(t *testing.T) {
|
||||
id := ident.New()
|
||||
parsed, err := ident.Parse(id.String())
|
||||
if err != nil {
|
||||
t.Fatalf("Parse(%q) error: %v", id, err)
|
||||
}
|
||||
if parsed != id {
|
||||
t.Fatalf("Parse round trip mismatch: %s != %s", parsed, id)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRejectsNonCanonicalForms(t *testing.T) {
|
||||
id := ident.New().String()
|
||||
for _, raw := range []string{
|
||||
"",
|
||||
"not-a-uuid",
|
||||
"{" + id + "}",
|
||||
"urn:uuid:" + id,
|
||||
id[:32] + id[33:], // hex without one dash
|
||||
id + "0",
|
||||
" " + id,
|
||||
} {
|
||||
if _, err := ident.Parse(raw); err == nil {
|
||||
t.Errorf("Parse(%q) must fail", raw)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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