forked from mtusi2026/mtusi2026lab5
chore: import lab4 baseline
This commit is contained in:
@@ -0,0 +1,25 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/config"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/database"
|
||||
)
|
||||
|
||||
func RunMigrations() error {
|
||||
settings, err := config.LoadMigration()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pool, err := database.Open(context.Background(), database.Config{
|
||||
URL: settings.DatabaseURL, MinConnections: settings.DBMinConns, MaxConnections: settings.DBMaxConns,
|
||||
MaxConnectionAge: settings.DBMaxConnectionAge, MaxConnectionIdle: settings.DBMaxConnectionIdle,
|
||||
HealthCheckPeriod: settings.DBHealthCheckPeriod, ConnectTimeout: settings.DependencyTimeout,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
return database.Migrate(context.Background(), pool, settings.MigrationTimeout)
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"flag"
|
||||
"io"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/config"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/database"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/objectstore"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/postgres"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/reconcile"
|
||||
)
|
||||
|
||||
type reconciliationOutput struct {
|
||||
Mode string `json:"mode"`
|
||||
GracePeriod string `json:"grace_period"`
|
||||
UnreferencedRetention string `json:"unreferenced_retention"`
|
||||
PageSize int `json:"page_size"`
|
||||
DurationMillis int64 `json:"duration_ms"`
|
||||
Report reconcile.Report `json:"report"`
|
||||
}
|
||||
|
||||
func RunReconciliation(arguments []string, output io.Writer) error {
|
||||
flags := flag.NewFlagSet("reconcile-attachments", flag.ContinueOnError)
|
||||
flags.SetOutput(io.Discard)
|
||||
apply := flags.Bool("apply", false, "apply safe repairs")
|
||||
gracePeriod := flags.Duration("grace-period", time.Hour, "minimum anomaly age")
|
||||
retention := flags.Duration("unreferenced-retention", 24*time.Hour, "retention for ready unreferenced attachments")
|
||||
pageSize := flags.Int("page-size", 500, "S3 and PostgreSQL page size")
|
||||
if err := flags.Parse(arguments); err != nil || flags.NArg() != 0 {
|
||||
return errors.New("usage: messenger reconcile-attachments [--apply] [--grace-period=1h] [--unreferenced-retention=24h] [--page-size=500]")
|
||||
}
|
||||
if *apply && *gracePeriod <= 0 {
|
||||
return errors.New("grace-period must be positive in apply mode")
|
||||
}
|
||||
settings, err := config.LoadReconciliation()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
pool, err := database.Open(ctx, database.Config{
|
||||
URL: settings.DatabaseURL, MinConnections: settings.DBMinConns, MaxConnections: settings.DBMaxConns,
|
||||
MaxConnectionAge: settings.DBMaxConnectionAge, MaxConnectionIdle: settings.DBMaxConnectionIdle,
|
||||
HealthCheckPeriod: settings.DBHealthCheckPeriod, ConnectTimeout: settings.DependencyTimeout,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
objects, err := objectstore.New(objectstore.Config{
|
||||
Endpoint: settings.S3Endpoint, Region: settings.S3Region, Bucket: settings.S3Bucket,
|
||||
AccessKey: settings.S3AccessKey, SecretKey: settings.S3SecretKey,
|
||||
UseTLS: settings.S3UseTLS, Timeout: settings.S3Timeout,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
reconciler, err := reconcile.New(postgres.New(pool), objects, reconcile.Config{
|
||||
Prefix: "attachments/", PageSize: *pageSize, GraceTime: *gracePeriod,
|
||||
UnreferencedRetention: *retention, Apply: *apply,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
started := time.Now()
|
||||
report, err := reconciler.Run(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
mode := "dry-run"
|
||||
if *apply {
|
||||
mode = "apply"
|
||||
}
|
||||
return json.NewEncoder(output).Encode(reconciliationOutput{
|
||||
Mode: mode, GracePeriod: gracePeriod.String(), UnreferencedRetention: retention.String(),
|
||||
PageSize: *pageSize, DurationMillis: time.Since(started).Milliseconds(), Report: report,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"io"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestApplyReconciliationRequiresPositiveGracePeriod(t *testing.T) {
|
||||
err := RunReconciliation([]string{"--apply", "--grace-period=0"}, io.Discard)
|
||||
require.EqualError(t, err, "grace-period must be positive in apply mode")
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/config"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/database"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/messenger/attachment"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/messenger/httpapi"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/objectstore"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/password"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/postgres"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/session"
|
||||
)
|
||||
|
||||
func RunServer(logger *slog.Logger) error {
|
||||
settings, err := config.LoadServer()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
instanceID, err := os.Hostname()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pool, err := database.Open(context.Background(), databaseConfig(settings))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
sessions, err := session.New(settings.CacheURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = sessions.Close() }()
|
||||
passwords, err := password.New(password.Config{
|
||||
MemoryKiB: settings.PasswordMemoryKiB, Iterations: settings.PasswordIterations,
|
||||
Parallelism: settings.PasswordParallelism, SaltLength: settings.PasswordSaltLength,
|
||||
KeyLength: settings.PasswordKeyLength,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
objects, err := objectstore.New(objectStoreConfig(settings))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
repository := postgres.New(pool)
|
||||
attachments, err := attachment.NewService(logger, repository, objects, attachment.Config{
|
||||
MaxBytes: settings.AttachmentMaxBytes, MaxPixels: settings.AttachmentMaxPixels,
|
||||
BodyMemoryBytes: settings.AttachmentBodyMemory, DecodeMemoryBytes: settings.AttachmentDecodeMemory,
|
||||
CleanupTimeout: settings.RequestTimeout,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
app := httpapi.NewServer(logger, httpapi.Dependencies{
|
||||
Users: repository, Chats: repository, Messages: repository, Attachments: attachments,
|
||||
Sessions: sessions, Passwords: passwords, Database: repository, Objects: objects,
|
||||
}, httpapi.Config{
|
||||
SessionTTL: settings.SessionTTL, IdempotencyTTL: settings.IdempotencyTTL,
|
||||
RequestTTL: settings.RequestTimeout, InstanceID: instanceID, SwaggerPort: settings.SwaggerPort,
|
||||
})
|
||||
server := &http.Server{
|
||||
Addr: settings.Address, Handler: app.Handler(), ReadHeaderTimeout: settings.HTTPReadHeaderTimeout,
|
||||
ReadTimeout: settings.HTTPReadTimeout, WriteTimeout: settings.HTTPWriteTimeout,
|
||||
IdleTimeout: settings.HTTPIdleTimeout,
|
||||
}
|
||||
listener, err := net.Listen("tcp", server.Addr)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
serveResult := make(chan error, 1)
|
||||
go func() { serveResult <- server.Serve(listener) }()
|
||||
logger.Info("server started", "address", server.Addr)
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
select {
|
||||
case err := <-serveResult:
|
||||
return err
|
||||
case <-ctx.Done():
|
||||
logger.Info("shutdown requested")
|
||||
app.SetReady(false)
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), settings.HTTPShutdownTimeout)
|
||||
defer cancel()
|
||||
if err := server.Shutdown(shutdownCtx); err != nil {
|
||||
_ = server.Close()
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func databaseConfig(settings config.ServerConfig) database.Config {
|
||||
return database.Config{
|
||||
URL: settings.DatabaseURL, MinConnections: settings.DBMinConns, MaxConnections: settings.DBMaxConns,
|
||||
MaxConnectionAge: settings.DBMaxConnectionAge, MaxConnectionIdle: settings.DBMaxConnectionIdle,
|
||||
HealthCheckPeriod: settings.DBHealthCheckPeriod, ConnectTimeout: settings.DependencyTimeout,
|
||||
}
|
||||
}
|
||||
|
||||
func objectStoreConfig(settings config.ServerConfig) objectstore.Config {
|
||||
return objectstore.Config{
|
||||
Endpoint: settings.S3Endpoint, Region: settings.S3Region, Bucket: settings.S3Bucket,
|
||||
AccessKey: settings.S3AccessKey, SecretKey: settings.S3SecretKey,
|
||||
UseTLS: settings.S3UseTLS, Timeout: settings.S3Timeout,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,400 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type ServerConfig struct {
|
||||
Address string
|
||||
DatabaseURL string
|
||||
CacheURL string
|
||||
SessionTTL time.Duration
|
||||
IdempotencyTTL time.Duration
|
||||
DBMaxConns int32
|
||||
DBMinConns int32
|
||||
DBMaxConnectionAge time.Duration
|
||||
DBMaxConnectionIdle time.Duration
|
||||
DBHealthCheckPeriod time.Duration
|
||||
DependencyTimeout time.Duration
|
||||
RequestTimeout time.Duration
|
||||
HTTPReadHeaderTimeout time.Duration
|
||||
HTTPReadTimeout time.Duration
|
||||
HTTPWriteTimeout time.Duration
|
||||
HTTPIdleTimeout time.Duration
|
||||
HTTPShutdownTimeout time.Duration
|
||||
PasswordMemoryKiB uint32
|
||||
PasswordIterations uint32
|
||||
PasswordParallelism uint8
|
||||
PasswordSaltLength uint32
|
||||
PasswordKeyLength uint32
|
||||
SwaggerPort string
|
||||
S3Endpoint string
|
||||
S3Region string
|
||||
S3Bucket string
|
||||
S3AccessKey string
|
||||
S3SecretKey string
|
||||
S3UseTLS bool
|
||||
S3Timeout time.Duration
|
||||
AttachmentMaxBytes int64
|
||||
AttachmentMaxPixels int64
|
||||
AttachmentBodyMemory int64
|
||||
AttachmentDecodeMemory int64
|
||||
}
|
||||
|
||||
type MigrationConfig struct {
|
||||
DatabaseURL string
|
||||
DBMaxConns int32
|
||||
DBMinConns int32
|
||||
DBMaxConnectionAge time.Duration
|
||||
DBMaxConnectionIdle time.Duration
|
||||
DBHealthCheckPeriod time.Duration
|
||||
DependencyTimeout time.Duration
|
||||
MigrationTimeout time.Duration
|
||||
}
|
||||
|
||||
type ReconciliationConfig struct {
|
||||
DatabaseURL string
|
||||
DBMaxConns int32
|
||||
DBMinConns int32
|
||||
DBMaxConnectionAge time.Duration
|
||||
DBMaxConnectionIdle time.Duration
|
||||
DBHealthCheckPeriod time.Duration
|
||||
DependencyTimeout time.Duration
|
||||
S3Endpoint string
|
||||
S3Region string
|
||||
S3Bucket string
|
||||
S3AccessKey string
|
||||
S3SecretKey string
|
||||
S3UseTLS bool
|
||||
S3Timeout time.Duration
|
||||
}
|
||||
|
||||
type databaseConfig struct {
|
||||
url string
|
||||
maxConns int
|
||||
minConns int
|
||||
maxConnectionAge time.Duration
|
||||
maxConnectionIdle time.Duration
|
||||
healthCheckPeriod time.Duration
|
||||
dependencyTimeout time.Duration
|
||||
}
|
||||
|
||||
type objectStorageConfig struct {
|
||||
endpoint string
|
||||
region string
|
||||
bucket string
|
||||
accessKey string
|
||||
secretKey string
|
||||
useTLS bool
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
func LoadServer() (ServerConfig, error) {
|
||||
values := viper.New()
|
||||
values.AutomaticEnv()
|
||||
|
||||
host, err := requiredString(values, "APP_HOST")
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
port, err := requiredPort(values, "APP_PORT")
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
database, err := loadDatabaseConfig(values)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
cacheURL, err := requiredString(values, "CACHE_URL")
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
store, err := requiredString(values, "SESSION_STORE")
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
if store != "valkey" {
|
||||
return ServerConfig{}, errors.New("SESSION_STORE must be valkey")
|
||||
}
|
||||
|
||||
sessionTTL, err := seconds(values, "SESSION_TTL_SECONDS", 1, 86400*30)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
idempotencyTTL, err := seconds(values, "IDEMPOTENCY_TTL_SECONDS", 86400, 86400*30)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
requestTimeout, err := seconds(values, "REQUEST_TIMEOUT_SECONDS", 1, 300)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
readHeaderTimeout, err := seconds(values, "HTTP_READ_HEADER_TIMEOUT_SECONDS", 1, 300)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
readTimeout, err := seconds(values, "HTTP_READ_TIMEOUT_SECONDS", 1, 300)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
writeTimeout, err := seconds(values, "HTTP_WRITE_TIMEOUT_SECONDS", 1, 300)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
idleTimeout, err := seconds(values, "HTTP_IDLE_TIMEOUT_SECONDS", 1, 3600)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
shutdownTimeout, err := seconds(values, "HTTP_SHUTDOWN_TIMEOUT_SECONDS", 1, 300)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
passwordMemory, err := integer(values, "PASSWORD_MEMORY_KIB", 8*1024, 1024*1024)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
passwordIterations, err := integer(values, "PASSWORD_ITERATIONS", 1, 20)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
passwordParallelism, err := integer(values, "PASSWORD_PARALLELISM", 1, 255)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
passwordSaltLength, err := integer(values, "PASSWORD_SALT_LENGTH", 8, 1024)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
passwordKeyLength, err := integer(values, "PASSWORD_KEY_LENGTH", 16, 1024)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
swaggerPort, err := requiredPort(values, "SWAGGER_PORT")
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
storage, err := loadObjectStorageConfig(values)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
attachmentMaxBytes, err := integer(values, "ATTACHMENT_MAX_BYTES", 1, 10*1024*1024)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
attachmentMaxPixels, err := integer(values, "ATTACHMENT_MAX_PIXELS", 1, 40_000_000)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
attachmentBodyMemory, err := integer(values, "ATTACHMENT_BODY_MEMORY_BYTES", 1, 1024*1024*1024)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
if int64(attachmentBodyMemory) < int64(attachmentMaxBytes) {
|
||||
return ServerConfig{}, fmt.Errorf("ATTACHMENT_BODY_MEMORY_BYTES: must be at least %d", attachmentMaxBytes)
|
||||
}
|
||||
attachmentDecodeMemory, err := integer(values, "ATTACHMENT_DECODE_MEMORY_BYTES", 1, 1024*1024*1024)
|
||||
if err != nil {
|
||||
return ServerConfig{}, err
|
||||
}
|
||||
minimumDecodeMemory := int64(attachmentMaxPixels) * 8
|
||||
if int64(attachmentDecodeMemory) < minimumDecodeMemory {
|
||||
return ServerConfig{}, fmt.Errorf("ATTACHMENT_DECODE_MEMORY_BYTES: must be at least %d", minimumDecodeMemory)
|
||||
}
|
||||
|
||||
return ServerConfig{
|
||||
Address: net.JoinHostPort(host, port), DatabaseURL: database.url, CacheURL: cacheURL,
|
||||
SessionTTL: sessionTTL, IdempotencyTTL: idempotencyTTL,
|
||||
DBMaxConns: int32(database.maxConns), DBMinConns: int32(database.minConns),
|
||||
DBMaxConnectionAge: database.maxConnectionAge, DBMaxConnectionIdle: database.maxConnectionIdle,
|
||||
DBHealthCheckPeriod: database.healthCheckPeriod, DependencyTimeout: database.dependencyTimeout,
|
||||
RequestTimeout: requestTimeout,
|
||||
HTTPReadHeaderTimeout: readHeaderTimeout, HTTPReadTimeout: readTimeout,
|
||||
HTTPWriteTimeout: writeTimeout, HTTPIdleTimeout: idleTimeout,
|
||||
HTTPShutdownTimeout: shutdownTimeout, PasswordMemoryKiB: uint32(passwordMemory),
|
||||
PasswordIterations: uint32(passwordIterations), PasswordParallelism: uint8(passwordParallelism),
|
||||
PasswordSaltLength: uint32(passwordSaltLength), PasswordKeyLength: uint32(passwordKeyLength),
|
||||
SwaggerPort: swaggerPort, S3Endpoint: storage.endpoint, S3Region: storage.region, S3Bucket: storage.bucket,
|
||||
S3AccessKey: storage.accessKey, S3SecretKey: storage.secretKey,
|
||||
S3UseTLS: storage.useTLS, S3Timeout: storage.timeout,
|
||||
AttachmentMaxBytes: int64(attachmentMaxBytes), AttachmentMaxPixels: int64(attachmentMaxPixels),
|
||||
AttachmentBodyMemory: int64(attachmentBodyMemory),
|
||||
AttachmentDecodeMemory: int64(attachmentDecodeMemory),
|
||||
}, nil
|
||||
}
|
||||
|
||||
func LoadMigration() (MigrationConfig, error) {
|
||||
values := viper.New()
|
||||
values.AutomaticEnv()
|
||||
database, err := loadDatabaseConfig(values)
|
||||
if err != nil {
|
||||
return MigrationConfig{}, err
|
||||
}
|
||||
migrationTimeout, err := seconds(values, "MIGRATION_TIMEOUT_SECONDS", 1, 600)
|
||||
if err != nil {
|
||||
return MigrationConfig{}, err
|
||||
}
|
||||
return MigrationConfig{
|
||||
DatabaseURL: database.url, DBMaxConns: int32(database.maxConns), DBMinConns: int32(database.minConns),
|
||||
DBMaxConnectionAge: database.maxConnectionAge, DBMaxConnectionIdle: database.maxConnectionIdle,
|
||||
DBHealthCheckPeriod: database.healthCheckPeriod, DependencyTimeout: database.dependencyTimeout,
|
||||
MigrationTimeout: migrationTimeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func LoadReconciliation() (ReconciliationConfig, error) {
|
||||
values := viper.New()
|
||||
values.AutomaticEnv()
|
||||
database, err := loadDatabaseConfig(values)
|
||||
if err != nil {
|
||||
return ReconciliationConfig{}, err
|
||||
}
|
||||
storage, err := loadObjectStorageConfig(values)
|
||||
if err != nil {
|
||||
return ReconciliationConfig{}, err
|
||||
}
|
||||
return ReconciliationConfig{
|
||||
DatabaseURL: database.url, DBMaxConns: int32(database.maxConns), DBMinConns: int32(database.minConns),
|
||||
DBMaxConnectionAge: database.maxConnectionAge, DBMaxConnectionIdle: database.maxConnectionIdle,
|
||||
DBHealthCheckPeriod: database.healthCheckPeriod, DependencyTimeout: database.dependencyTimeout,
|
||||
S3Endpoint: storage.endpoint, S3Region: storage.region, S3Bucket: storage.bucket,
|
||||
S3AccessKey: storage.accessKey, S3SecretKey: storage.secretKey,
|
||||
S3UseTLS: storage.useTLS, S3Timeout: storage.timeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func loadObjectStorageConfig(values *viper.Viper) (objectStorageConfig, error) {
|
||||
endpoint, err := requiredString(values, "S3_ENDPOINT")
|
||||
if err != nil {
|
||||
return objectStorageConfig{}, err
|
||||
}
|
||||
region, err := requiredString(values, "S3_REGION")
|
||||
if err != nil {
|
||||
return objectStorageConfig{}, err
|
||||
}
|
||||
bucket, err := requiredString(values, "S3_BUCKET")
|
||||
if err != nil {
|
||||
return objectStorageConfig{}, err
|
||||
}
|
||||
accessKey, err := requiredString(values, "S3_ACCESS_KEY")
|
||||
if err != nil {
|
||||
return objectStorageConfig{}, err
|
||||
}
|
||||
secretKey, err := requiredString(values, "S3_SECRET_KEY")
|
||||
if err != nil {
|
||||
return objectStorageConfig{}, err
|
||||
}
|
||||
useTLS, err := boolean(values, "S3_USE_TLS")
|
||||
if err != nil {
|
||||
return objectStorageConfig{}, err
|
||||
}
|
||||
timeout, err := seconds(values, "S3_TIMEOUT_SECONDS", 1, 300)
|
||||
if err != nil {
|
||||
return objectStorageConfig{}, err
|
||||
}
|
||||
return objectStorageConfig{
|
||||
endpoint: endpoint, region: region, bucket: bucket, accessKey: accessKey,
|
||||
secretKey: secretKey, useTLS: useTLS, timeout: timeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func loadDatabaseConfig(values *viper.Viper) (databaseConfig, error) {
|
||||
databaseURL, err := requiredString(values, "DATABASE_URL")
|
||||
if err != nil {
|
||||
return databaseConfig{}, err
|
||||
}
|
||||
maxConns, err := integer(values, "DB_MAX_CONNS", 1, 100)
|
||||
if err != nil {
|
||||
return databaseConfig{}, err
|
||||
}
|
||||
minConns, err := integer(values, "DB_MIN_CONNS", 0, maxConns)
|
||||
if err != nil {
|
||||
return databaseConfig{}, err
|
||||
}
|
||||
maxConnectionAge, err := seconds(values, "DB_MAX_CONNECTION_AGE_SECONDS", 1, 86400)
|
||||
if err != nil {
|
||||
return databaseConfig{}, err
|
||||
}
|
||||
maxConnectionIdle, err := seconds(values, "DB_MAX_CONNECTION_IDLE_SECONDS", 1, 86400)
|
||||
if err != nil {
|
||||
return databaseConfig{}, err
|
||||
}
|
||||
healthCheckPeriod, err := seconds(values, "DB_HEALTH_CHECK_SECONDS", 1, 3600)
|
||||
if err != nil {
|
||||
return databaseConfig{}, err
|
||||
}
|
||||
dependencyTimeout, err := seconds(values, "DEPENDENCY_TIMEOUT_SECONDS", 1, 60)
|
||||
if err != nil {
|
||||
return databaseConfig{}, err
|
||||
}
|
||||
return databaseConfig{
|
||||
url: databaseURL, maxConns: maxConns, minConns: minConns,
|
||||
maxConnectionAge: maxConnectionAge, maxConnectionIdle: maxConnectionIdle,
|
||||
healthCheckPeriod: healthCheckPeriod, dependencyTimeout: dependencyTimeout,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func requiredString(values *viper.Viper, name string) (string, error) {
|
||||
value := strings.TrimSpace(values.GetString(name))
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("%s is required", name)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func requiredPort(values *viper.Viper, name string) (string, error) {
|
||||
value, err := requiredString(values, name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err := integerValue(value, 1, 65535); err != nil {
|
||||
return "", fmt.Errorf("%s: %w", name, err)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func seconds(values *viper.Viper, name string, minimum, maximum int) (time.Duration, error) {
|
||||
value, err := integer(values, name, minimum, maximum)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
return time.Duration(value) * time.Second, nil
|
||||
}
|
||||
|
||||
func integer(values *viper.Viper, name string, minimum, maximum int) (int, error) {
|
||||
value, err := requiredString(values, name)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
parsed, err := integerValue(value, minimum, maximum)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("%s: %w", name, err)
|
||||
}
|
||||
return parsed, nil
|
||||
}
|
||||
|
||||
func integerValue(value string, minimum, maximum int) (int, error) {
|
||||
parsed, err := strconv.Atoi(value)
|
||||
if err != nil || parsed < minimum || parsed > maximum {
|
||||
return 0, fmt.Errorf("must be between %d and %d", minimum, maximum)
|
||||
}
|
||||
return parsed, nil
|
||||
}
|
||||
|
||||
func boolean(values *viper.Viper, name string) (bool, error) {
|
||||
value, err := requiredString(values, name)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
parsed, err := strconv.ParseBool(value)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("%s: must be true or false", name)
|
||||
}
|
||||
return parsed, nil
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestLoadReconciliationDoesNotRequireServerSettings(t *testing.T) {
|
||||
values := map[string]string{
|
||||
"DATABASE_URL": "postgres://user:password@postgres:5432/messenger",
|
||||
"DB_MIN_CONNS": "0", "DB_MAX_CONNS": "4",
|
||||
"DB_MAX_CONNECTION_AGE_SECONDS": "300", "DB_MAX_CONNECTION_IDLE_SECONDS": "60",
|
||||
"DB_HEALTH_CHECK_SECONDS": "30", "DEPENDENCY_TIMEOUT_SECONDS": "5",
|
||||
"S3_ENDPOINT": "s3:9000", "S3_REGION": "us-east-1", "S3_BUCKET": "attachments",
|
||||
"S3_ACCESS_KEY": "application", "S3_SECRET_KEY": "application-secret",
|
||||
"S3_USE_TLS": "false", "S3_TIMEOUT_SECONDS": "5",
|
||||
}
|
||||
for name, value := range values {
|
||||
t.Setenv(name, value)
|
||||
}
|
||||
t.Setenv("APP_HOST", "")
|
||||
t.Setenv("CACHE_URL", "")
|
||||
t.Setenv("SWAGGER_PORT", "")
|
||||
|
||||
settings, err := LoadReconciliation()
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "attachments", settings.S3Bucket)
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/migrations"
|
||||
)
|
||||
|
||||
var (
|
||||
errURLRequired = errors.New("database URL is required")
|
||||
errMinConnections = errors.New("minimum database connections must not be negative")
|
||||
errMaxConnections = errors.New("maximum database connections must be positive")
|
||||
errConnectionRange = errors.New("minimum database connections exceed maximum")
|
||||
errMaxConnectionAge = errors.New("maximum database connection age must be positive")
|
||||
errMaxConnectionIdle = errors.New("maximum database connection idle time must be positive")
|
||||
errHealthCheckPeriod = errors.New("database health check period must be positive")
|
||||
errConnectionTimeout = errors.New("database connection timeout must be positive")
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
URL string
|
||||
MinConnections int32
|
||||
MaxConnections int32
|
||||
MaxConnectionAge time.Duration
|
||||
MaxConnectionIdle time.Duration
|
||||
HealthCheckPeriod time.Duration
|
||||
ConnectTimeout time.Duration
|
||||
}
|
||||
|
||||
func Open(ctx context.Context, config Config) (*pgxpool.Pool, error) {
|
||||
if err := validateConfig(config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
poolConfig, err := pgxpool.ParseConfig(config.URL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse database configuration: %w", err)
|
||||
}
|
||||
poolConfig.MinConns = config.MinConnections
|
||||
poolConfig.MaxConns = config.MaxConnections
|
||||
poolConfig.MaxConnLifetime = config.MaxConnectionAge
|
||||
poolConfig.MaxConnIdleTime = config.MaxConnectionIdle
|
||||
poolConfig.HealthCheckPeriod = config.HealthCheckPeriod
|
||||
|
||||
connectCtx, cancel := context.WithTimeout(ctx, config.ConnectTimeout)
|
||||
defer cancel()
|
||||
pool, err := pgxpool.NewWithConfig(connectCtx, poolConfig)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create database pool: %w", err)
|
||||
}
|
||||
if err := pool.Ping(connectCtx); err != nil {
|
||||
pool.Close()
|
||||
return nil, fmt.Errorf("ping database: %w", err)
|
||||
}
|
||||
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
func Migrate(ctx context.Context, pool *pgxpool.Pool, timeout time.Duration) error {
|
||||
if timeout <= 0 {
|
||||
return errors.New("database migration timeout must be positive")
|
||||
}
|
||||
migrationCtx, cancel := context.WithTimeout(ctx, timeout)
|
||||
defer cancel()
|
||||
return applyMigrations(migrationCtx, pool, migrations.FS)
|
||||
}
|
||||
|
||||
func validateConfig(config Config) error {
|
||||
switch {
|
||||
case config.URL == "":
|
||||
return errURLRequired
|
||||
case config.MinConnections < 0:
|
||||
return errMinConnections
|
||||
case config.MaxConnections < 1:
|
||||
return errMaxConnections
|
||||
case config.MinConnections > config.MaxConnections:
|
||||
return errConnectionRange
|
||||
case config.MaxConnectionAge <= 0:
|
||||
return errMaxConnectionAge
|
||||
case config.MaxConnectionIdle <= 0:
|
||||
return errMaxConnectionIdle
|
||||
case config.HealthCheckPeriod <= 0:
|
||||
return errHealthCheckPeriod
|
||||
case config.ConnectTimeout <= 0:
|
||||
return errConnectionTimeout
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strconv"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
const (
|
||||
migrationLockID int64 = 0x4d54555349324c42
|
||||
migrationUnlockTimeout = 5 * time.Second
|
||||
)
|
||||
|
||||
var migrationNamePattern = regexp.MustCompile(`^(\d+)_([a-z0-9_]+)\.sql$`)
|
||||
|
||||
type migration struct {
|
||||
version int64
|
||||
name string
|
||||
checksum string
|
||||
sql string
|
||||
}
|
||||
|
||||
func applyMigrations(ctx context.Context, pool *pgxpool.Pool, migrationFS fs.FS) (returnErr error) {
|
||||
migrations, err := readMigrations(migrationFS)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
connection, err := pool.Acquire(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("acquire connection for migrations: %w", err)
|
||||
}
|
||||
defer connection.Release()
|
||||
if _, err := connection.Exec(ctx, "SELECT pg_advisory_lock($1)", migrationLockID); err != nil {
|
||||
return fmt.Errorf("lock migrations: %w", err)
|
||||
}
|
||||
defer func() {
|
||||
unlockCtx, cancel := context.WithTimeout(context.Background(), migrationUnlockTimeout)
|
||||
defer cancel()
|
||||
if _, err := connection.Exec(unlockCtx, "SELECT pg_advisory_unlock($1)", migrationLockID); err != nil {
|
||||
_ = connection.Conn().Close(unlockCtx)
|
||||
if returnErr == nil {
|
||||
returnErr = fmt.Errorf("unlock migrations: %w", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
if _, err := connection.Exec(ctx, `
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version BIGINT PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
checksum TEXT NOT NULL,
|
||||
applied_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp()
|
||||
)`); err != nil {
|
||||
return fmt.Errorf("create migration history: %w", err)
|
||||
}
|
||||
for _, migration := range migrations {
|
||||
if err := applyMigration(ctx, connection, migration); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func readMigrations(migrationFS fs.FS) ([]migration, error) {
|
||||
entries, err := fs.ReadDir(migrationFS, ".")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read embedded migrations: %w", err)
|
||||
}
|
||||
migrations := make([]migration, 0, len(entries))
|
||||
versions := make(map[int64]string)
|
||||
for _, entry := range entries {
|
||||
if entry.IsDir() || filepath.Ext(entry.Name()) != ".sql" {
|
||||
continue
|
||||
}
|
||||
matches := migrationNamePattern.FindStringSubmatch(entry.Name())
|
||||
if matches == nil {
|
||||
return nil, fmt.Errorf("invalid migration filename %q", entry.Name())
|
||||
}
|
||||
version, err := strconv.ParseInt(matches[1], 10, 64)
|
||||
if err != nil || version < 1 {
|
||||
return nil, fmt.Errorf("invalid migration version in %q", entry.Name())
|
||||
}
|
||||
if previous, exists := versions[version]; exists {
|
||||
return nil, fmt.Errorf("migration version %d is used by %q and %q", version, previous, entry.Name())
|
||||
}
|
||||
data, err := fs.ReadFile(migrationFS, entry.Name())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read migration %q: %w", entry.Name(), err)
|
||||
}
|
||||
hash := sha256.Sum256(data)
|
||||
versions[version] = entry.Name()
|
||||
migrations = append(migrations, migration{
|
||||
version: version,
|
||||
name: entry.Name(),
|
||||
checksum: hex.EncodeToString(hash[:]),
|
||||
sql: string(data),
|
||||
})
|
||||
}
|
||||
if len(migrations) == 0 {
|
||||
return nil, errors.New("no database migrations found")
|
||||
}
|
||||
sort.Slice(migrations, func(i, j int) bool {
|
||||
return migrations[i].version < migrations[j].version
|
||||
})
|
||||
return migrations, nil
|
||||
}
|
||||
|
||||
func applyMigration(ctx context.Context, connection *pgxpool.Conn, migration migration) error {
|
||||
var checksum string
|
||||
err := connection.QueryRow(ctx, "SELECT checksum FROM schema_migrations WHERE version = $1", migration.version).Scan(&checksum)
|
||||
switch {
|
||||
case err == nil && checksum != migration.checksum:
|
||||
return fmt.Errorf("migration %q checksum does not match applied version", migration.name)
|
||||
case err == nil:
|
||||
return nil
|
||||
case !errors.Is(err, pgx.ErrNoRows):
|
||||
return fmt.Errorf("read migration %q state: %w", migration.name, err)
|
||||
}
|
||||
|
||||
transaction, err := connection.Begin(ctx)
|
||||
if err != nil {
|
||||
return fmt.Errorf("begin migration %q: %w", migration.name, err)
|
||||
}
|
||||
defer func() {
|
||||
_ = transaction.Rollback(context.WithoutCancel(ctx))
|
||||
}()
|
||||
if _, err := transaction.Exec(ctx, migration.sql, pgx.QueryExecModeSimpleProtocol); err != nil {
|
||||
return fmt.Errorf("apply migration %q: %w", migration.name, err)
|
||||
}
|
||||
if _, err := transaction.Exec(ctx, `
|
||||
INSERT INTO schema_migrations (version, name, checksum)
|
||||
VALUES ($1, $2, $3)`, migration.version, migration.name, migration.checksum); err != nil {
|
||||
return fmt.Errorf("record migration %q: %w", migration.name, err)
|
||||
}
|
||||
if err := transaction.Commit(ctx); err != nil {
|
||||
return fmt.Errorf("commit migration %q: %w", migration.name, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package logger
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"os"
|
||||
)
|
||||
|
||||
func New() *slog.Logger {
|
||||
return slog.New(slog.NewJSONHandler(os.Stdout, nil))
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"image"
|
||||
_ "image/jpeg"
|
||||
_ "image/png"
|
||||
"io"
|
||||
"log/slog"
|
||||
"math"
|
||||
"mime"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/sync/semaphore"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
ChatForUser(context.Context, string, string) (model.Chat, error)
|
||||
CreatePendingAttachment(context.Context, model.Attachment) (model.Attachment, error)
|
||||
MarkAttachmentReady(context.Context, string, string) (model.Attachment, error)
|
||||
DeletePendingAttachment(context.Context, string, string) error
|
||||
AttachmentByStorage(context.Context, string, string) (model.Attachment, error)
|
||||
AttachmentForUser(context.Context, string, string) (model.Attachment, error)
|
||||
}
|
||||
|
||||
type ObjectStore interface {
|
||||
Put(context.Context, string, string, []byte) error
|
||||
Get(context.Context, string) (io.ReadCloser, error)
|
||||
Delete(context.Context, string) error
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
MaxBytes int64
|
||||
MaxPixels int64
|
||||
BodyMemoryBytes int64
|
||||
DecodeMemoryBytes int64
|
||||
CleanupTimeout time.Duration
|
||||
}
|
||||
|
||||
type Upload struct {
|
||||
ChatID string
|
||||
OwnerID string
|
||||
Filename string
|
||||
ContentType string
|
||||
ContentLength int64
|
||||
Body io.Reader
|
||||
}
|
||||
|
||||
type Content struct {
|
||||
Attachment model.Attachment
|
||||
Body io.ReadCloser
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
repository Repository
|
||||
objects ObjectStore
|
||||
config Config
|
||||
bodyMemory *semaphore.Weighted
|
||||
decodeMemory *semaphore.Weighted
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func NewService(logger *slog.Logger, repository Repository, objects ObjectStore, config Config) (*Service, error) {
|
||||
if config.MaxBytes < 1 || config.MaxPixels < 1 || config.MaxPixels > math.MaxInt64/8 || config.CleanupTimeout <= 0 {
|
||||
return nil, errors.New("invalid attachment service configuration")
|
||||
}
|
||||
if config.BodyMemoryBytes < config.MaxBytes {
|
||||
return nil, errors.New("attachment body memory must fit one maximum upload")
|
||||
}
|
||||
if config.DecodeMemoryBytes < config.MaxPixels*8 {
|
||||
return nil, errors.New("attachment decode memory must fit one maximum image")
|
||||
}
|
||||
return &Service{
|
||||
repository: repository, objects: objects, config: config,
|
||||
bodyMemory: semaphore.NewWeighted(config.BodyMemoryBytes),
|
||||
decodeMemory: semaphore.NewWeighted(config.DecodeMemoryBytes), logger: logger,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) Upload(ctx context.Context, input Upload) (model.Attachment, error) {
|
||||
if _, err := s.repository.ChatForUser(ctx, input.ChatID, input.OwnerID); err != nil {
|
||||
return model.Attachment{}, mapDependencyError(err)
|
||||
}
|
||||
data, contentType, release, err := s.readImage(input)
|
||||
if err != nil {
|
||||
return model.Attachment{}, err
|
||||
}
|
||||
defer release()
|
||||
|
||||
attachmentID := uuid.NewString()
|
||||
objectKey := "attachments/" + uuid.NewString() + "/original"
|
||||
digest := sha256.Sum256(data)
|
||||
pending, err := s.repository.CreatePendingAttachment(ctx, model.Attachment{
|
||||
ID: attachmentID, ChatID: input.ChatID, OwnerID: input.OwnerID, Filename: input.Filename,
|
||||
ContentType: contentType, SizeBytes: int64(len(data)), SHA256: hex.EncodeToString(digest[:]),
|
||||
ObjectKey: objectKey, Status: model.AttachmentPending,
|
||||
})
|
||||
if err != nil {
|
||||
return model.Attachment{}, mapDependencyError(err)
|
||||
}
|
||||
if err := s.objects.Put(ctx, objectKey, contentType, data); err != nil {
|
||||
s.deletePending(pending.ID, objectKey)
|
||||
return model.Attachment{}, model.ErrUnavailable
|
||||
}
|
||||
attachment, err := s.repository.MarkAttachmentReady(ctx, pending.ID, objectKey)
|
||||
if err == nil {
|
||||
return attachment, nil
|
||||
}
|
||||
return s.resolveReadyOutcome(pending.ID, objectKey)
|
||||
}
|
||||
|
||||
func (s *Service) resolveReadyOutcome(attachmentID, objectKey string) (model.Attachment, error) {
|
||||
cleanupCtx, cancel := context.WithTimeout(context.Background(), s.config.CleanupTimeout)
|
||||
defer cancel()
|
||||
stored, err := s.repository.AttachmentByStorage(cleanupCtx, attachmentID, objectKey)
|
||||
if err == nil && stored.Status == model.AttachmentReady {
|
||||
return stored, nil
|
||||
}
|
||||
if err == nil && stored.Status == model.AttachmentPending {
|
||||
if deleteErr := s.objects.Delete(cleanupCtx, objectKey); deleteErr != nil {
|
||||
s.logger.Error("attachment compensation failed", "object_key", objectKey, "error", deleteErr)
|
||||
return model.Attachment{}, model.ErrUnavailable
|
||||
}
|
||||
if deleteErr := s.repository.DeletePendingAttachment(cleanupCtx, attachmentID, objectKey); deleteErr != nil {
|
||||
s.logger.Error("pending attachment cleanup failed", "attachment_id", attachmentID, "error", deleteErr)
|
||||
}
|
||||
return model.Attachment{}, model.ErrUnavailable
|
||||
}
|
||||
if errors.Is(err, model.ErrNotFound) {
|
||||
if deleteErr := s.objects.Delete(cleanupCtx, objectKey); deleteErr != nil {
|
||||
s.logger.Error("orphan attachment compensation failed", "object_key", objectKey, "error", deleteErr)
|
||||
}
|
||||
return model.Attachment{}, model.ErrUnavailable
|
||||
}
|
||||
s.logger.Error("attachment outcome is unknown", "attachment_id", attachmentID, "error", err)
|
||||
return model.Attachment{}, model.ErrUnavailable
|
||||
}
|
||||
|
||||
func (s *Service) deletePending(attachmentID, objectKey string) {
|
||||
cleanupCtx, cancel := context.WithTimeout(context.Background(), s.config.CleanupTimeout)
|
||||
defer cancel()
|
||||
if err := s.repository.DeletePendingAttachment(cleanupCtx, attachmentID, objectKey); err != nil {
|
||||
s.logger.Error("pending attachment cleanup failed", "attachment_id", attachmentID, "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Service) Metadata(ctx context.Context, attachmentID, userID string) (model.Attachment, error) {
|
||||
attachment, err := s.repository.AttachmentForUser(ctx, attachmentID, userID)
|
||||
if err != nil {
|
||||
return model.Attachment{}, mapDependencyError(err)
|
||||
}
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *Service) Content(ctx context.Context, attachmentID, userID string) (Content, error) {
|
||||
attachment, err := s.Metadata(ctx, attachmentID, userID)
|
||||
if err != nil {
|
||||
return Content{}, err
|
||||
}
|
||||
body, err := s.objects.Get(ctx, attachment.ObjectKey)
|
||||
if err != nil {
|
||||
return Content{}, model.ErrUnavailable
|
||||
}
|
||||
return Content{Attachment: attachment, Body: body}, nil
|
||||
}
|
||||
|
||||
func (s *Service) readImage(input Upload) ([]byte, string, func(), error) {
|
||||
mediaType, parameters, err := mime.ParseMediaType(input.ContentType)
|
||||
if err != nil || len(parameters) != 0 || mediaType != "image/png" && mediaType != "image/jpeg" {
|
||||
return nil, "", nil, model.ErrUnsupportedMedia
|
||||
}
|
||||
if input.ContentLength > s.config.MaxBytes {
|
||||
return nil, "", nil, model.ErrPayloadTooLarge
|
||||
}
|
||||
reservation := s.config.MaxBytes
|
||||
if !s.bodyMemory.TryAcquire(reservation) {
|
||||
return nil, "", nil, model.ErrCapacity
|
||||
}
|
||||
releaseBody := func() { s.bodyMemory.Release(reservation) }
|
||||
data, err := io.ReadAll(io.LimitReader(input.Body, s.config.MaxBytes+1))
|
||||
if err != nil {
|
||||
releaseBody()
|
||||
return nil, "", nil, model.ErrInvalidInput
|
||||
}
|
||||
if int64(len(data)) > s.config.MaxBytes {
|
||||
releaseBody()
|
||||
return nil, "", nil, model.ErrPayloadTooLarge
|
||||
}
|
||||
if len(data) == 0 {
|
||||
releaseBody()
|
||||
return nil, "", nil, model.ErrUnsupportedMedia
|
||||
}
|
||||
detected := http.DetectContentType(data)
|
||||
if detected != mediaType {
|
||||
releaseBody()
|
||||
return nil, "", nil, model.ErrUnsupportedMedia
|
||||
}
|
||||
imageConfig, format, err := image.DecodeConfig(bytes.NewReader(data))
|
||||
if err != nil || imageContentType(format) != mediaType {
|
||||
releaseBody()
|
||||
return nil, "", nil, model.ErrUnsupportedMedia
|
||||
}
|
||||
if imageConfig.Width < 1 || imageConfig.Height < 1 || int64(imageConfig.Width) > s.config.MaxPixels/int64(imageConfig.Height) {
|
||||
releaseBody()
|
||||
return nil, "", nil, model.ErrPayloadTooLarge
|
||||
}
|
||||
pixels := int64(imageConfig.Width) * int64(imageConfig.Height)
|
||||
decodeBytes := pixels * 8
|
||||
if !s.decodeMemory.TryAcquire(decodeBytes) {
|
||||
releaseBody()
|
||||
return nil, "", nil, model.ErrCapacity
|
||||
}
|
||||
if _, format, err := image.Decode(bytes.NewReader(data)); err != nil || imageContentType(format) != mediaType {
|
||||
s.decodeMemory.Release(decodeBytes)
|
||||
releaseBody()
|
||||
return nil, "", nil, model.ErrUnsupportedMedia
|
||||
}
|
||||
release := func() {
|
||||
s.decodeMemory.Release(decodeBytes)
|
||||
releaseBody()
|
||||
}
|
||||
return data, mediaType, release, nil
|
||||
}
|
||||
|
||||
func imageContentType(format string) string {
|
||||
switch format {
|
||||
case "png":
|
||||
return "image/png"
|
||||
case "jpeg":
|
||||
return "image/jpeg"
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func mapDependencyError(err error) error {
|
||||
switch {
|
||||
case errors.Is(err, model.ErrNotFound):
|
||||
return model.ErrNotFound
|
||||
case errors.Is(err, model.ErrConflict):
|
||||
return model.ErrConflict
|
||||
default:
|
||||
return model.ErrUnavailable
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,218 @@
|
||||
package attachment
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"image"
|
||||
"image/color"
|
||||
"image/png"
|
||||
"io"
|
||||
"log/slog"
|
||||
"math"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
)
|
||||
|
||||
func TestUploadLifecycle(t *testing.T) {
|
||||
data := pngFixture(t, 2, 2)
|
||||
events := make([]string, 0, 3)
|
||||
repository := &repositoryStub{events: &events}
|
||||
objects := &objectStub{events: &events}
|
||||
service := newTestService(t, repository, objects, 1024, 4)
|
||||
|
||||
result, err := service.Upload(context.Background(), upload(data, "image/png"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, model.AttachmentReady, result.Status)
|
||||
require.Equal(t, []string{"pending", "put", "ready"}, events)
|
||||
}
|
||||
|
||||
func TestUploadValidation(t *testing.T) {
|
||||
data := pngFixture(t, 2, 2)
|
||||
tests := []struct {
|
||||
name string
|
||||
contentType string
|
||||
data []byte
|
||||
maxBytes int64
|
||||
maxPixels int64
|
||||
want error
|
||||
}{
|
||||
{name: "spoofed MIME", contentType: "image/jpeg", data: data, maxBytes: 1024, maxPixels: 4, want: model.ErrUnsupportedMedia},
|
||||
{name: "too many pixels", contentType: "image/png", data: data, maxBytes: 1024, maxPixels: 3, want: model.ErrPayloadTooLarge},
|
||||
{name: "too many bytes", contentType: "image/png", data: data, maxBytes: int64(len(data) - 1), maxPixels: 4, want: model.ErrPayloadTooLarge},
|
||||
{name: "damaged", contentType: "image/png", data: data[:16], maxBytes: 1024, maxPixels: 4, want: model.ErrUnsupportedMedia},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
service := newTestService(t, &repositoryStub{}, &objectStub{}, test.maxBytes, test.maxPixels)
|
||||
input := upload(test.data, test.contentType)
|
||||
_, err := service.Upload(context.Background(), input)
|
||||
require.ErrorIs(t, err, test.want)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadUsesSeparateBodyAndDecodeBudgets(t *testing.T) {
|
||||
data := pngFixture(t, 2, 2)
|
||||
service := newTestService(t, &repositoryStub{}, &objectStub{}, 1024, 4)
|
||||
require.True(t, service.bodyMemory.TryAcquire(1024))
|
||||
_, err := service.Upload(context.Background(), upload(data, "image/png"))
|
||||
require.ErrorIs(t, err, model.ErrCapacity)
|
||||
service.bodyMemory.Release(1024)
|
||||
|
||||
require.True(t, service.decodeMemory.TryAcquire(32))
|
||||
_, err = service.Upload(context.Background(), upload(data, "image/png"))
|
||||
require.ErrorIs(t, err, model.ErrCapacity)
|
||||
service.decodeMemory.Release(32)
|
||||
}
|
||||
|
||||
func TestUploadReleasesBodyMemoryAfterOversizedDimensions(t *testing.T) {
|
||||
oversized := pngFixture(t, 3, 2)
|
||||
valid := pngFixture(t, 2, 2)
|
||||
service := newTestService(t, &repositoryStub{}, &objectStub{}, 1024, 4)
|
||||
|
||||
_, err := service.Upload(context.Background(), upload(oversized, "image/png"))
|
||||
require.ErrorIs(t, err, model.ErrPayloadTooLarge)
|
||||
_, err = service.Upload(context.Background(), upload(valid, "image/png"))
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestNewServiceRejectsDecodeBudgetOverflow(t *testing.T) {
|
||||
_, err := NewService(
|
||||
slog.New(slog.NewTextHandler(io.Discard, nil)), &repositoryStub{}, &objectStub{},
|
||||
Config{
|
||||
MaxBytes: 1024, MaxPixels: math.MaxInt64/8 + 1, BodyMemoryBytes: 1024,
|
||||
DecodeMemoryBytes: math.MaxInt64, CleanupTimeout: time.Second,
|
||||
},
|
||||
)
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func TestUploadCleansPendingMetadataWhenObjectWriteFails(t *testing.T) {
|
||||
data := pngFixture(t, 2, 2)
|
||||
repository := &repositoryStub{}
|
||||
objects := &objectStub{putErr: errors.New("s3 unavailable")}
|
||||
service := newTestService(t, repository, objects, 1024, 4)
|
||||
|
||||
_, err := service.Upload(context.Background(), upload(data, "image/png"))
|
||||
require.ErrorIs(t, err, model.ErrUnavailable)
|
||||
require.True(t, repository.pendingDeleted)
|
||||
}
|
||||
|
||||
func TestUploadReturnsCommittedMetadataAfterAmbiguousReadyUpdate(t *testing.T) {
|
||||
data := pngFixture(t, 2, 2)
|
||||
repository := &repositoryStub{markErr: errors.New("connection lost"), lookupReady: true}
|
||||
objects := &objectStub{}
|
||||
service := newTestService(t, repository, objects, 1024, 4)
|
||||
|
||||
result, err := service.Upload(context.Background(), upload(data, "image/png"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, model.AttachmentReady, result.Status)
|
||||
require.False(t, objects.deleted)
|
||||
}
|
||||
|
||||
func newTestService(t *testing.T, repository Repository, objects ObjectStore, maxBytes, maxPixels int64) *Service {
|
||||
t.Helper()
|
||||
service, err := NewService(
|
||||
slog.New(slog.NewTextHandler(io.Discard, nil)), repository, objects,
|
||||
Config{
|
||||
MaxBytes: maxBytes, MaxPixels: maxPixels, BodyMemoryBytes: maxBytes,
|
||||
DecodeMemoryBytes: maxPixels * 8, CleanupTimeout: time.Second,
|
||||
},
|
||||
)
|
||||
require.NoError(t, err)
|
||||
return service
|
||||
}
|
||||
|
||||
func upload(data []byte, contentType string) Upload {
|
||||
return Upload{
|
||||
ChatID: "chat", OwnerID: "owner", Filename: "photo.png", ContentType: contentType,
|
||||
ContentLength: int64(len(data)), Body: bytes.NewReader(data),
|
||||
}
|
||||
}
|
||||
|
||||
type repositoryStub struct {
|
||||
events *[]string
|
||||
markErr error
|
||||
lookupReady bool
|
||||
pendingDeleted bool
|
||||
pending model.Attachment
|
||||
}
|
||||
|
||||
func (*repositoryStub) ChatForUser(context.Context, string, string) (model.Chat, error) {
|
||||
return model.Chat{}, nil
|
||||
}
|
||||
|
||||
func (s *repositoryStub) CreatePendingAttachment(_ context.Context, attachment model.Attachment) (model.Attachment, error) {
|
||||
attachment.Status = model.AttachmentPending
|
||||
s.pending = attachment
|
||||
s.record("pending")
|
||||
return attachment, nil
|
||||
}
|
||||
|
||||
func (s *repositoryStub) MarkAttachmentReady(context.Context, string, string) (model.Attachment, error) {
|
||||
if s.markErr != nil {
|
||||
return model.Attachment{}, s.markErr
|
||||
}
|
||||
s.pending.Status = model.AttachmentReady
|
||||
s.record("ready")
|
||||
return s.pending, nil
|
||||
}
|
||||
|
||||
func (s *repositoryStub) DeletePendingAttachment(context.Context, string, string) error {
|
||||
s.pendingDeleted = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *repositoryStub) AttachmentByStorage(context.Context, string, string) (model.Attachment, error) {
|
||||
if s.lookupReady {
|
||||
s.pending.Status = model.AttachmentReady
|
||||
return s.pending, nil
|
||||
}
|
||||
return model.Attachment{}, model.ErrNotFound
|
||||
}
|
||||
|
||||
func (s *repositoryStub) AttachmentForUser(context.Context, string, string) (model.Attachment, error) {
|
||||
return s.pending, nil
|
||||
}
|
||||
|
||||
func (s *repositoryStub) record(event string) {
|
||||
if s.events != nil {
|
||||
*s.events = append(*s.events, event)
|
||||
}
|
||||
}
|
||||
|
||||
type objectStub struct {
|
||||
events *[]string
|
||||
putErr error
|
||||
deleted bool
|
||||
}
|
||||
|
||||
func (s *objectStub) Put(context.Context, string, string, []byte) error {
|
||||
if s.events != nil {
|
||||
*s.events = append(*s.events, "put")
|
||||
}
|
||||
return s.putErr
|
||||
}
|
||||
|
||||
func (*objectStub) Get(context.Context, string) (io.ReadCloser, error) {
|
||||
return io.NopCloser(bytes.NewReader(nil)), nil
|
||||
}
|
||||
|
||||
func (s *objectStub) Delete(context.Context, string) error {
|
||||
s.deleted = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func pngFixture(t *testing.T, width, height int) []byte {
|
||||
t.Helper()
|
||||
var data bytes.Buffer
|
||||
value := image.NewRGBA(image.Rect(0, 0, width, height))
|
||||
value.Set(0, 0, color.White)
|
||||
require.NoError(t, png.Encode(&data, value))
|
||||
return data.Bytes()
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/messenger/attachment"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
)
|
||||
|
||||
func (s *Server) uploadAttachment(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
started := time.Now()
|
||||
result := "client_error"
|
||||
defer func() {
|
||||
s.metrics.attachmentUploads.WithLabelValues(result).Inc()
|
||||
s.metrics.attachmentDuration.Observe(time.Since(started).Seconds())
|
||||
}()
|
||||
|
||||
if r.Method != http.MethodPost {
|
||||
return methodNotAllowed(w, http.MethodPost)
|
||||
}
|
||||
user, _, authErr := s.authenticate(r)
|
||||
if authErr != nil {
|
||||
return authErr
|
||||
}
|
||||
chatID, valid := canonicalID(strings.Split(r.URL.Path, "/")[4])
|
||||
if !valid {
|
||||
return invalidRequest()
|
||||
}
|
||||
query, err := url.ParseQuery(r.URL.RawQuery)
|
||||
if err != nil {
|
||||
return invalidRequest()
|
||||
}
|
||||
filename, valid := attachmentFilename(query)
|
||||
if !valid {
|
||||
return invalidRequest()
|
||||
}
|
||||
uploaded, err := s.attachments.Upload(r.Context(), attachment.Upload{
|
||||
ChatID: chatID, OwnerID: user.ID, Filename: filename,
|
||||
ContentType: r.Header.Get("Content-Type"), ContentLength: r.ContentLength, Body: r.Body,
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, model.ErrCapacity) {
|
||||
result = "capacity_rejected"
|
||||
w.Header().Set("Retry-After", "1")
|
||||
} else if errors.Is(err, model.ErrUnavailable) {
|
||||
result = "dependency_error"
|
||||
}
|
||||
return attachmentError(err)
|
||||
}
|
||||
result = "success"
|
||||
s.metrics.attachmentBytes.Add(float64(uploaded.SizeBytes))
|
||||
writeJSON(w, http.StatusCreated, uploaded)
|
||||
return nil
|
||||
}
|
||||
|
||||
func attachmentFilename(query url.Values) (string, bool) {
|
||||
if len(query) != 1 || len(query["filename"]) != 1 {
|
||||
return "", false
|
||||
}
|
||||
filename := query["filename"][0]
|
||||
length := utf8.RuneCountInString(filename)
|
||||
if !utf8.ValidString(filename) || strings.TrimSpace(filename) == "" || length < 1 || length > 255 {
|
||||
return "", false
|
||||
}
|
||||
for _, char := range filename {
|
||||
if char == '/' || char == '\\' || char == 0 || unicode.IsControl(char) {
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
return filename, true
|
||||
}
|
||||
|
||||
func (s *Server) attachmentMetadata(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodGet {
|
||||
return methodNotAllowed(w, http.MethodGet)
|
||||
}
|
||||
user, _, authErr := s.authenticate(r)
|
||||
if authErr != nil {
|
||||
return authErr
|
||||
}
|
||||
attachmentID, apiErr := attachmentIDFromRequest(r)
|
||||
if apiErr != nil {
|
||||
return apiErr
|
||||
}
|
||||
value, err := s.attachments.Metadata(r.Context(), attachmentID, user.ID)
|
||||
if err != nil {
|
||||
return attachmentError(err)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, value)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) attachmentContent(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodGet {
|
||||
return methodNotAllowed(w, http.MethodGet)
|
||||
}
|
||||
user, _, authErr := s.authenticate(r)
|
||||
if authErr != nil {
|
||||
return authErr
|
||||
}
|
||||
query, err := url.ParseQuery(r.URL.RawQuery)
|
||||
if err != nil || !originalVariant(query) {
|
||||
return invalidRequest()
|
||||
}
|
||||
attachmentID, apiErr := attachmentIDFromRequest(r)
|
||||
if apiErr != nil {
|
||||
return apiErr
|
||||
}
|
||||
content, err := s.attachments.Content(r.Context(), attachmentID, user.ID)
|
||||
if err != nil {
|
||||
return attachmentError(err)
|
||||
}
|
||||
defer func() { _ = content.Body.Close() }()
|
||||
w.Header().Set("Content-Type", content.Attachment.ContentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(content.Attachment.SizeBytes, 10))
|
||||
w.Header().Set("Content-Disposition", mime.FormatMediaType("inline", map[string]string{"filename": content.Attachment.Filename}))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if _, err := io.Copy(w, content.Body); err != nil {
|
||||
s.logger.Warn("attachment download interrupted", "attachment_id", content.Attachment.ID, "error", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func originalVariant(query url.Values) bool {
|
||||
if len(query) == 0 {
|
||||
return true
|
||||
}
|
||||
return len(query) == 1 && len(query["variant"]) == 1 && query["variant"][0] == "original"
|
||||
}
|
||||
|
||||
func attachmentIDFromRequest(r *http.Request) (string, *apiError) {
|
||||
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
|
||||
attachmentID, valid := canonicalID(parts[3])
|
||||
if !valid {
|
||||
return "", invalidRequest()
|
||||
}
|
||||
return attachmentID, nil
|
||||
}
|
||||
|
||||
func attachmentError(err error) *apiError {
|
||||
switch {
|
||||
case errors.Is(err, model.ErrNotFound):
|
||||
return notFound()
|
||||
case errors.Is(err, model.ErrInvalidInput):
|
||||
return invalidRequest()
|
||||
case errors.Is(err, model.ErrUnsupportedMedia):
|
||||
return &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "unsupported image type"}
|
||||
case errors.Is(err, model.ErrPayloadTooLarge):
|
||||
return &apiError{http.StatusRequestEntityTooLarge, errorCodePayloadTooLarge, "image is too large"}
|
||||
case errors.Is(err, model.ErrCapacity):
|
||||
return &apiError{http.StatusTooManyRequests, errorCodeRateLimited, "image capacity is temporarily exhausted"}
|
||||
default:
|
||||
return unavailable()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
)
|
||||
|
||||
func (s *Server) createSession(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodPost {
|
||||
return methodNotAllowed(w, http.MethodPost)
|
||||
}
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, 1))
|
||||
if err != nil || len(body) != 0 {
|
||||
return invalidRequest()
|
||||
}
|
||||
username, passwordValue, ok := singleBasicAuth(r)
|
||||
if !ok {
|
||||
return unauthorized()
|
||||
}
|
||||
credentials, err := s.userRepository.UserByUsername(r.Context(), username)
|
||||
if errors.Is(err, model.ErrNotFound) {
|
||||
if _, verifyErr := s.passwords.Verify(passwordValue, s.passwords.DummyHash()); verifyErr != nil {
|
||||
return internalError()
|
||||
}
|
||||
return unauthorized()
|
||||
}
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
verified, err := s.passwords.Verify(passwordValue, credentials.PasswordHash)
|
||||
if err != nil {
|
||||
return internalError()
|
||||
}
|
||||
if !verified {
|
||||
return unauthorized()
|
||||
}
|
||||
token, expiresAt, err := s.sessions.Create(r.Context(), credentials.ID, s.sessionTTL)
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, struct {
|
||||
Token string `json:"token"`
|
||||
TokenType string `json:"token_type"`
|
||||
ExpiresAt string `json:"expires_at"`
|
||||
User User `json:"user"`
|
||||
}{token, "Bearer", model.FormatTime(expiresAt), credentials.User})
|
||||
return nil
|
||||
}
|
||||
|
||||
func singleBasicAuth(r *http.Request) (string, string, bool) {
|
||||
if len(r.Header.Values("Authorization")) != 1 {
|
||||
return "", "", false
|
||||
}
|
||||
username, passwordValue, ok := r.BasicAuth()
|
||||
return username, passwordValue, ok && username != ""
|
||||
}
|
||||
|
||||
func (s *Server) revokeSession(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodDelete {
|
||||
return methodNotAllowed(w, http.MethodDelete)
|
||||
}
|
||||
_, token, authErr := s.authenticate(r)
|
||||
if authErr != nil {
|
||||
return authErr
|
||||
}
|
||||
if err := s.sessions.Delete(r.Context(), token); errors.Is(err, model.ErrSessionNotFound) {
|
||||
return unauthorized()
|
||||
} else if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) authenticate(r *http.Request) (User, string, *apiError) {
|
||||
values := r.Header.Values("Authorization")
|
||||
if len(values) != 1 {
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
scheme, token, found := strings.Cut(values[0], " ")
|
||||
if !found || !strings.EqualFold(scheme, "Bearer") || token == "" || strings.ContainsAny(token, " \t\r\n") {
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
userID, err := s.sessions.UserID(r.Context(), token)
|
||||
if errors.Is(err, model.ErrSessionNotFound) || errors.Is(err, model.ErrInvalidToken) {
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
if err != nil {
|
||||
return User{}, "", unavailable()
|
||||
}
|
||||
user, err := s.userRepository.UserByID(r.Context(), userID)
|
||||
if errors.Is(err, model.ErrNotFound) {
|
||||
_ = s.sessions.Delete(r.Context(), token)
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
if err != nil {
|
||||
return User{}, "", unavailable()
|
||||
}
|
||||
return user, token, nil
|
||||
}
|
||||
|
||||
func authenticationChallenge(r *http.Request) string {
|
||||
if r.URL.Path == "/api/v1/auth/sessions" {
|
||||
return `Basic realm="messenger", charset="UTF-8"`
|
||||
}
|
||||
return `Bearer realm="messenger"`
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
)
|
||||
|
||||
const (
|
||||
errorCodeInvalidRequest = "invalid_request"
|
||||
errorCodeUnauthorized = "unauthorized"
|
||||
errorCodeNotFound = "not_found"
|
||||
errorCodeInternal = "internal_error"
|
||||
errorCodeUnsupportedMediaType = "unsupported_media_type"
|
||||
errorCodePayloadTooLarge = "payload_too_large"
|
||||
errorCodeUnavailable = "unavailable"
|
||||
errorCodeConflict = "conflict"
|
||||
errorCodeRateLimited = "rate_limited"
|
||||
)
|
||||
|
||||
type apiError struct {
|
||||
status int
|
||||
code string
|
||||
message string
|
||||
}
|
||||
|
||||
func methodNotAllowed(w http.ResponseWriter, allowed string) *apiError {
|
||||
w.Header().Set("Allow", allowed)
|
||||
return &apiError{http.StatusMethodNotAllowed, errorCodeInvalidRequest, "method not allowed"}
|
||||
}
|
||||
|
||||
func invalidRequest() *apiError {
|
||||
return &apiError{http.StatusBadRequest, errorCodeInvalidRequest, "invalid request"}
|
||||
}
|
||||
|
||||
func unauthorized() *apiError {
|
||||
return &apiError{http.StatusUnauthorized, errorCodeUnauthorized, "authentication required"}
|
||||
}
|
||||
|
||||
func notFound() *apiError {
|
||||
return &apiError{http.StatusNotFound, errorCodeNotFound, "resource not found"}
|
||||
}
|
||||
|
||||
func internalError() *apiError {
|
||||
return &apiError{http.StatusInternalServerError, errorCodeInternal, "internal server error"}
|
||||
}
|
||||
|
||||
func unavailable() *apiError {
|
||||
return &apiError{http.StatusServiceUnavailable, errorCodeUnavailable, "service unavailable"}
|
||||
}
|
||||
|
||||
func writeError(w http.ResponseWriter, requestID string, err *apiError) {
|
||||
writeJSON(w, err.status, map[string]any{"error": map[string]string{
|
||||
"code": err.code, "message": err.message, "request_id": requestID,
|
||||
}})
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, value any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
_ = json.NewEncoder(w).Encode(value)
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
)
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
func (s *Server) live(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodGet {
|
||||
return methodNotAllowed(w, http.MethodGet)
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) readiness(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodGet {
|
||||
return methodNotAllowed(w, http.MethodGet)
|
||||
}
|
||||
if !s.ready.Load() {
|
||||
return unavailable()
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
defer cancel()
|
||||
if err := s.database.Ping(ctx); err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
if err := s.sessions.Ping(ctx); err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
if err := s.objects.Ping(ctx); err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) users(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodPost {
|
||||
return methodNotAllowed(w, http.MethodPost)
|
||||
}
|
||||
var input struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if err := readJSON(w, r, &input); err != nil {
|
||||
return err
|
||||
}
|
||||
if !usernamePattern.MatchString(input.Username) || !validText(input.DisplayName, 100) || !validPassword(input.Password) {
|
||||
return invalidRequest()
|
||||
}
|
||||
passwordHash, err := s.passwords.Hash(input.Password)
|
||||
if err != nil {
|
||||
return internalError()
|
||||
}
|
||||
user, err := s.userRepository.CreateUser(r.Context(), input.Username, input.DisplayName, passwordHash)
|
||||
if errors.Is(err, model.ErrConflict) {
|
||||
return &apiError{http.StatusConflict, errorCodeConflict, "username already exists"}
|
||||
}
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, user)
|
||||
return nil
|
||||
}
|
||||
|
||||
func validPassword(value string) bool {
|
||||
length := utf8.RuneCountInString(value)
|
||||
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && length >= 12 && length <= 128
|
||||
}
|
||||
|
||||
func (s *Server) me(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodGet {
|
||||
return methodNotAllowed(w, http.MethodGet)
|
||||
}
|
||||
user, _, err := s.authenticate(r)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
writeJSON(w, http.StatusOK, user)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) chats(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodPost && r.Method != http.MethodGet {
|
||||
return methodNotAllowed(w, http.MethodGet+", "+http.MethodPost)
|
||||
}
|
||||
user, _, authErr := s.authenticate(r)
|
||||
if authErr != nil {
|
||||
return authErr
|
||||
}
|
||||
if r.Method == http.MethodGet {
|
||||
return s.listChats(w, r, user)
|
||||
}
|
||||
var input struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
if err := readJSON(w, r, &input); err != nil {
|
||||
return err
|
||||
}
|
||||
if !validText(input.Title, 100) || len(input.MemberIDs) < 1 || len(input.MemberIDs) > 100 {
|
||||
return invalidRequest()
|
||||
}
|
||||
members := make(map[string]struct{}, len(input.MemberIDs))
|
||||
for i, memberID := range input.MemberIDs {
|
||||
canonical, valid := canonicalID(memberID)
|
||||
if !valid {
|
||||
return invalidRequest()
|
||||
}
|
||||
if _, duplicate := members[canonical]; duplicate {
|
||||
return invalidRequest()
|
||||
}
|
||||
members[canonical] = struct{}{}
|
||||
input.MemberIDs[i] = canonical
|
||||
}
|
||||
if _, included := members[user.ID]; !included {
|
||||
return invalidRequest()
|
||||
}
|
||||
chat, err := s.chatRepository.CreateChat(r.Context(), input.Title, input.MemberIDs, user.ID)
|
||||
if errors.Is(err, model.ErrInvalidMembers) {
|
||||
return invalidRequest()
|
||||
}
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, chat)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) listChats(w http.ResponseWriter, r *http.Request, user User) *apiError {
|
||||
limit, cursor, err := pageParams(r, "chat", user.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
items, hasNext, listErr := s.chatRepository.ListChats(r.Context(), user.ID, cursorPosition(cursor), limit)
|
||||
if errors.Is(listErr, model.ErrInvalidCursor) {
|
||||
return invalidRequest()
|
||||
}
|
||||
if listErr != nil {
|
||||
return unavailable()
|
||||
}
|
||||
if items == nil {
|
||||
items = []Chat{}
|
||||
}
|
||||
var next *string
|
||||
if hasNext {
|
||||
last := items[len(items)-1]
|
||||
value := encodeCursor("chat", user.ID, last.CreatedAt, last.ID)
|
||||
next = &value
|
||||
}
|
||||
writeJSON(w, http.StatusOK, struct {
|
||||
Items []Chat `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}{items, next})
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) chat(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodGet {
|
||||
return methodNotAllowed(w, http.MethodGet)
|
||||
}
|
||||
user, _, authErr := s.authenticate(r)
|
||||
if authErr != nil {
|
||||
return authErr
|
||||
}
|
||||
chatID, valid := canonicalID(strings.Split(r.URL.Path, "/")[4])
|
||||
if !valid {
|
||||
return invalidRequest()
|
||||
}
|
||||
chat, err := s.chatRepository.ChatForUser(r.Context(), chatID, user.ID)
|
||||
if errors.Is(err, model.ErrNotFound) {
|
||||
return notFound()
|
||||
}
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
writeJSON(w, http.StatusOK, chat)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) messages(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
if r.Method != http.MethodPost && r.Method != http.MethodGet {
|
||||
return methodNotAllowed(w, http.MethodGet+", "+http.MethodPost)
|
||||
}
|
||||
user, _, authErr := s.authenticate(r)
|
||||
if authErr != nil {
|
||||
return authErr
|
||||
}
|
||||
chatID, valid := canonicalID(strings.Split(r.URL.Path, "/")[4])
|
||||
if !valid {
|
||||
return invalidRequest()
|
||||
}
|
||||
if r.Method == http.MethodGet {
|
||||
return s.listMessages(w, r, user, chatID)
|
||||
}
|
||||
key, valid := idempotencyKey(r)
|
||||
if !valid {
|
||||
return invalidRequest()
|
||||
}
|
||||
var input struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
if err := readJSON(w, r, &input); err != nil {
|
||||
return err
|
||||
}
|
||||
if !validMessage(input.Text, input.AttachmentIDs) || !canonicalAttachmentIDs(input.AttachmentIDs) {
|
||||
return invalidRequest()
|
||||
}
|
||||
message, replay, err := s.messageRepository.CreateMessage(
|
||||
r.Context(), chatID, user.ID, input.Text, input.AttachmentIDs, key, s.idempotencyTTL,
|
||||
)
|
||||
if errors.Is(err, model.ErrNotFound) {
|
||||
return notFound()
|
||||
}
|
||||
if errors.Is(err, model.ErrIdempotencyConflict) {
|
||||
return &apiError{http.StatusConflict, errorCodeConflict, "idempotency key conflicts with previous request"}
|
||||
}
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
if replay {
|
||||
s.metrics.replays.Inc()
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, message)
|
||||
return nil
|
||||
}
|
||||
|
||||
func validMessage(text string, attachmentIDs []string) bool {
|
||||
if !utf8.ValidString(text) || utf8.RuneCountInString(text) > 4000 {
|
||||
return false
|
||||
}
|
||||
return len(attachmentIDs) > 0 || strings.TrimSpace(text) != ""
|
||||
}
|
||||
|
||||
func canonicalAttachmentIDs(attachmentIDs []string) bool {
|
||||
if len(attachmentIDs) > 10 {
|
||||
return false
|
||||
}
|
||||
seen := make(map[string]struct{}, len(attachmentIDs))
|
||||
for index, attachmentID := range attachmentIDs {
|
||||
canonical, valid := canonicalID(attachmentID)
|
||||
if !valid {
|
||||
return false
|
||||
}
|
||||
if _, duplicate := seen[canonical]; duplicate {
|
||||
return false
|
||||
}
|
||||
seen[canonical] = struct{}{}
|
||||
attachmentIDs[index] = canonical
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) listMessages(w http.ResponseWriter, r *http.Request, user User, chatID string) *apiError {
|
||||
limit, cursor, err := pageParams(r, "message", chatID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
items, hasNext, listErr := s.messageRepository.ListMessages(r.Context(), chatID, user.ID, cursorPosition(cursor), limit)
|
||||
if errors.Is(listErr, model.ErrNotFound) {
|
||||
return notFound()
|
||||
}
|
||||
if errors.Is(listErr, model.ErrInvalidCursor) {
|
||||
return invalidRequest()
|
||||
}
|
||||
if listErr != nil {
|
||||
return unavailable()
|
||||
}
|
||||
if items == nil {
|
||||
items = []Message{}
|
||||
}
|
||||
var next *string
|
||||
if hasNext {
|
||||
last := items[len(items)-1]
|
||||
value := encodeCursor("message", chatID, last.CreatedAt, last.ID)
|
||||
next = &value
|
||||
}
|
||||
writeJSON(w, http.StatusOK, struct {
|
||||
Items []Message `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}{items, next})
|
||||
return nil
|
||||
}
|
||||
|
||||
func cursorPosition(cursor *pageCursor) *model.Position {
|
||||
if cursor == nil {
|
||||
return nil
|
||||
}
|
||||
return &model.Position{CreatedAt: cursor.Time, ID: cursor.ID}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/messenger/attachment"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
)
|
||||
|
||||
type UserRepository interface {
|
||||
CreateUser(context.Context, string, string, string) (model.User, error)
|
||||
UserByID(context.Context, string) (model.User, error)
|
||||
UserByUsername(context.Context, string) (model.UserCredentials, error)
|
||||
}
|
||||
|
||||
type ChatRepository interface {
|
||||
CreateChat(context.Context, string, []string, string) (model.Chat, error)
|
||||
ChatForUser(context.Context, string, string) (model.Chat, error)
|
||||
ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error)
|
||||
}
|
||||
|
||||
type MessageRepository interface {
|
||||
CreateMessage(context.Context, string, string, string, []string, string, time.Duration) (model.Message, bool, error)
|
||||
ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error)
|
||||
}
|
||||
|
||||
type AttachmentService interface {
|
||||
Upload(context.Context, attachment.Upload) (model.Attachment, error)
|
||||
Metadata(context.Context, string, string) (model.Attachment, error)
|
||||
Content(context.Context, string, string) (attachment.Content, error)
|
||||
}
|
||||
|
||||
type HealthChecker interface {
|
||||
Ping(context.Context) error
|
||||
}
|
||||
|
||||
type SessionStore interface {
|
||||
HealthChecker
|
||||
Create(context.Context, string, time.Duration) (string, time.Time, error)
|
||||
UserID(context.Context, string) (string, error)
|
||||
Delete(context.Context, string) error
|
||||
}
|
||||
|
||||
type PasswordService interface {
|
||||
Hash(string) (string, error)
|
||||
Verify(string, string) (bool, error)
|
||||
DummyHash() string
|
||||
}
|
||||
@@ -0,0 +1,114 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/prometheus/client_golang/prometheus"
|
||||
"github.com/prometheus/client_golang/prometheus/collectors"
|
||||
"github.com/prometheus/client_golang/prometheus/promhttp"
|
||||
)
|
||||
|
||||
type metrics struct {
|
||||
requests *prometheus.CounterVec
|
||||
duration *prometheus.HistogramVec
|
||||
inFlight prometheus.Gauge
|
||||
replays prometheus.Counter
|
||||
attachmentUploads *prometheus.CounterVec
|
||||
attachmentDuration prometheus.Histogram
|
||||
attachmentBytes prometheus.Counter
|
||||
handler http.Handler
|
||||
}
|
||||
|
||||
func newMetrics() *metrics {
|
||||
registry := prometheus.NewRegistry()
|
||||
result := &metrics{
|
||||
requests: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: "messenger",
|
||||
Subsystem: "http",
|
||||
Name: "requests_total",
|
||||
Help: "Completed HTTP requests.",
|
||||
}, []string{"method", "route", "status_class"}),
|
||||
duration: prometheus.NewHistogramVec(prometheus.HistogramOpts{
|
||||
Namespace: "messenger",
|
||||
Subsystem: "http",
|
||||
Name: "request_duration_seconds",
|
||||
Help: "HTTP request duration in seconds.",
|
||||
Buckets: prometheus.DefBuckets,
|
||||
}, []string{"method", "route"}),
|
||||
inFlight: prometheus.NewGauge(prometheus.GaugeOpts{
|
||||
Namespace: "messenger",
|
||||
Subsystem: "http",
|
||||
Name: "requests_in_flight",
|
||||
Help: "HTTP requests currently being served.",
|
||||
}),
|
||||
replays: prometheus.NewCounter(prometheus.CounterOpts{
|
||||
Namespace: "messenger",
|
||||
Subsystem: "http",
|
||||
Name: "idempotency_replays_total",
|
||||
Help: "Message requests served from an idempotency record.",
|
||||
}),
|
||||
attachmentUploads: prometheus.NewCounterVec(prometheus.CounterOpts{
|
||||
Namespace: "messenger",
|
||||
Name: "attachment_uploads_total",
|
||||
Help: "Completed attachment uploads by result.",
|
||||
}, []string{"result"}),
|
||||
attachmentDuration: prometheus.NewHistogram(prometheus.HistogramOpts{
|
||||
Namespace: "messenger",
|
||||
Name: "attachment_upload_duration_seconds",
|
||||
Help: "Attachment upload duration in seconds.",
|
||||
Buckets: prometheus.DefBuckets,
|
||||
}),
|
||||
attachmentBytes: prometheus.NewCounter(prometheus.CounterOpts{
|
||||
Namespace: "messenger",
|
||||
Name: "attachment_upload_bytes_total",
|
||||
Help: "Bytes accepted by successful attachment uploads.",
|
||||
}),
|
||||
}
|
||||
registry.MustRegister(
|
||||
result.requests,
|
||||
result.duration,
|
||||
result.inFlight,
|
||||
result.replays,
|
||||
result.attachmentUploads,
|
||||
result.attachmentDuration,
|
||||
result.attachmentBytes,
|
||||
collectors.NewGoCollector(),
|
||||
collectors.NewProcessCollector(collectors.ProcessCollectorOpts{}),
|
||||
)
|
||||
result.handler = promhttp.HandlerFor(registry, promhttp.HandlerOpts{})
|
||||
return result
|
||||
}
|
||||
|
||||
func (m *metrics) observe(r *http.Request, status int, started time.Time) {
|
||||
route := routeTemplate(r.URL.Path)
|
||||
m.requests.WithLabelValues(r.Method, route, strconv.Itoa(status/100)+"xx").Inc()
|
||||
m.duration.WithLabelValues(r.Method, route).Observe(time.Since(started).Seconds())
|
||||
}
|
||||
|
||||
func routeTemplate(path string) string {
|
||||
switch path {
|
||||
case "/health/live", "/health/ready", "/metrics", "/api/v1/users", "/api/v1/users/me",
|
||||
"/api/v1/auth/sessions", "/api/v1/auth/sessions/current", "/api/v1/chats":
|
||||
return path
|
||||
}
|
||||
parts := strings.Split(strings.Trim(path, "/"), "/")
|
||||
if len(parts) == 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" {
|
||||
return "/api/v1/chats/{chat_id}"
|
||||
}
|
||||
if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "messages" {
|
||||
return "/api/v1/chats/{chat_id}/messages"
|
||||
}
|
||||
if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "attachments" {
|
||||
return "/api/v1/chats/{chat_id}/attachments"
|
||||
}
|
||||
if len(parts) == 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" {
|
||||
return "/api/v1/attachments/{attachment_id}"
|
||||
}
|
||||
if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" && parts[4] == "content" {
|
||||
return "/api/v1/attachments/{attachment_id}/content"
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type User = model.User
|
||||
type Chat = model.Chat
|
||||
type Message = model.Message
|
||||
type Attachment = model.Attachment
|
||||
|
||||
func newID() (string, error) {
|
||||
id, err := uuid.NewRandom()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return id.String(), nil
|
||||
}
|
||||
|
||||
func canonicalID(value string) (string, bool) {
|
||||
if len(value) != 36 {
|
||||
return "", false
|
||||
}
|
||||
id, err := uuid.Parse(value)
|
||||
if err != nil {
|
||||
return "", false
|
||||
}
|
||||
return id.String(), true
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const maxRequestBytes = 1 << 20
|
||||
|
||||
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
func readJSON(w http.ResponseWriter, r *http.Request, target any) *apiError {
|
||||
mediaType, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||
if err != nil || mediaType != "application/json" || (params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8")) {
|
||||
return &apiError{http.StatusUnsupportedMediaType, errorCodeUnsupportedMediaType, "expected application/json"}
|
||||
}
|
||||
r.Body = http.MaxBytesReader(w, r.Body, maxRequestBytes)
|
||||
data, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
var tooLarge *http.MaxBytesError
|
||||
if errors.As(err, &tooLarge) {
|
||||
return &apiError{http.StatusRequestEntityTooLarge, errorCodePayloadTooLarge, "request body too large"}
|
||||
}
|
||||
return invalidRequest()
|
||||
}
|
||||
if !utf8.Valid(data) {
|
||||
return invalidRequest()
|
||||
}
|
||||
var object map[string]json.RawMessage
|
||||
if err := json.Unmarshal(data, &object); err != nil || object == nil {
|
||||
return invalidRequest()
|
||||
}
|
||||
normalized, err := json.Marshal(object)
|
||||
if err != nil {
|
||||
return invalidRequest()
|
||||
}
|
||||
decoder := json.NewDecoder(bytes.NewReader(normalized))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(target); err != nil {
|
||||
return invalidRequest()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validText(value string, maxRunes int) bool {
|
||||
return utf8.ValidString(value) && strings.TrimSpace(value) != "" && utf8.RuneCountInString(value) <= maxRunes
|
||||
}
|
||||
|
||||
func idempotencyKey(r *http.Request) (string, bool) {
|
||||
values := r.Header.Values("Idempotency-Key")
|
||||
if len(values) != 1 || !idempotencyKeyPattern.MatchString(values[0]) {
|
||||
return "", false
|
||||
}
|
||||
return values[0], true
|
||||
}
|
||||
|
||||
type pageCursor struct {
|
||||
Kind string `json:"kind"`
|
||||
Resource string `json:"resource"`
|
||||
Time time.Time `json:"time"`
|
||||
ID string `json:"id"`
|
||||
}
|
||||
|
||||
func pageParams(r *http.Request, kind, resource string) (int, *pageCursor, *apiError) {
|
||||
query, err := url.ParseQuery(r.URL.RawQuery)
|
||||
if err != nil {
|
||||
return 0, nil, invalidRequest()
|
||||
}
|
||||
for key := range query {
|
||||
if key != "limit" && key != "cursor" {
|
||||
return 0, nil, invalidRequest()
|
||||
}
|
||||
if len(query[key]) != 1 {
|
||||
return 0, nil, invalidRequest()
|
||||
}
|
||||
}
|
||||
limit := 50
|
||||
if value, present := query["limit"]; present {
|
||||
parsed, err := strconv.Atoi(value[0])
|
||||
if err != nil || parsed < 1 || parsed > 100 {
|
||||
return 0, nil, invalidRequest()
|
||||
}
|
||||
limit = parsed
|
||||
}
|
||||
if value, present := query["cursor"]; present {
|
||||
cursor, valid := decodeCursor(value[0], kind, resource)
|
||||
if !valid {
|
||||
return 0, nil, invalidRequest()
|
||||
}
|
||||
return limit, cursor, nil
|
||||
}
|
||||
return limit, nil, nil
|
||||
}
|
||||
|
||||
func encodeCursor(kind, resource string, createdAt time.Time, id string) string {
|
||||
data, _ := json.Marshal(pageCursor{kind, resource, createdAt, id})
|
||||
return base64.RawURLEncoding.EncodeToString(data)
|
||||
}
|
||||
|
||||
func decodeCursor(value, kind, resource string) (*pageCursor, bool) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(value)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
var cursor pageCursor
|
||||
if err := json.Unmarshal(data, &cursor); err != nil || cursor.Kind != kind || cursor.Resource != resource {
|
||||
return nil, false
|
||||
}
|
||||
if cursor.Time.IsZero() {
|
||||
return nil, false
|
||||
}
|
||||
if _, valid := canonicalID(cursor.ID); !valid {
|
||||
return nil, false
|
||||
}
|
||||
return &cursor, true
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type requestHandler func(http.ResponseWriter, *http.Request) *apiError
|
||||
|
||||
func (s *Server) route(w http.ResponseWriter, r *http.Request) *apiError {
|
||||
var handler requestHandler
|
||||
switch r.URL.Path {
|
||||
case "/health/live":
|
||||
handler = s.live
|
||||
case "/health/ready":
|
||||
handler = s.readiness
|
||||
case "/metrics":
|
||||
s.metrics.handler.ServeHTTP(w, r)
|
||||
return nil
|
||||
case "/api/v1/users":
|
||||
handler = s.users
|
||||
case "/api/v1/users/me":
|
||||
handler = s.me
|
||||
case "/api/v1/auth/sessions":
|
||||
handler = s.createSession
|
||||
case "/api/v1/auth/sessions/current":
|
||||
handler = s.revokeSession
|
||||
case "/api/v1/chats":
|
||||
handler = s.chats
|
||||
default:
|
||||
parts := strings.Split(strings.Trim(r.URL.Path, "/"), "/")
|
||||
if len(parts) == 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" {
|
||||
handler = s.chat
|
||||
} else if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "messages" {
|
||||
handler = s.messages
|
||||
} else if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "chats" && parts[4] == "attachments" {
|
||||
handler = s.uploadAttachment
|
||||
} else if len(parts) == 4 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" {
|
||||
handler = s.attachmentMetadata
|
||||
} else if len(parts) == 5 && parts[0] == "api" && parts[1] == "v1" && parts[2] == "attachments" && parts[4] == "content" {
|
||||
handler = s.attachmentContent
|
||||
} else {
|
||||
return notFound()
|
||||
}
|
||||
}
|
||||
return handler(w, r)
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Dependencies struct {
|
||||
Users UserRepository
|
||||
Chats ChatRepository
|
||||
Messages MessageRepository
|
||||
Attachments AttachmentService
|
||||
Sessions SessionStore
|
||||
Passwords PasswordService
|
||||
Database HealthChecker
|
||||
Objects HealthChecker
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
SessionTTL time.Duration
|
||||
IdempotencyTTL time.Duration
|
||||
RequestTTL time.Duration
|
||||
InstanceID string
|
||||
SwaggerPort string
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
userRepository UserRepository
|
||||
chatRepository ChatRepository
|
||||
messageRepository MessageRepository
|
||||
attachments AttachmentService
|
||||
sessions SessionStore
|
||||
passwords PasswordService
|
||||
database HealthChecker
|
||||
objects HealthChecker
|
||||
sessionTTL time.Duration
|
||||
idempotencyTTL time.Duration
|
||||
requestTTL time.Duration
|
||||
instanceID string
|
||||
logger *slog.Logger
|
||||
swaggerPort string
|
||||
metrics *metrics
|
||||
ready atomic.Bool
|
||||
}
|
||||
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
}
|
||||
|
||||
func (w *statusWriter) WriteHeader(status int) {
|
||||
w.status = status
|
||||
w.ResponseWriter.WriteHeader(status)
|
||||
}
|
||||
|
||||
func NewServer(
|
||||
logger *slog.Logger,
|
||||
dependencies Dependencies,
|
||||
config Config,
|
||||
) *Server {
|
||||
s := &Server{
|
||||
userRepository: dependencies.Users, chatRepository: dependencies.Chats,
|
||||
messageRepository: dependencies.Messages,
|
||||
attachments: dependencies.Attachments, sessions: dependencies.Sessions,
|
||||
passwords: dependencies.Passwords, database: dependencies.Database, objects: dependencies.Objects,
|
||||
sessionTTL: config.SessionTTL, idempotencyTTL: config.IdempotencyTTL, requestTTL: config.RequestTTL,
|
||||
instanceID: config.InstanceID, logger: logger, swaggerPort: config.SwaggerPort, metrics: newMetrics(),
|
||||
}
|
||||
s.ready.Store(true)
|
||||
return s
|
||||
}
|
||||
|
||||
func (s *Server) SetReady(ready bool) {
|
||||
s.ready.Store(ready)
|
||||
}
|
||||
|
||||
func (s *Server) Handler() http.Handler {
|
||||
return http.HandlerFunc(s.serve)
|
||||
}
|
||||
|
||||
func (s *Server) serve(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Instance-Id", s.instanceID)
|
||||
requestID, err := newID()
|
||||
if err != nil {
|
||||
http.Error(w, "server unavailable", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
wrapped := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
||||
started := time.Now()
|
||||
s.metrics.inFlight.Inc()
|
||||
defer func() {
|
||||
s.metrics.inFlight.Dec()
|
||||
if recovered := recover(); recovered != nil {
|
||||
s.logger.Error("request panic", "request_id", requestID, "method", r.Method, "path", r.URL.Path)
|
||||
if wrapped.status == http.StatusOK {
|
||||
writeError(wrapped, requestID, internalError())
|
||||
}
|
||||
}
|
||||
s.metrics.observe(r, wrapped.status, started)
|
||||
s.logger.Info("request", "request_id", requestID, "method", r.Method, "path", r.URL.Path, "status", wrapped.status, "duration_ms", time.Since(started).Milliseconds())
|
||||
}()
|
||||
if s.allowSwaggerOrigin(wrapped, r) && r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" {
|
||||
wrapped.Header().Set("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
|
||||
wrapped.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type, Idempotency-Key")
|
||||
wrapped.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), s.requestTTL)
|
||||
defer cancel()
|
||||
r = r.WithContext(ctx)
|
||||
if apiErr := s.route(wrapped, r); apiErr != nil {
|
||||
if apiErr.status == http.StatusUnauthorized {
|
||||
wrapped.Header().Set("WWW-Authenticate", authenticationChallenge(r))
|
||||
}
|
||||
writeError(wrapped, requestID, apiErr)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) allowSwaggerOrigin(w http.ResponseWriter, r *http.Request) bool {
|
||||
origin := r.Header.Get("Origin")
|
||||
if origin != "http://localhost:"+s.swaggerPort && origin != "http://127.0.0.1:"+s.swaggerPort {
|
||||
return false
|
||||
}
|
||||
w.Header().Set("Access-Control-Allow-Origin", origin)
|
||||
w.Header().Set("Access-Control-Expose-Headers", "X-Request-Id, X-Instance-Id")
|
||||
w.Header().Add("Vary", "Origin")
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
package httpapi
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/messenger/attachment"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
)
|
||||
|
||||
var errDependency = errors.New("dependency unavailable")
|
||||
|
||||
type MessengerSuite struct {
|
||||
suite.Suite
|
||||
logger *slog.Logger
|
||||
}
|
||||
|
||||
func TestMessengerSuite(t *testing.T) {
|
||||
suite.Run(t, new(MessengerSuite))
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) SetupTest() {
|
||||
s.logger = slog.New(slog.NewTextHandler(io.Discard, nil))
|
||||
}
|
||||
|
||||
type messengerStoreStub struct {
|
||||
pingErr error
|
||||
userByID model.User
|
||||
userByIDErr error
|
||||
credentials model.UserCredentials
|
||||
credentialsErr error
|
||||
message model.Message
|
||||
messageReplay bool
|
||||
messageErr error
|
||||
}
|
||||
|
||||
func (s messengerStoreStub) Ping(context.Context) error { return s.pingErr }
|
||||
func (messengerStoreStub) CreateUser(context.Context, string, string, string) (model.User, error) {
|
||||
return model.User{}, nil
|
||||
}
|
||||
func (s messengerStoreStub) UserByID(context.Context, string) (model.User, error) {
|
||||
return s.userByID, s.userByIDErr
|
||||
}
|
||||
func (s messengerStoreStub) UserByUsername(context.Context, string) (model.UserCredentials, error) {
|
||||
return s.credentials, s.credentialsErr
|
||||
}
|
||||
func (messengerStoreStub) CreateChat(context.Context, string, []string, string) (model.Chat, error) {
|
||||
return model.Chat{}, nil
|
||||
}
|
||||
func (messengerStoreStub) ChatForUser(context.Context, string, string) (model.Chat, error) {
|
||||
return model.Chat{}, nil
|
||||
}
|
||||
func (messengerStoreStub) ListChats(context.Context, string, *model.Position, int) ([]model.Chat, bool, error) {
|
||||
return nil, false, nil
|
||||
}
|
||||
func (s messengerStoreStub) CreateMessage(context.Context, string, string, string, []string, string, time.Duration) (model.Message, bool, error) {
|
||||
return s.message, s.messageReplay, s.messageErr
|
||||
}
|
||||
func (messengerStoreStub) ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error) {
|
||||
return nil, false, nil
|
||||
}
|
||||
|
||||
type objectStoreStub struct {
|
||||
pingErr error
|
||||
}
|
||||
|
||||
func (s objectStoreStub) Ping(context.Context) error { return s.pingErr }
|
||||
|
||||
type attachmentServiceStub struct {
|
||||
uploaded model.Attachment
|
||||
err error
|
||||
}
|
||||
|
||||
func (s attachmentServiceStub) Upload(context.Context, attachment.Upload) (model.Attachment, error) {
|
||||
return s.uploaded, s.err
|
||||
}
|
||||
func (s attachmentServiceStub) Metadata(context.Context, string, string) (model.Attachment, error) {
|
||||
return s.uploaded, s.err
|
||||
}
|
||||
func (s attachmentServiceStub) Content(context.Context, string, string) (attachment.Content, error) {
|
||||
return attachment.Content{Attachment: s.uploaded, Body: io.NopCloser(strings.NewReader("content"))}, s.err
|
||||
}
|
||||
|
||||
type sessionStub struct {
|
||||
pingErr error
|
||||
userID string
|
||||
userIDErr error
|
||||
}
|
||||
|
||||
func (s sessionStub) Ping(context.Context) error { return s.pingErr }
|
||||
func (sessionStub) Create(context.Context, string, time.Duration) (string, time.Time, error) {
|
||||
return "token", time.Now().Add(time.Hour), nil
|
||||
}
|
||||
func (s sessionStub) UserID(context.Context, string) (string, error) { return s.userID, s.userIDErr }
|
||||
func (sessionStub) Delete(context.Context, string) error { return nil }
|
||||
|
||||
type passwordsStub struct {
|
||||
verified bool
|
||||
err error
|
||||
}
|
||||
|
||||
func (passwordsStub) Hash(string) (string, error) { return "hash", nil }
|
||||
func (passwordsStub) DummyHash() string { return "hash" }
|
||||
func (s passwordsStub) Verify(string, string) (bool, error) {
|
||||
return s.verified, s.err
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestReadinessReturnsUnavailableForDependencyFailure() {
|
||||
t := s.T()
|
||||
tests := []struct {
|
||||
name string
|
||||
store messengerStoreStub
|
||||
sessions sessionStub
|
||||
objects objectStoreStub
|
||||
}{
|
||||
{name: "postgres", store: messengerStoreStub{pingErr: errDependency}},
|
||||
{name: "valkey", sessions: sessionStub{pingErr: errDependency}},
|
||||
{name: "s3", objects: objectStoreStub{pingErr: errDependency}},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
server := s.server(tt.store, tt.sessions, passwordsStub{}, tt.objects, attachmentServiceStub{})
|
||||
response := serveRequest(server, http.MethodGet, "/health/ready", "")
|
||||
if response.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestBusinessRequestReturnsUnavailableForDependencyFailure() {
|
||||
t := s.T()
|
||||
tests := []struct {
|
||||
name string
|
||||
store messengerStoreStub
|
||||
sessions sessionStub
|
||||
}{
|
||||
{name: "valkey", sessions: sessionStub{userIDErr: errDependency}},
|
||||
{name: "postgres", store: messengerStoreStub{userByIDErr: errDependency}, sessions: sessionStub{userID: "user-id"}},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
server := s.newTestServer(tt.store, tt.sessions, passwordsStub{})
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
|
||||
request.Header.Set("Authorization", "Bearer valid-token")
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusServiceUnavailable)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestAuthenticationChallenges() {
|
||||
t := s.T()
|
||||
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
|
||||
bearer := serveRequest(server, http.MethodGet, "/api/v1/users/me", "")
|
||||
if bearer.Code != http.StatusUnauthorized || bearer.Header().Get("WWW-Authenticate") != `Bearer realm="messenger"` {
|
||||
t.Fatalf("business challenge = %d %q", bearer.Code, bearer.Header().Get("WWW-Authenticate"))
|
||||
}
|
||||
|
||||
store := messengerStoreStub{credentials: model.UserCredentials{PasswordHash: "hash"}}
|
||||
server = s.newTestServer(store, sessionStub{}, passwordsStub{verified: false})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
request.SetBasicAuth("user", "wrong-password")
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusUnauthorized || response.Header().Get("WWW-Authenticate") != `Basic realm="messenger", charset="UTF-8"` {
|
||||
t.Fatalf("session challenge = %d %q", response.Code, response.Header().Get("WWW-Authenticate"))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestAttachmentContentAuthenticatesBeforeVariantValidation() {
|
||||
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
|
||||
response := serveRequest(
|
||||
server,
|
||||
http.MethodGet,
|
||||
"/api/v1/attachments/00000000-0000-0000-0000-000000000001/content?variant=invalid",
|
||||
"",
|
||||
)
|
||||
s.Equal(http.StatusUnauthorized, response.Code)
|
||||
s.Equal(`Bearer realm="messenger"`, response.Header().Get("WWW-Authenticate"))
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestSessionCreationRejectsChunkedBody() {
|
||||
t := s.T()
|
||||
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader("{}"))
|
||||
request.ContentLength = -1
|
||||
request.SetBasicAuth("user", "password")
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusBadRequest)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestRegistrationRejectsWhitespacePassword() {
|
||||
t := s.T()
|
||||
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
|
||||
response := serveRequest(server, http.MethodPost, "/api/v1/users", `{"username":"student","display_name":"Student","password":" "}`)
|
||||
if response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusBadRequest)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestInstanceHeaderIsSetOnSuccessAndError() {
|
||||
t := s.T()
|
||||
server := s.newTestServer(messengerStoreStub{}, sessionStub{}, passwordsStub{})
|
||||
for _, response := range []*httptest.ResponseRecorder{
|
||||
serveRequest(server, http.MethodGet, "/health/live", ""),
|
||||
serveRequest(server, http.MethodGet, "/api/v1/users/me", ""),
|
||||
} {
|
||||
if value := response.Header().Get("X-Instance-Id"); value != "test-instance" {
|
||||
t.Fatalf("X-Instance-Id = %q, want test-instance", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestMessageCreationValidatesIdempotencyKey() {
|
||||
t := s.T()
|
||||
store := messengerStoreStub{userByID: model.User{ID: "user-id"}}
|
||||
server := s.newTestServer(store, sessionStub{userID: "user-id"}, passwordsStub{})
|
||||
tests := []struct {
|
||||
name string
|
||||
key string
|
||||
}{
|
||||
{name: "missing"},
|
||||
{name: "invalid", key: "invalid key"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/chats/00000000-0000-0000-0000-000000000001/messages", strings.NewReader(`{"text":"message"}`))
|
||||
request.Header.Set("Authorization", "Bearer valid-token")
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
if tt.key != "" {
|
||||
request.Header.Set("Idempotency-Key", tt.key)
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusBadRequest)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestMessageCreationReturnsConflictForReusedKeyWithDifferentBody() {
|
||||
t := s.T()
|
||||
store := messengerStoreStub{
|
||||
userByID: model.User{ID: "user-id"},
|
||||
messageErr: fmt.Errorf("create message: %w", model.ErrIdempotencyConflict),
|
||||
}
|
||||
server := s.newTestServer(store, sessionStub{userID: "user-id"}, passwordsStub{})
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/chats/00000000-0000-0000-0000-000000000001/messages", strings.NewReader(`{"text":"different"}`))
|
||||
request.Header.Set("Authorization", "Bearer valid-token")
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("Idempotency-Key", "same-key")
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
if response.Code != http.StatusConflict {
|
||||
t.Fatalf("status = %d, want %d", response.Code, http.StatusConflict)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestAttachmentFilenameValidation() {
|
||||
for _, filename := range []string{"", " ", "../photo.png", "dir\\photo.png", "photo\x00.png", "photo\n.png"} {
|
||||
_, valid := attachmentFilename(map[string][]string{"filename": {filename}})
|
||||
s.False(valid, filename)
|
||||
}
|
||||
filename, valid := attachmentFilename(map[string][]string{"filename": {"фото.png"}})
|
||||
s.True(valid)
|
||||
s.Equal("фото.png", filename)
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) TestUploadRejectsMalformedQuery() {
|
||||
store := messengerStoreStub{userByID: model.User{ID: "user-id"}}
|
||||
server := s.newTestServer(store, sessionStub{userID: "user-id"}, passwordsStub{})
|
||||
request := httptest.NewRequest(
|
||||
http.MethodPost,
|
||||
"/api/v1/chats/00000000-0000-0000-0000-000000000002/attachments?filename=photo.png&junk=%GG",
|
||||
strings.NewReader("image"),
|
||||
)
|
||||
request.Header.Set("Authorization", "Bearer valid-token")
|
||||
request.Header.Set("Content-Type", "image/png")
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
s.Equal(http.StatusBadRequest, response.Code)
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) newTestServer(store messengerStoreStub, sessions SessionStore, passwords PasswordService) *Server {
|
||||
return s.server(store, sessions, passwords, objectStoreStub{}, attachmentServiceStub{})
|
||||
}
|
||||
|
||||
func (s *MessengerSuite) server(
|
||||
store messengerStoreStub,
|
||||
sessions SessionStore,
|
||||
passwords PasswordService,
|
||||
objects objectStoreStub,
|
||||
attachments AttachmentService,
|
||||
) *Server {
|
||||
return NewServer(s.logger, Dependencies{
|
||||
Users: store, Chats: store, Messages: store, Attachments: attachments,
|
||||
Sessions: sessions, Passwords: passwords, Database: store, Objects: objects,
|
||||
}, Config{
|
||||
SessionTTL: time.Hour, IdempotencyTTL: 24 * time.Hour, RequestTTL: time.Second,
|
||||
InstanceID: "test-instance", SwaggerPort: "8081",
|
||||
})
|
||||
}
|
||||
|
||||
func serveRequest(server *Server, method, path, body string) *httptest.ResponseRecorder {
|
||||
request := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
if body != "" {
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
server.Handler().ServeHTTP(response, request)
|
||||
return response
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package model
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrInvalidMembers = errors.New("invalid members")
|
||||
ErrInvalidCursor = errors.New("invalid cursor")
|
||||
ErrIdempotencyConflict = errors.New("idempotency conflict")
|
||||
ErrInvalidToken = errors.New("invalid token")
|
||||
ErrSessionNotFound = errors.New("session not found")
|
||||
ErrInvalidInput = errors.New("invalid input")
|
||||
ErrUnsupportedMedia = errors.New("unsupported media")
|
||||
ErrPayloadTooLarge = errors.New("payload too large")
|
||||
ErrCapacity = errors.New("capacity exhausted")
|
||||
ErrUnavailable = errors.New("dependency unavailable")
|
||||
)
|
||||
@@ -0,0 +1,153 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
AttachmentPending = "pending"
|
||||
AttachmentReady = "ready"
|
||||
AttachmentDeleting = "deleting"
|
||||
)
|
||||
|
||||
const timestampLayout = "2006-01-02T15:04:05.000000Z"
|
||||
|
||||
type User struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
type UserCredentials struct {
|
||||
User
|
||||
PasswordHash string `json:"-"`
|
||||
}
|
||||
|
||||
type Chat struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
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 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:"-"`
|
||||
ReadyAt *time.Time `json:"-"`
|
||||
Referenced bool `json:"-"`
|
||||
}
|
||||
|
||||
type StoredObject struct {
|
||||
Key string
|
||||
Size int64
|
||||
LastModified time.Time
|
||||
}
|
||||
|
||||
type Variant struct {
|
||||
Name string `json:"name"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Width int `json:"width"`
|
||||
Height int `json:"height"`
|
||||
}
|
||||
|
||||
type Position struct {
|
||||
CreatedAt time.Time
|
||||
ID string
|
||||
}
|
||||
|
||||
type userJSON struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type chatJSON struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type messageJSON struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
type attachmentJSON 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 string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (u User) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(userJSON{u.ID, u.Username, u.DisplayName, formatTime(u.CreatedAt)})
|
||||
}
|
||||
|
||||
func (c Chat) MarshalJSON() ([]byte, error) {
|
||||
return json.Marshal(chatJSON{c.ID, c.Title, c.MemberIDs, formatTime(c.CreatedAt)})
|
||||
}
|
||||
|
||||
func (m Message) MarshalJSON() ([]byte, error) {
|
||||
attachments := m.AttachmentIDs
|
||||
if attachments == nil {
|
||||
attachments = []string{}
|
||||
}
|
||||
return json.Marshal(messageJSON{m.ID, m.ChatID, m.SenderID, m.Text, formatTime(m.CreatedAt), attachments})
|
||||
}
|
||||
|
||||
func (a Attachment) MarshalJSON() ([]byte, error) {
|
||||
variants := a.Variants
|
||||
if variants == nil {
|
||||
variants = []Variant{}
|
||||
}
|
||||
return json.Marshal(attachmentJSON{
|
||||
a.ID, a.ChatID, a.OwnerID, a.Filename, a.ContentType, a.SizeBytes, a.SHA256,
|
||||
a.Status, variants, a.ErrorCode, formatTime(a.CreatedAt), formatTime(a.UpdatedAt),
|
||||
})
|
||||
}
|
||||
|
||||
func FormatTime(value time.Time) string {
|
||||
return formatTime(value)
|
||||
}
|
||||
|
||||
func formatTime(value time.Time) string {
|
||||
return value.UTC().Format(timestampLayout)
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
)
|
||||
|
||||
type ModelSuite struct {
|
||||
suite.Suite
|
||||
}
|
||||
|
||||
func TestModelSuite(t *testing.T) {
|
||||
suite.Run(t, new(ModelSuite))
|
||||
}
|
||||
|
||||
func (s *ModelSuite) TestUserTimestampHasFixedMicroseconds() {
|
||||
createdAt := time.Date(2026, time.September, 23, 21, 28, 15, 423030000, time.UTC)
|
||||
data, err := json.Marshal(User{ID: "id", Username: "user", DisplayName: "User", CreatedAt: createdAt})
|
||||
s.Require().NoError(err)
|
||||
s.Equal(`{"id":"id","username":"user","display_name":"User","created_at":"2026-09-23T21:28:15.423030Z"}`, string(data))
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package objectstore
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
)
|
||||
|
||||
var ErrNotFound = errors.New("object not found")
|
||||
|
||||
type Config struct {
|
||||
Endpoint string
|
||||
Region string
|
||||
Bucket string
|
||||
AccessKey string
|
||||
SecretKey string
|
||||
UseTLS bool
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
client *minio.Client
|
||||
bucket string
|
||||
timeout time.Duration
|
||||
}
|
||||
|
||||
func New(config Config) (*Store, error) {
|
||||
endpoint, err := endpointHost(config.Endpoint, config.UseTLS)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(config.Bucket) == "" || config.Timeout <= 0 {
|
||||
return nil, errors.New("invalid object store configuration")
|
||||
}
|
||||
client, err := minio.New(endpoint, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(config.AccessKey, config.SecretKey, ""),
|
||||
Secure: config.UseTLS,
|
||||
Region: config.Region,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create S3 client: %w", err)
|
||||
}
|
||||
return &Store{client: client, bucket: config.Bucket, timeout: config.Timeout}, nil
|
||||
}
|
||||
|
||||
func endpointHost(value string, useTLS bool) (string, error) {
|
||||
value = strings.TrimSpace(value)
|
||||
if !strings.Contains(value, "://") {
|
||||
if value == "" {
|
||||
return "", errors.New("S3 endpoint is required")
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
parsed, err := url.Parse(value)
|
||||
if err != nil || parsed.Host == "" || parsed.Path != "" && parsed.Path != "/" {
|
||||
return "", errors.New("invalid S3 endpoint")
|
||||
}
|
||||
if (parsed.Scheme == "https") != useTLS || parsed.Scheme != "http" && parsed.Scheme != "https" {
|
||||
return "", errors.New("S3 endpoint scheme conflicts with S3_USE_TLS")
|
||||
}
|
||||
return parsed.Host, nil
|
||||
}
|
||||
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
exists, err := s.client.BucketExists(ctx, s.bucket)
|
||||
if err != nil {
|
||||
return fmt.Errorf("check S3 bucket: %w", err)
|
||||
}
|
||||
if !exists {
|
||||
return errors.New("S3 bucket does not exist")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) Put(ctx context.Context, key, contentType string, data []byte) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
_, err := s.client.PutObject(
|
||||
ctx, s.bucket, key, bytes.NewReader(data), int64(len(data)), minio.PutObjectOptions{ContentType: contentType},
|
||||
)
|
||||
if err != nil {
|
||||
return fmt.Errorf("put S3 object: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) Get(ctx context.Context, key string) (io.ReadCloser, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
object, err := s.client.GetObject(ctx, s.bucket, key, minio.GetObjectOptions{})
|
||||
if err != nil {
|
||||
cancel()
|
||||
return nil, objectError("get S3 object", err)
|
||||
}
|
||||
if _, err := object.Stat(); err != nil {
|
||||
cancel()
|
||||
_ = object.Close()
|
||||
return nil, objectError("stat S3 object", err)
|
||||
}
|
||||
return &timeoutReader{ReadCloser: object, cancel: cancel}, nil
|
||||
}
|
||||
|
||||
func (s *Store) Stat(ctx context.Context, key string) (model.StoredObject, error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
info, err := s.client.StatObject(ctx, s.bucket, key, minio.StatObjectOptions{})
|
||||
if err != nil {
|
||||
return model.StoredObject{}, objectError("stat S3 object", err)
|
||||
}
|
||||
return model.StoredObject{Key: info.Key, Size: info.Size, LastModified: info.LastModified}, nil
|
||||
}
|
||||
|
||||
func (s *Store) Delete(ctx context.Context, key string) error {
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
if err := s.client.RemoveObject(ctx, s.bucket, key, minio.RemoveObjectOptions{}); err != nil {
|
||||
return objectError("delete S3 object", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) List(ctx context.Context, prefix, after string, limit int) ([]model.StoredObject, string, error) {
|
||||
if limit < 1 || limit > 1000 {
|
||||
return nil, "", errors.New("object list limit must be between 1 and 1000")
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(ctx, s.timeout)
|
||||
defer cancel()
|
||||
objects := make([]model.StoredObject, 0, limit+1)
|
||||
options := minio.ListObjectsOptions{Prefix: prefix, Recursive: true, StartAfter: after, MaxKeys: limit + 1}
|
||||
for info := range s.client.ListObjects(ctx, s.bucket, options) {
|
||||
if info.Err != nil {
|
||||
return nil, "", fmt.Errorf("list S3 objects: %w", info.Err)
|
||||
}
|
||||
objects = append(objects, model.StoredObject{Key: info.Key, Size: info.Size, LastModified: info.LastModified})
|
||||
if len(objects) == limit+1 {
|
||||
cancel()
|
||||
break
|
||||
}
|
||||
}
|
||||
var next string
|
||||
if len(objects) > limit {
|
||||
objects = objects[:limit]
|
||||
next = objects[len(objects)-1].Key
|
||||
}
|
||||
return objects, next, nil
|
||||
}
|
||||
|
||||
type timeoutReader struct {
|
||||
io.ReadCloser
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
func (r *timeoutReader) Close() error {
|
||||
err := r.ReadCloser.Close()
|
||||
r.cancel()
|
||||
return err
|
||||
}
|
||||
|
||||
func objectError(action string, err error) error {
|
||||
response := minio.ToErrorResponse(err)
|
||||
if response.Code == "NoSuchKey" || response.Code == "NoSuchObject" {
|
||||
return ErrNotFound
|
||||
}
|
||||
return fmt.Errorf("%s: %w", action, err)
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
package password
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidConfig = errors.New("invalid password configuration")
|
||||
ErrInvalidHash = errors.New("invalid password hash")
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
MemoryKiB uint32
|
||||
Iterations uint32
|
||||
Parallelism uint8
|
||||
SaltLength uint32
|
||||
KeyLength uint32
|
||||
}
|
||||
|
||||
type Hasher struct {
|
||||
config Config
|
||||
dummyHash string
|
||||
}
|
||||
|
||||
func New(config Config) (*Hasher, error) {
|
||||
if err := validateConfig(config); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
salt := make([]byte, config.SaltLength)
|
||||
digest := argon2.IDKey([]byte("invalid-user-password"), salt, config.Iterations, config.MemoryKiB, config.Parallelism, config.KeyLength)
|
||||
return &Hasher{config: config, dummyHash: encode(config, salt, digest)}, nil
|
||||
}
|
||||
|
||||
func validateConfig(config Config) error {
|
||||
if config.MemoryKiB < 8*1024 || config.MemoryKiB > 1024*1024 ||
|
||||
config.Iterations < 1 || config.Iterations > 20 ||
|
||||
config.Parallelism < 1 ||
|
||||
config.SaltLength < 8 || config.SaltLength > 1024 ||
|
||||
config.KeyLength < 16 || config.KeyLength > 1024 {
|
||||
return ErrInvalidConfig
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (h *Hasher) Hash(value string) (string, error) {
|
||||
salt := make([]byte, h.config.SaltLength)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("generate password salt: %w", err)
|
||||
}
|
||||
digest := argon2.IDKey([]byte(value), salt, h.config.Iterations, h.config.MemoryKiB, h.config.Parallelism, h.config.KeyLength)
|
||||
return encode(h.config, salt, digest), nil
|
||||
}
|
||||
|
||||
func (h *Hasher) Verify(value, encodedHash string) (bool, error) {
|
||||
config, salt, digest, err := decode(encodedHash)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
actual := argon2.IDKey([]byte(value), salt, config.Iterations, config.MemoryKiB, config.Parallelism, config.KeyLength)
|
||||
return subtle.ConstantTimeCompare(actual, digest) == 1, nil
|
||||
}
|
||||
|
||||
func (h *Hasher) DummyHash() string {
|
||||
return h.dummyHash
|
||||
}
|
||||
|
||||
func encode(config Config, salt, digest []byte) string {
|
||||
return fmt.Sprintf(
|
||||
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version,
|
||||
config.MemoryKiB,
|
||||
config.Iterations,
|
||||
config.Parallelism,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(digest),
|
||||
)
|
||||
}
|
||||
|
||||
func decode(encodedHash string) (Config, []byte, []byte, error) {
|
||||
parts := strings.Split(encodedHash, "$")
|
||||
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" || parts[2] != fmt.Sprintf("v=%d", argon2.Version) {
|
||||
return Config{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
|
||||
parameters := strings.Split(parts[3], ",")
|
||||
if len(parameters) != 3 {
|
||||
return Config{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
memory, err := parameter(parameters[0], "m=", 32)
|
||||
if err != nil {
|
||||
return Config{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
iterations, err := parameter(parameters[1], "t=", 32)
|
||||
if err != nil {
|
||||
return Config{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
parallelism, err := parameter(parameters[2], "p=", 8)
|
||||
if err != nil {
|
||||
return Config{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
|
||||
salt, err := base64.RawStdEncoding.Strict().DecodeString(parts[4])
|
||||
if err != nil {
|
||||
return Config{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
digest, err := base64.RawStdEncoding.Strict().DecodeString(parts[5])
|
||||
if err != nil {
|
||||
return Config{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
config := Config{
|
||||
MemoryKiB: uint32(memory), Iterations: uint32(iterations), Parallelism: uint8(parallelism),
|
||||
SaltLength: uint32(len(salt)), KeyLength: uint32(len(digest)),
|
||||
}
|
||||
if err := validateConfig(config); err != nil {
|
||||
return Config{}, nil, nil, ErrInvalidHash
|
||||
}
|
||||
return config, salt, digest, nil
|
||||
}
|
||||
|
||||
func parameter(value, prefix string, bitSize int) (uint64, error) {
|
||||
if !strings.HasPrefix(value, prefix) {
|
||||
return 0, ErrInvalidHash
|
||||
}
|
||||
return strconv.ParseUint(strings.TrimPrefix(value, prefix), 10, bitSize)
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package password
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
)
|
||||
|
||||
type PasswordSuite struct {
|
||||
suite.Suite
|
||||
hasher *Hasher
|
||||
}
|
||||
|
||||
func TestPasswordSuite(t *testing.T) {
|
||||
suite.Run(t, new(PasswordSuite))
|
||||
}
|
||||
|
||||
func (s *PasswordSuite) SetupTest() {
|
||||
hasher, err := New(testConfig())
|
||||
s.Require().NoError(err)
|
||||
s.hasher = hasher
|
||||
}
|
||||
|
||||
func (s *PasswordSuite) TestHasher() {
|
||||
hash, err := s.hasher.Hash("T3st-password-123")
|
||||
s.Require().NoError(err)
|
||||
|
||||
verified, err := s.hasher.Verify("T3st-password-123", hash)
|
||||
s.Require().NoError(err)
|
||||
s.True(verified)
|
||||
|
||||
verified, err = s.hasher.Verify("wrong-password", hash)
|
||||
s.Require().NoError(err)
|
||||
s.False(verified)
|
||||
}
|
||||
|
||||
func (s *PasswordSuite) TestVerifyRejectsMalformedHash() {
|
||||
_, err := s.hasher.Verify("password", "invalid")
|
||||
s.Error(err)
|
||||
}
|
||||
|
||||
func testConfig() Config {
|
||||
return Config{MemoryKiB: 8 * 1024, Iterations: 1, Parallelism: 1, SaltLength: 16, KeyLength: 32}
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
)
|
||||
|
||||
const attachmentColumns = `
|
||||
id, chat_id, owner_id, filename, content_type, size_bytes, sha256,
|
||||
object_key, status, created_at, updated_at, ready_at`
|
||||
|
||||
type rowScanner interface {
|
||||
Scan(...any) error
|
||||
}
|
||||
|
||||
func (s *Store) CreatePendingAttachment(ctx context.Context, attachment model.Attachment) (model.Attachment, error) {
|
||||
query := `
|
||||
INSERT INTO attachments (
|
||||
id, chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, status, ready_at
|
||||
)
|
||||
SELECT $1, $2, $3, $4, $5, $6, $7, $8, 'pending', NULL
|
||||
WHERE EXISTS (
|
||||
SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $3
|
||||
)
|
||||
RETURNING ` + attachmentColumns
|
||||
|
||||
err := scanAttachment(s.pool.QueryRow(
|
||||
ctx, query, attachment.ID, attachment.ChatID, attachment.OwnerID, attachment.Filename,
|
||||
attachment.ContentType, attachment.SizeBytes, attachment.SHA256, attachment.ObjectKey,
|
||||
), &attachment)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Attachment{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Attachment{}, fmt.Errorf("create pending attachment: %w", err)
|
||||
}
|
||||
return publicAttachment(attachment), nil
|
||||
}
|
||||
|
||||
func (s *Store) MarkAttachmentReady(ctx context.Context, attachmentID, objectKey string) (model.Attachment, error) {
|
||||
query := `
|
||||
UPDATE attachments
|
||||
SET status = 'ready', ready_at = clock_timestamp(), updated_at = clock_timestamp()
|
||||
WHERE id = $1 AND object_key = $2 AND status = 'pending'
|
||||
RETURNING ` + attachmentColumns
|
||||
|
||||
var attachment model.Attachment
|
||||
err := scanAttachment(s.pool.QueryRow(ctx, query, attachmentID, objectKey), &attachment)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Attachment{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Attachment{}, fmt.Errorf("mark attachment ready: %w", err)
|
||||
}
|
||||
return publicAttachment(attachment), nil
|
||||
}
|
||||
|
||||
func (s *Store) DeletePendingAttachment(ctx context.Context, attachmentID, objectKey string) error {
|
||||
const query = `DELETE FROM attachments WHERE id = $1 AND object_key = $2 AND status = 'pending'`
|
||||
if _, err := s.pool.Exec(ctx, query, attachmentID, objectKey); err != nil {
|
||||
return fmt.Errorf("delete pending attachment: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) AttachmentForUser(ctx context.Context, attachmentID, userID string) (model.Attachment, error) {
|
||||
query := `
|
||||
SELECT ` + attachmentColumnsWithAlias("a") + `
|
||||
FROM attachments a
|
||||
JOIN chat_members member ON member.chat_id = a.chat_id AND member.user_id = $2
|
||||
WHERE a.id = $1 AND a.status = 'ready'`
|
||||
|
||||
var attachment model.Attachment
|
||||
err := scanAttachment(s.pool.QueryRow(ctx, query, attachmentID, userID), &attachment)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Attachment{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Attachment{}, fmt.Errorf("get attachment for user: %w", err)
|
||||
}
|
||||
return publicAttachment(attachment), nil
|
||||
}
|
||||
|
||||
func (s *Store) AttachmentByStorage(ctx context.Context, attachmentID, objectKey string) (model.Attachment, error) {
|
||||
const query = `SELECT ` + attachmentColumns + ` FROM attachments WHERE id = $1 AND object_key = $2`
|
||||
|
||||
var attachment model.Attachment
|
||||
err := scanAttachment(s.pool.QueryRow(ctx, query, attachmentID, objectKey), &attachment)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Attachment{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Attachment{}, fmt.Errorf("get attachment by storage: %w", err)
|
||||
}
|
||||
return publicAttachment(attachment), nil
|
||||
}
|
||||
|
||||
func (s *Store) AttachmentExistsByObjectKey(ctx context.Context, objectKey string) (bool, error) {
|
||||
const query = `SELECT EXISTS (SELECT 1 FROM attachments WHERE object_key = $1)`
|
||||
var exists bool
|
||||
if err := s.pool.QueryRow(ctx, query, objectKey).Scan(&exists); err != nil {
|
||||
return false, fmt.Errorf("check attachment by object key: %w", err)
|
||||
}
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListAttachments(ctx context.Context, afterObjectKey string, limit int) ([]model.Attachment, string, error) {
|
||||
if limit < 1 || limit > 1000 {
|
||||
return nil, "", fmt.Errorf("attachment list limit must be between 1 and 1000")
|
||||
}
|
||||
query := `
|
||||
SELECT ` + attachmentColumnsWithAlias("a") + `,
|
||||
EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id)
|
||||
FROM attachments a
|
||||
WHERE a.object_key > $1
|
||||
ORDER BY a.object_key
|
||||
LIMIT $2`
|
||||
rows, err := s.pool.Query(ctx, query, afterObjectKey, limit+1)
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("list attachments: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
attachments, err := pgx.CollectRows(rows, pgx.RowToFunc[model.Attachment](func(row pgx.CollectableRow) (model.Attachment, error) {
|
||||
var attachment model.Attachment
|
||||
err := scanAttachmentWithReference(row, &attachment)
|
||||
return publicAttachment(attachment), err
|
||||
}))
|
||||
if err != nil {
|
||||
return nil, "", fmt.Errorf("scan attachments: %w", err)
|
||||
}
|
||||
var next string
|
||||
if len(attachments) > limit {
|
||||
attachments = attachments[:limit]
|
||||
next = attachments[len(attachments)-1].ObjectKey
|
||||
}
|
||||
return attachments, next, nil
|
||||
}
|
||||
|
||||
func scanAttachmentWithReference(row rowScanner, attachment *model.Attachment) error {
|
||||
return row.Scan(
|
||||
&attachment.ID, &attachment.ChatID, &attachment.OwnerID, &attachment.Filename,
|
||||
&attachment.ContentType, &attachment.SizeBytes, &attachment.SHA256, &attachment.ObjectKey,
|
||||
&attachment.Status, &attachment.CreatedAt, &attachment.UpdatedAt, &attachment.ReadyAt,
|
||||
&attachment.Referenced,
|
||||
)
|
||||
}
|
||||
|
||||
func (s *Store) AttachmentReferenced(ctx context.Context, attachmentID string) (bool, error) {
|
||||
const query = `SELECT EXISTS (SELECT 1 FROM message_attachments WHERE attachment_id = $1)`
|
||||
var referenced bool
|
||||
if err := s.pool.QueryRow(ctx, query, attachmentID).Scan(&referenced); err != nil {
|
||||
return false, fmt.Errorf("check attachment references: %w", err)
|
||||
}
|
||||
return referenced, nil
|
||||
}
|
||||
|
||||
func (s *Store) ClaimAttachmentForDeletion(ctx context.Context, candidate model.Attachment, createdBefore time.Time) (bool, error) {
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("begin attachment deletion claim: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||
|
||||
var status string
|
||||
var createdAt time.Time
|
||||
var readyAt *time.Time
|
||||
err = tx.QueryRow(
|
||||
ctx, `SELECT status, created_at, ready_at FROM attachments WHERE id = $1 FOR UPDATE`, candidate.ID,
|
||||
).Scan(&status, &createdAt, &readyAt)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("lock attachment deletion candidate: %w", err)
|
||||
}
|
||||
if status != candidate.Status {
|
||||
return false, nil
|
||||
}
|
||||
var age time.Time
|
||||
switch status {
|
||||
case model.AttachmentPending:
|
||||
age = createdAt
|
||||
case model.AttachmentReady:
|
||||
if readyAt == nil {
|
||||
return false, nil
|
||||
}
|
||||
age = *readyAt
|
||||
default:
|
||||
return false, nil
|
||||
}
|
||||
if age.After(createdBefore) {
|
||||
return false, nil
|
||||
}
|
||||
var referenced bool
|
||||
if err := tx.QueryRow(ctx, `SELECT EXISTS (SELECT 1 FROM message_attachments WHERE attachment_id = $1)`, candidate.ID).Scan(&referenced); err != nil {
|
||||
return false, fmt.Errorf("recheck attachment references: %w", err)
|
||||
}
|
||||
if referenced {
|
||||
return false, nil
|
||||
}
|
||||
if _, err := tx.Exec(
|
||||
ctx,
|
||||
`UPDATE attachments SET status = 'deleting', updated_at = clock_timestamp() WHERE id = $1 AND status = $2`,
|
||||
candidate.ID, candidate.Status,
|
||||
); err != nil {
|
||||
return false, fmt.Errorf("mark attachment deleting: %w", err)
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return false, fmt.Errorf("commit attachment deletion claim: %w", err)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
func (s *Store) DeleteAttachmentIfDeleting(ctx context.Context, attachmentID string) (bool, error) {
|
||||
const query = `
|
||||
DELETE FROM attachments a
|
||||
WHERE a.id = $1
|
||||
AND a.status = 'deleting'
|
||||
AND NOT EXISTS (SELECT 1 FROM message_attachments ma WHERE ma.attachment_id = a.id)`
|
||||
result, err := s.pool.Exec(ctx, query, attachmentID)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("delete claimed attachment: %w", err)
|
||||
}
|
||||
return result.RowsAffected() == 1, nil
|
||||
}
|
||||
|
||||
func scanAttachment(row rowScanner, attachment *model.Attachment) error {
|
||||
return row.Scan(
|
||||
&attachment.ID, &attachment.ChatID, &attachment.OwnerID, &attachment.Filename,
|
||||
&attachment.ContentType, &attachment.SizeBytes, &attachment.SHA256, &attachment.ObjectKey,
|
||||
&attachment.Status, &attachment.CreatedAt, &attachment.UpdatedAt, &attachment.ReadyAt,
|
||||
)
|
||||
}
|
||||
|
||||
func attachmentColumnsWithAlias(alias string) string {
|
||||
return fmt.Sprintf(
|
||||
"%[1]s.id, %[1]s.chat_id, %[1]s.owner_id, %[1]s.filename, %[1]s.content_type, "+
|
||||
"%[1]s.size_bytes, %[1]s.sha256, %[1]s.object_key, %[1]s.status, "+
|
||||
"%[1]s.created_at, %[1]s.updated_at, %[1]s.ready_at",
|
||||
alias,
|
||||
)
|
||||
}
|
||||
|
||||
func publicAttachment(attachment model.Attachment) model.Attachment {
|
||||
attachment.Variants = []model.Variant{}
|
||||
return attachment
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package postgres
|
||||
|
||||
import "gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
|
||||
var (
|
||||
ErrConflict = model.ErrConflict
|
||||
ErrNotFound = model.ErrNotFound
|
||||
ErrInvalidMembers = model.ErrInvalidMembers
|
||||
ErrInvalidCursor = model.ErrInvalidCursor
|
||||
ErrIdempotencyConflict = model.ErrIdempotencyConflict
|
||||
)
|
||||
@@ -0,0 +1,364 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
)
|
||||
|
||||
const expiredIdempotencyCleanupBatch = 100
|
||||
|
||||
func (s *Store) CreateMessage(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
senderID string,
|
||||
text string,
|
||||
attachmentIDs []string,
|
||||
idempotencyKey string,
|
||||
idempotencyTTL time.Duration,
|
||||
) (model.Message, bool, error) {
|
||||
if attachmentIDs == nil {
|
||||
attachmentIDs = []string{}
|
||||
}
|
||||
var (
|
||||
tx pgx.Tx
|
||||
err error
|
||||
visible bool
|
||||
requestHash [sha256.Size]byte
|
||||
message model.Message
|
||||
replay bool
|
||||
)
|
||||
|
||||
tx, err = s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return model.Message{}, false, fmt.Errorf("begin create message transaction: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||
|
||||
visible, err = chatVisibleInTransaction(ctx, tx, chatID, senderID)
|
||||
if err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
if !visible {
|
||||
return model.Message{}, false, ErrNotFound
|
||||
}
|
||||
validAttachments, err := attachmentsBelongToChat(ctx, tx, chatID, attachmentIDs)
|
||||
if err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
if !validAttachments {
|
||||
return model.Message{}, false, ErrNotFound
|
||||
}
|
||||
if err = deleteExpiredIdempotencyRecords(ctx, tx, expiredIdempotencyCleanupBatch); err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
|
||||
requestHash, err = messageRequestHash(text, attachmentIDs)
|
||||
if err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
message, replay, err = createIdempotentMessage(
|
||||
ctx, tx, chatID, senderID, text, attachmentIDs, idempotencyKey, requestHash[:], idempotencyTTL,
|
||||
)
|
||||
if err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Message{}, false, fmt.Errorf("commit create message transaction: %w", err)
|
||||
}
|
||||
return message, replay, nil
|
||||
}
|
||||
|
||||
func messageRequestHash(text string, attachmentIDs []string) ([sha256.Size]byte, error) {
|
||||
if attachmentIDs == nil {
|
||||
attachmentIDs = []string{}
|
||||
}
|
||||
payload, err := json.Marshal(struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}{text, attachmentIDs})
|
||||
if err != nil {
|
||||
return [sha256.Size]byte{}, fmt.Errorf("marshal message request: %w", err)
|
||||
}
|
||||
return sha256.Sum256(payload), nil
|
||||
}
|
||||
|
||||
func attachmentsBelongToChat(ctx context.Context, tx pgx.Tx, chatID string, attachmentIDs []string) (bool, error) {
|
||||
if len(attachmentIDs) == 0 {
|
||||
return true, nil
|
||||
}
|
||||
const query = `
|
||||
SELECT id
|
||||
FROM attachments
|
||||
WHERE chat_id = $1 AND id::text = ANY($2) AND status = 'ready'
|
||||
FOR UPDATE`
|
||||
rows, err := tx.Query(ctx, query, chatID, attachmentIDs)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("validate message attachments: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
count := 0
|
||||
for rows.Next() {
|
||||
count++
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return false, fmt.Errorf("validate message attachments: %w", err)
|
||||
}
|
||||
return count == len(attachmentIDs), nil
|
||||
}
|
||||
|
||||
func chatVisibleInTransaction(ctx context.Context, tx pgx.Tx, chatID, userID string) (bool, error) {
|
||||
const query = `
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = $1 AND user_id = $2
|
||||
)`
|
||||
|
||||
var visible bool
|
||||
if err := tx.QueryRow(ctx, query, chatID, userID).Scan(&visible); err != nil {
|
||||
return false, fmt.Errorf("check chat visibility: %w", err)
|
||||
}
|
||||
return visible, nil
|
||||
}
|
||||
|
||||
func createIdempotentMessage(
|
||||
ctx context.Context,
|
||||
tx pgx.Tx,
|
||||
chatID string,
|
||||
senderID string,
|
||||
text string,
|
||||
attachmentIDs []string,
|
||||
idempotencyKey string,
|
||||
requestHash []byte,
|
||||
idempotencyTTL time.Duration,
|
||||
) (model.Message, bool, error) {
|
||||
for {
|
||||
var (
|
||||
record idempotencyRecord
|
||||
found bool
|
||||
err error
|
||||
messageID string
|
||||
reserved bool
|
||||
message model.Message
|
||||
)
|
||||
|
||||
record, found, err = lockIdempotencyRecord(ctx, tx, senderID, chatID, idempotencyKey)
|
||||
if err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
if found && record.active {
|
||||
if !bytes.Equal(record.requestHash, requestHash) {
|
||||
return model.Message{}, false, ErrIdempotencyConflict
|
||||
}
|
||||
message, err = messageByID(ctx, tx, record.messageID)
|
||||
return message, true, err
|
||||
}
|
||||
if found {
|
||||
if err := deleteIdempotencyRecord(ctx, tx, senderID, chatID, idempotencyKey); err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
}
|
||||
|
||||
messageID = uuid.NewString()
|
||||
reserved, err = reserveIdempotencyKey(
|
||||
ctx, tx, senderID, chatID, idempotencyKey, requestHash, messageID, idempotencyTTL,
|
||||
)
|
||||
if err != nil {
|
||||
return model.Message{}, false, err
|
||||
}
|
||||
if !reserved {
|
||||
continue
|
||||
}
|
||||
|
||||
message, err = insertMessage(ctx, tx, messageID, chatID, senderID, text, attachmentIDs)
|
||||
return message, false, err
|
||||
}
|
||||
}
|
||||
|
||||
func deleteExpiredIdempotencyRecords(ctx context.Context, tx pgx.Tx, limit int) error {
|
||||
const query = `
|
||||
WITH expired AS (
|
||||
SELECT ctid
|
||||
FROM message_idempotency
|
||||
WHERE expires_at <= statement_timestamp()
|
||||
ORDER BY expires_at
|
||||
LIMIT $1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
DELETE FROM message_idempotency records
|
||||
USING expired
|
||||
WHERE records.ctid = expired.ctid`
|
||||
|
||||
if _, err := tx.Exec(ctx, query, limit); err != nil {
|
||||
return fmt.Errorf("delete expired idempotency records: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type idempotencyRecord struct {
|
||||
requestHash []byte
|
||||
messageID string
|
||||
active bool
|
||||
}
|
||||
|
||||
func lockIdempotencyRecord(
|
||||
ctx context.Context,
|
||||
tx pgx.Tx,
|
||||
userID string,
|
||||
chatID string,
|
||||
key string,
|
||||
) (idempotencyRecord, bool, error) {
|
||||
const query = `
|
||||
SELECT request_hash, message_id, expires_at > statement_timestamp()
|
||||
FROM message_idempotency
|
||||
WHERE user_id = $1 AND chat_id = $2 AND key = $3
|
||||
FOR UPDATE`
|
||||
|
||||
var (
|
||||
record idempotencyRecord
|
||||
err error
|
||||
)
|
||||
err = tx.QueryRow(ctx, query, userID, chatID, key).Scan(
|
||||
&record.requestHash,
|
||||
&record.messageID,
|
||||
&record.active,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return idempotencyRecord{}, false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return idempotencyRecord{}, false, fmt.Errorf("lock idempotency key: %w", err)
|
||||
}
|
||||
return record, true, nil
|
||||
}
|
||||
|
||||
func deleteIdempotencyRecord(ctx context.Context, tx pgx.Tx, userID, chatID, key string) error {
|
||||
const query = `
|
||||
DELETE FROM message_idempotency
|
||||
WHERE user_id = $1 AND chat_id = $2 AND key = $3`
|
||||
if _, err := tx.Exec(ctx, query, userID, chatID, key); err != nil {
|
||||
return fmt.Errorf("delete expired idempotency key: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func reserveIdempotencyKey(
|
||||
ctx context.Context,
|
||||
tx pgx.Tx,
|
||||
userID string,
|
||||
chatID string,
|
||||
key string,
|
||||
requestHash []byte,
|
||||
messageID string,
|
||||
ttl time.Duration,
|
||||
) (bool, error) {
|
||||
const query = `
|
||||
INSERT INTO message_idempotency (user_id, chat_id, key, request_hash, message_id, expires_at)
|
||||
VALUES ($1, $2, $3, $4, $5, statement_timestamp() + $6 * INTERVAL '1 second')
|
||||
ON CONFLICT (user_id, chat_id, key) DO NOTHING
|
||||
RETURNING true`
|
||||
|
||||
var (
|
||||
inserted bool
|
||||
err error
|
||||
)
|
||||
err = tx.QueryRow(ctx, query, userID, chatID, key, requestHash, messageID, int64(ttl/time.Second)).Scan(&inserted)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, nil
|
||||
}
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("reserve idempotency key: %w", err)
|
||||
}
|
||||
return inserted, nil
|
||||
}
|
||||
|
||||
func insertMessage(
|
||||
ctx context.Context,
|
||||
tx pgx.Tx,
|
||||
messageID string,
|
||||
chatID string,
|
||||
senderID string,
|
||||
text string,
|
||||
attachmentIDs []string,
|
||||
) (model.Message, error) {
|
||||
const query = `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id, chat_id, sender_id, text, created_at`
|
||||
|
||||
var (
|
||||
message model.Message
|
||||
err error
|
||||
)
|
||||
err = tx.QueryRow(ctx, query, messageID, chatID, senderID, text).Scan(
|
||||
&message.ID,
|
||||
&message.ChatID,
|
||||
&message.SenderID,
|
||||
&message.Text,
|
||||
&message.CreatedAt,
|
||||
)
|
||||
if err != nil {
|
||||
return model.Message{}, fmt.Errorf("insert message: %w", err)
|
||||
}
|
||||
if err := insertMessageAttachments(ctx, tx, messageID, chatID, attachmentIDs); err != nil {
|
||||
return model.Message{}, err
|
||||
}
|
||||
message.AttachmentIDs = make([]string, len(attachmentIDs))
|
||||
copy(message.AttachmentIDs, attachmentIDs)
|
||||
return message, nil
|
||||
}
|
||||
|
||||
func insertMessageAttachments(ctx context.Context, tx pgx.Tx, messageID, chatID string, attachmentIDs []string) error {
|
||||
const query = `
|
||||
INSERT INTO message_attachments (message_id, chat_id, attachment_id, position)
|
||||
VALUES ($1, $2, $3, $4)`
|
||||
for position, attachmentID := range attachmentIDs {
|
||||
if _, err := tx.Exec(ctx, query, messageID, chatID, attachmentID, position); err != nil {
|
||||
return fmt.Errorf("insert message attachment: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func messageByID(ctx context.Context, tx pgx.Tx, messageID string) (model.Message, error) {
|
||||
const query = `
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(
|
||||
SELECT ma.attachment_id::text
|
||||
FROM message_attachments ma
|
||||
WHERE ma.message_id = m.id
|
||||
ORDER BY ma.position
|
||||
)
|
||||
FROM messages m
|
||||
WHERE m.id = $1`
|
||||
|
||||
var (
|
||||
message model.Message
|
||||
err error
|
||||
)
|
||||
err = tx.QueryRow(ctx, query, messageID).Scan(
|
||||
&message.ID,
|
||||
&message.ChatID,
|
||||
&message.SenderID,
|
||||
&message.Text,
|
||||
&message.CreatedAt,
|
||||
&message.AttachmentIDs,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Message{}, fmt.Errorf("idempotency result message not found")
|
||||
}
|
||||
if err != nil {
|
||||
return model.Message{}, fmt.Errorf("get idempotency result message: %w", err)
|
||||
}
|
||||
return message, nil
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
}
|
||||
|
||||
func New(pool *pgxpool.Pool) *Store {
|
||||
return &Store{pool: pool}
|
||||
}
|
||||
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
return s.pool.Ping(ctx)
|
||||
}
|
||||
|
||||
func (s *Store) CreateUser(
|
||||
ctx context.Context,
|
||||
username string,
|
||||
displayName string,
|
||||
passwordHash string,
|
||||
) (model.User, error) {
|
||||
const query = `
|
||||
INSERT INTO users (id, username, display_name, password_hash)
|
||||
VALUES ($1, $2, $3, $4)
|
||||
RETURNING id, username, display_name, created_at`
|
||||
|
||||
var user model.User
|
||||
err := s.pool.QueryRow(ctx, query, uuid.NewString(), username, displayName, passwordHash).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
)
|
||||
if isUniqueViolation(err) {
|
||||
return model.User{}, ErrConflict
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, fmt.Errorf("create user: %w", err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *Store) UserByID(ctx context.Context, id string) (model.User, error) {
|
||||
const query = `
|
||||
SELECT id, username, display_name, created_at
|
||||
FROM users
|
||||
WHERE id = $1`
|
||||
|
||||
var user model.User
|
||||
err := s.pool.QueryRow(ctx, query, id).Scan(
|
||||
&user.ID,
|
||||
&user.Username,
|
||||
&user.DisplayName,
|
||||
&user.CreatedAt,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.User{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.User{}, fmt.Errorf("get user by id: %w", err)
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (s *Store) UserByUsername(ctx context.Context, username string) (model.UserCredentials, error) {
|
||||
const query = `
|
||||
SELECT id, username, display_name, created_at, password_hash
|
||||
FROM users
|
||||
WHERE username = $1`
|
||||
|
||||
var credentials model.UserCredentials
|
||||
err := s.pool.QueryRow(ctx, query, username).Scan(
|
||||
&credentials.ID,
|
||||
&credentials.Username,
|
||||
&credentials.DisplayName,
|
||||
&credentials.CreatedAt,
|
||||
&credentials.PasswordHash,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.UserCredentials{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.UserCredentials{}, fmt.Errorf("get user by username: %w", err)
|
||||
}
|
||||
|
||||
return credentials, nil
|
||||
}
|
||||
|
||||
func (s *Store) CreateChat(
|
||||
ctx context.Context,
|
||||
title string,
|
||||
memberIDs []string,
|
||||
callerID string,
|
||||
) (model.Chat, error) {
|
||||
if !validMembers(memberIDs, callerID) {
|
||||
return model.Chat{}, ErrInvalidMembers
|
||||
}
|
||||
|
||||
tx, err := s.pool.BeginTx(ctx, pgx.TxOptions{})
|
||||
if err != nil {
|
||||
return model.Chat{}, fmt.Errorf("begin create chat transaction: %w", err)
|
||||
}
|
||||
defer func() { _ = tx.Rollback(context.WithoutCancel(ctx)) }()
|
||||
|
||||
valid, err := allUsersExist(ctx, tx, memberIDs)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
if !valid {
|
||||
return model.Chat{}, ErrInvalidMembers
|
||||
}
|
||||
|
||||
chat, err := insertChat(ctx, tx, title)
|
||||
if err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
if err := insertMembers(ctx, tx, chat.ID, memberIDs); err != nil {
|
||||
return model.Chat{}, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return model.Chat{}, fmt.Errorf("commit create chat transaction: %w", err)
|
||||
}
|
||||
|
||||
chat.MemberIDs = append([]string(nil), memberIDs...)
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func validMembers(memberIDs []string, callerID string) bool {
|
||||
callerUUID, err := uuid.Parse(callerID)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]struct{}, len(memberIDs))
|
||||
callerIncluded := false
|
||||
for _, memberID := range memberIDs {
|
||||
memberUUID, err := uuid.Parse(memberID)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
if _, exists := seen[memberUUID]; exists {
|
||||
return false
|
||||
}
|
||||
|
||||
seen[memberUUID] = struct{}{}
|
||||
callerIncluded = callerIncluded || memberUUID == callerUUID
|
||||
}
|
||||
|
||||
return callerIncluded
|
||||
}
|
||||
|
||||
func allUsersExist(ctx context.Context, tx pgx.Tx, memberIDs []string) (bool, error) {
|
||||
const query = `
|
||||
SELECT count(*)
|
||||
FROM users
|
||||
WHERE id::text = ANY($1)`
|
||||
|
||||
var count int
|
||||
if err := tx.QueryRow(ctx, query, memberIDs).Scan(&count); err != nil {
|
||||
return false, fmt.Errorf("check chat members: %w", err)
|
||||
}
|
||||
|
||||
return count == len(memberIDs), nil
|
||||
}
|
||||
|
||||
func insertChat(ctx context.Context, tx pgx.Tx, title string) (model.Chat, error) {
|
||||
const query = `
|
||||
INSERT INTO chats (id, title)
|
||||
VALUES ($1, $2)
|
||||
RETURNING id, title, created_at`
|
||||
|
||||
var chat model.Chat
|
||||
if err := tx.QueryRow(ctx, query, uuid.NewString(), title).Scan(&chat.ID, &chat.Title, &chat.CreatedAt); err != nil {
|
||||
return model.Chat{}, fmt.Errorf("insert chat: %w", err)
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func insertMembers(ctx context.Context, tx pgx.Tx, chatID string, memberIDs []string) error {
|
||||
const query = `
|
||||
INSERT INTO chat_members (chat_id, user_id, position)
|
||||
VALUES ($1, $2, $3)`
|
||||
|
||||
batch := &pgx.Batch{}
|
||||
for position, memberID := range memberIDs {
|
||||
batch.Queue(query, chatID, memberID, position)
|
||||
}
|
||||
|
||||
results := tx.SendBatch(ctx, batch)
|
||||
defer func() { _ = results.Close() }()
|
||||
for range memberIDs {
|
||||
if _, err := results.Exec(); err != nil {
|
||||
return fmt.Errorf("insert chat member: %w", err)
|
||||
}
|
||||
}
|
||||
if err := results.Close(); err != nil {
|
||||
return fmt.Errorf("close chat members batch: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) ChatForUser(ctx context.Context, chatID, userID string) (model.Chat, error) {
|
||||
const query = `
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
array_agg(cm.user_id::text ORDER BY cm.position)
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE c.id = $1
|
||||
AND EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members visible
|
||||
WHERE visible.chat_id = c.id AND visible.user_id = $2
|
||||
)
|
||||
GROUP BY c.id, c.title, c.created_at`
|
||||
|
||||
var chat model.Chat
|
||||
err := s.pool.QueryRow(ctx, query, chatID, userID).Scan(
|
||||
&chat.ID,
|
||||
&chat.Title,
|
||||
&chat.CreatedAt,
|
||||
&chat.MemberIDs,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Chat{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Chat{}, fmt.Errorf("get chat for user: %w", err)
|
||||
}
|
||||
|
||||
return chat, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListChats(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
after *model.Position,
|
||||
limit int,
|
||||
) ([]model.Chat, bool, error) {
|
||||
if after != nil {
|
||||
valid, err := s.visibleChatPositionExists(ctx, userID, *after)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if !valid {
|
||||
return nil, false, ErrInvalidCursor
|
||||
}
|
||||
}
|
||||
|
||||
const query = `
|
||||
SELECT c.id, c.title, c.created_at,
|
||||
array_agg(all_members.user_id::text ORDER BY all_members.position)
|
||||
FROM chats c
|
||||
JOIN chat_members visible ON visible.chat_id = c.id AND visible.user_id = $1
|
||||
JOIN chat_members all_members ON all_members.chat_id = c.id
|
||||
WHERE ($2::timestamptz IS NULL OR (c.created_at, c.id) > ($2, $3::uuid))
|
||||
GROUP BY c.id, c.title, c.created_at
|
||||
ORDER BY c.created_at, c.id
|
||||
LIMIT $4`
|
||||
|
||||
var afterTime any
|
||||
var afterID any
|
||||
if after != nil {
|
||||
afterTime = after.CreatedAt
|
||||
afterID = after.ID
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, userID, afterTime, afterID, limit+1)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("list chats: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
chats, err := pgx.CollectRows(rows, pgx.RowToFunc[model.Chat](func(row pgx.CollectableRow) (model.Chat, error) {
|
||||
var chat model.Chat
|
||||
err := row.Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs)
|
||||
return chat, err
|
||||
}))
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("scan chats: %w", err)
|
||||
}
|
||||
|
||||
return page(chats, limit)
|
||||
}
|
||||
|
||||
func (s *Store) visibleChatPositionExists(
|
||||
ctx context.Context,
|
||||
userID string,
|
||||
position model.Position,
|
||||
) (bool, error) {
|
||||
const query = `
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM chats c
|
||||
JOIN chat_members cm ON cm.chat_id = c.id
|
||||
WHERE cm.user_id = $1 AND c.created_at = $2 AND c.id = $3
|
||||
)`
|
||||
|
||||
var exists bool
|
||||
if err := s.pool.QueryRow(ctx, query, userID, position.CreatedAt, position.ID).Scan(&exists); err != nil {
|
||||
return false, fmt.Errorf("validate chat cursor: %w", err)
|
||||
}
|
||||
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
func (s *Store) ListMessages(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
userID string,
|
||||
after *model.Position,
|
||||
limit int,
|
||||
) ([]model.Message, bool, error) {
|
||||
visible, err := s.chatVisible(ctx, chatID, userID)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if !visible {
|
||||
return nil, false, ErrNotFound
|
||||
}
|
||||
if after != nil {
|
||||
valid, err := s.messagePositionExists(ctx, chatID, *after)
|
||||
if err != nil {
|
||||
return nil, false, err
|
||||
}
|
||||
if !valid {
|
||||
return nil, false, ErrInvalidCursor
|
||||
}
|
||||
}
|
||||
|
||||
const query = `
|
||||
SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at,
|
||||
ARRAY(
|
||||
SELECT ma.attachment_id::text
|
||||
FROM message_attachments ma
|
||||
WHERE ma.message_id = m.id
|
||||
ORDER BY ma.position
|
||||
)
|
||||
FROM messages m
|
||||
WHERE m.chat_id = $1
|
||||
AND ($2::timestamptz IS NULL OR (m.created_at, m.id) > ($2, $3::uuid))
|
||||
ORDER BY m.created_at, m.id
|
||||
LIMIT $4`
|
||||
|
||||
var afterTime any
|
||||
var afterID any
|
||||
if after != nil {
|
||||
afterTime = after.CreatedAt
|
||||
afterID = after.ID
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx, query, chatID, afterTime, afterID, limit+1)
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("list messages: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
messages, err := pgx.CollectRows(rows, pgx.RowToFunc[model.Message](func(row pgx.CollectableRow) (model.Message, error) {
|
||||
var message model.Message
|
||||
err := row.Scan(
|
||||
&message.ID,
|
||||
&message.ChatID,
|
||||
&message.SenderID,
|
||||
&message.Text,
|
||||
&message.CreatedAt,
|
||||
&message.AttachmentIDs,
|
||||
)
|
||||
return message, err
|
||||
}))
|
||||
if err != nil {
|
||||
return nil, false, fmt.Errorf("scan messages: %w", err)
|
||||
}
|
||||
|
||||
return page(messages, limit)
|
||||
}
|
||||
|
||||
func (s *Store) chatVisible(ctx context.Context, chatID, userID string) (bool, error) {
|
||||
const query = `
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = $1 AND user_id = $2
|
||||
)`
|
||||
|
||||
var exists bool
|
||||
if err := s.pool.QueryRow(ctx, query, chatID, userID).Scan(&exists); err != nil {
|
||||
return false, fmt.Errorf("check chat visibility: %w", err)
|
||||
}
|
||||
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
func (s *Store) messagePositionExists(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
position model.Position,
|
||||
) (bool, error) {
|
||||
const query = `
|
||||
SELECT EXISTS (
|
||||
SELECT 1
|
||||
FROM messages
|
||||
WHERE chat_id = $1 AND created_at = $2 AND id = $3
|
||||
)`
|
||||
|
||||
var exists bool
|
||||
if err := s.pool.QueryRow(ctx, query, chatID, position.CreatedAt, position.ID).Scan(&exists); err != nil {
|
||||
return false, fmt.Errorf("validate message cursor: %w", err)
|
||||
}
|
||||
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
func page[T any](items []T, limit int) ([]T, bool, error) {
|
||||
if limit < 1 {
|
||||
return nil, false, fmt.Errorf("limit must be positive")
|
||||
}
|
||||
if len(items) <= limit {
|
||||
return items, false, nil
|
||||
}
|
||||
|
||||
return items[:limit], true, nil
|
||||
}
|
||||
|
||||
func isUniqueViolation(err error) bool {
|
||||
var postgresError *pgconn.PgError
|
||||
return errors.As(err, &postgresError) && postgresError.Code == "23505"
|
||||
}
|
||||
@@ -0,0 +1,401 @@
|
||||
package postgres_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/database"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/postgres"
|
||||
)
|
||||
|
||||
type PostgresSuite struct {
|
||||
suite.Suite
|
||||
pool *pgxpool.Pool
|
||||
store *postgres.Store
|
||||
}
|
||||
|
||||
func TestPostgresSuite(t *testing.T) {
|
||||
suite.Run(t, new(PostgresSuite))
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) SetupSuite() {
|
||||
s.pool = openTestDatabase(s.T())
|
||||
s.store = postgres.New(s.pool)
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TearDownSuite() {
|
||||
if s.pool != nil {
|
||||
s.pool.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestConcurrentUsernameCreation() {
|
||||
t := s.T()
|
||||
store := s.store
|
||||
username := "race_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:16]
|
||||
|
||||
const workers = 8
|
||||
results := make(chan error, workers)
|
||||
var group sync.WaitGroup
|
||||
for range workers {
|
||||
group.Add(1)
|
||||
go func() {
|
||||
defer group.Done()
|
||||
_, err := store.CreateUser(context.Background(), username, "Race user", "password-hash")
|
||||
results <- err
|
||||
}()
|
||||
}
|
||||
group.Wait()
|
||||
close(results)
|
||||
|
||||
var created, conflicts int
|
||||
for err := range results {
|
||||
switch {
|
||||
case err == nil:
|
||||
created++
|
||||
case errors.Is(err, postgres.ErrConflict):
|
||||
conflicts++
|
||||
default:
|
||||
t.Fatalf("CreateUser() error = %v", err)
|
||||
}
|
||||
}
|
||||
if created != 1 || conflicts != workers-1 {
|
||||
t.Fatalf("created = %d, conflicts = %d", created, conflicts)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestCreateChatRollsBackForUnknownMember() {
|
||||
t := s.T()
|
||||
pool := s.pool
|
||||
store := s.store
|
||||
owner, err := store.CreateUser(context.Background(), uniqueUsername(), "Owner", "password-hash")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateUser() error = %v", err)
|
||||
}
|
||||
|
||||
before := chatCount(t, pool)
|
||||
_, err = store.CreateChat(context.Background(), "Invalid chat", []string{owner.ID, uuid.NewString()}, owner.ID)
|
||||
if !errors.Is(err, postgres.ErrInvalidMembers) {
|
||||
t.Fatalf("CreateChat() error = %v, want ErrInvalidMembers", err)
|
||||
}
|
||||
if after := chatCount(t, pool); after != before {
|
||||
t.Fatalf("chat count changed from %d to %d", before, after)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestMessageIdempotencyReplayAndConflict() {
|
||||
t := s.T()
|
||||
pool := s.pool
|
||||
store := s.store
|
||||
owner, chatID := createOwnerAndChat(t, store)
|
||||
key := uuid.NewString()
|
||||
|
||||
first, replay, err := store.CreateMessage(context.Background(), chatID, owner.ID, "same body", nil, key, 24*time.Hour)
|
||||
if err != nil || replay {
|
||||
t.Fatalf("first CreateMessage() = (%v, %t, %v)", first, replay, err)
|
||||
}
|
||||
second, replay, err := store.CreateMessage(context.Background(), chatID, owner.ID, "same body", []string{}, key, 24*time.Hour)
|
||||
if err != nil || !replay {
|
||||
t.Fatalf("replay CreateMessage() = (%v, %t, %v)", second, replay, err)
|
||||
}
|
||||
s.Equal(first, second)
|
||||
if _, _, err := store.CreateMessage(context.Background(), chatID, owner.ID, "different body", nil, key, 24*time.Hour); !errors.Is(err, postgres.ErrIdempotencyConflict) {
|
||||
t.Fatalf("conflicting CreateMessage() error = %v, want ErrIdempotencyConflict", err)
|
||||
}
|
||||
if count := messageCount(t, pool, chatID); count != 1 {
|
||||
t.Fatalf("message count = %d, want 1", count)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestAttachmentAccessAndMessageLinking() {
|
||||
owner, chatID := createOwnerAndChat(s.T(), s.store)
|
||||
outsider, err := s.store.CreateUser(context.Background(), uniqueUsername(), "Outsider", "password-hash")
|
||||
s.Require().NoError(err)
|
||||
attachment := model.Attachment{
|
||||
ID: uuid.NewString(), ChatID: chatID, OwnerID: owner.ID, Filename: "photo.png",
|
||||
ContentType: "image/png", SizeBytes: 128, SHA256: strings.Repeat("a", 64),
|
||||
ObjectKey: "attachments/" + uuid.NewString() + "/original",
|
||||
}
|
||||
pending, err := s.store.CreatePendingAttachment(context.Background(), attachment)
|
||||
s.Require().NoError(err)
|
||||
created, err := s.store.MarkAttachmentReady(context.Background(), pending.ID, pending.ObjectKey)
|
||||
s.Require().NoError(err)
|
||||
s.Equal("ready", created.Status)
|
||||
s.Empty(created.Variants)
|
||||
s.Nil(created.ErrorCode)
|
||||
|
||||
visible, err := s.store.AttachmentForUser(context.Background(), created.ID, owner.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(created, visible)
|
||||
_, err = s.store.AttachmentForUser(context.Background(), created.ID, outsider.ID)
|
||||
s.ErrorIs(err, postgres.ErrNotFound)
|
||||
|
||||
message, replay, err := s.store.CreateMessage(
|
||||
context.Background(), chatID, owner.ID, "", []string{created.ID}, uuid.NewString(), 24*time.Hour,
|
||||
)
|
||||
s.Require().NoError(err)
|
||||
s.False(replay)
|
||||
s.Equal([]string{created.ID}, message.AttachmentIDs)
|
||||
|
||||
messages, _, err := s.store.ListMessages(context.Background(), chatID, owner.ID, nil, 10)
|
||||
s.Require().NoError(err)
|
||||
s.Len(messages, 1)
|
||||
s.Equal([]string{created.ID}, messages[0].AttachmentIDs)
|
||||
referenced, err := s.store.AttachmentReferenced(context.Background(), created.ID)
|
||||
s.Require().NoError(err)
|
||||
s.True(referenced)
|
||||
deleted, err := s.store.ClaimAttachmentForDeletion(context.Background(), created, time.Now().Add(time.Hour))
|
||||
s.Require().NoError(err)
|
||||
s.False(deleted)
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestAttachmentDeletionClaimChecksLifecycleUnderLock() {
|
||||
owner, chatID := createOwnerAndChat(s.T(), s.store)
|
||||
pending, err := s.store.CreatePendingAttachment(context.Background(), model.Attachment{
|
||||
ID: uuid.NewString(), ChatID: chatID, OwnerID: owner.ID, Filename: "pending.png",
|
||||
ContentType: "image/png", SizeBytes: 128, SHA256: strings.Repeat("c", 64),
|
||||
ObjectKey: "attachments/" + uuid.NewString() + "/original",
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
|
||||
claimed, err := s.store.ClaimAttachmentForDeletion(context.Background(), pending, time.Now().Add(time.Hour))
|
||||
s.Require().NoError(err)
|
||||
s.True(claimed)
|
||||
deleted, err := s.store.DeleteAttachmentIfDeleting(context.Background(), pending.ID)
|
||||
s.Require().NoError(err)
|
||||
s.True(deleted)
|
||||
|
||||
pending, err = s.store.CreatePendingAttachment(context.Background(), model.Attachment{
|
||||
ID: uuid.NewString(), ChatID: chatID, OwnerID: owner.ID, Filename: "completed.png",
|
||||
ContentType: "image/png", SizeBytes: 128, SHA256: strings.Repeat("d", 64),
|
||||
ObjectKey: "attachments/" + uuid.NewString() + "/original",
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
ready, err := s.store.MarkAttachmentReady(context.Background(), pending.ID, pending.ObjectKey)
|
||||
s.Require().NoError(err)
|
||||
|
||||
claimed, err = s.store.ClaimAttachmentForDeletion(context.Background(), pending, time.Now().Add(time.Hour))
|
||||
s.Require().NoError(err)
|
||||
s.False(claimed)
|
||||
visible, err := s.store.AttachmentForUser(context.Background(), ready.ID, owner.ID)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(model.AttachmentReady, visible.Status)
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestMessageRejectsAttachmentFromAnotherChat() {
|
||||
owner, firstChatID := createOwnerAndChat(s.T(), s.store)
|
||||
secondChat, err := s.store.CreateChat(context.Background(), "Second", []string{owner.ID}, owner.ID)
|
||||
s.Require().NoError(err)
|
||||
pending, err := s.store.CreatePendingAttachment(context.Background(), model.Attachment{
|
||||
ID: uuid.NewString(), ChatID: firstChatID, OwnerID: owner.ID, Filename: "photo.png",
|
||||
ContentType: "image/png", SizeBytes: 128, SHA256: strings.Repeat("b", 64),
|
||||
ObjectKey: "attachments/" + uuid.NewString() + "/original",
|
||||
})
|
||||
s.Require().NoError(err)
|
||||
attachment, err := s.store.MarkAttachmentReady(context.Background(), pending.ID, pending.ObjectKey)
|
||||
s.Require().NoError(err)
|
||||
_, _, err = s.store.CreateMessage(
|
||||
context.Background(), secondChat.ID, owner.ID, "wrong chat", []string{attachment.ID}, uuid.NewString(), 24*time.Hour,
|
||||
)
|
||||
s.ErrorIs(err, postgres.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestConcurrentMessageIdempotency() {
|
||||
t := s.T()
|
||||
pool := s.pool
|
||||
stores := []*postgres.Store{postgres.New(pool), postgres.New(pool)}
|
||||
owner, chatID := createOwnerAndChat(t, stores[0])
|
||||
key := uuid.NewString()
|
||||
|
||||
const workers = 8
|
||||
type result struct {
|
||||
message model.Message
|
||||
replay bool
|
||||
err error
|
||||
}
|
||||
results := make(chan result, workers)
|
||||
var group sync.WaitGroup
|
||||
for worker := range workers {
|
||||
group.Add(1)
|
||||
go func() {
|
||||
defer group.Done()
|
||||
message, replay, err := stores[worker%len(stores)].CreateMessage(
|
||||
context.Background(), chatID, owner.ID, "concurrent body", nil, key, 24*time.Hour,
|
||||
)
|
||||
results <- result{message: message, replay: replay, err: err}
|
||||
}()
|
||||
}
|
||||
group.Wait()
|
||||
close(results)
|
||||
|
||||
var messageID string
|
||||
var created int
|
||||
for result := range results {
|
||||
if result.err != nil {
|
||||
t.Fatalf("CreateMessage() error = %v", result.err)
|
||||
}
|
||||
if messageID == "" {
|
||||
messageID = result.message.ID
|
||||
}
|
||||
if result.message.ID != messageID {
|
||||
t.Fatalf("message ID = %s, want %s", result.message.ID, messageID)
|
||||
}
|
||||
if !result.replay {
|
||||
created++
|
||||
}
|
||||
}
|
||||
if created != 1 {
|
||||
t.Fatalf("new message results = %d, want 1", created)
|
||||
}
|
||||
if count := messageCount(t, pool, chatID); count != 1 {
|
||||
t.Fatalf("message count = %d, want 1", count)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestMessageIdempotencyScopeAndExpiry() {
|
||||
t := s.T()
|
||||
pool := s.pool
|
||||
store := s.store
|
||||
owner, chatID := createOwnerAndChat(t, store)
|
||||
second, err := store.CreateUser(context.Background(), uniqueUsername(), "Second", "password-hash")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateUser() error = %v", err)
|
||||
}
|
||||
chat, err := store.CreateChat(context.Background(), "Shared", []string{owner.ID, second.ID}, owner.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateChat() error = %v", err)
|
||||
}
|
||||
key := uuid.NewString()
|
||||
|
||||
if _, _, err := store.CreateMessage(context.Background(), chat.ID, owner.ID, "owner", nil, key, 24*time.Hour); err != nil {
|
||||
t.Fatalf("owner CreateMessage() error = %v", err)
|
||||
}
|
||||
if _, _, err := store.CreateMessage(context.Background(), chat.ID, second.ID, "second", nil, key, 24*time.Hour); err != nil {
|
||||
t.Fatalf("second user CreateMessage() error = %v", err)
|
||||
}
|
||||
if _, _, err := store.CreateMessage(context.Background(), chatID, owner.ID, "other chat", nil, key, 24*time.Hour); err != nil {
|
||||
t.Fatalf("other chat CreateMessage() error = %v", err)
|
||||
}
|
||||
if _, err := pool.Exec(context.Background(), `
|
||||
UPDATE message_idempotency
|
||||
SET created_at = clock_timestamp() - INTERVAL '2 days',
|
||||
expires_at = clock_timestamp() - INTERVAL '1 day'
|
||||
WHERE user_id = $1 AND chat_id = $2 AND key = $3`, owner.ID, chat.ID, key); err != nil {
|
||||
t.Fatalf("expire idempotency key: %v", err)
|
||||
}
|
||||
message, replay, err := store.CreateMessage(context.Background(), chat.ID, owner.ID, "after expiry", nil, key, 24*time.Hour)
|
||||
if err != nil || replay || message.Text != "after expiry" {
|
||||
t.Fatalf("expired CreateMessage() = (%v, %t, %v)", message, replay, err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PostgresSuite) TestExpiredIdempotencyRecordsAreCleanedOnNewMessages() {
|
||||
t := s.T()
|
||||
owner, chatID := createOwnerAndChat(t, s.store)
|
||||
expiredKey := uuid.NewString()
|
||||
if _, _, err := s.store.CreateMessage(context.Background(), chatID, owner.ID, "expired", nil, expiredKey, 24*time.Hour); err != nil {
|
||||
t.Fatalf("create expired message: %v", err)
|
||||
}
|
||||
if _, err := s.pool.Exec(context.Background(), `
|
||||
UPDATE message_idempotency
|
||||
SET created_at = clock_timestamp() - INTERVAL '2 days',
|
||||
expires_at = clock_timestamp() - INTERVAL '1 day'
|
||||
WHERE user_id = $1 AND chat_id = $2 AND key = $3`, owner.ID, chatID, expiredKey); err != nil {
|
||||
t.Fatalf("expire idempotency key: %v", err)
|
||||
}
|
||||
if _, _, err := s.store.CreateMessage(
|
||||
context.Background(), chatID, owner.ID, "new message", nil, uuid.NewString(), 24*time.Hour,
|
||||
); err != nil {
|
||||
t.Fatalf("create new message: %v", err)
|
||||
}
|
||||
|
||||
var remaining int
|
||||
if err := s.pool.QueryRow(context.Background(), `
|
||||
SELECT count(*)
|
||||
FROM message_idempotency
|
||||
WHERE user_id = $1 AND chat_id = $2 AND key = $3`, owner.ID, chatID, expiredKey).Scan(&remaining); err != nil {
|
||||
t.Fatalf("count expired idempotency records: %v", err)
|
||||
}
|
||||
if remaining != 0 {
|
||||
t.Fatalf("expired idempotency records = %d, want 0", remaining)
|
||||
}
|
||||
}
|
||||
|
||||
func createOwnerAndChat(t *testing.T, store *postgres.Store) (model.User, string) {
|
||||
t.Helper()
|
||||
owner, err := store.CreateUser(context.Background(), uniqueUsername(), "Owner", "password-hash")
|
||||
if err != nil {
|
||||
t.Fatalf("CreateUser() error = %v", err)
|
||||
}
|
||||
chat, err := store.CreateChat(context.Background(), "Chat", []string{owner.ID}, owner.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateChat() error = %v", err)
|
||||
}
|
||||
return owner, chat.ID
|
||||
}
|
||||
|
||||
func messageCount(t *testing.T, pool *pgxpool.Pool, chatID string) int {
|
||||
t.Helper()
|
||||
var count int
|
||||
if err := pool.QueryRow(context.Background(), "SELECT count(*) FROM messages WHERE chat_id = $1", chatID).Scan(&count); err != nil {
|
||||
t.Fatalf("count messages: %v", err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
func openTestDatabase(t *testing.T) *pgxpool.Pool {
|
||||
t.Helper()
|
||||
url := testSecret(t, "TEST_DATABASE_URL", "TEST_DATABASE_URL_FILE")
|
||||
pool, err := database.Open(context.Background(), database.Config{
|
||||
URL: url, MinConnections: 0, MaxConnections: 10,
|
||||
MaxConnectionAge: time.Minute, MaxConnectionIdle: time.Minute,
|
||||
HealthCheckPeriod: time.Minute, ConnectTimeout: 5 * time.Second,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("database.Open() error = %v", err)
|
||||
}
|
||||
if err := database.Migrate(context.Background(), pool, 30*time.Second); err != nil {
|
||||
pool.Close()
|
||||
t.Fatalf("database.Migrate() error = %v", err)
|
||||
}
|
||||
return pool
|
||||
}
|
||||
|
||||
func testSecret(t *testing.T, valueName, fileName string) string {
|
||||
t.Helper()
|
||||
if value := strings.TrimSpace(os.Getenv(valueName)); value != "" {
|
||||
return value
|
||||
}
|
||||
path := strings.TrimSpace(os.Getenv(fileName))
|
||||
if path == "" {
|
||||
t.Skipf("set %s or %s to run integration tests", valueName, fileName)
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("read %s: %v", fileName, err)
|
||||
}
|
||||
return strings.TrimSpace(string(data))
|
||||
}
|
||||
|
||||
func uniqueUsername() string {
|
||||
return "u_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:20]
|
||||
}
|
||||
|
||||
func chatCount(t *testing.T, pool *pgxpool.Pool) int {
|
||||
t.Helper()
|
||||
var count int
|
||||
if err := pool.QueryRow(context.Background(), "SELECT count(*) FROM chats").Scan(&count); err != nil {
|
||||
t.Fatalf("count chats: %v", err)
|
||||
}
|
||||
return count
|
||||
}
|
||||
@@ -0,0 +1,350 @@
|
||||
package reconcile
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
)
|
||||
|
||||
type MetadataStore interface {
|
||||
ListAttachments(context.Context, string, int) ([]model.Attachment, string, error)
|
||||
AttachmentExistsByObjectKey(context.Context, string) (bool, error)
|
||||
ClaimAttachmentForDeletion(context.Context, model.Attachment, time.Time) (bool, error)
|
||||
DeleteAttachmentIfDeleting(context.Context, string) (bool, error)
|
||||
}
|
||||
|
||||
type ObjectStore interface {
|
||||
List(context.Context, string, string, int) ([]model.StoredObject, string, error)
|
||||
Delete(context.Context, string) error
|
||||
}
|
||||
|
||||
type Config struct {
|
||||
Prefix string
|
||||
PageSize int
|
||||
GraceTime time.Duration
|
||||
UnreferencedRetention time.Duration
|
||||
Apply bool
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
type Report struct {
|
||||
MetadataScanned int `json:"metadata_scanned"`
|
||||
ObjectsScanned int `json:"objects_scanned"`
|
||||
Consistent int `json:"consistent"`
|
||||
FreshPendingAttachments int `json:"fresh_pending_attachments"`
|
||||
OldPendingAttachments int `json:"old_pending_attachments"`
|
||||
DeletingAttachments int `json:"deleting_attachments"`
|
||||
FreshUnreferencedAttachments int `json:"fresh_unreferenced_attachments"`
|
||||
OldUnreferencedAttachments int `json:"old_unreferenced_attachments"`
|
||||
DeletedAttachmentObjects int `json:"deleted_attachment_objects"`
|
||||
FreshOrphanObjects int `json:"fresh_orphan_objects"`
|
||||
OldOrphanObjects int `json:"old_orphan_objects"`
|
||||
DeletedOrphanObjects int `json:"deleted_orphan_objects"`
|
||||
FreshMissingObjects int `json:"fresh_missing_objects"`
|
||||
ReferencedMissingObjects int `json:"referenced_missing_objects"`
|
||||
OldUnreferencedMetadata int `json:"old_unreferenced_metadata"`
|
||||
DeletedUnreferencedRows int `json:"deleted_unreferenced_rows"`
|
||||
}
|
||||
|
||||
type Reconciler struct {
|
||||
metadata MetadataStore
|
||||
objects ObjectStore
|
||||
config Config
|
||||
}
|
||||
|
||||
func New(metadata MetadataStore, objects ObjectStore, config Config) (*Reconciler, error) {
|
||||
if config.PageSize < 1 || config.PageSize > 1000 {
|
||||
return nil, errors.New("page size must be between 1 and 1000")
|
||||
}
|
||||
if config.GraceTime < 0 {
|
||||
return nil, errors.New("grace time must not be negative")
|
||||
}
|
||||
if config.UnreferencedRetention <= 0 {
|
||||
return nil, errors.New("unreferenced retention must be positive")
|
||||
}
|
||||
if config.Now == nil {
|
||||
config.Now = time.Now
|
||||
}
|
||||
return &Reconciler{metadata: metadata, objects: objects, config: config}, nil
|
||||
}
|
||||
|
||||
func (r *Reconciler) Run(ctx context.Context) (Report, error) {
|
||||
metadata, err := newMetadataIterator(ctx, r.metadata, r.config.PageSize)
|
||||
if err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
objects, err := newObjectIterator(ctx, r.objects, r.config.Prefix, r.config.PageSize)
|
||||
if err != nil {
|
||||
return Report{}, err
|
||||
}
|
||||
|
||||
now := r.config.Now()
|
||||
anomalyCutoff := now.Add(-r.config.GraceTime)
|
||||
retentionCutoff := now.Add(-r.config.UnreferencedRetention)
|
||||
var report Report
|
||||
for metadata.current != nil || objects.current != nil {
|
||||
switch {
|
||||
case metadata.current == nil || objects.current != nil && objects.current.Key < metadata.current.ObjectKey:
|
||||
if err := r.handleOrphanObject(ctx, *objects.current, anomalyCutoff, &report); err != nil {
|
||||
return report, err
|
||||
}
|
||||
if err := objects.advance(ctx); err != nil {
|
||||
return report, err
|
||||
}
|
||||
case objects.current == nil || metadata.current.ObjectKey < objects.current.Key:
|
||||
if err := r.handleMissingObject(ctx, *metadata.current, anomalyCutoff, &report); err != nil {
|
||||
return report, err
|
||||
}
|
||||
if err := metadata.advance(ctx); err != nil {
|
||||
return report, err
|
||||
}
|
||||
default:
|
||||
if err := r.handlePair(ctx, *metadata.current, retentionCutoff, anomalyCutoff, &report); err != nil {
|
||||
return report, err
|
||||
}
|
||||
if err := metadata.advance(ctx); err != nil {
|
||||
return report, err
|
||||
}
|
||||
if err := objects.advance(ctx); err != nil {
|
||||
return report, err
|
||||
}
|
||||
}
|
||||
}
|
||||
return report, nil
|
||||
}
|
||||
|
||||
func (r *Reconciler) handlePair(
|
||||
ctx context.Context,
|
||||
metadata model.Attachment,
|
||||
retentionCutoff time.Time,
|
||||
anomalyCutoff time.Time,
|
||||
report *Report,
|
||||
) error {
|
||||
report.MetadataScanned++
|
||||
report.ObjectsScanned++
|
||||
switch metadata.Status {
|
||||
case model.AttachmentPending:
|
||||
if metadata.CreatedAt.After(anomalyCutoff) {
|
||||
report.FreshPendingAttachments++
|
||||
report.Consistent++
|
||||
return nil
|
||||
}
|
||||
report.OldPendingAttachments++
|
||||
return r.deletePair(ctx, metadata, anomalyCutoff, report)
|
||||
case model.AttachmentDeleting:
|
||||
report.DeletingAttachments++
|
||||
return r.deleteClaimedPair(ctx, metadata, report)
|
||||
case model.AttachmentReady:
|
||||
if metadata.Referenced {
|
||||
report.Consistent++
|
||||
return nil
|
||||
}
|
||||
age := metadata.CreatedAt
|
||||
if metadata.ReadyAt != nil {
|
||||
age = *metadata.ReadyAt
|
||||
}
|
||||
if age.After(retentionCutoff) {
|
||||
report.FreshUnreferencedAttachments++
|
||||
report.Consistent++
|
||||
return nil
|
||||
}
|
||||
report.OldUnreferencedAttachments++
|
||||
return r.deletePair(ctx, metadata, retentionCutoff, report)
|
||||
default:
|
||||
return fmt.Errorf("attachment %q has unknown status %q", metadata.ID, metadata.Status)
|
||||
}
|
||||
}
|
||||
|
||||
func (r *Reconciler) deletePair(ctx context.Context, attachment model.Attachment, cutoff time.Time, report *Report) error {
|
||||
if !r.config.Apply {
|
||||
return nil
|
||||
}
|
||||
claimed, err := r.metadata.ClaimAttachmentForDeletion(ctx, attachment, cutoff)
|
||||
if err != nil {
|
||||
return fmt.Errorf("claim attachment %q: %w", attachment.ID, err)
|
||||
}
|
||||
if !claimed {
|
||||
return nil
|
||||
}
|
||||
return r.deleteClaimedPair(ctx, attachment, report)
|
||||
}
|
||||
|
||||
func (r *Reconciler) deleteClaimedPair(ctx context.Context, attachment model.Attachment, report *Report) error {
|
||||
if !r.config.Apply {
|
||||
return nil
|
||||
}
|
||||
if err := r.objects.Delete(ctx, attachment.ObjectKey); err != nil {
|
||||
return fmt.Errorf("delete attachment object %q: %w", attachment.ObjectKey, err)
|
||||
}
|
||||
report.DeletedAttachmentObjects++
|
||||
deleted, err := r.metadata.DeleteAttachmentIfDeleting(ctx, attachment.ID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete attachment metadata %q: %w", attachment.ID, err)
|
||||
}
|
||||
if deleted {
|
||||
report.DeletedUnreferencedRows++
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Reconciler) handleOrphanObject(
|
||||
ctx context.Context,
|
||||
object model.StoredObject,
|
||||
cutoff time.Time,
|
||||
report *Report,
|
||||
) error {
|
||||
report.ObjectsScanned++
|
||||
if object.LastModified.After(cutoff) {
|
||||
report.FreshOrphanObjects++
|
||||
return nil
|
||||
}
|
||||
report.OldOrphanObjects++
|
||||
if !r.config.Apply {
|
||||
return nil
|
||||
}
|
||||
exists, err := r.metadata.AttachmentExistsByObjectKey(ctx, object.Key)
|
||||
if err != nil {
|
||||
return fmt.Errorf("recheck orphan object %q: %w", object.Key, err)
|
||||
}
|
||||
if exists {
|
||||
return nil
|
||||
}
|
||||
if err := r.objects.Delete(ctx, object.Key); err != nil {
|
||||
return fmt.Errorf("delete orphan object %q: %w", object.Key, err)
|
||||
}
|
||||
report.DeletedOrphanObjects++
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Reconciler) handleMissingObject(
|
||||
ctx context.Context,
|
||||
metadata model.Attachment,
|
||||
cutoff time.Time,
|
||||
report *Report,
|
||||
) error {
|
||||
report.MetadataScanned++
|
||||
if metadata.Status == model.AttachmentDeleting {
|
||||
return r.deleteClaimedMetadata(ctx, metadata, report)
|
||||
}
|
||||
if metadata.CreatedAt.After(cutoff) {
|
||||
report.FreshMissingObjects++
|
||||
return nil
|
||||
}
|
||||
if metadata.Referenced {
|
||||
report.ReferencedMissingObjects++
|
||||
return nil
|
||||
}
|
||||
report.OldUnreferencedMetadata++
|
||||
if !r.config.Apply {
|
||||
return nil
|
||||
}
|
||||
claimed, err := r.metadata.ClaimAttachmentForDeletion(ctx, metadata, cutoff)
|
||||
if err != nil {
|
||||
return fmt.Errorf("claim missing attachment metadata %q: %w", metadata.ID, err)
|
||||
}
|
||||
if !claimed {
|
||||
return nil
|
||||
}
|
||||
return r.deleteClaimedMetadata(ctx, metadata, report)
|
||||
}
|
||||
|
||||
func (r *Reconciler) deleteClaimedMetadata(ctx context.Context, metadata model.Attachment, report *Report) error {
|
||||
deleted, err := r.metadata.DeleteAttachmentIfDeleting(ctx, metadata.ID)
|
||||
if err != nil {
|
||||
return fmt.Errorf("delete missing attachment metadata %q: %w", metadata.ID, err)
|
||||
}
|
||||
if deleted {
|
||||
report.DeletedUnreferencedRows++
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type metadataIterator struct {
|
||||
store MetadataStore
|
||||
pageSize int
|
||||
after string
|
||||
page []model.Attachment
|
||||
index int
|
||||
current *model.Attachment
|
||||
done bool
|
||||
}
|
||||
|
||||
func newMetadataIterator(ctx context.Context, store MetadataStore, pageSize int) (*metadataIterator, error) {
|
||||
iterator := &metadataIterator{store: store, pageSize: pageSize}
|
||||
if err := iterator.advance(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return iterator, nil
|
||||
}
|
||||
|
||||
func (i *metadataIterator) advance(ctx context.Context) error {
|
||||
for {
|
||||
if i.index < len(i.page) {
|
||||
i.current = &i.page[i.index]
|
||||
i.index++
|
||||
return nil
|
||||
}
|
||||
if i.done {
|
||||
i.current = nil
|
||||
return nil
|
||||
}
|
||||
page, next, err := i.store.ListAttachments(ctx, i.after, i.pageSize)
|
||||
if err != nil {
|
||||
return fmt.Errorf("list attachment metadata: %w", err)
|
||||
}
|
||||
i.page = page
|
||||
i.index = 0
|
||||
i.after = next
|
||||
i.done = next == ""
|
||||
if len(page) == 0 && !i.done {
|
||||
return errors.New("metadata page is empty but has continuation")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type objectIterator struct {
|
||||
store ObjectStore
|
||||
prefix string
|
||||
pageSize int
|
||||
after string
|
||||
page []model.StoredObject
|
||||
index int
|
||||
current *model.StoredObject
|
||||
done bool
|
||||
}
|
||||
|
||||
func newObjectIterator(ctx context.Context, store ObjectStore, prefix string, pageSize int) (*objectIterator, error) {
|
||||
iterator := &objectIterator{store: store, prefix: prefix, pageSize: pageSize}
|
||||
if err := iterator.advance(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return iterator, nil
|
||||
}
|
||||
|
||||
func (i *objectIterator) advance(ctx context.Context) error {
|
||||
for {
|
||||
if i.index < len(i.page) {
|
||||
i.current = &i.page[i.index]
|
||||
i.index++
|
||||
return nil
|
||||
}
|
||||
if i.done {
|
||||
i.current = nil
|
||||
return nil
|
||||
}
|
||||
page, next, err := i.store.List(ctx, i.prefix, i.after, i.pageSize)
|
||||
if err != nil {
|
||||
return fmt.Errorf("list objects: %w", err)
|
||||
}
|
||||
i.page = page
|
||||
i.index = 0
|
||||
i.after = next
|
||||
i.done = next == ""
|
||||
if len(page) == 0 && !i.done {
|
||||
return errors.New("object page is empty but has continuation")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package reconcile
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
)
|
||||
|
||||
func TestReconcilerLifecycleAndRepeat(t *testing.T) {
|
||||
now := time.Date(2026, 10, 9, 12, 0, 0, 0, time.UTC)
|
||||
old := now.Add(-48 * time.Hour)
|
||||
fresh := now.Add(-10 * time.Minute)
|
||||
metadata := &metadataStub{items: map[string]model.Attachment{
|
||||
"attachments/a/original": attachment("a", "attachments/a/original", model.AttachmentReady, old, false),
|
||||
"attachments/b/original": attachment("b", "attachments/b/original", model.AttachmentReady, old, true),
|
||||
"attachments/c/original": attachment("c", "attachments/c/original", model.AttachmentPending, old, false),
|
||||
"attachments/d/original": attachment("d", "attachments/d/original", model.AttachmentReady, fresh, false),
|
||||
"attachments/missing/original": attachment("missing", "attachments/missing/original", model.AttachmentReady, old, false),
|
||||
}}
|
||||
objects := &objectStub{items: map[string]model.StoredObject{
|
||||
"attachments/a/original": {Key: "attachments/a/original", LastModified: old},
|
||||
"attachments/b/original": {Key: "attachments/b/original", LastModified: old},
|
||||
"attachments/c/original": {Key: "attachments/c/original", LastModified: old},
|
||||
"attachments/d/original": {Key: "attachments/d/original", LastModified: fresh},
|
||||
"attachments/orphan/original": {Key: "attachments/orphan/original", LastModified: old},
|
||||
}}
|
||||
reconciler, err := New(metadata, objects, Config{
|
||||
Prefix: "attachments/", PageSize: 2, GraceTime: time.Hour,
|
||||
UnreferencedRetention: 24 * time.Hour, Apply: true, Now: func() time.Time { return now },
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
report, err := reconciler.Run(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, 1, report.OldPendingAttachments)
|
||||
require.Equal(t, 1, report.OldUnreferencedAttachments)
|
||||
require.Equal(t, 1, report.FreshUnreferencedAttachments)
|
||||
require.Equal(t, 1, report.DeletedOrphanObjects)
|
||||
require.Equal(t, 2, report.DeletedAttachmentObjects)
|
||||
require.Equal(t, 3, report.DeletedUnreferencedRows)
|
||||
require.Contains(t, metadata.items, "attachments/b/original")
|
||||
require.Contains(t, metadata.items, "attachments/d/original")
|
||||
require.NotContains(t, metadata.items, "attachments/a/original")
|
||||
require.NotContains(t, metadata.items, "attachments/c/original")
|
||||
require.NotContains(t, metadata.items, "attachments/missing/original")
|
||||
require.NotContains(t, objects.items, "attachments/orphan/original")
|
||||
|
||||
repeated, err := reconciler.Run(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, repeated.DeletedOrphanObjects)
|
||||
require.Zero(t, repeated.DeletedAttachmentObjects)
|
||||
require.Zero(t, repeated.DeletedUnreferencedRows)
|
||||
}
|
||||
|
||||
func TestReconcilerRechecksOrphanBeforeDelete(t *testing.T) {
|
||||
now := time.Now().UTC()
|
||||
metadata := &metadataStub{items: map[string]model.Attachment{}, appeared: map[string]bool{"attachments/a/original": true}}
|
||||
objects := &objectStub{items: map[string]model.StoredObject{
|
||||
"attachments/a/original": {Key: "attachments/a/original", LastModified: now.Add(-time.Hour)},
|
||||
}}
|
||||
reconciler, err := New(metadata, objects, Config{
|
||||
Prefix: "attachments/", PageSize: 1, GraceTime: time.Minute,
|
||||
UnreferencedRetention: time.Hour, Apply: true, Now: func() time.Time { return now },
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
report, err := reconciler.Run(context.Background())
|
||||
require.NoError(t, err)
|
||||
require.Zero(t, report.DeletedOrphanObjects)
|
||||
require.Contains(t, objects.items, "attachments/a/original")
|
||||
}
|
||||
|
||||
func TestNewRejectsInvalidRetention(t *testing.T) {
|
||||
_, err := New(&metadataStub{}, &objectStub{}, Config{PageSize: 1})
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
func attachment(id, key, status string, createdAt time.Time, referenced bool) model.Attachment {
|
||||
readyAt := createdAt
|
||||
return model.Attachment{
|
||||
ID: id, ObjectKey: key, Status: status, CreatedAt: createdAt,
|
||||
ReadyAt: &readyAt, Referenced: referenced,
|
||||
}
|
||||
}
|
||||
|
||||
type metadataStub struct {
|
||||
items map[string]model.Attachment
|
||||
appeared map[string]bool
|
||||
}
|
||||
|
||||
func (s *metadataStub) ListAttachments(_ context.Context, after string, limit int) ([]model.Attachment, string, error) {
|
||||
keys := make([]string, 0, len(s.items))
|
||||
for key := range s.items {
|
||||
if key > after {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
}
|
||||
sort.Strings(keys)
|
||||
var next string
|
||||
if len(keys) > limit {
|
||||
keys = keys[:limit]
|
||||
next = keys[len(keys)-1]
|
||||
}
|
||||
items := make([]model.Attachment, 0, len(keys))
|
||||
for _, key := range keys {
|
||||
items = append(items, s.items[key])
|
||||
}
|
||||
return items, next, nil
|
||||
}
|
||||
|
||||
func (s *metadataStub) AttachmentExistsByObjectKey(_ context.Context, key string) (bool, error) {
|
||||
if s.appeared[key] {
|
||||
return true, nil
|
||||
}
|
||||
_, exists := s.items[key]
|
||||
return exists, nil
|
||||
}
|
||||
|
||||
func (s *metadataStub) ClaimAttachmentForDeletion(_ context.Context, candidate model.Attachment, cutoff time.Time) (bool, error) {
|
||||
for key, item := range s.items {
|
||||
if item.ID != candidate.ID || item.Status != candidate.Status || item.Referenced {
|
||||
continue
|
||||
}
|
||||
age := item.CreatedAt
|
||||
if item.Status == model.AttachmentReady && item.ReadyAt != nil {
|
||||
age = *item.ReadyAt
|
||||
}
|
||||
if age.After(cutoff) {
|
||||
return false, nil
|
||||
}
|
||||
item.Status = model.AttachmentDeleting
|
||||
s.items[key] = item
|
||||
return true, nil
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
func (s *metadataStub) DeleteAttachmentIfDeleting(_ context.Context, id string) (bool, error) {
|
||||
for key, item := range s.items {
|
||||
if item.ID == id && item.Status == model.AttachmentDeleting && !item.Referenced {
|
||||
delete(s.items, key)
|
||||
return true, nil
|
||||
}
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
type objectStub struct {
|
||||
items map[string]model.StoredObject
|
||||
}
|
||||
|
||||
func (s *objectStub) List(_ context.Context, prefix, after string, limit int) ([]model.StoredObject, string, error) {
|
||||
keys := make([]string, 0, len(s.items))
|
||||
for key := range s.items {
|
||||
if key > after && len(key) >= len(prefix) && key[:len(prefix)] == prefix {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
}
|
||||
sort.Strings(keys)
|
||||
var next string
|
||||
if len(keys) > limit {
|
||||
keys = keys[:limit]
|
||||
next = keys[len(keys)-1]
|
||||
}
|
||||
items := make([]model.StoredObject, 0, len(keys))
|
||||
for _, key := range keys {
|
||||
items = append(items, s.items[key])
|
||||
}
|
||||
return items, next, nil
|
||||
}
|
||||
|
||||
func (s *objectStub) Delete(_ context.Context, key string) error {
|
||||
delete(s.items, key)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/valkey-io/valkey-go"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/model"
|
||||
)
|
||||
|
||||
const (
|
||||
tokenLength = 32
|
||||
keyPrefix = "session:"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = model.ErrSessionNotFound
|
||||
ErrInvalidToken = model.ErrInvalidToken
|
||||
ErrInvalidRecord = errors.New("invalid session record")
|
||||
ErrInvalidTTL = errors.New("invalid session TTL")
|
||||
ErrTokenGeneration = errors.New("session token generation failed")
|
||||
ErrStore = model.ErrUnavailable
|
||||
)
|
||||
|
||||
type record struct {
|
||||
UserID string `json:"user_id"`
|
||||
ExpiresAt time.Time `json:"expires_at"`
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
client valkey.Client
|
||||
}
|
||||
|
||||
func New(rawURL string) (*Store, error) {
|
||||
option, err := valkey.ParseURL(rawURL)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: parse Valkey URL: %w", ErrStore, err)
|
||||
}
|
||||
|
||||
client, err := valkey.NewClient(option)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("%w: create Valkey client: %w", ErrStore, err)
|
||||
}
|
||||
|
||||
return &Store{client: client}, nil
|
||||
}
|
||||
|
||||
func (s *Store) Create(ctx context.Context, userID string, ttl time.Duration) (string, time.Time, error) {
|
||||
if strings.TrimSpace(userID) == "" {
|
||||
return "", time.Time{}, ErrInvalidRecord
|
||||
}
|
||||
if ttl < time.Second {
|
||||
return "", time.Time{}, ErrInvalidTTL
|
||||
}
|
||||
|
||||
token, err := newToken()
|
||||
if err != nil {
|
||||
return "", time.Time{}, err
|
||||
}
|
||||
|
||||
record := record{
|
||||
UserID: userID,
|
||||
ExpiresAt: time.Now().UTC().Add(ttl).Truncate(time.Microsecond),
|
||||
}
|
||||
payload, err := json.Marshal(record)
|
||||
if err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("%w: encode session: %w", ErrStore, err)
|
||||
}
|
||||
|
||||
command := s.client.B().Set().Key(s.key(token)).Value(valkey.BinaryString(payload)).Ex(ttl).Build()
|
||||
if err := s.client.Do(ctx, command).Error(); err != nil {
|
||||
return "", time.Time{}, fmt.Errorf("%w: create session: %w", ErrStore, err)
|
||||
}
|
||||
|
||||
return token, record.ExpiresAt, nil
|
||||
}
|
||||
|
||||
func newToken() (string, error) {
|
||||
random := make([]byte, tokenLength)
|
||||
if _, err := rand.Read(random); err != nil {
|
||||
return "", fmt.Errorf("%w: %v", ErrTokenGeneration, err)
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(random), nil
|
||||
}
|
||||
|
||||
func (s *Store) UserID(ctx context.Context, token string) (string, error) {
|
||||
key, err := s.sessionKey(token)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
payload, err := s.client.Do(ctx, s.client.B().Get().Key(key).Build()).AsBytes()
|
||||
if valkey.IsValkeyNil(err) {
|
||||
return "", ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("%w: get session: %w", ErrStore, err)
|
||||
}
|
||||
|
||||
var record record
|
||||
if err := json.Unmarshal(payload, &record); err != nil {
|
||||
return "", fmt.Errorf("%w: decode session: %w", ErrStore, err)
|
||||
}
|
||||
if strings.TrimSpace(record.UserID) == "" || record.ExpiresAt.IsZero() {
|
||||
return "", fmt.Errorf("%w: %w", ErrStore, ErrInvalidRecord)
|
||||
}
|
||||
if !record.ExpiresAt.After(time.Now()) {
|
||||
return "", ErrNotFound
|
||||
}
|
||||
|
||||
return record.UserID, nil
|
||||
}
|
||||
|
||||
func (s *Store) Delete(ctx context.Context, token string) error {
|
||||
key, err := s.sessionKey(token)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
deleted, err := s.client.Do(ctx, s.client.B().Del().Key(key).Build()).AsInt64()
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: delete session: %w", ErrStore, err)
|
||||
}
|
||||
if deleted == 0 {
|
||||
return ErrNotFound
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) Ping(ctx context.Context) error {
|
||||
if err := s.client.Do(ctx, s.client.B().Ping().Build()).Error(); err != nil {
|
||||
return fmt.Errorf("%w: ping Valkey: %w", ErrStore, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) Close() error {
|
||||
s.client.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Store) sessionKey(token string) (string, error) {
|
||||
decoded, err := base64.RawURLEncoding.Strict().DecodeString(token)
|
||||
if err != nil || len(decoded) != tokenLength {
|
||||
return "", ErrInvalidToken
|
||||
}
|
||||
return s.key(token), nil
|
||||
}
|
||||
|
||||
func (s *Store) key(token string) string {
|
||||
digest := sha256.Sum256([]byte(token))
|
||||
return keyPrefix + hex.EncodeToString(digest[:])
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
package session_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/suite"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab5/internal/session"
|
||||
)
|
||||
|
||||
type SessionSuite struct {
|
||||
suite.Suite
|
||||
store *session.Store
|
||||
}
|
||||
|
||||
func TestSessionSuite(t *testing.T) {
|
||||
suite.Run(t, new(SessionSuite))
|
||||
}
|
||||
|
||||
func (s *SessionSuite) SetupSuite() {
|
||||
rawURL := strings.TrimSpace(os.Getenv("TEST_CACHE_URL"))
|
||||
if rawURL == "" {
|
||||
path := strings.TrimSpace(os.Getenv("TEST_CACHE_URL_FILE"))
|
||||
if path == "" {
|
||||
s.T().Skip("set TEST_CACHE_URL or TEST_CACHE_URL_FILE to run integration tests")
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
s.Require().NoError(err)
|
||||
rawURL = strings.TrimSpace(string(data))
|
||||
}
|
||||
store, err := session.New(rawURL)
|
||||
s.Require().NoError(err)
|
||||
s.store = store
|
||||
}
|
||||
|
||||
func (s *SessionSuite) TearDownSuite() {
|
||||
if s.store != nil {
|
||||
s.Require().NoError(s.store.Close())
|
||||
}
|
||||
}
|
||||
|
||||
func (s *SessionSuite) TestSessionLifecycle() {
|
||||
userID := uuid.NewString()
|
||||
token, expiresAt, err := s.store.Create(context.Background(), userID, time.Minute)
|
||||
s.Require().NoError(err)
|
||||
s.NotEmpty(token)
|
||||
s.True(expiresAt.After(time.Now()))
|
||||
|
||||
actualUserID, err := s.store.UserID(context.Background(), token)
|
||||
s.Require().NoError(err)
|
||||
s.Equal(userID, actualUserID)
|
||||
s.Require().NoError(s.store.Delete(context.Background(), token))
|
||||
|
||||
_, err = s.store.UserID(context.Background(), token)
|
||||
s.ErrorIs(err, session.ErrNotFound)
|
||||
}
|
||||
|
||||
func (s *SessionSuite) TestSessionExpires() {
|
||||
token, _, err := s.store.Create(context.Background(), uuid.NewString(), time.Second)
|
||||
s.Require().NoError(err)
|
||||
|
||||
s.Eventually(func() bool {
|
||||
_, err = s.store.UserID(context.Background(), token)
|
||||
return errors.Is(err, session.ErrNotFound)
|
||||
}, 3*time.Second, 50*time.Millisecond)
|
||||
}
|
||||
Reference in New Issue
Block a user