lab7: безопасность, mTLS, OpenBao и PKI lifecycle
This commit is contained in:
@@ -0,0 +1,265 @@
|
||||
// Package broker provides confirmed publishing and consumption over certificate-
|
||||
// authenticated AMQP. The operator owns topology; PostgreSQL owns business state.
|
||||
package broker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
amqp "github.com/rabbitmq/amqp091-go"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/tlsconfig"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
URL string
|
||||
Role string
|
||||
Producer bool
|
||||
Exchange string
|
||||
Queue string
|
||||
ConnectTimeout time.Duration
|
||||
ConfirmTimeout time.Duration
|
||||
Heartbeat time.Duration
|
||||
Prefetch int
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
cfg Config
|
||||
|
||||
conn *amqp.Connection
|
||||
publisher *amqp.Channel
|
||||
|
||||
returns chan amqp.Return
|
||||
closeOnce sync.Once
|
||||
closeErr error
|
||||
}
|
||||
|
||||
// Dial connects using EXTERNAL only. Relay gets a confirm-mode publisher;
|
||||
// worker opens consumer channels only when Consume is called.
|
||||
func Dial(cfg Config) (*Client, error) {
|
||||
endpoint, err := url.Parse(cfg.URL)
|
||||
if err != nil || endpoint.Scheme != "amqps" || endpoint.Hostname() == "" || endpoint.User != nil {
|
||||
return nil, errors.New("broker: url must be amqps without credentials")
|
||||
}
|
||||
if endpoint.RawQuery != "" || endpoint.Fragment != "" {
|
||||
return nil, errors.New("broker: url query and fragment are not permitted")
|
||||
}
|
||||
switch cfg.Role {
|
||||
case "relay":
|
||||
if !cfg.Producer || cfg.Exchange == "" {
|
||||
return nil, errors.New("broker: relay requires producer mode and an exchange")
|
||||
}
|
||||
case "worker":
|
||||
if cfg.Producer || cfg.Queue == "" {
|
||||
return nil, errors.New("broker: worker requires consumer mode and a queue")
|
||||
}
|
||||
default:
|
||||
return nil, errors.New("broker: role must be relay or worker")
|
||||
}
|
||||
if cfg.ConnectTimeout <= 0 || cfg.ConnectTimeout > 5*time.Second {
|
||||
return nil, errors.New("broker: connect timeout must be positive and at most 5s")
|
||||
}
|
||||
clientTLS, err := tlsconfig.NewClientFromEnv(endpoint.Hostname())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("configure broker tls: %w", err)
|
||||
}
|
||||
conn, err := amqp.DialConfig(cfg.URL, amqp.Config{
|
||||
Heartbeat: cfg.Heartbeat,
|
||||
Dial: amqp.DefaultDial(cfg.ConnectTimeout),
|
||||
TLSClientConfig: clientTLS,
|
||||
SASL: []amqp.Authentication{&amqp.ExternalAuth{}},
|
||||
Properties: amqp.Table{
|
||||
"connection_name": "messenger-" + cfg.Role,
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("dial broker: %w", err)
|
||||
}
|
||||
client := &Client{cfg: cfg, conn: conn}
|
||||
if !cfg.Producer {
|
||||
return client, nil
|
||||
}
|
||||
publisher, err := conn.Channel()
|
||||
if err != nil {
|
||||
return nil, errors.Join(
|
||||
fmt.Errorf("open publisher channel: %w", err),
|
||||
client.Close(),
|
||||
)
|
||||
}
|
||||
client.publisher = publisher
|
||||
client.returns = make(chan amqp.Return, 16)
|
||||
if err := publisher.Confirm(false); err != nil {
|
||||
return nil, errors.Join(
|
||||
fmt.Errorf("enable publisher confirms: %w", err),
|
||||
client.Close(),
|
||||
)
|
||||
}
|
||||
publisher.NotifyReturn(client.returns)
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func (c *Client) Connected() bool {
|
||||
return c.conn != nil && !c.conn.IsClosed()
|
||||
}
|
||||
|
||||
// PublishConfirmed returns only after the broker acknowledged the persistent
|
||||
// message. A duplicate publication after a crash is normal and harmless.
|
||||
func (c *Client) PublishConfirmed(ctx context.Context, routingKey string, message domain.JobMessage) error {
|
||||
if c.cfg.Role != "relay" || !c.cfg.Producer || c.publisher == nil {
|
||||
return errors.New("broker: publication is restricted to relay")
|
||||
}
|
||||
payload, err := message.MarshalPayload()
|
||||
if err != nil {
|
||||
return fmt.Errorf("marshal job message: %w", err)
|
||||
}
|
||||
|
||||
confirmation, err := c.publisher.PublishWithDeferredConfirmWithContext(
|
||||
ctx,
|
||||
c.cfg.Exchange,
|
||||
routingKey,
|
||||
true,
|
||||
false,
|
||||
amqp.Publishing{
|
||||
ContentType: "application/json",
|
||||
DeliveryMode: amqp.Persistent,
|
||||
MessageId: message.JobID.String(),
|
||||
Type: message.Type,
|
||||
Timestamp: message.CreatedAt,
|
||||
Body: payload,
|
||||
},
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("publish job: %w", err)
|
||||
}
|
||||
|
||||
confirmCtx := ctx
|
||||
if c.cfg.ConfirmTimeout > 0 {
|
||||
var cancel context.CancelFunc
|
||||
confirmCtx, cancel = context.WithTimeout(ctx, c.cfg.ConfirmTimeout)
|
||||
defer cancel()
|
||||
}
|
||||
|
||||
confirmed, err := confirmation.WaitContext(confirmCtx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("await publisher confirm: %w", err)
|
||||
}
|
||||
|
||||
if !confirmed {
|
||||
return errors.New("broker nacked the job message")
|
||||
}
|
||||
|
||||
// mandatory=true: an unroutable message is returned even if confirmed.
|
||||
// The operator must provision bindings before relay startup.
|
||||
select {
|
||||
case returned := <-c.returns:
|
||||
if returned.MessageId == message.JobID.String() {
|
||||
return fmt.Errorf("broker returned unroutable message: %s", returned.ReplyText)
|
||||
}
|
||||
default:
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
type Outcome int
|
||||
|
||||
const (
|
||||
Ack Outcome = iota
|
||||
Requeue
|
||||
Drop
|
||||
)
|
||||
|
||||
type Handler func(ctx context.Context, delivery amqp.Delivery) Outcome
|
||||
|
||||
// Consume blocks until the context is cancelled or the consumer channel fails.
|
||||
// Each call uses its own channel so worker slots do not share prefetch state.
|
||||
func (c *Client) Consume(ctx context.Context, handler Handler) error {
|
||||
if c.cfg.Role != "worker" || c.cfg.Producer {
|
||||
return errors.New("broker: consumption is restricted to worker")
|
||||
}
|
||||
channel, err := c.conn.Channel()
|
||||
if err != nil {
|
||||
return fmt.Errorf("open consumer channel: %w", err)
|
||||
}
|
||||
defer channel.Close()
|
||||
|
||||
if err := channel.Qos(c.cfg.Prefetch, 0, false); err != nil {
|
||||
return fmt.Errorf("set qos: %w", err)
|
||||
}
|
||||
|
||||
consumerTag := fmt.Sprintf("messenger-%d", time.Now().UnixNano())
|
||||
|
||||
deliveries, err := channel.Consume(
|
||||
c.cfg.Queue,
|
||||
consumerTag,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
false,
|
||||
nil,
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("consume: %w", err)
|
||||
}
|
||||
|
||||
done := make(chan struct{})
|
||||
defer close(done)
|
||||
|
||||
go func() {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
_ = channel.Cancel(consumerTag, false)
|
||||
case <-done:
|
||||
}
|
||||
}()
|
||||
|
||||
for delivery := range deliveries {
|
||||
outcome := safeHandle(ctx, handler, delivery)
|
||||
|
||||
switch outcome {
|
||||
case Ack:
|
||||
_ = delivery.Ack(false)
|
||||
case Requeue:
|
||||
_ = delivery.Nack(false, true)
|
||||
case Drop:
|
||||
_ = delivery.Nack(false, false)
|
||||
}
|
||||
|
||||
if ctx.Err() != nil {
|
||||
// Let unacked deliveries return to the broker on channel close.
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
return errors.New("consumer channel closed")
|
||||
}
|
||||
|
||||
func safeHandle(ctx context.Context, handler Handler, delivery amqp.Delivery) (outcome Outcome) {
|
||||
defer func() {
|
||||
if recover() != nil {
|
||||
outcome = Requeue
|
||||
}
|
||||
}()
|
||||
|
||||
return handler(ctx, delivery)
|
||||
}
|
||||
|
||||
func (c *Client) Close() error {
|
||||
c.closeOnce.Do(func() {
|
||||
// Closing the connection first interrupts consumers and publication.
|
||||
// Keep pointers immutable while those operations unwind concurrently.
|
||||
if c.conn != nil && !c.conn.IsClosed() {
|
||||
c.closeErr = c.conn.CloseDeadline(time.Now().Add(time.Second))
|
||||
}
|
||||
})
|
||||
return c.closeErr
|
||||
}
|
||||
@@ -0,0 +1,472 @@
|
||||
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"
|
||||
"mtusi-messenger/internal/platform/secretfile"
|
||||
"mtusi-messenger/internal/platform/tlsconfig"
|
||||
)
|
||||
|
||||
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"`
|
||||
Broker Broker `mapstructure:"broker"`
|
||||
Worker Worker `mapstructure:"worker"`
|
||||
Relay Relay `mapstructure:"relay"`
|
||||
Outbox Outbox `mapstructure:"outbox"`
|
||||
Processing Processing `mapstructure:"processing"`
|
||||
Staging Staging `mapstructure:"staging"`
|
||||
Admission Admission `mapstructure:"admission"`
|
||||
}
|
||||
|
||||
// Broker carries the AMQP transport settings. The API never publishes; relay
|
||||
// and worker require a non-empty URL at startup.
|
||||
type Broker struct {
|
||||
URL string `mapstructure:"url"`
|
||||
ConnectTimeout time.Duration `mapstructure:"connect_timeout"`
|
||||
ConfirmTimeout time.Duration `mapstructure:"confirm_timeout"`
|
||||
Heartbeat time.Duration `mapstructure:"heartbeat"`
|
||||
Exchange string `mapstructure:"exchange" validate:"required"`
|
||||
Queue string `mapstructure:"queue" validate:"required"`
|
||||
Prefetch int `mapstructure:"prefetch" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
// Worker bounds the process that consumes jobs.
|
||||
type Worker struct {
|
||||
Concurrency int `mapstructure:"concurrency" validate:"required,gt=0,lte=32"`
|
||||
Prefetch int `mapstructure:"prefetch" validate:"required,gt=0,lte=100"`
|
||||
ShutdownTimeout time.Duration `mapstructure:"shutdown_timeout" validate:"required,gt=0"`
|
||||
HealthAddr string `mapstructure:"health_addr" validate:"required"`
|
||||
}
|
||||
|
||||
// Relay bounds the outbox publisher and lease reaper.
|
||||
type Relay struct {
|
||||
HealthAddr string `mapstructure:"health_addr" validate:"required"`
|
||||
}
|
||||
|
||||
// Outbox schedules publications and reclaims abandoned relay claims.
|
||||
type Outbox struct {
|
||||
PollInterval time.Duration `mapstructure:"poll_interval" validate:"required,gt=0"`
|
||||
ClaimTTL time.Duration `mapstructure:"claim_ttl" validate:"required,gt=0"`
|
||||
Batch int `mapstructure:"batch" validate:"required,gt=0,lte=1000"`
|
||||
ReaperInterval time.Duration `mapstructure:"reaper_interval" validate:"required,gt=0"`
|
||||
ReconcileAfter time.Duration `mapstructure:"reconcile_after" validate:"omitempty,gt=0"`
|
||||
Retention time.Duration `mapstructure:"retention" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
// Processing holds the shared job contract knobs read by API and worker.
|
||||
type Processing struct {
|
||||
PipelineVersion int `mapstructure:"pipeline_version" validate:"required,gte=1,lte=2"`
|
||||
MaxAttempts int `mapstructure:"max_attempts" validate:"required,gte=1,lte=100"`
|
||||
JobTimeout time.Duration `mapstructure:"job_timeout" validate:"required,gt=0"`
|
||||
LeaseTTL time.Duration `mapstructure:"lease_ttl" validate:"required,gt=0"`
|
||||
Heartbeat time.Duration `mapstructure:"heartbeat" validate:"required,gt=0"`
|
||||
RetryBase time.Duration `mapstructure:"retry_base" validate:"required,gt=0"`
|
||||
RetryCap time.Duration `mapstructure:"retry_cap" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
// Staging controls cleanup of objects that are no longer the active source.
|
||||
type Staging struct {
|
||||
OrphanGrace time.Duration `mapstructure:"orphan_grace" validate:"required,gt=0"`
|
||||
FailedRetention time.Duration `mapstructure:"failed_retention" validate:"required,gt=0"`
|
||||
}
|
||||
|
||||
// Admission bounds accepted-but-unfinished work per user and globally.
|
||||
type Admission struct {
|
||||
MaxPendingPerUser int `mapstructure:"max_pending_per_user" validate:"required,gte=0"`
|
||||
MaxPending int `mapstructure:"max_pending" validate:"required,gte=0"`
|
||||
MaxStagedBytes int64 `mapstructure:"max_staged_bytes" validate:"required,gte=0"`
|
||||
MaxConcurrent int `mapstructure:"max_concurrent_uploads" validate:"omitempty,gt=0"`
|
||||
}
|
||||
|
||||
// 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"`
|
||||
Username string `mapstructure:"username"`
|
||||
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,eq=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{}
|
||||
files := tlsconfig.FilesFromEnv()
|
||||
query.Set("sslmode", "verify-full")
|
||||
query.Set("sslrootcert", files.CA)
|
||||
query.Set("sslcert", files.Cert)
|
||||
query.Set("sslkey", files.Key)
|
||||
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": "https://localhost:8333",
|
||||
"s3.public_endpoint": "https://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,
|
||||
"postgres.host": "",
|
||||
"postgres.port": 0,
|
||||
"postgres.database": "",
|
||||
"postgres.user": "",
|
||||
"postgres.password": "",
|
||||
"postgres.ssl_mode": "verify-full",
|
||||
"redis.enabled": false,
|
||||
"redis.host": "localhost",
|
||||
"redis.port": 6379,
|
||||
"redis.username": "",
|
||||
"redis.password": "",
|
||||
"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",
|
||||
|
||||
"broker.url": "",
|
||||
"broker.connect_timeout": "5s",
|
||||
"broker.confirm_timeout": "5s",
|
||||
"broker.heartbeat": "10s",
|
||||
"broker.exchange": "attachments.jobs",
|
||||
"broker.queue": "attachment.process.v1",
|
||||
"broker.prefetch": 1,
|
||||
"worker.concurrency": 1,
|
||||
"worker.prefetch": 1,
|
||||
"worker.shutdown_timeout": "30s",
|
||||
"worker.health_addr": "127.0.0.1:8081",
|
||||
"relay.health_addr": "127.0.0.1:8082",
|
||||
"outbox.poll_interval": "1s",
|
||||
"outbox.claim_ttl": "30s",
|
||||
"outbox.batch": 20,
|
||||
"outbox.reaper_interval": "15s",
|
||||
"outbox.retention": "168h",
|
||||
"processing.pipeline_version": 1,
|
||||
"processing.max_attempts": 5,
|
||||
"processing.job_timeout": "120s",
|
||||
"processing.lease_ttl": "180s",
|
||||
"processing.heartbeat": "30s",
|
||||
"processing.retry_base": "2s",
|
||||
"processing.retry_cap": "60s",
|
||||
"staging.orphan_grace": "1h",
|
||||
"staging.failed_retention": "168h",
|
||||
"admission.max_pending_per_user": 20,
|
||||
"admission.max_pending": 200,
|
||||
"admission.max_staged_bytes": 2147483648,
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
return load("")
|
||||
}
|
||||
|
||||
// LoadOperator reads the migration credential from an operator-only mounted file.
|
||||
// Application credentials are acquired by Bao before Load instead.
|
||||
func LoadOperator() (Config, error) {
|
||||
path := os.Getenv("POSTGRES_PASSWORD_FILE")
|
||||
if path == "" {
|
||||
return Config{}, errors.New("operator config: postgres_password_file is required")
|
||||
}
|
||||
return load(path)
|
||||
}
|
||||
|
||||
func load(operatorPasswordFile string) (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)
|
||||
}
|
||||
}
|
||||
if operatorPasswordFile != "" {
|
||||
password, err := secretfile.Read(operatorPasswordFile)
|
||||
if err != nil {
|
||||
return Config{}, fmt.Errorf("read operator database password: %w", err)
|
||||
}
|
||||
value := strings.TrimRight(string(password), "\r\n")
|
||||
if value == "" {
|
||||
return Config{}, errors.New("operator database password is empty")
|
||||
}
|
||||
v.Set("postgres.password", value)
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
|
||||
if c.Processing.LeaseTTL < 3*c.Processing.Heartbeat {
|
||||
return errors.New("validate config: processing.lease_ttl must be at least 3x processing.heartbeat")
|
||||
}
|
||||
|
||||
if c.Processing.JobTimeout >= c.Processing.LeaseTTL {
|
||||
return errors.New("validate config: processing.job_timeout must be below processing.lease_ttl")
|
||||
}
|
||||
|
||||
if c.Processing.RetryCap < c.Processing.RetryBase {
|
||||
return errors.New("validate config: processing.retry_cap must be >= processing.retry_base")
|
||||
}
|
||||
|
||||
if c.Staging.FailedRetention < c.Staging.OrphanGrace {
|
||||
return errors.New("validate config: staging.failed_retention must be >= staging.orphan_grace")
|
||||
}
|
||||
|
||||
for _, endpoint := range []string{c.S3.Endpoint, c.S3.PublicEndpoint} {
|
||||
if endpoint == "" {
|
||||
continue
|
||||
}
|
||||
u, err := url.Parse(endpoint)
|
||||
if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil {
|
||||
return errors.New("validate config: s3 endpoints must be https urls without credentials")
|
||||
}
|
||||
}
|
||||
|
||||
if c.Broker.URL != "" {
|
||||
u, err := url.Parse(c.Broker.URL)
|
||||
if err != nil || u.Scheme != "amqps" || u.Hostname() == "" || u.User != nil {
|
||||
return errors.New("validate config: broker.url must be an amqps url without credentials")
|
||||
}
|
||||
}
|
||||
|
||||
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,396 @@
|
||||
package config_test
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"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 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) {
|
||||
t.Setenv("TLS_CA_FILE", "/identity/ca.crt")
|
||||
t.Setenv("TLS_CERT_FILE", "/identity/tls.crt")
|
||||
t.Setenv("TLS_KEY_FILE", "/identity/tls.key")
|
||||
cfg := config.Postgres{
|
||||
Host: "db",
|
||||
Port: 5432,
|
||||
Database: "app",
|
||||
User: "user",
|
||||
Password: "p@ss:w/rd",
|
||||
SSLMode: "verify-full",
|
||||
}
|
||||
|
||||
dsn, err := url.Parse(cfg.DSN())
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "user", dsn.User.Username())
|
||||
password, ok := dsn.User.Password()
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "p@ss:w/rd", password)
|
||||
assert.Equal(t, "db:5432", dsn.Host)
|
||||
assert.Equal(t, "/app", dsn.Path)
|
||||
assert.Equal(t, "verify-full", dsn.Query().Get("sslmode"))
|
||||
assert.Equal(t, "/identity/ca.crt", dsn.Query().Get("sslrootcert"))
|
||||
assert.Equal(t, "/identity/tls.crt", dsn.Query().Get("sslcert"))
|
||||
assert.Equal(t, "/identity/tls.key", dsn.Query().Get("sslkey"))
|
||||
}
|
||||
|
||||
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: verify-full
|
||||
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: verify-full
|
||||
`)
|
||||
|
||||
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: verify-full
|
||||
max_conns: 10
|
||||
`)
|
||||
|
||||
tests := map[string]map[string]string{
|
||||
"неизвестный ssl mode": {"POSTGRES_SSL_MODE": "bogus"},
|
||||
"plaintext ssl mode": {"POSTGRES_SSL_MODE": "disable"},
|
||||
"unverified ssl mode": {"POSTGRES_SSL_MODE": "require"},
|
||||
"hostname not verified": {"POSTGRES_SSL_MODE": "verify-ca"},
|
||||
"отрицательный 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("REDIS_USERNAME", "api-cache")
|
||||
t.Setenv("REDIS_PASSWORD", "cache-secret")
|
||||
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.Equal(t, "api-cache", cfg.Redis.Username)
|
||||
assert.Equal(t, "cache-secret", cfg.Redis.Password)
|
||||
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")
|
||||
}
|
||||
|
||||
func TestRejectsInsecureDependencyEndpoints(t *testing.T) {
|
||||
for key, value := range map[string]string{
|
||||
"S3_ENDPOINT": "http://seaweedfs:8333",
|
||||
"S3_PUBLIC_ENDPOINT": "http://localhost:8333",
|
||||
"BROKER_URL": "amqp://broker:5672/",
|
||||
} {
|
||||
t.Run(key, func(t *testing.T) {
|
||||
t.Setenv(key, value)
|
||||
_, err := config.Load()
|
||||
require.Error(t, err)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadOperatorUsesOnlyMountedDatabaseCredential(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "password")
|
||||
require.NoError(t, os.WriteFile(path, []byte("operator-secret\n"), 0o600))
|
||||
t.Setenv("POSTGRES_PASSWORD_FILE", path)
|
||||
t.Setenv("POSTGRES_PASSWORD", "application-secret")
|
||||
t.Setenv("S3_ACCESS_KEY_ID", "")
|
||||
t.Setenv("S3_SECRET_ACCESS_KEY", "")
|
||||
t.Setenv("REDIS_PASSWORD", "")
|
||||
cfg, err := config.LoadOperator()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "operator-secret", cfg.Postgres.Password)
|
||||
assert.Empty(t, cfg.S3.AccessKeyID)
|
||||
assert.Empty(t, cfg.S3.SecretAccessKey)
|
||||
assert.Empty(t, cfg.Redis.Password)
|
||||
}
|
||||
|
||||
func TestLoadOperatorRequiresReadableNonemptyPasswordFile(t *testing.T) {
|
||||
t.Setenv("POSTGRES_PASSWORD_FILE", "")
|
||||
_, err := config.LoadOperator()
|
||||
require.Error(t, err)
|
||||
t.Setenv("POSTGRES_PASSWORD_FILE", filepath.Join(t.TempDir(), "missing"))
|
||||
_, err = config.LoadOperator()
|
||||
require.Error(t, err)
|
||||
path := filepath.Join(t.TempDir(), "empty")
|
||||
require.NoError(t, os.WriteFile(path, []byte("\n"), 0o600))
|
||||
t.Setenv("POSTGRES_PASSWORD_FILE", path)
|
||||
_, err = config.LoadOperator()
|
||||
require.Error(t, err)
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// AttachmentStatus is the public lifecycle of an attachment. Pending is an
|
||||
// internal presign state and is never exposed by the API.
|
||||
type AttachmentStatus string
|
||||
|
||||
const (
|
||||
AttachmentPending AttachmentStatus = "pending"
|
||||
AttachmentQueued AttachmentStatus = "queued"
|
||||
AttachmentProcessing AttachmentStatus = "processing"
|
||||
AttachmentReady AttachmentStatus = "ready"
|
||||
AttachmentFailed AttachmentStatus = "failed"
|
||||
)
|
||||
|
||||
func (s AttachmentStatus) Valid() bool {
|
||||
switch s {
|
||||
case AttachmentPending, AttachmentQueued, AttachmentProcessing, AttachmentReady, AttachmentFailed:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Public reports whether the status is part of the API enum.
|
||||
func (s AttachmentStatus) Public() bool {
|
||||
switch s {
|
||||
case AttachmentQueued, AttachmentProcessing, AttachmentReady, AttachmentFailed:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// VariantName is the contract variant identifier.
|
||||
type VariantName string
|
||||
|
||||
const (
|
||||
VariantOriginal VariantName = "original"
|
||||
VariantThumbnail VariantName = "thumbnail"
|
||||
VariantCrop VariantName = "crop"
|
||||
VariantOptimized VariantName = "optimized"
|
||||
)
|
||||
|
||||
func (n VariantName) Valid() bool {
|
||||
switch n {
|
||||
case VariantThumbnail, VariantCrop, VariantOptimized:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// ContentType returns the contract media type of the variant.
|
||||
func (n VariantName) ContentType() string {
|
||||
if n == VariantOptimized {
|
||||
return "image/webp"
|
||||
}
|
||||
|
||||
return "image/jpeg"
|
||||
}
|
||||
|
||||
// ObjectName returns the object suffix for the variant.
|
||||
func (n VariantName) ObjectName() string {
|
||||
if n == VariantOptimized {
|
||||
return string(n) + ".webp"
|
||||
}
|
||||
|
||||
return string(n) + ".jpg"
|
||||
}
|
||||
|
||||
// Variant is one derived image. ObjectKey is internal and never leaves the
|
||||
// service.
|
||||
type Variant struct {
|
||||
Name VariantName
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
Width int
|
||||
Height int
|
||||
SHA256 string
|
||||
ObjectKey string
|
||||
}
|
||||
|
||||
// Attachment describes the original object and the current pipeline result.
|
||||
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
|
||||
StagingKey string
|
||||
PipelineVersion int
|
||||
Variants []Variant
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
ReadyAt *time.Time
|
||||
FailedAt *time.Time
|
||||
}
|
||||
|
||||
// AdmissionLimits bounds accepted-but-unfinished work. Zero means unlimited.
|
||||
type AdmissionLimits struct {
|
||||
PerUser int
|
||||
Total int
|
||||
Bytes int64
|
||||
}
|
||||
|
||||
// AttachmentDraft is a fully validated attachment awaiting persistence.
|
||||
type AttachmentDraft struct {
|
||||
ID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
OwnerID uuid.UUID
|
||||
ObjectKey string
|
||||
StagingKey string
|
||||
Filename string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
SHA256 string
|
||||
Status AttachmentStatus
|
||||
PipelineVersion int
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// StaleStaging is one staging object whose owner row is already terminal.
|
||||
type StaleStaging struct {
|
||||
AttachmentID uuid.UUID
|
||||
StagingKey string
|
||||
Status AttachmentStatus
|
||||
}
|
||||
|
||||
// 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,19 @@
|
||||
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")
|
||||
ErrRateLimited = errors.New("too many unfinished uploads")
|
||||
)
|
||||
@@ -0,0 +1,192 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"regexp"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// JobType is the fixed contract type from contracts/jobs.schema.json.
|
||||
const JobType = "attachment.process.v1"
|
||||
|
||||
// JobStatus is the durable state of one logical processing job. Superseded is
|
||||
// internal: a newer pipeline version replaced the job before it completed.
|
||||
type JobStatus string
|
||||
|
||||
const (
|
||||
JobQueued JobStatus = "queued"
|
||||
JobProcessing JobStatus = "processing"
|
||||
JobReady JobStatus = "ready"
|
||||
JobFailed JobStatus = "failed"
|
||||
JobSuperseded JobStatus = "superseded"
|
||||
)
|
||||
|
||||
func (s JobStatus) Valid() bool {
|
||||
switch s {
|
||||
case JobQueued, JobProcessing, JobReady, JobFailed, JobSuperseded:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// Job is the durable processing intent. SourceKey is the trusted object the
|
||||
// worker reads: staging for a fresh upload, the original object for reprocess.
|
||||
type Job struct {
|
||||
ID uuid.UUID
|
||||
AttachmentID uuid.UUID
|
||||
PipelineVersion int
|
||||
SourceKey string
|
||||
Attempt int
|
||||
MaxAttempts int
|
||||
Status JobStatus
|
||||
AvailableAt time.Time
|
||||
LeaseOwner string
|
||||
LeaseExpiresAt *time.Time
|
||||
LastErrorCode *string
|
||||
ReplayCount int
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
CompletedAt *time.Time
|
||||
Traceparent string
|
||||
Tracestate string
|
||||
}
|
||||
|
||||
// OutboxMessage is one pending broker publication. Payload is the exact
|
||||
// jobs.schema.json document; no binary data or credentials are stored.
|
||||
type OutboxMessage struct {
|
||||
ID int64
|
||||
JobID uuid.UUID
|
||||
Attempt int
|
||||
Kind string
|
||||
RoutingKey string
|
||||
Payload []byte
|
||||
AvailableAt time.Time
|
||||
PublishedAt *time.Time
|
||||
ClaimedBy string
|
||||
ClaimedUntil *time.Time
|
||||
PublishAttempts int
|
||||
LastError *string
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
// JobMessage is the broker carrier defined by contracts/jobs.schema.json.
|
||||
type JobMessage struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
JobID uuid.UUID `json:"job_id"`
|
||||
Type string `json:"type"`
|
||||
AttachmentID uuid.UUID `json:"attachment_id"`
|
||||
PipelineVersion int `json:"pipeline_version"`
|
||||
Attempt int `json:"attempt"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
Traceparent string `json:"traceparent,omitempty"`
|
||||
Tracestate string `json:"tracestate,omitempty"`
|
||||
}
|
||||
|
||||
// NewJobMessage builds the only message the application is allowed to publish.
|
||||
func NewJobMessage(job Job) JobMessage {
|
||||
return JobMessage{
|
||||
SchemaVersion: 1,
|
||||
JobID: job.ID,
|
||||
Type: JobType,
|
||||
AttachmentID: job.AttachmentID,
|
||||
PipelineVersion: job.PipelineVersion,
|
||||
Attempt: job.Attempt,
|
||||
CreatedAt: job.CreatedAt.UTC(),
|
||||
}
|
||||
}
|
||||
|
||||
// Validate enforces the closed schema. The worker must never trust paths or
|
||||
// storage metadata from this message.
|
||||
func (m JobMessage) Validate() error {
|
||||
if m.SchemaVersion != 1 {
|
||||
return errors.New("unsupported schema_version")
|
||||
}
|
||||
|
||||
if m.Type != JobType {
|
||||
return fmt.Errorf("unsupported type %q", m.Type)
|
||||
}
|
||||
|
||||
if m.JobID == uuid.Nil || m.AttachmentID == uuid.Nil {
|
||||
return errors.New("job_id and attachment_id are required")
|
||||
}
|
||||
|
||||
if m.PipelineVersion < 1 || m.Attempt < 1 {
|
||||
return errors.New("pipeline_version and attempt must be >= 1")
|
||||
}
|
||||
|
||||
if m.CreatedAt.IsZero() {
|
||||
return errors.New("created_at is required")
|
||||
}
|
||||
|
||||
if m.Traceparent != "" && !traceparentPattern.MatchString(m.Traceparent) {
|
||||
return errors.New("traceparent does not match W3C format")
|
||||
}
|
||||
if len(m.Tracestate) > 512 {
|
||||
return errors.New("tracestate is too long")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
var traceparentPattern = regexp.MustCompile(`^00-[0-9a-f]{32}-[0-9a-f]{16}-[0-9a-f]{2}$`)
|
||||
|
||||
func (m JobMessage) MarshalPayload() ([]byte, error) {
|
||||
return json.Marshal(m)
|
||||
}
|
||||
|
||||
func ParseJobMessage(payload []byte) (JobMessage, error) {
|
||||
var message JobMessage
|
||||
|
||||
if err := json.Unmarshal(payload, &message); err != nil {
|
||||
return JobMessage{}, fmt.Errorf("decode job message: %w", err)
|
||||
}
|
||||
|
||||
if err := message.Validate(); err != nil {
|
||||
return JobMessage{}, err
|
||||
}
|
||||
|
||||
return message, nil
|
||||
}
|
||||
|
||||
// ClaimOutcome explains why a delivery did or did not become the active
|
||||
// processing attempt. The worker maps it to ack/nack without guessing.
|
||||
type ClaimOutcome string
|
||||
|
||||
const (
|
||||
ClaimAcquired ClaimOutcome = "acquired"
|
||||
ClaimAlreadyReady ClaimOutcome = "already_ready"
|
||||
ClaimAlreadyFailed ClaimOutcome = "already_failed"
|
||||
ClaimSuperseded ClaimOutcome = "superseded"
|
||||
ClaimStaleAttempt ClaimOutcome = "stale_attempt"
|
||||
ClaimFutureAttempt ClaimOutcome = "future_attempt"
|
||||
ClaimBusyLease ClaimOutcome = "busy_lease"
|
||||
ClaimNotDue ClaimOutcome = "not_due"
|
||||
ClaimVersionStale ClaimOutcome = "version_stale"
|
||||
ClaimJobNotFound ClaimOutcome = "job_not_found"
|
||||
ClaimSourceMissing ClaimOutcome = "source_missing"
|
||||
ClaimPayloadInvalid ClaimOutcome = "payload_invalid"
|
||||
)
|
||||
|
||||
type ClaimResult struct {
|
||||
Outcome ClaimOutcome
|
||||
Job Job
|
||||
Attachment Attachment
|
||||
}
|
||||
|
||||
// Job event names used by the operator audit trail.
|
||||
const (
|
||||
EventEnqueued = "enqueued"
|
||||
EventClaimed = "claimed"
|
||||
EventRetried = "retried"
|
||||
EventReady = "ready"
|
||||
EventFailed = "failed"
|
||||
EventLeaseExpired = "lease_expired"
|
||||
EventReplayed = "replayed"
|
||||
EventReprocessed = "reprocessed"
|
||||
EventSuperseded = "superseded"
|
||||
)
|
||||
@@ -0,0 +1,31 @@
|
||||
package domain
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
StagingUploadPrefix = "staging/uploads/"
|
||||
StagingVerifiedPrefix = "staging/verified/"
|
||||
StagingPresignPrefix = "staging/presign/"
|
||||
AttachmentsPrefix = "attachments/"
|
||||
)
|
||||
|
||||
func StagingUploadKey(chatID, attachmentID uuid.UUID) string {
|
||||
return StagingUploadPrefix + chatID.String() + "/" + attachmentID.String()
|
||||
}
|
||||
|
||||
func StagingVerifiedKey(chatID, attachmentID uuid.UUID) string {
|
||||
return StagingVerifiedPrefix + chatID.String() + "/" + attachmentID.String()
|
||||
}
|
||||
|
||||
func OriginalObjectKey(chatID, attachmentID uuid.UUID) string {
|
||||
return AttachmentsPrefix + chatID.String() + "/" + attachmentID.String() + "/original"
|
||||
}
|
||||
|
||||
func VariantObjectKey(chatID, attachmentID uuid.UUID, pipelineVersion int, name VariantName) string {
|
||||
return AttachmentsPrefix + chatID.String() + "/" + attachmentID.String() +
|
||||
"/variants/v" + strconv.Itoa(pipelineVersion) + "/" + name.ObjectName()
|
||||
}
|
||||
@@ -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,107 @@
|
||||
// Package failpoint implements deterministic, environment-gated crash windows
|
||||
// for the lab5 fault-injection evidence. Nothing fires unless FAULTS_ENABLED=1
|
||||
// and the action matches both FAULT_<ACTION> and, for job-scoped faults,
|
||||
// FAULT_TARGET_JOB. Production and CI leave the variables unset.
|
||||
package failpoint
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// Enabled reports whether fault injection is explicitly switched on.
|
||||
func Enabled() bool {
|
||||
if os.Getenv("FAULTS_ENABLED") != "1" {
|
||||
return false
|
||||
}
|
||||
|
||||
env := os.Getenv("APP_ENV")
|
||||
return env == "" || env == "dev"
|
||||
}
|
||||
|
||||
// Check exits the process if the action is armed for this job. It must be
|
||||
// called at the exact window the evidence describes; a marker line is written
|
||||
// before exit so the harness can prove the fault actually fired.
|
||||
func Check(action string, jobID uuid.UUID) {
|
||||
if !Enabled() {
|
||||
return
|
||||
}
|
||||
|
||||
if os.Getenv("FAULT_"+action) != "exit" {
|
||||
return
|
||||
}
|
||||
|
||||
target := os.Getenv("FAULT_TARGET_JOB")
|
||||
if target != "" && target != jobID.String() {
|
||||
return
|
||||
}
|
||||
|
||||
// A one-shot marker survives the container restart performed by the
|
||||
// restart policy. Without it a targeted crash failpoint would loop forever.
|
||||
marker := filepath.Join(os.TempDir(), "messenger-failpoint-"+action+"-"+jobID.String())
|
||||
if _, err := os.Stat(marker); err == nil {
|
||||
return
|
||||
}
|
||||
|
||||
_ = os.WriteFile(marker, []byte("fired\n"), 0o600)
|
||||
|
||||
slog.Default().Error("failpoint fired",
|
||||
slog.String("action", action),
|
||||
slog.String("job_id", jobID.String()),
|
||||
slog.Int("exit_code", 70),
|
||||
)
|
||||
_ = os.Stdout.Sync()
|
||||
_ = os.Stderr.Sync()
|
||||
|
||||
os.Exit(70)
|
||||
}
|
||||
|
||||
// Mode returns the armed value for an action/job pair. Unlike Check it does not
|
||||
// exit; the worker uses it to inject a permanent or transient processing error.
|
||||
func Mode(action string, jobID uuid.UUID) string {
|
||||
if !Enabled() {
|
||||
return ""
|
||||
}
|
||||
|
||||
target := os.Getenv("FAULT_TARGET_JOB")
|
||||
if target != "" && target != jobID.String() {
|
||||
return ""
|
||||
}
|
||||
|
||||
return os.Getenv("FAULT_" + action)
|
||||
}
|
||||
|
||||
// Sleep blocks for the configured duration when the action is armed for this
|
||||
// job. It is used for hang/slow-worker scenarios where the heartbeat must keep
|
||||
// running (the caller controls that separately).
|
||||
func Sleep(action string, jobID uuid.UUID) {
|
||||
if !Enabled() {
|
||||
return
|
||||
}
|
||||
|
||||
raw := os.Getenv("FAULT_" + action)
|
||||
if raw == "" {
|
||||
return
|
||||
}
|
||||
|
||||
target := os.Getenv("FAULT_TARGET_JOB")
|
||||
if target != "" && target != jobID.String() {
|
||||
return
|
||||
}
|
||||
|
||||
delay, err := time.ParseDuration(raw)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
slog.Default().Warn("failpoint sleeping",
|
||||
slog.String("action", action),
|
||||
slog.String("job_id", jobID.String()),
|
||||
slog.Duration("duration", delay),
|
||||
)
|
||||
time.Sleep(delay)
|
||||
}
|
||||
@@ -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,668 @@
|
||||
// Package imagecheck validates PNG and JPEG structure without decoding the
|
||||
// raster into an image. A full decode of a 40-megapixel image would allocate
|
||||
// hundreds of megabytes; attachment uploads must stay bounded. For PNG the
|
||||
// parser verifies chunk CRCs and streams the zlib image data to check exact
|
||||
// scanline sizes and filter types without keeping the raster in memory. The
|
||||
// JPEG parser verifies marker/scan structure. Both catch truncation and
|
||||
// corruption while using bounded memory.
|
||||
package imagecheck
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"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
|
||||
paletteReady bool
|
||||
trnsSeen bool
|
||||
colorType byte
|
||||
bitDepth byte
|
||||
paletteEntries int
|
||||
idat bytes.Buffer
|
||||
raster []pngPass
|
||||
rasterBytes int64
|
||||
maxIDAT int64 = -1
|
||||
lastChunk string
|
||||
)
|
||||
|
||||
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 seen[chunkType] && (chunkType == "IHDR" || chunkType == "PLTE" || chunkType == "IEND") {
|
||||
return Info{}, corruptf("png duplicate %s chunk", chunkType)
|
||||
}
|
||||
|
||||
if chunkType == "PLTE" && hasIDAT {
|
||||
return Info{}, corruptf("png PLTE chunk after IDAT")
|
||||
}
|
||||
|
||||
if chunkType == "IDAT" && seen["IDAT"] && lastChunk != "IDAT" {
|
||||
return Info{}, corruptf("png IDAT chunks must be consecutive")
|
||||
}
|
||||
|
||||
if err := checkCriticalChunk(chunkType, seen); err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
|
||||
var chunkSink io.Writer
|
||||
if chunkType == "IDAT" {
|
||||
if maxIDAT >= 0 && int64(idat.Len())+length > maxIDAT {
|
||||
return Info{}, corruptf("png idat compressed data exceeds %d bytes", maxIDAT)
|
||||
}
|
||||
|
||||
chunkSink = &idat
|
||||
}
|
||||
|
||||
data, err := readChunkData(reader, checksum, length, chunkSink)
|
||||
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]))
|
||||
colorType = data[9]
|
||||
bitDepth = data[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)
|
||||
}
|
||||
|
||||
bound, err := pngRasterLayout(info, data[8], data[9], data[10], data[11], data[12])
|
||||
if err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
|
||||
raster = bound
|
||||
rasterBytes = pngRasterBytes(bound)
|
||||
if rasterBytes <= 1<<40 {
|
||||
// zlib overhead: ~5 bytes per 16 KiB block, 2-byte header and
|
||||
// a 4-byte Adler trailer. The 1 MiB constant covers tiny
|
||||
// images where the relative term vanishes.
|
||||
maxIDAT = rasterBytes + rasterBytes/256 + 1<<20
|
||||
}
|
||||
case "IDAT":
|
||||
hasIDAT = true
|
||||
case "PLTE":
|
||||
if colorType == 0 || colorType == 4 {
|
||||
return Info{}, corruptf("png PLTE is invalid for color type %d", colorType)
|
||||
}
|
||||
|
||||
if length == 0 || length%3 != 0 || length > 3*256 {
|
||||
return Info{}, corruptf("png PLTE length %d", length)
|
||||
}
|
||||
|
||||
if length/3 > 1<<bitDepth {
|
||||
return Info{}, corruptf(
|
||||
"png PLTE has %d entries for bit depth %d", length/3, bitDepth,
|
||||
)
|
||||
}
|
||||
|
||||
if trnsSeen {
|
||||
return Info{}, corruptf("png PLTE chunk after tRNS")
|
||||
}
|
||||
|
||||
paletteEntries = int(length / 3)
|
||||
|
||||
if !hasIDAT {
|
||||
paletteReady = true
|
||||
}
|
||||
case "tRNS":
|
||||
if trnsSeen {
|
||||
return Info{}, corruptf("png duplicate tRNS chunk")
|
||||
}
|
||||
|
||||
if hasIDAT {
|
||||
return Info{}, corruptf("png tRNS chunk after IDAT")
|
||||
}
|
||||
|
||||
switch colorType {
|
||||
case 0:
|
||||
if length != 2 {
|
||||
return Info{}, corruptf("png tRNS length %d for color type 0", length)
|
||||
}
|
||||
case 2:
|
||||
if length != 6 {
|
||||
return Info{}, corruptf("png tRNS length %d for color type 2", length)
|
||||
}
|
||||
case 3:
|
||||
if !paletteReady {
|
||||
return Info{}, corruptf("png tRNS before PLTE")
|
||||
}
|
||||
|
||||
if length > 256 {
|
||||
return Info{}, corruptf("png tRNS length %d", length)
|
||||
}
|
||||
|
||||
if int(length) > paletteEntries {
|
||||
return Info{}, corruptf(
|
||||
"png tRNS length %d exceeds %d palette entries",
|
||||
length, paletteEntries,
|
||||
)
|
||||
}
|
||||
default:
|
||||
return Info{}, corruptf("png tRNS invalid for color type %d", colorType)
|
||||
}
|
||||
|
||||
trnsSeen = 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 colorType == 3 && !paletteReady {
|
||||
return Info{}, corruptf("png palette image has no PLTE before IDAT")
|
||||
}
|
||||
|
||||
// The chunk walker proves structure, but a stream whose bytes
|
||||
// merely look like a chunk layout (valid length/type/CRC) may
|
||||
// still not be a PNG raster: the zlib payload must inflate to
|
||||
// exactly the IHDR-declared scanlines with valid filter bytes.
|
||||
if err := validateRaster(idat.Bytes(), raster); err != nil {
|
||||
return Info{}, err
|
||||
}
|
||||
|
||||
if _, err := io.Copy(io.Discard, reader); err != nil {
|
||||
return Info{}, corrupt("png trailing data", err)
|
||||
}
|
||||
|
||||
return info, nil
|
||||
}
|
||||
|
||||
lastChunk = chunkType
|
||||
}
|
||||
}
|
||||
|
||||
// pngPass is one consecutive block of scanlines in the inflated image stream.
|
||||
// Non-interlaced PNGs have a single pass; Adam7 has up to seven.
|
||||
type pngPass struct {
|
||||
rowBytes int64
|
||||
rows int64
|
||||
}
|
||||
|
||||
type pngPassSpec struct {
|
||||
x0, y0 int64
|
||||
dx, dy int64
|
||||
}
|
||||
|
||||
var adam7Passes = []pngPassSpec{
|
||||
{x0: 0, y0: 0, dx: 8, dy: 8},
|
||||
{x0: 4, y0: 0, dx: 8, dy: 8},
|
||||
{x0: 0, y0: 4, dx: 4, dy: 8},
|
||||
{x0: 2, y0: 0, dx: 4, dy: 4},
|
||||
{x0: 0, y0: 2, dx: 2, dy: 4},
|
||||
{x0: 1, y0: 0, dx: 2, dy: 2},
|
||||
{x0: 0, y0: 1, dx: 1, dy: 2},
|
||||
}
|
||||
|
||||
// pngRasterLayout returns the exact inflated size and row layout for the
|
||||
// IHDR. The Adam7 layout matters: a single non-interlaced formula either
|
||||
// rejects valid interlaced images or accepts oversized streams.
|
||||
func pngRasterLayout(
|
||||
info Info,
|
||||
bitDepth, colorType, compression, filter, interlace byte,
|
||||
) ([]pngPass, error) {
|
||||
if compression != 0 || filter != 0 {
|
||||
return nil, corruptf(
|
||||
"png compression/filter method %d/%d", compression, filter,
|
||||
)
|
||||
}
|
||||
|
||||
var bitsPerPixel int64
|
||||
|
||||
switch colorType {
|
||||
case 0: // grayscale
|
||||
if bitDepth != 1 && bitDepth != 2 && bitDepth != 4 && bitDepth != 8 && bitDepth != 16 {
|
||||
return nil, corruptf("png invalid bit depth %d for color type 0", bitDepth)
|
||||
}
|
||||
|
||||
bitsPerPixel = int64(bitDepth)
|
||||
case 2: // truecolor
|
||||
if bitDepth != 8 && bitDepth != 16 {
|
||||
return nil, corruptf("png invalid bit depth %d for color type 2", bitDepth)
|
||||
}
|
||||
|
||||
bitsPerPixel = 3 * int64(bitDepth)
|
||||
case 3: // palette
|
||||
if bitDepth != 1 && bitDepth != 2 && bitDepth != 4 && bitDepth != 8 {
|
||||
return nil, corruptf("png invalid bit depth %d for color type 3", bitDepth)
|
||||
}
|
||||
|
||||
bitsPerPixel = int64(bitDepth)
|
||||
case 4: // grayscale + alpha
|
||||
if bitDepth != 8 && bitDepth != 16 {
|
||||
return nil, corruptf("png invalid bit depth %d for color type 4", bitDepth)
|
||||
}
|
||||
|
||||
bitsPerPixel = 2 * int64(bitDepth)
|
||||
case 6: // RGBA
|
||||
if bitDepth != 8 && bitDepth != 16 {
|
||||
return nil, corruptf("png invalid bit depth %d for color type 6", bitDepth)
|
||||
}
|
||||
|
||||
bitsPerPixel = 4 * int64(bitDepth)
|
||||
default:
|
||||
return nil, corruptf("png invalid color type %d", colorType)
|
||||
}
|
||||
|
||||
specs := []pngPassSpec{{x0: 0, y0: 0, dx: 1, dy: 1}}
|
||||
switch interlace {
|
||||
case 0:
|
||||
case 1:
|
||||
specs = adam7Passes
|
||||
default:
|
||||
return nil, corruptf("png invalid interlace method %d", interlace)
|
||||
}
|
||||
|
||||
passes := make([]pngPass, 0, len(specs))
|
||||
|
||||
for _, spec := range specs {
|
||||
if info.Width <= spec.x0 || info.Height <= spec.y0 {
|
||||
continue
|
||||
}
|
||||
|
||||
width := (info.Width - spec.x0 + spec.dx - 1) / spec.dx
|
||||
rows := (info.Height - spec.y0 + spec.dy - 1) / spec.dy
|
||||
rowBytes := (width*bitsPerPixel + 7) / 8
|
||||
|
||||
// Keep the total overflow-safe. Valid PNGs are additionally bounded
|
||||
// by the pixel limit checked by the caller.
|
||||
if rowBytes+1 > (1<<62)/rows {
|
||||
return nil, fmt.Errorf("%w: png dimensions overflow", ErrTooLarge)
|
||||
}
|
||||
|
||||
passes = append(passes, pngPass{rowBytes: rowBytes, rows: rows})
|
||||
}
|
||||
|
||||
return passes, nil
|
||||
}
|
||||
|
||||
func pngRasterBytes(passes []pngPass) int64 {
|
||||
var total int64
|
||||
|
||||
for _, pass := range passes {
|
||||
row := (pass.rowBytes + 1) * pass.rows
|
||||
if total > (1<<62)-row {
|
||||
return 1<<62 - 1
|
||||
}
|
||||
|
||||
total += row
|
||||
}
|
||||
|
||||
return total
|
||||
}
|
||||
|
||||
// validateRaster streams the inflated image data, checking every scanline
|
||||
// filter byte and requiring exactly the IHDR-declared number of rows. It
|
||||
// catches zlib streams that decompress cleanly but do not describe a valid
|
||||
// raster (empty payloads, bogus filter bytes) and rejects extra data as a
|
||||
// decompression bomb.
|
||||
func validateRaster(compressed []byte, passes []pngPass) error {
|
||||
source := bytes.NewReader(compressed)
|
||||
|
||||
reader, err := zlib.NewReader(source)
|
||||
if err != nil {
|
||||
return corrupt("png idat zlib header", err)
|
||||
}
|
||||
|
||||
for _, pass := range passes {
|
||||
for range pass.rows {
|
||||
var filter [1]byte
|
||||
if _, err := io.ReadFull(reader, filter[:]); err != nil {
|
||||
return corrupt("png scanline filter", err)
|
||||
}
|
||||
|
||||
if filter[0] > 4 {
|
||||
return corruptf("png invalid scanline filter %d", filter[0])
|
||||
}
|
||||
|
||||
if _, err := io.CopyN(io.Discard, reader, pass.rowBytes); err != nil {
|
||||
return corrupt("png scanline data", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var extra [1]byte
|
||||
switch _, err := io.ReadFull(reader, extra[:]); {
|
||||
case errors.Is(err, io.EOF):
|
||||
// A clean zlib EOF also verifies the Adler-32 trailer. bytes.Reader
|
||||
// satisfies io.ByteReader, so the inflater consumes exactly the zlib
|
||||
// stream; anything left is data after the stream, which PNG forbids.
|
||||
if source.Len() != 0 {
|
||||
return corruptf("png idat has %d trailing bytes", source.Len())
|
||||
}
|
||||
|
||||
return nil
|
||||
case err == nil:
|
||||
return fmt.Errorf("%w: png raster exceeds declared dimensions", ErrTooLarge)
|
||||
default:
|
||||
return corrupt("png idat zlib trailer", err)
|
||||
}
|
||||
}
|
||||
|
||||
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, sink io.Writer) ([]byte, error) {
|
||||
if length <= 64<<10 {
|
||||
data := make([]byte, length)
|
||||
if _, err := io.ReadFull(reader, data); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
_, _ = checksum.Write(data)
|
||||
if sink != nil {
|
||||
_, _ = sink.Write(data)
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
destination := checksum
|
||||
if sink != nil {
|
||||
destination = io.MultiWriter(checksum, sink)
|
||||
}
|
||||
|
||||
if _, err := io.CopyN(destination, 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,483 @@
|
||||
package imagecheck_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"compress/zlib"
|
||||
"encoding/binary"
|
||||
"hash/crc32"
|
||||
"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 pngChunk(ctype string, payload []byte) []byte {
|
||||
out := make([]byte, 12+len(payload))
|
||||
binary.BigEndian.PutUint32(out[0:4], uint32(len(payload)))
|
||||
copy(out[4:8], ctype)
|
||||
copy(out[8:], payload)
|
||||
|
||||
checksum := crc32.NewIEEE()
|
||||
_, _ = checksum.Write(out[4 : 8+len(payload)])
|
||||
binary.BigEndian.PutUint32(out[8+len(payload):], checksum.Sum32())
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func pngFile(chunks ...[]byte) []byte {
|
||||
data := []byte(pngSignatureForTest)
|
||||
for _, chunk := range chunks {
|
||||
data = append(data, chunk...)
|
||||
}
|
||||
|
||||
return data
|
||||
}
|
||||
|
||||
const pngSignatureForTest = "\x89PNG\r\n\x1a\n"
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
// Builds a structurally valid PNG (signature, well-formed IHDR/IDAT/IEND,
|
||||
// correct CRCs) whose IDAT payload is not a zlib stream at all. Merely a
|
||||
// stream-like structure must not make the upload pass: it has to inflate.
|
||||
func TestValidateRejectsPNGIDATNotAZlibStream(t *testing.T) {
|
||||
ihdr := make([]byte, 13)
|
||||
binary.BigEndian.PutUint32(ihdr[0:4], 64) // width
|
||||
binary.BigEndian.PutUint32(ihdr[4:8], 32) // height
|
||||
ihdr[8] = 8 // bit depth
|
||||
ihdr[9] = 6 // color type RGBA
|
||||
|
||||
data := pngFile(
|
||||
pngChunk("IHDR", ihdr),
|
||||
pngChunk("IDAT", []byte("this is not a zlib stream, but the CRC is right")),
|
||||
pngChunk("IEND", nil),
|
||||
)
|
||||
|
||||
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
|
||||
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
|
||||
}
|
||||
|
||||
func craftedPNG(t *testing.T, width, height int, interlace byte, raster []byte) []byte {
|
||||
t.Helper()
|
||||
|
||||
return craftedPNGType(t, width, height, 6, interlace, raster)
|
||||
}
|
||||
|
||||
func craftedPNGType(t *testing.T, width, height int, colorType, interlace byte, raster []byte) []byte {
|
||||
t.Helper()
|
||||
|
||||
return craftedPNGDepth(t, width, height, 8, colorType, interlace, raster)
|
||||
}
|
||||
|
||||
func craftedPNGDepth(t *testing.T, width, height int, bitDepth, colorType, interlace byte, raster []byte) []byte {
|
||||
t.Helper()
|
||||
|
||||
return pngFile(
|
||||
pngChunk("IHDR", pngIHDR(width, height, bitDepth, colorType, interlace)),
|
||||
pngChunk("IDAT", zlibBytes(t, raster)),
|
||||
pngChunk("IEND", nil),
|
||||
)
|
||||
}
|
||||
|
||||
func pngIHDR(width, height int, bitDepth, colorType, interlace byte) []byte {
|
||||
ihdr := make([]byte, 13)
|
||||
binary.BigEndian.PutUint32(ihdr[0:4], uint32(width))
|
||||
binary.BigEndian.PutUint32(ihdr[4:8], uint32(height))
|
||||
ihdr[8] = bitDepth
|
||||
ihdr[9] = colorType
|
||||
ihdr[12] = interlace
|
||||
|
||||
return ihdr
|
||||
}
|
||||
|
||||
func zlibBytes(t *testing.T, raster []byte) []byte {
|
||||
t.Helper()
|
||||
|
||||
var compressed bytes.Buffer
|
||||
|
||||
writer := zlib.NewWriter(&compressed)
|
||||
_, err := writer.Write(raster)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, writer.Close())
|
||||
|
||||
return compressed.Bytes()
|
||||
}
|
||||
|
||||
func TestValidateRejectsPNGEmptyRaster(t *testing.T) {
|
||||
data := craftedPNG(t, 2, 2, 0, nil)
|
||||
|
||||
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
|
||||
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
|
||||
}
|
||||
|
||||
func TestValidateRejectsPNGInvalidScanlineFilter(t *testing.T) {
|
||||
raster := []byte{5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
|
||||
data := craftedPNG(t, 2, 2, 0, raster)
|
||||
|
||||
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
|
||||
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
|
||||
}
|
||||
|
||||
func TestValidateRejectsPNGPaletteWithoutPLTE(t *testing.T) {
|
||||
raster := []byte{0, 0, 0, 0, 0, 0} // two rows of two 8-bit palette indexes
|
||||
data := craftedPNGType(t, 2, 2, 3, 0, raster)
|
||||
|
||||
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
|
||||
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
|
||||
}
|
||||
|
||||
func TestValidateAcceptsPalettePNG(t *testing.T) {
|
||||
palette := color.Palette{color.RGBA{R: 255, A: 255}, color.RGBA{G: 255, A: 255}, color.RGBA{B: 255, A: 255}}
|
||||
source := image.NewPaletted(image.Rect(0, 0, 13, 5), palette)
|
||||
for x := range 13 {
|
||||
for y := range 5 {
|
||||
source.SetColorIndex(x, y, uint8((x+y)%len(palette)))
|
||||
}
|
||||
}
|
||||
|
||||
var buffer bytes.Buffer
|
||||
require.NoError(t, png.Encode(&buffer, source))
|
||||
|
||||
info, err := imagecheck.Validate(bytes.NewReader(buffer.Bytes()), 40_000_000)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(13), info.Width)
|
||||
require.Equal(t, int64(5), info.Height)
|
||||
}
|
||||
|
||||
func TestValidateRejectsPNGInvalidColorDepthCombination(t *testing.T) {
|
||||
data := craftedPNGDepth(t, 1, 1, 1, 6, 0, []byte{0, 0, 0})
|
||||
|
||||
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
|
||||
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
|
||||
}
|
||||
|
||||
func TestValidateRejectsPNGDuplicateIHDR(t *testing.T) {
|
||||
ihdr := pngChunk("IHDR", pngIHDR(1, 1, 8, 6, 0))
|
||||
data := pngFile(
|
||||
ihdr,
|
||||
ihdr,
|
||||
pngChunk("IDAT", zlibBytes(t, []byte{0, 0, 0, 0, 0})),
|
||||
pngChunk("IEND", nil),
|
||||
)
|
||||
|
||||
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
|
||||
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
|
||||
}
|
||||
|
||||
func TestValidateRejectsPNGDuplicatePLTE(t *testing.T) {
|
||||
plte := pngChunk("PLTE", []byte{255, 0, 0})
|
||||
data := pngFile(
|
||||
pngChunk("IHDR", pngIHDR(1, 1, 8, 3, 0)),
|
||||
plte,
|
||||
plte,
|
||||
pngChunk("IDAT", zlibBytes(t, []byte{0, 0})),
|
||||
pngChunk("IEND", nil),
|
||||
)
|
||||
|
||||
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
|
||||
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
|
||||
}
|
||||
|
||||
func TestValidateRejectsPNGNonConsecutiveIDAT(t *testing.T) {
|
||||
compressed := zlibBytes(t, []byte{0, 0, 0, 0, 0})
|
||||
middle := len(compressed) / 2
|
||||
|
||||
data := pngFile(
|
||||
pngChunk("IHDR", pngIHDR(1, 1, 8, 6, 0)),
|
||||
pngChunk("IDAT", compressed[:middle]),
|
||||
pngChunk("tEXt", []byte("k\x00v")),
|
||||
pngChunk("IDAT", compressed[middle:]),
|
||||
pngChunk("IEND", nil),
|
||||
)
|
||||
|
||||
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
|
||||
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
|
||||
}
|
||||
|
||||
func TestValidateRejectsPNGTrailingIDATData(t *testing.T) {
|
||||
idat := append(zlibBytes(t, []byte{0, 0, 0, 0, 0}), []byte("junk")...)
|
||||
data := pngFile(
|
||||
pngChunk("IHDR", pngIHDR(1, 1, 8, 6, 0)),
|
||||
pngChunk("IDAT", idat),
|
||||
pngChunk("IEND", nil),
|
||||
)
|
||||
|
||||
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
|
||||
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
|
||||
}
|
||||
|
||||
func TestValidateAcceptsSplitIDAT(t *testing.T) {
|
||||
compressed := zlibBytes(t, []byte{0, 0, 0, 0, 0})
|
||||
middle := len(compressed) / 2
|
||||
|
||||
data := pngFile(
|
||||
pngChunk("IHDR", pngIHDR(1, 1, 8, 6, 0)),
|
||||
pngChunk("IDAT", compressed[:middle]),
|
||||
pngChunk("IDAT", compressed[middle:]),
|
||||
pngChunk("IEND", nil),
|
||||
)
|
||||
|
||||
info, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(1), info.Width)
|
||||
}
|
||||
|
||||
func TestValidateAcceptsStandardEncodings(t *testing.T) {
|
||||
bounds := image.Rect(0, 0, 7, 5)
|
||||
images := []image.Image{
|
||||
image.NewGray(bounds),
|
||||
image.NewGray16(bounds),
|
||||
image.NewRGBA(bounds),
|
||||
image.NewNRGBA(bounds),
|
||||
image.NewNRGBA64(bounds),
|
||||
}
|
||||
|
||||
for _, source := range images {
|
||||
var buffer bytes.Buffer
|
||||
require.NoError(t, png.Encode(&buffer, source))
|
||||
|
||||
info, err := imagecheck.Validate(bytes.NewReader(buffer.Bytes()), 40_000_000)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(7), info.Width)
|
||||
require.Equal(t, int64(5), info.Height)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRejectsPNGPLTEEntriesExceedBitDepth(t *testing.T) {
|
||||
data := pngFile(
|
||||
pngChunk("IHDR", pngIHDR(1, 1, 1, 3, 0)),
|
||||
pngChunk("PLTE", []byte{255, 0, 0, 0, 255, 0, 0, 0, 255}),
|
||||
pngChunk("IDAT", zlibBytes(t, []byte{0, 0})),
|
||||
pngChunk("IEND", nil),
|
||||
)
|
||||
|
||||
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
|
||||
require.ErrorIs(t, err, imagecheck.ErrCorrupt)
|
||||
}
|
||||
|
||||
func TestValidateRejectsInvalidTRNS(t *testing.T) {
|
||||
rgb := pngChunk("IDAT", zlibBytes(t, []byte{0, 10, 20, 30}))
|
||||
gray := pngChunk("IDAT", zlibBytes(t, []byte{0, 10}))
|
||||
rgba := pngChunk("IDAT", zlibBytes(t, []byte{0, 10, 20, 30, 255}))
|
||||
paletted := pngChunk("IDAT", zlibBytes(t, []byte{0, 0}))
|
||||
|
||||
cases := map[string][]byte{
|
||||
"tRNS on RGBA": pngFile(
|
||||
pngChunk("IHDR", pngIHDR(1, 1, 8, 6, 0)),
|
||||
pngChunk("tRNS", []byte{0}),
|
||||
rgba,
|
||||
pngChunk("IEND", nil),
|
||||
),
|
||||
"RGB length": pngFile(
|
||||
pngChunk("IHDR", pngIHDR(1, 1, 8, 2, 0)),
|
||||
pngChunk("tRNS", []byte{0}),
|
||||
rgb,
|
||||
pngChunk("IEND", nil),
|
||||
),
|
||||
"gray length": pngFile(
|
||||
pngChunk("IHDR", pngIHDR(1, 1, 8, 0, 0)),
|
||||
pngChunk("tRNS", []byte{0}),
|
||||
gray,
|
||||
pngChunk("IEND", nil),
|
||||
),
|
||||
"palette before PLTE": pngFile(
|
||||
pngChunk("IHDR", pngIHDR(1, 1, 8, 3, 0)),
|
||||
pngChunk("tRNS", []byte{0}),
|
||||
pngChunk("PLTE", []byte{255, 0, 0, 0, 255, 0}),
|
||||
paletted,
|
||||
pngChunk("IEND", nil),
|
||||
),
|
||||
"palette tRNS longer than PLTE": pngFile(
|
||||
pngChunk("IHDR", pngIHDR(1, 1, 8, 3, 0)),
|
||||
pngChunk("PLTE", []byte{255, 0, 0}),
|
||||
pngChunk("tRNS", []byte{0, 0}),
|
||||
paletted,
|
||||
pngChunk("IEND", nil),
|
||||
),
|
||||
"duplicate tRNS": pngFile(
|
||||
pngChunk("IHDR", pngIHDR(1, 1, 8, 2, 0)),
|
||||
pngChunk("tRNS", make([]byte, 6)),
|
||||
pngChunk("tRNS", make([]byte, 6)),
|
||||
rgb,
|
||||
pngChunk("IEND", nil),
|
||||
),
|
||||
"tRNS after IDAT": pngFile(
|
||||
pngChunk("IHDR", pngIHDR(1, 1, 8, 2, 0)),
|
||||
rgb,
|
||||
pngChunk("tRNS", make([]byte, 6)),
|
||||
pngChunk("IEND", nil),
|
||||
),
|
||||
}
|
||||
|
||||
for name, data := range cases {
|
||||
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
|
||||
require.ErrorIs(t, err, imagecheck.ErrCorrupt, name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateAcceptsValidTRNS(t *testing.T) {
|
||||
cases := map[string][]byte{
|
||||
"RGB": pngFile(
|
||||
pngChunk("IHDR", pngIHDR(1, 1, 8, 2, 0)),
|
||||
pngChunk("tRNS", make([]byte, 6)),
|
||||
pngChunk("IDAT", zlibBytes(t, []byte{0, 10, 20, 30})),
|
||||
pngChunk("IEND", nil),
|
||||
),
|
||||
"gray": pngFile(
|
||||
pngChunk("IHDR", pngIHDR(1, 1, 8, 0, 0)),
|
||||
pngChunk("tRNS", make([]byte, 2)),
|
||||
pngChunk("IDAT", zlibBytes(t, []byte{0, 10})),
|
||||
pngChunk("IEND", nil),
|
||||
),
|
||||
"palette": pngFile(
|
||||
pngChunk("IHDR", pngIHDR(1, 1, 1, 3, 0)),
|
||||
pngChunk("PLTE", []byte{255, 0, 0, 0, 255, 0}),
|
||||
pngChunk("tRNS", []byte{128}),
|
||||
pngChunk("IDAT", zlibBytes(t, []byte{0, 0})),
|
||||
pngChunk("IEND", nil),
|
||||
),
|
||||
}
|
||||
|
||||
for name, data := range cases {
|
||||
_, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
|
||||
require.NoError(t, err, name)
|
||||
}
|
||||
}
|
||||
|
||||
// A valid Adam7 stream for a tall, narrow image exceeds the old
|
||||
// (rowBytes+1)*(height+8) guess; the exact pass layout must accept it.
|
||||
func TestValidateAcceptsAdam7PNG(t *testing.T) {
|
||||
const width, height = 2, 256
|
||||
|
||||
var raster bytes.Buffer
|
||||
|
||||
passes := [][4]int{
|
||||
{0, 0, 8, 8},
|
||||
{4, 0, 8, 8},
|
||||
{0, 4, 4, 8},
|
||||
{2, 0, 4, 4},
|
||||
{0, 2, 2, 4},
|
||||
{1, 0, 2, 2},
|
||||
{0, 1, 1, 2},
|
||||
}
|
||||
for _, pass := range passes {
|
||||
x0, y0, dx, dy := pass[0], pass[1], pass[2], pass[3]
|
||||
if width <= x0 || height <= y0 {
|
||||
continue
|
||||
}
|
||||
|
||||
for y := y0; y < height; y += dy {
|
||||
raster.WriteByte(0) // filter: none
|
||||
|
||||
for x := x0; x < width; x += dx {
|
||||
raster.Write([]byte{byte(x), byte(y), 128, 255})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
data := craftedPNG(t, width, height, 1, raster.Bytes())
|
||||
|
||||
info, err := imagecheck.Validate(bytes.NewReader(data), 40_000_000)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, int64(width), info.Width)
|
||||
require.Equal(t, int64(height), info.Height)
|
||||
}
|
||||
|
||||
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,118 @@
|
||||
package imageproc
|
||||
|
||||
import (
|
||||
"encoding/binary"
|
||||
"io"
|
||||
)
|
||||
|
||||
const (
|
||||
exifMaxBytes = 64 << 10
|
||||
exifTagOrient = 0x0112
|
||||
)
|
||||
|
||||
// readEXIFOrientation extracts only IFD0 Orientation from a JPEG APP1 segment.
|
||||
// The parser is deliberately small and bounded: no TIFF offsets are trusted and
|
||||
// the whole segment is capped at 64 KiB, so attacker-controlled EXIF cannot make
|
||||
// the worker allocate unbounded memory.
|
||||
func readEXIFOrientation(r io.Reader) int {
|
||||
data, err := io.ReadAll(io.LimitReader(r, exifMaxBytes))
|
||||
if err != nil || len(data) < 4 || data[0] != 0xff || data[1] != 0xd8 {
|
||||
return 1
|
||||
}
|
||||
|
||||
pos := 2
|
||||
|
||||
for pos+4 <= len(data) {
|
||||
if data[pos] != 0xff {
|
||||
return 1
|
||||
}
|
||||
|
||||
marker := data[pos+1]
|
||||
pos += 2
|
||||
|
||||
// Standalone markers without a length field.
|
||||
if marker == 0xd8 || marker == 0xd9 || marker == 0x01 || (marker >= 0xd0 && marker <= 0xd7) {
|
||||
continue
|
||||
}
|
||||
|
||||
if pos+2 > len(data) {
|
||||
return 1
|
||||
}
|
||||
|
||||
length := int(binary.BigEndian.Uint16(data[pos : pos+2]))
|
||||
if length < 2 || pos+length > len(data) {
|
||||
return 1
|
||||
}
|
||||
|
||||
segment := data[pos+2 : pos+length]
|
||||
pos += length
|
||||
|
||||
if marker != 0xe1 || len(segment) < 6 {
|
||||
continue
|
||||
}
|
||||
|
||||
if string(segment[:6]) != "Exif\x00\x00" {
|
||||
continue
|
||||
}
|
||||
|
||||
return parseTIFFOrientation(segment[6:])
|
||||
}
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
func parseTIFFOrientation(tiff []byte) int {
|
||||
if len(tiff) < 8 {
|
||||
return 1
|
||||
}
|
||||
|
||||
var order binary.ByteOrder
|
||||
|
||||
switch string(tiff[:2]) {
|
||||
case "II":
|
||||
order = binary.LittleEndian
|
||||
case "MM":
|
||||
order = binary.BigEndian
|
||||
default:
|
||||
return 1
|
||||
}
|
||||
|
||||
if order.Uint16(tiff[2:4]) != 42 {
|
||||
return 1
|
||||
}
|
||||
|
||||
ifdOffset := int(order.Uint32(tiff[4:8]))
|
||||
if ifdOffset < 8 || ifdOffset+2 > len(tiff) {
|
||||
return 1
|
||||
}
|
||||
|
||||
count := int(order.Uint16(tiff[ifdOffset : ifdOffset+2]))
|
||||
if count > 512 {
|
||||
count = 512
|
||||
}
|
||||
|
||||
entry := ifdOffset + 2
|
||||
|
||||
for range count {
|
||||
if entry+12 > len(tiff) {
|
||||
return 1
|
||||
}
|
||||
|
||||
tag := order.Uint16(tiff[entry : entry+2])
|
||||
typ := order.Uint16(tiff[entry+2 : entry+4])
|
||||
n := order.Uint32(tiff[entry+4 : entry+8])
|
||||
|
||||
if tag == exifTagOrient && typ == 3 && n == 1 {
|
||||
value := order.Uint16(tiff[entry+8 : entry+10])
|
||||
if value >= 1 && value <= 8 {
|
||||
return int(value)
|
||||
}
|
||||
|
||||
return 1
|
||||
}
|
||||
|
||||
entry += 12
|
||||
}
|
||||
|
||||
return 1
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
// Package imageproc turns one decoded original into the contract variants.
|
||||
// Output bytes are deterministic for a given pipeline version, source bytes and
|
||||
// encoder versions; the worker uses that property for idempotent retries.
|
||||
package imageproc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
_ "image/png" // register the PNG decoder
|
||||
"io"
|
||||
"math"
|
||||
"os"
|
||||
|
||||
"github.com/gen2brain/webp"
|
||||
xdraw "golang.org/x/image/draw"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
const (
|
||||
thumbnailMax = 256
|
||||
cropSize = 128
|
||||
optimizedMax = 1280
|
||||
defaultMethod = 2
|
||||
)
|
||||
|
||||
// Params are immutable per pipeline version. They are compiled into the binary
|
||||
// so a retry can never silently produce different bytes than the first attempt.
|
||||
type Params struct {
|
||||
JPEGQuality int
|
||||
WebPQuality int
|
||||
WebPMethod int
|
||||
}
|
||||
|
||||
// Pipeline returns the versioned encoder parameters. Only v1 and v2 are
|
||||
// defined; the course baseline is v1.
|
||||
func Pipeline(version int) (Params, bool) {
|
||||
switch version {
|
||||
case 1:
|
||||
return Params{JPEGQuality: 85, WebPQuality: 80, WebPMethod: defaultMethod}, true
|
||||
case 2:
|
||||
return Params{JPEGQuality: 70, WebPQuality: 65, WebPMethod: 4}, true
|
||||
default:
|
||||
return Params{}, false
|
||||
}
|
||||
}
|
||||
|
||||
// Image is one encoded variant.
|
||||
type Image struct {
|
||||
Name domain.VariantName
|
||||
ContentType string
|
||||
Data []byte
|
||||
SizeBytes int64
|
||||
Width int
|
||||
Height int
|
||||
SHA256 string
|
||||
}
|
||||
|
||||
// Load decodes a PNG/JPEG file, applies EXIF orientation and composites alpha
|
||||
// on white. The returned image is always *image.RGBA, which bounds the variant
|
||||
// encoders to 8-bit output.
|
||||
func Load(path string, maxPixels int64) (image.Image, string, error) {
|
||||
file, err := os.Open(path)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("open source: %w", err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
cfg, format, err := image.DecodeConfig(file)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("decode config: %w", err)
|
||||
}
|
||||
|
||||
if cfg.Width <= 0 || cfg.Height <= 0 {
|
||||
return nil, "", fmt.Errorf("invalid dimensions %dx%d", cfg.Width, cfg.Height)
|
||||
}
|
||||
|
||||
if maxPixels > 0 && int64(cfg.Width)*int64(cfg.Height) > maxPixels {
|
||||
return nil, "", fmt.Errorf("image has %d pixels, limit %d", int64(cfg.Width)*int64(cfg.Height), maxPixels)
|
||||
}
|
||||
|
||||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, "", fmt.Errorf("rewind source: %w", err)
|
||||
}
|
||||
|
||||
decoded, _, err := image.Decode(file)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("decode image: %w", err)
|
||||
}
|
||||
|
||||
orientation := 1
|
||||
if format == "jpeg" {
|
||||
if _, err := file.Seek(0, io.SeekStart); err == nil {
|
||||
orientation = readEXIFOrientation(file)
|
||||
}
|
||||
}
|
||||
|
||||
return toWhiteRGBA(decoded, orientation), format, nil
|
||||
}
|
||||
|
||||
func toWhiteRGBA(src image.Image, orientation int) image.Image {
|
||||
transformed := orient(src, orientation)
|
||||
bounds := transformed.Bounds()
|
||||
|
||||
dst := image.NewRGBA(image.Rect(0, 0, bounds.Dx(), bounds.Dy()))
|
||||
xdraw.Draw(dst, dst.Bounds(), image.NewUniform(color.White), image.Point{}, xdraw.Src)
|
||||
xdraw.Draw(dst, dst.Bounds(), transformed, bounds.Min, xdraw.Over)
|
||||
|
||||
return dst
|
||||
}
|
||||
|
||||
// orient applies the eight EXIF orientation values. The result has the same
|
||||
// bounds as the source except for 90-degree rotations.
|
||||
func orient(src image.Image, orientation int) image.Image {
|
||||
if orientation < 2 || orientation > 8 {
|
||||
return src
|
||||
}
|
||||
|
||||
b := src.Bounds()
|
||||
w, h := b.Dx(), b.Dy()
|
||||
|
||||
width, height := w, h
|
||||
if orientation >= 5 {
|
||||
width, height = h, w
|
||||
}
|
||||
|
||||
dst := image.NewRGBA(image.Rect(0, 0, width, height))
|
||||
|
||||
for y := range h {
|
||||
for x := range w {
|
||||
nx, ny := orientPoint(orientation, x, y, w, h)
|
||||
|
||||
dst.Set(nx, ny, src.At(b.Min.X+x, b.Min.Y+y))
|
||||
}
|
||||
}
|
||||
|
||||
return dst
|
||||
}
|
||||
|
||||
func orientPoint(orientation, x, y, w, h int) (int, int) {
|
||||
switch orientation {
|
||||
case 2:
|
||||
return w - 1 - x, y
|
||||
case 3:
|
||||
return w - 1 - x, h - 1 - y
|
||||
case 4:
|
||||
return x, h - 1 - y
|
||||
case 5:
|
||||
return y, x
|
||||
case 6:
|
||||
return h - 1 - y, x
|
||||
case 7:
|
||||
return h - 1 - y, w - 1 - x
|
||||
case 8:
|
||||
return y, w - 1 - x
|
||||
default:
|
||||
return x, y
|
||||
}
|
||||
}
|
||||
|
||||
// Thumbnail fits inside 256x256 without upscaling; dimensions are floored and
|
||||
// never below 1 px.
|
||||
func Thumbnail(src image.Image, params Params) (Image, error) {
|
||||
return encodeJPEG(fit(src, thumbnailMax, thumbnailMax, false), domain.VariantThumbnail, params)
|
||||
}
|
||||
|
||||
// Crop takes the centered square and scales it to 128x128. Upscaling small
|
||||
// sources is allowed by the contract.
|
||||
func Crop(src image.Image, params Params) (Image, error) {
|
||||
b := src.Bounds()
|
||||
side := b.Dx()
|
||||
if b.Dy() < side {
|
||||
side = b.Dy()
|
||||
}
|
||||
|
||||
left := b.Min.X + (b.Dx()-side)/2
|
||||
top := b.Min.Y + (b.Dy()-side)/2
|
||||
|
||||
square := image.NewRGBA(image.Rect(0, 0, side, side))
|
||||
xdraw.Draw(square, square.Bounds(), src, image.Pt(left, top), xdraw.Src)
|
||||
|
||||
dst := image.NewRGBA(image.Rect(0, 0, cropSize, cropSize))
|
||||
xdraw.CatmullRom.Scale(dst, dst.Bounds(), square, square.Bounds(), xdraw.Over, nil)
|
||||
|
||||
return encodeJPEG(dst, domain.VariantCrop, params)
|
||||
}
|
||||
|
||||
// Optimized fits inside 1280x1280 without upscaling and encodes WebP. Metadata
|
||||
// is stripped because the output is a fresh re-encode.
|
||||
func Optimized(src image.Image, params Params) (Image, error) {
|
||||
dst := fit(src, optimizedMax, optimizedMax, false)
|
||||
|
||||
var buf bytes.Buffer
|
||||
|
||||
if err := webp.Encode(&buf, dst, webp.Options{
|
||||
Quality: params.WebPQuality,
|
||||
Method: params.WebPMethod,
|
||||
}); err != nil {
|
||||
return Image{}, fmt.Errorf("encode webp: %w", err)
|
||||
}
|
||||
|
||||
return newImage(domain.VariantOptimized, "image/webp", buf.Bytes(), dst.Bounds().Dx(), dst.Bounds().Dy()), nil
|
||||
}
|
||||
|
||||
func encodeJPEG(dst image.Image, name domain.VariantName, params Params) (Image, error) {
|
||||
var buf bytes.Buffer
|
||||
|
||||
if err := jpeg.Encode(&buf, dst, &jpeg.Options{Quality: params.JPEGQuality}); err != nil {
|
||||
return Image{}, fmt.Errorf("encode jpeg: %w", err)
|
||||
}
|
||||
|
||||
return newImage(name, "image/jpeg", buf.Bytes(), dst.Bounds().Dx(), dst.Bounds().Dy()), nil
|
||||
}
|
||||
|
||||
func newImage(name domain.VariantName, contentType string, data []byte, width, height int) Image {
|
||||
sum := sha256.Sum256(data)
|
||||
|
||||
return Image{
|
||||
Name: name,
|
||||
ContentType: contentType,
|
||||
Data: data,
|
||||
SizeBytes: int64(len(data)),
|
||||
Width: width,
|
||||
Height: height,
|
||||
SHA256: hex.EncodeToString(sum[:]),
|
||||
}
|
||||
}
|
||||
|
||||
// fit scales src into maxWidth x maxHeight preserving aspect ratio, floors the
|
||||
// dimensions, enforces at least 1 px and, unless allowUpscale is set, never
|
||||
// enlarges the source.
|
||||
func fit(src image.Image, maxWidth, maxHeight int, allowUpscale bool) *image.RGBA {
|
||||
b := src.Bounds()
|
||||
w, h := b.Dx(), b.Dy()
|
||||
|
||||
scale := math.Min(float64(maxWidth)/float64(w), float64(maxHeight)/float64(h))
|
||||
if !allowUpscale && scale > 1 {
|
||||
scale = 1
|
||||
}
|
||||
|
||||
width := int(math.Floor(float64(w) * scale))
|
||||
height := int(math.Floor(float64(h) * scale))
|
||||
if width < 1 {
|
||||
width = 1
|
||||
}
|
||||
if height < 1 {
|
||||
height = 1
|
||||
}
|
||||
|
||||
dst := image.NewRGBA(image.Rect(0, 0, width, height))
|
||||
xdraw.CatmullRom.Scale(dst, dst.Bounds(), src, b, xdraw.Over, nil)
|
||||
|
||||
return dst
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package imageproc_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/jpeg"
|
||||
"image/png"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/gen2brain/webp"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/imageproc"
|
||||
)
|
||||
|
||||
func writePNG(t *testing.T, width, height int, alpha bool) string {
|
||||
t.Helper()
|
||||
|
||||
img := image.NewNRGBA(image.Rect(0, 0, width, height))
|
||||
for x := range width {
|
||||
for y := range height {
|
||||
a := uint8(255)
|
||||
if alpha && x < width/2 && y < height/2 {
|
||||
a = 0
|
||||
}
|
||||
img.Set(x, y, color.NRGBA{R: 200, G: 40, B: 20, A: a})
|
||||
}
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
require.NoError(t, png.Encode(&buf, img))
|
||||
|
||||
path := filepath.Join(t.TempDir(), "source.png")
|
||||
require.NoError(t, os.WriteFile(path, buf.Bytes(), 0o600))
|
||||
|
||||
return path
|
||||
}
|
||||
|
||||
func writeJPEG(t *testing.T, width, height, orientation int) string {
|
||||
t.Helper()
|
||||
|
||||
img := image.NewRGBA(image.Rect(0, 0, width, height))
|
||||
for x := range width {
|
||||
for y := range height {
|
||||
img.Set(x, y, color.RGBA{R: 200, G: 40, B: 20, A: 255})
|
||||
}
|
||||
}
|
||||
|
||||
var raw bytes.Buffer
|
||||
require.NoError(t, jpeg.Encode(&raw, img, &jpeg.Options{Quality: 95}))
|
||||
|
||||
data := append([]byte(nil), raw.Bytes()...)
|
||||
if orientation > 1 {
|
||||
data = insertEXIFOrientation(t, data, uint16(orientation))
|
||||
}
|
||||
|
||||
path := filepath.Join(t.TempDir(), "source.jpg")
|
||||
require.NoError(t, os.WriteFile(path, data, 0o600))
|
||||
|
||||
return path
|
||||
}
|
||||
|
||||
func insertEXIFOrientation(t *testing.T, jpegBytes []byte, orientation uint16) []byte {
|
||||
t.Helper()
|
||||
|
||||
// TIFF: II, 42, IFD0 at offset 8, one entry (0x0112 SHORT 1 = orientation).
|
||||
tiff := make([]byte, 8+2+12+4)
|
||||
binary.LittleEndian.PutUint16(tiff[0:2], 0x4949)
|
||||
binary.LittleEndian.PutUint16(tiff[2:4], 42)
|
||||
binary.LittleEndian.PutUint32(tiff[4:8], 8)
|
||||
binary.LittleEndian.PutUint16(tiff[8:10], 1)
|
||||
binary.LittleEndian.PutUint16(tiff[10:12], 0x0112)
|
||||
binary.LittleEndian.PutUint16(tiff[12:14], 3)
|
||||
binary.LittleEndian.PutUint32(tiff[14:18], 1)
|
||||
binary.LittleEndian.PutUint16(tiff[18:20], orientation)
|
||||
|
||||
payload := append([]byte("Exif\x00\x00"), tiff...)
|
||||
segment := make([]byte, 4+len(payload))
|
||||
segment[0] = 0xff
|
||||
segment[1] = 0xe1
|
||||
binary.BigEndian.PutUint16(segment[2:4], uint16(len(payload)+2))
|
||||
copy(segment[4:], payload)
|
||||
|
||||
// Insert immediately after SOI (before the first DQT/SOF).
|
||||
out := append([]byte(nil), jpegBytes[:2]...)
|
||||
out = append(out, segment...)
|
||||
out = append(out, jpegBytes[2:]...)
|
||||
|
||||
return out
|
||||
}
|
||||
|
||||
func decodeConfig(t *testing.T, data []byte) image.Config {
|
||||
t.Helper()
|
||||
|
||||
cfg, _, err := image.DecodeConfig(bytes.NewReader(data))
|
||||
require.NoError(t, err)
|
||||
|
||||
return cfg
|
||||
}
|
||||
|
||||
func TestThumbnailContract(t *testing.T) {
|
||||
params, ok := imageproc.Pipeline(1)
|
||||
require.True(t, ok)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
width int
|
||||
height int
|
||||
expected [2]int
|
||||
}{
|
||||
{"320x200", 320, 200, [2]int{256, 160}},
|
||||
{"no upscale 64x64", 64, 64, [2]int{64, 64}},
|
||||
{"no upscale 64x40", 64, 40, [2]int{64, 40}},
|
||||
{"floor 1000x10", 1000, 10, [2]int{256, 2}},
|
||||
{"height limited", 100, 320, [2]int{80, 256}},
|
||||
{"minimum 1x1", 1, 1, [2]int{1, 1}},
|
||||
}
|
||||
|
||||
for _, test := range cases {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
img, _, err := imageproc.Load(writePNG(t, test.width, test.height, false), 40_000_000)
|
||||
require.NoError(t, err)
|
||||
|
||||
thumb, err := imageproc.Thumbnail(img, params)
|
||||
require.NoError(t, err)
|
||||
|
||||
cfg := decodeConfig(t, thumb.Data)
|
||||
require.Equal(t, test.expected[0], cfg.Width)
|
||||
require.Equal(t, test.expected[1], cfg.Height)
|
||||
require.Equal(t, test.expected[0], thumb.Width)
|
||||
require.Equal(t, test.expected[1], thumb.Height)
|
||||
require.Equal(t, "image/jpeg", thumb.ContentType)
|
||||
require.NotContains(t, string(thumb.Data), "Exif")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCropAndOptimized(t *testing.T) {
|
||||
params, ok := imageproc.Pipeline(1)
|
||||
require.True(t, ok)
|
||||
|
||||
img, _, err := imageproc.Load(writePNG(t, 320, 200, false), 40_000_000)
|
||||
require.NoError(t, err)
|
||||
|
||||
crop, err := imageproc.Crop(img, params)
|
||||
require.NoError(t, err)
|
||||
cfg := decodeConfig(t, crop.Data)
|
||||
require.Equal(t, 128, cfg.Width)
|
||||
require.Equal(t, 128, cfg.Height)
|
||||
|
||||
optimized, err := imageproc.Optimized(img, params)
|
||||
require.NoError(t, err)
|
||||
cfg = decodeConfig(t, optimized.Data)
|
||||
require.Equal(t, 320, cfg.Width)
|
||||
require.Equal(t, 200, cfg.Height)
|
||||
require.Equal(t, "image/webp", optimized.ContentType)
|
||||
|
||||
decoded, err := webp.Decode(bytes.NewReader(optimized.Data))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 320, decoded.Bounds().Dx())
|
||||
require.Equal(t, 200, decoded.Bounds().Dy())
|
||||
}
|
||||
|
||||
func TestEXIFOrientationChangesThumbnailDimensions(t *testing.T) {
|
||||
params, ok := imageproc.Pipeline(1)
|
||||
require.True(t, ok)
|
||||
|
||||
for _, orientation := range []int{6, 8} {
|
||||
img, _, err := imageproc.Load(writeJPEG(t, 320, 200, orientation), 40_000_000)
|
||||
require.NoError(t, err)
|
||||
|
||||
thumb, err := imageproc.Thumbnail(img, params)
|
||||
require.NoError(t, err)
|
||||
|
||||
cfg := decodeConfig(t, thumb.Data)
|
||||
require.Equal(t, 160, cfg.Width, "orientation %d", orientation)
|
||||
require.Equal(t, 256, cfg.Height, "orientation %d", orientation)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAlphaCompositedOnWhite(t *testing.T) {
|
||||
params, ok := imageproc.Pipeline(1)
|
||||
require.True(t, ok)
|
||||
|
||||
img, _, err := imageproc.Load(writePNG(t, 100, 100, true), 40_000_000)
|
||||
require.NoError(t, err)
|
||||
|
||||
thumb, err := imageproc.Thumbnail(img, params)
|
||||
require.NoError(t, err)
|
||||
|
||||
decoded, err := jpeg.Decode(bytes.NewReader(thumb.Data))
|
||||
require.NoError(t, err)
|
||||
|
||||
r, g, b, _ := decoded.At(0, 0).RGBA()
|
||||
require.Greater(t, r, uint32(0xf000), "transparent corner must be white")
|
||||
require.Greater(t, g, uint32(0xf000), "transparent corner must be white")
|
||||
require.Greater(t, b, uint32(0xf000), "transparent corner must be white")
|
||||
}
|
||||
|
||||
func TestPipelineVersionsDiffer(t *testing.T) {
|
||||
v1, ok := imageproc.Pipeline(1)
|
||||
require.True(t, ok)
|
||||
v2, ok := imageproc.Pipeline(2)
|
||||
require.True(t, ok)
|
||||
require.NotEqual(t, v1, v2)
|
||||
|
||||
_, ok = imageproc.Pipeline(3)
|
||||
require.False(t, ok)
|
||||
}
|
||||
|
||||
func TestVariantNames(t *testing.T) {
|
||||
require.Equal(t, "image/jpeg", domain.VariantThumbnail.ContentType())
|
||||
require.Equal(t, "image/jpeg", domain.VariantCrop.ContentType())
|
||||
require.Equal(t, "image/webp", domain.VariantOptimized.ContentType())
|
||||
require.Equal(t, "thumbnail.jpg", domain.VariantThumbnail.ObjectName())
|
||||
require.Equal(t, "optimized.webp", domain.VariantOptimized.ObjectName())
|
||||
}
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
// Package outbox publishes the durable job intents with publisher confirms and
|
||||
// reclaims abandoned relay claims and expired worker leases.
|
||||
package outbox
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/failpoint"
|
||||
"mtusi-messenger/internal/telemetry"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
ClaimOutbox(ctx context.Context, owner string, claimTTL time.Duration, limit int) ([]domain.OutboxMessage, error)
|
||||
MarkPublished(ctx context.Context, ids []int64) error
|
||||
ReleaseOutbox(ctx context.Context, id int64, reason string) error
|
||||
ReapOutboxClaims(ctx context.Context) error
|
||||
ReapExpiredLeases(ctx context.Context, limit int) (int, error)
|
||||
ReconcileQueuedJobs(ctx context.Context, olderThan time.Duration, limit int, traceparent, tracestate string) (int, error)
|
||||
OldestActiveJobAge(ctx context.Context) (float64, error)
|
||||
CountOverdueJobs(ctx context.Context, olderThan time.Duration) (int64, error)
|
||||
MarkTTRMissed(ctx context.Context, objective time.Duration) (int64, error)
|
||||
PruneOutbox(ctx context.Context, retention time.Duration) error
|
||||
OldestUnpublished(ctx context.Context) (time.Time, error)
|
||||
}
|
||||
|
||||
type Publisher interface {
|
||||
PublishConfirmed(ctx context.Context, routingKey string, message domain.JobMessage) error
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Owner string
|
||||
PollInterval time.Duration
|
||||
ClaimTTL time.Duration
|
||||
Batch int
|
||||
ReaperInterval time.Duration
|
||||
ReconcileAfter time.Duration
|
||||
Retention time.Duration
|
||||
}
|
||||
|
||||
type Relay struct {
|
||||
repo Repository
|
||||
publisher Publisher
|
||||
config Config
|
||||
log *slog.Logger
|
||||
|
||||
lastPublished time.Time
|
||||
lastReap time.Time
|
||||
startedAt time.Time
|
||||
}
|
||||
|
||||
func New(repo Repository, publisher Publisher, config Config, log *slog.Logger) *Relay {
|
||||
if log == nil {
|
||||
log = slog.Default()
|
||||
}
|
||||
|
||||
return &Relay{repo: repo, publisher: publisher, config: config, log: log, startedAt: time.Now()}
|
||||
}
|
||||
|
||||
func (r *Relay) Run(ctx context.Context) {
|
||||
telemetry.RecordTTRMissed(ctx, 0)
|
||||
poll := time.NewTicker(r.config.PollInterval)
|
||||
defer poll.Stop()
|
||||
|
||||
reaper := time.NewTicker(r.config.ReaperInterval)
|
||||
defer reaper.Stop()
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-poll.C:
|
||||
if _, err := r.RunOnce(ctx); err != nil {
|
||||
r.log.WarnContext(ctx, "outbox publish cycle failed", slog.Any("error", err))
|
||||
}
|
||||
case <-reaper.C:
|
||||
r.reap(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// RunOnce claims due rows, publishes each with a broker confirm and marks only
|
||||
// confirmed rows. A crash between confirm and mark causes a duplicate publish,
|
||||
// which the worker tolerates by CAS.
|
||||
func (r *Relay) RunOnce(ctx context.Context) (int, error) {
|
||||
messages, err := r.repo.ClaimOutbox(ctx, r.config.Owner, r.config.ClaimTTL, r.config.Batch)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
published := make([]int64, 0, len(messages))
|
||||
|
||||
for _, message := range messages {
|
||||
job, err := domain.ParseJobMessage(message.Payload)
|
||||
if err != nil {
|
||||
// A malformed payload is an application bug, not a transient
|
||||
// failure. Keep the row claim until it expires and log loudly; the
|
||||
// operator can inspect the outbox.
|
||||
r.log.ErrorContext(ctx, "outbox payload is invalid",
|
||||
slog.Int64("outbox_id", message.ID),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
_ = r.repo.ReleaseOutbox(ctx, message.ID, "invalid payload")
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
failpoint.Check("OUTBOX_AFTER_COMMIT", job.JobID)
|
||||
|
||||
publishCtx, span := telemetry.StartPublishSpan(ctx, job)
|
||||
job.Traceparent, job.Tracestate = telemetry.Inject(publishCtx)
|
||||
err = r.publisher.PublishConfirmed(publishCtx, message.RoutingKey, job)
|
||||
if err != nil {
|
||||
span.RecordError(errors.New(telemetry.Redact(err.Error())))
|
||||
span.SetStatus(codes.Error, telemetry.Redact(err.Error()))
|
||||
}
|
||||
span.End()
|
||||
if err != nil {
|
||||
_ = r.repo.ReleaseOutbox(ctx, message.ID, err.Error())
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
published = append(published, message.ID)
|
||||
r.lastPublished = time.Now()
|
||||
}
|
||||
|
||||
if err := r.repo.MarkPublished(ctx, published); err != nil {
|
||||
return len(published), err
|
||||
}
|
||||
|
||||
return len(published), nil
|
||||
}
|
||||
|
||||
func (r *Relay) reap(ctx context.Context) {
|
||||
ctx, span := telemetry.StartRequeueSpan(ctx, "requeue")
|
||||
defer span.End()
|
||||
|
||||
if err := r.repo.ReapOutboxClaims(ctx); err != nil {
|
||||
r.log.WarnContext(ctx, "outbox claim reaper failed", slog.Any("error", err))
|
||||
}
|
||||
|
||||
if time.Since(r.startedAt) >= 30*time.Second {
|
||||
missed, err := r.repo.MarkTTRMissed(ctx, 30*time.Second)
|
||||
if err != nil {
|
||||
r.log.WarnContext(ctx, "TTR miss sweep failed", slog.Any("error", err))
|
||||
} else if missed > 0 {
|
||||
telemetry.RecordTTRMissed(ctx, missed)
|
||||
r.log.InfoContext(ctx, "TTR misses recorded", slog.Int64("count", missed))
|
||||
}
|
||||
}
|
||||
|
||||
reaped, err := r.repo.ReapExpiredLeases(ctx, 100)
|
||||
if err != nil {
|
||||
r.log.WarnContext(ctx, "lease reaper failed", slog.Any("error", err))
|
||||
} else if reaped > 0 {
|
||||
r.log.InfoContext(ctx, "expired job leases requeued", slog.Int("count", reaped))
|
||||
}
|
||||
|
||||
// The broker is not the source of truth. If a delivery was dead-lettered
|
||||
// or lost, the queued job has no unpublished outbox row; republish it.
|
||||
if r.config.ReconcileAfter > 0 {
|
||||
traceparent, tracestate := telemetry.Inject(ctx)
|
||||
reconciled, err := r.repo.ReconcileQueuedJobs(ctx, r.config.ReconcileAfter, 100, traceparent, tracestate)
|
||||
if err != nil {
|
||||
r.log.WarnContext(ctx, "queued-job reconciliation failed", slog.Any("error", err))
|
||||
} else if reconciled > 0 {
|
||||
r.log.InfoContext(ctx, "lost queued jobs reconciled", slog.Int("count", reconciled))
|
||||
}
|
||||
}
|
||||
|
||||
if r.config.Retention > 0 {
|
||||
if err := r.repo.PruneOutbox(ctx, r.config.Retention); err != nil {
|
||||
r.log.WarnContext(ctx, "outbox retention failed", slog.Any("error", err))
|
||||
}
|
||||
}
|
||||
|
||||
r.lastReap = time.Now()
|
||||
}
|
||||
|
||||
// Health returns the age of the oldest unpublished intent. A bounded age is a
|
||||
// better relay readiness signal than "connected to broker".
|
||||
func (r *Relay) Health(ctx context.Context) (oldest time.Duration, err error) {
|
||||
oldestAt, err := r.repo.OldestUnpublished(ctx)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
|
||||
if oldestAt.IsZero() {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
return time.Since(oldestAt), nil
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package bao
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
const maxReplyBytes = 1 << 20
|
||||
|
||||
type authReply struct {
|
||||
Auth struct {
|
||||
Token string `json:"client_token"`
|
||||
TTL int64 `json:"lease_duration"`
|
||||
Renewable bool `json:"renewable"`
|
||||
} `json:"auth"`
|
||||
}
|
||||
|
||||
type kvReply struct {
|
||||
Data struct {
|
||||
Data map[string]json.RawMessage `json:"data"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
func (m *Manager) request(ctx context.Context, method, path string, body any, result any) error {
|
||||
var payload []byte
|
||||
var err error
|
||||
if body != nil {
|
||||
payload, err = json.Marshal(body)
|
||||
if err != nil {
|
||||
return errors.New("encode bao request failed")
|
||||
}
|
||||
}
|
||||
requestCtx, cancel := context.WithTimeout(ctx, requestTimeout)
|
||||
defer cancel()
|
||||
request, err := http.NewRequestWithContext(requestCtx, method, m.address+"/v1/"+path, bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return errors.New("create bao request failed")
|
||||
}
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
m.mu.Lock()
|
||||
token := m.token
|
||||
m.mu.Unlock()
|
||||
if token != "" && path != "auth/cert/login" {
|
||||
request.Header.Set("X-Vault-Token", token)
|
||||
}
|
||||
response, err := m.client.Do(request)
|
||||
if err != nil {
|
||||
// URL errors and response bodies are deliberately not propagated: they
|
||||
// may contain service-generated tokens or confidential request details.
|
||||
return errors.New("bao https request failed")
|
||||
}
|
||||
defer response.Body.Close()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return errors.New("bao request was not authorized or server is unavailable")
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(response.Body, maxReplyBytes+1))
|
||||
if err != nil {
|
||||
return errors.New("read bao response failed")
|
||||
}
|
||||
if len(data) > maxReplyBytes {
|
||||
return errors.New("bao response exceeds size limit")
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(data))
|
||||
if err := decoder.Decode(result); err != nil {
|
||||
return errors.New("decode bao response failed")
|
||||
}
|
||||
var trailing any
|
||||
if err := decoder.Decode(&trailing); !errors.Is(err, io.EOF) {
|
||||
return errors.New("bao response contains trailing data")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func leaseDuration(reply authReply) (time.Duration, error) {
|
||||
if reply.Auth.Token == "" || reply.Auth.TTL <= 0 || reply.Auth.TTL > 300 {
|
||||
return 0, errors.New("bao token lease is invalid")
|
||||
}
|
||||
// Never let an unexpectedly relaxed server default widen normal admission.
|
||||
ttl := time.Duration(reply.Auth.TTL) * time.Second
|
||||
if ttl > 60*time.Second {
|
||||
ttl = 60 * time.Second
|
||||
}
|
||||
return ttl, nil
|
||||
}
|
||||
|
||||
func (m *Manager) authenticate(ctx context.Context) error {
|
||||
started := m.now()
|
||||
var reply authReply
|
||||
if err := m.request(ctx, http.MethodPost, "auth/cert/login", map[string]string{"name": m.role}, &reply); err != nil {
|
||||
return err
|
||||
}
|
||||
ttl, err := leaseDuration(reply)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !m.now().Before(started.Add(ttl).Add(-time.Second)) {
|
||||
return errors.New("bao token expired during authentication")
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.token = reply.Auth.Token
|
||||
m.isRenewable = reply.Auth.Renewable
|
||||
m.leases.tokenExpires = started.Add(ttl)
|
||||
m.renewAt = started.Add(ttl / 2)
|
||||
m.maxUntil = started.Add(maxTokenLifetime)
|
||||
m.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) renew(ctx context.Context) error {
|
||||
started := m.now()
|
||||
m.mu.Lock()
|
||||
canRenew := m.isRenewable && started.Add(60*time.Second).Before(m.maxUntil)
|
||||
maxUntil := m.maxUntil
|
||||
m.mu.Unlock()
|
||||
if !canRenew {
|
||||
return m.authenticate(ctx)
|
||||
}
|
||||
var reply authReply
|
||||
if err := m.request(ctx, http.MethodPost, "auth/token/renew-self", map[string]string{"increment": "60s"}, &reply); err != nil {
|
||||
return err
|
||||
}
|
||||
ttl, err := leaseDuration(reply)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
expires := started.Add(ttl)
|
||||
if expires.After(maxUntil) {
|
||||
expires = maxUntil
|
||||
}
|
||||
if !m.now().Before(expires.Add(-time.Second)) {
|
||||
return errors.New("bao token expired during renewal")
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.token = reply.Auth.Token
|
||||
m.isRenewable = reply.Auth.Renewable
|
||||
m.leases.tokenExpires = expires
|
||||
m.renewAt = started.Add(expires.Sub(started) / 2)
|
||||
m.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *Manager) readSettings(ctx context.Context) (map[string]string, error) {
|
||||
started := m.now()
|
||||
var reply kvReply
|
||||
if err := m.request(ctx, http.MethodGet, m.path, nil, &reply); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
settings := make(map[string]string, len(confidentialKeys))
|
||||
for _, key := range confidentialKeys {
|
||||
raw, exists := reply.Data.Data[key]
|
||||
if !exists {
|
||||
continue
|
||||
}
|
||||
var value string
|
||||
if err := json.Unmarshal(raw, &value); err != nil || value == "" {
|
||||
return nil, errors.New("bao confidential configuration value is invalid")
|
||||
}
|
||||
settings[key] = value
|
||||
}
|
||||
required := []string{"POSTGRES_PASSWORD"}
|
||||
if m.role == "api" || m.role == "worker" {
|
||||
required = append(required, "S3_ACCESS_KEY_ID", "S3_SECRET_ACCESS_KEY")
|
||||
}
|
||||
if m.role == "api" {
|
||||
required = append(required, "REDIS_PASSWORD")
|
||||
}
|
||||
for _, key := range required {
|
||||
if settings[key] == "" {
|
||||
return nil, errors.New("bao own-role confidential configuration is incomplete")
|
||||
}
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.leases.kvExpires = started.Add(freshness)
|
||||
m.refreshAt = started.Add(freshness / 3)
|
||||
m.mu.Unlock()
|
||||
return settings, nil
|
||||
}
|
||||
@@ -0,0 +1,345 @@
|
||||
// Package bao acquires only an application's own confidential configuration
|
||||
// and bounds its admission by independent token, authorization and leaf leases.
|
||||
package bao
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"mtusi-messenger/internal/platform/tlsconfig"
|
||||
)
|
||||
|
||||
const (
|
||||
requestTimeout = 5 * time.Second
|
||||
freshness = 60 * time.Second
|
||||
maxTokenLifetime = 300 * time.Second
|
||||
shutdownTimeout = 30 * time.Second
|
||||
)
|
||||
|
||||
var ErrExpired = errors.New("bao: authorization lease expired")
|
||||
|
||||
var confidentialKeys = []string{
|
||||
"POSTGRES_PASSWORD", "REDIS_PASSWORD", "S3_ACCESS_KEY_ID", "S3_SECRET_ACCESS_KEY",
|
||||
}
|
||||
|
||||
type leases struct {
|
||||
tokenExpires time.Time
|
||||
kvExpires time.Time
|
||||
leafExpires time.Time
|
||||
}
|
||||
|
||||
func (l leases) deadline() time.Time {
|
||||
deadline := l.tokenExpires
|
||||
if l.kvExpires.Before(deadline) {
|
||||
deadline = l.kvExpires
|
||||
}
|
||||
if l.leafExpires.Before(deadline) {
|
||||
deadline = l.leafExpires
|
||||
}
|
||||
return deadline.Add(-time.Second)
|
||||
}
|
||||
|
||||
type Manager struct {
|
||||
cancel context.CancelCauseFunc
|
||||
loader *tlsconfig.Loader
|
||||
client *http.Client
|
||||
transport *http.Transport
|
||||
address string
|
||||
role string
|
||||
path string
|
||||
mu sync.Mutex
|
||||
leases leases
|
||||
token string
|
||||
isRenewable bool
|
||||
renewAt time.Time
|
||||
maxUntil time.Time
|
||||
refreshAt time.Time
|
||||
version string
|
||||
settings map[string]string
|
||||
shutdownDeadline time.Time
|
||||
workers int
|
||||
done chan struct{}
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
// Start requires cert authentication even when legacy secret environment values
|
||||
// exist. Neither a sealed server nor an unavailable server can bootstrap an app.
|
||||
func Start(ctx context.Context, expectedRole string) (context.Context, *Manager, error) {
|
||||
for _, key := range confidentialKeys {
|
||||
if err := os.Unsetenv(key); err != nil {
|
||||
return nil, nil, errors.New("clear legacy confidential configuration failed")
|
||||
}
|
||||
}
|
||||
address, role, path, err := environment(expectedRole)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
loader, err := tlsconfig.New(tlsconfig.FilesFromEnv())
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("load bao tls identity: %w", err)
|
||||
}
|
||||
leaf, err := loader.Leaf()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !hasRole(leaf, role) {
|
||||
return nil, nil, errors.New("bao certificate does not match application role")
|
||||
}
|
||||
endpoint, err := url.Parse(address)
|
||||
if err != nil {
|
||||
return nil, nil, errors.New("invalid bao address")
|
||||
}
|
||||
transport := &http.Transport{
|
||||
TLSClientConfig: loader.Client(endpoint.Hostname()),
|
||||
DisableKeepAlives: true,
|
||||
TLSHandshakeTimeout: requestTimeout,
|
||||
ResponseHeaderTimeout: requestTimeout,
|
||||
}
|
||||
managedCtx, cancel := context.WithCancelCause(context.WithoutCancel(ctx))
|
||||
manager := &Manager{
|
||||
cancel: cancel, loader: loader,
|
||||
transport: transport,
|
||||
client: &http.Client{
|
||||
Transport: transport, Timeout: requestTimeout,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return errors.New("bao redirects are forbidden")
|
||||
},
|
||||
},
|
||||
address: address, role: role, path: path, now: time.Now,
|
||||
}
|
||||
manager.version, err = loader.Version()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
manager.leases.leafExpires = leaf.NotAfter
|
||||
if err := manager.authenticate(ctx); err != nil {
|
||||
manager.Stop()
|
||||
transport.CloseIdleConnections()
|
||||
return nil, nil, err
|
||||
}
|
||||
settings, err := manager.readSettings(ctx)
|
||||
if err != nil {
|
||||
manager.Stop()
|
||||
transport.CloseIdleConnections()
|
||||
return nil, nil, err
|
||||
}
|
||||
manager.settings = settings
|
||||
if !manager.now().Before(manager.leases.deadline()) {
|
||||
manager.stop(ErrExpired)
|
||||
return nil, nil, ErrExpired
|
||||
}
|
||||
if err := ctx.Err(); err != nil {
|
||||
manager.stop(err)
|
||||
return nil, nil, err
|
||||
}
|
||||
for key, value := range settings {
|
||||
if err := os.Setenv(key, value); err != nil {
|
||||
manager.Stop()
|
||||
return nil, nil, errors.New("inject confidential configuration failed")
|
||||
}
|
||||
}
|
||||
manager.workers = 2
|
||||
manager.done = make(chan struct{})
|
||||
go manager.watchdog(managedCtx, ctx)
|
||||
go manager.refresh(managedCtx)
|
||||
return managedCtx, manager, nil
|
||||
}
|
||||
|
||||
func environment(expectedRole string) (string, string, string, error) {
|
||||
if expectedRole != "api" && expectedRole != "worker" && expectedRole != "relay" {
|
||||
return "", "", "", errors.New("bao application role is unsupported")
|
||||
}
|
||||
role := os.Getenv("BAO_ROLE")
|
||||
path := os.Getenv("BAO_KV_PATH")
|
||||
address := os.Getenv("BAO_ADDR")
|
||||
if role != expectedRole || path != "secret/data/"+role {
|
||||
return "", "", "", errors.New("bao role and kv path must match application identity")
|
||||
}
|
||||
endpoint, err := url.Parse(address)
|
||||
if err != nil || endpoint.Scheme != "https" || endpoint.Hostname() == "" {
|
||||
return "", "", "", errors.New("bao native https address is required")
|
||||
}
|
||||
if endpoint.User != nil || endpoint.RawQuery != "" || endpoint.Fragment != "" {
|
||||
return "", "", "", errors.New("bao address cannot contain credentials or parameters")
|
||||
}
|
||||
if endpoint.Path != "" && endpoint.Path != "/" {
|
||||
return "", "", "", errors.New("bao address must name the server root")
|
||||
}
|
||||
endpoint.Path = ""
|
||||
return endpoint.String(), role, path, nil
|
||||
}
|
||||
|
||||
func hasRole(leaf *x509.Certificate, role string) bool {
|
||||
for _, uri := range leaf.URIs {
|
||||
if uri.String() == "spiffe://mtusi/"+role {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (m *Manager) stop(cause error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if !m.shutdownDeadline.IsZero() {
|
||||
return
|
||||
}
|
||||
m.shutdownDeadline = m.now().Add(shutdownTimeout)
|
||||
m.cancel(cause)
|
||||
}
|
||||
|
||||
func (m *Manager) Stop() { m.stop(context.Canceled) }
|
||||
|
||||
// ShutdownContext always uses the first cancellation's deadline, never a new
|
||||
// thirty-second budget after consumer/sweeper waits have already elapsed.
|
||||
func (m *Manager) ShutdownContext(parent context.Context) (context.Context, context.CancelFunc) {
|
||||
m.Stop()
|
||||
m.mu.Lock()
|
||||
deadline := m.shutdownDeadline
|
||||
m.mu.Unlock()
|
||||
return context.WithDeadline(context.WithoutCancel(parent), deadline)
|
||||
}
|
||||
|
||||
func (m *Manager) Close(parent context.Context) error {
|
||||
m.Stop()
|
||||
m.transport.CloseIdleConnections()
|
||||
ctx, cancel := m.ShutdownContext(parent)
|
||||
defer cancel()
|
||||
select {
|
||||
case <-m.done:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return errors.New("bao shutdown exceeded deadline")
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) workerFinished() {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.workers--
|
||||
if m.workers == 0 {
|
||||
close(m.done)
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) watchdog(ctx, parent context.Context) {
|
||||
defer m.workerFinished()
|
||||
timer := time.NewTimer(0)
|
||||
defer timer.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-parent.Done():
|
||||
m.stop(parent.Err())
|
||||
return
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-timer.C:
|
||||
leaf, err := m.loader.Leaf()
|
||||
if !m.observeLeaf(leaf, err) {
|
||||
return
|
||||
}
|
||||
m.mu.Lock()
|
||||
remaining := m.leases.deadline().Sub(m.now())
|
||||
m.mu.Unlock()
|
||||
if remaining > time.Second {
|
||||
remaining = time.Second
|
||||
}
|
||||
if remaining < 0 {
|
||||
remaining = 0
|
||||
}
|
||||
timer.Reset(remaining)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) observeLeaf(leaf *x509.Certificate, loadError error) bool {
|
||||
if loadError != nil || leaf == nil || !hasRole(leaf, m.role) {
|
||||
m.stop(ErrExpired)
|
||||
return false
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.leases.leafExpires = leaf.NotAfter
|
||||
deadline := m.leases.deadline()
|
||||
m.mu.Unlock()
|
||||
if !m.now().Before(deadline) {
|
||||
m.stop(ErrExpired)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (m *Manager) refresh(ctx context.Context) {
|
||||
defer m.workerFinished()
|
||||
ticker := time.NewTicker(time.Second)
|
||||
defer ticker.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-ticker.C:
|
||||
m.refreshOnce(ctx)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Manager) refreshOnce(ctx context.Context) {
|
||||
version, err := m.loader.Version()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
m.mu.Lock()
|
||||
changed := version != m.version
|
||||
now := m.now()
|
||||
renewDue := !now.Before(m.renewAt)
|
||||
refreshDue := !now.Before(m.refreshAt)
|
||||
m.mu.Unlock()
|
||||
if changed {
|
||||
m.transport.CloseIdleConnections()
|
||||
if err := m.authenticate(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
m.mu.Lock()
|
||||
m.version = version
|
||||
m.mu.Unlock()
|
||||
refreshDue = true
|
||||
} else if renewDue {
|
||||
if err := m.renew(ctx); err != nil {
|
||||
return
|
||||
}
|
||||
refreshDue = true
|
||||
}
|
||||
if !refreshDue {
|
||||
return
|
||||
}
|
||||
settings, err := m.readSettings(ctx)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
m.mu.Lock()
|
||||
unchanged := sameSettings(m.settings, settings)
|
||||
m.mu.Unlock()
|
||||
if !unchanged {
|
||||
// Dependency pools hold the original credentials. A rotation restarts
|
||||
// the service rather than falsely authorizing old, cached credentials.
|
||||
m.stop(fmt.Errorf("bao confidential configuration changed: %w", ErrExpired))
|
||||
}
|
||||
}
|
||||
|
||||
func sameSettings(a, b map[string]string) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for key, value := range a {
|
||||
if b[key] != value {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package bao
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func testManager(t *testing.T, handler http.Handler) (context.Context, *Manager, *time.Time) {
|
||||
t.Helper()
|
||||
server := httptest.NewServer(handler)
|
||||
t.Cleanup(server.Close)
|
||||
now := time.Date(2026, time.June, 1, 0, 0, 0, 0, time.UTC)
|
||||
ctx, cancel := context.WithCancelCause(t.Context())
|
||||
t.Cleanup(func() { cancel(context.Canceled) })
|
||||
return ctx, &Manager{
|
||||
cancel: cancel, client: server.Client(), address: server.URL,
|
||||
role: "relay", path: "secret/data/relay", now: func() time.Time { return now },
|
||||
settings: map[string]string{},
|
||||
}, &now
|
||||
}
|
||||
|
||||
func TestAuthorizationLeasesAreIndependent(t *testing.T) {
|
||||
start := time.Date(2026, time.June, 1, 0, 0, 0, 0, time.UTC)
|
||||
lease := leases{
|
||||
tokenExpires: start.Add(60 * time.Second),
|
||||
kvExpires: start.Add(40 * time.Second),
|
||||
leafExpires: start.Add(20 * time.Second),
|
||||
}
|
||||
if got := lease.deadline(); !got.Equal(start.Add(19 * time.Second)) {
|
||||
t.Fatalf("leaf deadline = %v", got)
|
||||
}
|
||||
lease.tokenExpires = start.Add(300 * time.Second)
|
||||
lease.kvExpires = start.Add(60 * time.Second)
|
||||
if got := lease.deadline(); !got.Equal(start.Add(19 * time.Second)) {
|
||||
t.Fatal("token/kv refresh extended the leaf deadline")
|
||||
}
|
||||
lease.leafExpires = start.Add(90 * time.Second)
|
||||
if got := lease.deadline(); !got.Equal(start.Add(59 * time.Second)) {
|
||||
t.Fatal("leaf refresh extended kv authorization freshness")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTokenRenewalHalfTTLAndReauthenticationBeforeMaxTTL(t *testing.T) {
|
||||
var logins, renewals atomic.Int64
|
||||
ctx, manager, now := testManager(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/v1/auth/cert/login":
|
||||
logins.Add(1)
|
||||
case "/v1/auth/token/renew-self":
|
||||
renewals.Add(1)
|
||||
if r.Header.Get("X-Vault-Token") != "test-token" {
|
||||
t.Error("renew-self missing token")
|
||||
}
|
||||
default:
|
||||
t.Errorf("unexpected request %s", r.URL.Path)
|
||||
}
|
||||
fmt.Fprint(w, `{"auth":{"client_token":"test-token","lease_duration":60,"renewable":true}}`)
|
||||
}))
|
||||
start := *now
|
||||
if err := manager.authenticate(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !manager.renewAt.Equal(start.Add(30 * time.Second)) {
|
||||
t.Fatal("not scheduled at half ttl")
|
||||
}
|
||||
*now = start.Add(30 * time.Second)
|
||||
if err := manager.renew(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if logins.Load() != 1 || renewals.Load() != 1 {
|
||||
t.Fatalf("login=%d renew=%d", logins.Load(), renewals.Load())
|
||||
}
|
||||
if !manager.maxUntil.Equal(start.Add(300 * time.Second)) {
|
||||
t.Fatal("renewal extended max lifetime")
|
||||
}
|
||||
*now = start.Add(240 * time.Second)
|
||||
if err := manager.renew(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if logins.Load() != 2 {
|
||||
t.Fatal("max lifetime did not force reauthentication")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFailedTokenAndKVOperationsDoNotExtendDeadlines(t *testing.T) {
|
||||
var isUnavailable atomic.Bool
|
||||
ctx, manager, now := testManager(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if isUnavailable.Load() {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
fmt.Fprint(w, "secret-sentinel-test-token")
|
||||
return
|
||||
}
|
||||
if r.URL.Path == "/v1/secret/data/relay" {
|
||||
fmt.Fprint(w, `{"data":{"data":{"POSTGRES_PASSWORD":"secret-sentinel","SERVER_PORT":"1"}}}`)
|
||||
return
|
||||
}
|
||||
fmt.Fprint(w, `{"auth":{"client_token":"test-token","lease_duration":60,"renewable":true}}`)
|
||||
}))
|
||||
if err := manager.authenticate(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
settings, err := manager.readSettings(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(settings) != 1 || settings["SERVER_PORT"] != "" {
|
||||
t.Fatal("nonconfidential key was injected")
|
||||
}
|
||||
before := manager.leases
|
||||
isUnavailable.Store(true)
|
||||
*now = now.Add(30 * time.Second)
|
||||
if err := manager.renew(ctx); err == nil || strings.Contains(err.Error(), "sentinel") {
|
||||
t.Fatalf("failed renew error = %v", err)
|
||||
}
|
||||
if _, err := manager.readSettings(ctx); err == nil || strings.Contains(err.Error(), "sentinel") {
|
||||
t.Fatalf("failed kv error = %v", err)
|
||||
}
|
||||
if manager.leases != before {
|
||||
t.Fatal("failure extended authorization deadlines")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCurrentLeafObservationResetsOnlyActualLeafDeadline(t *testing.T) {
|
||||
ctx, manager, now := testManager(t, http.NotFoundHandler())
|
||||
start := *now
|
||||
manager.leases = leases{
|
||||
tokenExpires: start.Add(time.Minute), kvExpires: start.Add(time.Minute),
|
||||
leafExpires: start.Add(20 * time.Second),
|
||||
}
|
||||
uri, err := url.Parse("spiffe://mtusi/relay")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
leaf := &x509.Certificate{NotAfter: start.Add(40 * time.Second), URIs: []*url.URL{uri}}
|
||||
*now = start.Add(19 * time.Second)
|
||||
if !manager.observeLeaf(leaf, nil) {
|
||||
t.Fatal("valid rotated short leaf was rejected")
|
||||
}
|
||||
if !manager.leases.leafExpires.Equal(leaf.NotAfter) {
|
||||
t.Fatal("retained initial leaf deadline")
|
||||
}
|
||||
*now = start.Add(39 * time.Second)
|
||||
if manager.observeLeaf(leaf, nil) {
|
||||
t.Fatal("expired safety-margin admission remains open")
|
||||
}
|
||||
if !errors.Is(context.Cause(ctx), ErrExpired) {
|
||||
t.Fatal("expiry did not cancel services")
|
||||
}
|
||||
deadline := manager.shutdownDeadline
|
||||
*now = now.Add(10 * time.Second)
|
||||
shutdownCtx, cancel := manager.ShutdownContext(ctx)
|
||||
defer cancel()
|
||||
actual, ok := shutdownCtx.Deadline()
|
||||
if !ok || !actual.Equal(deadline) {
|
||||
t.Fatal("shutdown gained a second full budget after waiting")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthorizationFailureClosesAdmissionImmediately(t *testing.T) {
|
||||
ctx, manager, now := testManager(t, http.NotFoundHandler())
|
||||
manager.leases = leases{
|
||||
tokenExpires: now.Add(time.Minute), kvExpires: now.Add(time.Minute),
|
||||
leafExpires: now.Add(time.Minute),
|
||||
}
|
||||
if manager.observeLeaf(nil, errors.New("revoked leaf")) {
|
||||
t.Fatal("failed identity remains admitted")
|
||||
}
|
||||
if ctx.Err() == nil {
|
||||
t.Fatal("identity failure did not cancel service context")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResponseSizeAndMalformedLeaseAreRejected(t *testing.T) {
|
||||
ctx, manager, _ := testManager(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
fmt.Fprint(w, strings.Repeat("x", maxReplyBytes+1))
|
||||
}))
|
||||
if _, err := manager.readSettings(ctx); err == nil {
|
||||
t.Fatal("oversized response accepted")
|
||||
}
|
||||
for _, ttl := range []int64{0, -1, 301} {
|
||||
var reply authReply
|
||||
reply.Auth.Token = "test-token"
|
||||
reply.Auth.TTL = ttl
|
||||
if _, err := leaseDuration(reply); err == nil {
|
||||
t.Fatalf("invalid ttl %d accepted", ttl)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfiguredBaoNeverBootstrapsFromLegacySecrets(t *testing.T) {
|
||||
t.Setenv("BAO_ADDR", "https://openbao:8200")
|
||||
t.Setenv("BAO_ROLE", "relay")
|
||||
t.Setenv("BAO_KV_PATH", "secret/data/relay")
|
||||
t.Setenv("POSTGRES_PASSWORD", "legacy-password")
|
||||
t.Setenv("TLS_CA_FILE", "/missing/current/ca.crt")
|
||||
t.Setenv("TLS_CERT_FILE", "/missing/current/tls.crt")
|
||||
t.Setenv("TLS_KEY_FILE", "/missing/current/tls.key")
|
||||
t.Setenv("TLS_CRL_FILE", "/missing/current/ca.crl")
|
||||
t.Setenv("TLS_VERSION_FILE", "/missing/current-version")
|
||||
if _, _, err := Start(t.Context(), "relay"); err == nil {
|
||||
t.Fatal("missing identity accepted")
|
||||
}
|
||||
if os.Getenv("POSTGRES_PASSWORD") != "" {
|
||||
t.Fatal("legacy secret remains usable after failed acquisition")
|
||||
}
|
||||
}
|
||||
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
+152
@@ -0,0 +1,152 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"mtusi-messenger/internal/platform/tlsconfig"
|
||||
)
|
||||
|
||||
type RedisConfig struct {
|
||||
Host string
|
||||
Port int
|
||||
Username string
|
||||
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(ctx context.Context, cfg RedisConfig) (*RedisCache, error) {
|
||||
if cfg.Username == "" || cfg.Password == "" {
|
||||
return nil, errors.New("redis: username and password are required")
|
||||
}
|
||||
clientTLS, err := tlsconfig.NewClientFromEnv(cfg.Host)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("configure redis tls: %w", err)
|
||||
}
|
||||
opts := newClientOptions(cfg)
|
||||
opts.TLSConfig = clientTLS
|
||||
client := redis.NewClient(opts)
|
||||
|
||||
pingCtx, cancel := context.WithTimeout(ctx, cfg.DialTimeout)
|
||||
defer cancel()
|
||||
|
||||
if err := client.Ping(pingCtx).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)),
|
||||
Username: cfg.Username,
|
||||
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,18 @@
|
||||
// Package instanceid returns the stable identifier this process reports in
|
||||
// X-Instance-Id and in the telemetry resource. INSTANCE_ID wins; otherwise the
|
||||
// container hostname (short container id) is used.
|
||||
package instanceid
|
||||
|
||||
import "os"
|
||||
|
||||
func FromEnvOrHostname() string {
|
||||
if id := os.Getenv("INSTANCE_ID"); id != "" {
|
||||
return id
|
||||
}
|
||||
|
||||
if host, err := os.Hostname(); err == nil && host != "" {
|
||||
return host
|
||||
}
|
||||
|
||||
return "unknown"
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
// 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 {
|
||||
// Ping verifies that the bucket is reachable and the credentials are valid.
|
||||
Ping(ctx context.Context) error
|
||||
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,330 @@
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"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"
|
||||
"mtusi-messenger/internal/platform/tlsconfig"
|
||||
)
|
||||
|
||||
// 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
|
||||
transport *http.Transport
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
for _, endpoint := range []string{cfg.Endpoint, cfg.PublicEndpoint} {
|
||||
u, err := url.Parse(endpoint)
|
||||
if err != nil || u.Scheme != "https" || u.Hostname() == "" || u.User != nil {
|
||||
return nil, errors.New("object store: endpoints must be https urls without credentials")
|
||||
}
|
||||
if u.RawQuery != "" || u.Fragment != "" {
|
||||
return nil, errors.New("object store: endpoints must not contain a query or fragment")
|
||||
}
|
||||
}
|
||||
clientTLS, err := tlsconfig.NewClientFromEnv("")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("configure object store tls: %w", err)
|
||||
}
|
||||
transport := &http.Transport{
|
||||
Proxy: http.ProxyFromEnvironment,
|
||||
DialContext: (&net.Dialer{
|
||||
Timeout: 3 * time.Second,
|
||||
KeepAlive: 30 * time.Second,
|
||||
}).DialContext,
|
||||
TLSClientConfig: clientTLS,
|
||||
TLSHandshakeTimeout: 3 * time.Second,
|
||||
ResponseHeaderTimeout: 15 * time.Second,
|
||||
MaxIdleConnsPerHost: 16,
|
||||
IdleConnTimeout: 90 * time.Second,
|
||||
}
|
||||
httpClient := &http.Client{
|
||||
Transport: transport,
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error {
|
||||
return errors.New("object store: redirects are not permitted")
|
||||
},
|
||||
// Downloads stream through the response body; an overall 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,
|
||||
transport: transport,
|
||||
}
|
||||
|
||||
return st, nil
|
||||
}
|
||||
|
||||
// Close releases idle connections owned by the S3 clients.
|
||||
func (s *S3) Close() { s.transport.CloseIdleConnections() }
|
||||
|
||||
func (s *S3) Ping(ctx context.Context) error {
|
||||
// HeadBucket needs bucket-level permissions that the application identity
|
||||
// intentionally does not have. A HeadObject on a sentinel staging key is
|
||||
// enough to prove connectivity and the object-level credentials; a missing
|
||||
// sentinel is the expected healthy result.
|
||||
_, err := s.Head(ctx, "staging/.health/ping")
|
||||
if err == nil || errors.Is(err, domain.ErrNotFound) {
|
||||
return nil
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
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,197 @@
|
||||
package password
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argonTime = 2
|
||||
argonMemory = 19456
|
||||
argonThreads = 1
|
||||
argonKeyLen = 32
|
||||
argonSaltLen = 16
|
||||
maxEncodedLen = 512
|
||||
)
|
||||
|
||||
var ErrBusy = errors.New("password: derivation capacity exhausted")
|
||||
|
||||
// All entry points share the same nonblocking, per-process derivation budget.
|
||||
// Legacy PHC strings can ask for 64 MiB per derivation; they get a separate
|
||||
// single slot so two upgrades cannot exceed the API memory limit.
|
||||
var (
|
||||
derivations = make(chan struct{}, 2)
|
||||
legacyDerivations = make(chan struct{}, 1)
|
||||
)
|
||||
|
||||
type Verification struct {
|
||||
Match bool
|
||||
NeedsRehash bool
|
||||
}
|
||||
|
||||
type parameters struct {
|
||||
memory uint32
|
||||
time uint32
|
||||
threads uint8
|
||||
isLegacy bool
|
||||
salt [argonSaltLen]byte
|
||||
hash [argonKeyLen]byte
|
||||
}
|
||||
|
||||
func Hash(plain string) (string, error) {
|
||||
if !acquire() {
|
||||
return "", ErrBusy
|
||||
}
|
||||
defer release()
|
||||
|
||||
var salt [argonSaltLen]byte
|
||||
if _, err := rand.Read(salt[:]); err != nil {
|
||||
return "", fmt.Errorf("generate password salt: %w", err)
|
||||
}
|
||||
hash := argon2.IDKey([]byte(plain), salt[:], argonTime, argonMemory, argonThreads, argonKeyLen)
|
||||
|
||||
return "$argon2id$v=19$m=19456,t=2,p=1$" +
|
||||
base64.RawStdEncoding.EncodeToString(salt[:]) + "$" +
|
||||
base64.RawStdEncoding.EncodeToString(hash), nil
|
||||
}
|
||||
|
||||
func Verify(plain, encoded string) (Verification, error) {
|
||||
p, ok := parse(encoded)
|
||||
if !ok {
|
||||
return Verification{}, nil
|
||||
}
|
||||
if p.memory > argonMemory {
|
||||
if !acquireLegacy() {
|
||||
return Verification{}, ErrBusy
|
||||
}
|
||||
defer releaseLegacy()
|
||||
} else {
|
||||
if !acquire() {
|
||||
return Verification{}, ErrBusy
|
||||
}
|
||||
defer release()
|
||||
}
|
||||
|
||||
actual := argon2.IDKey([]byte(plain), p.salt[:], p.time, p.memory, p.threads, argonKeyLen)
|
||||
if subtle.ConstantTimeCompare(actual, p.hash[:]) != 1 {
|
||||
return Verification{}, nil
|
||||
}
|
||||
|
||||
obsolete := p.memory != argonMemory || p.time != argonTime || p.threads != argonThreads
|
||||
return Verification{Match: true, NeedsRehash: p.isLegacy || obsolete}, nil
|
||||
}
|
||||
|
||||
// DummyVerify spends the same derivation budget as Verify for a caller that
|
||||
// cannot prove a match, so an unknown username is not cheaper than a known one.
|
||||
func DummyVerify(plain string) error {
|
||||
if !acquire() {
|
||||
return ErrBusy
|
||||
}
|
||||
defer release()
|
||||
|
||||
var salt [argonSaltLen]byte
|
||||
_ = argon2.IDKey([]byte(plain), salt[:], argonTime, argonMemory, argonThreads, argonKeyLen)
|
||||
return nil
|
||||
}
|
||||
|
||||
func acquire() bool {
|
||||
select {
|
||||
case derivations <- struct{}{}:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func release() {
|
||||
<-derivations
|
||||
}
|
||||
|
||||
func acquireLegacy() bool {
|
||||
select {
|
||||
case legacyDerivations <- struct{}{}:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func releaseLegacy() {
|
||||
<-legacyDerivations
|
||||
}
|
||||
|
||||
func parse(encoded string) (parameters, bool) {
|
||||
if len(encoded) > maxEncodedLen {
|
||||
return parameters{}, false
|
||||
}
|
||||
var p parameters
|
||||
var payload string
|
||||
switch {
|
||||
case strings.HasPrefix(encoded, "argon2id$"):
|
||||
p.memory, p.time, p.threads, p.isLegacy = 64*1024, 1, 4, true
|
||||
payload = strings.TrimPrefix(encoded, "argon2id$")
|
||||
case strings.HasPrefix(encoded, "$argon2id$v=19$"):
|
||||
body := strings.TrimPrefix(encoded, "$argon2id$v=19$")
|
||||
costs, rest, hasPayload := strings.Cut(body, "$")
|
||||
memoryPart, restCosts, hasMemory := strings.Cut(costs, ",")
|
||||
timePart, threadsPart, hasTime := strings.Cut(restCosts, ",")
|
||||
complete := hasPayload && hasMemory && hasTime
|
||||
if !complete {
|
||||
return parameters{}, false
|
||||
}
|
||||
memory, okMemory := cost(memoryPart, "m=", 64*1024)
|
||||
iterations, okTime := cost(timePart, "t=", 4)
|
||||
threads, okThreads := cost(threadsPart, "p=", 4)
|
||||
validCosts := okMemory && okTime && okThreads
|
||||
if !validCosts || threads > 4 || memory < 8*threads {
|
||||
return parameters{}, false
|
||||
}
|
||||
p.memory, p.time, p.threads = memory, iterations, uint8(threads)
|
||||
payload = rest
|
||||
default:
|
||||
return parameters{}, false
|
||||
}
|
||||
salt, hash, hasHash := strings.Cut(payload, "$")
|
||||
if !hasHash {
|
||||
return parameters{}, false
|
||||
}
|
||||
|
||||
if len(salt) != 22 || len(hash) != 43 {
|
||||
return parameters{}, false
|
||||
}
|
||||
encoding := base64.RawStdEncoding.Strict()
|
||||
if n, err := encoding.Decode(p.salt[:], []byte(salt)); err != nil || n != argonSaltLen {
|
||||
return parameters{}, false
|
||||
}
|
||||
if n, err := encoding.Decode(p.hash[:], []byte(hash)); err != nil || n != argonKeyLen {
|
||||
return parameters{}, false
|
||||
}
|
||||
return p, true
|
||||
}
|
||||
|
||||
func cost(encoded, prefix string, maximum uint32) (uint32, bool) {
|
||||
if !strings.HasPrefix(encoded, prefix) {
|
||||
return 0, false
|
||||
}
|
||||
value := strings.TrimPrefix(encoded, prefix)
|
||||
if len(value) == 0 || value[0] == '0' {
|
||||
return 0, false
|
||||
}
|
||||
for _, digit := range value {
|
||||
if digit < '0' || digit > '9' {
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
n, err := strconv.ParseUint(value, 10, 32)
|
||||
if err != nil || n == 0 || n > uint64(maximum) {
|
||||
return 0, false
|
||||
}
|
||||
return uint32(n), true
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
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)
|
||||
verified, err := password.Verify("very-secret-password", encoded)
|
||||
require.NoError(t, err)
|
||||
require.True(t, verified.Match)
|
||||
require.False(t, verified.NeedsRehash)
|
||||
verified, err = password.Verify("wrong-password-value", encoded)
|
||||
require.NoError(t, err)
|
||||
require.False(t, verified.Match)
|
||||
require.False(t, verified.NeedsRehash)
|
||||
}
|
||||
|
||||
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) {
|
||||
for _, encoded := range []string{"", "plain-text", strings.Repeat("x", 64)} {
|
||||
verified, err := password.Verify("very-secret-password", encoded)
|
||||
require.NoError(t, err)
|
||||
require.False(t, verified.Match)
|
||||
require.False(t, verified.NeedsRehash)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package password
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
func TestVerifyRejectsMalformedAndCostlyPHCBeforeDerivation(t *testing.T) {
|
||||
salt := base64.RawStdEncoding.EncodeToString(make([]byte, argonSaltLen))
|
||||
hash := base64.RawStdEncoding.EncodeToString(make([]byte, argonKeyLen))
|
||||
prefix := "$argon2id$v=19$"
|
||||
suffix := "$" + salt + "$" + hash
|
||||
invalid := []string{
|
||||
strings.Repeat("x", 513),
|
||||
prefix + "m=65537,t=2,p=1" + suffix,
|
||||
prefix + "m=19456,t=5,p=1" + suffix,
|
||||
prefix + "m=19456,t=2,p=5" + suffix,
|
||||
prefix + "m=7,t=2,p=1" + suffix,
|
||||
prefix + "m=31,t=2,p=4" + suffix,
|
||||
prefix + "m=0,t=2,p=1" + suffix,
|
||||
prefix + "m=19456,t=0,p=1" + suffix,
|
||||
prefix + "m=19456,t=2,p=0" + suffix,
|
||||
prefix + "m=-1,t=2,p=1" + suffix,
|
||||
prefix + "m=+19456,t=2,p=1" + suffix,
|
||||
prefix + "m=019456,t=2,p=1" + suffix,
|
||||
prefix + "m=4294967296,t=2,p=1" + suffix,
|
||||
prefix + "m=19456,t=2,p=1,x=1" + suffix,
|
||||
prefix + "m=19456,t=2,t=1" + suffix,
|
||||
"$argon2id$v=16$m=19456,t=2,p=1" + suffix,
|
||||
prefix + "m=19456,t=2,p=1$" + salt + "$" + hash[:42] + "!",
|
||||
prefix + "m=19456,t=2,p=1$" + salt + "=$" + hash,
|
||||
"argon2id$" + salt + "$" + hash + "$extra",
|
||||
}
|
||||
// Exhausting the budget proves these inputs never reach Argon2: a valid
|
||||
// encoding returns ErrBusy here, while malformed encodings are denied.
|
||||
require.True(t, acquire())
|
||||
defer release()
|
||||
require.True(t, acquire())
|
||||
defer release()
|
||||
for _, encoded := range invalid {
|
||||
got, err := Verify("password", encoded)
|
||||
require.NoError(t, err)
|
||||
require.False(t, got.Match)
|
||||
require.False(t, got.NeedsRehash)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDerivationBudgetIsNonblockingAndShared(t *testing.T) {
|
||||
encoded, err := Hash("secret-password")
|
||||
require.NoError(t, err)
|
||||
require.True(t, acquire())
|
||||
defer release()
|
||||
require.True(t, acquire())
|
||||
defer release()
|
||||
require.False(t, acquire())
|
||||
_, err = Hash("secret-password")
|
||||
require.ErrorIs(t, err, ErrBusy)
|
||||
_, err = Verify("secret-password", encoded)
|
||||
require.ErrorIs(t, err, ErrBusy)
|
||||
}
|
||||
|
||||
func TestLegacyAndObsoletePHCRequireOnlySuccessfulRehash(t *testing.T) {
|
||||
var salt [argonSaltLen]byte
|
||||
legacy := argon2.IDKey([]byte("secret-password"), salt[:], 1, 64*1024, 4, argonKeyLen)
|
||||
legacyEncoded := "argon2id$" + base64.RawStdEncoding.EncodeToString(salt[:]) + "$" +
|
||||
base64.RawStdEncoding.EncodeToString(legacy)
|
||||
obsolete := argon2.IDKey([]byte("secret-password"), salt[:], 1, 32, 1, argonKeyLen)
|
||||
obsoleteEncoded := "$argon2id$v=19$m=32,t=1,p=1$" + base64.RawStdEncoding.EncodeToString(salt[:]) + "$" +
|
||||
base64.RawStdEncoding.EncodeToString(obsolete)
|
||||
for _, encoded := range []string{legacyEncoded, obsoleteEncoded} {
|
||||
got, err := Verify("wrong-password", encoded)
|
||||
require.NoError(t, err)
|
||||
require.False(t, got.Match)
|
||||
require.False(t, got.NeedsRehash)
|
||||
got, err = Verify("secret-password", encoded)
|
||||
require.NoError(t, err)
|
||||
require.True(t, got.Match)
|
||||
require.True(t, got.NeedsRehash)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package ratelimit
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Limit struct {
|
||||
Key string
|
||||
Count int
|
||||
Window time.Duration
|
||||
}
|
||||
|
||||
// Reserve admits all dimensions atomically. A positive retryAfter rejects the
|
||||
// reservation without consuming any dimension; errors must fail closed.
|
||||
type Limiter interface {
|
||||
Reserve(ctx context.Context, limits []Limit) (retryAfter time.Duration, err error)
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
// Package secretfile reads an operator-configured secret inside a filesystem
|
||||
// root, without permitting symlink escape or unbounded reads.
|
||||
package secretfile
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
const maxSize = 64 * 1024
|
||||
|
||||
func Read(path string) (contents []byte, err error) {
|
||||
if !filepath.IsAbs(path) {
|
||||
return nil, errors.New("secret file must use an absolute path")
|
||||
}
|
||||
root, err := os.OpenRoot(filepath.Dir(path))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open secret directory: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
if closeErr := root.Close(); closeErr != nil {
|
||||
err = errors.Join(err, fmt.Errorf("close secret directory: %w", closeErr))
|
||||
}
|
||||
}()
|
||||
file, err := root.Open(filepath.Base(path))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("open secret file: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
if closeErr := file.Close(); closeErr != nil {
|
||||
err = errors.Join(err, fmt.Errorf("close secret file: %w", closeErr))
|
||||
}
|
||||
}()
|
||||
info, err := file.Stat()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("stat secret file: %w", err)
|
||||
}
|
||||
if !info.Mode().IsRegular() || info.Size() > maxSize {
|
||||
return nil, errors.New("secret file is not a bounded regular file")
|
||||
}
|
||||
contents, err = io.ReadAll(io.LimitReader(file, maxSize+1))
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read secret file: %w", err)
|
||||
}
|
||||
if len(contents) > maxSize {
|
||||
return nil, errors.New("secret file grew beyond its limit")
|
||||
}
|
||||
return contents, nil
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package secretfile
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestReadConfinesSymlinksAndBoundsAllocation(t *testing.T) {
|
||||
inside := t.TempDir()
|
||||
outside := t.TempDir()
|
||||
secret := filepath.Join(inside, "password")
|
||||
if err := os.WriteFile(secret, []byte("operator-value\n"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := Read(secret)
|
||||
if err != nil || string(got) != "operator-value\n" {
|
||||
t.Fatalf("secret read: %q, %v", got, err)
|
||||
}
|
||||
escaped := filepath.Join(outside, "private")
|
||||
if err := os.WriteFile(escaped, []byte("must not be exposed"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
link := filepath.Join(inside, "link")
|
||||
if err := os.Symlink(escaped, link); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if contents, err := Read(link); err == nil || len(contents) != 0 {
|
||||
t.Fatal("secret symlink escaped its configured directory")
|
||||
}
|
||||
oversized := filepath.Join(inside, "large")
|
||||
if err := os.WriteFile(oversized, bytes.Repeat([]byte{'x'}, maxSize+1), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if contents, err := Read(oversized); err == nil || len(contents) != 0 {
|
||||
t.Fatal("oversized secret file was admitted")
|
||||
}
|
||||
if _, err := Read("relative-password"); err == nil {
|
||||
t.Fatal("relative secret file was admitted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
package tlsconfig
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"mtusi-messenger/internal/platform/secretfile"
|
||||
)
|
||||
|
||||
type revocations struct {
|
||||
mu sync.Mutex
|
||||
stamp fileStamp
|
||||
lists []*x509.RevocationList
|
||||
}
|
||||
|
||||
func (l *Loader) revocationLists() ([]*x509.RevocationList, error) {
|
||||
files, err := l.files.snapshot()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
current, err := stamp(files.CRL)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l.crls.mu.Lock()
|
||||
defer l.crls.mu.Unlock()
|
||||
if l.crls.lists != nil && l.crls.stamp == current {
|
||||
return l.crls.lists, nil
|
||||
}
|
||||
data, err := secretfile.Read(files.CRL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read tls revocations: %w", err)
|
||||
}
|
||||
lists, err := parseRevocations(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l.crls.lists = lists
|
||||
l.crls.stamp = current
|
||||
return lists, nil
|
||||
}
|
||||
|
||||
func parseRevocations(data []byte) ([]*x509.RevocationList, error) {
|
||||
lists := []*x509.RevocationList{}
|
||||
for len(bytes.TrimSpace(data)) > 0 {
|
||||
block, rest := pem.Decode(data)
|
||||
if block == nil || block.Type != "X509 CRL" {
|
||||
return nil, errors.New("malformed tls crl pem")
|
||||
}
|
||||
list, err := x509.ParseRevocationList(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, errors.New("malformed tls crl")
|
||||
}
|
||||
lists = append(lists, list)
|
||||
data = rest
|
||||
}
|
||||
if len(lists) == 0 {
|
||||
return nil, errors.New("tls crl bundle is empty")
|
||||
}
|
||||
return lists, nil
|
||||
}
|
||||
|
||||
func (l *Loader) verifyChains(chains [][]*x509.Certificate) error {
|
||||
if len(chains) == 0 {
|
||||
return errors.New("tls peer has no verified chain")
|
||||
}
|
||||
lists, err := l.revocationLists()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var reason error
|
||||
for _, chain := range chains {
|
||||
if err := verifyRevocations(chain, lists, l.now()); err == nil {
|
||||
return nil
|
||||
} else if reason == nil {
|
||||
reason = err
|
||||
}
|
||||
}
|
||||
return fmt.Errorf("tls certificate chain revocation verification failed: %w", reason)
|
||||
}
|
||||
|
||||
func verifyRevocations(chain []*x509.Certificate, lists []*x509.RevocationList, now time.Time) error {
|
||||
if len(chain) < 2 {
|
||||
return errors.New("tls chain lacks an issuing authority")
|
||||
}
|
||||
for index, cert := range chain[:len(chain)-1] {
|
||||
issuer := chain[index+1]
|
||||
var applicable *x509.RevocationList
|
||||
var signatureErr error
|
||||
for _, list := range lists {
|
||||
if !bytes.Equal(list.RawIssuer, issuer.RawSubject) {
|
||||
continue
|
||||
}
|
||||
if len(list.AuthorityKeyId) > 0 && !bytes.Equal(list.AuthorityKeyId, issuer.SubjectKeyId) {
|
||||
continue
|
||||
}
|
||||
// A bundle may carry several lists for one subject (old and new
|
||||
// issuer versions). An invalid signature disqualifies that list,
|
||||
// not every later candidate for the same issuer.
|
||||
if err := list.CheckSignatureFrom(issuer); err != nil {
|
||||
signatureErr = err
|
||||
continue
|
||||
}
|
||||
if applicable == nil || list.ThisUpdate.After(applicable.ThisUpdate) {
|
||||
applicable = list
|
||||
}
|
||||
}
|
||||
if applicable == nil {
|
||||
if signatureErr != nil {
|
||||
return fmt.Errorf("tls applicable crl signature is invalid: %w", signatureErr)
|
||||
}
|
||||
return errors.New("tls issuing authority crl is missing")
|
||||
}
|
||||
if applicable.ThisUpdate.After(now) {
|
||||
return errors.New("tls applicable crl is not yet valid")
|
||||
}
|
||||
if !applicable.NextUpdate.After(now) || !applicable.NextUpdate.After(applicable.ThisUpdate) {
|
||||
return errors.New("tls applicable crl is stale")
|
||||
}
|
||||
for _, entry := range applicable.RevokedCertificateEntries {
|
||||
if cert.SerialNumber.Cmp(entry.SerialNumber) == 0 {
|
||||
return errors.New("tls certificate is revoked")
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,479 @@
|
||||
// Package tlsconfig owns verified, revocation-aware TLS identities. An atomic
|
||||
// regular-file selector names a complete immutable version; trust changes
|
||||
// restart the process, while leaf certificates and issuer CRLs reload.
|
||||
package tlsconfig
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"mtusi-messenger/internal/platform/secretfile"
|
||||
)
|
||||
|
||||
type Files struct {
|
||||
CA string
|
||||
Cert string
|
||||
Key string
|
||||
CRL string
|
||||
Selector string
|
||||
}
|
||||
|
||||
func FilesFromEnv() Files {
|
||||
return Files{
|
||||
CA: envFile("TLS_CA_FILE", "/run/identity/current/ca.crt"),
|
||||
Cert: envFile("TLS_CERT_FILE", "/run/identity/current/tls.crt"),
|
||||
Key: envFile("TLS_KEY_FILE", "/run/identity/current/tls.key"),
|
||||
CRL: envFile("TLS_CRL_FILE", "/run/identity/current/ca.crl"),
|
||||
Selector: envFile("TLS_VERSION_FILE", "/run/identity/current-version"),
|
||||
}
|
||||
}
|
||||
|
||||
func envFile(name, fallback string) string {
|
||||
if value := os.Getenv(name); value != "" {
|
||||
return value
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
type fileStamp struct {
|
||||
path string
|
||||
size int64
|
||||
modified time.Time
|
||||
}
|
||||
|
||||
type Loader struct {
|
||||
files Files
|
||||
trust []byte
|
||||
trustRoots map[string]struct{}
|
||||
roots *x509.CertPool
|
||||
issuers []*x509.Certificate
|
||||
mu sync.Mutex
|
||||
cert *tls.Certificate
|
||||
ownChains [][]*x509.Certificate
|
||||
certStamp fileStamp
|
||||
keyStamp fileStamp
|
||||
version string
|
||||
crls revocations
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func New(files Files) (*Loader, error) {
|
||||
resolved, err := files.snapshot()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data, err := secretfile.Read(resolved.CA)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read tls trust: %w", err)
|
||||
}
|
||||
issuers, err := parseCertificates(data)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
roots := x509.NewCertPool()
|
||||
trustRoots := map[string]struct{}{}
|
||||
rootCount := 0
|
||||
for _, cert := range issuers {
|
||||
if !cert.IsCA || !cert.BasicConstraintsValid {
|
||||
return nil, errors.New("tls trust contains a non-ca certificate")
|
||||
}
|
||||
// Only trust anchors go in Roots. Intermediates remain chain candidates,
|
||||
// so their revocation by the root cannot be skipped by chain shortening.
|
||||
if bytes.Equal(cert.RawIssuer, cert.RawSubject) {
|
||||
if err := cert.CheckSignatureFrom(cert); err != nil {
|
||||
return nil, errors.New("tls trust contains an invalid root signature")
|
||||
}
|
||||
roots.AddCert(cert)
|
||||
trustRoots[string(cert.Raw)] = struct{}{}
|
||||
rootCount++
|
||||
}
|
||||
}
|
||||
if rootCount == 0 {
|
||||
return nil, errors.New("tls trust has no root certificate")
|
||||
}
|
||||
loader := &Loader{files: files, trust: data, trustRoots: trustRoots, roots: roots, issuers: issuers, now: time.Now}
|
||||
if _, err := loader.Leaf(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return loader, nil
|
||||
}
|
||||
|
||||
func NewClientFromEnv(serverName string) (*tls.Config, error) {
|
||||
loader, err := New(FilesFromEnv())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return loader.Client(serverName), nil
|
||||
}
|
||||
|
||||
func (f Files) snapshot() (Files, error) {
|
||||
missing := f.CA == "" || f.Cert == "" || f.Key == "" || f.CRL == "" || f.Selector == ""
|
||||
if missing {
|
||||
return Files{}, errors.New("all tls identity files are required")
|
||||
}
|
||||
directory := filepath.Clean(filepath.Dir(f.Cert))
|
||||
for _, path := range []string{f.CA, f.Key, f.CRL} {
|
||||
if filepath.Clean(filepath.Dir(path)) != directory {
|
||||
return Files{}, errors.New("tls identity files must share one version directory")
|
||||
}
|
||||
}
|
||||
if filepath.Clean(filepath.Dir(f.Selector)) != filepath.Dir(directory) {
|
||||
return Files{}, errors.New("tls version selector must belong to the identity directory")
|
||||
}
|
||||
data, err := secretfile.Read(f.Selector)
|
||||
if err != nil {
|
||||
return Files{}, fmt.Errorf("read tls identity version: %w", err)
|
||||
}
|
||||
if len(data) > 256 {
|
||||
return Files{}, errors.New("tls identity version is too long")
|
||||
}
|
||||
version := strings.TrimSpace(string(data))
|
||||
invalid := version == "" || version == "." || version == ".."
|
||||
if invalid || strings.ContainsAny(version, "/\\\x00") {
|
||||
return Files{}, errors.New("tls identity version is not a directory name")
|
||||
}
|
||||
resolved := filepath.Join(filepath.Dir(f.Selector), "versions", version)
|
||||
return Files{
|
||||
CA: filepath.Join(resolved, filepath.Base(f.CA)),
|
||||
Cert: filepath.Join(resolved, filepath.Base(f.Cert)),
|
||||
Key: filepath.Join(resolved, filepath.Base(f.Key)),
|
||||
CRL: filepath.Join(resolved, filepath.Base(f.CRL)),
|
||||
Selector: f.Selector,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func stamp(path string) (fileStamp, error) {
|
||||
info, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return fileStamp{}, fmt.Errorf("stat tls identity: %w", err)
|
||||
}
|
||||
if !info.Mode().IsRegular() {
|
||||
return fileStamp{}, errors.New("tls identity file is not regular")
|
||||
}
|
||||
return fileStamp{path: path, size: info.Size(), modified: info.ModTime()}, nil
|
||||
}
|
||||
|
||||
func (l *Loader) certificate() (*tls.Certificate, error) {
|
||||
files, err := l.files.snapshot()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
certStamp, err := stamp(files.Cert)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
keyStamp, err := stamp(files.Key)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if l.cert != nil && l.certStamp == certStamp && l.keyStamp == keyStamp {
|
||||
return l.cert, nil
|
||||
}
|
||||
certPEM, err := secretfile.Read(files.Cert)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read tls certificate: %w", err)
|
||||
}
|
||||
keyPEM, err := secretfile.Read(files.Key)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read tls key: %w", err)
|
||||
}
|
||||
cert, err := tls.X509KeyPair(certPEM, keyPEM)
|
||||
if err != nil {
|
||||
return nil, errors.New("load tls certificate and key failed")
|
||||
}
|
||||
leaf, err := x509.ParseCertificate(cert.Certificate[0])
|
||||
if err != nil {
|
||||
return nil, errors.New("parse tls leaf failed")
|
||||
}
|
||||
cert.Leaf = leaf
|
||||
chains, err := l.verifyOwnChain(&cert)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := l.verifyChains(chains); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
l.cert = &cert
|
||||
l.ownChains = chains
|
||||
l.certStamp = certStamp
|
||||
l.keyStamp = keyStamp
|
||||
l.version = fmt.Sprintf("%s:%d:%d:%d:%d", certStamp.path,
|
||||
certStamp.size, certStamp.modified.UnixNano(), keyStamp.size, keyStamp.modified.UnixNano())
|
||||
return l.cert, nil
|
||||
}
|
||||
|
||||
func (l *Loader) currentTrust() (*x509.CertPool, []*x509.Certificate, error) {
|
||||
files, err := l.files.snapshot()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
data, err := secretfile.Read(files.CA)
|
||||
if err != nil {
|
||||
return nil, nil, fmt.Errorf("read tls trust: %w", err)
|
||||
}
|
||||
issuers, err := parseCertificates(data)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
roots := x509.NewCertPool()
|
||||
count := 0
|
||||
for _, cert := range issuers {
|
||||
if !cert.IsCA || !cert.BasicConstraintsValid {
|
||||
return nil, nil, errors.New("tls trust contains a non-ca certificate")
|
||||
}
|
||||
if bytes.Equal(cert.RawIssuer, cert.RawSubject) {
|
||||
if err := cert.CheckSignatureFrom(cert); err != nil {
|
||||
return nil, nil, errors.New("tls trust contains an invalid root signature")
|
||||
}
|
||||
roots.AddCert(cert)
|
||||
count++
|
||||
}
|
||||
}
|
||||
if count == 0 {
|
||||
return nil, nil, errors.New("tls trust has no root certificate")
|
||||
}
|
||||
return roots, issuers, nil
|
||||
}
|
||||
|
||||
func (l *Loader) verifyOwnChain(cert *tls.Certificate) ([][]*x509.Certificate, error) {
|
||||
roots, issuers, err := l.currentTrust()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
intermediates := x509.NewCertPool()
|
||||
for _, issuer := range issuers {
|
||||
intermediates.AddCert(issuer)
|
||||
}
|
||||
for _, der := range cert.Certificate[1:] {
|
||||
issuer, err := x509.ParseCertificate(der)
|
||||
if err != nil {
|
||||
return nil, errors.New("parse tls certificate chain failed")
|
||||
}
|
||||
intermediates.AddCert(issuer)
|
||||
}
|
||||
chains, err := cert.Leaf.Verify(x509.VerifyOptions{
|
||||
Roots: roots,
|
||||
Intermediates: intermediates,
|
||||
CurrentTime: l.now(),
|
||||
KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageAny},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, errors.New("tls own identity verification failed")
|
||||
}
|
||||
return chains, nil
|
||||
}
|
||||
|
||||
func (l *Loader) mountedRoots(files Files) (map[string]struct{}, error) {
|
||||
trust, err := secretfile.Read(files.CA)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read tls trust: %w", err)
|
||||
}
|
||||
issuers, err := parseCertificates(trust)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
current := map[string]struct{}{}
|
||||
for _, cert := range issuers {
|
||||
if bytes.Equal(cert.RawIssuer, cert.RawSubject) {
|
||||
current[string(cert.Raw)] = struct{}{}
|
||||
}
|
||||
}
|
||||
return current, nil
|
||||
}
|
||||
|
||||
func (l *Loader) checkTrust(files Files) error {
|
||||
trust, err := secretfile.Read(files.CA)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read tls trust: %w", err)
|
||||
}
|
||||
if bytes.Equal(trust, l.trust) {
|
||||
return nil
|
||||
}
|
||||
current, err := l.mountedRoots(files)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
// Adding roots (prepare overlap) is safe before a restart; removing a
|
||||
// startup root requires a restart and fails closed.
|
||||
for raw := range l.trustRoots {
|
||||
if _, ok := current[raw]; !ok {
|
||||
return errors.New("tls trust changed; restart required")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// VerifyTrustExact closes readiness unless the mounted roots equal the startup
|
||||
// roots. A superset is safe for handshakes but not for the frozen TLS pools.
|
||||
func (l *Loader) VerifyTrustExact() error {
|
||||
files, err := l.files.snapshot()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
current, err := l.mountedRoots(files)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(current) != len(l.trustRoots) {
|
||||
return errors.New("tls trust differs from startup; restart required")
|
||||
}
|
||||
for raw := range l.trustRoots {
|
||||
if _, ok := current[raw]; !ok {
|
||||
return errors.New("tls trust differs from startup; restart required")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// VerifyTrust reports whether the mounted trust bundle still contains every
|
||||
// root loaded at startup. Kept for handshake-level subset checks.
|
||||
func (l *Loader) VerifyTrust() error {
|
||||
return l.verifyTrust()
|
||||
}
|
||||
|
||||
func (l *Loader) verifyTrust() error {
|
||||
files, err := l.files.snapshot()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return l.checkTrust(files)
|
||||
}
|
||||
|
||||
func (l *Loader) verifyOwn(cert *tls.Certificate) error {
|
||||
l.mu.Lock()
|
||||
var chains [][]*x509.Certificate
|
||||
if l.cert == cert {
|
||||
chains = l.ownChains
|
||||
}
|
||||
l.mu.Unlock()
|
||||
if len(chains) == 0 {
|
||||
var err error
|
||||
chains, err = l.verifyOwnChain(cert)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
now := l.now()
|
||||
for _, chain := range chains {
|
||||
for _, member := range chain {
|
||||
if now.Before(member.NotBefore) || !now.Before(member.NotAfter) {
|
||||
return errors.New("tls own identity chain is outside its validity period")
|
||||
}
|
||||
}
|
||||
}
|
||||
return l.verifyChains(chains)
|
||||
}
|
||||
|
||||
func (l *Loader) Leaf() (*x509.Certificate, error) {
|
||||
cert, err := l.certificate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := l.verifyOwn(cert); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cert.Leaf, nil
|
||||
}
|
||||
|
||||
// Version changes with the presented leaf/key, not an independently updated CRL.
|
||||
func (l *Loader) Version() (string, error) {
|
||||
if _, err := l.certificate(); err != nil {
|
||||
return "", err
|
||||
}
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
return l.version, nil
|
||||
}
|
||||
|
||||
func (l *Loader) Client(serverName string) *tls.Config {
|
||||
return &tls.Config{
|
||||
MinVersion: tls.VersionTLS12,
|
||||
RootCAs: l.roots,
|
||||
ServerName: serverName,
|
||||
SessionTicketsDisabled: true,
|
||||
ClientSessionCache: nil,
|
||||
GetClientCertificate: func(*tls.CertificateRequestInfo) (*tls.Certificate, error) {
|
||||
cert, err := l.certificate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := l.verifyOwn(cert); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cert, nil
|
||||
},
|
||||
VerifyConnection: func(state tls.ConnectionState) error {
|
||||
if err := l.verifyTrust(); err != nil {
|
||||
return err
|
||||
}
|
||||
return l.verifyChains(state.VerifiedChains)
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Loader) Server(requiredURI string) *tls.Config {
|
||||
return &tls.Config{
|
||||
MinVersion: tls.VersionTLS12,
|
||||
ClientCAs: l.roots,
|
||||
ClientAuth: tls.RequireAndVerifyClientCert,
|
||||
SessionTicketsDisabled: true,
|
||||
GetCertificate: func(*tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||
cert, err := l.certificate()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := l.verifyOwn(cert); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cert, nil
|
||||
},
|
||||
VerifyConnection: func(state tls.ConnectionState) error {
|
||||
if err := l.verifyTrust(); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := l.verifyChains(state.VerifiedChains); err != nil {
|
||||
return err
|
||||
}
|
||||
if requiredURI == "" {
|
||||
return errors.New("tls required client identity is empty")
|
||||
}
|
||||
for _, uri := range state.PeerCertificates[0].URIs {
|
||||
if uri.String() == requiredURI {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return errors.New("tls client identity is not authorized")
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func parseCertificates(data []byte) ([]*x509.Certificate, error) {
|
||||
certs := []*x509.Certificate{}
|
||||
for len(bytes.TrimSpace(data)) > 0 {
|
||||
block, rest := pem.Decode(data)
|
||||
if block == nil || block.Type != "CERTIFICATE" {
|
||||
return nil, errors.New("malformed tls trust pem")
|
||||
}
|
||||
cert, err := x509.ParseCertificate(block.Bytes)
|
||||
if err != nil {
|
||||
return nil, errors.New("malformed tls trust certificate")
|
||||
}
|
||||
certs = append(certs, cert)
|
||||
data = rest
|
||||
}
|
||||
if len(certs) == 0 {
|
||||
return nil, errors.New("tls trust is empty")
|
||||
}
|
||||
return certs, nil
|
||||
}
|
||||
@@ -0,0 +1,430 @@
|
||||
package tlsconfig
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"io"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func getWithContext(t *testing.T, client *http.Client, endpoint string) (*http.Response, error) {
|
||||
t.Helper()
|
||||
request, err := http.NewRequestWithContext(t.Context(), http.MethodGet, endpoint, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return client.Do(request)
|
||||
}
|
||||
|
||||
type testPKI struct {
|
||||
now time.Time
|
||||
root *x509.Certificate
|
||||
issuer *x509.Certificate
|
||||
rootKey ed25519.PrivateKey
|
||||
issuerKey ed25519.PrivateKey
|
||||
}
|
||||
|
||||
func newTestPKI(t *testing.T) testPKI {
|
||||
t.Helper()
|
||||
now := time.Now().Truncate(time.Second)
|
||||
rootKey := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{1}, ed25519.SeedSize))
|
||||
issuerKey := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{2}, ed25519.SeedSize))
|
||||
rootTemplate := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "root"},
|
||||
NotBefore: now.Add(-time.Hour), NotAfter: now.Add(24 * time.Hour),
|
||||
IsCA: true, BasicConstraintsValid: true,
|
||||
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
|
||||
SubjectKeyId: []byte{1},
|
||||
}
|
||||
root := createTestCertificate(t, rootTemplate, rootTemplate, rootKey.Public(), rootKey)
|
||||
issuerTemplate := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: "issuer"},
|
||||
NotBefore: now.Add(-time.Hour), NotAfter: now.Add(12 * time.Hour),
|
||||
IsCA: true, BasicConstraintsValid: true,
|
||||
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
|
||||
SubjectKeyId: []byte{2},
|
||||
}
|
||||
issuer := createTestCertificate(t, issuerTemplate, root, issuerKey.Public(), rootKey)
|
||||
return testPKI{now: now, root: root, issuer: issuer, rootKey: rootKey, issuerKey: issuerKey}
|
||||
}
|
||||
|
||||
func createTestCertificate(
|
||||
t *testing.T,
|
||||
template, parent *x509.Certificate,
|
||||
public any,
|
||||
key ed25519.PrivateKey,
|
||||
) *x509.Certificate {
|
||||
t.Helper()
|
||||
der, err := x509.CreateCertificate(rand.Reader, template, parent, public, key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cert, err := x509.ParseCertificate(der)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return cert
|
||||
}
|
||||
|
||||
func (p testPKI) leaf(t *testing.T, role string, serial int64) (*x509.Certificate, ed25519.PrivateKey) {
|
||||
t.Helper()
|
||||
key := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{byte(serial)}, ed25519.SeedSize))
|
||||
uri, err := url.Parse("spiffe://mtusi/" + role)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
leaf := createTestCertificate(t, &x509.Certificate{
|
||||
SerialNumber: big.NewInt(serial), Subject: pkix.Name{CommonName: role},
|
||||
DNSNames: []string{"localhost", role}, URIs: []*url.URL{uri},
|
||||
NotBefore: p.now.Add(-time.Minute), NotAfter: p.now.Add(time.Hour),
|
||||
KeyUsage: x509.KeyUsageDigitalSignature,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
|
||||
}, p.issuer, key.Public(), p.issuerKey)
|
||||
return leaf, key
|
||||
}
|
||||
|
||||
func (p testPKI) crl(
|
||||
t *testing.T,
|
||||
issuer *x509.Certificate,
|
||||
key ed25519.PrivateKey,
|
||||
revoked int64,
|
||||
thisUpdate, nextUpdate time.Time,
|
||||
) []byte {
|
||||
t.Helper()
|
||||
entries := []x509.RevocationListEntry{}
|
||||
if revoked > 0 {
|
||||
entries = append(entries, x509.RevocationListEntry{
|
||||
SerialNumber: big.NewInt(revoked), RevocationTime: p.now.Add(-time.Minute),
|
||||
})
|
||||
}
|
||||
der, err := x509.CreateRevocationList(rand.Reader, &x509.RevocationList{
|
||||
Number: big.NewInt(1), ThisUpdate: thisUpdate, NextUpdate: nextUpdate,
|
||||
RevokedCertificateEntries: entries,
|
||||
}, issuer, key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return pem.EncodeToMemory(&pem.Block{Type: "X509 CRL", Bytes: der})
|
||||
}
|
||||
|
||||
func (p testPKI) bundle(t *testing.T, revokedLeaf, revokedIssuer int64) []byte {
|
||||
t.Helper()
|
||||
root := p.crl(t, p.root, p.rootKey, revokedIssuer, p.now.Add(-time.Minute), p.now.Add(time.Hour))
|
||||
issuer := p.crl(t, p.issuer, p.issuerKey, revokedLeaf, p.now.Add(-time.Minute), p.now.Add(time.Hour))
|
||||
return append(root, issuer...)
|
||||
}
|
||||
|
||||
func writeTestFile(t *testing.T, path string, data []byte) {
|
||||
t.Helper()
|
||||
if err := os.WriteFile(path, data, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func (p testPKI) publish(t *testing.T, directory, version, role string, serial int64) Files {
|
||||
t.Helper()
|
||||
path := filepath.Join(directory, "versions", version)
|
||||
if err := os.MkdirAll(path, 0o700); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
leaf, key := p.leaf(t, role, serial)
|
||||
certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: leaf.Raw})
|
||||
certPEM = append(certPEM, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: p.issuer.Raw})...)
|
||||
keyDER, err := x509.MarshalPKCS8PrivateKey(key)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeTestFile(t, filepath.Join(path, "tls.crt"), certPEM)
|
||||
writeTestFile(t, filepath.Join(path, "tls.key"), pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER}))
|
||||
ca := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: p.root.Raw})
|
||||
ca = append(ca, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: p.issuer.Raw})...)
|
||||
writeTestFile(t, filepath.Join(path, "ca.crt"), ca)
|
||||
writeTestFile(t, filepath.Join(path, "ca.crl"), p.bundle(t, 0, 0))
|
||||
if err := os.Symlink(filepath.Join("versions", version), filepath.Join(directory, "next")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.Rename(filepath.Join(directory, "next"), filepath.Join(directory, "current")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeTestFile(t, filepath.Join(directory, "next-version"), []byte(version+"\n"))
|
||||
if err := os.Rename(filepath.Join(directory, "next-version"), filepath.Join(directory, "current-version")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
current := filepath.Join(directory, "current")
|
||||
return Files{
|
||||
CA: filepath.Join(current, "ca.crt"),
|
||||
Cert: filepath.Join(current, "tls.crt"),
|
||||
Key: filepath.Join(current, "tls.key"),
|
||||
CRL: filepath.Join(current, "ca.crl"),
|
||||
Selector: filepath.Join(directory, "current-version"),
|
||||
}
|
||||
}
|
||||
|
||||
func TestRevocationsRequireEveryIssuingAuthority(t *testing.T) {
|
||||
p := newTestPKI(t)
|
||||
leaf, _ := p.leaf(t, "lb", 3)
|
||||
chain := []*x509.Certificate{leaf, p.issuer, p.root}
|
||||
cases := []struct {
|
||||
name string
|
||||
bundle []byte
|
||||
wantError bool
|
||||
}{
|
||||
{name: "valid", bundle: p.bundle(t, 0, 0)},
|
||||
{name: "revoked leaf", bundle: p.bundle(t, 3, 0), wantError: true},
|
||||
{name: "revoked intermediate", bundle: p.bundle(t, 0, 2), wantError: true},
|
||||
{name: "missing root crl", bundle: p.crl(t, p.issuer, p.issuerKey, 0,
|
||||
p.now.Add(-time.Minute), p.now.Add(time.Hour)), wantError: true},
|
||||
{name: "stale intermediate crl", bundle: append(p.crl(t, p.root, p.rootKey, 0,
|
||||
p.now.Add(-time.Minute), p.now.Add(time.Hour)), p.crl(t, p.issuer, p.issuerKey, 0,
|
||||
p.now.Add(-time.Hour), p.now.Add(-time.Minute))...), wantError: true},
|
||||
{name: "future intermediate crl", bundle: append(p.crl(t, p.root, p.rootKey, 0,
|
||||
p.now.Add(-time.Minute), p.now.Add(time.Hour)), p.crl(t, p.issuer, p.issuerKey, 0,
|
||||
p.now.Add(time.Minute), p.now.Add(time.Hour))...), wantError: true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
lists, err := parseRevocations(tc.bundle)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err = verifyRevocations(chain, lists, p.now)
|
||||
if (err != nil) != tc.wantError {
|
||||
t.Fatalf("error = %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
wrongKey := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{9}, ed25519.SeedSize))
|
||||
wrongIssuer := *p.issuer
|
||||
wrongIssuer.PublicKey = wrongKey.Public()
|
||||
bad := p.crl(t, &wrongIssuer, wrongKey, 0, p.now.Add(-time.Minute), p.now.Add(time.Hour))
|
||||
lists, err := parseRevocations(append(p.crl(t, p.root, p.rootKey, 0,
|
||||
p.now.Add(-time.Minute), p.now.Add(time.Hour)), bad...))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := verifyRevocations(chain, lists, p.now); err == nil {
|
||||
t.Fatal("bad signature accepted")
|
||||
}
|
||||
lists, err = parseRevocations(append(bad, p.bundle(t, 0, 0)...))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := verifyRevocations(chain, lists, p.now); err != nil {
|
||||
t.Fatalf("valid crl after an invalid candidate rejected: %v", err)
|
||||
}
|
||||
if _, err := parseRevocations([]byte("not a crl")); err == nil {
|
||||
t.Fatal("malformed crl accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdentityRotationAndCurrentCRLRevocation(t *testing.T) {
|
||||
p := newTestPKI(t)
|
||||
directory := t.TempDir()
|
||||
files := p.publish(t, directory, "one", "lb", 3)
|
||||
loader, err := New(files)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p.publish(t, directory, "two", "lb", 4)
|
||||
leaf, err := loader.Leaf()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if leaf.SerialNumber.Int64() != 4 {
|
||||
t.Fatal("atomic identity version not reloaded")
|
||||
}
|
||||
writeTestFile(t, filepath.Join(directory, "versions", "two", "ca.crl"), p.bundle(t, 4, 0))
|
||||
if _, err := loader.Leaf(); err == nil {
|
||||
t.Fatal("independent crl refresh did not revoke cached leaf")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrustChangeFailsClosed(t *testing.T) {
|
||||
p := newTestPKI(t)
|
||||
files := p.publish(t, t.TempDir(), "one", "lb", 3)
|
||||
loader, err := New(files)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
data, err := os.ReadFile(files.CA)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Removing a startup root must fail closed; adding one is allowed.
|
||||
var withoutRoot []byte
|
||||
for len(bytes.TrimSpace(data)) > 0 {
|
||||
block, rest := pem.Decode(data)
|
||||
if block == nil || block.Type != "CERTIFICATE" {
|
||||
t.Fatal("malformed test trust bundle")
|
||||
}
|
||||
cert, err := x509.ParseCertificate(block.Bytes)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(cert.RawIssuer, cert.RawSubject) {
|
||||
withoutRoot = append(withoutRoot, pem.EncodeToMemory(block)...)
|
||||
}
|
||||
data = rest
|
||||
}
|
||||
writeTestFile(t, files.CA, withoutRoot)
|
||||
if err := loader.verifyTrust(); err == nil || !strings.Contains(err.Error(), "trust changed") {
|
||||
t.Fatalf("removed startup root was not rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTLSRequiresHostnameAndExactClientURI(t *testing.T) {
|
||||
p := newTestPKI(t)
|
||||
serverFiles := p.publish(t, t.TempDir(), "one", "api", 3)
|
||||
serverLoader, err := New(serverFiles)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
server.TLS = serverLoader.Server("spiffe://mtusi/lb")
|
||||
server.StartTLS()
|
||||
defer server.Close()
|
||||
for _, role := range []string{"lb", "rogue"} {
|
||||
t.Run(role, func(t *testing.T) {
|
||||
files := p.publish(t, t.TempDir(), "one", role, 4)
|
||||
loader, err := New(files)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
transport := &http.Transport{TLSClientConfig: loader.Client("localhost"), DisableKeepAlives: true}
|
||||
defer transport.CloseIdleConnections()
|
||||
client := &http.Client{Transport: transport, Timeout: time.Second}
|
||||
response, err := getWithContext(t, client, server.URL)
|
||||
if role == "rogue" {
|
||||
if err == nil {
|
||||
response.Body.Close()
|
||||
t.Fatal("wrong same-ca identity accepted")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := io.Copy(io.Discard, response.Body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response.Body.Close()
|
||||
transport.TLSClientConfig = loader.Client("wrong-host")
|
||||
if response, err := getWithContext(t, client, server.URL); err == nil {
|
||||
response.Body.Close()
|
||||
t.Fatal("wrong server hostname accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
// No client certificate is rejected by the native TLS boundary.
|
||||
transport := &http.Transport{TLSClientConfig: &tls.Config{
|
||||
RootCAs: serverLoader.roots,
|
||||
ServerName: "localhost", MinVersion: tls.VersionTLS12,
|
||||
}, DisableKeepAlives: true}
|
||||
defer transport.CloseIdleConnections()
|
||||
if response, err := getWithContext(t, &http.Client{Transport: transport, Timeout: time.Second}, server.URL); err == nil {
|
||||
response.Body.Close()
|
||||
t.Fatal("missing client certificate accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTLSRevocationRejectsBothClientAndServerAfterSuccessfulConnection(t *testing.T) {
|
||||
p := newTestPKI(t)
|
||||
serverDirectory := t.TempDir()
|
||||
serverFiles := p.publish(t, serverDirectory, "one", "api", 3)
|
||||
serverLoader, err := New(serverFiles)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
server.TLS = serverLoader.Server("spiffe://mtusi/lb")
|
||||
server.StartTLS()
|
||||
defer server.Close()
|
||||
clientDirectory := t.TempDir()
|
||||
clientFiles := p.publish(t, clientDirectory, "one", "lb", 4)
|
||||
clientLoader, err := New(clientFiles)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
transport := &http.Transport{
|
||||
TLSClientConfig: clientLoader.Client("localhost"), DisableKeepAlives: true,
|
||||
}
|
||||
defer transport.CloseIdleConnections()
|
||||
client := &http.Client{Transport: transport, Timeout: time.Second}
|
||||
response, err := getWithContext(t, client, server.URL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response.Body.Close()
|
||||
// Only the client's local CRL changes: the server's own identity is valid,
|
||||
// but the client rejects its serial during normal server verification.
|
||||
writeTestFile(t, filepath.Join(clientDirectory, "versions", "one", "ca.crl"), p.bundle(t, 3, 0))
|
||||
if response, err := getWithContext(t, client, server.URL); err == nil {
|
||||
response.Body.Close()
|
||||
t.Fatal("revoked server accepted on a fresh connection")
|
||||
}
|
||||
writeTestFile(t, filepath.Join(clientDirectory, "versions", "one", "ca.crl"), p.bundle(t, 0, 0))
|
||||
// Only the server's CRL changes: the client can still present its identity,
|
||||
// but server-side RequireAndVerifyClientCert rejects the client's serial.
|
||||
writeTestFile(t, filepath.Join(serverDirectory, "versions", "one", "ca.crl"), p.bundle(t, 4, 0))
|
||||
if response, err := getWithContext(t, client, server.URL); err == nil {
|
||||
response.Body.Close()
|
||||
t.Fatal("revoked client accepted on a fresh connection")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAtomicSelectorServesRotatedIdentityWithoutNativeAlias(t *testing.T) {
|
||||
p := newTestPKI(t)
|
||||
serverDirectory := t.TempDir()
|
||||
serverFiles := p.publish(t, serverDirectory, "one", "api", 3)
|
||||
serverLoader, err := New(serverFiles)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
server.TLS = serverLoader.Server("spiffe://mtusi/lb")
|
||||
server.StartTLS()
|
||||
defer server.Close()
|
||||
clientLoader, err := New(p.publish(t, t.TempDir(), "one", "lb", 4))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
transport := &http.Transport{TLSClientConfig: clientLoader.Client("localhost"), DisableKeepAlives: true}
|
||||
defer transport.CloseIdleConnections()
|
||||
client := &http.Client{Transport: transport, Timeout: time.Second}
|
||||
p.publish(t, serverDirectory, "two", "api", 5)
|
||||
if err := os.Remove(filepath.Join(serverDirectory, "current")); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response, err := getWithContext(t, client, server.URL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
response.Body.Close()
|
||||
if response.StatusCode != http.StatusNoContent || response.TLS.PeerCertificates[0].SerialNumber.Int64() != 5 {
|
||||
t.Fatal("fresh tls did not authenticate the complete selected identity")
|
||||
}
|
||||
writeTestFile(t, serverFiles.Selector, []byte("../outside\n"))
|
||||
if response, err := getWithContext(t, client, server.URL); err == nil {
|
||||
response.Body.Close()
|
||||
t.Fatal("invalid selector retained admission through a cached identity")
|
||||
}
|
||||
}
|
||||
@@ -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,804 @@
|
||||
// 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}
|
||||
}
|
||||
|
||||
// Admission provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Admission(ctx context.Context, ownerID uuid.UUID) (int, int, int64, error) {
|
||||
ret := _mock.Called(ctx, ownerID)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Admission")
|
||||
}
|
||||
|
||||
var r0 int
|
||||
var r1 int
|
||||
var r2 int64
|
||||
var r3 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) (int, int, int64, error)); ok {
|
||||
return returnFunc(ctx, ownerID)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID) int); ok {
|
||||
r0 = returnFunc(ctx, ownerID)
|
||||
} else {
|
||||
r0 = ret.Get(0).(int)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID) int); ok {
|
||||
r1 = returnFunc(ctx, ownerID)
|
||||
} else {
|
||||
r1 = ret.Get(1).(int)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(2).(func(context.Context, uuid.UUID) int64); ok {
|
||||
r2 = returnFunc(ctx, ownerID)
|
||||
} else {
|
||||
r2 = ret.Get(2).(int64)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(3).(func(context.Context, uuid.UUID) error); ok {
|
||||
r3 = returnFunc(ctx, ownerID)
|
||||
} else {
|
||||
r3 = ret.Error(3)
|
||||
}
|
||||
return r0, r1, r2, r3
|
||||
}
|
||||
|
||||
// MockRepository_Admission_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Admission'
|
||||
type MockRepository_Admission_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Admission is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - ownerID uuid.UUID
|
||||
func (_e *MockRepository_Expecter) Admission(ctx any, ownerID any) *MockRepository_Admission_Call {
|
||||
return &MockRepository_Admission_Call{Call: _e.mock.On("Admission", ctx, ownerID)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Admission_Call) Run(run func(ctx context.Context, ownerID uuid.UUID)) *MockRepository_Admission_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_Admission_Call) Return(userPending int, totalPending int, stagedBytes int64, err error) *MockRepository_Admission_Call {
|
||||
_c.Call.Return(userPending, totalPending, stagedBytes, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Admission_Call) RunAndReturn(run func(ctx context.Context, ownerID uuid.UUID) (int, int, int64, error)) *MockRepository_Admission_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// CompletePresign provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) CompletePresign(ctx context.Context, ownerID uuid.UUID, attachmentID uuid.UUID, verifiedKey string, finalKey string, pipelineVersion int, maxAttempts int, jobID uuid.UUID) (domain.Attachment, error) {
|
||||
ret := _mock.Called(ctx, ownerID, attachmentID, verifiedKey, finalKey, pipelineVersion, maxAttempts, jobID)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for CompletePresign")
|
||||
}
|
||||
|
||||
var r0 domain.Attachment
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID, string, string, int, int, uuid.UUID) (domain.Attachment, error)); ok {
|
||||
return returnFunc(ctx, ownerID, attachmentID, verifiedKey, finalKey, pipelineVersion, maxAttempts, jobID)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, uuid.UUID, string, string, int, int, uuid.UUID) domain.Attachment); ok {
|
||||
r0 = returnFunc(ctx, ownerID, attachmentID, verifiedKey, finalKey, pipelineVersion, maxAttempts, jobID)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Attachment)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, uuid.UUID, string, string, int, int, uuid.UUID) error); ok {
|
||||
r1 = returnFunc(ctx, ownerID, attachmentID, verifiedKey, finalKey, pipelineVersion, maxAttempts, jobID)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_CompletePresign_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CompletePresign'
|
||||
type MockRepository_CompletePresign_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// CompletePresign is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - ownerID uuid.UUID
|
||||
// - attachmentID uuid.UUID
|
||||
// - verifiedKey string
|
||||
// - finalKey string
|
||||
// - pipelineVersion int
|
||||
// - maxAttempts int
|
||||
// - jobID uuid.UUID
|
||||
func (_e *MockRepository_Expecter) CompletePresign(ctx any, ownerID any, attachmentID any, verifiedKey any, finalKey any, pipelineVersion any, maxAttempts any, jobID any) *MockRepository_CompletePresign_Call {
|
||||
return &MockRepository_CompletePresign_Call{Call: _e.mock.On("CompletePresign", ctx, ownerID, attachmentID, verifiedKey, finalKey, pipelineVersion, maxAttempts, jobID)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_CompletePresign_Call) Run(run func(ctx context.Context, ownerID uuid.UUID, attachmentID uuid.UUID, verifiedKey string, finalKey string, pipelineVersion int, maxAttempts int, jobID uuid.UUID)) *MockRepository_CompletePresign_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 string
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(string)
|
||||
}
|
||||
var arg4 string
|
||||
if args[4] != nil {
|
||||
arg4 = args[4].(string)
|
||||
}
|
||||
var arg5 int
|
||||
if args[5] != nil {
|
||||
arg5 = args[5].(int)
|
||||
}
|
||||
var arg6 int
|
||||
if args[6] != nil {
|
||||
arg6 = args[6].(int)
|
||||
}
|
||||
var arg7 uuid.UUID
|
||||
if args[7] != nil {
|
||||
arg7 = args[7].(uuid.UUID)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
arg4,
|
||||
arg5,
|
||||
arg6,
|
||||
arg7,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_CompletePresign_Call) Return(attachment domain.Attachment, err error) *MockRepository_CompletePresign_Call {
|
||||
_c.Call.Return(attachment, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_CompletePresign_Call) RunAndReturn(run func(ctx context.Context, ownerID uuid.UUID, attachmentID uuid.UUID, verifiedKey string, finalKey string, pipelineVersion int, maxAttempts int, jobID uuid.UUID) (domain.Attachment, error)) *MockRepository_CompletePresign_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// CreatePresign provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) CreatePresign(ctx context.Context, draft domain.AttachmentDraft, limits domain.AdmissionLimits) (domain.Attachment, error) {
|
||||
ret := _mock.Called(ctx, draft, limits)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for CreatePresign")
|
||||
}
|
||||
|
||||
var r0 domain.Attachment
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.AdmissionLimits) (domain.Attachment, error)); ok {
|
||||
return returnFunc(ctx, draft, limits)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.AdmissionLimits) domain.Attachment); ok {
|
||||
r0 = returnFunc(ctx, draft, limits)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Attachment)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.AttachmentDraft, domain.AdmissionLimits) error); ok {
|
||||
r1 = returnFunc(ctx, draft, limits)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_CreatePresign_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreatePresign'
|
||||
type MockRepository_CreatePresign_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// CreatePresign is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - draft domain.AttachmentDraft
|
||||
// - limits domain.AdmissionLimits
|
||||
func (_e *MockRepository_Expecter) CreatePresign(ctx any, draft any, limits any) *MockRepository_CreatePresign_Call {
|
||||
return &MockRepository_CreatePresign_Call{Call: _e.mock.On("CreatePresign", ctx, draft, limits)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_CreatePresign_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft, limits domain.AdmissionLimits)) *MockRepository_CreatePresign_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)
|
||||
}
|
||||
var arg2 domain.AdmissionLimits
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(domain.AdmissionLimits)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_CreatePresign_Call) Return(attachment domain.Attachment, err error) *MockRepository_CreatePresign_Call {
|
||||
_c.Call.Return(attachment, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_CreatePresign_Call) RunAndReturn(run func(ctx context.Context, draft domain.AttachmentDraft, limits domain.AdmissionLimits) (domain.Attachment, error)) *MockRepository_CreatePresign_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// CreateQueued provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) CreateQueued(ctx context.Context, draft domain.AttachmentDraft, job domain.Job, limits domain.AdmissionLimits) (domain.Attachment, error) {
|
||||
ret := _mock.Called(ctx, draft, job, limits)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for CreateQueued")
|
||||
}
|
||||
|
||||
var r0 domain.Attachment
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.Job, domain.AdmissionLimits) (domain.Attachment, error)); ok {
|
||||
return returnFunc(ctx, draft, job, limits)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.AttachmentDraft, domain.Job, domain.AdmissionLimits) domain.Attachment); ok {
|
||||
r0 = returnFunc(ctx, draft, job, limits)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Attachment)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, domain.AttachmentDraft, domain.Job, domain.AdmissionLimits) error); ok {
|
||||
r1 = returnFunc(ctx, draft, job, limits)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_CreateQueued_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'CreateQueued'
|
||||
type MockRepository_CreateQueued_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// CreateQueued is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - draft domain.AttachmentDraft
|
||||
// - job domain.Job
|
||||
// - limits domain.AdmissionLimits
|
||||
func (_e *MockRepository_Expecter) CreateQueued(ctx any, draft any, job any, limits any) *MockRepository_CreateQueued_Call {
|
||||
return &MockRepository_CreateQueued_Call{Call: _e.mock.On("CreateQueued", ctx, draft, job, limits)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_CreateQueued_Call) Run(run func(ctx context.Context, draft domain.AttachmentDraft, job domain.Job, limits domain.AdmissionLimits)) *MockRepository_CreateQueued_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)
|
||||
}
|
||||
var arg2 domain.Job
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(domain.Job)
|
||||
}
|
||||
var arg3 domain.AdmissionLimits
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(domain.AdmissionLimits)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_CreateQueued_Call) Return(attachment domain.Attachment, err error) *MockRepository_CreateQueued_Call {
|
||||
_c.Call.Return(attachment, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_CreateQueued_Call) RunAndReturn(run func(ctx context.Context, draft domain.AttachmentDraft, job domain.Job, limits domain.AdmissionLimits) (domain.Attachment, error)) *MockRepository_CreateQueued_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
|
||||
}
|
||||
|
||||
// GetVariant provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) GetVariant(ctx context.Context, attachmentID uuid.UUID, pipelineVersion int, name domain.VariantName) (domain.Variant, error) {
|
||||
ret := _mock.Called(ctx, attachmentID, pipelineVersion, name)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for GetVariant")
|
||||
}
|
||||
|
||||
var r0 domain.Variant
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, int, domain.VariantName) (domain.Variant, error)); ok {
|
||||
return returnFunc(ctx, attachmentID, pipelineVersion, name)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, int, domain.VariantName) domain.Variant); ok {
|
||||
r0 = returnFunc(ctx, attachmentID, pipelineVersion, name)
|
||||
} else {
|
||||
r0 = ret.Get(0).(domain.Variant)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, int, domain.VariantName) error); ok {
|
||||
r1 = returnFunc(ctx, attachmentID, pipelineVersion, name)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_GetVariant_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'GetVariant'
|
||||
type MockRepository_GetVariant_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// GetVariant is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - attachmentID uuid.UUID
|
||||
// - pipelineVersion int
|
||||
// - name domain.VariantName
|
||||
func (_e *MockRepository_Expecter) GetVariant(ctx any, attachmentID any, pipelineVersion any, name any) *MockRepository_GetVariant_Call {
|
||||
return &MockRepository_GetVariant_Call{Call: _e.mock.On("GetVariant", ctx, attachmentID, pipelineVersion, name)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetVariant_Call) Run(run func(ctx context.Context, attachmentID uuid.UUID, pipelineVersion int, name domain.VariantName)) *MockRepository_GetVariant_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 int
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(int)
|
||||
}
|
||||
var arg3 domain.VariantName
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(domain.VariantName)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetVariant_Call) Return(variant domain.Variant, err error) *MockRepository_GetVariant_Call {
|
||||
_c.Call.Return(variant, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_GetVariant_Call) RunAndReturn(run func(ctx context.Context, attachmentID uuid.UUID, pipelineVersion int, name domain.VariantName) (domain.Variant, error)) *MockRepository_GetVariant_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
|
||||
}
|
||||
|
||||
// ListVariants provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) ListVariants(ctx context.Context, attachmentID uuid.UUID, pipelineVersion int) ([]domain.Variant, error) {
|
||||
ret := _mock.Called(ctx, attachmentID, pipelineVersion)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListVariants")
|
||||
}
|
||||
|
||||
var r0 []domain.Variant
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, int) ([]domain.Variant, error)); ok {
|
||||
return returnFunc(ctx, attachmentID, pipelineVersion)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, int) []domain.Variant); ok {
|
||||
r0 = returnFunc(ctx, attachmentID, pipelineVersion)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]domain.Variant)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, int) error); ok {
|
||||
r1 = returnFunc(ctx, attachmentID, pipelineVersion)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_ListVariants_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListVariants'
|
||||
type MockRepository_ListVariants_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListVariants is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - attachmentID uuid.UUID
|
||||
// - pipelineVersion int
|
||||
func (_e *MockRepository_Expecter) ListVariants(ctx any, attachmentID any, pipelineVersion any) *MockRepository_ListVariants_Call {
|
||||
return &MockRepository_ListVariants_Call{Call: _e.mock.On("ListVariants", ctx, attachmentID, pipelineVersion)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListVariants_Call) Run(run func(ctx context.Context, attachmentID uuid.UUID, pipelineVersion int)) *MockRepository_ListVariants_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 int
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(int)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListVariants_Call) Return(variants []domain.Variant, err error) *MockRepository_ListVariants_Call {
|
||||
_c.Call.Return(variants, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_ListVariants_Call) RunAndReturn(run func(ctx context.Context, attachmentID uuid.UUID, pipelineVersion int) ([]domain.Variant, error)) *MockRepository_ListVariants_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
// 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"
|
||||
)
|
||||
|
||||
// NewMockSweepRepository creates a new instance of MockSweepRepository. 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 NewMockSweepRepository(t interface {
|
||||
mock.TestingT
|
||||
Cleanup(func())
|
||||
}) *MockSweepRepository {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
|
||||
mock := &MockSweepRepository{}
|
||||
mock.Mock.Test(t)
|
||||
|
||||
t.Cleanup(func() {
|
||||
if helper, ok := t.(interface{ Helper() }); ok {
|
||||
helper.Helper()
|
||||
}
|
||||
mock.AssertExpectations(t)
|
||||
})
|
||||
|
||||
return mock
|
||||
}
|
||||
|
||||
// MockSweepRepository is an autogenerated mock type for the SweepRepository type
|
||||
type MockSweepRepository struct {
|
||||
mock.Mock
|
||||
}
|
||||
|
||||
type MockSweepRepository_Expecter struct {
|
||||
mock *mock.Mock
|
||||
}
|
||||
|
||||
func (_m *MockSweepRepository) EXPECT() *MockSweepRepository_Expecter {
|
||||
return &MockSweepRepository_Expecter{mock: &_m.Mock}
|
||||
}
|
||||
|
||||
// DeletePending provides a mock function for the type MockSweepRepository
|
||||
func (_mock *MockSweepRepository) 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
|
||||
}
|
||||
|
||||
// MockSweepRepository_DeletePending_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'DeletePending'
|
||||
type MockSweepRepository_DeletePending_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// DeletePending is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - id uuid.UUID
|
||||
func (_e *MockSweepRepository_Expecter) DeletePending(ctx any, id any) *MockSweepRepository_DeletePending_Call {
|
||||
return &MockSweepRepository_DeletePending_Call{Call: _e.mock.On("DeletePending", ctx, id)}
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_DeletePending_Call) Run(run func(ctx context.Context, id uuid.UUID)) *MockSweepRepository_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 *MockSweepRepository_DeletePending_Call) Return(err error) *MockSweepRepository_DeletePending_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_DeletePending_Call) RunAndReturn(run func(ctx context.Context, id uuid.UUID) error) *MockSweepRepository_DeletePending_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// ListPendingPresign provides a mock function for the type MockSweepRepository
|
||||
func (_mock *MockSweepRepository) ListPendingPresign(ctx context.Context, createdBefore time.Time, limit int) ([]domain.Attachment, error) {
|
||||
ret := _mock.Called(ctx, createdBefore, limit)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListPendingPresign")
|
||||
}
|
||||
|
||||
var r0 []domain.Attachment
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, time.Time, int) ([]domain.Attachment, error)); ok {
|
||||
return returnFunc(ctx, createdBefore, limit)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, time.Time, int) []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, int) error); ok {
|
||||
r1 = returnFunc(ctx, createdBefore, limit)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockSweepRepository_ListPendingPresign_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListPendingPresign'
|
||||
type MockSweepRepository_ListPendingPresign_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListPendingPresign is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - createdBefore time.Time
|
||||
// - limit int
|
||||
func (_e *MockSweepRepository_Expecter) ListPendingPresign(ctx any, createdBefore any, limit any) *MockSweepRepository_ListPendingPresign_Call {
|
||||
return &MockSweepRepository_ListPendingPresign_Call{Call: _e.mock.On("ListPendingPresign", ctx, createdBefore, limit)}
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_ListPendingPresign_Call) Run(run func(ctx context.Context, createdBefore time.Time, limit int)) *MockSweepRepository_ListPendingPresign_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 int
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(int)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_ListPendingPresign_Call) Return(attachments []domain.Attachment, err error) *MockSweepRepository_ListPendingPresign_Call {
|
||||
_c.Call.Return(attachments, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_ListPendingPresign_Call) RunAndReturn(run func(ctx context.Context, createdBefore time.Time, limit int) ([]domain.Attachment, error)) *MockSweepRepository_ListPendingPresign_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// ListReferencedKeys provides a mock function for the type MockSweepRepository
|
||||
func (_mock *MockSweepRepository) ListReferencedKeys(ctx context.Context, afterKey string, limit int) ([]string, error) {
|
||||
ret := _mock.Called(ctx, afterKey, limit)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListReferencedKeys")
|
||||
}
|
||||
|
||||
var r0 []string
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string, int) ([]string, error)); ok {
|
||||
return returnFunc(ctx, afterKey, limit)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, string, int) []string); ok {
|
||||
r0 = returnFunc(ctx, afterKey, limit)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]string)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, string, int) error); ok {
|
||||
r1 = returnFunc(ctx, afterKey, limit)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockSweepRepository_ListReferencedKeys_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListReferencedKeys'
|
||||
type MockSweepRepository_ListReferencedKeys_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListReferencedKeys is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - afterKey string
|
||||
// - limit int
|
||||
func (_e *MockSweepRepository_Expecter) ListReferencedKeys(ctx any, afterKey any, limit any) *MockSweepRepository_ListReferencedKeys_Call {
|
||||
return &MockSweepRepository_ListReferencedKeys_Call{Call: _e.mock.On("ListReferencedKeys", ctx, afterKey, limit)}
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_ListReferencedKeys_Call) Run(run func(ctx context.Context, afterKey string, limit int)) *MockSweepRepository_ListReferencedKeys_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 int
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(int)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_ListReferencedKeys_Call) Return(strings []string, err error) *MockSweepRepository_ListReferencedKeys_Call {
|
||||
_c.Call.Return(strings, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_ListReferencedKeys_Call) RunAndReturn(run func(ctx context.Context, afterKey string, limit int) ([]string, error)) *MockSweepRepository_ListReferencedKeys_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// ListStaleStaging provides a mock function for the type MockSweepRepository
|
||||
func (_mock *MockSweepRepository) ListStaleStaging(ctx context.Context, readyBefore time.Time, failedBefore time.Time, limit int) ([]domain.StaleStaging, error) {
|
||||
ret := _mock.Called(ctx, readyBefore, failedBefore, limit)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for ListStaleStaging")
|
||||
}
|
||||
|
||||
var r0 []domain.StaleStaging
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, time.Time, time.Time, int) ([]domain.StaleStaging, error)); ok {
|
||||
return returnFunc(ctx, readyBefore, failedBefore, limit)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, time.Time, time.Time, int) []domain.StaleStaging); ok {
|
||||
r0 = returnFunc(ctx, readyBefore, failedBefore, limit)
|
||||
} else {
|
||||
if ret.Get(0) != nil {
|
||||
r0 = ret.Get(0).([]domain.StaleStaging)
|
||||
}
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, time.Time, time.Time, int) error); ok {
|
||||
r1 = returnFunc(ctx, readyBefore, failedBefore, limit)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockSweepRepository_ListStaleStaging_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'ListStaleStaging'
|
||||
type MockSweepRepository_ListStaleStaging_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// ListStaleStaging is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - readyBefore time.Time
|
||||
// - failedBefore time.Time
|
||||
// - limit int
|
||||
func (_e *MockSweepRepository_Expecter) ListStaleStaging(ctx any, readyBefore any, failedBefore any, limit any) *MockSweepRepository_ListStaleStaging_Call {
|
||||
return &MockSweepRepository_ListStaleStaging_Call{Call: _e.mock.On("ListStaleStaging", ctx, readyBefore, failedBefore, limit)}
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_ListStaleStaging_Call) Run(run func(ctx context.Context, readyBefore time.Time, failedBefore time.Time, limit int)) *MockSweepRepository_ListStaleStaging_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 time.Time
|
||||
if args[2] != nil {
|
||||
arg2 = args[2].(time.Time)
|
||||
}
|
||||
var arg3 int
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(int)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_ListStaleStaging_Call) Return(staleStagings []domain.StaleStaging, err error) *MockSweepRepository_ListStaleStaging_Call {
|
||||
_c.Call.Return(staleStagings, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_ListStaleStaging_Call) RunAndReturn(run func(ctx context.Context, readyBefore time.Time, failedBefore time.Time, limit int) ([]domain.StaleStaging, error)) *MockSweepRepository_ListStaleStaging_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
|
||||
// MarkStagingDeleted provides a mock function for the type MockSweepRepository
|
||||
func (_mock *MockSweepRepository) MarkStagingDeleted(ctx context.Context, attachmentID uuid.UUID, stagingKey string) error {
|
||||
ret := _mock.Called(ctx, attachmentID, stagingKey)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for MarkStagingDeleted")
|
||||
}
|
||||
|
||||
var r0 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, string) error); ok {
|
||||
r0 = returnFunc(ctx, attachmentID, stagingKey)
|
||||
} else {
|
||||
r0 = ret.Error(0)
|
||||
}
|
||||
return r0
|
||||
}
|
||||
|
||||
// MockSweepRepository_MarkStagingDeleted_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'MarkStagingDeleted'
|
||||
type MockSweepRepository_MarkStagingDeleted_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// MarkStagingDeleted is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - attachmentID uuid.UUID
|
||||
// - stagingKey string
|
||||
func (_e *MockSweepRepository_Expecter) MarkStagingDeleted(ctx any, attachmentID any, stagingKey any) *MockSweepRepository_MarkStagingDeleted_Call {
|
||||
return &MockSweepRepository_MarkStagingDeleted_Call{Call: _e.mock.On("MarkStagingDeleted", ctx, attachmentID, stagingKey)}
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_MarkStagingDeleted_Call) Run(run func(ctx context.Context, attachmentID uuid.UUID, stagingKey string)) *MockSweepRepository_MarkStagingDeleted_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 *MockSweepRepository_MarkStagingDeleted_Call) Return(err error) *MockSweepRepository_MarkStagingDeleted_Call {
|
||||
_c.Call.Return(err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockSweepRepository_MarkStagingDeleted_Call) RunAndReturn(run func(ctx context.Context, attachmentID uuid.UUID, stagingKey string) error) *MockSweepRepository_MarkStagingDeleted_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,712 @@
|
||||
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"
|
||||
"golang.org/x/sync/semaphore"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/imagecheck"
|
||||
"mtusi-messenger/internal/platform/objectstore"
|
||||
"mtusi-messenger/internal/telemetry"
|
||||
)
|
||||
|
||||
const (
|
||||
contentTypePNG = "image/png"
|
||||
contentTypeJPEG = "image/jpeg"
|
||||
|
||||
objectPrefixAttachments = domain.AttachmentsPrefix
|
||||
objectPrefixStaging = domain.StagingUploadPrefix
|
||||
objectPrefixPresign = domain.StagingPresignPrefix
|
||||
)
|
||||
|
||||
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. Job/outbox writes are atomic with the attachment
|
||||
// row inside CreateQueued/CompletePresign.
|
||||
type Repository interface {
|
||||
IsChatMember(ctx context.Context, chatID, userID uuid.UUID) (bool, error)
|
||||
GetForMember(ctx context.Context, userID, id uuid.UUID) (domain.Attachment, error)
|
||||
GetForOwner(ctx context.Context, ownerID, id uuid.UUID) (domain.Attachment, error)
|
||||
ListVariants(ctx context.Context, attachmentID uuid.UUID, pipelineVersion int) ([]domain.Variant, error)
|
||||
GetVariant(
|
||||
ctx context.Context,
|
||||
attachmentID uuid.UUID,
|
||||
pipelineVersion int,
|
||||
name domain.VariantName,
|
||||
) (domain.Variant, error)
|
||||
CreateQueued(
|
||||
ctx context.Context,
|
||||
draft domain.AttachmentDraft,
|
||||
job domain.Job,
|
||||
limits domain.AdmissionLimits,
|
||||
) (domain.Attachment, error)
|
||||
CreatePresign(
|
||||
ctx context.Context,
|
||||
draft domain.AttachmentDraft,
|
||||
limits domain.AdmissionLimits,
|
||||
) (domain.Attachment, error)
|
||||
CompletePresign(
|
||||
ctx context.Context,
|
||||
ownerID, attachmentID uuid.UUID,
|
||||
verifiedKey, finalKey string,
|
||||
pipelineVersion, maxAttempts int,
|
||||
jobID uuid.UUID,
|
||||
) (domain.Attachment, error)
|
||||
Admission(ctx context.Context, ownerID uuid.UUID) (userPending, totalPending int, stagedBytes int64, err error)
|
||||
DeletePending(ctx context.Context, id uuid.UUID) error
|
||||
}
|
||||
|
||||
// Config carries attachment limits and the shared job contract knobs.
|
||||
type Config struct {
|
||||
MaxUploadBytes int64
|
||||
MaxImagePixels int64
|
||||
PresignTTL time.Duration
|
||||
|
||||
PipelineVersion int
|
||||
MaxAttempts int
|
||||
MaxPendingPerUser int
|
||||
MaxPending int
|
||||
MaxStagedBytes int64
|
||||
MaxConcurrent int
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
repo Repository
|
||||
store objectstore.Store
|
||||
config Config
|
||||
log *slog.Logger
|
||||
upload *semaphore.Weighted
|
||||
}
|
||||
|
||||
func NewService(repo Repository, store objectstore.Store, config Config, log *slog.Logger) *Service {
|
||||
if log == nil {
|
||||
log = slog.Default()
|
||||
}
|
||||
|
||||
service := &Service{repo: repo, store: store, config: config, log: log}
|
||||
if config.MaxConcurrent > 0 {
|
||||
service.upload = semaphore.NewWeighted(int64(config.MaxConcurrent))
|
||||
}
|
||||
|
||||
return service
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
// Upload durably stages the original, records the job intent and returns the
|
||||
// queued snapshot. It never waits for the broker or the worker.
|
||||
func (s *Service) Upload(ctx context.Context, input UploadInput) (domain.Attachment, error) {
|
||||
if s.upload != nil {
|
||||
if err := s.upload.Acquire(ctx, 1); err != nil {
|
||||
return domain.Attachment{}, unavailable("acquire upload slot", err)
|
||||
}
|
||||
defer s.upload.Release(1)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
userPending, totalPending, stagedBytes, err := s.repo.Admission(ctx, input.OwnerID)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, unavailable("check admission", err)
|
||||
}
|
||||
|
||||
if (s.config.MaxPendingPerUser > 0 && userPending >= s.config.MaxPendingPerUser) ||
|
||||
(s.config.MaxPending > 0 && totalPending >= s.config.MaxPending) ||
|
||||
(s.config.MaxStagedBytes > 0 && stagedBytes >= s.config.MaxStagedBytes) {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: too many unfinished uploads", domain.ErrRateLimited)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
jobID, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("generate job id: %w", err)
|
||||
}
|
||||
|
||||
stagingKey := domain.StagingUploadKey(input.ChatID, id)
|
||||
finalKey := domain.OriginalObjectKey(input.ChatID, id)
|
||||
|
||||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("rewind upload: %w", err)
|
||||
}
|
||||
|
||||
if err := s.store.Put(ctx, stagingKey, file, size, info.ContentType, map[string]string{"sha256": sum}); err != nil {
|
||||
return domain.Attachment{}, unavailable("store staging object", err)
|
||||
}
|
||||
|
||||
if err := s.verifyStaging(ctx, stagingKey, size, sum); err != nil {
|
||||
s.deleteObject(ctx, id, stagingKey)
|
||||
|
||||
return domain.Attachment{}, unavailable("verify staging object", err)
|
||||
}
|
||||
|
||||
job := domain.Job{
|
||||
ID: jobID,
|
||||
AttachmentID: id,
|
||||
PipelineVersion: s.config.PipelineVersion,
|
||||
SourceKey: stagingKey,
|
||||
Attempt: 1,
|
||||
MaxAttempts: s.config.MaxAttempts,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
}
|
||||
|
||||
limits := s.admissionLimits()
|
||||
|
||||
created, err := s.repo.CreateQueued(ctx, domain.AttachmentDraft{
|
||||
ID: id,
|
||||
ChatID: input.ChatID,
|
||||
OwnerID: input.OwnerID,
|
||||
ObjectKey: finalKey,
|
||||
StagingKey: stagingKey,
|
||||
Filename: input.Filename,
|
||||
ContentType: info.ContentType,
|
||||
SizeBytes: size,
|
||||
SHA256: sum,
|
||||
Status: domain.AttachmentQueued,
|
||||
PipelineVersion: s.config.PipelineVersion,
|
||||
}, job, limits)
|
||||
if err != nil {
|
||||
if errors.Is(err, domain.ErrRateLimited) {
|
||||
s.deleteObject(ctx, id, stagingKey)
|
||||
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
|
||||
// An ambiguous COMMIT may have persisted the intent; leave the staging
|
||||
// object for the sweeper instead of destroying a queued job's source.
|
||||
return domain.Attachment{}, unavailable("commit attachment intent", err)
|
||||
}
|
||||
|
||||
created.Variants = []domain.Variant{}
|
||||
telemetry.RecordJobAccepted(ctx, created.PipelineVersion)
|
||||
|
||||
return created, nil
|
||||
}
|
||||
|
||||
// Get returns metadata for any public status. Variants are exposed only for the
|
||||
// currently published pipeline version and only when ready.
|
||||
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
|
||||
}
|
||||
|
||||
if !attachment.Status.Public() {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: attachment is %s", domain.ErrConflict, attachment.Status)
|
||||
}
|
||||
|
||||
return s.withVariants(ctx, attachment)
|
||||
}
|
||||
|
||||
// OpenVariant returns metadata plus the selected content stream. Only a ready
|
||||
// attachment has bytes.
|
||||
func (s *Service) OpenVariant(
|
||||
ctx context.Context,
|
||||
callerID, id uuid.UUID,
|
||||
name domain.VariantName,
|
||||
) (domain.Attachment, domain.Variant, io.ReadCloser, error) {
|
||||
attachment, err := s.repo.GetForMember(ctx, callerID, id)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, domain.Variant{}, nil, err
|
||||
}
|
||||
|
||||
if !attachment.Status.Public() || attachment.Status != domain.AttachmentReady {
|
||||
return domain.Attachment{}, domain.Variant{}, nil, fmt.Errorf(
|
||||
"%w: attachment is %s", domain.ErrConflict, attachment.Status,
|
||||
)
|
||||
}
|
||||
|
||||
if name == "" || name == domain.VariantOriginal {
|
||||
body, _, err := s.store.Open(ctx, attachment.ObjectKey)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, domain.Variant{}, nil, err
|
||||
}
|
||||
|
||||
return attachment, domain.Variant{
|
||||
Name: domain.VariantOriginal,
|
||||
ContentType: attachment.ContentType,
|
||||
SizeBytes: attachment.SizeBytes,
|
||||
SHA256: attachment.SHA256,
|
||||
ObjectKey: attachment.ObjectKey,
|
||||
}, body, nil
|
||||
}
|
||||
|
||||
if !name.Valid() {
|
||||
return domain.Attachment{}, domain.Variant{}, nil, fmt.Errorf(
|
||||
"%w: variant %q", domain.ErrValidation, name,
|
||||
)
|
||||
}
|
||||
|
||||
variant, err := s.repo.GetVariant(ctx, attachment.ID, attachment.PipelineVersion, name)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, domain.Variant{}, nil, err
|
||||
}
|
||||
|
||||
body, _, err := s.store.Open(ctx, variant.ObjectKey)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, domain.Variant{}, nil, err
|
||||
}
|
||||
|
||||
return attachment, variant, body, nil
|
||||
}
|
||||
|
||||
// Open is kept for the legacy service port used by tests.
|
||||
func (s *Service) Open(ctx context.Context, callerID, id uuid.UUID) (domain.Attachment, io.ReadCloser, error) {
|
||||
attachment, _, body, err := s.OpenVariant(ctx, callerID, id, domain.VariantOriginal)
|
||||
|
||||
return attachment, body, err
|
||||
}
|
||||
|
||||
func (s *Service) withVariants(ctx context.Context, attachment domain.Attachment) (domain.Attachment, error) {
|
||||
attachment.Variants = []domain.Variant{}
|
||||
|
||||
if attachment.Status != domain.AttachmentReady {
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
variants, err := s.repo.ListVariants(ctx, attachment.ID, attachment.PipelineVersion)
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
|
||||
if variants != nil {
|
||||
attachment.Variants = variants
|
||||
}
|
||||
|
||||
return attachment, 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.CreatePresign(ctx, domain.AttachmentDraft{
|
||||
ID: id,
|
||||
ChatID: request.ChatID,
|
||||
OwnerID: request.OwnerID,
|
||||
ObjectKey: stagingKey,
|
||||
StagingKey: stagingKey,
|
||||
Filename: request.Filename,
|
||||
ContentType: request.ContentType,
|
||||
SizeBytes: request.SizeBytes,
|
||||
SHA256: request.SHA256,
|
||||
Status: domain.AttachmentPending,
|
||||
PipelineVersion: s.config.PipelineVersion,
|
||||
}, s.admissionLimits()); 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
|
||||
}
|
||||
|
||||
// Complete verifies the presigned object, copies the verified bytes to a
|
||||
// server-owned staging key, and enqueues the same async pipeline as the proxy
|
||||
// upload. The client's staging key remains writable until the verified copy is
|
||||
// durable.
|
||||
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, domain.AttachmentQueued, domain.AttachmentProcessing:
|
||||
if attachment.SHA256 != requestSHA {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: attachment already completed with another checksum", domain.ErrConflict)
|
||||
}
|
||||
|
||||
return s.withVariants(ctx, attachment)
|
||||
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
|
||||
}
|
||||
|
||||
file, size, sum, err := s.spool(body)
|
||||
_ = body.Close()
|
||||
|
||||
if err != nil {
|
||||
return domain.Attachment{}, err
|
||||
}
|
||||
|
||||
defer func() { _ = file.Close() }()
|
||||
defer func() { _ = os.Remove(file.Name()) }()
|
||||
|
||||
if size != attachment.SizeBytes {
|
||||
s.cleanupPending(ctx, id, attachment.ObjectKey)
|
||||
|
||||
return domain.Attachment{}, fmt.Errorf("%w: uploaded object size changed", domain.ErrValidation)
|
||||
}
|
||||
|
||||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("rewind uploaded object: %w", err)
|
||||
}
|
||||
|
||||
info, err := imagecheck.Validate(file, s.config.MaxImagePixels)
|
||||
if err != nil {
|
||||
s.cleanupPending(ctx, id, attachment.ObjectKey)
|
||||
|
||||
return domain.Attachment{}, mapImageError(err)
|
||||
}
|
||||
|
||||
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,
|
||||
)
|
||||
}
|
||||
|
||||
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 {
|
||||
return domain.Attachment{}, fmt.Errorf("%w: completion checksum mismatch", domain.ErrConflict)
|
||||
}
|
||||
|
||||
verifiedKey := domain.StagingVerifiedKey(attachment.ChatID, attachment.ID)
|
||||
finalKey := domain.OriginalObjectKey(attachment.ChatID, attachment.ID)
|
||||
|
||||
if _, err := file.Seek(0, io.SeekStart); err != nil {
|
||||
return domain.Attachment{}, fmt.Errorf("rewind verified object: %w", err)
|
||||
}
|
||||
|
||||
if err := s.store.Put(ctx, verifiedKey, file, size, info.ContentType, map[string]string{"sha256": sum}); err != nil {
|
||||
return domain.Attachment{}, unavailable("store verified object", err)
|
||||
}
|
||||
|
||||
if err := s.verifyStaging(ctx, verifiedKey, size, sum); err != nil {
|
||||
s.deleteObject(ctx, id, verifiedKey)
|
||||
|
||||
return domain.Attachment{}, unavailable("verify staging object", err)
|
||||
}
|
||||
|
||||
jobID, err := uuid.NewV7()
|
||||
if err != nil {
|
||||
s.deleteObject(ctx, id, verifiedKey)
|
||||
|
||||
return domain.Attachment{}, fmt.Errorf("generate job id: %w", err)
|
||||
}
|
||||
|
||||
queued, err := s.repo.CompletePresign(
|
||||
ctx, ownerID, id, verifiedKey, finalKey,
|
||||
s.config.PipelineVersion, s.config.MaxAttempts, jobID,
|
||||
)
|
||||
if err != nil {
|
||||
// The verified key is shared by concurrent completions of this
|
||||
// attachment. Never delete it here: a winning request may already have
|
||||
// queued a job pointing at it. The orphan sweeper owns abandoned keys.
|
||||
if errors.Is(err, domain.ErrConflict) {
|
||||
current, getErr := s.repo.GetForOwner(ctx, ownerID, id)
|
||||
if getErr == nil && current.SHA256 == requestSHA && current.Status.Public() {
|
||||
return s.withVariants(ctx, current)
|
||||
}
|
||||
|
||||
return domain.Attachment{}, fmt.Errorf("%w: attachment is no longer pending", domain.ErrConflict)
|
||||
}
|
||||
|
||||
return domain.Attachment{}, unavailable("commit presigned attachment", err)
|
||||
}
|
||||
|
||||
if err := s.store.Delete(ctx, attachment.ObjectKey); err != nil && !errors.Is(err, domain.ErrNotFound) {
|
||||
s.log.WarnContext(ctx, "presign staging cleanup failed",
|
||||
slog.String("attachment_id", id.String()),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
}
|
||||
|
||||
queued.Variants = []domain.Variant{}
|
||||
telemetry.RecordJobAccepted(ctx, queued.PipelineVersion)
|
||||
|
||||
return queued, nil
|
||||
}
|
||||
|
||||
// verifyStaging checks the freshly written object; a mismatch is a broken
|
||||
// staging handoff and must never become a 202.
|
||||
func (s *Service) admissionLimits() domain.AdmissionLimits {
|
||||
return domain.AdmissionLimits{
|
||||
PerUser: s.config.MaxPendingPerUser,
|
||||
Total: s.config.MaxPending,
|
||||
Bytes: s.config.MaxStagedBytes,
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) verifyStaging(ctx context.Context, key string, size int64, sum string) error {
|
||||
head, err := s.store.Head(ctx, key)
|
||||
if err != nil {
|
||||
return fmt.Errorf("head staging object: %w", err)
|
||||
}
|
||||
|
||||
if head.Size != size {
|
||||
return fmt.Errorf("staging size %d, want %d", head.Size, size)
|
||||
}
|
||||
|
||||
if sha := head.Metadata["sha256"]; sha != "" && sha != sum {
|
||||
return errors.New("staging checksum metadata does not match")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Service) spool(body io.Reader) (*os.File, int64, string, error) {
|
||||
file, err := os.CreateTemp("", "lab5-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) deleteObject(ctx context.Context, id uuid.UUID, key string) {
|
||||
if key == "" {
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.store.Delete(ctx, key); err != nil && !errors.Is(err, domain.ErrNotFound) {
|
||||
s.log.WarnContext(ctx, "object cleanup failed",
|
||||
slog.String("attachment_id", id.String()),
|
||||
slog.Any("error", err),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) cleanupPending(ctx context.Context, id uuid.UUID, objectKey string) {
|
||||
s.deleteObject(ctx, id, objectKey)
|
||||
|
||||
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,509 @@
|
||||
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) Ping(context.Context) error { return 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,
|
||||
PipelineVersion: 1,
|
||||
MaxAttempts: 5,
|
||||
}
|
||||
}
|
||||
|
||||
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 TestUploadStagesAndQueues(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)
|
||||
digest := hex.EncodeToString(sum[:])
|
||||
|
||||
repo.EXPECT().IsChatMember(mock.Anything, chatID, ownerID).Return(true, nil).Once()
|
||||
repo.EXPECT().Admission(mock.Anything, ownerID).Return(0, 0, int64(0), nil).Once()
|
||||
repo.EXPECT().CreateQueued(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 == digest && draft.Status == domain.AttachmentQueued &&
|
||||
draft.PipelineVersion == 1 &&
|
||||
strings.HasPrefix(draft.ObjectKey, "attachments/") &&
|
||||
strings.HasPrefix(draft.StagingKey, "staging/uploads/")
|
||||
}), mock.MatchedBy(func(job domain.Job) bool {
|
||||
return job.PipelineVersion == 1 && job.Attempt == 1 &&
|
||||
job.MaxAttempts == 5 && job.SourceKey != ""
|
||||
}), domain.AdmissionLimits{}).Return(domain.Attachment{
|
||||
ID: uuid.New(), ChatID: chatID, OwnerID: ownerID,
|
||||
ContentType: "image/png", SizeBytes: int64(len(content)), SHA256: digest,
|
||||
Status: domain.AttachmentQueued, PipelineVersion: 1,
|
||||
}, 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.AttachmentQueued, result.Status)
|
||||
require.Len(t, store.objects, 1)
|
||||
for key := range store.objects {
|
||||
require.Contains(t, key, "staging/uploads/")
|
||||
}
|
||||
}
|
||||
|
||||
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,
|
||||
PipelineVersion: 1, MaxAttempts: 5,
|
||||
}, slog.Default())
|
||||
|
||||
repo.EXPECT().IsChatMember(mock.Anything, mock.Anything, mock.Anything).Return(true, nil).Once()
|
||||
repo.EXPECT().Admission(mock.Anything, mock.Anything).Return(0, 0, int64(0), 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()
|
||||
repo.EXPECT().Admission(mock.Anything, mock.Anything).Return(0, 0, int64(0), 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 TestUploadAdmissionRejectsFlood(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
service := attachment.NewService(repo, newFakeStore(), attachment.Config{
|
||||
MaxUploadBytes: 1 << 20, MaxImagePixels: 1_000_000, PresignTTL: time.Minute,
|
||||
PipelineVersion: 1, MaxAttempts: 5, MaxPendingPerUser: 1,
|
||||
}, slog.Default())
|
||||
|
||||
repo.EXPECT().IsChatMember(mock.Anything, mock.Anything, mock.Anything).Return(true, nil).Once()
|
||||
repo.EXPECT().Admission(mock.Anything, mock.Anything).Return(1, 1, int64(0), nil).Once()
|
||||
|
||||
_, err := service.Upload(t.Context(), attachment.UploadInput{
|
||||
ChatID: uuid.New(), OwnerID: uuid.New(), Filename: "photo.png",
|
||||
DeclaredContentType: "image/png", Body: bytes.NewReader(pngBytes(t, 8, 8)),
|
||||
})
|
||||
require.ErrorIs(t, err, domain.ErrRateLimited)
|
||||
}
|
||||
|
||||
func TestGetReturnsQueuedSnapshotWithoutVariants(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.AttachmentQueued, PipelineVersion: 1}, nil).Once()
|
||||
|
||||
got, err := service.Get(t.Context(), uuid.New(), uuid.New())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, domain.AttachmentQueued, got.Status)
|
||||
require.Empty(t, got.Variants)
|
||||
}
|
||||
|
||||
func TestGetReadyLoadsCurrentVariants(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
service := attachment.NewService(repo, newFakeStore(), serviceConfig(), slog.Default())
|
||||
|
||||
attachmentID := uuid.New()
|
||||
variant := domain.Variant{Name: domain.VariantThumbnail, ContentType: "image/jpeg", SizeBytes: 10, Width: 256, Height: 160, SHA256: strings.Repeat("a", 64)}
|
||||
|
||||
repo.EXPECT().GetForMember(mock.Anything, mock.Anything, attachmentID).
|
||||
Return(domain.Attachment{ID: attachmentID, Status: domain.AttachmentReady, PipelineVersion: 2}, nil).Once()
|
||||
repo.EXPECT().ListVariants(mock.Anything, attachmentID, 2).Return([]domain.Variant{variant}, nil).Once()
|
||||
|
||||
got, err := service.Get(t.Context(), uuid.New(), attachmentID)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []domain.Variant{variant}, got.Variants)
|
||||
}
|
||||
|
||||
func TestGetRejectsInternalPending(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 TestOpenVariantRejectsQueued(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.AttachmentQueued}, nil).Once()
|
||||
|
||||
_, _, _, err := service.OpenVariant(t.Context(), uuid.New(), uuid.New(), domain.VariantOriginal)
|
||||
require.ErrorIs(t, err, domain.ErrConflict)
|
||||
}
|
||||
|
||||
func TestCompleteQueuesPresignedObject(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,
|
||||
StagingKey: stagingKey, ContentType: "image/png",
|
||||
SizeBytes: int64(len(content)), SHA256: digest,
|
||||
Status: domain.AttachmentPending, PipelineVersion: 1,
|
||||
}
|
||||
|
||||
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(pending, nil).Once()
|
||||
repo.EXPECT().CompletePresign(
|
||||
mock.Anything, ownerID, id,
|
||||
mock.MatchedBy(func(key string) bool { return strings.HasPrefix(key, "staging/verified/") }),
|
||||
mock.MatchedBy(func(key string) bool { return strings.HasPrefix(key, "attachments/") }),
|
||||
1, 5, mock.Anything,
|
||||
).Return(domain.Attachment{
|
||||
ID: id, ChatID: chatID, OwnerID: ownerID, ContentType: "image/png",
|
||||
SizeBytes: int64(len(content)), SHA256: digest,
|
||||
Status: domain.AttachmentQueued, PipelineVersion: 1,
|
||||
}, nil).Once()
|
||||
|
||||
completed, err := service.Complete(t.Context(), ownerID, id, digest)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, domain.AttachmentQueued, completed.Status)
|
||||
require.NotContains(t, store.objects, stagingKey)
|
||||
require.Len(t, store.objects, 1)
|
||||
}
|
||||
|
||||
func TestCompleteConcurrentConflictKeepsVerifiedSource(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,
|
||||
StagingKey: stagingKey, ContentType: "image/png",
|
||||
SizeBytes: int64(len(content)), SHA256: digest,
|
||||
Status: domain.AttachmentPending, PipelineVersion: 1,
|
||||
}
|
||||
queued := domain.Attachment{
|
||||
ID: id, ChatID: chatID, OwnerID: ownerID, ObjectKey: "attachments/" + chatID.String() + "/" + id.String(),
|
||||
ContentType: "image/png", SizeBytes: int64(len(content)), SHA256: digest,
|
||||
Status: domain.AttachmentQueued, PipelineVersion: 1,
|
||||
}
|
||||
|
||||
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(pending, nil).Once()
|
||||
repo.EXPECT().CompletePresign(
|
||||
mock.Anything, ownerID, id, mock.Anything, mock.Anything,
|
||||
1, 5, mock.Anything,
|
||||
).Return(domain.Attachment{}, domain.ErrConflict).Once()
|
||||
repo.EXPECT().GetForOwner(mock.Anything, ownerID, id).Return(queued, nil).Once()
|
||||
|
||||
got, err := service.Complete(t.Context(), ownerID, id, digest)
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, domain.AttachmentQueued, got.Status)
|
||||
|
||||
verified := 0
|
||||
for key := range store.objects {
|
||||
if strings.HasPrefix(key, "staging/verified/") {
|
||||
verified++
|
||||
}
|
||||
}
|
||||
require.Equal(t, 1, verified, "loser must not delete the winner's verified source")
|
||||
}
|
||||
|
||||
func TestPresignHonoursAdmissionLimit(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()
|
||||
repo.EXPECT().CreatePresign(mock.Anything, mock.Anything, mock.Anything).
|
||||
Return(domain.Attachment{}, domain.ErrRateLimited).Once()
|
||||
|
||||
_, err := service.Presign(t.Context(), domain.PresignRequest{
|
||||
ChatID: uuid.New(), OwnerID: uuid.New(), Filename: "photo.png",
|
||||
ContentType: "image/png", SizeBytes: 10, SHA256: strings.Repeat("a", 64),
|
||||
})
|
||||
require.ErrorIs(t, err, domain.ErrRateLimited)
|
||||
}
|
||||
|
||||
func TestUploadRateLimitedByAtomicAdmissionRemovesStaging(t *testing.T) {
|
||||
repo := mocks.NewMockRepository(t)
|
||||
store := newFakeStore()
|
||||
service := attachment.NewService(repo, store, serviceConfig(), slog.Default())
|
||||
|
||||
repo.EXPECT().IsChatMember(mock.Anything, mock.Anything, mock.Anything).Return(true, nil).Once()
|
||||
repo.EXPECT().Admission(mock.Anything, mock.Anything).Return(0, 0, int64(0), nil).Once()
|
||||
repo.EXPECT().CreateQueued(mock.Anything, mock.Anything, mock.Anything, mock.Anything).
|
||||
Return(domain.Attachment{}, domain.ErrRateLimited).Once()
|
||||
|
||||
_, err := service.Upload(t.Context(), attachment.UploadInput{
|
||||
ChatID: uuid.New(), OwnerID: uuid.New(), Filename: "photo.png",
|
||||
DeclaredContentType: "image/png", Body: bytes.NewReader(pngBytes(t, 8, 8)),
|
||||
})
|
||||
require.ErrorIs(t, err, domain.ErrRateLimited)
|
||||
require.Empty(t, store.objects, "a rejected atomic admission must not leave staging")
|
||||
}
|
||||
|
||||
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,
|
||||
StagingKey: stagingKey, ContentType: "image/png",
|
||||
SizeBytes: int64(len(content)) + 1, SHA256: digest,
|
||||
Status: domain.AttachmentPending, PipelineVersion: 1,
|
||||
}
|
||||
|
||||
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,
|
||||
StagingKey: stagingKey, ContentType: "image/png",
|
||||
SizeBytes: int64(len(content)), SHA256: digest,
|
||||
Status: domain.AttachmentPending, PipelineVersion: 1,
|
||||
}
|
||||
|
||||
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,236 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"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)
|
||||
}
|
||||
|
||||
// SweepRepository is the storage port used by cleanup. It exposes only
|
||||
// read/delete projections; object bytes still live in S3.
|
||||
type SweepRepository interface {
|
||||
ListPendingPresign(ctx context.Context, createdBefore time.Time, limit int) ([]domain.Attachment, error)
|
||||
DeletePending(ctx context.Context, id uuid.UUID) error
|
||||
ListStaleStaging(ctx context.Context, readyBefore, failedBefore time.Time, limit int) ([]domain.StaleStaging, error)
|
||||
MarkStagingDeleted(ctx context.Context, attachmentID uuid.UUID, stagingKey string) error
|
||||
ListReferencedKeys(ctx context.Context, afterKey string, limit int) ([]string, error)
|
||||
}
|
||||
|
||||
type SweepStats struct {
|
||||
RowsDeleted int
|
||||
ObjectsDeleted int
|
||||
StagingCleared int
|
||||
}
|
||||
|
||||
type Sweeper struct {
|
||||
repo SweepRepository
|
||||
store objectstore.Store
|
||||
locker LockStore
|
||||
grace time.Duration
|
||||
orphanGrace time.Duration
|
||||
failedRetain time.Duration
|
||||
interval time.Duration
|
||||
log *slog.Logger
|
||||
}
|
||||
|
||||
func NewSweeper(
|
||||
repo SweepRepository,
|
||||
store objectstore.Store,
|
||||
locker LockStore,
|
||||
grace, orphanGrace, failedRetain, interval time.Duration,
|
||||
log *slog.Logger,
|
||||
) *Sweeper {
|
||||
if log == nil {
|
||||
log = slog.Default()
|
||||
}
|
||||
|
||||
return &Sweeper{
|
||||
repo: repo,
|
||||
store: store,
|
||||
locker: locker,
|
||||
grace: grace,
|
||||
orphanGrace: orphanGrace,
|
||||
failedRetain: failedRetain,
|
||||
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.RowsDeleted+stats.ObjectsDeleted+stats.StagingCleared > 0 {
|
||||
s.log.InfoContext(ctx, "attachment sweep finished",
|
||||
slog.Int("rows_deleted", stats.RowsDeleted),
|
||||
slog.Int("objects_deleted", stats.ObjectsDeleted),
|
||||
slog.Int("staging_cleared", stats.StagingCleared),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// SweepOnce applies explicit, status-aware retention rules. It never deletes
|
||||
// staging of a queued/processing attachment and aborts object collection if any
|
||||
// database page or S3 listing fails.
|
||||
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()
|
||||
|
||||
now := time.Now().UTC()
|
||||
var stats SweepStats
|
||||
|
||||
// Abandoned presign rows: no completion ever arrived.
|
||||
pending, err := s.repo.ListPendingPresign(ctx, now.Add(-s.grace), 100)
|
||||
if err != nil {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
for _, row := range pending {
|
||||
if row.StagingKey != "" {
|
||||
if s.deleteObject(ctx, row.StagingKey) {
|
||||
stats.ObjectsDeleted++
|
||||
}
|
||||
}
|
||||
|
||||
if err := s.repo.DeletePending(ctx, row.ID); err != nil && !errors.Is(err, domain.ErrNotFound) {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
stats.RowsDeleted++
|
||||
}
|
||||
|
||||
// Ready/failed rows keep their staging key until the object is safely
|
||||
// removed. Active queued/processing staging is never in this list.
|
||||
stale, err := s.repo.ListStaleStaging(
|
||||
ctx, now.Add(-s.orphanGrace), now.Add(-s.failedRetain), 100,
|
||||
)
|
||||
if err != nil {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
for _, row := range stale {
|
||||
if s.deleteObject(ctx, row.StagingKey) {
|
||||
stats.ObjectsDeleted++
|
||||
}
|
||||
|
||||
if err := s.repo.MarkStagingDeleted(ctx, row.AttachmentID, row.StagingKey); err != nil {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
stats.StagingCleared++
|
||||
}
|
||||
|
||||
referenced, err := s.referencedKeys(ctx)
|
||||
if err != nil {
|
||||
return stats, err
|
||||
}
|
||||
|
||||
// Orphans: objects no row references. Final objects and variants use the
|
||||
// normal grace; staging uses the longer orphan grace.
|
||||
for _, prefix := range []string{domain.AttachmentsPrefix, "staging/"} {
|
||||
before := now.Add(-s.grace)
|
||||
if prefix == "staging/" {
|
||||
before = now.Add(-s.orphanGrace)
|
||||
}
|
||||
|
||||
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{})
|
||||
after := ""
|
||||
|
||||
for {
|
||||
rows, err := s.repo.ListReferencedKeys(ctx, after, pageSize)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, key := range rows {
|
||||
keys[key] = struct{}{}
|
||||
}
|
||||
|
||||
if len(rows) < pageSize {
|
||||
return keys, nil
|
||||
}
|
||||
|
||||
after = rows[len(rows)-1]
|
||||
}
|
||||
}
|
||||
|
||||
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.Any("error", err),
|
||||
)
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
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 TestSweepAppliesStatusAwareRetention(t *testing.T) {
|
||||
repo := mocks.NewMockSweepRepository(t)
|
||||
locker := mocks.NewMockLockStore(t)
|
||||
store := newFakeStore()
|
||||
|
||||
stale := time.Now().UTC().Add(-2 * time.Hour)
|
||||
|
||||
presign := domain.Attachment{
|
||||
ID: uuid.New(), StagingKey: "staging/presign/chat/" + uuid.NewString(),
|
||||
Status: domain.AttachmentPending,
|
||||
}
|
||||
staleStaging := domain.StaleStaging{
|
||||
AttachmentID: uuid.New(), StagingKey: "staging/uploads/chat/ready", Status: domain.AttachmentReady,
|
||||
}
|
||||
activeStaging := "staging/uploads/chat/active"
|
||||
readyKey := "attachments/chat/ready/original"
|
||||
variantKey := "attachments/chat/ready/variants/v1/thumbnail.jpg"
|
||||
|
||||
for _, key := range []string{
|
||||
presign.StagingKey, staleStaging.StagingKey, activeStaging, readyKey, variantKey,
|
||||
"attachments/chat/orphan", "staging/orphan",
|
||||
} {
|
||||
store.objects[key] = storedObject{data: []byte("x"), lastModified: stale}
|
||||
}
|
||||
store.objects["staging/fresh"] = storedObject{data: []byte("x"), lastModified: time.Now().UTC()}
|
||||
|
||||
repo.EXPECT().ListPendingPresign(mock.Anything, mock.Anything, 100).
|
||||
Return([]domain.Attachment{presign}, nil).Once()
|
||||
repo.EXPECT().DeletePending(mock.Anything, presign.ID).Return(nil).Once()
|
||||
repo.EXPECT().ListStaleStaging(mock.Anything, mock.Anything, mock.Anything, 100).
|
||||
Return([]domain.StaleStaging{staleStaging}, nil).Once()
|
||||
repo.EXPECT().MarkStagingDeleted(mock.Anything, staleStaging.AttachmentID, staleStaging.StagingKey).
|
||||
Return(nil).Once()
|
||||
repo.EXPECT().ListReferencedKeys(mock.Anything, "", 1000).
|
||||
Return([]string{activeStaging, readyKey, variantKey}, nil).Once()
|
||||
locker.EXPECT().AcquireSweepLock(mock.Anything).Return(func() {}, true, nil).Once()
|
||||
|
||||
sweeper := attachment.NewSweeper(
|
||||
repo, store, locker,
|
||||
10*time.Minute, time.Hour, 24*time.Hour, time.Minute, slog.Default(),
|
||||
)
|
||||
|
||||
stats, err := sweeper.SweepOnce(t.Context())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, stats.RowsDeleted)
|
||||
require.Equal(t, 1, stats.StagingCleared)
|
||||
require.Equal(t, 4, stats.ObjectsDeleted)
|
||||
|
||||
require.NotContains(t, store.objects, presign.StagingKey)
|
||||
require.NotContains(t, store.objects, staleStaging.StagingKey)
|
||||
require.NotContains(t, store.objects, "attachments/chat/orphan")
|
||||
require.NotContains(t, store.objects, "staging/orphan")
|
||||
require.Contains(t, store.objects, activeStaging)
|
||||
require.Contains(t, store.objects, readyKey)
|
||||
require.Contains(t, store.objects, variantKey)
|
||||
require.Contains(t, store.objects, "staging/fresh")
|
||||
}
|
||||
|
||||
func TestSweepSkipsWhenAnotherReplicaHoldsTheLock(t *testing.T) {
|
||||
repo := mocks.NewMockSweepRepository(t)
|
||||
locker := mocks.NewMockLockStore(t)
|
||||
sweeper := attachment.NewSweeper(
|
||||
repo, newFakeStore(), locker,
|
||||
time.Minute, time.Hour, 24*time.Hour, time.Minute, 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 TestSweepAbortsObjectCollectionWhenKeysCannotBeRead(t *testing.T) {
|
||||
repo := mocks.NewMockSweepRepository(t)
|
||||
locker := mocks.NewMockLockStore(t)
|
||||
store := newFakeStore()
|
||||
|
||||
orphan := "attachments/chat/orphan"
|
||||
store.objects[orphan] = storedObject{data: []byte("x"), lastModified: time.Now().UTC().Add(-2 * time.Hour)}
|
||||
|
||||
repo.EXPECT().ListPendingPresign(mock.Anything, mock.Anything, 100).Return(nil, nil).Once()
|
||||
repo.EXPECT().ListStaleStaging(mock.Anything, mock.Anything, mock.Anything, 100).Return(nil, nil).Once()
|
||||
repo.EXPECT().ListReferencedKeys(mock.Anything, "", 1000).
|
||||
Return(nil, context.DeadlineExceeded).Once()
|
||||
locker.EXPECT().AcquireSweepLock(mock.Anything).Return(func() {}, true, nil).Once()
|
||||
|
||||
sweeper := attachment.NewSweeper(
|
||||
repo, store, locker,
|
||||
time.Minute, time.Hour, 24*time.Hour, time.Minute, slog.Default(),
|
||||
)
|
||||
|
||||
_, err := sweeper.SweepOnce(t.Context())
|
||||
require.ErrorIs(t, err, context.DeadlineExceeded)
|
||||
require.Contains(t, store.objects, orphan, "fail-closed: no deletion when the key set is unknown")
|
||||
}
|
||||
@@ -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,343 @@
|
||||
// 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
|
||||
}
|
||||
|
||||
// Replay provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) Replay(ctx context.Context, draft domain.MessageDraft) (domain.Message, bool, error) {
|
||||
ret := _mock.Called(ctx, draft)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for Replay")
|
||||
}
|
||||
|
||||
var r0 domain.Message
|
||||
var r1 bool
|
||||
var r2 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, domain.MessageDraft) (domain.Message, bool, 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) bool); ok {
|
||||
r1 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r1 = ret.Get(1).(bool)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(2).(func(context.Context, domain.MessageDraft) error); ok {
|
||||
r2 = returnFunc(ctx, draft)
|
||||
} else {
|
||||
r2 = ret.Error(2)
|
||||
}
|
||||
return r0, r1, r2
|
||||
}
|
||||
|
||||
// MockRepository_Replay_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'Replay'
|
||||
type MockRepository_Replay_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// Replay is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - draft domain.MessageDraft
|
||||
func (_e *MockRepository_Expecter) Replay(ctx any, draft any) *MockRepository_Replay_Call {
|
||||
return &MockRepository_Replay_Call{Call: _e.mock.On("Replay", ctx, draft)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Replay_Call) Run(run func(ctx context.Context, draft domain.MessageDraft)) *MockRepository_Replay_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_Replay_Call) Return(message domain.Message, b bool, err error) *MockRepository_Replay_Call {
|
||||
_c.Call.Return(message, b, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_Replay_Call) RunAndReturn(run func(ctx context.Context, draft domain.MessageDraft) (domain.Message, bool, error)) *MockRepository_Replay_Call {
|
||||
_c.Call.Return(run)
|
||||
return _c
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
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)
|
||||
// Replay returns the stored message for a live Idempotency-Key. It must be
|
||||
// checked before attachment-state validation: a message that was accepted
|
||||
// while the attachment was queued keeps replaying as 201 even after the
|
||||
// attachment later fails.
|
||||
Replay(ctx context.Context, draft domain.MessageDraft) (domain.Message, 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)
|
||||
}
|
||||
|
||||
replayed, found, err := s.messages.Replay(ctx, draft)
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("replay message: %w", err)
|
||||
}
|
||||
|
||||
if found {
|
||||
return replayed, nil
|
||||
}
|
||||
|
||||
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 {
|
||||
switch state.Status {
|
||||
case domain.AttachmentQueued, domain.AttachmentProcessing, domain.AttachmentReady:
|
||||
// Accepted work is linkable by contract.
|
||||
default:
|
||||
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,261 @@
|
||||
package message_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/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)
|
||||
s.messages.EXPECT().Replay(mock.Anything, mock.Anything).
|
||||
Return(domain.Message{}, false, nil).Maybe()
|
||||
}
|
||||
|
||||
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) TestSendReplaysBeforeAttachmentValidation() {
|
||||
draft := s.draft()
|
||||
draft.AttachmentIDs = []uuid.UUID{uuid.New()}
|
||||
stored := domain.Message{
|
||||
ID: uuid.New(), ChatID: draft.ChatID, SenderID: draft.SenderID,
|
||||
Text: draft.Text, AttachmentIDs: draft.AttachmentIDs, CreatedAt: s.now,
|
||||
}
|
||||
|
||||
// The stored key is authoritative even if the attachment has since failed;
|
||||
// ListStates must not be consulted on a replay.
|
||||
s.messages.ExpectedCalls = nil
|
||||
s.messages.EXPECT().IsChatMember(s.T().Context(), draft.ChatID, draft.SenderID).Return(true, nil).Once()
|
||||
s.messages.EXPECT().Replay(s.T().Context(), draft).Return(stored, true, nil).Once()
|
||||
|
||||
got, err := s.service.Send(s.T().Context(), draft)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(stored, got)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestSendRejectsFailedAttachment() {
|
||||
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.AttachmentFailed}}, nil).
|
||||
Once()
|
||||
|
||||
_, err := s.service.Send(s.T().Context(), draft)
|
||||
s.Require().ErrorIs(err, domain.ErrConflict)
|
||||
}
|
||||
|
||||
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,388 @@
|
||||
// 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
|
||||
}
|
||||
|
||||
// UpdatePasswordHash provides a mock function for the type MockRepository
|
||||
func (_mock *MockRepository) UpdatePasswordHash(ctx context.Context, userID uuid.UUID, oldHash string, newHash string) (bool, error) {
|
||||
ret := _mock.Called(ctx, userID, oldHash, newHash)
|
||||
|
||||
if len(ret) == 0 {
|
||||
panic("no return value specified for UpdatePasswordHash")
|
||||
}
|
||||
|
||||
var r0 bool
|
||||
var r1 error
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, string, string) (bool, error)); ok {
|
||||
return returnFunc(ctx, userID, oldHash, newHash)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(0).(func(context.Context, uuid.UUID, string, string) bool); ok {
|
||||
r0 = returnFunc(ctx, userID, oldHash, newHash)
|
||||
} else {
|
||||
r0 = ret.Get(0).(bool)
|
||||
}
|
||||
if returnFunc, ok := ret.Get(1).(func(context.Context, uuid.UUID, string, string) error); ok {
|
||||
r1 = returnFunc(ctx, userID, oldHash, newHash)
|
||||
} else {
|
||||
r1 = ret.Error(1)
|
||||
}
|
||||
return r0, r1
|
||||
}
|
||||
|
||||
// MockRepository_UpdatePasswordHash_Call is a *mock.Call that shadows Run/Return methods with type explicit version for method 'UpdatePasswordHash'
|
||||
type MockRepository_UpdatePasswordHash_Call struct {
|
||||
*mock.Call
|
||||
}
|
||||
|
||||
// UpdatePasswordHash is a helper method to define mock.On call
|
||||
// - ctx context.Context
|
||||
// - userID uuid.UUID
|
||||
// - oldHash string
|
||||
// - newHash string
|
||||
func (_e *MockRepository_Expecter) UpdatePasswordHash(ctx any, userID any, oldHash any, newHash any) *MockRepository_UpdatePasswordHash_Call {
|
||||
return &MockRepository_UpdatePasswordHash_Call{Call: _e.mock.On("UpdatePasswordHash", ctx, userID, oldHash, newHash)}
|
||||
}
|
||||
|
||||
func (_c *MockRepository_UpdatePasswordHash_Call) Run(run func(ctx context.Context, userID uuid.UUID, oldHash string, newHash string)) *MockRepository_UpdatePasswordHash_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)
|
||||
}
|
||||
var arg3 string
|
||||
if args[3] != nil {
|
||||
arg3 = args[3].(string)
|
||||
}
|
||||
run(
|
||||
arg0,
|
||||
arg1,
|
||||
arg2,
|
||||
arg3,
|
||||
)
|
||||
})
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_UpdatePasswordHash_Call) Return(b bool, err error) *MockRepository_UpdatePasswordHash_Call {
|
||||
_c.Call.Return(b, err)
|
||||
return _c
|
||||
}
|
||||
|
||||
func (_c *MockRepository_UpdatePasswordHash_Call) RunAndReturn(run func(ctx context.Context, userID uuid.UUID, oldHash string, newHash string) (bool, error)) *MockRepository_UpdatePasswordHash_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,122 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"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)
|
||||
UpdatePasswordHash(ctx context.Context, userID uuid.UUID, oldHash, newHash string) (bool, 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 {
|
||||
if errors.Is(err, domain.ErrUnauthenticated) {
|
||||
// Spend the same derivation budget as a real credential check so
|
||||
// an unknown username does not answer measurably faster.
|
||||
if dummyErr := password.DummyVerify(plain); dummyErr != nil {
|
||||
return domain.User{}, fmt.Errorf("verify password: %w", dummyErr)
|
||||
}
|
||||
}
|
||||
return domain.User{}, fmt.Errorf("authenticate: %w", err)
|
||||
}
|
||||
|
||||
verified, err := password.Verify(plain, credentials.PasswordHash)
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("verify password: %w", err)
|
||||
}
|
||||
if !verified.Match {
|
||||
return domain.User{}, fmt.Errorf("authenticate: %w", domain.ErrUnauthenticated)
|
||||
}
|
||||
if verified.NeedsRehash {
|
||||
// Optional upgrade: a busy derivation or transient write error must not
|
||||
// turn an already verified login into a failure.
|
||||
s.rehash(ctx, credentials.User.ID, credentials.PasswordHash, plain)
|
||||
}
|
||||
|
||||
return credentials.User, nil
|
||||
}
|
||||
|
||||
func (s *Service) rehash(ctx context.Context, userID uuid.UUID, oldHash, plain string) {
|
||||
hash, err := password.Hash(plain)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
// A concurrent upgrade wins the CAS; both outcomes are acceptable.
|
||||
_, _ = s.sessions.UpdatePasswordHash(ctx, userID, oldHash, hash)
|
||||
}
|
||||
|
||||
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,203 @@
|
||||
package session_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/mock"
|
||||
"github.com/stretchr/testify/suite"
|
||||
"golang.org/x/crypto/argon2"
|
||||
|
||||
"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)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestAuthenticateUpgradesHashesWithCAS() {
|
||||
plain := "secret-password-123"
|
||||
for _, legacy := range []bool{false, true} {
|
||||
oldHash := obsoleteHash(plain, legacy)
|
||||
for _, updated := range []bool{true, false} {
|
||||
s.sessions.EXPECT().Credentials(mock.Anything, "alice").
|
||||
Return(domain.UserCredentials{User: s.user, PasswordHash: oldHash}, nil).Once()
|
||||
s.sessions.On("UpdatePasswordHash", mock.Anything, s.user.ID, oldHash,
|
||||
mock.MatchedBy(func(hash string) bool {
|
||||
verified, err := password.Verify(plain, hash)
|
||||
return err == nil && verified.Match && !verified.NeedsRehash
|
||||
})).Return(updated, nil).Once()
|
||||
|
||||
got, err := s.service.Authenticate(s.T().Context(), "alice", plain)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(s.user, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestWrongLegacyPasswordDoesNotUpgrade() {
|
||||
oldHash := obsoleteHash("secret-password-123", true)
|
||||
s.sessions.EXPECT().Credentials(mock.Anything, "alice").
|
||||
Return(domain.UserCredentials{User: s.user, PasswordHash: oldHash}, nil).Once()
|
||||
|
||||
_, err := s.service.Authenticate(s.T().Context(), "alice", "wrong-password-value")
|
||||
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
||||
s.sessions.AssertNotCalled(s.T(), "UpdatePasswordHash", mock.Anything, mock.Anything, mock.Anything, mock.Anything)
|
||||
}
|
||||
|
||||
func (s *ServiceSuite) TestPasswordUpgradeFailureDoesNotBlockLogin() {
|
||||
oldHash := obsoleteHash("secret-password-123", false)
|
||||
s.sessions.EXPECT().Credentials(mock.Anything, "alice").
|
||||
Return(domain.UserCredentials{User: s.user, PasswordHash: oldHash}, nil).Once()
|
||||
s.sessions.On("UpdatePasswordHash", mock.Anything, s.user.ID, oldHash, mock.Anything).
|
||||
Return(false, domain.ErrUnavailable).Once()
|
||||
|
||||
got, err := s.service.Authenticate(s.T().Context(), "alice", "secret-password-123")
|
||||
s.Require().NoError(err)
|
||||
s.Equal(s.user, got)
|
||||
}
|
||||
|
||||
func obsoleteHash(plain string, legacy bool) string {
|
||||
var salt [16]byte
|
||||
memory, threads := uint32(32), uint8(1)
|
||||
prefix := "$argon2id$v=19$m=32,t=1,p=1$"
|
||||
if legacy {
|
||||
memory, threads = 64*1024, 4
|
||||
prefix = "argon2id$"
|
||||
}
|
||||
hash := argon2.IDKey([]byte(plain), salt[:], 1, memory, threads, 32)
|
||||
return prefix + base64.RawStdEncoding.EncodeToString(salt[:]) + "$" +
|
||||
base64.RawStdEncoding.EncodeToString(hash)
|
||||
}
|
||||
@@ -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,162 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"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),
|
||||
Username: envOr("TEST_REDIS_USERNAME", "operator"),
|
||||
Password: os.Getenv("TEST_REDIS_PASSWORD"),
|
||||
DB: envInt("TEST_REDIS_DB", 7),
|
||||
DialTimeout: 5 * time.Second,
|
||||
ReadTimeout: 3 * time.Second,
|
||||
WriteTimeout: 3 * time.Second,
|
||||
PoolSize: 5,
|
||||
}
|
||||
require.NotZero(t, redisConfig.DB, "cache experiment must not use production redis db 0")
|
||||
redisCache, err := cache.NewRedis(ctx, 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,195 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"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),
|
||||
Username: envOr("TEST_REDIS_USERNAME", "operator"),
|
||||
Password: os.Getenv("TEST_REDIS_PASSWORD"),
|
||||
DB: envInt("TEST_REDIS_DB", 7),
|
||||
DialTimeout: 5 * time.Second,
|
||||
ReadTimeout: 3 * time.Second,
|
||||
WriteTimeout: 3 * time.Second,
|
||||
PoolSize: 10,
|
||||
}
|
||||
require.NotZero(t, redisConfig.DB, "cache experiment must not use production redis db 0")
|
||||
redisCache, err := cache.NewRedis(ctx, 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,111 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
"mtusi-messenger/internal/platform/tlsconfig"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultHost = "localhost"
|
||||
defaultPort = 5432
|
||||
defaultDatabase = "messenger"
|
||||
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 strings.ContainsAny(cfg.Host, "/, \t\r\n") {
|
||||
return cfg, errors.New("postgres: host must be a single tcp hostname or ip address")
|
||||
}
|
||||
if cfg.Port == 0 {
|
||||
cfg.Port = defaultPort
|
||||
}
|
||||
|
||||
if cfg.Database == "" {
|
||||
cfg.Database = defaultDatabase
|
||||
}
|
||||
|
||||
if cfg.User == "" || cfg.Password == "" {
|
||||
return cfg, errors.New("postgres: user and password are required")
|
||||
}
|
||||
if cfg.SSLMode == "" {
|
||||
cfg.SSLMode = "verify-full"
|
||||
}
|
||||
if cfg.SSLMode != "verify-full" {
|
||||
return cfg, errors.New("postgres: ssl_mode must be verify-full")
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
// PoolConfig is shared by application pools and operator migration connections.
|
||||
// Every new connection verifies the hostname, current trust bundle and CRLs.
|
||||
func PoolConfig(cfg config.Postgres) (*pgxpool.Config, error) {
|
||||
cfg, err := normalize(cfg)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return poolConfig(cfg)
|
||||
}
|
||||
|
||||
func poolConfig(cfg config.Postgres) (*pgxpool.Config, error) {
|
||||
clientTLS, err := tlsconfig.NewClientFromEnv(cfg.Host)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
poolCfg, err := pgxpool.ParseConfig(cfg.DSN())
|
||||
if err != nil {
|
||||
// pgx parse errors include the DSN, which contains a password.
|
||||
return nil, errors.New("postgres: invalid connection configuration")
|
||||
}
|
||||
poolCfg.ConnConfig.TLSConfig = clientTLS
|
||||
poolCfg.ConnConfig.Fallbacks = nil
|
||||
poolCfg.MaxConns = cfg.MaxConns
|
||||
poolCfg.MinConns = cfg.MinConns
|
||||
poolCfg.MaxConnLifetime = cfg.MaxConnLifetime
|
||||
poolCfg.MaxConnIdleTime = cfg.MaxConnIdleTime
|
||||
poolCfg.ConnConfig.ConnectTimeout = cfg.ConnectTimeout
|
||||
return poolCfg, nil
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/config"
|
||||
)
|
||||
|
||||
func TestNormalizeKeepsProvidedValues(t *testing.T) {
|
||||
cfg, err := normalize(config.Postgres{
|
||||
Host: "db",
|
||||
Port: 6543,
|
||||
Database: "app",
|
||||
User: "app",
|
||||
Password: "database-secret",
|
||||
SSLMode: "verify-full",
|
||||
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, "verify-full", cfg.SSLMode)
|
||||
require.Equal(t, int32(7), cfg.MaxConns)
|
||||
}
|
||||
|
||||
func TestNormalizeRejectsMinGreaterThanMax(t *testing.T) {
|
||||
_, err := normalize(config.Postgres{User: "app", Password: "secret", MinConns: 5, MaxConns: 2})
|
||||
require.ErrorContains(t, err, "min_conns must not exceed max_conns")
|
||||
}
|
||||
|
||||
func TestNormalizeRequiresCredentials(t *testing.T) {
|
||||
for _, cfg := range []config.Postgres{{User: "app"}, {Password: "secret"}} {
|
||||
_, err := normalize(cfg)
|
||||
require.ErrorContains(t, err, "user and password are required")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeRejectsUnverifiedTLS(t *testing.T) {
|
||||
for _, mode := range []string{"disable", "allow", "prefer", "require", "verify-ca"} {
|
||||
_, err := normalize(config.Postgres{User: "app", Password: "secret", SSLMode: mode})
|
||||
require.ErrorContains(t, err, "ssl_mode must be verify-full")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeRejectsNonTCPHost(t *testing.T) {
|
||||
for _, host := range []string{"/var/run/postgresql", "db,other", "db\n"} {
|
||||
_, err := normalize(config.Postgres{Host: host, User: "app", Password: "secret"})
|
||||
require.ErrorContains(t, err, "single tcp hostname")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
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 pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) {
|
||||
switch pgErr.Code {
|
||||
// Class 08 — connection exception. 57P01/57P02/57P03 are the
|
||||
// server-side shutdown/startup states; 53300 is "too many
|
||||
// connections". All are dependency outages, not caller errors.
|
||||
case "57P01", "57P02", "57P03", "53300":
|
||||
return true
|
||||
}
|
||||
if len(pgErr.Code) >= 2 && pgErr.Code[:2] == "08" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
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,32 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
)
|
||||
|
||||
func TestIsUnavailablePostgresConnectionClasses(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
for _, code := range []string{"08000", "08006", "57P01", "57P02", "57P03", "53300"} {
|
||||
if !isUnavailable(&pgconn.PgError{Code: code}) {
|
||||
t.Errorf("code %s was not classified as unavailable", code)
|
||||
}
|
||||
}
|
||||
if isUnavailable(&pgconn.PgError{Code: "23505"}) {
|
||||
t.Error("unique violation was classified as unavailable")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMapErrorConnectionClassIsUnavailable(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
err := mapError(&pgconn.PgError{Code: "57P03"})
|
||||
if !errors.Is(err, domain.ErrUnavailable) {
|
||||
t.Fatalf("mapError = %v, want ErrUnavailable", 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,60 @@
|
||||
// Code generated by sqlc. DO NOT EDIT.
|
||||
// versions:
|
||||
// sqlc v1.31.1
|
||||
// source: attachments.sql
|
||||
|
||||
package sqlcgen
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"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 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
|
||||
}
|
||||
@@ -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,157 @@
|
||||
// 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
|
||||
}
|
||||
|
||||
const lookupMessageIdempotency = `-- name: LookupMessageIdempotency :one
|
||||
SELECT message_id, request_hash
|
||||
FROM message_idempotency
|
||||
WHERE actor_id = $1
|
||||
AND chat_id = $2
|
||||
AND key = $3
|
||||
AND expires_at > now()
|
||||
`
|
||||
|
||||
type LookupMessageIdempotencyParams struct {
|
||||
ActorID uuid.UUID
|
||||
ChatID uuid.UUID
|
||||
Key string
|
||||
}
|
||||
|
||||
type LookupMessageIdempotencyRow struct {
|
||||
MessageID pgtype.UUID
|
||||
RequestHash []byte
|
||||
}
|
||||
|
||||
// Read-only replay lookup used before attachment-state validation. A live key
|
||||
// returns the stored message; an expired key is ignored and may be claimed.
|
||||
func (q *Queries) LookupMessageIdempotency(ctx context.Context, arg LookupMessageIdempotencyParams) (LookupMessageIdempotencyRow, error) {
|
||||
row := q.db.QueryRow(ctx, lookupMessageIdempotency, arg.ActorID, arg.ChatID, arg.Key)
|
||||
var i LookupMessageIdempotencyRow
|
||||
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,152 @@
|
||||
// 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
|
||||
PipelineVersion int32
|
||||
StagingKey pgtype.Text
|
||||
ReadyAt pgtype.Timestamptz
|
||||
FailedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AttachmentJob struct {
|
||||
JobID uuid.UUID
|
||||
AttachmentID uuid.UUID
|
||||
PipelineVersion int32
|
||||
SourceKey string
|
||||
Attempt int32
|
||||
MaxAttempts int32
|
||||
Status string
|
||||
AvailableAt time.Time
|
||||
LeaseOwner pgtype.Text
|
||||
LeaseExpiresAt pgtype.Timestamptz
|
||||
LastErrorCode pgtype.Text
|
||||
ReplayCount int32
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
CompletedAt pgtype.Timestamptz
|
||||
Traceparent string
|
||||
Tracestate string
|
||||
TtrMissedAt pgtype.Timestamptz
|
||||
}
|
||||
|
||||
type AttachmentJobEvent struct {
|
||||
ID int64
|
||||
JobID uuid.UUID
|
||||
Event string
|
||||
Attempt pgtype.Int4
|
||||
Detail []byte
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
type AttachmentVariant struct {
|
||||
AttachmentID uuid.UUID
|
||||
PipelineVersion int32
|
||||
Name string
|
||||
ContentType string
|
||||
SizeBytes int64
|
||||
Width int32
|
||||
Height int32
|
||||
Sha256 string
|
||||
ObjectKey string
|
||||
CreatedAt 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 LoginLimit struct {
|
||||
KeyHash string
|
||||
Count int64
|
||||
ExpiresAt 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 OutboxMessage struct {
|
||||
ID int64
|
||||
JobID uuid.UUID
|
||||
Attempt int32
|
||||
Kind string
|
||||
RoutingKey string
|
||||
Payload []byte
|
||||
AvailableAt time.Time
|
||||
PublishedAt pgtype.Timestamptz
|
||||
ClaimedBy pgtype.Text
|
||||
ClaimedUntil pgtype.Timestamptz
|
||||
PublishAttempts int32
|
||||
LastError pgtype.Text
|
||||
CreatedAt 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,104 @@
|
||||
// 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
|
||||
}
|
||||
|
||||
const updatePasswordHash = `-- name: UpdatePasswordHash :execrows
|
||||
UPDATE users
|
||||
SET password_hash = $1
|
||||
WHERE id = $2
|
||||
AND password_hash = $3
|
||||
`
|
||||
|
||||
type UpdatePasswordHashParams struct {
|
||||
NewHash string
|
||||
UserID uuid.UUID
|
||||
OldHash string
|
||||
}
|
||||
|
||||
func (q *Queries) UpdatePasswordHash(ctx context.Context, arg UpdatePasswordHashParams) (int64, error) {
|
||||
result, err := q.db.Exec(ctx, updatePasswordHash, arg.NewHash, arg.UserID, arg.OldHash)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return result.RowsAffected(), nil
|
||||
}
|
||||
@@ -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,322 @@
|
||||
//go:build integration
|
||||
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
"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"
|
||||
)
|
||||
|
||||
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", "lab_operator"),
|
||||
Password: os.Getenv("TEST_POSTGRES_PASSWORD"),
|
||||
SSLMode: envOr("TEST_POSTGRES_SSL_MODE", "verify-full"),
|
||||
MaxConns: 5,
|
||||
MinConns: 1,
|
||||
MaxConnLifetime: time.Hour,
|
||||
MaxConnIdleTime: 30 * time.Minute,
|
||||
ConnectTimeout: 5 * time.Second,
|
||||
QueryTimeout: 5 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
func poolConfigFor(database string) (*pgxpool.Config, error) {
|
||||
cfg := testConfig()
|
||||
cfg.Database = database
|
||||
|
||||
return postgres.PoolConfig(cfg)
|
||||
}
|
||||
|
||||
func configureOperatorTLS() error {
|
||||
identity, err := filepath.Abs("../../../secrets/lab7/pki/operator/current")
|
||||
if err != nil {
|
||||
return fmt.Errorf("resolve operator identity: %w", err)
|
||||
}
|
||||
for key, filename := range map[string]string{
|
||||
"TLS_CA_FILE": "ca.crt", "TLS_CERT_FILE": "tls.crt",
|
||||
"TLS_KEY_FILE": "tls.key", "TLS_CRL_FILE": "ca.crl",
|
||||
} {
|
||||
if os.Getenv(key) == "" {
|
||||
if err := os.Setenv(key, filepath.Join(identity, filename)); err != nil {
|
||||
return fmt.Errorf("set operator tls path: %w", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
if os.Getenv("TLS_VERSION_FILE") == "" {
|
||||
if err := os.Setenv("TLS_VERSION_FILE", filepath.Join(filepath.Dir(identity), "current-version")); err != nil {
|
||||
return fmt.Errorf("set operator tls selector: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func TestMain(m *testing.M) {
|
||||
ctx := context.Background()
|
||||
|
||||
if err := configureOperatorTLS(); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "operator tls:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
poolCfg, err := poolConfigFor(testConfig().Database)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "operator pool configuration:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
adminPool, err = pgxpool.NewWithConfig(ctx, poolCfg)
|
||||
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
|
||||
}
|
||||
|
||||
poolCfg, err := poolConfigFor(templateDB)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
db := stdlib.OpenDB(*poolCfg.ConnConfig)
|
||||
|
||||
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)
|
||||
}))
|
||||
|
||||
poolCfg, err := poolConfigFor(s.db)
|
||||
s.Require().NoError(err)
|
||||
s.pool, err = pgxpool.NewWithConfig(ctx, poolCfg)
|
||||
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,361 @@
|
||||
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
|
||||
}
|
||||
|
||||
// Replay returns the stored message for a live Idempotency-Key without
|
||||
// touching attachment state. The caller uses it before attachment validation so
|
||||
// a replay stays 201 even if a linked attachment later failed.
|
||||
func (r *MessageRepository) Replay(
|
||||
ctx context.Context,
|
||||
draft domain.MessageDraft,
|
||||
) (domain.Message, bool, error) {
|
||||
var (
|
||||
replayed domain.Message
|
||||
found bool
|
||||
)
|
||||
|
||||
err := r.store.RunInTx(ctx, func(queries *sqlcgen.Queries) error {
|
||||
stored, err := queries.LookupMessageIdempotency(ctx, sqlcgen.LookupMessageIdempotencyParams{
|
||||
ActorID: draft.SenderID,
|
||||
ChatID: draft.ChatID,
|
||||
Key: draft.Idempotency.Key,
|
||||
})
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return mapError(err)
|
||||
}
|
||||
|
||||
if !bytes.Equal(stored.RequestHash, draft.Idempotency.RequestHash[:]) {
|
||||
return domain.ErrIdempotency
|
||||
}
|
||||
|
||||
if !stored.MessageID.Valid {
|
||||
return errors.New("idempotency record without a message")
|
||||
}
|
||||
|
||||
row, err := queries.GetMessageByID(ctx, uuid.UUID(stored.MessageID.Bytes))
|
||||
if err != nil {
|
||||
return 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 err
|
||||
}
|
||||
|
||||
found = true
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Message{}, false, fmt.Errorf("replay idempotent message: %w", mapError(err))
|
||||
}
|
||||
|
||||
return replayed, found, 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,150 @@
|
||||
-- +goose Up
|
||||
-- Lab5 async attachment pipeline: durable intent (jobs + transactional outbox),
|
||||
-- per-version results (variants), and operator audit (events).
|
||||
|
||||
ALTER TABLE attachments DROP CONSTRAINT attachments_status_check;
|
||||
ALTER TABLE attachments ADD CONSTRAINT attachments_status_check CHECK (
|
||||
status IN ('pending', 'queued', 'processing', 'ready', 'failed')
|
||||
) NOT VALID;
|
||||
ALTER TABLE attachments VALIDATE CONSTRAINT attachments_status_check;
|
||||
|
||||
ALTER TABLE attachments DROP CONSTRAINT attachments_error_consistency;
|
||||
ALTER TABLE attachments ADD CONSTRAINT attachments_error_consistency CHECK (
|
||||
(status IN ('ready', 'queued', 'processing') AND error_code IS NULL) OR
|
||||
(status = 'failed' AND error_code IS NOT NULL) OR
|
||||
status = 'pending'
|
||||
) NOT VALID;
|
||||
ALTER TABLE attachments VALIDATE CONSTRAINT attachments_error_consistency;
|
||||
|
||||
ALTER TABLE attachments
|
||||
ADD COLUMN pipeline_version integer NOT NULL DEFAULT 1
|
||||
CHECK (pipeline_version >= 1),
|
||||
ADD COLUMN staging_key text,
|
||||
ADD COLUMN ready_at timestamptz,
|
||||
ADD COLUMN failed_at timestamptz;
|
||||
|
||||
CREATE UNIQUE INDEX attachments_staging_key_key
|
||||
ON attachments (staging_key)
|
||||
WHERE staging_key IS NOT NULL;
|
||||
|
||||
CREATE INDEX attachments_pipeline_status_idx
|
||||
ON attachments (status, pipeline_version);
|
||||
|
||||
-- One logical job per (attachment, pipeline version). job_id is stable across
|
||||
-- redelivery; attempt is the managed attempt number (1-based).
|
||||
CREATE TABLE attachment_jobs (
|
||||
job_id uuid PRIMARY KEY,
|
||||
attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE CASCADE,
|
||||
pipeline_version integer NOT NULL CHECK (pipeline_version >= 1),
|
||||
source_key text NOT NULL,
|
||||
attempt integer NOT NULL DEFAULT 1 CHECK (attempt >= 1),
|
||||
max_attempts integer NOT NULL CHECK (max_attempts BETWEEN 1 AND 100),
|
||||
status text NOT NULL CHECK (
|
||||
status IN ('queued', 'processing', 'ready', 'failed', 'superseded')
|
||||
),
|
||||
available_at timestamptz NOT NULL DEFAULT now(),
|
||||
lease_owner text,
|
||||
lease_expires_at timestamptz,
|
||||
last_error_code text,
|
||||
replay_count integer NOT NULL DEFAULT 0,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
completed_at timestamptz,
|
||||
|
||||
CONSTRAINT attachment_jobs_attachment_version_key UNIQUE (attachment_id, pipeline_version),
|
||||
CONSTRAINT attachment_jobs_lease_consistency CHECK (
|
||||
(status = 'processing' AND lease_owner IS NOT NULL AND lease_expires_at IS NOT NULL) OR
|
||||
(status <> 'processing')
|
||||
)
|
||||
);
|
||||
|
||||
CREATE INDEX attachment_jobs_due_idx
|
||||
ON attachment_jobs (status, available_at);
|
||||
|
||||
CREATE INDEX attachment_jobs_lease_idx
|
||||
ON attachment_jobs (status, lease_expires_at);
|
||||
|
||||
-- Delivery ledger. available_at is the only retry scheduler; RabbitMQ is the
|
||||
-- durable transport. No UNIQUE(job_id, attempt): a graceful shutdown may
|
||||
-- re-publish the same attempt, and duplicates are harmless (worker CAS).
|
||||
CREATE TABLE outbox_messages (
|
||||
id bigserial PRIMARY KEY,
|
||||
job_id uuid NOT NULL REFERENCES attachment_jobs (job_id) ON DELETE CASCADE,
|
||||
attempt integer NOT NULL CHECK (attempt >= 1),
|
||||
kind text NOT NULL DEFAULT 'publish',
|
||||
routing_key text NOT NULL,
|
||||
payload jsonb NOT NULL,
|
||||
available_at timestamptz NOT NULL DEFAULT now(),
|
||||
published_at timestamptz,
|
||||
claimed_by text,
|
||||
claimed_until timestamptz,
|
||||
publish_attempts integer NOT NULL DEFAULT 0,
|
||||
last_error text,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX outbox_due_idx
|
||||
ON outbox_messages (available_at, id)
|
||||
WHERE published_at IS NULL;
|
||||
|
||||
CREATE INDEX outbox_claim_expiry_idx
|
||||
ON outbox_messages (claimed_until)
|
||||
WHERE published_at IS NULL AND claimed_by IS NOT NULL;
|
||||
|
||||
-- Effect key (attachment_id, pipeline_version, name). The primary key is the
|
||||
-- idempotency boundary for redelivery and versioned pipelines.
|
||||
CREATE TABLE attachment_variants (
|
||||
attachment_id uuid NOT NULL REFERENCES attachments (id) ON DELETE CASCADE,
|
||||
pipeline_version integer NOT NULL CHECK (pipeline_version >= 1),
|
||||
name text NOT NULL CHECK (name IN ('thumbnail', 'crop', 'optimized')),
|
||||
content_type text NOT NULL CHECK (
|
||||
content_type IN ('image/jpeg', 'image/png', 'image/webp')
|
||||
),
|
||||
size_bytes bigint NOT NULL CHECK (size_bytes > 0),
|
||||
width integer NOT NULL CHECK (width > 0),
|
||||
height integer NOT NULL CHECK (height > 0),
|
||||
sha256 text NOT NULL CHECK (sha256 ~ '^[0-9a-f]{64}$'),
|
||||
object_key text NOT NULL UNIQUE,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
|
||||
PRIMARY KEY (attachment_id, pipeline_version, name)
|
||||
);
|
||||
|
||||
CREATE TABLE attachment_job_events (
|
||||
id bigserial PRIMARY KEY,
|
||||
job_id uuid NOT NULL REFERENCES attachment_jobs (job_id) ON DELETE CASCADE,
|
||||
event text NOT NULL,
|
||||
attempt integer,
|
||||
detail jsonb,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX attachment_job_events_job_idx
|
||||
ON attachment_job_events (job_id, created_at);
|
||||
|
||||
-- +goose Down
|
||||
DROP TABLE attachment_job_events;
|
||||
DROP TABLE attachment_variants;
|
||||
DROP TABLE outbox_messages;
|
||||
DROP TABLE attachment_jobs;
|
||||
|
||||
DROP INDEX attachments_pipeline_status_idx;
|
||||
DROP INDEX attachments_staging_key_key;
|
||||
|
||||
ALTER TABLE attachments
|
||||
DROP COLUMN failed_at,
|
||||
DROP COLUMN ready_at,
|
||||
DROP COLUMN staging_key,
|
||||
DROP COLUMN pipeline_version;
|
||||
|
||||
ALTER TABLE attachments DROP CONSTRAINT attachments_error_consistency;
|
||||
ALTER TABLE attachments ADD CONSTRAINT attachments_error_consistency CHECK (
|
||||
(status = 'ready' AND error_code IS NULL) OR
|
||||
(status = 'failed' AND error_code IS NOT NULL) OR
|
||||
status = 'pending'
|
||||
) NOT VALID;
|
||||
|
||||
ALTER TABLE attachments DROP CONSTRAINT attachments_status_check;
|
||||
ALTER TABLE attachments ADD CONSTRAINT attachments_status_check CHECK (
|
||||
status IN ('pending', 'ready', 'failed')
|
||||
) NOT VALID;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user