forked from mtusi2026/mtusi2026lab2
feat: persist data in PostgreSQL and add Basic/Bearer sessions in Redis
This commit is contained in:
+66
-14
@@ -12,48 +12,100 @@ import (
|
|||||||
|
|
||||||
"messenger/internal/config"
|
"messenger/internal/config"
|
||||||
"messenger/internal/handler"
|
"messenger/internal/handler"
|
||||||
"messenger/internal/repository/memory"
|
"messenger/internal/repository/postgres"
|
||||||
|
"messenger/internal/repository/redis"
|
||||||
"messenger/internal/router"
|
"messenger/internal/router"
|
||||||
"messenger/internal/service"
|
"messenger/internal/service"
|
||||||
)
|
)
|
||||||
|
|
||||||
const shutdownTimeout = 5 * time.Second
|
const (
|
||||||
|
shutdownTimeout = 5 * time.Second
|
||||||
|
migrateAttempts = 60
|
||||||
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
|
log := slog.New(slog.NewJSONHandler(os.Stdout, nil))
|
||||||
cfg := config.Load()
|
if err := run(log); err != nil {
|
||||||
|
log.Error("server failed", "err", err)
|
||||||
|
os.Exit(1)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func run(log *slog.Logger) error {
|
||||||
|
cfg, err := config.Load()
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := migrateWithRetry(log, cfg.DatabaseURL); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
pool, err := postgres.NewPool(context.Background(), cfg.DatabaseURL)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer pool.Close()
|
||||||
|
store := postgres.New(pool)
|
||||||
|
|
||||||
|
redisClient, err := redis.NewClient(cfg.CacheURL)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer redisClient.Close()
|
||||||
|
sessions := redis.NewSessionStore(redisClient)
|
||||||
|
|
||||||
store := memory.New()
|
|
||||||
users := service.NewUserService(store)
|
users := service.NewUserService(store)
|
||||||
|
auth := service.NewAuthService(store, sessions, cfg.SessionTTL)
|
||||||
chats := service.NewChatService(store)
|
chats := service.NewChatService(store)
|
||||||
messages := service.NewMessageService(chats, store)
|
messages := service.NewMessageService(chats, store)
|
||||||
|
deps := []handler.Pinger{store.Ping, sessions.Ping}
|
||||||
|
|
||||||
srv := &http.Server{
|
srv := &http.Server{
|
||||||
Addr: cfg.Addr(),
|
Addr: cfg.Addr(),
|
||||||
Handler: router.New(handler.New(users, chats, messages, log)),
|
Handler: router.New(handler.New(users, auth, chats, messages, deps, log)),
|
||||||
ReadHeaderTimeout: 5 * time.Second,
|
ReadHeaderTimeout: 5 * time.Second,
|
||||||
|
ReadTimeout: 15 * time.Second,
|
||||||
|
WriteTimeout: 15 * time.Second,
|
||||||
|
IdleTimeout: 60 * time.Second,
|
||||||
}
|
}
|
||||||
|
|
||||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
|
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, os.Interrupt)
|
||||||
defer stop()
|
defer stop()
|
||||||
|
|
||||||
|
errCh := make(chan error, 1)
|
||||||
go func() {
|
go func() {
|
||||||
log.Info("starting server", "addr", srv.Addr, "env", cfg.Env)
|
log.Info("starting server", "addr", srv.Addr, "env", cfg.Env, "session_ttl", cfg.SessionTTL.String())
|
||||||
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||||
log.Error("server failed", "err", err)
|
errCh <- err
|
||||||
os.Exit(1)
|
|
||||||
}
|
}
|
||||||
}()
|
}()
|
||||||
|
|
||||||
<-ctx.Done()
|
select {
|
||||||
|
case err := <-errCh:
|
||||||
|
return err
|
||||||
|
case <-ctx.Done():
|
||||||
|
}
|
||||||
log.Info("shutdown signal received", "timeout", shutdownTimeout.String())
|
log.Info("shutdown signal received", "timeout", shutdownTimeout.String())
|
||||||
|
|
||||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
|
shutdownCtx, cancel := context.WithTimeout(context.Background(), shutdownTimeout)
|
||||||
err := srv.Shutdown(shutdownCtx)
|
defer cancel()
|
||||||
cancel()
|
if err := srv.Shutdown(shutdownCtx); err != nil {
|
||||||
if err != nil {
|
return err
|
||||||
log.Error("graceful shutdown failed", "err", err)
|
|
||||||
os.Exit(1)
|
|
||||||
}
|
}
|
||||||
log.Info("server stopped")
|
log.Info("server stopped")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func migrateWithRetry(log *slog.Logger, databaseURL string) error {
|
||||||
|
var err error
|
||||||
|
for attempt := 1; attempt <= migrateAttempts; attempt++ {
|
||||||
|
if err = postgres.Migrate(databaseURL); err == nil {
|
||||||
|
log.Info("migrations applied")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
log.Warn("migrations failed, retrying", "attempt", attempt, "err", err)
|
||||||
|
time.Sleep(time.Second)
|
||||||
|
}
|
||||||
|
return err
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,4 +2,22 @@ module messenger
|
|||||||
|
|
||||||
go 1.27.1
|
go 1.27.1
|
||||||
|
|
||||||
require github.com/go-chi/chi/v5 v5.3.2
|
require (
|
||||||
|
github.com/go-chi/chi/v5 v5.3.2
|
||||||
|
github.com/golang-migrate/migrate/v4 v4.20.1
|
||||||
|
github.com/jackc/pgx/v5 v5.11.0
|
||||||
|
github.com/redis/go-redis/v9 v9.23.0
|
||||||
|
golang.org/x/crypto v0.58.0
|
||||||
|
)
|
||||||
|
|
||||||
|
require (
|
||||||
|
github.com/cespare/xxhash/v2 v2.3.0 // indirect
|
||||||
|
github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa // 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
|
||||||
|
go.uber.org/atomic v1.12.0 // indirect
|
||||||
|
golang.org/x/sync v0.24.0 // indirect
|
||||||
|
golang.org/x/sys v0.49.0 // indirect
|
||||||
|
golang.org/x/text v0.43.0 // indirect
|
||||||
|
)
|
||||||
|
|||||||
@@ -1,2 +1,99 @@
|
|||||||
|
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c h1:udKWzYgxTojEKWjV8V+WSxDXJ4NFATAsZjh8iIbsQIg=
|
||||||
|
github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c/go.mod h1:xomTg63KZ2rFqZQzSB4Vz2SUXa1BpHTVz9L5PTmPC4E=
|
||||||
|
github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY=
|
||||||
|
github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU=
|
||||||
|
github.com/bsm/ginkgo/v2 v2.12.0 h1:Ny8MWAHyOepLGlLKYmXG4IEkioBysk6GpaRTLC8zwWs=
|
||||||
|
github.com/bsm/ginkgo/v2 v2.12.0/go.mod h1:SwYbGRRDovPVboqFv0tPTcG1sN61LM1Z4ARdbAV9g4c=
|
||||||
|
github.com/bsm/gomega v1.27.10 h1:yeMWxP2pV2fG3FgAODIY8EiRE3dy0aeFYt4l7wh6yKA=
|
||||||
|
github.com/bsm/gomega v1.27.10/go.mod h1:JyEr/xRbxbtgWNi8tIEVPUYZ5Dzef52k01W3YH0H+O0=
|
||||||
|
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/containerd/errdefs v1.0.0 h1:tg5yIfIlQIrxYtu9ajqY42W3lpS19XqdxRQeEwYG8PI=
|
||||||
|
github.com/containerd/errdefs v1.0.0/go.mod h1:+YBYIdtsnF4Iw6nWZhJcqGSg/dwvV7tyJ/kCkyJ2k+M=
|
||||||
|
github.com/containerd/errdefs/pkg v0.3.0 h1:9IKJ06FvyNlexW690DXuQNx2KA2cUJXx151Xdx3ZPPE=
|
||||||
|
github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmCQvQ4GpJHEqRLVk=
|
||||||
|
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||||
|
github.com/dhui/dktest v0.4.6 h1:+DPKyScKSEp3VLtbMDHcUq6V5Lm5zfZZVb0Sk7Ahom4=
|
||||||
|
github.com/dhui/dktest v0.4.6/go.mod h1:JHTSYDtKkvFNFHJKqCzVzqXecyv+tKt8EzceOmQOgbU=
|
||||||
|
github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk=
|
||||||
|
github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E=
|
||||||
|
github.com/docker/docker v28.5.2+incompatible h1:DBX0Y0zAjZbSrm1uzOkdr1onVghKaftjlSWt4AFexzM=
|
||||||
|
github.com/docker/docker v28.5.2+incompatible/go.mod h1:eEKB0N0r5NX/I1kEveEz05bcu8tLC/8azJZsviup8Sk=
|
||||||
|
github.com/docker/go-connections v0.7.0 h1:6SsRfJddP22WMrCkj19x9WKjEDTB+ahsdiGYf0mN39c=
|
||||||
|
github.com/docker/go-connections v0.7.0/go.mod h1:no1qkHdjq7kLMGUXYAduOhYPSJxxvgWBh7ogVvptn3Q=
|
||||||
|
github.com/docker/go-units v0.5.0 h1:69rxXcBk27SvSaaxTtLh/8llcHD8vYHT7WSdRZ/jvr4=
|
||||||
|
github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDDbaIK4Dk=
|
||||||
|
github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc=
|
||||||
|
github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE=
|
||||||
github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY=
|
github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY=
|
||||||
github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
|
github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto=
|
||||||
|
github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
|
||||||
|
github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
|
||||||
|
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
|
||||||
|
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
|
||||||
|
github.com/golang-migrate/migrate/v4 v4.20.1 h1:2N/ToVTKrKl58ynBpgeVJ4In7VcLCjWTZtm4eP1LxhU=
|
||||||
|
github.com/golang-migrate/migrate/v4 v4.20.1/go.mod h1:DDPgKVb4ovSWc4FwSPfV2Uz1160f4XBiTHTrAJtljmM=
|
||||||
|
github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa h1:s+4MhCQ6YrzisK6hFJUX53drDT4UsSW3DEhKn0ifuHw=
|
||||||
|
github.com/jackc/pgerrcode v0.0.0-20220416144525-469b46aa5efa/go.mod h1:a/s9Lp5W7n/DD0VrVoyJ00FbP2ytTPDVOivvn2bMlds=
|
||||||
|
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/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
|
||||||
|
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
|
||||||
|
github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||||
|
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||||
|
github.com/moby/docker-image-spec v1.3.1 h1:jMKff3w6PgbfSa69GfNg+zN/XLhfXJGnEx3Nl2EsFP0=
|
||||||
|
github.com/moby/docker-image-spec v1.3.1/go.mod h1:eKmb5VW8vQEh/BAr2yvVNvuiJuY6UIocYsFu/DxxRpo=
|
||||||
|
github.com/moby/moby/api v1.54.2 h1:wiat9QAhnDQjA7wk1kh/TqHz2I1uUA7M7t9SAl/JNXg=
|
||||||
|
github.com/moby/moby/api v1.54.2/go.mod h1:+RQ6wluLwtYaTd1WnPLykIDPekkuyD/ROWQClE83pzs=
|
||||||
|
github.com/moby/moby/client v0.4.1 h1:DMQgisVoMkmMs7fp3ROSdiBnoAu8+vo3GggFl06M/wY=
|
||||||
|
github.com/moby/moby/client v0.4.1/go.mod h1:z52C9O2POPOsnxZAy//WtKcQ32P+jT/NGeXu/7nfjGQ=
|
||||||
|
github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ=
|
||||||
|
github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc=
|
||||||
|
github.com/morikuni/aec v1.0.0 h1:nP9CBfwrvYnBRgY6qfDQkygYDmYwOilePFkwzv4dU8A=
|
||||||
|
github.com/morikuni/aec v1.0.0/go.mod h1:BbKIizmSmc5MMPqRYbxO4ZU0S0+P200+tUnFx7PXmsc=
|
||||||
|
github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U=
|
||||||
|
github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM=
|
||||||
|
github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040=
|
||||||
|
github.com/opencontainers/image-spec v1.1.1/go.mod h1:qpqAh3Dmcf36wStyyWU+kCeDgrGnAve2nCC8+7h8Q0M=
|
||||||
|
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||||
|
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||||
|
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||||
|
github.com/redis/go-redis/v9 v9.23.0 h1:/TTVdJa8BRNsybwwGGnmiYktHNlUXtbOQxlWpHBPL3s=
|
||||||
|
github.com/redis/go-redis/v9 v9.23.0/go.mod h1:EWP2UUk+XDaI1s5nQB5mablZN6vccXlmBQTyfnF87D0=
|
||||||
|
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.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
|
||||||
|
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
|
||||||
|
github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
|
||||||
|
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
|
||||||
|
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||||
|
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||||
|
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo=
|
||||||
|
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI=
|
||||||
|
go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU=
|
||||||
|
go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc=
|
||||||
|
go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc=
|
||||||
|
go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo=
|
||||||
|
go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk=
|
||||||
|
go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE=
|
||||||
|
go.uber.org/atomic v1.12.0 h1:BvcXdFKuviU4fTL/f+SxdQ5qJX/Jix8pAkgdUcb3XOE=
|
||||||
|
go.uber.org/atomic v1.12.0/go.mod h1:I6c4cg+6HCxRjfjSsYtApoFILnpc0CGUdGkXVqbYVNk=
|
||||||
|
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.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54=
|
||||||
|
golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w=
|
||||||
|
golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA=
|
||||||
|
golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=
|
||||||
|
golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA=
|
||||||
|
golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og=
|
||||||
|
golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc=
|
||||||
|
golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s=
|
||||||
|
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||||
|
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||||
|
|||||||
@@ -1,26 +1,57 @@
|
|||||||
package config
|
package config
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"fmt"
|
||||||
"net"
|
"net"
|
||||||
"os"
|
"os"
|
||||||
|
"strconv"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
)
|
)
|
||||||
|
|
||||||
type Config struct {
|
type Config struct {
|
||||||
Host string
|
Host string
|
||||||
Port string
|
Port string
|
||||||
Env string
|
Env string
|
||||||
|
SessionTTL time.Duration
|
||||||
|
DatabaseURL string
|
||||||
|
CacheURL string
|
||||||
}
|
}
|
||||||
|
|
||||||
func Load() Config {
|
func Load() (Config, error) {
|
||||||
return Config{
|
ttl, err := strconv.Atoi(getenv("SESSION_TTL_SECONDS", "3600"))
|
||||||
Host: getenv("APP_HOST", "0.0.0.0"),
|
if err != nil || ttl <= 0 {
|
||||||
Port: getenv("APP_PORT", "8080"),
|
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS must be a positive integer")
|
||||||
Env: getenv("APP_ENV", "lab"),
|
|
||||||
}
|
}
|
||||||
|
databaseURL, err := readSecret("DATABASE_URL_FILE", "/run/secrets/database_url")
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
cacheURL, err := readSecret("CACHE_URL_FILE", "/run/secrets/cache_url")
|
||||||
|
if err != nil {
|
||||||
|
return Config{}, err
|
||||||
|
}
|
||||||
|
return Config{
|
||||||
|
Host: getenv("APP_HOST", "0.0.0.0"),
|
||||||
|
Port: getenv("APP_PORT", "8080"),
|
||||||
|
Env: getenv("APP_ENV", "lab"),
|
||||||
|
SessionTTL: time.Duration(ttl) * time.Second,
|
||||||
|
DatabaseURL: databaseURL,
|
||||||
|
CacheURL: cacheURL,
|
||||||
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c Config) Addr() string { return net.JoinHostPort(c.Host, c.Port) }
|
func (c Config) Addr() string { return net.JoinHostPort(c.Host, c.Port) }
|
||||||
|
|
||||||
|
func readSecret(key, def string) (string, error) {
|
||||||
|
path := getenv(key, def)
|
||||||
|
b, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
return "", fmt.Errorf("%s: cannot read %s", key, path)
|
||||||
|
}
|
||||||
|
return strings.TrimSpace(string(b)), nil
|
||||||
|
}
|
||||||
|
|
||||||
func getenv(key, def string) string {
|
func getenv(key, def string) string {
|
||||||
if v := os.Getenv(key); v != "" {
|
if v := os.Getenv(key); v != "" {
|
||||||
return v
|
return v
|
||||||
|
|||||||
@@ -36,6 +36,12 @@ type Message struct {
|
|||||||
CreatedAt time.Time
|
CreatedAt time.Time
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type Session struct {
|
||||||
|
Token string
|
||||||
|
ExpiresAt time.Time
|
||||||
|
User User
|
||||||
|
}
|
||||||
|
|
||||||
type Cursor struct {
|
type Cursor struct {
|
||||||
Scope uuid.UUID
|
Scope uuid.UUID
|
||||||
CreatedAt time.Time
|
CreatedAt time.Time
|
||||||
|
|||||||
@@ -7,4 +7,5 @@ var (
|
|||||||
ErrUnauthorized = errors.New("unauthorized")
|
ErrUnauthorized = errors.New("unauthorized")
|
||||||
ErrNotFound = errors.New("not found")
|
ErrNotFound = errors.New("not found")
|
||||||
ErrConflict = errors.New("conflict")
|
ErrConflict = errors.New("conflict")
|
||||||
|
ErrUnavailable = errors.New("dependency unavailable")
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
package handler
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"unicode/utf8"
|
||||||
|
|
||||||
|
"messenger/internal/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
func (h *Handler) CreateSession(w http.ResponseWriter, r *http.Request) {
|
||||||
|
username, password, ok := basicCredentials(r)
|
||||||
|
if !ok {
|
||||||
|
h.failLogin(w, r, domain.ErrUnauthorized)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
session, err := h.auth.Login(r.Context(), username, password)
|
||||||
|
if err != nil {
|
||||||
|
h.failLogin(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
writeJSON(w, http.StatusCreated, toSessionResponse(session))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) failLogin(w http.ResponseWriter, r *http.Request, err error) {
|
||||||
|
if errors.Is(err, domain.ErrUnauthorized) {
|
||||||
|
w.Header().Set(headerWWWAuthenticate, basicChallenge)
|
||||||
|
}
|
||||||
|
h.fail(w, r, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (h *Handler) DeleteSession(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if err := h.auth.Logout(r.Context(), current(r).token); err != nil {
|
||||||
|
h.fail(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
w.WriteHeader(http.StatusNoContent)
|
||||||
|
}
|
||||||
|
|
||||||
|
func basicCredentials(r *http.Request) (string, string, bool) {
|
||||||
|
encoded, ok := authCredentials(r, "Basic")
|
||||||
|
if !ok {
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
|
raw, err := base64.StdEncoding.DecodeString(encoded)
|
||||||
|
if err != nil || !utf8.Valid(raw) {
|
||||||
|
return "", "", false
|
||||||
|
}
|
||||||
|
username, password, ok := strings.Cut(string(raw), ":")
|
||||||
|
return username, password, ok
|
||||||
|
}
|
||||||
@@ -0,0 +1,102 @@
|
|||||||
|
package handler_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
deadDatabaseURL = "postgres://messenger:x@127.0.0.1:1/messenger?sslmode=disable"
|
||||||
|
deadRedisURL = "redis://127.0.0.1:1/0"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSessionExpiry(t *testing.T) {
|
||||||
|
dbURL, redisURL := testURLs(t)
|
||||||
|
srv := newStack(t, dbURL, redisURL, 2*time.Second)
|
||||||
|
alice := createUser(t, srv, "alice")
|
||||||
|
|
||||||
|
if status, _ := do(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, ""); status != http.StatusOK {
|
||||||
|
t.Fatalf("fresh session: got %d, want 200", status)
|
||||||
|
}
|
||||||
|
time.Sleep(3 * time.Second)
|
||||||
|
resp := request(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, "")
|
||||||
|
resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusUnauthorized {
|
||||||
|
t.Fatalf("expired session: got %d, want 401", resp.StatusCode)
|
||||||
|
}
|
||||||
|
if got := resp.Header.Get("WWW-Authenticate"); !strings.HasPrefix(got, "Bearer") {
|
||||||
|
t.Errorf("WWW-Authenticate = %q, want Bearer challenge", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestLogout(t *testing.T) {
|
||||||
|
srv := newServer(t)
|
||||||
|
alice := createUser(t, srv, "alice")
|
||||||
|
|
||||||
|
resp := request(t, srv, http.MethodDelete, "/api/v1/auth/sessions/current", alice.Token, "")
|
||||||
|
resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusNoContent {
|
||||||
|
t.Fatalf("logout: got %d, want 204", resp.StatusCode)
|
||||||
|
}
|
||||||
|
if status, _ := do(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, ""); status != http.StatusUnauthorized {
|
||||||
|
t.Errorf("revoked token on /users/me: got %d, want 401", status)
|
||||||
|
}
|
||||||
|
if status, _ := do(t, srv, http.MethodDelete, "/api/v1/auth/sessions/current", alice.Token, ""); status != http.StatusUnauthorized {
|
||||||
|
t.Errorf("repeated logout: got %d, want 401", status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWrongPassword(t *testing.T) {
|
||||||
|
srv := newServer(t)
|
||||||
|
alice := createUser(t, srv, "alice")
|
||||||
|
|
||||||
|
for name, password := range map[string]string{"wrong password": "Wrong-password-123", "unknown user": alice.Password} {
|
||||||
|
username := alice.Username
|
||||||
|
if name == "unknown user" {
|
||||||
|
username = "nobody_" + alice.Username[:10]
|
||||||
|
}
|
||||||
|
resp := login(t, srv, username, password)
|
||||||
|
resp.Body.Close()
|
||||||
|
if resp.StatusCode != http.StatusUnauthorized {
|
||||||
|
t.Errorf("%s: got %d, want 401", name, resp.StatusCode)
|
||||||
|
}
|
||||||
|
if got := resp.Header.Get("WWW-Authenticate"); got != `Basic realm="messenger", charset="UTF-8"` {
|
||||||
|
t.Errorf("%s: WWW-Authenticate = %q", name, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRedisUnavailable(t *testing.T) {
|
||||||
|
dbURL, _ := testURLs(t)
|
||||||
|
srv := newStack(t, dbURL, deadRedisURL, time.Hour)
|
||||||
|
|
||||||
|
if status, body := do(t, srv, http.MethodGet, "/api/v1/users/me", "some-token-from-before-the-outage", ""); status != http.StatusServiceUnavailable || errorCode(body) != "unavailable" {
|
||||||
|
t.Errorf("bearer request: got %d %q, want 503 unavailable", status, errorCode(body))
|
||||||
|
}
|
||||||
|
if status, _ := do(t, srv, http.MethodGet, "/api/v1/users/me", "", ""); status != http.StatusUnauthorized {
|
||||||
|
t.Errorf("anonymous request: got %d, want 401", status)
|
||||||
|
}
|
||||||
|
if status, _ := do(t, srv, http.MethodGet, "/health/ready", "", ""); status != http.StatusServiceUnavailable {
|
||||||
|
t.Errorf("ready: got %d, want 503", status)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDatabaseUnavailable(t *testing.T) {
|
||||||
|
dbURL, redisURL := testURLs(t)
|
||||||
|
healthy := newStack(t, dbURL, redisURL, time.Hour)
|
||||||
|
alice := createUser(t, healthy, "alice")
|
||||||
|
|
||||||
|
srv := newStack(t, deadDatabaseURL, redisURL, time.Hour)
|
||||||
|
if status, body := do(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, ""); status != http.StatusServiceUnavailable || errorCode(body) != "unavailable" {
|
||||||
|
t.Errorf("valid session: got %d %q, want 503 unavailable", status, errorCode(body))
|
||||||
|
}
|
||||||
|
if status, _ := do(t, srv, http.MethodPost, "/api/v1/users", "",
|
||||||
|
`{"username":"db_down_user","display_name":"X","password":"long-enough-pass"}`); status != http.StatusServiceUnavailable {
|
||||||
|
t.Errorf("register: got %d, want 503", status)
|
||||||
|
}
|
||||||
|
if status, _ := do(t, srv, http.MethodGet, "/health/ready", "", ""); status != http.StatusServiceUnavailable {
|
||||||
|
t.Errorf("ready: got %d, want 503", status)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -9,6 +9,7 @@ import (
|
|||||||
type createUserRequest struct {
|
type createUserRequest struct {
|
||||||
Username *string `json:"username"`
|
Username *string `json:"username"`
|
||||||
DisplayName *string `json:"display_name"`
|
DisplayName *string `json:"display_name"`
|
||||||
|
Password *string `json:"password"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type createChatRequest struct {
|
type createChatRequest struct {
|
||||||
@@ -47,6 +48,13 @@ type pageResponse[T any] struct {
|
|||||||
NextCursor *string `json:"next_cursor"`
|
NextCursor *string `json:"next_cursor"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type sessionResponse struct {
|
||||||
|
Token string `json:"token"`
|
||||||
|
TokenType string `json:"token_type"`
|
||||||
|
ExpiresAt string `json:"expires_at"`
|
||||||
|
User userResponse `json:"user"`
|
||||||
|
}
|
||||||
|
|
||||||
type healthResponse struct {
|
type healthResponse struct {
|
||||||
Status string `json:"status"`
|
Status string `json:"status"`
|
||||||
}
|
}
|
||||||
@@ -74,6 +82,15 @@ func toUserResponse(u domain.User) userResponse {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func toSessionResponse(s domain.Session) sessionResponse {
|
||||||
|
return sessionResponse{
|
||||||
|
Token: s.Token,
|
||||||
|
TokenType: "Bearer",
|
||||||
|
ExpiresAt: formatTime(s.ExpiresAt),
|
||||||
|
User: toUserResponse(s.User),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func toChatResponse(c domain.Chat) chatResponse {
|
func toChatResponse(c domain.Chat) chatResponse {
|
||||||
members := make([]string, len(c.MemberIDs))
|
members := make([]string, len(c.MemberIDs))
|
||||||
for i, id := range c.MemberIDs {
|
for i, id := range c.MemberIDs {
|
||||||
|
|||||||
@@ -35,11 +35,18 @@ func (h *Handler) fail(w http.ResponseWriter, r *http.Request, err error) {
|
|||||||
case errors.Is(err, domain.ErrInvalidInput):
|
case errors.Is(err, domain.ErrInvalidInput):
|
||||||
writeError(w, http.StatusBadRequest, "invalid_request", err.Error())
|
writeError(w, http.StatusBadRequest, "invalid_request", err.Error())
|
||||||
case errors.Is(err, domain.ErrUnauthorized):
|
case errors.Is(err, domain.ErrUnauthorized):
|
||||||
writeError(w, http.StatusUnauthorized, "unauthorized", "valid X-User-Id header is required")
|
if w.Header().Get(headerWWWAuthenticate) == "" {
|
||||||
|
w.Header().Set(headerWWWAuthenticate, bearerChallenge)
|
||||||
|
}
|
||||||
|
writeError(w, http.StatusUnauthorized, "unauthorized", "valid authentication is required")
|
||||||
case errors.Is(err, domain.ErrNotFound):
|
case errors.Is(err, domain.ErrNotFound):
|
||||||
writeError(w, http.StatusNotFound, "not_found", "resource not found")
|
writeError(w, http.StatusNotFound, "not_found", "resource not found")
|
||||||
case errors.Is(err, domain.ErrConflict):
|
case errors.Is(err, domain.ErrConflict):
|
||||||
writeError(w, http.StatusConflict, "conflict", "username is already taken")
|
writeError(w, http.StatusConflict, "conflict", "username is already taken")
|
||||||
|
case errors.Is(err, domain.ErrUnavailable):
|
||||||
|
h.log.Error("dependency unavailable", "request_id", w.Header().Get(headerRequestID),
|
||||||
|
"method", r.Method, "path", r.URL.Path, "err", err)
|
||||||
|
writeError(w, http.StatusServiceUnavailable, "unavailable", "service temporarily unavailable")
|
||||||
default:
|
default:
|
||||||
h.log.Error("unexpected error", "request_id", w.Header().Get(headerRequestID),
|
h.log.Error("unexpected error", "request_id", w.Header().Get(headerRequestID),
|
||||||
"method", r.Method, "path", r.URL.Path, "err", err)
|
"method", r.Method, "path", r.URL.Path, "err", err)
|
||||||
|
|||||||
@@ -1,21 +1,27 @@
|
|||||||
package handler
|
package handler
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
|
||||||
"messenger/internal/service"
|
"messenger/internal/service"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type Pinger func(ctx context.Context) error
|
||||||
|
|
||||||
type Handler struct {
|
type Handler struct {
|
||||||
users *service.UserService
|
users *service.UserService
|
||||||
|
auth *service.AuthService
|
||||||
chats *service.ChatService
|
chats *service.ChatService
|
||||||
messages *service.MessageService
|
messages *service.MessageService
|
||||||
|
deps []Pinger
|
||||||
log *slog.Logger
|
log *slog.Logger
|
||||||
}
|
}
|
||||||
|
|
||||||
func New(users *service.UserService, chats *service.ChatService, messages *service.MessageService, log *slog.Logger) *Handler {
|
func New(users *service.UserService, auth *service.AuthService, chats *service.ChatService,
|
||||||
return &Handler{users: users, chats: chats, messages: messages, log: log}
|
messages *service.MessageService, deps []Pinger, log *slog.Logger) *Handler {
|
||||||
|
return &Handler{users: users, auth: auth, chats: chats, messages: messages, deps: deps, log: log}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) NotFound(w http.ResponseWriter, _ *http.Request) {
|
func (h *Handler) NotFound(w http.ResponseWriter, _ *http.Request) {
|
||||||
|
|||||||
@@ -1,33 +1,75 @@
|
|||||||
package handler_test
|
package handler_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/base64"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"log/slog"
|
"log/slog"
|
||||||
"net/http"
|
"net/http"
|
||||||
"net/http/httptest"
|
"net/http/httptest"
|
||||||
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"sync"
|
"sync"
|
||||||
"testing"
|
"testing"
|
||||||
|
"time"
|
||||||
|
"uuid"
|
||||||
|
|
||||||
"messenger/internal/handler"
|
"messenger/internal/handler"
|
||||||
"messenger/internal/repository/memory"
|
"messenger/internal/repository/postgres"
|
||||||
|
"messenger/internal/repository/redis"
|
||||||
"messenger/internal/router"
|
"messenger/internal/router"
|
||||||
"messenger/internal/service"
|
"messenger/internal/service"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
func testURLs(t *testing.T) (string, string) {
|
||||||
|
t.Helper()
|
||||||
|
dbURL, redisURL := os.Getenv("TEST_DATABASE_URL"), os.Getenv("TEST_REDIS_URL")
|
||||||
|
if dbURL == "" || redisURL == "" {
|
||||||
|
t.Skip("TEST_DATABASE_URL and TEST_REDIS_URL are required")
|
||||||
|
}
|
||||||
|
return dbURL, redisURL
|
||||||
|
}
|
||||||
|
|
||||||
func newServer(t *testing.T) *httptest.Server {
|
func newServer(t *testing.T) *httptest.Server {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
store := memory.New()
|
dbURL, redisURL := testURLs(t)
|
||||||
|
return newStack(t, dbURL, redisURL, time.Hour)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newStack(t *testing.T, dbURL, redisURL string, ttl time.Duration) *httptest.Server {
|
||||||
|
t.Helper()
|
||||||
|
pool, err := postgres.NewPool(context.Background(), dbURL)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(pool.Close)
|
||||||
|
store := postgres.New(pool)
|
||||||
|
client, err := redis.NewClient(redisURL)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(func() { client.Close() })
|
||||||
|
sessions := redis.NewSessionStore(client)
|
||||||
|
|
||||||
users := service.NewUserService(store)
|
users := service.NewUserService(store)
|
||||||
|
auth := service.NewAuthService(store, sessions, ttl)
|
||||||
chats := service.NewChatService(store)
|
chats := service.NewChatService(store)
|
||||||
messages := service.NewMessageService(chats, store)
|
messages := service.NewMessageService(chats, store)
|
||||||
srv := httptest.NewServer(router.New(handler.New(users, chats, messages, slog.New(slog.DiscardHandler))))
|
h := handler.New(users, auth, chats, messages, []handler.Pinger{store.Ping, sessions.Ping}, slog.New(slog.DiscardHandler))
|
||||||
|
srv := httptest.NewServer(router.New(h))
|
||||||
t.Cleanup(srv.Close)
|
t.Cleanup(srv.Close)
|
||||||
return srv
|
return srv
|
||||||
}
|
}
|
||||||
|
|
||||||
func do(t *testing.T, srv *httptest.Server, method, path, userID, body string) (int, map[string]any) {
|
type testUser struct {
|
||||||
|
ID string
|
||||||
|
Username string
|
||||||
|
Password string
|
||||||
|
Token string
|
||||||
|
}
|
||||||
|
|
||||||
|
func request(t *testing.T, srv *httptest.Server, method, path, token, body string) *http.Response {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
req, err := http.NewRequest(method, srv.URL+path, strings.NewReader(body))
|
req, err := http.NewRequest(method, srv.URL+path, strings.NewReader(body))
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -36,13 +78,19 @@ func do(t *testing.T, srv *httptest.Server, method, path, userID, body string) (
|
|||||||
if body != "" {
|
if body != "" {
|
||||||
req.Header.Set("Content-Type", "application/json")
|
req.Header.Set("Content-Type", "application/json")
|
||||||
}
|
}
|
||||||
if userID != "" {
|
if token != "" {
|
||||||
req.Header.Set("X-User-Id", userID)
|
req.Header.Set("Authorization", "Bearer "+token)
|
||||||
}
|
}
|
||||||
resp, err := srv.Client().Do(req)
|
resp, err := srv.Client().Do(req)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
t.Fatal(err)
|
t.Fatal(err)
|
||||||
}
|
}
|
||||||
|
return resp
|
||||||
|
}
|
||||||
|
|
||||||
|
func do(t *testing.T, srv *httptest.Server, method, path, token, body string) (int, map[string]any) {
|
||||||
|
t.Helper()
|
||||||
|
resp := request(t, srv, method, path, token, body)
|
||||||
defer resp.Body.Close()
|
defer resp.Body.Close()
|
||||||
var out map[string]any
|
var out map[string]any
|
||||||
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
|
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
|
||||||
@@ -57,21 +105,56 @@ func errorCode(body map[string]any) string {
|
|||||||
return code
|
return code
|
||||||
}
|
}
|
||||||
|
|
||||||
func createUser(t *testing.T, srv *httptest.Server, username string) string {
|
func basic(username, password string) string {
|
||||||
t.Helper()
|
return "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":"+password))
|
||||||
status, body := do(t, srv, http.MethodPost, "/api/v1/users", "",
|
|
||||||
fmt.Sprintf(`{"username":%q,"display_name":"Test"}`, username))
|
|
||||||
if status != http.StatusCreated {
|
|
||||||
t.Fatalf("create user %s: status %d", username, status)
|
|
||||||
}
|
|
||||||
return body["id"].(string)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
func createChat(t *testing.T, srv *httptest.Server, owner string, members ...string) string {
|
func login(t *testing.T, srv *httptest.Server, username, password string) *http.Response {
|
||||||
t.Helper()
|
t.Helper()
|
||||||
ids, _ := json.Marshal(members)
|
req, err := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/auth/sessions", nil)
|
||||||
status, body := do(t, srv, http.MethodPost, "/api/v1/chats", owner,
|
if err != nil {
|
||||||
fmt.Sprintf(`{"title":"Test","member_ids":%s}`, ids))
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
req.Header.Set("Authorization", basic(username, password))
|
||||||
|
resp, err := srv.Client().Do(req)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return resp
|
||||||
|
}
|
||||||
|
|
||||||
|
func createUser(t *testing.T, srv *httptest.Server, label string) testUser {
|
||||||
|
t.Helper()
|
||||||
|
u := testUser{
|
||||||
|
Username: label + "_" + strings.ReplaceAll(uuid.New().String(), "-", "")[:12],
|
||||||
|
Password: "Test-password-" + label,
|
||||||
|
}
|
||||||
|
status, body := do(t, srv, http.MethodPost, "/api/v1/users", "",
|
||||||
|
fmt.Sprintf(`{"username":%q,"display_name":"Test","password":%q}`, u.Username, u.Password))
|
||||||
|
if status != http.StatusCreated {
|
||||||
|
t.Fatalf("create user %s: status %d", u.Username, status)
|
||||||
|
}
|
||||||
|
u.ID = body["id"].(string)
|
||||||
|
|
||||||
|
resp := login(t, srv, u.Username, u.Password)
|
||||||
|
defer resp.Body.Close()
|
||||||
|
var session map[string]any
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&session); err != nil || resp.StatusCode != http.StatusCreated {
|
||||||
|
t.Fatalf("login %s: status %d", u.Username, resp.StatusCode)
|
||||||
|
}
|
||||||
|
u.Token = session["token"].(string)
|
||||||
|
return u
|
||||||
|
}
|
||||||
|
|
||||||
|
func createChat(t *testing.T, srv *httptest.Server, owner testUser, members ...testUser) string {
|
||||||
|
t.Helper()
|
||||||
|
ids := make([]string, len(members))
|
||||||
|
for i, m := range members {
|
||||||
|
ids[i] = m.ID
|
||||||
|
}
|
||||||
|
raw, _ := json.Marshal(ids)
|
||||||
|
status, body := do(t, srv, http.MethodPost, "/api/v1/chats", owner.Token,
|
||||||
|
fmt.Sprintf(`{"title":"Test","member_ids":%s}`, raw))
|
||||||
if status != http.StatusCreated {
|
if status != http.StatusCreated {
|
||||||
t.Fatalf("create chat: status %d", status)
|
t.Fatalf("create chat: status %d", status)
|
||||||
}
|
}
|
||||||
@@ -80,7 +163,7 @@ func createChat(t *testing.T, srv *httptest.Server, owner string, members ...str
|
|||||||
|
|
||||||
func TestInvalidJSON(t *testing.T) {
|
func TestInvalidJSON(t *testing.T) {
|
||||||
srv := newServer(t)
|
srv := newServer(t)
|
||||||
for _, body := range []string{`{"username":`, `not json`, `{"username":5,"display_name":"x"}`} {
|
for _, body := range []string{`{"username":`, `not json`, `{"username":5,"display_name":"x","password":"long-enough-pass"}`} {
|
||||||
status, resp := do(t, srv, http.MethodPost, "/api/v1/users", "", body)
|
status, resp := do(t, srv, http.MethodPost, "/api/v1/users", "", body)
|
||||||
if status != http.StatusBadRequest || errorCode(resp) != "invalid_request" {
|
if status != http.StatusBadRequest || errorCode(resp) != "invalid_request" {
|
||||||
t.Errorf("body %q: got %d %q, want 400 invalid_request", body, status, errorCode(resp))
|
t.Errorf("body %q: got %d %q, want 400 invalid_request", body, status, errorCode(resp))
|
||||||
@@ -101,13 +184,13 @@ func TestForeignChat(t *testing.T) {
|
|||||||
{http.MethodPost, "/api/v1/chats/" + chat + "/messages", `{"text":"hi"}`},
|
{http.MethodPost, "/api/v1/chats/" + chat + "/messages", `{"text":"hi"}`},
|
||||||
}
|
}
|
||||||
for _, c := range cases {
|
for _, c := range cases {
|
||||||
status, resp := do(t, srv, c.method, c.path, eve, c.body)
|
status, resp := do(t, srv, c.method, c.path, eve.Token, c.body)
|
||||||
if status != http.StatusNotFound || errorCode(resp) != "not_found" {
|
if status != http.StatusNotFound || errorCode(resp) != "not_found" {
|
||||||
t.Errorf("%s %s by outsider: got %d, want 404", c.method, c.path, status)
|
t.Errorf("%s %s by outsider: got %d, want 404", c.method, c.path, status)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
status, resp := do(t, srv, http.MethodGet, "/api/v1/chats", eve, "")
|
status, resp := do(t, srv, http.MethodGet, "/api/v1/chats", eve.Token, "")
|
||||||
if status != http.StatusOK || len(resp["items"].([]any)) != 0 {
|
if status != http.StatusOK || len(resp["items"].([]any)) != 0 {
|
||||||
t.Errorf("outsider chat list: got %d %v, want 200 with no items", status, resp["items"])
|
t.Errorf("outsider chat list: got %d %v, want 200 with no items", status, resp["items"])
|
||||||
}
|
}
|
||||||
@@ -120,7 +203,7 @@ func TestEmptyMessage(t *testing.T) {
|
|||||||
|
|
||||||
for _, text := range []string{"", " ", "\n\t"} {
|
for _, text := range []string{"", " ", "\n\t"} {
|
||||||
body, _ := json.Marshal(map[string]string{"text": text})
|
body, _ := json.Marshal(map[string]string{"text": text})
|
||||||
status, resp := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", alice, string(body))
|
status, resp := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", alice.Token, string(body))
|
||||||
if status != http.StatusBadRequest || errorCode(resp) != "invalid_request" {
|
if status != http.StatusBadRequest || errorCode(resp) != "invalid_request" {
|
||||||
t.Errorf("text %q: got %d, want 400", text, status)
|
t.Errorf("text %q: got %d, want 400", text, status)
|
||||||
}
|
}
|
||||||
@@ -129,8 +212,9 @@ func TestEmptyMessage(t *testing.T) {
|
|||||||
|
|
||||||
func TestDuplicateUsername(t *testing.T) {
|
func TestDuplicateUsername(t *testing.T) {
|
||||||
srv := newServer(t)
|
srv := newServer(t)
|
||||||
createUser(t, srv, "alice")
|
alice := createUser(t, srv, "alice")
|
||||||
status, resp := do(t, srv, http.MethodPost, "/api/v1/users", "", `{"username":"alice","display_name":"Other"}`)
|
status, resp := do(t, srv, http.MethodPost, "/api/v1/users", "",
|
||||||
|
fmt.Sprintf(`{"username":%q,"display_name":"Other","password":"another-password"}`, alice.Username))
|
||||||
if status != http.StatusConflict || errorCode(resp) != "conflict" {
|
if status != http.StatusConflict || errorCode(resp) != "conflict" {
|
||||||
t.Errorf("got %d %q, want 409 conflict", status, errorCode(resp))
|
t.Errorf("got %d %q, want 409 conflict", status, errorCode(resp))
|
||||||
}
|
}
|
||||||
@@ -143,7 +227,7 @@ func TestPaginationMultiplePages(t *testing.T) {
|
|||||||
|
|
||||||
const total, limit = 7, 3
|
const total, limit = 7, 3
|
||||||
for i := range total {
|
for i := range total {
|
||||||
status, _ := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", alice, fmt.Sprintf(`{"text":"msg %d"}`, i))
|
status, _ := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", alice.Token, fmt.Sprintf(`{"text":"msg %d"}`, i))
|
||||||
if status != http.StatusCreated {
|
if status != http.StatusCreated {
|
||||||
t.Fatalf("send message %d: status %d", i, status)
|
t.Fatalf("send message %d: status %d", i, status)
|
||||||
}
|
}
|
||||||
@@ -158,7 +242,7 @@ func TestPaginationMultiplePages(t *testing.T) {
|
|||||||
if cursor != "" {
|
if cursor != "" {
|
||||||
path += "&cursor=" + cursor
|
path += "&cursor=" + cursor
|
||||||
}
|
}
|
||||||
status, resp := do(t, srv, http.MethodGet, path, alice, "")
|
status, resp := do(t, srv, http.MethodGet, path, alice.Token, "")
|
||||||
if status != http.StatusOK {
|
if status != http.StatusOK {
|
||||||
t.Fatalf("page %d: status %d", pages+1, status)
|
t.Fatalf("page %d: status %d", pages+1, status)
|
||||||
}
|
}
|
||||||
@@ -194,7 +278,7 @@ func TestConcurrentMessages(t *testing.T) {
|
|||||||
srv := newServer(t)
|
srv := newServer(t)
|
||||||
const clients, perClient = 10, 10
|
const clients, perClient = 10, 10
|
||||||
|
|
||||||
users := make([]string, clients)
|
users := make([]testUser, clients)
|
||||||
for i := range users {
|
for i := range users {
|
||||||
users[i] = createUser(t, srv, fmt.Sprintf("client_%d", i))
|
users[i] = createUser(t, srv, fmt.Sprintf("client_%d", i))
|
||||||
}
|
}
|
||||||
@@ -205,7 +289,7 @@ func TestConcurrentMessages(t *testing.T) {
|
|||||||
for c, user := range users {
|
for c, user := range users {
|
||||||
wg.Go(func() {
|
wg.Go(func() {
|
||||||
for i := range perClient {
|
for i := range perClient {
|
||||||
status, _ := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", user,
|
status, _ := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", user.Token,
|
||||||
fmt.Sprintf(`{"text":"client %d msg %d"}`, c, i))
|
fmt.Sprintf(`{"text":"client %d msg %d"}`, c, i))
|
||||||
if status != http.StatusCreated {
|
if status != http.StatusCreated {
|
||||||
errs <- fmt.Errorf("client %d msg %d: status %d", c, i, status)
|
errs <- fmt.Errorf("client %d msg %d: status %d", c, i, status)
|
||||||
@@ -219,7 +303,7 @@ func TestConcurrentMessages(t *testing.T) {
|
|||||||
t.Error(err)
|
t.Error(err)
|
||||||
}
|
}
|
||||||
|
|
||||||
status, resp := do(t, srv, http.MethodGet, "/api/v1/chats/"+chat+"/messages?limit=100", users[0], "")
|
status, resp := do(t, srv, http.MethodGet, "/api/v1/chats/"+chat+"/messages?limit=100", users[0].Token, "")
|
||||||
if status != http.StatusOK {
|
if status != http.StatusOK {
|
||||||
t.Fatalf("read history: status %d", status)
|
t.Fatalf("read history: status %d", status)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,25 @@
|
|||||||
package handler
|
package handler
|
||||||
|
|
||||||
import "net/http"
|
import (
|
||||||
|
"context"
|
||||||
|
"net/http"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const readyTimeout = time.Second
|
||||||
|
|
||||||
func (h *Handler) Live(w http.ResponseWriter, _ *http.Request) {
|
func (h *Handler) Live(w http.ResponseWriter, _ *http.Request) {
|
||||||
writeJSON(w, http.StatusOK, healthResponse{Status: "ok"})
|
writeJSON(w, http.StatusOK, healthResponse{Status: "ok"})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (h *Handler) Ready(w http.ResponseWriter, _ *http.Request) {
|
func (h *Handler) Ready(w http.ResponseWriter, r *http.Request) {
|
||||||
|
ctx, cancel := context.WithTimeout(r.Context(), readyTimeout)
|
||||||
|
defer cancel()
|
||||||
|
for _, dep := range h.deps {
|
||||||
|
if err := dep(ctx); err != nil {
|
||||||
|
h.fail(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
writeJSON(w, http.StatusOK, healthResponse{Status: "ok"})
|
writeJSON(w, http.StatusOK, healthResponse{Status: "ok"})
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ import (
|
|||||||
"errors"
|
"errors"
|
||||||
"net/http"
|
"net/http"
|
||||||
"runtime/debug"
|
"runtime/debug"
|
||||||
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
"uuid"
|
"uuid"
|
||||||
|
|
||||||
@@ -15,8 +16,10 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
headerRequestID = "X-Request-Id"
|
headerRequestID = "X-Request-Id"
|
||||||
headerUserID = "X-User-Id"
|
headerWWWAuthenticate = "WWW-Authenticate"
|
||||||
|
bearerChallenge = `Bearer realm="messenger"`
|
||||||
|
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||||
)
|
)
|
||||||
|
|
||||||
func RequestID(next http.Handler) http.Handler {
|
func RequestID(next http.Handler) http.Handler {
|
||||||
@@ -66,26 +69,44 @@ func (h *Handler) Recoverer(next http.Handler) http.Handler {
|
|||||||
|
|
||||||
type ctxKey struct{}
|
type ctxKey struct{}
|
||||||
|
|
||||||
|
type principal struct {
|
||||||
|
user domain.User
|
||||||
|
token string
|
||||||
|
}
|
||||||
|
|
||||||
func (h *Handler) Authenticate(next http.Handler) http.Handler {
|
func (h *Handler) Authenticate(next http.Handler) http.Handler {
|
||||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||||
id, ok := parseUUID(r.Header.Get(headerUserID))
|
token, ok := authCredentials(r, "Bearer")
|
||||||
if !ok {
|
if !ok || token == "" {
|
||||||
h.fail(w, r, domain.ErrUnauthorized)
|
h.fail(w, r, domain.ErrUnauthorized)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
user, err := h.users.Authenticate(r.Context(), id)
|
user, err := h.auth.Authenticate(r.Context(), token)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.fail(w, r, err)
|
h.fail(w, r, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, user)))
|
ctx := context.WithValue(r.Context(), ctxKey{}, principal{user: user, token: token})
|
||||||
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func actor(r *http.Request) domain.User {
|
func authCredentials(r *http.Request, scheme string) (string, bool) {
|
||||||
u, ok := r.Context().Value(ctxKey{}).(domain.User)
|
gotScheme, credentials, ok := strings.Cut(r.Header.Get("Authorization"), " ")
|
||||||
|
if !ok || !strings.EqualFold(gotScheme, scheme) {
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
return credentials, true
|
||||||
|
}
|
||||||
|
|
||||||
|
func current(r *http.Request) principal {
|
||||||
|
p, ok := r.Context().Value(ctxKey{}).(principal)
|
||||||
if !ok {
|
if !ok {
|
||||||
panic(errors.New("handler: actor requested on unauthenticated route"))
|
panic(errors.New("handler: actor requested on unauthenticated route"))
|
||||||
}
|
}
|
||||||
return u
|
return p
|
||||||
|
}
|
||||||
|
|
||||||
|
func actor(r *http.Request) domain.User {
|
||||||
|
return current(r).user
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,11 +8,11 @@ func (h *Handler) RegisterUser(w http.ResponseWriter, r *http.Request) {
|
|||||||
h.fail(w, r, err)
|
h.fail(w, r, err)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if req.Username == nil || req.DisplayName == nil {
|
if req.Username == nil || req.DisplayName == nil || req.Password == nil {
|
||||||
h.fail(w, r, badRequest("username and display_name are required strings"))
|
h.fail(w, r, badRequest("username, display_name and password are required strings"))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
user, err := h.users.Register(r.Context(), *req.Username, *req.DisplayName)
|
user, err := h.users.Register(r.Context(), *req.Username, *req.DisplayName, *req.Password)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
h.fail(w, r, err)
|
h.fail(w, r, err)
|
||||||
return
|
return
|
||||||
|
|||||||
@@ -1,133 +0,0 @@
|
|||||||
package memory
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"slices"
|
|
||||||
"sync"
|
|
||||||
"time"
|
|
||||||
"uuid"
|
|
||||||
|
|
||||||
"messenger/internal/domain"
|
|
||||||
)
|
|
||||||
|
|
||||||
type Store struct {
|
|
||||||
mu sync.RWMutex
|
|
||||||
|
|
||||||
users map[uuid.UUID]domain.User
|
|
||||||
usernames map[string]uuid.UUID
|
|
||||||
chats map[uuid.UUID]domain.Chat
|
|
||||||
userChats map[uuid.UUID][]domain.Chat
|
|
||||||
chatHistory map[uuid.UUID][]domain.Message
|
|
||||||
}
|
|
||||||
|
|
||||||
func New() *Store {
|
|
||||||
return &Store{
|
|
||||||
users: make(map[uuid.UUID]domain.User),
|
|
||||||
usernames: make(map[string]uuid.UUID),
|
|
||||||
chats: make(map[uuid.UUID]domain.Chat),
|
|
||||||
userChats: make(map[uuid.UUID][]domain.Chat),
|
|
||||||
chatHistory: make(map[uuid.UUID][]domain.Message),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) CreateUser(_ context.Context, u domain.User) error {
|
|
||||||
s.mu.Lock()
|
|
||||||
defer s.mu.Unlock()
|
|
||||||
if _, taken := s.usernames[u.Username]; taken {
|
|
||||||
return domain.ErrConflict
|
|
||||||
}
|
|
||||||
s.users[u.ID] = u
|
|
||||||
s.usernames[u.Username] = u.ID
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) GetUser(_ context.Context, id uuid.UUID) (domain.User, error) {
|
|
||||||
s.mu.RLock()
|
|
||||||
defer s.mu.RUnlock()
|
|
||||||
u, ok := s.users[id]
|
|
||||||
if !ok {
|
|
||||||
return domain.User{}, domain.ErrNotFound
|
|
||||||
}
|
|
||||||
return u, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) CreateChat(_ context.Context, c domain.Chat) error {
|
|
||||||
c.MemberIDs = slices.Clone(c.MemberIDs)
|
|
||||||
s.mu.Lock()
|
|
||||||
defer s.mu.Unlock()
|
|
||||||
for _, id := range c.MemberIDs {
|
|
||||||
if _, ok := s.users[id]; !ok {
|
|
||||||
return domain.ErrNotFound
|
|
||||||
}
|
|
||||||
}
|
|
||||||
s.chats[c.ID] = c
|
|
||||||
for _, id := range c.MemberIDs {
|
|
||||||
s.userChats[id] = insertSorted(s.userChats[id], c, chatKey)
|
|
||||||
}
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) GetChat(_ context.Context, id uuid.UUID) (domain.Chat, error) {
|
|
||||||
s.mu.RLock()
|
|
||||||
defer s.mu.RUnlock()
|
|
||||||
c, ok := s.chats[id]
|
|
||||||
if !ok {
|
|
||||||
return domain.Chat{}, domain.ErrNotFound
|
|
||||||
}
|
|
||||||
c.MemberIDs = slices.Clone(c.MemberIDs)
|
|
||||||
return c, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) ListUserChats(_ context.Context, userID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Chat, bool, error) {
|
|
||||||
s.mu.RLock()
|
|
||||||
defer s.mu.RUnlock()
|
|
||||||
items, more := pageAfter(s.userChats[userID], after, limit, chatKey)
|
|
||||||
for i := range items {
|
|
||||||
items[i].MemberIDs = slices.Clone(items[i].MemberIDs)
|
|
||||||
}
|
|
||||||
return items, more, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) CreateMessage(_ context.Context, m domain.Message) error {
|
|
||||||
s.mu.Lock()
|
|
||||||
defer s.mu.Unlock()
|
|
||||||
if _, ok := s.chats[m.ChatID]; !ok {
|
|
||||||
return domain.ErrNotFound
|
|
||||||
}
|
|
||||||
s.chatHistory[m.ChatID] = insertSorted(s.chatHistory[m.ChatID], m, messageKey)
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func (s *Store) ListMessages(_ context.Context, chatID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Message, bool, error) {
|
|
||||||
s.mu.RLock()
|
|
||||||
defer s.mu.RUnlock()
|
|
||||||
items, more := pageAfter(s.chatHistory[chatID], after, limit, messageKey)
|
|
||||||
return items, more, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
func chatKey(c domain.Chat) (time.Time, uuid.UUID) { return c.CreatedAt, c.ID }
|
|
||||||
func messageKey(m domain.Message) (time.Time, uuid.UUID) { return m.CreatedAt, m.ID }
|
|
||||||
|
|
||||||
func insertSorted[T any](list []T, item T, key func(T) (time.Time, uuid.UUID)) []T {
|
|
||||||
t, id := key(item)
|
|
||||||
i, _ := slices.BinarySearchFunc(list, item, func(e T, _ T) int {
|
|
||||||
et, eid := key(e)
|
|
||||||
return domain.CompareKey(et, eid, t, id)
|
|
||||||
})
|
|
||||||
return slices.Insert(list, i, item)
|
|
||||||
}
|
|
||||||
|
|
||||||
func pageAfter[T any](list []T, after *domain.Cursor, limit int, key func(T) (time.Time, uuid.UUID)) ([]T, bool) {
|
|
||||||
start := 0
|
|
||||||
if after != nil {
|
|
||||||
start, _ = slices.BinarySearchFunc(list, after, func(e T, c *domain.Cursor) int {
|
|
||||||
et, eid := key(e)
|
|
||||||
if r := domain.CompareKey(et, eid, c.CreatedAt, c.ID); r != 0 {
|
|
||||||
return r
|
|
||||||
}
|
|
||||||
return -1
|
|
||||||
})
|
|
||||||
}
|
|
||||||
end := min(start+limit, len(list))
|
|
||||||
return slices.Clone(list[start:end]), end < len(list)
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
package postgres
|
||||||
|
|
||||||
|
import (
|
||||||
|
"embed"
|
||||||
|
"errors"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"github.com/golang-migrate/migrate/v4"
|
||||||
|
_ "github.com/golang-migrate/migrate/v4/database/pgx/v5"
|
||||||
|
"github.com/golang-migrate/migrate/v4/source/iofs"
|
||||||
|
)
|
||||||
|
|
||||||
|
//go:embed migrations/*.sql
|
||||||
|
var migrationsFS embed.FS
|
||||||
|
|
||||||
|
func Migrate(databaseURL string) error {
|
||||||
|
src, err := iofs.New(migrationsFS, "migrations")
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
m, err := migrate.NewWithSourceInstance("iofs", src, migrateURL(databaseURL))
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer m.Close()
|
||||||
|
if err := m.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func migrateURL(databaseURL string) string {
|
||||||
|
for _, prefix := range []string{"postgresql://", "postgres://"} {
|
||||||
|
if rest, ok := strings.CutPrefix(databaseURL, prefix); ok {
|
||||||
|
return "pgx5://" + rest
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return databaseURL
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
DROP TABLE IF EXISTS messages;
|
||||||
|
DROP TABLE IF EXISTS chat_members;
|
||||||
|
DROP TABLE IF EXISTS chats;
|
||||||
|
DROP TABLE IF EXISTS users;
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
CREATE TABLE users (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
username text NOT NULL UNIQUE,
|
||||||
|
display_name text NOT NULL,
|
||||||
|
password_hash text NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE chats (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
title text NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE TABLE chat_members (
|
||||||
|
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||||
|
user_id uuid NOT NULL REFERENCES users (id),
|
||||||
|
position int NOT NULL,
|
||||||
|
PRIMARY KEY (chat_id, user_id)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX chat_members_user_id_idx ON chat_members (user_id);
|
||||||
|
|
||||||
|
CREATE TABLE messages (
|
||||||
|
id uuid PRIMARY KEY,
|
||||||
|
chat_id uuid NOT NULL REFERENCES chats (id) ON DELETE CASCADE,
|
||||||
|
sender_id uuid NOT NULL REFERENCES users (id),
|
||||||
|
text text NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX messages_chat_created_id_idx ON messages (chat_id, created_at, id);
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
package postgres_test
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"os"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
"uuid"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
|
"messenger/internal/domain"
|
||||||
|
"messenger/internal/repository/postgres"
|
||||||
|
)
|
||||||
|
|
||||||
|
func newStore(t *testing.T) (*postgres.Store, *pgxpool.Pool) {
|
||||||
|
t.Helper()
|
||||||
|
dbURL := os.Getenv("TEST_DATABASE_URL")
|
||||||
|
if dbURL == "" {
|
||||||
|
t.Skip("TEST_DATABASE_URL is required")
|
||||||
|
}
|
||||||
|
if err := postgres.Migrate(dbURL); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
pool, err := postgres.NewPool(context.Background(), dbURL)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
t.Cleanup(pool.Close)
|
||||||
|
return postgres.New(pool), pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func newUser(username string) domain.User {
|
||||||
|
return domain.User{ID: uuid.New(), Username: username, DisplayName: "Test", CreatedAt: time.Now().UTC()}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRegisterUsernameRace(t *testing.T) {
|
||||||
|
store, pool := newStore(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
username := "race_" + uuid.New().String()[:8]
|
||||||
|
|
||||||
|
const workers = 20
|
||||||
|
var wg sync.WaitGroup
|
||||||
|
errs := make([]error, workers)
|
||||||
|
start := make(chan struct{})
|
||||||
|
for i := range workers {
|
||||||
|
wg.Go(func() {
|
||||||
|
<-start
|
||||||
|
errs[i] = store.CreateUser(ctx, newUser(username), "hash")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
close(start)
|
||||||
|
wg.Wait()
|
||||||
|
|
||||||
|
created := 0
|
||||||
|
for _, err := range errs {
|
||||||
|
switch {
|
||||||
|
case err == nil:
|
||||||
|
created++
|
||||||
|
case !errors.Is(err, domain.ErrConflict):
|
||||||
|
t.Errorf("unexpected error: %v", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if created != 1 {
|
||||||
|
t.Errorf("created %d users, want exactly 1", created)
|
||||||
|
}
|
||||||
|
var rows int
|
||||||
|
if err := pool.QueryRow(ctx, `SELECT count(*) FROM users WHERE username = $1`, username).Scan(&rows); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if rows != 1 {
|
||||||
|
t.Errorf("users rows = %d, want 1", rows)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreateChatRollback(t *testing.T) {
|
||||||
|
store, pool := newStore(t)
|
||||||
|
ctx := context.Background()
|
||||||
|
alice := newUser("rb_" + uuid.New().String()[:8])
|
||||||
|
if err := store.CreateUser(ctx, alice, "hash"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
chat := domain.Chat{
|
||||||
|
ID: uuid.New(),
|
||||||
|
Title: "rollback",
|
||||||
|
MemberIDs: []uuid.UUID{alice.ID, uuid.New()},
|
||||||
|
CreatedAt: time.Now().UTC(),
|
||||||
|
}
|
||||||
|
if err := store.CreateChat(ctx, chat); !errors.Is(err, domain.ErrNotFound) {
|
||||||
|
t.Fatalf("CreateChat with unknown member: got %v, want ErrNotFound", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
var chats, members int
|
||||||
|
if err := pool.QueryRow(ctx, `SELECT count(*) FROM chats WHERE id = $1`, chat.ID).Scan(&chats); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := pool.QueryRow(ctx, `SELECT count(*) FROM chat_members WHERE chat_id = $1`, chat.ID).Scan(&members); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if chats != 0 || members != 0 {
|
||||||
|
t.Errorf("after rollback: chats=%d chat_members=%d, want 0 and 0", chats, members)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,237 @@
|
|||||||
|
package postgres
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
"uuid"
|
||||||
|
|
||||||
|
"github.com/jackc/pgx/v5"
|
||||||
|
"github.com/jackc/pgx/v5/pgconn"
|
||||||
|
"github.com/jackc/pgx/v5/pgxpool"
|
||||||
|
|
||||||
|
"messenger/internal/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
maxConns = 10
|
||||||
|
connectTimeout = 3 * time.Second
|
||||||
|
statementTimeout = "5000"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Store struct {
|
||||||
|
pool *pgxpool.Pool
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewPool(ctx context.Context, databaseURL string) (*pgxpool.Pool, error) {
|
||||||
|
cfg, err := pgxpool.ParseConfig(databaseURL)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
cfg.MaxConns = maxConns
|
||||||
|
cfg.ConnConfig.ConnectTimeout = connectTimeout
|
||||||
|
cfg.ConnConfig.RuntimeParams["statement_timeout"] = statementTimeout
|
||||||
|
return pgxpool.NewWithConfig(ctx, cfg)
|
||||||
|
}
|
||||||
|
|
||||||
|
func New(pool *pgxpool.Pool) *Store {
|
||||||
|
return &Store{pool: pool}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) Ping(ctx context.Context) error {
|
||||||
|
return dbErr(s.pool.Ping(ctx))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) CreateUser(ctx context.Context, u domain.User, passwordHash string) error {
|
||||||
|
_, err := s.pool.Exec(ctx,
|
||||||
|
`INSERT INTO users (id, username, display_name, password_hash, created_at) VALUES ($1, $2, $3, $4, $5)`,
|
||||||
|
u.ID, u.Username, u.DisplayName, passwordHash, u.CreatedAt)
|
||||||
|
return dbErr(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) GetUser(ctx context.Context, id uuid.UUID) (domain.User, error) {
|
||||||
|
var u domain.User
|
||||||
|
err := s.pool.QueryRow(ctx,
|
||||||
|
`SELECT id, username, display_name, created_at FROM users WHERE id = $1`, id,
|
||||||
|
).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt)
|
||||||
|
return u, dbErr(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) GetUserByUsername(ctx context.Context, username string) (domain.User, string, error) {
|
||||||
|
var u domain.User
|
||||||
|
var hash string
|
||||||
|
err := s.pool.QueryRow(ctx,
|
||||||
|
`SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = $1`, username,
|
||||||
|
).Scan(&u.ID, &u.Username, &u.DisplayName, &u.CreatedAt, &hash)
|
||||||
|
return u, hash, dbErr(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) CreateChat(ctx context.Context, c domain.Chat) error {
|
||||||
|
tx, err := s.pool.Begin(ctx)
|
||||||
|
if err != nil {
|
||||||
|
return dbErr(err)
|
||||||
|
}
|
||||||
|
defer tx.Rollback(ctx)
|
||||||
|
|
||||||
|
if _, err := tx.Exec(ctx, `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`,
|
||||||
|
c.ID, c.Title, c.CreatedAt); err != nil {
|
||||||
|
return dbErr(err)
|
||||||
|
}
|
||||||
|
for i, userID := range c.MemberIDs {
|
||||||
|
if _, err := tx.Exec(ctx, `INSERT INTO chat_members (chat_id, user_id, position) VALUES ($1, $2, $3)`,
|
||||||
|
c.ID, userID, i); err != nil {
|
||||||
|
return dbErr(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return dbErr(tx.Commit(ctx))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) GetChat(ctx context.Context, id uuid.UUID) (domain.Chat, error) {
|
||||||
|
var c domain.Chat
|
||||||
|
err := s.pool.QueryRow(ctx, `SELECT id, title, created_at FROM chats WHERE id = $1`, id).
|
||||||
|
Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||||
|
if err != nil {
|
||||||
|
return domain.Chat{}, dbErr(err)
|
||||||
|
}
|
||||||
|
chats := []domain.Chat{c}
|
||||||
|
if err := s.loadMembers(ctx, chats); err != nil {
|
||||||
|
return domain.Chat{}, err
|
||||||
|
}
|
||||||
|
return chats[0], nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) ListUserChats(ctx context.Context, userID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Chat, bool, error) {
|
||||||
|
var rows pgx.Rows
|
||||||
|
var err error
|
||||||
|
if after == nil {
|
||||||
|
rows, err = s.pool.Query(ctx, `
|
||||||
|
SELECT c.id, c.title, c.created_at
|
||||||
|
FROM chats c
|
||||||
|
JOIN chat_members m ON m.chat_id = c.id
|
||||||
|
WHERE m.user_id = $1
|
||||||
|
ORDER BY c.created_at, c.id
|
||||||
|
LIMIT $2`, userID, limit+1)
|
||||||
|
} else {
|
||||||
|
rows, err = s.pool.Query(ctx, `
|
||||||
|
SELECT c.id, c.title, c.created_at
|
||||||
|
FROM chats c
|
||||||
|
JOIN chat_members m ON m.chat_id = c.id
|
||||||
|
WHERE m.user_id = $1 AND (c.created_at, c.id) > ($2, $3)
|
||||||
|
ORDER BY c.created_at, c.id
|
||||||
|
LIMIT $4`, userID, after.CreatedAt, after.ID, limit+1)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, dbErr(err)
|
||||||
|
}
|
||||||
|
chats, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (domain.Chat, error) {
|
||||||
|
var c domain.Chat
|
||||||
|
err := row.Scan(&c.ID, &c.Title, &c.CreatedAt)
|
||||||
|
return c, err
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, dbErr(err)
|
||||||
|
}
|
||||||
|
more := len(chats) > limit
|
||||||
|
if more {
|
||||||
|
chats = chats[:limit]
|
||||||
|
}
|
||||||
|
if err := s.loadMembers(ctx, chats); err != nil {
|
||||||
|
return nil, false, err
|
||||||
|
}
|
||||||
|
return chats, more, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) loadMembers(ctx context.Context, chats []domain.Chat) error {
|
||||||
|
if len(chats) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
ids := make([]uuid.UUID, len(chats))
|
||||||
|
index := make(map[uuid.UUID]int, len(chats))
|
||||||
|
for i, c := range chats {
|
||||||
|
ids[i] = c.ID
|
||||||
|
index[c.ID] = i
|
||||||
|
}
|
||||||
|
rows, err := s.pool.Query(ctx,
|
||||||
|
`SELECT chat_id, user_id FROM chat_members WHERE chat_id = ANY($1) ORDER BY chat_id, position`, ids)
|
||||||
|
if err != nil {
|
||||||
|
return dbErr(err)
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
for rows.Next() {
|
||||||
|
var chatID, userID uuid.UUID
|
||||||
|
if err := rows.Scan(&chatID, &userID); err != nil {
|
||||||
|
return dbErr(err)
|
||||||
|
}
|
||||||
|
i := index[chatID]
|
||||||
|
chats[i].MemberIDs = append(chats[i].MemberIDs, userID)
|
||||||
|
}
|
||||||
|
return dbErr(rows.Err())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) CreateMessage(ctx context.Context, m domain.Message) error {
|
||||||
|
_, err := s.pool.Exec(ctx,
|
||||||
|
`INSERT INTO messages (id, chat_id, sender_id, text, created_at) VALUES ($1, $2, $3, $4, $5)`,
|
||||||
|
m.ID, m.ChatID, m.SenderID, m.Text, m.CreatedAt)
|
||||||
|
return dbErr(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *Store) ListMessages(ctx context.Context, chatID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Message, bool, error) {
|
||||||
|
var rows pgx.Rows
|
||||||
|
var err error
|
||||||
|
if after == nil {
|
||||||
|
rows, err = s.pool.Query(ctx, `
|
||||||
|
SELECT id, chat_id, sender_id, text, created_at
|
||||||
|
FROM messages
|
||||||
|
WHERE chat_id = $1
|
||||||
|
ORDER BY created_at, id
|
||||||
|
LIMIT $2`, chatID, limit+1)
|
||||||
|
} else {
|
||||||
|
rows, err = s.pool.Query(ctx, `
|
||||||
|
SELECT id, chat_id, sender_id, text, created_at
|
||||||
|
FROM messages
|
||||||
|
WHERE chat_id = $1 AND (created_at, id) > ($2, $3)
|
||||||
|
ORDER BY created_at, id
|
||||||
|
LIMIT $4`, chatID, after.CreatedAt, after.ID, limit+1)
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, dbErr(err)
|
||||||
|
}
|
||||||
|
msgs, err := pgx.CollectRows(rows, func(row pgx.CollectableRow) (domain.Message, error) {
|
||||||
|
var m domain.Message
|
||||||
|
err := row.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt)
|
||||||
|
return m, err
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, false, dbErr(err)
|
||||||
|
}
|
||||||
|
more := len(msgs) > limit
|
||||||
|
if more {
|
||||||
|
msgs = msgs[:limit]
|
||||||
|
}
|
||||||
|
return msgs, more, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func dbErr(err error) error {
|
||||||
|
if err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return domain.ErrNotFound
|
||||||
|
}
|
||||||
|
var pgErr *pgconn.PgError
|
||||||
|
if errors.As(err, &pgErr) {
|
||||||
|
switch pgErr.Code {
|
||||||
|
case "23505":
|
||||||
|
return domain.ErrConflict
|
||||||
|
case "23503":
|
||||||
|
return domain.ErrNotFound
|
||||||
|
}
|
||||||
|
switch pgErr.Code[:2] {
|
||||||
|
case "08", "53", "57":
|
||||||
|
return fmt.Errorf("%w: %v", domain.ErrUnavailable, err)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return fmt.Errorf("%w: %v", domain.ErrUnavailable, err)
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package redis
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"time"
|
||||||
|
"uuid"
|
||||||
|
|
||||||
|
goredis "github.com/redis/go-redis/v9"
|
||||||
|
|
||||||
|
"messenger/internal/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
const keyPrefix = "session:"
|
||||||
|
|
||||||
|
type SessionStore struct {
|
||||||
|
client *goredis.Client
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewClient(url string) (*goredis.Client, error) {
|
||||||
|
opts, err := goredis.ParseURL(url)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
opts.PoolSize = 10
|
||||||
|
opts.DialTimeout = 2 * time.Second
|
||||||
|
opts.ReadTimeout = time.Second
|
||||||
|
opts.WriteTimeout = time.Second
|
||||||
|
opts.MaxRetries = 0
|
||||||
|
return goredis.NewClient(opts), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewSessionStore(client *goredis.Client) *SessionStore {
|
||||||
|
return &SessionStore{client: client}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SessionStore) Ping(ctx context.Context) error {
|
||||||
|
return cacheErr(s.client.Ping(ctx).Err())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SessionStore) Create(ctx context.Context, tokenHash string, userID uuid.UUID, expiresAt time.Time) error {
|
||||||
|
return cacheErr(s.client.SetArgs(ctx, keyPrefix+tokenHash, userID.String(),
|
||||||
|
goredis.SetArgs{ExpireAt: expiresAt}).Err())
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SessionStore) Get(ctx context.Context, tokenHash string) (uuid.UUID, error) {
|
||||||
|
v, err := s.client.Get(ctx, keyPrefix+tokenHash).Result()
|
||||||
|
if errors.Is(err, goredis.Nil) {
|
||||||
|
return uuid.UUID{}, domain.ErrUnauthorized
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return uuid.UUID{}, cacheErr(err)
|
||||||
|
}
|
||||||
|
id, err := uuid.Parse(v)
|
||||||
|
if err != nil {
|
||||||
|
return uuid.UUID{}, domain.ErrUnauthorized
|
||||||
|
}
|
||||||
|
return id, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *SessionStore) Delete(ctx context.Context, tokenHash string) error {
|
||||||
|
return cacheErr(s.client.Del(ctx, keyPrefix+tokenHash).Err())
|
||||||
|
}
|
||||||
|
|
||||||
|
func cacheErr(err error) error {
|
||||||
|
if err == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return fmt.Errorf("%w: %v", domain.ErrUnavailable, err)
|
||||||
|
}
|
||||||
@@ -20,9 +20,11 @@ func New(h *handler.Handler) http.Handler {
|
|||||||
|
|
||||||
r.Route("/api/v1", func(r chi.Router) {
|
r.Route("/api/v1", func(r chi.Router) {
|
||||||
r.Post("/users", h.RegisterUser)
|
r.Post("/users", h.RegisterUser)
|
||||||
|
r.Post("/auth/sessions", h.CreateSession)
|
||||||
|
|
||||||
r.Group(func(r chi.Router) {
|
r.Group(func(r chi.Router) {
|
||||||
r.Use(h.Authenticate)
|
r.Use(h.Authenticate)
|
||||||
|
r.Delete("/auth/sessions/current", h.DeleteSession)
|
||||||
r.Get("/users/me", h.CurrentUser)
|
r.Get("/users/me", h.CurrentUser)
|
||||||
r.Post("/chats", h.CreateChat)
|
r.Post("/chats", h.CreateChat)
|
||||||
r.Get("/chats", h.ListChats)
|
r.Get("/chats", h.ListChats)
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/sha256"
|
||||||
|
"encoding/base64"
|
||||||
|
"encoding/hex"
|
||||||
|
"errors"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"messenger/internal/domain"
|
||||||
|
)
|
||||||
|
|
||||||
|
const tokenBytes = 32
|
||||||
|
|
||||||
|
type AuthService struct {
|
||||||
|
users UserRepository
|
||||||
|
sessions SessionStore
|
||||||
|
ttl time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewAuthService(users UserRepository, sessions SessionStore, ttl time.Duration) *AuthService {
|
||||||
|
return &AuthService{users: users, sessions: sessions, ttl: ttl}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AuthService) Login(ctx context.Context, username, password string) (domain.Session, error) {
|
||||||
|
user, hash, err := s.users.GetUserByUsername(ctx, username)
|
||||||
|
if errors.Is(err, domain.ErrNotFound) {
|
||||||
|
return domain.Session{}, domain.ErrUnauthorized
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return domain.Session{}, err
|
||||||
|
}
|
||||||
|
ok, err := verifyPassword(password, hash)
|
||||||
|
if err != nil {
|
||||||
|
return domain.Session{}, err
|
||||||
|
}
|
||||||
|
if !ok {
|
||||||
|
return domain.Session{}, domain.ErrUnauthorized
|
||||||
|
}
|
||||||
|
|
||||||
|
raw := make([]byte, tokenBytes)
|
||||||
|
if _, err := rand.Read(raw); err != nil {
|
||||||
|
return domain.Session{}, err
|
||||||
|
}
|
||||||
|
token := base64.RawURLEncoding.EncodeToString(raw)
|
||||||
|
expiresAt := now().Add(s.ttl)
|
||||||
|
if err := s.sessions.Create(ctx, HashToken(token), user.ID, expiresAt); err != nil {
|
||||||
|
return domain.Session{}, err
|
||||||
|
}
|
||||||
|
return domain.Session{Token: token, ExpiresAt: expiresAt, User: user}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AuthService) Authenticate(ctx context.Context, token string) (domain.User, error) {
|
||||||
|
userID, err := s.sessions.Get(ctx, HashToken(token))
|
||||||
|
if err != nil {
|
||||||
|
return domain.User{}, err
|
||||||
|
}
|
||||||
|
u, err := s.users.GetUser(ctx, userID)
|
||||||
|
if errors.Is(err, domain.ErrNotFound) {
|
||||||
|
return domain.User{}, domain.ErrUnauthorized
|
||||||
|
}
|
||||||
|
return u, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *AuthService) Logout(ctx context.Context, token string) error {
|
||||||
|
return s.sessions.Delete(ctx, HashToken(token))
|
||||||
|
}
|
||||||
|
|
||||||
|
func HashToken(token string) string {
|
||||||
|
sum := sha256.Sum256([]byte(token))
|
||||||
|
return hex.EncodeToString(sum[:])
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
package service
|
||||||
|
|
||||||
|
import (
|
||||||
|
"crypto/rand"
|
||||||
|
"crypto/subtle"
|
||||||
|
"encoding/base64"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
"golang.org/x/crypto/argon2"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
argonMemory = 19 * 1024
|
||||||
|
argonTime = 2
|
||||||
|
argonThreads = 1
|
||||||
|
argonSaltLen = 16
|
||||||
|
argonKeyLen = 32
|
||||||
|
)
|
||||||
|
|
||||||
|
var errBadHash = errors.New("malformed password hash")
|
||||||
|
|
||||||
|
func hashPassword(password string) (string, error) {
|
||||||
|
salt := make([]byte, argonSaltLen)
|
||||||
|
if _, err := rand.Read(salt); err != nil {
|
||||||
|
return "", err
|
||||||
|
}
|
||||||
|
key := argon2.IDKey([]byte(password), salt, argonTime, argonMemory, argonThreads, argonKeyLen)
|
||||||
|
b64 := base64.RawStdEncoding
|
||||||
|
return fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s",
|
||||||
|
argon2.Version, argonMemory, argonTime, argonThreads, b64.EncodeToString(salt), b64.EncodeToString(key)), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func verifyPassword(password, encoded string) (bool, error) {
|
||||||
|
parts := strings.Split(encoded, "$")
|
||||||
|
if len(parts) != 6 || parts[1] != "argon2id" {
|
||||||
|
return false, errBadHash
|
||||||
|
}
|
||||||
|
var version int
|
||||||
|
var memory, time uint32
|
||||||
|
var threads uint8
|
||||||
|
if _, err := fmt.Sscanf(parts[2], "v=%d", &version); err != nil || version != argon2.Version {
|
||||||
|
return false, errBadHash
|
||||||
|
}
|
||||||
|
if _, err := fmt.Sscanf(parts[3], "m=%d,t=%d,p=%d", &memory, &time, &threads); err != nil {
|
||||||
|
return false, errBadHash
|
||||||
|
}
|
||||||
|
b64 := base64.RawStdEncoding
|
||||||
|
salt, err := b64.DecodeString(parts[4])
|
||||||
|
if err != nil {
|
||||||
|
return false, errBadHash
|
||||||
|
}
|
||||||
|
want, err := b64.DecodeString(parts[5])
|
||||||
|
if err != nil {
|
||||||
|
return false, errBadHash
|
||||||
|
}
|
||||||
|
got := argon2.IDKey([]byte(password), salt, time, memory, threads, uint32(len(want)))
|
||||||
|
return subtle.ConstantTimeCompare(got, want) == 1, nil
|
||||||
|
}
|
||||||
@@ -9,8 +9,9 @@ import (
|
|||||||
)
|
)
|
||||||
|
|
||||||
type UserRepository interface {
|
type UserRepository interface {
|
||||||
CreateUser(ctx context.Context, u domain.User) error
|
CreateUser(ctx context.Context, u domain.User, passwordHash string) error
|
||||||
GetUser(ctx context.Context, id uuid.UUID) (domain.User, error)
|
GetUser(ctx context.Context, id uuid.UUID) (domain.User, error)
|
||||||
|
GetUserByUsername(ctx context.Context, username string) (domain.User, string, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
type ChatRepository interface {
|
type ChatRepository interface {
|
||||||
@@ -24,6 +25,12 @@ type MessageRepository interface {
|
|||||||
ListMessages(ctx context.Context, chatID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Message, bool, error)
|
ListMessages(ctx context.Context, chatID uuid.UUID, after *domain.Cursor, limit int) ([]domain.Message, bool, error)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type SessionStore interface {
|
||||||
|
Create(ctx context.Context, tokenHash string, userID uuid.UUID, expiresAt time.Time) error
|
||||||
|
Get(ctx context.Context, tokenHash string) (uuid.UUID, error)
|
||||||
|
Delete(ctx context.Context, tokenHash string) error
|
||||||
|
}
|
||||||
|
|
||||||
func now() time.Time {
|
func now() time.Time {
|
||||||
return time.Now().UTC().Truncate(time.Microsecond)
|
return time.Now().UTC().Truncate(time.Microsecond)
|
||||||
}
|
}
|
||||||
|
|||||||
+18
-11
@@ -2,9 +2,9 @@ package service
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"errors"
|
|
||||||
"fmt"
|
"fmt"
|
||||||
"regexp"
|
"regexp"
|
||||||
|
"unicode/utf8"
|
||||||
"uuid"
|
"uuid"
|
||||||
|
|
||||||
"messenger/internal/domain"
|
"messenger/internal/domain"
|
||||||
@@ -12,6 +12,11 @@ import (
|
|||||||
|
|
||||||
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||||
|
|
||||||
|
const (
|
||||||
|
minPasswordLen = 12
|
||||||
|
maxPasswordLen = 128
|
||||||
|
)
|
||||||
|
|
||||||
type UserService struct {
|
type UserService struct {
|
||||||
repo UserRepository
|
repo UserRepository
|
||||||
}
|
}
|
||||||
@@ -20,29 +25,31 @@ func NewUserService(repo UserRepository) *UserService {
|
|||||||
return &UserService{repo: repo}
|
return &UserService{repo: repo}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *UserService) Register(ctx context.Context, username, displayName string) (domain.User, error) {
|
func (s *UserService) Register(ctx context.Context, username, displayName, password string) (domain.User, error) {
|
||||||
if !usernameRe.MatchString(username) {
|
if !usernameRe.MatchString(username) {
|
||||||
return domain.User{}, fmt.Errorf("%w: username must match [a-z0-9_]{3,32}", domain.ErrInvalidInput)
|
return domain.User{}, fmt.Errorf("%w: username must match [a-z0-9_]{3,32}", domain.ErrInvalidInput)
|
||||||
}
|
}
|
||||||
if err := checkText("display_name", displayName, 100); err != nil {
|
if err := checkText("display_name", displayName, 100); err != nil {
|
||||||
return domain.User{}, err
|
return domain.User{}, err
|
||||||
}
|
}
|
||||||
|
if err := checkText("password", password, maxPasswordLen); err != nil {
|
||||||
|
return domain.User{}, err
|
||||||
|
}
|
||||||
|
if utf8.RuneCountInString(password) < minPasswordLen {
|
||||||
|
return domain.User{}, fmt.Errorf("%w: password must be at least %d characters", domain.ErrInvalidInput, minPasswordLen)
|
||||||
|
}
|
||||||
|
hash, err := hashPassword(password)
|
||||||
|
if err != nil {
|
||||||
|
return domain.User{}, err
|
||||||
|
}
|
||||||
u := domain.User{
|
u := domain.User{
|
||||||
ID: uuid.New(),
|
ID: uuid.New(),
|
||||||
Username: username,
|
Username: username,
|
||||||
DisplayName: displayName,
|
DisplayName: displayName,
|
||||||
CreatedAt: now(),
|
CreatedAt: now(),
|
||||||
}
|
}
|
||||||
if err := s.repo.CreateUser(ctx, u); err != nil {
|
if err := s.repo.CreateUser(ctx, u, hash); err != nil {
|
||||||
return domain.User{}, err
|
return domain.User{}, err
|
||||||
}
|
}
|
||||||
return u, nil
|
return u, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
func (s *UserService) Authenticate(ctx context.Context, id uuid.UUID) (domain.User, error) {
|
|
||||||
u, err := s.repo.GetUser(ctx, id)
|
|
||||||
if errors.Is(err, domain.ErrNotFound) {
|
|
||||||
return domain.User{}, domain.ErrUnauthorized
|
|
||||||
}
|
|
||||||
return u, err
|
|
||||||
}
|
|
||||||
|
|||||||
Reference in New Issue
Block a user