forked from mtusi2026/mtusi2026lab5
lab5 na4
This commit is contained in:
@@ -0,0 +1,76 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
argonTime = 1
|
||||
argonMemory = 64 * 1024
|
||||
argonThreads = 4
|
||||
argonKeyLen = 32
|
||||
saltLen = 16
|
||||
)
|
||||
|
||||
var ErrInvalidHash = errors.New("invalid password hash format")
|
||||
|
||||
func HashPassword(password string) (string, error) {
|
||||
salt := make([]byte, saltLen)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("generate salt: %w", err)
|
||||
}
|
||||
|
||||
hash := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
||||
|
||||
encoded := fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version, argonMemory, argonTime, argonThreads,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(hash),
|
||||
)
|
||||
return encoded, nil
|
||||
}
|
||||
|
||||
func VerifyPassword(password, encodedHash string) (bool, error) {
|
||||
parts := strings.Split(encodedHash, "$")
|
||||
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
var version int
|
||||
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
if version != argon2.Version {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
var memory uint32
|
||||
var time uint32
|
||||
var threads uint8
|
||||
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &time, &threads); err != nil {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
salt, err := base64.RawStdEncoding.DecodeString(parts[4])
|
||||
if err != nil {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
storedHash, err := base64.RawStdEncoding.DecodeString(parts[5])
|
||||
if err != nil {
|
||||
return false, ErrInvalidHash
|
||||
}
|
||||
|
||||
computedHash := argon2.IDKey([]byte(password), salt, time, memory, threads, uint32(len(storedHash)))
|
||||
|
||||
if subtle.ConstantTimeCompare(storedHash, computedHash) == 1 {
|
||||
return true, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func GenerateSessionToken() (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", fmt.Errorf("generate token: %w", err)
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(b), nil
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
package blobstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/config"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/smithy-go"
|
||||
)
|
||||
|
||||
var ErrNotFound = errors.New("object not found")
|
||||
|
||||
type Store interface {
|
||||
Put(ctx context.Context, key string, body io.ReadSeeker, size int64, contentType string) error
|
||||
Get(ctx context.Context, key string) (io.ReadCloser, error)
|
||||
Delete(ctx context.Context, key string) error
|
||||
Ping(ctx context.Context) error
|
||||
List(ctx context.Context, prefix string, fn func(key string, modified time.Time) error) error
|
||||
Exists(ctx context.Context, key string) (bool, error)
|
||||
}
|
||||
|
||||
type S3Config struct {
|
||||
Endpoint, Region, Bucket, AccessKey, SecretKey string
|
||||
}
|
||||
|
||||
type S3 struct {
|
||||
client *s3.Client
|
||||
bucket string
|
||||
}
|
||||
|
||||
func NewS3(ctx context.Context, c S3Config) (*S3, error) {
|
||||
if c.Endpoint == "" || c.Bucket == "" || c.AccessKey == "" || c.SecretKey == "" {
|
||||
return nil, errors.New("incomplete S3 configuration")
|
||||
}
|
||||
cfg, err := config.LoadDefaultConfig(ctx,
|
||||
config.WithRegion(c.Region),
|
||||
config.WithRetryMaxAttempts(2),
|
||||
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(c.AccessKey, c.SecretKey, "")),
|
||||
config.WithRequestChecksumCalculation(aws.RequestChecksumCalculationWhenRequired),
|
||||
config.WithResponseChecksumValidation(aws.ResponseChecksumValidationWhenRequired),
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
client := s3.NewFromConfig(cfg, func(o *s3.Options) {
|
||||
o.BaseEndpoint = aws.String(c.Endpoint)
|
||||
o.UsePathStyle = true
|
||||
})
|
||||
return &S3{client: client, bucket: c.Bucket}, nil
|
||||
}
|
||||
|
||||
func (s *S3) Put(ctx context.Context, key string, body io.ReadSeeker, size int64, contentType string) error {
|
||||
_, err := s.client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
Body: body,
|
||||
ContentLength: aws.Int64(size),
|
||||
ContentType: aws.String(contentType),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *S3) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
||||
out, err := s.client.GetObject(ctx, &s3.GetObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
if err != nil {
|
||||
if isNotFound(err) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return out.Body, nil
|
||||
}
|
||||
|
||||
func (s *S3) Delete(ctx context.Context, key string) error {
|
||||
_, err := s.client.DeleteObject(ctx, &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *S3) Ping(ctx context.Context) error {
|
||||
body := []byte("ok")
|
||||
if _, err := s.client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String("_health/probe"),
|
||||
Body: bytes.NewReader(body),
|
||||
ContentLength: aws.Int64(int64(len(body))),
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
out, err := s.client.GetObject(ctx, &s3.GetObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String("_health/probe"),
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer out.Body.Close()
|
||||
_, err = io.Copy(io.Discard, out.Body)
|
||||
return err
|
||||
}
|
||||
|
||||
func (s *S3) List(ctx context.Context, prefix string, fn func(key string, modified time.Time) error) error {
|
||||
p := s3.NewListObjectsV2Paginator(s.client, &s3.ListObjectsV2Input{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Prefix: aws.String(prefix),
|
||||
})
|
||||
for p.HasMorePages() {
|
||||
page, err := p.NextPage(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, o := range page.Contents {
|
||||
if err := fn(aws.ToString(o.Key), aws.ToTime(o.LastModified)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *S3) Exists(ctx context.Context, key string) (bool, error) {
|
||||
_, err := s.client.HeadObject(ctx, &s3.HeadObjectInput{
|
||||
Bucket: aws.String(s.bucket),
|
||||
Key: aws.String(key),
|
||||
})
|
||||
if err != nil {
|
||||
if isNotFound(err) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func isNotFound(err error) bool {
|
||||
var apiErr smithy.APIError
|
||||
if errors.As(err, &apiErr) {
|
||||
switch apiErr.ErrorCode() {
|
||||
case "NoSuchKey", "NotFound":
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type Memory struct {
|
||||
mu sync.Mutex
|
||||
m map[string][]byte
|
||||
mod map[string]time.Time
|
||||
Err error
|
||||
}
|
||||
|
||||
func NewMemory() *Memory { return &Memory{m: map[string][]byte{}, mod: map[string]time.Time{}} }
|
||||
|
||||
func (s *Memory) Put(_ context.Context, key string, body io.ReadSeeker, _ int64, _ string) error {
|
||||
if s.Err != nil {
|
||||
return s.Err
|
||||
}
|
||||
b, err := io.ReadAll(body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.m[key], s.mod[key] = b, time.Now()
|
||||
s.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Memory) Get(_ context.Context, key string) (io.ReadCloser, error) {
|
||||
if s.Err != nil {
|
||||
return nil, s.Err
|
||||
}
|
||||
s.mu.Lock()
|
||||
b, ok := s.m[key]
|
||||
s.mu.Unlock()
|
||||
if !ok {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return io.NopCloser(bytes.NewReader(b)), nil
|
||||
}
|
||||
|
||||
func (s *Memory) Delete(_ context.Context, key string) error {
|
||||
if s.Err != nil {
|
||||
return s.Err
|
||||
}
|
||||
s.mu.Lock()
|
||||
delete(s.m, key)
|
||||
delete(s.mod, key)
|
||||
s.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Memory) Ping(_ context.Context) error { return s.Err }
|
||||
|
||||
func (s *Memory) Exists(_ context.Context, key string) (bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
_, ok := s.m[key]
|
||||
return ok, s.Err
|
||||
}
|
||||
|
||||
func (s *Memory) List(_ context.Context, prefix string, fn func(string, time.Time) error) error {
|
||||
s.mu.Lock()
|
||||
keys := make([]string, 0, len(s.m))
|
||||
for k := range s.m {
|
||||
if strings.HasPrefix(k, prefix) {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
}
|
||||
s.mu.Unlock()
|
||||
for _, k := range keys {
|
||||
if err := fn(k, s.mod[k]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Memory) Len() int { s.mu.Lock(); defer s.mu.Unlock(); return len(s.m) }
|
||||
Vendored
+67
@@ -0,0 +1,67 @@
|
||||
package cache
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"mtusi2026/internal/model"
|
||||
)
|
||||
|
||||
type Cache struct {
|
||||
client *redis.Client
|
||||
ttl time.Duration
|
||||
}
|
||||
|
||||
func New(client *redis.Client, ttl time.Duration) *Cache {
|
||||
return &Cache{
|
||||
client: client,
|
||||
ttl: ttl,
|
||||
}
|
||||
}
|
||||
|
||||
func key(userID, chatID string) string {
|
||||
return "chat:" + userID + ":" + chatID
|
||||
}
|
||||
|
||||
func (c *Cache) Get(ctx context.Context, userID, chatID string) (model.Chat, bool, error) {
|
||||
raw, err := c.client.Get(ctx, key(userID, chatID)).Bytes()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return model.Chat{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return model.Chat{}, false, fmt.Errorf("chat cache get: %w", err)
|
||||
}
|
||||
|
||||
var chat model.Chat
|
||||
if err := json.Unmarshal(raw, &chat); err != nil {
|
||||
_ = c.client.Del(ctx, key(userID, chatID)).Err()
|
||||
return model.Chat{}, false, nil
|
||||
}
|
||||
|
||||
return chat, true, nil
|
||||
}
|
||||
|
||||
func (c *Cache) Set(ctx context.Context, userID, chatID string, chat model.Chat) error {
|
||||
raw, err := json.Marshal(chat)
|
||||
if err != nil {
|
||||
return fmt.Errorf("chat cache marshal: %w", err)
|
||||
}
|
||||
|
||||
if err := c.client.Set(ctx, key(userID, chatID), raw, c.ttl).Err(); err != nil {
|
||||
return fmt.Errorf("chat cache set: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Cache) Delete(ctx context.Context, userID, chatID string) error {
|
||||
if err := c.client.Del(ctx, key(userID, chatID)).Err(); err != nil {
|
||||
return fmt.Errorf("chat cache delete: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func GetEnv(key, fallback string) string {
|
||||
if v := os.Getenv(key); v != "" {
|
||||
return v
|
||||
}
|
||||
if p := os.Getenv(key + "_FILE"); p != "" {
|
||||
if b, err := os.ReadFile(p); err == nil {
|
||||
return strings.TrimSpace(string(b))
|
||||
}
|
||||
}
|
||||
return fallback
|
||||
}
|
||||
|
||||
func ParseIntEnv(key string, fallback int) int {
|
||||
v := GetEnv(key, "")
|
||||
if v == "" {
|
||||
return fallback
|
||||
}
|
||||
n, err := strconv.Atoi(v)
|
||||
if err != nil {
|
||||
return fallback
|
||||
}
|
||||
return n
|
||||
}
|
||||
|
||||
func ParseDurationSecondsEnv(key string, fallbackSeconds int) time.Duration {
|
||||
n := ParseIntEnv(key, fallbackSeconds)
|
||||
return time.Duration(n) * time.Second
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package cursor
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Cursor struct {
|
||||
Scope string
|
||||
CreatedAt time.Time
|
||||
ID string
|
||||
}
|
||||
|
||||
func Encode(c Cursor) string {
|
||||
raw := fmt.Sprintf("%s|%s|%s", c.Scope, c.CreatedAt.UTC().Format(time.RFC3339Nano), c.ID)
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
func Decode(s string) (Cursor, error) {
|
||||
raw, err := base64.RawURLEncoding.DecodeString(s)
|
||||
if err != nil {
|
||||
return Cursor{}, fmt.Errorf("malformed cursor encoding")
|
||||
}
|
||||
parts := strings.SplitN(string(raw), "|", 3)
|
||||
if len(parts) != 3 {
|
||||
return Cursor{}, fmt.Errorf("malformed cursor structure")
|
||||
}
|
||||
t, err := time.Parse(time.RFC3339Nano, parts[1])
|
||||
if err != nil {
|
||||
return Cursor{}, fmt.Errorf("malformed cursor timestamp")
|
||||
}
|
||||
return Cursor{Scope: parts[0], CreatedAt: t, ID: parts[2]}, nil
|
||||
}
|
||||
|
||||
func IsAfter(createdAt time.Time, id string, c Cursor) bool {
|
||||
if createdAt.After(c.CreatedAt) {
|
||||
return true
|
||||
}
|
||||
if createdAt.Equal(c.CreatedAt) {
|
||||
return id > c.ID
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
DSN string
|
||||
MaxConns int32
|
||||
MinConns int32
|
||||
ConnMaxLifetime time.Duration
|
||||
ConnTimeout time.Duration
|
||||
}
|
||||
|
||||
func Connect(ctx context.Context, cfg Config) (*pgxpool.Pool, error) {
|
||||
poolCfg, err := pgxpool.ParseConfig(cfg.DSN)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse dsn: %w", err)
|
||||
}
|
||||
poolCfg.MaxConns = cfg.MaxConns
|
||||
poolCfg.MinConns = cfg.MinConns
|
||||
poolCfg.MaxConnLifetime = cfg.ConnMaxLifetime
|
||||
|
||||
connCtx, cancel := context.WithTimeout(ctx, cfg.ConnTimeout)
|
||||
defer cancel()
|
||||
pool, err := pgxpool.NewWithConfig(connCtx, poolCfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create pool: %w", err)
|
||||
}
|
||||
|
||||
pingCtx, cancel2 := context.WithTimeout(ctx, cfg.ConnTimeout)
|
||||
defer cancel2()
|
||||
if err := pool.Ping(pingCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping db: %w", err)
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
@@ -0,0 +1,983 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mtusi2026/internal/cache"
|
||||
"mtusi2026/internal/idgen"
|
||||
"mtusi2026/internal/model"
|
||||
"mtusi2026/internal/sessionstore"
|
||||
"mtusi2026/internal/store"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
//вспомогательные функции
|
||||
|
||||
func newKey() string { return idgen.GenerateUUIDv4() }
|
||||
|
||||
func doMessage(srv *httptest.Server, chatID, token, key string, body any) (*http.Response, error) {
|
||||
var buf bytes.Buffer
|
||||
if s, ok := body.(string); ok {
|
||||
buf.WriteString(s)
|
||||
} else if err := json.NewEncoder(&buf).Encode(body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodPost,
|
||||
fmt.Sprintf("%s/api/v1/chats/%s/messages", srv.URL, chatID), &buf)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
if key != "" {
|
||||
req.Header.Set("Idempotency-Key", key)
|
||||
}
|
||||
return srv.Client().Do(req)
|
||||
}
|
||||
|
||||
func postMessage(t *testing.T, srv *httptest.Server, chatID, token, key string, body any) *http.Response {
|
||||
t.Helper()
|
||||
resp, err := doMessage(srv, chatID, token, key, body)
|
||||
if err != nil {
|
||||
t.Fatalf("do request: %v", err)
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
func newUnlimitedLimiter() *store.Limiter {
|
||||
return store.NewLimiter(1_000_000, 1000)
|
||||
}
|
||||
|
||||
func newTestServer(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
srv, _ := newTestServerWithStore(t)
|
||||
return srv
|
||||
}
|
||||
|
||||
func newTestServerWithStore(t *testing.T) (*httptest.Server, *store.Store) {
|
||||
t.Helper()
|
||||
truncateAll(t)
|
||||
|
||||
s := store.New(testPool, newUnlimitedLimiter())
|
||||
ss := newMemorySessionStore()
|
||||
|
||||
return httptest.NewServer(NewRouter(s, testPool, ss)), s
|
||||
}
|
||||
|
||||
func newRedisTestServer(t *testing.T) *httptest.Server {
|
||||
t.Helper()
|
||||
srv, _ := newRedisTestServerWithStore(t)
|
||||
return srv
|
||||
}
|
||||
|
||||
func newRedisTestServerWithStore(t *testing.T) (*httptest.Server, *store.Store) {
|
||||
t.Helper()
|
||||
truncateAll(t)
|
||||
|
||||
if err := testRedis.FlushDB(context.Background()).Err(); err != nil {
|
||||
t.Fatalf("flush redis: %v", err)
|
||||
}
|
||||
|
||||
s := store.New(testPool, newUnlimitedLimiter())
|
||||
ss := sessionstore.NewRedis(testRedis)
|
||||
|
||||
return httptest.NewServer(NewRouter(s, testPool, ss)), s
|
||||
}
|
||||
|
||||
func newCachedRedisTestServer(t *testing.T) (*httptest.Server, *store.Store) {
|
||||
t.Helper()
|
||||
truncateAll(t)
|
||||
|
||||
if err := testRedis.FlushDB(context.Background()).Err(); err != nil {
|
||||
t.Fatalf("flush redis: %v", err)
|
||||
}
|
||||
|
||||
s := store.New(testPool, newUnlimitedLimiter())
|
||||
ss := sessionstore.NewRedis(testRedis)
|
||||
chatCache := cache.New(testRedis, 30*time.Second)
|
||||
|
||||
srv := httptest.NewServer(
|
||||
NewRouterWithCache(s, testPool, ss, chatCache),
|
||||
)
|
||||
|
||||
return srv, s
|
||||
}
|
||||
|
||||
type testUser struct {
|
||||
model.User
|
||||
Token string
|
||||
}
|
||||
|
||||
func postJSON(t *testing.T, srv *httptest.Server, path string, token string, body any) *http.Response {
|
||||
t.Helper()
|
||||
var buf bytes.Buffer
|
||||
if s, ok := body.(string); ok {
|
||||
buf.WriteString(s)
|
||||
} else if err := json.NewEncoder(&buf).Encode(body); err != nil {
|
||||
t.Fatalf("encode request body: %v", err)
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodPost, srv.URL+path, &buf)
|
||||
if err != nil {
|
||||
t.Fatalf("build request: %v", err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
resp, err := srv.Client().Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("do request: %v", err)
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
func getJSON(t *testing.T, srv *httptest.Server, path string, token string) *http.Response {
|
||||
t.Helper()
|
||||
req, err := http.NewRequest(http.MethodGet, srv.URL+path, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("build request: %v", err)
|
||||
}
|
||||
if token != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
}
|
||||
resp, err := srv.Client().Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("do request: %v", err)
|
||||
}
|
||||
return resp
|
||||
}
|
||||
|
||||
func decodeBody[T any](t *testing.T, resp *http.Response) T {
|
||||
t.Helper()
|
||||
defer resp.Body.Close()
|
||||
var v T
|
||||
if err := json.NewDecoder(resp.Body).Decode(&v); err != nil {
|
||||
t.Fatalf("decode response body: %v", err)
|
||||
}
|
||||
return v
|
||||
}
|
||||
|
||||
func mustLogin(t *testing.T, srv *httptest.Server, username, password string) string {
|
||||
t.Helper()
|
||||
req, err := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/auth/sessions", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("build login request: %v", err)
|
||||
}
|
||||
req.SetBasicAuth(username, password)
|
||||
|
||||
resp, err := srv.Client().Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("do login request: %v", err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("login %s: expected 201, got %d", username, resp.StatusCode)
|
||||
}
|
||||
session := decodeBody[model.Session](t, resp)
|
||||
return session.Token
|
||||
}
|
||||
|
||||
func mustRegisterUser(t *testing.T, srv *httptest.Server, username string) testUser {
|
||||
t.Helper()
|
||||
const password = "correct-horse-battery-staple"
|
||||
|
||||
resp := postJSON(t, srv, "/api/v1/users", "", model.CreateUserRequest{
|
||||
Username: username,
|
||||
DisplayName: "Test " + username,
|
||||
Password: password,
|
||||
})
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("register %s: expected 201, got %d", username, resp.StatusCode)
|
||||
}
|
||||
u := decodeBody[model.User](t, resp)
|
||||
|
||||
token := mustLogin(t, srv, username, password)
|
||||
return testUser{User: u, Token: token}
|
||||
}
|
||||
|
||||
func mustCreateChat(t *testing.T, srv *httptest.Server, caller testUser, title string, memberIDs []string) model.Chat {
|
||||
t.Helper()
|
||||
resp := postJSON(t, srv, "/api/v1/chats", caller.Token, model.CreateChatRequest{
|
||||
Title: title,
|
||||
MemberIDs: memberIDs,
|
||||
})
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("create chat: expected 201, got %d", resp.StatusCode)
|
||||
}
|
||||
return decodeBody[model.Chat](t, resp)
|
||||
}
|
||||
|
||||
// тесты пользователи
|
||||
|
||||
func TestRegisterUser_DuplicateUsername_Returns409(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
mustRegisterUser(t, srv, "alice")
|
||||
|
||||
resp := postJSON(t, srv, "/api/v1/users", "", model.CreateUserRequest{
|
||||
Username: "alice",
|
||||
DisplayName: "Другая Алиса",
|
||||
Password: "correct-horse-battery-staple",
|
||||
})
|
||||
if resp.StatusCode != http.StatusConflict {
|
||||
t.Fatalf("expected 409, got %d", resp.StatusCode)
|
||||
}
|
||||
errBody := decodeBody[model.ErrorEnvelope](t, resp)
|
||||
if errBody.Error.Code != "conflict" {
|
||||
t.Fatalf("expected error code 'conflict', got %q", errBody.Error.Code)
|
||||
}
|
||||
if errBody.Error.RequestID == "" {
|
||||
t.Fatal("expected non-empty request_id")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterUser_InvalidPasswordLength_Returns400(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
cases := []string{"short", strings.Repeat("a", 129)}
|
||||
for _, password := range cases {
|
||||
resp := postJSON(t, srv, "/api/v1/users", "", model.CreateUserRequest{
|
||||
Username: "alice",
|
||||
DisplayName: "Алиса",
|
||||
Password: password,
|
||||
})
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Errorf("password len %d: expected 400, got %d", len(password), resp.StatusCode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterUser_InvalidJSON_Returns400(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
resp := postJSON(t, srv, "/api/v1/users", "", `{"username":`)
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterUser_UnknownField_Returns400(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
resp := postJSON(t, srv, "/api/v1/users", "", `{"username":"bob","display_name":"Боб","password":"correct-horse-battery-staple","extra":"whatever"}`)
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 on unknown field, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterUser_InvalidUsernamePattern_Returns400(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
cases := []string{"AB", "ab", "Has-Dash", "こんにちは"}
|
||||
for _, username := range cases {
|
||||
resp := postJSON(t, srv, "/api/v1/users", "", model.CreateUserRequest{
|
||||
Username: username,
|
||||
DisplayName: "Тест",
|
||||
Password: "correct-horse-battery-staple",
|
||||
})
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Errorf("username %q: expected 400, got %d", username, resp.StatusCode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCurrentUser_MissingHeader_Returns401(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
resp := getJSON(t, srv, "/api/v1/users/me", "")
|
||||
if resp.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCurrentUser_UnknownToken_Returns401(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
resp := getJSON(t, srv, "/api/v1/users/me", "totally-made-up-token")
|
||||
if resp.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
//тесты вход и сессии
|
||||
|
||||
func TestCreateSession_WrongPassword_Returns401(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
mustRegisterUser(t, srv, "alice")
|
||||
|
||||
req, _ := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/auth/sessions", nil)
|
||||
req.SetBasicAuth("alice", "totally-wrong-password")
|
||||
resp, err := srv.Client().Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("do request: %v", err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401, got %d", resp.StatusCode)
|
||||
}
|
||||
if resp.Header.Get("WWW-Authenticate") == "" {
|
||||
t.Error("expected WWW-Authenticate header on failed login")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateSession_UnknownUsername_Returns401(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
req, _ := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/auth/sessions", nil)
|
||||
req.SetBasicAuth("nobody_here", "whatever-password-12")
|
||||
resp, err := srv.Client().Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("do request: %v", err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeleteSession_ThenReuse_Returns401(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
alice := mustRegisterUser(t, srv, "alice")
|
||||
|
||||
req, _ := http.NewRequest(http.MethodDelete, srv.URL+"/api/v1/auth/sessions/current", nil)
|
||||
req.Header.Set("Authorization", "Bearer "+alice.Token)
|
||||
resp, err := srv.Client().Do(req)
|
||||
if err != nil {
|
||||
t.Fatalf("do logout request: %v", err)
|
||||
}
|
||||
if resp.StatusCode != http.StatusNoContent {
|
||||
t.Fatalf("expected 204, got %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
// повторное использование отозванного токена -401
|
||||
resp2 := getJSON(t, srv, "/api/v1/users/me", alice.Token)
|
||||
if resp2.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401 after logout, got %d", resp2.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
//тесты чаты и membership
|
||||
|
||||
func TestCreateChat_CallerNotInMembers_Returns400(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
alice := mustRegisterUser(t, srv, "alice")
|
||||
bob := mustRegisterUser(t, srv, "bob")
|
||||
|
||||
resp := postJSON(t, srv, "/api/v1/chats", alice.Token, model.CreateChatRequest{
|
||||
Title: "Без себя",
|
||||
MemberIDs: []string{bob.ID},
|
||||
})
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateChat_DuplicateMemberIDs_Returns400(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
alice := mustRegisterUser(t, srv, "alice")
|
||||
|
||||
resp := postJSON(t, srv, "/api/v1/chats", alice.Token, model.CreateChatRequest{
|
||||
Title: "Дубли",
|
||||
MemberIDs: []string{alice.ID, alice.ID},
|
||||
})
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetChat_NotMember_Returns404NotForbidden(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
alice := mustRegisterUser(t, srv, "alice")
|
||||
bob := mustRegisterUser(t, srv, "bob")
|
||||
carol := mustRegisterUser(t, srv, "carol")
|
||||
|
||||
chat := mustCreateChat(t, srv, alice, "Приватный", []string{alice.ID, bob.ID})
|
||||
|
||||
resp := getJSON(t, srv, "/api/v1/chats/"+chat.ID, carol.Token)
|
||||
if resp.StatusCode != http.StatusNotFound {
|
||||
t.Fatalf("expected 404 for non-member (never 403), got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetChat_UnknownChatID_Returns404(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
alice := mustRegisterUser(t, srv, "alice")
|
||||
|
||||
resp := getJSON(t, srv, "/api/v1/chats/11111111-1111-4111-8111-111111111111", alice.Token)
|
||||
if resp.StatusCode != http.StatusNotFound {
|
||||
t.Fatalf("expected 404, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// тесты: сообщения
|
||||
|
||||
func TestCreateMessage_EmptyText_Returns400(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
alice := mustRegisterUser(t, srv, "alice")
|
||||
chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID})
|
||||
|
||||
resp := postMessage(t, srv, chat.ID, alice.Token, newKey(), model.CreateMessageRequest{Text: ""})
|
||||
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for empty text, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateMessage_WhitespaceOnlyText_Returns400(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
alice := mustRegisterUser(t, srv, "alice")
|
||||
chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID})
|
||||
|
||||
resp := postMessage(t, srv, chat.ID, alice.Token, newKey(), model.CreateMessageRequest{Text: " \t\n "})
|
||||
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for whitespace-only text, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateMessage_ForeignChat_Returns404(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
alice := mustRegisterUser(t, srv, "alice")
|
||||
bob := mustRegisterUser(t, srv, "bob")
|
||||
carol := mustRegisterUser(t, srv, "carol")
|
||||
|
||||
chat := mustCreateChat(t, srv, alice, "Приватный", []string{alice.ID, bob.ID})
|
||||
|
||||
resp := postMessage(t, srv, chat.ID, carol.Token, newKey(), model.CreateMessageRequest{Text: "Я тут чужая"})
|
||||
|
||||
if resp.StatusCode != http.StatusNotFound {
|
||||
t.Fatalf("expected 404 for foreign chat, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateMessage_SenderIDIgnoredFromRequestBody(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
alice := mustRegisterUser(t, srv, "alice")
|
||||
bob := mustRegisterUser(t, srv, "bob")
|
||||
chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID, bob.ID})
|
||||
|
||||
raw := fmt.Sprintf(`{"text":"Привет","sender_id":%q}`, bob.ID)
|
||||
resp := postMessage(t, srv, chat.ID, alice.Token, newKey(), raw)
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 (unknown field sender_id), got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
// тесты пагинация
|
||||
|
||||
func TestListMessages_PaginationAcrossMultiplePages(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
alice := mustRegisterUser(t, srv, "alice")
|
||||
chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID})
|
||||
|
||||
const total = 5
|
||||
for i := 0; i < total; i++ {
|
||||
resp := postMessage(t, srv, chat.ID, alice.Token, newKey(), model.CreateMessageRequest{
|
||||
Text: fmt.Sprintf("сообщение %d", i),
|
||||
})
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("create message %d: expected 201, got %d", i, resp.StatusCode)
|
||||
}
|
||||
resp.Body.Close()
|
||||
}
|
||||
|
||||
seen := make(map[string]bool)
|
||||
cursor := ""
|
||||
pages := 0
|
||||
for {
|
||||
path := fmt.Sprintf("/api/v1/chats/%s/messages?limit=2", chat.ID)
|
||||
if cursor != "" {
|
||||
path += "&cursor=" + cursor
|
||||
}
|
||||
resp := getJSON(t, srv, path, alice.Token)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("list messages: expected 200, got %d", resp.StatusCode)
|
||||
}
|
||||
page := decodeBody[model.MessagePage](t, resp)
|
||||
pages++
|
||||
|
||||
for _, m := range page.Items {
|
||||
if seen[m.ID] {
|
||||
t.Fatalf("duplicate message across pages: %s", m.ID)
|
||||
}
|
||||
seen[m.ID] = true
|
||||
}
|
||||
|
||||
if page.NextCursor == nil {
|
||||
break
|
||||
}
|
||||
cursor = *page.NextCursor
|
||||
|
||||
if pages > total {
|
||||
t.Fatal("too many pages — possible cursor bug (infinite loop)")
|
||||
}
|
||||
}
|
||||
|
||||
if len(seen) != total {
|
||||
t.Fatalf("expected %d unique messages across all pages, got %d", total, len(seen))
|
||||
}
|
||||
if pages < 2 {
|
||||
t.Fatalf("expected pagination to span multiple pages, got %d page(s)", pages)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListMessages_CursorFromDifferentChat_Returns400(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
alice := mustRegisterUser(t, srv, "alice")
|
||||
chatA := mustCreateChat(t, srv, alice, "Чат A", []string{alice.ID})
|
||||
chatB := mustCreateChat(t, srv, alice, "Чат B", []string{alice.ID})
|
||||
|
||||
postMessage(t, srv, chatA.ID, alice.Token, newKey(), model.CreateMessageRequest{Text: "первое"}).Body.Close()
|
||||
postMessage(t, srv, chatA.ID, alice.Token, newKey(), model.CreateMessageRequest{Text: "второе"}).Body.Close()
|
||||
|
||||
respA := getJSON(t, srv, fmt.Sprintf("/api/v1/chats/%s/messages?limit=1", chatA.ID), alice.Token)
|
||||
pageA := decodeBody[model.MessagePage](t, respA)
|
||||
if pageA.NextCursor == nil {
|
||||
t.Fatal("expected next_cursor to be present after inserting 2 messages with limit=1")
|
||||
}
|
||||
|
||||
resp := getJSON(t, srv, fmt.Sprintf("/api/v1/chats/%s/messages?cursor=%s", chatB.ID, *pageA.NextCursor), alice.Token)
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("expected 400 for cross-chat cursor, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateSession_RedisTTLExpires(t *testing.T) {
|
||||
srv := newRedisTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
mustRegisterUser(t, srv, "alice")
|
||||
|
||||
t.Setenv("SESSION_TTL_SECONDS", "1")
|
||||
|
||||
token := mustLogin(t, srv, "alice", "correct-horse-battery-staple")
|
||||
|
||||
resp := getJSON(t, srv, "/api/v1/users/me", token)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("expected 200 immediately after login, got %d", resp.StatusCode)
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
time.Sleep(1500 * time.Millisecond)
|
||||
|
||||
resp = getJSON(t, srv, "/api/v1/users/me", token)
|
||||
if resp.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401 after session TTL expiration, got %d", resp.StatusCode)
|
||||
}
|
||||
resp.Body.Close()
|
||||
}
|
||||
|
||||
func TestCurrentUser_RedisUnavailable_Returns503(t *testing.T) {
|
||||
srv, s := newRedisTestServerWithStore(t)
|
||||
defer srv.Close()
|
||||
|
||||
alice := mustRegisterUser(t, srv, "alice")
|
||||
|
||||
resp := getJSON(t, srv, "/api/v1/users/me", alice.Token)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("expected 200 before redis failure, got %d", resp.StatusCode)
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
redisDownClient := redis.NewClient(&redis.Options{
|
||||
Addr: "127.0.0.1:1",
|
||||
})
|
||||
defer redisDownClient.Close()
|
||||
|
||||
redisDownSessionStore := sessionstore.NewRedis(redisDownClient)
|
||||
|
||||
downSrv := httptest.NewServer(
|
||||
NewRouter(s, testPool, redisDownSessionStore),
|
||||
)
|
||||
defer downSrv.Close()
|
||||
|
||||
resp = getJSON(t, downSrv, "/api/v1/users/me", alice.Token)
|
||||
if resp.StatusCode != http.StatusServiceUnavailable {
|
||||
t.Fatalf(
|
||||
"expected 503 when redis is unavailable, got %d",
|
||||
resp.StatusCode,
|
||||
)
|
||||
}
|
||||
resp.Body.Close()
|
||||
|
||||
}
|
||||
|
||||
func TestChatCache_ConcurrentRequests(t *testing.T) {
|
||||
const concurrentRequests = 50
|
||||
|
||||
baselineSrv, baselineStore := newTestServerWithStore(t)
|
||||
defer baselineSrv.Close()
|
||||
|
||||
baselineUser := mustRegisterUser(t, baselineSrv, "cachebaseline")
|
||||
baselineChat := mustCreateChat(
|
||||
t,
|
||||
baselineSrv,
|
||||
baselineUser,
|
||||
"Cache baseline",
|
||||
[]string{baselineUser.ID},
|
||||
)
|
||||
|
||||
baselineStore.ResetChatSQLQueries()
|
||||
|
||||
start := make(chan struct{})
|
||||
errCh := make(chan error, concurrentRequests)
|
||||
|
||||
baselineStart := time.Now()
|
||||
|
||||
for i := 0; i < concurrentRequests; i++ {
|
||||
go func() {
|
||||
<-start
|
||||
|
||||
_, err := baselineStore.GetChat(
|
||||
context.Background(),
|
||||
baselineChat.ID,
|
||||
baselineUser.ID,
|
||||
)
|
||||
errCh <- err
|
||||
}()
|
||||
}
|
||||
|
||||
close(start)
|
||||
|
||||
for i := 0; i < concurrentRequests; i++ {
|
||||
if err := <-errCh; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
baselineLatency := time.Since(baselineStart)
|
||||
baselineQueries := baselineStore.ChatSQLQueries()
|
||||
|
||||
cachedSrv, cachedStore := newCachedRedisTestServer(t)
|
||||
defer cachedSrv.Close()
|
||||
|
||||
cachedUser := mustRegisterUser(t, cachedSrv, "cacheprotected")
|
||||
cachedChat := mustCreateChat(
|
||||
t,
|
||||
cachedSrv,
|
||||
cachedUser,
|
||||
"Cache protected",
|
||||
[]string{cachedUser.ID},
|
||||
)
|
||||
|
||||
cacheKey := "chat:" + cachedUser.ID + ":" + cachedChat.ID
|
||||
|
||||
if err := testRedis.Del(context.Background(), cacheKey).Err(); err != nil {
|
||||
t.Fatalf("delete cache key: %v", err)
|
||||
}
|
||||
|
||||
cachedStore.ResetChatSQLQueries()
|
||||
|
||||
start = make(chan struct{})
|
||||
errCh = make(chan error, concurrentRequests)
|
||||
|
||||
cachedStart := time.Now()
|
||||
|
||||
for i := 0; i < concurrentRequests; i++ {
|
||||
go func() {
|
||||
<-start
|
||||
|
||||
resp := getJSON(
|
||||
t,
|
||||
cachedSrv,
|
||||
"/api/v1/chats/"+cachedChat.ID,
|
||||
cachedUser.Token,
|
||||
)
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
errCh <- fmt.Errorf("unexpected status: %d", resp.StatusCode)
|
||||
return
|
||||
}
|
||||
|
||||
errCh <- nil
|
||||
}()
|
||||
}
|
||||
|
||||
close(start)
|
||||
|
||||
for i := 0; i < concurrentRequests; i++ {
|
||||
if err := <-errCh; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
cachedLatency := time.Since(cachedStart)
|
||||
cachedQueries := cachedStore.ChatSQLQueries()
|
||||
|
||||
t.Logf(
|
||||
"baseline: requests=%d sql_queries=%d latency=%s",
|
||||
concurrentRequests,
|
||||
baselineQueries,
|
||||
baselineLatency,
|
||||
)
|
||||
|
||||
t.Logf(
|
||||
"cold cache + singleflight: requests=%d sql_queries=%d latency=%s",
|
||||
concurrentRequests,
|
||||
cachedQueries,
|
||||
cachedLatency,
|
||||
)
|
||||
|
||||
expectedBaselineQueries := int64(concurrentRequests * 2)
|
||||
|
||||
if baselineQueries != expectedBaselineQueries {
|
||||
t.Errorf(
|
||||
"baseline: expected %d SQL queries, got %d",
|
||||
expectedBaselineQueries,
|
||||
baselineQueries,
|
||||
)
|
||||
}
|
||||
|
||||
if cachedQueries > 2 {
|
||||
t.Errorf(
|
||||
"cold cache + singleflight: expected <=2 SQL queries, got %d",
|
||||
cachedQueries,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatCache_WarmCache(t *testing.T) {
|
||||
const concurrentRequests = 50
|
||||
|
||||
srv, s := newCachedRedisTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
user := mustRegisterUser(t, srv, "cachewarm")
|
||||
chat := mustCreateChat(
|
||||
t,
|
||||
srv,
|
||||
user,
|
||||
"Warm cache",
|
||||
[]string{user.ID},
|
||||
)
|
||||
|
||||
// Первый GET прогревает cache
|
||||
resp := getJSON(
|
||||
t,
|
||||
srv,
|
||||
"/api/v1/chats/"+chat.ID,
|
||||
user.Token,
|
||||
)
|
||||
resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("warm-up GET: unexpected status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
s.ResetChatSQLQueries()
|
||||
|
||||
start := make(chan struct{})
|
||||
errCh := make(chan error, concurrentRequests)
|
||||
|
||||
startedAt := time.Now()
|
||||
|
||||
for i := 0; i < concurrentRequests; i++ {
|
||||
go func() {
|
||||
<-start
|
||||
|
||||
resp := getJSON(
|
||||
t,
|
||||
srv,
|
||||
"/api/v1/chats/"+chat.ID,
|
||||
user.Token,
|
||||
)
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
errCh <- fmt.Errorf(
|
||||
"unexpected status: %d",
|
||||
resp.StatusCode,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
errCh <- nil
|
||||
}()
|
||||
}
|
||||
|
||||
close(start)
|
||||
|
||||
for i := 0; i < concurrentRequests; i++ {
|
||||
if err := <-errCh; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
latency := time.Since(startedAt)
|
||||
queries := s.ChatSQLQueries()
|
||||
|
||||
t.Logf(
|
||||
"warm cache: requests=%d sql_queries=%d latency=%s",
|
||||
concurrentRequests,
|
||||
queries,
|
||||
latency,
|
||||
)
|
||||
|
||||
if queries != 0 {
|
||||
t.Errorf(
|
||||
"warm cache: expected 0 SQL queries, got %d",
|
||||
queries,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatCache_ReadAfterWriteAndRecovery(t *testing.T) {
|
||||
srv, s := newCachedRedisTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
user := mustRegisterUser(t, srv, "cacherecovery")
|
||||
|
||||
chat := mustCreateChat(
|
||||
t,
|
||||
srv,
|
||||
user,
|
||||
"Read after write",
|
||||
[]string{user.ID},
|
||||
)
|
||||
|
||||
s.ResetChatSQLQueries()
|
||||
|
||||
resp := getJSON(
|
||||
t,
|
||||
srv,
|
||||
"/api/v1/chats/"+chat.ID,
|
||||
user.Token,
|
||||
)
|
||||
defer resp.Body.Close()
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("read-after-write: unexpected status %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
got := decodeBody[model.Chat](t, resp)
|
||||
|
||||
if got.ID != chat.ID {
|
||||
t.Fatalf(
|
||||
"read-after-write: expected chat %s, got %s",
|
||||
chat.ID,
|
||||
got.ID,
|
||||
)
|
||||
}
|
||||
|
||||
if got.Title != "Read after write" {
|
||||
t.Fatalf(
|
||||
"read-after-write: expected title %q, got %q",
|
||||
"Read after write",
|
||||
got.Title,
|
||||
)
|
||||
}
|
||||
|
||||
if queries := s.ChatSQLQueries(); queries != 2 {
|
||||
t.Fatalf(
|
||||
"read-after-write: expected 2 SQL queries on cache miss, got %d",
|
||||
queries,
|
||||
)
|
||||
}
|
||||
|
||||
cacheKey := "chat:" + user.ID + ":" + chat.ID
|
||||
|
||||
exists, err := testRedis.Exists(context.Background(), cacheKey).Result()
|
||||
if err != nil {
|
||||
t.Fatalf("check cache: %v", err)
|
||||
}
|
||||
|
||||
if exists != 1 {
|
||||
t.Fatalf("expected chat to be present in cache")
|
||||
}
|
||||
|
||||
if err := testRedis.Del(context.Background(), cacheKey).Err(); err != nil {
|
||||
t.Fatalf("delete cache: %v", err)
|
||||
}
|
||||
|
||||
s.ResetChatSQLQueries()
|
||||
|
||||
resp2 := getJSON(
|
||||
t,
|
||||
srv,
|
||||
"/api/v1/chats/"+chat.ID,
|
||||
user.Token,
|
||||
)
|
||||
defer resp2.Body.Close()
|
||||
|
||||
if resp2.StatusCode != http.StatusOK {
|
||||
t.Fatalf(
|
||||
"recovery after cache loss: unexpected status %d",
|
||||
resp2.StatusCode,
|
||||
)
|
||||
}
|
||||
|
||||
recovered := decodeBody[model.Chat](t, resp2)
|
||||
|
||||
if recovered.ID != chat.ID {
|
||||
t.Fatalf(
|
||||
"recovery: expected chat %s, got %s",
|
||||
chat.ID,
|
||||
recovered.ID,
|
||||
)
|
||||
}
|
||||
|
||||
if recovered.Title != chat.Title {
|
||||
t.Fatalf(
|
||||
"recovery: expected title %q, got %q",
|
||||
chat.Title,
|
||||
recovered.Title,
|
||||
)
|
||||
}
|
||||
|
||||
if queries := s.ChatSQLQueries(); queries != 2 {
|
||||
t.Fatalf(
|
||||
"recovery: expected 2 SQL queries after cache loss, got %d",
|
||||
queries,
|
||||
)
|
||||
}
|
||||
|
||||
exists, err = testRedis.Exists(context.Background(), cacheKey).Result()
|
||||
if err != nil {
|
||||
t.Fatalf("check recovered cache: %v", err)
|
||||
}
|
||||
|
||||
if exists != 1 {
|
||||
t.Fatalf("expected cache to be restored after database read")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,271 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"log"
|
||||
"mime"
|
||||
"net/http"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"mtusi2026/internal/blobstore"
|
||||
"mtusi2026/internal/idgen"
|
||||
"mtusi2026/internal/images"
|
||||
"mtusi2026/internal/jobs"
|
||||
"mtusi2026/internal/model"
|
||||
"mtusi2026/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
maxAttachmentBytes = 10 << 20
|
||||
maxPixels = 40_000_000
|
||||
)
|
||||
|
||||
func validFilename(s string) bool {
|
||||
n := utf8.RuneCountInString(s)
|
||||
if n < 1 || n > 255 || strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
for _, r := range s {
|
||||
if r == '/' || r == '\\' || r == 0 || unicode.IsControl(r) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (a *api) acquireUploadSlot(ctx context.Context) (func(), bool) {
|
||||
t := time.NewTimer(5 * time.Second)
|
||||
defer t.Stop()
|
||||
select {
|
||||
case a.uploadSem <- struct{}{}:
|
||||
return func() { <-a.uploadSem }, true
|
||||
case <-t.C:
|
||||
return nil, false
|
||||
case <-ctx.Done():
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
|
||||
func (a *api) handleUploadAttachment(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
|
||||
chatID, ok := uuidParam(w, r, requestID, "chat_id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if a.blobs == nil {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable")
|
||||
return
|
||||
}
|
||||
member, err := a.store.IsChatMember(r.Context(), chatID, u.ID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "database unavailable")
|
||||
return
|
||||
}
|
||||
if !member {
|
||||
writeError(w, http.StatusNotFound, requestID, codeNotFound, "chat not found")
|
||||
return
|
||||
}
|
||||
|
||||
q := r.URL.Query()
|
||||
filename := q.Get("filename")
|
||||
if !q.Has("filename") || !validFilename(filename) {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid filename")
|
||||
return
|
||||
}
|
||||
mt, _, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil || (mt != "image/png" && mt != "image/jpeg") {
|
||||
writeError(w, http.StatusUnsupportedMediaType, requestID, codeUnsupportedMedia, "only image/png and image/jpeg are accepted")
|
||||
return
|
||||
}
|
||||
if r.ContentLength > maxAttachmentBytes {
|
||||
writeError(w, http.StatusRequestEntityTooLarge, requestID, codeTooLarge, "file is too large")
|
||||
return
|
||||
}
|
||||
|
||||
tmp, err := os.CreateTemp("", "upload-*")
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
return
|
||||
}
|
||||
defer func() { tmp.Close(); os.Remove(tmp.Name()) }()
|
||||
|
||||
h := sha256.New()
|
||||
n, err := io.Copy(io.MultiWriter(tmp, h), http.MaxBytesReader(w, r.Body, maxAttachmentBytes))
|
||||
if err != nil {
|
||||
var mbe *http.MaxBytesError
|
||||
if errors.As(err, &mbe) {
|
||||
writeError(w, http.StatusRequestEntityTooLarge, requestID, codeTooLarge, "file is too large")
|
||||
} else {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "upload interrupted")
|
||||
}
|
||||
return
|
||||
}
|
||||
if n == 0 {
|
||||
writeError(w, http.StatusUnsupportedMediaType, requestID, codeUnsupportedMedia, "empty or invalid image")
|
||||
return
|
||||
}
|
||||
|
||||
release, ok := a.acquireUploadSlot(r.Context())
|
||||
if !ok {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "upload capacity reached, retry later")
|
||||
return
|
||||
}
|
||||
defer release()
|
||||
|
||||
head := make([]byte, 512)
|
||||
hn, _ := tmp.ReadAt(head, 0)
|
||||
if http.DetectContentType(head[:hn]) != mt {
|
||||
writeError(w, http.StatusUnsupportedMediaType, requestID, codeUnsupportedMedia, "content does not match declared type")
|
||||
return
|
||||
}
|
||||
cfg, format, err := image.DecodeConfig(io.NewSectionReader(tmp, 0, n))
|
||||
want := map[string]string{"image/png": "png", "image/jpeg": "jpeg"}[mt]
|
||||
if err != nil || format != want || cfg.Width <= 0 || cfg.Height <= 0 {
|
||||
writeError(w, http.StatusUnsupportedMediaType, requestID, codeUnsupportedMedia, "invalid image")
|
||||
return
|
||||
}
|
||||
pixels := int64(cfg.Width) * int64(cfg.Height)
|
||||
if pixels > maxPixels {
|
||||
writeError(w, http.StatusRequestEntityTooLarge, requestID, codeTooLarge, "image has too many pixels")
|
||||
return
|
||||
}
|
||||
if _, err := images.Run(r.Context(), "validate", tmp.Name(), ""); err != nil {
|
||||
if errors.Is(err, images.ErrLimit) || errors.Is(err, context.DeadlineExceeded) {
|
||||
writeError(w, http.StatusRequestEntityTooLarge, requestID, codeTooLarge, "image exceeds processing limits")
|
||||
return
|
||||
}
|
||||
if !errors.Is(err, images.ErrInvalid) {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "image validator unavailable")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusUnsupportedMediaType, requestID, codeUnsupportedMedia, "corrupted image")
|
||||
return
|
||||
}
|
||||
|
||||
id := idgen.GenerateUUIDv4()
|
||||
key := "attachments/" + chatID + "/" + id
|
||||
stagingKey := "staging/" + id
|
||||
|
||||
baseCtx := context.WithoutCancel(r.Context())
|
||||
putCtx, cancel := context.WithTimeout(baseCtx, 30*time.Second)
|
||||
err = a.blobs.Put(putCtx, stagingKey, io.NewSectionReader(tmp, 0, n), n, mt)
|
||||
cancel()
|
||||
if err != nil {
|
||||
log.Printf("s3 put failed: %v", err)
|
||||
delCtx, delCancel := context.WithTimeout(baseCtx, 5*time.Second)
|
||||
_ = a.blobs.Delete(delCtx, stagingKey)
|
||||
delCancel()
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
dbCtx, dbCancel := context.WithTimeout(baseCtx, 10*time.Second)
|
||||
defer dbCancel()
|
||||
att, err := a.store.CreateAttachment(dbCtx, model.Attachment{
|
||||
ID: id, ChatID: chatID, OwnerID: u.ID, Filename: filename, ContentType: mt,
|
||||
SizeBytes: n, SHA256: hex.EncodeToString(h.Sum(nil)), ObjectKey: key, StagingKey: stagingKey,
|
||||
})
|
||||
if err != nil {
|
||||
log.Printf("attachment metadata commit uncertain, staging retained: %v", err)
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusAccepted, requestID, att)
|
||||
}
|
||||
|
||||
func (a *api) loadAttachment(w http.ResponseWriter, r *http.Request, u model.User, requestID string) (model.Attachment, bool) {
|
||||
id, ok := uuidParam(w, r, requestID, "attachment_id")
|
||||
if !ok {
|
||||
return model.Attachment{}, false
|
||||
}
|
||||
att, err := a.store.GetAttachmentForUser(r.Context(), id, u.ID)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrAttachmentNotFound) {
|
||||
writeError(w, http.StatusNotFound, requestID, codeNotFound, "attachment not found")
|
||||
} else {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "database unavailable")
|
||||
}
|
||||
return model.Attachment{}, false
|
||||
}
|
||||
return att, true
|
||||
}
|
||||
|
||||
func (a *api) handleGetAttachment(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
|
||||
att, ok := a.loadAttachment(w, r, u, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, requestID, att)
|
||||
}
|
||||
|
||||
func (a *api) handleDownloadAttachment(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
|
||||
variant := r.URL.Query().Get("variant")
|
||||
if variant == "" && !r.URL.Query().Has("variant") {
|
||||
variant = "original"
|
||||
}
|
||||
if variant != "original" && variant != "thumbnail" && variant != "crop" && variant != "optimized" {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "unknown variant")
|
||||
return
|
||||
}
|
||||
att, ok := a.loadAttachment(w, r, u, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if att.Status != "ready" {
|
||||
writeError(w, http.StatusConflict, requestID, codeConflict, "attachment is not ready")
|
||||
return
|
||||
}
|
||||
key, contentType, size := att.ObjectKey, att.ContentType, att.SizeBytes
|
||||
if variant != "original" {
|
||||
found := false
|
||||
for _, v := range att.Variants {
|
||||
if v.Name == variant {
|
||||
key, contentType, size = jobs.VariantKey(att.ObjectKey, v.Name), v.ContentType, v.SizeBytes
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
writeError(w, http.StatusNotFound, requestID, codeNotFound, "variant not found")
|
||||
return
|
||||
}
|
||||
}
|
||||
if a.blobs == nil {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable")
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithCancel(r.Context())
|
||||
defer cancel()
|
||||
t := time.AfterFunc(8*time.Second, cancel)
|
||||
body, err := a.blobs.Get(ctx, key)
|
||||
t.Stop()
|
||||
if err != nil {
|
||||
if errors.Is(err, blobstore.ErrNotFound) {
|
||||
log.Printf("INCONSISTENCY: metadata without object id=%s key=%s", att.ID, att.ObjectKey)
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
} else {
|
||||
log.Printf("s3 get failed: %v", err)
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable")
|
||||
}
|
||||
return
|
||||
}
|
||||
defer body.Close()
|
||||
|
||||
w.Header().Set("Content-Type", contentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(size, 10))
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = io.Copy(w, body)
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi2026/internal/auth"
|
||||
"mtusi2026/internal/config"
|
||||
"mtusi2026/internal/model"
|
||||
"mtusi2026/internal/store"
|
||||
)
|
||||
|
||||
const sessionTTLEnvKey = "SESSION_TTL_SECONDS"
|
||||
|
||||
var dummyPasswordHash = func() string {
|
||||
h, err := auth.HashPassword("timing-equalizer-password")
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
return h
|
||||
}()
|
||||
|
||||
func (a *api) handleCreateSession(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := newRequestID()
|
||||
|
||||
username, password, ok := r.BasicAuth()
|
||||
if !ok {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "missing or malformed Basic credentials")
|
||||
return
|
||||
}
|
||||
|
||||
u, passwordHash, err := a.store.GetUserByUsername(r.Context(), username)
|
||||
if err != nil {
|
||||
if !errors.Is(err, store.ErrUsernameNotFound) {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "database unavailable")
|
||||
return
|
||||
}
|
||||
_, _ = auth.VerifyPassword(password, dummyPasswordHash)
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "invalid username or password")
|
||||
return
|
||||
}
|
||||
|
||||
valid, err := auth.VerifyPassword(password, passwordHash)
|
||||
if err != nil || !valid {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
|
||||
writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "invalid username or password")
|
||||
return
|
||||
}
|
||||
|
||||
token, err := auth.GenerateSessionToken()
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
return
|
||||
}
|
||||
|
||||
ttl := config.ParseDurationSecondsEnv(sessionTTLEnvKey, 3600)
|
||||
expiresAt, err := a.sessionStore.Create(r.Context(), token, u.ID, ttl)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeInternal, "session service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, requestID, model.Session{
|
||||
Token: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: expiresAt,
|
||||
User: u,
|
||||
})
|
||||
}
|
||||
|
||||
func (a *api) handleDeleteSession(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := newRequestID()
|
||||
|
||||
token, ok := bearerToken(r)
|
||||
if !ok {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "missing or malformed Bearer token")
|
||||
return
|
||||
}
|
||||
|
||||
deleted, err := a.sessionStore.Delete(r.Context(), token)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeInternal, "session service unavailable")
|
||||
return
|
||||
}
|
||||
if !deleted {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "unknown or already revoked token")
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func bearerToken(r *http.Request) (string, bool) {
|
||||
h := r.Header.Get("Authorization")
|
||||
const prefix = "Bearer "
|
||||
if !strings.HasPrefix(h, prefix) {
|
||||
return "", false
|
||||
}
|
||||
token := strings.TrimPrefix(h, prefix)
|
||||
if token == "" {
|
||||
return "", false
|
||||
}
|
||||
return token, true
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi2026/internal/idgen"
|
||||
"mtusi2026/internal/model"
|
||||
"mtusi2026/internal/store"
|
||||
)
|
||||
|
||||
func parseLimit(r *http.Request) (int, bool) {
|
||||
q := r.URL.Query()
|
||||
if !q.Has("limit") {
|
||||
return 50, true
|
||||
}
|
||||
raw := q.Get("limit")
|
||||
n, err := strconv.Atoi(raw)
|
||||
if err != nil || n < 1 || n > 100 || raw != strconv.Itoa(n) {
|
||||
return 0, false
|
||||
}
|
||||
return n, true
|
||||
}
|
||||
|
||||
func (a *api) handleCreateChat(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
|
||||
var req model.CreateChatRequest
|
||||
if err := decodeJSONStrict(r, &req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "malformed request body")
|
||||
return
|
||||
}
|
||||
if !validText(req.Title, 100) || len(req.MemberIDs) == 0 {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid title or member_ids")
|
||||
return
|
||||
}
|
||||
for i, id := range req.MemberIDs {
|
||||
if !idgen.IsValidUUID(id) {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid title or member_ids")
|
||||
return
|
||||
}
|
||||
req.MemberIDs[i] = strings.ToLower(id)
|
||||
}
|
||||
|
||||
c, err := a.store.CreateChat(r.Context(), u.ID, req.Title, req.MemberIDs)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrValidation) {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid title or member_ids")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, requestID, c)
|
||||
}
|
||||
|
||||
func (a *api) handleListChats(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
|
||||
limit, ok := parseLimit(r)
|
||||
if !ok {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid limit")
|
||||
return
|
||||
}
|
||||
cursorStr, ok := parseCursor(r)
|
||||
if !ok {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid cursor")
|
||||
return
|
||||
}
|
||||
|
||||
items, next, err := a.store.ListChatsForUser(r.Context(), u.ID, cursorStr, limit)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrValidation) {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid cursor")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
return
|
||||
}
|
||||
if items == nil {
|
||||
items = []model.Chat{}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, requestID, model.ChatPage{Items: items, NextCursor: next})
|
||||
}
|
||||
|
||||
func (a *api) handleGetChat(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
|
||||
chatID, ok := chatIDParam(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
if a.chatCache != nil {
|
||||
if c, hit, err := a.chatCache.Get(r.Context(), u.ID, chatID); err == nil && hit {
|
||||
writeJSON(w, http.StatusOK, requestID, c)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
result, err, _ := a.chatFlight.Do(u.ID+":"+chatID, func() (any, error) {
|
||||
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), 5*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if a.chatCache != nil {
|
||||
if c, hit, err := a.chatCache.Get(ctx, u.ID, chatID); err == nil && hit {
|
||||
return c, nil
|
||||
}
|
||||
}
|
||||
c, err := a.store.GetChat(ctx, chatID, u.ID)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
if a.chatCache != nil {
|
||||
_ = a.chatCache.Set(ctx, u.ID, chatID, c)
|
||||
}
|
||||
return c, nil
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrChatNotFound) {
|
||||
writeError(w, http.StatusNotFound, requestID, codeNotFound, "chat not found")
|
||||
} else {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "database unavailable")
|
||||
}
|
||||
return
|
||||
}
|
||||
c, ok := result.(model.Chat)
|
||||
if !ok {
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, requestID, c)
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"mtusi2026/internal/blobstore"
|
||||
)
|
||||
|
||||
func handleHealthLive(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, newRequestID(), map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
type blobProbe struct {
|
||||
mu sync.Mutex
|
||||
at time.Time
|
||||
err error
|
||||
st blobstore.Store
|
||||
}
|
||||
|
||||
func (p *blobProbe) check(ctx context.Context) error {
|
||||
p.mu.Lock()
|
||||
defer p.mu.Unlock()
|
||||
if time.Since(p.at) < time.Second {
|
||||
return p.err
|
||||
}
|
||||
cctx, cancel := context.WithTimeout(ctx, 2*time.Second)
|
||||
defer cancel()
|
||||
p.err = p.st.Ping(cctx)
|
||||
p.at = time.Now()
|
||||
return p.err
|
||||
}
|
||||
|
||||
func handleHealthReady(pool *pgxpool.Pool, rdb *redis.Client, blobs blobstore.Store, draining *atomic.Bool) http.HandlerFunc {
|
||||
var probe *blobProbe
|
||||
if blobs != nil {
|
||||
probe = &blobProbe{st: blobs}
|
||||
}
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := newRequestID()
|
||||
if draining.Load() {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "shutting down")
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := pool.Ping(ctx); err != nil {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "database unavailable")
|
||||
return
|
||||
}
|
||||
if rdb != nil {
|
||||
if err := rdb.Ping(ctx).Err(); err != nil {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "session store unavailable")
|
||||
return
|
||||
}
|
||||
}
|
||||
if probe != nil {
|
||||
if err := probe.check(ctx); err != nil {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "attachment storage unavailable")
|
||||
return
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, requestID, map[string]string{"status": "ok"})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type errorCode string
|
||||
|
||||
const (
|
||||
codeInvalidRequest errorCode = "invalid_request"
|
||||
codeUnauthorized errorCode = "unauthorized"
|
||||
codeNotFound errorCode = "not_found"
|
||||
codeConflict errorCode = "conflict"
|
||||
codeUnavailable errorCode = "unavailable"
|
||||
codeInternal errorCode = "internal_error"
|
||||
codeTooLarge errorCode = "payload_too_large"
|
||||
codeUnsupportedMedia errorCode = "unsupported_media_type"
|
||||
)
|
||||
|
||||
func newRequestID() string {
|
||||
b := make([]byte, 12)
|
||||
_, _ = rand.Read(b)
|
||||
return fmt.Sprintf("%x", b)
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, requestID string, payload any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
w.WriteHeader(status)
|
||||
if payload != nil {
|
||||
_ = json.NewEncoder(w).Encode(payload)
|
||||
}
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, status int, requestID string, code errorCode, message string) {
|
||||
writeJSON(w, status, requestID, map[string]any{
|
||||
"error": map[string]any{
|
||||
"code": code,
|
||||
"message": message,
|
||||
"request_id": requestID,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func jsonFieldNames(dst any) map[string]bool {
|
||||
names := map[string]bool{}
|
||||
t := reflect.TypeOf(dst)
|
||||
for t.Kind() == reflect.Ptr {
|
||||
t = t.Elem()
|
||||
}
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
tag := strings.Split(t.Field(i).Tag.Get("json"), ",")[0]
|
||||
if tag != "" && tag != "-" {
|
||||
names[tag] = true
|
||||
}
|
||||
}
|
||||
return names
|
||||
}
|
||||
func decodeJSONStrict(r *http.Request, dst any) error {
|
||||
contentType := r.Header.Get("Content-Type")
|
||||
mediaType, _, err := mime.ParseMediaType(contentType)
|
||||
if err != nil || mediaType != "application/json" {
|
||||
return fmt.Errorf("unsupported Content-Type")
|
||||
}
|
||||
|
||||
raw, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(bytes.TrimSpace(raw)) == 0 {
|
||||
return fmt.Errorf("empty body")
|
||||
}
|
||||
var probe map[string]json.RawMessage
|
||||
if err := json.Unmarshal(raw, &probe); err != nil {
|
||||
return err
|
||||
}
|
||||
allowed := jsonFieldNames(dst)
|
||||
for k := range probe {
|
||||
if !allowed[k] {
|
||||
return fmt.Errorf("unknown field %q", k)
|
||||
}
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(raw))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(dst); err != nil {
|
||||
return err
|
||||
}
|
||||
if dec.More() {
|
||||
return fmt.Errorf("trailing data after JSON body")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"mtusi2026/internal/model"
|
||||
)
|
||||
|
||||
func TestIdempotency_RepeatReturnsSameMessage(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
alice := mustRegisterUser(t, srv, "alice")
|
||||
chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID})
|
||||
|
||||
key := newKey()
|
||||
body := model.CreateMessageRequest{Text: "привет"}
|
||||
|
||||
r1 := postMessage(t, srv, chat.ID, alice.Token, key, body)
|
||||
if r1.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("first: expected 201, got %d", r1.StatusCode)
|
||||
}
|
||||
m1 := decodeBody[model.Message](t, r1)
|
||||
|
||||
r2 := postMessage(t, srv, chat.ID, alice.Token, key, body)
|
||||
if r2.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("repeat: expected 201, got %d", r2.StatusCode)
|
||||
}
|
||||
m2 := decodeBody[model.Message](t, r2)
|
||||
|
||||
if m1.ID != m2.ID || !m1.CreatedAt.Equal(m2.CreatedAt) {
|
||||
t.Fatalf("repeat returned a different message: %+v vs %+v", m1, m2)
|
||||
}
|
||||
|
||||
page := decodeBody[model.MessagePage](t,
|
||||
getJSON(t, srv, fmt.Sprintf("/api/v1/chats/%s/messages", chat.ID), alice.Token))
|
||||
if len(page.Items) != 1 {
|
||||
t.Fatalf("expected 1 message in history, got %d", len(page.Items))
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdempotency_DifferentBodySameKey_Returns409(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
alice := mustRegisterUser(t, srv, "alice")
|
||||
chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID})
|
||||
|
||||
key := newKey()
|
||||
postMessage(t, srv, chat.ID, alice.Token, key, model.CreateMessageRequest{Text: "один"}).Body.Close()
|
||||
|
||||
resp := postMessage(t, srv, chat.ID, alice.Token, key, model.CreateMessageRequest{Text: "два"})
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusConflict {
|
||||
t.Fatalf("expected 409, got %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdempotency_MissingOrInvalidKey_Returns400(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
alice := mustRegisterUser(t, srv, "alice")
|
||||
chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID})
|
||||
|
||||
keys := map[string]string{
|
||||
"missing": "",
|
||||
"space": "bad key",
|
||||
"too long": strings.Repeat("a", 129),
|
||||
"cyrillic": "ключ",
|
||||
}
|
||||
for name, key := range keys {
|
||||
resp := postMessage(t, srv, chat.ID, alice.Token, key, model.CreateMessageRequest{Text: "x"})
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Errorf("%s: expected 400, got %d", name, resp.StatusCode)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdempotency_ConcurrentSameKey_OneMessage(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
alice := mustRegisterUser(t, srv, "alice")
|
||||
chat := mustCreateChat(t, srv, alice, "Чат", []string{alice.ID})
|
||||
|
||||
const workers = 20
|
||||
key := newKey()
|
||||
start := make(chan struct{})
|
||||
type result struct {
|
||||
status int
|
||||
id string
|
||||
err error
|
||||
}
|
||||
results := make(chan result, workers)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < workers; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
resp, err := doMessage(srv, chat.ID, alice.Token, key, model.CreateMessageRequest{Text: "гонка"})
|
||||
if err != nil {
|
||||
results <- result{err: err}
|
||||
return
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
var m model.Message
|
||||
_ = t.Fatal
|
||||
results <- result{status: resp.StatusCode, id: m.ID}
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
close(results)
|
||||
|
||||
ids := map[string]bool{}
|
||||
for r := range results {
|
||||
if r.err != nil {
|
||||
t.Errorf("request error: %v", r.err)
|
||||
continue
|
||||
}
|
||||
if r.status != http.StatusCreated {
|
||||
t.Errorf("expected 201, got %d", r.status)
|
||||
}
|
||||
ids[r.id] = true
|
||||
}
|
||||
if len(ids) != 1 {
|
||||
t.Fatalf("expected one distinct message id, got %d", len(ids))
|
||||
}
|
||||
|
||||
page := decodeBody[model.MessagePage](t,
|
||||
getJSON(t, srv, fmt.Sprintf("/api/v1/chats/%s/messages", chat.ID), alice.Token))
|
||||
if len(page.Items) != 1 {
|
||||
t.Fatalf("expected exactly 1 message stored, got %d", len(page.Items))
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdempotency_ScopeIsPerUserAndChat(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
alice := mustRegisterUser(t, srv, "alice")
|
||||
bob := mustRegisterUser(t, srv, "bob")
|
||||
chatA := mustCreateChat(t, srv, alice, "A", []string{alice.ID, bob.ID})
|
||||
chatB := mustCreateChat(t, srv, alice, "B", []string{alice.ID, bob.ID})
|
||||
|
||||
key := newKey()
|
||||
body := model.CreateMessageRequest{Text: "то же самое"}
|
||||
ids := map[string]bool{}
|
||||
for _, c := range []struct {
|
||||
chat string
|
||||
token string
|
||||
}{
|
||||
{chatA.ID, alice.Token}, {chatB.ID, alice.Token}, {chatA.ID, bob.Token},
|
||||
} {
|
||||
resp := postMessage(t, srv, c.chat, c.token, key, body)
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("expected 201, got %d", resp.StatusCode)
|
||||
}
|
||||
ids[decodeBody[model.Message](t, resp).ID] = true
|
||||
}
|
||||
if len(ids) != 3 {
|
||||
t.Fatalf("same key in different scopes must create 3 messages, got %d", len(ids))
|
||||
}
|
||||
}
|
||||
|
||||
func TestIdempotency_ForeignChatRepeat_Returns404(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
alice := mustRegisterUser(t, srv, "alice")
|
||||
carol := mustRegisterUser(t, srv, "carol")
|
||||
chat := mustCreateChat(t, srv, alice, "Приватный", []string{alice.ID})
|
||||
|
||||
key := newKey()
|
||||
for i := 0; i < 2; i++ {
|
||||
resp := postMessage(t, srv, chat.ID, carol.Token, key, model.CreateMessageRequest{Text: "чужой"})
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusNotFound {
|
||||
t.Fatalf("attempt %d: expected 404, got %d", i, resp.StatusCode)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"mtusi2026/internal/idgen"
|
||||
"mtusi2026/internal/model"
|
||||
"mtusi2026/internal/store"
|
||||
)
|
||||
|
||||
var idemKeyRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
func (a *api) handleCreateMessage(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
|
||||
chatID, ok := uuidParam(w, r, requestID, "chat_id")
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
key := r.Header.Get("Idempotency-Key")
|
||||
if !idemKeyRe.MatchString(key) {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "missing or invalid Idempotency-Key")
|
||||
return
|
||||
}
|
||||
|
||||
var req model.CreateMessageRequest
|
||||
if err := decodeJSONStrict(r, &req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "malformed request body")
|
||||
return
|
||||
}
|
||||
|
||||
ids := make([]string, 0, len(req.AttachmentIDs))
|
||||
seen := map[string]bool{}
|
||||
for _, id := range req.AttachmentIDs {
|
||||
id = strings.ToLower(id)
|
||||
if !idgen.IsValidUUID(id) || seen[id] {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid attachment_ids")
|
||||
return
|
||||
}
|
||||
seen[id] = true
|
||||
ids = append(ids, id)
|
||||
}
|
||||
if len(ids) > 10 || !store.ValidMessageBody(req.Text, len(ids) > 0) {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid text or attachment_ids")
|
||||
return
|
||||
}
|
||||
|
||||
m, err := a.store.CreateMessage(r.Context(), chatID, u.ID, key, req.Text, ids)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, store.ErrChatNotFound), errors.Is(err, store.ErrAttachmentNotFound):
|
||||
writeError(w, http.StatusNotFound, requestID, codeNotFound, "chat or attachment not found")
|
||||
case errors.Is(err, store.ErrAttachmentFailed):
|
||||
writeError(w, http.StatusConflict, requestID, codeConflict, "attachment processing failed")
|
||||
case errors.Is(err, store.ErrIdempotencyConflict):
|
||||
writeError(w, http.StatusConflict, requestID, codeConflict, "Idempotency-Key was used with a different request body")
|
||||
case errors.Is(err, store.ErrValidation):
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid text")
|
||||
default:
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
}
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, requestID, m)
|
||||
}
|
||||
|
||||
func (a *api) handleListMessages(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
|
||||
chatID, ok := chatIDParam(w, r, requestID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, ok := parseLimit(r)
|
||||
if !ok {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid limit")
|
||||
return
|
||||
}
|
||||
cursorStr, ok := parseCursor(r)
|
||||
if !ok {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid cursor")
|
||||
return
|
||||
}
|
||||
|
||||
items, next, err := a.store.ListMessages(r.Context(), chatID, u.ID, cursorStr, limit)
|
||||
if err != nil {
|
||||
switch {
|
||||
case errors.Is(err, store.ErrChatNotFound):
|
||||
writeError(w, http.StatusNotFound, requestID, codeNotFound, "chat not found")
|
||||
case errors.Is(err, store.ErrValidation):
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid cursor")
|
||||
default:
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
}
|
||||
return
|
||||
}
|
||||
if items == nil {
|
||||
items = []model.Message{}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, requestID, model.MessagePage{Items: items, NextCursor: next})
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"mtusi2026/internal/store"
|
||||
)
|
||||
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (r *statusRecorder) WriteHeader(status int) {
|
||||
r.status = status
|
||||
r.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func loggingMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
||||
next.ServeHTTP(rec, r)
|
||||
log.Printf("method=%s path=%s status=%d duration=%s",
|
||||
r.Method, r.URL.Path, rec.status, time.Since(start))
|
||||
})
|
||||
}
|
||||
|
||||
func concurrencyMiddleware(limiter *store.Limiter, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !limiter.TryAcquire() {
|
||||
requestID := newRequestID()
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "сервер перегружен, попробуйте позже")
|
||||
return
|
||||
}
|
||||
defer limiter.Release()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mtusi2026/internal/idgen"
|
||||
"mtusi2026/internal/jobs"
|
||||
"mtusi2026/internal/model"
|
||||
"mtusi2026/internal/store"
|
||||
)
|
||||
|
||||
func TestPipeline_AtomicIntentClaimsFencingAndReplay(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
user := mustRegisterUser(t, srv, "pipeline_user")
|
||||
chat := mustCreateChat(t, srv, user, "pipeline", []string{user.ID})
|
||||
ctx := context.Background()
|
||||
st := store.New(testPool, newUnlimitedLimiter())
|
||||
id := idgen.GenerateUUIDv4()
|
||||
att, err := st.CreateAttachment(ctx, model.Attachment{ID: id, ChatID: chat.ID, OwnerID: user.ID,
|
||||
Filename: "test.png", ContentType: "image/png", SizeBytes: 100, SHA256: strings.Repeat("a", 64), ObjectKey: "attachments/" + id, StagingKey: "staging/" + id})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if att.Status != "queued" {
|
||||
t.Fatal(att.Status)
|
||||
}
|
||||
confirmed, err := st.CreateMessage(ctx, chat.ID, user.ID, "queued-before-failure", "", []string{id})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
j := jobs.Job{SchemaVersion: 1, Type: "attachment.process.v1", AttachmentID: id, PipelineVersion: 1, Attempt: 1}
|
||||
if err = testPool.QueryRow(ctx, `SELECT j.id,j.created_at FROM attachment_jobs j JOIN attachment_outbox o ON o.job_id=j.id WHERE j.attachment_id=$1 AND o.published_at IS NULL`, id).Scan(&j.ID, &j.CreatedAt); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
repo := jobs.Repo{Pool: testPool, MaxAttempts: 2, Lease: time.Minute}
|
||||
var claimed atomic.Int32
|
||||
var work *jobs.Work
|
||||
var mu sync.Mutex
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < 8; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
w, err := repo.Claim(ctx, j)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
if w != nil {
|
||||
claimed.Add(1)
|
||||
mu.Lock()
|
||||
work = w
|
||||
mu.Unlock()
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if claimed.Load() != 1 {
|
||||
t.Fatalf("concurrent claims=%d", claimed.Load())
|
||||
}
|
||||
stale := *work
|
||||
stale.Token = idgen.GenerateUUIDv4()
|
||||
if ok, err := repo.Complete(ctx, &stale, []model.Variant{}); err != nil || ok {
|
||||
t.Fatalf("stale commit ok=%v err=%v", ok, err)
|
||||
}
|
||||
if _, err = testPool.Exec(ctx, `UPDATE attachment_jobs SET lease_until=now()-interval '1 second' WHERE id=$1`, j.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = repo.Recover(ctx); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ok, err := repo.Complete(ctx, work, []model.Variant{}); err != nil || ok {
|
||||
t.Fatalf("expired commit ok=%v err=%v", ok, err)
|
||||
}
|
||||
if _, err = testPool.Exec(ctx, `UPDATE attachment_jobs SET next_attempt_at=now() WHERE id=$1`, j.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
j.Attempt = 2
|
||||
work, err = repo.Claim(ctx, j)
|
||||
if err != nil || work == nil {
|
||||
t.Fatalf("retry claim %v %v", work, err)
|
||||
}
|
||||
if err = repo.Fail(ctx, work, "storage_unavailable", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
failed, err := st.GetAttachmentForUser(ctx, id, user.ID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if failed.Status != "failed" || failed.ErrorCode == nil || *failed.ErrorCode != "retry_exhausted" {
|
||||
t.Fatalf("failed: %+v", failed)
|
||||
}
|
||||
replayed, err := st.CreateMessage(ctx, chat.ID, user.ID, "queued-before-failure", "", []string{id})
|
||||
if err != nil || replayed.ID != confirmed.ID {
|
||||
t.Fatalf("confirmed message changed after attachment failure: %+v %v", replayed, err)
|
||||
}
|
||||
if _, err = st.CreateMessage(ctx, chat.ID, user.ID, "failed-att", "", []string{id}); err != store.ErrAttachmentFailed {
|
||||
t.Fatalf("failed attachment allowed: %v", err)
|
||||
}
|
||||
if err = repo.Replay(ctx, j.ID, "storage recovered"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
j.Attempt = 3
|
||||
work, err = repo.Claim(ctx, j)
|
||||
if err != nil || work == nil {
|
||||
t.Fatalf("replay claim %v %v", work, err)
|
||||
}
|
||||
if err = repo.Fail(ctx, work, "storage_unavailable", false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = testPool.Exec(ctx, `UPDATE attachment_jobs SET next_attempt_at=now() WHERE id=$1`, j.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
j.Attempt = 4
|
||||
work, err = repo.Claim(ctx, j)
|
||||
if err != nil || work == nil {
|
||||
t.Fatalf("replay retry claim %v %v", work, err)
|
||||
}
|
||||
if ok, err := repo.Complete(ctx, work, []model.Variant{}); err != nil || !ok {
|
||||
t.Fatalf("complete %v %v", ok, err)
|
||||
}
|
||||
if w, err := repo.Claim(ctx, j); err != nil || w != nil {
|
||||
t.Fatalf("ready redelivery executed %v %v", w, err)
|
||||
}
|
||||
if err = repo.Replay(ctx, j.ID, "must refuse"); err == nil {
|
||||
t.Fatal("ready replay accepted")
|
||||
}
|
||||
var audits int
|
||||
if err = testPool.QueryRow(ctx, `SELECT count(*) FROM job_replays WHERE job_id=$1`, j.ID).Scan(&audits); err != nil || audits != 1 {
|
||||
t.Fatalf("audit %d %v", audits, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPipeline_IntentRollsBackWithAttachment(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
user := mustRegisterUser(t, srv, "pipeline_rollback")
|
||||
chat := mustCreateChat(t, srv, user, "rollback", []string{user.ID})
|
||||
ctx := context.Background()
|
||||
_, err := testPool.Exec(ctx, `CREATE FUNCTION reject_test_outbox() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected outbox write failure'; END $$;
|
||||
CREATE TRIGGER reject_test_outbox BEFORE INSERT ON attachment_outbox FOR EACH ROW EXECUTE FUNCTION reject_test_outbox()`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer testPool.Exec(ctx, `DROP TRIGGER reject_test_outbox ON attachment_outbox; DROP FUNCTION reject_test_outbox()`)
|
||||
id := idgen.GenerateUUIDv4()
|
||||
st := store.New(testPool, newUnlimitedLimiter())
|
||||
_, err = st.CreateAttachment(ctx, model.Attachment{ID: id, ChatID: chat.ID, OwnerID: user.ID, Filename: "x.png", ContentType: "image/png", SizeBytes: 10, SHA256: strings.Repeat("b", 64), ObjectKey: "attachments/" + id, StagingKey: "staging/" + id})
|
||||
if err == nil {
|
||||
t.Fatal("expected injected failure")
|
||||
}
|
||||
var count int
|
||||
if err = testPool.QueryRow(ctx, `SELECT (SELECT count(*) FROM attachments WHERE id=$1)+(SELECT count(*) FROM attachment_jobs WHERE attachment_id=$1)`, id).Scan(&count); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if count != 0 {
|
||||
t.Fatalf("partial durable intent rows=%d", count)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"mtusi2026/internal/model"
|
||||
)
|
||||
|
||||
func TestConcurrentMessages_NoLostOrDuplicated(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
alice := mustRegisterUser(t, srv, "alice")
|
||||
chat := mustCreateChat(t, srv, alice, "нагрузочный чат", []string{alice.ID})
|
||||
const clients = 10
|
||||
const perClients = 10
|
||||
const total = clients * perClients
|
||||
|
||||
var wg sync.WaitGroup
|
||||
errCh := make(chan error, total)
|
||||
client := srv.Client()
|
||||
|
||||
for c := 0; c < clients; c++ {
|
||||
wg.Add(1)
|
||||
go func(clientNum int) {
|
||||
defer wg.Done()
|
||||
for i := 0; i < perClients; i++ {
|
||||
text := fmt.Sprintf("client-%d-msg-%d", clientNum, i)
|
||||
body, _ := json.Marshal(model.CreateMessageRequest{Text: text})
|
||||
req, err := http.NewRequest(
|
||||
http.MethodPost,
|
||||
fmt.Sprintf("%s/api/v1/chats/%s/messages", srv.URL, chat.ID),
|
||||
bytes.NewReader(body),
|
||||
)
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("client %d: build request: %w", clientNum, err)
|
||||
continue
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+alice.Token)
|
||||
req.Header.Set("Idempotency-Key", fmt.Sprintf("race-%d-%d", clientNum, i))
|
||||
resp, err := client.Do(req)
|
||||
if err != nil {
|
||||
errCh <- fmt.Errorf("client %d: do request: %w", clientNum, err)
|
||||
continue
|
||||
}
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
errCh <- fmt.Errorf("client %d msg %d: expected 201, got %d", clientNum, i, resp.StatusCode)
|
||||
}
|
||||
resp.Body.Close()
|
||||
}
|
||||
}(c)
|
||||
}
|
||||
wg.Wait()
|
||||
close(errCh)
|
||||
|
||||
for err := range errCh {
|
||||
t.Error(err)
|
||||
}
|
||||
if t.Failed() {
|
||||
t.Fatal("прекращение из-за ошбок запросов")
|
||||
}
|
||||
|
||||
resp := getJSON(t, srv, fmt.Sprintf("/api/v1/chats/%s/messages?limit=100", chat.ID), alice.Token)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("list messages: expected 200, got %d", resp.StatusCode)
|
||||
}
|
||||
page := decodeBody[model.MessagePage](t, resp)
|
||||
|
||||
if page.NextCursor != nil {
|
||||
t.Fatalf("expected all %d messages to fit on one page with limit=100, got next_cursor", total)
|
||||
}
|
||||
if len(page.Items) != total {
|
||||
t.Fatalf("expected exactly %d messages, got %d", total, len(page.Items))
|
||||
}
|
||||
|
||||
seen := make(map[string]bool, total)
|
||||
for _, m := range page.Items {
|
||||
if seen[m.ID] {
|
||||
t.Fatalf("duplicate message ID found: %s", m.ID)
|
||||
}
|
||||
seen[m.ID] = true
|
||||
if m.SenderID != alice.ID {
|
||||
t.Fatalf("unexpected sender_id: %s", m.SenderID)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRegisterUser_ConcurrentDuplicateUsername_OnlyOneSucceeds(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
const workers = 20
|
||||
|
||||
statuses := make(chan int, workers)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
wg.Add(workers)
|
||||
|
||||
for i := 0; i < workers; i++ {
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
|
||||
body := `{
|
||||
"username": "raceuser",
|
||||
"display_name": "Race User",
|
||||
"password": "correct-horse-battery-staple"
|
||||
}`
|
||||
|
||||
req, err := http.NewRequest(
|
||||
http.MethodPost,
|
||||
srv.URL+"/api/v1/users",
|
||||
strings.NewReader(body),
|
||||
)
|
||||
if err != nil {
|
||||
statuses <- -1
|
||||
return
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := srv.Client().Do(req)
|
||||
if err != nil {
|
||||
statuses <- -1
|
||||
return
|
||||
}
|
||||
|
||||
statuses <- resp.StatusCode
|
||||
resp.Body.Close()
|
||||
}()
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
close(statuses)
|
||||
|
||||
created := 0
|
||||
conflicts := 0
|
||||
|
||||
for status := range statuses {
|
||||
switch status {
|
||||
case http.StatusCreated:
|
||||
created++
|
||||
case http.StatusConflict:
|
||||
conflicts++
|
||||
default:
|
||||
t.Errorf("unexpected status code: %d", status)
|
||||
}
|
||||
}
|
||||
|
||||
if created != 1 {
|
||||
t.Fatalf("ожидалась одна успешная регистрация, got %d", created)
|
||||
}
|
||||
|
||||
if conflicts != workers-1 {
|
||||
t.Fatalf("expected %d conflicts, got %d", workers-1, conflicts)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"mtusi2026/internal/blobstore"
|
||||
"mtusi2026/internal/cache"
|
||||
"mtusi2026/internal/model"
|
||||
"mtusi2026/internal/sessionstore"
|
||||
"mtusi2026/internal/store"
|
||||
)
|
||||
|
||||
type Options struct {
|
||||
InstanceID string
|
||||
Redis *redis.Client
|
||||
Draining *atomic.Bool
|
||||
Blobs blobstore.Store
|
||||
MaxUploads int
|
||||
}
|
||||
|
||||
func NewRouter(s *store.Store, pool *pgxpool.Pool, sessionStores ...sessionstore.Store) http.Handler {
|
||||
var ss sessionstore.Store
|
||||
if len(sessionStores) > 0 {
|
||||
ss = sessionStores[0]
|
||||
}
|
||||
return NewRouterWithCache(s, pool, ss, nil)
|
||||
}
|
||||
|
||||
func NewRouterWithCache(
|
||||
s *store.Store,
|
||||
pool *pgxpool.Pool,
|
||||
sessionStore sessionstore.Store,
|
||||
chatCache *cache.Cache,
|
||||
opts ...Options,
|
||||
) http.Handler {
|
||||
var o Options
|
||||
if len(opts) > 0 {
|
||||
o = opts[0]
|
||||
}
|
||||
if o.InstanceID == "" {
|
||||
o.InstanceID = "local"
|
||||
}
|
||||
if o.Draining == nil {
|
||||
o.Draining = new(atomic.Bool)
|
||||
}
|
||||
|
||||
if o.MaxUploads <= 0 {
|
||||
o.MaxUploads = 4
|
||||
}
|
||||
|
||||
a := &api{
|
||||
store: s,
|
||||
sessionStore: sessionStore,
|
||||
chatCache: chatCache,
|
||||
blobs: o.Blobs,
|
||||
uploadSem: make(chan struct{}, o.MaxUploads),
|
||||
}
|
||||
|
||||
apiMux := http.NewServeMux()
|
||||
apiMux.HandleFunc("POST /api/v1/users", a.handleRegisterUser)
|
||||
apiMux.HandleFunc("GET /api/v1/users/me", a.authMiddleware(a.handleCurrentUser))
|
||||
apiMux.HandleFunc("POST /api/v1/chats", a.authMiddleware(a.handleCreateChat))
|
||||
apiMux.HandleFunc("GET /api/v1/chats", a.authMiddleware(a.handleListChats))
|
||||
apiMux.HandleFunc("GET /api/v1/chats/{chat_id}", a.authMiddleware(a.handleGetChat))
|
||||
apiMux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", a.authMiddleware(a.handleCreateMessage))
|
||||
apiMux.HandleFunc("GET /api/v1/chats/{chat_id}/messages", a.authMiddleware(a.handleListMessages))
|
||||
apiMux.HandleFunc("POST /api/v1/auth/sessions", a.handleCreateSession)
|
||||
apiMux.HandleFunc("POST /api/v1/chats/{chat_id}/attachments", a.authMiddleware(a.handleUploadAttachment))
|
||||
apiMux.HandleFunc("GET /api/v1/attachments/{attachment_id}", a.authMiddleware(a.handleGetAttachment))
|
||||
apiMux.HandleFunc("GET /api/v1/attachments/{attachment_id}/content", a.authMiddleware(a.handleDownloadAttachment))
|
||||
apiMux.HandleFunc("DELETE /api/v1/auth/sessions/current", a.authMiddleware(
|
||||
func(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
|
||||
a.handleDeleteSession(w, r)
|
||||
}))
|
||||
|
||||
root := http.NewServeMux()
|
||||
root.HandleFunc("GET /health/live", handleHealthLive)
|
||||
root.HandleFunc("GET /health/ready", handleHealthReady(pool, o.Redis, o.Blobs, o.Draining))
|
||||
root.Handle("/", concurrencyMiddleware(s.Limiter, apiMux))
|
||||
|
||||
var h http.Handler = root
|
||||
h = loggingMiddleware(h)
|
||||
h = instanceMiddleware(o.InstanceID, h)
|
||||
return h
|
||||
}
|
||||
|
||||
func instanceMiddleware(id string, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Instance-Id", id)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"mtusi2026/internal/sessionstore"
|
||||
)
|
||||
|
||||
type memorySession struct {
|
||||
userID string
|
||||
expiresAt time.Time
|
||||
}
|
||||
|
||||
type memorySessionStore struct {
|
||||
mu sync.Mutex
|
||||
sessions map[string]memorySession
|
||||
}
|
||||
|
||||
func newMemorySessionStore() *memorySessionStore {
|
||||
return &memorySessionStore{
|
||||
sessions: make(map[string]memorySession),
|
||||
}
|
||||
}
|
||||
|
||||
func (s *memorySessionStore) Create(
|
||||
_ context.Context,
|
||||
token string,
|
||||
userID string,
|
||||
ttl time.Duration,
|
||||
) (time.Time, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
expiresAt := time.Now().UTC().Add(ttl)
|
||||
s.sessions[token] = memorySession{
|
||||
userID: userID,
|
||||
expiresAt: expiresAt,
|
||||
}
|
||||
return expiresAt, nil
|
||||
}
|
||||
|
||||
func (s *memorySessionStore) GetUserID(
|
||||
_ context.Context,
|
||||
token string,
|
||||
) (string, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
session, ok := s.sessions[token]
|
||||
if !ok || !time.Now().UTC().Before(session.expiresAt) {
|
||||
delete(s.sessions, token)
|
||||
return "", sessionstore.ErrNotFound
|
||||
}
|
||||
|
||||
return session.userID, nil
|
||||
}
|
||||
|
||||
func (s *memorySessionStore) Delete(
|
||||
_ context.Context,
|
||||
token string,
|
||||
) (bool, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if _, ok := s.sessions[token]; !ok {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
delete(s.sessions, token)
|
||||
return true, nil
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/golang-migrate/migrate/v4"
|
||||
_ "github.com/golang-migrate/migrate/v4/database/pgx/v5"
|
||||
_ "github.com/golang-migrate/migrate/v4/source/file"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/testcontainers/testcontainers-go"
|
||||
tcpostgres "github.com/testcontainers/testcontainers-go/modules/postgres"
|
||||
tcredis "github.com/testcontainers/testcontainers-go/modules/redis"
|
||||
"github.com/testcontainers/testcontainers-go/wait"
|
||||
)
|
||||
|
||||
var testPool *pgxpool.Pool
|
||||
var testRedis *redis.Client
|
||||
|
||||
// поднимает эфемерный Postgres в Docker применяет миграции даёт testPool
|
||||
// всем тестам пакета и гарантированно убивает контейнер в конце прогона :)
|
||||
func TestMain(m *testing.M) {
|
||||
os.Exit(runTests(m))
|
||||
}
|
||||
|
||||
func runTests(m *testing.M) int {
|
||||
ctx := context.Background()
|
||||
|
||||
pgContainer, err := tcpostgres.Run(ctx,
|
||||
"postgres:16.4-alpine",
|
||||
tcpostgres.WithDatabase("messenger_test"),
|
||||
tcpostgres.WithUsername("messenger_test"),
|
||||
tcpostgres.WithPassword("messenger_test"),
|
||||
testcontainers.WithWaitStrategy(
|
||||
wait.ForLog("database system is ready to accept connections").
|
||||
WithOccurrence(2).
|
||||
WithStartupTimeout(30*time.Second),
|
||||
),
|
||||
)
|
||||
if err != nil {
|
||||
log.Fatalf("start postgres container: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
if err := pgContainer.Terminate(ctx); err != nil {
|
||||
log.Printf("terminate postgres container: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
dsn, err := pgContainer.ConnectionString(ctx, "sslmode=disable")
|
||||
if err != nil {
|
||||
log.Fatalf("get connection string: %v", err)
|
||||
}
|
||||
|
||||
if err := applyMigrations(dsn); err != nil {
|
||||
log.Fatalf("apply migrations: %v", err)
|
||||
}
|
||||
|
||||
poolCfg, err := pgxpool.ParseConfig(dsn)
|
||||
if err != nil {
|
||||
log.Fatalf("parse pool config: %v", err)
|
||||
}
|
||||
testPool, err = pgxpool.NewWithConfig(ctx, poolCfg)
|
||||
if err != nil {
|
||||
log.Fatalf("create pool: %v", err)
|
||||
}
|
||||
defer testPool.Close()
|
||||
|
||||
if err := testPool.Ping(ctx); err != nil {
|
||||
log.Fatalf("ping test db: %v", err)
|
||||
}
|
||||
|
||||
redisContainer, err := tcredis.Run(ctx, "redis:7.4-alpine")
|
||||
if err != nil {
|
||||
log.Fatalf("start redis container: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
if err := testcontainers.TerminateContainer(redisContainer); err != nil {
|
||||
log.Printf("terminate redis container: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
redisURL, err := redisContainer.ConnectionString(ctx)
|
||||
if err != nil {
|
||||
log.Fatalf("get redis connection string: %v", err)
|
||||
}
|
||||
|
||||
redisOpts, err := redis.ParseURL(redisURL)
|
||||
if err != nil {
|
||||
log.Fatalf("parse redis url: %v", err)
|
||||
}
|
||||
|
||||
testRedis = redis.NewClient(redisOpts)
|
||||
defer testRedis.Close()
|
||||
|
||||
if err := testRedis.Ping(ctx).Err(); err != nil {
|
||||
log.Fatalf("ping test redis: %v", err)
|
||||
}
|
||||
|
||||
return m.Run()
|
||||
}
|
||||
|
||||
// тесты запускаются из internal/httpapi/ поэтому путь на три уровня вверх
|
||||
// и прогоняет все .up.sql через golang-migrate
|
||||
func applyMigrations(dsn string) error {
|
||||
migrationsPath, err := filepath.Abs(filepath.Join("..", "..", "migrations"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
u, err := url.Parse(dsn)
|
||||
if err != nil {
|
||||
return fmt.Errorf("parse dsn: %w", err)
|
||||
}
|
||||
u.Scheme = "pgx5"
|
||||
|
||||
m, err := migrate.New(
|
||||
fmt.Sprintf("file://%s", migrationsPath),
|
||||
u.String(),
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("migrate.New: %w", err)
|
||||
}
|
||||
defer m.Close()
|
||||
|
||||
if err := m.Up(); err != nil && err != migrate.ErrNoChange {
|
||||
return fmt.Errorf("migrate.Up: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// truncateAll очищает все таблицы между тестами сохраняя схему
|
||||
// быстрее чем пересоздавать контейнер на каждый тест
|
||||
func truncateAll(t *testing.T) {
|
||||
t.Helper()
|
||||
ctx := context.Background()
|
||||
_, err := testPool.Exec(ctx,
|
||||
`TRUNCATE TABLE messages, chat_members, chats, sessions, users RESTART IDENTITY CASCADE`,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("truncate tables: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"mtusi2026/internal/store"
|
||||
)
|
||||
|
||||
func TestCreateChat_RollsBackOnMemberInsertFailure(t *testing.T) {
|
||||
srv := newTestServer(t)
|
||||
defer srv.Close()
|
||||
|
||||
alice := mustRegisterUser(t, srv, "rollback_alice")
|
||||
|
||||
ctx := context.Background()
|
||||
s := store.New(testPool, newUnlimitedLimiter())
|
||||
|
||||
missingUserID := "00000000-0000-0000-0000-000000000000"
|
||||
|
||||
_, err := s.CreateChat(
|
||||
ctx,
|
||||
alice.ID,
|
||||
"rollback-test",
|
||||
[]string{alice.ID, missingUserID},
|
||||
)
|
||||
|
||||
if !errors.Is(err, store.ErrValidation) {
|
||||
t.Fatalf("expected ErrValidation, got %v", err)
|
||||
}
|
||||
|
||||
var chatCount int
|
||||
err = testPool.QueryRow(
|
||||
ctx,
|
||||
`SELECT COUNT(*) FROM chats WHERE title = $1`,
|
||||
"rollback-test",
|
||||
).Scan(&chatCount)
|
||||
if err != nil {
|
||||
t.Fatalf("check chats after rollback: %v", err)
|
||||
}
|
||||
|
||||
if chatCount != 0 {
|
||||
t.Fatalf("expected 0 chats after rollback, got %d", chatCount)
|
||||
}
|
||||
|
||||
var membershipCount int
|
||||
err = testPool.QueryRow(
|
||||
ctx,
|
||||
`SELECT COUNT(*)
|
||||
FROM chat_members cm
|
||||
JOIN chats c ON c.id = cm.chat_id
|
||||
WHERE c.title = $1`,
|
||||
"rollback-test",
|
||||
).Scan(&membershipCount)
|
||||
if err != nil {
|
||||
t.Fatalf("check chat_members after rollback: %v", err)
|
||||
}
|
||||
|
||||
if membershipCount != 0 {
|
||||
t.Fatalf("expected 0 chat members after rollback, got %d", membershipCount)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"golang.org/x/sync/singleflight"
|
||||
|
||||
"mtusi2026/internal/auth"
|
||||
"mtusi2026/internal/blobstore"
|
||||
"mtusi2026/internal/cache"
|
||||
"mtusi2026/internal/model"
|
||||
"mtusi2026/internal/sessionstore"
|
||||
"mtusi2026/internal/store"
|
||||
)
|
||||
|
||||
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
type api struct {
|
||||
store *store.Store
|
||||
sessionStore sessionstore.Store
|
||||
chatCache *cache.Cache
|
||||
chatFlight singleflight.Group
|
||||
blobs blobstore.Store
|
||||
uploadSem chan struct{}
|
||||
}
|
||||
|
||||
func (a *api) authMiddleware(next func(w http.ResponseWriter, r *http.Request, u model.User, requestID string)) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := newRequestID()
|
||||
|
||||
token, ok := bearerToken(r)
|
||||
if !ok {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "missing or malformed Bearer token")
|
||||
return
|
||||
}
|
||||
|
||||
userID, err := a.sessionStore.GetUserID(r.Context(), token)
|
||||
if err != nil {
|
||||
if errors.Is(err, sessionstore.ErrNotFound) {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "invalid, expired or revoked token")
|
||||
return
|
||||
}
|
||||
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeInternal, "session service unavailable")
|
||||
return
|
||||
}
|
||||
|
||||
dbCtx, dbCancel := context.WithTimeout(r.Context(), 3*time.Second)
|
||||
defer dbCancel()
|
||||
|
||||
u, ok, err := a.store.GetUserByID(dbCtx, userID)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "database unavailable")
|
||||
return
|
||||
}
|
||||
if !ok {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "invalid session user")
|
||||
return
|
||||
}
|
||||
|
||||
next(w, r, u, requestID)
|
||||
}
|
||||
}
|
||||
|
||||
func validDisplayName(s string) bool {
|
||||
return validText(s, 100)
|
||||
}
|
||||
|
||||
func validPassword(s string) bool {
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 12 && n <= 128
|
||||
}
|
||||
|
||||
func (a *api) handleRegisterUser(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := newRequestID()
|
||||
|
||||
var req model.CreateUserRequest
|
||||
if err := decodeJSONStrict(r, &req); err != nil {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "malformed request body")
|
||||
return
|
||||
}
|
||||
|
||||
if !usernameRe.MatchString(req.Username) {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "username must match ^[a-z0-9_]{3,32}$")
|
||||
return
|
||||
}
|
||||
if !validDisplayName(req.DisplayName) {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "display_name must be 1-100 non-blank code points")
|
||||
return
|
||||
}
|
||||
if !validPassword(req.Password) {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "password must be 12-128 code points")
|
||||
return
|
||||
}
|
||||
|
||||
passwordHash, err := auth.HashPassword(req.Password)
|
||||
if err != nil {
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
return
|
||||
}
|
||||
|
||||
u, err := a.store.CreateUser(r.Context(), req.Username, req.DisplayName, passwordHash)
|
||||
if err != nil {
|
||||
if err == store.ErrUsernameTaken {
|
||||
writeError(w, http.StatusConflict, requestID, codeConflict, "username already taken")
|
||||
return
|
||||
}
|
||||
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusCreated, requestID, u)
|
||||
}
|
||||
|
||||
func (a *api) handleCurrentUser(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
|
||||
writeJSON(w, http.StatusOK, requestID, u)
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"mtusi2026/internal/idgen"
|
||||
)
|
||||
|
||||
func validText(s string, max int) bool {
|
||||
n := utf8.RuneCountInString(s)
|
||||
if n < 1 || n > max {
|
||||
return false
|
||||
}
|
||||
hasContent := false
|
||||
for _, r := range s {
|
||||
if r == 0 {
|
||||
return false
|
||||
}
|
||||
if !unicode.IsSpace(r) {
|
||||
hasContent = true
|
||||
}
|
||||
}
|
||||
return hasContent
|
||||
}
|
||||
|
||||
func parseCursor(r *http.Request) (string, bool) {
|
||||
q := r.URL.Query()
|
||||
if !q.Has("cursor") {
|
||||
return "", true
|
||||
}
|
||||
c := q.Get("cursor")
|
||||
return c, c != ""
|
||||
}
|
||||
|
||||
func chatIDParam(w http.ResponseWriter, r *http.Request, requestID string) (string, bool) {
|
||||
id := r.PathValue("chat_id")
|
||||
if !idgen.IsValidUUID(id) {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid chat_id")
|
||||
return "", false
|
||||
}
|
||||
return strings.ToLower(id), true
|
||||
}
|
||||
|
||||
func uuidParam(w http.ResponseWriter, r *http.Request, requestID, name string) (string, bool) {
|
||||
id := r.PathValue(name)
|
||||
if !idgen.IsValidUUID(id) {
|
||||
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid "+name)
|
||||
return "", false
|
||||
}
|
||||
return strings.ToLower(id), true
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
package idgen
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"regexp"
|
||||
)
|
||||
|
||||
var uuidRe = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`)
|
||||
|
||||
func IsValidUUID(s string) bool {
|
||||
return uuidRe.MatchString(s)
|
||||
}
|
||||
|
||||
func GenerateUUIDv4() string {
|
||||
b := make([]byte, 16)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
b[6] = (b[6] & 0x0f) | 0x40
|
||||
b[8] = (b[8] & 0x3f) | 0x80
|
||||
return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:16])
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package images
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"mtusi2026/internal/config"
|
||||
"os/exec"
|
||||
"time"
|
||||
)
|
||||
|
||||
var ErrInvalid = errors.New("invalid_image")
|
||||
var ErrLimit = errors.New("image_resource_limit")
|
||||
|
||||
func Run(ctx context.Context, mode, source, dir string) ([]byte, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, 25*time.Second)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, config.GetEnv("PYTHON", "python3"), config.GetEnv("IMAGE_SCRIPT", "scripts/process_image.py"), mode, source, dir)
|
||||
out, err := cmd.Output()
|
||||
if ctx.Err() != nil {
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
var ex *exec.ExitError
|
||||
if errors.As(err, &ex) {
|
||||
switch ex.ExitCode() {
|
||||
case 2:
|
||||
return nil, ErrInvalid
|
||||
case 3:
|
||||
return nil, ErrLimit
|
||||
}
|
||||
}
|
||||
return out, err
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package images
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestImageSubprocessDeadlineKillsChild(t *testing.T) {
|
||||
if _, err := exec.LookPath("python3"); err != nil {
|
||||
t.Skip("python3 is required for subprocess test")
|
||||
}
|
||||
script := filepath.Join(t.TempDir(), "slow.py")
|
||||
if err := os.WriteFile(script, []byte("import time\ntime.sleep(60)\n"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Setenv("IMAGE_SCRIPT", script)
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
defer cancel()
|
||||
start := time.Now()
|
||||
_, err := Run(ctx, "process", "unused", "unused")
|
||||
if !errors.Is(err, context.DeadlineExceeded) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if time.Since(start) > 3*time.Second {
|
||||
t.Fatal("child was not killed within deadline")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
package jobs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand/v2"
|
||||
"time"
|
||||
|
||||
"mtusi2026/internal/idgen"
|
||||
"mtusi2026/internal/model"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
type Job struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
ID string `json:"job_id"`
|
||||
Type string `json:"type"`
|
||||
AttachmentID string `json:"attachment_id"`
|
||||
PipelineVersion int `json:"pipeline_version"`
|
||||
Attempt int `json:"attempt"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type Repo struct {
|
||||
Pool *pgxpool.Pool
|
||||
MaxAttempts int
|
||||
Lease time.Duration
|
||||
}
|
||||
type Work struct {
|
||||
Job
|
||||
Token, StagingKey, ObjectKey, SHA256, ContentType string
|
||||
Size int64
|
||||
}
|
||||
|
||||
func Enqueue(ctx context.Context, tx pgx.Tx, attachmentID string) error {
|
||||
id := idgen.GenerateUUIDv4()
|
||||
_, err := tx.Exec(ctx, `INSERT INTO attachment_jobs(id,attachment_id) VALUES($1,$2)`, id, attachmentID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO attachment_outbox(job_id,attempt) VALUES($1,1)`, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r Repo) Claim(ctx context.Context, j Job) (*Work, error) {
|
||||
tx, err := r.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
w := &Work{Job: j, Token: idgen.GenerateUUIDv4()}
|
||||
err = tx.QueryRow(ctx, `UPDATE attachment_jobs SET status='processing',attempt=attempt+1,
|
||||
lease_token=$3,lease_until=now()+$4::interval,updated_at=now()
|
||||
WHERE id=$1 AND attachment_id=$2 AND pipeline_version=$5 AND status='queued'
|
||||
AND next_attempt_at<=now() AND attempt=$6-1
|
||||
RETURNING attempt`, j.ID, j.AttachmentID, w.Token, r.Lease.String(), j.PipelineVersion, j.Attempt).Scan(&w.Attempt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
err = tx.QueryRow(ctx, `UPDATE attachments SET status='processing',updated_at=now()
|
||||
WHERE id=$1 RETURNING staging_key,object_key,sha256,content_type,size_bytes`, j.AttachmentID).
|
||||
Scan(&w.StagingKey, &w.ObjectKey, &w.SHA256, &w.ContentType, &w.Size)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return w, nil
|
||||
}
|
||||
|
||||
func (r Repo) Complete(ctx context.Context, w *Work, variants []model.Variant) (bool, error) {
|
||||
tx, err := r.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
tag, err := tx.Exec(ctx, `UPDATE attachment_jobs SET status='ready',error_code=NULL,
|
||||
lease_token=NULL,lease_until=NULL,updated_at=now() WHERE id=$1 AND status='processing'
|
||||
AND lease_token=$2 AND lease_until>now()`, w.ID, w.Token)
|
||||
if err != nil || tag.RowsAffected() == 0 {
|
||||
return false, err
|
||||
}
|
||||
b, err := json.Marshal(variants)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `UPDATE attachments SET status='ready',variants=$2,error_code=NULL,updated_at=now() WHERE id=$1`, w.AttachmentID, b)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func RetryDelay(attempt int) time.Duration {
|
||||
base := time.Second
|
||||
for i := 1; i < attempt && base < 60*time.Second; i++ {
|
||||
base *= 2
|
||||
}
|
||||
if base > 60*time.Second {
|
||||
base = 60 * time.Second
|
||||
}
|
||||
return base/2 + time.Duration(rand.Int64N(int64(base/2)+1))
|
||||
}
|
||||
|
||||
func (r Repo) Fail(ctx context.Context, w *Work, code string, permanent bool) error {
|
||||
tx, err := r.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
var attempt, replayBase int
|
||||
err = tx.QueryRow(ctx, `SELECT attempt FROM attachment_jobs WHERE id=$1 AND status='processing'
|
||||
AND lease_token=$2 FOR UPDATE`, w.ID, w.Token).Scan(&attempt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err = tx.QueryRow(ctx, `SELECT COALESCE(max(previous_attempt),0) FROM job_replays WHERE job_id=$1`, w.ID).Scan(&replayBase); err != nil {
|
||||
return err
|
||||
}
|
||||
state := "queued"
|
||||
if permanent || attempt-replayBase >= r.MaxAttempts {
|
||||
state = "failed"
|
||||
if !permanent {
|
||||
code = "retry_exhausted"
|
||||
}
|
||||
}
|
||||
delay := RetryDelay(attempt)
|
||||
_, err = tx.Exec(ctx, `UPDATE attachment_jobs SET status=$2,error_code=$3,lease_until=NULL,lease_token=NULL,
|
||||
next_attempt_at=now()+$4::interval,updated_at=now() WHERE id=$1`, w.ID, state, code, delay.String())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `UPDATE attachments SET status=$2,error_code=$3,updated_at=now() WHERE id=$1`, w.AttachmentID, state, code)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if state == "queued" {
|
||||
_, err = tx.Exec(ctx, `INSERT INTO attachment_outbox(job_id,attempt,available_at)
|
||||
SELECT id,attempt+1,next_attempt_at FROM attachment_jobs WHERE id=$1`, w.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (r Repo) Recover(ctx context.Context) error {
|
||||
rows, err := r.Pool.Query(ctx, `SELECT id,attachment_id,lease_token FROM attachment_jobs
|
||||
WHERE status='processing' AND lease_until<now() LIMIT 100`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var ws []Work
|
||||
for rows.Next() {
|
||||
var w Work
|
||||
if err = rows.Scan(&w.ID, &w.AttachmentID, &w.Token); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
ws = append(ws, w)
|
||||
}
|
||||
rows.Close()
|
||||
if err = rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
for i := range ws {
|
||||
if err = r.Fail(ctx, &ws[i], "lease_expired", false); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r Repo) Replay(ctx context.Context, id, reason string) error {
|
||||
if !idgen.IsValidUUID(id) || len(reason) < 1 || len(reason) > 200 {
|
||||
return errors.New("provide job UUID and reason (1..200 bytes)")
|
||||
}
|
||||
tx, err := r.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
var attempt int
|
||||
var aid string
|
||||
err = tx.QueryRow(ctx, `SELECT attempt,attachment_id FROM attachment_jobs WHERE id=$1 AND status='failed' FOR UPDATE`, id).Scan(&attempt, &aid)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return errors.New("replay allowed only for failed jobs; ready is never replayed")
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var staging *string
|
||||
if err = tx.QueryRow(ctx, `SELECT staging_key FROM attachments WHERE id=$1 FOR UPDATE`, aid).Scan(&staging); err != nil {
|
||||
return err
|
||||
}
|
||||
if staging == nil {
|
||||
return errors.New("staging retention expired; original must be uploaded again")
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO job_replays(job_id,reason,previous_attempt) VALUES($1,$2,$3)`, id, reason, attempt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `UPDATE attachment_jobs SET status='queued',error_code=NULL,next_attempt_at=now(),updated_at=now() WHERE id=$1`, id)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `UPDATE attachments SET status='queued',error_code=NULL,updated_at=now() WHERE id=$1`, aid)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = tx.Exec(ctx, `INSERT INTO attachment_outbox(job_id,attempt) VALUES($1,$2)`, id, attempt+1)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func VariantKey(original, name string) string { return original + "/v1/" + name }
|
||||
|
||||
func (r Repo) Failed(ctx context.Context) ([]map[string]any, error) {
|
||||
rows, err := r.Pool.Query(ctx, `SELECT id,attachment_id,attempt,error_code FROM attachment_jobs WHERE status='failed' ORDER BY updated_at`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
result := []map[string]any{}
|
||||
for rows.Next() {
|
||||
var id, aid, code string
|
||||
var n int
|
||||
if err = rows.Scan(&id, &aid, &n, &code); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result = append(result, map[string]any{"job_id": id, "attachment_id": aid, "attempt": n, "error_code": code})
|
||||
}
|
||||
return result, rows.Err()
|
||||
}
|
||||
|
||||
func (j Job) Validate() error {
|
||||
if j.SchemaVersion != 1 || j.Type != "attachment.process.v1" || j.PipelineVersion != 1 || j.Attempt < 1 || !idgen.IsValidUUID(j.ID) || !idgen.IsValidUUID(j.AttachmentID) || j.CreatedAt.IsZero() {
|
||||
return fmt.Errorf("invalid job envelope")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package jobs
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestRetryBackoffJitterAndCap(t *testing.T) {
|
||||
for attempt := 1; attempt <= 12; attempt++ {
|
||||
base := time.Second
|
||||
for i := 1; i < attempt && base < 60*time.Second; i++ {
|
||||
base *= 2
|
||||
}
|
||||
if base > 60*time.Second {
|
||||
base = 60 * time.Second
|
||||
}
|
||||
values := map[time.Duration]bool{}
|
||||
for i := 0; i < 50; i++ {
|
||||
d := RetryDelay(attempt)
|
||||
if d < base/2 || d > base {
|
||||
t.Fatalf("attempt=%d delay=%s", attempt, d)
|
||||
}
|
||||
values[d] = true
|
||||
}
|
||||
if len(values) < 2 {
|
||||
t.Fatal("jitter absent")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,367 @@
|
||||
package jobs
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"mtusi2026/internal/blobstore"
|
||||
"mtusi2026/internal/images"
|
||||
"mtusi2026/internal/model"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
const Stream = "attachment-jobs-v1"
|
||||
const Group = "image-workers-v1"
|
||||
|
||||
type Runtime struct {
|
||||
Repo Repo
|
||||
Broker *redis.Client
|
||||
Blobs blobstore.Store
|
||||
Timeout time.Duration
|
||||
Concurrency int
|
||||
Fault string
|
||||
Retention time.Duration
|
||||
}
|
||||
|
||||
func (r *Runtime) PublishOne(ctx context.Context) (bool, error) {
|
||||
tx, err := r.Repo.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
var oid int64
|
||||
j := Job{SchemaVersion: 1, Type: "attachment.process.v1"}
|
||||
err = tx.QueryRow(ctx, `SELECT o.id,j.id,j.attachment_id,j.pipeline_version,o.attempt,j.created_at
|
||||
FROM attachment_outbox o JOIN attachment_jobs j ON j.id=o.job_id
|
||||
WHERE o.published_at IS NULL AND o.available_at<=now()
|
||||
ORDER BY o.id LIMIT 1 FOR UPDATE OF o SKIP LOCKED`).Scan(&oid, &j.ID, &j.AttachmentID, &j.PipelineVersion, &j.Attempt, &j.CreatedAt)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
if r.Fault == "before_publish" {
|
||||
log.Print("FAULT before_publish: committed outbox remains pending")
|
||||
os.Exit(86)
|
||||
}
|
||||
payload, err := json.Marshal(j)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
pubCtx, cancel := context.WithTimeout(ctx, 3*time.Second)
|
||||
_, err = r.Broker.XAdd(pubCtx, &redis.XAddArgs{Stream: Stream, Values: map[string]any{"payload": string(payload)}}).Result()
|
||||
cancel()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if r.Fault == "after_publish" {
|
||||
log.Print("FAULT after_publish: duplicate publication expected")
|
||||
os.Exit(86)
|
||||
}
|
||||
_, err = tx.Exec(ctx, `UPDATE attachment_outbox SET published_at=now() WHERE id=$1`, oid)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return true, tx.Commit(ctx)
|
||||
}
|
||||
|
||||
func (r *Runtime) Relay(ctx context.Context) {
|
||||
tick := time.NewTicker(300 * time.Millisecond)
|
||||
defer tick.Stop()
|
||||
lastClean := time.Time{}
|
||||
for ctx.Err() == nil {
|
||||
if err := r.Repo.Recover(ctx); err != nil && ctx.Err() == nil {
|
||||
log.Printf("lease recovery: %v", err)
|
||||
}
|
||||
for i := 0; i < 100 && ctx.Err() == nil; i++ {
|
||||
ok, err := r.PublishOne(ctx)
|
||||
if err != nil {
|
||||
log.Printf("outbox publish: %v", err)
|
||||
break
|
||||
}
|
||||
if !ok {
|
||||
break
|
||||
}
|
||||
}
|
||||
if time.Since(lastClean) > time.Minute {
|
||||
if err := r.Cleanup(ctx); err != nil {
|
||||
log.Printf("staging cleanup: %v", err)
|
||||
}
|
||||
lastClean = time.Now()
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Runtime) Workers(ctx context.Context) error {
|
||||
err := r.Broker.XGroupCreateMkStream(ctx, Stream, Group, "0").Err()
|
||||
if err != nil && !strings.Contains(err.Error(), "BUSYGROUP") {
|
||||
return err
|
||||
}
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < r.Concurrency; i++ {
|
||||
wg.Add(1)
|
||||
go func() { defer wg.Done(); r.consume(ctx) }()
|
||||
}
|
||||
wg.Wait()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Runtime) consume(ctx context.Context) {
|
||||
host, _ := os.Hostname()
|
||||
consumer := host + "-" + time.Now().Format("150405.000000000")
|
||||
for ctx.Err() == nil {
|
||||
msgs, _, err := r.Broker.XAutoClaim(ctx, &redis.XAutoClaimArgs{Stream: Stream, Group: Group, Consumer: consumer, MinIdle: r.Repo.Lease, Start: "0-0", Count: 1}).Result()
|
||||
if err == nil && len(msgs) > 0 {
|
||||
r.deliver(ctx, msgs[0])
|
||||
continue
|
||||
}
|
||||
streams, err := r.Broker.XReadGroup(ctx, &redis.XReadGroupArgs{Group: Group, Consumer: consumer, Streams: []string{Stream, ">"}, Count: 1, Block: time.Second}).Result()
|
||||
if err != nil {
|
||||
if !errors.Is(err, redis.Nil) && ctx.Err() == nil {
|
||||
log.Printf("broker read: %v", err)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
for _, s := range streams {
|
||||
for _, m := range s.Messages {
|
||||
r.deliver(ctx, m)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Runtime) deliver(ctx context.Context, m redis.XMessage) {
|
||||
var j Job
|
||||
payload, _ := m.Values["payload"].(string)
|
||||
if json.Unmarshal([]byte(payload), &j) != nil || j.Validate() != nil {
|
||||
if r.Broker.XAdd(ctx, &redis.XAddArgs{Stream: Stream + "-invalid", Values: map[string]any{"message_id": m.ID, "error_code": "invalid_job"}}).Err() == nil {
|
||||
r.Broker.XAck(ctx, Stream, Group, m.ID)
|
||||
}
|
||||
return
|
||||
}
|
||||
w, err := r.Repo.Claim(ctx, j)
|
||||
if err != nil {
|
||||
log.Printf("claim job=%s: %v", j.ID, err)
|
||||
return
|
||||
}
|
||||
if w != nil {
|
||||
err = r.process(ctx, w)
|
||||
if err != nil {
|
||||
log.Printf("process job=%s attempt=%d: %v", j.ID, w.Attempt, err)
|
||||
return
|
||||
}
|
||||
}
|
||||
if r.Fault == "before_ack" {
|
||||
log.Print("FAULT before_ack: durable DB result, pending broker delivery")
|
||||
os.Exit(86)
|
||||
}
|
||||
if err = r.Broker.XAck(ctx, Stream, Group, m.ID).Err(); err != nil {
|
||||
log.Printf("ack job=%s: %v", j.ID, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Runtime) process(ctx context.Context, w *Work) error {
|
||||
workCtx, cancel := context.WithTimeout(ctx, r.Timeout)
|
||||
defer cancel()
|
||||
variants, err := r.effects(workCtx, w)
|
||||
dbCtx, dbCancel := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second)
|
||||
defer dbCancel()
|
||||
if err != nil {
|
||||
code, permanent := "storage_unavailable", false
|
||||
switch {
|
||||
case errors.Is(err, images.ErrInvalid):
|
||||
code, permanent = "invalid_image", true
|
||||
case errors.Is(err, images.ErrLimit):
|
||||
code, permanent = "image_resource_limit", true
|
||||
case errors.Is(err, context.DeadlineExceeded):
|
||||
code = "processing_timeout"
|
||||
case errors.Is(err, blobstore.ErrNotFound):
|
||||
code, permanent = "staging_missing", true
|
||||
}
|
||||
log.Printf("job=%s attempt=%d error_code=%s", w.ID, w.Attempt, code)
|
||||
return r.Repo.Fail(dbCtx, w, code, permanent)
|
||||
}
|
||||
ok, err := r.Repo.Complete(dbCtx, w, variants)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !ok {
|
||||
return errors.New("completion lease expired or replaced; delivery left pending")
|
||||
}
|
||||
if ok {
|
||||
log.Printf("job=%s attempt=%d ready variants=%d", w.ID, w.Attempt, len(variants))
|
||||
if r.Fault == "after_commit" {
|
||||
log.Print("FAULT after_commit")
|
||||
os.Exit(86)
|
||||
}
|
||||
if err = r.Blobs.Delete(dbCtx, w.StagingKey); err == nil {
|
||||
_, err = r.Repo.Pool.Exec(dbCtx, `UPDATE attachments SET staging_key=NULL WHERE id=$1 AND status='ready'`, w.AttachmentID)
|
||||
}
|
||||
if err != nil {
|
||||
log.Printf("defer staging cleanup job=%s", w.ID)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Runtime) effects(ctx context.Context, w *Work) ([]model.Variant, error) {
|
||||
dir, err := os.MkdirTemp("", "pipeline-*")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer os.RemoveAll(dir)
|
||||
body, err := r.Blobs.Get(ctx, w.StagingKey)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
raw, err := io.ReadAll(io.LimitReader(body, (10<<20)+1))
|
||||
body.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sum := sha256.Sum256(raw)
|
||||
if int64(len(raw)) != w.Size || hex.EncodeToString(sum[:]) != w.SHA256 {
|
||||
return nil, images.ErrInvalid
|
||||
}
|
||||
source := filepath.Join(dir, "source")
|
||||
if err = os.WriteFile(source, raw, 0600); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out, err := images.Run(ctx, "process", source, dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var variants []model.Variant
|
||||
if err = json.Unmarshal(out, &variants); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(variants) != 3 {
|
||||
return nil, images.ErrInvalid
|
||||
}
|
||||
if err = r.Blobs.Put(ctx, w.ObjectKey, bytes.NewReader(raw), w.Size, w.ContentType); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if r.Fault == "after_object" {
|
||||
log.Print("FAULT after_object: original persisted, no DB commit or ack")
|
||||
os.Exit(86)
|
||||
}
|
||||
for i := range variants {
|
||||
v := &variants[i]
|
||||
if v.Name != "thumbnail" && v.Name != "crop" && v.Name != "optimized" {
|
||||
return nil, images.ErrInvalid
|
||||
}
|
||||
b, err := os.ReadFile(filepath.Join(dir, v.Name))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sum := sha256.Sum256(b)
|
||||
v.SHA256 = hex.EncodeToString(sum[:])
|
||||
v.SizeBytes = int64(len(b))
|
||||
if err = r.Blobs.Put(ctx, VariantKey(w.ObjectKey, v.Name), bytes.NewReader(b), v.SizeBytes, v.ContentType); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return variants, nil
|
||||
}
|
||||
|
||||
func (r *Runtime) Cleanup(ctx context.Context) error {
|
||||
tx, err := r.Repo.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
failed, err := tx.Query(ctx, `SELECT a.id,a.staging_key FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id
|
||||
WHERE j.status='failed' AND j.updated_at<now()-$1::interval AND a.staging_key IS NOT NULL
|
||||
LIMIT 100 FOR UPDATE OF j,a SKIP LOCKED`, r.Retention.String())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
type expired struct{ id, key string }
|
||||
var old []expired
|
||||
for failed.Next() {
|
||||
var e expired
|
||||
if err = failed.Scan(&e.id, &e.key); err != nil {
|
||||
failed.Close()
|
||||
return err
|
||||
}
|
||||
old = append(old, e)
|
||||
}
|
||||
failed.Close()
|
||||
if err = failed.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, e := range old {
|
||||
if err = r.Blobs.Delete(ctx, e.key); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = tx.Exec(ctx, `UPDATE attachments SET staging_key=NULL WHERE id=$1`, e.id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err = tx.Commit(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
rows, err := r.Repo.Pool.Query(ctx, `SELECT id,staging_key FROM attachments WHERE status='ready' AND staging_key IS NOT NULL LIMIT 100`)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
type rec struct{ id, key string }
|
||||
var ready []rec
|
||||
for rows.Next() {
|
||||
var v rec
|
||||
if err = rows.Scan(&v.id, &v.key); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
ready = append(ready, v)
|
||||
}
|
||||
rows.Close()
|
||||
if err = rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, v := range ready {
|
||||
if err = r.Blobs.Delete(ctx, v.key); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err = r.Repo.Pool.Exec(ctx, `UPDATE attachments SET staging_key=NULL WHERE id=$1 AND status='ready'`, v.id); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return r.Blobs.List(ctx, "staging/", func(key string, modified time.Time) error {
|
||||
if time.Since(modified) < r.Retention {
|
||||
return nil
|
||||
}
|
||||
var exists bool
|
||||
if err := r.Repo.Pool.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM attachments WHERE staging_key=$1)`, key).Scan(&exists); err != nil {
|
||||
return err
|
||||
}
|
||||
if !exists {
|
||||
return r.Blobs.Delete(ctx, key)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package model
|
||||
|
||||
import "time"
|
||||
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type CreateUserRequest struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
|
||||
type Chat struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type CreateChatRequest struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
type ChatPage struct {
|
||||
Items []Chat `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type Message struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
type CreateMessageRequest struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
type MessagePage struct {
|
||||
Items []Message `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type ErrorEnvelope struct {
|
||||
Error struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
} `json:"error"`
|
||||
}
|
||||
|
||||
type Session struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
User User `json:"user"`
|
||||
}
|
||||
|
||||
type Variant struct {
|
||||
Name string `json:"name"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
SHA256 string `json:"sha256"`
|
||||
}
|
||||
|
||||
type Attachment struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status string `json:"status"`
|
||||
Variants []Variant `json:"variants"`
|
||||
ErrorCode *string `json:"error_code"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ObjectKey string `json:"-"`
|
||||
StagingKey string `json:"-"`
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
package reconcile
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi2026/internal/blobstore"
|
||||
)
|
||||
|
||||
type Report struct {
|
||||
Scanned, Young, Orphans, Deleted, Missing int
|
||||
}
|
||||
|
||||
type cand struct{ key string }
|
||||
|
||||
func Run(ctx context.Context, pool *pgxpool.Pool, blobs blobstore.Store, grace time.Duration,
|
||||
dryRun, checkMissing bool, logf func(string, ...any)) (Report, error) {
|
||||
|
||||
var rep Report
|
||||
cutoff := time.Now().Add(-grace)
|
||||
var batch []string
|
||||
|
||||
flush := func() error {
|
||||
if len(batch) == 0 {
|
||||
return nil
|
||||
}
|
||||
rows, err := pool.Query(ctx, `SELECT k FROM attachments a CROSS JOIN LATERAL
|
||||
unnest(ARRAY[a.object_key, a.object_key||'/v1/thumbnail', a.object_key||'/v1/crop', a.object_key||'/v1/optimized']) AS k
|
||||
WHERE k = ANY($1)`, batch)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
known := map[string]bool{}
|
||||
for rows.Next() {
|
||||
var k string
|
||||
if err := rows.Scan(&k); err != nil {
|
||||
rows.Close()
|
||||
return err
|
||||
}
|
||||
known[k] = true
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, k := range batch {
|
||||
if known[k] {
|
||||
continue
|
||||
}
|
||||
rep.Orphans++
|
||||
if dryRun {
|
||||
logf("orphan (dry-run, not deleted): %s", k)
|
||||
continue
|
||||
}
|
||||
if err := blobs.Delete(ctx, k); err != nil {
|
||||
logf("orphan delete failed: %s: %v", k, err)
|
||||
continue
|
||||
}
|
||||
rep.Deleted++
|
||||
logf("orphan deleted: %s", k)
|
||||
}
|
||||
batch = batch[:0]
|
||||
return nil
|
||||
}
|
||||
|
||||
err := blobs.List(ctx, "attachments/", func(key string, modified time.Time) error {
|
||||
rep.Scanned++
|
||||
if modified.After(cutoff) {
|
||||
rep.Young++
|
||||
return nil
|
||||
}
|
||||
batch = append(batch, key)
|
||||
if len(batch) >= 500 {
|
||||
return flush()
|
||||
}
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return rep, fmt.Errorf("list: %w", err)
|
||||
}
|
||||
if err := flush(); err != nil {
|
||||
return rep, fmt.Errorf("check db: %w", err)
|
||||
}
|
||||
|
||||
if checkMissing {
|
||||
rows, err := pool.Query(ctx,
|
||||
`SELECT id, object_key FROM attachments WHERE status='ready' AND created_at < $1 ORDER BY created_at`, cutoff)
|
||||
if err != nil {
|
||||
return rep, err
|
||||
}
|
||||
type rec struct{ id, key string }
|
||||
var recs []rec
|
||||
for rows.Next() {
|
||||
var r rec
|
||||
if err := rows.Scan(&r.id, &r.key); err != nil {
|
||||
rows.Close()
|
||||
return rep, err
|
||||
}
|
||||
recs = append(recs, r)
|
||||
}
|
||||
rows.Close()
|
||||
for _, r := range recs {
|
||||
ok, err := blobs.Exists(ctx, r.key)
|
||||
if err != nil {
|
||||
logf("exists check failed: %s: %v", r.key, err)
|
||||
continue
|
||||
}
|
||||
if !ok {
|
||||
rep.Missing++
|
||||
logf("MISSING object for attachment id=%s key=%s (metadata kept, needs manual decision)", r.id, r.key)
|
||||
}
|
||||
}
|
||||
}
|
||||
return rep, nil
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package sessionstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
)
|
||||
|
||||
type RedisStore struct {
|
||||
client *redis.Client
|
||||
}
|
||||
|
||||
func NewRedis(client *redis.Client) *RedisStore {
|
||||
return &RedisStore{client: client}
|
||||
}
|
||||
|
||||
func NewRedisClient(ctx context.Context, addr string) (*redis.Client, error) {
|
||||
client := redis.NewClient(&redis.Options{
|
||||
Addr: addr,
|
||||
})
|
||||
|
||||
if err := client.Ping(ctx).Err(); err != nil {
|
||||
_ = client.Close()
|
||||
return nil, fmt.Errorf("%w: redis ping: %v", ErrUnavailable, err)
|
||||
}
|
||||
|
||||
return client, nil
|
||||
}
|
||||
|
||||
func sessionKey(token string) string {
|
||||
return "session:" + token
|
||||
}
|
||||
|
||||
func (s *RedisStore) Create(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
userID string,
|
||||
ttl time.Duration,
|
||||
) (time.Time, error) {
|
||||
if ttl <= 0 {
|
||||
return time.Time{}, fmt.Errorf("invalid session ttl: %s", ttl)
|
||||
}
|
||||
|
||||
if err := s.client.Set(ctx, sessionKey(token), userID, ttl).Err(); err != nil {
|
||||
return time.Time{}, fmt.Errorf("%w: create session: %v", ErrUnavailable, err)
|
||||
}
|
||||
|
||||
return time.Now().UTC().Add(ttl), nil
|
||||
}
|
||||
|
||||
func (s *RedisStore) GetUserID(ctx context.Context, token string) (string, error) {
|
||||
userID, err := s.client.Get(ctx, sessionKey(token)).Result()
|
||||
if errors.Is(err, redis.Nil) {
|
||||
return "", ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%w: get session: %v", ErrUnavailable, err)
|
||||
}
|
||||
|
||||
return userID, nil
|
||||
}
|
||||
|
||||
func (s *RedisStore) Delete(ctx context.Context, token string) (bool, error) {
|
||||
n, err := s.client.Del(ctx, sessionKey(token)).Result()
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%w: delete session: %v", ErrUnavailable, err)
|
||||
}
|
||||
|
||||
return n > 0, nil
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package sessionstore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("session not found or expired")
|
||||
ErrUnavailable = errors.New("session store unavailable")
|
||||
)
|
||||
|
||||
type Store interface {
|
||||
Create(ctx context.Context, token, userID string, ttl time.Duration) (time.Time, error)
|
||||
GetUserID(ctx context.Context, token string) (string, error)
|
||||
Delete(ctx context.Context, token string) (bool, error)
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package store
|
||||
|
||||
import "sync/atomic"
|
||||
|
||||
type Limiter struct {
|
||||
maxMessages int64
|
||||
messageCount int64
|
||||
maxConcurrent int
|
||||
inFlight chan struct{}
|
||||
}
|
||||
|
||||
func NewLimiter(maxMessages int64, maxConcurrent int) *Limiter {
|
||||
return &Limiter{
|
||||
maxMessages: maxMessages,
|
||||
maxConcurrent: maxConcurrent,
|
||||
inFlight: make(chan struct{}, maxConcurrent),
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Limiter) TryReserveMessage() bool {
|
||||
for {
|
||||
cur := atomic.LoadInt64(&l.messageCount)
|
||||
if cur >= l.maxMessages {
|
||||
return false
|
||||
}
|
||||
if atomic.CompareAndSwapInt64(&l.messageCount, cur, cur+1) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Limiter) ReleaseMessage() {
|
||||
atomic.AddInt64(&l.messageCount, -1)
|
||||
}
|
||||
|
||||
func (l *Limiter) CurrentMessageCount() int64 {
|
||||
return atomic.LoadInt64(&l.messageCount)
|
||||
}
|
||||
|
||||
func (l *Limiter) TryAcquire() bool {
|
||||
select {
|
||||
case l.inFlight <- struct{}{}:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (l *Limiter) Release() {
|
||||
<-l.inFlight
|
||||
}
|
||||
@@ -0,0 +1,612 @@
|
||||
package store
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"mtusi2026/internal/cursor"
|
||||
"mtusi2026/internal/idgen"
|
||||
"mtusi2026/internal/jobs"
|
||||
"mtusi2026/internal/model"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrUsernameTaken = errors.New("username taken")
|
||||
ErrChatNotFound = errors.New("chat not found or not accessible")
|
||||
ErrValidation = errors.New("validation failed")
|
||||
ErrCapacityExceeded = errors.New("message capacity exceeded")
|
||||
ErrAttachmentNotFound = errors.New("attachment not found or not accessible")
|
||||
ErrAttachmentFailed = errors.New("attachment processing failed")
|
||||
ErrUsernameNotFound = errors.New("username not found")
|
||||
ErrSessionNotFound = errors.New("session not found or expired")
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
Limiter *Limiter
|
||||
chatSQLQueries atomic.Int64
|
||||
}
|
||||
|
||||
func (s *Store) ResetChatSQLQueries() {
|
||||
s.chatSQLQueries.Store(0)
|
||||
}
|
||||
|
||||
func (s *Store) ChatSQLQueries() int64 {
|
||||
return s.chatSQLQueries.Load()
|
||||
}
|
||||
|
||||
func (s *Store) IsChatMember(ctx context.Context, chatID, userID string) (bool, error) {
|
||||
var ok bool
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`,
|
||||
chatID, userID).Scan(&ok)
|
||||
return ok, err
|
||||
}
|
||||
|
||||
func (s *Store) CreateAttachment(ctx context.Context, a model.Attachment) (model.Attachment, error) {
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return a, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
err = tx.QueryRow(ctx,
|
||||
`INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, staging_key, status)
|
||||
VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,'queued')
|
||||
RETURNING status, created_at, updated_at`,
|
||||
a.ID, a.ChatID, a.OwnerID, a.Filename, a.ContentType, a.SizeBytes, a.SHA256, a.ObjectKey, a.StagingKey,
|
||||
).Scan(&a.Status, &a.CreatedAt, &a.UpdatedAt)
|
||||
if err != nil {
|
||||
return a, err
|
||||
}
|
||||
if err = jobs.Enqueue(ctx, tx, a.ID); err != nil {
|
||||
return a, err
|
||||
}
|
||||
err = tx.Commit(ctx)
|
||||
a.Variants = []model.Variant{}
|
||||
return a, err
|
||||
}
|
||||
func (s *Store) GetAttachmentForUser(ctx context.Context, id, userID string) (model.Attachment, error) {
|
||||
var a model.Attachment
|
||||
var variants []byte
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type, a.size_bytes, a.sha256,
|
||||
a.object_key, a.status, a.created_at, a.updated_at, a.variants, a.error_code
|
||||
FROM attachments a
|
||||
JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = $2
|
||||
WHERE a.id = $1`, id, userID,
|
||||
).Scan(&a.ID, &a.ChatID, &a.OwnerID, &a.Filename, &a.ContentType, &a.SizeBytes, &a.SHA256,
|
||||
&a.ObjectKey, &a.Status, &a.CreatedAt, &a.UpdatedAt, &variants, &a.ErrorCode)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Attachment{}, ErrAttachmentNotFound
|
||||
}
|
||||
a.Variants = []model.Variant{}
|
||||
if err == nil {
|
||||
err = json.Unmarshal(variants, &a.Variants)
|
||||
}
|
||||
return a, err
|
||||
}
|
||||
|
||||
func (s *Store) loadAttachmentIDs(ctx context.Context, msgs []model.Message) error {
|
||||
if len(msgs) == 0 {
|
||||
return nil
|
||||
}
|
||||
ids := make([]string, len(msgs))
|
||||
pos := make(map[string]int, len(msgs))
|
||||
for i := range msgs {
|
||||
ids[i] = msgs[i].ID
|
||||
pos[msgs[i].ID] = i
|
||||
msgs[i].AttachmentIDs = []string{}
|
||||
}
|
||||
rows, err := s.pool.Query(ctx,
|
||||
`SELECT message_id, attachment_id FROM message_attachments
|
||||
WHERE message_id IN (SELECT unnest($1::text[])::uuid)
|
||||
ORDER BY message_id, position`, ids)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer rows.Close()
|
||||
for rows.Next() {
|
||||
var mid, aid string
|
||||
if err := rows.Scan(&mid, &aid); err != nil {
|
||||
return err
|
||||
}
|
||||
if i, ok := pos[mid]; ok {
|
||||
msgs[i].AttachmentIDs = append(msgs[i].AttachmentIDs, aid)
|
||||
}
|
||||
}
|
||||
return rows.Err()
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool, limiter *Limiter) *Store {
|
||||
return &Store{pool: pool, Limiter: limiter}
|
||||
}
|
||||
|
||||
func txAttachmentIDs(ctx context.Context, tx pgx.Tx, messageID string) ([]string, error) {
|
||||
rows, err := tx.Query(ctx,
|
||||
`SELECT attachment_id FROM message_attachments WHERE message_id = $1 ORDER BY position`, messageID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
ids := []string{}
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) {
|
||||
var u model.User
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`INSERT INTO users (username, display_name, password_hash)
|
||||
VALUES ($1, $2, $3)
|
||||
RETURNING id, username, display_name, created_at`,
|
||||
username, displayName, passwordHash,
|
||||
).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||
|
||||
if err != nil {
|
||||
if isUniqueViolation(err) {
|
||||
return model.User{}, ErrUsernameTaken
|
||||
}
|
||||
return model.User{}, err
|
||||
}
|
||||
return u, nil
|
||||
}
|
||||
|
||||
func (s *Store) GetUserByID(ctx context.Context, id string) (model.User, bool, error) {
|
||||
var u model.User
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT id, username, display_name, created_at FROM users WHERE id = $1`,
|
||||
id,
|
||||
).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, false, err
|
||||
}
|
||||
|
||||
return u, true, nil
|
||||
}
|
||||
|
||||
func (s *Store) CreateChat(ctx context.Context, callerID, title string, memberIDs []string) (model.Chat, error) {
|
||||
if len(memberIDs) == 0 || len(memberIDs) > 100 {
|
||||
return model.Chat{}, ErrValidation
|
||||
}
|
||||
|
||||
seen := make(map[string]bool, len(memberIDs))
|
||||
callerIncluded := false
|
||||
for _, id := range memberIDs {
|
||||
if seen[id] {
|
||||
return model.Chat{}, ErrValidation
|
||||
}
|
||||
seen[id] = true
|
||||
if id == callerID {
|
||||
callerIncluded = true
|
||||
}
|
||||
}
|
||||
if !callerIncluded {
|
||||
return model.Chat{}, ErrValidation
|
||||
}
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
var c model.Chat
|
||||
err = tx.QueryRow(ctx,
|
||||
`INSERT INTO chats (title) VALUES ($1) RETURNING id, title, created_at`,
|
||||
title,
|
||||
).Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
|
||||
for _, memberID := range memberIDs {
|
||||
_, err = tx.Exec(ctx,
|
||||
`INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)`,
|
||||
c.ID, memberID,
|
||||
)
|
||||
if err != nil {
|
||||
if isForeignKeyViolation(err) {
|
||||
return model.Chat{}, ErrValidation
|
||||
}
|
||||
return model.Chat{}, err
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
|
||||
c.MemberIDs = append([]string{}, memberIDs...)
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *Store) GetChat(ctx context.Context, chatID, userID string) (model.Chat, error) {
|
||||
var c model.Chat
|
||||
s.chatSQLQueries.Add(1)
|
||||
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id AND cm.user_id = $2
|
||||
WHERE c.id = $1`,
|
||||
chatID, userID,
|
||||
).Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Chat{}, ErrChatNotFound
|
||||
}
|
||||
return model.Chat{}, fmt.Errorf("get chat: %w", err)
|
||||
}
|
||||
|
||||
memberIDs, err := s.listChatMemberIDs(ctx, c.ID)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
c.MemberIDs = memberIDs
|
||||
return c, nil
|
||||
}
|
||||
|
||||
func (s *Store) listChatMemberIDs(ctx context.Context, chatID string) ([]string, error) {
|
||||
s.chatSQLQueries.Add(1)
|
||||
|
||||
rows, err := s.pool.Query(ctx, `SELECT user_id FROM chat_members WHERE chat_id = $1`, chatID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var ids []string
|
||||
for rows.Next() {
|
||||
var id string
|
||||
if err := rows.Scan(&id); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ids = append(ids, id)
|
||||
}
|
||||
return ids, rows.Err()
|
||||
}
|
||||
|
||||
func (s *Store) ListChatsForUser(ctx context.Context, userID, cursorStr string, limit int) ([]model.Chat, *string, error) {
|
||||
var after *cursor.Cursor
|
||||
if cursorStr != "" {
|
||||
c, err := cursor.Decode(cursorStr)
|
||||
if err != nil || c.Scope != "chats:"+userID {
|
||||
return nil, nil, ErrValidation
|
||||
}
|
||||
after = &c
|
||||
}
|
||||
|
||||
query := `
|
||||
SELECT c.id, c.title, c.created_at
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE cm.user_id = $1`
|
||||
args := []any{userID}
|
||||
|
||||
if after != nil {
|
||||
query += ` AND (c.created_at, c.id) > ($2, $3)`
|
||||
args = append(args, after.CreatedAt, after.ID)
|
||||
}
|
||||
query += ` ORDER BY c.created_at ASC, c.id ASC LIMIT $` + strconv.Itoa(len(args)+1)
|
||||
args = append(args, limit+1)
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var page []model.Chat
|
||||
for rows.Next() {
|
||||
var c model.Chat
|
||||
if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
page = append(page, c)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
var next *string
|
||||
if len(page) > limit {
|
||||
last := page[limit-1]
|
||||
nc := cursor.Encode(cursor.Cursor{Scope: "chats:" + userID, CreatedAt: last.CreatedAt, ID: last.ID})
|
||||
next = &nc
|
||||
page = page[:limit]
|
||||
}
|
||||
|
||||
for i := range page {
|
||||
memberIDs, err := s.listChatMemberIDs(ctx, page[i].ID)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
page[i].MemberIDs = memberIDs
|
||||
}
|
||||
|
||||
return page, next, nil
|
||||
}
|
||||
|
||||
var ErrIdempotencyConflict = errors.New("idempotency key reused with different body")
|
||||
|
||||
func (s *Store) CreateMessage(ctx context.Context, chatID, senderID, idemKey, text string, attIDs []string) (model.Message, error) {
|
||||
if attIDs == nil {
|
||||
attIDs = []string{}
|
||||
}
|
||||
if !ValidMessageBody(text, len(attIDs) > 0) {
|
||||
return model.Message{}, ErrValidation
|
||||
}
|
||||
hash := requestHash(text, attIDs)
|
||||
|
||||
tx, err := s.pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
var isMember bool
|
||||
if err := tx.QueryRow(ctx,
|
||||
`SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id=$1 AND user_id=$2)`,
|
||||
chatID, senderID).Scan(&isMember); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
if !isMember {
|
||||
return model.Message{}, ErrChatNotFound
|
||||
}
|
||||
|
||||
if len(attIDs) > 0 {
|
||||
var n int
|
||||
if err := tx.QueryRow(ctx,
|
||||
`SELECT count(*) FROM attachments
|
||||
WHERE chat_id = $1 AND id IN (SELECT unnest($2::text[])::uuid)`,
|
||||
chatID, attIDs).Scan(&n); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
if n != len(attIDs) {
|
||||
return model.Message{}, ErrAttachmentNotFound
|
||||
}
|
||||
}
|
||||
|
||||
msgID := idgen.GenerateUUIDv4()
|
||||
tag, err := tx.Exec(ctx,
|
||||
`INSERT INTO idempotency_keys (user_id, chat_id, key, request_hash, message_id)
|
||||
VALUES ($1,$2,$3,$4,$5)
|
||||
ON CONFLICT (user_id, chat_id, key) DO NOTHING`,
|
||||
senderID, chatID, idemKey, hash, msgID)
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
|
||||
if tag.RowsAffected() == 0 {
|
||||
var storedHash string
|
||||
var m model.Message
|
||||
var textBytes []byte
|
||||
|
||||
if err := tx.QueryRow(ctx, `
|
||||
SELECT k.request_hash, m.id, m.chat_id, m.sender_id, m.text, m.created_at
|
||||
FROM idempotency_keys k
|
||||
JOIN messages m ON m.id = k.message_id
|
||||
WHERE k.user_id=$1 AND k.chat_id=$2 AND k.key=$3
|
||||
`, senderID, chatID, idemKey).Scan(
|
||||
&storedHash, &m.ID, &m.ChatID, &m.SenderID, &textBytes, &m.CreatedAt,
|
||||
); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
|
||||
m.Text = string(textBytes)
|
||||
if storedHash != hash {
|
||||
return model.Message{}, ErrIdempotencyConflict
|
||||
}
|
||||
if m.AttachmentIDs, err = txAttachmentIDs(ctx, tx, m.ID); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
if len(attIDs) > 0 {
|
||||
rows, err := tx.Query(ctx, `SELECT status FROM attachments WHERE id IN
|
||||
(SELECT unnest($1::text[])::uuid) ORDER BY id FOR SHARE`, attIDs)
|
||||
if err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
failed := false
|
||||
for rows.Next() {
|
||||
var state string
|
||||
if err := rows.Scan(&state); err != nil {
|
||||
rows.Close()
|
||||
return model.Message{}, err
|
||||
}
|
||||
failed = failed || state == "failed"
|
||||
}
|
||||
rows.Close()
|
||||
if err := rows.Err(); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
if failed {
|
||||
return model.Message{}, ErrAttachmentFailed
|
||||
}
|
||||
}
|
||||
|
||||
var m model.Message
|
||||
var textBytes []byte
|
||||
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text, created_at)
|
||||
VALUES ($1,$2,$3,$4, clock_timestamp())
|
||||
RETURNING id, chat_id, sender_id, text, created_at
|
||||
`, msgID, chatID, senderID, []byte(text)).Scan(
|
||||
&m.ID, &m.ChatID, &m.SenderID, &textBytes, &m.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
if isCheckViolation(err) {
|
||||
return model.Message{}, ErrValidation
|
||||
}
|
||||
return model.Message{}, err
|
||||
}
|
||||
m.Text = string(textBytes)
|
||||
for i, id := range attIDs {
|
||||
if _, err := tx.Exec(ctx,
|
||||
`INSERT INTO message_attachments (message_id, attachment_id, position) VALUES ($1,$2,$3)`,
|
||||
m.ID, id, i); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
m.AttachmentIDs = attIDs
|
||||
return m, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListMessages(ctx context.Context, chatID, userID, cursorStr string, limit int) ([]model.Message, *string, error) {
|
||||
var isMember bool
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT EXISTS(SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2)`,
|
||||
chatID, userID,
|
||||
).Scan(&isMember)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if !isMember {
|
||||
return nil, nil, ErrChatNotFound
|
||||
}
|
||||
|
||||
var after *cursor.Cursor
|
||||
if cursorStr != "" {
|
||||
dc, err := cursor.Decode(cursorStr)
|
||||
if err != nil || dc.Scope != "messages:"+chatID {
|
||||
return nil, nil, ErrValidation
|
||||
}
|
||||
after = &dc
|
||||
}
|
||||
|
||||
query := `
|
||||
SELECT id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1`
|
||||
args := []any{chatID}
|
||||
|
||||
if after != nil {
|
||||
query += ` AND (created_at, id) > ($2, $3)`
|
||||
args = append(args, after.CreatedAt, after.ID)
|
||||
}
|
||||
query += ` ORDER BY created_at ASC, id ASC LIMIT $` + strconv.Itoa(len(args)+1)
|
||||
args = append(args, limit+1)
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var page []model.Message
|
||||
for rows.Next() {
|
||||
var m model.Message
|
||||
var textBytes []byte
|
||||
|
||||
if err := rows.Scan(
|
||||
&m.ID, &m.ChatID, &m.SenderID, &textBytes, &m.CreatedAt,
|
||||
); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
m.Text = string(textBytes)
|
||||
page = append(page, m)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
|
||||
var next *string
|
||||
if len(page) > limit {
|
||||
last := page[limit-1]
|
||||
nc := cursor.Encode(cursor.Cursor{Scope: "messages:" + chatID, CreatedAt: last.CreatedAt, ID: last.ID})
|
||||
next = &nc
|
||||
page = page[:limit]
|
||||
}
|
||||
if err := s.loadAttachmentIDs(ctx, page); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return page, next, nil
|
||||
}
|
||||
|
||||
func isUniqueViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23505"
|
||||
}
|
||||
|
||||
func isForeignKeyViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23503"
|
||||
}
|
||||
|
||||
func isCheckViolation(err error) bool {
|
||||
var pgErr *pgconn.PgError
|
||||
return errors.As(err, &pgErr) && pgErr.Code == "23514"
|
||||
}
|
||||
|
||||
func ValidMessageBody(s string, hasAttachments bool) bool {
|
||||
if !utf8.ValidString(s) || utf8.RuneCountInString(s) > 4000 {
|
||||
return false
|
||||
}
|
||||
|
||||
hasContent := false
|
||||
for _, r := range s {
|
||||
if !unicode.IsSpace(r) {
|
||||
hasContent = true
|
||||
}
|
||||
}
|
||||
return hasAttachments || hasContent
|
||||
}
|
||||
|
||||
func requestHash(text string, ids []string) string {
|
||||
b, _ := json.Marshal(struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}{text, ids})
|
||||
sum := sha256.Sum256(b)
|
||||
return hex.EncodeToString(sum[:])
|
||||
}
|
||||
|
||||
func (s *Store) GetUserByUsername(ctx context.Context, username string) (model.User, string, error) {
|
||||
var u model.User
|
||||
var passwordHash string
|
||||
|
||||
err := s.pool.QueryRow(ctx,
|
||||
`SELECT id, username, display_name, created_at, password_hash
|
||||
FROM users WHERE username = $1`,
|
||||
username,
|
||||
).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt, &passwordHash)
|
||||
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, "", ErrUsernameNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, "", err
|
||||
}
|
||||
|
||||
return u, passwordHash, nil
|
||||
}
|
||||
Reference in New Issue
Block a user