Перенесите реализацию lab3 и сохраните серии нагрузочных экспериментов
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,187 @@
|
||||
// Package config reads the process configuration from the environment.
|
||||
// Settings have defaults suited to the lab stand, except credentials, which
|
||||
// are required and read from files named by *_FILE variables so that their
|
||||
// values never appear in the environment. An invalid value stops the process
|
||||
// at start-up with a message naming the variable, never the secret.
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Logging struct {
|
||||
Env string
|
||||
Level slog.Level
|
||||
}
|
||||
|
||||
func (l Logging) NewLogger() *slog.Logger {
|
||||
opts := &slog.HandlerOptions{Level: l.Level}
|
||||
if l.Env == "dev" {
|
||||
return slog.New(slog.NewTextHandler(os.Stdout, opts))
|
||||
}
|
||||
return slog.New(slog.NewJSONHandler(os.Stdout, opts))
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Logging
|
||||
Host string
|
||||
Port int
|
||||
ShutdownTimeout time.Duration
|
||||
MaxBodyBytes int64
|
||||
DatabaseURL string
|
||||
SessionStoreURL string
|
||||
SessionTTL time.Duration
|
||||
// DrainDelay keeps a stopping process serving with readiness off; it must
|
||||
// exceed the balancer's detection time.
|
||||
DrainDelay time.Duration
|
||||
IdempotencyTTL time.Duration
|
||||
DBMaxConns int32
|
||||
DebugAddr string
|
||||
}
|
||||
|
||||
type Migrate struct {
|
||||
Logging
|
||||
DatabaseURL string
|
||||
}
|
||||
|
||||
// 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,
|
||||
ShutdownTimeout: 8 * time.Second,
|
||||
MaxBodyBytes: 64 * 1024,
|
||||
SessionTTL: time.Hour,
|
||||
DrainDelay: 2 * time.Second,
|
||||
IdempotencyTTL: 24 * time.Hour,
|
||||
DBMaxConns: 10,
|
||||
}
|
||||
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
|
||||
}
|
||||
var err error
|
||||
if cfg.Logging, err = loadLogging(lookup); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
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
|
||||
}
|
||||
if v, ok := lookup("SESSION_TTL_SECONDS"); ok {
|
||||
n, err := strconv.ParseUint(v, 10, 32)
|
||||
if err != nil || n == 0 {
|
||||
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS must be a positive whole number of seconds, got %q", v)
|
||||
}
|
||||
cfg.SessionTTL = time.Duration(n) * time.Second
|
||||
}
|
||||
if v, ok := lookup("APP_DRAIN_DELAY"); ok {
|
||||
d, err := time.ParseDuration(v)
|
||||
if err != nil || d < 0 {
|
||||
return Config{}, fmt.Errorf("APP_DRAIN_DELAY must be a non-negative duration such as 2s, got %q", v)
|
||||
}
|
||||
cfg.DrainDelay = d
|
||||
}
|
||||
if v, ok := lookup("IDEMPOTENCY_TTL_SECONDS"); ok {
|
||||
n, err := strconv.ParseUint(v, 10, 32)
|
||||
if err != nil || n == 0 {
|
||||
return Config{}, fmt.Errorf("IDEMPOTENCY_TTL_SECONDS must be a positive whole number of seconds, got %q", v)
|
||||
}
|
||||
cfg.IdempotencyTTL = time.Duration(n) * time.Second
|
||||
}
|
||||
if v, ok := lookup("DB_MAX_CONNS"); ok {
|
||||
n, err := strconv.ParseInt(v, 10, 32)
|
||||
if err != nil || n < 1 || n > 1000 {
|
||||
return Config{}, fmt.Errorf("DB_MAX_CONNS must be an integer between 1 and 1000, got %q", v)
|
||||
}
|
||||
cfg.DBMaxConns = int32(n)
|
||||
}
|
||||
if v, ok := lookup("APP_DEBUG_ADDR"); ok && v != "" {
|
||||
if _, _, err := net.SplitHostPort(v); err != nil {
|
||||
return Config{}, fmt.Errorf("APP_DEBUG_ADDR must be host:port such as :9090, got %q", v)
|
||||
}
|
||||
cfg.DebugAddr = v
|
||||
}
|
||||
if cfg.DatabaseURL, err = secret(lookup, "DATABASE_URL_FILE"); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if cfg.SessionStoreURL, err = secret(lookup, "SESSION_STORE_URL_FILE"); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func LoadMigrate(lookup Lookup) (Migrate, error) {
|
||||
var cfg Migrate
|
||||
var err error
|
||||
if cfg.Logging, err = loadLogging(lookup); err != nil {
|
||||
return Migrate{}, err
|
||||
}
|
||||
if cfg.DatabaseURL, err = secret(lookup, "DATABASE_URL_FILE"); err != nil {
|
||||
return Migrate{}, err
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func loadLogging(lookup Lookup) (Logging, error) {
|
||||
l := Logging{Env: "lab", Level: slog.LevelInfo}
|
||||
if v, ok := lookup("APP_ENV"); ok && strings.TrimSpace(v) != "" {
|
||||
l.Env = v
|
||||
}
|
||||
if v, ok := lookup("APP_LOG_LEVEL"); ok {
|
||||
if err := l.Level.UnmarshalText([]byte(v)); err != nil {
|
||||
return Logging{}, fmt.Errorf("APP_LOG_LEVEL must be debug, info, warn or error, got %q", v)
|
||||
}
|
||||
}
|
||||
return l, nil
|
||||
}
|
||||
|
||||
// secret reads the file named by the variable; surrounding whitespace,
|
||||
// including the trailing newline editors add, is dropped.
|
||||
func secret(lookup Lookup, key string) (string, error) {
|
||||
path, ok := lookup(key)
|
||||
if !ok || strings.TrimSpace(path) == "" {
|
||||
return "", fmt.Errorf("%s must name a file with the value", key)
|
||||
}
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%s: cannot read %s: %w", key, path, err)
|
||||
}
|
||||
value := strings.TrimSpace(string(raw))
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("%s: file %s is empty", key, path)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (c Config) Addr() string {
|
||||
return net.JoinHostPort(c.Host, strconv.Itoa(c.Port))
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
package config_test
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"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 secretFile(t *testing.T, content string) string {
|
||||
t.Helper()
|
||||
path := filepath.Join(t.TempDir(), "secret")
|
||||
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
|
||||
const (
|
||||
databaseURL = "postgres://app:s3cret@db:5432/messenger"
|
||||
sessionStoreURL = "redis://:s3cret@valkey:6379/0"
|
||||
)
|
||||
|
||||
// required holds the variables without defaults, merged with extra.
|
||||
func required(t *testing.T, extra map[string]string) map[string]string {
|
||||
t.Helper()
|
||||
values := map[string]string{
|
||||
"DATABASE_URL_FILE": secretFile(t, databaseURL+"\n"),
|
||||
"SESSION_STORE_URL_FILE": secretFile(t, sessionStoreURL+"\r\n"),
|
||||
}
|
||||
for k, v := range extra {
|
||||
values[k] = v
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func TestDefaults(t *testing.T) {
|
||||
cfg, err := config.Load(env(required(t, 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.Level != slog.LevelInfo {
|
||||
t.Fatalf("cfg = %+v", cfg)
|
||||
}
|
||||
if cfg.ShutdownTimeout != 8*time.Second || cfg.MaxBodyBytes != 65536 {
|
||||
t.Fatalf("cfg = %+v", cfg)
|
||||
}
|
||||
if cfg.DatabaseURL != databaseURL || cfg.SessionStoreURL != sessionStoreURL {
|
||||
t.Fatalf("urls = %q, %q; want the file contents without line endings", cfg.DatabaseURL, cfg.SessionStoreURL)
|
||||
}
|
||||
if cfg.SessionTTL != time.Hour {
|
||||
t.Fatalf("SessionTTL = %v, want 1h", cfg.SessionTTL)
|
||||
}
|
||||
if cfg.DrainDelay != 2*time.Second || cfg.IdempotencyTTL != 24*time.Hour || cfg.DBMaxConns != 10 || cfg.DebugAddr != "" {
|
||||
t.Fatalf("lab3 defaults = drain %v, key ttl %v, pool %d, debug %q", cfg.DrainDelay, cfg.IdempotencyTTL, cfg.DBMaxConns, cfg.DebugAddr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSecretFilesAreRequiredAndNeverEchoed(t *testing.T) {
|
||||
for _, key := range []string{"DATABASE_URL_FILE", "SESSION_STORE_URL_FILE"} {
|
||||
cases := map[string]func(map[string]string){
|
||||
"unset": func(v map[string]string) { delete(v, key) },
|
||||
"empty path": func(v map[string]string) { v[key] = "" },
|
||||
"no file": func(v map[string]string) { v[key] = filepath.Join(t.TempDir(), "missing") },
|
||||
"blank file": func(v map[string]string) { v[key] = secretFile(t, " \r\n") },
|
||||
}
|
||||
for name, breakIt := range cases {
|
||||
values := required(t, nil)
|
||||
breakIt(values)
|
||||
_, err := config.Load(env(values))
|
||||
if err == nil {
|
||||
t.Errorf("%s %s: want error", key, name)
|
||||
continue
|
||||
}
|
||||
if !strings.Contains(err.Error(), key) || strings.Contains(err.Error(), "s3cret") {
|
||||
t.Errorf("%s %s: error must name the variable and hide the secret: %v", key, name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOverrides(t *testing.T) {
|
||||
cfg, err := config.Load(env(required(t, 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",
|
||||
"SESSION_TTL_SECONDS": "300",
|
||||
"APP_DRAIN_DELAY": "0s",
|
||||
"IDEMPOTENCY_TTL_SECONDS": "60",
|
||||
"DB_MAX_CONNS": "25",
|
||||
"APP_DEBUG_ADDR": ":9090",
|
||||
})))
|
||||
if err != nil {
|
||||
t.Fatalf("Load error: %v", err)
|
||||
}
|
||||
if cfg.Addr() != "127.0.0.1:9090" || cfg.Env != "dev" || cfg.Level != slog.LevelDebug {
|
||||
t.Fatalf("cfg = %+v", cfg)
|
||||
}
|
||||
if cfg.ShutdownTimeout != 3*time.Second || cfg.MaxBodyBytes != 1024 || cfg.SessionTTL != 5*time.Minute {
|
||||
t.Fatalf("cfg = %+v", cfg)
|
||||
}
|
||||
if cfg.DrainDelay != 0 || cfg.IdempotencyTTL != time.Minute || cfg.DBMaxConns != 25 || cfg.DebugAddr != ":9090" {
|
||||
t.Fatalf("lab3 overrides = drain %v, key ttl %v, pool %d, debug %q", cfg.DrainDelay, cfg.IdempotencyTTL, cfg.DBMaxConns, cfg.DebugAddr)
|
||||
}
|
||||
}
|
||||
|
||||
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": ""},
|
||||
"ttl zero": {"SESSION_TTL_SECONDS": "0"},
|
||||
"ttl negative": {"SESSION_TTL_SECONDS": "-5"},
|
||||
"ttl text": {"SESSION_TTL_SECONDS": "hour"},
|
||||
"ttl fraction": {"SESSION_TTL_SECONDS": "1.5"},
|
||||
"drain negative": {"APP_DRAIN_DELAY": "-1s"},
|
||||
"drain text": {"APP_DRAIN_DELAY": "abc"},
|
||||
"key ttl zero": {"IDEMPOTENCY_TTL_SECONDS": "0"},
|
||||
"key ttl text": {"IDEMPOTENCY_TTL_SECONDS": "day"},
|
||||
"pool zero": {"DB_MAX_CONNS": "0"},
|
||||
"pool too big": {"DB_MAX_CONNS": "1001"},
|
||||
"pool text": {"DB_MAX_CONNS": "many"},
|
||||
"debug addr": {"APP_DEBUG_ADDR": "nonsense"},
|
||||
}
|
||||
for name, values := range cases {
|
||||
_, err := config.Load(env(required(t, values)))
|
||||
if err == nil {
|
||||
t.Errorf("%s: want error", name)
|
||||
continue
|
||||
}
|
||||
for key := range values {
|
||||
if !strings.Contains(err.Error(), key) {
|
||||
t.Errorf("%s: error %q does not name %s", name, err, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadMigrateNeedsOnlyTheDatabaseURL(t *testing.T) {
|
||||
cfg, err := config.LoadMigrate(env(map[string]string{
|
||||
"DATABASE_URL_FILE": secretFile(t, databaseURL+"\n"),
|
||||
"APP_ENV": "dev",
|
||||
"APP_LOG_LEVEL": "warn",
|
||||
}))
|
||||
if err != nil {
|
||||
t.Fatalf("LoadMigrate error: %v", err)
|
||||
}
|
||||
if cfg.DatabaseURL != databaseURL || cfg.Env != "dev" || cfg.Level != slog.LevelWarn {
|
||||
t.Fatalf("cfg = %+v", cfg)
|
||||
}
|
||||
if _, err := config.LoadMigrate(env(map[string]string{})); err == nil || !strings.Contains(err.Error(), "DATABASE_URL_FILE") {
|
||||
t.Fatalf("missing database url: err = %v", err)
|
||||
}
|
||||
}
|
||||
@@ -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,50 @@
|
||||
// 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-Instance-Id, X-Request-Id and the contract
|
||||
// error body.
|
||||
func NewEngine(log *slog.Logger, maxBodyBytes int64, instanceID string) *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(instance(instanceID), 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,409 @@
|
||||
package httpx_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"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"`
|
||||
}
|
||||
|
||||
const testInstance = "0123456789abcdef"
|
||||
|
||||
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, testInstance)
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// The balancer spreads one client's requests over the replicas; the header
|
||||
// is how a client tells which process answered, so no response may lack it.
|
||||
func TestEveryResponseCarriesInstanceID(t *testing.T) {
|
||||
e := newEngine(t, nil)
|
||||
for _, r := range []struct{ method, path string }{
|
||||
{http.MethodGet, "/ok"},
|
||||
{http.MethodGet, "/missing"},
|
||||
{http.MethodDelete, "/ok"},
|
||||
{http.MethodGet, "/panic"},
|
||||
{http.MethodGet, "/fail"},
|
||||
{http.MethodPost, "/decode"},
|
||||
} {
|
||||
rec, _ := do(t, e, r.method, r.path, "", nil)
|
||||
if got := rec.Header().Get("X-Instance-Id"); got != testInstance {
|
||||
t.Errorf("%s %s (status %d): X-Instance-Id = %q, want %q", r.method, r.path, rec.Code, got, testInstance)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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())
|
||||
}
|
||||
}
|
||||
|
||||
// The balancer sets X-Request-Id on every request, overwriting what the
|
||||
// client sent; the API keeps it so that one id spans both logs.
|
||||
func TestRequestIDFromTheBalancerIsKept(t *testing.T) {
|
||||
const fromLB = "0123456789abcdef0123456789abcdef"
|
||||
rec, _ := do(t, newEngine(t, nil), http.MethodGet, "/ok", "", map[string]string{"X-Request-Id": fromLB})
|
||||
if got := rec.Header().Get("X-Request-Id"); got != fromLB {
|
||||
t.Fatalf("X-Request-Id = %q, want %q", got, fromLB)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMalformedRequestIDIsReplaced(t *testing.T) {
|
||||
for _, bad := range []string{"has space", "semi;colon", "tab\there", strings.Repeat("a", 65)} {
|
||||
rec, _ := do(t, newEngine(t, nil), http.MethodGet, "/ok", "", map[string]string{"X-Request-Id": bad})
|
||||
if got := rec.Header().Get("X-Request-Id"); got == "" || got == bad {
|
||||
t.Errorf("X-Request-Id for %q = %q, want a generated value", bad, 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 TestWithUserPassesTheIdentifiedCaller(t *testing.T) {
|
||||
actor := uuid.MustParse("22222222-2222-4222-8222-222222222222")
|
||||
e := newEngine(t, nil)
|
||||
e.GET("/actor",
|
||||
func(c *gin.Context) { httpx.SetUserID(c, actor) },
|
||||
httpx.WithUser(func(c *gin.Context, got uuid.UUID) {
|
||||
httpx.JSON(c, http.StatusOK, gin.H{"id": got.String()})
|
||||
}))
|
||||
rec, _ := do(t, e, http.MethodGet, "/actor", "", nil)
|
||||
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), actor.String()) {
|
||||
t.Fatalf("handler did not receive the caller: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// Reaching WithUser without an authentication middleware in front is a
|
||||
// wiring mistake, so it must not be blamed on the client with a 401.
|
||||
func TestWithUserWithoutIdentityIsAWiringError(t *testing.T) {
|
||||
e := newEngine(t, nil)
|
||||
e.GET("/actor", httpx.WithUser(func(c *gin.Context, _ uuid.UUID) {
|
||||
httpx.JSON(c, http.StatusOK, gin.H{})
|
||||
}))
|
||||
rec, eb := do(t, e, http.MethodGet, "/actor", "", nil)
|
||||
assertError(t, rec, eb, http.StatusInternalServerError, "internal_error")
|
||||
}
|
||||
|
||||
// A 5xx tells the client only the safe message; the operator must still see
|
||||
// why the dependency failed, so the cause goes to the log.
|
||||
func TestUnavailableCauseIsLoggedButNotReturned(t *testing.T) {
|
||||
logs := &bytes.Buffer{}
|
||||
e := newEngine(t, logs)
|
||||
e.GET("/down", func(c *gin.Context) {
|
||||
cause := errors.New("dial tcp 10.0.0.7:5432: connect: connection refused")
|
||||
httpx.Error(c, fmt.Errorf("select user: %w", apperr.Wrap(apperr.KindUnavailable, "database unavailable", cause)))
|
||||
})
|
||||
rec, eb := do(t, e, http.MethodGet, "/down", "", nil)
|
||||
assertError(t, rec, eb, http.StatusServiceUnavailable, "unavailable")
|
||||
// Neither the cause nor the wrapping context of internal operations
|
||||
// ("select user: ...") may reach the client.
|
||||
if eb.Error.Message != "database unavailable" {
|
||||
t.Fatalf("client message = %q, want only the application message", eb.Error.Message)
|
||||
}
|
||||
if !strings.Contains(logs.String(), "connection refused") || !strings.Contains(logs.String(), eb.Error.RequestID) {
|
||||
t.Fatalf("log must carry the cause and the request id, got:\n%s", logs.String())
|
||||
}
|
||||
}
|
||||
|
||||
// Everything below Timeout sees one deadline, so waiting on a dependency
|
||||
// ends with the request instead of holding the client.
|
||||
func TestTimeoutBoundsTheRequestContext(t *testing.T) {
|
||||
e := newEngine(t, nil)
|
||||
e.GET("/slow", httpx.Timeout(50*time.Millisecond), func(c *gin.Context) {
|
||||
select {
|
||||
case <-c.Request.Context().Done():
|
||||
httpx.Error(c, apperr.Wrap(apperr.KindUnavailable, "gave up", c.Request.Context().Err()))
|
||||
case <-time.After(5 * time.Second):
|
||||
httpx.JSON(c, http.StatusOK, gin.H{})
|
||||
}
|
||||
})
|
||||
start := time.Now()
|
||||
rec, eb := do(t, e, http.MethodGet, "/slow", "", nil)
|
||||
assertError(t, rec, eb, http.StatusServiceUnavailable, "unavailable")
|
||||
if elapsed := time.Since(start); elapsed > time.Second {
|
||||
t.Fatalf("request took %v, want it cut at the 50ms deadline", elapsed)
|
||||
}
|
||||
}
|
||||
|
||||
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,42 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"errors"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const keyUserID = "messenger.user_id"
|
||||
|
||||
// SetUserID records the authenticated caller for the handlers behind the
|
||||
// authentication middleware and for the access log.
|
||||
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
|
||||
}
|
||||
|
||||
// UserHandler is a handler that needs the authenticated caller.
|
||||
type UserHandler func(c *gin.Context, actor uuid.UUID)
|
||||
|
||||
// WithUser adapts a UserHandler to gin. Reaching it without the
|
||||
// authentication middleware in front is a wiring mistake, so it is reported
|
||||
// as an internal error rather than blamed on the client with a 401.
|
||||
func WithUser(h UserHandler) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
actor, ok := UserID(c)
|
||||
if !ok {
|
||||
Error(c, errors.New("route is missing the authentication middleware"))
|
||||
return
|
||||
}
|
||||
h(c, actor)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"runtime/debug"
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// instance names the process that answered, so a client behind the load
|
||||
// balancer can tell the replicas apart.
|
||||
func instance(id string) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Writer.Header().Set("X-Instance-Id", id)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
var requestIDPattern = regexp.MustCompile(`^[A-Za-z0-9-]{1,64}$`)
|
||||
|
||||
// requestID keeps the X-Request-Id set by the load balancer, which overwrites
|
||||
// any value a client sends; a malformed value is replaced, so a direct caller
|
||||
// cannot inject into the logs.
|
||||
func requestID(log *slog.Logger) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
id := c.GetHeader("X-Request-Id")
|
||||
if !requestIDPattern.MatchString(id) {
|
||||
id = newRequestID()
|
||||
}
|
||||
c.Set(keyRequestID, id)
|
||||
c.Set(keyLogger, log)
|
||||
c.Writer.Header().Set("X-Request-Id", id)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func newRequestID() string {
|
||||
var raw [16]byte
|
||||
if _, err := rand.Read(raw[:]); err != nil {
|
||||
panic("httpx: random source unavailable: " + err.Error())
|
||||
}
|
||||
return hex.EncodeToString(raw[:])
|
||||
}
|
||||
|
||||
// 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()
|
||||
}
|
||||
}
|
||||
|
||||
// Timeout bounds the whole request with one deadline: waiting for a pooled
|
||||
// connection, SQL statements and session lookups all observe it, so a hung
|
||||
// dependency ends in a 503 within d instead of holding the client.
|
||||
func Timeout(d time.Duration) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
ctx, cancel := context.WithTimeout(c.Request.Context(), d)
|
||||
defer cancel()
|
||||
c.Request = c.Request.WithContext(ctx)
|
||||
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,87 @@
|
||||
package httpx
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"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. An application error shows the
|
||||
// client only its own message, never the context it was wrapped in on the
|
||||
// way up; when it is answered with a 5xx (a dependency outage) the full
|
||||
// chain and the cause go to the log for the operator.
|
||||
func Error(c *gin.Context, err error) {
|
||||
appErr, isApp := errors.AsType[*apperr.Error](err)
|
||||
var mapped statusCode
|
||||
known := false
|
||||
if isApp {
|
||||
mapped, known = kinds[appErr.Kind]
|
||||
}
|
||||
if !known {
|
||||
logger(c).Error("request failed", "request_id", RequestID(c), "error", err.Error())
|
||||
Fail(c, http.StatusInternalServerError, "internal_error", "internal error")
|
||||
return
|
||||
}
|
||||
if mapped.status >= http.StatusInternalServerError {
|
||||
attrs := []any{"request_id", RequestID(c), "error", err.Error()}
|
||||
if appErr.Cause != nil {
|
||||
attrs = append(attrs, "cause", appErr.Cause.Error())
|
||||
}
|
||||
logger(c).Error("request failed", attrs...)
|
||||
}
|
||||
Fail(c, mapped.status, mapped.code, appErr.Message)
|
||||
}
|
||||
|
||||
// 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,56 @@
|
||||
// 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 (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"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
|
||||
}
|
||||
|
||||
// NewAlias names one server process for X-Instance-Id; random rather than the
|
||||
// hostname, so the header reveals nothing about the infrastructure.
|
||||
func NewAlias() string {
|
||||
var raw [8]byte
|
||||
_, _ = rand.Read(raw[:]) // crypto/rand.Read never returns an error since Go 1.24.
|
||||
return hex.EncodeToString(raw[:])
|
||||
}
|
||||
|
||||
// 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,84 @@
|
||||
package ident_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"regexp"
|
||||
"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)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewAliasIs16HexAndRandom(t *testing.T) {
|
||||
a, b := ident.NewAlias(), ident.NewAlias()
|
||||
hex16 := regexp.MustCompile(`^[0-9a-f]{16}$`)
|
||||
if !hex16.MatchString(a) || !hex16.MatchString(b) {
|
||||
t.Fatalf("aliases %q, %q are not 16 lowercase hex characters", a, b)
|
||||
}
|
||||
if a == b {
|
||||
t.Fatalf("two aliases are equal: %q", a)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
// Package password hashes user passwords with Argon2id.
|
||||
//
|
||||
// A password has little entropy, so its hash must be slow and memory-hard to
|
||||
// make offline guessing expensive. Session tokens are the opposite case: they
|
||||
// are random 256-bit values, and a fast digest is enough for them.
|
||||
package password
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
// OWASP baseline for Argon2id. The parameters are written into every hash,
|
||||
// so raising them later does not invalidate stored hashes.
|
||||
const (
|
||||
memoryKiB = 19 * 1024
|
||||
iterations = 2
|
||||
threads = 1
|
||||
saltLen = 16
|
||||
keyLen = 32
|
||||
)
|
||||
|
||||
var ErrMalformed = errors.New("malformed password hash")
|
||||
|
||||
var b64 = base64.RawStdEncoding
|
||||
|
||||
// Hash returns the PHC string $argon2id$v=19$m=…,t=…,p=…$<salt>$<key>.
|
||||
func Hash(plain string) string {
|
||||
salt := make([]byte, saltLen)
|
||||
// Since Go 1.24 crypto/rand.Read never returns an error.
|
||||
_, _ = rand.Read(salt)
|
||||
key := argon2.IDKey([]byte(plain), salt, iterations, memoryKiB, threads, keyLen)
|
||||
return fmt.Sprintf("$argon2id$v=%d$%s$%s$%s",
|
||||
argon2.Version, params(memoryKiB, iterations, threads), b64.EncodeToString(salt), b64.EncodeToString(key))
|
||||
}
|
||||
|
||||
// Verify reports whether plain matches encoded. An error means the stored
|
||||
// hash itself is unreadable, not that the password is wrong.
|
||||
func Verify(encoded, plain string) (bool, error) {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" {
|
||||
return false, ErrMalformed
|
||||
}
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version {
|
||||
return false, ErrMalformed
|
||||
}
|
||||
var memory, time uint32
|
||||
var parallelism uint8
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &time, ¶llelism); err != nil ||
|
||||
memory == 0 || time == 0 || parallelism == 0 {
|
||||
return false, ErrMalformed
|
||||
}
|
||||
salt, err := b64.DecodeString(parts[4])
|
||||
if err != nil || len(salt) == 0 {
|
||||
return false, ErrMalformed
|
||||
}
|
||||
key, err := b64.DecodeString(parts[5])
|
||||
if err != nil || len(key) == 0 {
|
||||
return false, ErrMalformed
|
||||
}
|
||||
got := argon2.IDKey([]byte(plain), salt, time, memory, parallelism, uint32(len(key)))
|
||||
return subtle.ConstantTimeCompare(got, key) == 1, nil
|
||||
}
|
||||
|
||||
func params(memory, time uint32, parallelism uint8) string {
|
||||
return fmt.Sprintf("m=%d,t=%d,p=%d", memory, time, parallelism)
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package password_test
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
|
||||
"messenger/internal/platform/password"
|
||||
)
|
||||
|
||||
func TestHashVerifiesOnlyTheOriginalPassword(t *testing.T) {
|
||||
for _, plain := range []string{
|
||||
"correct horse battery staple",
|
||||
"с:двоеточием:и кириллицей",
|
||||
"emoji 👋👋👋 and : colon",
|
||||
} {
|
||||
encoded := password.Hash(plain)
|
||||
ok, err := password.Verify(encoded, plain)
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("Verify(%q) = %v, %v; want true", plain, ok, err)
|
||||
}
|
||||
ok, err = password.Verify(encoded, plain+"x")
|
||||
if err != nil || ok {
|
||||
t.Fatalf("Verify(wrong) = %v, %v; want false", ok, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestHashIsSaltedPHCString(t *testing.T) {
|
||||
a, b := password.Hash("same password"), password.Hash("same password")
|
||||
if a == b {
|
||||
t.Fatal("two hashes of one password are equal: salt is missing")
|
||||
}
|
||||
if !strings.HasPrefix(a, "$argon2id$v=19$m=19456,t=2,p=1$") {
|
||||
t.Fatalf("unexpected encoding %q", a)
|
||||
}
|
||||
if strings.Contains(a, "same password") {
|
||||
t.Fatal("hash contains the plaintext")
|
||||
}
|
||||
}
|
||||
|
||||
// A hash made with other parameters must still verify: parameters travel in
|
||||
// the encoded string, so they can be raised without invalidating old hashes.
|
||||
func TestVerifyUsesParametersFromTheEncoding(t *testing.T) {
|
||||
salt := make([]byte, 16)
|
||||
_, _ = rand.Read(salt)
|
||||
key := argon2.IDKey([]byte("legacy password"), salt, 1, 8*1024, 2, 32)
|
||||
b64 := base64.RawStdEncoding
|
||||
encoded := fmt.Sprintf("$argon2id$v=19$m=8192,t=1,p=2$%s$%s", b64.EncodeToString(salt), b64.EncodeToString(key))
|
||||
|
||||
ok, err := password.Verify(encoded, "legacy password")
|
||||
if err != nil || !ok {
|
||||
t.Fatalf("Verify = %v, %v; want true", ok, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyRejectsMalformedEncoding(t *testing.T) {
|
||||
valid := password.Hash("whatever password")
|
||||
parts := strings.Split(valid, "$")
|
||||
for name, encoded := range map[string]string{
|
||||
"empty": "",
|
||||
"wrong algo": strings.Replace(valid, "argon2id", "argon2i", 1),
|
||||
"wrong version": strings.Replace(valid, "v=19", "v=16", 1),
|
||||
"bad params": strings.Replace(valid, "m=19456,t=2,p=1", "m=x,t=2,p=1", 1),
|
||||
"zero params": strings.Replace(valid, "m=19456,t=2,p=1", "m=19456,t=0,p=1", 1),
|
||||
"bad salt": strings.Join([]string{"", parts[1], parts[2], parts[3], "!!!", parts[5]}, "$"),
|
||||
"bad key": strings.Join([]string{"", parts[1], parts[2], parts[3], parts[4], "!!!"}, "$"),
|
||||
"missing fields": strings.Join(parts[:5], "$"),
|
||||
} {
|
||||
if _, err := password.Verify(encoded, "whatever password"); err == nil {
|
||||
t.Errorf("%s: Verify accepted %q", name, encoded)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
// Package postgres opens the connection pool and applies the schema.
|
||||
//
|
||||
// Server-side timeouts are constants rather than settings: they bound how
|
||||
// long one request can hold a connection, and the request deadline of the API
|
||||
// is chosen against them.
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/pressly/goose/v3"
|
||||
"github.com/pressly/goose/v3/lock"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/migrations"
|
||||
)
|
||||
|
||||
const (
|
||||
connectTimeout = time.Second
|
||||
statementTimeout = 5 * time.Second
|
||||
idleInTxTimeout = 10 * time.Second
|
||||
)
|
||||
|
||||
const codeUniqueViolation = "23505"
|
||||
|
||||
func NewPool(ctx context.Context, dsn string, maxConns int32) (*pgxpool.Pool, error) {
|
||||
cfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse database url: %w", err)
|
||||
}
|
||||
cfg.MaxConns = maxConns
|
||||
cfg.ConnConfig.ConnectTimeout = connectTimeout
|
||||
// Unlike net.Dialer, pgx resolves the host before ConnectTimeout starts.
|
||||
// Docker DNS takes seconds to give up on a stopped container: unbounded,
|
||||
// every request would wait out its deadline and log only "context
|
||||
// deadline exceeded" instead of the failed lookup.
|
||||
cfg.ConnConfig.LookupFunc = func(ctx context.Context, host string) ([]string, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, connectTimeout)
|
||||
defer cancel()
|
||||
return net.DefaultResolver.LookupHost(ctx, host)
|
||||
}
|
||||
cfg.ConnConfig.RuntimeParams["statement_timeout"] = strconv.FormatInt(statementTimeout.Milliseconds(), 10)
|
||||
cfg.ConnConfig.RuntimeParams["idle_in_transaction_session_timeout"] = strconv.FormatInt(idleInTxTimeout.Milliseconds(), 10)
|
||||
// The application keeps every time in UTC; pgx would otherwise scan
|
||||
// timestamptz into time.Local.
|
||||
cfg.AfterConnect = func(_ context.Context, conn *pgx.Conn) error {
|
||||
conn.TypeMap().RegisterType(&pgtype.Type{
|
||||
Name: "timestamptz",
|
||||
OID: pgtype.TimestamptzOID,
|
||||
Codec: &pgtype.TimestamptzCodec{ScanLocation: time.UTC},
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create pool: %w", err)
|
||||
}
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping database: %w", err)
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
// Migrate applies pending migrations and returns their versions; a session
|
||||
// advisory lock makes overlapping runs wait for each other.
|
||||
func Migrate(ctx context.Context, pool *pgxpool.Pool) ([]int64, error) {
|
||||
locker, err := lock.NewPostgresSessionLocker()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("migration lock: %w", err)
|
||||
}
|
||||
db := stdlib.OpenDBFromPool(pool)
|
||||
provider, err := goose.NewProvider(goose.DialectPostgres, db, migrations.FS, goose.WithSessionLocker(locker))
|
||||
if err != nil {
|
||||
db.Close()
|
||||
return nil, fmt.Errorf("load migrations: %w", err)
|
||||
}
|
||||
defer provider.Close()
|
||||
results, err := provider.Up(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("apply migrations: %w", err)
|
||||
}
|
||||
applied := make([]int64, 0, len(results))
|
||||
for _, r := range results {
|
||||
applied = append(applied, r.Source.Version)
|
||||
}
|
||||
return applied, nil
|
||||
}
|
||||
|
||||
// Classify marks a failure to reach the database as apperr.KindUnavailable,
|
||||
// which the API answers with 503 instead of 500; any other error is returned
|
||||
// unchanged. Unreachable means: the connection could not be made or broke,
|
||||
// the request deadline passed, or the server refused work (PostgreSQL error
|
||||
// classes 08 connection exception, 53 insufficient resources, 57 operator
|
||||
// intervention such as shutdown or statement timeout).
|
||||
func Classify(err error) error {
|
||||
if err == nil || !unreachable(err) {
|
||||
return err
|
||||
}
|
||||
return apperr.Wrap(apperr.KindUnavailable, "database unavailable", err)
|
||||
}
|
||||
|
||||
func unreachable(err error) bool {
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok {
|
||||
switch class := pgErr.Code[:min(2, len(pgErr.Code))]; class {
|
||||
case "08", "53", "57":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
if _, ok := errors.AsType[*pgconn.ConnectError](err); ok {
|
||||
return true
|
||||
}
|
||||
if _, ok := errors.AsType[net.Error](err); ok {
|
||||
return true
|
||||
}
|
||||
return errors.Is(err, context.DeadlineExceeded) ||
|
||||
errors.Is(err, context.Canceled) ||
|
||||
errors.Is(err, io.EOF) ||
|
||||
errors.Is(err, io.ErrUnexpectedEOF) ||
|
||||
errors.Is(err, net.ErrClosed) ||
|
||||
pgconn.Timeout(err) ||
|
||||
pgconn.SafeToRetry(err)
|
||||
}
|
||||
|
||||
// IsUniqueViolation reports whether err is a unique violation of the named
|
||||
// constraint.
|
||||
func IsUniqueViolation(err error, constraint string) bool {
|
||||
pgErr, ok := errors.AsType[*pgconn.PgError](err)
|
||||
return ok && pgErr.Code == codeUniqueViolation && pgErr.ConstraintName == constraint
|
||||
}
|
||||
@@ -0,0 +1,212 @@
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"messenger/internal/platform/apperr"
|
||||
"messenger/internal/platform/postgres"
|
||||
"messenger/internal/testenv"
|
||||
"messenger/migrations"
|
||||
)
|
||||
|
||||
var db *testenv.DB
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
var err error
|
||||
db, err = testenv.StartPostgres(context.Background())
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, err)
|
||||
os.Exit(1)
|
||||
}
|
||||
code := m.Run()
|
||||
db.Close()
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
func TestPoolScansTimestamptzInUTC(t *testing.T) {
|
||||
var got time.Time
|
||||
if err := db.Pool.QueryRow(context.Background(), `SELECT now()`).Scan(&got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got.Location() != time.UTC {
|
||||
t.Fatalf("timestamptz scanned in %v, want UTC", got.Location())
|
||||
}
|
||||
}
|
||||
|
||||
func TestMigrateIsRepeatable(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
applied, err := postgres.Migrate(ctx, db.Pool)
|
||||
if err != nil {
|
||||
t.Fatalf("second migrate: %v", err)
|
||||
}
|
||||
if len(applied) != 0 {
|
||||
t.Fatalf("second migrate applied %v, want nothing", applied)
|
||||
}
|
||||
var version int64
|
||||
if err := db.Pool.QueryRow(ctx, `SELECT max(version_id) FROM goose_db_version`).Scan(&version); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
files, err := fs.Glob(migrations.FS, "*.sql")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if version != int64(len(files)) {
|
||||
t.Fatalf("schema version = %d, want %d (one per migration file)", version, len(files))
|
||||
}
|
||||
for _, table := range []string{"users", "chats", "chat_members", "messages", "message_idempotency_keys"} {
|
||||
var exists bool
|
||||
if err := db.Pool.QueryRow(ctx, `SELECT to_regclass('public.' || $1) IS NOT NULL`, table).Scan(&exists); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !exists {
|
||||
t.Fatalf("table %s is missing", table)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolAppliesLimitsAndTimeouts(t *testing.T) {
|
||||
if got := db.Pool.Config().MaxConns; got != 10 {
|
||||
t.Fatalf("MaxConns = %d, want 10", got)
|
||||
}
|
||||
if got := db.Pool.Config().ConnConfig.ConnectTimeout; got != time.Second {
|
||||
t.Fatalf("ConnectTimeout = %v, want 1s", got)
|
||||
}
|
||||
ctx := context.Background()
|
||||
for setting, want := range map[string]string{
|
||||
"statement_timeout": "5s",
|
||||
"idle_in_transaction_session_timeout": "10s",
|
||||
} {
|
||||
var got string
|
||||
if err := db.Pool.QueryRow(ctx, "SHOW "+setting).Scan(&got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != want {
|
||||
t.Fatalf("%s = %q, want %q", setting, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetEmptiesEveryTableButKeepsSchemaVersion(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
_, err := db.Pool.Exec(ctx, `
|
||||
WITH u AS (
|
||||
INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ('0190f1d2-0000-7000-8000-000000000001', 'reset_check', 'Reset', 'x', now())
|
||||
RETURNING id
|
||||
), c AS (
|
||||
INSERT INTO chats (id, title, created_at)
|
||||
VALUES ('0190f1d2-0000-7000-8000-000000000002', 'Reset', now())
|
||||
RETURNING id
|
||||
), m AS (
|
||||
INSERT INTO chat_members (chat_id, user_id) SELECT c.id, u.id FROM c, u
|
||||
)
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
SELECT '0190f1d2-0000-7000-8000-000000000003', c.id, u.id, 'hi', now() FROM c, u`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
db.Reset(t)
|
||||
|
||||
for _, table := range []string{"users", "chats", "chat_members", "messages"} {
|
||||
var n int
|
||||
if err := db.Pool.QueryRow(ctx, "SELECT count(*) FROM "+table).Scan(&n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n != 0 {
|
||||
t.Fatalf("%s has %d rows after Reset", table, n)
|
||||
}
|
||||
}
|
||||
var versions int
|
||||
if err := db.Pool.QueryRow(ctx, `SELECT count(*) FROM goose_db_version`).Scan(&versions); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if versions == 0 {
|
||||
t.Fatal("Reset wiped the schema version table")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsUniqueViolation(t *testing.T) {
|
||||
db.Reset(t)
|
||||
ctx := context.Background()
|
||||
insert := `INSERT INTO users (id, username, display_name, password_hash, created_at)
|
||||
VALUES ($1, 'taken', 'Taken', 'x', now())`
|
||||
if _, err := db.Pool.Exec(ctx, insert, "0190f1d2-0000-7000-8000-000000000011"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, dup := db.Pool.Exec(ctx, insert, "0190f1d2-0000-7000-8000-000000000012")
|
||||
if dup == nil {
|
||||
t.Fatal("duplicate username was accepted")
|
||||
}
|
||||
|
||||
if !postgres.IsUniqueViolation(dup, "users_username_key") {
|
||||
t.Fatalf("not recognised as a username violation: %v", dup)
|
||||
}
|
||||
if postgres.IsUniqueViolation(dup, "some_other_key") {
|
||||
t.Fatal("matched a different constraint")
|
||||
}
|
||||
if postgres.IsUniqueViolation(fmt.Errorf("wrapped: %w", dup), "users_username_key") == false {
|
||||
t.Fatal("wrapped error not recognised")
|
||||
}
|
||||
if postgres.IsUniqueViolation(errors.New("plain"), "users_username_key") || postgres.IsUniqueViolation(nil, "users_username_key") {
|
||||
t.Fatal("non-database error recognised as a violation")
|
||||
}
|
||||
}
|
||||
|
||||
func TestClassifyMarksUnreachableDatabaseAsUnavailable(t *testing.T) {
|
||||
unavailable := map[string]error{
|
||||
"admin shutdown": &pgconn.PgError{Code: "57P01"},
|
||||
"statement timeout": &pgconn.PgError{Code: "57014"},
|
||||
"connection failure": &pgconn.PgError{Code: "08006"},
|
||||
"too many connections": &pgconn.PgError{Code: "53300"},
|
||||
"deadline": fmt.Errorf("query: %w", context.DeadlineExceeded),
|
||||
"network": &net.OpError{Op: "read", Net: "tcp", Err: errors.New("connection reset")},
|
||||
"unexpected eof": fmt.Errorf("read: %w", io.ErrUnexpectedEOF),
|
||||
}
|
||||
for name, err := range unavailable {
|
||||
got := postgres.Classify(err)
|
||||
if apperr.KindOf(got) != apperr.KindUnavailable || !errors.Is(got, err) {
|
||||
t.Errorf("%s: Classify = %v (kind %v), want KindUnavailable keeping the cause", name, got, apperr.KindOf(got))
|
||||
}
|
||||
}
|
||||
for name, err := range map[string]error{
|
||||
"unique violation": &pgconn.PgError{Code: "23505"},
|
||||
"plain": errors.New("boom"),
|
||||
"nil": nil,
|
||||
} {
|
||||
if got := postgres.Classify(err); got != err {
|
||||
t.Errorf("%s: Classify = %v, want the error unchanged", name, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewPoolUsesTheRequestedSize(t *testing.T) {
|
||||
pool, err := postgres.NewPool(context.Background(), db.DSN, 3)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer pool.Close()
|
||||
if got := pool.Config().MaxConns; got != 3 {
|
||||
t.Fatalf("MaxConns = %d, want 3", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestClassifyRealConnectFailure(t *testing.T) {
|
||||
_, err := postgres.NewPool(context.Background(), "postgres://u:p@127.0.0.1:1/db?connect_timeout=1", 1)
|
||||
if err == nil {
|
||||
t.Fatal("NewPool to a closed port must fail")
|
||||
}
|
||||
if apperr.KindOf(postgres.Classify(err)) != apperr.KindUnavailable {
|
||||
t.Fatalf("connect failure classified as %v: %v", apperr.KindOf(postgres.Classify(err)), err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
// Package valkey connects to the Valkey session store.
|
||||
//
|
||||
// Timeouts are constants: every authenticated request reads a session, so
|
||||
// they bound how long a request can wait when the store is slow. Command
|
||||
// retries are disabled and a connection is dialled once for the same reason:
|
||||
// a request that cannot reach the store fails fast with 503 instead of
|
||||
// waiting through a backoff. On the compose stand Docker DNS takes seconds
|
||||
// to give up on a stopped container, so one dial attempt is already bounded
|
||||
// only by dialTimeout.
|
||||
package valkey
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
const (
|
||||
dialTimeout = time.Second
|
||||
ioTimeout = time.Second
|
||||
poolSize = 10
|
||||
noRetries = -1
|
||||
singleAttempt = 1
|
||||
)
|
||||
|
||||
// NewClient connects to url (redis:// scheme) and pings the server. Errors
|
||||
// never include the URL, which carries the password.
|
||||
func NewClient(ctx context.Context, url string) (*redis.Client, error) {
|
||||
opts, err := redis.ParseURL(url)
|
||||
if err != nil {
|
||||
return nil, errors.New("session store url is invalid")
|
||||
}
|
||||
opts.DialTimeout = dialTimeout
|
||||
opts.ReadTimeout = ioTimeout
|
||||
opts.WriteTimeout = ioTimeout
|
||||
opts.PoolSize = poolSize
|
||||
opts.MaxRetries = noRetries
|
||||
opts.DialerRetries = singleAttempt
|
||||
|
||||
client := redis.NewClient(opts)
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
_ = client.Close()
|
||||
return nil, fmt.Errorf("ping session store at %s: %w", opts.Addr, err)
|
||||
}
|
||||
return client, nil
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package valkey_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/internal/platform/valkey"
|
||||
"messenger/internal/testenv"
|
||||
)
|
||||
|
||||
func TestNewClientPingsAndBoundsWaiting(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
kv, err := testenv.StartValkey(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer kv.Close()
|
||||
|
||||
client, err := valkey.NewClient(ctx, kv.URL)
|
||||
if err != nil {
|
||||
t.Fatalf("NewClient: %v", err)
|
||||
}
|
||||
defer client.Close()
|
||||
opts := client.Options()
|
||||
if opts.DialTimeout != time.Second || opts.ReadTimeout != time.Second || opts.WriteTimeout != time.Second {
|
||||
t.Fatalf("timeouts = %v/%v/%v, want 1s each", opts.DialTimeout, opts.ReadTimeout, opts.WriteTimeout)
|
||||
}
|
||||
// go-redis dials up to five times by default; with Docker DNS taking
|
||||
// seconds to give up on a stopped container that alone would exceed the
|
||||
// request deadline.
|
||||
if opts.DialerRetries != 1 {
|
||||
t.Fatalf("DialerRetries = %d, want a single dial attempt", opts.DialerRetries)
|
||||
}
|
||||
// go-redis stores the requested -1 ("no retries") as 0 after init; its
|
||||
// default would be 3.
|
||||
if opts.PoolSize != 10 || opts.MaxRetries != 0 {
|
||||
t.Fatalf("PoolSize = %d, MaxRetries = %d; want 10 and 0 (fail fast)", opts.PoolSize, opts.MaxRetries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewClientErrorsNeverEchoTheURL(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
for name, url := range map[string]string{
|
||||
"malformed": "redis://:s3cret@host:port/x",
|
||||
"unreachable": "redis://:s3cret@127.0.0.1:1/0",
|
||||
} {
|
||||
_, err := valkey.NewClient(ctx, url)
|
||||
if err == nil {
|
||||
t.Fatalf("%s: want error", name)
|
||||
}
|
||||
if strings.Contains(err.Error(), "s3cret") {
|
||||
t.Fatalf("%s: error leaks the password: %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user