lab4
This commit is contained in:
@@ -0,0 +1,302 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/spf13/viper"
|
||||
|
||||
"mtusi-messenger/internal/logger"
|
||||
)
|
||||
|
||||
const (
|
||||
configEnvKey = "APP_CONFIG"
|
||||
envKey = "APP_ENV"
|
||||
configName = "config"
|
||||
defaultEnv = "dev"
|
||||
configDir = "./config/"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Env string `mapstructure:"env" validate:"omitempty,eq=dev"`
|
||||
Server Server `mapstructure:"server"`
|
||||
Log Log `mapstructure:"log"`
|
||||
Postgres Postgres `mapstructure:"postgres"`
|
||||
Redis Redis `mapstructure:"redis"`
|
||||
Cache Cache `mapstructure:"cache"`
|
||||
Session Session `mapstructure:"session"`
|
||||
Idempotency Idempotency `mapstructure:"idempotency"`
|
||||
S3 S3 `mapstructure:"s3"`
|
||||
}
|
||||
|
||||
// S3 describes the object store and attachment limits. Access keys are checked
|
||||
// by the object-store constructor rather than the global validator: cmd/migrate
|
||||
// and unit tests load this config without any S3 credentials.
|
||||
type S3 struct {
|
||||
Endpoint string `mapstructure:"endpoint" validate:"required,url"`
|
||||
PublicEndpoint string `mapstructure:"public_endpoint" validate:"omitempty,url"`
|
||||
Region string `mapstructure:"region" validate:"required"`
|
||||
Bucket string `mapstructure:"bucket" validate:"required"`
|
||||
AccessKeyID string `mapstructure:"access_key_id"`
|
||||
SecretAccessKey string `mapstructure:"secret_access_key"`
|
||||
UsePathStyle bool `mapstructure:"use_path_style"`
|
||||
Timeout time.Duration `mapstructure:"timeout" validate:"required,gt=0"`
|
||||
|
||||
MaxUploadBytes int64 `mapstructure:"max_upload_bytes" validate:"required,gt=0,lte=10485760"`
|
||||
MaxImagePixels int64 `mapstructure:"max_image_pixels" validate:"required,gt=0,lte=40000000"`
|
||||
PresignTTL time.Duration `mapstructure:"presign_ttl" validate:"required,gt=0,lte=168h"`
|
||||
SweepInterval time.Duration `mapstructure:"sweep_interval" validate:"required,gt=0"`
|
||||
SweepGrace time.Duration `mapstructure:"sweep_grace" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
TTLSeconds int `mapstructure:"ttl_seconds" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
// Idempotency holds the retention window of a message Idempotency-Key (contract
|
||||
// 1.3.0 requires at least 24 hours).
|
||||
type Idempotency struct {
|
||||
TTLSeconds int `mapstructure:"ttl_seconds" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type Redis struct {
|
||||
Enabled bool `mapstructure:"enabled"`
|
||||
Host string `mapstructure:"host" validate:"omitempty,hostname|ip"`
|
||||
Port int `mapstructure:"port" validate:"omitempty,min=1,max=65535"`
|
||||
Password string `mapstructure:"password"`
|
||||
DB int `mapstructure:"db" validate:"omitempty,gte=0,lte=15"`
|
||||
MaxRetries int `mapstructure:"max_retries" validate:"omitempty,gte=-1"`
|
||||
DialTimeout time.Duration `mapstructure:"dial_timeout" validate:"omitempty,gt=0"`
|
||||
ReadTimeout time.Duration `mapstructure:"read_timeout" validate:"omitempty,gt=0"`
|
||||
WriteTimeout time.Duration `mapstructure:"write_timeout" validate:"omitempty,gt=0"`
|
||||
PoolSize int `mapstructure:"pool_size" validate:"omitempty,gt=0"`
|
||||
}
|
||||
|
||||
type Cache struct {
|
||||
Enabled bool `mapstructure:"enabled"`
|
||||
ChatListTTL time.Duration `mapstructure:"chat_list_ttl" validate:"required,gt=0"`
|
||||
LockTTL time.Duration `mapstructure:"lock_ttl" validate:"required,gt=1s"`
|
||||
LockWaitTimeout time.Duration `mapstructure:"lock_wait_timeout" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
Host string `mapstructure:"host" validate:"required,hostname|ip"`
|
||||
Port int `mapstructure:"port" validate:"required,min=1,max=65535"`
|
||||
ReadHeaderTimeout time.Duration `mapstructure:"read_header_timeout" validate:"required,gt=0"`
|
||||
ReadTimeout time.Duration `mapstructure:"read_timeout" validate:"required,gt=0"`
|
||||
ShutdownTimeout time.Duration `mapstructure:"shutdown_timeout" validate:"required,gt=0"`
|
||||
// MaxBodyBytes bounds a request body before the transport decodes it; uploads
|
||||
// of a later lab raise it explicitly (contract 4: 10 MiB attachments).
|
||||
MaxBodyBytes int64 `mapstructure:"max_body_bytes" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
type Log struct {
|
||||
Level string `mapstructure:"level" validate:"required,oneof=debug info warn error"`
|
||||
Format string `mapstructure:"format" validate:"required,oneof=json console"`
|
||||
}
|
||||
|
||||
type Postgres struct {
|
||||
Host string `mapstructure:"host" validate:"omitempty,hostname|ip"`
|
||||
Port int `mapstructure:"port" validate:"omitempty,min=1,max=65535"`
|
||||
Database string `mapstructure:"database" validate:"omitempty,min=1"`
|
||||
User string `mapstructure:"user" validate:"omitempty,min=1"`
|
||||
Password string `mapstructure:"password"`
|
||||
SSLMode string `mapstructure:"ssl_mode" validate:"omitempty,oneof=disable require verify-ca verify-full"`
|
||||
MaxConns int32 `mapstructure:"max_conns" validate:"omitempty,gt=0"`
|
||||
MinConns int32 `mapstructure:"min_conns" validate:"omitempty,gte=0"`
|
||||
MaxConnLifetime time.Duration `mapstructure:"max_conn_lifetime" validate:"omitempty,gt=0"`
|
||||
MaxConnIdleTime time.Duration `mapstructure:"max_conn_idle_time" validate:"omitempty,gt=0"`
|
||||
ConnectTimeout time.Duration `mapstructure:"connect_timeout" validate:"omitempty,gt=0"`
|
||||
QueryTimeout time.Duration `mapstructure:"query_timeout" validate:"omitempty,gt=0"`
|
||||
}
|
||||
|
||||
func (p Postgres) DSN() string {
|
||||
u := &url.URL{
|
||||
Scheme: "postgres",
|
||||
Host: net.JoinHostPort(p.Host, strconv.Itoa(p.Port)),
|
||||
Path: "/" + p.Database,
|
||||
}
|
||||
|
||||
if p.Password == "" {
|
||||
u.User = url.User(p.User)
|
||||
} else {
|
||||
u.User = url.UserPassword(p.User, p.Password)
|
||||
}
|
||||
|
||||
query := url.Values{}
|
||||
query.Set("sslmode", p.SSLMode)
|
||||
u.RawQuery = query.Encode()
|
||||
|
||||
return u.String()
|
||||
}
|
||||
|
||||
var defaults = map[string]any{
|
||||
"env": "dev",
|
||||
"server.host": "0.0.0.0",
|
||||
"server.port": 8080,
|
||||
"server.read_header_timeout": "10s",
|
||||
"server.read_timeout": "60s",
|
||||
"server.shutdown_timeout": "10s",
|
||||
"server.max_body_bytes": 262144,
|
||||
"s3.endpoint": "http://localhost:8333",
|
||||
"s3.public_endpoint": "http://localhost:8333",
|
||||
"s3.region": "us-east-1",
|
||||
"s3.bucket": "messenger-attachments",
|
||||
"s3.access_key_id": "",
|
||||
"s3.secret_access_key": "",
|
||||
"s3.use_path_style": true,
|
||||
"s3.timeout": "30s",
|
||||
"s3.max_upload_bytes": 10485760,
|
||||
"s3.max_image_pixels": 40000000,
|
||||
"s3.presign_ttl": "5m",
|
||||
"s3.sweep_interval": "1m",
|
||||
"s3.sweep_grace": "10m",
|
||||
"log.level": "info",
|
||||
"log.format": "json",
|
||||
"session.ttl_seconds": 3600,
|
||||
"idempotency.ttl_seconds": 86400,
|
||||
"redis.enabled": false,
|
||||
"redis.host": "localhost",
|
||||
"redis.port": 6379,
|
||||
"redis.db": 0,
|
||||
"redis.max_retries": -1,
|
||||
"redis.dial_timeout": "300ms",
|
||||
"redis.read_timeout": "200ms",
|
||||
"redis.write_timeout": "200ms",
|
||||
"redis.pool_size": 10,
|
||||
"cache.enabled": false,
|
||||
"cache.chat_list_ttl": "5m",
|
||||
"cache.lock_ttl": "10s",
|
||||
"cache.lock_wait_timeout": "2s",
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
v := viper.New()
|
||||
|
||||
if err := configureSource(v); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
v.AllowEmptyEnv(true)
|
||||
v.AutomaticEnv()
|
||||
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
||||
|
||||
for key := range defaults {
|
||||
if err := v.BindEnv(key); err != nil {
|
||||
return Config{}, fmt.Errorf("bind env %q: %w", key, err)
|
||||
}
|
||||
}
|
||||
|
||||
// The skeleton suggests MAX_UPLOAD_BYTES / MAX_IMAGE_PIXELS. Keep those
|
||||
// names while storing the values under the S3 section.
|
||||
for key, env := range map[string]string{
|
||||
"s3.max_upload_bytes": "MAX_UPLOAD_BYTES",
|
||||
"s3.max_image_pixels": "MAX_IMAGE_PIXELS",
|
||||
} {
|
||||
if err := v.BindEnv(key, env); err != nil {
|
||||
return Config{}, fmt.Errorf("bind env %q: %w", env, err)
|
||||
}
|
||||
}
|
||||
|
||||
var cfg Config
|
||||
if err := v.Unmarshal(&cfg); err != nil {
|
||||
return Config{}, fmt.Errorf("unmarshal config: %w", err)
|
||||
}
|
||||
|
||||
if err := validate.Struct(cfg); err != nil {
|
||||
return Config{}, fmt.Errorf("validate config: %w", err)
|
||||
}
|
||||
|
||||
if err := cfg.validateDependencies(); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
|
||||
func (c Config) validateDependencies() error {
|
||||
if c.Cache.Enabled && !c.Redis.Enabled {
|
||||
return errors.New("validate config: cache.enabled requires redis.enabled")
|
||||
}
|
||||
|
||||
if c.S3.SweepGrace <= c.S3.PresignTTL {
|
||||
return errors.New("validate config: s3.sweep_grace must exceed s3.presign_ttl")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func configureSource(v *viper.Viper) error {
|
||||
for key, value := range defaults {
|
||||
v.SetDefault(key, value)
|
||||
}
|
||||
|
||||
v.SetConfigType("yaml")
|
||||
|
||||
if path := os.Getenv(configEnvKey); path != "" {
|
||||
v.SetConfigFile(path)
|
||||
} else {
|
||||
env := os.Getenv(envKey)
|
||||
if env == "" {
|
||||
env = defaultEnv
|
||||
}
|
||||
|
||||
v.SetConfigName(configName)
|
||||
v.AddConfigPath(filepath.Join(configDir, env))
|
||||
}
|
||||
|
||||
if err := v.ReadInConfig(); err != nil {
|
||||
var notFound viper.ConfigFileNotFoundError
|
||||
if errors.As(err, ¬Found) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return fmt.Errorf("read config: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c Config) Addr() string {
|
||||
return net.JoinHostPort(c.Server.Host, strconv.Itoa(c.Server.Port))
|
||||
}
|
||||
|
||||
func (c Config) SlogLevel() slog.Level {
|
||||
level, _ := logger.ParseLevel(c.Log.Level)
|
||||
|
||||
return level
|
||||
}
|
||||
|
||||
func (c Config) LoggerFormat() logger.Format {
|
||||
format, _ := logger.ParseFormat(c.Log.Format)
|
||||
|
||||
return format
|
||||
}
|
||||
|
||||
var validate = newValidator()
|
||||
|
||||
func newValidator() *validator.Validate {
|
||||
v := validator.New(validator.WithRequiredStructEnabled())
|
||||
v.RegisterTagNameFunc(envName)
|
||||
|
||||
return v
|
||||
}
|
||||
|
||||
func envName(field reflect.StructField) string {
|
||||
key := field.Tag.Get("mapstructure")
|
||||
if key == "" {
|
||||
return field.Name
|
||||
}
|
||||
|
||||
return strings.ToUpper(key)
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
package config_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/go-playground/validator/v10"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
"mtusi-messenger/internal/logger"
|
||||
)
|
||||
|
||||
func TestDefaults(t *testing.T) {
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "0.0.0.0", cfg.Server.Host)
|
||||
assert.Equal(t, 8080, cfg.Server.Port)
|
||||
assert.Equal(t, 10*time.Second, cfg.Server.ReadHeaderTimeout)
|
||||
assert.Equal(t, 10*time.Second, cfg.Server.ShutdownTimeout)
|
||||
assert.Equal(t, "info", cfg.Log.Level)
|
||||
assert.Equal(t, "json", cfg.Log.Format)
|
||||
assert.Equal(t, config.Postgres{}, cfg.Postgres, "postgres defaults live in the adapter")
|
||||
}
|
||||
|
||||
func TestEnvOverridesDefaults(t *testing.T) {
|
||||
t.Setenv("SERVER_HOST", "127.0.0.1")
|
||||
t.Setenv("SERVER_PORT", "9090")
|
||||
t.Setenv("SERVER_READ_HEADER_TIMEOUT", "3s")
|
||||
t.Setenv("SERVER_SHUTDOWN_TIMEOUT", "30s")
|
||||
t.Setenv("LOG_LEVEL", "debug")
|
||||
t.Setenv("LOG_FORMAT", "console")
|
||||
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "127.0.0.1", cfg.Server.Host)
|
||||
assert.Equal(t, 9090, cfg.Server.Port)
|
||||
assert.Equal(t, 3*time.Second, cfg.Server.ReadHeaderTimeout)
|
||||
assert.Equal(t, 30*time.Second, cfg.Server.ShutdownTimeout)
|
||||
assert.Equal(t, "debug", cfg.Log.Level)
|
||||
assert.Equal(t, "console", cfg.Log.Format)
|
||||
}
|
||||
|
||||
func TestDsnEncodesCredentials(t *testing.T) {
|
||||
cfg := config.Postgres{
|
||||
Host: "db",
|
||||
Port: 5432,
|
||||
Database: "app",
|
||||
User: "user",
|
||||
Password: "p@ss:w/rd",
|
||||
SSLMode: "disable",
|
||||
}
|
||||
|
||||
assert.Equal(t, "postgres://user:p%40ss%3Aw%2Frd@db:5432/app?sslmode=disable", cfg.DSN())
|
||||
}
|
||||
|
||||
func writeConfig(t *testing.T, body string) string {
|
||||
t.Helper()
|
||||
|
||||
path := filepath.Join(t.TempDir(), "config.yaml")
|
||||
require.NoError(t, os.WriteFile(path, []byte(body), 0o600))
|
||||
|
||||
return path
|
||||
}
|
||||
|
||||
func TestLoadsYAMLFile(t *testing.T) {
|
||||
path := writeConfig(t, `
|
||||
env: dev
|
||||
server:
|
||||
host: 10.0.0.1
|
||||
port: 9999
|
||||
read_header_timeout: 3s
|
||||
shutdown_timeout: 7s
|
||||
log:
|
||||
level: debug
|
||||
format: console
|
||||
postgres:
|
||||
host: db
|
||||
port: 5433
|
||||
database: app
|
||||
user: app
|
||||
password: secret
|
||||
ssl_mode: disable
|
||||
max_conns: 7
|
||||
min_conns: 2
|
||||
max_conn_lifetime: 2h
|
||||
max_conn_idle_time: 10m
|
||||
connect_timeout: 2s
|
||||
query_timeout: 3s
|
||||
`)
|
||||
|
||||
t.Setenv("APP_CONFIG", path)
|
||||
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "10.0.0.1", cfg.Server.Host)
|
||||
assert.Equal(t, 9999, cfg.Server.Port)
|
||||
assert.Equal(t, 3*time.Second, cfg.Server.ReadHeaderTimeout)
|
||||
assert.Equal(t, "debug", cfg.Log.Level)
|
||||
assert.Equal(t, "console", cfg.Log.Format)
|
||||
assert.Equal(t, "db", cfg.Postgres.Host)
|
||||
assert.Equal(t, 5433, cfg.Postgres.Port)
|
||||
assert.Equal(t, "app", cfg.Postgres.Database)
|
||||
assert.Equal(t, int32(7), cfg.Postgres.MaxConns)
|
||||
assert.Equal(t, 2*time.Second, cfg.Postgres.ConnectTimeout)
|
||||
}
|
||||
|
||||
func TestEnvOverridesYAML(t *testing.T) {
|
||||
path := writeConfig(t, `
|
||||
env: dev
|
||||
server:
|
||||
host: 10.0.0.1
|
||||
port: 9999
|
||||
read_header_timeout: 3s
|
||||
shutdown_timeout: 7s
|
||||
log:
|
||||
level: debug
|
||||
format: console
|
||||
postgres:
|
||||
host: db
|
||||
port: 5433
|
||||
database: app
|
||||
user: app
|
||||
password: file
|
||||
ssl_mode: disable
|
||||
`)
|
||||
|
||||
t.Setenv("APP_CONFIG", path)
|
||||
t.Setenv("SERVER_HOST", "127.0.0.1")
|
||||
t.Setenv("POSTGRES_PASSWORD", "env")
|
||||
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "127.0.0.1", cfg.Server.Host, "env переопределяет YAML")
|
||||
assert.Equal(t, 9999, cfg.Server.Port)
|
||||
assert.Equal(t, "env", cfg.Postgres.Password)
|
||||
}
|
||||
|
||||
func TestSessionTTLFromContractEnv(t *testing.T) {
|
||||
t.Setenv("SESSION_TTL_SECONDS", "2")
|
||||
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, 2, cfg.Session.TTLSeconds)
|
||||
}
|
||||
|
||||
func TestInvalidValues(t *testing.T) {
|
||||
tests := map[string]map[string]string{
|
||||
"пустой server.host": {"SERVER_HOST": ""},
|
||||
"host не адрес и не имя": {"SERVER_HOST": "не адрес"},
|
||||
"порт ниже диапазона": {"SERVER_PORT": "0"},
|
||||
"порт выше диапазона": {"SERVER_PORT": "65536"},
|
||||
"нулевой read header timeout": {"SERVER_READ_HEADER_TIMEOUT": "0s"},
|
||||
"отрицательный shutdown": {"SERVER_SHUTDOWN_TIMEOUT": "-1s"},
|
||||
"неизвестный log level": {"LOG_LEVEL": "trace"},
|
||||
"неизвестный log format": {"LOG_FORMAT": "xml"},
|
||||
}
|
||||
|
||||
for name, env := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
for key, value := range env {
|
||||
t.Setenv(key, value)
|
||||
}
|
||||
|
||||
_, err := config.Load()
|
||||
require.Error(t, err)
|
||||
|
||||
var validationErrs validator.ValidationErrors
|
||||
require.ErrorAs(t, err, &validationErrs)
|
||||
require.NotEmpty(t, validationErrs)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidPostgresValues(t *testing.T) {
|
||||
path := writeConfig(t, `
|
||||
env: dev
|
||||
postgres:
|
||||
host: db
|
||||
port: 5432
|
||||
database: messenger
|
||||
user: messenger
|
||||
ssl_mode: disable
|
||||
max_conns: 10
|
||||
`)
|
||||
|
||||
tests := map[string]map[string]string{
|
||||
"неизвестный ssl mode": {"POSTGRES_SSL_MODE": "bogus"},
|
||||
"отрицательный max_conns": {"POSTGRES_MAX_CONNS": "-1"},
|
||||
}
|
||||
|
||||
for name, env := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
t.Setenv("APP_CONFIG", path)
|
||||
for key, value := range env {
|
||||
t.Setenv(key, value)
|
||||
}
|
||||
|
||||
_, err := config.Load()
|
||||
require.Error(t, err)
|
||||
|
||||
var validationErrs validator.ValidationErrors
|
||||
require.ErrorAs(t, err, &validationErrs)
|
||||
require.NotEmpty(t, validationErrs)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnparsableValues(t *testing.T) {
|
||||
tests := map[string]map[string]string{
|
||||
"порт не число": {"SERVER_PORT": "не-число"},
|
||||
"timeout не duration": {"SERVER_READ_HEADER_TIMEOUT": "быстро"},
|
||||
}
|
||||
|
||||
for name, env := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
for key, value := range env {
|
||||
t.Setenv(key, value)
|
||||
}
|
||||
|
||||
_, err := config.Load()
|
||||
require.Error(t, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoggerSettings(t *testing.T) {
|
||||
t.Setenv("LOG_LEVEL", "warn")
|
||||
t.Setenv("LOG_FORMAT", "console")
|
||||
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
level, err := logger.ParseLevel(cfg.Log.Level)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, level, cfg.SlogLevel())
|
||||
|
||||
format, err := logger.ParseFormat(cfg.Log.Format)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, format, cfg.LoggerFormat())
|
||||
}
|
||||
|
||||
func TestAddr(t *testing.T) {
|
||||
t.Setenv("SERVER_HOST", "0.0.0.0")
|
||||
t.Setenv("SERVER_PORT", "8080")
|
||||
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "0.0.0.0:8080", cfg.Addr())
|
||||
}
|
||||
|
||||
func TestAddrWithIPv6Host(t *testing.T) {
|
||||
t.Setenv("SERVER_HOST", "::1")
|
||||
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, "[::1]:8080", cfg.Addr())
|
||||
}
|
||||
|
||||
func TestLoadIsIndependentOfProcessState(t *testing.T) {
|
||||
t.Setenv("SERVER_PORT", "7070")
|
||||
|
||||
first, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
second, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.Equal(t, first, second)
|
||||
}
|
||||
|
||||
func TestRedisDefaultsDisabled(t *testing.T) {
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.False(t, cfg.Redis.Enabled)
|
||||
assert.Equal(t, "localhost", cfg.Redis.Host)
|
||||
assert.Equal(t, 6379, cfg.Redis.Port)
|
||||
assert.Equal(t, -1, cfg.Redis.MaxRetries)
|
||||
assert.Equal(t, 300*time.Millisecond, cfg.Redis.DialTimeout)
|
||||
assert.Equal(t, 200*time.Millisecond, cfg.Redis.ReadTimeout)
|
||||
assert.Equal(t, 200*time.Millisecond, cfg.Redis.WriteTimeout)
|
||||
assert.False(t, cfg.Cache.Enabled)
|
||||
assert.Equal(t, 5*time.Minute, cfg.Cache.ChatListTTL)
|
||||
assert.Equal(t, 10*time.Second, cfg.Cache.LockTTL)
|
||||
assert.Equal(t, 2*time.Second, cfg.Cache.LockWaitTimeout)
|
||||
}
|
||||
|
||||
func TestRedisEnvOverrides(t *testing.T) {
|
||||
t.Setenv("REDIS_ENABLED", "true")
|
||||
t.Setenv("REDIS_HOST", "cache")
|
||||
t.Setenv("REDIS_PORT", "6380")
|
||||
t.Setenv("CACHE_ENABLED", "true")
|
||||
t.Setenv("CACHE_CHAT_LIST_TTL", "1m")
|
||||
t.Setenv("CACHE_LOCK_TTL", "7s")
|
||||
t.Setenv("CACHE_LOCK_WAIT_TIMEOUT", "1500ms")
|
||||
|
||||
cfg, err := config.Load()
|
||||
require.NoError(t, err)
|
||||
|
||||
assert.True(t, cfg.Redis.Enabled)
|
||||
assert.Equal(t, "cache", cfg.Redis.Host)
|
||||
assert.Equal(t, 6380, cfg.Redis.Port)
|
||||
assert.True(t, cfg.Cache.Enabled)
|
||||
assert.Equal(t, time.Minute, cfg.Cache.ChatListTTL)
|
||||
assert.Equal(t, 7*time.Second, cfg.Cache.LockTTL)
|
||||
assert.Equal(t, 1500*time.Millisecond, cfg.Cache.LockWaitTimeout)
|
||||
}
|
||||
|
||||
func TestInvalidCacheTTL(t *testing.T) {
|
||||
for _, key := range []string{
|
||||
"CACHE_CHAT_LIST_TTL",
|
||||
"CACHE_LOCK_TTL",
|
||||
"CACHE_LOCK_WAIT_TIMEOUT",
|
||||
} {
|
||||
for _, value := range []string{"0s", "-1s"} {
|
||||
t.Run(key+"/"+value, func(t *testing.T) {
|
||||
t.Setenv(key, value)
|
||||
_, err := config.Load()
|
||||
require.Error(t, err)
|
||||
var validationErrs validator.ValidationErrors
|
||||
require.ErrorAs(t, err, &validationErrs)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCacheRequiresRedis(t *testing.T) {
|
||||
t.Setenv("CACHE_ENABLED", "true")
|
||||
|
||||
_, err := config.Load()
|
||||
require.ErrorContains(t, err, "cache.enabled requires redis.enabled")
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// AttachmentStatus is the lifecycle of an attachment. Only ready attachments
|
||||
// are exposed to members; pending rows exist while the object is being written,
|
||||
// failed rows are reserved for later labs.
|
||||
type AttachmentStatus string
|
||||
|
||||
const (
|
||||
AttachmentPending AttachmentStatus = "pending"
|
||||
AttachmentReady AttachmentStatus = "ready"
|
||||
AttachmentFailed AttachmentStatus = "failed"
|
||||
)
|
||||
|
||||
func (s AttachmentStatus) Valid() bool {
|
||||
switch s {
|
||||
case AttachmentPending, AttachmentReady, AttachmentFailed:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Attachment describes the original object. ObjectKey is internal: it never
|
||||
// leaves the service and must not be mapped into an API response.
|
||||
type Attachment struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
OwnerID uuid.UUID
|
||||
Filename string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
SHA256 string
|
||||
Status AttachmentStatus
|
||||
ErrorCode *string
|
||||
ObjectKey string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
// AttachmentDraft is a fully validated attachment awaiting persistence.
|
||||
type AttachmentDraft struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
OwnerID uuid.UUID
|
||||
ObjectKey string
|
||||
Filename string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
SHA256 string
|
||||
}
|
||||
|
||||
// AttachmentState is the minimal projection used while validating message
|
||||
// attachments in a transaction.
|
||||
type AttachmentState struct {
|
||||
ID uuid.UUID
|
||||
Status AttachmentStatus
|
||||
}
|
||||
|
||||
// AttachmentKey is the minimal projection used by the orphan sweeper.
|
||||
type AttachmentKey struct {
|
||||
ID uuid.UUID
|
||||
ObjectKey string
|
||||
Status AttachmentStatus
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// PresignRequest is the validated client intent for a direct upload.
|
||||
type PresignRequest struct {
|
||||
ChatID uuid.UUID
|
||||
OwnerID uuid.UUID
|
||||
Filename string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
SHA256 string
|
||||
}
|
||||
|
||||
// PresignResult is returned by the server and never contains credentials.
|
||||
type PresignResult struct {
|
||||
AttachmentID uuid.UUID
|
||||
UploadURL string
|
||||
ExpiresAt time.Time
|
||||
SizeBytes int64
|
||||
SHA256 string
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Chat struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
MemberIDs []uuid.UUID
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func (c Chat) HasMember(userID uuid.UUID) bool {
|
||||
return slices.Contains(c.MemberIDs, userID)
|
||||
}
|
||||
|
||||
type ChatDraft struct {
|
||||
Title string
|
||||
MemberIDs []uuid.UUID
|
||||
CallerID uuid.UUID
|
||||
}
|
||||
|
||||
func (d ChatDraft) Validate() error {
|
||||
if err := validateNotBlank("title", d.Title); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if len(d.MemberIDs) == 0 {
|
||||
return fmt.Errorf("member_ids must not be empty: %w", ErrValidation)
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, len(d.MemberIDs))
|
||||
for _, id := range d.MemberIDs {
|
||||
if _, ok := seen[id]; ok {
|
||||
return fmt.Errorf("member_ids contains duplicates: %w", ErrValidation)
|
||||
}
|
||||
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
|
||||
if _, ok := seen[d.CallerID]; !ok {
|
||||
return fmt.Errorf("member_ids must contain the caller: %w", ErrValidation)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Cursor struct {
|
||||
Scope uuid.UUID
|
||||
CreatedAt time.Time
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
func (c Cursor) BelongsTo(scope uuid.UUID) bool {
|
||||
return c.Scope == scope
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package domain
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrUsernameTaken = errors.New("username already taken")
|
||||
ErrUnknownMember = errors.New("member does not exist")
|
||||
ErrValidation = errors.New("validation failed")
|
||||
ErrInvalidCursor = errors.New("invalid cursor")
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrIdempotency = errors.New("idempotency key already used with another payload")
|
||||
ErrUnauthenticated = errors.New("unauthenticated")
|
||||
ErrUnavailable = errors.New("temporarily unavailable")
|
||||
ErrTooLarge = errors.New("payload is too large")
|
||||
ErrUnsupportedMedia = errors.New("unsupported media type")
|
||||
ErrIncomplete = errors.New("object is not fully uploaded")
|
||||
)
|
||||
@@ -0,0 +1,70 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// MaxMessageAttachments is the contract limit for attachment_ids on a message.
|
||||
const MaxMessageAttachments = 10
|
||||
|
||||
type Message struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
AttachmentIDs []uuid.UUID
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// MessageIdempotency is the client Idempotency-Key together with the fingerprint
|
||||
// of the payload it was first used with. The same key and fingerprint replay the
|
||||
// stored message; the same key with another payload is a conflict.
|
||||
type MessageIdempotency struct {
|
||||
Key string
|
||||
RequestHash [sha256.Size]byte
|
||||
}
|
||||
|
||||
type MessageDraft struct {
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
AttachmentIDs []uuid.UUID
|
||||
Idempotency MessageIdempotency
|
||||
}
|
||||
|
||||
// Validate enforces the contract rule that a message carries either non-blank
|
||||
// text or at least one attachment, never neither.
|
||||
func (d MessageDraft) Validate() error {
|
||||
if strings.TrimSpace(d.Text) == "" && len(d.AttachmentIDs) == 0 {
|
||||
return fmt.Errorf("message has neither text nor attachments: %w", ErrValidation)
|
||||
}
|
||||
|
||||
if len(d.AttachmentIDs) > MaxMessageAttachments {
|
||||
return fmt.Errorf("too many attachments: %w", ErrValidation)
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, len(d.AttachmentIDs))
|
||||
|
||||
for _, id := range d.AttachmentIDs {
|
||||
if id == uuid.Nil {
|
||||
return fmt.Errorf("attachment id is empty: %w", ErrValidation)
|
||||
}
|
||||
|
||||
if _, ok := seen[id]; ok {
|
||||
return fmt.Errorf("duplicate attachment id %s: %w", id, ErrValidation)
|
||||
}
|
||||
|
||||
seen[id] = struct{}{}
|
||||
}
|
||||
|
||||
if d.Idempotency.Key == "" {
|
||||
return fmt.Errorf("idempotency key is missing: %w", ErrValidation)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package domain
|
||||
|
||||
const DefaultPageLimit = 50
|
||||
|
||||
type Page[T any] struct {
|
||||
Items []T
|
||||
Next *Cursor
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Session struct {
|
||||
Token string
|
||||
ExpiresAt time.Time
|
||||
User User
|
||||
}
|
||||
|
||||
type NewSession struct {
|
||||
TokenHash []byte
|
||||
UserID uuid.UUID
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func validateNotBlank(field, value string) error {
|
||||
if strings.TrimSpace(value) == "" {
|
||||
return fmt.Errorf("%s consists of whitespace only: %w", field, ErrValidation)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type UserDraft struct {
|
||||
Username string
|
||||
DisplayName string
|
||||
Password string
|
||||
}
|
||||
|
||||
func (d UserDraft) Validate() error {
|
||||
if err := validateNotBlank("display_name", d.DisplayName); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if length := len([]rune(d.Password)); length < 12 || length > 128 {
|
||||
return fmt.Errorf("password length must be between 12 and 128 code points: %w", ErrValidation)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type NewUser struct {
|
||||
Username string
|
||||
DisplayName string
|
||||
PasswordHash string
|
||||
}
|
||||
|
||||
type UserCredentials struct {
|
||||
User User
|
||||
PasswordHash string
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package domain_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
// Длины, regex и uniqueItems проверяет сгенерированный слой по contracts/openapi.json.
|
||||
// Домен закрывает только то, что схема выразить не может.
|
||||
|
||||
func TestUserDraftRejectsBlankDisplayName(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for _, blank := range []string{" ", " ", "\t", "\n", "\u00a0"} {
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: blank}
|
||||
require.ErrorIs(t, draft.Validate(), domain.ErrValidation)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUserDraftAcceptsVisibleName(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "very-secret-password"}
|
||||
assert.NoError(t, draft.Validate())
|
||||
}
|
||||
|
||||
func TestUserDraftRejectsShortPassword(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "too-short"}
|
||||
require.ErrorIs(t, draft.Validate(), domain.ErrValidation)
|
||||
}
|
||||
|
||||
func TestUserDraftRejectsTooLongPassword(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: strings.Repeat("a", 129)}
|
||||
require.ErrorIs(t, draft.Validate(), domain.ErrValidation)
|
||||
}
|
||||
|
||||
func TestUserDraftAcceptsMinimalPassword(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: strings.Repeat("a", 12)}
|
||||
assert.NoError(t, draft.Validate())
|
||||
}
|
||||
|
||||
func TestChatDraftRequiresCallerAmongMembers(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
caller := uuid.New()
|
||||
|
||||
outside := domain.ChatDraft{
|
||||
Title: "Проект",
|
||||
MemberIDs: []uuid.UUID{uuid.New(), uuid.New()},
|
||||
CallerID: caller,
|
||||
}
|
||||
require.ErrorIs(t, outside.Validate(), domain.ErrValidation)
|
||||
|
||||
inside := domain.ChatDraft{
|
||||
Title: "Проект",
|
||||
MemberIDs: []uuid.UUID{uuid.New(), caller},
|
||||
CallerID: caller,
|
||||
}
|
||||
assert.NoError(t, inside.Validate())
|
||||
}
|
||||
|
||||
func TestChatDraftRejectsBlankTitle(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
caller := uuid.New()
|
||||
|
||||
draft := domain.ChatDraft{
|
||||
Title: " ",
|
||||
MemberIDs: []uuid.UUID{caller},
|
||||
CallerID: caller,
|
||||
}
|
||||
require.ErrorIs(t, draft.Validate(), domain.ErrValidation)
|
||||
}
|
||||
|
||||
func TestMessageDraftRejectsBlankText(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
draft := domain.MessageDraft{
|
||||
ChatID: uuid.New(),
|
||||
SenderID: uuid.New(),
|
||||
Text: strings.Repeat(" ", 10),
|
||||
Idempotency: domain.MessageIdempotency{Key: "key-1"},
|
||||
}
|
||||
require.ErrorIs(t, draft.Validate(), domain.ErrValidation)
|
||||
}
|
||||
|
||||
func TestMessageDraftRejectsMissingIdempotencyKey(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
draft := domain.MessageDraft{
|
||||
ChatID: uuid.New(),
|
||||
SenderID: uuid.New(),
|
||||
Text: "привет",
|
||||
}
|
||||
require.ErrorIs(t, draft.Validate(), domain.ErrValidation,
|
||||
"с lab3 отправка сообщения невозможна без Idempotency-Key")
|
||||
}
|
||||
|
||||
func TestMessageDraftAcceptsTextWithSurroundingSpaces(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
draft := domain.MessageDraft{
|
||||
ChatID: uuid.New(),
|
||||
SenderID: uuid.New(),
|
||||
Text: " привет ",
|
||||
Idempotency: domain.MessageIdempotency{Key: "key-1"},
|
||||
}
|
||||
assert.NoError(t, draft.Validate(), "контракт запрещает только полностью пробельный текст")
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package health
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type Pinger interface {
|
||||
Ping(ctx context.Context) error
|
||||
}
|
||||
|
||||
type Checker struct {
|
||||
pingers []Pinger
|
||||
}
|
||||
|
||||
func New(pingers ...Pinger) *Checker {
|
||||
return &Checker{pingers: pingers}
|
||||
}
|
||||
|
||||
func (c *Checker) Ping(ctx context.Context) error {
|
||||
for _, pinger := range c.pingers {
|
||||
if err := pinger.Ping(ctx); err != nil {
|
||||
return fmt.Errorf("ping %T: %w", pinger, err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package health_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/health"
|
||||
)
|
||||
|
||||
type stubPinger struct {
|
||||
err error
|
||||
}
|
||||
|
||||
func (s stubPinger) Ping(context.Context) error { return s.err }
|
||||
|
||||
func TestCheckerPassesWhenAllHealthy(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
checker := health.New(stubPinger{}, stubPinger{})
|
||||
require.NoError(t, checker.Ping(context.Background()))
|
||||
}
|
||||
|
||||
func TestCheckerReturnsFirstFailure(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
sentinel := errors.New("dependency down")
|
||||
checker := health.New(stubPinger{}, stubPinger{err: sentinel}, stubPinger{err: errors.New("later")})
|
||||
|
||||
require.ErrorIs(t, checker.Ping(context.Background()), sentinel)
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
// Package imagecheck validates PNG and JPEG structure without decoding the
|
||||
// raster. A full decode of a 40-megapixel image would allocate hundreds of
|
||||
// megabytes; attachment uploads must stay bounded. The parser verifies chunk
|
||||
// CRCs and the JPEG marker/scan structure, which catches truncation and
|
||||
// corruption while using constant memory.
|
||||
package imagecheck
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"encoding/binary"
|
||||
"errors"
|
||||
"fmt"
|
||||
"hash/crc32"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUnsupported = errors.New("unsupported image format")
|
||||
ErrCorrupt = errors.New("corrupt image")
|
||||
ErrTooLarge = errors.New("image has too many pixels")
|
||||
)
|
||||
|
||||
const (
|
||||
pngSignature = "\x89PNG\r\n\x1a\n"
|
||||
maxChunkSize = 1 << 30
|
||||
)
|
||||
|
||||
// Info is the validated header. ContentType is one of image/png or image/jpeg.
|
||||
type Info struct {
|
||||
ContentType string
|
||||
Width int64
|
||||
Height int64
|
||||
}
|
||||
|
||||
func ValidateFile(path string, maxPixels int64) (Info, error) {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return Info{}, fmt.Errorf("open upload: %w", err)
|
||||
}
|
||||
defer func() { _ = file.Close() }()
|
||||
|
||||
return Validate(file, maxPixels)
|
||||
}
|
||||
|
||||
// Validate consumes the reader to EOF (so a caller hashing the stream gets all
|
||||
// bytes) and returns the detected format and dimensions.
|
||||
func Validate(r io.Reader, maxPixels int64) (Info, error) {
|
||||
reader := bufio.NewReaderSize(r, 64<<10)
|
||||
|
||||
header, err := reader.Peek(8)
|
||||
if err != nil {
|
||||
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
|
||||
return Info{}, fmt.Errorf("%w: image is empty or truncated", ErrUnsupported)
|
||||
}
|
||||
|
||||
return Info{}, err
|
||||
}
|
||||
|
||||
switch {
|
||||
case string(header[:8]) == pngSignature:
|
||||
return validatePNG(reader, maxPixels)
|
||||
case header[0] == 0xFF && header[1] == 0xD8 && header[2] == 0xFF:
|
||||
return validateJPEG(reader, maxPixels)
|
||||
default:
|
||||
return Info{}, fmt.Errorf("%w: unrecognised signature", ErrUnsupported)
|
||||
}
|
||||
}
|
||||
|
||||
func validatePNG(reader *bufio.Reader, maxPixels int64) (Info, error) {
|
||||
if _, err := reader.Discard(len(pngSignature)); err != nil {
|
||||
return Info{}, corrupt("png signature", err)
|
||||
}
|
||||
|
||||
var (
|
||||
info Info
|
||||
seen = make(map[string]bool, 4)
|
||||
first = true
|
||||
hasIDAT bool
|
||||
)
|
||||
|
||||
info.ContentType = "image/png"
|
||||
|
||||
for {
|
||||
var lengthBytes [4]byte
|
||||
if _, err := io.ReadFull(reader, lengthBytes[:]); err != nil {
|
||||
return Info{}, corrupt("png chunk length", err)
|
||||
}
|
||||
|
||||
length := int64(binary.BigEndian.Uint32(lengthBytes[:]))
|
||||
if length < 0 || length > maxChunkSize {
|
||||
return Info{}, corruptf("png chunk length %d", length)
|
||||
}
|
||||
|
||||
var typeBytes [4]byte
|
||||
if _, err := io.ReadFull(reader, typeBytes[:]); err != nil {
|
||||
return Info{}, corrupt("png chunk type", err)
|
||||
}
|
||||
|
||||
chunkType := string(typeBytes[:])
|
||||
checksum := crc32.NewIEEE()
|
||||
_, _ = checksum.Write(typeBytes[:])
|
||||
|
||||
if first && chunkType != "IHDR" {
|
||||
return Info{}, corruptf("png first chunk is %q, want IHDR", chunkType)
|
||||
}
|
||||
|
||||
first = false
|
||||
|
||||
if err := checkCriticalChunk(chunkType, seen); err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
|
||||
data, err := readChunkData(reader, checksum, length)
|
||||
if err != nil {
|
||||
return Info{}, corrupt("png chunk data", err)
|
||||
}
|
||||
|
||||
var crcBytes [4]byte
|
||||
if _, err := io.ReadFull(reader, crcBytes[:]); err != nil {
|
||||
return Info{}, corrupt("png chunk crc", err)
|
||||
}
|
||||
|
||||
if binary.BigEndian.Uint32(crcBytes[:]) != checksum.Sum32() {
|
||||
return Info{}, corruptf("png chunk %q crc mismatch", chunkType)
|
||||
}
|
||||
|
||||
switch chunkType {
|
||||
case "IHDR":
|
||||
if length != 13 {
|
||||
return Info{}, corruptf("png IHDR length %d", length)
|
||||
}
|
||||
|
||||
info.Width = int64(binary.BigEndian.Uint32(data[0:4]))
|
||||
info.Height = int64(binary.BigEndian.Uint32(data[4:8]))
|
||||
|
||||
if info.Width <= 0 || info.Height <= 0 {
|
||||
return Info{}, corruptf("png dimensions %dx%d", info.Width, info.Height)
|
||||
}
|
||||
|
||||
// Short-circuit before multiplying: a malicious IHDR can contain
|
||||
// 32-bit dimensions whose product overflows int64.
|
||||
if maxPixels > 0 && (info.Width > maxPixels || info.Height > maxPixels || info.Width*info.Height > maxPixels) {
|
||||
return Info{}, fmt.Errorf("%w: %dx%d", ErrTooLarge, info.Width, info.Height)
|
||||
}
|
||||
case "IDAT":
|
||||
hasIDAT = true
|
||||
case "IEND":
|
||||
if length != 0 {
|
||||
return Info{}, corruptf("png IEND length %d", length)
|
||||
}
|
||||
|
||||
if !hasIDAT {
|
||||
return Info{}, corruptf("png has no IDAT chunk")
|
||||
}
|
||||
|
||||
if _, err := io.Copy(io.Discard, reader); err != nil {
|
||||
return Info{}, corrupt("png trailing data", err)
|
||||
}
|
||||
|
||||
return info, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func checkCriticalChunk(chunkType string, seen map[string]bool) error {
|
||||
if chunkType == "IHDR" || chunkType == "PLTE" || chunkType == "IDAT" || chunkType == "IEND" {
|
||||
seen[chunkType] = true
|
||||
return nil
|
||||
}
|
||||
|
||||
if chunkType[0] >= 'A' && chunkType[0] <= 'Z' {
|
||||
return corruptf("png unknown critical chunk %q", chunkType)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func readChunkData(reader io.Reader, checksum io.Writer, length int64) ([]byte, error) {
|
||||
if length <= 64<<10 {
|
||||
data := make([]byte, length)
|
||||
if _, err := io.ReadFull(reader, data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_, _ = checksum.Write(data)
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
if _, err := io.CopyN(checksum, reader, length); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func validateJPEG(reader *bufio.Reader, maxPixels int64) (Info, error) {
|
||||
if _, err := reader.Discard(2); err != nil {
|
||||
return Info{}, corrupt("jpeg SOI", err)
|
||||
}
|
||||
|
||||
var (
|
||||
info Info
|
||||
hasSOF bool
|
||||
hasSOS bool
|
||||
pending byte
|
||||
markerErr error
|
||||
)
|
||||
|
||||
info.ContentType = "image/jpeg"
|
||||
|
||||
for {
|
||||
marker := pending
|
||||
pending = 0
|
||||
|
||||
if marker == 0 {
|
||||
marker, markerErr = nextMarker(reader)
|
||||
if markerErr != nil {
|
||||
return Info{}, corrupt("jpeg marker", markerErr)
|
||||
}
|
||||
}
|
||||
|
||||
switch {
|
||||
case marker == 0xD9: // EOI
|
||||
if !hasSOF || !hasSOS {
|
||||
return Info{}, corruptf("jpeg missing SOF or SOS")
|
||||
}
|
||||
|
||||
if _, err := io.Copy(io.Discard, reader); err != nil {
|
||||
return Info{}, corrupt("jpeg trailing data", err)
|
||||
}
|
||||
|
||||
return info, nil
|
||||
case isStandalone(marker):
|
||||
continue
|
||||
}
|
||||
|
||||
length, err := readUint16(reader)
|
||||
if err != nil {
|
||||
return Info{}, corrupt("jpeg segment length", err)
|
||||
}
|
||||
|
||||
if length < 2 {
|
||||
return Info{}, corruptf("jpeg segment %02x length %d", marker, length)
|
||||
}
|
||||
|
||||
data := make([]byte, int(length)-2)
|
||||
if _, err := io.ReadFull(reader, data); err != nil {
|
||||
return Info{}, corrupt("jpeg segment data", err)
|
||||
}
|
||||
|
||||
switch {
|
||||
case isSOF(marker):
|
||||
if len(data) < 5 {
|
||||
return Info{}, corruptf("jpeg SOF %02x is too short", marker)
|
||||
}
|
||||
|
||||
info.Height = int64(binary.BigEndian.Uint16(data[1:3]))
|
||||
info.Width = int64(binary.BigEndian.Uint16(data[3:5]))
|
||||
|
||||
if info.Width <= 0 || info.Height <= 0 {
|
||||
return Info{}, corruptf("jpeg dimensions %dx%d", info.Width, info.Height)
|
||||
}
|
||||
|
||||
hasSOF = true
|
||||
|
||||
if maxPixels > 0 && info.Width*info.Height > maxPixels {
|
||||
return Info{}, fmt.Errorf("%w: %dx%d", ErrTooLarge, info.Width, info.Height)
|
||||
}
|
||||
case marker == 0xDA: // SOS
|
||||
hasSOS = true
|
||||
|
||||
next, err := scanEntropy(reader)
|
||||
if err != nil {
|
||||
return Info{}, corrupt("jpeg scan", err)
|
||||
}
|
||||
|
||||
pending = next
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func nextMarker(reader *bufio.Reader) (byte, error) {
|
||||
for {
|
||||
value, err := reader.ReadByte()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if value != 0xFF {
|
||||
return 0, fmt.Errorf("unexpected byte %02x before marker", value)
|
||||
}
|
||||
|
||||
value, err = reader.ReadByte()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if value == 0xFF {
|
||||
continue
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
}
|
||||
|
||||
// scanEntropy consumes entropy-coded data after SOS and returns the next
|
||||
// non-RST marker (0xFF prefix consumed).
|
||||
func scanEntropy(reader *bufio.Reader) (byte, error) {
|
||||
for {
|
||||
value, err := reader.ReadByte()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if value != 0xFF {
|
||||
continue
|
||||
}
|
||||
|
||||
value, err = reader.ReadByte()
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
switch {
|
||||
case value == 0x00:
|
||||
continue
|
||||
case value >= 0xD0 && value <= 0xD7:
|
||||
continue
|
||||
default:
|
||||
return value, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func readUint16(reader io.Reader) (uint16, error) {
|
||||
var raw [2]byte
|
||||
if _, err := io.ReadFull(reader, raw[:]); err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
return binary.BigEndian.Uint16(raw[:]), nil
|
||||
}
|
||||
|
||||
func isSOF(marker byte) bool {
|
||||
switch marker {
|
||||
case 0xC0, 0xC1, 0xC2, 0xC3, 0xC5, 0xC6, 0xC7, 0xC9, 0xCA, 0xCB, 0xCD, 0xCE, 0xCF:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func isStandalone(marker byte) bool {
|
||||
return marker == 0x01 || (marker >= 0xD0 && marker <= 0xD7)
|
||||
}
|
||||
|
||||
func corrupt(context string, err error) error {
|
||||
return fmt.Errorf("%w: %s: %w", ErrCorrupt, context, err)
|
||||
}
|
||||
|
||||
func corruptf(format string, args ...any) error {
|
||||
return fmt.Errorf("%w: %s", ErrCorrupt, fmt.Sprintf(format, args...))
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package imagecheck_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/imagecheck"
|
||||
)
|
||||
|
||||
func encodePNG(t *testing.T, width, height int) []byte {
|
||||
t.Helper()
|
||||
|
||||
source := image.NewRGBA(image.Rect(0, 0, width, height))
|
||||
for x := range width {
|
||||
for y := range height {
|
||||
source.Set(x, y, color.RGBA{R: uint8(x), G: uint8(y), B: 128, A: 255})
|
||||
}
|
||||
}
|
||||
|
||||
var buffer bytes.Buffer
|
||||
require.NoError(t, png.Encode(&buffer, source))
|
||||
|
||||
return buffer.Bytes()
|
||||
}
|
||||
|
||||
func encodeJPEG(t *testing.T, width, height int) []byte {
|
||||
t.Helper()
|
||||
|
||||
source := image.NewRGBA(image.Rect(0, 0, width, height))
|
||||
for x := range width {
|
||||
for y := range height {
|
||||
source.Set(x, y, color.RGBA{R: uint8(x), G: uint8(y), B: 64, A: 255})
|
||||
}
|
||||
}
|
||||
|
||||
var buffer bytes.Buffer
|
||||
require.NoError(t, jpeg.Encode(&buffer, source, &jpeg.Options{Quality: 90}))
|
||||
|
||||
return buffer.Bytes()
|
||||
}
|
||||
|
||||
func TestValidatePNG(t *testing.T) {
|
||||
info, err := imagecheck.Validate(bytes.NewReader(encodePNG(t, 32, 20)), 40_000_000)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "image/png", info.ContentType)
|
||||
require.Equal(t, int64(32), info.Width)
|
||||
require.Equal(t, int64(20), info.Height)
|
||||
}
|
||||
|
||||
func TestValidateJPEG(t *testing.T) {
|
||||
info, err := imagecheck.Validate(bytes.NewReader(encodeJPEG(t, 24, 16)), 40_000_000)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "image/jpeg", info.ContentType)
|
||||
require.Equal(t, int64(24), info.Width)
|
||||
require.Equal(t, int64(16), info.Height)
|
||||
}
|
||||
|
||||
func TestValidateRejectsUnsupported(t *testing.T) {
|
||||
_, err := imagecheck.Validate(bytes.NewReader([]byte("not an image at all")), 40_000_000)
|
||||
require.ErrorIs(t, err, imagecheck.ErrUnsupported)
|
||||
|
||||
_, err = imagecheck.Validate(bytes.NewReader(nil), 40_000_000)
|
||||
require.ErrorIs(t, err, imagecheck.ErrUnsupported)
|
||||
}
|
||||
|
||||
func TestValidateRejectsTruncatedPNG(t *testing.T) {
|
||||
data := encodePNG(t, 64, 64)
|
||||
_, err := imagecheck.Validate(bytes.NewReader(data[:len(data)/2]), 40_000_000)
|
||||
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
|
||||
}
|
||||
|
||||
func TestValidateRejectsPNGCRCMismatch(t *testing.T) {
|
||||
data := encodePNG(t, 64, 64)
|
||||
index := bytes.Index(data, []byte("IDAT"))
|
||||
require.Positive(t, index)
|
||||
data[index+8] ^= 0xFF // first IDAT payload byte; CRC no longer matches
|
||||
|
||||
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
|
||||
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
|
||||
}
|
||||
|
||||
func TestValidateRejectsTruncatedJPEG(t *testing.T) {
|
||||
data := encodeJPEG(t, 64, 64)
|
||||
_, err := imagecheck.Validate(bytes.NewReader(data[:len(data)-32]), 40_000_000)
|
||||
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
|
||||
}
|
||||
|
||||
func TestValidateRejectsTooManyPixels(t *testing.T) {
|
||||
_, err := imagecheck.Validate(bytes.NewReader(encodePNG(t, 100, 100)), 9_999)
|
||||
require.ErrorIs(t, err, imagecheck.ErrTooLarge)
|
||||
|
||||
_, err = imagecheck.Validate(bytes.NewReader(encodeJPEG(t, 100, 100)), 9_999)
|
||||
require.ErrorIs(t, err, imagecheck.ErrTooLarge)
|
||||
}
|
||||
|
||||
func TestValidateAllowsTrailingBytes(t *testing.T) {
|
||||
pngData := append(encodePNG(t, 8, 8), []byte("trailing")...)
|
||||
_, err := imagecheck.Validate(bytes.NewReader(pngData), 40_000_000)
|
||||
require.NoError(t, err)
|
||||
|
||||
jpegData := append(encodeJPEG(t, 8, 8), []byte("trailing")...)
|
||||
_, err = imagecheck.Validate(bytes.NewReader(jpegData), 40_000_000)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package logger
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrUnknownLevel = errors.New("unknown log level")
|
||||
ErrUnknownFormat = errors.New("unknown log format")
|
||||
)
|
||||
@@ -0,0 +1,138 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"go.uber.org/zap/exp/zapslog"
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
type Format string
|
||||
|
||||
const (
|
||||
FormatJSON Format = "json"
|
||||
FormatConsole Format = "console"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultLevel = slog.LevelInfo
|
||||
DefaultFormat = FormatJSON
|
||||
)
|
||||
|
||||
type options struct {
|
||||
writer io.Writer
|
||||
level slog.Level
|
||||
format Format
|
||||
name string
|
||||
}
|
||||
|
||||
type Option func(*options)
|
||||
|
||||
func WithWriter(writer io.Writer) Option {
|
||||
return func(opts *options) {
|
||||
if writer != nil {
|
||||
opts.writer = writer
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func WithLevel(level slog.Level) Option {
|
||||
return func(opts *options) {
|
||||
opts.level = level
|
||||
}
|
||||
}
|
||||
|
||||
func WithFormat(format Format) Option {
|
||||
return func(opts *options) {
|
||||
if format != "" {
|
||||
opts.format = format
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func WithName(name string) Option {
|
||||
return func(opts *options) {
|
||||
opts.name = name
|
||||
}
|
||||
}
|
||||
|
||||
func New(options ...Option) *slog.Logger {
|
||||
opts := optionsConfig()
|
||||
for _, option := range options {
|
||||
option(&opts)
|
||||
}
|
||||
|
||||
encoderCfg := zapcore.EncoderConfig{
|
||||
TimeKey: "time",
|
||||
LevelKey: "level",
|
||||
NameKey: "logger",
|
||||
CallerKey: "caller",
|
||||
MessageKey: "msg",
|
||||
StacktraceKey: "stacktrace",
|
||||
LineEnding: zapcore.DefaultLineEnding,
|
||||
EncodeLevel: zapcore.LowercaseLevelEncoder,
|
||||
EncodeTime: zapcore.RFC3339NanoTimeEncoder,
|
||||
EncodeDuration: zapcore.StringDurationEncoder,
|
||||
EncodeCaller: zapcore.ShortCallerEncoder,
|
||||
}
|
||||
|
||||
var encoder zapcore.Encoder
|
||||
if opts.format == FormatConsole {
|
||||
encoder = zapcore.NewConsoleEncoder(encoderCfg)
|
||||
} else {
|
||||
encoder = zapcore.NewJSONEncoder(encoderCfg)
|
||||
}
|
||||
|
||||
core := zapcore.NewCore(encoder, zapcore.AddSync(opts.writer), zapLevel(opts.level))
|
||||
handlerOptions := make([]zapslog.HandlerOption, 0, 1)
|
||||
if opts.name != "" {
|
||||
handlerOptions = append(handlerOptions, zapslog.WithName(opts.name))
|
||||
}
|
||||
|
||||
return slog.New(zapslog.NewHandler(core, handlerOptions...))
|
||||
}
|
||||
|
||||
func optionsConfig() options {
|
||||
return options{
|
||||
writer: os.Stdout,
|
||||
level: DefaultLevel,
|
||||
format: DefaultFormat,
|
||||
}
|
||||
}
|
||||
|
||||
func ParseLevel(raw string) (slog.Level, error) {
|
||||
var level slog.Level
|
||||
if err := level.UnmarshalText([]byte(strings.TrimSpace(raw))); err != nil {
|
||||
return 0, fmt.Errorf("%q: %w", raw, ErrUnknownLevel)
|
||||
}
|
||||
|
||||
return level, nil
|
||||
}
|
||||
|
||||
func ParseFormat(raw string) (Format, error) {
|
||||
switch Format(strings.ToLower(strings.TrimSpace(raw))) {
|
||||
case FormatJSON:
|
||||
return FormatJSON, nil
|
||||
case FormatConsole:
|
||||
return FormatConsole, nil
|
||||
default:
|
||||
return "", fmt.Errorf("%q: %w", raw, ErrUnknownFormat)
|
||||
}
|
||||
}
|
||||
|
||||
func zapLevel(level slog.Level) zapcore.Level {
|
||||
switch {
|
||||
case level < slog.LevelInfo:
|
||||
return zapcore.DebugLevel
|
||||
case level < slog.LevelWarn:
|
||||
return zapcore.InfoLevel
|
||||
case level < slog.LevelError:
|
||||
return zapcore.WarnLevel
|
||||
default:
|
||||
return zapcore.ErrorLevel
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,193 @@
|
||||
package logger_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/logger"
|
||||
)
|
||||
|
||||
type LoggerSuite struct {
|
||||
suite.Suite
|
||||
|
||||
bb *bytes.Buffer
|
||||
}
|
||||
|
||||
func TestLoggerSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, new(LoggerSuite))
|
||||
}
|
||||
|
||||
func (s *LoggerSuite) SetupTest() {
|
||||
s.bb = &bytes.Buffer{}
|
||||
}
|
||||
|
||||
func (s *LoggerSuite) records() []map[string]any {
|
||||
var out []map[string]any
|
||||
|
||||
for line := range strings.SplitSeq(strings.TrimSpace(s.bb.String()), "\n") {
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
var record map[string]any
|
||||
s.Require().NoError(json.Unmarshal([]byte(line), &record))
|
||||
|
||||
out = append(out, record)
|
||||
}
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func (s *LoggerSuite) TestJSONOutputCarriesAttributes() {
|
||||
log := logger.New(logger.WithWriter(s.bb))
|
||||
|
||||
log.Info("сервер запущен", slog.String("addr", "0.0.0.0:8080"))
|
||||
|
||||
records := s.records()
|
||||
s.Require().Len(records, 1)
|
||||
|
||||
s.Equal("info", records[0]["level"])
|
||||
s.Equal("сервер запущен", records[0]["msg"])
|
||||
s.Equal("0.0.0.0:8080", records[0]["addr"])
|
||||
s.Contains(records[0], "time")
|
||||
}
|
||||
|
||||
func (s *LoggerSuite) TestDefaultLevelDropsDebug() {
|
||||
log := logger.New(logger.WithWriter(s.bb))
|
||||
|
||||
log.Debug("не должно попасть в вывод")
|
||||
log.Info("должно попасть")
|
||||
|
||||
records := s.records()
|
||||
s.Require().Len(records, 1)
|
||||
s.Equal("должно попасть", records[0]["msg"])
|
||||
}
|
||||
|
||||
func (s *LoggerSuite) TestWithLevelEnablesDebug() {
|
||||
log := logger.New(logger.WithWriter(s.bb), logger.WithLevel(slog.LevelDebug))
|
||||
|
||||
log.Debug("подробность")
|
||||
|
||||
records := s.records()
|
||||
s.Require().Len(records, 1)
|
||||
s.Equal("debug", records[0]["level"])
|
||||
}
|
||||
|
||||
func (s *LoggerSuite) TestGroupsAreNested() {
|
||||
log := logger.New(logger.WithWriter(s.bb))
|
||||
|
||||
log.Info("запрос", slog.Group("payload", slog.Int("size", 12)))
|
||||
|
||||
records := s.records()
|
||||
s.Require().Len(records, 1)
|
||||
|
||||
payload, ok := records[0]["payload"].(map[string]any)
|
||||
s.Require().True(ok, "группа должна кодироваться вложенным объектом")
|
||||
s.InDelta(12, payload["size"], 0)
|
||||
}
|
||||
|
||||
func (s *LoggerSuite) TestWithNameSetsLoggerField() {
|
||||
log := logger.New(logger.WithWriter(s.bb), logger.WithName("messenger"))
|
||||
|
||||
log.Info("старт")
|
||||
|
||||
records := s.records()
|
||||
s.Require().Len(records, 1)
|
||||
s.Equal("messenger", records[0]["logger"])
|
||||
}
|
||||
|
||||
func (s *LoggerSuite) TestConsoleFormatIsNotJSON() {
|
||||
log := logger.New(s.consoleOptions()...)
|
||||
|
||||
log.Info("человекочитаемо")
|
||||
|
||||
line := strings.TrimSpace(s.bb.String())
|
||||
s.Require().NotEmpty(line)
|
||||
|
||||
var record map[string]any
|
||||
s.Require().Error(json.Unmarshal([]byte(line), &record), "console-формат не должен быть JSON")
|
||||
s.Contains(line, "человекочитаемо")
|
||||
}
|
||||
|
||||
func (s *LoggerSuite) consoleOptions() []logger.Option {
|
||||
return []logger.Option{
|
||||
logger.WithWriter(s.bb),
|
||||
logger.WithFormat(logger.FormatConsole),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *LoggerSuite) TestNilWriterKeepsDefault() {
|
||||
s.Require().NotPanics(func() {
|
||||
logger.New(logger.WithWriter(nil)).Info("пишем в stdout по умолчанию")
|
||||
})
|
||||
}
|
||||
|
||||
func TestParseLevel(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := map[string]struct {
|
||||
want slog.Level
|
||||
wantErr bool
|
||||
}{
|
||||
"debug": {want: slog.LevelDebug},
|
||||
"info": {want: slog.LevelInfo},
|
||||
"WARN": {want: slog.LevelWarn},
|
||||
"error": {want: slog.LevelError},
|
||||
"trace": {wantErr: true},
|
||||
"": {wantErr: true},
|
||||
}
|
||||
|
||||
for raw, tt := range tests {
|
||||
t.Run(raw, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
got, err := logger.ParseLevel(raw)
|
||||
if tt.wantErr {
|
||||
require.ErrorIs(t, err, logger.ErrUnknownLevel)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tt.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseFormat(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := map[string]struct {
|
||||
want logger.Format
|
||||
wantErr bool
|
||||
}{
|
||||
"json": {want: logger.FormatJSON},
|
||||
"JSON": {want: logger.FormatJSON},
|
||||
"console": {want: logger.FormatConsole},
|
||||
"xml": {wantErr: true},
|
||||
"": {wantErr: true},
|
||||
}
|
||||
|
||||
for raw, tt := range tests {
|
||||
t.Run(raw, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
got, err := logger.ParseFormat(raw)
|
||||
if tt.wantErr {
|
||||
require.ErrorIs(t, err, logger.ErrUnknownFormat)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tt.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
Vendored
+31
@@ -0,0 +1,31 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrCacheMiss = errors.New("cache miss")
|
||||
|
||||
type Cache interface {
|
||||
Get(ctx context.Context, key string) ([]byte, error)
|
||||
Set(ctx context.Context, key string, value []byte, ttl time.Duration) error
|
||||
Delete(ctx context.Context, keys ...string) error
|
||||
Ping(ctx context.Context) error
|
||||
Close() error
|
||||
}
|
||||
|
||||
type NoOpCache struct{}
|
||||
|
||||
func (NoOpCache) Get(context.Context, string) ([]byte, error) { return nil, ErrCacheMiss }
|
||||
func (NoOpCache) Set(context.Context, string, []byte, time.Duration) error { return nil }
|
||||
func (NoOpCache) Delete(context.Context, ...string) error { return nil }
|
||||
func (NoOpCache) AcquireLock(context.Context, string, string, time.Duration) (bool, error) {
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (NoOpCache) ReleaseLock(context.Context, string, string) (bool, error) { return true, nil }
|
||||
func (NoOpCache) LockHeld(context.Context, string) (bool, error) { return false, nil }
|
||||
func (NoOpCache) Ping(context.Context) error { return nil }
|
||||
func (NoOpCache) Close() error { return nil }
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package cache_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/platform/cache"
|
||||
)
|
||||
|
||||
func TestNoOpCache(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := t.Context()
|
||||
store := cache.NoOpCache{}
|
||||
require.NoError(t, store.Set(ctx, "key", []byte("value"), time.Minute))
|
||||
_, err := store.Get(ctx, "key")
|
||||
require.ErrorIs(t, err, cache.ErrCacheMiss)
|
||||
require.NoError(t, store.Delete(ctx, "key"))
|
||||
acquired, err := store.AcquireLock(ctx, "lock", "token", time.Second)
|
||||
require.NoError(t, err)
|
||||
require.True(t, acquired)
|
||||
held, err := store.LockHeld(ctx, "lock")
|
||||
require.NoError(t, err)
|
||||
require.False(t, held)
|
||||
released, err := store.ReleaseLock(ctx, "lock", "token")
|
||||
require.NoError(t, err)
|
||||
require.True(t, released)
|
||||
require.NoError(t, store.Ping(ctx))
|
||||
require.NoError(t, store.Close())
|
||||
}
|
||||
+307
@@ -0,0 +1,307 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
mathrand "math/rand/v2"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"golang.org/x/sync/singleflight"
|
||||
)
|
||||
|
||||
const (
|
||||
DefaultLockTTL = 10 * time.Second
|
||||
DefaultWaitTimeout = 2 * time.Second
|
||||
minLockTTL = time.Second
|
||||
redisOpTimeout = 200 * time.Millisecond
|
||||
releaseTimeout = 300 * time.Millisecond
|
||||
)
|
||||
|
||||
type DistributedConfig struct {
|
||||
LockTTL time.Duration
|
||||
WaitTimeout time.Duration
|
||||
}
|
||||
|
||||
type LockStore interface {
|
||||
Cache
|
||||
AcquireLock(ctx context.Context, key, token string, ttl time.Duration) (bool, error)
|
||||
ReleaseLock(ctx context.Context, key, token string) (bool, error)
|
||||
LockHeld(ctx context.Context, key string) (bool, error)
|
||||
}
|
||||
|
||||
type DistributedCache struct {
|
||||
store LockStore
|
||||
lockTTL time.Duration
|
||||
waitTimeout time.Duration
|
||||
log *slog.Logger
|
||||
group singleflight.Group
|
||||
}
|
||||
|
||||
var fallbackTokenCounter atomic.Uint64
|
||||
|
||||
func NewDistributed(store LockStore, cfg DistributedConfig, log *slog.Logger) (*DistributedCache, error) {
|
||||
if cfg.LockTTL <= 0 {
|
||||
cfg.LockTTL = DefaultLockTTL
|
||||
}
|
||||
|
||||
if cfg.WaitTimeout <= 0 {
|
||||
cfg.WaitTimeout = DefaultWaitTimeout
|
||||
}
|
||||
|
||||
if cfg.LockTTL <= minLockTTL {
|
||||
return nil, fmt.Errorf("cache: lock ttl %s must be greater than %s", cfg.LockTTL, minLockTTL)
|
||||
}
|
||||
|
||||
if cfg.WaitTimeout > cfg.LockTTL {
|
||||
return nil, fmt.Errorf("cache: wait timeout %s must not exceed lock ttl %s", cfg.WaitTimeout, cfg.LockTTL)
|
||||
}
|
||||
|
||||
return &DistributedCache{
|
||||
store: store,
|
||||
lockTTL: cfg.LockTTL,
|
||||
waitTimeout: cfg.WaitTimeout,
|
||||
log: log,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (d *DistributedCache) GetOrLoad(
|
||||
ctx context.Context,
|
||||
key string,
|
||||
ttl time.Duration,
|
||||
loader func(ctx context.Context) ([]byte, error),
|
||||
) ([]byte, error) {
|
||||
ch := d.group.DoChan(key, func() (any, error) {
|
||||
lctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), d.lockTTL+d.waitTimeout)
|
||||
defer cancel()
|
||||
|
||||
return d.getOrLoad(lctx, key, ttl, loader)
|
||||
})
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
case result := <-ch:
|
||||
if result.Err != nil {
|
||||
return nil, result.Err
|
||||
}
|
||||
|
||||
value, ok := result.Val.([]byte)
|
||||
if !ok {
|
||||
return nil, errors.New("cache: unexpected singleflight result")
|
||||
}
|
||||
|
||||
return bytes.Clone(value), nil
|
||||
}
|
||||
}
|
||||
|
||||
func (d *DistributedCache) getOrLoad(
|
||||
ctx context.Context,
|
||||
key string,
|
||||
ttl time.Duration,
|
||||
loader func(ctx context.Context) ([]byte, error),
|
||||
) ([]byte, error) {
|
||||
lockKey := "lock:" + key
|
||||
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if value, err := d.store.Get(ctx, key); err == nil {
|
||||
return value, nil
|
||||
} else if !errors.Is(err, ErrCacheMiss) {
|
||||
return loader(ctx)
|
||||
}
|
||||
|
||||
token := randomToken()
|
||||
|
||||
acquired, err := d.store.AcquireLock(ctx, lockKey, token, d.lockTTL)
|
||||
if err != nil {
|
||||
return loader(ctx)
|
||||
}
|
||||
|
||||
if acquired {
|
||||
return d.fill(ctx, key, lockKey, token, ttl, loader)
|
||||
}
|
||||
|
||||
value, outcome, err := d.await(ctx, key, lockKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch outcome {
|
||||
case waitHit:
|
||||
return value, nil
|
||||
case waitDegraded:
|
||||
return loader(ctx)
|
||||
case waitTimeout:
|
||||
return loader(ctx)
|
||||
case waitRetry:
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
case waitNone:
|
||||
return nil, errors.New("cache: unexpected wait outcome")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (d *DistributedCache) fill(
|
||||
ctx context.Context,
|
||||
key, lockKey, token string,
|
||||
ttl time.Duration,
|
||||
loader func(ctx context.Context) ([]byte, error),
|
||||
) ([]byte, error) {
|
||||
base := context.WithoutCancel(ctx)
|
||||
|
||||
defer func() {
|
||||
rctx, cancel := context.WithTimeout(base, releaseTimeout)
|
||||
defer cancel()
|
||||
|
||||
held, err := d.store.ReleaseLock(rctx, lockKey, token)
|
||||
switch {
|
||||
case err != nil:
|
||||
d.warn(base, "lock release failed", key, err)
|
||||
case !held:
|
||||
d.warn(base, "lock expired before release: loader slower than lock ttl", key, nil)
|
||||
}
|
||||
}()
|
||||
|
||||
getCtx, cancelGet := context.WithTimeout(base, redisOpTimeout)
|
||||
value, err := d.store.Get(getCtx, key)
|
||||
cancelGet()
|
||||
|
||||
if err == nil {
|
||||
return value, nil
|
||||
}
|
||||
|
||||
loadCtx, cancel := context.WithTimeout(base, d.lockTTL-minLockTTL)
|
||||
defer cancel()
|
||||
|
||||
value, err = loader(loadCtx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
setCtx, cancelSet := context.WithTimeout(base, redisOpTimeout)
|
||||
setErr := d.store.Set(setCtx, key, value, ttl)
|
||||
cancelSet()
|
||||
|
||||
if setErr != nil {
|
||||
d.warn(base, "distributed cache write failed", key, setErr)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
type waitOutcome int
|
||||
|
||||
const (
|
||||
waitNone waitOutcome = iota
|
||||
waitHit
|
||||
waitRetry
|
||||
waitTimeout
|
||||
waitDegraded
|
||||
)
|
||||
|
||||
func (d *DistributedCache) await(ctx context.Context, key, lockKey string) ([]byte, waitOutcome, error) {
|
||||
wctx, cancel := context.WithTimeout(ctx, d.waitTimeout)
|
||||
defer cancel()
|
||||
|
||||
for attempt := 1; ; attempt++ {
|
||||
value, err := d.store.Get(wctx, key)
|
||||
switch {
|
||||
case err == nil:
|
||||
return value, waitHit, nil
|
||||
case ctx.Err() != nil:
|
||||
return nil, waitNone, ctx.Err()
|
||||
case wctx.Err() != nil:
|
||||
return nil, waitTimeout, nil
|
||||
case !errors.Is(err, ErrCacheMiss):
|
||||
return nil, waitDegraded, nil
|
||||
}
|
||||
|
||||
if held, err := d.store.LockHeld(wctx, lockKey); err == nil && !held {
|
||||
return nil, waitRetry, nil
|
||||
}
|
||||
|
||||
select {
|
||||
case <-wctx.Done():
|
||||
if err := ctx.Err(); err != nil {
|
||||
return nil, waitNone, err
|
||||
}
|
||||
|
||||
return nil, waitTimeout, nil
|
||||
case <-time.After(jittered(waitBackoff(attempt))):
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (d *DistributedCache) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
return d.store.Get(ctx, key)
|
||||
}
|
||||
|
||||
func (d *DistributedCache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error {
|
||||
return d.store.Set(ctx, key, value, ttl)
|
||||
}
|
||||
|
||||
func (d *DistributedCache) Delete(ctx context.Context, keys ...string) error {
|
||||
return d.store.Delete(ctx, keys...)
|
||||
}
|
||||
|
||||
func (d *DistributedCache) Ping(ctx context.Context) error {
|
||||
return d.store.Ping(ctx)
|
||||
}
|
||||
|
||||
func (d *DistributedCache) Close() error {
|
||||
return d.store.Close()
|
||||
}
|
||||
|
||||
func (d *DistributedCache) warn(ctx context.Context, msg, key string, err error) {
|
||||
if d.log == nil {
|
||||
return
|
||||
}
|
||||
|
||||
attrs := []slog.Attr{slog.String("key", key)}
|
||||
if err != nil {
|
||||
attrs = append(attrs, slog.Any("error", err))
|
||||
}
|
||||
|
||||
d.log.LogAttrs(ctx, slog.LevelWarn, msg, attrs...)
|
||||
}
|
||||
|
||||
func waitBackoff(attempt int) time.Duration {
|
||||
const base, maxWait = 50 * time.Millisecond, 500 * time.Millisecond
|
||||
if attempt > 4 {
|
||||
return maxWait
|
||||
}
|
||||
|
||||
return base << (attempt - 1)
|
||||
}
|
||||
|
||||
func jittered(d time.Duration) time.Duration {
|
||||
half := d / 2
|
||||
if half <= 0 {
|
||||
return d
|
||||
}
|
||||
|
||||
return half + mathrand.N(half)
|
||||
}
|
||||
|
||||
func randomToken() string {
|
||||
raw := make([]byte, 16)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
counter := fallbackTokenCounter.Add(1)
|
||||
|
||||
return strconv.FormatInt(time.Now().UnixNano(), 10) + ":" + strconv.FormatUint(counter, 10)
|
||||
}
|
||||
|
||||
return hex.EncodeToString(raw)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/platform/cache/mocks"
|
||||
)
|
||||
|
||||
func TestAwaitChecksCacheBeforePolling(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := mocks.NewMockLockStore(t)
|
||||
store.EXPECT().Get(mock.Anything, "key").Return([]byte("ready"), nil).Once()
|
||||
|
||||
d, err := NewDistributed(store, DistributedConfig{WaitTimeout: time.Second}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
started := time.Now()
|
||||
value, outcome, err := d.await(t.Context(), "key", "lock:key")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, waitHit, outcome)
|
||||
require.Equal(t, "ready", string(value))
|
||||
require.Less(t, time.Since(started), 25*time.Millisecond, "cache must be checked before the first sleep")
|
||||
}
|
||||
|
||||
func TestAwaitReturnsTimeoutWhileLockHeld(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := mocks.NewMockLockStore(t)
|
||||
store.EXPECT().Get(mock.Anything, "key").Return(nil, ErrCacheMiss).Maybe()
|
||||
store.EXPECT().LockHeld(mock.Anything, "lock:key").Return(true, nil).Maybe()
|
||||
|
||||
d, err := NewDistributed(store, DistributedConfig{WaitTimeout: 60 * time.Millisecond}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, outcome, err := d.await(t.Context(), "key", "lock:key")
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, waitTimeout, outcome)
|
||||
}
|
||||
+374
@@ -0,0 +1,374 @@
|
||||
package cache_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/platform/cache"
|
||||
"mtusi-messenger/internal/platform/cache/mocks"
|
||||
)
|
||||
|
||||
func newDistributed(t *testing.T, store cache.LockStore, cfg cache.DistributedConfig) *cache.DistributedCache {
|
||||
t.Helper()
|
||||
|
||||
dc, err := cache.NewDistributed(store, cfg, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
return dc
|
||||
}
|
||||
|
||||
func expectFill(store *mocks.MockLockStore, key string) {
|
||||
store.EXPECT().Get(mock.Anything, key).Return(nil, cache.ErrCacheMiss).Once()
|
||||
store.EXPECT().AcquireLock(mock.Anything, "lock:"+key, mock.AnythingOfType("string"), mock.Anything).Return(true, nil).Once()
|
||||
store.EXPECT().Get(mock.Anything, key).Return(nil, cache.ErrCacheMiss).Once()
|
||||
store.EXPECT().Set(mock.Anything, key, mock.Anything, mock.Anything).Return(nil).Once()
|
||||
store.EXPECT().ReleaseLock(mock.Anything, "lock:"+key, mock.AnythingOfType("string")).Return(true, nil).Once()
|
||||
}
|
||||
|
||||
// sharedWaitTimeout bounds every wait in these tests: a stuck helper must fail
|
||||
// the test instead of hanging the whole package until -timeout fires.
|
||||
const sharedWaitTimeout = 5 * time.Second
|
||||
|
||||
func awaitSignal(t *testing.T, ch <-chan struct{}, message string) {
|
||||
t.Helper()
|
||||
|
||||
select {
|
||||
case <-ch:
|
||||
case <-time.After(sharedWaitTimeout):
|
||||
t.Fatal("timed out: " + message)
|
||||
}
|
||||
}
|
||||
|
||||
func awaitValue[T any](t *testing.T, ch <-chan T) T {
|
||||
t.Helper()
|
||||
|
||||
select {
|
||||
case value := <-ch:
|
||||
return value
|
||||
case <-time.After(sharedWaitTimeout):
|
||||
var zero T
|
||||
|
||||
t.Fatal("timed out waiting for the shared load to report its result")
|
||||
|
||||
return zero
|
||||
}
|
||||
}
|
||||
|
||||
func awaitWaitGroup(t *testing.T, wg *sync.WaitGroup) {
|
||||
t.Helper()
|
||||
|
||||
done := make(chan struct{})
|
||||
|
||||
go func() {
|
||||
wg.Wait()
|
||||
close(done)
|
||||
}()
|
||||
|
||||
awaitSignal(t, done, "goroutines did not finish")
|
||||
}
|
||||
|
||||
func TestDistributedCachesResult(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := mocks.NewMockLockStore(t)
|
||||
dc := newDistributed(t, store, cache.DistributedConfig{})
|
||||
ctx := context.Background()
|
||||
|
||||
var calls atomic.Int32
|
||||
|
||||
loader := func(context.Context) ([]byte, error) {
|
||||
calls.Add(1)
|
||||
|
||||
return []byte("payload"), nil
|
||||
}
|
||||
|
||||
expectFill(store, "key")
|
||||
store.EXPECT().Get(mock.Anything, "key").Return([]byte("payload"), nil).Once()
|
||||
|
||||
first, err := dc.GetOrLoad(ctx, "key", time.Minute, loader)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []byte("payload"), first)
|
||||
|
||||
second, err := dc.GetOrLoad(ctx, "key", time.Minute, loader)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []byte("payload"), second)
|
||||
require.Equal(t, int32(1), calls.Load())
|
||||
}
|
||||
|
||||
func TestDistributedDeduplicatesConcurrentMisses(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := mocks.NewMockLockStore(t)
|
||||
dc := newDistributed(t, store, cache.DistributedConfig{})
|
||||
ctx := context.Background()
|
||||
|
||||
var calls atomic.Int32
|
||||
|
||||
loader := func(context.Context) ([]byte, error) {
|
||||
calls.Add(1)
|
||||
time.Sleep(30 * time.Millisecond)
|
||||
|
||||
return []byte("payload"), nil
|
||||
}
|
||||
|
||||
store.EXPECT().Get(mock.Anything, "shared").Return(nil, cache.ErrCacheMiss).Twice()
|
||||
store.EXPECT().AcquireLock(mock.Anything, "lock:shared", mock.AnythingOfType("string"), mock.Anything).Return(true, nil).Once()
|
||||
store.EXPECT().Set(mock.Anything, "shared", mock.Anything, mock.Anything).Return(nil).Once()
|
||||
store.EXPECT().ReleaseLock(mock.Anything, "lock:shared", mock.AnythingOfType("string")).Return(true, nil).Once()
|
||||
|
||||
const workers = 50
|
||||
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
failures atomic.Int32
|
||||
)
|
||||
|
||||
wg.Add(workers)
|
||||
|
||||
for range workers {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
value, err := dc.GetOrLoad(ctx, "shared", time.Minute, loader)
|
||||
if err != nil || string(value) != "payload" {
|
||||
failures.Add(1)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
awaitWaitGroup(t, &wg)
|
||||
|
||||
require.Zero(t, failures.Load())
|
||||
require.Equal(t, int32(1), calls.Load(), "one instance must load once for concurrent misses")
|
||||
}
|
||||
|
||||
func TestDistributedFallsBackOnWaitTimeout(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := mocks.NewMockLockStore(t)
|
||||
dc := newDistributed(t, store, cache.DistributedConfig{WaitTimeout: 100 * time.Millisecond})
|
||||
ctx := context.Background()
|
||||
|
||||
store.EXPECT().Get(mock.Anything, "key").Return(nil, cache.ErrCacheMiss).Maybe()
|
||||
store.EXPECT().AcquireLock(mock.Anything, "lock:key", mock.AnythingOfType("string"), mock.Anything).Return(false, nil).Once()
|
||||
store.EXPECT().LockHeld(mock.Anything, "lock:key").Return(true, nil).Maybe()
|
||||
|
||||
var calls atomic.Int32
|
||||
|
||||
value, err := dc.GetOrLoad(ctx, "key", time.Minute, func(context.Context) ([]byte, error) {
|
||||
calls.Add(1)
|
||||
|
||||
return []byte("fallback"), nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []byte("fallback"), value)
|
||||
require.Equal(t, int32(1), calls.Load(), "a wait timeout must fall back to a direct load")
|
||||
}
|
||||
|
||||
func TestDistributedSharedLoadSurvivesCallerCancellation(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := mocks.NewMockLockStore(t)
|
||||
dc := newDistributed(t, store, cache.DistributedConfig{})
|
||||
leaderCtx, cancelLeader := context.WithCancel(context.Background())
|
||||
defer cancelLeader()
|
||||
|
||||
var calls atomic.Int32
|
||||
|
||||
started := make(chan struct{})
|
||||
release := make(chan struct{})
|
||||
|
||||
loader := func(loadCtx context.Context) ([]byte, error) {
|
||||
calls.Add(1)
|
||||
close(started)
|
||||
<-release
|
||||
|
||||
if err := loadCtx.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return []byte("value"), nil
|
||||
}
|
||||
|
||||
store.EXPECT().Get(mock.Anything, "key").Return(nil, cache.ErrCacheMiss).Twice()
|
||||
store.EXPECT().AcquireLock(mock.Anything, "lock:key", mock.AnythingOfType("string"), mock.Anything).Return(true, nil).Once()
|
||||
store.EXPECT().Set(mock.Anything, "key", mock.Anything, mock.Anything).Return(nil).Once()
|
||||
store.EXPECT().ReleaseLock(mock.Anything, "lock:key", mock.AnythingOfType("string")).Return(true, nil).Once()
|
||||
|
||||
leaderErr := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
_, err := dc.GetOrLoad(leaderCtx, "key", time.Minute, loader)
|
||||
leaderErr <- err
|
||||
}()
|
||||
|
||||
awaitSignal(t, started, "leader must reach the loader")
|
||||
|
||||
// The follower starts while the leader's loader is still blocked, so the
|
||||
// singleflight call cannot complete: the signal below means DoChan was
|
||||
// already called, i.e. the follower joined the leader's in-flight call
|
||||
// instead of starting its own load.
|
||||
followerJoined := make(chan struct{})
|
||||
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
followerV []byte
|
||||
followerE error
|
||||
)
|
||||
|
||||
wg.Add(1)
|
||||
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
ctx := newJoiningContext(followerJoined)
|
||||
followerV, followerE = dc.GetOrLoad(ctx, "key", time.Minute, loader)
|
||||
}()
|
||||
|
||||
awaitSignal(t, followerJoined, "follower must join the in-flight load")
|
||||
|
||||
cancelLeader()
|
||||
close(release)
|
||||
|
||||
require.ErrorIs(t, awaitValue(t, leaderErr), context.Canceled)
|
||||
awaitWaitGroup(t, &wg)
|
||||
|
||||
require.NoError(t, followerE)
|
||||
require.Equal(t, []byte("value"), followerV)
|
||||
require.Equal(t, int32(1), calls.Load())
|
||||
}
|
||||
|
||||
// joiningContext reports when GetOrLoad reaches the shared-result wait path. The
|
||||
// delegate is kept as function fields so no struct holds a context.Context.
|
||||
type joiningContext struct {
|
||||
deadline func() (time.Time, bool)
|
||||
done func() <-chan struct{}
|
||||
err func() error
|
||||
value func(any) any
|
||||
|
||||
once *sync.Once
|
||||
joined chan struct{}
|
||||
}
|
||||
|
||||
func newJoiningContext(joined chan struct{}) joiningContext {
|
||||
base := context.Background()
|
||||
|
||||
return joiningContext{
|
||||
deadline: base.Deadline,
|
||||
done: base.Done,
|
||||
err: base.Err,
|
||||
value: base.Value,
|
||||
once: new(sync.Once),
|
||||
joined: joined,
|
||||
}
|
||||
}
|
||||
|
||||
func (c joiningContext) Deadline() (time.Time, bool) { return c.deadline() }
|
||||
|
||||
func (c joiningContext) Done() <-chan struct{} {
|
||||
c.once.Do(func() { close(c.joined) })
|
||||
|
||||
return c.done()
|
||||
}
|
||||
|
||||
func (c joiningContext) Err() error { return c.err() }
|
||||
|
||||
func (c joiningContext) Value(key any) any { return c.value(key) }
|
||||
|
||||
func TestDistributedRetriesWhenLockVanishes(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := mocks.NewMockLockStore(t)
|
||||
dc := newDistributed(t, store, cache.DistributedConfig{})
|
||||
ctx := context.Background()
|
||||
|
||||
var released atomic.Bool
|
||||
|
||||
time.AfterFunc(120*time.Millisecond, func() { released.Store(true) })
|
||||
|
||||
store.EXPECT().Get(mock.Anything, "key").Return(nil, cache.ErrCacheMiss).Maybe()
|
||||
store.EXPECT().AcquireLock(mock.Anything, "lock:key", mock.AnythingOfType("string"), mock.Anything).Return(false, nil).Once()
|
||||
store.EXPECT().AcquireLock(mock.Anything, "lock:key", mock.AnythingOfType("string"), mock.Anything).Return(true, nil).Once()
|
||||
store.EXPECT().LockHeld(mock.Anything, "lock:key").RunAndReturn(func(context.Context, string) (bool, error) {
|
||||
return !released.Load(), nil
|
||||
}).Maybe()
|
||||
store.EXPECT().Set(mock.Anything, "key", mock.Anything, mock.Anything).Return(nil).Once()
|
||||
store.EXPECT().ReleaseLock(mock.Anything, "lock:key", mock.AnythingOfType("string")).Return(true, nil).Once()
|
||||
|
||||
var calls atomic.Int32
|
||||
|
||||
value, err := dc.GetOrLoad(ctx, "key", time.Minute, func(context.Context) ([]byte, error) {
|
||||
calls.Add(1)
|
||||
|
||||
return []byte("recovered"), nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []byte("recovered"), value)
|
||||
require.Equal(t, int32(1), calls.Load())
|
||||
}
|
||||
|
||||
func TestFillStoreCallsAreBoundedByDeadline(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
store := mocks.NewMockLockStore(t)
|
||||
dc := newDistributed(t, store, cache.DistributedConfig{})
|
||||
|
||||
var (
|
||||
mu sync.Mutex
|
||||
getBudgets []time.Duration
|
||||
setBudget time.Duration
|
||||
setHasDead bool
|
||||
)
|
||||
|
||||
store.EXPECT().Get(mock.Anything, "key").RunAndReturn(func(ctx context.Context, _ string) ([]byte, error) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
if deadline, ok := ctx.Deadline(); ok {
|
||||
getBudgets = append(getBudgets, time.Until(deadline))
|
||||
}
|
||||
|
||||
return nil, cache.ErrCacheMiss
|
||||
}).Twice()
|
||||
store.EXPECT().AcquireLock(mock.Anything, "lock:key", mock.AnythingOfType("string"), mock.Anything).Return(true, nil).Once()
|
||||
store.EXPECT().Set(mock.Anything, "key", mock.Anything, mock.Anything).
|
||||
RunAndReturn(func(ctx context.Context, _ string, _ []byte, _ time.Duration) error {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
deadline, ok := ctx.Deadline()
|
||||
setHasDead = ok
|
||||
if ok {
|
||||
setBudget = time.Until(deadline)
|
||||
}
|
||||
|
||||
return nil
|
||||
}).Once()
|
||||
store.EXPECT().ReleaseLock(mock.Anything, "lock:key", mock.AnythingOfType("string")).Return(true, nil).Once()
|
||||
|
||||
_, err := dc.GetOrLoad(context.Background(), "key", time.Minute, func(context.Context) ([]byte, error) {
|
||||
return []byte("value"), nil
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
require.True(t, setHasDead, "Set must receive a bounded context")
|
||||
require.LessOrEqual(t, setBudget, 300*time.Millisecond)
|
||||
|
||||
minGetBudget := time.Hour
|
||||
for _, budget := range getBudgets {
|
||||
if budget < minGetBudget {
|
||||
minGetBudget = budget
|
||||
}
|
||||
}
|
||||
|
||||
require.LessOrEqual(t, minGetBudget, 300*time.Millisecond, "fill's Get must receive a bounded context")
|
||||
}
|
||||
+346
@@ -0,0 +1,346 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockCache creates a new instance of MockCache. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockCache(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockCache {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockCache{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockCache is an autogenerated mock type for the Cache type
|
||||
type MockCache struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockCache_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockCache) EXPECT() *MockCache_Expecter {
|
||||
return &MockCache_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Close provides a mock function for the type MockCache
|
||||
func (_mock *MockCache) Close() error {
|
||||
ret := _mock.Called()
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Close")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func() error); ok {
|
||||
r0 = returnFunc()
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockCache_Close_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Close'
|
||||
type MockCache_Close_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Close is a helper method to define mock.On call
|
||||
func (_e *MockCache_Expecter) Close() *MockCache_Close_Call {
|
||||
return &MockCache_Close_Call{Call: _e.mock.On("Close")}
|
||||
}
|
||||
|
||||
func (_c *MockCache_Close_Call) Run(run func()) *MockCache_Close_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run()
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockCache_Close_Call) Return(err error) *MockCache_Close_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockCache_Close_Call) RunAndReturn(run func() error) *MockCache_Close_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Delete provides a mock function for the type MockCache
|
||||
func (_mock *MockCache) Delete(ctx context.Context, keys ...string) error {
|
||||
var tmpRet mock.Arguments
|
||||
if len(keys) > 0 {
|
||||
tmpRet = _mock.Called(ctx, keys)
|
||||
} else {
|
||||
tmpRet = _mock.Called(ctx)
|
||||
}
|
||||
ret := tmpRet
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Delete")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, ...string) error); ok {
|
||||
r0 = returnFunc(ctx, keys...)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockCache_Delete_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Delete'
|
||||
type MockCache_Delete_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Delete is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - keys ...string
|
||||
func (_e *MockCache_Expecter) Delete(ctx any, keys ...any) *MockCache_Delete_Call {
|
||||
return &MockCache_Delete_Call{Call: _e.mock.On("Delete",
|
||||
append([]any{ctx}, keys...)...)}
|
||||
}
|
||||
|
||||
func (_c *MockCache_Delete_Call) Run(run func(ctx context.Context, keys ...string)) *MockCache_Delete_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 []string
|
||||
var variadicArgs []string
|
||||
if len(args) > 1 {
|
||||
variadicArgs = args[1].([]string)
|
||||
}
|
||||
arg1 = variadicArgs
|
||||
run(
|
||||
arg0,
|
||||
arg1...,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockCache_Delete_Call) Return(err error) *MockCache_Delete_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockCache_Delete_Call) RunAndReturn(run func(ctx context.Context, keys ...string) error) *MockCache_Delete_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Get provides a mock function for the type MockCache
|
||||
func (_mock *MockCache) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
ret := _mock.Called(ctx, key)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Get")
|
||||
}
|
||||
|
||||
var r0 []byte
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) ([]byte, error)); ok {
|
||||
return returnFunc(ctx, key)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) []byte); ok {
|
||||
r0 = returnFunc(ctx, key)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]byte)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok {
|
||||
r1 = returnFunc(ctx, key)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockCache_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get'
|
||||
type MockCache_Get_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Get is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - key string
|
||||
func (_e *MockCache_Expecter) Get(ctx any, key any) *MockCache_Get_Call {
|
||||
return &MockCache_Get_Call{Call: _e.mock.On("Get", ctx, key)}
|
||||
}
|
||||
|
||||
func (_c *MockCache_Get_Call) Run(run func(ctx context.Context, key string)) *MockCache_Get_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockCache_Get_Call) Return(bytes []byte, err error) *MockCache_Get_Call {
|
||||
_c.Call.Return(bytes, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockCache_Get_Call) RunAndReturn(run func(ctx context.Context, key string) ([]byte, error)) *MockCache_Get_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Ping provides a mock function for the type MockCache
|
||||
func (_mock *MockCache) Ping(ctx context.Context) error {
|
||||
ret := _mock.Called(ctx)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Ping")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context) error); ok {
|
||||
r0 = returnFunc(ctx)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockCache_Ping_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ping'
|
||||
type MockCache_Ping_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Ping is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
func (_e *MockCache_Expecter) Ping(ctx any) *MockCache_Ping_Call {
|
||||
return &MockCache_Ping_Call{Call: _e.mock.On("Ping", ctx)}
|
||||
}
|
||||
|
||||
func (_c *MockCache_Ping_Call) Run(run func(ctx context.Context)) *MockCache_Ping_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockCache_Ping_Call) Return(err error) *MockCache_Ping_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockCache_Ping_Call) RunAndReturn(run func(ctx context.Context) error) *MockCache_Ping_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Set provides a mock function for the type MockCache
|
||||
func (_mock *MockCache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error {
|
||||
ret := _mock.Called(ctx, key, value, ttl)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Set")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string, []byte, time.Duration) error); ok {
|
||||
r0 = returnFunc(ctx, key, value, ttl)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockCache_Set_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Set'
|
||||
type MockCache_Set_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Set is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - key string
|
||||
// - value []byte
|
||||
// - ttl time.Duration
|
||||
func (_e *MockCache_Expecter) Set(ctx any, key any, value any, ttl any) *MockCache_Set_Call {
|
||||
return &MockCache_Set_Call{Call: _e.mock.On("Set", ctx, key, value, ttl)}
|
||||
}
|
||||
|
||||
func (_c *MockCache_Set_Call) Run(run func(ctx context.Context, key string, value []byte, ttl time.Duration)) *MockCache_Set_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
var arg2 []byte
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].([]byte)
|
||||
}
|
||||
var arg3 time.Duration
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(time.Duration)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockCache_Set_Call) Return(err error) *MockCache_Set_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockCache_Set_Call) RunAndReturn(run func(ctx context.Context, key string, value []byte, ttl time.Duration) error) *MockCache_Set_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
+562
@@ -0,0 +1,562 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockLockStore creates a new instance of MockLockStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockLockStore(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockLockStore {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockLockStore{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockLockStore is an autogenerated mock type for the LockStore type
|
||||
type MockLockStore struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockLockStore_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockLockStore) EXPECT() *MockLockStore_Expecter {
|
||||
return &MockLockStore_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// AcquireLock provides a mock function for the type MockLockStore
|
||||
func (_mock *MockLockStore) AcquireLock(ctx context.Context, key string, token string, ttl time.Duration) (bool, error) {
|
||||
ret := _mock.Called(ctx, key, token, ttl)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for AcquireLock")
|
||||
}
|
||||
|
||||
var r0 bool
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string, string, time.Duration) (bool, error)); ok {
|
||||
return returnFunc(ctx, key, token, ttl)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string, string, time.Duration) bool); ok {
|
||||
r0 = returnFunc(ctx, key, token, ttl)
|
||||
} else {
|
||||
r0 = ret.Get(0).(bool)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, string, string, time.Duration) error); ok {
|
||||
r1 = returnFunc(ctx, key, token, ttl)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockLockStore_AcquireLock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AcquireLock'
|
||||
type MockLockStore_AcquireLock_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// AcquireLock is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - key string
|
||||
// - token string
|
||||
// - ttl time.Duration
|
||||
func (_e *MockLockStore_Expecter) AcquireLock(ctx any, key any, token any, ttl any) *MockLockStore_AcquireLock_Call {
|
||||
return &MockLockStore_AcquireLock_Call{Call: _e.mock.On("AcquireLock", ctx, key, token, ttl)}
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_AcquireLock_Call) Run(run func(ctx context.Context, key string, token string, ttl time.Duration)) *MockLockStore_AcquireLock_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
var arg2 string
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(string)
|
||||
}
|
||||
var arg3 time.Duration
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(time.Duration)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_AcquireLock_Call) Return(b bool, err error) *MockLockStore_AcquireLock_Call {
|
||||
_c.Call.Return(b, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_AcquireLock_Call) RunAndReturn(run func(ctx context.Context, key string, token string, ttl time.Duration) (bool, error)) *MockLockStore_AcquireLock_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Close provides a mock function for the type MockLockStore
|
||||
func (_mock *MockLockStore) Close() error {
|
||||
ret := _mock.Called()
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Close")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func() error); ok {
|
||||
r0 = returnFunc()
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockLockStore_Close_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Close'
|
||||
type MockLockStore_Close_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Close is a helper method to define mock.On call
|
||||
func (_e *MockLockStore_Expecter) Close() *MockLockStore_Close_Call {
|
||||
return &MockLockStore_Close_Call{Call: _e.mock.On("Close")}
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Close_Call) Run(run func()) *MockLockStore_Close_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run()
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Close_Call) Return(err error) *MockLockStore_Close_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Close_Call) RunAndReturn(run func() error) *MockLockStore_Close_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Delete provides a mock function for the type MockLockStore
|
||||
func (_mock *MockLockStore) Delete(ctx context.Context, keys ...string) error {
|
||||
var tmpRet mock.Arguments
|
||||
if len(keys) > 0 {
|
||||
tmpRet = _mock.Called(ctx, keys)
|
||||
} else {
|
||||
tmpRet = _mock.Called(ctx)
|
||||
}
|
||||
ret := tmpRet
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Delete")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, ...string) error); ok {
|
||||
r0 = returnFunc(ctx, keys...)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockLockStore_Delete_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Delete'
|
||||
type MockLockStore_Delete_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Delete is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - keys ...string
|
||||
func (_e *MockLockStore_Expecter) Delete(ctx any, keys ...any) *MockLockStore_Delete_Call {
|
||||
return &MockLockStore_Delete_Call{Call: _e.mock.On("Delete",
|
||||
append([]any{ctx}, keys...)...)}
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Delete_Call) Run(run func(ctx context.Context, keys ...string)) *MockLockStore_Delete_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 []string
|
||||
var variadicArgs []string
|
||||
if len(args) > 1 {
|
||||
variadicArgs = args[1].([]string)
|
||||
}
|
||||
arg1 = variadicArgs
|
||||
run(
|
||||
arg0,
|
||||
arg1...,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Delete_Call) Return(err error) *MockLockStore_Delete_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Delete_Call) RunAndReturn(run func(ctx context.Context, keys ...string) error) *MockLockStore_Delete_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Get provides a mock function for the type MockLockStore
|
||||
func (_mock *MockLockStore) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
ret := _mock.Called(ctx, key)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Get")
|
||||
}
|
||||
|
||||
var r0 []byte
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) ([]byte, error)); ok {
|
||||
return returnFunc(ctx, key)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) []byte); ok {
|
||||
r0 = returnFunc(ctx, key)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]byte)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok {
|
||||
r1 = returnFunc(ctx, key)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockLockStore_Get_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Get'
|
||||
type MockLockStore_Get_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Get is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - key string
|
||||
func (_e *MockLockStore_Expecter) Get(ctx any, key any) *MockLockStore_Get_Call {
|
||||
return &MockLockStore_Get_Call{Call: _e.mock.On("Get", ctx, key)}
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Get_Call) Run(run func(ctx context.Context, key string)) *MockLockStore_Get_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Get_Call) Return(bytes []byte, err error) *MockLockStore_Get_Call {
|
||||
_c.Call.Return(bytes, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Get_Call) RunAndReturn(run func(ctx context.Context, key string) ([]byte, error)) *MockLockStore_Get_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// LockHeld provides a mock function for the type MockLockStore
|
||||
func (_mock *MockLockStore) LockHeld(ctx context.Context, key string) (bool, error) {
|
||||
ret := _mock.Called(ctx, key)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for LockHeld")
|
||||
}
|
||||
|
||||
var r0 bool
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) (bool, error)); ok {
|
||||
return returnFunc(ctx, key)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) bool); ok {
|
||||
r0 = returnFunc(ctx, key)
|
||||
} else {
|
||||
r0 = ret.Get(0).(bool)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok {
|
||||
r1 = returnFunc(ctx, key)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockLockStore_LockHeld_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'LockHeld'
|
||||
type MockLockStore_LockHeld_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// LockHeld is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - key string
|
||||
func (_e *MockLockStore_Expecter) LockHeld(ctx any, key any) *MockLockStore_LockHeld_Call {
|
||||
return &MockLockStore_LockHeld_Call{Call: _e.mock.On("LockHeld", ctx, key)}
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_LockHeld_Call) Run(run func(ctx context.Context, key string)) *MockLockStore_LockHeld_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_LockHeld_Call) Return(b bool, err error) *MockLockStore_LockHeld_Call {
|
||||
_c.Call.Return(b, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_LockHeld_Call) RunAndReturn(run func(ctx context.Context, key string) (bool, error)) *MockLockStore_LockHeld_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Ping provides a mock function for the type MockLockStore
|
||||
func (_mock *MockLockStore) Ping(ctx context.Context) error {
|
||||
ret := _mock.Called(ctx)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Ping")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context) error); ok {
|
||||
r0 = returnFunc(ctx)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockLockStore_Ping_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Ping'
|
||||
type MockLockStore_Ping_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Ping is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
func (_e *MockLockStore_Expecter) Ping(ctx any) *MockLockStore_Ping_Call {
|
||||
return &MockLockStore_Ping_Call{Call: _e.mock.On("Ping", ctx)}
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Ping_Call) Run(run func(ctx context.Context)) *MockLockStore_Ping_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Ping_Call) Return(err error) *MockLockStore_Ping_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Ping_Call) RunAndReturn(run func(ctx context.Context) error) *MockLockStore_Ping_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// ReleaseLock provides a mock function for the type MockLockStore
|
||||
func (_mock *MockLockStore) ReleaseLock(ctx context.Context, key string, token string) (bool, error) {
|
||||
ret := _mock.Called(ctx, key, token)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ReleaseLock")
|
||||
}
|
||||
|
||||
var r0 bool
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string, string) (bool, error)); ok {
|
||||
return returnFunc(ctx, key, token)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string, string) bool); ok {
|
||||
r0 = returnFunc(ctx, key, token)
|
||||
} else {
|
||||
r0 = ret.Get(0).(bool)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, string, string) error); ok {
|
||||
r1 = returnFunc(ctx, key, token)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockLockStore_ReleaseLock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ReleaseLock'
|
||||
type MockLockStore_ReleaseLock_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ReleaseLock is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - key string
|
||||
// - token string
|
||||
func (_e *MockLockStore_Expecter) ReleaseLock(ctx any, key any, token any) *MockLockStore_ReleaseLock_Call {
|
||||
return &MockLockStore_ReleaseLock_Call{Call: _e.mock.On("ReleaseLock", ctx, key, token)}
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_ReleaseLock_Call) Run(run func(ctx context.Context, key string, token string)) *MockLockStore_ReleaseLock_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
var arg2 string
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_ReleaseLock_Call) Return(b bool, err error) *MockLockStore_ReleaseLock_Call {
|
||||
_c.Call.Return(b, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_ReleaseLock_Call) RunAndReturn(run func(ctx context.Context, key string, token string) (bool, error)) *MockLockStore_ReleaseLock_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Set provides a mock function for the type MockLockStore
|
||||
func (_mock *MockLockStore) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error {
|
||||
ret := _mock.Called(ctx, key, value, ttl)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Set")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string, []byte, time.Duration) error); ok {
|
||||
r0 = returnFunc(ctx, key, value, ttl)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockLockStore_Set_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Set'
|
||||
type MockLockStore_Set_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Set is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - key string
|
||||
// - value []byte
|
||||
// - ttl time.Duration
|
||||
func (_e *MockLockStore_Expecter) Set(ctx any, key any, value any, ttl any) *MockLockStore_Set_Call {
|
||||
return &MockLockStore_Set_Call{Call: _e.mock.On("Set", ctx, key, value, ttl)}
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Set_Call) Run(run func(ctx context.Context, key string, value []byte, ttl time.Duration)) *MockLockStore_Set_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
var arg2 []byte
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].([]byte)
|
||||
}
|
||||
var arg3 time.Duration
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(time.Duration)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Set_Call) Return(err error) *MockLockStore_Set_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_Set_Call) RunAndReturn(run func(ctx context.Context, key string, value []byte, ttl time.Duration) error) *MockLockStore_Set_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
Vendored
+139
@@ -0,0 +1,139 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type RedisConfig struct {
|
||||
Host string
|
||||
Port int
|
||||
Password string
|
||||
DB int
|
||||
MaxRetries int
|
||||
DialTimeout time.Duration
|
||||
ReadTimeout time.Duration
|
||||
WriteTimeout time.Duration
|
||||
PoolSize int
|
||||
}
|
||||
|
||||
type RedisCache struct {
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
func NewRedis(cfg RedisConfig) (*RedisCache, error) {
|
||||
client := redis.NewClient(newClientOptions(cfg))
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), cfg.DialTimeout)
|
||||
defer cancel()
|
||||
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
_ = client.Close()
|
||||
|
||||
return nil, fmt.Errorf("ping redis: %w", err)
|
||||
}
|
||||
|
||||
return &RedisCache{client: client}, nil
|
||||
}
|
||||
|
||||
func newClientOptions(cfg RedisConfig) *redis.Options {
|
||||
return &redis.Options{
|
||||
Addr: net.JoinHostPort(cfg.Host, strconv.Itoa(cfg.Port)),
|
||||
Password: cfg.Password,
|
||||
DB: cfg.DB,
|
||||
MaxRetries: cfg.MaxRetries,
|
||||
DialTimeout: cfg.DialTimeout,
|
||||
ReadTimeout: cfg.ReadTimeout,
|
||||
WriteTimeout: cfg.WriteTimeout,
|
||||
PoolSize: cfg.PoolSize,
|
||||
}
|
||||
}
|
||||
|
||||
func (r *RedisCache) Get(ctx context.Context, key string) ([]byte, error) {
|
||||
value, err := r.client.Get(ctx, key).Bytes()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return nil, ErrCacheMiss
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("redis get %q: %w", key, err)
|
||||
}
|
||||
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func (r *RedisCache) Set(ctx context.Context, key string, value []byte, ttl time.Duration) error {
|
||||
if err := r.client.Set(ctx, key, value, ttl).Err(); err != nil {
|
||||
return fmt.Errorf("redis set %q: %w", key, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RedisCache) Delete(ctx context.Context, keys ...string) error {
|
||||
if len(keys) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
if err := r.client.Del(ctx, keys...).Err(); err != nil {
|
||||
return fmt.Errorf("redis delete: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
var releaseLockScript = redis.NewScript(`
|
||||
if redis.call("GET", KEYS[1]) == ARGV[1] then
|
||||
return redis.call("DEL", KEYS[1])
|
||||
end
|
||||
return 0
|
||||
`)
|
||||
|
||||
func (r *RedisCache) AcquireLock(ctx context.Context, key, token string, ttl time.Duration) (bool, error) {
|
||||
acquired, err := r.client.SetNX(ctx, key, token, ttl).Result()
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("redis acquire lock %q: %w", key, err)
|
||||
}
|
||||
|
||||
return acquired, nil
|
||||
}
|
||||
|
||||
func (r *RedisCache) ReleaseLock(ctx context.Context, key, token string) (bool, error) {
|
||||
deleted, err := releaseLockScript.Run(ctx, r.client, []string{key}, token).Int64()
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("redis release lock %q: %w", key, err)
|
||||
}
|
||||
|
||||
return deleted > 0, nil
|
||||
}
|
||||
|
||||
func (r *RedisCache) LockHeld(ctx context.Context, key string) (bool, error) {
|
||||
exists, err := r.client.Exists(ctx, key).Result()
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("redis check lock %q: %w", key, err)
|
||||
}
|
||||
|
||||
return exists > 0, nil
|
||||
}
|
||||
|
||||
func (r *RedisCache) Ping(ctx context.Context) error {
|
||||
if err := r.client.Ping(ctx).Err(); err != nil {
|
||||
return fmt.Errorf("redis ping: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *RedisCache) Close() error {
|
||||
if err := r.client.Close(); err != nil {
|
||||
return fmt.Errorf("redis close: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestNewClientOptionsAppliesTimeoutsAndRetries(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
client := redis.NewClient(newClientOptions(RedisConfig{
|
||||
Host: "localhost",
|
||||
Port: 6379,
|
||||
MaxRetries: -1,
|
||||
DialTimeout: 300 * time.Millisecond,
|
||||
ReadTimeout: 200 * time.Millisecond,
|
||||
WriteTimeout: 200 * time.Millisecond,
|
||||
PoolSize: 5,
|
||||
}))
|
||||
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
opts := client.Options()
|
||||
require.Equal(t, 0, opts.MaxRetries, "go-redis: -1 disables retries, 0 would restore the default of 3")
|
||||
require.Equal(t, 300*time.Millisecond, opts.DialTimeout)
|
||||
require.Equal(t, 200*time.Millisecond, opts.ReadTimeout)
|
||||
require.Equal(t, 200*time.Millisecond, opts.WriteTimeout)
|
||||
require.Equal(t, 5, opts.PoolSize)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// Package objectstore defines the S3-compatible port used by attachments.
|
||||
// Metadata never belongs here: PostgreSQL is the source of truth, this package
|
||||
// only moves bytes and exposes object timestamps for the orphan sweeper.
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Object is the provider-neutral view of one stored object.
|
||||
type Object struct {
|
||||
Key string
|
||||
Size int64
|
||||
ContentType string
|
||||
LastModified time.Time
|
||||
Metadata map[string]string
|
||||
}
|
||||
|
||||
// Store is implemented by S3-compatible backends. Put requires a seekable body
|
||||
// because AWS SigV4 may need to rewind the payload; the proxy upload path always
|
||||
// passes an *os.File.
|
||||
type Store interface {
|
||||
Put(ctx context.Context, key string, body io.ReadSeeker, size int64, contentType string, metadata map[string]string) error
|
||||
Open(ctx context.Context, key string) (io.ReadCloser, Object, error)
|
||||
Head(ctx context.Context, key string) (Object, error)
|
||||
Copy(ctx context.Context, src, dst, contentType string, metadata map[string]string) error
|
||||
Delete(ctx context.Context, key string) error
|
||||
List(ctx context.Context, prefix string) ([]Object, error)
|
||||
PresignPut(ctx context.Context, key string, size int64, ttl time.Duration) (string, time.Time, error)
|
||||
}
|
||||
@@ -0,0 +1,292 @@
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
"github.com/aws/smithy-go"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
// Config is the S3 connection subset. Limits belong to the attachment service.
|
||||
type Config struct {
|
||||
Endpoint string
|
||||
PublicEndpoint string
|
||||
Region string
|
||||
Bucket string
|
||||
AccessKeyID string
|
||||
SecretAccessKey string
|
||||
UsePathStyle bool
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// S3 is an object store backed by an S3-compatible server (SeaweedFS in the
|
||||
// lab stand, MinIO/AWS in other deployments).
|
||||
type S3 struct {
|
||||
bucket string
|
||||
internal *s3.Client
|
||||
public *s3.Client
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
var _ Store = (*S3)(nil)
|
||||
|
||||
func New(cfg Config) (*S3, error) {
|
||||
if cfg.Endpoint == "" || cfg.Region == "" || cfg.Bucket == "" {
|
||||
return nil, errors.New("object store: endpoint, region and bucket are required")
|
||||
}
|
||||
|
||||
if cfg.AccessKeyID == "" || cfg.SecretAccessKey == "" {
|
||||
return nil, errors.New("object store: access key id and secret access key are required")
|
||||
}
|
||||
|
||||
if cfg.PublicEndpoint == "" {
|
||||
cfg.PublicEndpoint = cfg.Endpoint
|
||||
}
|
||||
|
||||
httpClient := &http.Client{
|
||||
Transport: &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 3 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
}).DialContext,
|
||||
TLSHandshakeTimeout: 3 * time.Second,
|
||||
ResponseHeaderTimeout: 15 * time.Second,
|
||||
MaxIdleConnsPerHost: 16,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
},
|
||||
// Downloads stream through the response body; an overall client
|
||||
// timeout would abort them.
|
||||
}
|
||||
|
||||
newClient := func(endpoint string) *s3.Client {
|
||||
return s3.New(s3.Options{
|
||||
Region: cfg.Region,
|
||||
BaseEndpoint: aws.String(endpoint),
|
||||
UsePathStyle: cfg.UsePathStyle,
|
||||
Credentials: credentials.NewStaticCredentialsProvider(cfg.AccessKeyID, cfg.SecretAccessKey, ""),
|
||||
HTTPClient: httpClient,
|
||||
})
|
||||
}
|
||||
|
||||
st := &S3{
|
||||
bucket: cfg.Bucket,
|
||||
internal: newClient(cfg.Endpoint),
|
||||
public: newClient(cfg.PublicEndpoint),
|
||||
timeout: cfg.Timeout,
|
||||
}
|
||||
|
||||
return st, nil
|
||||
}
|
||||
|
||||
func (s *S3) Put(
|
||||
ctx context.Context,
|
||||
key string,
|
||||
body io.ReadSeeker,
|
||||
size int64,
|
||||
contentType string,
|
||||
metadata map[string]string,
|
||||
) error {
|
||||
ctx, cancel := s.operationContext(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := s.internal.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
Body: body,
|
||||
ContentLength: aws.Int64(size),
|
||||
ContentType: aws.String(contentType),
|
||||
Metadata: metadata,
|
||||
})
|
||||
if err != nil {
|
||||
return mapObjectError("put object", key, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *S3) Open(ctx context.Context, key string) (io.ReadCloser, Object, error) {
|
||||
output, err := s.internal.GetObject(ctx, &s3.GetObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
if err != nil {
|
||||
return nil, Object{}, mapObjectError("open object", key, err)
|
||||
}
|
||||
|
||||
object := Object{
|
||||
Key: key,
|
||||
Size: aws.ToInt64(output.ContentLength),
|
||||
ContentType: aws.ToString(output.ContentType),
|
||||
LastModified: aws.ToTime(output.LastModified),
|
||||
Metadata: output.Metadata,
|
||||
}
|
||||
|
||||
return output.Body, object, nil
|
||||
}
|
||||
|
||||
func (s *S3) Head(ctx context.Context, key string) (Object, error) {
|
||||
output, err := s.internal.HeadObject(ctx, &s3.HeadObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
if err != nil {
|
||||
return Object{}, mapObjectError("head object", key, err)
|
||||
}
|
||||
|
||||
return Object{
|
||||
Key: key,
|
||||
Size: aws.ToInt64(output.ContentLength),
|
||||
ContentType: aws.ToString(output.ContentType),
|
||||
LastModified: aws.ToTime(output.LastModified),
|
||||
Metadata: output.Metadata,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *S3) Copy(ctx context.Context, src, dst, contentType string, metadata map[string]string) error {
|
||||
ctx, cancel := s.operationContext(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := s.internal.CopyObject(ctx, &s3.CopyObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(dst),
|
||||
CopySource: aws.String(s.bucket + "/" + src),
|
||||
MetadataDirective: types.MetadataDirectiveReplace,
|
||||
ContentType: aws.String(contentType),
|
||||
Metadata: metadata,
|
||||
})
|
||||
if err != nil {
|
||||
return mapObjectError("copy object", src+" -> "+dst, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *S3) Delete(ctx context.Context, key string) error {
|
||||
ctx, cancel := s.operationContext(ctx)
|
||||
defer cancel()
|
||||
|
||||
_, err := s.internal.DeleteObject(ctx, &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
if err != nil {
|
||||
return mapObjectError("delete object", key, err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *S3) List(ctx context.Context, prefix string) ([]Object, error) {
|
||||
ctx, cancel := s.operationContext(ctx)
|
||||
defer cancel()
|
||||
|
||||
var (
|
||||
objects []Object
|
||||
token *string
|
||||
)
|
||||
|
||||
for {
|
||||
output, err := s.internal.ListObjectsV2(ctx, &s3.ListObjectsV2Input{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Prefix: aws.String(prefix),
|
||||
ContinuationToken: token,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, mapObjectError("list objects", prefix, err)
|
||||
}
|
||||
|
||||
for _, item := range output.Contents {
|
||||
objects = append(objects, Object{
|
||||
Key: aws.ToString(item.Key),
|
||||
Size: aws.ToInt64(item.Size),
|
||||
LastModified: aws.ToTime(item.LastModified),
|
||||
})
|
||||
}
|
||||
|
||||
if !aws.ToBool(output.IsTruncated) {
|
||||
break
|
||||
}
|
||||
|
||||
token = output.NextContinuationToken
|
||||
if token == nil || *token == "" {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return objects, nil
|
||||
}
|
||||
|
||||
// PresignPut signs the bucket, key, host and exact Content-Length. The size is
|
||||
// therefore enforced by S3 at write time: a client that uploads a different
|
||||
// number of bytes gets 403 SignatureDoesNotMatch. Content-Type and checksums
|
||||
// are not signed (SeaweedFS does not validate checksums); completion verifies
|
||||
// the actual bytes and their structure.
|
||||
func (s *S3) PresignPut(
|
||||
ctx context.Context,
|
||||
key string,
|
||||
size int64,
|
||||
ttl time.Duration,
|
||||
) (string, time.Time, error) {
|
||||
expiresAt := time.Now().UTC().Add(ttl)
|
||||
|
||||
presigned, err := s3.NewPresignClient(s.public).PresignPutObject(
|
||||
ctx,
|
||||
&s3.PutObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
ContentLength: aws.Int64(size),
|
||||
},
|
||||
func(options *s3.PresignOptions) {
|
||||
options.Expires = ttl
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return "", time.Time{}, mapObjectError("presign put", key, err)
|
||||
}
|
||||
|
||||
return presigned.URL, expiresAt, nil
|
||||
}
|
||||
|
||||
func (s *S3) operationContext(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
if s.timeout <= 0 {
|
||||
return context.WithCancel(ctx)
|
||||
}
|
||||
|
||||
return context.WithTimeout(ctx, s.timeout)
|
||||
}
|
||||
|
||||
func mapObjectError(operation, subject string, err error) error {
|
||||
var apiErr smithy.APIError
|
||||
|
||||
if errors.As(err, &apiErr) {
|
||||
switch apiErr.ErrorCode() {
|
||||
case "NoSuchBucket":
|
||||
return fmt.Errorf("%w: %s %q: %w", domain.ErrUnavailable, operation, subject, err)
|
||||
case "NotFound", "NoSuchKey":
|
||||
return fmt.Errorf("%s %q: %w", operation, subject, domain.ErrNotFound)
|
||||
}
|
||||
}
|
||||
|
||||
if errors.Is(err, context.Canceled) {
|
||||
return fmt.Errorf("%s %q: %w", operation, subject, err)
|
||||
}
|
||||
|
||||
if strings.Contains(strings.ToLower(err.Error()), "no such key") {
|
||||
return fmt.Errorf("%s %q: %w", operation, subject, domain.ErrNotFound)
|
||||
}
|
||||
|
||||
return fmt.Errorf("%w: %s %q: %w", domain.ErrUnavailable, operation, subject, err)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/aws/smithy-go"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
func TestMapObjectErrorBucketIsUnavailable(t *testing.T) {
|
||||
err := mapObjectError("put object", "key", &smithy.GenericAPIError{
|
||||
Code: "NoSuchBucket",
|
||||
Message: "bucket is missing",
|
||||
})
|
||||
require.ErrorIs(t, err, domain.ErrUnavailable)
|
||||
}
|
||||
|
||||
func TestMapObjectErrorMissingKeyIsNotFound(t *testing.T) {
|
||||
err := mapObjectError("open object", "key", &smithy.GenericAPIError{
|
||||
Code: "NoSuchKey",
|
||||
Message: "object is missing",
|
||||
})
|
||||
require.ErrorIs(t, err, domain.ErrNotFound)
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package password
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argonTime = 1
|
||||
argonMemory = 64 * 1024
|
||||
argonThreads = 4
|
||||
argonKeyLen = 32
|
||||
argonSaltLen = 16
|
||||
)
|
||||
|
||||
func Hash(plain string) (string, error) {
|
||||
salt := make([]byte, argonSaltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
hash := argon2.IDKey([]byte(plain), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
||||
|
||||
return "argon2id$" +
|
||||
base64.RawStdEncoding.EncodeToString(salt) + "$" +
|
||||
base64.RawStdEncoding.EncodeToString(hash), nil
|
||||
}
|
||||
|
||||
func Verify(plain, encoded string) bool {
|
||||
parts := strings.Split(encoded, "$")
|
||||
if len(parts) != 3 || parts[0] != "argon2id" {
|
||||
return false
|
||||
}
|
||||
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[1])
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
expected, err := base64.RawStdEncoding.DecodeString(parts[2])
|
||||
if err != nil || len(salt) != argonSaltLen || len(expected) != argonKeyLen {
|
||||
return false
|
||||
}
|
||||
|
||||
actual := argon2.IDKey([]byte(plain), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
||||
|
||||
return subtle.ConstantTimeCompare(actual, expected) == 1
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package password_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
)
|
||||
|
||||
func TestHashVerifyRoundTrip(t *testing.T) {
|
||||
encoded, err := password.Hash("very-secret-password")
|
||||
require.NoError(t, err)
|
||||
require.True(t, password.Verify("very-secret-password", encoded))
|
||||
require.False(t, password.Verify("wrong-password-value", encoded))
|
||||
}
|
||||
|
||||
func TestHashIsSalted(t *testing.T) {
|
||||
first, err := password.Hash("very-secret-password")
|
||||
require.NoError(t, err)
|
||||
|
||||
second, err := password.Hash("very-secret-password")
|
||||
require.NoError(t, err)
|
||||
|
||||
require.NotEqual(t, first, second)
|
||||
}
|
||||
|
||||
func TestVerifyRejectsMalformedHash(t *testing.T) {
|
||||
require.False(t, password.Verify("very-secret-password", ""))
|
||||
require.False(t, password.Verify("very-secret-password", "plain-text"))
|
||||
require.False(t, password.Verify("very-secret-password", strings.Repeat("x", 64)))
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
package token
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
)
|
||||
|
||||
const size = 32
|
||||
|
||||
var ErrInvalid = errors.New("invalid token")
|
||||
|
||||
type Token struct{}
|
||||
|
||||
func New() Token {
|
||||
return Token{}
|
||||
}
|
||||
|
||||
func (Token) Generate() (string, []byte, error) {
|
||||
raw := make([]byte, size)
|
||||
if _, err := rand.Read(raw); err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
|
||||
sum := sha256.Sum256(raw)
|
||||
|
||||
return base64.RawURLEncoding.EncodeToString(raw), sum[:], nil
|
||||
}
|
||||
|
||||
func (Token) Hash(raw string) ([]byte, error) {
|
||||
decoded, err := base64.RawURLEncoding.DecodeString(raw)
|
||||
if err != nil || len(decoded) != size {
|
||||
return nil, ErrInvalid
|
||||
}
|
||||
|
||||
sum := sha256.Sum256(decoded)
|
||||
|
||||
return sum[:], nil
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package token_test
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/platform/token"
|
||||
)
|
||||
|
||||
func TestGenerateProducesUniqueOpaqueTokens(t *testing.T) {
|
||||
tokens := token.New()
|
||||
|
||||
first, firstHash, err := tokens.Generate()
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, first)
|
||||
require.Len(t, firstHash, sha256.Size)
|
||||
|
||||
second, secondHash, err := tokens.Generate()
|
||||
require.NoError(t, err)
|
||||
require.NotEqual(t, first, second)
|
||||
require.NotEqual(t, firstHash, secondHash)
|
||||
}
|
||||
|
||||
func TestHashMatchesGeneratedHash(t *testing.T) {
|
||||
tokens := token.New()
|
||||
|
||||
raw, hash, err := tokens.Generate()
|
||||
require.NoError(t, err)
|
||||
|
||||
actual, err := tokens.Hash(raw)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, hash, actual)
|
||||
}
|
||||
|
||||
func TestHashRejectsMalformed(t *testing.T) {
|
||||
tokens := token.New()
|
||||
|
||||
for _, raw := range []string{"", "not-base64!", "c2hvcnQ"} {
|
||||
_, err := tokens.Hash(raw)
|
||||
require.ErrorIs(t, err, token.ErrInvalid, raw)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockLockStore creates a new instance of MockLockStore. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockLockStore(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockLockStore {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockLockStore{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockLockStore is an autogenerated mock type for the LockStore type
|
||||
type MockLockStore struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockLockStore_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockLockStore) EXPECT() *MockLockStore_Expecter {
|
||||
return &MockLockStore_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// AcquireSweepLock provides a mock function for the type MockLockStore
|
||||
func (_mock *MockLockStore) AcquireSweepLock(ctx context.Context) (func(), bool, error) {
|
||||
ret := _mock.Called(ctx)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for AcquireSweepLock")
|
||||
}
|
||||
|
||||
var r0 func()
|
||||
var r1 bool
|
||||
var r2 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context) (func(), bool, error)); ok {
|
||||
return returnFunc(ctx)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context) func()); ok {
|
||||
r0 = returnFunc(ctx)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).(func())
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context) bool); ok {
|
||||
r1 = returnFunc(ctx)
|
||||
} else {
|
||||
r1 = ret.Get(1).(bool)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(2).(func(context.Context) error); ok {
|
||||
r2 = returnFunc(ctx)
|
||||
} else {
|
||||
r2 = ret.Error(2)
|
||||
}
|
||||
return r0, r1, r2
|
||||
}
|
||||
|
||||
// MockLockStore_AcquireSweepLock_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'AcquireSweepLock'
|
||||
type MockLockStore_AcquireSweepLock_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// AcquireSweepLock is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
func (_e *MockLockStore_Expecter) AcquireSweepLock(ctx any) *MockLockStore_AcquireSweepLock_Call {
|
||||
return &MockLockStore_AcquireSweepLock_Call{Call: _e.mock.On("AcquireSweepLock", ctx)}
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_AcquireSweepLock_Call) Run(run func(ctx context.Context)) *MockLockStore_AcquireSweepLock_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_AcquireSweepLock_Call) Return(release func(), acquired bool, err error) *MockLockStore_AcquireSweepLock_Call {
|
||||
_c.Call.Return(release, acquired, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockLockStore_AcquireSweepLock_Call) RunAndReturn(run func(ctx context.Context) (func(), bool, error)) *MockLockStore_AcquireSweepLock_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,683 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mtusi-messenger/internal/domain"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockRepository creates a new instance of MockRepository. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockRepository(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockRepository {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockRepository{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockRepository is an autogenerated mock type for the Repository type
|
||||
type MockRepository struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockRepository_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockRepository) EXPECT() *MockRepository_Expecter {
|
||||
return &MockRepository_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Create provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Create(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error) {
|
||||
ret := _mock.Called(ctx, draft)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Create")
|
||||
}
|
||||
|
||||
var r0 domain.Attachment
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft) (domain.Attachment, error)); ok {
|
||||
return returnFunc(ctx, draft)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft) domain.Attachment); ok {
|
||||
r0 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Attachment)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.AttachmentDraft) error); ok {
|
||||
r1 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'
|
||||
type MockRepository_Create_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Create is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - draft domain.AttachmentDraft
|
||||
func (_e *MockRepository_Expecter) Create(ctx any, draft any) *MockRepository_Create_Call {
|
||||
return &MockRepository_Create_Call{Call: _e.mock.On("Create", ctx, draft)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft)) *MockRepository_Create_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.AttachmentDraft
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.AttachmentDraft)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Return(attachment domain.Attachment, err error) *MockRepository_Create_Call {
|
||||
_c.Call.Return(attachment, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) RunAndReturn(run func(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error)) *MockRepository_Create_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// DeletePending provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) DeletePending(ctx context.Context, id uuid.UUID) error {
|
||||
ret := _mock.Called(ctx, id)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for DeletePending")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) error); ok {
|
||||
r0 = returnFunc(ctx, id)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockRepository_DeletePending_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeletePending'
|
||||
type MockRepository_DeletePending_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// DeletePending is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - id uuid.UUID
|
||||
func (_e *MockRepository_Expecter) DeletePending(ctx any, id any) *MockRepository_DeletePending_Call {
|
||||
return &MockRepository_DeletePending_Call{Call: _e.mock.On("DeletePending", ctx, id)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_DeletePending_Call) Run(run func(ctx context.Context, id uuid.UUID)) *MockRepository_DeletePending_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_DeletePending_Call) Return(err error) *MockRepository_DeletePending_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_DeletePending_Call) RunAndReturn(run func(ctx context.Context, id uuid.UUID) error) *MockRepository_DeletePending_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// GetForMember provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) GetForMember(ctx context.Context, userID uuid.UUID, id uuid.UUID) (domain.Attachment, error) {
|
||||
ret := _mock.Called(ctx, userID, id)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for GetForMember")
|
||||
}
|
||||
|
||||
var r0 domain.Attachment
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) (domain.Attachment, error)); ok {
|
||||
return returnFunc(ctx, userID, id)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) domain.Attachment); ok {
|
||||
r0 = returnFunc(ctx, userID, id)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Attachment)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, userID, id)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_GetForMember_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetForMember'
|
||||
type MockRepository_GetForMember_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// GetForMember is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - userID uuid.UUID
|
||||
// - id uuid.UUID
|
||||
func (_e *MockRepository_Expecter) GetForMember(ctx any, userID any, id any) *MockRepository_GetForMember_Call {
|
||||
return &MockRepository_GetForMember_Call{Call: _e.mock.On("GetForMember", ctx, userID, id)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetForMember_Call) Run(run func(ctx context.Context, userID uuid.UUID, id uuid.UUID)) *MockRepository_GetForMember_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 uuid.UUID
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetForMember_Call) Return(attachment domain.Attachment, err error) *MockRepository_GetForMember_Call {
|
||||
_c.Call.Return(attachment, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetForMember_Call) RunAndReturn(run func(ctx context.Context, userID uuid.UUID, id uuid.UUID) (domain.Attachment, error)) *MockRepository_GetForMember_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// GetForOwner provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) GetForOwner(ctx context.Context, ownerID uuid.UUID, id uuid.UUID) (domain.Attachment, error) {
|
||||
ret := _mock.Called(ctx, ownerID, id)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for GetForOwner")
|
||||
}
|
||||
|
||||
var r0 domain.Attachment
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) (domain.Attachment, error)); ok {
|
||||
return returnFunc(ctx, ownerID, id)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) domain.Attachment); ok {
|
||||
r0 = returnFunc(ctx, ownerID, id)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Attachment)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, ownerID, id)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_GetForOwner_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetForOwner'
|
||||
type MockRepository_GetForOwner_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// GetForOwner is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - ownerID uuid.UUID
|
||||
// - id uuid.UUID
|
||||
func (_e *MockRepository_Expecter) GetForOwner(ctx any, ownerID any, id any) *MockRepository_GetForOwner_Call {
|
||||
return &MockRepository_GetForOwner_Call{Call: _e.mock.On("GetForOwner", ctx, ownerID, id)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetForOwner_Call) Run(run func(ctx context.Context, ownerID uuid.UUID, id uuid.UUID)) *MockRepository_GetForOwner_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 uuid.UUID
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetForOwner_Call) Return(attachment domain.Attachment, err error) *MockRepository_GetForOwner_Call {
|
||||
_c.Call.Return(attachment, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetForOwner_Call) RunAndReturn(run func(ctx context.Context, ownerID uuid.UUID, id uuid.UUID) (domain.Attachment, error)) *MockRepository_GetForOwner_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// IsChatMember provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) IsChatMember(ctx context.Context, chatID uuid.UUID, userID uuid.UUID) (bool, error) {
|
||||
ret := _mock.Called(ctx, chatID, userID)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for IsChatMember")
|
||||
}
|
||||
|
||||
var r0 bool
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) (bool, error)); ok {
|
||||
return returnFunc(ctx, chatID, userID)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) bool); ok {
|
||||
r0 = returnFunc(ctx, chatID, userID)
|
||||
} else {
|
||||
r0 = ret.Get(0).(bool)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, chatID, userID)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_IsChatMember_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsChatMember'
|
||||
type MockRepository_IsChatMember_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// IsChatMember is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - chatID uuid.UUID
|
||||
// - userID uuid.UUID
|
||||
func (_e *MockRepository_Expecter) IsChatMember(ctx any, chatID any, userID any) *MockRepository_IsChatMember_Call {
|
||||
return &MockRepository_IsChatMember_Call{Call: _e.mock.On("IsChatMember", ctx, chatID, userID)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_IsChatMember_Call) Run(run func(ctx context.Context, chatID uuid.UUID, userID uuid.UUID)) *MockRepository_IsChatMember_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 uuid.UUID
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_IsChatMember_Call) Return(b bool, err error) *MockRepository_IsChatMember_Call {
|
||||
_c.Call.Return(b, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_IsChatMember_Call) RunAndReturn(run func(ctx context.Context, chatID uuid.UUID, userID uuid.UUID) (bool, error)) *MockRepository_IsChatMember_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// ListKeys provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) ListKeys(ctx context.Context, limit int32, offset int32) ([]domain.AttachmentKey, error) {
|
||||
ret := _mock.Called(ctx, limit, offset)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListKeys")
|
||||
}
|
||||
|
||||
var r0 []domain.AttachmentKey
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, int32, int32) ([]domain.AttachmentKey, error)); ok {
|
||||
return returnFunc(ctx, limit, offset)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, int32, int32) []domain.AttachmentKey); ok {
|
||||
r0 = returnFunc(ctx, limit, offset)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]domain.AttachmentKey)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, int32, int32) error); ok {
|
||||
r1 = returnFunc(ctx, limit, offset)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_ListKeys_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListKeys'
|
||||
type MockRepository_ListKeys_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListKeys is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - limit int32
|
||||
// - offset int32
|
||||
func (_e *MockRepository_Expecter) ListKeys(ctx any, limit any, offset any) *MockRepository_ListKeys_Call {
|
||||
return &MockRepository_ListKeys_Call{Call: _e.mock.On("ListKeys", ctx, limit, offset)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListKeys_Call) Run(run func(ctx context.Context, limit int32, offset int32)) *MockRepository_ListKeys_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 int32
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(int32)
|
||||
}
|
||||
var arg2 int32
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(int32)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListKeys_Call) Return(attachmentKeys []domain.AttachmentKey, err error) *MockRepository_ListKeys_Call {
|
||||
_c.Call.Return(attachmentKeys, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListKeys_Call) RunAndReturn(run func(ctx context.Context, limit int32, offset int32) ([]domain.AttachmentKey, error)) *MockRepository_ListKeys_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// ListStalePending provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) ListStalePending(ctx context.Context, createdBefore time.Time, limit int32) ([]domain.Attachment, error) {
|
||||
ret := _mock.Called(ctx, createdBefore, limit)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListStalePending")
|
||||
}
|
||||
|
||||
var r0 []domain.Attachment
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, time.Time, int32) ([]domain.Attachment, error)); ok {
|
||||
return returnFunc(ctx, createdBefore, limit)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, time.Time, int32) []domain.Attachment); ok {
|
||||
r0 = returnFunc(ctx, createdBefore, limit)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]domain.Attachment)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, time.Time, int32) error); ok {
|
||||
r1 = returnFunc(ctx, createdBefore, limit)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_ListStalePending_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListStalePending'
|
||||
type MockRepository_ListStalePending_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListStalePending is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - createdBefore time.Time
|
||||
// - limit int32
|
||||
func (_e *MockRepository_Expecter) ListStalePending(ctx any, createdBefore any, limit any) *MockRepository_ListStalePending_Call {
|
||||
return &MockRepository_ListStalePending_Call{Call: _e.mock.On("ListStalePending", ctx, createdBefore, limit)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListStalePending_Call) Run(run func(ctx context.Context, createdBefore time.Time, limit int32)) *MockRepository_ListStalePending_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 time.Time
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(time.Time)
|
||||
}
|
||||
var arg2 int32
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(int32)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListStalePending_Call) Return(attachments []domain.Attachment, err error) *MockRepository_ListStalePending_Call {
|
||||
_c.Call.Return(attachments, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListStalePending_Call) RunAndReturn(run func(ctx context.Context, createdBefore time.Time, limit int32) ([]domain.Attachment, error)) *MockRepository_ListStalePending_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// ListStates provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) ListStates(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID) ([]domain.AttachmentState, error) {
|
||||
ret := _mock.Called(ctx, chatID, ids)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListStates")
|
||||
}
|
||||
|
||||
var r0 []domain.AttachmentState
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, []uuid.UUID) ([]domain.AttachmentState, error)); ok {
|
||||
return returnFunc(ctx, chatID, ids)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, []uuid.UUID) []domain.AttachmentState); ok {
|
||||
r0 = returnFunc(ctx, chatID, ids)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]domain.AttachmentState)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, []uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, chatID, ids)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_ListStates_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListStates'
|
||||
type MockRepository_ListStates_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListStates is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - chatID uuid.UUID
|
||||
// - ids []uuid.UUID
|
||||
func (_e *MockRepository_Expecter) ListStates(ctx any, chatID any, ids any) *MockRepository_ListStates_Call {
|
||||
return &MockRepository_ListStates_Call{Call: _e.mock.On("ListStates", ctx, chatID, ids)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListStates_Call) Run(run func(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID)) *MockRepository_ListStates_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 []uuid.UUID
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].([]uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListStates_Call) Return(attachmentStates []domain.AttachmentState, err error) *MockRepository_ListStates_Call {
|
||||
_c.Call.Return(attachmentStates, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListStates_Call) RunAndReturn(run func(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID) ([]domain.AttachmentState, error)) *MockRepository_ListStates_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// MarkReady provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) MarkReady(ctx context.Context, id uuid.UUID, objectKey string) (domain.Attachment, error) {
|
||||
ret := _mock.Called(ctx, id, objectKey)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for MarkReady")
|
||||
}
|
||||
|
||||
var r0 domain.Attachment
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, string) (domain.Attachment, error)); ok {
|
||||
return returnFunc(ctx, id, objectKey)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, string) domain.Attachment); ok {
|
||||
r0 = returnFunc(ctx, id, objectKey)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Attachment)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, string) error); ok {
|
||||
r1 = returnFunc(ctx, id, objectKey)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_MarkReady_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MarkReady'
|
||||
type MockRepository_MarkReady_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// MarkReady is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - id uuid.UUID
|
||||
// - objectKey string
|
||||
func (_e *MockRepository_Expecter) MarkReady(ctx any, id any, objectKey any) *MockRepository_MarkReady_Call {
|
||||
return &MockRepository_MarkReady_Call{Call: _e.mock.On("MarkReady", ctx, id, objectKey)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_MarkReady_Call) Run(run func(ctx context.Context, id uuid.UUID, objectKey string)) *MockRepository_MarkReady_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 string
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_MarkReady_Call) Return(attachment domain.Attachment, err error) *MockRepository_MarkReady_Call {
|
||||
_c.Call.Return(attachment, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_MarkReady_Call) RunAndReturn(run func(ctx context.Context, id uuid.UUID, objectKey string) (domain.Attachment, error)) *MockRepository_MarkReady_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,495 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"os"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/imagecheck"
|
||||
"mtusi-messenger/internal/platform/objectstore"
|
||||
)
|
||||
|
||||
const (
|
||||
contentTypePNG = "image/png"
|
||||
contentTypeJPEG = "image/jpeg"
|
||||
|
||||
objectPrefixAttachments = "attachments/"
|
||||
objectPrefixStaging = "staging/"
|
||||
objectPrefixPresign = "staging/presign/"
|
||||
)
|
||||
|
||||
var sha256Pattern = regexp.MustCompile(`^[0-9a-f]{64}$`)
|
||||
|
||||
// Repository is the persistence port. It is consumer-side so the service can be
|
||||
// tested without PostgreSQL.
|
||||
type Repository interface {
|
||||
IsChatMember(ctx context.Context, chatID, userID uuid.UUID) (bool, error)
|
||||
Create(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error)
|
||||
MarkReady(ctx context.Context, id uuid.UUID, objectKey string) (domain.Attachment, error)
|
||||
DeletePending(ctx context.Context, id uuid.UUID) error
|
||||
GetForMember(ctx context.Context, userID, id uuid.UUID) (domain.Attachment, error)
|
||||
GetForOwner(ctx context.Context, ownerID, id uuid.UUID) (domain.Attachment, error)
|
||||
ListStates(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID) ([]domain.AttachmentState, error)
|
||||
ListStalePending(ctx context.Context, createdBefore time.Time, limit int32) ([]domain.Attachment, error)
|
||||
ListKeys(ctx context.Context, limit, offset int32) ([]domain.AttachmentKey, error)
|
||||
}
|
||||
|
||||
// Config carries the attachment limits. They are validated by config.Load.
|
||||
type Config struct {
|
||||
MaxUploadBytes int64
|
||||
MaxImagePixels int64
|
||||
PresignTTL time.Duration
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
repo Repository
|
||||
store objectstore.Store
|
||||
config Config
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func NewService(repo Repository, store objectstore.Store, config Config, log *slog.Logger) *Service {
|
||||
if log == nil {
|
||||
log = slog.Default()
|
||||
}
|
||||
|
||||
return &Service{repo: repo, store: store, config: config, log: log}
|
||||
}
|
||||
|
||||
// UploadInput is one raw-body upload. DeclaredContentType comes from the HTTP
|
||||
// Content-Type header and is cross-checked against the detected format.
|
||||
type UploadInput struct {
|
||||
ChatID uuid.UUID
|
||||
OwnerID uuid.UUID
|
||||
Filename string
|
||||
DeclaredContentType string
|
||||
Body io.Reader
|
||||
}
|
||||
|
||||
func (s *Service) Upload(ctx context.Context, input UploadInput) (domain.Attachment, error) {
|
||||
if err := ValidateFilename(input.Filename); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
|
||||
member, err := s.repo.IsChatMember(ctx, input.ChatID, input.OwnerID)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
|
||||
if !member {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: chat is not visible", domain.ErrNotFound)
|
||||
}
|
||||
|
||||
file, size, sum, err := s.spool(input.Body)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
|
||||
defer func() { _ = file.Close() }()
|
||||
defer func() { _ = os.Remove(file.Name()) }()
|
||||
|
||||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("rewind upload: %w", err)
|
||||
}
|
||||
|
||||
info, err := imagecheck.Validate(file, s.config.MaxImagePixels)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, mapImageError(err)
|
||||
}
|
||||
|
||||
if info.ContentType != input.DeclaredContentType {
|
||||
return domain.Attachment{}, fmt.Errorf(
|
||||
"%w: declared %q, detected %q",
|
||||
domain.ErrUnsupportedMedia, input.DeclaredContentType, info.ContentType,
|
||||
)
|
||||
}
|
||||
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("generate attachment id: %w", err)
|
||||
}
|
||||
|
||||
objectKey := objectPrefixAttachments + input.ChatID.String() + "/" + id.String()
|
||||
|
||||
if _, err := s.repo.Create(ctx, domain.AttachmentDraft{
|
||||
ID: id,
|
||||
ChatID: input.ChatID,
|
||||
OwnerID: input.OwnerID,
|
||||
ObjectKey: objectKey,
|
||||
Filename: input.Filename,
|
||||
ContentType: info.ContentType,
|
||||
SizeBytes: size,
|
||||
SHA256: sum,
|
||||
}); err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
|
||||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("rewind upload: %w", err)
|
||||
}
|
||||
|
||||
if err := s.store.Put(ctx, objectKey, file, size, info.ContentType, map[string]string{"sha256": sum}); err != nil {
|
||||
s.cleanupPending(ctx, id, "")
|
||||
|
||||
return domain.Attachment{}, unavailable("store attachment", err)
|
||||
}
|
||||
|
||||
ready, err := s.repo.MarkReady(ctx, id, objectKey)
|
||||
if err != nil {
|
||||
// The object and the pending row remain; the sweeper either finalises
|
||||
// the row or removes both after the grace period. The client must not
|
||||
// receive 201 until metadata is committed.
|
||||
return domain.Attachment{}, unavailable("commit attachment", err)
|
||||
}
|
||||
|
||||
return ready, nil
|
||||
}
|
||||
|
||||
func (s *Service) Get(ctx context.Context, callerID, id uuid.UUID) (domain.Attachment, error) {
|
||||
attachment, err := s.repo.GetForMember(ctx, callerID, id)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
|
||||
// Contract 1.4.0 declares Attachment.status as the single value "ready".
|
||||
// Pending/failed rows therefore cannot be represented in a 200 response;
|
||||
// they are reported as 409 until lab5 extends the enum.
|
||||
if attachment.Status != domain.AttachmentReady {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: attachment is %s", domain.ErrConflict, attachment.Status)
|
||||
}
|
||||
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
// Open returns metadata and the original stream. Only ready attachments have
|
||||
// bytes; pending/failed return 409 on the content endpoint.
|
||||
func (s *Service) Open(
|
||||
ctx context.Context,
|
||||
callerID, id uuid.UUID,
|
||||
) (domain.Attachment, io.ReadCloser, error) {
|
||||
attachment, err := s.repo.GetForMember(ctx, callerID, id)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, nil, err
|
||||
}
|
||||
|
||||
if attachment.Status != domain.AttachmentReady {
|
||||
return domain.Attachment{}, nil, fmt.Errorf("%w: attachment is %s", domain.ErrConflict, attachment.Status)
|
||||
}
|
||||
|
||||
body, _, err := s.store.Open(ctx, attachment.ObjectKey)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, nil, err
|
||||
}
|
||||
|
||||
return attachment, body, nil
|
||||
}
|
||||
|
||||
func (s *Service) Presign(ctx context.Context, request domain.PresignRequest) (domain.PresignResult, error) {
|
||||
if err := ValidateFilename(request.Filename); err != nil {
|
||||
return domain.PresignResult{}, err
|
||||
}
|
||||
|
||||
if request.ContentType != contentTypePNG && request.ContentType != contentTypeJPEG {
|
||||
return domain.PresignResult{}, fmt.Errorf("%w: content type %q", domain.ErrUnsupportedMedia, request.ContentType)
|
||||
}
|
||||
|
||||
if request.SizeBytes < 1 {
|
||||
return domain.PresignResult{}, fmt.Errorf("%w: size %d", domain.ErrValidation, request.SizeBytes)
|
||||
}
|
||||
|
||||
if request.SizeBytes > s.config.MaxUploadBytes {
|
||||
return domain.PresignResult{}, fmt.Errorf("%w: size %d", domain.ErrTooLarge, request.SizeBytes)
|
||||
}
|
||||
|
||||
if !sha256Pattern.MatchString(request.SHA256) {
|
||||
return domain.PresignResult{}, fmt.Errorf("%w: sha256 must be 64 lowercase hex characters", domain.ErrValidation)
|
||||
}
|
||||
|
||||
member, err := s.repo.IsChatMember(ctx, request.ChatID, request.OwnerID)
|
||||
if err != nil {
|
||||
return domain.PresignResult{}, err
|
||||
}
|
||||
|
||||
if !member {
|
||||
return domain.PresignResult{}, fmt.Errorf("%w: chat is not visible", domain.ErrNotFound)
|
||||
}
|
||||
|
||||
id, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return domain.PresignResult{}, fmt.Errorf("generate attachment id: %w", err)
|
||||
}
|
||||
|
||||
stagingKey := objectPrefixPresign + request.ChatID.String() + "/" + id.String()
|
||||
|
||||
if _, err := s.repo.Create(ctx, domain.AttachmentDraft{
|
||||
ID: id,
|
||||
ChatID: request.ChatID,
|
||||
OwnerID: request.OwnerID,
|
||||
ObjectKey: stagingKey,
|
||||
Filename: request.Filename,
|
||||
ContentType: request.ContentType,
|
||||
SizeBytes: request.SizeBytes,
|
||||
SHA256: request.SHA256,
|
||||
}); err != nil {
|
||||
return domain.PresignResult{}, err
|
||||
}
|
||||
|
||||
url, expiresAt, err := s.store.PresignPut(ctx, stagingKey, request.SizeBytes, s.config.PresignTTL)
|
||||
if err != nil {
|
||||
s.cleanupPending(ctx, id, "")
|
||||
|
||||
return domain.PresignResult{}, unavailable("presign attachment", err)
|
||||
}
|
||||
|
||||
return domain.PresignResult{
|
||||
AttachmentID: id,
|
||||
UploadURL: url,
|
||||
ExpiresAt: expiresAt,
|
||||
SizeBytes: request.SizeBytes,
|
||||
SHA256: request.SHA256,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) Complete(
|
||||
ctx context.Context,
|
||||
ownerID, id uuid.UUID,
|
||||
requestSHA string,
|
||||
) (domain.Attachment, error) {
|
||||
if !sha256Pattern.MatchString(requestSHA) {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: sha256 must be 64 lowercase hex characters", domain.ErrValidation)
|
||||
}
|
||||
|
||||
attachment, err := s.repo.GetForOwner(ctx, ownerID, id)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
|
||||
switch attachment.Status {
|
||||
case domain.AttachmentReady:
|
||||
if attachment.SHA256 != requestSHA {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: attachment already completed with another checksum", domain.ErrConflict)
|
||||
}
|
||||
|
||||
return attachment, nil
|
||||
case domain.AttachmentFailed:
|
||||
return domain.Attachment{}, fmt.Errorf("%w: attachment is failed", domain.ErrConflict)
|
||||
case domain.AttachmentPending:
|
||||
default:
|
||||
return domain.Attachment{}, fmt.Errorf("%w: unknown attachment status", domain.ErrConflict)
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(attachment.ObjectKey, objectPrefixPresign) {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: attachment is not a presigned upload", domain.ErrConflict)
|
||||
}
|
||||
|
||||
head, err := s.store.Head(ctx, attachment.ObjectKey)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: object was not uploaded", domain.ErrIncomplete)
|
||||
}
|
||||
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
|
||||
if head.Size != attachment.SizeBytes {
|
||||
s.cleanupPending(ctx, id, attachment.ObjectKey)
|
||||
|
||||
return domain.Attachment{}, fmt.Errorf(
|
||||
"%w: uploaded %d bytes, declared %d",
|
||||
domain.ErrValidation, head.Size, attachment.SizeBytes,
|
||||
)
|
||||
}
|
||||
|
||||
body, _, err := s.store.Open(ctx, attachment.ObjectKey)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
|
||||
hasher := sha256.New()
|
||||
info, validateErr := imagecheck.Validate(io.TeeReader(body, hasher), s.config.MaxImagePixels)
|
||||
closeErr := body.Close()
|
||||
|
||||
if validateErr != nil {
|
||||
s.cleanupPending(ctx, id, attachment.ObjectKey)
|
||||
|
||||
return domain.Attachment{}, mapImageError(validateErr)
|
||||
}
|
||||
|
||||
if closeErr != nil {
|
||||
return domain.Attachment{}, unavailable("read uploaded object", closeErr)
|
||||
}
|
||||
|
||||
if info.ContentType != attachment.ContentType {
|
||||
s.cleanupPending(ctx, id, attachment.ObjectKey)
|
||||
|
||||
return domain.Attachment{}, fmt.Errorf(
|
||||
"%w: declared %q, detected %q",
|
||||
domain.ErrUnsupportedMedia, attachment.ContentType, info.ContentType,
|
||||
)
|
||||
}
|
||||
|
||||
sum := hex.EncodeToString(hasher.Sum(nil))
|
||||
if sum != attachment.SHA256 {
|
||||
s.cleanupPending(ctx, id, attachment.ObjectKey)
|
||||
|
||||
return domain.Attachment{}, fmt.Errorf("%w: uploaded object checksum mismatch", domain.ErrValidation)
|
||||
}
|
||||
|
||||
if requestSHA != attachment.SHA256 {
|
||||
// The object is valid; only the completion request is inconsistent.
|
||||
// Keep the pending row and staging object so a retry can succeed.
|
||||
return domain.Attachment{}, fmt.Errorf("%w: completion checksum mismatch", domain.ErrConflict)
|
||||
}
|
||||
|
||||
finalKey := objectPrefixAttachments + attachment.ChatID.String() + "/" + id.String()
|
||||
|
||||
if err := s.store.Copy(ctx, attachment.ObjectKey, finalKey, attachment.ContentType, map[string]string{"sha256": sum}); err != nil {
|
||||
return domain.Attachment{}, unavailable("publish attachment", err)
|
||||
}
|
||||
|
||||
ready, err := s.repo.MarkReady(ctx, id, finalKey)
|
||||
if err != nil {
|
||||
// A concurrent completion may have won. Re-read instead of reporting a
|
||||
// spurious failure.
|
||||
current, getErr := s.repo.GetForOwner(ctx, ownerID, id)
|
||||
if getErr == nil && current.Status == domain.AttachmentReady && current.SHA256 == requestSHA {
|
||||
return current, nil
|
||||
}
|
||||
|
||||
return domain.Attachment{}, unavailable("commit attachment", err)
|
||||
}
|
||||
|
||||
if err := s.store.Delete(ctx, attachment.ObjectKey); err != nil {
|
||||
// The final object is already committed; a stale staging object is an
|
||||
// orphan and the sweeper removes it after the grace period.
|
||||
s.log.WarnContext(ctx, "staging object cleanup failed",
|
||||
slog.String("attachment_id", id.String()),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
}
|
||||
|
||||
return ready, nil
|
||||
}
|
||||
|
||||
func (s *Service) spool(body io.Reader) (*os.File, int64, string, error) {
|
||||
file, err := os.CreateTemp("", "lab4-upload-*")
|
||||
if err != nil {
|
||||
return nil, 0, "", fmt.Errorf("create upload spool: %w", err)
|
||||
}
|
||||
|
||||
cleanup := func() {
|
||||
_ = file.Close()
|
||||
_ = os.Remove(file.Name())
|
||||
}
|
||||
|
||||
hasher := sha256.New()
|
||||
limited := io.LimitReader(body, s.config.MaxUploadBytes+1)
|
||||
buffer := make([]byte, 32<<10)
|
||||
|
||||
size, err := io.CopyBuffer(io.MultiWriter(file, hasher), limited, buffer)
|
||||
if err != nil {
|
||||
cleanup()
|
||||
|
||||
var maxBytes *http.MaxBytesError
|
||||
if errors.As(err, &maxBytes) {
|
||||
return nil, 0, "", fmt.Errorf("%w: request body exceeds %d bytes", domain.ErrTooLarge, s.config.MaxUploadBytes)
|
||||
}
|
||||
|
||||
return nil, 0, "", fmt.Errorf("%w: read upload: %w", domain.ErrValidation, err)
|
||||
}
|
||||
|
||||
if size > s.config.MaxUploadBytes {
|
||||
cleanup()
|
||||
|
||||
return nil, 0, "", fmt.Errorf("%w: upload exceeds %d bytes", domain.ErrTooLarge, s.config.MaxUploadBytes)
|
||||
}
|
||||
|
||||
if size == 0 {
|
||||
cleanup()
|
||||
|
||||
return nil, 0, "", fmt.Errorf("%w: empty image", domain.ErrUnsupportedMedia)
|
||||
}
|
||||
|
||||
return file, size, hex.EncodeToString(hasher.Sum(nil)), nil
|
||||
}
|
||||
|
||||
func (s *Service) cleanupPending(ctx context.Context, id uuid.UUID, objectKey string) {
|
||||
if objectKey != "" {
|
||||
if err := s.store.Delete(ctx, objectKey); err != nil && !errors.Is(err, domain.ErrNotFound) {
|
||||
s.log.WarnContext(ctx, "object cleanup failed",
|
||||
slog.String("attachment_id", id.String()),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.repo.DeletePending(ctx, id); err != nil && !errors.Is(err, domain.ErrNotFound) {
|
||||
s.log.WarnContext(ctx, "pending attachment cleanup failed",
|
||||
slog.String("attachment_id", id.String()),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// ValidateFilename implements the contract rule: 1-255 Unicode code points,
|
||||
// no path separators, NUL or control characters. The name is display-only; the
|
||||
// S3 key is always generated.
|
||||
func ValidateFilename(name string) error {
|
||||
if !utf8.ValidString(name) {
|
||||
return fmt.Errorf("%w: filename is not valid UTF-8", domain.ErrValidation)
|
||||
}
|
||||
|
||||
length := utf8.RuneCountInString(name)
|
||||
if length < 1 || length > 255 {
|
||||
return fmt.Errorf("%w: filename length is %d, want 1-255 code points", domain.ErrValidation, length)
|
||||
}
|
||||
|
||||
if strings.TrimSpace(name) == "" {
|
||||
return fmt.Errorf("%w: filename consists of whitespace only", domain.ErrValidation)
|
||||
}
|
||||
|
||||
if strings.ContainsAny(name, "/\\\x00") {
|
||||
return fmt.Errorf("%w: filename contains a path separator or NUL", domain.ErrValidation)
|
||||
}
|
||||
|
||||
for _, r := range name {
|
||||
if unicode.IsControl(r) {
|
||||
return fmt.Errorf("%w: filename contains a control character", domain.ErrValidation)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func mapImageError(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, imagecheck.ErrTooLarge):
|
||||
return fmt.Errorf("%w: %w", domain.ErrTooLarge, err)
|
||||
case errors.Is(err, imagecheck.ErrUnsupported), errors.Is(err, imagecheck.ErrCorrupt):
|
||||
return fmt.Errorf("%w: %w", domain.ErrUnsupportedMedia, err)
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func unavailable(operation string, err error) error {
|
||||
if errors.Is(err, domain.ErrUnavailable) || errors.Is(err, domain.ErrNotFound) {
|
||||
return err
|
||||
}
|
||||
|
||||
return fmt.Errorf("%w: %s: %w", domain.ErrUnavailable, operation, err)
|
||||
}
|
||||
@@ -0,0 +1,361 @@
|
||||
package attachment_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"io"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/objectstore"
|
||||
"mtusi-messenger/internal/service/attachment"
|
||||
"mtusi-messenger/internal/service/attachment/mocks"
|
||||
)
|
||||
|
||||
type storedObject struct {
|
||||
data []byte
|
||||
contentType string
|
||||
metadata map[string]string
|
||||
lastModified time.Time
|
||||
}
|
||||
|
||||
type fakeStore struct {
|
||||
objects map[string]storedObject
|
||||
}
|
||||
|
||||
func newFakeStore() *fakeStore {
|
||||
return &fakeStore{objects: make(map[string]storedObject)}
|
||||
}
|
||||
|
||||
func (f *fakeStore) Put(
|
||||
_ context.Context,
|
||||
key string,
|
||||
body io.ReadSeeker,
|
||||
_ int64,
|
||||
contentType string,
|
||||
metadata map[string]string,
|
||||
) error {
|
||||
data, err := io.ReadAll(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
f.objects[key] = storedObject{
|
||||
data: data,
|
||||
contentType: contentType,
|
||||
metadata: metadata,
|
||||
lastModified: time.Now().UTC(),
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) Open(_ context.Context, key string) (io.ReadCloser, objectstore.Object, error) {
|
||||
object, ok := f.objects[key]
|
||||
if !ok {
|
||||
return nil, objectstore.Object{}, domain.ErrNotFound
|
||||
}
|
||||
|
||||
return io.NopCloser(bytes.NewReader(object.data)), f.object(key, object), nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) Head(_ context.Context, key string) (objectstore.Object, error) {
|
||||
object, ok := f.objects[key]
|
||||
if !ok {
|
||||
return objectstore.Object{}, domain.ErrNotFound
|
||||
}
|
||||
|
||||
return f.object(key, object), nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) Copy(_ context.Context, src, dst, contentType string, metadata map[string]string) error {
|
||||
object, ok := f.objects[src]
|
||||
if !ok {
|
||||
return domain.ErrNotFound
|
||||
}
|
||||
|
||||
f.objects[dst] = storedObject{
|
||||
data: append([]byte(nil), object.data...),
|
||||
contentType: contentType,
|
||||
metadata: metadata,
|
||||
lastModified: time.Now().UTC(),
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) Delete(_ context.Context, key string) error {
|
||||
delete(f.objects, key)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) List(_ context.Context, prefix string) ([]objectstore.Object, error) {
|
||||
objects := make([]objectstore.Object, 0, len(f.objects))
|
||||
for key, object := range f.objects {
|
||||
if strings.HasPrefix(key, prefix) {
|
||||
objects = append(objects, f.object(key, object))
|
||||
}
|
||||
}
|
||||
|
||||
return objects, nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) PresignPut(_ context.Context, key string, _ int64, ttl time.Duration) (string, time.Time, error) {
|
||||
return "http://s3.example/" + key, time.Now().UTC().Add(ttl), nil
|
||||
}
|
||||
|
||||
func (f *fakeStore) object(key string, object storedObject) objectstore.Object {
|
||||
return objectstore.Object{
|
||||
Key: key,
|
||||
Size: int64(len(object.data)),
|
||||
ContentType: object.contentType,
|
||||
LastModified: object.lastModified,
|
||||
Metadata: object.metadata,
|
||||
}
|
||||
}
|
||||
|
||||
func pngBytes(t *testing.T, width, height int) []byte {
|
||||
t.Helper()
|
||||
|
||||
source := image.NewRGBA(image.Rect(0, 0, width, height))
|
||||
for x := range width {
|
||||
for y := range height {
|
||||
source.Set(x, y, color.RGBA{R: uint8(x), G: uint8(y), B: 200, A: 255})
|
||||
}
|
||||
}
|
||||
|
||||
var buffer bytes.Buffer
|
||||
require.NoError(t, png.Encode(&buffer, source))
|
||||
|
||||
return buffer.Bytes()
|
||||
}
|
||||
|
||||
func serviceConfig() attachment.Config {
|
||||
return attachment.Config{
|
||||
MaxUploadBytes: 1 << 20,
|
||||
MaxImagePixels: 1_000_000,
|
||||
PresignTTL: 5 * time.Minute,
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateFilename(t *testing.T) {
|
||||
valid := []string{"photo.png", "фото.png", "a b.jpeg", strings.Repeat("я", 255)}
|
||||
for _, name := range valid {
|
||||
require.NoError(t, attachment.ValidateFilename(name), name)
|
||||
}
|
||||
|
||||
invalid := []string{"", " ", "\t\n", strings.Repeat("x", 256), "a/b.png", `a\b.png`, "a\x00b.png", "a\nb.png"}
|
||||
for _, name := range invalid {
|
||||
require.ErrorIs(t, attachment.ValidateFilename(name), domain.ErrValidation, name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadStoresOriginal(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
store := newFakeStore()
|
||||
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
|
||||
|
||||
chatID := uuid.New()
|
||||
ownerID := uuid.New()
|
||||
content := pngBytes(t, 16, 16)
|
||||
sum := sha256.Sum256(content)
|
||||
|
||||
repo.EXPECT().IsChatMember(mock.Anything, chatID, ownerID).Return(true, nil).Once()
|
||||
repo.EXPECT().Create(mock.Anything, mock.MatchedBy(func(draft domain.AttachmentDraft) bool {
|
||||
return draft.ChatID == chatID && draft.OwnerID == ownerID &&
|
||||
draft.ContentType == "image/png" && draft.SizeBytes == int64(len(content)) &&
|
||||
draft.SHA256 == hex.EncodeToString(sum[:]) && strings.HasPrefix(draft.ObjectKey, "attachments/")
|
||||
})).Return(domain.Attachment{Status: domain.AttachmentPending}, nil).Once()
|
||||
repo.EXPECT().MarkReady(mock.Anything, mock.Anything, mock.Anything).
|
||||
Return(domain.Attachment{Status: domain.AttachmentReady, ContentType: "image/png", SizeBytes: int64(len(content))}, nil).
|
||||
Once()
|
||||
|
||||
result, err := service.Upload(t.Context(), attachment.UploadInput{
|
||||
ChatID: chatID,
|
||||
OwnerID: ownerID,
|
||||
Filename: "photo.png",
|
||||
DeclaredContentType: "image/png",
|
||||
Body: bytes.NewReader(content),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, domain.AttachmentReady, result.Status)
|
||||
require.Len(t, store.objects, 1)
|
||||
}
|
||||
|
||||
func TestUploadRejectsTooLargeBody(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
service := attachment.NewService(repo, newFakeStore(), attachment.Config{
|
||||
MaxUploadBytes: 8,
|
||||
MaxImagePixels: 1_000_000,
|
||||
PresignTTL: time.Minute,
|
||||
}, slog.Default())
|
||||
|
||||
repo.EXPECT().IsChatMember(mock.Anything, mock.Anything, mock.Anything).Return(true, nil).Once()
|
||||
|
||||
_, err := service.Upload(t.Context(), attachment.UploadInput{
|
||||
ChatID: uuid.New(),
|
||||
OwnerID: uuid.New(),
|
||||
Filename: "photo.png",
|
||||
DeclaredContentType: "image/png",
|
||||
Body: bytes.NewReader(bytes.Repeat([]byte("x"), 9)),
|
||||
})
|
||||
|
||||
require.ErrorIs(t, err, domain.ErrTooLarge)
|
||||
}
|
||||
|
||||
func TestUploadRejectsMIMEMismatch(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
|
||||
|
||||
repo.EXPECT().IsChatMember(mock.Anything, mock.Anything, mock.Anything).Return(true, nil).Once()
|
||||
|
||||
_, err := service.Upload(t.Context(), attachment.UploadInput{
|
||||
ChatID: uuid.New(),
|
||||
OwnerID: uuid.New(),
|
||||
Filename: "photo.jpg",
|
||||
DeclaredContentType: "image/jpeg",
|
||||
Body: bytes.NewReader(pngBytes(t, 8, 8)),
|
||||
})
|
||||
|
||||
require.ErrorIs(t, err, domain.ErrUnsupportedMedia)
|
||||
}
|
||||
|
||||
func TestGetRejectsNonReadyAttachment(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
|
||||
|
||||
repo.EXPECT().GetForMember(mock.Anything, mock.Anything, mock.Anything).
|
||||
Return(domain.Attachment{Status: domain.AttachmentPending}, nil).Once()
|
||||
|
||||
_, err := service.Get(t.Context(), uuid.New(), uuid.New())
|
||||
require.ErrorIs(t, err, domain.ErrConflict)
|
||||
}
|
||||
|
||||
func TestCompletePublishesPresignedObject(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
store := newFakeStore()
|
||||
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
|
||||
|
||||
id := uuid.New()
|
||||
chatID := uuid.New()
|
||||
ownerID := uuid.New()
|
||||
content := pngBytes(t, 10, 10)
|
||||
sum := sha256.Sum256(content)
|
||||
digest := hex.EncodeToString(sum[:])
|
||||
stagingKey := "staging/presign/" + chatID.String() + "/" + id.String()
|
||||
|
||||
store.objects[stagingKey] = storedObject{
|
||||
data: content,
|
||||
contentType: "image/png",
|
||||
metadata: map[string]string{"sha256": digest},
|
||||
lastModified: time.Now().UTC(),
|
||||
}
|
||||
|
||||
pending := domain.Attachment{
|
||||
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: stagingKey,
|
||||
ContentType: "image/png", SizeBytes: int64(len(content)), SHA256: digest,
|
||||
Status: domain.AttachmentPending,
|
||||
}
|
||||
|
||||
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(pending, nil).Once()
|
||||
repo.EXPECT().MarkReady(mock.Anything, id, mock.MatchedBy(func(key string) bool {
|
||||
return strings.HasPrefix(key, "attachments/")
|
||||
})).Return(domain.Attachment{
|
||||
ID: id, ChatID: chatID, OwnerID: ownerID, ContentType: "image/png",
|
||||
SizeBytes: int64(len(content)), SHA256: digest, Status: domain.AttachmentReady,
|
||||
}, nil).Once()
|
||||
|
||||
completed, err := service.Complete(t.Context(), ownerID, id, digest)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, domain.AttachmentReady, completed.Status)
|
||||
require.NotContains(t, store.objects, stagingKey)
|
||||
require.Len(t, store.objects, 1)
|
||||
}
|
||||
|
||||
func TestCompleteRejectsChecksumMismatch(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
store := newFakeStore()
|
||||
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
|
||||
|
||||
id := uuid.New()
|
||||
chatID := uuid.New()
|
||||
ownerID := uuid.New()
|
||||
content := pngBytes(t, 10, 10)
|
||||
sum := sha256.Sum256(content)
|
||||
digest := hex.EncodeToString(sum[:])
|
||||
stagingKey := "staging/presign/" + chatID.String() + "/" + id.String()
|
||||
|
||||
store.objects[stagingKey] = storedObject{
|
||||
data: content,
|
||||
contentType: "image/png",
|
||||
metadata: map[string]string{"sha256": digest},
|
||||
}
|
||||
|
||||
pending := domain.Attachment{
|
||||
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: stagingKey,
|
||||
ContentType: "image/png", SizeBytes: int64(len(content)) + 1, SHA256: digest,
|
||||
Status: domain.AttachmentPending,
|
||||
}
|
||||
|
||||
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(pending, nil).Once()
|
||||
repo.EXPECT().DeletePending(mock.Anything, id).Return(nil).Once()
|
||||
|
||||
_, err := service.Complete(t.Context(), ownerID, id, digest)
|
||||
require.ErrorIs(t, err, domain.ErrValidation)
|
||||
require.NotContains(t, store.objects, stagingKey)
|
||||
}
|
||||
|
||||
func TestCompleteKeepsObjectOnWrongRequestChecksum(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
store := newFakeStore()
|
||||
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
|
||||
|
||||
id := uuid.New()
|
||||
chatID := uuid.New()
|
||||
ownerID := uuid.New()
|
||||
content := pngBytes(t, 10, 10)
|
||||
sum := sha256.Sum256(content)
|
||||
digest := hex.EncodeToString(sum[:])
|
||||
stagingKey := "staging/presign/" + chatID.String() + "/" + id.String()
|
||||
|
||||
store.objects[stagingKey] = storedObject{
|
||||
data: content,
|
||||
contentType: "image/png",
|
||||
metadata: map[string]string{"sha256": digest},
|
||||
}
|
||||
pending := domain.Attachment{
|
||||
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: stagingKey,
|
||||
ContentType: "image/png", SizeBytes: int64(len(content)), SHA256: digest,
|
||||
Status: domain.AttachmentPending,
|
||||
}
|
||||
|
||||
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(pending, nil).Once()
|
||||
|
||||
_, err := service.Complete(t.Context(), ownerID, id, strings.Repeat("0", 64))
|
||||
require.ErrorIs(t, err, domain.ErrConflict)
|
||||
require.Contains(t, store.objects, stagingKey)
|
||||
}
|
||||
|
||||
func TestPresignRejectsNonPositiveSize(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
|
||||
|
||||
_, err := service.Presign(t.Context(), domain.PresignRequest{
|
||||
ChatID: uuid.New(), OwnerID: uuid.New(),
|
||||
Filename: "photo.png", ContentType: "image/png",
|
||||
SizeBytes: 0, SHA256: strings.Repeat("a", 64),
|
||||
})
|
||||
require.ErrorIs(t, err, domain.ErrValidation)
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/objectstore"
|
||||
)
|
||||
|
||||
// LockStore serialises sweepers across API replicas.
|
||||
type LockStore interface {
|
||||
AcquireSweepLock(ctx context.Context) (release func(), acquired bool, err error)
|
||||
}
|
||||
|
||||
type SweepStats struct {
|
||||
Recovered int
|
||||
RowsDeleted int
|
||||
ObjectsDeleted int
|
||||
}
|
||||
|
||||
type Sweeper struct {
|
||||
repo Repository
|
||||
store objectstore.Store
|
||||
locker LockStore
|
||||
grace time.Duration
|
||||
interval time.Duration
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func NewSweeper(
|
||||
repo Repository,
|
||||
store objectstore.Store,
|
||||
locker LockStore,
|
||||
grace, interval time.Duration,
|
||||
log *slog.Logger,
|
||||
) *Sweeper {
|
||||
if log == nil {
|
||||
log = slog.Default()
|
||||
}
|
||||
|
||||
return &Sweeper{
|
||||
repo: repo,
|
||||
store: store,
|
||||
locker: locker,
|
||||
grace: grace,
|
||||
interval: interval,
|
||||
log: log,
|
||||
}
|
||||
}
|
||||
|
||||
// Run sweeps immediately, then on every interval until the context is done.
|
||||
func (s *Sweeper) Run(ctx context.Context) {
|
||||
s.sweep(ctx)
|
||||
|
||||
ticker := time.NewTicker(s.interval)
|
||||
defer ticker.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
s.sweep(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Sweeper) sweep(ctx context.Context) {
|
||||
stats, err := s.SweepOnce(ctx)
|
||||
if err != nil {
|
||||
s.log.WarnContext(ctx, "attachment sweep failed", slog.Any("error", err))
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if stats.Recovered+stats.RowsDeleted+stats.ObjectsDeleted > 0 {
|
||||
s.log.InfoContext(ctx, "attachment sweep finished",
|
||||
slog.Int("recovered", stats.Recovered),
|
||||
slog.Int("rows_deleted", stats.RowsDeleted),
|
||||
slog.Int("objects_deleted", stats.ObjectsDeleted),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// SweepOnce reconciles PostgreSQL metadata with S3 objects. It never deletes a
|
||||
// ready row or an object referenced by any row. Only objects older than the
|
||||
// grace period are candidates, so an in-flight upload cannot be collected.
|
||||
func (s *Sweeper) SweepOnce(ctx context.Context) (SweepStats, error) {
|
||||
release, acquired, err := s.locker.AcquireSweepLock(ctx)
|
||||
if err != nil {
|
||||
return SweepStats{}, err
|
||||
}
|
||||
|
||||
if !acquired {
|
||||
return SweepStats{}, nil
|
||||
}
|
||||
|
||||
defer release()
|
||||
|
||||
before := time.Now().UTC().Add(-s.grace)
|
||||
|
||||
var stats SweepStats
|
||||
|
||||
stale, err := s.repo.ListStalePending(ctx, before, 100)
|
||||
if err != nil {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
for _, row := range stale {
|
||||
if row.Status != domain.AttachmentPending {
|
||||
continue
|
||||
}
|
||||
|
||||
if strings.HasPrefix(row.ObjectKey, objectPrefixPresign) {
|
||||
if s.deleteObject(ctx, row.ObjectKey) {
|
||||
stats.ObjectsDeleted++
|
||||
}
|
||||
|
||||
if err := s.repo.DeletePending(ctx, row.ID); err != nil && !errors.Is(err, domain.ErrNotFound) {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
stats.RowsDeleted++
|
||||
continue
|
||||
}
|
||||
|
||||
// A proxy upload writes directly to its final key. If the process died
|
||||
// between PutObject and MarkReady, the object is complete and can be
|
||||
// recovered instead of discarded.
|
||||
head, err := s.store.Head(ctx, row.ObjectKey)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
if err := s.repo.DeletePending(ctx, row.ID); err != nil && !errors.Is(err, domain.ErrNotFound) {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
stats.RowsDeleted++
|
||||
continue
|
||||
}
|
||||
|
||||
s.log.WarnContext(ctx, "sweep head failed",
|
||||
slog.String("attachment_id", row.ID.String()),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if head.Size == row.SizeBytes && head.Metadata["sha256"] == row.SHA256 {
|
||||
if _, err := s.repo.MarkReady(ctx, row.ID, row.ObjectKey); err != nil {
|
||||
// A transient database failure must not destroy a valid object.
|
||||
// Leave both the row and the object for the next sweep.
|
||||
s.log.WarnContext(ctx, "sweep recovery failed",
|
||||
slog.String("attachment_id", row.ID.String()),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
continue
|
||||
}
|
||||
|
||||
stats.Recovered++
|
||||
continue
|
||||
}
|
||||
|
||||
if s.deleteObject(ctx, row.ObjectKey) {
|
||||
stats.ObjectsDeleted++
|
||||
}
|
||||
|
||||
if err := s.repo.DeletePending(ctx, row.ID); err != nil && !errors.Is(err, domain.ErrNotFound) {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
stats.RowsDeleted++
|
||||
}
|
||||
|
||||
referenced, err := s.referencedKeys(ctx)
|
||||
if err != nil {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
for _, prefix := range []string{objectPrefixAttachments, objectPrefixStaging} {
|
||||
objects, err := s.store.List(ctx, prefix)
|
||||
if err != nil {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
for _, object := range objects {
|
||||
if object.LastModified.IsZero() || !object.LastModified.Before(before) {
|
||||
continue
|
||||
}
|
||||
|
||||
if _, ok := referenced[object.Key]; ok {
|
||||
continue
|
||||
}
|
||||
|
||||
if s.deleteObject(ctx, object.Key) {
|
||||
stats.ObjectsDeleted++
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return stats, nil
|
||||
}
|
||||
|
||||
func (s *Sweeper) referencedKeys(ctx context.Context) (map[string]struct{}, error) {
|
||||
const pageSize = 1000
|
||||
|
||||
keys := make(map[string]struct{})
|
||||
|
||||
for offset := int32(0); ; offset += pageSize {
|
||||
rows, err := s.repo.ListKeys(ctx, pageSize, offset)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, row := range rows {
|
||||
keys[row.ObjectKey] = struct{}{}
|
||||
}
|
||||
|
||||
if len(rows) < pageSize {
|
||||
return keys, nil
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Sweeper) deleteObject(ctx context.Context, key string) bool {
|
||||
err := s.store.Delete(ctx, key)
|
||||
if err == nil {
|
||||
return true
|
||||
}
|
||||
|
||||
if !errors.Is(err, domain.ErrNotFound) {
|
||||
s.log.WarnContext(ctx, "sweep delete failed",
|
||||
slog.String("object_key", key),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,126 @@
|
||||
package attachment_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/service/attachment"
|
||||
"mtusi-messenger/internal/service/attachment/mocks"
|
||||
)
|
||||
|
||||
func TestSweepReconcilesPendingAndOrphanObjects(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
locker := mocks.NewMockLockStore(t)
|
||||
store := newFakeStore()
|
||||
|
||||
stale := time.Now().UTC().Add(-time.Hour)
|
||||
|
||||
presign := domain.Attachment{
|
||||
ID: uuid.New(), ObjectKey: "staging/presign/chat/" + uuid.NewString(),
|
||||
Status: domain.AttachmentPending, CreatedAt: stale,
|
||||
}
|
||||
proxyRecoverable := domain.Attachment{
|
||||
ID: uuid.New(), ObjectKey: "attachments/chat/" + uuid.NewString(),
|
||||
SizeBytes: 3, SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
Status: domain.AttachmentPending, CreatedAt: stale,
|
||||
}
|
||||
proxyMissing := domain.Attachment{
|
||||
ID: uuid.New(), ObjectKey: "attachments/chat/" + uuid.NewString(),
|
||||
Status: domain.AttachmentPending, CreatedAt: stale,
|
||||
}
|
||||
readyKey := "attachments/chat/ready"
|
||||
|
||||
store.objects[presign.ObjectKey] = storedObject{data: []byte("x"), lastModified: stale}
|
||||
store.objects[proxyRecoverable.ObjectKey] = storedObject{
|
||||
data: []byte("abc"),
|
||||
lastModified: stale,
|
||||
metadata: map[string]string{"sha256": proxyRecoverable.SHA256},
|
||||
}
|
||||
store.objects[readyKey] = storedObject{data: []byte("ready"), lastModified: stale}
|
||||
store.objects["attachments/chat/orphan"] = storedObject{data: []byte("orphan"), lastModified: stale}
|
||||
store.objects["staging/abandoned"] = storedObject{data: []byte("stale"), lastModified: stale}
|
||||
store.objects["staging/fresh"] = storedObject{data: []byte("fresh"), lastModified: time.Now().UTC()}
|
||||
|
||||
repo.EXPECT().ListStalePending(mock.Anything, mock.Anything, int32(100)).
|
||||
Return([]domain.Attachment{presign, proxyRecoverable, proxyMissing}, nil).Once()
|
||||
repo.EXPECT().DeletePending(mock.Anything, presign.ID).Return(nil).Once()
|
||||
repo.EXPECT().MarkReady(mock.Anything, proxyRecoverable.ID, proxyRecoverable.ObjectKey).
|
||||
Return(domain.Attachment{ID: proxyRecoverable.ID, Status: domain.AttachmentReady}, nil).Once()
|
||||
repo.EXPECT().DeletePending(mock.Anything, proxyMissing.ID).Return(nil).Once()
|
||||
repo.EXPECT().ListKeys(mock.Anything, int32(1000), int32(0)).
|
||||
Return([]domain.AttachmentKey{
|
||||
{ID: proxyRecoverable.ID, ObjectKey: proxyRecoverable.ObjectKey, Status: domain.AttachmentReady},
|
||||
{ID: uuid.New(), ObjectKey: readyKey, Status: domain.AttachmentReady},
|
||||
}, nil).Once()
|
||||
locker.EXPECT().AcquireSweepLock(mock.Anything).
|
||||
Return(func() {}, true, nil).Once()
|
||||
|
||||
sweeper := attachment.NewSweeper(repo, store, locker, time.Minute, time.Hour, slog.Default())
|
||||
|
||||
stats, err := sweeper.SweepOnce(t.Context())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, stats.Recovered)
|
||||
require.Equal(t, 2, stats.RowsDeleted)
|
||||
require.Equal(t, 3, stats.ObjectsDeleted)
|
||||
|
||||
require.NotContains(t, store.objects, presign.ObjectKey)
|
||||
require.NotContains(t, store.objects, "attachments/chat/orphan")
|
||||
require.NotContains(t, store.objects, "staging/abandoned")
|
||||
require.Contains(t, store.objects, proxyRecoverable.ObjectKey)
|
||||
require.Contains(t, store.objects, readyKey)
|
||||
require.Contains(t, store.objects, "staging/fresh")
|
||||
}
|
||||
|
||||
func TestSweepSkipsWhenAnotherReplicaHoldsTheLock(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
locker := mocks.NewMockLockStore(t)
|
||||
sweeper := attachment.NewSweeper(repo, newFakeStore(), locker, time.Minute, time.Hour, slog.Default())
|
||||
|
||||
locker.EXPECT().AcquireSweepLock(mock.Anything).Return(nil, false, nil).Once()
|
||||
|
||||
stats, err := sweeper.SweepOnce(t.Context())
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, stats)
|
||||
}
|
||||
|
||||
func TestSweepKeepsObjectWhenMarkReadyFails(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
locker := mocks.NewMockLockStore(t)
|
||||
store := newFakeStore()
|
||||
|
||||
stale := time.Now().UTC().Add(-time.Hour)
|
||||
row := domain.Attachment{
|
||||
ID: uuid.New(), ObjectKey: "attachments/chat/" + uuid.NewString(),
|
||||
SizeBytes: 3, SHA256: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
|
||||
Status: domain.AttachmentPending, CreatedAt: stale,
|
||||
}
|
||||
|
||||
store.objects[row.ObjectKey] = storedObject{
|
||||
data: []byte("abc"),
|
||||
lastModified: stale,
|
||||
metadata: map[string]string{"sha256": row.SHA256},
|
||||
}
|
||||
|
||||
repo.EXPECT().ListStalePending(mock.Anything, mock.Anything, int32(100)).
|
||||
Return([]domain.Attachment{row}, nil).Once()
|
||||
repo.EXPECT().MarkReady(mock.Anything, row.ID, row.ObjectKey).
|
||||
Return(domain.Attachment{}, context.DeadlineExceeded).Once()
|
||||
repo.EXPECT().ListKeys(mock.Anything, int32(1000), int32(0)).
|
||||
Return([]domain.AttachmentKey{{ID: row.ID, ObjectKey: row.ObjectKey, Status: domain.AttachmentPending}}, nil).Once()
|
||||
locker.EXPECT().AcquireSweepLock(mock.Anything).Return(func() {}, true, nil).Once()
|
||||
|
||||
sweeper := attachment.NewSweeper(repo, store, locker, time.Minute, time.Hour, slog.Default())
|
||||
|
||||
stats, err := sweeper.SweepOnce(t.Context())
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, stats.Recovered)
|
||||
require.Zero(t, stats.RowsDeleted)
|
||||
require.Contains(t, store.objects, row.ObjectKey)
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mtusi-messenger/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockRepository creates a new instance of MockRepository. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockRepository(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockRepository {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockRepository{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockRepository is an autogenerated mock type for the Repository type
|
||||
type MockRepository struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockRepository_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockRepository) EXPECT() *MockRepository_Expecter {
|
||||
return &MockRepository_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Create provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error) {
|
||||
ret := _mock.Called(ctx, draft)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Create")
|
||||
}
|
||||
|
||||
var r0 domain.Chat
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.ChatDraft) (domain.Chat, error)); ok {
|
||||
return returnFunc(ctx, draft)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.ChatDraft) domain.Chat); ok {
|
||||
r0 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Chat)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.ChatDraft) error); ok {
|
||||
r1 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'
|
||||
type MockRepository_Create_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Create is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - draft domain.ChatDraft
|
||||
func (_e *MockRepository_Expecter) Create(ctx any, draft any) *MockRepository_Create_Call {
|
||||
return &MockRepository_Create_Call{Call: _e.mock.On("Create", ctx, draft)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, draft domain.ChatDraft)) *MockRepository_Create_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.ChatDraft
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.ChatDraft)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Return(chat domain.Chat, err error) *MockRepository_Create_Call {
|
||||
_c.Call.Return(chat, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) RunAndReturn(run func(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error)) *MockRepository_Create_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// GetVisible provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) GetVisible(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID) (domain.Chat, error) {
|
||||
ret := _mock.Called(ctx, chatID, callerID)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for GetVisible")
|
||||
}
|
||||
|
||||
var r0 domain.Chat
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) (domain.Chat, error)); ok {
|
||||
return returnFunc(ctx, chatID, callerID)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) domain.Chat); ok {
|
||||
r0 = returnFunc(ctx, chatID, callerID)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Chat)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, chatID, callerID)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_GetVisible_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetVisible'
|
||||
type MockRepository_GetVisible_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// GetVisible is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - chatID uuid.UUID
|
||||
// - callerID uuid.UUID
|
||||
func (_e *MockRepository_Expecter) GetVisible(ctx any, chatID any, callerID any) *MockRepository_GetVisible_Call {
|
||||
return &MockRepository_GetVisible_Call{Call: _e.mock.On("GetVisible", ctx, chatID, callerID)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetVisible_Call) Run(run func(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID)) *MockRepository_GetVisible_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 uuid.UUID
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetVisible_Call) Return(chat domain.Chat, err error) *MockRepository_GetVisible_Call {
|
||||
_c.Call.Return(chat, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetVisible_Call) RunAndReturn(run func(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID) (domain.Chat, error)) *MockRepository_GetVisible_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// ListVisible provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) ListVisible(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) {
|
||||
ret := _mock.Called(ctx, callerID, after, limit)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListVisible")
|
||||
}
|
||||
|
||||
var r0 domain.Page[domain.Chat]
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error)); ok {
|
||||
return returnFunc(ctx, callerID, after, limit)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, *domain.Cursor, int) domain.Page[domain.Chat]); ok {
|
||||
r0 = returnFunc(ctx, callerID, after, limit)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Page[domain.Chat])
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, *domain.Cursor, int) error); ok {
|
||||
r1 = returnFunc(ctx, callerID, after, limit)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_ListVisible_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListVisible'
|
||||
type MockRepository_ListVisible_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListVisible is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - callerID uuid.UUID
|
||||
// - after *domain.Cursor
|
||||
// - limit int
|
||||
func (_e *MockRepository_Expecter) ListVisible(ctx any, callerID any, after any, limit any) *MockRepository_ListVisible_Call {
|
||||
return &MockRepository_ListVisible_Call{Call: _e.mock.On("ListVisible", ctx, callerID, after, limit)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListVisible_Call) Run(run func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int)) *MockRepository_ListVisible_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 *domain.Cursor
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(*domain.Cursor)
|
||||
}
|
||||
var arg3 int
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(int)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListVisible_Call) Return(page domain.Page[domain.Chat], err error) *MockRepository_ListVisible_Call {
|
||||
_c.Call.Return(page, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListVisible_Call) RunAndReturn(run func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error)) *MockRepository_ListVisible_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package chat
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error)
|
||||
GetVisible(ctx context.Context, chatID, callerID uuid.UUID) (domain.Chat, error)
|
||||
ListVisible(
|
||||
ctx context.Context,
|
||||
callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Chat], error)
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
chats Repository
|
||||
}
|
||||
|
||||
func NewService(chats Repository) *Service {
|
||||
return &Service{chats: chats}
|
||||
}
|
||||
|
||||
func (s *Service) Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error) {
|
||||
if err := draft.Validate(); err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
|
||||
created, err := s.chats.Create(ctx, draft)
|
||||
if err != nil {
|
||||
return domain.Chat{}, fmt.Errorf("create chat: %w", err)
|
||||
}
|
||||
|
||||
return created, nil
|
||||
}
|
||||
|
||||
func (s *Service) Get(ctx context.Context, callerID, chatID uuid.UUID) (domain.Chat, error) {
|
||||
found, err := s.chats.GetVisible(ctx, chatID, callerID)
|
||||
if err != nil {
|
||||
return domain.Chat{}, fmt.Errorf("get chat: %w", err)
|
||||
}
|
||||
|
||||
return found, nil
|
||||
}
|
||||
|
||||
func (s *Service) List(
|
||||
ctx context.Context,
|
||||
callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Chat], error) {
|
||||
if after != nil && !after.BelongsTo(callerID) {
|
||||
return domain.Page[domain.Chat]{}, fmt.Errorf("cursor is bound to another list: %w", domain.ErrInvalidCursor)
|
||||
}
|
||||
|
||||
page, err := s.chats.ListVisible(ctx, callerID, after, limit)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Chat]{}, fmt.Errorf("list chats: %w", err)
|
||||
}
|
||||
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
package chat_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/service/chat"
|
||||
"mtusi-messenger/internal/service/chat/mocks"
|
||||
)
|
||||
|
||||
var errRepository = errors.New("repository is unavailable")
|
||||
|
||||
type ServiceSuite struct {
|
||||
suite.Suite
|
||||
|
||||
chats *mocks.MockRepository
|
||||
service *chat.Service
|
||||
caller uuid.UUID
|
||||
now time.Time
|
||||
}
|
||||
|
||||
func TestServiceSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, new(ServiceSuite))
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) SetupTest() {
|
||||
s.chats = mocks.NewMockRepository(s.T())
|
||||
s.service = chat.NewService(s.chats)
|
||||
s.caller = uuid.New()
|
||||
s.now = time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) draft() domain.ChatDraft {
|
||||
return domain.ChatDraft{
|
||||
Title: "Проект по ВНП",
|
||||
MemberIDs: []uuid.UUID{s.caller},
|
||||
CallerID: s.caller,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestCreateReturnsStoredChat() {
|
||||
draft := s.draft()
|
||||
stored := domain.Chat{
|
||||
ID: uuid.New(),
|
||||
Title: draft.Title,
|
||||
MemberIDs: draft.MemberIDs,
|
||||
CreatedAt: s.now,
|
||||
}
|
||||
|
||||
s.chats.EXPECT().Create(s.T().Context(), draft).Return(stored, nil).Once()
|
||||
|
||||
got, err := s.service.Create(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(stored, got)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestCreateRejectsDraftWithoutCallerWithoutRepositoryCall() {
|
||||
draft := s.draft()
|
||||
draft.MemberIDs = []uuid.UUID{uuid.New()}
|
||||
|
||||
_, err := s.service.Create(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrValidation)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestCreateRejectsBlankTitleWithoutRepositoryCall() {
|
||||
draft := s.draft()
|
||||
draft.Title = " "
|
||||
|
||||
_, err := s.service.Create(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrValidation)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestCreatePropagatesUnknownMember() {
|
||||
draft := s.draft()
|
||||
|
||||
s.chats.EXPECT().Create(s.T().Context(), draft).Return(domain.Chat{}, domain.ErrUnknownMember).Once()
|
||||
|
||||
_, err := s.service.Create(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrUnknownMember,
|
||||
"целостность участников проверяет хранилище, сервис только пробрасывает исход")
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestGetPropagatesNotFoundForForeignChat() {
|
||||
chatID := uuid.New()
|
||||
|
||||
s.chats.EXPECT().GetVisible(s.T().Context(), chatID, s.caller).Return(domain.Chat{}, domain.ErrNotFound).Once()
|
||||
|
||||
_, err := s.service.Get(s.T().Context(), s.caller, chatID)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestListPassesNilCursorOnFirstPage() {
|
||||
stored := domain.Chat{ID: uuid.New(), Title: "Проект", MemberIDs: []uuid.UUID{s.caller}, CreatedAt: s.now}
|
||||
|
||||
s.chats.EXPECT().
|
||||
ListVisible(s.T().Context(), s.caller, (*domain.Cursor)(nil), domain.DefaultPageLimit).
|
||||
Return(domain.Page[domain.Chat]{Items: []domain.Chat{stored}}, nil).
|
||||
Once()
|
||||
|
||||
page, err := s.service.List(s.T().Context(), s.caller, nil, domain.DefaultPageLimit)
|
||||
s.Require().NoError(err)
|
||||
s.Equal([]domain.Chat{stored}, page.Items)
|
||||
s.Nil(page.Next, "на последней странице курсора нет")
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestListRejectsCursorFromAnotherCaller() {
|
||||
foreign := &domain.Cursor{Scope: uuid.New(), CreatedAt: s.now, ID: uuid.New()}
|
||||
|
||||
_, err := s.service.List(s.T().Context(), s.caller, foreign, domain.DefaultPageLimit)
|
||||
s.Require().ErrorIs(err, domain.ErrInvalidCursor,
|
||||
"курсор чужого списка не должен открывать чужие чаты")
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestListAcceptsOwnCursor() {
|
||||
own := &domain.Cursor{Scope: s.caller, CreatedAt: s.now, ID: uuid.New()}
|
||||
|
||||
s.chats.EXPECT().
|
||||
ListVisible(s.T().Context(), s.caller, own, 10).
|
||||
Return(domain.Page[domain.Chat]{}, nil).
|
||||
Once()
|
||||
|
||||
_, err := s.service.List(s.T().Context(), s.caller, own, 10)
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestListWrapsRepositoryFailure() {
|
||||
s.chats.EXPECT().
|
||||
ListVisible(s.T().Context(), s.caller, (*domain.Cursor)(nil), domain.DefaultPageLimit).
|
||||
Return(domain.Page[domain.Chat]{}, errRepository).
|
||||
Once()
|
||||
|
||||
_, err := s.service.List(s.T().Context(), s.caller, nil, domain.DefaultPageLimit)
|
||||
s.Require().ErrorIs(err, errRepository)
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mtusi-messenger/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockAttachmentChecker creates a new instance of MockAttachmentChecker. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockAttachmentChecker(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockAttachmentChecker {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockAttachmentChecker{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockAttachmentChecker is an autogenerated mock type for the AttachmentChecker type
|
||||
type MockAttachmentChecker struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockAttachmentChecker_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockAttachmentChecker) EXPECT() *MockAttachmentChecker_Expecter {
|
||||
return &MockAttachmentChecker_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// ListStates provides a mock function for the type MockAttachmentChecker
|
||||
func (_mock *MockAttachmentChecker) ListStates(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID) ([]domain.AttachmentState, error) {
|
||||
ret := _mock.Called(ctx, chatID, ids)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListStates")
|
||||
}
|
||||
|
||||
var r0 []domain.AttachmentState
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, []uuid.UUID) ([]domain.AttachmentState, error)); ok {
|
||||
return returnFunc(ctx, chatID, ids)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, []uuid.UUID) []domain.AttachmentState); ok {
|
||||
r0 = returnFunc(ctx, chatID, ids)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]domain.AttachmentState)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, []uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, chatID, ids)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockAttachmentChecker_ListStates_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListStates'
|
||||
type MockAttachmentChecker_ListStates_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListStates is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - chatID uuid.UUID
|
||||
// - ids []uuid.UUID
|
||||
func (_e *MockAttachmentChecker_Expecter) ListStates(ctx any, chatID any, ids any) *MockAttachmentChecker_ListStates_Call {
|
||||
return &MockAttachmentChecker_ListStates_Call{Call: _e.mock.On("ListStates", ctx, chatID, ids)}
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentChecker_ListStates_Call) Run(run func(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID)) *MockAttachmentChecker_ListStates_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 []uuid.UUID
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].([]uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentChecker_ListStates_Call) Return(attachmentStates []domain.AttachmentState, err error) *MockAttachmentChecker_ListStates_Call {
|
||||
_c.Call.Return(attachmentStates, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockAttachmentChecker_ListStates_Call) RunAndReturn(run func(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID) ([]domain.AttachmentState, error)) *MockAttachmentChecker_ListStates_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mtusi-messenger/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockRepository creates a new instance of MockRepository. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockRepository(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockRepository {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockRepository{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockRepository is an autogenerated mock type for the Repository type
|
||||
type MockRepository struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockRepository_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockRepository) EXPECT() *MockRepository_Expecter {
|
||||
return &MockRepository_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Create provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Create(ctx context.Context, draft domain.MessageDraft) (domain.Message, error) {
|
||||
ret := _mock.Called(ctx, draft)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Create")
|
||||
}
|
||||
|
||||
var r0 domain.Message
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.MessageDraft) (domain.Message, error)); ok {
|
||||
return returnFunc(ctx, draft)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.MessageDraft) domain.Message); ok {
|
||||
r0 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Message)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.MessageDraft) error); ok {
|
||||
r1 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'
|
||||
type MockRepository_Create_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Create is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - draft domain.MessageDraft
|
||||
func (_e *MockRepository_Expecter) Create(ctx any, draft any) *MockRepository_Create_Call {
|
||||
return &MockRepository_Create_Call{Call: _e.mock.On("Create", ctx, draft)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, draft domain.MessageDraft)) *MockRepository_Create_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.MessageDraft
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.MessageDraft)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Return(message domain.Message, err error) *MockRepository_Create_Call {
|
||||
_c.Call.Return(message, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) RunAndReturn(run func(ctx context.Context, draft domain.MessageDraft) (domain.Message, error)) *MockRepository_Create_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// IsChatMember provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) IsChatMember(ctx context.Context, chatID uuid.UUID, userID uuid.UUID) (bool, error) {
|
||||
ret := _mock.Called(ctx, chatID, userID)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for IsChatMember")
|
||||
}
|
||||
|
||||
var r0 bool
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) (bool, error)); ok {
|
||||
return returnFunc(ctx, chatID, userID)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) bool); ok {
|
||||
r0 = returnFunc(ctx, chatID, userID)
|
||||
} else {
|
||||
r0 = ret.Get(0).(bool)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, chatID, userID)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_IsChatMember_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'IsChatMember'
|
||||
type MockRepository_IsChatMember_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// IsChatMember is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - chatID uuid.UUID
|
||||
// - userID uuid.UUID
|
||||
func (_e *MockRepository_Expecter) IsChatMember(ctx any, chatID any, userID any) *MockRepository_IsChatMember_Call {
|
||||
return &MockRepository_IsChatMember_Call{Call: _e.mock.On("IsChatMember", ctx, chatID, userID)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_IsChatMember_Call) Run(run func(ctx context.Context, chatID uuid.UUID, userID uuid.UUID)) *MockRepository_IsChatMember_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 uuid.UUID
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_IsChatMember_Call) Return(b bool, err error) *MockRepository_IsChatMember_Call {
|
||||
_c.Call.Return(b, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_IsChatMember_Call) RunAndReturn(run func(ctx context.Context, chatID uuid.UUID, userID uuid.UUID) (bool, error)) *MockRepository_IsChatMember_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// ListVisible provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) ListVisible(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Message], error) {
|
||||
ret := _mock.Called(ctx, chatID, callerID, after, limit)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListVisible")
|
||||
}
|
||||
|
||||
var r0 domain.Page[domain.Message]
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Message], error)); ok {
|
||||
return returnFunc(ctx, chatID, callerID, after, limit)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID, *domain.Cursor, int) domain.Page[domain.Message]); ok {
|
||||
r0 = returnFunc(ctx, chatID, callerID, after, limit)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Page[domain.Message])
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID, *domain.Cursor, int) error); ok {
|
||||
r1 = returnFunc(ctx, chatID, callerID, after, limit)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_ListVisible_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListVisible'
|
||||
type MockRepository_ListVisible_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListVisible is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - chatID uuid.UUID
|
||||
// - callerID uuid.UUID
|
||||
// - after *domain.Cursor
|
||||
// - limit int
|
||||
func (_e *MockRepository_Expecter) ListVisible(ctx any, chatID any, callerID any, after any, limit any) *MockRepository_ListVisible_Call {
|
||||
return &MockRepository_ListVisible_Call{Call: _e.mock.On("ListVisible", ctx, chatID, callerID, after, limit)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListVisible_Call) Run(run func(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID, after *domain.Cursor, limit int)) *MockRepository_ListVisible_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 uuid.UUID
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(uuid.UUID)
|
||||
}
|
||||
var arg3 *domain.Cursor
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(*domain.Cursor)
|
||||
}
|
||||
var arg4 int
|
||||
if args[4] != nil {
|
||||
arg4 = args[4].(int)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
arg4,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListVisible_Call) Return(page domain.Page[domain.Message], err error) *MockRepository_ListVisible_Call {
|
||||
_c.Call.Return(page, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListVisible_Call) RunAndReturn(run func(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Message], error)) *MockRepository_ListVisible_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package message
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
IsChatMember(ctx context.Context, chatID, userID uuid.UUID) (bool, error)
|
||||
Create(ctx context.Context, draft domain.MessageDraft) (domain.Message, error)
|
||||
ListVisible(
|
||||
ctx context.Context,
|
||||
chatID, callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Message], error)
|
||||
}
|
||||
|
||||
// AttachmentChecker validates that requested attachments exist in the chat and
|
||||
// are ready. The contract returns 404 for unknown/foreign IDs and 409 for
|
||||
// attachments that cannot be linked.
|
||||
type AttachmentChecker interface {
|
||||
ListStates(ctx context.Context, chatID uuid.UUID, ids []uuid.UUID) ([]domain.AttachmentState, error)
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
messages Repository
|
||||
attachments AttachmentChecker
|
||||
}
|
||||
|
||||
func NewService(messages Repository, attachments AttachmentChecker) *Service {
|
||||
return &Service{messages: messages, attachments: attachments}
|
||||
}
|
||||
|
||||
func (s *Service) Send(ctx context.Context, draft domain.MessageDraft) (domain.Message, error) {
|
||||
if err := draft.Validate(); err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
|
||||
member, err := s.messages.IsChatMember(ctx, draft.ChatID, draft.SenderID)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("check chat membership: %w", err)
|
||||
}
|
||||
|
||||
if !member {
|
||||
return domain.Message{}, fmt.Errorf("%w: chat is not visible", domain.ErrNotFound)
|
||||
}
|
||||
|
||||
if len(draft.AttachmentIDs) > 0 {
|
||||
if s.attachments == nil {
|
||||
return domain.Message{}, fmt.Errorf("attachment checker is not configured: %w", domain.ErrUnavailable)
|
||||
}
|
||||
|
||||
states, err := s.attachments.ListStates(ctx, draft.ChatID, draft.AttachmentIDs)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("check attachments: %w", err)
|
||||
}
|
||||
|
||||
if len(states) != len(draft.AttachmentIDs) {
|
||||
return domain.Message{}, fmt.Errorf("%w: attachment is not visible", domain.ErrNotFound)
|
||||
}
|
||||
|
||||
for _, state := range states {
|
||||
if state.Status != domain.AttachmentReady {
|
||||
return domain.Message{}, fmt.Errorf(
|
||||
"%w: attachment %s is %s",
|
||||
domain.ErrConflict, state.ID, state.Status,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
sent, err := s.messages.Create(ctx, draft)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("create message: %w", err)
|
||||
}
|
||||
|
||||
return sent, nil
|
||||
}
|
||||
|
||||
func (s *Service) History(
|
||||
ctx context.Context,
|
||||
callerID, chatID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Message], error) {
|
||||
if after != nil && !after.BelongsTo(chatID) {
|
||||
return domain.Page[domain.Message]{}, fmt.Errorf("cursor is bound to another chat: %w", domain.ErrInvalidCursor)
|
||||
}
|
||||
|
||||
page, err := s.messages.ListVisible(ctx, chatID, callerID, after, limit)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, fmt.Errorf("list messages: %w", err)
|
||||
}
|
||||
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
package message_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/service/message"
|
||||
"mtusi-messenger/internal/service/message/mocks"
|
||||
)
|
||||
|
||||
var errRepository = errors.New("repository is unavailable")
|
||||
|
||||
type ServiceSuite struct {
|
||||
suite.Suite
|
||||
|
||||
messages *mocks.MockRepository
|
||||
attachments *mocks.MockAttachmentChecker
|
||||
service *message.Service
|
||||
caller uuid.UUID
|
||||
chatID uuid.UUID
|
||||
now time.Time
|
||||
}
|
||||
|
||||
func TestServiceSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, new(ServiceSuite))
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) SetupTest() {
|
||||
s.messages = mocks.NewMockRepository(s.T())
|
||||
s.attachments = mocks.NewMockAttachmentChecker(s.T())
|
||||
s.service = message.NewService(s.messages, s.attachments)
|
||||
s.caller = uuid.New()
|
||||
s.chatID = uuid.New()
|
||||
s.now = time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) draft() domain.MessageDraft {
|
||||
return domain.MessageDraft{
|
||||
ChatID: s.chatID,
|
||||
SenderID: s.caller,
|
||||
Text: "Привет, Боб!",
|
||||
Idempotency: domain.MessageIdempotency{Key: "service-suite-key"},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestSendReturnsStoredMessage() {
|
||||
draft := s.draft()
|
||||
stored := domain.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: draft.ChatID,
|
||||
SenderID: draft.SenderID,
|
||||
Text: draft.Text,
|
||||
CreatedAt: s.now,
|
||||
}
|
||||
|
||||
s.messages.EXPECT().IsChatMember(s.T().Context(), draft.ChatID, draft.SenderID).Return(true, nil).Once()
|
||||
s.messages.EXPECT().Create(s.T().Context(), draft).Return(stored, nil).Once()
|
||||
|
||||
got, err := s.service.Send(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(stored, got)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestSendRejectsWhitespaceTextWithoutRepositoryCall() {
|
||||
draft := s.draft()
|
||||
draft.Text = " \t\n "
|
||||
|
||||
_, err := s.service.Send(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrValidation,
|
||||
"пробельный текст не проходит схему контракта, но проходит minLength")
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestSendPropagatesNotFoundForOutsider() {
|
||||
draft := s.draft()
|
||||
|
||||
s.messages.EXPECT().IsChatMember(s.T().Context(), draft.ChatID, draft.SenderID).Return(false, nil).Once()
|
||||
|
||||
_, err := s.service.Send(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound,
|
||||
"посторонний не должен узнать о существовании чата")
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestHistoryPassesNilCursorOnFirstPage() {
|
||||
stored := domain.Message{
|
||||
ID: uuid.New(),
|
||||
ChatID: s.chatID,
|
||||
SenderID: s.caller,
|
||||
Text: "первое",
|
||||
CreatedAt: s.now,
|
||||
}
|
||||
|
||||
s.messages.EXPECT().
|
||||
ListVisible(s.T().Context(), s.chatID, s.caller, (*domain.Cursor)(nil), domain.DefaultPageLimit).
|
||||
Return(domain.Page[domain.Message]{Items: []domain.Message{stored}}, nil).
|
||||
Once()
|
||||
|
||||
page, err := s.service.History(s.T().Context(), s.caller, s.chatID, nil, domain.DefaultPageLimit)
|
||||
s.Require().NoError(err)
|
||||
s.Equal([]domain.Message{stored}, page.Items)
|
||||
s.Nil(page.Next)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestHistoryRejectsCursorFromAnotherChat() {
|
||||
foreign := &domain.Cursor{Scope: uuid.New(), CreatedAt: s.now, ID: uuid.New()}
|
||||
|
||||
_, err := s.service.History(s.T().Context(), s.caller, s.chatID, foreign, domain.DefaultPageLimit)
|
||||
s.Require().ErrorIs(err, domain.ErrInvalidCursor,
|
||||
"контракт требует 400 на курсор от другого чата")
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestHistoryAcceptsCursorOfSameChat() {
|
||||
own := &domain.Cursor{Scope: s.chatID, CreatedAt: s.now, ID: uuid.New()}
|
||||
|
||||
s.messages.EXPECT().
|
||||
ListVisible(s.T().Context(), s.chatID, s.caller, own, 7).
|
||||
Return(domain.Page[domain.Message]{}, nil).
|
||||
Once()
|
||||
|
||||
_, err := s.service.History(s.T().Context(), s.caller, s.chatID, own, 7)
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestHistoryPropagatesNotFoundForOutsider() {
|
||||
s.messages.EXPECT().
|
||||
ListVisible(s.T().Context(), s.chatID, s.caller, (*domain.Cursor)(nil), domain.DefaultPageLimit).
|
||||
Return(domain.Page[domain.Message]{}, domain.ErrNotFound).
|
||||
Once()
|
||||
|
||||
_, err := s.service.History(s.T().Context(), s.caller, s.chatID, nil, domain.DefaultPageLimit)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestHistoryWrapsRepositoryFailure() {
|
||||
s.messages.EXPECT().
|
||||
ListVisible(s.T().Context(), s.chatID, s.caller, (*domain.Cursor)(nil), domain.DefaultPageLimit).
|
||||
Return(domain.Page[domain.Message]{}, errRepository).
|
||||
Once()
|
||||
|
||||
_, err := s.service.History(s.T().Context(), s.caller, s.chatID, nil, domain.DefaultPageLimit)
|
||||
s.Require().ErrorIs(err, errRepository)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestSendAcceptsReadyAttachment() {
|
||||
attachmentID := uuid.New()
|
||||
draft := s.draft()
|
||||
draft.AttachmentIDs = []uuid.UUID{attachmentID}
|
||||
stored := domain.Message{
|
||||
ID: uuid.New(), ChatID: draft.ChatID, SenderID: draft.SenderID,
|
||||
AttachmentIDs: []uuid.UUID{attachmentID}, CreatedAt: s.now,
|
||||
}
|
||||
|
||||
s.messages.EXPECT().IsChatMember(s.T().Context(), draft.ChatID, draft.SenderID).Return(true, nil).Once()
|
||||
s.attachments.EXPECT().
|
||||
ListStates(s.T().Context(), draft.ChatID, []uuid.UUID{attachmentID}).
|
||||
Return([]domain.AttachmentState{{ID: attachmentID, Status: domain.AttachmentReady}}, nil).
|
||||
Once()
|
||||
s.messages.EXPECT().Create(s.T().Context(), draft).Return(stored, nil).Once()
|
||||
|
||||
got, err := s.service.Send(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
s.Equal([]uuid.UUID{attachmentID}, got.AttachmentIDs)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestSendAllowsAttachmentOnlyMessage() {
|
||||
attachmentID := uuid.New()
|
||||
draft := s.draft()
|
||||
draft.Text = ""
|
||||
draft.AttachmentIDs = []uuid.UUID{attachmentID}
|
||||
|
||||
s.messages.EXPECT().IsChatMember(s.T().Context(), draft.ChatID, draft.SenderID).Return(true, nil).Once()
|
||||
s.attachments.EXPECT().
|
||||
ListStates(s.T().Context(), draft.ChatID, []uuid.UUID{attachmentID}).
|
||||
Return([]domain.AttachmentState{{ID: attachmentID, Status: domain.AttachmentReady}}, nil).
|
||||
Once()
|
||||
s.messages.EXPECT().Create(s.T().Context(), draft).Return(domain.Message{AttachmentIDs: draft.AttachmentIDs}, nil).Once()
|
||||
|
||||
_, err := s.service.Send(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestSendRejectsForeignAttachment() {
|
||||
attachmentID := uuid.New()
|
||||
draft := s.draft()
|
||||
draft.AttachmentIDs = []uuid.UUID{attachmentID}
|
||||
|
||||
s.messages.EXPECT().IsChatMember(s.T().Context(), draft.ChatID, draft.SenderID).Return(true, nil).Once()
|
||||
s.attachments.EXPECT().
|
||||
ListStates(s.T().Context(), draft.ChatID, []uuid.UUID{attachmentID}).
|
||||
Return([]domain.AttachmentState{}, nil).
|
||||
Once()
|
||||
|
||||
_, err := s.service.Send(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestSendRejectsPendingAttachment() {
|
||||
attachmentID := uuid.New()
|
||||
draft := s.draft()
|
||||
draft.AttachmentIDs = []uuid.UUID{attachmentID}
|
||||
|
||||
s.messages.EXPECT().IsChatMember(s.T().Context(), draft.ChatID, draft.SenderID).Return(true, nil).Once()
|
||||
s.attachments.EXPECT().
|
||||
ListStates(s.T().Context(), draft.ChatID, []uuid.UUID{attachmentID}).
|
||||
Return([]domain.AttachmentState{{ID: attachmentID, Status: domain.AttachmentPending}}, nil).
|
||||
Once()
|
||||
|
||||
_, err := s.service.Send(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrConflict)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestSendRejectsDuplicateAttachments() {
|
||||
id := uuid.New()
|
||||
draft := s.draft()
|
||||
draft.AttachmentIDs = []uuid.UUID{id, id}
|
||||
|
||||
_, err := s.service.Send(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrValidation)
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mtusi-messenger/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockRepository creates a new instance of MockRepository. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockRepository(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockRepository {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockRepository{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockRepository is an autogenerated mock type for the Repository type
|
||||
type MockRepository struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockRepository_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockRepository) EXPECT() *MockRepository_Expecter {
|
||||
return &MockRepository_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Create provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Create(ctx context.Context, session domain.NewSession) (domain.Session, error) {
|
||||
ret := _mock.Called(ctx, session)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Create")
|
||||
}
|
||||
|
||||
var r0 domain.Session
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewSession) (domain.Session, error)); ok {
|
||||
return returnFunc(ctx, session)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewSession) domain.Session); ok {
|
||||
r0 = returnFunc(ctx, session)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Session)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.NewSession) error); ok {
|
||||
r1 = returnFunc(ctx, session)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'
|
||||
type MockRepository_Create_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Create is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - session domain.NewSession
|
||||
func (_e *MockRepository_Expecter) Create(ctx any, session any) *MockRepository_Create_Call {
|
||||
return &MockRepository_Create_Call{Call: _e.mock.On("Create", ctx, session)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, session domain.NewSession)) *MockRepository_Create_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.NewSession
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.NewSession)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Return(session1 domain.Session, err error) *MockRepository_Create_Call {
|
||||
_c.Call.Return(session1, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) RunAndReturn(run func(ctx context.Context, session domain.NewSession) (domain.Session, error)) *MockRepository_Create_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Credentials provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Credentials(ctx context.Context, username string) (domain.UserCredentials, error) {
|
||||
ret := _mock.Called(ctx, username)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Credentials")
|
||||
}
|
||||
|
||||
var r0 domain.UserCredentials
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) (domain.UserCredentials, error)); ok {
|
||||
return returnFunc(ctx, username)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string) domain.UserCredentials); ok {
|
||||
r0 = returnFunc(ctx, username)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.UserCredentials)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, string) error); ok {
|
||||
r1 = returnFunc(ctx, username)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_Credentials_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Credentials'
|
||||
type MockRepository_Credentials_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Credentials is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - username string
|
||||
func (_e *MockRepository_Expecter) Credentials(ctx any, username any) *MockRepository_Credentials_Call {
|
||||
return &MockRepository_Credentials_Call{Call: _e.mock.On("Credentials", ctx, username)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Credentials_Call) Run(run func(ctx context.Context, username string)) *MockRepository_Credentials_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 string
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Credentials_Call) Return(userCredentials domain.UserCredentials, err error) *MockRepository_Credentials_Call {
|
||||
_c.Call.Return(userCredentials, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Credentials_Call) RunAndReturn(run func(ctx context.Context, username string) (domain.UserCredentials, error)) *MockRepository_Credentials_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Resolve provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Resolve(ctx context.Context, tokenHash []byte) (domain.Session, error) {
|
||||
ret := _mock.Called(ctx, tokenHash)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Resolve")
|
||||
}
|
||||
|
||||
var r0 domain.Session
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, []byte) (domain.Session, error)); ok {
|
||||
return returnFunc(ctx, tokenHash)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, []byte) domain.Session); ok {
|
||||
r0 = returnFunc(ctx, tokenHash)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Session)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, []byte) error); ok {
|
||||
r1 = returnFunc(ctx, tokenHash)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_Resolve_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Resolve'
|
||||
type MockRepository_Resolve_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Resolve is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - tokenHash []byte
|
||||
func (_e *MockRepository_Expecter) Resolve(ctx any, tokenHash any) *MockRepository_Resolve_Call {
|
||||
return &MockRepository_Resolve_Call{Call: _e.mock.On("Resolve", ctx, tokenHash)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Resolve_Call) Run(run func(ctx context.Context, tokenHash []byte)) *MockRepository_Resolve_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 []byte
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].([]byte)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Resolve_Call) Return(session domain.Session, err error) *MockRepository_Resolve_Call {
|
||||
_c.Call.Return(session, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Resolve_Call) RunAndReturn(run func(ctx context.Context, tokenHash []byte) (domain.Session, error)) *MockRepository_Resolve_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Revoke provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error {
|
||||
ret := _mock.Called(ctx, userID, tokenHash)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Revoke")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, []byte) error); ok {
|
||||
r0 = returnFunc(ctx, userID, tokenHash)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockRepository_Revoke_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Revoke'
|
||||
type MockRepository_Revoke_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Revoke is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - userID uuid.UUID
|
||||
// - tokenHash []byte
|
||||
func (_e *MockRepository_Expecter) Revoke(ctx any, userID any, tokenHash any) *MockRepository_Revoke_Call {
|
||||
return &MockRepository_Revoke_Call{Call: _e.mock.On("Revoke", ctx, userID, tokenHash)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Revoke_Call) Run(run func(ctx context.Context, userID uuid.UUID, tokenHash []byte)) *MockRepository_Revoke_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 []byte
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].([]byte)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Revoke_Call) Return(err error) *MockRepository_Revoke_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Revoke_Call) RunAndReturn(run func(ctx context.Context, userID uuid.UUID, tokenHash []byte) error) *MockRepository_Revoke_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockTokens creates a new instance of MockTokens. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockTokens(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockTokens {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockTokens{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockTokens is an autogenerated mock type for the Tokens type
|
||||
type MockTokens struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockTokens_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockTokens) EXPECT() *MockTokens_Expecter {
|
||||
return &MockTokens_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Generate provides a mock function for the type MockTokens
|
||||
func (_mock *MockTokens) Generate() (string, []byte, error) {
|
||||
ret := _mock.Called()
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Generate")
|
||||
}
|
||||
|
||||
var r0 string
|
||||
var r1 []byte
|
||||
var r2 error
|
||||
if returnFunc, ok := ret.Get(0).(func() (string, []byte, error)); ok {
|
||||
return returnFunc()
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func() string); ok {
|
||||
r0 = returnFunc()
|
||||
} else {
|
||||
r0 = ret.Get(0).(string)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func() []byte); ok {
|
||||
r1 = returnFunc()
|
||||
} else {
|
||||
if ret.Get(1) != nil {
|
||||
r1 = ret.Get(1).([]byte)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(2).(func() error); ok {
|
||||
r2 = returnFunc()
|
||||
} else {
|
||||
r2 = ret.Error(2)
|
||||
}
|
||||
return r0, r1, r2
|
||||
}
|
||||
|
||||
// MockTokens_Generate_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Generate'
|
||||
type MockTokens_Generate_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Generate is a helper method to define mock.On call
|
||||
func (_e *MockTokens_Expecter) Generate() *MockTokens_Generate_Call {
|
||||
return &MockTokens_Generate_Call{Call: _e.mock.On("Generate")}
|
||||
}
|
||||
|
||||
func (_c *MockTokens_Generate_Call) Run(run func()) *MockTokens_Generate_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
run()
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockTokens_Generate_Call) Return(s string, bytes []byte, err error) *MockTokens_Generate_Call {
|
||||
_c.Call.Return(s, bytes, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockTokens_Generate_Call) RunAndReturn(run func() (string, []byte, error)) *MockTokens_Generate_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// Hash provides a mock function for the type MockTokens
|
||||
func (_mock *MockTokens) Hash(raw string) ([]byte, error) {
|
||||
ret := _mock.Called(raw)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Hash")
|
||||
}
|
||||
|
||||
var r0 []byte
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(string) ([]byte, error)); ok {
|
||||
return returnFunc(raw)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(string) []byte); ok {
|
||||
r0 = returnFunc(raw)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]byte)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(string) error); ok {
|
||||
r1 = returnFunc(raw)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockTokens_Hash_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Hash'
|
||||
type MockTokens_Hash_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Hash is a helper method to define mock.On call
|
||||
// - raw string
|
||||
func (_e *MockTokens_Expecter) Hash(raw any) *MockTokens_Hash_Call {
|
||||
return &MockTokens_Hash_Call{Call: _e.mock.On("Hash", raw)}
|
||||
}
|
||||
|
||||
func (_c *MockTokens_Hash_Call) Run(run func(raw string)) *MockTokens_Hash_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 string
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockTokens_Hash_Call) Return(bytes []byte, err error) *MockTokens_Hash_Call {
|
||||
_c.Call.Return(bytes, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockTokens_Hash_Call) RunAndReturn(run func(raw string) ([]byte, error)) *MockTokens_Hash_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
Credentials(ctx context.Context, username string) (domain.UserCredentials, error)
|
||||
Create(ctx context.Context, session domain.NewSession) (domain.Session, error)
|
||||
Resolve(ctx context.Context, tokenHash []byte) (domain.Session, error)
|
||||
Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error
|
||||
}
|
||||
|
||||
type Tokens interface {
|
||||
Generate() (string, []byte, error)
|
||||
Hash(raw string) ([]byte, error)
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
sessions Repository
|
||||
tokens Tokens
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
func NewService(sessions Repository, tokens Tokens, ttl time.Duration) *Service {
|
||||
return &Service{sessions: sessions, tokens: tokens, ttl: ttl}
|
||||
}
|
||||
|
||||
func (s *Service) Authenticate(ctx context.Context, username, plain string) (domain.User, error) {
|
||||
credentials, err := s.sessions.Credentials(ctx, username)
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("authenticate: %w", err)
|
||||
}
|
||||
|
||||
if !password.Verify(plain, credentials.PasswordHash) {
|
||||
return domain.User{}, fmt.Errorf("authenticate: %w", domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
return credentials.User, nil
|
||||
}
|
||||
|
||||
func (s *Service) Resolve(ctx context.Context, raw string) (domain.User, error) {
|
||||
hash, err := s.tokens.Hash(raw)
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("resolve session: %w", domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
session, err := s.sessions.Resolve(ctx, hash)
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("resolve session: %w", err)
|
||||
}
|
||||
|
||||
return session.User, nil
|
||||
}
|
||||
|
||||
func (s *Service) Create(ctx context.Context, user domain.User) (domain.Session, error) {
|
||||
raw, hash, err := s.tokens.Generate()
|
||||
if err != nil {
|
||||
return domain.Session{}, fmt.Errorf("generate token: %w", err)
|
||||
}
|
||||
|
||||
session, err := s.sessions.Create(ctx, domain.NewSession{
|
||||
TokenHash: hash,
|
||||
UserID: user.ID,
|
||||
ExpiresAt: time.Now().UTC().Add(s.ttl),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Session{}, fmt.Errorf("create session: %w", err)
|
||||
}
|
||||
|
||||
session.Token = raw
|
||||
session.User = user
|
||||
|
||||
return session, nil
|
||||
}
|
||||
|
||||
func (s *Service) Revoke(ctx context.Context, userID uuid.UUID, raw string) error {
|
||||
hash, err := s.tokens.Hash(raw)
|
||||
if err != nil {
|
||||
return fmt.Errorf("revoke session: %w", domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
if err := s.sessions.Revoke(ctx, userID, hash); err != nil {
|
||||
return fmt.Errorf("revoke session: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package session_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
"mtusi-messenger/internal/service/session"
|
||||
"mtusi-messenger/internal/service/session/mocks"
|
||||
)
|
||||
|
||||
type ServiceSuite struct {
|
||||
suite.Suite
|
||||
|
||||
sessions *mocks.MockRepository
|
||||
tokens *mocks.MockTokens
|
||||
service *session.Service
|
||||
ttl time.Duration
|
||||
user domain.User
|
||||
}
|
||||
|
||||
func TestServiceSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, new(ServiceSuite))
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) SetupTest() {
|
||||
s.sessions = mocks.NewMockRepository(s.T())
|
||||
s.tokens = mocks.NewMockTokens(s.T())
|
||||
s.ttl = time.Hour
|
||||
s.service = session.NewService(s.sessions, s.tokens, s.ttl)
|
||||
s.user = domain.User{
|
||||
ID: uuid.New(),
|
||||
Username: "alice",
|
||||
DisplayName: "Алиса",
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestResolveHashesTokenBeforeStorage() {
|
||||
hash := []byte("hashed-token")
|
||||
stored := domain.Session{ExpiresAt: time.Now().Add(time.Hour), User: s.user}
|
||||
|
||||
s.tokens.EXPECT().Hash("raw-token").Return(hash, nil).Once()
|
||||
s.sessions.EXPECT().Resolve(mock.Anything, hash).Return(stored, nil).Once()
|
||||
|
||||
got, err := s.service.Resolve(s.T().Context(), "raw-token")
|
||||
s.Require().NoError(err)
|
||||
s.Equal(s.user, got)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestResolveRejectsMalformedTokenWithoutStorage() {
|
||||
s.tokens.EXPECT().Hash("garbage").Return(nil, errors.New("invalid token")).Once()
|
||||
|
||||
_, err := s.service.Resolve(s.T().Context(), "garbage")
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestCreateGeneratesTokenAndReturnsIt() {
|
||||
hash := []byte("hashed-token")
|
||||
expiresAt := time.Now().Add(s.ttl)
|
||||
|
||||
s.tokens.EXPECT().Generate().Return("raw-token", hash, nil).Once()
|
||||
s.sessions.EXPECT().
|
||||
Create(mock.Anything, mock.MatchedBy(func(candidate domain.NewSession) bool {
|
||||
return bytes.Equal(candidate.TokenHash, hash) &&
|
||||
candidate.UserID == s.user.ID &&
|
||||
candidate.ExpiresAt.After(time.Now())
|
||||
})).
|
||||
Return(domain.Session{ExpiresAt: expiresAt}, nil).
|
||||
Once()
|
||||
|
||||
got, err := s.service.Create(s.T().Context(), s.user)
|
||||
s.Require().NoError(err)
|
||||
s.Equal("raw-token", got.Token)
|
||||
s.Equal(s.user, got.User)
|
||||
s.Equal(expiresAt, got.ExpiresAt)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestCreatePropagatesTokenGenerationError() {
|
||||
s.tokens.EXPECT().Generate().Return("", nil, errors.New("no entropy")).Once()
|
||||
|
||||
_, err := s.service.Create(s.T().Context(), s.user)
|
||||
s.Require().Error(err)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestRevokeHashesTokenBeforeStorage() {
|
||||
hash := []byte("hashed-token")
|
||||
userID := uuid.New()
|
||||
|
||||
s.tokens.EXPECT().Hash("raw-token").Return(hash, nil).Once()
|
||||
s.sessions.EXPECT().Revoke(mock.Anything, userID, hash).Return(nil).Once()
|
||||
|
||||
s.Require().NoError(s.service.Revoke(s.T().Context(), userID, "raw-token"))
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestRevokeRejectsMalformedToken() {
|
||||
s.tokens.EXPECT().Hash("garbage").Return(nil, errors.New("invalid token")).Once()
|
||||
|
||||
err := s.service.Revoke(s.T().Context(), uuid.New(), "garbage")
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestAuthenticateVerifiesPassword() {
|
||||
hash, err := password.Hash("secret-password-123")
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.sessions.EXPECT().
|
||||
Credentials(mock.Anything, "alice").
|
||||
Return(domain.UserCredentials{User: s.user, PasswordHash: hash}, nil).
|
||||
Once()
|
||||
|
||||
got, err := s.service.Authenticate(s.T().Context(), "alice", "secret-password-123")
|
||||
s.Require().NoError(err)
|
||||
s.Equal(s.user, got)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestAuthenticateRejectsWrongPassword() {
|
||||
hash, err := password.Hash("secret-password-123")
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.sessions.EXPECT().
|
||||
Credentials(mock.Anything, "alice").
|
||||
Return(domain.UserCredentials{User: s.user, PasswordHash: hash}, nil).
|
||||
Once()
|
||||
|
||||
_, err = s.service.Authenticate(s.T().Context(), "alice", "wrong-password-value")
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestAuthenticatePropagatesUnknownUser() {
|
||||
s.sessions.EXPECT().
|
||||
Credentials(mock.Anything, "nobody").
|
||||
Return(domain.UserCredentials{}, domain.ErrUnauthenticated).
|
||||
Once()
|
||||
|
||||
_, err := s.service.Authenticate(s.T().Context(), "nobody", "secret-password-123")
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
}
|
||||
@@ -0,0 +1,181 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mtusi-messenger/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockRepository creates a new instance of MockRepository. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockRepository(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockRepository {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockRepository{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockRepository is an autogenerated mock type for the Repository type
|
||||
type MockRepository struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockRepository_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockRepository) EXPECT() *MockRepository_Expecter {
|
||||
return &MockRepository_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Create provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Create(ctx context.Context, draft domain.NewUser) (domain.User, error) {
|
||||
ret := _mock.Called(ctx, draft)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Create")
|
||||
}
|
||||
|
||||
var r0 domain.User
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewUser) (domain.User, error)); ok {
|
||||
return returnFunc(ctx, draft)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.NewUser) domain.User); ok {
|
||||
r0 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.User)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.NewUser) error); ok {
|
||||
r1 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'
|
||||
type MockRepository_Create_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Create is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - draft domain.NewUser
|
||||
func (_e *MockRepository_Expecter) Create(ctx any, draft any) *MockRepository_Create_Call {
|
||||
return &MockRepository_Create_Call{Call: _e.mock.On("Create", ctx, draft)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Run(run func(ctx context.Context, draft domain.NewUser)) *MockRepository_Create_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.NewUser
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.NewUser)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) Return(user domain.User, err error) *MockRepository_Create_Call {
|
||||
_c.Call.Return(user, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Create_Call) RunAndReturn(run func(ctx context.Context, draft domain.NewUser) (domain.User, error)) *MockRepository_Create_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// GetByID provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) GetByID(ctx context.Context, id uuid.UUID) (domain.User, error) {
|
||||
ret := _mock.Called(ctx, id)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for GetByID")
|
||||
}
|
||||
|
||||
var r0 domain.User
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) (domain.User, error)); ok {
|
||||
return returnFunc(ctx, id)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) domain.User); ok {
|
||||
r0 = returnFunc(ctx, id)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.User)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, id)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_GetByID_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetByID'
|
||||
type MockRepository_GetByID_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// GetByID is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - id uuid.UUID
|
||||
func (_e *MockRepository_Expecter) GetByID(ctx any, id any) *MockRepository_GetByID_Call {
|
||||
return &MockRepository_GetByID_Call{Call: _e.mock.On("GetByID", ctx, id)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetByID_Call) Run(run func(ctx context.Context, id uuid.UUID)) *MockRepository_GetByID_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetByID_Call) Return(user domain.User, err error) *MockRepository_GetByID_Call {
|
||||
_c.Call.Return(user, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetByID_Call) RunAndReturn(run func(ctx context.Context, id uuid.UUID) (domain.User, error)) *MockRepository_GetByID_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
Create(ctx context.Context, draft domain.NewUser) (domain.User, error)
|
||||
GetByID(ctx context.Context, id uuid.UUID) (domain.User, error)
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
users Repository
|
||||
}
|
||||
|
||||
func NewService(users Repository) *Service {
|
||||
return &Service{users: users}
|
||||
}
|
||||
|
||||
func (s *Service) Register(ctx context.Context, draft domain.UserDraft) (domain.User, error) {
|
||||
if err := draft.Validate(); err != nil {
|
||||
return domain.User{}, err
|
||||
}
|
||||
|
||||
hash, err := password.Hash(draft.Password)
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("hash password: %w", err)
|
||||
}
|
||||
|
||||
user, err := s.users.Create(ctx, domain.NewUser{
|
||||
Username: draft.Username,
|
||||
DisplayName: draft.DisplayName,
|
||||
PasswordHash: hash,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("create user: %w", err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *Service) GetByID(ctx context.Context, id uuid.UUID) (domain.User, error) {
|
||||
user, err := s.users.GetByID(ctx, id)
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("get user: %w", err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package user_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/service/user"
|
||||
"mtusi-messenger/internal/service/user/mocks"
|
||||
)
|
||||
|
||||
var errRepository = errors.New("repository is unavailable")
|
||||
|
||||
type ServiceSuite struct {
|
||||
suite.Suite
|
||||
|
||||
users *mocks.MockRepository
|
||||
service *user.Service
|
||||
now time.Time
|
||||
}
|
||||
|
||||
func TestServiceSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, new(ServiceSuite))
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) SetupTest() {
|
||||
s.users = mocks.NewMockRepository(s.T())
|
||||
s.service = user.NewService(s.users)
|
||||
s.now = time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestRegisterHashesPasswordAndReturnsStoredUser() {
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "very-secret-password"}
|
||||
stored := domain.User{
|
||||
ID: uuid.New(),
|
||||
Username: draft.Username,
|
||||
DisplayName: draft.DisplayName,
|
||||
CreatedAt: s.now,
|
||||
}
|
||||
|
||||
s.users.EXPECT().
|
||||
Create(s.T().Context(), mock.MatchedBy(func(candidate domain.NewUser) bool {
|
||||
return candidate.Username == draft.Username &&
|
||||
candidate.DisplayName == draft.DisplayName &&
|
||||
candidate.PasswordHash != "" &&
|
||||
candidate.PasswordHash != draft.Password
|
||||
})).
|
||||
Return(stored, nil).
|
||||
Once()
|
||||
|
||||
got, err := s.service.Register(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(stored, got, "сервис отдаёт то, что присвоило хранилище")
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestRegisterRejectsBlankDisplayNameWithoutRepositoryCall() {
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: " ", Password: "very-secret-password"}
|
||||
|
||||
_, err := s.service.Register(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrValidation)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestRegisterRejectsShortPasswordWithoutRepositoryCall() {
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "too-short"}
|
||||
|
||||
_, err := s.service.Register(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrValidation)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestRegisterPropagatesUsernameConflict() {
|
||||
draft := domain.UserDraft{Username: "alice", DisplayName: "Алиса", Password: "very-secret-password"}
|
||||
|
||||
s.users.EXPECT().
|
||||
Create(s.T().Context(), mock.Anything).
|
||||
Return(domain.User{}, domain.ErrUsernameTaken).
|
||||
Once()
|
||||
|
||||
_, err := s.service.Register(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrUsernameTaken)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestGetByIDPropagatesNotFound() {
|
||||
id := uuid.New()
|
||||
|
||||
s.users.EXPECT().GetByID(s.T().Context(), id).Return(domain.User{}, domain.ErrNotFound).Once()
|
||||
|
||||
_, err := s.service.GetByID(s.T().Context(), id)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestGetByIDWrapsRepositoryFailure() {
|
||||
id := uuid.New()
|
||||
|
||||
s.users.EXPECT().GetByID(s.T().Context(), id).Return(domain.User{}, errRepository).Once()
|
||||
|
||||
_, err := s.service.GetByID(s.T().Context(), id)
|
||||
s.Require().ErrorIs(err, errRepository)
|
||||
}
|
||||
@@ -0,0 +1,215 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
|
||||
)
|
||||
|
||||
type AttachmentRepository struct {
|
||||
store *Store
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) IsChatMember(ctx context.Context, chatID, userID uuid.UUID) (bool, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
member, err := r.store.queries.IsChatMember(ctx, sqlcgen.IsChatMemberParams{
|
||||
ChatID: chatID,
|
||||
UserID: userID,
|
||||
})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("check chat membership: %w", mapError(err))
|
||||
}
|
||||
|
||||
return member, nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) Create(ctx context.Context, draft domain.AttachmentDraft) (domain.Attachment, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
row, err := r.store.queries.CreateAttachment(ctx, sqlcgen.CreateAttachmentParams{
|
||||
ID: draft.ID,
|
||||
ChatID: draft.ChatID,
|
||||
OwnerID: draft.OwnerID,
|
||||
ObjectKey: draft.ObjectKey,
|
||||
Filename: draft.Filename,
|
||||
ContentType: draft.ContentType,
|
||||
SizeBytes: draft.SizeBytes,
|
||||
Sha256: draft.SHA256,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("create attachment: %w", mapError(err))
|
||||
}
|
||||
|
||||
return mapAttachment(row), nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) MarkReady(
|
||||
ctx context.Context,
|
||||
id uuid.UUID,
|
||||
objectKey string,
|
||||
) (domain.Attachment, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
row, err := r.store.queries.MarkAttachmentReady(ctx, sqlcgen.MarkAttachmentReadyParams{
|
||||
ID: id,
|
||||
ObjectKey: objectKey,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("mark attachment ready: %w", mapError(err))
|
||||
}
|
||||
|
||||
return mapAttachment(row), nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) DeletePending(ctx context.Context, id uuid.UUID) error {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
if err := r.store.queries.DeletePendingAttachment(ctx, id); err != nil {
|
||||
return fmt.Errorf("delete pending attachment: %w", mapError(err))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) GetForMember(
|
||||
ctx context.Context,
|
||||
userID, id uuid.UUID,
|
||||
) (domain.Attachment, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
row, err := r.store.queries.GetAttachmentForMember(ctx, sqlcgen.GetAttachmentForMemberParams{
|
||||
ID: id,
|
||||
UserID: userID,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("get attachment for member: %w", mapError(err))
|
||||
}
|
||||
|
||||
return mapAttachment(row), nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) GetForOwner(
|
||||
ctx context.Context,
|
||||
ownerID, id uuid.UUID,
|
||||
) (domain.Attachment, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
row, err := r.store.queries.GetAttachmentForOwner(ctx, sqlcgen.GetAttachmentForOwnerParams{
|
||||
ID: id,
|
||||
OwnerID: ownerID,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("get attachment for owner: %w", mapError(err))
|
||||
}
|
||||
|
||||
return mapAttachment(row), nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) ListStates(
|
||||
ctx context.Context,
|
||||
chatID uuid.UUID,
|
||||
ids []uuid.UUID,
|
||||
) ([]domain.AttachmentState, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := r.store.queries.ListAttachmentStatesForChat(ctx, sqlcgen.ListAttachmentStatesForChatParams{
|
||||
ChatID: chatID,
|
||||
Ids: ids,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list attachment states: %w", mapError(err))
|
||||
}
|
||||
|
||||
states := make([]domain.AttachmentState, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
states = append(states, domain.AttachmentState{
|
||||
ID: row.ID,
|
||||
Status: domain.AttachmentStatus(row.Status),
|
||||
})
|
||||
}
|
||||
|
||||
return states, nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) ListStalePending(
|
||||
ctx context.Context,
|
||||
createdBefore time.Time,
|
||||
limit int32,
|
||||
) ([]domain.Attachment, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := r.store.queries.ListStalePendingAttachments(ctx, sqlcgen.ListStalePendingAttachmentsParams{
|
||||
CreatedBefore: createdBefore,
|
||||
RowLimit: limit,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list stale attachments: %w", mapError(err))
|
||||
}
|
||||
|
||||
return mapAll(rows, mapAttachment), nil
|
||||
}
|
||||
|
||||
func (r *AttachmentRepository) ListKeys(
|
||||
ctx context.Context,
|
||||
limit, offset int32,
|
||||
) ([]domain.AttachmentKey, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
rows, err := r.store.queries.ListAttachmentKeys(ctx, sqlcgen.ListAttachmentKeysParams{
|
||||
RowLimit: limit,
|
||||
RowOffset: offset,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list attachment keys: %w", mapError(err))
|
||||
}
|
||||
|
||||
keys := make([]domain.AttachmentKey, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
keys = append(keys, domain.AttachmentKey{
|
||||
ID: row.ID,
|
||||
ObjectKey: row.ObjectKey,
|
||||
Status: domain.AttachmentStatus(row.Status),
|
||||
CreatedAt: toUTCTime(row.CreatedAt),
|
||||
})
|
||||
}
|
||||
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
func mapAttachment(row sqlcgen.Attachment) domain.Attachment {
|
||||
attachment := domain.Attachment{
|
||||
ID: row.ID,
|
||||
ChatID: row.ChatID,
|
||||
OwnerID: row.OwnerID,
|
||||
ObjectKey: row.ObjectKey,
|
||||
Filename: row.Filename,
|
||||
ContentType: row.ContentType,
|
||||
SizeBytes: row.SizeBytes,
|
||||
SHA256: row.Sha256,
|
||||
Status: domain.AttachmentStatus(row.Status),
|
||||
CreatedAt: toUTCTime(row.CreatedAt),
|
||||
UpdatedAt: toUTCTime(row.UpdatedAt),
|
||||
}
|
||||
|
||||
if row.ErrorCode.Valid {
|
||||
code := row.ErrorCode.String
|
||||
attachment.ErrorCode = &code
|
||||
}
|
||||
|
||||
return attachment
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
type AttachmentRepositorySuite struct {
|
||||
BaseSuite
|
||||
}
|
||||
|
||||
func TestAttachmentRepositorySuite(t *testing.T) {
|
||||
suite.Run(t, new(AttachmentRepositorySuite))
|
||||
}
|
||||
|
||||
func (s *AttachmentRepositorySuite) TestLifecycleAndMessageLinks() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
eve := s.createUser("eve")
|
||||
chat := s.createChat(alice, bob)
|
||||
|
||||
id, err := uuid.NewV7()
|
||||
s.Require().NoError(err)
|
||||
|
||||
objectKey := "attachments/" + chat.ID.String() + "/" + id.String()
|
||||
digest := strings.Repeat("a", 64)
|
||||
|
||||
created, err := s.store.Attachments().Create(s.T().Context(), domain.AttachmentDraft{
|
||||
ID: id,
|
||||
ChatID: chat.ID,
|
||||
OwnerID: alice.ID,
|
||||
ObjectKey: objectKey,
|
||||
Filename: "photo.png",
|
||||
ContentType: "image/png",
|
||||
SizeBytes: 123,
|
||||
SHA256: digest,
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.AttachmentPending, created.Status)
|
||||
|
||||
visible, err := s.store.Attachments().GetForMember(s.T().Context(), bob.ID, id)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(alice.ID, visible.OwnerID)
|
||||
|
||||
_, err = s.store.Attachments().GetForMember(s.T().Context(), eve.ID, id)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
|
||||
ready, err := s.store.Attachments().MarkReady(s.T().Context(), id, objectKey)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(domain.AttachmentReady, ready.Status)
|
||||
|
||||
states, err := s.store.Attachments().ListStates(
|
||||
s.T().Context(), chat.ID, []uuid.UUID{id},
|
||||
)
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(states, 1)
|
||||
s.Equal(domain.AttachmentReady, states[0].Status)
|
||||
|
||||
key := uuid.NewString()
|
||||
draft := domain.MessageDraft{
|
||||
ChatID: chat.ID,
|
||||
SenderID: alice.ID,
|
||||
Text: "",
|
||||
AttachmentIDs: []uuid.UUID{id},
|
||||
Idempotency: domain.MessageIdempotency{
|
||||
Key: key,
|
||||
RequestHash: [32]byte{1},
|
||||
},
|
||||
}
|
||||
|
||||
message, err := s.store.Messages().Create(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
s.Equal([]uuid.UUID{id}, message.AttachmentIDs)
|
||||
|
||||
page, err := s.store.Messages().ListVisible(s.T().Context(), chat.ID, bob.ID, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(page.Items, 1)
|
||||
s.Equal([]uuid.UUID{id}, page.Items[0].AttachmentIDs)
|
||||
s.Empty(page.Items[0].Text)
|
||||
|
||||
replayed, err := s.store.Messages().Create(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(message.ID, replayed.ID)
|
||||
s.Equal([]uuid.UUID{id}, replayed.AttachmentIDs)
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/cache"
|
||||
storageredis "mtusi-messenger/internal/storage/redis"
|
||||
"mtusi-messenger/internal/storage/redis/mocks"
|
||||
)
|
||||
|
||||
func TestCacheLatencyExperiment(t *testing.T) {
|
||||
suite := new(BaseSuite)
|
||||
suite.SetT(t)
|
||||
suite.SetupTest()
|
||||
defer suite.TearDownTest()
|
||||
|
||||
ctx := context.Background()
|
||||
redisConfig := cache.RedisConfig{
|
||||
Host: envOr("TEST_REDIS_HOST", "localhost"),
|
||||
Port: envInt("TEST_REDIS_PORT", 6379),
|
||||
Password: envOr("TEST_REDIS_PASSWORD", ""),
|
||||
DB: envInt("TEST_REDIS_DB", 2),
|
||||
DialTimeout: 5 * time.Second,
|
||||
ReadTimeout: 3 * time.Second,
|
||||
WriteTimeout: 3 * time.Second,
|
||||
PoolSize: 5,
|
||||
}
|
||||
redisCache, err := cache.NewRedis(redisConfig)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = redisCache.Close() }()
|
||||
|
||||
alice := suite.createUser("latency_alice")
|
||||
for range 20 {
|
||||
suite.createChat(alice)
|
||||
}
|
||||
|
||||
realChats := suite.store.Chats()
|
||||
|
||||
var loads atomic.Int32
|
||||
|
||||
source := mocks.NewMockChatSource(t)
|
||||
source.EXPECT().ListVersion(mock.Anything, mock.Anything).RunAndReturn(
|
||||
func(ctx context.Context, userID uuid.UUID) (int64, error) {
|
||||
return realChats.ListVersion(ctx, userID)
|
||||
}).Maybe()
|
||||
source.EXPECT().ListVisible(mock.Anything, mock.Anything, mock.Anything, mock.Anything).
|
||||
RunAndReturn(func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) {
|
||||
loads.Add(1)
|
||||
|
||||
return realChats.ListVisible(ctx, callerID, after, limit)
|
||||
}).Maybe()
|
||||
|
||||
for range 50 {
|
||||
_, err := source.ListVisible(ctx, alice.ID, nil, 50)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
loads.Store(0)
|
||||
baseline := measureLatency(ctx, t, source.ListVisible, &loads, alice.ID, 1000)
|
||||
|
||||
distributed, err := cache.NewDistributed(redisCache, cache.DistributedConfig{}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
cached := storageredis.NewChatRepository(
|
||||
source,
|
||||
distributed,
|
||||
time.Minute,
|
||||
nil,
|
||||
)
|
||||
loads.Store(0)
|
||||
cachedStats := measureCachedLatency(ctx, t, cached, alice.ID, 1000)
|
||||
cachedStats.Loads = int(loads.Load())
|
||||
require.Equal(t, 1000, baseline.Loads)
|
||||
require.Equal(t, 1, cachedStats.Loads)
|
||||
|
||||
t.Logf("baseline: %s", formatLatency(baseline))
|
||||
t.Logf("redis cache: %s", formatLatency(cachedStats))
|
||||
}
|
||||
|
||||
func measureLatency(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
list func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error),
|
||||
loads *atomic.Int32,
|
||||
callerID uuid.UUID,
|
||||
requests int,
|
||||
) latencyStats {
|
||||
t.Helper()
|
||||
values := make([]time.Duration, 0, requests)
|
||||
for range requests {
|
||||
started := time.Now()
|
||||
_, err := list(ctx, callerID, nil, 50)
|
||||
require.NoError(t, err)
|
||||
values = append(values, time.Since(started))
|
||||
}
|
||||
|
||||
return makeLatencyStats(values, int(loads.Load()))
|
||||
}
|
||||
|
||||
func measureCachedLatency(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
repository *storageredis.ChatRepository,
|
||||
callerID uuid.UUID,
|
||||
requests int,
|
||||
) latencyStats {
|
||||
t.Helper()
|
||||
values := make([]time.Duration, 0, requests)
|
||||
for range requests {
|
||||
started := time.Now()
|
||||
_, err := repository.ListVisible(ctx, callerID, nil, 50)
|
||||
require.NoError(t, err)
|
||||
values = append(values, time.Since(started))
|
||||
}
|
||||
|
||||
return makeLatencyStats(values, 0)
|
||||
}
|
||||
|
||||
type latencyStats struct {
|
||||
Requests int
|
||||
Loads int
|
||||
P50 time.Duration
|
||||
P95 time.Duration
|
||||
P99 time.Duration
|
||||
}
|
||||
|
||||
func makeLatencyStats(values []time.Duration, loads int) latencyStats {
|
||||
sort.Slice(values, func(i, j int) bool { return values[i] < values[j] })
|
||||
percentile := func(percent int) time.Duration {
|
||||
index := (len(values)*percent + 99) / 100
|
||||
if index > 0 {
|
||||
index--
|
||||
}
|
||||
return values[index]
|
||||
}
|
||||
|
||||
return latencyStats{
|
||||
Requests: len(values), Loads: loads,
|
||||
P50: percentile(50), P95: percentile(95), P99: percentile(99),
|
||||
}
|
||||
}
|
||||
|
||||
func formatLatency(value latencyStats) string {
|
||||
return fmt.Sprintf(
|
||||
"requests=%d source_loads=%d p50=%s p95=%s p99=%s",
|
||||
value.Requests, value.Loads, value.P50, value.P95, value.P99,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"sort"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/cache"
|
||||
storageredis "mtusi-messenger/internal/storage/redis"
|
||||
"mtusi-messenger/internal/storage/redis/mocks"
|
||||
)
|
||||
|
||||
func TestCachePerformanceExperiment(t *testing.T) {
|
||||
suite := new(BaseSuite)
|
||||
suite.SetT(t)
|
||||
suite.SetupTest()
|
||||
defer suite.TearDownTest()
|
||||
|
||||
ctx := context.Background()
|
||||
redisConfig := cache.RedisConfig{
|
||||
Host: envOr("TEST_REDIS_HOST", "localhost"),
|
||||
Port: envInt("TEST_REDIS_PORT", 6379),
|
||||
Password: envOr("TEST_REDIS_PASSWORD", ""),
|
||||
DB: envInt("TEST_REDIS_DB", 2),
|
||||
DialTimeout: 5 * time.Second,
|
||||
ReadTimeout: 3 * time.Second,
|
||||
WriteTimeout: 3 * time.Second,
|
||||
PoolSize: 10,
|
||||
}
|
||||
redisCache, err := cache.NewRedis(redisConfig)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = redisCache.Close() }()
|
||||
|
||||
alice := suite.createUser("perf_alice")
|
||||
bob := suite.createUser("perf_bob")
|
||||
carol := suite.createUser("perf_carol")
|
||||
|
||||
for i := range 150 {
|
||||
title := fmt.Sprintf("Chat %d with Alice", i+1)
|
||||
members := []uuid.UUID{alice.ID}
|
||||
if i%3 == 0 {
|
||||
members = append(members, bob.ID)
|
||||
}
|
||||
if i%5 == 0 {
|
||||
members = append(members, carol.ID)
|
||||
}
|
||||
_, err := suite.store.Chats().Create(ctx, domain.ChatDraft{
|
||||
Title: title,
|
||||
MemberIDs: members,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
realChats := suite.store.Chats()
|
||||
|
||||
var loads atomic.Int32
|
||||
|
||||
source := mocks.NewMockChatSource(t)
|
||||
source.EXPECT().ListVersion(mock.Anything, mock.Anything).RunAndReturn(
|
||||
func(ctx context.Context, userID uuid.UUID) (int64, error) {
|
||||
return realChats.ListVersion(ctx, userID)
|
||||
}).Maybe()
|
||||
source.EXPECT().ListVisible(mock.Anything, mock.Anything, mock.Anything, mock.Anything).
|
||||
RunAndReturn(func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) {
|
||||
loads.Add(1)
|
||||
|
||||
return realChats.ListVisible(ctx, callerID, after, limit)
|
||||
}).Maybe()
|
||||
|
||||
distributed, err := cache.NewDistributed(redisCache, cache.DistributedConfig{}, nil)
|
||||
require.NoError(t, err)
|
||||
|
||||
cached := storageredis.NewChatRepository(
|
||||
source,
|
||||
distributed,
|
||||
time.Minute,
|
||||
nil,
|
||||
)
|
||||
|
||||
baselineStats := benchmarkConcurrent(ctx, t, func(ctx context.Context) error {
|
||||
_, err := source.ListVisible(ctx, alice.ID, nil, 50)
|
||||
return err
|
||||
}, 50, 200)
|
||||
|
||||
baselineStats.SQLQueries = int(loads.Load())
|
||||
loads.Store(0)
|
||||
cachedStats := benchmarkConcurrent(ctx, t, func(ctx context.Context) error {
|
||||
_, err := cached.ListVisible(ctx, alice.ID, nil, 50)
|
||||
return err
|
||||
}, 50, 200)
|
||||
|
||||
cachedStats.SQLQueries = int(loads.Load())
|
||||
loads.Store(0)
|
||||
|
||||
_, err = cached.ListVisible(ctx, alice.ID, nil, 50)
|
||||
require.NoError(t, err)
|
||||
|
||||
cachedHotStats := benchmarkConcurrent(ctx, t, func(ctx context.Context) error {
|
||||
_, err := cached.ListVisible(ctx, alice.ID, nil, 50)
|
||||
return err
|
||||
}, 50, 200)
|
||||
cachedHotStats.SQLQueries = int(loads.Load())
|
||||
|
||||
t.Logf("baseline (no cache): %s", formatPerfStats(baselineStats))
|
||||
t.Logf("redis cache (cold): %s", formatPerfStats(cachedStats))
|
||||
t.Logf("redis cache (hot): %s", formatPerfStats(cachedHotStats))
|
||||
}
|
||||
|
||||
type perfStats struct {
|
||||
TotalRequests int
|
||||
Concurrency int
|
||||
SQLQueries int
|
||||
Duration time.Duration
|
||||
RPS float64
|
||||
P50 time.Duration
|
||||
P95 time.Duration
|
||||
P99 time.Duration
|
||||
}
|
||||
|
||||
func benchmarkConcurrent(
|
||||
ctx context.Context,
|
||||
t *testing.T,
|
||||
operation func(context.Context) error,
|
||||
concurrency int,
|
||||
requestsPerWorker int,
|
||||
) perfStats {
|
||||
t.Helper()
|
||||
|
||||
totalRequests := concurrency * requestsPerWorker
|
||||
latencies := make([]time.Duration, totalRequests)
|
||||
var wg sync.WaitGroup
|
||||
var failures atomic.Int32
|
||||
started := time.Now()
|
||||
|
||||
for worker := range concurrency {
|
||||
wg.Add(1)
|
||||
go func(workerID int) {
|
||||
defer wg.Done()
|
||||
offset := workerID * requestsPerWorker
|
||||
for i := range requestsPerWorker {
|
||||
reqStart := time.Now()
|
||||
err := operation(ctx)
|
||||
if err != nil {
|
||||
failures.Add(1)
|
||||
}
|
||||
latencies[offset+i] = time.Since(reqStart)
|
||||
}
|
||||
}(worker)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
require.Zero(t, failures.Load(), "some requests failed")
|
||||
duration := time.Since(started)
|
||||
|
||||
sort.Slice(latencies, func(i, j int) bool { return latencies[i] < latencies[j] })
|
||||
percentile := func(p int) time.Duration {
|
||||
index := (len(latencies)*p + 99) / 100
|
||||
if index > 0 {
|
||||
index--
|
||||
}
|
||||
return latencies[index]
|
||||
}
|
||||
|
||||
return perfStats{
|
||||
TotalRequests: totalRequests,
|
||||
Concurrency: concurrency,
|
||||
Duration: duration,
|
||||
RPS: float64(totalRequests) / duration.Seconds(),
|
||||
P50: percentile(50),
|
||||
P95: percentile(95),
|
||||
P99: percentile(99),
|
||||
}
|
||||
}
|
||||
|
||||
func formatPerfStats(s perfStats) string {
|
||||
return fmt.Sprintf(
|
||||
"requests=%d concurrency=%d sql=%d duration=%s rps=%.0f p50=%s p95=%s p99=%s",
|
||||
s.TotalRequests, s.Concurrency, s.SQLQueries, s.Duration.Round(time.Millisecond),
|
||||
s.RPS, s.P50, s.P95, s.P99,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"slices"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
|
||||
)
|
||||
|
||||
type ChatRepository struct {
|
||||
store *Store
|
||||
}
|
||||
|
||||
func (r *ChatRepository) Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
var created domain.Chat
|
||||
|
||||
if err := r.store.RunInTx(ctx, func(queries *sqlcgen.Queries) error {
|
||||
missing, err := queries.ListMissingUserIDs(ctx, draft.MemberIDs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check chat members: %w", mapError(err))
|
||||
}
|
||||
|
||||
if len(missing) > 0 {
|
||||
return domain.ErrUnknownMember
|
||||
}
|
||||
|
||||
row, err := queries.CreateChat(ctx, draft.Title)
|
||||
if err != nil {
|
||||
return fmt.Errorf("create chat: %w", mapError(err))
|
||||
}
|
||||
|
||||
if err := queries.AddChatMembers(ctx, sqlcgen.AddChatMembersParams{
|
||||
ChatID: row.ID,
|
||||
UserIds: draft.MemberIDs,
|
||||
}); err != nil {
|
||||
return fmt.Errorf("add chat members: %w", mapError(err))
|
||||
}
|
||||
|
||||
if err := queries.BumpChatListVersions(ctx, sortedUnique(draft.MemberIDs)); err != nil {
|
||||
return fmt.Errorf("bump chat list versions: %w", mapError(err))
|
||||
}
|
||||
|
||||
created = mapChat(row.ID, row.Title, row.CreatedAt, draft.MemberIDs)
|
||||
|
||||
return nil
|
||||
}); err != nil {
|
||||
return domain.Chat{}, err
|
||||
}
|
||||
|
||||
return created, nil
|
||||
}
|
||||
|
||||
func (r *ChatRepository) ListVersion(ctx context.Context, userID uuid.UUID) (int64, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
version, err := r.store.queries.GetChatListVersion(ctx, userID)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("get chat list version: %w", mapError(err))
|
||||
}
|
||||
|
||||
return version, nil
|
||||
}
|
||||
|
||||
func sortedUnique(ids []uuid.UUID) []uuid.UUID {
|
||||
sorted := slices.Clone(ids)
|
||||
slices.SortFunc(sorted, func(a, b uuid.UUID) int {
|
||||
return bytes.Compare(a[:], b[:])
|
||||
})
|
||||
|
||||
return slices.Compact(sorted)
|
||||
}
|
||||
|
||||
func (r *ChatRepository) GetVisible(ctx context.Context, chatID, callerID uuid.UUID) (domain.Chat, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
row, err := r.store.queries.GetChatForMember(ctx, sqlcgen.GetChatForMemberParams{
|
||||
UserID: callerID,
|
||||
ID: chatID,
|
||||
})
|
||||
if err != nil {
|
||||
mapped := mapError(err)
|
||||
if errors.Is(mapped, domain.ErrNotFound) {
|
||||
return domain.Chat{}, fmt.Errorf("%w: chat %s for user %s", domain.ErrNotFound, chatID, callerID)
|
||||
}
|
||||
|
||||
return domain.Chat{}, fmt.Errorf("get chat: %w", mapped)
|
||||
}
|
||||
|
||||
return mapChat(row.ID, row.Title, row.CreatedAt, row.MemberIds), nil
|
||||
}
|
||||
|
||||
func (r *ChatRepository) ListVisible(
|
||||
ctx context.Context,
|
||||
callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Chat], error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
limit = clampLimit(limit)
|
||||
fetch := int32(limit + 1) //nolint:gosec // limit is clamped to maxPageSize
|
||||
|
||||
var rows []domain.Chat
|
||||
|
||||
if after == nil {
|
||||
pageRows, err := r.store.queries.ListChatsForMember(ctx, sqlcgen.ListChatsForMemberParams{
|
||||
UserID: callerID,
|
||||
RowLimit: fetch,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Page[domain.Chat]{}, fmt.Errorf("list chats: %w", mapError(err))
|
||||
}
|
||||
|
||||
rows = mapAll(pageRows, mapChatRow)
|
||||
} else {
|
||||
pageRows, err := r.store.queries.ListChatsForMemberAfter(ctx, sqlcgen.ListChatsForMemberAfterParams{
|
||||
UserID: callerID,
|
||||
AfterCreatedAt: after.CreatedAt,
|
||||
AfterID: after.ID,
|
||||
RowLimit: fetch,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Page[domain.Chat]{}, fmt.Errorf("list chats: %w", mapError(err))
|
||||
}
|
||||
|
||||
rows = mapAll(pageRows, mapChatRowAfter)
|
||||
}
|
||||
|
||||
return buildPage(rows, limit, func(chat domain.Chat) domain.Cursor {
|
||||
return domain.Cursor{Scope: callerID, CreatedAt: chat.CreatedAt, ID: chat.ID}
|
||||
}), nil
|
||||
}
|
||||
|
||||
func mapChatRow(row sqlcgen.ListChatsForMemberRow) domain.Chat {
|
||||
return mapChat(row.ID, row.Title, row.CreatedAt, row.MemberIds)
|
||||
}
|
||||
|
||||
func mapChatRowAfter(row sqlcgen.ListChatsForMemberAfterRow) domain.Chat {
|
||||
return mapChat(row.ID, row.Title, row.CreatedAt, row.MemberIds)
|
||||
}
|
||||
|
||||
func mapChat(id uuid.UUID, title string, createdAt time.Time, memberIDs []uuid.UUID) domain.Chat {
|
||||
return domain.Chat{
|
||||
ID: id,
|
||||
Title: title,
|
||||
MemberIDs: memberIDs,
|
||||
CreatedAt: toUTCTime(createdAt),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,239 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"slices"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
type ChatRepositorySuite struct {
|
||||
BaseSuite
|
||||
}
|
||||
|
||||
func TestChatRepositorySuite(t *testing.T) {
|
||||
suite.Run(t, new(ChatRepositorySuite))
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestCreateRejectsUnknownMemberAtomically() {
|
||||
alice := s.createUser("alice")
|
||||
|
||||
_, err := s.store.Chats().Create(s.T().Context(), domain.ChatDraft{
|
||||
Title: "С неизвестным участником",
|
||||
MemberIDs: []uuid.UUID{alice.ID, uuid.New()},
|
||||
CallerID: alice.ID,
|
||||
})
|
||||
s.Require().ErrorIs(err, domain.ErrUnknownMember)
|
||||
|
||||
var chats int
|
||||
s.Require().NoError(s.pool.QueryRow(s.T().Context(), "SELECT count(*) FROM chats").Scan(&chats))
|
||||
s.Zero(chats, "неуспешное создание чата не оставляет строк")
|
||||
|
||||
var members int
|
||||
s.Require().NoError(s.pool.QueryRow(s.T().Context(), "SELECT count(*) FROM chat_members").Scan(&members))
|
||||
s.Zero(members)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestCreateRejectsDuplicateMembers() {
|
||||
alice := s.createUser("alice")
|
||||
|
||||
_, err := s.store.Chats().Create(s.T().Context(), domain.ChatDraft{
|
||||
Title: "Дубликаты",
|
||||
MemberIDs: []uuid.UUID{alice.ID, alice.ID},
|
||||
CallerID: alice.ID,
|
||||
})
|
||||
s.Require().ErrorIs(err, domain.ErrConflict)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestCreateBumpsMemberListVersions() {
|
||||
ctx := s.T().Context()
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
carol := s.createUser("carol")
|
||||
|
||||
s.createChat(alice, bob)
|
||||
|
||||
aliceVersion, err := s.store.Chats().ListVersion(ctx, alice.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(int64(1), aliceVersion, "creator version must be bumped")
|
||||
|
||||
bobVersion, err := s.store.Chats().ListVersion(ctx, bob.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(int64(1), bobVersion, "member version must be bumped")
|
||||
|
||||
carolVersion, err := s.store.Chats().ListVersion(ctx, carol.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Zero(carolVersion, "non-member version must stay unchanged")
|
||||
|
||||
s.createChat(alice, carol)
|
||||
|
||||
aliceVersion, err = s.store.Chats().ListVersion(ctx, alice.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(int64(2), aliceVersion, "version must grow monotonically")
|
||||
|
||||
carolVersion, err = s.store.Chats().ListVersion(ctx, carol.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(int64(1), carolVersion)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestConcurrentCreateNoDeadlock() {
|
||||
ctx := s.T().Context()
|
||||
|
||||
users := make([]domain.User, 0, 8)
|
||||
for i := range 8 {
|
||||
users = append(users, s.createUser(fmt.Sprintf("member%d", i)))
|
||||
}
|
||||
|
||||
const workers = 16
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
errs := make(chan error, workers)
|
||||
|
||||
wg.Add(workers)
|
||||
|
||||
for w := range workers {
|
||||
go func(w int) {
|
||||
defer wg.Done()
|
||||
|
||||
ids := []uuid.UUID{
|
||||
users[w%len(users)].ID,
|
||||
users[(w+1)%len(users)].ID,
|
||||
users[(w+2)%len(users)].ID,
|
||||
}
|
||||
if w%2 == 1 {
|
||||
slices.Reverse(ids)
|
||||
}
|
||||
|
||||
_, err := s.store.Chats().Create(ctx, domain.ChatDraft{
|
||||
Title: fmt.Sprintf("chat-%d", w),
|
||||
MemberIDs: ids,
|
||||
CallerID: ids[0],
|
||||
})
|
||||
if err != nil {
|
||||
errs <- err
|
||||
}
|
||||
}(w)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
close(errs)
|
||||
|
||||
for err := range errs {
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestCreateStoresAllMembers() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
eve := s.createUser("eve")
|
||||
|
||||
chat := s.createChat(alice, bob, eve)
|
||||
s.Equal(uuid.Version(7), chat.ID.Version())
|
||||
s.False(chat.CreatedAt.IsZero())
|
||||
|
||||
visible, err := s.store.Chats().GetVisible(s.T().Context(), chat.ID, bob.ID)
|
||||
s.Require().NoError(err)
|
||||
s.ElementsMatch([]uuid.UUID{alice.ID, bob.ID, eve.ID}, visible.MemberIDs)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestVisibility() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
eve := s.createUser("eve")
|
||||
|
||||
chat := s.createChat(alice, bob)
|
||||
|
||||
visible, err := s.store.Chats().GetVisible(s.T().Context(), chat.ID, bob.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(chat.ID, visible.ID)
|
||||
s.ElementsMatch([]uuid.UUID{alice.ID, bob.ID}, visible.MemberIDs)
|
||||
|
||||
_, err = s.store.Chats().GetVisible(s.T().Context(), chat.ID, eve.ID)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
|
||||
page, err := s.store.Chats().ListVisible(s.T().Context(), eve.ID, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
s.Empty(page.Items)
|
||||
|
||||
page, err = s.store.Chats().ListVisible(s.T().Context(), alice.ID, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
s.Require().Len(page.Items, 1)
|
||||
s.ElementsMatch([]uuid.UUID{alice.ID, bob.ID}, page.Items[0].MemberIDs)
|
||||
s.Nil(page.Next)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestListPagination() {
|
||||
alice := s.createUser("alice")
|
||||
|
||||
const total = 5
|
||||
for range total {
|
||||
s.createChat(alice)
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, total)
|
||||
|
||||
var cursor *domain.Cursor
|
||||
|
||||
for {
|
||||
page, err := s.store.Chats().ListVisible(s.T().Context(), alice.ID, cursor, 2)
|
||||
s.Require().NoError(err)
|
||||
s.Require().NotEmpty(page.Items)
|
||||
|
||||
for _, chat := range page.Items {
|
||||
_, duplicate := seen[chat.ID]
|
||||
s.Require().False(duplicate)
|
||||
seen[chat.ID] = struct{}{}
|
||||
}
|
||||
|
||||
if page.Next == nil {
|
||||
break
|
||||
}
|
||||
|
||||
cursor = page.Next
|
||||
}
|
||||
|
||||
s.Len(seen, total)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestListPaginationWithSharedTimestamp() {
|
||||
alice := s.createUser("alice")
|
||||
|
||||
for range 5 {
|
||||
s.createChat(alice)
|
||||
}
|
||||
|
||||
_, err := s.pool.Exec(s.T().Context(), "UPDATE chats SET created_at = '2026-01-01 00:00:00+00'")
|
||||
s.Require().NoError(err)
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, 5)
|
||||
|
||||
var cursor *domain.Cursor
|
||||
|
||||
for {
|
||||
page, err := s.store.Chats().ListVisible(s.T().Context(), alice.ID, cursor, 2)
|
||||
s.Require().NoError(err)
|
||||
|
||||
for _, chat := range page.Items {
|
||||
_, duplicate := seen[chat.ID]
|
||||
s.Require().False(duplicate)
|
||||
seen[chat.ID] = struct{}{}
|
||||
}
|
||||
|
||||
if page.Next == nil {
|
||||
break
|
||||
}
|
||||
|
||||
cursor = page.Next
|
||||
}
|
||||
|
||||
s.Len(seen, 5)
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultHost = "localhost"
|
||||
defaultPort = 5432
|
||||
defaultDatabase = "messenger"
|
||||
defaultUser = "messenger"
|
||||
defaultSSLMode = "disable"
|
||||
defaultMaxConns = int32(10)
|
||||
defaultMinConns = int32(1)
|
||||
defaultMaxConnLifetime = time.Hour
|
||||
defaultMaxConnIdleTime = 30 * time.Minute
|
||||
defaultConnectTimeout = 5 * time.Second
|
||||
defaultQueryTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
func normalize(cfg config.Postgres) (config.Postgres, error) {
|
||||
if cfg.Host == "" {
|
||||
cfg.Host = defaultHost
|
||||
}
|
||||
|
||||
if cfg.Port == 0 {
|
||||
cfg.Port = defaultPort
|
||||
}
|
||||
|
||||
if cfg.Database == "" {
|
||||
cfg.Database = defaultDatabase
|
||||
}
|
||||
|
||||
if cfg.User == "" {
|
||||
cfg.User = defaultUser
|
||||
}
|
||||
|
||||
if cfg.SSLMode == "" {
|
||||
cfg.SSLMode = defaultSSLMode
|
||||
}
|
||||
|
||||
if cfg.MaxConns == 0 {
|
||||
cfg.MaxConns = defaultMaxConns
|
||||
}
|
||||
|
||||
if cfg.MinConns == 0 {
|
||||
cfg.MinConns = defaultMinConns
|
||||
}
|
||||
|
||||
if cfg.MaxConnLifetime == 0 {
|
||||
cfg.MaxConnLifetime = defaultMaxConnLifetime
|
||||
}
|
||||
|
||||
if cfg.MaxConnIdleTime == 0 {
|
||||
cfg.MaxConnIdleTime = defaultMaxConnIdleTime
|
||||
}
|
||||
|
||||
if cfg.ConnectTimeout == 0 {
|
||||
cfg.ConnectTimeout = defaultConnectTimeout
|
||||
}
|
||||
|
||||
if cfg.QueryTimeout == 0 {
|
||||
cfg.QueryTimeout = defaultQueryTimeout
|
||||
}
|
||||
|
||||
if cfg.MinConns > cfg.MaxConns {
|
||||
return cfg, errors.New("postgres: min_conns must not exceed max_conns")
|
||||
}
|
||||
|
||||
return cfg, nil
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
)
|
||||
|
||||
func TestNormalizeAppliesDefaults(t *testing.T) {
|
||||
cfg, err := normalize(config.Postgres{})
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, "localhost", cfg.Host)
|
||||
require.Equal(t, 5432, cfg.Port)
|
||||
require.Equal(t, "messenger", cfg.Database)
|
||||
require.Equal(t, "messenger", cfg.User)
|
||||
require.Equal(t, "disable", cfg.SSLMode)
|
||||
require.Equal(t, int32(10), cfg.MaxConns)
|
||||
require.Equal(t, int32(1), cfg.MinConns)
|
||||
require.Equal(t, time.Hour, cfg.MaxConnLifetime)
|
||||
require.Equal(t, 5*time.Second, cfg.ConnectTimeout)
|
||||
}
|
||||
|
||||
func TestNormalizeKeepsProvidedValues(t *testing.T) {
|
||||
cfg, err := normalize(config.Postgres{
|
||||
Host: "db",
|
||||
Port: 6543,
|
||||
Database: "app",
|
||||
User: "app",
|
||||
SSLMode: "require",
|
||||
MaxConns: 7,
|
||||
MinConns: 2,
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
require.Equal(t, "db", cfg.Host)
|
||||
require.Equal(t, 6543, cfg.Port)
|
||||
require.Equal(t, "app", cfg.Database)
|
||||
require.Equal(t, "require", cfg.SSLMode)
|
||||
require.Equal(t, int32(7), cfg.MaxConns)
|
||||
}
|
||||
|
||||
func TestNormalizeRejectsMinGreaterThanMax(t *testing.T) {
|
||||
_, err := normalize(config.Postgres{MinConns: 5, MaxConns: 2})
|
||||
require.Error(t, err)
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"syscall"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
pgUniqueViolation = "23505"
|
||||
pgForeignKeyViolation = "23503"
|
||||
pgCheckViolation = "23514"
|
||||
)
|
||||
|
||||
func isUniqueViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
|
||||
return errors.As(err, &pgErr) && pgErr.Code == pgUniqueViolation
|
||||
}
|
||||
|
||||
// isUnavailable reports whether err is a transport-level failure — the server is
|
||||
// down, the connection dropped, or the pool/query deadline expired — rather than
|
||||
// a statement-level error. Such failures are dependency outages, not caller errors.
|
||||
func isUnavailable(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
|
||||
var (
|
||||
connectErr *pgconn.ConnectError
|
||||
netErr net.Error
|
||||
)
|
||||
|
||||
return errors.As(err, &connectErr) ||
|
||||
errors.As(err, &netErr) ||
|
||||
errors.Is(err, context.DeadlineExceeded) ||
|
||||
errors.Is(err, syscall.ECONNREFUSED) ||
|
||||
errors.Is(err, syscall.ECONNRESET) ||
|
||||
errors.Is(err, syscall.EPIPE) ||
|
||||
errors.Is(err, io.EOF) ||
|
||||
errors.Is(err, io.ErrUnexpectedEOF) ||
|
||||
errors.Is(err, pgx.ErrTxClosed) ||
|
||||
errors.Is(err, pgx.ErrTxCommitRollback)
|
||||
}
|
||||
|
||||
func mapError(err error) error {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.ErrNotFound
|
||||
}
|
||||
|
||||
if pgErr, ok := errors.AsType[*pgconn.PgError](err); ok {
|
||||
switch pgErr.Code {
|
||||
case pgUniqueViolation:
|
||||
return domain.ErrConflict
|
||||
case pgForeignKeyViolation:
|
||||
// Нарушение внешнего ключа означает ссылку на отсутствующую сущность:
|
||||
// например, отправка сообщения в несуществующий чат или в чат, где
|
||||
// отправителя нет. Для клиента это 404, а не 500.
|
||||
return domain.ErrNotFound
|
||||
case pgCheckViolation:
|
||||
return domain.ErrValidation
|
||||
}
|
||||
}
|
||||
|
||||
if isUnavailable(err) {
|
||||
return fmt.Errorf("%w: %w", domain.ErrUnavailable, err)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
type IdempotencySuite struct {
|
||||
BaseSuite
|
||||
}
|
||||
|
||||
func TestIdempotencySuite(t *testing.T) {
|
||||
suite.Run(t, new(IdempotencySuite))
|
||||
}
|
||||
|
||||
func messageDraft(chat domain.Chat, sender domain.User, key, text string) domain.MessageDraft {
|
||||
return domain.MessageDraft{
|
||||
ChatID: chat.ID,
|
||||
SenderID: sender.ID,
|
||||
Text: text,
|
||||
Idempotency: domain.MessageIdempotency{
|
||||
Key: key,
|
||||
RequestHash: sha256.Sum256([]byte(text)),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) history(chat domain.Chat, actor domain.User) []domain.Message {
|
||||
s.T().Helper()
|
||||
|
||||
page, err := s.store.Messages().ListVisible(s.T().Context(), chat.ID, actor.ID, nil, 100)
|
||||
s.Require().NoError(err)
|
||||
|
||||
return page.Items
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) TestReplayReturnsStoredMessage() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
chat := s.createChat(alice, bob)
|
||||
draft := messageDraft(chat, alice, "key-1", "привет")
|
||||
|
||||
created, err := s.store.Messages().Create(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
|
||||
replayed, err := s.store.Messages().Create(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Equal(created, replayed, "повтор с тем же ключом и payload возвращает исходное сообщение")
|
||||
s.Len(s.history(chat, bob), 1, "повтор не создаёт дубль")
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) TestSameKeyWithAnotherPayloadConflicts() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
chat := s.createChat(alice, bob)
|
||||
|
||||
created, err := s.store.Messages().Create(s.T().Context(), messageDraft(chat, alice, "key-1", "привет"))
|
||||
s.Require().NoError(err)
|
||||
|
||||
_, err = s.store.Messages().Create(s.T().Context(), messageDraft(chat, alice, "key-1", "другое"))
|
||||
s.Require().ErrorIs(err, domain.ErrIdempotency)
|
||||
|
||||
history := s.history(chat, bob)
|
||||
s.Require().Len(history, 1, "конфликт не создаёт сообщение")
|
||||
s.Equal(created.ID, history[0].ID, "исходное сообщение не изменено")
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) TestConcurrentReplaysCreateOneMessage() {
|
||||
const callers = 8
|
||||
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
chat := s.createChat(alice, bob)
|
||||
draft := messageDraft(chat, alice, "key-concurrent", "конкурентный повтор")
|
||||
|
||||
ctx := s.T().Context()
|
||||
results := make([]domain.Message, callers)
|
||||
errs := make([]error, callers)
|
||||
|
||||
start := make(chan struct{})
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
for i := range callers {
|
||||
wg.Add(1)
|
||||
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
<-start
|
||||
|
||||
results[i], errs[i] = s.store.Messages().Create(ctx, draft)
|
||||
}()
|
||||
}
|
||||
|
||||
close(start)
|
||||
wg.Wait()
|
||||
|
||||
for i := range callers {
|
||||
s.Require().NoError(errs[i], "caller %d", i)
|
||||
s.Equal(results[0].ID, results[i].ID, "все одновременные повторы получают одно сообщение")
|
||||
}
|
||||
|
||||
s.Len(s.history(chat, bob), 1, "конкурентный повтор создаёт ровно одно сообщение")
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) TestKeyIsScopedToActorAndChat() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
carol := s.createUser("carol")
|
||||
|
||||
first := s.createChat(alice, bob)
|
||||
second := s.createChat(alice, carol)
|
||||
|
||||
mine, err := s.store.Messages().Create(s.T().Context(), messageDraft(first, alice, "shared-key", "от Алисы"))
|
||||
s.Require().NoError(err)
|
||||
|
||||
byBob, err := s.store.Messages().Create(s.T().Context(), messageDraft(first, bob, "shared-key", "от Боба"))
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.NotEqual(mine.ID, byBob.ID, "одинаковый ключ разных пользователей независим")
|
||||
|
||||
another, err := s.store.Messages().Create(s.T().Context(), messageDraft(second, alice, "shared-key", "в другом чате"))
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.NotEqual(mine.ID, another.ID, "одинаковый ключ в другом чате независим")
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) TestExpiredKeyIsReplaced() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
chat := s.createChat(alice, bob)
|
||||
draft := messageDraft(chat, alice, "key-expiring", "первое")
|
||||
|
||||
// Отрицательный TTL: записи идемпотентности истекают сразу.
|
||||
expiring := openStoreWithTTL(s.T(), s.db, -time.Second, nil)
|
||||
s.T().Cleanup(expiring.Close)
|
||||
|
||||
created, err := expiring.Messages().Create(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
|
||||
replaced, err := expiring.Messages().Create(s.T().Context(), messageDraft(chat, alice, "key-expiring", "второе"))
|
||||
s.Require().NoError(err, "истёкший ключ можно использовать с другим payload")
|
||||
s.NotEqual(created.ID, replaced.ID)
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) TestClaimForMissingChatIsNotFound() {
|
||||
alice := s.createUser("alice")
|
||||
|
||||
// Чат не существует: claim ключа ссылается на chats(id), поэтому наружу
|
||||
// должен уйти 404, а не 500 из-за нарушения внешнего ключа.
|
||||
_, err := s.store.Messages().Create(
|
||||
s.T().Context(),
|
||||
messageDraft(domain.Chat{ID: uuid.New()}, alice, "key-1", "привет"),
|
||||
)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *IdempotencySuite) TestFailedAttemptLeavesNoClaim() {
|
||||
alice := s.createUser("alice")
|
||||
outsider := s.createUser("outsider")
|
||||
chat := s.createChat(alice)
|
||||
|
||||
_, err := s.store.Messages().Create(s.T().Context(), messageDraft(chat, outsider, "key-1", "привет"))
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
|
||||
var claims int
|
||||
|
||||
s.Require().NoError(
|
||||
s.pool.QueryRow(s.T().Context(), "SELECT count(*) FROM message_idempotency").Scan(&claims),
|
||||
)
|
||||
s.Zero(claims, "отклонённая попытка не оставляет claim: транзакция откатывается целиком")
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: attachments.sql
|
||||
|
||||
package sqlcgen
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const attachToMessage = `-- name: AttachToMessage :exec
|
||||
INSERT INTO message_attachments (message_id, attachment_id, position)
|
||||
VALUES ($1, $2, $3)
|
||||
`
|
||||
|
||||
type AttachToMessageParams struct {
|
||||
MessageID uuid.UUID
|
||||
AttachmentID uuid.UUID
|
||||
Position int16
|
||||
}
|
||||
|
||||
func (q *Queries) AttachToMessage(ctx context.Context, arg AttachToMessageParams) error {
|
||||
_, err := q.db.Exec(ctx, attachToMessage, arg.MessageID, arg.AttachmentID, arg.Position)
|
||||
return err
|
||||
}
|
||||
|
||||
const createAttachment = `-- name: CreateAttachment :one
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256, status
|
||||
)
|
||||
VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5,
|
||||
$6,
|
||||
$7,
|
||||
$8,
|
||||
'pending'
|
||||
)
|
||||
RETURNING id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256,
|
||||
status, error_code, created_at, updated_at
|
||||
`
|
||||
|
||||
type CreateAttachmentParams struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
OwnerID uuid.UUID
|
||||
ObjectKey string
|
||||
Filename string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
Sha256 string
|
||||
}
|
||||
|
||||
func (q *Queries) CreateAttachment(ctx context.Context, arg CreateAttachmentParams) (Attachment, error) {
|
||||
row := q.db.QueryRow(ctx, createAttachment,
|
||||
arg.ID,
|
||||
arg.ChatID,
|
||||
arg.OwnerID,
|
||||
arg.ObjectKey,
|
||||
arg.Filename,
|
||||
arg.ContentType,
|
||||
arg.SizeBytes,
|
||||
arg.Sha256,
|
||||
)
|
||||
var i Attachment
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.OwnerID,
|
||||
&i.ObjectKey,
|
||||
&i.Filename,
|
||||
&i.ContentType,
|
||||
&i.SizeBytes,
|
||||
&i.Sha256,
|
||||
&i.Status,
|
||||
&i.ErrorCode,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const deletePendingAttachment = `-- name: DeletePendingAttachment :exec
|
||||
DELETE FROM attachments
|
||||
WHERE id = $1
|
||||
AND status = 'pending'
|
||||
`
|
||||
|
||||
func (q *Queries) DeletePendingAttachment(ctx context.Context, id uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, deletePendingAttachment, id)
|
||||
return err
|
||||
}
|
||||
|
||||
const getAttachmentForMember = `-- name: GetAttachmentForMember :one
|
||||
SELECT a.id, a.chat_id, a.owner_id, a.object_key, a.filename, a.content_type,
|
||||
a.size_bytes, a.sha256, a.status, a.error_code, a.created_at, a.updated_at
|
||||
FROM attachments a
|
||||
JOIN chat_members cm
|
||||
ON cm.chat_id = a.chat_id
|
||||
AND cm.user_id = $1
|
||||
WHERE a.id = $2
|
||||
`
|
||||
|
||||
type GetAttachmentForMemberParams struct {
|
||||
UserID uuid.UUID
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) GetAttachmentForMember(ctx context.Context, arg GetAttachmentForMemberParams) (Attachment, error) {
|
||||
row := q.db.QueryRow(ctx, getAttachmentForMember, arg.UserID, arg.ID)
|
||||
var i Attachment
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.OwnerID,
|
||||
&i.ObjectKey,
|
||||
&i.Filename,
|
||||
&i.ContentType,
|
||||
&i.SizeBytes,
|
||||
&i.Sha256,
|
||||
&i.Status,
|
||||
&i.ErrorCode,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getAttachmentForOwner = `-- name: GetAttachmentForOwner :one
|
||||
SELECT a.id, a.chat_id, a.owner_id, a.object_key, a.filename, a.content_type,
|
||||
a.size_bytes, a.sha256, a.status, a.error_code, a.created_at, a.updated_at
|
||||
FROM attachments a
|
||||
JOIN chat_members cm
|
||||
ON cm.chat_id = a.chat_id
|
||||
AND cm.user_id = a.owner_id
|
||||
WHERE a.id = $1
|
||||
AND a.owner_id = $2
|
||||
`
|
||||
|
||||
type GetAttachmentForOwnerParams struct {
|
||||
ID uuid.UUID
|
||||
OwnerID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) GetAttachmentForOwner(ctx context.Context, arg GetAttachmentForOwnerParams) (Attachment, error) {
|
||||
row := q.db.QueryRow(ctx, getAttachmentForOwner, arg.ID, arg.OwnerID)
|
||||
var i Attachment
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.OwnerID,
|
||||
&i.ObjectKey,
|
||||
&i.Filename,
|
||||
&i.ContentType,
|
||||
&i.SizeBytes,
|
||||
&i.Sha256,
|
||||
&i.Status,
|
||||
&i.ErrorCode,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const listAttachmentKeys = `-- name: ListAttachmentKeys :many
|
||||
SELECT id, object_key, status, created_at
|
||||
FROM attachments
|
||||
ORDER BY id
|
||||
LIMIT $2 OFFSET $1
|
||||
`
|
||||
|
||||
type ListAttachmentKeysParams struct {
|
||||
RowOffset int32
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
type ListAttachmentKeysRow struct {
|
||||
ID uuid.UUID
|
||||
ObjectKey string
|
||||
Status string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) ListAttachmentKeys(ctx context.Context, arg ListAttachmentKeysParams) ([]ListAttachmentKeysRow, error) {
|
||||
rows, err := q.db.Query(ctx, listAttachmentKeys, arg.RowOffset, arg.RowLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []ListAttachmentKeysRow{}
|
||||
for rows.Next() {
|
||||
var i ListAttachmentKeysRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.ObjectKey,
|
||||
&i.Status,
|
||||
&i.CreatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listAttachmentStatesForChat = `-- name: ListAttachmentStatesForChat :many
|
||||
SELECT id, status
|
||||
FROM attachments
|
||||
WHERE chat_id = $1
|
||||
AND id = ANY($2::uuid[])
|
||||
`
|
||||
|
||||
type ListAttachmentStatesForChatParams struct {
|
||||
ChatID uuid.UUID
|
||||
Ids []uuid.UUID
|
||||
}
|
||||
|
||||
type ListAttachmentStatesForChatRow struct {
|
||||
ID uuid.UUID
|
||||
Status string
|
||||
}
|
||||
|
||||
func (q *Queries) ListAttachmentStatesForChat(ctx context.Context, arg ListAttachmentStatesForChatParams) ([]ListAttachmentStatesForChatRow, error) {
|
||||
rows, err := q.db.Query(ctx, listAttachmentStatesForChat, arg.ChatID, arg.Ids)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []ListAttachmentStatesForChatRow{}
|
||||
for rows.Next() {
|
||||
var i ListAttachmentStatesForChatRow
|
||||
if err := rows.Scan(&i.ID, &i.Status); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listMessageAttachments = `-- name: ListMessageAttachments :many
|
||||
SELECT message_id, attachment_id
|
||||
FROM message_attachments
|
||||
WHERE message_id = ANY($1::uuid[])
|
||||
ORDER BY message_id, position
|
||||
`
|
||||
|
||||
type ListMessageAttachmentsRow struct {
|
||||
MessageID uuid.UUID
|
||||
AttachmentID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) ListMessageAttachments(ctx context.Context, messageIds []uuid.UUID) ([]ListMessageAttachmentsRow, error) {
|
||||
rows, err := q.db.Query(ctx, listMessageAttachments, messageIds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []ListMessageAttachmentsRow{}
|
||||
for rows.Next() {
|
||||
var i ListMessageAttachmentsRow
|
||||
if err := rows.Scan(&i.MessageID, &i.AttachmentID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listStalePendingAttachments = `-- name: ListStalePendingAttachments :many
|
||||
SELECT id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256,
|
||||
status, error_code, created_at, updated_at
|
||||
FROM attachments
|
||||
WHERE status = 'pending'
|
||||
AND created_at < $1
|
||||
ORDER BY created_at
|
||||
LIMIT $2
|
||||
`
|
||||
|
||||
type ListStalePendingAttachmentsParams struct {
|
||||
CreatedBefore time.Time
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
func (q *Queries) ListStalePendingAttachments(ctx context.Context, arg ListStalePendingAttachmentsParams) ([]Attachment, error) {
|
||||
rows, err := q.db.Query(ctx, listStalePendingAttachments, arg.CreatedBefore, arg.RowLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []Attachment{}
|
||||
for rows.Next() {
|
||||
var i Attachment
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.OwnerID,
|
||||
&i.ObjectKey,
|
||||
&i.Filename,
|
||||
&i.ContentType,
|
||||
&i.SizeBytes,
|
||||
&i.Sha256,
|
||||
&i.Status,
|
||||
&i.ErrorCode,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const markAttachmentReady = `-- name: MarkAttachmentReady :one
|
||||
UPDATE attachments
|
||||
SET status = 'ready',
|
||||
object_key = $1,
|
||||
updated_at = now()
|
||||
WHERE id = $2
|
||||
AND status = 'pending'
|
||||
RETURNING id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256,
|
||||
status, error_code, created_at, updated_at
|
||||
`
|
||||
|
||||
type MarkAttachmentReadyParams struct {
|
||||
ObjectKey string
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) MarkAttachmentReady(ctx context.Context, arg MarkAttachmentReadyParams) (Attachment, error) {
|
||||
row := q.db.QueryRow(ctx, markAttachmentReady, arg.ObjectKey, arg.ID)
|
||||
var i Attachment
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.OwnerID,
|
||||
&i.ObjectKey,
|
||||
&i.Filename,
|
||||
&i.ContentType,
|
||||
&i.SizeBytes,
|
||||
&i.Sha256,
|
||||
&i.Status,
|
||||
&i.ErrorCode,
|
||||
&i.CreatedAt,
|
||||
&i.UpdatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -0,0 +1,251 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: chats.sql
|
||||
|
||||
package sqlcgen
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const addChatMembers = `-- name: AddChatMembers :exec
|
||||
INSERT INTO chat_members (chat_id, user_id)
|
||||
SELECT $1, members.member_id
|
||||
FROM unnest($2::uuid[]) AS members(member_id)
|
||||
`
|
||||
|
||||
type AddChatMembersParams struct {
|
||||
ChatID uuid.UUID
|
||||
UserIds []uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) AddChatMembers(ctx context.Context, arg AddChatMembersParams) error {
|
||||
_, err := q.db.Exec(ctx, addChatMembers, arg.ChatID, arg.UserIds)
|
||||
return err
|
||||
}
|
||||
|
||||
const bumpChatListVersions = `-- name: BumpChatListVersions :exec
|
||||
INSERT INTO user_chat_versions (user_id, version)
|
||||
SELECT DISTINCT m, 1
|
||||
FROM unnest($1::uuid[]) AS m
|
||||
ORDER BY m
|
||||
ON CONFLICT (user_id) DO UPDATE SET version = user_chat_versions.version + 1
|
||||
`
|
||||
|
||||
func (q *Queries) BumpChatListVersions(ctx context.Context, userIds []uuid.UUID) error {
|
||||
_, err := q.db.Exec(ctx, bumpChatListVersions, userIds)
|
||||
return err
|
||||
}
|
||||
|
||||
const createChat = `-- name: CreateChat :one
|
||||
INSERT INTO chats (title)
|
||||
VALUES ($1)
|
||||
RETURNING id, title, created_at
|
||||
`
|
||||
|
||||
func (q *Queries) CreateChat(ctx context.Context, title string) (Chat, error) {
|
||||
row := q.db.QueryRow(ctx, createChat, title)
|
||||
var i Chat
|
||||
err := row.Scan(&i.ID, &i.Title, &i.CreatedAt)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getChatForMember = `-- name: GetChatForMember :one
|
||||
SELECT
|
||||
c.id,
|
||||
c.title,
|
||||
c.created_at,
|
||||
(
|
||||
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
|
||||
FROM chat_members m
|
||||
WHERE m.chat_id = c.id
|
||||
)::uuid[] AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members visible
|
||||
ON visible.chat_id = c.id AND visible.user_id = $1
|
||||
WHERE c.id = $2
|
||||
`
|
||||
|
||||
type GetChatForMemberParams struct {
|
||||
UserID uuid.UUID
|
||||
ID uuid.UUID
|
||||
}
|
||||
|
||||
type GetChatForMemberRow struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
CreatedAt time.Time
|
||||
MemberIds []uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) GetChatForMember(ctx context.Context, arg GetChatForMemberParams) (GetChatForMemberRow, error) {
|
||||
row := q.db.QueryRow(ctx, getChatForMember, arg.UserID, arg.ID)
|
||||
var i GetChatForMemberRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Title,
|
||||
&i.CreatedAt,
|
||||
&i.MemberIds,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getChatListVersion = `-- name: GetChatListVersion :one
|
||||
SELECT COALESCE(MAX(version), 0)::bigint AS version
|
||||
FROM user_chat_versions
|
||||
WHERE user_id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetChatListVersion(ctx context.Context, userID uuid.UUID) (int64, error) {
|
||||
row := q.db.QueryRow(ctx, getChatListVersion, userID)
|
||||
var version int64
|
||||
err := row.Scan(&version)
|
||||
return version, err
|
||||
}
|
||||
|
||||
const listChatsForMember = `-- name: ListChatsForMember :many
|
||||
SELECT
|
||||
c.id,
|
||||
c.title,
|
||||
c.created_at,
|
||||
(
|
||||
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
|
||||
FROM chat_members m
|
||||
WHERE m.chat_id = c.id
|
||||
)::uuid[] AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members visible ON visible.chat_id = c.id
|
||||
WHERE visible.user_id = $1
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $2
|
||||
`
|
||||
|
||||
type ListChatsForMemberParams struct {
|
||||
UserID uuid.UUID
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
type ListChatsForMemberRow struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
CreatedAt time.Time
|
||||
MemberIds []uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) ListChatsForMember(ctx context.Context, arg ListChatsForMemberParams) ([]ListChatsForMemberRow, error) {
|
||||
rows, err := q.db.Query(ctx, listChatsForMember, arg.UserID, arg.RowLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []ListChatsForMemberRow{}
|
||||
for rows.Next() {
|
||||
var i ListChatsForMemberRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Title,
|
||||
&i.CreatedAt,
|
||||
&i.MemberIds,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listChatsForMemberAfter = `-- name: ListChatsForMemberAfter :many
|
||||
SELECT
|
||||
c.id,
|
||||
c.title,
|
||||
c.created_at,
|
||||
(
|
||||
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
|
||||
FROM chat_members m
|
||||
WHERE m.chat_id = c.id
|
||||
)::uuid[] AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members visible ON visible.chat_id = c.id
|
||||
WHERE visible.user_id = $1
|
||||
AND (c.created_at, c.id) > ($2::timestamptz, $3::uuid)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4
|
||||
`
|
||||
|
||||
type ListChatsForMemberAfterParams struct {
|
||||
UserID uuid.UUID
|
||||
AfterCreatedAt time.Time
|
||||
AfterID uuid.UUID
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
type ListChatsForMemberAfterRow struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
CreatedAt time.Time
|
||||
MemberIds []uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) ListChatsForMemberAfter(ctx context.Context, arg ListChatsForMemberAfterParams) ([]ListChatsForMemberAfterRow, error) {
|
||||
rows, err := q.db.Query(ctx, listChatsForMemberAfter,
|
||||
arg.UserID,
|
||||
arg.AfterCreatedAt,
|
||||
arg.AfterID,
|
||||
arg.RowLimit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []ListChatsForMemberAfterRow{}
|
||||
for rows.Next() {
|
||||
var i ListChatsForMemberAfterRow
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.Title,
|
||||
&i.CreatedAt,
|
||||
&i.MemberIds,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listMissingUserIDs = `-- name: ListMissingUserIDs :many
|
||||
SELECT input.id::uuid AS missing_id
|
||||
FROM unnest($1::uuid[]) AS input(id)
|
||||
LEFT JOIN users u ON u.id = input.id
|
||||
WHERE u.id IS NULL
|
||||
`
|
||||
|
||||
func (q *Queries) ListMissingUserIDs(ctx context.Context, userIds []uuid.UUID) ([]uuid.UUID, error) {
|
||||
rows, err := q.db.Query(ctx, listMissingUserIDs, userIds)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []uuid.UUID{}
|
||||
for rows.Next() {
|
||||
var missing_id uuid.UUID
|
||||
if err := rows.Scan(&missing_id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, missing_id)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
|
||||
package sqlcgen
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
type DBTX interface {
|
||||
Exec(context.Context, string, ...interface{}) (pgconn.CommandTag, error)
|
||||
Query(context.Context, string, ...interface{}) (pgx.Rows, error)
|
||||
QueryRow(context.Context, string, ...interface{}) pgx.Row
|
||||
}
|
||||
|
||||
func New(db DBTX) *Queries {
|
||||
return &Queries{db: db}
|
||||
}
|
||||
|
||||
type Queries struct {
|
||||
db DBTX
|
||||
}
|
||||
|
||||
func (q *Queries) WithTx(tx pgx.Tx) *Queries {
|
||||
return &Queries{
|
||||
db: tx,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: idempotency.sql
|
||||
|
||||
package sqlcgen
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
const claimMessageIdempotency = `-- name: ClaimMessageIdempotency :one
|
||||
INSERT INTO message_idempotency (actor_id, chat_id, key, request_hash, expires_at)
|
||||
VALUES (
|
||||
$1,
|
||||
$2,
|
||||
$3,
|
||||
$4,
|
||||
$5
|
||||
)
|
||||
ON CONFLICT (actor_id, chat_id, key) DO UPDATE
|
||||
SET request_hash = EXCLUDED.request_hash,
|
||||
expires_at = EXCLUDED.expires_at,
|
||||
message_id = NULL
|
||||
WHERE message_idempotency.expires_at <= now()
|
||||
RETURNING key
|
||||
`
|
||||
|
||||
type ClaimMessageIdempotencyParams struct {
|
||||
ActorID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
Key string
|
||||
RequestHash []byte
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
// Claims the key for this actor/chat and returns whether this request owns it.
|
||||
// A live record wins: the statement returns nothing and the caller replays the
|
||||
// stored message. An expired record is replaced in place.
|
||||
func (q *Queries) ClaimMessageIdempotency(ctx context.Context, arg ClaimMessageIdempotencyParams) (string, error) {
|
||||
row := q.db.QueryRow(ctx, claimMessageIdempotency,
|
||||
arg.ActorID,
|
||||
arg.ChatID,
|
||||
arg.Key,
|
||||
arg.RequestHash,
|
||||
arg.ExpiresAt,
|
||||
)
|
||||
var key string
|
||||
err := row.Scan(&key)
|
||||
return key, err
|
||||
}
|
||||
|
||||
const completeMessageIdempotency = `-- name: CompleteMessageIdempotency :exec
|
||||
UPDATE message_idempotency
|
||||
SET message_id = $1
|
||||
WHERE actor_id = $2
|
||||
AND chat_id = $3
|
||||
AND key = $4
|
||||
`
|
||||
|
||||
type CompleteMessageIdempotencyParams struct {
|
||||
MessageID pgtype.UUID
|
||||
ActorID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
Key string
|
||||
}
|
||||
|
||||
func (q *Queries) CompleteMessageIdempotency(ctx context.Context, arg CompleteMessageIdempotencyParams) error {
|
||||
_, err := q.db.Exec(ctx, completeMessageIdempotency,
|
||||
arg.MessageID,
|
||||
arg.ActorID,
|
||||
arg.ChatID,
|
||||
arg.Key,
|
||||
)
|
||||
return err
|
||||
}
|
||||
|
||||
const getMessageByID = `-- name: GetMessageByID :one
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE id = $1
|
||||
`
|
||||
|
||||
func (q *Queries) GetMessageByID(ctx context.Context, id uuid.UUID) (Message, error) {
|
||||
row := q.db.QueryRow(ctx, getMessageByID, id)
|
||||
var i Message
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.SenderID,
|
||||
&i.Text,
|
||||
&i.CreatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getMessageIdempotency = `-- name: GetMessageIdempotency :one
|
||||
SELECT message_id, request_hash
|
||||
FROM message_idempotency
|
||||
WHERE actor_id = $1
|
||||
AND chat_id = $2
|
||||
AND key = $3
|
||||
FOR UPDATE
|
||||
`
|
||||
|
||||
type GetMessageIdempotencyParams struct {
|
||||
ActorID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
Key string
|
||||
}
|
||||
|
||||
type GetMessageIdempotencyRow struct {
|
||||
MessageID pgtype.UUID
|
||||
RequestHash []byte
|
||||
}
|
||||
|
||||
// Concurrent duplicates block here until the owner commits, then read the
|
||||
// result it stored in the same transaction.
|
||||
func (q *Queries) GetMessageIdempotency(ctx context.Context, arg GetMessageIdempotencyParams) (GetMessageIdempotencyRow, error) {
|
||||
row := q.db.QueryRow(ctx, getMessageIdempotency, arg.ActorID, arg.ChatID, arg.Key)
|
||||
var i GetMessageIdempotencyRow
|
||||
err := row.Scan(&i.MessageID, &i.RequestHash)
|
||||
return i, err
|
||||
}
|
||||
@@ -0,0 +1,160 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: messages.sql
|
||||
|
||||
package sqlcgen
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const createMessage = `-- name: CreateMessage :one
|
||||
INSERT INTO messages (chat_id, sender_id, text)
|
||||
SELECT $1, $2, $3
|
||||
WHERE EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = $1
|
||||
AND user_id = $2
|
||||
)
|
||||
RETURNING id, chat_id, sender_id, text, created_at
|
||||
`
|
||||
|
||||
type CreateMessageParams struct {
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
}
|
||||
|
||||
func (q *Queries) CreateMessage(ctx context.Context, arg CreateMessageParams) (Message, error) {
|
||||
row := q.db.QueryRow(ctx, createMessage, arg.ChatID, arg.SenderID, arg.Text)
|
||||
var i Message
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.SenderID,
|
||||
&i.Text,
|
||||
&i.CreatedAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const isChatMember = `-- name: IsChatMember :one
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = $1
|
||||
AND user_id = $2
|
||||
) AS is_member
|
||||
`
|
||||
|
||||
type IsChatMemberParams struct {
|
||||
ChatID uuid.UUID
|
||||
UserID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) IsChatMember(ctx context.Context, arg IsChatMemberParams) (bool, error) {
|
||||
row := q.db.QueryRow(ctx, isChatMember, arg.ChatID, arg.UserID)
|
||||
var is_member bool
|
||||
err := row.Scan(&is_member)
|
||||
return is_member, err
|
||||
}
|
||||
|
||||
const listMessagesForChat = `-- name: ListMessagesForChat :many
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
FROM messages m
|
||||
JOIN chat_members cm
|
||||
ON cm.chat_id = m.chat_id
|
||||
AND cm.user_id = $1
|
||||
WHERE m.chat_id = $2
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $3
|
||||
`
|
||||
|
||||
type ListMessagesForChatParams struct {
|
||||
CallerID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
func (q *Queries) ListMessagesForChat(ctx context.Context, arg ListMessagesForChatParams) ([]Message, error) {
|
||||
rows, err := q.db.Query(ctx, listMessagesForChat, arg.CallerID, arg.ChatID, arg.RowLimit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []Message{}
|
||||
for rows.Next() {
|
||||
var i Message
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.SenderID,
|
||||
&i.Text,
|
||||
&i.CreatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
const listMessagesForChatAfter = `-- name: ListMessagesForChatAfter :many
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
FROM messages m
|
||||
JOIN chat_members cm
|
||||
ON cm.chat_id = m.chat_id
|
||||
AND cm.user_id = $1
|
||||
WHERE m.chat_id = $2
|
||||
AND (m.created_at, m.id) > ($3::timestamptz, $4::uuid)
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $5
|
||||
`
|
||||
|
||||
type ListMessagesForChatAfterParams struct {
|
||||
CallerID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
AfterCreatedAt time.Time
|
||||
AfterID uuid.UUID
|
||||
RowLimit int32
|
||||
}
|
||||
|
||||
func (q *Queries) ListMessagesForChatAfter(ctx context.Context, arg ListMessagesForChatAfterParams) ([]Message, error) {
|
||||
rows, err := q.db.Query(ctx, listMessagesForChatAfter,
|
||||
arg.CallerID,
|
||||
arg.ChatID,
|
||||
arg.AfterCreatedAt,
|
||||
arg.AfterID,
|
||||
arg.RowLimit,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
items := []Message{}
|
||||
for rows.Next() {
|
||||
var i Message
|
||||
if err := rows.Scan(
|
||||
&i.ID,
|
||||
&i.ChatID,
|
||||
&i.SenderID,
|
||||
&i.Text,
|
||||
&i.CreatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, i)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
|
||||
package sqlcgen
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
)
|
||||
|
||||
type Attachment struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
OwnerID uuid.UUID
|
||||
ObjectKey string
|
||||
Filename string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
Sha256 string
|
||||
Status string
|
||||
ErrorCode pgtype.Text
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type Chat struct {
|
||||
ID uuid.UUID
|
||||
Title string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type ChatMember struct {
|
||||
ChatID uuid.UUID
|
||||
UserID uuid.UUID
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
SenderID uuid.UUID
|
||||
Text string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type MessageAttachment struct {
|
||||
MessageID uuid.UUID
|
||||
AttachmentID uuid.UUID
|
||||
Position int16
|
||||
}
|
||||
|
||||
type MessageIdempotency struct {
|
||||
ActorID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
Key string
|
||||
RequestHash []byte
|
||||
MessageID pgtype.UUID
|
||||
CreatedAt time.Time
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
TokenHash []byte
|
||||
UserID uuid.UUID
|
||||
ExpiresAt time.Time
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type User struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
PasswordHash string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type UserChatVersion struct {
|
||||
UserID uuid.UUID
|
||||
Version int64
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: sessions.sql
|
||||
|
||||
package sqlcgen
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const createSession = `-- name: CreateSession :one
|
||||
INSERT INTO sessions (token_hash, user_id, expires_at)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING token_hash, user_id, expires_at
|
||||
`
|
||||
|
||||
type CreateSessionParams struct {
|
||||
TokenHash []byte
|
||||
UserID uuid.UUID
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
type CreateSessionRow struct {
|
||||
TokenHash []byte
|
||||
UserID uuid.UUID
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) CreateSession(ctx context.Context, arg CreateSessionParams) (CreateSessionRow, error) {
|
||||
row := q.db.QueryRow(ctx, createSession, arg.TokenHash, arg.UserID, arg.ExpiresAt)
|
||||
var i CreateSessionRow
|
||||
err := row.Scan(&i.TokenHash, &i.UserID, &i.ExpiresAt)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const deleteSession = `-- name: DeleteSession :exec
|
||||
DELETE FROM sessions
|
||||
WHERE token_hash = $1
|
||||
AND user_id = $2
|
||||
`
|
||||
|
||||
type DeleteSessionParams struct {
|
||||
TokenHash []byte
|
||||
UserID uuid.UUID
|
||||
}
|
||||
|
||||
func (q *Queries) DeleteSession(ctx context.Context, arg DeleteSessionParams) error {
|
||||
_, err := q.db.Exec(ctx, deleteSession, arg.TokenHash, arg.UserID)
|
||||
return err
|
||||
}
|
||||
|
||||
const getSessionUser = `-- name: GetSessionUser :one
|
||||
SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = $1
|
||||
AND s.expires_at > now()
|
||||
`
|
||||
|
||||
type GetSessionUserRow struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
ExpiresAt time.Time
|
||||
}
|
||||
|
||||
func (q *Queries) GetSessionUser(ctx context.Context, tokenHash []byte) (GetSessionUserRow, error) {
|
||||
row := q.db.QueryRow(ctx, getSessionUser, tokenHash)
|
||||
var i GetSessionUserRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Username,
|
||||
&i.DisplayName,
|
||||
&i.CreatedAt,
|
||||
&i.ExpiresAt,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: users.sql
|
||||
|
||||
package sqlcgen
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const createUser = `-- name: CreateUser :one
|
||||
INSERT INTO users (username, display_name, password_hash)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING id, username, display_name, created_at, password_hash
|
||||
`
|
||||
|
||||
type CreateUserParams struct {
|
||||
Username string
|
||||
DisplayName string
|
||||
PasswordHash string
|
||||
}
|
||||
|
||||
type CreateUserRow struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
PasswordHash string
|
||||
}
|
||||
|
||||
func (q *Queries) CreateUser(ctx context.Context, arg CreateUserParams) (CreateUserRow, error) {
|
||||
row := q.db.QueryRow(ctx, createUser, arg.Username, arg.DisplayName, arg.PasswordHash)
|
||||
var i CreateUserRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Username,
|
||||
&i.DisplayName,
|
||||
&i.CreatedAt,
|
||||
&i.PasswordHash,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getUserByID = `-- name: GetUserByID :one
|
||||
SELECT id, username, display_name, created_at, password_hash
|
||||
FROM users
|
||||
WHERE id = $1
|
||||
`
|
||||
|
||||
type GetUserByIDRow struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
PasswordHash string
|
||||
}
|
||||
|
||||
func (q *Queries) GetUserByID(ctx context.Context, id uuid.UUID) (GetUserByIDRow, error) {
|
||||
row := q.db.QueryRow(ctx, getUserByID, id)
|
||||
var i GetUserByIDRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Username,
|
||||
&i.DisplayName,
|
||||
&i.CreatedAt,
|
||||
&i.PasswordHash,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
|
||||
const getUserByUsername = `-- name: GetUserByUsername :one
|
||||
SELECT id, username, display_name, created_at, password_hash
|
||||
FROM users
|
||||
WHERE username = $1
|
||||
`
|
||||
|
||||
type GetUserByUsernameRow struct {
|
||||
ID uuid.UUID
|
||||
Username string
|
||||
DisplayName string
|
||||
CreatedAt time.Time
|
||||
PasswordHash string
|
||||
}
|
||||
|
||||
func (q *Queries) GetUserByUsername(ctx context.Context, username string) (GetUserByUsernameRow, error) {
|
||||
row := q.db.QueryRow(ctx, getUserByUsername, username)
|
||||
var i GetUserByUsernameRow
|
||||
err := row.Scan(
|
||||
&i.ID,
|
||||
&i.Username,
|
||||
&i.DisplayName,
|
||||
&i.CreatedAt,
|
||||
&i.PasswordHash,
|
||||
)
|
||||
return i, err
|
||||
}
|
||||
@@ -0,0 +1,291 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/pressly/goose/v3"
|
||||
"github.com/stretchr/testify/require"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
"mtusi-messenger/internal/storage/postgres"
|
||||
"mtusi-messenger/internal/storage/postgres/migrations"
|
||||
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
)
|
||||
|
||||
const templateDB = "messenger_template"
|
||||
|
||||
var adminPool *pgxpool.Pool
|
||||
|
||||
func envOr(key, fallback string) string {
|
||||
if value := os.Getenv(key); value != "" {
|
||||
return value
|
||||
}
|
||||
|
||||
return fallback
|
||||
}
|
||||
|
||||
func envInt(key string, fallback int) int {
|
||||
value := os.Getenv(key)
|
||||
if value == "" {
|
||||
return fallback
|
||||
}
|
||||
|
||||
parsed, err := strconv.Atoi(value)
|
||||
if err != nil {
|
||||
return fallback
|
||||
}
|
||||
|
||||
return parsed
|
||||
}
|
||||
|
||||
func testConfig() config.Postgres {
|
||||
return config.Postgres{
|
||||
Host: envOr("TEST_POSTGRES_HOST", "localhost"),
|
||||
Port: envInt("TEST_POSTGRES_PORT", 5432),
|
||||
Database: envOr("TEST_POSTGRES_DATABASE", "messenger"),
|
||||
User: envOr("TEST_POSTGRES_USER", "messenger"),
|
||||
Password: envOr("TEST_POSTGRES_PASSWORD", "messenger"),
|
||||
SSLMode: envOr("TEST_POSTGRES_SSL_MODE", "disable"),
|
||||
MaxConns: 5,
|
||||
MinConns: 1,
|
||||
MaxConnLifetime: time.Hour,
|
||||
MaxConnIdleTime: 30 * time.Minute,
|
||||
ConnectTimeout: 5 * time.Second,
|
||||
QueryTimeout: 5 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
func dsnFor(database string) string {
|
||||
cfg := testConfig()
|
||||
cfg.Database = database
|
||||
|
||||
return cfg.DSN()
|
||||
}
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
ctx := context.Background()
|
||||
|
||||
var err error
|
||||
|
||||
adminPool, err = pgxpool.New(ctx, dsnFor(testConfig().Database))
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "admin pool:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if err := waitForDatabase(ctx, adminPool); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "database is not ready:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if err := recreateTemplate(ctx); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "create template:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
code := m.Run()
|
||||
|
||||
adminPool.Close()
|
||||
os.Exit(code)
|
||||
}
|
||||
|
||||
func waitForDatabase(ctx context.Context, pool *pgxpool.Pool) error {
|
||||
var lastErr error
|
||||
|
||||
for range 60 {
|
||||
err := pool.Ping(ctx)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
lastErr = err
|
||||
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
}
|
||||
|
||||
return lastErr
|
||||
}
|
||||
|
||||
func adminExec(ctx context.Context, query string) error {
|
||||
conn, err := adminPool.Acquire(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer conn.Release()
|
||||
|
||||
_, err = conn.Conn().PgConn().Exec(ctx, query).ReadAll()
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
const templateLockKey int64 = 0x6d657373656e6765
|
||||
|
||||
func withAdvisoryLock(ctx context.Context, shared bool, fn func() error) error {
|
||||
conn, err := adminPool.Acquire(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer conn.Release()
|
||||
|
||||
lock, unlock := "pg_advisory_lock", "pg_advisory_unlock"
|
||||
if shared {
|
||||
lock, unlock = "pg_advisory_lock_shared", "pg_advisory_unlock_shared"
|
||||
}
|
||||
|
||||
if _, err := conn.Exec(ctx, "SELECT "+lock+"($1)", templateLockKey); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() { _, _ = conn.Exec(context.WithoutCancel(ctx), "SELECT "+unlock+"($1)", templateLockKey) }()
|
||||
|
||||
return fn()
|
||||
}
|
||||
|
||||
func recreateTemplate(ctx context.Context) error {
|
||||
return withAdvisoryLock(ctx, false, func() error {
|
||||
if err := adminExec(ctx, "DROP DATABASE IF EXISTS "+templateDB+" WITH (FORCE)"); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := adminExec(ctx, "CREATE DATABASE "+templateDB); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
db, err := sql.Open("pgx", dsnFor(templateDB))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
defer func() { _ = db.Close() }()
|
||||
|
||||
if err := db.PingContext(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
goose.SetBaseFS(migrations.FS)
|
||||
|
||||
if err := goose.SetDialect("postgres"); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return goose.Up(db, ".")
|
||||
})
|
||||
}
|
||||
|
||||
type BaseSuite struct {
|
||||
suite.Suite
|
||||
|
||||
store *postgres.Store
|
||||
pool *pgxpool.Pool
|
||||
db string
|
||||
}
|
||||
|
||||
func (s *BaseSuite) SetupTest() {
|
||||
ctx := s.T().Context()
|
||||
s.db = "test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
|
||||
|
||||
s.Require().NoError(withAdvisoryLock(ctx, true, func() error {
|
||||
return adminExec(ctx, "CREATE DATABASE "+s.db+" TEMPLATE "+templateDB)
|
||||
}))
|
||||
|
||||
var err error
|
||||
|
||||
s.pool, err = pgxpool.New(ctx, dsnFor(s.db))
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.store = openStore(s.T(), s.db, nil)
|
||||
}
|
||||
|
||||
func (s *BaseSuite) TearDownTest() {
|
||||
if s.store != nil {
|
||||
s.store.Close()
|
||||
}
|
||||
|
||||
if s.pool != nil {
|
||||
s.pool.Close()
|
||||
}
|
||||
|
||||
if s.db != "" {
|
||||
s.Require().NoError(adminExec(s.T().Context(), "DROP DATABASE "+s.db+" WITH (FORCE)"))
|
||||
}
|
||||
}
|
||||
|
||||
const testIdempotencyTTL = 24 * time.Hour
|
||||
|
||||
func openStore(t *testing.T, database string, override func(*config.Postgres)) *postgres.Store {
|
||||
t.Helper()
|
||||
|
||||
return openStoreWithTTL(t, database, testIdempotencyTTL, override)
|
||||
}
|
||||
|
||||
func openStoreWithTTL(
|
||||
t *testing.T,
|
||||
database string,
|
||||
idempotencyTTL time.Duration,
|
||||
override func(*config.Postgres),
|
||||
) *postgres.Store {
|
||||
t.Helper()
|
||||
|
||||
cfg := testConfig()
|
||||
cfg.Database = database
|
||||
|
||||
if override != nil {
|
||||
override(&cfg)
|
||||
}
|
||||
|
||||
store, err := postgres.New(t.Context(), cfg, idempotencyTTL)
|
||||
require.NoError(t, err)
|
||||
|
||||
return store
|
||||
}
|
||||
|
||||
func (s *BaseSuite) createUser(username string) domain.User {
|
||||
s.T().Helper()
|
||||
|
||||
hash, err := password.Hash("strong-test-password")
|
||||
s.Require().NoError(err)
|
||||
|
||||
user, err := s.store.Users().Create(s.T().Context(), domain.NewUser{
|
||||
Username: username,
|
||||
DisplayName: "Пользователь " + username,
|
||||
PasswordHash: hash,
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
return user
|
||||
}
|
||||
|
||||
func (s *BaseSuite) createChat(owner domain.User, members ...domain.User) domain.Chat {
|
||||
s.T().Helper()
|
||||
|
||||
ids := []uuid.UUID{owner.ID}
|
||||
for _, member := range members {
|
||||
ids = append(ids, member.ID)
|
||||
}
|
||||
|
||||
chat, err := s.store.Chats().Create(s.T().Context(), domain.ChatDraft{
|
||||
Title: "Чат",
|
||||
MemberIDs: ids,
|
||||
CallerID: owner.ID,
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
return chat
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package postgres
|
||||
|
||||
import "time"
|
||||
|
||||
func toUTCTime(t time.Time) time.Time {
|
||||
if t.Location() == time.UTC {
|
||||
return t
|
||||
}
|
||||
|
||||
return t.UTC()
|
||||
}
|
||||
|
||||
func mapAll[S, D any](rows []S, mapRow func(S) D) []D {
|
||||
mapped := make([]D, 0, len(rows))
|
||||
|
||||
for _, row := range rows {
|
||||
mapped = append(mapped, mapRow(row))
|
||||
}
|
||||
|
||||
return mapped
|
||||
}
|
||||
@@ -0,0 +1,306 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgtype"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
|
||||
)
|
||||
|
||||
type MessageRepository struct {
|
||||
store *Store
|
||||
}
|
||||
|
||||
func (r *MessageRepository) IsChatMember(ctx context.Context, chatID, userID uuid.UUID) (bool, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
member, err := r.store.queries.IsChatMember(ctx, sqlcgen.IsChatMemberParams{
|
||||
ChatID: chatID,
|
||||
UserID: userID,
|
||||
})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("check chat membership: %w", mapError(err))
|
||||
}
|
||||
|
||||
return member, nil
|
||||
}
|
||||
|
||||
func (r *MessageRepository) Create(ctx context.Context, draft domain.MessageDraft) (domain.Message, error) {
|
||||
var created domain.Message
|
||||
|
||||
err := r.store.RunInTx(ctx, func(queries *sqlcgen.Queries) error {
|
||||
message, err := createIdempotent(ctx, queries, draft, r.store.idempotencyTTL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
created = message
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
// mapError нужен и здесь: отказ BEGIN/COMMIT (недоступная БД, исчерпанный
|
||||
// пул, истёкший контекст) обязан давать 503, а не 500.
|
||||
return domain.Message{}, fmt.Errorf("create message: %w", mapError(err))
|
||||
}
|
||||
|
||||
return created, nil
|
||||
}
|
||||
|
||||
// createIdempotent stores the message and its Idempotency-Key in one
|
||||
// transaction: either both are committed or neither, so a replay never observes
|
||||
// a claimed key whose message is missing. Claiming is a single statement, so
|
||||
// concurrent duplicates with the same key wait for the winner and then replay
|
||||
// the message it stored.
|
||||
func createIdempotent(
|
||||
ctx context.Context,
|
||||
queries *sqlcgen.Queries,
|
||||
draft domain.MessageDraft,
|
||||
ttl time.Duration,
|
||||
) (domain.Message, error) {
|
||||
_, err := queries.ClaimMessageIdempotency(ctx, sqlcgen.ClaimMessageIdempotencyParams{
|
||||
ActorID: draft.SenderID,
|
||||
ChatID: draft.ChatID,
|
||||
Key: draft.Idempotency.Key,
|
||||
RequestHash: draft.Idempotency.RequestHash[:],
|
||||
ExpiresAt: time.Now().Add(ttl),
|
||||
})
|
||||
|
||||
switch {
|
||||
case errors.Is(err, pgx.ErrNoRows): // the key is still live: replay it
|
||||
return replayIdempotent(ctx, queries, draft)
|
||||
case err != nil:
|
||||
return domain.Message{}, mapError(err)
|
||||
default:
|
||||
return createClaimed(ctx, queries, draft)
|
||||
}
|
||||
}
|
||||
|
||||
func createClaimed(ctx context.Context, queries *sqlcgen.Queries, draft domain.MessageDraft) (domain.Message, error) {
|
||||
row, err := queries.CreateMessage(ctx, sqlcgen.CreateMessageParams{
|
||||
ChatID: draft.ChatID,
|
||||
SenderID: draft.SenderID,
|
||||
Text: draft.Text,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Message{}, mapError(err)
|
||||
}
|
||||
|
||||
for position, attachmentID := range draft.AttachmentIDs {
|
||||
if err := queries.AttachToMessage(ctx, sqlcgen.AttachToMessageParams{
|
||||
MessageID: row.ID,
|
||||
AttachmentID: attachmentID,
|
||||
Position: int16(position),
|
||||
}); err != nil {
|
||||
return domain.Message{}, mapError(err)
|
||||
}
|
||||
}
|
||||
|
||||
err = queries.CompleteMessageIdempotency(ctx, sqlcgen.CompleteMessageIdempotencyParams{
|
||||
MessageID: pgtype.UUID{Bytes: row.ID, Valid: true},
|
||||
ActorID: draft.SenderID,
|
||||
ChatID: draft.ChatID,
|
||||
Key: draft.Idempotency.Key,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Message{}, mapError(err)
|
||||
}
|
||||
|
||||
created := mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt)
|
||||
created.AttachmentIDs = make([]uuid.UUID, 0, len(draft.AttachmentIDs))
|
||||
created.AttachmentIDs = append(created.AttachmentIDs, draft.AttachmentIDs...)
|
||||
|
||||
return created, nil
|
||||
}
|
||||
|
||||
func replayIdempotent(ctx context.Context, queries *sqlcgen.Queries, draft domain.MessageDraft) (domain.Message, error) {
|
||||
stored, err := queries.GetMessageIdempotency(ctx, sqlcgen.GetMessageIdempotencyParams{
|
||||
ActorID: draft.SenderID,
|
||||
ChatID: draft.ChatID,
|
||||
Key: draft.Idempotency.Key,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Message{}, mapError(err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(stored.RequestHash, draft.Idempotency.RequestHash[:]) {
|
||||
return domain.Message{}, domain.ErrIdempotency
|
||||
}
|
||||
|
||||
if !stored.MessageID.Valid {
|
||||
return domain.Message{}, errors.New("idempotency record without a message")
|
||||
}
|
||||
|
||||
row, err := queries.GetMessageByID(ctx, uuid.UUID(stored.MessageID.Bytes))
|
||||
if err != nil {
|
||||
return domain.Message{}, mapError(err)
|
||||
}
|
||||
|
||||
replayed := mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt)
|
||||
replayed.AttachmentIDs, err = listAttachmentIDs(ctx, queries, row.ID)
|
||||
if err != nil {
|
||||
return domain.Message{}, err
|
||||
}
|
||||
|
||||
return replayed, nil
|
||||
}
|
||||
|
||||
// listAttachmentIDs returns attachment IDs in the order the sender supplied
|
||||
// them. An empty result is normalised to an empty slice, never nil: the
|
||||
// contract marks attachment_ids as required.
|
||||
func listAttachmentIDs(
|
||||
ctx context.Context,
|
||||
queries *sqlcgen.Queries,
|
||||
messageID uuid.UUID,
|
||||
) ([]uuid.UUID, error) {
|
||||
rows, err := queries.ListMessageAttachments(ctx, []uuid.UUID{messageID})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list message attachments: %w", mapError(err))
|
||||
}
|
||||
|
||||
ids := make([]uuid.UUID, 0, len(rows))
|
||||
for _, row := range rows {
|
||||
ids = append(ids, row.AttachmentID)
|
||||
}
|
||||
|
||||
return ids, nil
|
||||
}
|
||||
|
||||
func (r *MessageRepository) ListVisible(
|
||||
ctx context.Context,
|
||||
chatID, callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Message], error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
limit = clampLimit(limit)
|
||||
fetch := int32(limit + 1) //nolint:gosec // limit is clamped to maxPageSize
|
||||
|
||||
messages, err := r.fetch(ctx, chatID, callerID, after, fetch)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, err
|
||||
}
|
||||
|
||||
if len(messages) == 0 {
|
||||
member, err := r.store.queries.IsChatMember(ctx, sqlcgen.IsChatMemberParams{
|
||||
ChatID: chatID,
|
||||
UserID: callerID,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Page[domain.Message]{}, fmt.Errorf("check chat membership: %w", mapError(err))
|
||||
}
|
||||
|
||||
if !member {
|
||||
return domain.Page[domain.Message]{}, fmt.Errorf(
|
||||
"%w: chat %s for user %s",
|
||||
domain.ErrNotFound, chatID, callerID,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
return buildPage(messages, limit, func(message domain.Message) domain.Cursor {
|
||||
return domain.Cursor{Scope: chatID, CreatedAt: message.CreatedAt, ID: message.ID}
|
||||
}), nil
|
||||
}
|
||||
|
||||
func (r *MessageRepository) fetch(
|
||||
ctx context.Context,
|
||||
chatID, callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
fetch int32,
|
||||
) ([]domain.Message, error) {
|
||||
var messages []domain.Message
|
||||
|
||||
if after == nil {
|
||||
rows, err := r.store.queries.ListMessagesForChat(ctx, sqlcgen.ListMessagesForChatParams{
|
||||
ChatID: chatID,
|
||||
CallerID: callerID,
|
||||
RowLimit: fetch,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list messages: %w", mapError(err))
|
||||
}
|
||||
|
||||
messages = mapAll(rows, mapMessageRow)
|
||||
} else {
|
||||
rows, err := r.store.queries.ListMessagesForChatAfter(ctx, sqlcgen.ListMessagesForChatAfterParams{
|
||||
ChatID: chatID,
|
||||
CallerID: callerID,
|
||||
AfterCreatedAt: after.CreatedAt,
|
||||
AfterID: after.ID,
|
||||
RowLimit: fetch,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list messages: %w", mapError(err))
|
||||
}
|
||||
|
||||
messages = mapAll(rows, mapMessageRow)
|
||||
}
|
||||
|
||||
if err := attachMessageLinks(ctx, r.store.queries, messages); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return messages, nil
|
||||
}
|
||||
|
||||
// attachMessageLinks fetches all links for a page in one query and normalises
|
||||
// absent lists to empty slices.
|
||||
func attachMessageLinks(
|
||||
ctx context.Context,
|
||||
queries *sqlcgen.Queries,
|
||||
messages []domain.Message,
|
||||
) error {
|
||||
if len(messages) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
ids := make([]uuid.UUID, 0, len(messages))
|
||||
for index := range messages {
|
||||
ids = append(ids, messages[index].ID)
|
||||
messages[index].AttachmentIDs = []uuid.UUID{}
|
||||
}
|
||||
|
||||
rows, err := queries.ListMessageAttachments(ctx, ids)
|
||||
if err != nil {
|
||||
return fmt.Errorf("list message attachments: %w", mapError(err))
|
||||
}
|
||||
|
||||
byMessage := make(map[uuid.UUID][]uuid.UUID, len(messages))
|
||||
for _, row := range rows {
|
||||
byMessage[row.MessageID] = append(byMessage[row.MessageID], row.AttachmentID)
|
||||
}
|
||||
|
||||
for index := range messages {
|
||||
if linked, ok := byMessage[messages[index].ID]; ok {
|
||||
messages[index].AttachmentIDs = linked
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func mapMessageRow(row sqlcgen.Message) domain.Message {
|
||||
return mapMessage(row.ID, row.ChatID, row.SenderID, row.Text, row.CreatedAt)
|
||||
}
|
||||
|
||||
func mapMessage(id, chatID, senderID uuid.UUID, text string, createdAt time.Time) domain.Message {
|
||||
return domain.Message{
|
||||
ID: id,
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
CreatedAt: toUTCTime(createdAt),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,161 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
type MessageRepositorySuite struct {
|
||||
BaseSuite
|
||||
}
|
||||
|
||||
func TestMessageRepositorySuite(t *testing.T) {
|
||||
suite.Run(t, new(MessageRepositorySuite))
|
||||
}
|
||||
|
||||
// draft builds a message draft with a fresh Idempotency-Key (lab3 contract).
|
||||
func (s *MessageRepositorySuite) draft(chatID, senderID uuid.UUID, text string) domain.MessageDraft {
|
||||
s.T().Helper()
|
||||
|
||||
key := uuid.NewString()
|
||||
|
||||
return domain.MessageDraft{
|
||||
ChatID: chatID,
|
||||
SenderID: senderID,
|
||||
Text: text,
|
||||
Idempotency: domain.MessageIdempotency{
|
||||
Key: key,
|
||||
RequestHash: sha256.Sum256([]byte(key + text)),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessageRepositorySuite) TestCreateAndPagination() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
|
||||
chat := s.createChat(alice, bob)
|
||||
|
||||
const total = 5
|
||||
for i := range total {
|
||||
message, err := s.store.Messages().Create(s.T().Context(), s.draft(chat.ID, alice.ID, fmt.Sprintf("сообщение %d", i)))
|
||||
s.Require().NoError(err)
|
||||
s.Equal(uuid.Version(7), message.ID.Version())
|
||||
s.False(message.CreatedAt.IsZero())
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, total)
|
||||
|
||||
var cursor *domain.Cursor
|
||||
|
||||
for {
|
||||
page, err := s.store.Messages().ListVisible(s.T().Context(), chat.ID, alice.ID, cursor, 2)
|
||||
s.Require().NoError(err)
|
||||
s.Require().NotEmpty(page.Items)
|
||||
|
||||
for _, message := range page.Items {
|
||||
_, duplicate := seen[message.ID]
|
||||
s.Require().False(duplicate, "keyset-пагинация не повторяет сообщения")
|
||||
seen[message.ID] = struct{}{}
|
||||
}
|
||||
|
||||
if page.Next == nil {
|
||||
break
|
||||
}
|
||||
|
||||
cursor = page.Next
|
||||
}
|
||||
|
||||
s.Len(seen, total)
|
||||
}
|
||||
|
||||
func (s *MessageRepositorySuite) TestPaginationWithSharedTimestamp() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
|
||||
for range 5 {
|
||||
_, err := s.store.Messages().Create(s.T().Context(), s.draft(chat.ID, alice.ID, "same timestamp"))
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
|
||||
_, err := s.pool.Exec(s.T().Context(), "UPDATE messages SET created_at = '2026-01-01 00:00:00+00'")
|
||||
s.Require().NoError(err)
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, 5)
|
||||
|
||||
var cursor *domain.Cursor
|
||||
|
||||
for {
|
||||
page, err := s.store.Messages().ListVisible(s.T().Context(), chat.ID, alice.ID, cursor, 2)
|
||||
s.Require().NoError(err)
|
||||
|
||||
for _, message := range page.Items {
|
||||
_, duplicate := seen[message.ID]
|
||||
s.Require().False(duplicate)
|
||||
seen[message.ID] = struct{}{}
|
||||
}
|
||||
|
||||
if page.Next == nil {
|
||||
break
|
||||
}
|
||||
|
||||
cursor = page.Next
|
||||
}
|
||||
|
||||
s.Len(seen, 5)
|
||||
}
|
||||
|
||||
func (s *MessageRepositorySuite) TestAccessIsRestricted() {
|
||||
alice := s.createUser("alice")
|
||||
bob := s.createUser("bob")
|
||||
|
||||
chat := s.createChat(alice)
|
||||
|
||||
_, err := s.store.Messages().Create(s.T().Context(), s.draft(chat.ID, bob.ID, "чужое"))
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound, "не участник не может писать в чат")
|
||||
|
||||
_, err = s.store.Messages().ListVisible(s.T().Context(), chat.ID, bob.ID, nil, 50)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound, "не участник не может читать историю")
|
||||
}
|
||||
|
||||
func (s *MessageRepositorySuite) TestListingForMissingChatReturnsNotFound() {
|
||||
alice := s.createUser("alice")
|
||||
|
||||
_, err := s.store.Messages().ListVisible(s.T().Context(), uuid.New(), alice.ID, nil, 50)
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *MessageRepositorySuite) TestFinishedMessageSurvivesConcurrentReads() {
|
||||
alice := s.createUser("alice")
|
||||
chat := s.createChat(alice)
|
||||
|
||||
const total = 20
|
||||
|
||||
var wg sync.WaitGroup
|
||||
|
||||
wg.Go(func() {
|
||||
for i := range total {
|
||||
_, err := s.store.Messages().Create(s.T().Context(), s.draft(chat.ID, alice.ID, fmt.Sprintf("message %d", i)))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
for range total {
|
||||
page, err := s.store.Messages().ListVisible(s.T().Context(), chat.ID, alice.ID, nil, 100)
|
||||
s.Require().NoError(err)
|
||||
s.LessOrEqual(len(page.Items), total)
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
-- +goose Up
|
||||
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY DEFAULT uuidv7(),
|
||||
username text NOT NULL,
|
||||
password_hash text NOT NULL,
|
||||
display_name text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
|
||||
CONSTRAINT users_username_key UNIQUE (username),
|
||||
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
CONSTRAINT users_display_name_not_blank CHECK (btrim(display_name) <> ''),
|
||||
CONSTRAINT users_display_name_length CHECK (char_length(display_name) BETWEEN 1 AND 100)
|
||||
);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY DEFAULT uuidv7(),
|
||||
title text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT chats_title_not_blank CHECK (btrim(title) <> '')
|
||||
);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY DEFAULT uuidv7(),
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
sender_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT,
|
||||
text text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
CONSTRAINT messages_text_not_blank CHECK (btrim(text) <> ''),
|
||||
CONSTRAINT messages_text_length CHECK (char_length(text) <= 4000)
|
||||
);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
token_hash bytea PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
expires_at timestamptz NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE TABLE user_chat_versions (
|
||||
user_id uuid PRIMARY KEY REFERENCES users (id) ON DELETE CASCADE,
|
||||
version bigint NOT NULL DEFAULT 0
|
||||
);
|
||||
|
||||
CREATE INDEX messages_chat_id_created_at_id_idx
|
||||
ON messages (chat_id, created_at, id);
|
||||
|
||||
CREATE INDEX chat_members_user_id_chat_id_idx
|
||||
ON chat_members (user_id, chat_id);
|
||||
|
||||
CREATE INDEX chats_created_at_id_idx
|
||||
ON chats (created_at, id);
|
||||
|
||||
CREATE INDEX sessions_user_id_idx
|
||||
ON sessions (user_id);
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP TABLE sessions;
|
||||
DROP TABLE messages;
|
||||
DROP TABLE chat_members;
|
||||
DROP TABLE chats;
|
||||
DROP TABLE users;
|
||||
DROP TABLE user_chat_versions;
|
||||
@@ -0,0 +1,25 @@
|
||||
-- +goose Up
|
||||
-- Версия 3, а не 2: в базе, перенесённой из лабораторной 2, goose уже содержит
|
||||
-- запись версии 2 (другая миграция того же репозитория), и одноимённый номер был
|
||||
-- бы молча пропущен при обновлении существующего стенда до ЛР3.
|
||||
|
||||
CREATE TABLE message_idempotency (
|
||||
actor_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
key text NOT NULL,
|
||||
request_hash bytea NOT NULL,
|
||||
message_id uuid REFERENCES messages (id) ON DELETE CASCADE,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
expires_at timestamptz NOT NULL,
|
||||
|
||||
PRIMARY KEY (actor_id, chat_id, key),
|
||||
CONSTRAINT message_idempotency_key_length CHECK (char_length(key) BETWEEN 1 AND 128)
|
||||
);
|
||||
|
||||
-- Expired records are replaced lazily by a new claim, the index keeps that
|
||||
-- lookup and a future sweep cheap.
|
||||
CREATE INDEX message_idempotency_expires_at_idx ON message_idempotency (expires_at);
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP TABLE message_idempotency;
|
||||
@@ -0,0 +1,55 @@
|
||||
-- +goose Up
|
||||
-- Attachment metadata lives in PostgreSQL; the original bytes live only in S3.
|
||||
CREATE TABLE attachments (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||
owner_id uuid NOT NULL REFERENCES users (id) ON DELETE RESTRICT,
|
||||
object_key text NOT NULL,
|
||||
filename text NOT NULL,
|
||||
content_type text NOT NULL,
|
||||
size_bytes bigint NOT NULL,
|
||||
sha256 text NOT NULL,
|
||||
status text NOT NULL,
|
||||
error_code text,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
|
||||
CONSTRAINT attachments_object_key_key UNIQUE (object_key),
|
||||
CONSTRAINT attachments_status_check CHECK (status IN ('pending', 'ready', 'failed')),
|
||||
CONSTRAINT attachments_content_type_check CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||
CONSTRAINT attachments_filename_length CHECK (char_length(filename) BETWEEN 1 AND 255),
|
||||
CONSTRAINT attachments_size_check CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||
CONSTRAINT attachments_sha256_check CHECK (sha256 ~ '^[0-9a-f]{64}$'),
|
||||
CONSTRAINT attachments_error_consistency CHECK (
|
||||
(status = 'ready' AND error_code IS NULL) OR
|
||||
(status = 'failed' AND error_code IS NOT NULL) OR
|
||||
status = 'pending'
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX attachments_chat_id_created_at_id_idx ON attachments (chat_id, created_at, id);
|
||||
CREATE INDEX attachments_status_created_at_idx ON attachments (status, created_at);
|
||||
|
||||
CREATE TABLE message_attachments (
|
||||
message_id uuid NOT NULL REFERENCES messages (id) ON DELETE CASCADE,
|
||||
attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE RESTRICT,
|
||||
position smallint NOT NULL,
|
||||
|
||||
PRIMARY KEY (message_id, attachment_id),
|
||||
CONSTRAINT message_attachments_position_check CHECK (position BETWEEN 0 AND 9),
|
||||
CONSTRAINT message_attachments_position_key UNIQUE (message_id, position)
|
||||
);
|
||||
|
||||
CREATE INDEX message_attachments_attachment_id_idx ON message_attachments (attachment_id);
|
||||
|
||||
-- Lab1-3 messages must stay valid. Attachment-only messages use text = '';
|
||||
-- the "text OR attachment" rule is enforced by the service and ogen.
|
||||
ALTER TABLE messages DROP CONSTRAINT messages_text_not_blank;
|
||||
|
||||
-- +goose Down
|
||||
-- WARNING: fails if attachment-only messages already exist. Roll back such
|
||||
-- rows or the constraint cannot be restored.
|
||||
ALTER TABLE messages ADD CONSTRAINT messages_text_not_blank CHECK (btrim(text) <> '');
|
||||
|
||||
DROP TABLE message_attachments;
|
||||
DROP TABLE attachments;
|
||||
@@ -0,0 +1,6 @@
|
||||
package migrations
|
||||
|
||||
import "embed"
|
||||
|
||||
//go:embed *.sql
|
||||
var FS embed.FS
|
||||
@@ -0,0 +1,25 @@
|
||||
package postgres
|
||||
|
||||
import "mtusi-messenger/internal/domain"
|
||||
|
||||
const (
|
||||
minPageSize = 1
|
||||
maxPageSize = 100
|
||||
)
|
||||
|
||||
func clampLimit(limit int) int {
|
||||
return min(max(limit, minPageSize), maxPageSize)
|
||||
}
|
||||
|
||||
func buildPage[T any](items []T, limit int, cursor func(item T) domain.Cursor) domain.Page[T] {
|
||||
if len(items) > limit {
|
||||
next := cursor(items[limit-1])
|
||||
|
||||
return domain.Page[T]{
|
||||
Items: append([]T(nil), items[:limit]...),
|
||||
Next: &next,
|
||||
}
|
||||
}
|
||||
|
||||
return domain.Page[T]{Items: append([]T(nil), items...)}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
-- name: CreateAttachment :one
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256, status
|
||||
)
|
||||
VALUES (
|
||||
sqlc.arg(id),
|
||||
sqlc.arg(chat_id),
|
||||
sqlc.arg(owner_id),
|
||||
sqlc.arg(object_key),
|
||||
sqlc.arg(filename),
|
||||
sqlc.arg(content_type),
|
||||
sqlc.arg(size_bytes),
|
||||
sqlc.arg(sha256),
|
||||
'pending'
|
||||
)
|
||||
RETURNING id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256,
|
||||
status, error_code, created_at, updated_at;
|
||||
|
||||
-- name: MarkAttachmentReady :one
|
||||
UPDATE attachments
|
||||
SET status = 'ready',
|
||||
object_key = sqlc.arg(object_key),
|
||||
updated_at = now()
|
||||
WHERE id = sqlc.arg(id)
|
||||
AND status = 'pending'
|
||||
RETURNING id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256,
|
||||
status, error_code, created_at, updated_at;
|
||||
|
||||
-- name: GetAttachmentForMember :one
|
||||
SELECT a.id, a.chat_id, a.owner_id, a.object_key, a.filename, a.content_type,
|
||||
a.size_bytes, a.sha256, a.status, a.error_code, a.created_at, a.updated_at
|
||||
FROM attachments a
|
||||
JOIN chat_members cm
|
||||
ON cm.chat_id = a.chat_id
|
||||
AND cm.user_id = sqlc.arg(user_id)
|
||||
WHERE a.id = sqlc.arg(id);
|
||||
|
||||
-- name: GetAttachmentForOwner :one
|
||||
SELECT a.id, a.chat_id, a.owner_id, a.object_key, a.filename, a.content_type,
|
||||
a.size_bytes, a.sha256, a.status, a.error_code, a.created_at, a.updated_at
|
||||
FROM attachments a
|
||||
JOIN chat_members cm
|
||||
ON cm.chat_id = a.chat_id
|
||||
AND cm.user_id = a.owner_id
|
||||
WHERE a.id = sqlc.arg(id)
|
||||
AND a.owner_id = sqlc.arg(owner_id);
|
||||
|
||||
-- name: ListAttachmentStatesForChat :many
|
||||
SELECT id, status
|
||||
FROM attachments
|
||||
WHERE chat_id = sqlc.arg(chat_id)
|
||||
AND id = ANY(sqlc.arg(ids)::uuid[]);
|
||||
|
||||
-- name: AttachToMessage :exec
|
||||
INSERT INTO message_attachments (message_id, attachment_id, position)
|
||||
VALUES (sqlc.arg(message_id), sqlc.arg(attachment_id), sqlc.arg(position));
|
||||
|
||||
-- name: ListMessageAttachments :many
|
||||
SELECT message_id, attachment_id
|
||||
FROM message_attachments
|
||||
WHERE message_id = ANY(sqlc.arg(message_ids)::uuid[])
|
||||
ORDER BY message_id, position;
|
||||
|
||||
-- name: DeletePendingAttachment :exec
|
||||
DELETE FROM attachments
|
||||
WHERE id = sqlc.arg(id)
|
||||
AND status = 'pending';
|
||||
|
||||
-- name: ListStalePendingAttachments :many
|
||||
SELECT id, chat_id, owner_id, object_key, filename, content_type, size_bytes, sha256,
|
||||
status, error_code, created_at, updated_at
|
||||
FROM attachments
|
||||
WHERE status = 'pending'
|
||||
AND created_at < sqlc.arg(created_before)
|
||||
ORDER BY created_at
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
|
||||
-- name: ListAttachmentKeys :many
|
||||
SELECT id, object_key, status, created_at
|
||||
FROM attachments
|
||||
ORDER BY id
|
||||
LIMIT sqlc.arg(row_limit) OFFSET sqlc.arg(row_offset);
|
||||
@@ -0,0 +1,75 @@
|
||||
-- name: CreateChat :one
|
||||
INSERT INTO chats (title)
|
||||
VALUES (sqlc.arg(title))
|
||||
RETURNING id, title, created_at;
|
||||
|
||||
-- name: AddChatMembers :exec
|
||||
INSERT INTO chat_members (chat_id, user_id)
|
||||
SELECT sqlc.arg(chat_id), members.member_id
|
||||
FROM unnest(sqlc.arg(user_ids)::uuid[]) AS members(member_id);
|
||||
|
||||
-- name: ListMissingUserIDs :many
|
||||
SELECT input.id::uuid AS missing_id
|
||||
FROM unnest(sqlc.arg(user_ids)::uuid[]) AS input(id)
|
||||
LEFT JOIN users u ON u.id = input.id
|
||||
WHERE u.id IS NULL;
|
||||
|
||||
-- name: BumpChatListVersions :exec
|
||||
INSERT INTO user_chat_versions (user_id, version)
|
||||
SELECT DISTINCT m, 1
|
||||
FROM unnest(sqlc.arg(user_ids)::uuid[]) AS m
|
||||
ORDER BY m
|
||||
ON CONFLICT (user_id) DO UPDATE SET version = user_chat_versions.version + 1;
|
||||
|
||||
-- name: GetChatListVersion :one
|
||||
SELECT COALESCE(MAX(version), 0)::bigint AS version
|
||||
FROM user_chat_versions
|
||||
WHERE user_id = sqlc.arg(user_id);
|
||||
|
||||
-- name: GetChatForMember :one
|
||||
SELECT
|
||||
c.id,
|
||||
c.title,
|
||||
c.created_at,
|
||||
(
|
||||
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
|
||||
FROM chat_members m
|
||||
WHERE m.chat_id = c.id
|
||||
)::uuid[] AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members visible
|
||||
ON visible.chat_id = c.id AND visible.user_id = sqlc.arg(user_id)
|
||||
WHERE c.id = sqlc.arg(id);
|
||||
|
||||
-- name: ListChatsForMember :many
|
||||
SELECT
|
||||
c.id,
|
||||
c.title,
|
||||
c.created_at,
|
||||
(
|
||||
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
|
||||
FROM chat_members m
|
||||
WHERE m.chat_id = c.id
|
||||
)::uuid[] AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members visible ON visible.chat_id = c.id
|
||||
WHERE visible.user_id = sqlc.arg(user_id)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
|
||||
-- name: ListChatsForMemberAfter :many
|
||||
SELECT
|
||||
c.id,
|
||||
c.title,
|
||||
c.created_at,
|
||||
(
|
||||
SELECT COALESCE(array_agg(m.user_id ORDER BY m.user_id), '{}')
|
||||
FROM chat_members m
|
||||
WHERE m.chat_id = c.id
|
||||
)::uuid[] AS member_ids
|
||||
FROM chats c
|
||||
JOIN chat_members visible ON visible.chat_id = c.id
|
||||
WHERE visible.user_id = sqlc.arg(user_id)
|
||||
AND (c.created_at, c.id) > (sqlc.arg(after_created_at)::timestamptz, sqlc.arg(after_id)::uuid)
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
@@ -0,0 +1,40 @@
|
||||
-- Claims the key for this actor/chat and returns whether this request owns it.
|
||||
-- A live record wins: the statement returns nothing and the caller replays the
|
||||
-- stored message. An expired record is replaced in place.
|
||||
-- name: ClaimMessageIdempotency :one
|
||||
INSERT INTO message_idempotency (actor_id, chat_id, key, request_hash, expires_at)
|
||||
VALUES (
|
||||
sqlc.arg(actor_id),
|
||||
sqlc.arg(chat_id),
|
||||
sqlc.arg(key),
|
||||
sqlc.arg(request_hash),
|
||||
sqlc.arg(expires_at)
|
||||
)
|
||||
ON CONFLICT (actor_id, chat_id, key) DO UPDATE
|
||||
SET request_hash = EXCLUDED.request_hash,
|
||||
expires_at = EXCLUDED.expires_at,
|
||||
message_id = NULL
|
||||
WHERE message_idempotency.expires_at <= now()
|
||||
RETURNING key;
|
||||
|
||||
-- Concurrent duplicates block here until the owner commits, then read the
|
||||
-- result it stored in the same transaction.
|
||||
-- name: GetMessageIdempotency :one
|
||||
SELECT message_id, request_hash
|
||||
FROM message_idempotency
|
||||
WHERE actor_id = sqlc.arg(actor_id)
|
||||
AND chat_id = sqlc.arg(chat_id)
|
||||
AND key = sqlc.arg(key)
|
||||
FOR UPDATE;
|
||||
|
||||
-- name: CompleteMessageIdempotency :exec
|
||||
UPDATE message_idempotency
|
||||
SET message_id = sqlc.arg(message_id)
|
||||
WHERE actor_id = sqlc.arg(actor_id)
|
||||
AND chat_id = sqlc.arg(chat_id)
|
||||
AND key = sqlc.arg(key);
|
||||
|
||||
-- name: GetMessageByID :one
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE id = sqlc.arg(id);
|
||||
@@ -0,0 +1,39 @@
|
||||
-- name: CreateMessage :one
|
||||
INSERT INTO messages (chat_id, sender_id, text)
|
||||
SELECT sqlc.arg(chat_id), sqlc.arg(sender_id), sqlc.arg(text)
|
||||
WHERE EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = sqlc.arg(chat_id)
|
||||
AND user_id = sqlc.arg(sender_id)
|
||||
)
|
||||
RETURNING id, chat_id, sender_id, text, created_at;
|
||||
|
||||
-- name: IsChatMember :one
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = sqlc.arg(chat_id)
|
||||
AND user_id = sqlc.arg(user_id)
|
||||
) AS is_member;
|
||||
|
||||
-- name: ListMessagesForChat :many
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
FROM messages m
|
||||
JOIN chat_members cm
|
||||
ON cm.chat_id = m.chat_id
|
||||
AND cm.user_id = sqlc.arg(caller_id)
|
||||
WHERE m.chat_id = sqlc.arg(chat_id)
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
|
||||
-- name: ListMessagesForChatAfter :many
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
FROM messages m
|
||||
JOIN chat_members cm
|
||||
ON cm.chat_id = m.chat_id
|
||||
AND cm.user_id = sqlc.arg(caller_id)
|
||||
WHERE m.chat_id = sqlc.arg(chat_id)
|
||||
AND (m.created_at, m.id) > (sqlc.arg(after_created_at)::timestamptz, sqlc.arg(after_id)::uuid)
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
@@ -0,0 +1,16 @@
|
||||
-- name: CreateSession :one
|
||||
INSERT INTO sessions (token_hash, user_id, expires_at)
|
||||
VALUES (sqlc.arg(token_hash), sqlc.arg(user_id), sqlc.arg(expires_at))
|
||||
RETURNING token_hash, user_id, expires_at;
|
||||
|
||||
-- name: GetSessionUser :one
|
||||
SELECT u.id, u.username, u.display_name, u.created_at, s.expires_at
|
||||
FROM sessions s
|
||||
JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = sqlc.arg(token_hash)
|
||||
AND s.expires_at > now();
|
||||
|
||||
-- name: DeleteSession :exec
|
||||
DELETE FROM sessions
|
||||
WHERE token_hash = sqlc.arg(token_hash)
|
||||
AND user_id = sqlc.arg(user_id);
|
||||
@@ -0,0 +1,14 @@
|
||||
-- name: CreateUser :one
|
||||
INSERT INTO users (username, display_name, password_hash)
|
||||
VALUES (sqlc.arg(username), sqlc.arg(display_name), sqlc.arg(password_hash))
|
||||
RETURNING id, username, display_name, created_at, password_hash;
|
||||
|
||||
-- name: GetUserByID :one
|
||||
SELECT id, username, display_name, created_at, password_hash
|
||||
FROM users
|
||||
WHERE id = sqlc.arg(id);
|
||||
|
||||
-- name: GetUserByUsername :one
|
||||
SELECT id, username, display_name, created_at, password_hash
|
||||
FROM users
|
||||
WHERE username = sqlc.arg(username);
|
||||
@@ -0,0 +1,94 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
|
||||
)
|
||||
|
||||
type SessionRepository struct {
|
||||
store *Store
|
||||
}
|
||||
|
||||
func (r *SessionRepository) Credentials(ctx context.Context, username string) (domain.UserCredentials, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
row, err := r.store.queries.GetUserByUsername(ctx, username)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.UserCredentials{}, fmt.Errorf("%w: username %q", domain.ErrUnauthenticated, username)
|
||||
}
|
||||
|
||||
return domain.UserCredentials{}, fmt.Errorf("load credentials: %w", mapError(err))
|
||||
}
|
||||
|
||||
return domain.UserCredentials{
|
||||
User: domain.User{
|
||||
ID: row.ID,
|
||||
Username: row.Username,
|
||||
DisplayName: row.DisplayName,
|
||||
CreatedAt: toUTCTime(row.CreatedAt),
|
||||
},
|
||||
PasswordHash: row.PasswordHash,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *SessionRepository) Create(ctx context.Context, session domain.NewSession) (domain.Session, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
row, err := r.store.queries.CreateSession(ctx, sqlcgen.CreateSessionParams{
|
||||
TokenHash: session.TokenHash,
|
||||
UserID: session.UserID,
|
||||
ExpiresAt: session.ExpiresAt,
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Session{}, fmt.Errorf("create session: %w", mapError(err))
|
||||
}
|
||||
|
||||
return domain.Session{ExpiresAt: toUTCTime(row.ExpiresAt)}, nil
|
||||
}
|
||||
|
||||
func (r *SessionRepository) Resolve(ctx context.Context, tokenHash []byte) (domain.Session, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
row, err := r.store.queries.GetSessionUser(ctx, tokenHash)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return domain.Session{}, fmt.Errorf("%w: session not found or expired", domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
return domain.Session{}, fmt.Errorf("resolve session: %w", mapError(err))
|
||||
}
|
||||
|
||||
return domain.Session{
|
||||
ExpiresAt: toUTCTime(row.ExpiresAt),
|
||||
User: domain.User{
|
||||
ID: row.ID,
|
||||
Username: row.Username,
|
||||
DisplayName: row.DisplayName,
|
||||
CreatedAt: toUTCTime(row.CreatedAt),
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *SessionRepository) Revoke(ctx context.Context, userID uuid.UUID, tokenHash []byte) error {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
if err := r.store.queries.DeleteSession(
|
||||
ctx, sqlcgen.DeleteSessionParams{TokenHash: tokenHash, UserID: userID},
|
||||
); err != nil {
|
||||
return fmt.Errorf("revoke session: %w", mapError(err))
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
"mtusi-messenger/internal/platform/token"
|
||||
)
|
||||
|
||||
type SessionRepositorySuite struct {
|
||||
BaseSuite
|
||||
}
|
||||
|
||||
func TestSessionRepositorySuite(t *testing.T) {
|
||||
suite.Run(t, new(SessionRepositorySuite))
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) TestCredentials() {
|
||||
alice := s.createUser("alice")
|
||||
|
||||
credentials, err := s.store.Sessions().Credentials(s.T().Context(), "alice")
|
||||
s.Require().NoError(err)
|
||||
s.Equal(alice.ID, credentials.User.ID)
|
||||
s.True(password.Verify("strong-test-password", credentials.PasswordHash))
|
||||
s.False(password.Verify("wrong-password-value", credentials.PasswordHash))
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) TestCredentialsUnknownUser() {
|
||||
_, err := s.store.Sessions().Credentials(s.T().Context(), "nobody")
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) TestCreateResolveRevoke() {
|
||||
alice := s.createUser("alice")
|
||||
|
||||
_, hash, err := token.New().Generate()
|
||||
s.Require().NoError(err)
|
||||
|
||||
expiresAt := time.Now().UTC().Add(time.Hour).Truncate(time.Microsecond)
|
||||
|
||||
created, err := s.store.Sessions().Create(s.T().Context(), domain.NewSession{
|
||||
TokenHash: hash,
|
||||
UserID: alice.ID,
|
||||
ExpiresAt: expiresAt,
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
s.Equal(expiresAt, created.ExpiresAt)
|
||||
|
||||
resolved, err := s.store.Sessions().Resolve(s.T().Context(), hash)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(alice.ID, resolved.User.ID)
|
||||
s.Equal(created.ExpiresAt, resolved.ExpiresAt)
|
||||
|
||||
s.Require().NoError(s.store.Sessions().Revoke(s.T().Context(), alice.ID, hash))
|
||||
|
||||
_, err = s.store.Sessions().Resolve(s.T().Context(), hash)
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
}
|
||||
|
||||
func (s *SessionRepositorySuite) TestResolveRejectsExpiredToken() {
|
||||
alice := s.createUser("alice")
|
||||
|
||||
_, hash, err := token.New().Generate()
|
||||
s.Require().NoError(err)
|
||||
|
||||
_, err = s.store.Sessions().Create(s.T().Context(), domain.NewSession{
|
||||
TokenHash: hash,
|
||||
UserID: alice.ID,
|
||||
ExpiresAt: time.Now().UTC().Add(-time.Minute),
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
_, err = s.store.Sessions().Resolve(s.T().Context(), hash)
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
queries *sqlcgen.Queries
|
||||
queryTimeout time.Duration
|
||||
idempotencyTTL time.Duration
|
||||
|
||||
users *UserRepository
|
||||
chats *ChatRepository
|
||||
messages *MessageRepository
|
||||
sessions *SessionRepository
|
||||
attachments *AttachmentRepository
|
||||
}
|
||||
|
||||
func New(ctx context.Context, cfg config.Postgres, idempotencyTTL time.Duration) (*Store, error) {
|
||||
cfg, err := normalize(cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("normalize database config: %w", err)
|
||||
}
|
||||
|
||||
poolCfg, err := pgxpool.ParseConfig(cfg.DSN())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse database dsn: %w", err)
|
||||
}
|
||||
|
||||
poolCfg.MaxConns = cfg.MaxConns
|
||||
poolCfg.MinConns = cfg.MinConns
|
||||
poolCfg.MaxConnLifetime = cfg.MaxConnLifetime
|
||||
poolCfg.MaxConnIdleTime = cfg.MaxConnIdleTime
|
||||
poolCfg.ConnConfig.ConnectTimeout = cfg.ConnectTimeout
|
||||
|
||||
pool, err := pgxpool.NewWithConfig(ctx, poolCfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create pool: %w", err)
|
||||
}
|
||||
|
||||
pingCtx, cancel := context.WithTimeout(ctx, cfg.ConnectTimeout)
|
||||
defer cancel()
|
||||
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
pool.Close()
|
||||
|
||||
return nil, fmt.Errorf("ping database: %w", err)
|
||||
}
|
||||
|
||||
store := &Store{
|
||||
pool: pool,
|
||||
queries: sqlcgen.New(pool),
|
||||
queryTimeout: cfg.QueryTimeout,
|
||||
idempotencyTTL: idempotencyTTL,
|
||||
}
|
||||
|
||||
store.users = &UserRepository{store: store}
|
||||
store.chats = &ChatRepository{store: store}
|
||||
store.messages = &MessageRepository{store: store}
|
||||
store.sessions = &SessionRepository{store: store}
|
||||
store.attachments = &AttachmentRepository{store: store}
|
||||
|
||||
return store, nil
|
||||
}
|
||||
|
||||
func (s *Store) Users() *UserRepository { return s.users }
|
||||
|
||||
func (s *Store) Chats() *ChatRepository { return s.chats }
|
||||
|
||||
func (s *Store) Messages() *MessageRepository { return s.messages }
|
||||
|
||||
func (s *Store) Sessions() *SessionRepository { return s.sessions }
|
||||
|
||||
func (s *Store) Attachments() *AttachmentRepository { return s.attachments }
|
||||
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
if err := s.pool.Ping(ctx); err != nil {
|
||||
return fmt.Errorf("ping database: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) Close() { s.pool.Close() }
|
||||
|
||||
// sweepLockKey is a process-independent constant: every replica contends for the
|
||||
// same PostgreSQL session lock, so only one sweeper runs at a time.
|
||||
const sweepLockKey int64 = 0x4c414234 // "LAB4"
|
||||
|
||||
// AcquireSweepLock holds a session-level advisory lock on a dedicated
|
||||
// connection. The returned release function must be called on that same
|
||||
// connection before it is returned to the pool.
|
||||
func (s *Store) AcquireSweepLock(ctx context.Context) (func(), bool, error) {
|
||||
conn, err := s.pool.Acquire(ctx)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("acquire sweep connection: %w", err)
|
||||
}
|
||||
|
||||
var acquired bool
|
||||
if err := conn.QueryRow(ctx, "SELECT pg_try_advisory_lock($1)", sweepLockKey).Scan(&acquired); err != nil {
|
||||
conn.Release()
|
||||
|
||||
return nil, false, fmt.Errorf("acquire sweep lock: %w", err)
|
||||
}
|
||||
|
||||
if !acquired {
|
||||
conn.Release()
|
||||
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
release := func() {
|
||||
unlockCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
_, _ = conn.Exec(unlockCtx, "SELECT pg_advisory_unlock($1)", sweepLockKey)
|
||||
conn.Release()
|
||||
}
|
||||
|
||||
return release, true, nil
|
||||
}
|
||||
|
||||
func (s *Store) timeout(ctx context.Context) (context.Context, context.CancelFunc) {
|
||||
if s.queryTimeout <= 0 {
|
||||
return context.WithCancel(ctx)
|
||||
}
|
||||
|
||||
return context.WithTimeout(ctx, s.queryTimeout)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
|
||||
)
|
||||
|
||||
func (s *Store) RunInTx(ctx context.Context, fn func(queries *sqlcgen.Queries) error) error {
|
||||
ctx, cancel := s.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin transaction: %w", err)
|
||||
}
|
||||
|
||||
defer func() { _ = tx.Rollback(ctx) }()
|
||||
|
||||
if err := fn(s.queries.WithTx(tx)); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit transaction: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/storage/postgres/internal/sqlcgen"
|
||||
)
|
||||
|
||||
type UserRepository struct {
|
||||
store *Store
|
||||
}
|
||||
|
||||
func (r *UserRepository) Create(ctx context.Context, draft domain.NewUser) (domain.User, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
row, err := r.store.queries.CreateUser(ctx, sqlcgen.CreateUserParams{
|
||||
Username: draft.Username,
|
||||
DisplayName: draft.DisplayName,
|
||||
PasswordHash: draft.PasswordHash,
|
||||
})
|
||||
if err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
return domain.User{}, fmt.Errorf("%w: username %q", domain.ErrUsernameTaken, draft.Username)
|
||||
}
|
||||
|
||||
return domain.User{}, fmt.Errorf("create user: %w", mapError(err))
|
||||
}
|
||||
|
||||
return domain.User{
|
||||
ID: row.ID,
|
||||
Username: row.Username,
|
||||
DisplayName: row.DisplayName,
|
||||
CreatedAt: toUTCTime(row.CreatedAt),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetByID(ctx context.Context, id uuid.UUID) (domain.User, error) {
|
||||
ctx, cancel := r.store.timeout(ctx)
|
||||
defer cancel()
|
||||
|
||||
row, err := r.store.queries.GetUserByID(ctx, id)
|
||||
if err != nil {
|
||||
mapped := mapError(err)
|
||||
if errors.Is(mapped, domain.ErrNotFound) {
|
||||
return domain.User{}, fmt.Errorf("%w: user %s", domain.ErrNotFound, id)
|
||||
}
|
||||
|
||||
return domain.User{}, fmt.Errorf("get user: %w", mapped)
|
||||
}
|
||||
|
||||
return domain.User{
|
||||
ID: row.ID,
|
||||
Username: row.Username,
|
||||
DisplayName: row.DisplayName,
|
||||
CreatedAt: toUTCTime(row.CreatedAt),
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
)
|
||||
|
||||
type UserRepositorySuite struct {
|
||||
BaseSuite
|
||||
}
|
||||
|
||||
func TestUserRepositorySuite(t *testing.T) {
|
||||
suite.Run(t, new(UserRepositorySuite))
|
||||
}
|
||||
|
||||
func (s *UserRepositorySuite) TestCreateAndLookup() {
|
||||
created := s.createUser("alice")
|
||||
s.NotEqual(uuid.Nil, created.ID)
|
||||
s.Equal(uuid.Version(7), created.ID.Version())
|
||||
s.Equal("alice", created.Username)
|
||||
s.False(created.CreatedAt.IsZero())
|
||||
|
||||
found, err := s.store.Users().GetByID(s.T().Context(), created.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(created, found)
|
||||
|
||||
_, err = s.store.Users().GetByID(s.T().Context(), uuid.New())
|
||||
s.Require().ErrorIs(err, domain.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *UserRepositorySuite) TestDuplicateUsernameConflicts() {
|
||||
s.createUser("alice")
|
||||
|
||||
hash, err := password.Hash("strong-test-password")
|
||||
s.Require().NoError(err)
|
||||
|
||||
_, err = s.store.Users().Create(s.T().Context(), domain.NewUser{
|
||||
Username: "alice",
|
||||
DisplayName: "Другая Алиса",
|
||||
PasswordHash: hash,
|
||||
})
|
||||
s.Require().ErrorIs(err, domain.ErrUsernameTaken)
|
||||
}
|
||||
|
||||
func (s *UserRepositorySuite) TestConcurrentRegistrationCreatesSingleUser() {
|
||||
hash, err := password.Hash("strong-test-password")
|
||||
s.Require().NoError(err)
|
||||
|
||||
const attempts = 8
|
||||
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
mu sync.Mutex
|
||||
successes int
|
||||
failures []error
|
||||
)
|
||||
|
||||
for range attempts {
|
||||
wg.Go(func() {
|
||||
_, err := s.store.Users().Create(s.T().Context(), domain.NewUser{
|
||||
Username: "racer",
|
||||
DisplayName: "Racer",
|
||||
PasswordHash: hash,
|
||||
})
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
if err == nil {
|
||||
successes++
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
failures = append(failures, err)
|
||||
})
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
s.Equal(1, successes, "ровно одна регистрация выигрывает гонку")
|
||||
s.Len(failures, attempts-1)
|
||||
|
||||
for _, failure := range failures {
|
||||
ok := errors.Is(failure, domain.ErrUsernameTaken) || errors.Is(failure, domain.ErrConflict)
|
||||
s.True(ok, "проигравшая регистрация должна давать конфликт, получено: %v", failure)
|
||||
}
|
||||
|
||||
var count int
|
||||
s.Require().NoError(s.pool.QueryRow(s.T().Context(), "SELECT count(*) FROM users WHERE username = 'racer'").Scan(&count))
|
||||
s.Equal(1, count)
|
||||
}
|
||||
|
||||
func (s *UserRepositorySuite) TestQueryTimeoutReturnsError() {
|
||||
store := openStore(s.T(), s.db, func(cfg *config.Postgres) {
|
||||
cfg.QueryTimeout = time.Nanosecond
|
||||
})
|
||||
defer store.Close()
|
||||
|
||||
_, err := store.Users().GetByID(s.T().Context(), uuid.New())
|
||||
s.Require().Error(err)
|
||||
s.NotErrorIs(err, domain.ErrNotFound)
|
||||
}
|
||||
@@ -0,0 +1,183 @@
|
||||
package redis
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/cache"
|
||||
)
|
||||
|
||||
type ChatSource interface {
|
||||
Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error)
|
||||
GetVisible(ctx context.Context, chatID, callerID uuid.UUID) (domain.Chat, error)
|
||||
ListVersion(ctx context.Context, userID uuid.UUID) (int64, error)
|
||||
ListVisible(
|
||||
ctx context.Context,
|
||||
callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Chat], error)
|
||||
}
|
||||
|
||||
type ChatRepository struct {
|
||||
source ChatSource
|
||||
cache *cache.DistributedCache
|
||||
ttl time.Duration
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func NewChatRepository(
|
||||
source ChatSource,
|
||||
cache *cache.DistributedCache,
|
||||
ttl time.Duration,
|
||||
log *slog.Logger,
|
||||
) *ChatRepository {
|
||||
return &ChatRepository{source: source, cache: cache, ttl: ttl, log: log}
|
||||
}
|
||||
|
||||
func (r *ChatRepository) Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error) {
|
||||
return r.source.Create(ctx, draft)
|
||||
}
|
||||
|
||||
func (r *ChatRepository) GetVisible(ctx context.Context, chatID, callerID uuid.UUID) (domain.Chat, error) {
|
||||
return r.source.GetVisible(ctx, chatID, callerID)
|
||||
}
|
||||
|
||||
type sourceError struct{ err error }
|
||||
|
||||
func (e sourceError) Error() string { return e.err.Error() }
|
||||
|
||||
func (e sourceError) Unwrap() error { return e.err }
|
||||
|
||||
const cacheOperationTimeout = 500 * time.Millisecond
|
||||
|
||||
func (r *ChatRepository) ListVisible(
|
||||
ctx context.Context,
|
||||
callerID uuid.UUID,
|
||||
after *domain.Cursor,
|
||||
limit int,
|
||||
) (domain.Page[domain.Chat], error) {
|
||||
if after != nil {
|
||||
return r.source.ListVisible(ctx, callerID, after, limit)
|
||||
}
|
||||
|
||||
version, err := r.source.ListVersion(ctx, callerID)
|
||||
if err != nil {
|
||||
return domain.Page[domain.Chat]{}, fmt.Errorf("chat list version: %w", err)
|
||||
}
|
||||
|
||||
key := chatListKey(callerID, version, limit)
|
||||
|
||||
loader := func(ctx context.Context) ([]byte, error) {
|
||||
page, err := r.source.ListVisible(ctx, callerID, nil, limit)
|
||||
if err != nil {
|
||||
return nil, sourceError{err}
|
||||
}
|
||||
|
||||
return json.Marshal(newChatPageDTO(page))
|
||||
}
|
||||
|
||||
cctx, cancel := context.WithTimeout(ctx, cacheOperationTimeout)
|
||||
defer cancel()
|
||||
|
||||
encoded, err := r.cache.GetOrLoad(cctx, key, r.ttl, loader)
|
||||
if err != nil {
|
||||
var sourceErr sourceError
|
||||
switch {
|
||||
case errors.As(err, &sourceErr):
|
||||
return domain.Page[domain.Chat]{}, sourceErr.err
|
||||
case ctx.Err() != nil:
|
||||
return domain.Page[domain.Chat]{}, ctx.Err()
|
||||
}
|
||||
} else {
|
||||
var dto chatPageDTO
|
||||
unmarshalErr := json.Unmarshal(encoded, &dto)
|
||||
if unmarshalErr == nil {
|
||||
return dto.toDomain(), nil
|
||||
}
|
||||
err = unmarshalErr
|
||||
|
||||
_ = r.cache.Delete(ctx, key)
|
||||
}
|
||||
|
||||
if r.log != nil {
|
||||
r.log.WarnContext(ctx, "chat list cache unavailable, falling back to source", slog.Any("error", err))
|
||||
}
|
||||
|
||||
return r.source.ListVisible(ctx, callerID, nil, limit)
|
||||
}
|
||||
|
||||
func chatListKey(userID uuid.UUID, version int64, limit int) string {
|
||||
return fmt.Sprintf("chat_list:%s:%d:%d", userID, version, limit)
|
||||
}
|
||||
|
||||
type chatPageDTO struct {
|
||||
Items []chatDTO `json:"items"`
|
||||
Next *cursorDTO `json:"next,omitempty"`
|
||||
}
|
||||
|
||||
type chatDTO struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []uuid.UUID `json:"member_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type cursorDTO struct {
|
||||
Scope uuid.UUID `json:"scope"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
ID uuid.UUID `json:"id"`
|
||||
}
|
||||
|
||||
func newChatPageDTO(page domain.Page[domain.Chat]) chatPageDTO {
|
||||
items := make([]chatDTO, 0, len(page.Items))
|
||||
for _, chat := range page.Items {
|
||||
items = append(items, chatDTO{
|
||||
ID: chat.ID,
|
||||
Title: chat.Title,
|
||||
MemberIDs: chat.MemberIDs,
|
||||
CreatedAt: chat.CreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
var next *cursorDTO
|
||||
if page.Next != nil {
|
||||
next = &cursorDTO{
|
||||
Scope: page.Next.Scope,
|
||||
CreatedAt: page.Next.CreatedAt,
|
||||
ID: page.Next.ID,
|
||||
}
|
||||
}
|
||||
|
||||
return chatPageDTO{Items: items, Next: next}
|
||||
}
|
||||
|
||||
func (d chatPageDTO) toDomain() domain.Page[domain.Chat] {
|
||||
items := make([]domain.Chat, 0, len(d.Items))
|
||||
for _, chat := range d.Items {
|
||||
items = append(items, domain.Chat{
|
||||
ID: chat.ID,
|
||||
Title: chat.Title,
|
||||
MemberIDs: chat.MemberIDs,
|
||||
CreatedAt: chat.CreatedAt,
|
||||
})
|
||||
}
|
||||
|
||||
var next *domain.Cursor
|
||||
if d.Next != nil {
|
||||
next = &domain.Cursor{
|
||||
Scope: d.Next.Scope,
|
||||
CreatedAt: d.Next.CreatedAt,
|
||||
ID: d.Next.ID,
|
||||
}
|
||||
}
|
||||
|
||||
return domain.Page[domain.Chat]{Items: items, Next: next}
|
||||
}
|
||||
@@ -0,0 +1,428 @@
|
||||
//go:build integration
|
||||
|
||||
package redis_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/cache"
|
||||
cachemocks "mtusi-messenger/internal/platform/cache/mocks"
|
||||
storageredis "mtusi-messenger/internal/storage/redis"
|
||||
storagemocks "mtusi-messenger/internal/storage/redis/mocks"
|
||||
)
|
||||
|
||||
type ChatRepositorySuite struct {
|
||||
suite.Suite
|
||||
|
||||
cache *cache.RedisCache
|
||||
}
|
||||
|
||||
func TestChatRepositorySuite(t *testing.T) {
|
||||
suite.Run(t, new(ChatRepositorySuite))
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) SetupSuite() {
|
||||
var err error
|
||||
|
||||
s.cache, err = cache.NewRedis(testRedisConfig())
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Require().NoError(s.cache.Ping(s.T().Context()))
|
||||
s.Require().NoError(flushRedisDB(s.T().Context()))
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TearDownSuite() {
|
||||
if s.cache != nil {
|
||||
s.Require().NoError(s.cache.Close())
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) newDistributed() *cache.DistributedCache {
|
||||
s.T().Helper()
|
||||
|
||||
dc, err := cache.NewDistributed(s.cache, cache.DistributedConfig{}, nil)
|
||||
s.Require().NoError(err)
|
||||
|
||||
return dc
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) newRepo(source storageredis.ChatSource) *storageredis.ChatRepository {
|
||||
s.T().Helper()
|
||||
|
||||
return storageredis.NewChatRepository(source, s.newDistributed(), time.Minute, nil)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestFirstPageIsCached() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
page := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Twice()
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(page, nil).Once()
|
||||
|
||||
repo := s.newRepo(source)
|
||||
|
||||
first, err := repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
s.Empty(first.Items)
|
||||
|
||||
second, err := repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
s.Empty(second.Items)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestCreateInvalidatesMemberCaches() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
bob := uuid.New()
|
||||
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
chat := domain.Chat{
|
||||
ID: uuid.New(),
|
||||
Title: "Чат",
|
||||
MemberIDs: []uuid.UUID{alice, bob},
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
page := domain.Page[domain.Chat]{Items: []domain.Chat{chat}}
|
||||
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Once()
|
||||
source.EXPECT().ListVersion(mock.Anything, bob).Return(int64(0), nil).Once()
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(empty, nil).Once()
|
||||
source.EXPECT().ListVisible(mock.Anything, bob, (*domain.Cursor)(nil), 50).Return(empty, nil).Once()
|
||||
source.EXPECT().Create(mock.Anything, mock.AnythingOfType("domain.ChatDraft")).Return(chat, nil).Once()
|
||||
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(1), nil).Once()
|
||||
source.EXPECT().ListVersion(mock.Anything, bob).Return(int64(1), nil).Once()
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(page, nil).Once()
|
||||
source.EXPECT().ListVisible(mock.Anything, bob, (*domain.Cursor)(nil), 50).Return(page, nil).Once()
|
||||
|
||||
repo := s.newRepo(source)
|
||||
|
||||
_, err := repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
_, err = repo.ListVisible(ctx, bob, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
|
||||
_, err = repo.Create(ctx, domain.ChatDraft{
|
||||
Title: "Чат",
|
||||
MemberIDs: []uuid.UUID{alice, bob},
|
||||
CallerID: alice,
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
alicePage, err := repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
s.Len(alicePage.Items, 1, "creator must observe the new chat immediately")
|
||||
|
||||
bobPage, err := repo.ListVisible(ctx, bob, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
s.Len(bobPage.Items, 1, "other member must observe the new chat immediately")
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestEvictedCacheEntryReloadsFromSource() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Twice()
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(empty, nil).Twice()
|
||||
|
||||
repo := s.newRepo(source)
|
||||
|
||||
_, err := repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
|
||||
// Simulate a Redis flush/restart by dropping all cache entries.
|
||||
s.Require().NoError(flushRedisDB(ctx))
|
||||
|
||||
_, err = repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestDeeperPagesBypassCache() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
cursor := &domain.Cursor{Scope: alice, CreatedAt: time.Now().UTC(), ID: uuid.New()}
|
||||
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, cursor, 50).Return(empty, nil).Twice()
|
||||
|
||||
repo := s.newRepo(source)
|
||||
|
||||
_, err := repo.ListVisible(ctx, alice, cursor, 50)
|
||||
s.Require().NoError(err)
|
||||
_, err = repo.ListVisible(ctx, alice, cursor, 50)
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestLimitIsPartOfCacheKey() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Twice()
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 10).Return(empty, nil).Once()
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(empty, nil).Once()
|
||||
|
||||
repo := s.newRepo(source)
|
||||
|
||||
_, err := repo.ListVisible(ctx, alice, nil, 10)
|
||||
s.Require().NoError(err)
|
||||
_, err = repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestConcurrentColdReadsAreDeduplicated() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Maybe()
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).
|
||||
RunAndReturn(func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error) {
|
||||
time.Sleep(25 * time.Millisecond)
|
||||
|
||||
return empty, nil
|
||||
}).Once()
|
||||
|
||||
repo := s.newRepo(source)
|
||||
|
||||
const workers = 100
|
||||
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
failures atomic.Int32
|
||||
)
|
||||
|
||||
wg.Add(workers)
|
||||
|
||||
for range workers {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
if _, err := repo.ListVisible(ctx, alice, nil, 50); err != nil {
|
||||
failures.Add(1)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
s.Require().Zero(failures.Load())
|
||||
s.T().Logf("distributed lock: %d concurrent cold reads -> 1 source load", workers)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestMultipleInstancesShareDistributedLock() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Maybe()
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).
|
||||
RunAndReturn(func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error) {
|
||||
time.Sleep(25 * time.Millisecond)
|
||||
|
||||
return empty, nil
|
||||
}).Once()
|
||||
|
||||
const (
|
||||
instances = 3
|
||||
workersPerInstance = 30
|
||||
)
|
||||
|
||||
repos := make([]*storageredis.ChatRepository, instances)
|
||||
for i := range repos {
|
||||
repos[i] = s.newRepo(source)
|
||||
}
|
||||
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
failures atomic.Int32
|
||||
)
|
||||
|
||||
wg.Add(instances * workersPerInstance)
|
||||
|
||||
for i := range repos {
|
||||
repo := repos[i]
|
||||
for range workersPerInstance {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
if _, err := repo.ListVisible(ctx, alice, nil, 50); err != nil {
|
||||
failures.Add(1)
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
s.Require().Zero(failures.Load())
|
||||
s.T().Logf("multi-instance distributed lock: %d instances x %d reads -> 1 source load",
|
||||
instances, workersPerInstance)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestCacheUnavailableFallsBackToSource() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
page := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Once()
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(page, nil).Once()
|
||||
|
||||
lockStore := cachemocks.NewMockLockStore(s.T())
|
||||
lockStore.EXPECT().Get(mock.Anything, mock.Anything).Return(nil, errors.New("redis down")).Maybe()
|
||||
|
||||
distributed, err := cache.NewDistributed(lockStore, cache.DistributedConfig{}, nil)
|
||||
s.Require().NoError(err)
|
||||
|
||||
repo := storageredis.NewChatRepository(source, distributed, time.Minute, nil)
|
||||
|
||||
got, err := repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err, "cache failure must not fail the read")
|
||||
s.Empty(got.Items)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestBrokenCacheEntryIsDroppedAndRepopulated() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
page := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Times(3)
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).Return(page, nil).Twice()
|
||||
|
||||
repo := s.newRepo(source)
|
||||
|
||||
key := "chat_list:" + alice.String() + ":0:50"
|
||||
s.Require().NoError(s.cache.Set(ctx, key, []byte("{not json"), time.Minute))
|
||||
|
||||
// 1st: garbage -> dropped -> source.
|
||||
first, err := repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err, "a corrupted cache entry must not fail the read")
|
||||
|
||||
// 2nd: miss -> source -> repopulate.
|
||||
second, err := repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
|
||||
// 3rd: served from cache, no source call.
|
||||
third, err := repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Equal(first, second)
|
||||
s.Equal(second, third)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestSlowLoaderBeyondCacheBudgetReturnsData() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
page := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
|
||||
release := make(chan struct{})
|
||||
var calls atomic.Int32
|
||||
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Once()
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).
|
||||
RunAndReturn(func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error) {
|
||||
if calls.Add(1) == 1 {
|
||||
<-release // the loader outlives the caller's cache budget
|
||||
}
|
||||
|
||||
return page, nil
|
||||
}).Maybe()
|
||||
|
||||
repo := s.newRepo(source)
|
||||
|
||||
started := time.Now()
|
||||
got, err := repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().NoError(err, "budget expiry must fall back to the source, not fail")
|
||||
s.Empty(got.Items)
|
||||
s.GreaterOrEqual(time.Since(started), 450*time.Millisecond, "the caller must be bounded by the cache budget")
|
||||
|
||||
// Let the background loader finish before the test (and its mock) is torn down.
|
||||
close(release)
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestSourceErrorIsNotRetried() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
sentinel := errors.New("postgres down")
|
||||
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVersion(mock.Anything, alice).Return(int64(0), nil).Once()
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).
|
||||
Return(domain.Page[domain.Chat]{}, sentinel).Once()
|
||||
|
||||
repo := s.newRepo(source)
|
||||
|
||||
_, err := repo.ListVisible(ctx, alice, nil, 50)
|
||||
s.Require().ErrorIs(err, sentinel, "source error must propagate")
|
||||
}
|
||||
|
||||
func (s *ChatRepositorySuite) TestConcurrentColdReadsWithoutProtectionStampede() {
|
||||
ctx := s.T().Context()
|
||||
alice := uuid.New()
|
||||
key := "naive:" + alice.String()
|
||||
empty := domain.Page[domain.Chat]{Items: []domain.Chat{}}
|
||||
|
||||
var loads atomic.Int32
|
||||
|
||||
source := storagemocks.NewMockChatSource(s.T())
|
||||
source.EXPECT().ListVisible(mock.Anything, alice, (*domain.Cursor)(nil), 50).
|
||||
RunAndReturn(func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error) {
|
||||
loads.Add(1)
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
|
||||
return empty, nil
|
||||
}).Maybe()
|
||||
|
||||
const workers = 100
|
||||
|
||||
var (
|
||||
wg sync.WaitGroup
|
||||
failures atomic.Int32
|
||||
)
|
||||
|
||||
wg.Add(workers)
|
||||
|
||||
for range workers {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
// Naive cache-aside without distributed coordination: every concurrent miss loads.
|
||||
if _, err := s.cache.Get(ctx, key); err != nil {
|
||||
if _, loadErr := source.ListVisible(ctx, alice, nil, 50); loadErr != nil {
|
||||
failures.Add(1)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
_ = s.cache.Set(ctx, key, []byte("page"), time.Minute)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
s.Require().Zero(failures.Load())
|
||||
s.Greater(loads.Load(), int32(1), "without distributed coordination concurrent misses stampede the source")
|
||||
s.T().Logf("stampede demonstration: %d concurrent reads -> %d source loads", workers, loads.Load())
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
//go:build integration
|
||||
|
||||
package redis_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
goredis "github.com/redis/go-redis/v9"
|
||||
|
||||
"mtusi-messenger/internal/platform/cache"
|
||||
)
|
||||
|
||||
const testRedisDB = 1
|
||||
|
||||
func redisEnv(key, fallback string) string {
|
||||
if value := os.Getenv(key); value != "" {
|
||||
return value
|
||||
}
|
||||
|
||||
return fallback
|
||||
}
|
||||
|
||||
func redisEnvInt(key string, fallback int) int {
|
||||
value := os.Getenv(key)
|
||||
if value == "" {
|
||||
return fallback
|
||||
}
|
||||
|
||||
parsed, err := strconv.Atoi(value)
|
||||
if err != nil {
|
||||
return fallback
|
||||
}
|
||||
|
||||
return parsed
|
||||
}
|
||||
|
||||
func testRedisConfig() cache.RedisConfig {
|
||||
return cache.RedisConfig{
|
||||
Host: redisEnv("TEST_REDIS_HOST", "localhost"),
|
||||
Port: redisEnvInt("TEST_REDIS_PORT", 6379),
|
||||
Password: os.Getenv("TEST_REDIS_PASSWORD"),
|
||||
DB: redisEnvInt("TEST_REDIS_DB", testRedisDB),
|
||||
MaxRetries: 3,
|
||||
DialTimeout: 5 * time.Second,
|
||||
ReadTimeout: 3 * time.Second,
|
||||
WriteTimeout: 3 * time.Second,
|
||||
PoolSize: 5,
|
||||
}
|
||||
}
|
||||
|
||||
func flushRedisDB(ctx context.Context) error {
|
||||
cfg := testRedisConfig()
|
||||
|
||||
client := goredis.NewClient(&goredis.Options{
|
||||
Addr: cfg.Host + ":" + strconv.Itoa(cfg.Port),
|
||||
Password: cfg.Password,
|
||||
DB: cfg.DB,
|
||||
})
|
||||
|
||||
defer func() { _ = client.Close() }()
|
||||
|
||||
return client.FlushDB(ctx).Err()
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
// Code generated by mockery; DO NOT EDIT.
|
||||
// github.com/vektra/mockery
|
||||
// template: testify
|
||||
|
||||
package mocks
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mtusi-messenger/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
mock "github.com/stretchr/testify/mock"
|
||||
)
|
||||
|
||||
// NewMockChatSource creates a new instance of MockChatSource. It also registers a testing interface on the mock and a cleanup function to assert the mocks expectations.
|
||||
// The first argument is typically a *testing.T value.
|
||||
func NewMockChatSource(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockChatSource {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockChatSource{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockChatSource is an autogenerated mock type for the ChatSource type
|
||||
type MockChatSource struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockChatSource_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockChatSource) EXPECT() *MockChatSource_Expecter {
|
||||
return &MockChatSource_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// Create provides a mock function for the type MockChatSource
|
||||
func (_mock *MockChatSource) Create(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error) {
|
||||
ret := _mock.Called(ctx, draft)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Create")
|
||||
}
|
||||
|
||||
var r0 domain.Chat
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.ChatDraft) (domain.Chat, error)); ok {
|
||||
return returnFunc(ctx, draft)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.ChatDraft) domain.Chat); ok {
|
||||
r0 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Chat)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.ChatDraft) error); ok {
|
||||
r1 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockChatSource_Create_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Create'
|
||||
type MockChatSource_Create_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Create is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - draft domain.ChatDraft
|
||||
func (_e *MockChatSource_Expecter) Create(ctx any, draft any) *MockChatSource_Create_Call {
|
||||
return &MockChatSource_Create_Call{Call: _e.mock.On("Create", ctx, draft)}
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_Create_Call) Run(run func(ctx context.Context, draft domain.ChatDraft)) *MockChatSource_Create_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 domain.ChatDraft
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(domain.ChatDraft)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_Create_Call) Return(chat domain.Chat, err error) *MockChatSource_Create_Call {
|
||||
_c.Call.Return(chat, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_Create_Call) RunAndReturn(run func(ctx context.Context, draft domain.ChatDraft) (domain.Chat, error)) *MockChatSource_Create_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// GetVisible provides a mock function for the type MockChatSource
|
||||
func (_mock *MockChatSource) GetVisible(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID) (domain.Chat, error) {
|
||||
ret := _mock.Called(ctx, chatID, callerID)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for GetVisible")
|
||||
}
|
||||
|
||||
var r0 domain.Chat
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) (domain.Chat, error)); ok {
|
||||
return returnFunc(ctx, chatID, callerID)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID) domain.Chat); ok {
|
||||
r0 = returnFunc(ctx, chatID, callerID)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Chat)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, chatID, callerID)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockChatSource_GetVisible_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetVisible'
|
||||
type MockChatSource_GetVisible_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// GetVisible is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - chatID uuid.UUID
|
||||
// - callerID uuid.UUID
|
||||
func (_e *MockChatSource_Expecter) GetVisible(ctx any, chatID any, callerID any) *MockChatSource_GetVisible_Call {
|
||||
return &MockChatSource_GetVisible_Call{Call: _e.mock.On("GetVisible", ctx, chatID, callerID)}
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_GetVisible_Call) Run(run func(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID)) *MockChatSource_GetVisible_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 uuid.UUID
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_GetVisible_Call) Return(chat domain.Chat, err error) *MockChatSource_GetVisible_Call {
|
||||
_c.Call.Return(chat, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_GetVisible_Call) RunAndReturn(run func(ctx context.Context, chatID uuid.UUID, callerID uuid.UUID) (domain.Chat, error)) *MockChatSource_GetVisible_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// ListVersion provides a mock function for the type MockChatSource
|
||||
func (_mock *MockChatSource) ListVersion(ctx context.Context, userID uuid.UUID) (int64, error) {
|
||||
ret := _mock.Called(ctx, userID)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListVersion")
|
||||
}
|
||||
|
||||
var r0 int64
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) (int64, error)); ok {
|
||||
return returnFunc(ctx, userID)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) int64); ok {
|
||||
r0 = returnFunc(ctx, userID)
|
||||
} else {
|
||||
r0 = ret.Get(0).(int64)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, userID)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockChatSource_ListVersion_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListVersion'
|
||||
type MockChatSource_ListVersion_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListVersion is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - userID uuid.UUID
|
||||
func (_e *MockChatSource_Expecter) ListVersion(ctx any, userID any) *MockChatSource_ListVersion_Call {
|
||||
return &MockChatSource_ListVersion_Call{Call: _e.mock.On("ListVersion", ctx, userID)}
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_ListVersion_Call) Run(run func(ctx context.Context, userID uuid.UUID)) *MockChatSource_ListVersion_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_ListVersion_Call) Return(n int64, err error) *MockChatSource_ListVersion_Call {
|
||||
_c.Call.Return(n, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_ListVersion_Call) RunAndReturn(run func(ctx context.Context, userID uuid.UUID) (int64, error)) *MockChatSource_ListVersion_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// ListVisible provides a mock function for the type MockChatSource
|
||||
func (_mock *MockChatSource) ListVisible(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error) {
|
||||
ret := _mock.Called(ctx, callerID, after, limit)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListVisible")
|
||||
}
|
||||
|
||||
var r0 domain.Page[domain.Chat]
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, *domain.Cursor, int) (domain.Page[domain.Chat], error)); ok {
|
||||
return returnFunc(ctx, callerID, after, limit)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, *domain.Cursor, int) domain.Page[domain.Chat]); ok {
|
||||
r0 = returnFunc(ctx, callerID, after, limit)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Page[domain.Chat])
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, *domain.Cursor, int) error); ok {
|
||||
r1 = returnFunc(ctx, callerID, after, limit)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockChatSource_ListVisible_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListVisible'
|
||||
type MockChatSource_ListVisible_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListVisible is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - callerID uuid.UUID
|
||||
// - after *domain.Cursor
|
||||
// - limit int
|
||||
func (_e *MockChatSource_Expecter) ListVisible(ctx any, callerID any, after any, limit any) *MockChatSource_ListVisible_Call {
|
||||
return &MockChatSource_ListVisible_Call{Call: _e.mock.On("ListVisible", ctx, callerID, after, limit)}
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_ListVisible_Call) Run(run func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int)) *MockChatSource_ListVisible_Call {
|
||||
_c.Call.Run(func(args mock.Arguments) {
|
||||
var arg0 context.Context
|
||||
if args[0] != nil {
|
||||
arg0 = args[0].(context.Context)
|
||||
}
|
||||
var arg1 uuid.UUID
|
||||
if args[1] != nil {
|
||||
arg1 = args[1].(uuid.UUID)
|
||||
}
|
||||
var arg2 *domain.Cursor
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(*domain.Cursor)
|
||||
}
|
||||
var arg3 int
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(int)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_ListVisible_Call) Return(page domain.Page[domain.Chat], err error) *MockChatSource_ListVisible_Call {
|
||||
_c.Call.Return(page, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockChatSource_ListVisible_Call) RunAndReturn(run func(ctx context.Context, callerID uuid.UUID, after *domain.Cursor, limit int) (domain.Page[domain.Chat], error)) *MockChatSource_ListVisible_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
attachmentService "mtusi-messenger/internal/service/attachment"
|
||||
"mtusi-messenger/internal/transport/rest/internal/oas"
|
||||
)
|
||||
|
||||
func (h *Handler) UploadAttachment(
|
||||
ctx context.Context,
|
||||
req oas.UploadAttachmentReq,
|
||||
params oas.UploadAttachmentParams,
|
||||
) (oas.UploadAttachmentRes, error) {
|
||||
body, declared, err := uploadBody(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
attachment, err := h.attachments.Upload(ctx, attachmentService.UploadInput{
|
||||
ChatID: params.ChatID,
|
||||
OwnerID: caller(ctx),
|
||||
Filename: params.Filename,
|
||||
DeclaredContentType: declared,
|
||||
Body: body,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &oas.AttachmentHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: attachmentResponse(attachment),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) GetAttachment(
|
||||
ctx context.Context,
|
||||
params oas.GetAttachmentParams,
|
||||
) (oas.GetAttachmentRes, error) {
|
||||
attachment, err := h.attachments.Get(ctx, caller(ctx), params.AttachmentID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &oas.AttachmentHeaders{
|
||||
XRequestID: oas.NewOptString(requestIDFromContext(ctx)),
|
||||
Response: attachmentResponse(attachment),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (h *Handler) DownloadAttachment(
|
||||
ctx context.Context,
|
||||
params oas.DownloadAttachmentParams,
|
||||
) (oas.DownloadAttachmentRes, error) {
|
||||
if variant, ok := params.Variant.Get(); ok && variant != oas.DownloadAttachmentVariantOriginal {
|
||||
return nil, fmt.Errorf("%w: variant %q is not available", domain.ErrNotFound, variant)
|
||||
}
|
||||
|
||||
attachment, body, err := h.attachments.Open(ctx, caller(ctx), params.AttachmentID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// The generated transport copies the body after the handler returns. Close
|
||||
// the S3 stream when the client disconnects; closeOnEOF covers the normal
|
||||
// path.
|
||||
_ = context.AfterFunc(ctx, func() { _ = body.Close() })
|
||||
|
||||
requestID := oas.NewOptString(requestIDFromContext(ctx))
|
||||
reader := closeOnEOF{ReadCloser: body}
|
||||
|
||||
switch attachment.ContentType {
|
||||
case "image/png":
|
||||
return &oas.DownloadAttachmentOKImagePNGHeaders{
|
||||
XRequestID: requestID,
|
||||
Response: oas.DownloadAttachmentOKImagePNG{Data: reader},
|
||||
}, nil
|
||||
case "image/jpeg":
|
||||
return &oas.DownloadAttachmentOKImageJpegHeaders{
|
||||
XRequestID: requestID,
|
||||
Response: oas.DownloadAttachmentOKImageJpeg{Data: reader},
|
||||
}, nil
|
||||
default:
|
||||
_ = body.Close()
|
||||
|
||||
return nil, fmt.Errorf("%w: unexpected content type %q", domain.ErrUnavailable, attachment.ContentType)
|
||||
}
|
||||
}
|
||||
|
||||
func uploadBody(req oas.UploadAttachmentReq) (io.Reader, string, error) {
|
||||
switch typed := req.(type) {
|
||||
case *oas.UploadAttachmentReqImagePNG:
|
||||
return typed.Data, "image/png", nil
|
||||
case *oas.UploadAttachmentReqImageJpeg:
|
||||
return typed.Data, "image/jpeg", nil
|
||||
default:
|
||||
return nil, "", fmt.Errorf("%w: request body must be image/png or image/jpeg", domain.ErrUnsupportedMedia)
|
||||
}
|
||||
}
|
||||
|
||||
func attachmentResponse(attachment domain.Attachment) oas.Attachment {
|
||||
response := oas.Attachment{
|
||||
ID: attachment.ID,
|
||||
ChatID: attachment.ChatID,
|
||||
OwnerID: attachment.OwnerID,
|
||||
Filename: attachment.Filename,
|
||||
SizeBytes: int(attachment.SizeBytes),
|
||||
SHA256: attachment.SHA256,
|
||||
Status: oas.AttachmentStatusReady,
|
||||
Variants: []oas.Variant{},
|
||||
ErrorCode: oas.NilString{Null: true},
|
||||
CreatedAt: attachment.CreatedAt,
|
||||
UpdatedAt: attachment.UpdatedAt,
|
||||
}
|
||||
|
||||
switch attachment.ContentType {
|
||||
case "image/png":
|
||||
response.ContentType = oas.AttachmentContentTypeImagePNG
|
||||
case "image/jpeg":
|
||||
response.ContentType = oas.AttachmentContentTypeImageJpeg
|
||||
default:
|
||||
response.ContentType = oas.AttachmentContentType(attachment.ContentType)
|
||||
}
|
||||
|
||||
if attachment.ErrorCode != nil {
|
||||
response.ErrorCode = oas.NilString{Value: *attachment.ErrorCode}
|
||||
}
|
||||
|
||||
return response
|
||||
}
|
||||
|
||||
type closeOnEOF struct {
|
||||
io.ReadCloser
|
||||
}
|
||||
|
||||
func (r closeOnEOF) Read(p []byte) (int, error) {
|
||||
n, err := r.ReadCloser.Read(p)
|
||||
if err != nil {
|
||||
_ = r.Close()
|
||||
}
|
||||
|
||||
return n, err
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
// attachmentUploadPath matches POST /api/v1/chats/{chat_id}/attachments. The
|
||||
// UUID syntax is not validated here; this middleware only selects a body limit,
|
||||
// and the generated transport rejects malformed identifiers later.
|
||||
var attachmentUploadPath = regexp.MustCompile(`^/api/v1/chats/[^/]+/attachments$`)
|
||||
|
||||
// bodyLimitMiddleware bounds the request body before it reaches the generated
|
||||
// transport. JSON endpoints keep the small default limit; the attachment upload
|
||||
// gets its own larger limit. Without this split the 10 MiB upload would be
|
||||
// rejected before the handler, and raising the global limit would let any
|
||||
// public JSON endpoint read a 10 MiB body.
|
||||
func bodyLimitMiddleware(
|
||||
defaultLimit, uploadLimit int64,
|
||||
log *slog.Logger,
|
||||
next http.Handler,
|
||||
) http.Handler {
|
||||
if defaultLimit <= 0 && uploadLimit <= 0 {
|
||||
return next
|
||||
}
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
limit := limitForRequest(r, defaultLimit, uploadLimit)
|
||||
if limit <= 0 {
|
||||
next.ServeHTTP(w, r)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if r.ContentLength > limit {
|
||||
logRejected(r.Context(), log, r, http.StatusRequestEntityTooLarge, nil)
|
||||
writeError(r.Context(), log, w, r, http.StatusRequestEntityTooLarge)
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if r.Body != nil {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, limit)
|
||||
}
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func limitForRequest(r *http.Request, defaultLimit, uploadLimit int64) int64 {
|
||||
if r.Method == http.MethodPost && attachmentUploadPath.MatchString(r.URL.Path) {
|
||||
return uploadLimit
|
||||
}
|
||||
|
||||
return defaultLimit
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user