Перенесите реализацию ЛР 4 на стенд ЛР 5

This commit is contained in:
2026-11-18 15:33:31 +03:00
parent 276dbdad8a
commit 911d97a77a
153 changed files with 17451 additions and 1 deletions
+54
View File
@@ -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) }
+49
View File
@@ -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())
}
}
+200
View File
@@ -0,0 +1,200 @@
// 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"
)
// Allow a 30s binary request, its independent 3s cleanup, and 5s margin.
const defaultShutdownTimeout = 38 * time.Second
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
S3 S3
}
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: defaultShutdownTimeout,
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 = LoadDatabaseURL(lookup); err != nil {
return Config{}, err
}
if cfg.SessionStoreURL, err = secret(lookup, "SESSION_STORE_URL_FILE"); err != nil {
return Config{}, err
}
if _, ok := lookup("S3_ENDPOINT"); ok {
if cfg.S3, err = LoadS3(lookup); 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 = LoadDatabaseURL(lookup); err != nil {
return Migrate{}, err
}
return cfg, nil
}
func LoadDatabaseURL(lookup Lookup) (string, error) {
return secret(lookup, "DATABASE_URL_FILE")
}
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))
}
+190
View File
@@ -0,0 +1,190 @@
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 != 38*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 TestDefaultShutdownTimeoutCoversBinaryLifecycle(t *testing.T) {
cfg, err := config.Load(env(required(t, nil)))
if err != nil {
t.Fatal(err)
}
// Binary requests can use 30s, followed by 3s independent cleanup. Keep
// another 5s for shutdown scheduling and closing the remaining resources.
budget := 30*time.Second + 3*time.Second + 5*time.Second
if cfg.ShutdownTimeout < budget {
t.Fatalf("default shutdown budget %v cannot cover binary request and cleanup budget %v", cfg.ShutdownTimeout, budget)
}
}
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)
}
}
+55
View File
@@ -0,0 +1,55 @@
package config
import (
"fmt"
"strconv"
)
type S3 struct {
Endpoint, Region, Bucket string
AccessKey, SecretKey string
MaxBytes, MaxPixels int64
}
func LoadS3(lookup Lookup) (S3, error) {
cfg := S3{Endpoint: "http://s3:8333", Region: "us-east-1", Bucket: "messenger-attachments", MaxBytes: 10485760, MaxPixels: 40000000}
for key, dest := range map[string]*string{"S3_ENDPOINT": &cfg.Endpoint, "S3_REGION": &cfg.Region, "S3_BUCKET": &cfg.Bucket} {
if v, ok := lookup(key); ok {
*dest = v
}
}
var err error
if cfg.AccessKey, err = secret(lookup, "S3_ACCESS_KEY_ID_FILE"); err != nil {
return S3{}, err
}
if cfg.SecretKey, err = secret(lookup, "S3_SECRET_ACCESS_KEY_FILE"); err != nil {
return S3{}, err
}
for _, p := range []struct {
key string
dest *int64
max int64
}{{"MAX_UPLOAD_BYTES", &cfg.MaxBytes, 10485760}, {"MAX_IMAGE_PIXELS", &cfg.MaxPixels, 40000000}} {
if v, ok := lookup(p.key); ok {
n, e := strconv.ParseInt(v, 10, 64)
if e != nil || n < 1 || n > p.max {
return S3{}, fmt.Errorf("%s must be between 1 and %d", p.key, p.max)
}
*p.dest = n
}
}
return cfg, nil
}
// ReconcileS3 selects the separate listing identity used by background scans.
func ReconcileS3(lookup Lookup) Lookup {
return func(key string) (string, bool) {
if key == "S3_ACCESS_KEY_ID_FILE" {
return lookup("S3_RECONCILE_ACCESS_KEY_ID_FILE")
}
if key == "S3_SECRET_ACCESS_KEY_FILE" {
return lookup("S3_RECONCILE_SECRET_ACCESS_KEY_FILE")
}
return lookup(key)
}
}
+27
View File
@@ -0,0 +1,27 @@
package config_test
import (
"messenger/internal/platform/config"
"testing"
)
func TestS3LimitsAndSecretFiles(t *testing.T) {
values := map[string]string{"S3_ACCESS_KEY_ID_FILE": secretFile(t, "access\n"), "S3_SECRET_ACCESS_KEY_FILE": secretFile(t, "private\n")}
cfg, err := config.LoadS3(env(values))
if err != nil {
t.Fatal(err)
}
if cfg.AccessKey != "access" || cfg.SecretKey != "private" || cfg.MaxBytes != 10485760 || cfg.MaxPixels != 40000000 {
t.Fatal("S3 defaults or secret trimming broken")
}
for _, tc := range []struct{ k, v string }{{"MAX_UPLOAD_BYTES", "0"}, {"MAX_UPLOAD_BYTES", "10485761"}, {"MAX_IMAGE_PIXELS", "40000001"}, {"MAX_IMAGE_PIXELS", "x"}} {
v := map[string]string{}
for k, x := range values {
v[k] = x
}
v[tc.k] = tc.v
if _, err := config.LoadS3(env(v)); err == nil {
t.Fatalf("accepted %s=%s", tc.k, tc.v)
}
}
}
+70
View File
@@ -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)
}
+50
View File
@@ -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()
}
+409
View File
@@ -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]
}
+42
View File
@@ -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)
}
}
+136
View File
@@ -0,0 +1,136 @@
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) {
// The authenticated binary handler installs its own 10 MiB limit.
if c.Request.Method == http.MethodPost && c.FullPath() == "/api/v1/chats/:chat_id/attachments" {
c.Next()
return
}
if c.Request.Body != nil {
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBytes)
}
c.Next()
}
}
+87
View File
@@ -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")
}
+56
View File
@@ -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
}
+84
View File
@@ -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)
}
}
+63
View File
@@ -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)
}
}
}
+41
View File
@@ -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
}
+60
View File
@@ -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)
}
}
+74
View File
@@ -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, &parallelism); 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)
}
}
}
+143
View File
@@ -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
}
+212
View File
@@ -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)
}
}
+143
View File
@@ -0,0 +1,143 @@
package s3store_test
import (
"context"
"errors"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/http/httputil"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
"messenger/internal/platform/config"
"messenger/internal/platform/s3store"
)
func TestBootstrapWaitsForRetainedBytesAndCleansWriteProbe(t *testing.T) {
var ready atomic.Bool
var reads atomic.Int32
var mu sync.Mutex
objects := map[string]string{".health/storage-v1": "messenger s3 readiness v1\n"}
var freshReads, deleted int
requested := make(chan struct{}, 1)
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
key := strings.TrimPrefix(r.URL.Path, "/attachments/")
if r.Method == "PUT" && strings.TrimSuffix(r.URL.Path, "/") == "/attachments" {
w.WriteHeader(200)
return
}
if r.Method == "GET" && key == ".health/storage-v1" {
reads.Add(1)
if !ready.Load() {
select {
case requested <- struct{}{}:
default:
}
w.WriteHeader(500)
io.WriteString(w, `<Error><Code>InternalError</Code><Message>volume not registered</Message></Error>`)
return
}
}
mu.Lock()
defer mu.Unlock()
switch r.Method {
case "GET":
value, ok := objects[key]
if !ok {
w.WriteHeader(404)
io.WriteString(w, `<Error><Code>NoSuchKey</Code></Error>`)
return
}
if key != ".health/storage-v1" {
freshReads++
}
w.Header().Set("ETag", `"probe"`)
w.Header().Set("Last-Modified", "Mon, 16 Nov 2026 08:00:00 GMT")
w.Header().Set("Content-Length", fmt.Sprint(len(value)))
io.WriteString(w, value)
case "PUT":
var body io.Reader = r.Body
if strings.Contains(r.Header.Get("Content-Encoding"), "aws-chunked") {
body = httputil.NewChunkedReader(body)
}
data, err := io.ReadAll(io.LimitReader(body, 1024))
if err != nil {
t.Error(err)
w.WriteHeader(400)
return
}
objects[key] = string(data)
w.Header().Set("ETag", `"probe"`)
case "DELETE":
if key == ".health/storage-v1" {
t.Error("deleted retained readiness marker")
}
delete(objects, key)
deleted++
w.WriteHeader(204)
default:
t.Errorf("unexpected storage probe: %s %s", r.Method, r.URL)
w.WriteHeader(400)
}
}))
defer server.Close()
s, err := s3store.New(config.S3{Endpoint: server.URL, Region: "us-east-1", Bucket: "attachments", AccessKey: "access", SecretKey: "secret"})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
done := make(chan error, 1)
go func() { done <- s.Bootstrap(ctx) }()
select {
case err := <-done:
t.Fatalf("bootstrap returned before reading retained storage: %v", err)
case <-requested:
case <-ctx.Done():
t.Fatal(ctx.Err())
}
select {
case err := <-done:
t.Fatalf("bootstrap accepted unavailable retained storage: %v", err)
case <-time.After(40 * time.Millisecond):
}
ready.Store(true)
if err := <-done; err != nil {
t.Fatal(err)
}
mu.Lock()
defer mu.Unlock()
if reads.Load() < 2 || freshReads == 0 || deleted == 0 || len(objects) != 1 {
t.Fatalf("incomplete readiness proof: retainedReads=%d freshReads=%d deletes=%d remaining=%d", reads.Load(), freshReads, deleted, len(objects))
}
}
func TestBootstrapDeadlineIncludesStorageReadiness(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method == "PUT" && strings.TrimSuffix(r.URL.Path, "/") == "/attachments" {
w.WriteHeader(200)
return
}
w.WriteHeader(503)
io.WriteString(w, `<Error><Code>ServiceUnavailable</Code><Message>volume not registered</Message></Error>`)
}))
defer server.Close()
s, err := s3store.New(config.S3{Endpoint: server.URL, Region: "us-east-1", Bucket: "attachments", AccessKey: "access", SecretKey: "secret"})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
started := time.Now()
if err := s.Bootstrap(ctx); !errors.Is(err, context.DeadlineExceeded) {
t.Fatalf("storage readiness escaped its deadline: %v", err)
}
if time.Since(started) > time.Second {
t.Fatal("readiness did not honor caller deadline")
}
}
@@ -0,0 +1,271 @@
package s3store_test
import (
"context"
"errors"
"io"
"net"
"net/http"
"strings"
"testing"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/credentials/insecure"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/types/known/emptypb"
"messenger/internal/attachment"
"messenger/internal/platform/config"
"messenger/internal/platform/s3store"
"messenger/internal/testenv"
)
func TestSeaweedStore(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Minute)
defer cancel()
s, err := testenv.StartS3(ctx)
if err != nil {
t.Fatal(err)
}
defer s.Close()
newClient := func(access, secret string) *minio.Client {
t.Helper()
c, err := minio.New(strings.TrimPrefix(s.Endpoint, "http://"), &minio.Options{Creds: credentials.NewStaticV4(access, secret, ""), Region: s.Region, BucketLookup: minio.BucketLookupPath, MaxRetries: 1})
if err != nil {
t.Fatal(err)
}
return c
}
api := newClient(s.APIAccessKey, s.APISecretKey)
admin := newClient(s.AdminAccessKey, s.AdminSecretKey)
denied := func(t *testing.T, err error) {
t.Helper()
var response minio.ErrorResponse
if !errors.As(err, &response) || response.StatusCode != http.StatusForbidden {
t.Fatalf("expected access denied, got %v", err)
}
}
t.Run("remote gRPC cannot modify identity cache", func(t *testing.T) {
conn, err := grpc.NewClient("passthrough:///"+s.GRPCAddress, grpc.WithTransportCredentials(insecure.NewCredentials()),
grpc.WithContextDialer(func(ctx context.Context, address string) (net.Conn, error) {
return (&net.Dialer{Timeout: time.Second}).DialContext(ctx, "tcp", address)
}))
if err != nil {
t.Fatal(err)
}
defer conn.Close()
opCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
err = conn.Invoke(opCtx, "/messaging_pb.SeaweedS3IamCache/PutIdentity", &emptypb.Empty{}, &emptypb.Empty{})
if code := status.Code(err); code != codes.PermissionDenied && code != codes.Unauthenticated {
t.Fatalf("remote IAM mutation was not rejected before argument validation: %v", err)
}
})
t.Run("bootstrap is idempotent and API cannot administer", func(t *testing.T) {
if err := s.Admin.Bootstrap(ctx); err != nil {
t.Fatal(err)
}
denied(t, s.APIStore.Bootstrap(ctx))
denied(t, api.MakeBucket(ctx, "forbidden-bucket", minio.MakeBucketOptions{Region: s.Region}))
denied(t, api.RemoveBucket(ctx, s.Bucket))
buckets, err := api.ListBuckets(ctx)
// SeaweedFS returns a filtered empty result for an authenticated caller
// without List rights, rather than rejecting ListBuckets outright.
if err != nil || len(buckets) != 0 {
t.Fatalf("API enumerated buckets: count=%d error=%v", len(buckets), err)
}
_, err = s.APIStore.List(ctx, "", "", 1)
denied(t, err)
})
t.Run("known length nonseekable put copy stat and stream", func(t *testing.T) {
const payload = "nonseekable image payload"
r := struct{ io.Reader }{strings.NewReader(payload)}
started := time.Now()
if err := s.APIStore.Put(ctx, "staging/source", r, int64(len(payload)), "image/png"); err != nil {
t.Fatal(err)
}
t.Logf("cold first PUT: %s", time.Since(started))
if err := s.APIStore.Copy(ctx, "staging/source", "blobs/durable"); err != nil {
t.Fatal(err)
}
obj, err := s.APIStore.Stat(ctx, "blobs/durable")
if err != nil {
t.Fatal(err)
}
if obj.Key != "blobs/durable" || obj.Size != 25 || obj.Modified.IsZero() {
t.Fatalf("wrong metadata: %+v", obj)
}
body, err := s.APIStore.Open(ctx, "blobs/durable")
if err != nil {
t.Fatal(err)
}
b, err := io.ReadAll(body)
body.Close()
if err != nil {
t.Fatal(err)
}
if string(b) != payload {
t.Fatalf("wrong body: %q", b)
}
meta, err := api.StatObject(ctx, s.Bucket, "blobs/durable", minio.StatObjectOptions{})
if err != nil {
t.Fatal(err)
}
if meta.ContentType != "image/png" {
t.Fatalf("copy lost MIME: %s", meta.ContentType)
}
for range 2 {
if err := s.APIStore.Delete(ctx, "staging/source"); err != nil {
t.Fatal(err)
}
}
if _, err := s.APIStore.Stat(ctx, "staging/source"); !errors.Is(err, attachment.ErrObjectMissing) {
t.Fatalf("API delete did not remove staging: %v", err)
}
})
t.Run("anonymous get put head and listing are refused", func(t *testing.T) {
client := &http.Client{Timeout: 3 * time.Second}
defer client.CloseIdleConnections()
for _, tc := range []struct{ method, path string }{{"GET", "/"}, {"GET", "/" + s.Bucket + "?list-type=2"}, {"GET", "/" + s.Bucket + "/blobs/durable"}, {"HEAD", "/" + s.Bucket + "/blobs/durable"}, {"PUT", "/" + s.Bucket + "/anonymous"}} {
req, _ := http.NewRequestWithContext(ctx, tc.method, s.Endpoint+tc.path, strings.NewReader("x"))
resp, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
t.Fatalf("anonymous %s %s: %d", tc.method, tc.path, resp.StatusCode)
}
}
})
t.Run("identities cannot escape their bucket", func(t *testing.T) {
if err := admin.MakeBucket(ctx, "private-other", minio.MakeBucketOptions{Region: s.Region}); err != nil {
t.Fatal(err)
}
if _, err := admin.PutObject(ctx, "private-other", "secret", strings.NewReader("private"), 7, minio.PutObjectOptions{DisableMultipart: true}); err != nil {
t.Fatal(err)
}
for _, pair := range [][2]string{{s.APIAccessKey, s.APISecretKey}, {s.AccessKey, s.SecretKey}} {
outside, err := s3store.New(config.S3{Endpoint: s.Endpoint, Region: s.Region, Bucket: "private-other", AccessKey: pair[0], SecretKey: pair[1]})
if err != nil {
t.Fatal(err)
}
_, err = outside.Stat(ctx, "secret")
denied(t, err)
_, err = outside.Open(ctx, "secret")
denied(t, err)
denied(t, outside.Put(ctx, "secret", strings.NewReader("x"), 1, "image/png"))
denied(t, outside.Delete(ctx, "secret"))
_, err = outside.List(ctx, "", "", 1)
denied(t, err)
c := newClient(pair[0], pair[1])
_, err = c.CopyObject(ctx, minio.CopyDestOptions{Bucket: s.Bucket, Object: "blobs/stolen"}, minio.CopySrcOptions{Bucket: "private-other", Object: "secret"})
denied(t, err)
}
})
t.Run("exclusive lexicographic pages including absent cursor", func(t *testing.T) {
for _, key := range []string{"page/z", "page/a", "page/a/nested", "page/b", "page/c"} {
if err := s.Store.Put(ctx, key, strings.NewReader("x"), 1, "image/png"); err != nil {
t.Fatal(err)
}
}
var got []string
after := ""
for {
page, err := s.Store.List(ctx, "page/", after, 2)
if err != nil {
t.Fatal(err)
}
if len(page) == 0 {
break
}
for _, obj := range page {
if obj.Size != 1 || obj.Modified.IsZero() {
t.Fatalf("wrong list metadata: %+v", obj)
}
got = append(got, obj.Key)
}
after = page[len(page)-1].Key
if len(got) > 5 {
t.Fatal("pagination did not advance")
}
}
if strings.Join(got, ",") != "page/a,page/a/nested,page/b,page/c,page/z" {
t.Fatalf("wrong order: %v", got)
}
page, err := s.Store.List(ctx, "page/", "page/az", 2)
if err != nil {
t.Fatal(err)
}
if len(page) != 2 || page[0].Key != "page/b" || page[1].Key != "page/c" {
t.Fatalf("absent cursor: %+v", page)
}
})
t.Run("missing objects differ from bucket and permission failures", func(t *testing.T) {
if _, err := s.Store.Stat(ctx, "absent"); !errors.Is(err, attachment.ErrObjectMissing) {
t.Fatalf("stat missing: %v", err)
}
if _, err := s.Store.Open(ctx, "absent"); !errors.Is(err, attachment.ErrObjectMissing) {
t.Fatalf("open missing: %v", err)
}
if err := s.Store.Copy(ctx, "absent", "blobs/absent"); !errors.Is(err, attachment.ErrObjectMissing) {
t.Fatalf("copy missing: %v", err)
}
for range 2 {
if err := s.Store.Delete(ctx, "absent"); err != nil {
t.Fatal(err)
}
}
missingBucket, err := s3store.New(config.S3{Endpoint: s.Endpoint, Region: s.Region, Bucket: "absent-bucket", AccessKey: s.AdminAccessKey, SecretKey: s.AdminSecretKey})
if err != nil {
t.Fatal(err)
}
if _, err := missingBucket.Stat(ctx, "absent"); err == nil || errors.Is(err, attachment.ErrObjectMissing) {
t.Fatalf("missing bucket treated as missing object: %v", err)
}
})
t.Run("short readers are not successful uploads", func(t *testing.T) {
if err := s.Store.Put(ctx, "staging/short", struct{ io.Reader }{strings.NewReader("short")}, 100, "image/png"); err == nil {
t.Fatal("short body accepted")
}
})
t.Run("container replacement preserves volume data and authentication", func(t *testing.T) {
if err := s.Recreate(ctx); err != nil {
t.Fatal(err)
}
body, err := s.APIStore.Open(ctx, "blobs/durable")
if err != nil {
t.Fatal(err)
}
b, err := io.ReadAll(body)
body.Close()
if err != nil {
t.Fatal(err)
}
if string(b) != "nonseekable image payload" {
t.Fatalf("object lost on replacement: %q", b)
}
if _, err := s.Store.List(ctx, "page/", "", 2); err != nil {
t.Fatal(err)
}
})
t.Run("outage is bounded and never missing", func(t *testing.T) {
if err := s.Stop(ctx); err != nil {
t.Fatal(err)
}
opCtx, stop := context.WithTimeout(ctx, 150*time.Millisecond)
defer stop()
start := time.Now()
_, err := s.Store.Stat(opCtx, "blobs/durable")
if err == nil || errors.Is(err, attachment.ErrObjectMissing) {
t.Fatalf("outage treated as missing: %v", err)
}
if time.Since(start) > 2*time.Second {
t.Fatal("outage exceeded caller deadline")
}
})
}
+114
View File
@@ -0,0 +1,114 @@
package s3store
import (
"context"
"crypto/rand"
"errors"
"fmt"
"io"
"strings"
"time"
"github.com/minio/minio-go/v7"
"messenger/internal/attachment"
)
const (
storageMarkerKey = ".health/storage-v1"
storageMarkerBody = "messenger s3 readiness v1\n"
)
var errStorageMarker = errors.New("s3: storage readiness marker has unexpected contents")
// WaitReady is a startup barrier, deliberately separate from API readiness and
// ordinary object operations. Gateway authentication and bucket metadata can be
// available before the master elects its leader and registers retained volumes.
// Read the persistent marker before writing anything, then prove new writes,
// reads and deletes work. The marker lives outside the reconciler's namespaces.
func (s *Store) WaitReady(ctx context.Context) error {
if err := ctx.Err(); err != nil {
return err
}
readyCtx, cancel := context.WithTimeout(ctx, 60*time.Second)
defer cancel()
probeKey := ".health/check-" + rand.Text()
dirty := false
defer func() {
if dirty {
cleanupCtx, stop := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second)
defer stop()
_ = s.Delete(cleanupCtx, probeKey)
}
}()
ticker := time.NewTicker(200 * time.Millisecond)
defer ticker.Stop()
for {
err := s.checkStorage(readyCtx, probeKey, &dirty)
if err == nil {
return nil
}
if permanentStorageError(err) {
return err
}
select {
case <-readyCtx.Done():
return fmt.Errorf("s3: wait for readable and writable storage: %w (last probe: %v)", readyCtx.Err(), err)
case <-ticker.C:
}
}
}
func (s *Store) checkStorage(ctx context.Context, probeKey string, dirty *bool) error {
err := s.readStorageMarker(ctx, storageMarkerKey)
if errors.Is(err, attachment.ErrObjectMissing) {
// Only a genuinely absent marker permits its first creation. Never
// overwrite retained data to hide an unavailable volume or a bad marker.
if err := s.Put(ctx, storageMarkerKey, strings.NewReader(storageMarkerBody), int64(len(storageMarkerBody)), "application/octet-stream"); err != nil {
return err
}
err = s.readStorageMarker(ctx, storageMarkerKey)
}
if err != nil {
return err
}
*dirty = true
if err := s.Put(ctx, probeKey, strings.NewReader(storageMarkerBody), int64(len(storageMarkerBody)), "application/octet-stream"); err != nil {
return err
}
if err := s.readStorageMarker(ctx, probeKey); err != nil {
return err
}
if err := s.Delete(ctx, probeKey); err != nil {
return err
}
*dirty = false
return nil
}
func (s *Store) readStorageMarker(ctx context.Context, key string) error {
r, err := s.Open(ctx, key)
if err != nil {
return err
}
data, readErr := io.ReadAll(io.LimitReader(r, int64(len(storageMarkerBody))+1))
closeErr := r.Close()
if readErr != nil {
return readErr
}
if closeErr != nil {
return closeErr
}
if string(data) != storageMarkerBody {
return errStorageMarker
}
return nil
}
func permanentStorageError(err error) bool {
if errors.Is(err, errStorageMarker) {
return true
}
var response minio.ErrorResponse
return errors.As(err, &response) && response.StatusCode >= 400 && response.StatusCode < 500 && response.StatusCode != 408 && response.StatusCode != 429
}
@@ -0,0 +1,48 @@
package s3store_test
import (
"context"
"io"
"strings"
"testing"
"time"
"messenger/internal/testenv"
)
func TestRecreateReturnsWithRetainedObjectReadable(t *testing.T) {
// Three independent server replacements each have the production 60-second
// startup budget; no per-request transport timeout is changed by this test.
ctx, cancel := context.WithTimeout(context.Background(), 4*time.Minute)
defer cancel()
s, err := testenv.StartS3(ctx)
if err != nil {
t.Fatal(err)
}
defer s.Close()
defer func() {
if t.Failed() {
t.Log(s.Diagnostics(context.Background()))
}
}()
const payload = "retained storage readiness proof"
if err := s.Store.Put(ctx, "blobs/retained", strings.NewReader(payload), int64(len(payload)), "application/octet-stream"); err != nil {
t.Fatal(err)
}
for attempt := range 3 {
started := time.Now()
if err := s.Recreate(ctx); err != nil {
t.Fatal(err)
}
r, err := s.Store.Open(ctx, "blobs/retained")
if err != nil {
t.Fatalf("replacement %d returned before retained bytes were readable (%s): %v", attempt+1, time.Since(started), err)
}
data, err := io.ReadAll(r)
r.Close()
if err != nil || string(data) != payload {
t.Fatalf("replacement %d lost retained bytes: %q %v", attempt+1, data, err)
}
t.Logf("replacement %d ready and retained bytes verified in %s", attempt+1, time.Since(started))
}
}
+201
View File
@@ -0,0 +1,201 @@
package s3store
import (
"context"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"strings"
"time"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"github.com/minio/minio-go/v7/pkg/s3utils"
"messenger/internal/attachment"
"messenger/internal/platform/config"
)
const MaxPageSize = 500
const codeBucketAlreadyOwnedByYou = "BucketAlreadyOwnedByYou"
type Store struct {
client *minio.Core
region string
bucket string
}
var _ attachment.Blobs = (*Store)(nil)
// New validates configuration without contacting S3, so text-only service startup
// and readiness do not depend on object storage being reachable.
func New(cfg config.S3) (*Store, error) {
u, err := url.Parse(cfg.Endpoint)
if err != nil || u == nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.User != nil || (u.Path != "" && u.Path != "/") || u.RawQuery != "" || u.ForceQuery || u.Fragment != "" {
return nil, errors.New("s3: endpoint must be an http(s) origin without credentials, query or fragment")
}
if strings.TrimSpace(cfg.Region) == "" || cfg.AccessKey == "" || cfg.SecretKey == "" {
return nil, errors.New("s3: region and credentials are required")
}
if err := s3utils.CheckValidBucketNameStrict(cfg.Bucket); err != nil {
return nil, fmt.Errorf("s3: invalid bucket: %w", err)
}
transport := &http.Transport{
Proxy: http.ProxyFromEnvironment,
DialContext: (&net.Dialer{Timeout: time.Second, KeepAlive: 30 * time.Second}).DialContext,
TLSHandshakeTimeout: time.Second,
// The first write can wait for the single master's election and volume
// creation. The caller's shorter context still takes precedence.
ResponseHeaderTimeout: 30 * time.Second,
ExpectContinueTimeout: time.Second,
IdleConnTimeout: 30 * time.Second,
MaxIdleConns: 64,
MaxIdleConnsPerHost: 32,
MaxConnsPerHost: 64,
DisableCompression: true,
}
client, err := minio.NewCore(u.Host, &minio.Options{
Creds: credentials.NewStaticV4(cfg.AccessKey, cfg.SecretKey, ""),
Secure: u.Scheme == "https",
Region: cfg.Region,
BucketLookup: minio.BucketLookupPath,
Transport: transport,
// A consumed upload stream cannot be replayed. Let the caller decide
// whether to retry a whole operation within its own deadline.
MaxRetries: 1,
})
if err != nil {
return nil, fmt.Errorf("s3: client: %w", err)
}
return &Store{client: client, region: cfg.Region, bucket: cfg.Bucket}, nil
}
// Bootstrap is used only by the admin init command, never by API startup.
func (s *Store) Bootstrap(ctx context.Context) error {
if err := ctx.Err(); err != nil {
return err
}
err := s.client.MakeBucket(ctx, s.bucket, minio.MakeBucketOptions{Region: s.region})
code := minio.ToErrorResponse(err).Code
if err != nil && code != codeBucketAlreadyOwnedByYou {
return wrap("create bucket", err)
}
return s.WaitReady(ctx)
}
func (s *Store) Put(ctx context.Context, key string, r io.Reader, size int64, mime string) error {
if err := ctx.Err(); err != nil {
return err
}
if size < 0 || r == nil {
return errors.New("s3: PUT requires a reader and known nonnegative length")
}
_, err := s.client.PutObject(ctx, s.bucket, key, r, size, "", "", minio.PutObjectOptions{
ContentType: mime,
DisableMultipart: true,
})
return wrap("put object", err)
}
func (s *Store) Open(ctx context.Context, key string) (io.ReadCloser, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
// Core.GetObject performs GET eagerly and returns the streaming body;
// Client.GetObject is lazy and would defer missing/access errors to Read.
r, _, _, err := s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
if err != nil {
return nil, wrap("open object", err)
}
return r, nil
}
func (s *Store) Stat(ctx context.Context, key string) (attachment.Object, error) {
if err := ctx.Err(); err != nil {
return attachment.Object{}, err
}
obj, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{})
if err != nil {
// HEAD has no XML error body. The SDK synthesizes NoSuchKey for any
// object-path 404, including a missing bucket; confirm the bucket first.
if minio.ToErrorResponse(err).Code == "NoSuchKey" {
exists, bucketErr := s.client.BucketExists(ctx, s.bucket)
if bucketErr != nil {
return attachment.Object{}, wrap("stat bucket", bucketErr)
}
if !exists {
return attachment.Object{}, errors.New("s3: stat object: bucket does not exist")
}
}
return attachment.Object{}, wrap("stat object", err)
}
return attachment.Object{Key: key, Size: obj.Size, Modified: obj.LastModified}, nil
}
func (s *Store) Copy(ctx context.Context, source, dest string) error {
if err := ctx.Err(); err != nil {
return err
}
_, err := s.client.Client.CopyObject(ctx,
minio.CopyDestOptions{Bucket: s.bucket, Object: dest},
minio.CopySrcOptions{Bucket: s.bucket, Object: source},
)
return wrap("copy object", err)
}
func (s *Store) Delete(ctx context.Context, key string) error {
if err := ctx.Err(); err != nil {
return err
}
err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{})
// S3 DELETE is idempotent even when the object no longer exists.
if minio.ToErrorResponse(err).Code == "NoSuchKey" {
return nil
}
return wrap("delete object", err)
}
// List returns at most limit keys in byte-lexicographic order, strictly after
// after. The synchronous iterator stops before fetching the next page.
func (s *Store) List(ctx context.Context, prefix, after string, limit int) ([]attachment.Object, error) {
if err := ctx.Err(); err != nil {
return nil, err
}
if limit < 1 || limit > MaxPageSize {
return nil, fmt.Errorf("s3: list limit must be between 1 and %d", MaxPageSize)
}
listCtx, cancel := context.WithCancel(ctx)
defer cancel()
objects := make([]attachment.Object, 0, limit)
for obj := range s.client.ListObjectsIter(listCtx, s.bucket, minio.ListObjectsOptions{
Prefix: prefix, StartAfter: after, Recursive: true, MaxKeys: limit,
}) {
if obj.Err != nil {
return nil, wrap("list objects", obj.Err)
}
objects = append(objects, attachment.Object{Key: obj.Key, Size: obj.Size, Modified: obj.LastModified})
if len(objects) == limit {
break
}
}
if err := ctx.Err(); err != nil {
return nil, err
}
return objects, nil
}
func wrap(op string, err error) error {
if err == nil {
return nil
}
// Never treat authorization errors, a missing bucket, or an outage as a
// missing blob: the reconciler would otherwise mark valid files failed.
if code := minio.ToErrorResponse(err).Code; code == "NoSuchKey" || code == "NoSuchObject" {
return fmt.Errorf("s3: %s: %w", op, attachment.ErrObjectMissing)
}
return fmt.Errorf("s3: %s: %w", op, err)
}
+172
View File
@@ -0,0 +1,172 @@
package s3store_test
import (
"context"
"errors"
"io"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"time"
"messenger/internal/platform/config"
"messenger/internal/platform/s3store"
)
func TestNewIsOfflineAndRejectsInvalidConfiguration(t *testing.T) {
var calls atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls.Add(1); w.WriteHeader(503) }))
defer server.Close()
if _, err := s3store.New(config.S3{Endpoint: server.URL, Region: "us-east-1", Bucket: "attachments", AccessKey: "access", SecretKey: "secret"}); err != nil {
t.Fatal(err)
}
if calls.Load() != 0 {
t.Fatal("constructor performed network I/O")
}
for _, tc := range []struct{ name, endpoint, region, bucket, access, secret string }{
{"scheme", "ftp://localhost:8333", "us-east-1", "attachments", "access", "secret"},
{"path", "http://localhost:8333/path", "us-east-1", "attachments", "access", "secret"},
{"userinfo", "http://user:password@localhost:8333", "us-east-1", "attachments", "access", "secret"},
{"query", "http://localhost:8333?x=1", "us-east-1", "attachments", "access", "secret"},
{"fragment", "http://localhost:8333/#x", "us-east-1", "attachments", "access", "secret"},
{"region", server.URL, "", "attachments", "access", "secret"},
{"bucket", server.URL, "us-east-1", "INVALID", "access", "secret"},
{"access", server.URL, "us-east-1", "attachments", "", "secret"},
{"secret", server.URL, "us-east-1", "attachments", "access", ""},
} {
t.Run(tc.name, func(t *testing.T) {
if _, err := s3store.New(config.S3{Endpoint: tc.endpoint, Region: tc.region, Bucket: tc.bucket, AccessKey: tc.access, SecretKey: tc.secret}); err == nil {
t.Fatal("accepted invalid configuration")
}
})
}
}
func TestPutStreamsWithoutReadingTheWholeBodyFirst(t *testing.T) {
first := make(chan struct{})
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
if r.Method != http.MethodPut || r.URL.Path != "/attachments/staging/stream" || r.URL.RawQuery != "" {
t.Errorf("unexpected request: %s %s", r.Method, r.URL)
w.WriteHeader(400)
return
}
if r.ContentLength <= 0 || len(r.TransferEncoding) != 0 {
t.Error("PUT is not a known-length single request")
}
b := make([]byte, 1)
if _, err := io.ReadFull(r.Body, b); err != nil {
t.Error(err)
return
}
close(first)
if _, err := io.Copy(io.Discard, r.Body); err != nil {
t.Error(err)
return
}
w.Header().Set("ETag", `"probe"`)
}))
defer server.Close()
store, err := s3store.New(config.S3{Endpoint: server.URL, Region: "us-east-1", Bucket: "attachments", AccessKey: "access", SecretKey: "secret"})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
// One signing chunk can be buffered; the remaining bytes wait for the server.
r, w := io.Pipe()
defer r.Close()
go func() {
defer w.Close()
if _, err := w.Write(make([]byte, 256*1024)); err != nil {
return
}
select {
case <-first:
case <-ctx.Done():
_ = w.CloseWithError(ctx.Err())
return
}
_, _ = w.Write(make([]byte, 256*1024))
}()
if err := store.Put(ctx, "staging/stream", r, 512*1024, "image/png"); err != nil {
t.Fatal(err)
}
if requests.Load() != 1 {
t.Fatalf("got %d requests, want one PUT", requests.Load())
}
}
func TestCanceledAndInvalidCallsNeverReachTheServer(t *testing.T) {
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { requests.Add(1); w.WriteHeader(500) }))
defer server.Close()
store, err := s3store.New(config.S3{Endpoint: server.URL, Region: "us-east-1", Bucket: "attachments", AccessKey: "access", SecretKey: "secret"})
if err != nil {
t.Fatal(err)
}
ctx, cancel := context.WithCancel(context.Background())
cancel()
for name, call := range map[string]func() error{
"put": func() error { return store.Put(ctx, "key", strings.NewReader("x"), 1, "image/png") },
"open": func() error {
r, e := store.Open(ctx, "key")
if r != nil {
r.Close()
}
return e
},
"stat": func() error { _, e := store.Stat(ctx, "key"); return e },
"copy": func() error { return store.Copy(ctx, "a", "b") },
"delete": func() error { return store.Delete(ctx, "key") },
"list": func() error { _, e := store.List(ctx, "", "", 1); return e },
"bootstrap": func() error { return store.Bootstrap(ctx) },
} {
t.Run(name, func(t *testing.T) {
if err := call(); !errors.Is(err, context.Canceled) {
t.Fatalf("got %v, want canceled", err)
}
})
}
if err := store.Put(context.Background(), "key", strings.NewReader("x"), -1, "image/png"); err == nil {
t.Fatal("accepted unknown length")
}
for _, limit := range []int{-1, 0, 501, 1000000000} {
if _, err := store.List(context.Background(), "", "", limit); err == nil {
t.Fatalf("accepted unbounded page %d", limit)
}
}
if requests.Load() != 0 {
t.Fatalf("invalid calls reached server %d times", requests.Load())
}
}
func TestListStopsAfterOneBoundedPage(t *testing.T) {
var requests atomic.Int32
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requests.Add(1)
if r.URL.Query().Get("start-after") != "blobs/a" || r.URL.Query().Get("prefix") != "blobs/" || r.URL.Query().Get("max-keys") != "2" {
t.Errorf("wrong list query: %s", r.URL.RawQuery)
}
w.Header().Set("Content-Type", "application/xml")
io.WriteString(w, `<ListBucketResult xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Name>attachments</Name><IsTruncated>true</IsTruncated><NextContinuationToken>next-page</NextContinuationToken><Contents><Key>blobs/b</Key><Size>1</Size><LastModified>2026-01-01T00:00:00Z</LastModified></Contents><Contents><Key>blobs/c</Key><Size>2</Size><LastModified>2026-01-01T00:00:01Z</LastModified></Contents></ListBucketResult>`)
}))
defer server.Close()
store, err := s3store.New(config.S3{Endpoint: server.URL, Region: "us-east-1", Bucket: "attachments", AccessKey: "access", SecretKey: "secret"})
if err != nil {
t.Fatal(err)
}
objects, err := store.List(context.Background(), "blobs/", "blobs/a", 2)
if err != nil {
t.Fatal(err)
}
if len(objects) != 2 || objects[0].Key != "blobs/b" || objects[1].Key != "blobs/c" {
t.Fatalf("wrong page: %+v", objects)
}
if requests.Load() != 1 {
t.Fatalf("prefetched %d pages", requests.Load())
}
}
+49
View File
@@ -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
}
+57
View File
@@ -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)
}
}
}