From 71174f844cb7fe4306d567e8baeb0adcab7a6f81 Mon Sep 17 00:00:00 2001 From: imadev Date: Mon, 26 Oct 2026 19:39:45 +0300 Subject: [PATCH] refactor(app) AI refactoring before moving to Lab3 done --- app/cmd/server/main.go | 9 +- app/go.mod | 7 +- app/go.sum | 66 +++- app/internal/app.go | 42 ++- app/internal/auth/handler.go | 10 +- app/internal/auth/router.go | 2 +- app/internal/chats/handler.go | 10 +- app/internal/chats/router.go | 2 +- app/internal/common/binding.go | 44 +++ app/internal/common/helpers.go | 17 - app/internal/common/locals.go | 36 ++ app/internal/common/time.go | 36 ++ app/internal/common/time_test.go | 48 +++ .../common/{validator.go => validation.go} | 54 +-- app/internal/database/database.go | 83 +---- app/internal/database/migrations.go | 162 +++++++++ .../database/migrations/0001_init.down.sql | 6 + .../{0001_init.sql => 0001_init.up.sql} | 0 app/internal/database/migrations_test.go | 43 +++ app/internal/messages/handler.go | 6 +- app/internal/messages/router.go | 2 +- app/internal/model/model.go | 34 +- app/internal/store/chats.go | 148 ++++++++ app/internal/store/errors.go | 44 +++ app/internal/store/messages.go | 104 ++++++ app/internal/store/pagination.go | 17 + app/internal/store/store.go | 337 +----------------- app/internal/store/users.go | 72 ++++ app/internal/users/handler.go | 12 +- app/internal/users/router.go | 2 +- 30 files changed, 895 insertions(+), 560 deletions(-) create mode 100644 app/internal/common/binding.go delete mode 100644 app/internal/common/helpers.go create mode 100644 app/internal/common/locals.go create mode 100644 app/internal/common/time.go create mode 100644 app/internal/common/time_test.go rename app/internal/common/{validator.go => validation.go} (62%) create mode 100644 app/internal/database/migrations.go create mode 100644 app/internal/database/migrations/0001_init.down.sql rename app/internal/database/migrations/{0001_init.sql => 0001_init.up.sql} (100%) create mode 100644 app/internal/database/migrations_test.go create mode 100644 app/internal/store/chats.go create mode 100644 app/internal/store/errors.go create mode 100644 app/internal/store/messages.go create mode 100644 app/internal/store/pagination.go create mode 100644 app/internal/store/users.go diff --git a/app/cmd/server/main.go b/app/cmd/server/main.go index 5b7fae6..9bfa9da 100755 --- a/app/cmd/server/main.go +++ b/app/cmd/server/main.go @@ -3,6 +3,7 @@ package main import ( "context" "log" + "net" "os/signal" "syscall" "time" @@ -29,11 +30,11 @@ func main() { defer pool.Close() migrateCtx, cancelMigrate := context.WithTimeout(rootCtx, 60*time.Second) - if err = database.Migrate(migrateCtx, pool); err != nil { - cancelMigrate() + err = database.Migrate(migrateCtx, pool, cfg.DatabaseURL) + cancelMigrate() + if err != nil { log.Fatalf("migrations: %v", err) } - cancelMigrate() sessions, err := session.New(cfg.CacheURL, cfg.SessionTTL, cfg.RedisTimeout) if err != nil { @@ -43,7 +44,7 @@ func main() { app := internal.New(cfg, pool, sessions) - addr := cfg.Host + ":" + cfg.Port + addr := net.JoinHostPort(cfg.Host, cfg.Port) listenErr := make(chan error, 1) go func() { listenErr <- app.Listen(addr) diff --git a/app/go.mod b/app/go.mod index 7219bb5..3340a24 100755 --- a/app/go.mod +++ b/app/go.mod @@ -3,8 +3,8 @@ module gitflic.ru/project/bulla-max/mtusi2026lab2 go 1.27.1 require ( - github.com/go-playground/validator v9.31.0+incompatible github.com/gofiber/fiber/v3 v3.5.0 + github.com/golang-migrate/migrate/v4 v4.20.1 github.com/google/uuid v1.6.0 github.com/jackc/pgx/v5 v5.11.0 github.com/redis/go-redis/v9 v9.23.0 @@ -13,15 +13,13 @@ require ( require ( github.com/cespare/xxhash/v2 v2.3.0 // indirect - github.com/go-playground/locales v0.14.1 // indirect - github.com/go-playground/universal-translator v0.18.2 // indirect github.com/gofiber/schema v1.8.8 // indirect github.com/gofiber/utils/v2 v2.6.1 // 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 github.com/klauspost/compress v1.20.1 // indirect - github.com/leodido/go-urn v1.5.0 // indirect github.com/mattn/go-colorable v0.1.15 // indirect github.com/mattn/go-isatty v0.0.24 // indirect github.com/molecule-man/go-brrr v1.1.1 // indirect @@ -35,5 +33,4 @@ require ( golang.org/x/sys v0.48.0 // indirect golang.org/x/text v0.42.0 // indirect golang.org/x/tools v0.50.0 // indirect - gopkg.in/go-playground/assert.v1 v1.2.1 // indirect ) diff --git a/app/go.sum b/app/go.sum index da9f026..623cc7e 100755 --- a/app/go.sum +++ b/app/go.sum @@ -1,26 +1,48 @@ +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/fxamacker/cbor/v2 v2.9.4 h1:xwjVlxEMR3S605oUlgBjKLTTeGFciYPGYCtF/35LKGo= github.com/fxamacker/cbor/v2 v2.9.4/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= -github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= -github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= -github.com/go-playground/universal-translator v0.18.2 h1:LCsMLC9RzmbUMNUPVYD15dmcjwYAJhmX8mPZRW4rAVU= -github.com/go-playground/universal-translator v0.18.2/go.mod h1:67VZIMp5lQpDWlnStOct22q1bkdJGJqHghbOtmkawxk= -github.com/go-playground/validator v9.31.0+incompatible h1:UA72EPEogEnq76ehGdEDp4Mit+3FDh548oRqwVgNsHA= -github.com/go-playground/validator v9.31.0+incompatible/go.mod h1:yrEkQXlcI+PugkyDjY2bRrL/UBU4f3rvrgkN3V8JEig= +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/gofiber/fiber/v3 v3.5.0 h1:dk7TOUH6DXJGtOLsN2XEG+0ZML7cznzHILTVozbNEK8= github.com/gofiber/fiber/v3 v3.5.0/go.mod h1:GOVDTW+gjJvfe0iJyVujbQ1Lnx+JUjFySJRI/9/xX/w= github.com/gofiber/schema v1.8.8 h1:md5t65+Z9LttOuj7FdMcQ63D2+6GniT2ganLXwvTJM4= github.com/gofiber/schema v1.8.8/go.mod h1:Hzf0L/fTPP1IwOAwKipKflm9C2722aebnSKJCMOgb1I= github.com/gofiber/utils/v2 v2.6.1 h1:x3zsS/oUQz0ia2Zx8XXtG/7naR5a+/95FRO8mwQ5QQ4= github.com/gofiber/utils/v2 v2.6.1/go.mod h1:tc9KqdRAQZRD/u0mN2d1ZHROGheSZv+0FcC9cg5OEdw= +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/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/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= @@ -33,16 +55,32 @@ github.com/klauspost/compress v1.20.1 h1:T7kKElXUMXrUJ2E9QhQhxFtcK5rPyLdsGZvdbLM github.com/klauspost/compress v1.20.1/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= 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/leodido/go-urn v1.5.0 h1:pLqT2kq1zpHW/1D18QMjMpdtX7cekxqtJJjg5ANyWw0= -github.com/leodido/go-urn v1.5.0/go.mod h1:9BORnCDhdPBJNDEX+w1bJisa8yOKYi116VeO96s4ifE= +github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw= +github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o= github.com/mattn/go-colorable v0.1.15 h1:+u9SLTRGnXv73cEsnsmoZBom+dMU88B2M0aDcWy0/jY= github.com/mattn/go-colorable v0.1.15/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= github.com/mattn/go-isatty v0.0.24 h1:tGZZoVgT/KiqK1c8ocVLeDS8BSWMRd47J3Lbz7vsReI= github.com/mattn/go-isatty v0.0.24/go.mod h1:nMCL3Zebbrt45jsMDgnfIwz6ydEQApk5oEI3HqDio6A= +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/molecule-man/go-brrr v1.1.1 h1:KYwusQhjtV3smALnhmafZf4OBrh7vP4p8O47DyUmmuY= github.com/molecule-man/go-brrr v1.1.1/go.mod h1:7ybW6/7gA3oKY45jOfVNjSJDtrr6ea4tzbsTkjmQDC4= +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/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM= github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM= +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= @@ -63,6 +101,16 @@ github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= 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= @@ -80,6 +128,4 @@ golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= golang.org/x/tools v0.50.0 h1:c2ifzfcuY7L90lZ2aKd8S4K2NpASF08SZx9ZuJkHmSU= golang.org/x/tools v0.50.0/go.mod h1:7ulVMw3831Mwi5EZD6RomGyffr4VFjuNYXf2BbCEAV0= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/go-playground/assert.v1 v1.2.1 h1:xoYuJVE7KT85PYWrN730RguIQO0ePzVRfFMXadIrXTM= -gopkg.in/go-playground/assert.v1 v1.2.1/go.mod h1:9RXL0bg/zibRAgZUYszZSwO/z8Y/a8bDuhia5mkpMnE= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/app/internal/app.go b/app/internal/app.go index b843526..c91bd6b 100755 --- a/app/internal/app.go +++ b/app/internal/app.go @@ -31,21 +31,7 @@ func New(cfg config.Config, pool *pgxpool.Pool, sessions *session.Store) *fiber. WriteTimeout: 10 * time.Second, IdleTimeout: 60 * time.Second, BodyLimit: 1 * 1024 * 1024, - ErrorHandler: func(c fiber.Ctx, err error) error { - var appErr *common.AppError - if errors.As(err, &appErr) { - return common.SendError(c, appErr.Status, appErr.Code, appErr.Message) - } - - var fiberErr *fiber.Error - if errors.As(err, &fiberErr) { - return common.SendError(c, fiberErr.Code, - common.ErrorCodeFromStatus(fiberErr.Code), fiberErr.Message) - } - - return common.SendError(c, fiber.StatusInternalServerError, - common.ErrorCodeInternal, "Internal server error") - }, + ErrorHandler: handleError, }) app.Use(recover.New()) @@ -59,10 +45,28 @@ func New(cfg config.Config, pool *pgxpool.Pool, sessions *session.Store) *fiber. protected := api.Group("") protected.Use(auth.BearerAuth(sessions)) - auth.RegisterRoutes(protected, st, sessions) - users.RegisterRoutes(protected, st) - chats.RegisterRoutes(protected, st) - messages.RegisterRoutes(protected, st) + auth.RegisterProtectedRoutes(protected, st, sessions) + users.RegisterProtectedRoutes(protected, st) + chats.RegisterProtectedRoutes(protected, st) + messages.RegisterProtectedRoutes(protected, st) return app } + +// handleError keeps every failure in the contract error envelope, including +// Fiber's own errors (404, 405, 413) and recovered panics. +func handleError(c fiber.Ctx, err error) error { + var appErr *common.AppError + if errors.As(err, &appErr) { + return common.SendError(c, appErr.Status, appErr.Code, appErr.Message) + } + + var fiberErr *fiber.Error + if errors.As(err, &fiberErr) { + return common.SendError(c, fiberErr.Code, + common.ErrorCodeFromStatus(fiberErr.Code), fiberErr.Message) + } + + return common.SendError(c, fiber.StatusInternalServerError, + common.ErrorCodeInternal, "Internal server error") +} diff --git a/app/internal/auth/handler.go b/app/internal/auth/handler.go index 7a0b42d..9e60ddc 100644 --- a/app/internal/auth/handler.go +++ b/app/internal/auth/handler.go @@ -65,8 +65,8 @@ func (h *Handler) CreateSession(c fiber.Ctx) error { // RevokeSession deletes the current token. The middleware has already proven // that the token exists, so a repeated DELETE is a 401, not a 204. func (h *Handler) RevokeSession(c fiber.Ctx) error { - token, _ := c.Locals(sessionTokenLocal).(string) - if token == "" { + token, ok := common.SessionToken(c) + if !ok { return common.SendChallenge(c, bearerChallenge, "authentication required") } @@ -79,8 +79,6 @@ func (h *Handler) RevokeSession(c fiber.Ctx) error { return c.SendStatus(fiber.StatusNoContent) } -const sessionTokenLocal = "sessionToken" - // BearerAuth accepts only an opaque Bearer token. X-User-Id is deliberately // never read: with lab 2 it can neither create nor override an identity. func BearerAuth(sessions *session.Store) fiber.Handler { @@ -104,8 +102,8 @@ func BearerAuth(sessions *session.Store) fiber.Handler { common.ErrorCodeUnavailable, "session store unavailable") } - c.Locals("userID", userID) - c.Locals(sessionTokenLocal, token) + c.Locals(common.KeyUserID, userID) + c.Locals(common.KeySessionToken, token) return c.Next() } } diff --git a/app/internal/auth/router.go b/app/internal/auth/router.go index 23cc3da..04775b3 100644 --- a/app/internal/auth/router.go +++ b/app/internal/auth/router.go @@ -11,7 +11,7 @@ func RegisterPublicRoutes(router fiber.Router, st *store.Store, sessions *sessio router.Post("/auth/sessions", handler.CreateSession) } -func RegisterRoutes(router fiber.Router, st *store.Store, sessions *session.Store) { +func RegisterProtectedRoutes(router fiber.Router, st *store.Store, sessions *session.Store) { handler := NewHandler(st, sessions) router.Delete("/auth/sessions/current", handler.RevokeSession) } diff --git a/app/internal/chats/handler.go b/app/internal/chats/handler.go index 2a8fbc3..4fa0c0b 100644 --- a/app/internal/chats/handler.go +++ b/app/internal/chats/handler.go @@ -16,12 +16,12 @@ func NewHandler(st *store.Store) *Handler { } type CreateChatRequest struct { - Title string `json:"title" validate:"required"` - MemberIDs []uuid.UUID `json:"member_ids" validate:"required"` + Title string `json:"title"` + MemberIDs []uuid.UUID `json:"member_ids"` } func (h *Handler) CreateChat(c fiber.Ctx) error { - userID := c.Locals("userID").(uuid.UUID) + userID := common.MustUserID(c) var req CreateChatRequest if err := common.BindJSON(c, &req); err != nil { @@ -44,7 +44,7 @@ func (h *Handler) CreateChat(c fiber.Ctx) error { } func (h *Handler) ListChats(c fiber.Ctx) error { - userID := c.Locals("userID").(uuid.UUID) + userID := common.MustUserID(c) limit, err := common.ParseLimit(c, 50) if err != nil { @@ -69,7 +69,7 @@ func (h *Handler) ListChats(c fiber.Ctx) error { } func (h *Handler) GetChat(c fiber.Ctx) error { - userID := c.Locals("userID").(uuid.UUID) + userID := common.MustUserID(c) chatID, err := uuid.Parse(c.Params("chat_id")) if err != nil { diff --git a/app/internal/chats/router.go b/app/internal/chats/router.go index 4ee3c19..3329ac3 100644 --- a/app/internal/chats/router.go +++ b/app/internal/chats/router.go @@ -5,7 +5,7 @@ import ( "github.com/gofiber/fiber/v3" ) -func RegisterRoutes(router fiber.Router, st *store.Store) { +func RegisterProtectedRoutes(router fiber.Router, st *store.Store) { handler := NewHandler(st) router.Post("/chats", handler.CreateChat) router.Get("/chats", handler.ListChats) diff --git a/app/internal/common/binding.go b/app/internal/common/binding.go new file mode 100644 index 0000000..f715a72 --- /dev/null +++ b/app/internal/common/binding.go @@ -0,0 +1,44 @@ +package common + +import ( + "bytes" + "encoding/json" + "io" + "strings" + + "github.com/gofiber/fiber/v3" +) + +// AGENT: Field-level validation is deliberately not delegated to a generic +// struct validator. The contract needs specific messages for blank strings, +// Unicode length and duplicate member IDs, so handlers call the Validators in +// validation.go after this strict JSON decoding step. +// +// BindJSON enforces the request format from the contract: JSON content type, +// exactly one JSON value, no unknown fields and correct Go types. Field-level +// rules (non-blank strings, lengths, UUID lists) stay in the handlers so their +// messages can be specific. +func BindJSON(c fiber.Ctx, dst any) error { + if contentType := c.Get(fiber.HeaderContentType); !strings.HasPrefix(contentType, "application/json") { + return UnsupportedMedia("invalid JSON body") + } + + body := c.Body() + if len(body) == 0 { + return BadRequest("request body is empty") + } + + decoder := json.NewDecoder(bytes.NewReader(body)) + decoder.DisallowUnknownFields() + + if err := decoder.Decode(dst); err != nil { + return BadRequest("invalid JSON body") + } + + var extra json.RawMessage + if err := decoder.Decode(&extra); err != io.EOF { + return BadRequest("request body has extra trailing bytes") + } + + return nil +} diff --git a/app/internal/common/helpers.go b/app/internal/common/helpers.go deleted file mode 100644 index 56634b7..0000000 --- a/app/internal/common/helpers.go +++ /dev/null @@ -1,17 +0,0 @@ -package common - -import ( - "encoding/json" - "time" -) - -type RFCFormTime time.Time - -func (t RFCFormTime) MarshalJSON() ([]byte, error) { - ftime := time.Time(t).UTC().Format(time.RFC3339) - return json.Marshal(ftime) -} - -func NowUTC() RFCFormTime { - return RFCFormTime(time.Now().UTC()) -} diff --git a/app/internal/common/locals.go b/app/internal/common/locals.go new file mode 100644 index 0000000..9f97760 --- /dev/null +++ b/app/internal/common/locals.go @@ -0,0 +1,36 @@ +package common + +import ( + "github.com/gofiber/fiber/v3" + "github.com/google/uuid" +) + +const ( + // KeyUserID is the request-scoped key set by the Bearer middleware. + KeyUserID = "userID" + // KeySessionToken is the raw token of the current request. + KeySessionToken = "sessionToken" +) + +// UserID returns the authenticated user ID and whether the middleware set it. +func UserID(c fiber.Ctx) (uuid.UUID, bool) { + userID, ok := c.Locals(KeyUserID).(uuid.UUID) + return userID, ok +} + +// MustUserID is for handlers mounted behind BearerAuth, where the middleware +// guarantees the local. A missing value is a programming error, not a client +// error, so it becomes a recovered 500 instead of an anonymous request. +func MustUserID(c fiber.Ctx) uuid.UUID { + userID, ok := UserID(c) + if !ok { + panic("common: authenticated user ID is missing from the request context") + } + return userID +} + +// SessionToken returns the raw bearer token of the current request. +func SessionToken(c fiber.Ctx) (string, bool) { + token, ok := c.Locals(KeySessionToken).(string) + return token, ok && token != "" +} diff --git a/app/internal/common/time.go b/app/internal/common/time.go new file mode 100644 index 0000000..6903069 --- /dev/null +++ b/app/internal/common/time.go @@ -0,0 +1,36 @@ +package common + +import ( + "encoding/json" + "time" +) + +// storageTimePrecision is the maximum precision shared by PostgreSQL +// timestamptz columns and the JSON representation. PostgreSQL stores +// microseconds, so keeping the same boundary in Go prevents a create response +// from showing more precision than a later read can reproduce. +const storageTimePrecision = time.Microsecond + +type RFCFormTime time.Time + +func (t RFCFormTime) MarshalJSON() ([]byte, error) { + // RFC 3339 permits an optional fractional second. Use all six digits that + // PostgreSQL can store, and omit the fraction only for an exact second. + // A fixed six-digit fraction is also accepted by strict consumers that only + // understand 3- or 6-digit fractions (for example Python 3.9's parser). + utc := time.Time(t).UTC().Truncate(storageTimePrecision) + layout := "2006-01-02T15:04:05Z" + if utc.Nanosecond() != 0 { + layout = "2006-01-02T15:04:05.000000Z" + } + return json.Marshal(utc.Format(layout)) +} + +func NowUTC() RFCFormTime { + // AGENT: The API used to truncate timestamps to whole seconds to keep + // keyset ordering consistent with JSON. RFC 3339 supports fractional seconds + // and PostgreSQL has microsecond precision, so use that precision end to end: + // timestamps remain ordered after serialization without discarding sub-second + // information. + return RFCFormTime(time.Now().UTC().Truncate(storageTimePrecision)) +} diff --git a/app/internal/common/time_test.go b/app/internal/common/time_test.go new file mode 100644 index 0000000..a177d48 --- /dev/null +++ b/app/internal/common/time_test.go @@ -0,0 +1,48 @@ +package common + +import ( + "encoding/json" + "testing" + "time" +) + +func TestNowUTCHasMicrosecondPrecision(t *testing.T) { + now := time.Time(NowUTC()) + if now.Nanosecond()%1000 != 0 { + t.Fatalf("NowUTC() kept precision below a microsecond: %v", now) + } + if now.Location() != time.UTC { + t.Fatalf("NowUTC() location = %v, want UTC", now.Location()) + } +} + +func TestRFCFormTimeSerializesFractionalSeconds(t *testing.T) { + cases := []struct { + name string + value time.Time + want string + }{ + { + name: "microseconds", + value: time.Date(2026, 10, 26, 12, 34, 56, 123456789, time.UTC), + want: `"2026-10-26T12:34:56.123456Z"`, + }, + { + name: "exact second", + value: time.Date(2026, 10, 26, 12, 34, 56, 0, time.UTC), + want: `"2026-10-26T12:34:56Z"`, + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + encoded, err := json.Marshal(RFCFormTime(tc.value)) + if err != nil { + t.Fatalf("marshal RFC form time: %v", err) + } + if string(encoded) != tc.want { + t.Fatalf("RFC form time = %s, want %s", encoded, tc.want) + } + }) + } +} diff --git a/app/internal/common/validator.go b/app/internal/common/validation.go similarity index 62% rename from app/internal/common/validator.go rename to app/internal/common/validation.go index c9a7b0c..7610417 100644 --- a/app/internal/common/validator.go +++ b/app/internal/common/validation.go @@ -1,53 +1,14 @@ package common import ( - "bytes" - "encoding/json" - "io" "regexp" - "strconv" "strings" "unicode/utf8" - "github.com/go-playground/validator" - "github.com/gofiber/fiber/v3" "github.com/google/uuid" ) -var ( - validate = validator.New() - usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) -) - -func BindJSON(c fiber.Ctx, req any) error { - contentType := c.Get(fiber.HeaderContentType) - if !strings.HasPrefix(contentType, "application/json") { - return UnsupportedMedia("invalid JSON body") - } - - body := c.Body() - if len(body) == 0 { - return BadRequest("request body is empty") - } - - decoder := json.NewDecoder(bytes.NewReader(body)) - decoder.DisallowUnknownFields() - - if err := decoder.Decode(req); err != nil { - return BadRequest("invalid JSON body") - } - - var extra json.RawMessage - if err := decoder.Decode(&extra); err != io.EOF { - return BadRequest("request body has extra trailing bytes") - } - - if err := validate.Struct(req); err != nil { - return BadRequest("field validation failed") - } - - return nil -} +var usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) func blank(s string) bool { return strings.TrimSpace(s) == "" @@ -110,19 +71,6 @@ func ValidateMessageText(text string) string { return "" } -func validateLimitStr(s string) (int, bool) { - n, err := strconv.Atoi(s) - if err != nil { - return 0, false - } - - if n < 1 || n > 100 { - return 0, false - } - - return n, true -} - func ValidateMemberIDs(ids []uuid.UUID, callerID uuid.UUID) string { if len(ids) < 1 || len(ids) > 100 { return "member_ids must contain between 1 and 100 members" diff --git a/app/internal/database/database.go b/app/internal/database/database.go index 36d887e..be4383d 100644 --- a/app/internal/database/database.go +++ b/app/internal/database/database.go @@ -1,23 +1,14 @@ -// AGENT: A tiny migration runner instead of a framework: one advisory lock, -// one schema_migrations row per file, each file in its own transaction. +// Package database owns the PostgreSQL connection pool and schema migrations. package database import ( "context" - "embed" "fmt" - "io/fs" - "sort" "time" "github.com/jackc/pgx/v5/pgxpool" ) -//go:embed migrations/*.sql -var migrationFiles embed.FS - -const migrationLockID int64 = 728_2026 - func Connect(ctx context.Context, url string, maxConns int32, wait time.Duration) (*pgxpool.Pool, error) { cfg, err := pgxpool.ParseConfig(url) if err != nil { @@ -53,75 +44,3 @@ func Connect(ctx context.Context, url string, maxConns int32, wait time.Duration time.Sleep(500 * time.Millisecond) } } - -func Migrate(ctx context.Context, pool *pgxpool.Pool) error { - conn, err := pool.Acquire(ctx) - if err != nil { - return fmt.Errorf("acquire migration connection: %w", err) - } - defer conn.Release() - - if _, err = conn.Exec(ctx, "SELECT pg_advisory_lock($1)", migrationLockID); err != nil { - return fmt.Errorf("acquire migration lock: %w", err) - } - defer func() { - unlockCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) - defer cancel() - _, _ = conn.Exec(unlockCtx, "SELECT pg_advisory_unlock($1)", migrationLockID) - }() - - if _, err = conn.Exec(ctx, ` - CREATE TABLE IF NOT EXISTS schema_migrations ( - version text PRIMARY KEY, - applied_at timestamptz NOT NULL DEFAULT now() - )`); err != nil { - return fmt.Errorf("create schema_migrations: %w", err) - } - - entries, err := fs.ReadDir(migrationFiles, "migrations") - if err != nil { - return fmt.Errorf("read embedded migrations: %w", err) - } - sort.Slice(entries, func(i, j int) bool { return entries[i].Name() < entries[j].Name() }) - - for _, entry := range entries { - if entry.IsDir() { - continue - } - - var applied bool - if err = conn.QueryRow(ctx, - "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version = $1)", entry.Name(), - ).Scan(&applied); err != nil { - return fmt.Errorf("check migration %s: %w", entry.Name(), err) - } - if applied { - continue - } - - body, readErr := migrationFiles.ReadFile("migrations/" + entry.Name()) - if readErr != nil { - return fmt.Errorf("read migration %s: %w", entry.Name(), readErr) - } - - tx, beginErr := conn.Begin(ctx) - if beginErr != nil { - return fmt.Errorf("begin migration %s: %w", entry.Name(), beginErr) - } - if _, execErr := tx.Exec(ctx, string(body)); execErr != nil { - _ = tx.Rollback(ctx) - return fmt.Errorf("apply migration %s: %w", entry.Name(), execErr) - } - if _, insertErr := tx.Exec(ctx, - "INSERT INTO schema_migrations (version) VALUES ($1)", entry.Name(), - ); insertErr != nil { - _ = tx.Rollback(ctx) - return fmt.Errorf("record migration %s: %w", entry.Name(), insertErr) - } - if commitErr := tx.Commit(ctx); commitErr != nil { - return fmt.Errorf("commit migration %s: %w", entry.Name(), commitErr) - } - } - - return nil -} diff --git a/app/internal/database/migrations.go b/app/internal/database/migrations.go new file mode 100644 index 0000000..6c89955 --- /dev/null +++ b/app/internal/database/migrations.go @@ -0,0 +1,162 @@ +// AGENT: golang-migrate now runs the embedded SQL files instead of the previous +// hand-written runner. The legacy table upgrade below keeps existing lab 2 +// volumes usable, so switching engines does not require deleting data. +package database + +import ( + "context" + "embed" + "errors" + "fmt" + "time" + + "github.com/golang-migrate/migrate/v4" + pgxmigrate "github.com/golang-migrate/migrate/v4/database/pgx/v5" + "github.com/golang-migrate/migrate/v4/source/iofs" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "github.com/jackc/pgx/v5/stdlib" +) + +//go:embed migrations/*.sql +var migrationFiles embed.FS + +const ( + // The old in-house runner used this advisory lock. We keep the same key for + // the one-time table upgrade so an upgrade cannot race a still-running old + // instance that is applying the baseline migration. + legacyMigrationLockID int64 = 728_2026 + migrationsTable = "schema_migrations" +) + +// Migrate applies the embedded golang-migrate migrations. golang-migrate takes +// its own PostgreSQL advisory lock, records the current version and dirty flag +// in schema_migrations, and wraps each migration file in one transaction. +func Migrate(ctx context.Context, pool *pgxpool.Pool, databaseURL string) error { + if err := upgradeLegacyMigrationsTable(ctx, pool); err != nil { + return err + } + + source, err := iofs.New(migrationFiles, "migrations") + if err != nil { + return fmt.Errorf("load embedded migrations: %w", err) + } + + connConfig, err := pgx.ParseConfig(databaseURL) + if err != nil { + _ = source.Close() + return fmt.Errorf("parse DATABASE_URL for migrations: %w", err) + } + // golang-migrate acquires its lock with context.Background(). A PostgreSQL + // lock timeout keeps startup bounded if another instance never releases it. + if connConfig.RuntimeParams == nil { + connConfig.RuntimeParams = make(map[string]string) + } + connConfig.RuntimeParams["lock_timeout"] = "30000" + connConfig.ConnectTimeout = 3 * time.Second + + db := stdlib.OpenDB(*connConfig) + db.SetMaxOpenConns(1) + db.SetMaxIdleConns(1) + + driver, err := pgxmigrate.WithInstance(db, &pgxmigrate.Config{ + MigrationsTable: migrationsTable, + StatementTimeout: 30 * time.Second, + }) + if err != nil { + _ = source.Close() + _ = db.Close() + return fmt.Errorf("create migration driver: %w", err) + } + + migrator, err := migrate.NewWithInstance("iofs", source, "pgx5", driver) + if err != nil { + _ = source.Close() + _ = driver.Close() + return fmt.Errorf("create migrator: %w", err) + } + defer func() { + // Close closes both the embedded source and the database connection. + _, _ = migrator.Close() + }() + + if err := migrator.Up(); err != nil && !errors.Is(err, migrate.ErrNoChange) { + return fmt.Errorf("apply migrations: %w", err) + } + + return nil +} + +// upgradeLegacyMigrationsTable replaces the table written by the previous +// in-house runner (version text, applied_at) with the golang-migrate schema +// (version bigint, dirty boolean). The schema itself is left untouched and the +// highest applied version is carried over, so a preserved volume does not need +// to be recreated. The migration DDL is idempotent, but preserving the version +// keeps the migration history truthful. +// +// AGENT: This is a one-time compatibility bridge, not a permanent second +// migration format. It runs under the old advisory lock before golang-migrate +// creates its own lock and metadata. +func upgradeLegacyMigrationsTable(ctx context.Context, pool *pgxpool.Pool) error { + conn, err := pool.Acquire(ctx) + if err != nil { + return fmt.Errorf("acquire migration connection: %w", err) + } + defer conn.Release() + + if _, err := conn.Exec(ctx, "SELECT pg_advisory_lock($1)", legacyMigrationLockID); err != nil { + return fmt.Errorf("acquire migration lock: %w", err) + } + defer func() { + unlockCtx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + _, _ = conn.Exec(unlockCtx, "SELECT pg_advisory_unlock($1)", legacyMigrationLockID) + }() + + var legacy bool + if err := conn.QueryRow(ctx, ` + SELECT EXISTS ( + SELECT 1 + FROM information_schema.columns + WHERE table_schema = current_schema() + AND table_name = $1 + AND column_name = 'applied_at' + )`, migrationsTable).Scan(&legacy); err != nil { + return fmt.Errorf("inspect %s: %w", migrationsTable, err) + } + if !legacy { + return nil + } + + tx, err := conn.Begin(ctx) + if err != nil { + return fmt.Errorf("begin migration table upgrade: %w", err) + } + defer func() { _ = tx.Rollback(context.Background()) }() + + const upgrade = ` + DROP TABLE IF EXISTS schema_migrations_migrate_tmp; + + CREATE TABLE schema_migrations_migrate_tmp ( + version bigint NOT NULL PRIMARY KEY, + dirty boolean NOT NULL + ); + + INSERT INTO schema_migrations_migrate_tmp (version, dirty) + SELECT MAX(substring(version FROM '^[0-9]+')::bigint), false + FROM schema_migrations + WHERE version ~ '^[0-9]+' + HAVING COUNT(*) > 0; + + DROP TABLE schema_migrations; + ALTER TABLE schema_migrations_migrate_tmp RENAME TO schema_migrations;` + + if _, err := tx.Exec(ctx, upgrade); err != nil { + return fmt.Errorf("upgrade legacy %s: %w", migrationsTable, err) + } + if err := tx.Commit(ctx); err != nil { + return fmt.Errorf("commit migration table upgrade: %w", err) + } + + return nil +} diff --git a/app/internal/database/migrations/0001_init.down.sql b/app/internal/database/migrations/0001_init.down.sql new file mode 100644 index 0000000..1cd9784 --- /dev/null +++ b/app/internal/database/migrations/0001_init.down.sql @@ -0,0 +1,6 @@ +-- AGENT: Local rollback for the baseline schema. The application only runs Up +-- migrations; this file exists so golang-migrate can also step down in tests. +DROP TABLE IF EXISTS messages; +DROP TABLE IF EXISTS chat_members; +DROP TABLE IF EXISTS chats; +DROP TABLE IF EXISTS users; diff --git a/app/internal/database/migrations/0001_init.sql b/app/internal/database/migrations/0001_init.up.sql similarity index 100% rename from app/internal/database/migrations/0001_init.sql rename to app/internal/database/migrations/0001_init.up.sql diff --git a/app/internal/database/migrations_test.go b/app/internal/database/migrations_test.go new file mode 100644 index 0000000..45942fb --- /dev/null +++ b/app/internal/database/migrations_test.go @@ -0,0 +1,43 @@ +package database + +import ( + "errors" + "io/fs" + "testing" + + "github.com/golang-migrate/migrate/v4/source/iofs" +) + +func TestEmbeddedMigrationsParse(t *testing.T) { + entries, err := fs.ReadDir(migrationFiles, "migrations") + if err != nil { + t.Fatalf("read embedded migrations: %v", err) + } + + names := make(map[string]bool, len(entries)) + for _, entry := range entries { + names[entry.Name()] = true + } + for _, want := range []string{"0001_init.up.sql", "0001_init.down.sql"} { + if !names[want] { + t.Fatalf("migration %q is missing from the embedded filesystem", want) + } + } + + source, err := iofs.New(migrationFiles, "migrations") + if err != nil { + t.Fatalf("parse migrations with golang-migrate: %v", err) + } + defer func() { _ = source.Close() }() + + version, err := source.First() + if err != nil { + t.Fatalf("read first migration: %v", err) + } + if version != 1 { + t.Fatalf("first migration version = %d, want 1", version) + } + if _, err := source.Next(version); !errors.Is(err, fs.ErrNotExist) { + t.Fatalf("expected the baseline to be the last migration, got %v", err) + } +} diff --git a/app/internal/messages/handler.go b/app/internal/messages/handler.go index aa7fe96..189a22f 100644 --- a/app/internal/messages/handler.go +++ b/app/internal/messages/handler.go @@ -16,11 +16,11 @@ func NewHandler(st *store.Store) *Handler { } type CreateMessageRequest struct { - Text string `json:"text" validate:"required"` + Text string `json:"text"` } func (h *Handler) CreateMessage(c fiber.Ctx) error { - userID := c.Locals("userID").(uuid.UUID) + userID := common.MustUserID(c) chatID, err := uuid.Parse(c.Params("chat_id")) if err != nil { @@ -45,7 +45,7 @@ func (h *Handler) CreateMessage(c fiber.Ctx) error { } func (h *Handler) ListMessages(c fiber.Ctx) error { - userID := c.Locals("userID").(uuid.UUID) + userID := common.MustUserID(c) chatID, err := uuid.Parse(c.Params("chat_id")) if err != nil { diff --git a/app/internal/messages/router.go b/app/internal/messages/router.go index c6bbe58..f370f31 100644 --- a/app/internal/messages/router.go +++ b/app/internal/messages/router.go @@ -5,7 +5,7 @@ import ( "github.com/gofiber/fiber/v3" ) -func RegisterRoutes(router fiber.Router, st *store.Store) { +func RegisterProtectedRoutes(router fiber.Router, st *store.Store) { handler := NewHandler(st) router.Post("/chats/:chat_id/messages", handler.CreateMessage) router.Get("/chats/:chat_id/messages", handler.ListMessages) diff --git a/app/internal/model/model.go b/app/internal/model/model.go index 54c478e..d427628 100644 --- a/app/internal/model/model.go +++ b/app/internal/model/model.go @@ -8,40 +8,40 @@ import ( ) type User struct { - ID uuid.UUID `json:"id" validate:"required"` - Username string `json:"username" validate:"required"` - DisplayName string `json:"display_name" validate:"required"` + ID uuid.UUID `json:"id"` + Username string `json:"username"` + DisplayName string `json:"display_name"` PasswordHash string `json:"-"` - CreatedAt common.RFCFormTime `json:"created_at" validate:"required"` + CreatedAt common.RFCFormTime `json:"created_at"` } func (u User) GetID() uuid.UUID { return u.ID } func (u User) GetCreatedAt() time.Time { return time.Time(u.CreatedAt) } type Chat struct { - ID uuid.UUID `json:"id" validate:"required"` - Title string `json:"title" validate:"required"` - MemberIDs []uuid.UUID `json:"member_ids" validate:"required"` - CreatedAt common.RFCFormTime `json:"created_at" validate:"required"` + ID uuid.UUID `json:"id"` + Title string `json:"title"` + MemberIDs []uuid.UUID `json:"member_ids"` + CreatedAt common.RFCFormTime `json:"created_at"` } func (c Chat) GetID() uuid.UUID { return c.ID } func (c Chat) GetCreatedAt() time.Time { return time.Time(c.CreatedAt) } type Message struct { - ID uuid.UUID `json:"id" validate:"required"` - ChatID uuid.UUID `json:"chat_id" validate:"required"` - SenderID uuid.UUID `json:"sender_id" validate:"required"` - Text string `json:"text" validate:"required"` - CreatedAt common.RFCFormTime `json:"created_at" validate:"required"` + ID uuid.UUID `json:"id"` + ChatID uuid.UUID `json:"chat_id"` + SenderID uuid.UUID `json:"sender_id"` + Text string `json:"text"` + CreatedAt common.RFCFormTime `json:"created_at"` } func (m Message) GetID() uuid.UUID { return m.ID } func (m Message) GetCreatedAt() time.Time { return time.Time(m.CreatedAt) } type Session struct { - Token string `json:"token" validate:"required"` - TokenType string `json:"token_type" validate:"required"` - ExpiresAt common.RFCFormTime `json:"expires_at" validate:"required"` - User User `json:"user" validate:"required"` + Token string `json:"token"` + TokenType string `json:"token_type"` + ExpiresAt common.RFCFormTime `json:"expires_at"` + User User `json:"user"` } diff --git a/app/internal/store/chats.go b/app/internal/store/chats.go new file mode 100644 index 0000000..b2ff65d --- /dev/null +++ b/app/internal/store/chats.go @@ -0,0 +1,148 @@ +package store + +import ( + "context" + "errors" + "time" + + "gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common" + "gitflic.ru/project/bulla-max/mtusi2026lab2/internal/model" + "github.com/google/uuid" + "github.com/jackc/pgx/v5" +) + +// CreateChat inserts the chat and every membership row in one transaction. +// Any unknown member aborts the whole transaction, so a partially created chat +// can never be observed. +func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []uuid.UUID) (model.Chat, error) { + ctx, cancel := s.withTimeout(ctx) + defer cancel() + + tx, err := s.pool.Begin(ctx) + if err != nil { + return model.Chat{}, dbError(err) + } + defer func() { _ = tx.Rollback(context.Background()) }() + + for _, memberID := range memberIDs { + var exists int + err = tx.QueryRow(ctx, `SELECT 1 FROM users WHERE id = $1`, memberID).Scan(&exists) + if errors.Is(err, pgx.ErrNoRows) { + return model.Chat{}, common.BadRequest("member_id refers to non-existent user") + } + if err != nil { + return model.Chat{}, dbError(err) + } + } + + chat := model.Chat{ + ID: uuid.New(), + Title: title, + MemberIDs: append([]uuid.UUID(nil), memberIDs...), + CreatedAt: common.NowUTC(), + } + + if _, err = tx.Exec(ctx, + `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`, + chat.ID, chat.Title, time.Time(chat.CreatedAt)); err != nil { + return model.Chat{}, dbError(err) + } + + for _, memberID := range memberIDs { + if _, err = tx.Exec(ctx, + `INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)`, + chat.ID, memberID); err != nil { + return model.Chat{}, dbError(err) + } + } + + if err = tx.Commit(ctx); err != nil { + return model.Chat{}, dbError(err) + } + + return chat, nil +} + +func (s *Store) GetChatForUser(ctx context.Context, userID, chatID uuid.UUID) (model.Chat, error) { + ctx, cancel := s.withTimeout(ctx) + defer cancel() + + chat, err := scanChat(s.pool.QueryRow(ctx, ` + SELECT c.id, c.title, c.created_at, + ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY user_id) + FROM chats c + JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2 + WHERE c.id = $1`, chatID, userID)) + if errors.Is(err, pgx.ErrNoRows) { + return model.Chat{}, common.NotFound("chat not found") + } + if err != nil { + return model.Chat{}, dbError(err) + } + return chat, nil +} + +func (s *Store) ListChats(ctx context.Context, userID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.Page[model.Chat], error) { + ctx, cancel := s.withTimeout(ctx) + defer cancel() + + cursorTime, cursorID := cursorValues(cursor) + rows, err := s.pool.Query(ctx, ` + SELECT c.id, c.title, c.created_at, + ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY user_id) + FROM chats c + JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $1 + WHERE (c.created_at, c.id) > ($2, $3) + ORDER BY c.created_at, c.id + LIMIT $4`, userID, cursorTime, cursorID, limit+1) + if err != nil { + return nil, dbError(err) + } + defer rows.Close() + + chats := make([]model.Chat, 0, limit) + for rows.Next() { + chat, scanErr := scanChat(rows) + if scanErr != nil { + return nil, dbError(scanErr) + } + chats = append(chats, chat) + } + if err = rows.Err(); err != nil { + return nil, dbError(err) + } + + hasMore := len(chats) > limit + if hasMore { + chats = chats[:limit] + } + + return &common.Page[model.Chat]{Items: chats, NextCursor: common.NextCursor(chats, hasMore, userID)}, nil +} + +func (s *Store) IsMember(ctx context.Context, userID, chatID uuid.UUID) (bool, error) { + ctx, cancel := s.withTimeout(ctx) + defer cancel() + + var exists int + err := s.pool.QueryRow(ctx, + `SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`, + chatID, userID).Scan(&exists) + if errors.Is(err, pgx.ErrNoRows) { + return false, nil + } + if err != nil { + return false, dbError(err) + } + return true, nil +} + +func scanChat(row rowScanner) (model.Chat, error) { + var chat model.Chat + var createdAt time.Time + if err := row.Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs); err != nil { + return model.Chat{}, err + } + chat.CreatedAt = common.RFCFormTime(createdAt.UTC()) + return chat, nil +} diff --git a/app/internal/store/errors.go b/app/internal/store/errors.go new file mode 100644 index 0000000..0f60f26 --- /dev/null +++ b/app/internal/store/errors.go @@ -0,0 +1,44 @@ +package store + +import ( + "context" + "errors" + "net" + + "gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgconn" +) + +func isUniqueViolation(err error) bool { + var pgErr *pgconn.PgError + return errors.As(err, &pgErr) && pgErr.Code == "23505" +} + +// dbError separates a drained dependency (503) from a real bug (500). SQL +// details never reach the client; callers only emit the AppError message. +func dbError(err error) error { + if err == nil { + return nil + } + + var pgErr *pgconn.PgError + if errors.As(err, &pgErr) { + switch pgErr.Code { + case "23505": + return common.Conflict("resource already exists") + case "23503", "23514", "22P02": + return common.BadRequest("request conflicts with stored data") + } + } + + var netErr net.Error + if errors.As(err, &netErr) || errors.Is(err, context.DeadlineExceeded) || + errors.Is(err, context.Canceled) || + pgconn.SafeToRetry(err) || + errors.Is(err, pgx.ErrTxClosed) { + return common.Unavailable("database unavailable") + } + + return common.Internal() +} diff --git a/app/internal/store/messages.go b/app/internal/store/messages.go new file mode 100644 index 0000000..5454d59 --- /dev/null +++ b/app/internal/store/messages.go @@ -0,0 +1,104 @@ +package store + +import ( + "context" + "time" + + "gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common" + "gitflic.ru/project/bulla-max/mtusi2026lab2/internal/model" + "github.com/google/uuid" +) + +// CreateMessage uses INSERT ... SELECT so the membership check and the insert +// are a single atomic statement: no window where the user is removed between +// check and write. Zero affected rows means the chat is missing or foreign. +func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, text string) (model.Message, error) { + ctx, cancel := s.withTimeout(ctx) + defer cancel() + + message := model.Message{ + ID: uuid.New(), + ChatID: chatID, + SenderID: senderID, + Text: text, + CreatedAt: common.NowUTC(), + } + + tag, err := s.pool.Exec(ctx, ` + INSERT INTO messages (id, chat_id, sender_id, text, created_at) + SELECT $1, $2, $3, $4, $5 + WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $3)`, + message.ID, message.ChatID, message.SenderID, message.Text, time.Time(message.CreatedAt)) + if err != nil { + return model.Message{}, dbError(err) + } + if tag.RowsAffected() == 0 { + return model.Message{}, common.NotFound("chat not found") + } + + return message, nil +} + +func (s *Store) ListMessages(ctx context.Context, userID, chatID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.Page[model.Message], error) { + isMember, err := s.IsMember(ctx, userID, chatID) + if err != nil { + return nil, err + } + if !isMember { + return nil, common.NotFound("chat not found") + } + // AGENT: Cursor context is checked only after membership, so a foreign + // caller gets 404 and cannot probe cursor validity against someone else's chat. + if cursor != nil && cursor.ContextID != chatID { + return nil, common.BadRequest("bad cursor value") + } + + ctx, cancel := s.withTimeout(ctx) + defer cancel() + + // AGENT: limit+1 is fetched so next_cursor is known to be non-null without a + // second COUNT query; the extra row is never returned to the client. + cursorTime, cursorID := cursorValues(cursor) + 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, cursorTime, cursorID, limit+1) + if err != nil { + return nil, dbError(err) + } + defer rows.Close() + + messages := make([]model.Message, 0, limit) + for rows.Next() { + message, scanErr := scanMessage(rows) + if scanErr != nil { + return nil, dbError(scanErr) + } + messages = append(messages, message) + } + if err = rows.Err(); err != nil { + return nil, dbError(err) + } + + hasMore := len(messages) > limit + if hasMore { + messages = messages[:limit] + } + + return &common.Page[model.Message]{ + Items: messages, + NextCursor: common.NextCursor(messages, hasMore, chatID), + }, nil +} + +func scanMessage(row rowScanner) (model.Message, error) { + var message model.Message + var createdAt time.Time + if err := row.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt); err != nil { + return model.Message{}, err + } + message.CreatedAt = common.RFCFormTime(createdAt.UTC()) + return message, nil +} diff --git a/app/internal/store/pagination.go b/app/internal/store/pagination.go new file mode 100644 index 0000000..dd4a342 --- /dev/null +++ b/app/internal/store/pagination.go @@ -0,0 +1,17 @@ +package store + +import ( + "time" + + "gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common" + "github.com/google/uuid" +) + +// cursorValues converts an optional page cursor to the two keyset columns used +// by every paginated query. A nil cursor means "start from the beginning". +func cursorValues(cursor *common.CursorKeyCtx) (time.Time, uuid.UUID) { + if cursor == nil { + return time.Time{}, uuid.Nil + } + return cursor.Time, cursor.ID +} diff --git a/app/internal/store/store.go b/app/internal/store/store.go index f4ed4d1..102b2ad 100644 --- a/app/internal/store/store.go +++ b/app/internal/store/store.go @@ -1,19 +1,17 @@ -// AGENT: Concrete PostgreSQL store: plain parameterized SQL, one bounded pool, -// explicit transaction boundaries. It returns contract AppErrors so HTTP status -// mapping stays in one place. +// Package store contains the PostgreSQL persistence layer. It uses plain +// parameterized SQL, one bounded pool and explicit transaction boundaries. +// Contract errors are returned as common.AppError so HTTP status mapping stays +// in one place. +// +// AGENT: Persistence was split from one large file by aggregate (users, chats, +// messages). Queries, transaction boundaries and error mapping are unchanged; +// only file organization and scan helpers changed. package store import ( "context" - "errors" - "net" "time" - "gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common" - "gitflic.ru/project/bulla-max/mtusi2026lab2/internal/model" - "github.com/google/uuid" - "github.com/jackc/pgx/v5" - "github.com/jackc/pgx/v5/pgconn" "github.com/jackc/pgx/v5/pgxpool" ) @@ -36,324 +34,7 @@ func (s *Store) Ping(ctx context.Context) error { return s.pool.Ping(pingCtx) } -func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) { - ctx, cancel := s.withTimeout(ctx) - defer cancel() - - user := model.User{ - ID: uuid.New(), - Username: username, - DisplayName: displayName, - PasswordHash: passwordHash, - CreatedAt: common.NowUTC(), - } - - _, err := s.pool.Exec(ctx, ` - INSERT INTO users (id, username, display_name, password_hash, created_at) - VALUES ($1, $2, $3, $4, $5)`, - user.ID, user.Username, user.DisplayName, user.PasswordHash, time.Time(user.CreatedAt)) - if err != nil { - // AGENT: The unique index is the real guard. Two concurrent registrations - // with the same username both reach INSERT; exactly one commits, the other - // gets SQLSTATE 23505 and is mapped to 409 instead of a 500. - if isUniqueViolation(err) { - return model.User{}, common.Conflict("username already taken") - } - return model.User{}, dbError(err) - } - - return user, nil -} - -func (s *Store) GetUserByID(ctx context.Context, id uuid.UUID) (model.User, error) { - ctx, cancel := s.withTimeout(ctx) - defer cancel() - - return s.scanUser(s.pool.QueryRow(ctx, ` - SELECT id, username, display_name, password_hash, created_at - FROM users WHERE id = $1`, id)) -} - -func (s *Store) GetUserByUsername(ctx context.Context, username string) (model.User, error) { - ctx, cancel := s.withTimeout(ctx) - defer cancel() - - return s.scanUser(s.pool.QueryRow(ctx, ` - SELECT id, username, display_name, password_hash, created_at - FROM users WHERE username = $1`, username)) -} - +// rowScanner is the common subset of pgx.Row and pgx.Rows used by scan helpers. type rowScanner interface { Scan(dest ...any) error } - -func (s *Store) scanUser(row rowScanner) (model.User, error) { - var user model.User - var createdAt time.Time - if err := row.Scan(&user.ID, &user.Username, &user.DisplayName, &user.PasswordHash, &createdAt); err != nil { - if errors.Is(err, pgx.ErrNoRows) { - return model.User{}, common.NotFound("user not found") - } - return model.User{}, dbError(err) - } - user.CreatedAt = common.RFCFormTime(createdAt.UTC()) - return user, nil -} - -// CreateChat inserts the chat and every membership row in one transaction. -// Any unknown member aborts the whole transaction, so a partially created chat -// can never be observed. -func (s *Store) CreateChat(ctx context.Context, title string, memberIDs []uuid.UUID) (model.Chat, error) { - ctx, cancel := s.withTimeout(ctx) - defer cancel() - - tx, err := s.pool.Begin(ctx) - if err != nil { - return model.Chat{}, dbError(err) - } - defer func() { _ = tx.Rollback(context.Background()) }() - - for _, memberID := range memberIDs { - var exists int - err = tx.QueryRow(ctx, `SELECT 1 FROM users WHERE id = $1`, memberID).Scan(&exists) - if errors.Is(err, pgx.ErrNoRows) { - return model.Chat{}, common.BadRequest("member_id refers to non-existent user") - } - if err != nil { - return model.Chat{}, dbError(err) - } - } - - chat := model.Chat{ - ID: uuid.New(), - Title: title, - MemberIDs: append([]uuid.UUID(nil), memberIDs...), - CreatedAt: common.NowUTC(), - } - - if _, err = tx.Exec(ctx, - `INSERT INTO chats (id, title, created_at) VALUES ($1, $2, $3)`, - chat.ID, chat.Title, time.Time(chat.CreatedAt)); err != nil { - return model.Chat{}, dbError(err) - } - - for _, memberID := range memberIDs { - if _, err = tx.Exec(ctx, - `INSERT INTO chat_members (chat_id, user_id) VALUES ($1, $2)`, - chat.ID, memberID); err != nil { - return model.Chat{}, dbError(err) - } - } - - if err = tx.Commit(ctx); err != nil { - return model.Chat{}, dbError(err) - } - - return chat, nil -} - -func (s *Store) GetChatForUser(ctx context.Context, userID, chatID uuid.UUID) (model.Chat, error) { - ctx, cancel := s.withTimeout(ctx) - defer cancel() - - var chat model.Chat - var createdAt time.Time - err := s.pool.QueryRow(ctx, ` - SELECT c.id, c.title, c.created_at, - ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY user_id) - FROM chats c - JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $2 - WHERE c.id = $1`, chatID, userID). - Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs) - if errors.Is(err, pgx.ErrNoRows) { - return model.Chat{}, common.NotFound("chat not found") - } - if err != nil { - return model.Chat{}, dbError(err) - } - chat.CreatedAt = common.RFCFormTime(createdAt.UTC()) - return chat, nil -} - -func (s *Store) ListChats(ctx context.Context, userID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.Page[model.Chat], error) { - ctx, cancel := s.withTimeout(ctx) - defer cancel() - - cursorTime, cursorID := cursorValues(cursor) - rows, err := s.pool.Query(ctx, ` - SELECT c.id, c.title, c.created_at, - ARRAY(SELECT user_id FROM chat_members WHERE chat_id = c.id ORDER BY user_id) - FROM chats c - JOIN chat_members me ON me.chat_id = c.id AND me.user_id = $1 - WHERE (c.created_at, c.id) > ($2, $3) - ORDER BY c.created_at, c.id - LIMIT $4`, userID, cursorTime, cursorID, limit+1) - if err != nil { - return nil, dbError(err) - } - defer rows.Close() - - chats := make([]model.Chat, 0, limit) - for rows.Next() { - var chat model.Chat - var createdAt time.Time - if err = rows.Scan(&chat.ID, &chat.Title, &createdAt, &chat.MemberIDs); err != nil { - return nil, dbError(err) - } - chat.CreatedAt = common.RFCFormTime(createdAt.UTC()) - chats = append(chats, chat) - } - if err = rows.Err(); err != nil { - return nil, dbError(err) - } - - hasMore := len(chats) > limit - if hasMore { - chats = chats[:limit] - } - - return &common.Page[model.Chat]{Items: chats, NextCursor: common.NextCursor(chats, hasMore, userID)}, nil -} - -func (s *Store) IsMember(ctx context.Context, userID, chatID uuid.UUID) (bool, error) { - ctx, cancel := s.withTimeout(ctx) - defer cancel() - - var exists int - err := s.pool.QueryRow(ctx, - `SELECT 1 FROM chat_members WHERE chat_id = $1 AND user_id = $2`, - chatID, userID).Scan(&exists) - if errors.Is(err, pgx.ErrNoRows) { - return false, nil - } - if err != nil { - return false, dbError(err) - } - return true, nil -} - -// CreateMessage uses INSERT ... SELECT so the membership check and the insert -// are a single atomic statement: no window where the user is removed between -// check and write. Zero affected rows means the chat is missing or foreign. -func (s *Store) CreateMessage(ctx context.Context, chatID, senderID uuid.UUID, text string) (model.Message, error) { - ctx, cancel := s.withTimeout(ctx) - defer cancel() - - message := model.Message{ - ID: uuid.New(), - ChatID: chatID, - SenderID: senderID, - Text: text, - CreatedAt: common.NowUTC(), - } - - tag, err := s.pool.Exec(ctx, ` - INSERT INTO messages (id, chat_id, sender_id, text, created_at) - SELECT $1, $2, $3, $4, $5 - WHERE EXISTS (SELECT 1 FROM chat_members WHERE chat_id = $2 AND user_id = $3)`, - message.ID, message.ChatID, message.SenderID, message.Text, time.Time(message.CreatedAt)) - if err != nil { - return model.Message{}, dbError(err) - } - if tag.RowsAffected() == 0 { - return model.Message{}, common.NotFound("chat not found") - } - - return message, nil -} - -func (s *Store) ListMessages(ctx context.Context, userID, chatID uuid.UUID, limit int, cursor *common.CursorKeyCtx) (*common.Page[model.Message], error) { - isMember, err := s.IsMember(ctx, userID, chatID) - if err != nil { - return nil, err - } - if !isMember { - return nil, common.NotFound("chat not found") - } - // AGENT: Cursor context is checked only after membership, so a foreign - // caller gets 404 and cannot probe cursor validity against someone else's chat. - if cursor != nil && cursor.ContextID != chatID { - return nil, common.BadRequest("bad cursor value") - } - - ctx, cancel := s.withTimeout(ctx) - defer cancel() - - // AGENT: limit+1 is fetched so next_cursor is known to be non-null without a - // second COUNT query; the extra row is never returned to the client. - cursorTime, cursorID := cursorValues(cursor) - 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, cursorTime, cursorID, limit+1) - if err != nil { - return nil, dbError(err) - } - defer rows.Close() - - messages := make([]model.Message, 0, limit) - for rows.Next() { - var message model.Message - var createdAt time.Time - if err = rows.Scan(&message.ID, &message.ChatID, &message.SenderID, &message.Text, &createdAt); err != nil { - return nil, dbError(err) - } - message.CreatedAt = common.RFCFormTime(createdAt.UTC()) - messages = append(messages, message) - } - if err = rows.Err(); err != nil { - return nil, dbError(err) - } - - hasMore := len(messages) > limit - if hasMore { - messages = messages[:limit] - } - - return &common.Page[model.Message]{ - Items: messages, - NextCursor: common.NextCursor(messages, hasMore, chatID), - }, nil -} - -func cursorValues(cursor *common.CursorKeyCtx) (time.Time, uuid.UUID) { - if cursor == nil { - return time.Time{}, uuid.Nil - } - return cursor.Time, cursor.ID -} - -func isUniqueViolation(err error) bool { - var pgErr *pgconn.PgError - return errors.As(err, &pgErr) && pgErr.Code == "23505" -} - -// dbError separates a drained dependency (503) from a real bug (500). SQL -// details never reach the client; callers only emit the AppError message. -func dbError(err error) error { - if err == nil { - return nil - } - - var pgErr *pgconn.PgError - if errors.As(err, &pgErr) { - switch pgErr.Code { - case "23505": - return common.Conflict("resource already exists") - case "23503", "23514", "22P02": - return common.BadRequest("request conflicts with stored data") - } - } - - var netErr net.Error - if errors.As(err, &netErr) || errors.Is(err, context.DeadlineExceeded) || - errors.Is(err, context.Canceled) || - pgconn.SafeToRetry(err) || - errors.Is(err, pgx.ErrTxClosed) { - return common.Unavailable("database unavailable") - } - - return common.Internal() -} diff --git a/app/internal/store/users.go b/app/internal/store/users.go new file mode 100644 index 0000000..e0e5013 --- /dev/null +++ b/app/internal/store/users.go @@ -0,0 +1,72 @@ +package store + +import ( + "context" + "errors" + "time" + + "gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common" + "gitflic.ru/project/bulla-max/mtusi2026lab2/internal/model" + "github.com/google/uuid" + "github.com/jackc/pgx/v5" +) + +func (s *Store) CreateUser(ctx context.Context, username, displayName, passwordHash string) (model.User, error) { + ctx, cancel := s.withTimeout(ctx) + defer cancel() + + user := model.User{ + ID: uuid.New(), + Username: username, + DisplayName: displayName, + PasswordHash: passwordHash, + CreatedAt: common.NowUTC(), + } + + _, err := s.pool.Exec(ctx, ` + INSERT INTO users (id, username, display_name, password_hash, created_at) + VALUES ($1, $2, $3, $4, $5)`, + user.ID, user.Username, user.DisplayName, user.PasswordHash, time.Time(user.CreatedAt)) + if err != nil { + // AGENT: The unique index is the real guard. Two concurrent registrations + // with the same username both reach INSERT; exactly one commits, the other + // gets SQLSTATE 23505 and is mapped to 409 instead of a 500. + if isUniqueViolation(err) { + return model.User{}, common.Conflict("username already taken") + } + return model.User{}, dbError(err) + } + + return user, nil +} + +func (s *Store) GetUserByID(ctx context.Context, id uuid.UUID) (model.User, error) { + ctx, cancel := s.withTimeout(ctx) + defer cancel() + + return s.scanUser(s.pool.QueryRow(ctx, ` + SELECT id, username, display_name, password_hash, created_at + FROM users WHERE id = $1`, id)) +} + +func (s *Store) GetUserByUsername(ctx context.Context, username string) (model.User, error) { + ctx, cancel := s.withTimeout(ctx) + defer cancel() + + return s.scanUser(s.pool.QueryRow(ctx, ` + SELECT id, username, display_name, password_hash, created_at + FROM users WHERE username = $1`, username)) +} + +func (s *Store) scanUser(row rowScanner) (model.User, error) { + var user model.User + var createdAt time.Time + if err := row.Scan(&user.ID, &user.Username, &user.DisplayName, &user.PasswordHash, &createdAt); err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return model.User{}, common.NotFound("user not found") + } + return model.User{}, dbError(err) + } + user.CreatedAt = common.RFCFormTime(createdAt.UTC()) + return user, nil +} diff --git a/app/internal/users/handler.go b/app/internal/users/handler.go index 9b144af..ff88cbb 100644 --- a/app/internal/users/handler.go +++ b/app/internal/users/handler.go @@ -5,7 +5,6 @@ import ( "gitflic.ru/project/bulla-max/mtusi2026lab2/internal/common" "gitflic.ru/project/bulla-max/mtusi2026lab2/internal/store" "github.com/gofiber/fiber/v3" - "github.com/google/uuid" ) type Handler struct { @@ -17,9 +16,9 @@ func NewHandler(st *store.Store) *Handler { } type CreateUserRequest struct { - Username string `json:"username" validate:"required"` - DisplayName string `json:"display_name" validate:"required"` - Password string `json:"password" validate:"required"` + Username string `json:"username"` + DisplayName string `json:"display_name"` + Password string `json:"password"` } func (h *Handler) CreateUser(c fiber.Ctx) error { @@ -37,8 +36,7 @@ func (h *Handler) CreateUser(c fiber.Ctx) error { hash, err := auth.HashPassword(req.Password) if err != nil { - return common.SendError(c, fiber.StatusInternalServerError, - common.ErrorCodeInternal, "Internal server error") + return common.SendAppError(c, common.Internal()) } user, err := h.store.CreateUser(c.Context(), req.Username, req.DisplayName, hash) @@ -50,7 +48,7 @@ func (h *Handler) CreateUser(c fiber.Ctx) error { } func (h *Handler) GetCurrentUser(c fiber.Ctx) error { - userID, ok := c.Locals("userID").(uuid.UUID) + userID, ok := common.UserID(c) if !ok { return common.SendChallenge(c, `Bearer realm="messenger"`, "authentication required") } diff --git a/app/internal/users/router.go b/app/internal/users/router.go index 31f6208..cf0c6f5 100644 --- a/app/internal/users/router.go +++ b/app/internal/users/router.go @@ -10,7 +10,7 @@ func RegisterPublicRoutes(router fiber.Router, st *store.Store) { router.Post("/users", handler.CreateUser) } -func RegisterRoutes(router fiber.Router, st *store.Store) { +func RegisterProtectedRoutes(router fiber.Router, st *store.Store) { handler := NewHandler(st) router.Get("/users/me", handler.GetCurrentUser) }