forked from mtusi2026/mtusi2026lab2
feat: add PostgreSQL persistence and sessions
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/config"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/database"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/messenger"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/password"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/postgres"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/session"
|
||||
)
|
||||
|
||||
func main() {
|
||||
logger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
|
||||
if err := run(logger); err != nil {
|
||||
logger.Error("server stopped", "error", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(logger *slog.Logger) error {
|
||||
settings, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
pool, err := database.Open(context.Background(), database.Config{
|
||||
URL: settings.DatabaseURL, MinConnections: settings.DBMinConns, MaxConnections: settings.DBMaxConns,
|
||||
MaxConnectionAge: 30 * time.Minute, MaxConnectionIdle: 5 * time.Minute,
|
||||
HealthCheckPeriod: 30 * time.Second, ConnectTimeout: settings.ConnectTimeout,
|
||||
MigrationTimeout: 30 * time.Second,
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer pool.Close()
|
||||
sessions, err := session.New(settings.CacheURL)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = sessions.Close() }()
|
||||
app := messenger.NewServer(
|
||||
logger,
|
||||
postgres.New(pool),
|
||||
sessions,
|
||||
password.Hasher{},
|
||||
settings.SessionTTL,
|
||||
settings.RequestTimeout,
|
||||
settings.SwaggerPort,
|
||||
)
|
||||
server := &http.Server{
|
||||
Addr: settings.Address,
|
||||
Handler: app.Handler(),
|
||||
ReadHeaderTimeout: 5 * time.Second,
|
||||
ReadTimeout: 10 * time.Second,
|
||||
WriteTimeout: settings.RequestTimeout + 5*time.Second,
|
||||
IdleTimeout: 60 * time.Second,
|
||||
}
|
||||
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(), 10*time.Second)
|
||||
defer cancel()
|
||||
if err := server.Shutdown(shutdownCtx); err != nil {
|
||||
_ = server.Close()
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
module gitea.privcloud.tech/dizi/mtusi2026lab2
|
||||
|
||||
go 1.26.0
|
||||
|
||||
require (
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/jackc/pgx/v5 v5.11.0
|
||||
github.com/prometheus/client_golang v1.23.2
|
||||
github.com/valkey-io/valkey-go v1.0.78
|
||||
golang.org/x/crypto v0.57.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||
github.com/jackc/pgpassfile v1.0.0 // indirect
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect
|
||||
github.com/jackc/puddle/v2 v2.2.2 // indirect
|
||||
github.com/kr/text v0.2.0 // indirect
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 // indirect
|
||||
github.com/prometheus/client_model v0.6.2 // indirect
|
||||
github.com/prometheus/common v0.66.1 // indirect
|
||||
github.com/prometheus/procfs v0.16.1 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.2 // indirect
|
||||
golang.org/x/sync v0.23.0 // indirect
|
||||
golang.org/x/sys v0.48.0 // indirect
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
google.golang.org/protobuf v1.36.8 // indirect
|
||||
)
|
||||
@@ -0,0 +1,75 @@
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
|
||||
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
|
||||
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
|
||||
github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
|
||||
github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
|
||||
github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM=
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.11.0 h1:IzBBtyK9AHqf98cctWFifYSci2hgQR/cd56wB4p+ogg=
|
||||
github.com/jackc/pgx/v5 v5.11.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/klauspost/compress v1.18.0 h1:c/Cqfb0r+Yi+JtIEq73FWXVkRonBlf0CRNYc8Zttxdo=
|
||||
github.com/klauspost/compress v1.18.0/go.mod h1:2Pp+KzxcywXVXMr50+X0Q/Lsb43OQHYWRCY2AiWywWQ=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc=
|
||||
github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822 h1:C3w9PqII01/Oq1c1nUAm88MOHcQC9l5mIlSMApZMrHA=
|
||||
github.com/munnerz/goautoneg v0.0.0-20191010083416-a7dc8b61c822/go.mod h1:+n7T8mK8HuQTcFwEeznm/DIxMOiR9yIdICNftLE1DvQ=
|
||||
github.com/onsi/gomega v1.42.1 h1:iN1rCUX+44NZ1Dc97MPoeFYbFR0vh8zxoxMFwKdyZ6I=
|
||||
github.com/onsi/gomega v1.42.1/go.mod h1:REff/hsDsodHoKlWsP2mAPhu1+5/6hVYNf9rIEBpeSg=
|
||||
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/prometheus/client_golang v1.23.2 h1:Je96obch5RDVy3FDMndoUsjAhG5Edi49h0RJWRi/o0o=
|
||||
github.com/prometheus/client_golang v1.23.2/go.mod h1:Tb1a6LWHB3/SPIzCoaDXI4I8UHKeFTEQ1YCr+0Gyqmg=
|
||||
github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk=
|
||||
github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE=
|
||||
github.com/prometheus/common v0.66.1 h1:h5E0h5/Y8niHc5DlaLlWLArTQI7tMrsfQjHV+d9ZoGs=
|
||||
github.com/prometheus/common v0.66.1/go.mod h1:gcaUsgf3KfRSwHY4dIMXLPV0K/Wg1oZ8+SbZk/HH/dA=
|
||||
github.com/prometheus/procfs v0.16.1 h1:hZ15bTNuirocR6u0JZ6BAHHmwS1p8B4P6MRqxtzMyRg=
|
||||
github.com/prometheus/procfs v0.16.1/go.mod h1:teAbpZRB1iIAJYREa1LsoWUXykVXA1KlTmWl8x/U+Is=
|
||||
github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ=
|
||||
github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/valkey-io/valkey-go v1.0.78 h1:1Ce8hRaaNXpKfqmqZQRhnbVh1eW8MGR873pdXVvE4y8=
|
||||
github.com/valkey-io/valkey-go v1.0.78/go.mod h1:gvC/r2m3eW4Hbj0YnjogTzNtFdPSM/D+NCqen+5OABM=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.yaml.in/yaml/v2 v2.4.2 h1:DzmwEr2rDGHl7lsFgAHxmNz/1NlQ7xLIrlN2h5d1eGI=
|
||||
go.yaml.in/yaml/v2 v2.4.2/go.mod h1:081UH+NErpNdqlCXm3TtEran0rJZGxAYx9hb/ELlsPU=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M=
|
||||
golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA=
|
||||
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
||||
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
|
||||
golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=
|
||||
golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||
golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=
|
||||
golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||
golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI=
|
||||
golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E=
|
||||
google.golang.org/protobuf v1.36.8 h1:xHScyCOEuuwZEc6UtSOvPbAT4zRh0xcNRYekJwfqyMc=
|
||||
google.golang.org/protobuf v1.36.8/go.mod h1:fuxRtAxBytpl4zzqUh6/eyUujkJdNiuEkXntxiD/uRU=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
@@ -0,0 +1,148 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
Address string
|
||||
DatabaseURL string
|
||||
CacheURL string
|
||||
SessionTTL time.Duration
|
||||
DBMaxConns int32
|
||||
DBMinConns int32
|
||||
ConnectTimeout time.Duration
|
||||
RequestTimeout time.Duration
|
||||
SwaggerPort string
|
||||
}
|
||||
|
||||
func Load() (Config, error) {
|
||||
host, err := requiredEnv("APP_HOST")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
port, err := requiredPort("APP_PORT")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
databaseURL, err := secretFromEnv("DATABASE_URL_FILE")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
cacheURL, err := secretFromEnv("CACHE_URL_FILE")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
if store, err := requiredEnv("SESSION_STORE"); err != nil {
|
||||
return Config{}, err
|
||||
} else if store != "valkey" {
|
||||
return Config{}, errors.New("SESSION_STORE must be valkey")
|
||||
}
|
||||
ttlSeconds, err := requiredPositiveInt("SESSION_TTL_SECONDS")
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
maxConns, err := intEnv("DB_MAX_CONNS", 10, 1, 100)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
minConns, err := intEnv("DB_MIN_CONNS", 1, 0, maxConns)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
connectSeconds, err := intEnv("DEPENDENCY_TIMEOUT_SECONDS", 5, 1, 60)
|
||||
if err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
swaggerPort := os.Getenv("SWAGGER_PORT")
|
||||
if swaggerPort == "" {
|
||||
swaggerPort = "8081"
|
||||
}
|
||||
if _, err := parsePort(swaggerPort); err != nil {
|
||||
return Config{}, fmt.Errorf("SWAGGER_PORT: %w", err)
|
||||
}
|
||||
return Config{
|
||||
Address: net.JoinHostPort(host, port),
|
||||
DatabaseURL: databaseURL,
|
||||
CacheURL: cacheURL,
|
||||
SessionTTL: time.Duration(ttlSeconds) * time.Second,
|
||||
DBMaxConns: int32(maxConns),
|
||||
DBMinConns: int32(minConns),
|
||||
ConnectTimeout: time.Duration(connectSeconds) * time.Second,
|
||||
RequestTimeout: time.Duration(connectSeconds) * time.Second,
|
||||
SwaggerPort: swaggerPort,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func requiredEnv(name string) (string, error) {
|
||||
value := strings.TrimSpace(os.Getenv(name))
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("%s is required", name)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func requiredPort(name string) (string, error) {
|
||||
value, err := requiredEnv(name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if _, err := parsePort(value); err != nil {
|
||||
return "", fmt.Errorf("%s: %w", name, err)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func parsePort(value string) (int, error) {
|
||||
port, err := strconv.Atoi(value)
|
||||
if err != nil || port < 1 || port > 65535 {
|
||||
return 0, errors.New("must be between 1 and 65535")
|
||||
}
|
||||
return port, nil
|
||||
}
|
||||
|
||||
func requiredPositiveInt(name string) (int, error) {
|
||||
value, err := requiredEnv(name)
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
parsed, err := strconv.Atoi(value)
|
||||
if err != nil || parsed <= 0 {
|
||||
return 0, fmt.Errorf("%s must be a positive integer", name)
|
||||
}
|
||||
return parsed, nil
|
||||
}
|
||||
|
||||
func intEnv(name string, fallback, minimum, maximum int) (int, error) {
|
||||
value := os.Getenv(name)
|
||||
if value == "" {
|
||||
return fallback, nil
|
||||
}
|
||||
parsed, err := strconv.Atoi(value)
|
||||
if err != nil || parsed < minimum || parsed > maximum {
|
||||
return 0, fmt.Errorf("%s must be between %d and %d", name, minimum, maximum)
|
||||
}
|
||||
return parsed, nil
|
||||
}
|
||||
|
||||
func secretFromEnv(name string) (string, error) {
|
||||
path, err := requiredEnv(name)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("read %s: %w", name, err)
|
||||
}
|
||||
value := strings.TrimSpace(string(data))
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("%s points to an empty file", name)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package database
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/migrations"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
URL string
|
||||
MinConnections int32
|
||||
MaxConnections int32
|
||||
MaxConnectionAge time.Duration
|
||||
MaxConnectionIdle time.Duration
|
||||
HealthCheckPeriod time.Duration
|
||||
ConnectTimeout time.Duration
|
||||
MigrationTimeout 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)
|
||||
}
|
||||
|
||||
migrationCtx, cancel := context.WithTimeout(ctx, config.MigrationTimeout)
|
||||
defer cancel()
|
||||
if err := applyMigrations(migrationCtx, pool, migrations.FS); err != nil {
|
||||
pool.Close()
|
||||
return nil, err
|
||||
}
|
||||
return pool, nil
|
||||
}
|
||||
|
||||
func validateConfig(config Config) error {
|
||||
switch {
|
||||
case config.URL == "":
|
||||
return fmt.Errorf("database URL is required")
|
||||
case config.MinConnections < 0:
|
||||
return fmt.Errorf("minimum database connections must not be negative")
|
||||
case config.MaxConnections < 1:
|
||||
return fmt.Errorf("maximum database connections must be positive")
|
||||
case config.MinConnections > config.MaxConnections:
|
||||
return fmt.Errorf("minimum database connections exceed maximum")
|
||||
case config.MaxConnectionAge <= 0:
|
||||
return fmt.Errorf("maximum database connection age must be positive")
|
||||
case config.MaxConnectionIdle <= 0:
|
||||
return fmt.Errorf("maximum database connection idle time must be positive")
|
||||
case config.HealthCheckPeriod <= 0:
|
||||
return fmt.Errorf("database health check period must be positive")
|
||||
case config.ConnectTimeout <= 0:
|
||||
return fmt.Errorf("database connection timeout must be positive")
|
||||
case config.MigrationTimeout <= 0:
|
||||
return fmt.Errorf("database migration timeout must be positive")
|
||||
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,33 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/model"
|
||||
)
|
||||
|
||||
type Repository interface {
|
||||
Ping(context.Context) error
|
||||
CreateUser(context.Context, string, string, string) (model.User, error)
|
||||
UserByID(context.Context, string) (model.User, error)
|
||||
UserByUsername(context.Context, string) (model.UserCredentials, error)
|
||||
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)
|
||||
CreateMessage(context.Context, string, string, string) (model.Message, error)
|
||||
ListMessages(context.Context, string, string, *model.Position, int) ([]model.Message, bool, error)
|
||||
}
|
||||
|
||||
type SessionStore interface {
|
||||
Ping(context.Context) error
|
||||
Create(context.Context, string, time.Duration) (string, time.Time, error)
|
||||
UserID(context.Context, string) (string, error)
|
||||
Delete(context.Context, string) error
|
||||
}
|
||||
|
||||
type Passwords interface {
|
||||
Hash(string) (string, error)
|
||||
Verify(string, string) (bool, error)
|
||||
DummyHash() string
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package messenger
|
||||
|
||||
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"
|
||||
)
|
||||
|
||||
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,357 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/model"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/postgres"
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/session"
|
||||
)
|
||||
|
||||
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.repository.Ping(ctx); err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
if err := s.sessions.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.repository.CreateUser(r.Context(), input.Username, input.DisplayName, passwordHash)
|
||||
if errors.Is(err, postgres.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) 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.repository.UserByUsername(r.Context(), username)
|
||||
if errors.Is(err, postgres.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, session.ErrNotFound) {
|
||||
return unauthorized()
|
||||
} else if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return nil
|
||||
}
|
||||
|
||||
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.repository.CreateChat(r.Context(), input.Title, input.MemberIDs, user.ID)
|
||||
if errors.Is(err, postgres.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.repository.ListChats(r.Context(), user.ID, cursorPosition(cursor), limit)
|
||||
if errors.Is(listErr, postgres.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.repository.ChatForUser(r.Context(), chatID, user.ID)
|
||||
if errors.Is(err, postgres.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)
|
||||
}
|
||||
var input struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
if err := readJSON(w, r, &input); err != nil {
|
||||
return err
|
||||
}
|
||||
if !validText(input.Text, 4000) {
|
||||
return invalidRequest()
|
||||
}
|
||||
message, err := s.repository.CreateMessage(r.Context(), chatID, user.ID, input.Text)
|
||||
if errors.Is(err, postgres.ErrNotFound) {
|
||||
return notFound()
|
||||
}
|
||||
if err != nil {
|
||||
return unavailable()
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, message)
|
||||
return nil
|
||||
}
|
||||
|
||||
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.repository.ListMessages(r.Context(), chatID, user.ID, cursorPosition(cursor), limit)
|
||||
if errors.Is(listErr, postgres.ErrNotFound) {
|
||||
return notFound()
|
||||
}
|
||||
if errors.Is(listErr, postgres.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}
|
||||
}
|
||||
|
||||
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, session.ErrNotFound) || errors.Is(err, session.ErrInvalidToken) {
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
if err != nil {
|
||||
return User{}, "", unavailable()
|
||||
}
|
||||
user, err := s.repository.UserByID(r.Context(), userID)
|
||||
if errors.Is(err, postgres.ErrNotFound) {
|
||||
_ = s.sessions.Delete(r.Context(), token)
|
||||
return User{}, "", unauthorized()
|
||||
}
|
||||
if err != nil {
|
||||
return User{}, "", unavailable()
|
||||
}
|
||||
return user, token, nil
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
package messenger
|
||||
|
||||
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
|
||||
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.",
|
||||
}),
|
||||
}
|
||||
registry.MustRegister(
|
||||
result.requests,
|
||||
result.duration,
|
||||
result.inFlight,
|
||||
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"
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"gitea.privcloud.tech/dizi/mtusi2026lab2/internal/model"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type User = model.User
|
||||
type Chat = model.Chat
|
||||
type Message = model.Message
|
||||
|
||||
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,116 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const maxRequestBytes = 1 << 20
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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,41 @@
|
||||
package messenger
|
||||
|
||||
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 {
|
||||
return notFound()
|
||||
}
|
||||
}
|
||||
return handler(w, r)
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package messenger
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Server struct {
|
||||
repository Repository
|
||||
sessions SessionStore
|
||||
passwords Passwords
|
||||
sessionTTL time.Duration
|
||||
requestTTL time.Duration
|
||||
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, repository Repository, sessions SessionStore, passwords Passwords, sessionTTL, requestTTL time.Duration, swaggerPort string) *Server {
|
||||
s := &Server{
|
||||
repository: repository, sessions: sessions, passwords: passwords,
|
||||
sessionTTL: sessionTTL, requestTTL: requestTTL, logger: logger, swaggerPort: 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) {
|
||||
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, OPTIONS")
|
||||
wrapped.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
|
||||
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 {
|
||||
challenge := `Bearer realm="messenger"`
|
||||
if r.URL.Path == "/api/v1/auth/sessions" {
|
||||
challenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
}
|
||||
wrapped.Header().Set("WWW-Authenticate", challenge)
|
||||
}
|
||||
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")
|
||||
w.Header().Add("Vary", "Origin")
|
||||
return true
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
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"`
|
||||
}
|
||||
|
||||
type Position struct {
|
||||
CreatedAt time.Time
|
||||
ID string
|
||||
}
|
||||
|
||||
func (u User) MarshalJSON() ([]byte, error) {
|
||||
type response struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
return json.Marshal(response{u.ID, u.Username, u.DisplayName, formatTime(u.CreatedAt)})
|
||||
}
|
||||
|
||||
func (c Chat) MarshalJSON() ([]byte, error) {
|
||||
type response struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
return json.Marshal(response{c.ID, c.Title, c.MemberIDs, formatTime(c.CreatedAt)})
|
||||
}
|
||||
|
||||
func (m Message) MarshalJSON() ([]byte, error) {
|
||||
type response struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
return json.Marshal(response{m.ID, m.ChatID, m.SenderID, m.Text, formatTime(m.CreatedAt)})
|
||||
}
|
||||
|
||||
func FormatTime(value time.Time) string {
|
||||
return formatTime(value)
|
||||
}
|
||||
|
||||
func formatTime(value time.Time) string {
|
||||
return value.UTC().Format(timestampLayout)
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package password
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"golang.org/x/crypto/argon2"
|
||||
)
|
||||
|
||||
const (
|
||||
MemoryKiB uint32 = 64 * 1024
|
||||
Iterations uint32 = 3
|
||||
Parallelism uint8 = 2
|
||||
SaltLength = 16
|
||||
KeyLength uint32 = 32
|
||||
)
|
||||
|
||||
var ErrInvalidHash = errors.New("invalid password hash")
|
||||
|
||||
var dummyHash = encode(
|
||||
make([]byte, SaltLength),
|
||||
argon2.IDKey([]byte("invalid-user-password"), make([]byte, SaltLength), Iterations, MemoryKiB, Parallelism, KeyLength),
|
||||
)
|
||||
|
||||
type Hasher struct{}
|
||||
|
||||
func (Hasher) Hash(value string) (string, error) {
|
||||
return Hash(value)
|
||||
}
|
||||
|
||||
func (Hasher) Verify(value, encodedHash string) (bool, error) {
|
||||
return Verify(value, encodedHash)
|
||||
}
|
||||
|
||||
func (Hasher) DummyHash() string {
|
||||
return dummyHash
|
||||
}
|
||||
|
||||
func Hash(value string) (string, error) {
|
||||
salt := make([]byte, SaltLength)
|
||||
if _, err := rand.Read(salt); err != nil {
|
||||
return "", fmt.Errorf("generate password salt: %w", err)
|
||||
}
|
||||
|
||||
digest := argon2.IDKey([]byte(value), salt, Iterations, MemoryKiB, Parallelism, KeyLength)
|
||||
|
||||
return encode(salt, digest), nil
|
||||
}
|
||||
|
||||
func encode(salt, digest []byte) string {
|
||||
return fmt.Sprintf(
|
||||
"$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||
argon2.Version,
|
||||
MemoryKiB,
|
||||
Iterations,
|
||||
Parallelism,
|
||||
base64.RawStdEncoding.EncodeToString(salt),
|
||||
base64.RawStdEncoding.EncodeToString(digest),
|
||||
)
|
||||
}
|
||||
|
||||
func Verify(value, encodedHash string) (bool, error) {
|
||||
salt, digest, err := decode(encodedHash)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
|
||||
actual := argon2.IDKey([]byte(value), salt, Iterations, MemoryKiB, Parallelism, KeyLength)
|
||||
return subtle.ConstantTimeCompare(actual, digest) == 1, nil
|
||||
}
|
||||
|
||||
func decode(encodedHash string) ([]byte, []byte, error) {
|
||||
parts := strings.Split(encodedHash, "$")
|
||||
if len(parts) != 6 || parts[0] != "" || parts[1] != "argon2id" {
|
||||
return nil, nil, ErrInvalidHash
|
||||
}
|
||||
|
||||
if parts[2] != fmt.Sprintf("v=%d", argon2.Version) {
|
||||
return nil, nil, ErrInvalidHash
|
||||
}
|
||||
if parts[3] != fmt.Sprintf("m=%d,t=%d,p=%d", MemoryKiB, Iterations, Parallelism) {
|
||||
return nil, nil, ErrInvalidHash
|
||||
}
|
||||
|
||||
salt, err := base64.RawStdEncoding.Strict().DecodeString(parts[4])
|
||||
if err != nil || len(salt) != SaltLength {
|
||||
return nil, nil, ErrInvalidHash
|
||||
}
|
||||
|
||||
digest, err := base64.RawStdEncoding.Strict().DecodeString(parts[5])
|
||||
if err != nil || len(digest) != int(KeyLength) {
|
||||
return nil, nil, ErrInvalidHash
|
||||
}
|
||||
|
||||
return salt, digest, nil
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
package postgres
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrConflict = errors.New("conflict")
|
||||
ErrNotFound = errors.New("not found")
|
||||
ErrInvalidMembers = errors.New("invalid members")
|
||||
ErrInvalidCursor = errors.New("invalid cursor")
|
||||
)
|
||||
@@ -0,0 +1,469 @@
|
||||
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/mtusi2026lab2/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(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) CreateMessage(
|
||||
ctx context.Context,
|
||||
chatID string,
|
||||
senderID string,
|
||||
text string,
|
||||
) (model.Message, error) {
|
||||
const query = `
|
||||
INSERT INTO messages (id, chat_id, sender_id, text)
|
||||
SELECT $1, $2, $3, $4
|
||||
WHERE EXISTS (
|
||||
SELECT 1
|
||||
FROM chat_members
|
||||
WHERE chat_id = $2 AND user_id = $3
|
||||
)
|
||||
RETURNING id, chat_id, sender_id, text, created_at`
|
||||
|
||||
var message model.Message
|
||||
err := s.pool.QueryRow(ctx, query, uuid.NewString(), chatID, senderID, text).Scan(
|
||||
&message.ID,
|
||||
&message.ChatID,
|
||||
&message.SenderID,
|
||||
&message.Text,
|
||||
&message.CreatedAt,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return model.Message{}, ErrNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return model.Message{}, fmt.Errorf("create message: %w", err)
|
||||
}
|
||||
|
||||
return message, 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 id, chat_id, sender_id, text, created_at
|
||||
FROM messages
|
||||
WHERE chat_id = $1
|
||||
AND ($2::timestamptz IS NULL OR (created_at, id) > ($2, $3::uuid))
|
||||
ORDER BY created_at, 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,
|
||||
)
|
||||
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,161 @@
|
||||
package session
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/valkey-io/valkey-go"
|
||||
)
|
||||
|
||||
const (
|
||||
tokenLength = 32
|
||||
keyPrefix = "session:"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrNotFound = errors.New("session not found")
|
||||
ErrInvalidToken = errors.New("invalid session token")
|
||||
ErrInvalidRecord = errors.New("invalid session record")
|
||||
ErrInvalidTTL = errors.New("invalid session TTL")
|
||||
ErrTokenGeneration = errors.New("session token generation failed")
|
||||
ErrStore = errors.New("session store failure")
|
||||
)
|
||||
|
||||
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,50 @@
|
||||
CREATE TABLE users (
|
||||
id UUID PRIMARY KEY,
|
||||
username TEXT NOT NULL,
|
||||
display_name TEXT NOT NULL,
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
||||
CONSTRAINT users_username_unique UNIQUE (username),
|
||||
CONSTRAINT users_username_format CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
CONSTRAINT users_display_name_length CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||
CONSTRAINT users_display_name_not_blank CHECK (display_name ~ '[^[:space:]]'),
|
||||
CONSTRAINT users_password_hash_length CHECK (char_length(password_hash) BETWEEN 1 AND 1024),
|
||||
CONSTRAINT users_password_hash_not_blank CHECK (password_hash ~ '[^[:space:]]')
|
||||
);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id UUID PRIMARY KEY,
|
||||
title TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
||||
CONSTRAINT chats_title_length CHECK (char_length(title) BETWEEN 1 AND 100),
|
||||
CONSTRAINT chats_title_not_blank CHECK (title ~ '[^[:space:]]')
|
||||
);
|
||||
|
||||
CREATE INDEX chats_created_at_id_idx ON chats (created_at, id);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id UUID NOT NULL,
|
||||
user_id UUID NOT NULL,
|
||||
position SMALLINT NOT NULL,
|
||||
CONSTRAINT chat_members_pk PRIMARY KEY (chat_id, user_id),
|
||||
CONSTRAINT chat_members_chat_position_unique UNIQUE (chat_id, position),
|
||||
CONSTRAINT chat_members_position_range CHECK (position BETWEEN 0 AND 99),
|
||||
CONSTRAINT chat_members_chat_fk FOREIGN KEY (chat_id) REFERENCES chats (id) ON DELETE CASCADE,
|
||||
CONSTRAINT chat_members_user_fk FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX chat_members_user_id_chat_id_idx ON chat_members (user_id, chat_id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id UUID PRIMARY KEY,
|
||||
chat_id UUID NOT NULL,
|
||||
sender_id UUID NOT NULL,
|
||||
text TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(),
|
||||
CONSTRAINT messages_text_length CHECK (char_length(text) BETWEEN 1 AND 4000),
|
||||
CONSTRAINT messages_text_not_blank CHECK (text ~ '[^[:space:]]'),
|
||||
CONSTRAINT messages_sender_membership_fk FOREIGN KEY (chat_id, sender_id)
|
||||
REFERENCES chat_members (chat_id, user_id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX messages_chat_id_created_at_id_idx ON messages (chat_id, created_at, id);
|
||||
@@ -0,0 +1,8 @@
|
||||
package migrations
|
||||
|
||||
import "embed"
|
||||
|
||||
// FS contains database migrations applied by the application at startup.
|
||||
//
|
||||
//go:embed *.sql
|
||||
var FS embed.FS
|
||||
Reference in New Issue
Block a user