diff --git a/.github/workflows/statictest.yml b/.github/workflows/statictest.yml index d28e470..d5df73a 100644 --- a/.github/workflows/statictest.yml +++ b/.github/workflows/statictest.yml @@ -10,7 +10,7 @@ on: jobs: statictest: runs-on: ubuntu-latest - container: golang:1.23 + container: golang:1.22 steps: - name: Checkout code uses: actions/checkout@v2 diff --git a/cmd/gophermart/main.go b/cmd/gophermart/main.go index 38dd16d..d218331 100644 --- a/cmd/gophermart/main.go +++ b/cmd/gophermart/main.go @@ -1,3 +1,75 @@ package main -func main() {} +import ( + "context" + "errors" + "github.com/spqrcor/gofermart/internal/authenticate" + "github.com/spqrcor/gofermart/internal/client" + "github.com/spqrcor/gofermart/internal/config" + "github.com/spqrcor/gofermart/internal/db" + "github.com/spqrcor/gofermart/internal/logger" + "github.com/spqrcor/gofermart/internal/server" + "github.com/spqrcor/gofermart/internal/services" + "github.com/spqrcor/gofermart/internal/workers" + "log" + "net/http" +) + +func main() { + mainCtx := context.Background() + conf := config.NewConfig() + + loggerRes, err := logger.NewLogger(conf.LogLevel) + if err != nil { + log.Fatal(err) + } + dbRes, err := db.NewDB(loggerRes, conf.DatabaseURI) + if err != nil { + loggerRes.Fatal(err.Error()) + } + if err := db.Migrate(dbRes); err != nil { + loggerRes.Fatal(err.Error()) + } + + orderQueue := make(chan string) + defer close(orderQueue) + + authService := authenticate.NewAuthenticateService( + authenticate.WithLogger(loggerRes), + authenticate.WithSecretKey(conf.SecretKey), + authenticate.WithTokenExp(conf.TokenExp), + ) + userService := services.NewUserService(dbRes, conf.QueryTimeOut) + orderService := services.NewOrderService(orderQueue, dbRes, loggerRes, conf.QueryTimeOut) + withdrawalService := services.NewWithdrawalService(dbRes, loggerRes, conf.QueryTimeOut) + orderClient := client.NewOrderClient( + client.WithLogger(loggerRes), + client.WithAccrualSystemAddress(conf.AccrualSystemAddress), + ) + + orderWorker := workers.NewOrderWorker( + workers.WithCtx(mainCtx), + workers.WithOrderService(orderService), + workers.WithOrderQueue(orderQueue), + workers.WithLogger(loggerRes), + workers.WithConfig(conf), + workers.WithOrderClient(orderClient), + ) + orderWorker.Run() + + appServer := server.NewServer( + server.WithUserService(userService), + server.WithOrderService(orderService), + server.WithWithdrawalService(withdrawalService), + server.WithLogger(loggerRes), + server.WithRunAddress(conf.RunAddr), + server.WithAuthService(authService), + ) + err = appServer.Start() + if errors.Is(err, http.ErrServerClosed) { + loggerRes.Error("Server stop") + } + if err != nil { + loggerRes.Error(err.Error()) + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..70da1f9 --- /dev/null +++ b/go.mod @@ -0,0 +1,101 @@ +module github.com/spqrcor/gofermart + +go 1.22 + +require ( + filippo.io/edwards25519 v1.1.0 // indirect + github.com/ClickHouse/ch-go v0.62.0 // indirect + github.com/ClickHouse/clickhouse-go/v2 v2.28.1 // indirect + github.com/TylerBrock/colorjson v0.0.0-20200706003622-8a50f05110d2 // indirect + github.com/ajg/form v1.5.1 // indirect + github.com/andybalholm/brotli v1.1.0 // indirect + github.com/antlr4-go/antlr/v4 v4.13.1 // indirect + github.com/brianvoe/gofakeit/v7 v7.0.4 // indirect + github.com/coder/websocket v1.8.12 // indirect + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/dustin/go-humanize v1.0.1 // indirect + github.com/elastic/go-sysinfo v1.14.1 // indirect + github.com/elastic/go-windows v1.0.2 // indirect + github.com/fatih/color v1.15.0 // indirect + github.com/fatih/structs v1.1.0 // indirect + github.com/gavv/httpexpect/v2 v2.16.0 // indirect + github.com/go-chi/chi/v5 v5.1.0 // indirect + github.com/go-faster/city v1.0.1 // indirect + github.com/go-faster/errors v0.7.1 // indirect + github.com/go-sql-driver/mysql v1.8.1 // indirect + github.com/gobwas/glob v0.2.3 // indirect + github.com/golang-jwt/jwt/v4 v4.5.0 // indirect + github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 // indirect + github.com/golang-sql/sqlexp v0.1.0 // indirect + github.com/golang/mock v1.6.0 // indirect + github.com/golang/protobuf v1.5.4 // indirect + github.com/google/go-querystring v1.1.0 // indirect + github.com/google/uuid v1.6.0 // indirect + github.com/gorilla/websocket v1.4.2 // indirect + github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect + github.com/imkira/go-interpol v1.1.0 // indirect + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect + github.com/jackc/pgx/v5 v5.6.0 // indirect + github.com/jackc/puddle/v2 v2.2.1 // indirect + github.com/joeshaw/multierror v0.0.0-20140124173710-69b34d4ec901 // indirect + github.com/jonboulle/clockwork v0.4.0 // indirect + github.com/klauspost/compress v1.17.9 // indirect + github.com/libsql/sqlite-antlr4-parser v0.0.0-20240721121621-c0bdc870f11c // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/mfridman/interpolate v0.0.2 // indirect + github.com/microsoft/go-mssqldb v1.7.2 // indirect + github.com/mitchellh/go-wordwrap v1.0.1 // indirect + github.com/ncruces/go-strftime v0.1.9 // indirect + github.com/paulmach/orb v0.11.1 // indirect + github.com/pierrec/lz4/v4 v4.1.21 // indirect + github.com/pkg/errors v0.9.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect + github.com/pressly/goose/v3 v3.21.1 // indirect + github.com/prometheus/procfs v0.15.1 // indirect + github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect + github.com/sanity-io/litter v1.5.5 // indirect + github.com/segmentio/asm v1.2.0 // indirect + github.com/sergi/go-diff v1.0.0 // indirect + github.com/sethvargo/go-retry v0.3.0 // indirect + github.com/shopspring/decimal v1.4.0 // indirect + github.com/stretchr/testify v1.9.0 // indirect + github.com/tursodatabase/libsql-client-go v0.0.0-20240812094001-348a4e45b535 // indirect + github.com/valyala/bytebufferpool v1.0.0 // indirect + github.com/valyala/fasthttp v1.34.0 // indirect + github.com/vertica/vertica-sql-go v1.3.3 // indirect + github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect + github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect + github.com/xeipuuv/gojsonschema v1.2.0 // indirect + github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0 // indirect + github.com/ydb-platform/ydb-go-genproto v0.0.0-20240821162910-6cb364b2ccc8 // indirect + github.com/ydb-platform/ydb-go-sdk/v3 v3.77.1 // indirect + github.com/yudai/gojsondiff v1.0.0 // indirect + github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 // indirect + github.com/ziutek/mymysql v1.5.4 // indirect + go.opentelemetry.io/otel v1.29.0 // indirect + go.opentelemetry.io/otel/trace v1.29.0 // indirect + go.uber.org/multierr v1.11.0 // indirect + go.uber.org/zap v1.27.0 // indirect + golang.org/x/crypto v0.26.0 // indirect + golang.org/x/exp v0.0.0-20240823005443-9b4947da3948 // indirect + golang.org/x/net v0.28.0 // indirect + golang.org/x/sync v0.8.0 // indirect + golang.org/x/sys v0.24.0 // indirect + golang.org/x/text v0.17.0 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20240827150818-7e3bb234dfed // indirect + google.golang.org/grpc v1.66.0 // indirect + google.golang.org/protobuf v1.34.2 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect + howett.net/plist v1.0.1 // indirect + modernc.org/gc/v3 v3.0.0-20240801135723-a856999a2e4a // indirect + modernc.org/libc v1.60.0 // indirect + modernc.org/mathutil v1.6.0 // indirect + modernc.org/memory v1.8.0 // indirect + modernc.org/sqlite v1.32.0 // indirect + modernc.org/strutil v1.2.0 // indirect + modernc.org/token v1.1.0 // indirect + moul.io/http2curl/v2 v2.3.0 // indirect + nhooyr.io/websocket v1.8.17 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..dd272d0 --- /dev/null +++ b/go.sum @@ -0,0 +1,388 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +filippo.io/edwards25519 v1.1.0 h1:FNf4tywRC1HmFuKW5xopWpigGjJKiJSV0Cqo0cJWDaA= +filippo.io/edwards25519 v1.1.0/go.mod h1:BxyFTGdWcka3PhytdK4V28tE5sGfRvvvRV7EaN4VDT4= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/ClickHouse/ch-go v0.62.0 h1:eXH0hytXeCEEZHgMvOX9IiW7wqBb4w1MJMp9rArbkrc= +github.com/ClickHouse/ch-go v0.62.0/go.mod h1:uzso52/PD9+gZj7tL6XAo8/EYDrx7CIwNF4c6PnO6S0= +github.com/ClickHouse/clickhouse-go v1.5.4 h1:cKjXeYLNWVJIx2J1K6H2CqyRmfwVJVY1OV1coaaFcI0= +github.com/ClickHouse/clickhouse-go v1.5.4/go.mod h1:EaI/sW7Azgz9UATzd5ZdZHRUhHgv5+JMS9NSr2smCJI= +github.com/ClickHouse/clickhouse-go/v2 v2.28.1 h1:tpdOxWZlZ4IYiFWpIteU57JVdWVbSI5OwflofAdhFno= +github.com/ClickHouse/clickhouse-go/v2 v2.28.1/go.mod h1:0U915l9qynE508ehh3ea9+UMGc7gZlAV+9W6pUZd7kk= +github.com/TylerBrock/colorjson v0.0.0-20200706003622-8a50f05110d2 h1:ZBbLwSJqkHBuFDA6DUhhse0IGJ7T5bemHyNILUjvOq4= +github.com/TylerBrock/colorjson v0.0.0-20200706003622-8a50f05110d2/go.mod h1:VSw57q4QFiWDbRnjdX8Cb3Ow0SFncRw+bA/ofY6Q83w= +github.com/ajg/form v1.5.1 h1:t9c7v8JUKu/XxOGBU0yjNpaMloxGEJhUkqFRq0ibGeU= +github.com/ajg/form v1.5.1/go.mod h1:uL1WgH+h2mgNtvBq0339dVnzXdBETtL2LeUXaIv25UY= +github.com/andybalholm/brotli v1.0.4/go.mod h1:fO7iG3H7G2nSZ7m0zPUDn85XEX2GTukHGRSepvi9Eig= +github.com/andybalholm/brotli v1.1.0 h1:eLKJA0d02Lf0mVpIDgYnqXcUn0GqVmEFny3VuID1U3M= +github.com/andybalholm/brotli v1.1.0/go.mod h1:sms7XGricyQI9K10gOSf56VKKWS4oLer58Q+mhRPtnY= +github.com/antihax/optional v1.0.0/go.mod h1:uupD/76wgC+ih3iEmQUL+0Ugr19nfwCT1kdvxnR2qWY= +github.com/antlr4-go/antlr/v4 v4.13.1 h1:SqQKkuVZ+zWkMMNkjy5FZe5mr5WURWnlpmOuzYWrPrQ= +github.com/antlr4-go/antlr/v4 v4.13.1/go.mod h1:GKmUxMtwp6ZgGwZSva4eWPC5mS6vUAmOABFgjdkM7Nw= +github.com/brianvoe/gofakeit/v7 v7.0.4 h1:Mkxwz9jYg8Ad8NvT9HA27pCMZGFQo08MK6jD0QTKEww= +github.com/brianvoe/gofakeit/v7 v7.0.4/go.mod h1:QXuPeBw164PJCzCUZVmgpgHJ3Llj49jSLVkKPMtxtxA= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +github.com/cespare/xxhash/v2 v2.1.1/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs= +github.com/client9/misspell v0.3.4/go.mod h1:qj6jICC3Q7zFZvVWo7KLAzC3yx5G7kyvSDkc90ppPyw= +github.com/cncf/udpa/go v0.0.0-20191209042840-269d4d468f6f/go.mod h1:M8M6+tZqaGXZJjfX53e64911xZQV5JYwmTeXPW+k8Sc= +github.com/cncf/udpa/go v0.0.0-20201120205902-5459f2c99403/go.mod h1:WmhPx2Nbnhtbo57+VJT5O0JRkEi1Wbu0z5j0R8u5Hbk= +github.com/cncf/udpa/go v0.0.0-20210930031921-04548b0d99d4/go.mod h1:6pvJx4me5XPnfI9Z40ddWsdw2W/uZgQLFXToKeRcDiI= +github.com/cncf/xds/go v0.0.0-20210922020428-25de7278fc84/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211001041855-01bcc9b48dfe/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/cncf/xds/go v0.0.0-20211011173535-cb28da3451f1/go.mod h1:eXthEFrGJvWHgFFCl3hGmgk+/aYT6PnTQLykKQRLhEs= +github.com/coder/websocket v1.8.12 h1:5bUXkEPPIbewrnkU8LTCLVaxi4N4J8ahufH2vlo4NAo= +github.com/coder/websocket v1.8.12/go.mod h1:LNVeNrXQZfe5qhS9ALED3uA+l5pPqvwXg3CKoDBB2gs= +github.com/davecgh/go-spew v0.0.0-20161028175848-04cdfd42973b/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= +github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= +github.com/elastic/go-sysinfo v1.8.1/go.mod h1:JfllUnzoQV/JRYymbH3dO1yggI3mV2oTKSXsDHM+uIM= +github.com/elastic/go-sysinfo v1.14.1 h1:BpY/Utfz75oKSpsQnbAJmmlnT3gBV9WFsopBEYgjhZY= +github.com/elastic/go-sysinfo v1.14.1/go.mod h1:FKUXnZWhnYI0ueO7jhsGV3uQJ5hiz8OqM5b3oGyaRr8= +github.com/elastic/go-windows v1.0.0/go.mod h1:TsU0Nrp7/y3+VwE82FoZF8gC/XFg/Elz6CcloAxnPgU= +github.com/elastic/go-windows v1.0.2 h1:yoLLsAsV5cfg9FLhZ9EXZ2n2sQFKeDYrHenkcivY4vI= +github.com/elastic/go-windows v1.0.2/go.mod h1:bGcDpBzXgYSqM0Gx3DM4+UxFj300SZLixie9u9ixLM8= +github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= +github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= +github.com/envoyproxy/go-control-plane v0.9.9-0.20201210154907-fd9021fe5dad/go.mod h1:cXg6YxExXjJnVBQHBLXeUAgxn2UodCpnH306RInaBQk= +github.com/envoyproxy/go-control-plane v0.10.2-0.20220325020618-49ff273808a1/go.mod h1:KJwIaB5Mv44NWtYuAOFCVOjcI94vtpEz2JU/D2v6IjE= +github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/fatih/color v1.15.0 h1:kOqh6YHBtK8aywxGerMG2Eq3H6Qgoqeo13Bk2Mv/nBs= +github.com/fatih/color v1.15.0/go.mod h1:0h5ZqXfHYED7Bhv2ZJamyIOUej9KtShiJESRwBDUSsw= +github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo= +github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= +github.com/gavv/httpexpect/v2 v2.16.0 h1:Ty2favARiTYTOkCRZGX7ojXXjGyNAIohM1lZ3vqaEwI= +github.com/gavv/httpexpect/v2 v2.16.0/go.mod h1:uJLaO+hQ25ukBJtQi750PsztObHybNllN+t+MbbW8PY= +github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= +github.com/go-chi/chi/v5 v5.1.0 h1:acVI1TYaD+hhedDJ3r54HyA6sExp3HfXq7QWEEY/xMw= +github.com/go-chi/chi/v5 v5.1.0/go.mod h1:DslCQbL2OYiznFReuXYUmQ2hGd1aDpCnlMNITLSKoi8= +github.com/go-faster/city v1.0.1 h1:4WAxSZ3V2Ws4QRDrscLEDcibJY8uf41H6AhXDrNDcGw= +github.com/go-faster/city v1.0.1/go.mod h1:jKcUJId49qdW3L1qKHH/3wPeUstCVpVSXTM6vO3VcTw= +github.com/go-faster/errors v0.7.1 h1:MkJTnDoEdi9pDabt1dpWf7AA8/BaSYZqibYyhZ20AYg= +github.com/go-faster/errors v0.7.1/go.mod h1:5ySTjWFiphBs07IKuiL69nxdfd5+fzh1u7FPGZP2quo= +github.com/go-sql-driver/mysql v1.8.1 h1:LedoTUt/eveggdHS9qUFC1EFSa8bU2+1pZjSRpvNJ1Y= +github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= +github.com/gobwas/glob v0.2.3 h1:A4xDbljILXROh+kObIiy5kIaPYD8e96x1tgBhUI5J+Y= +github.com/gobwas/glob v0.2.3/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +github.com/golang-jwt/jwt/v4 v4.5.0 h1:7cYmW1XlMY7h7ii7UhUyChSgS5wUJEnm9uZVTGqOWzg= +github.com/golang-jwt/jwt/v4 v4.5.0/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0= +github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9 h1:au07oEsX2xN0ktxqI+Sida1w446QrXBRJ0nee3SNZlA= +github.com/golang-sql/civil v0.0.0-20220223132316-b832511892a9/go.mod h1:8vg3r2VgvsThLBIFL93Qb5yWzgyZWhEmBwUJWevAkK0= +github.com/golang-sql/sqlexp v0.1.0 h1:ZCD6MBpcuOVfGVqsEmY5/4FtYiKz6tSyUv9LPEDei6A= +github.com/golang-sql/sqlexp v0.1.0/go.mod h1:J4ad9Vo8ZCWQ2GMrC4UCQy1JpCbwU9m3EOqtpKwwwHI= +github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b/go.mod h1:SBH7ygxi8pfUlaOkMMuAQtPIUF8ecWP5IEl/CR7VP2Q= +github.com/golang/mock v1.1.1/go.mod h1:oTYuIxOrZwtPieC+H1uAHpcLFnEyAGVDL/k47Jfbm0A= +github.com/golang/mock v1.6.0 h1:ErTB+efbowRARo13NNdxyJji2egdxLGQhRaY+DUumQc= +github.com/golang/mock v1.6.0/go.mod h1:p6yTPP+5HYm5mzsMV8JkE6ZKdX+/wYM6Hr+LicevLPs= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= +github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= +github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= +github.com/golang/protobuf v1.4.0-rc.2/go.mod h1:LlEzMj4AhA7rCAGe4KMBDvJI+AwstrUpVNzEA03Pprs= +github.com/golang/protobuf v1.4.0-rc.4.0.20200313231945-b860323f09d0/go.mod h1:WU3c8KckQ9AFe+yFwt9sWVRKCVIyN9cPHBJSNnbL67w= +github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvqG2KuDX0= +github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= +github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= +github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.2/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-cmp v0.5.6/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/go-querystring v1.1.0 h1:AnCroh3fv4ZBgVIf1Iwtovgjaw/GiKJo8M8yD/fhyJ8= +github.com/google/go-querystring v1.1.0/go.mod h1:Kcdr2DB4koayq7X8pmAG4sNG59So17icRSOU623lUBU= +github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +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/gorilla/websocket v1.4.2 h1:+/TMaTYc4QFitKJxsQ7Yye35DkWvkdLcvGKqM+x0Ufc= +github.com/gorilla/websocket v1.4.2/go.mod h1:YR8l580nyteQvAITg2hZ9XVh4b55+EU/adAjf1fMHhE= +github.com/grpc-ecosystem/grpc-gateway v1.16.0/go.mod h1:BDjrQk3hbvj6Nolgz8mAMFbcEtjT1g+wF4CSlocrBnw= +github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k= +github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM= +github.com/imkira/go-interpol v1.1.0 h1:KIiKr0VSG2CUW1hl1jpiyuzuJeKUUpC8iM1AIE7N1Vk= +github.com/imkira/go-interpol v1.1.0/go.mod h1:z0h2/2T3XF8kyEPpRgJ3kmNv+C43p+I/CoI+jC3w2iA= +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.6.0 h1:SWJzexBzPL5jb0GEsrPMLIsi/3jOo7RHlzTjcAeDrPY= +github.com/jackc/pgx/v5 v5.6.0/go.mod h1:DNZ/vlrUnhWCoFGxHAG8U2ljioxukquj7utPDgtQdTw= +github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk= +github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= +github.com/joeshaw/multierror v0.0.0-20140124173710-69b34d4ec901 h1:rp+c0RAYOWj8l6qbCUTSiRLG/iKnW3K3/QfPPuSsBt4= +github.com/joeshaw/multierror v0.0.0-20140124173710-69b34d4ec901/go.mod h1:Z86h9688Y0wesXCyonoVr47MasHilkuLMqGhRZ4Hpak= +github.com/jonboulle/clockwork v0.4.0 h1:p4Cf1aMWXnXAUh8lVfewRBx1zaTSYKrKMF2g3ST4RZ4= +github.com/jonboulle/clockwork v0.4.0/go.mod h1:xgRqUGwRcjKCO1vbZUEtSLrqKoPSsUpK7fnezOII0kc= +github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8= +github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck= +github.com/klauspost/compress v1.13.6/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= +github.com/klauspost/compress v1.15.0/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk= +github.com/klauspost/compress v1.17.9 h1:6KIumPrER1LHsvBVuDa0r5xaG0Es51mhhB9BQB2qeMA= +github.com/klauspost/compress v1.17.9/go.mod h1:Di0epgTjJY877eYKx5yC51cX2A2Vl2ibi7bDH9ttBbw= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= +github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/libsql/sqlite-antlr4-parser v0.0.0-20240721121621-c0bdc870f11c h1:WsJ6G+hkDXIMfQE8FIxnnziT26WmsRgZhdWQ0IQGlcc= +github.com/libsql/sqlite-antlr4-parser v0.0.0-20240721121621-c0bdc870f11c/go.mod h1:gIcFddvsvPcRCO6QDmWH9/zcFd5U26QWWRMgZh4ddyo= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mfridman/interpolate v0.0.2 h1:pnuTK7MQIxxFz1Gr+rjSIx9u7qVjf5VOoM/u6BbAxPY= +github.com/mfridman/interpolate v0.0.2/go.mod h1:p+7uk6oE07mpE/Ik1b8EckO0O4ZXiGAfshKBWLUM9Xg= +github.com/microsoft/go-mssqldb v1.7.2 h1:CHkFJiObW7ItKTJfHo1QX7QBBD1iV+mn1eOyRP3b/PA= +github.com/microsoft/go-mssqldb v1.7.2/go.mod h1:kOvZKUdrhhFQmxLZqbwUV0rHkNkZpthMITIb2Ko1IoA= +github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0= +github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0= +github.com/montanaflynn/stats v0.0.0-20171201202039-1bf9dbcd8cbe/go.mod h1:wL8QJuTMNUDYhXwkmfOly8iTdp5TEcJFWZD2D7SIkUc= +github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4= +github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls= +github.com/paulmach/orb v0.11.1 h1:3koVegMC4X/WeiXYz9iswopaTwMem53NzTJuTF20JzU= +github.com/paulmach/orb v0.11.1/go.mod h1:5mULz1xQfs3bmQm63QEJA6lNGujuRafwA5S/EnuLaLU= +github.com/paulmach/protoscan v0.2.1/go.mod h1:SpcSwydNLrxUGSDvXvO0P7g7AuhJ7lcKfDlhJCDw2gY= +github.com/pierrec/lz4/v4 v4.1.21 h1:yOVMLb6qSIDP67pl/5F7RepeKYu/VmTyEXvuMI5d9mQ= +github.com/pierrec/lz4/v4 v4.1.21/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= +github.com/pkg/diff v0.0.0-20200914180035-5b29258ca4f7/go.mod h1:zO8QMzTeZd5cpnIkz/Gn6iK0jDfGicM1nynOkkPIl28= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +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 v0.0.0-20151028094244-d8ed2627bdf0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pressly/goose/v3 v3.21.1 h1:5SSAKKWej8LVVzNLuT6KIvP1eFDuPvxa+B6H0w78buQ= +github.com/pressly/goose/v3 v3.21.1/go.mod h1:sqthmzV8PitchEkjecFJII//l43dLOCzfWh8pHEe+vE= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/prometheus/procfs v0.0.0-20190425082905-87a4384529e0/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsTZCD3I8kEA= +github.com/prometheus/procfs v0.15.1 h1:YagwOFzUgYfKKHX6Dr+sHT7km/hxC76UB0learggepc= +github.com/prometheus/procfs v0.15.1/go.mod h1:fB45yRUv8NstnjriLhBQLuOUt+WW4BsoGhij/e3PBqk= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE= +github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= +github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= +github.com/sanity-io/litter v1.5.5 h1:iE+sBxPBzoK6uaEP5Lt3fHNgpKcHXc/A2HGETy0uJQo= +github.com/sanity-io/litter v1.5.5/go.mod h1:9gzJgR2i4ZpjZHsKvUXIRQVk7P+yM3e+jAF7bU2UI5U= +github.com/segmentio/asm v1.2.0 h1:9BQrFxC+YOHJlTlHGkTrFWf59nbL3XnCoFLTwDCI7ys= +github.com/segmentio/asm v1.2.0/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs= +github.com/sergi/go-diff v1.0.0 h1:Kpca3qRNrduNnOQeazBd0ysaKrUJiIuISHxogkT9RPQ= +github.com/sergi/go-diff v1.0.0/go.mod h1:0CfEIISq7TuYL3j771MWULgwwjU+GofnZX9QAmXWZgo= +github.com/sethvargo/go-retry v0.3.0 h1:EEt31A35QhrcRZtrYFDTBg91cqZVnFL2navjDrah2SE= +github.com/sethvargo/go-retry v0.3.0/go.mod h1:mNX17F0C/HguQMyMyJxcnU471gOZGxCLyYaFyAZraas= +github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k= +github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v0.0.0-20161117074351-18a02ba4a312/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4= +github.com/stretchr/testify v1.5.1/go.mod h1:5W2xD1RspED5o8YsWQXVCued0rvSQ+mT+I5cxcmMvtA= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg= +github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= +github.com/tailscale/depaware v0.0.0-20210622194025-720c4b409502/go.mod h1:p9lPsd+cx33L3H9nNoecRRxPssFKUwwI50I3pZ0yT+8= +github.com/tidwall/pretty v1.0.0/go.mod h1:XNkn88O1ChpSDQmQeStsy+sBenx6DDtFZJxhVysOjyk= +github.com/tursodatabase/libsql-client-go v0.0.0-20240812094001-348a4e45b535 h1:iLjJLq2A5J6L9zrhyNn+fpmxFvtEpYB4XLMr0rX3epI= +github.com/tursodatabase/libsql-client-go v0.0.0-20240812094001-348a4e45b535/go.mod h1:l8xTsYB90uaVdMHXMCxKKLSgw5wLYBwBKKefNIUnm9s= +github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw= +github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc= +github.com/valyala/fasthttp v1.34.0 h1:d3AAQJ2DRcxJYHm7OXNXtXt2as1vMDfxeIcFvhmGGm4= +github.com/valyala/fasthttp v1.34.0/go.mod h1:epZA5N+7pY6ZaEKRmstzOuYJx9HI8DI1oaCGZpdH4h0= +github.com/valyala/tcplisten v1.0.0/go.mod h1:T0xQ8SeCZGxckz9qRXTfG43PvQ/mcWh7FwZEA7Ioqkc= +github.com/vertica/vertica-sql-go v1.3.3 h1:fL+FKEAEy5ONmsvya2WH5T8bhkvY27y/Ik3ReR2T+Qw= +github.com/vertica/vertica-sql-go v1.3.3/go.mod h1:jnn2GFuv+O2Jcjktb7zyc4Utlbu9YVqpHH/lx63+1M4= +github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= +github.com/xdg-go/scram v1.1.1/go.mod h1:RaEWvsqvNKKvBPvcKeFjrG2cJqOkHTiyTpzz23ni57g= +github.com/xdg-go/stringprep v1.0.3/go.mod h1:W3f5j4i+9rC0kuIEJL0ky1VpHXQU3ocBgklLGvcBnW8= +github.com/xeipuuv/gojsonpointer v0.0.0-20180127040702-4e3ac2762d5f/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb h1:zGWFAtiMcyryUHoUjUJX0/lt1H2+i2Ka2n+D3DImSNo= +github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb/go.mod h1:N2zxlSyiKSe5eX1tZViRH5QA0qijqEDrYZiPEAiq3wU= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHovont7NscjpAxXsDA8S8BMYve8Y5+7cuRE7R0= +github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= +github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= +github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= +github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0 h1:6fRhSjgLCkTD3JnJxvaJ4Sj+TYblw757bqYgZaOq5ZY= +github.com/yalp/jsonpath v0.0.0-20180802001716-5cc68e5049a0/go.mod h1:/LWChgwKmvncFJFHJ7Gvn9wZArjbV5/FppcK2fKk/tI= +github.com/ydb-platform/ydb-go-genproto v0.0.0-20240821162910-6cb364b2ccc8 h1:ZWxYw6L51aNAMLbTpC/VbXP0rcnvsCAJqx7EI/CjWmc= +github.com/ydb-platform/ydb-go-genproto v0.0.0-20240821162910-6cb364b2ccc8/go.mod h1:Er+FePu1dNUieD+XTMDduGpQuCPssK5Q4BjF+IIXJ3I= +github.com/ydb-platform/ydb-go-sdk/v3 v3.77.1 h1:1ICGD18cquyG7/bKQ1ZFdQYSvDvmF7m62b5bIYC8Dkw= +github.com/ydb-platform/ydb-go-sdk/v3 v3.77.1/go.mod h1:IHwuXyolaAmGK2Dp7+dlhsnXphG1pwCoaP/OITT3+tU= +github.com/youmark/pkcs8 v0.0.0-20181117223130-1be2e3e5546d/go.mod h1:rHwXgn7JulP+udvsHwJoVG1YGAP6VLg4y9I5dyZdqmA= +github.com/yudai/gojsondiff v1.0.0 h1:27cbfqXLVEJ1o8I6v3y9lg8Ydm53EKqHXAOMxEGlCOA= +github.com/yudai/gojsondiff v1.0.0/go.mod h1:AY32+k2cwILAkW1fbgxQ5mUmMiZFgLIV+FBNExI05xg= +github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82 h1:BHyfKlQyqbsFN5p3IfnEUduWvb9is428/nNb5L3U01M= +github.com/yudai/golcs v0.0.0-20170316035057-ecda9a501e82/go.mod h1:lgjkn3NuSvDfVJdfcVVdX+jpBxNmX4rDAzaS45IcYoM= +github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +github.com/yuin/goldmark v1.3.5/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k= +github.com/ziutek/mymysql v1.5.4 h1:GB0qdRGsTwQSBVYuVShFBKaXSnSnYYC2d9knnE1LHFs= +github.com/ziutek/mymysql v1.5.4/go.mod h1:LMSpPZ6DbqWFxNCHW77HeMg9I646SAhApZ/wKdgO/C0= +go.mongodb.org/mongo-driver v1.11.4/go.mod h1:PTSz5yu21bkT/wXpkS7WR5f0ddqw5quethTUn9WM+2g= +go.opentelemetry.io/otel v1.29.0 h1:PdomN/Al4q/lN6iBJEN3AwPvUiHPMlt93c8bqTG5Llw= +go.opentelemetry.io/otel v1.29.0/go.mod h1:N/WtXPs1CNCUEx+Agz5uouwCba+i+bJGFicT8SR4NP8= +go.opentelemetry.io/otel/trace v1.29.0 h1:J/8ZNK4XgR7a21DZUAsbF8pZ5Jcw1VhACmnYt39JTi4= +go.opentelemetry.io/otel/trace v1.29.0/go.mod h1:eHl3w0sp3paPkYstJOmAimxhiFXPg+MMTlEh3nsQgWQ= +go.opentelemetry.io/proto/otlp v0.7.0/go.mod h1:PqfVotwruBrMGOCsRd/89rSnXhoiJIqeYNgFYFoEGnI= +go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= +go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8= +go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E= +golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= +golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI= +golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= +golang.org/x/crypto v0.0.0-20220214200702-86341886e292/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.0.0-20220622213112-05595931fe9d/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4= +golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw= +golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54= +golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= +golang.org/x/exp v0.0.0-20240823005443-9b4947da3948 h1:kx6Ds3MlpiUHKj7syVnbp57++8WpuKPcR5yjLBjvLEA= +golang.org/x/exp v0.0.0-20240823005443-9b4947da3948/go.mod h1:akd2r19cwCdwSwWeIdzYQGa/EZZyqcOdwWiwj5L5eKQ= +golang.org/x/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= +golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= +golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= +golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200226121028-0de0cce0169b/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA= +golang.org/x/net v0.0.0-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= +golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y= +golang.org/x/net v0.0.0-20220225172249-27dd8689420f/go.mod h1:CfG3xpIq0wQ8r1q4Su4UZFWDARRcnwPjda9FqA0JpMk= +golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE= +golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg= +golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= +golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20190911185100-cd5d95a43a6e/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20201020160332-67f06af15bc9/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.8.0 h1:3NFvSEYkUoMifnESzZl15y791HH1qU2xm6eCJU5ZPXQ= +golang.org/x/sync v0.8.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk= +golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210119212857-b64e53b001e4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210510120138-977fb7262007/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220227234510-4e6760a101f9/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg= +golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= +golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= +golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc= +golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY= +golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= +golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= +golang.org/x/tools v0.0.0-20190311212946-11955173bddd/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs= +golang.org/x/tools v0.0.0-20190524140312-2c0ae7006135/go.mod h1:RgjU9mgBXZiqYHBnxXauZ1Gv1EHHAz9KjViQ78xBX0Q= +golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE= +golang.org/x/tools v0.0.0-20201211185031-d93e913c1a58/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/appengine v1.1.0/go.mod h1:EbEs0AVv82hx2wNQdGPgUI5lhzA/G0D9YwlJXL52JkM= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= +google.golang.org/genproto v0.0.0-20180817151627-c66870c02cf8/go.mod h1:JiN7NxoALGmiZfu7CAH4rXhgtRTLTxftemlI0sWmxmc= +google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98Agz4BDEuKkezgsaosCRResVns1a3J2ZsMNc= +google.golang.org/genproto v0.0.0-20200513103714-09dca8ec2884/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240827150818-7e3bb234dfed h1:J6izYgfBXAI3xTKLgxzTmUltdYaLsuBxFCgDHWJ/eXg= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240827150818-7e3bb234dfed/go.mod h1:UqMtugtsSgubUsoxbuAoiCXvqvErP7Gf0so0mK9tHxU= +google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= +google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= +google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= +google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= +google.golang.org/grpc v1.33.1/go.mod h1:fr5YgcSWrqhRRxogOsw7RzIpsmvOZ6IcH4kBYTpR3n0= +google.golang.org/grpc v1.36.0/go.mod h1:qjiiYl8FncCW8feJPdyg3v6XW24KsRHe+dy9BAGRRjU= +google.golang.org/grpc v1.47.0/go.mod h1:vN9eftEi1UMyUsIF80+uQXhHjbXYbm0uXoFCACuMGWk= +google.golang.org/grpc v1.66.0 h1:DibZuoBznOxbDQxRINckZcUvnCEvrW9pcWIE2yF9r1c= +google.golang.org/grpc v1.66.0/go.mod h1:s3/l6xSSCURdVfAnL+TqCNMyTDAGN6+lZeVxnZR128Y= +google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= +google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= +google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= +google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miEFZTKqfCUM6K7xSMQL9OKL/b6hQv+e19PK+JZNE= +google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= +google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= +google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.26.0/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.27.1/go.mod h1:9q0QmTI4eRPtz6boOQmLYwt+qCgq0jsYwAQnmE0givc= +google.golang.org/protobuf v1.28.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6hg= +google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v1 v1.0.0-20140924161607-9f9df34309c0/go.mod h1:WDnlLJ4WF5VGsH/HVa3CI79GS0ol3YnhVnKP89i0kNg= +gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= +howett.net/plist v0.0.0-20181124034731-591f970eefbb/go.mod h1:vMygbs4qMhSZSc4lCUl2OEE+rDiIIJAIdR4m7MiMcm0= +howett.net/plist v1.0.1 h1:37GdZ8tP09Q35o9ych3ehygcsL+HqKSwzctveSlarvM= +howett.net/plist v1.0.1/go.mod h1:lqaXoTrLY4hg8tnEzNru53gicrbv7rrk+2xJA/7hw9g= +modernc.org/gc/v3 v3.0.0-20240801135723-a856999a2e4a h1:CfbpOLEo2IwNzJdMvE8aiRbPMxoTpgAJeyePh0SmO8M= +modernc.org/gc/v3 v3.0.0-20240801135723-a856999a2e4a/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4= +modernc.org/libc v1.60.0 h1:XeRF1gXky7JE5E8IErtYAdKj+ykZPdYUsgJNQ8RFWIA= +modernc.org/libc v1.60.0/go.mod h1:xJuobKuNxKH3RUatS7GjR+suWj+5c2K7bi4m/S5arOY= +modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4= +modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo= +modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E= +modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU= +modernc.org/sqlite v1.32.0 h1:6BM4uGza7bWypsw4fdLRsLxut6bHe4c58VeqjRgST8s= +modernc.org/sqlite v1.32.0/go.mod h1:UqoylwmTb9F+IqXERT8bW9zzOWN8qwAIcLdzeBZs4hA= +modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA= +modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0= +modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y= +modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM= +moul.io/http2curl/v2 v2.3.0 h1:9r3JfDzWPcbIklMOs2TnIFzDYvfAZvjeavG6EzP7jYs= +moul.io/http2curl/v2 v2.3.0/go.mod h1:RW4hyBjTWSYDOxapodpNEtX0g5Eb16sxklBqmd2RHcE= +nhooyr.io/websocket v1.8.17 h1:KEVeLJkUywCKVsnLIDlD/5gtayKp8VoCkksHCGGfT9Y= +nhooyr.io/websocket v1.8.17/go.mod h1:rN9OFWIUwuxg4fR5tELlYC04bXYowCP9GX47ivo2l+c= diff --git a/internal/authenticate/authenticate.go b/internal/authenticate/authenticate.go new file mode 100644 index 0000000..e803e30 --- /dev/null +++ b/internal/authenticate/authenticate.go @@ -0,0 +1,104 @@ +package authenticate + +import ( + "fmt" + "github.com/golang-jwt/jwt/v4" + "github.com/google/uuid" + "go.uber.org/zap" + "net/http" + "strings" + "time" +) + +type Claims struct { + jwt.RegisteredClaims + UserID uuid.UUID +} +type ContextKey string + +var ContextUserID ContextKey = "UserID" + +type Auth interface { + GetUserIDFromCookie(tokenString string) (uuid.UUID, error) + SetCookie(rw http.ResponseWriter, UserID uuid.UUID) +} + +type Authenticate struct { + logger *zap.Logger + secretKey string + tokenExp time.Duration +} + +func NewAuthenticateService(opts ...func(*Authenticate)) *Authenticate { + auth := &Authenticate{} + for _, opt := range opts { + opt(auth) + } + return auth +} + +func WithLogger(logger *zap.Logger) func(*Authenticate) { + return func(a *Authenticate) { + a.logger = logger + } +} + +func WithSecretKey(secretKey string) func(*Authenticate) { + return func(a *Authenticate) { + a.secretKey = secretKey + } +} + +func WithTokenExp(tokenExp time.Duration) func(*Authenticate) { + return func(a *Authenticate) { + a.tokenExp = tokenExp + } +} + +func (a *Authenticate) createCookie(UserID uuid.UUID) (http.Cookie, error) { + token, err := a.createToken(UserID) + if err != nil { + return http.Cookie{}, err + } + return http.Cookie{Name: "Authorization", Value: token, Expires: time.Now().Add(a.tokenExp), HttpOnly: true, Path: "/"}, nil +} + +func (a *Authenticate) createToken(UserID uuid.UUID) (string, error) { + token := jwt.NewWithClaims(jwt.SigningMethodHS256, Claims{ + RegisteredClaims: jwt.RegisteredClaims{ + ExpiresAt: jwt.NewNumericDate(time.Now().Add(a.tokenExp)), + }, + UserID: UserID, + }) + + tokenString, err := token.SignedString([]byte(a.secretKey)) + if err != nil { + return "", err + } + return "Bearer " + tokenString, nil +} + +func (a *Authenticate) GetUserIDFromCookie(tokenString string) (uuid.UUID, error) { + claims := &Claims{} + token, err := jwt.ParseWithClaims(strings.TrimPrefix(tokenString, "Bearer "), claims, + func(t *jwt.Token) (interface{}, error) { + return []byte(a.secretKey), nil + }) + if err != nil { + return uuid.Nil, err + } + + if !token.Valid { + return uuid.Nil, fmt.Errorf("invalid token") + } + return claims.UserID, nil +} + +func (a *Authenticate) SetCookie(rw http.ResponseWriter, UserID uuid.UUID) { + cookie, err := a.createCookie(UserID) + if err != nil { + a.logger.Error(err.Error()) + } else { + http.SetCookie(rw, &cookie) + } +} diff --git a/internal/authenticate/mocks/authenticate.go b/internal/authenticate/mocks/authenticate.go new file mode 100644 index 0000000..80dc611 --- /dev/null +++ b/internal/authenticate/mocks/authenticate.go @@ -0,0 +1,63 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: internal/authenticate/authenticate.go + +// Package amocks is a generated GoMock package. +package amocks + +import ( + http "net/http" + reflect "reflect" + + gomock "github.com/golang/mock/gomock" + uuid "github.com/google/uuid" +) + +// MockAuth is a mock of Auth interface. +type MockAuth struct { + ctrl *gomock.Controller + recorder *MockAuthMockRecorder +} + +// MockAuthMockRecorder is the mock recorder for MockAuth. +type MockAuthMockRecorder struct { + mock *MockAuth +} + +// NewMockAuth creates a new mock instance. +func NewMockAuth(ctrl *gomock.Controller) *MockAuth { + mock := &MockAuth{ctrl: ctrl} + mock.recorder = &MockAuthMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockAuth) EXPECT() *MockAuthMockRecorder { + return m.recorder +} + +// GetUserIDFromCookie mocks base method. +func (m *MockAuth) GetUserIDFromCookie(tokenString string) (uuid.UUID, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetUserIDFromCookie", tokenString) + ret0, _ := ret[0].(uuid.UUID) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetUserIDFromCookie indicates an expected call of GetUserIDFromCookie. +func (mr *MockAuthMockRecorder) GetUserIDFromCookie(tokenString interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUserIDFromCookie", reflect.TypeOf((*MockAuth)(nil).GetUserIDFromCookie), tokenString) +} + +// SetCookie mocks base method. +func (m *MockAuth) SetCookie(rw http.ResponseWriter, UserID uuid.UUID) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "SetCookie", rw, UserID) +} + +// SetCookie indicates an expected call of SetCookie. +func (mr *MockAuthMockRecorder) SetCookie(rw, UserID interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetCookie", reflect.TypeOf((*MockAuth)(nil).SetCookie), rw, UserID) +} diff --git a/internal/client/order.go b/internal/client/order.go new file mode 100644 index 0000000..bed5803 --- /dev/null +++ b/internal/client/order.go @@ -0,0 +1,68 @@ +package client + +import ( + "encoding/json" + "errors" + "github.com/spqrcor/gofermart/internal/services" + "go.uber.org/zap" + "io" + "net/http" + "strconv" +) + +type OrderClient interface { + CheckOrder(OrderNum string) (services.OrderFromAccrual, int, error) +} + +type OrderClientService struct { + logger *zap.Logger + accrualSystemAddress string +} + +func NewOrderClient(opts ...func(*OrderClientService)) *OrderClientService { + orderClient := &OrderClientService{} + for _, opt := range opts { + opt(orderClient) + } + return orderClient +} + +func WithLogger(logger *zap.Logger) func(*OrderClientService) { + return func(o *OrderClientService) { + o.logger = logger + } +} + +func WithAccrualSystemAddress(accrualSystemAddress string) func(*OrderClientService) { + return func(o *OrderClientService) { + o.accrualSystemAddress = accrualSystemAddress + } +} + +func (c OrderClientService) CheckOrder(OrderNum string) (services.OrderFromAccrual, int, error) { + data := services.OrderFromAccrual{} + resp, err := http.Get(c.accrualSystemAddress + "/api/orders/" + OrderNum) + if err != nil { + return data, 0, err + } + defer func() { + _ = resp.Body.Close() + }() + if resp.StatusCode == http.StatusTooManyRequests { + retryAfter := resp.Header.Get("Retry-After") + seconds, err := strconv.Atoi(retryAfter) + if err != nil { + seconds = 0 + } + return data, seconds, errors.New("Error " + resp.Status) + } + if resp.StatusCode != http.StatusOK { + return data, 0, errors.New("Error " + resp.Status) + } + + bodyBytes, _ := io.ReadAll(resp.Body) + if err = json.Unmarshal(bodyBytes, &data); err != nil { + return data, 0, err + } + return data, 0, nil +} diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..42b7557 --- /dev/null +++ b/internal/config/config.go @@ -0,0 +1,59 @@ +package config + +import ( + "flag" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" + "os" + "sync" + "time" +) + +type Config struct { + RunAddr string `env:"RUN_ADDRESS"` + AccrualSystemAddress string `env:"ACCRUAL_SYSTEM_ADDRESS"` + LogLevel zapcore.Level `env:"LOG_LEVEL"` + DatabaseURI string `env:"DATABASE_URI"` + QueryTimeOut time.Duration `env:"QUERY_TIME_OUT"` + WorkerCount int `env:"WORKER_COUNT"` + RetryStartWorkerCount int `env:"RETRY_START_WORKER_COUNT"` + SecretKey string `env:"SECRET_KEY"` + TokenExp time.Duration `env:"TOKEN_EXP"` +} + +var cfg = Config{ + RunAddr: "localhost:8080", + LogLevel: zap.InfoLevel, + AccrualSystemAddress: "", + DatabaseURI: "", + QueryTimeOut: 3, + WorkerCount: 3, + RetryStartWorkerCount: 10, + SecretKey: "KLJ-fo3Fksd3fl!=", + TokenExp: time.Hour * 3, +} +var once sync.Once + +func NewConfig() Config { + once.Do(func() { + flag.StringVar(&cfg.RunAddr, "a", cfg.RunAddr, "address and port to run server") + flag.StringVar(&cfg.AccrualSystemAddress, "r", cfg.AccrualSystemAddress, "accrual system address") + flag.StringVar(&cfg.DatabaseURI, "d", cfg.DatabaseURI, "database uri") + flag.Parse() + + serverAddressEnv, findAddress := os.LookupEnv("RUN_ADDRESS") + serverDatabaseURI, findDatabaseURI := os.LookupEnv("DATABASE_URI") + serverAccrualSystemAddress, findAccrualSystemAddress := os.LookupEnv("ACCRUAL_SYSTEM_ADDRESS") + + if findAddress { + cfg.RunAddr = serverAddressEnv + } + if findDatabaseURI { + cfg.DatabaseURI = serverDatabaseURI + } + if findAccrualSystemAddress { + cfg.AccrualSystemAddress = serverAccrualSystemAddress + } + }) + return cfg +} diff --git a/internal/db/connector.go b/internal/db/connector.go new file mode 100644 index 0000000..11220cd --- /dev/null +++ b/internal/db/connector.go @@ -0,0 +1,45 @@ +package db + +import ( + "database/sql" + _ "github.com/jackc/pgx/v5/stdlib" + "github.com/pressly/goose/v3" + "go.uber.org/zap" + "time" +) + +func connect(logger *zap.Logger, databaseURI string) (*sql.DB, error) { + db, err := sql.Open("pgx", databaseURI) + if err != nil { + logger.Fatal(err.Error()) + return nil, err + } + + db.SetConnMaxLifetime(time.Minute * 5) + db.SetMaxOpenConns(10) + db.SetMaxIdleConns(10) + + if err := db.Ping(); err != nil { + logger.Error(err.Error()) + return nil, err + } + return db, nil +} + +func NewDB(logger *zap.Logger, databaseURI string) (*sql.DB, error) { + res, err := connect(logger, databaseURI) + if err != nil { + return nil, err + } + return res, nil +} + +func Migrate(res *sql.DB) error { + if err := goose.SetDialect("postgres"); err != nil { + return err + } + if err := goose.Up(res, "internal/migrations"); err != nil { + return err + } + return nil +} diff --git a/internal/handlers/add_orders.go b/internal/handlers/add_orders.go new file mode 100644 index 0000000..fc03b07 --- /dev/null +++ b/internal/handlers/add_orders.go @@ -0,0 +1,35 @@ +package handlers + +import ( + "errors" + "github.com/spqrcor/gofermart/internal/services" + "github.com/spqrcor/gofermart/internal/utils" + "net/http" +) + +func AddOrdersHandler(o services.Order) http.HandlerFunc { + return func(res http.ResponseWriter, req *http.Request) { + orderNum, err := utils.FromPostPlain(req) + if err != nil { + res.WriteHeader(http.StatusBadRequest) + return + } + + err = o.Add(req.Context(), orderNum) + if errors.Is(err, services.ErrOrderInvalidFormat) { + http.Error(res, err.Error(), http.StatusUnprocessableEntity) + return + } else if errors.Is(err, services.ErrOrderAnotherUserExists) { + res.WriteHeader(http.StatusConflict) + return + } else if errors.Is(err, services.ErrOrderUserExists) { + res.WriteHeader(http.StatusOK) + return + } + if err != nil { + res.WriteHeader(http.StatusInternalServerError) + return + } + res.WriteHeader(http.StatusAccepted) + } +} diff --git a/internal/handlers/add_orders_test.go b/internal/handlers/add_orders_test.go new file mode 100644 index 0000000..3ef13cc --- /dev/null +++ b/internal/handlers/add_orders_test.go @@ -0,0 +1,75 @@ +package handlers + +import ( + "bytes" + "context" + "github.com/golang/mock/gomock" + "github.com/spqrcor/gofermart/internal/services" + "github.com/spqrcor/gofermart/internal/services/mocks" + "github.com/stretchr/testify/assert" + "net/http" + "net/http/httptest" + "testing" +) + +func TestAddOrdersHandler(t *testing.T) { + mockCtrl := gomock.NewController(t) + defer mockCtrl.Finish() + + order := mocks.NewMockOrder(mockCtrl) + order.EXPECT().Add(context.Background(), "333").Return(services.ErrOrderInvalidFormat).AnyTimes() + order.EXPECT().Add(context.Background(), "9278923470").Return(nil).MaxTimes(1) + order.EXPECT().Add(context.Background(), "9278923470").Return(services.ErrOrderUserExists).MinTimes(1) + order.EXPECT().Add(context.Background(), "12345678903").Return(services.ErrOrderAnotherUserExists).AnyTimes() + + tests := []struct { + name string + contentType string + body []byte + statusCode int + }{ + { + name: "content type error", + contentType: "application/json", + body: []byte(`3333`), + statusCode: http.StatusBadRequest, + }, + { + name: "format number error", + contentType: "text/plain", + body: []byte(`333`), + statusCode: http.StatusUnprocessableEntity, + }, + { + name: "success", + contentType: "text/plain", + body: []byte(`9278923470`), + statusCode: http.StatusAccepted, + }, + { + name: "order user exists", + contentType: "text/plain", + body: []byte(`9278923470`), + statusCode: http.StatusOK, + }, + { + name: "order another user exists", + contentType: "text/plain", + body: []byte(`12345678903`), + statusCode: http.StatusConflict, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + rw := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/api/user/orders", bytes.NewReader(tt.body)) + req.Header.Add("Content-Type", tt.contentType) + AddOrdersHandler(order)(rw, req) + + resp := rw.Result() + assert.Equal(t, tt.statusCode, resp.StatusCode, "Error http status code") + _ = resp.Body.Close() + }) + } +} diff --git a/internal/handlers/add_withdrawals.go b/internal/handlers/add_withdrawals.go new file mode 100644 index 0000000..d47059e --- /dev/null +++ b/internal/handlers/add_withdrawals.go @@ -0,0 +1,33 @@ +package handlers + +import ( + "errors" + "github.com/spqrcor/gofermart/internal/services" + "github.com/spqrcor/gofermart/internal/utils" + "net/http" +) + +func AddWithdrawalHandler(w services.Withdrawal) http.HandlerFunc { + return func(res http.ResponseWriter, req *http.Request) { + var input services.InputWithdrawal + if err := utils.FromPostJSON(req, &input); err != nil { + res.WriteHeader(http.StatusInternalServerError) + return + } + + err := w.Add(req.Context(), input) + if errors.Is(err, services.ErrOrderInvalidFormat) { + http.Error(res, err.Error(), http.StatusUnprocessableEntity) + return + } else if errors.Is(err, services.ErrBalance) { + http.Error(res, err.Error(), http.StatusPaymentRequired) + return + } + if err != nil { + res.WriteHeader(http.StatusInternalServerError) + return + } + + res.WriteHeader(http.StatusOK) + } +} diff --git a/internal/handlers/add_withdrawals_test.go b/internal/handlers/add_withdrawals_test.go new file mode 100644 index 0000000..aa65dab --- /dev/null +++ b/internal/handlers/add_withdrawals_test.go @@ -0,0 +1,68 @@ +package handlers + +import ( + "bytes" + "context" + "github.com/golang/mock/gomock" + "github.com/spqrcor/gofermart/internal/services" + "github.com/spqrcor/gofermart/internal/services/mocks" + "github.com/stretchr/testify/assert" + "net/http" + "net/http/httptest" + "testing" +) + +func TestAddWithdrawalHandler(t *testing.T) { + mockCtrl := gomock.NewController(t) + defer mockCtrl.Finish() + + withdrawal := mocks.NewMockWithdrawal(mockCtrl) + withdrawal.EXPECT().Add(context.Background(), services.InputWithdrawal{OrderNum: "333", Sum: 100}).Return(services.ErrOrderInvalidFormat).AnyTimes() + withdrawal.EXPECT().Add(context.Background(), services.InputWithdrawal{OrderNum: "9278923470", Sum: 100}).Return(nil).AnyTimes() + withdrawal.EXPECT().Add(context.Background(), services.InputWithdrawal{OrderNum: "12345678903", Sum: 100}).Return(services.ErrBalance).AnyTimes() + + tests := []struct { + name string + contentType string + body []byte + statusCode int + }{ + { + name: "content type error", + contentType: "text/plain", + body: []byte(`1111`), + statusCode: http.StatusInternalServerError, + }, + { + name: "format order error", + contentType: "application/json", + body: []byte(`{"order":"333","sum":100}`), + statusCode: http.StatusUnprocessableEntity, + }, + { + name: "success", + contentType: "application/json", + body: []byte(`{"order":"9278923470","sum":100}`), + statusCode: http.StatusOK, + }, + { + name: "balance error", + contentType: "application/json", + body: []byte(`{"order":"12345678903","sum":100}`), + statusCode: http.StatusPaymentRequired, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + rw := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/api/user/balance/withdraw", bytes.NewReader(tt.body)) + req.Header.Add("Content-Type", tt.contentType) + AddWithdrawalHandler(withdrawal)(rw, req) + + resp := rw.Result() + assert.Equal(t, tt.statusCode, resp.StatusCode, "Error http status code") + _ = resp.Body.Close() + }) + } +} diff --git a/internal/handlers/get_balance.go b/internal/handlers/get_balance.go new file mode 100644 index 0000000..ea77501 --- /dev/null +++ b/internal/handlers/get_balance.go @@ -0,0 +1,25 @@ +package handlers + +import ( + "encoding/json" + "github.com/spqrcor/gofermart/internal/services" + "net/http" +) + +func GetBalanceHandler(w services.Withdrawal) http.HandlerFunc { + return func(res http.ResponseWriter, req *http.Request) { + balance, err := w.GetBalance(req.Context()) + if err != nil { + http.Error(res, err.Error(), http.StatusInternalServerError) + return + } + + res.Header().Set("Content-Type", "application/json; charset=utf-8") + res.WriteHeader(http.StatusOK) + enc := json.NewEncoder(res) + if err := enc.Encode(balance); err != nil { + res.WriteHeader(http.StatusInternalServerError) + return + } + } +} diff --git a/internal/handlers/get_balance_test.go b/internal/handlers/get_balance_test.go new file mode 100644 index 0000000..67c9d8b --- /dev/null +++ b/internal/handlers/get_balance_test.go @@ -0,0 +1,48 @@ +package handlers + +import ( + "context" + "errors" + "github.com/golang/mock/gomock" + "github.com/spqrcor/gofermart/internal/services" + "github.com/spqrcor/gofermart/internal/services/mocks" + "github.com/stretchr/testify/assert" + "net/http" + "net/http/httptest" + "testing" +) + +func TestGetBalanceHandler(t *testing.T) { + mockCtrl := gomock.NewController(t) + defer mockCtrl.Finish() + + withdrawal := mocks.NewMockWithdrawal(mockCtrl) + withdrawal.EXPECT().GetBalance(context.Background()).Return(services.BalanceInfo{}, errors.New("user not found")).MaxTimes(1) + withdrawal.EXPECT().GetBalance(context.Background()).Return(services.BalanceInfo{Current: 100, Withdrawn: 100}, nil).MinTimes(1) + tests := []struct { + name string + statusCode int + }{ + { + name: "no content error", + statusCode: http.StatusInternalServerError, + }, + { + name: "success", + statusCode: http.StatusOK, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + rw := httptest.NewRecorder() + req := httptest.NewRequest("GET", "/api/user/balance", nil) + GetBalanceHandler(withdrawal)(rw, req) + + resp := rw.Result() + assert.Equal(t, tt.statusCode, resp.StatusCode, "Error http status code") + _ = resp.Body.Close() + }) + } + +} diff --git a/internal/handlers/get_orders.go b/internal/handlers/get_orders.go new file mode 100644 index 0000000..56cab4a --- /dev/null +++ b/internal/handlers/get_orders.go @@ -0,0 +1,30 @@ +package handlers + +import ( + "encoding/json" + "errors" + "github.com/spqrcor/gofermart/internal/services" + "net/http" +) + +func GetOrdersHandler(o services.Order) http.HandlerFunc { + return func(res http.ResponseWriter, req *http.Request) { + orders, err := o.GetAll(req.Context()) + if errors.Is(err, services.ErrOrdersNotFound) { + res.WriteHeader(http.StatusNoContent) + return + } + if err != nil { + http.Error(res, err.Error(), http.StatusInternalServerError) + return + } + + res.Header().Set("Content-Type", "application/json; charset=utf-8") + res.WriteHeader(http.StatusOK) + enc := json.NewEncoder(res) + if err := enc.Encode(orders); err != nil { + res.WriteHeader(http.StatusInternalServerError) + return + } + } +} diff --git a/internal/handlers/get_orders_test.go b/internal/handlers/get_orders_test.go new file mode 100644 index 0000000..960286a --- /dev/null +++ b/internal/handlers/get_orders_test.go @@ -0,0 +1,51 @@ +package handlers + +import ( + "context" + "github.com/golang/mock/gomock" + "github.com/spqrcor/gofermart/internal/services" + "github.com/spqrcor/gofermart/internal/services/mocks" + "github.com/stretchr/testify/assert" + "net/http" + "net/http/httptest" + "testing" +) + +func TestGetOrdersHandler(t *testing.T) { + mockCtrl := gomock.NewController(t) + defer mockCtrl.Finish() + + order := mocks.NewMockOrder(mockCtrl) + order.EXPECT().GetAll(context.Background()).Return([]services.OrderData{}, services.ErrOrdersNotFound).MaxTimes(1) + order.EXPECT().GetAll(context.Background()).Return([]services.OrderData{ + services.OrderData{ + Number: "9278923470", Status: "NEW", UploadedAt: "2024-01-01 00:00:00+3", + }, + }, nil).MinTimes(1) + + tests := []struct { + name string + statusCode int + }{ + { + name: "no content error", + statusCode: http.StatusNoContent, + }, + { + name: "success", + statusCode: http.StatusOK, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + rw := httptest.NewRecorder() + req := httptest.NewRequest("GET", "/api/user/orders", nil) + GetOrdersHandler(order)(rw, req) + + resp := rw.Result() + assert.Equal(t, tt.statusCode, resp.StatusCode, "Error http status code") + _ = resp.Body.Close() + }) + } +} diff --git a/internal/handlers/get_withdrawals.go b/internal/handlers/get_withdrawals.go new file mode 100644 index 0000000..9c28a25 --- /dev/null +++ b/internal/handlers/get_withdrawals.go @@ -0,0 +1,30 @@ +package handlers + +import ( + "encoding/json" + "errors" + "github.com/spqrcor/gofermart/internal/services" + "net/http" +) + +func GetWithdrawalsHandler(w services.Withdrawal) http.HandlerFunc { + return func(res http.ResponseWriter, req *http.Request) { + withdrawals, err := w.GetAll(req.Context()) + if errors.Is(err, services.ErrWithdrawNotFound) { + res.WriteHeader(http.StatusNoContent) + return + } + if err != nil { + http.Error(res, err.Error(), http.StatusInternalServerError) + return + } + + res.Header().Set("Content-Type", "application/json; charset=utf-8") + res.WriteHeader(http.StatusOK) + enc := json.NewEncoder(res) + if err := enc.Encode(withdrawals); err != nil { + res.WriteHeader(http.StatusInternalServerError) + return + } + } +} diff --git a/internal/handlers/get_withdrawals_test.go b/internal/handlers/get_withdrawals_test.go new file mode 100644 index 0000000..18b93f2 --- /dev/null +++ b/internal/handlers/get_withdrawals_test.go @@ -0,0 +1,51 @@ +package handlers + +import ( + "context" + "github.com/golang/mock/gomock" + "github.com/spqrcor/gofermart/internal/services" + "github.com/spqrcor/gofermart/internal/services/mocks" + "github.com/stretchr/testify/assert" + "net/http" + "net/http/httptest" + "testing" +) + +func TestGetWithdrawalsHandler(t *testing.T) { + mockCtrl := gomock.NewController(t) + defer mockCtrl.Finish() + + withdrawal := mocks.NewMockWithdrawal(mockCtrl) + withdrawal.EXPECT().GetAll(context.Background()).Return([]services.WithdrawalData{}, services.ErrWithdrawNotFound).MaxTimes(1) + withdrawal.EXPECT().GetAll(context.Background()).Return([]services.WithdrawalData{ + services.WithdrawalData{ + OrderNum: "9278923470", Sum: 100, ProcessedAt: "2024-01-01 00:00:00+3", + }, + }, nil).MinTimes(1) + + tests := []struct { + name string + statusCode int + }{ + { + name: "no content error", + statusCode: http.StatusNoContent, + }, + { + name: "success", + statusCode: http.StatusOK, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + rw := httptest.NewRecorder() + req := httptest.NewRequest("GET", "/api/user/withdrawals", nil) + GetWithdrawalsHandler(withdrawal)(rw, req) + + resp := rw.Result() + assert.Equal(t, tt.statusCode, resp.StatusCode, "Error http status code") + _ = resp.Body.Close() + }) + } +} diff --git a/internal/handlers/login.go b/internal/handlers/login.go new file mode 100644 index 0000000..b594767 --- /dev/null +++ b/internal/handlers/login.go @@ -0,0 +1,32 @@ +package handlers + +import ( + "errors" + "github.com/spqrcor/gofermart/internal/authenticate" + "github.com/spqrcor/gofermart/internal/services" + "github.com/spqrcor/gofermart/internal/utils" + "net/http" +) + +func LoginHandler(u services.User, a authenticate.Auth) http.HandlerFunc { + return func(res http.ResponseWriter, req *http.Request) { + var input services.InputDataUser + if err := utils.FromPostJSON(req, &input); err != nil { + res.WriteHeader(http.StatusBadRequest) + return + } + + UserID, err := u.Login(req.Context(), input) + if errors.Is(err, services.ErrLogin) { + http.Error(res, err.Error(), http.StatusUnauthorized) + return + } + if err != nil { + res.WriteHeader(http.StatusInternalServerError) + return + } + + a.SetCookie(res, UserID) + res.WriteHeader(http.StatusOK) + } +} diff --git a/internal/handlers/login_test.go b/internal/handlers/login_test.go new file mode 100644 index 0000000..254842a --- /dev/null +++ b/internal/handlers/login_test.go @@ -0,0 +1,70 @@ +package handlers + +import ( + "bytes" + "context" + "github.com/golang/mock/gomock" + "github.com/google/uuid" + amocks "github.com/spqrcor/gofermart/internal/authenticate/mocks" + "github.com/spqrcor/gofermart/internal/services" + "github.com/spqrcor/gofermart/internal/services/mocks" + "github.com/stretchr/testify/assert" + "net/http" + "net/http/httptest" + "testing" +) + +func TestLoginHandler(t *testing.T) { + mockCtrl := gomock.NewController(t) + defer mockCtrl.Finish() + + userUUID := uuid.New() + user := mocks.NewMockUser(mockCtrl) + authenticate := amocks.NewMockAuth(mockCtrl) + user.EXPECT().Login(context.Background(), services.InputDataUser{ + Login: "spqr", Password: "1", + }).Return(uuid.Nil, services.ErrLogin).AnyTimes() + user.EXPECT().Login(context.Background(), services.InputDataUser{ + Login: "spqr", Password: "123456", + }).Return(userUUID, nil).AnyTimes() + + tests := []struct { + name string + contentType string + body []byte + statusCode int + }{ + { + name: "not format error", + contentType: "application/json", + body: []byte(`3333`), + statusCode: http.StatusBadRequest, + }, + { + name: "login error", + contentType: "application/json", + body: []byte(`{"login":"spqr","password":"1"}`), + statusCode: http.StatusUnauthorized, + }, + { + name: "success", + contentType: "application/json", + body: []byte(`{"login":"spqr","password":"123456"}`), + statusCode: http.StatusOK, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + rw := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/api/user/login", bytes.NewReader(tt.body)) + req.Header.Add("Content-Type", tt.contentType) + authenticate.EXPECT().SetCookie(rw, userUUID).AnyTimes() + LoginHandler(user, authenticate)(rw, req) + + resp := rw.Result() + assert.Equal(t, tt.statusCode, resp.StatusCode, "Error http status code") + _ = resp.Body.Close() + }) + } +} diff --git a/internal/handlers/register.go b/internal/handlers/register.go new file mode 100644 index 0000000..493dfa4 --- /dev/null +++ b/internal/handlers/register.go @@ -0,0 +1,36 @@ +package handlers + +import ( + "errors" + "github.com/spqrcor/gofermart/internal/authenticate" + "github.com/spqrcor/gofermart/internal/services" + "github.com/spqrcor/gofermart/internal/utils" + "net/http" +) + +func RegisterHandler(u services.User, a authenticate.Auth) http.HandlerFunc { + return func(res http.ResponseWriter, req *http.Request) { + var input services.InputDataUser + if err := utils.FromPostJSON(req, &input); err != nil { + res.WriteHeader(http.StatusBadRequest) + return + } + + UserID, err := u.Add(req.Context(), input) + if errors.Is(err, services.ErrValidation) { + http.Error(res, err.Error(), http.StatusBadRequest) + return + } + if errors.Is(err, services.ErrLoginExists) { + res.WriteHeader(http.StatusConflict) + return + } + if err != nil { + res.WriteHeader(http.StatusInternalServerError) + return + } + + a.SetCookie(res, UserID) + res.WriteHeader(http.StatusOK) + } +} diff --git a/internal/handlers/register_test.go b/internal/handlers/register_test.go new file mode 100644 index 0000000..43fc231 --- /dev/null +++ b/internal/handlers/register_test.go @@ -0,0 +1,80 @@ +package handlers + +import ( + "bytes" + "context" + "github.com/golang/mock/gomock" + "github.com/google/uuid" + "github.com/spqrcor/gofermart/internal/authenticate/mocks" + "github.com/spqrcor/gofermart/internal/services" + "github.com/spqrcor/gofermart/internal/services/mocks" + "github.com/stretchr/testify/assert" + "net/http" + "net/http/httptest" + "testing" +) + +func TestRegisterHandler(t *testing.T) { + mockCtrl := gomock.NewController(t) + defer mockCtrl.Finish() + + userUUID := uuid.New() + user := mocks.NewMockUser(mockCtrl) + authenticate := amocks.NewMockAuth(mockCtrl) + + user.EXPECT().Add(context.Background(), services.InputDataUser{ + Login: "s", Password: "123456", + }).Return(uuid.Nil, services.ErrValidation).AnyTimes() + user.EXPECT().Add(context.Background(), services.InputDataUser{ + Login: "spqr", Password: "123456", + }).Return(userUUID, nil).AnyTimes().MaxTimes(1) + user.EXPECT().Add(context.Background(), services.InputDataUser{ + Login: "spqr", Password: "123456", + }).Return(uuid.Nil, services.ErrLoginExists).AnyTimes().MinTimes(1) + + tests := []struct { + name string + contentType string + body []byte + statusCode int + }{ + { + name: "not format error", + contentType: "application/json", + body: []byte(`3333`), + statusCode: http.StatusBadRequest, + }, + { + name: "validation error", + contentType: "application/json", + body: []byte(`{"login":"s","password":"123456"}`), + statusCode: http.StatusBadRequest, + }, + { + name: "success", + contentType: "application/json", + body: []byte(`{"login":"spqr","password":"123456"}`), + statusCode: http.StatusOK, + }, + { + name: "user exists error", + contentType: "application/json", + body: []byte(`{"login":"spqr","password":"123456"}`), + statusCode: http.StatusConflict, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + rw := httptest.NewRecorder() + req := httptest.NewRequest("POST", "/api/user/register", bytes.NewReader(tt.body)) + authenticate.EXPECT().SetCookie(rw, userUUID).AnyTimes() + req.Header.Add("Content-Type", tt.contentType) + RegisterHandler(user, authenticate)(rw, req) + + resp := rw.Result() + assert.Equal(t, tt.statusCode, resp.StatusCode, "Error http status code") + _ = resp.Body.Close() + }) + } +} diff --git a/internal/logger/logger.go b/internal/logger/logger.go new file mode 100644 index 0000000..516e28e --- /dev/null +++ b/internal/logger/logger.go @@ -0,0 +1,16 @@ +package logger + +import ( + "go.uber.org/zap" + "go.uber.org/zap/zapcore" +) + +func NewLogger(logLevel zapcore.Level) (*zap.Logger, error) { + cfg := zap.NewProductionConfig() + cfg.Level = zap.NewAtomicLevelAt(logLevel) + zl, err := cfg.Build() + if err != nil { + return nil, err + } + return zl, nil +} diff --git a/internal/migrations/20240829113459_create_users_table.sql b/internal/migrations/20240829113459_create_users_table.sql new file mode 100644 index 0000000..f513255 --- /dev/null +++ b/internal/migrations/20240829113459_create_users_table.sql @@ -0,0 +1,23 @@ +-- +goose Up +-- +goose StatementBegin +CREATE TABLE public.users ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + login varchar(255) NOT NULL, + password varchar(60) NOT NULL, + balance numeric(12, 2) DEFAULT 0 NOT NULL CHECK (balance >= 0), + created_at timestamptz DEFAULT now() NOT NULL, + CONSTRAINT users_pkey PRIMARY KEY (id) +); +CREATE UNIQUE INDEX users_login_idx ON public.users (login); + +COMMENT ON COLUMN public.users.id IS 'UUID'; +COMMENT ON COLUMN public.users.login IS 'Логин'; +COMMENT ON COLUMN public.users.password IS 'Пароль'; +COMMENT ON COLUMN public.users.balance IS 'Текущий баланс'; +COMMENT ON COLUMN public.users.created_at IS 'Дата создания'; +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +DROP TABLE public.users; +-- +goose StatementEnd diff --git a/internal/migrations/20240903125144_create_orders_table.sql b/internal/migrations/20240903125144_create_orders_table.sql new file mode 100644 index 0000000..cb5effc --- /dev/null +++ b/internal/migrations/20240903125144_create_orders_table.sql @@ -0,0 +1,37 @@ +-- +goose Up +-- +goose StatementBegin +CREATE TYPE e_order_status AS ENUM ('NEW', 'PROCESSING', 'INVALID', 'PROCESSED'); + +CREATE TABLE public.orders ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + user_id uuid NOT NULL, + number varchar(20) NOT NULL, + status e_order_status DEFAULT 'NEW' NOT NULL, + accrual numeric(12, 2), + created_at timestamptz DEFAULT now() NOT NULL, + updated_at timestamptz, + CONSTRAINT orders_pkey PRIMARY KEY (id), + CONSTRAINT orders_user_id_fkey + FOREIGN KEY (user_id) + REFERENCES public.users(id) + ON DELETE CASCADE +); +CREATE UNIQUE INDEX orders_number_idx ON public.orders (number); +CREATE INDEX orders_user_id_idx ON public.orders (user_id); +CREATE INDEX orders_created_at_idx ON public.orders (created_at DESC); + +COMMENT ON COLUMN public.orders.id IS 'UUID'; +COMMENT ON COLUMN public.orders.user_id IS 'UUID пользователя'; +COMMENT ON COLUMN public.orders.number IS 'Номер заказа'; +COMMENT ON COLUMN public.orders.status IS 'Статус заказа'; +COMMENT ON COLUMN public.orders.accrual IS 'Рассчитанные баллы к начислению'; +COMMENT ON COLUMN public.orders.created_at IS 'Дата создания'; +COMMENT ON COLUMN public.orders.updated_at IS 'Дата последнего обновления'; +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +DROP TABLE public.orders; + +DROP TYPE public.e_order_status; +-- +goose StatementEnd diff --git a/internal/migrations/20240903131837_create_withdrawals_table.sql b/internal/migrations/20240903131837_create_withdrawals_table.sql new file mode 100644 index 0000000..249292e --- /dev/null +++ b/internal/migrations/20240903131837_create_withdrawals_table.sql @@ -0,0 +1,29 @@ +-- +goose Up +-- +goose StatementBegin +CREATE TABLE public.withdrawals ( + id uuid DEFAULT gen_random_uuid() NOT NULL, + user_id uuid NOT NULL, + number varchar(20) NOT NULL, + sum numeric(12, 2) NOT NULL CHECK (sum > 0), + created_at timestamptz DEFAULT now() NOT NULL, + CONSTRAINT withdraw_list_pkey PRIMARY KEY (id), + CONSTRAINT withdrawals_user_id_fkey + FOREIGN KEY (user_id) + REFERENCES public.users(id) + ON DELETE CASCADE +); +CREATE INDEX withdrawals_user_id_idx ON public.withdrawals (user_id); +CREATE INDEX withdrawals_created_at_idx ON public.withdrawals (created_at DESC); +CREATE UNIQUE INDEX withdrawals_number_idx ON public.withdrawals (number); + +COMMENT ON COLUMN public.withdrawals.id IS 'UUID'; +COMMENT ON COLUMN public.withdrawals.user_id IS 'UUID пользователя'; +COMMENT ON COLUMN public.withdrawals.number IS 'Номер заказа'; +COMMENT ON COLUMN public.withdrawals.sum IS 'Сумма баллов к списанию'; +COMMENT ON COLUMN public.withdrawals.created_at IS 'Дата создания'; +-- +goose StatementEnd + +-- +goose Down +-- +goose StatementBegin +DROP TABLE public.withdrawals; +-- +goose StatementEnd diff --git a/internal/server/authenticate.go b/internal/server/authenticate.go new file mode 100644 index 0000000..fc834be --- /dev/null +++ b/internal/server/authenticate.go @@ -0,0 +1,28 @@ +package server + +import ( + "context" + "github.com/spqrcor/gofermart/internal/authenticate" + "go.uber.org/zap" + "net/http" +) + +func authenticateMiddleware(logger *zap.Logger, auth authenticate.Auth) func(next http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + cookie, err := r.Cookie("Authorization") + if err != nil { + http.Error(rw, err.Error(), http.StatusUnauthorized) + return + } + UserID, err := auth.GetUserIDFromCookie(cookie.Value) + if err != nil { + logger.Error(err.Error()) + http.Error(rw, err.Error(), http.StatusInternalServerError) + return + } + ctx := context.WithValue(r.Context(), authenticate.ContextUserID, UserID) + next.ServeHTTP(rw, r.WithContext(ctx)) + }) + } +} diff --git a/internal/server/gzip.go b/internal/server/gzip.go new file mode 100644 index 0000000..7d954ac --- /dev/null +++ b/internal/server/gzip.go @@ -0,0 +1,28 @@ +package server + +import ( + "compress/gzip" + "go.uber.org/zap" + "net/http" +) + +func getBodyMiddleware(logger *zap.Logger) func(next http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + if r.Header.Get(`Content-Encoding`) != `gzip` { + next.ServeHTTP(rw, r) + return + } + gz, err := gzip.NewReader(r.Body) + if err != nil { + logger.Error(err.Error()) + } else { + r.Body = gz + } + if err = gz.Close(); err != nil { + logger.Error(err.Error()) + } + next.ServeHTTP(rw, r) + }) + } +} diff --git a/internal/server/logger.go b/internal/server/logger.go new file mode 100644 index 0000000..81a64f0 --- /dev/null +++ b/internal/server/logger.go @@ -0,0 +1,27 @@ +package server + +import ( + "github.com/go-chi/chi/v5/middleware" + "go.uber.org/zap" + "net/http" + "time" +) + +func loggerMiddleware(logger *zap.Logger) func(next http.Handler) http.Handler { + return func(next http.Handler) http.Handler { + return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) { + start := time.Now() + ww := middleware.NewWrapResponseWriter(rw, r.ProtoMajor) + next.ServeHTTP(ww, r) + duration := time.Since(start) + + logger.Info("HTTP request", + zap.String("method", r.Method), + zap.String("path", r.URL.Path), + zap.Int("status", ww.Status()), + zap.Int("content-length", ww.BytesWritten()), + zap.String("duration", duration.String()), + ) + }) + } +} diff --git a/internal/server/server.go b/internal/server/server.go new file mode 100644 index 0000000..84a11c6 --- /dev/null +++ b/internal/server/server.go @@ -0,0 +1,90 @@ +package server + +import ( + "github.com/go-chi/chi/v5" + "github.com/go-chi/chi/v5/middleware" + "github.com/spqrcor/gofermart/internal/authenticate" + "github.com/spqrcor/gofermart/internal/handlers" + "github.com/spqrcor/gofermart/internal/services" + "go.uber.org/zap" + "net/http" +) + +type HTTPServer struct { + userService services.User + orderService services.Order + withdrawalService services.Withdrawal + logger *zap.Logger + runAddress string + authService authenticate.Auth +} + +func NewServer(opts ...func(*HTTPServer)) *HTTPServer { + server := &HTTPServer{} + for _, opt := range opts { + opt(server) + } + return server +} + +func WithUserService(userService services.User) func(*HTTPServer) { + return func(h *HTTPServer) { + h.userService = userService + } +} + +func WithOrderService(orderService services.Order) func(*HTTPServer) { + return func(h *HTTPServer) { + h.orderService = orderService + } +} + +func WithWithdrawalService(withdrawalService services.Withdrawal) func(*HTTPServer) { + return func(h *HTTPServer) { + h.withdrawalService = withdrawalService + } +} + +func WithLogger(logger *zap.Logger) func(*HTTPServer) { + return func(h *HTTPServer) { + h.logger = logger + } +} + +func WithRunAddress(runAddress string) func(*HTTPServer) { + return func(h *HTTPServer) { + h.runAddress = runAddress + } +} + +func WithAuthService(authService authenticate.Auth) func(*HTTPServer) { + return func(h *HTTPServer) { + h.authService = authService + } +} + +func (s *HTTPServer) Start() error { + r := chi.NewRouter() + r.Use(loggerMiddleware(s.logger)) + r.Use(middleware.Compress(5, "application/json", "text/html")) + r.Use(getBodyMiddleware(s.logger)) + + r.Group(func(r chi.Router) { + r.Post("/api/user/register", handlers.RegisterHandler(s.userService, s.authService)) + r.Post("/api/user/login", handlers.LoginHandler(s.userService, s.authService)) + }) + + r.Group(func(r chi.Router) { + r.Use(authenticateMiddleware(s.logger, s.authService)) + r.Post("/api/user/orders", handlers.AddOrdersHandler(s.orderService)) + r.Get("/api/user/orders", handlers.GetOrdersHandler(s.orderService)) + r.Get("/api/user/balance", handlers.GetBalanceHandler(s.withdrawalService)) + r.Post("/api/user/balance/withdraw", handlers.AddWithdrawalHandler(s.withdrawalService)) + r.Get("/api/user/withdrawals", handlers.GetWithdrawalsHandler(s.withdrawalService)) + }) + + r.HandleFunc(`/*`, func(res http.ResponseWriter, req *http.Request) { + res.WriteHeader(http.StatusBadRequest) + }) + return http.ListenAndServe(s.runAddress, r) +} diff --git a/internal/services/mocks/order.go b/internal/services/mocks/order.go new file mode 100644 index 0000000..502c459 --- /dev/null +++ b/internal/services/mocks/order.go @@ -0,0 +1,94 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: internal/services/order.go + +// Package mocks is a generated GoMock package. +package mocks + +import ( + context "context" + reflect "reflect" + + gomock "github.com/golang/mock/gomock" + services "github.com/spqrcor/gofermart/internal/services" +) + +// MockOrder is a mock of Order interface. +type MockOrder struct { + ctrl *gomock.Controller + recorder *MockOrderMockRecorder +} + +// MockOrderMockRecorder is the mock recorder for MockOrder. +type MockOrderMockRecorder struct { + mock *MockOrder +} + +// NewMockOrder creates a new mock instance. +func NewMockOrder(ctrl *gomock.Controller) *MockOrder { + mock := &MockOrder{ctrl: ctrl} + mock.recorder = &MockOrderMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockOrder) EXPECT() *MockOrderMockRecorder { + return m.recorder +} + +// Add mocks base method. +func (m *MockOrder) Add(ctx context.Context, orderNum string) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Add", ctx, orderNum) + ret0, _ := ret[0].(error) + return ret0 +} + +// Add indicates an expected call of Add. +func (mr *MockOrderMockRecorder) Add(ctx, orderNum interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Add", reflect.TypeOf((*MockOrder)(nil).Add), ctx, orderNum) +} + +// ChangeStatus mocks base method. +func (m *MockOrder) ChangeStatus(ctx context.Context, data services.OrderFromAccrual) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "ChangeStatus", ctx, data) + ret0, _ := ret[0].(error) + return ret0 +} + +// ChangeStatus indicates an expected call of ChangeStatus. +func (mr *MockOrderMockRecorder) ChangeStatus(ctx, data interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ChangeStatus", reflect.TypeOf((*MockOrder)(nil).ChangeStatus), ctx, data) +} + +// GetAll mocks base method. +func (m *MockOrder) GetAll(ctx context.Context) ([]services.OrderData, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAll", ctx) + ret0, _ := ret[0].([]services.OrderData) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetAll indicates an expected call of GetAll. +func (mr *MockOrderMockRecorder) GetAll(ctx interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAll", reflect.TypeOf((*MockOrder)(nil).GetAll), ctx) +} + +// GetUnComplete mocks base method. +func (m *MockOrder) GetUnComplete(ctx context.Context) ([]string, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetUnComplete", ctx) + ret0, _ := ret[0].([]string) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetUnComplete indicates an expected call of GetUnComplete. +func (mr *MockOrderMockRecorder) GetUnComplete(ctx interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetUnComplete", reflect.TypeOf((*MockOrder)(nil).GetUnComplete), ctx) +} diff --git a/internal/services/mocks/user.go b/internal/services/mocks/user.go new file mode 100644 index 0000000..da8c6e1 --- /dev/null +++ b/internal/services/mocks/user.go @@ -0,0 +1,67 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: internal/services/user.go + +// Package mocks is a generated GoMock package. +package mocks + +import ( + context "context" + reflect "reflect" + + gomock "github.com/golang/mock/gomock" + uuid "github.com/google/uuid" + services "github.com/spqrcor/gofermart/internal/services" +) + +// MockUser is a mock of User interface. +type MockUser struct { + ctrl *gomock.Controller + recorder *MockUserMockRecorder +} + +// MockUserMockRecorder is the mock recorder for MockUser. +type MockUserMockRecorder struct { + mock *MockUser +} + +// NewMockUser creates a new mock instance. +func NewMockUser(ctrl *gomock.Controller) *MockUser { + mock := &MockUser{ctrl: ctrl} + mock.recorder = &MockUserMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockUser) EXPECT() *MockUserMockRecorder { + return m.recorder +} + +// Add mocks base method. +func (m *MockUser) Add(ctx context.Context, input services.InputDataUser) (uuid.UUID, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Add", ctx, input) + ret0, _ := ret[0].(uuid.UUID) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Add indicates an expected call of Add. +func (mr *MockUserMockRecorder) Add(ctx, input interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Add", reflect.TypeOf((*MockUser)(nil).Add), ctx, input) +} + +// Login mocks base method. +func (m *MockUser) Login(ctx context.Context, input services.InputDataUser) (uuid.UUID, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Login", ctx, input) + ret0, _ := ret[0].(uuid.UUID) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// Login indicates an expected call of Login. +func (mr *MockUserMockRecorder) Login(ctx, input interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Login", reflect.TypeOf((*MockUser)(nil).Login), ctx, input) +} diff --git a/internal/services/mocks/withdrawal.go b/internal/services/mocks/withdrawal.go new file mode 100644 index 0000000..c4c9f14 --- /dev/null +++ b/internal/services/mocks/withdrawal.go @@ -0,0 +1,80 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: internal/services/withdrawal.go + +// Package mocks is a generated GoMock package. +package mocks + +import ( + context "context" + reflect "reflect" + + gomock "github.com/golang/mock/gomock" + services "github.com/spqrcor/gofermart/internal/services" +) + +// MockWithdrawal is a mock of Withdrawal interface. +type MockWithdrawal struct { + ctrl *gomock.Controller + recorder *MockWithdrawalMockRecorder +} + +// MockWithdrawalMockRecorder is the mock recorder for MockWithdrawal. +type MockWithdrawalMockRecorder struct { + mock *MockWithdrawal +} + +// NewMockWithdrawal creates a new mock instance. +func NewMockWithdrawal(ctrl *gomock.Controller) *MockWithdrawal { + mock := &MockWithdrawal{ctrl: ctrl} + mock.recorder = &MockWithdrawalMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockWithdrawal) EXPECT() *MockWithdrawalMockRecorder { + return m.recorder +} + +// Add mocks base method. +func (m *MockWithdrawal) Add(ctx context.Context, input services.InputWithdrawal) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "Add", ctx, input) + ret0, _ := ret[0].(error) + return ret0 +} + +// Add indicates an expected call of Add. +func (mr *MockWithdrawalMockRecorder) Add(ctx, input interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "Add", reflect.TypeOf((*MockWithdrawal)(nil).Add), ctx, input) +} + +// GetAll mocks base method. +func (m *MockWithdrawal) GetAll(ctx context.Context) ([]services.WithdrawalData, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetAll", ctx) + ret0, _ := ret[0].([]services.WithdrawalData) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetAll indicates an expected call of GetAll. +func (mr *MockWithdrawalMockRecorder) GetAll(ctx interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetAll", reflect.TypeOf((*MockWithdrawal)(nil).GetAll), ctx) +} + +// GetBalance mocks base method. +func (m *MockWithdrawal) GetBalance(ctx context.Context) (services.BalanceInfo, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetBalance", ctx) + ret0, _ := ret[0].(services.BalanceInfo) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetBalance indicates an expected call of GetBalance. +func (mr *MockWithdrawalMockRecorder) GetBalance(ctx interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetBalance", reflect.TypeOf((*MockWithdrawal)(nil).GetBalance), ctx) +} diff --git a/internal/services/order.go b/internal/services/order.go new file mode 100644 index 0000000..d7b7bec --- /dev/null +++ b/internal/services/order.go @@ -0,0 +1,167 @@ +package services + +import ( + "context" + "database/sql" + "fmt" + "github.com/google/uuid" + "github.com/spqrcor/gofermart/internal/authenticate" + "github.com/spqrcor/gofermart/internal/utils" + "go.uber.org/zap" + "time" +) + +const ( + addOrderQuery = "INSERT INTO orders (id, user_id, number) VALUES ($1, $2, $3) ON CONFLICT(number) DO UPDATE SET number = EXCLUDED.number RETURNING id, user_id" + getAllOrdersQuery = "SELECT number, status, accrual, created_at FROM orders WHERE user_id = $1 ORDER BY created_at DESC" + getUnCompleteOrdersQuery = "SELECT number FROM orders WHERE status IN ('NEW', 'PROCESSING') ORDER BY created_at" + updateOrderByNumberQuery = "UPDATE orders SET status = $1, accrual =$2 WHERE number = $3" +) + +type OrderData struct { + Number string `json:"number"` + Status string `json:"status"` + Accrual float64 `json:"accrual,omitempty"` + UploadedAt string `json:"uploaded_at"` +} + +type OrderFromAccrual struct { + Order string `json:"order"` + Status string `json:"status"` + Accrual float64 `json:"accrual,omitempty"` +} + +var ErrOrderAnotherUserExists = fmt.Errorf("order another user exists") +var ErrOrderUserExists = fmt.Errorf("order user exists") +var ErrOrderInvalidFormat = fmt.Errorf("order invalid format") +var ErrOrdersNotFound = fmt.Errorf("orders not found") + +type Order interface { + Add(ctx context.Context, orderNum string) error + GetAll(ctx context.Context) ([]OrderData, error) + GetUnComplete(ctx context.Context) ([]string, error) + ChangeStatus(ctx context.Context, data OrderFromAccrual) error +} + +type OrderService struct { + orderQueue chan string + db *sql.DB + logger *zap.Logger + queryTimeOut time.Duration +} + +func NewOrderService(orderQueue chan string, db *sql.DB, logger *zap.Logger, queryTimeOut time.Duration) *OrderService { + return &OrderService{ + orderQueue: orderQueue, + db: db, logger: logger, + queryTimeOut: queryTimeOut, + } +} + +func (o *OrderService) Add(ctx context.Context, orderNum string) error { + if !utils.IsNumberValid(orderNum) { + return ErrOrderInvalidFormat + } + var baseUserID, baseOrderID string + orderID := uuid.NewString() + + childCtx, cancel := context.WithTimeout(ctx, time.Second*o.queryTimeOut) + defer cancel() + err := o.db.QueryRowContext(childCtx, addOrderQuery, orderID, ctx.Value(authenticate.ContextUserID), orderNum).Scan(&baseOrderID, &baseUserID) + if err != nil { + return err + } + if ctx.Value(authenticate.ContextUserID) != uuid.MustParse(baseUserID) { + return ErrOrderAnotherUserExists + } else if orderID != baseOrderID { + return ErrOrderUserExists + } + o.orderQueue <- orderNum + return nil +} + +func (o *OrderService) GetAll(ctx context.Context) ([]OrderData, error) { + var orders []OrderData + childCtx, cancel := context.WithTimeout(ctx, time.Second*o.queryTimeOut) + defer cancel() + + rows, err := o.db.QueryContext(childCtx, getAllOrdersQuery, ctx.Value(authenticate.ContextUserID)) + if err != nil { + return nil, err + } + defer func() { + if err := rows.Close(); err != nil { + o.logger.Error(err.Error()) + } + if err := rows.Err(); err != nil { + o.logger.Error(err.Error()) + } + }() + + for rows.Next() { + o := OrderData{} + var accrual sql.NullFloat64 + if err = rows.Scan(&o.Number, &o.Status, &accrual, &o.UploadedAt); err != nil { + return nil, err + } + o.Accrual = accrual.Float64 + orders = append(orders, o) + } + + if len(orders) == 0 { + return nil, ErrOrdersNotFound + } + return orders, nil +} + +func (o *OrderService) GetUnComplete(ctx context.Context) ([]string, error) { + var orders []string + + childCtx, cancel := context.WithTimeout(ctx, time.Second*o.queryTimeOut) + defer cancel() + + rows, err := o.db.QueryContext(childCtx, getUnCompleteOrdersQuery) + if err != nil { + return nil, err + } + defer func() { + if err := rows.Close(); err != nil { + o.logger.Error(err.Error()) + } + if err := rows.Err(); err != nil { + o.logger.Error(err.Error()) + } + }() + + for rows.Next() { + var orderNum string + if err = rows.Scan(&orderNum); err != nil { + return nil, err + } + orders = append(orders, orderNum) + } + return orders, nil +} + +func (o *OrderService) ChangeStatus(ctx context.Context, data OrderFromAccrual) error { + childCtx, cancel := context.WithTimeout(ctx, time.Second*o.queryTimeOut) + defer cancel() + + tx, err := o.db.BeginTx(childCtx, nil) + if err != nil { + return err + } + _, err = tx.ExecContext(childCtx, updateOrderByNumberQuery, data.Status, data.Accrual, data.Order) + if err != nil { + _ = tx.Rollback() + return err + } + if data.Accrual > 0 { + _, err = tx.ExecContext(childCtx, updateBalanceByOrderQuery, data.Accrual, data.Order) + if err != nil { + _ = tx.Rollback() + return err + } + } + return tx.Commit() +} diff --git a/internal/services/user.go b/internal/services/user.go new file mode 100644 index 0000000..c51fdc7 --- /dev/null +++ b/internal/services/user.go @@ -0,0 +1,105 @@ +package services + +import ( + "context" + "database/sql" + "errors" + "fmt" + "github.com/google/uuid" + "golang.org/x/crypto/bcrypt" + "time" +) + +var ErrLogin = fmt.Errorf("login error") +var ErrLoginExists = fmt.Errorf("login exists") +var ErrValidation = fmt.Errorf("validation error") +var ErrGeneratePassword = fmt.Errorf("generate password error") + +const ( + minPasswordLength = 6 + maxPasswordLength = 72 + minLoginLength = 3 + maxLoginLength = 255 +) + +const ( + addUserQuery = "INSERT INTO users (id, login, password) VALUES ($1, $2, $3) ON CONFLICT(login) DO UPDATE SET login = EXCLUDED.login RETURNING id" + getUserByLoginQuery = "SELECT id, password FROM users WHERE login = $1" + updateBalanceByOrderQuery = "UPDATE users SET balance = balance + $1 WHERE id = (SELECT user_id FROM orders WHERE number = $2)" + updateBalanceByIDQuery = "UPDATE users SET balance = balance - $2 WHERE id = $1" +) + +type InputDataUser struct { + Login string `json:"login"` + Password string `json:"password"` +} + +type User interface { + Add(ctx context.Context, input InputDataUser) (uuid.UUID, error) + Login(ctx context.Context, input InputDataUser) (uuid.UUID, error) +} + +type UserService struct { + db *sql.DB + queryTimeOut time.Duration +} + +func NewUserService(db *sql.DB, queryTimeOut time.Duration) *UserService { + return &UserService{ + db: db, + queryTimeOut: queryTimeOut, + } +} + +func (u *UserService) Add(ctx context.Context, input InputDataUser) (uuid.UUID, error) { + if err := validate(input); err != nil { + return uuid.Nil, err + } + bytes, err := bcrypt.GenerateFromPassword([]byte(input.Password), 14) + if err != nil { + return uuid.Nil, errors.Join(ErrGeneratePassword, err) + } + + baseUserID := "" + userID := uuid.NewString() + childCtx, cancel := context.WithTimeout(ctx, time.Second*u.queryTimeOut) + defer cancel() + err = u.db.QueryRowContext(childCtx, addUserQuery, userID, input.Login, string(bytes)).Scan(&baseUserID) + if err != nil { + return uuid.Nil, err + } + if userID != baseUserID { + return uuid.Nil, ErrLoginExists + } + return uuid.MustParse(baseUserID), nil +} + +func (u *UserService) Login(ctx context.Context, input InputDataUser) (uuid.UUID, error) { + childCtx, cancel := context.WithTimeout(ctx, time.Second*u.queryTimeOut) + defer cancel() + row := u.db.QueryRowContext(childCtx, getUserByLoginQuery, input.Login) + + var userID, password string + err := row.Scan(&userID, &password) + if errors.Is(err, sql.ErrNoRows) { + return uuid.Nil, ErrLogin + } + if err != nil { + return uuid.Nil, err + } + + if err := bcrypt.CompareHashAndPassword([]byte(password), []byte(input.Password)); err != nil { + return uuid.Nil, ErrLogin + } + return uuid.MustParse(userID), nil +} + +func validate(input InputDataUser) error { + if (len(input.Login) < minLoginLength) || (len(input.Login) > maxLoginLength) { + return fmt.Errorf("%w: ошибка при заполнении login, корректная длина от 3 до 255", ErrValidation) + } + if (len(input.Password) < minPasswordLength) || (len(input.Password) > maxPasswordLength) { + return fmt.Errorf("%w: ошибка при заполнении password, корректная длина от 6 до 72", ErrValidation) + } + return nil +} diff --git a/internal/services/withdrawal.go b/internal/services/withdrawal.go new file mode 100644 index 0000000..96f48c0 --- /dev/null +++ b/internal/services/withdrawal.go @@ -0,0 +1,136 @@ +package services + +import ( + "context" + "database/sql" + "errors" + "fmt" + "github.com/jackc/pgx/v5/pgconn" + "github.com/spqrcor/gofermart/internal/authenticate" + "github.com/spqrcor/gofermart/internal/utils" + "go.uber.org/zap" + "time" +) + +const ( + addWithdrawalQuery = "INSERT INTO withdrawals (user_id, number, sum) VALUES ($1, $2, $3) RETURNING id" + getAllWithdrawalsQuery = "SELECT number, sum, created_at FROM withdrawals WHERE user_id = $1 ORDER BY created_at DESC" + getBalanceQuery = "SELECT balance, (SELECT COALESCE(SUM(w.sum), 0) FROM withdrawals w WHERE w.user_id = u.id) FROM users u WHERE id = $1" +) + +type InputWithdrawal struct { + OrderNum string `json:"order"` + Sum float64 `json:"sum"` +} + +type WithdrawalData struct { + OrderNum string `json:"order"` + Sum float64 `json:"sum"` + ProcessedAt string `json:"processed_at"` +} + +type BalanceInfo struct { + Current float64 `json:"current"` + Withdrawn float64 `json:"withdrawn"` +} + +var ErrBalance = fmt.Errorf("balance error") +var ErrWithdrawNotFound = fmt.Errorf("withdraw not found") + +type Withdrawal interface { + Add(ctx context.Context, input InputWithdrawal) error + GetAll(ctx context.Context) ([]WithdrawalData, error) + GetBalance(ctx context.Context) (BalanceInfo, error) +} + +type WithdrawalService struct { + db *sql.DB + logger *zap.Logger + queryTimeOut time.Duration +} + +func NewWithdrawalService(db *sql.DB, logger *zap.Logger, queryTimeOut time.Duration) *WithdrawalService { + return &WithdrawalService{ + db: db, + logger: logger, + queryTimeOut: queryTimeOut, + } +} + +func (w *WithdrawalService) Add(ctx context.Context, input InputWithdrawal) error { + if !utils.IsNumberValid(input.OrderNum) { + return ErrOrderInvalidFormat + } + userID := ctx.Value(authenticate.ContextUserID) + + childCtx, cancel := context.WithTimeout(ctx, time.Second*w.queryTimeOut) + defer cancel() + + tx, err := w.db.BeginTx(childCtx, nil) + if err != nil { + return err + } + _, err = tx.ExecContext(childCtx, updateBalanceByIDQuery, userID, input.Sum) + if err != nil { + _ = tx.Rollback() + var pgError *pgconn.PgError + if errors.As(err, &pgError) && pgError.ConstraintName == "users_balance_check" { + return ErrBalance + } + return err + } + + var withdrawID string + err = tx.QueryRowContext(childCtx, addWithdrawalQuery, userID, input.OrderNum, input.Sum).Scan(&withdrawID) + if err != nil { + _ = tx.Rollback() + if errors.Is(err, sql.ErrNoRows) { + return ErrOrderInvalidFormat + } + return err + } + return tx.Commit() +} + +func (w *WithdrawalService) GetAll(ctx context.Context) ([]WithdrawalData, error) { + var withdrawals []WithdrawalData + childCtx, cancel := context.WithTimeout(ctx, time.Second*w.queryTimeOut) + defer cancel() + + rows, err := w.db.QueryContext(childCtx, getAllWithdrawalsQuery, ctx.Value(authenticate.ContextUserID)) + if err != nil { + return nil, err + } + defer func() { + if err := rows.Close(); err != nil { + w.logger.Error(err.Error()) + } + if err := rows.Err(); err != nil { + w.logger.Error(err.Error()) + } + }() + + for rows.Next() { + w := WithdrawalData{} + if err = rows.Scan(&w.OrderNum, &w.Sum, &w.ProcessedAt); err != nil { + return nil, err + } + withdrawals = append(withdrawals, w) + } + if len(withdrawals) == 0 { + return nil, ErrWithdrawNotFound + } + return withdrawals, nil +} + +func (w *WithdrawalService) GetBalance(ctx context.Context) (BalanceInfo, error) { + balanceInfo := BalanceInfo{} + childCtx, cancel := context.WithTimeout(ctx, time.Second*w.queryTimeOut) + defer cancel() + + row := w.db.QueryRowContext(childCtx, getBalanceQuery, ctx.Value(authenticate.ContextUserID)) + if err := row.Scan(&balanceInfo.Current, &balanceInfo.Withdrawn); err != nil { + return balanceInfo, errors.New("user not found") + } + return balanceInfo, nil +} diff --git a/internal/utils/utils.go b/internal/utils/utils.go new file mode 100644 index 0000000..4e3bdee --- /dev/null +++ b/internal/utils/utils.go @@ -0,0 +1,55 @@ +package utils + +import ( + "bytes" + "encoding/json" + "errors" + "net/http" + "strings" +) + +func FromPostJSON(req *http.Request, input any) error { + if req.Method != http.MethodPost || !strings.Contains(req.Header.Get("Content-Type"), "application/json") { + return errors.New("invalid request") + } + + var buf bytes.Buffer + _, err := buf.ReadFrom(req.Body) + if err != nil { + return err + } + if err = json.Unmarshal(buf.Bytes(), &input); err != nil { + return err + } + return nil +} + +func FromPostPlain(req *http.Request) (string, error) { + if req.Method != http.MethodPost || !strings.Contains(req.Header.Get("Content-Type"), "text/plain") { + return "", errors.New("invalid request") + } + + var buf bytes.Buffer + _, err := buf.ReadFrom(req.Body) + if err != nil { + return "", err + } + return buf.String(), nil +} + +func IsNumberValid(orderNum string) bool { + total := 0 + isSecondDigit := false + for i := len(orderNum) - 1; i >= 0; i-- { + digit := int(orderNum[i] - '0') + if isSecondDigit { + digit *= 2 + if digit > 9 { + digit -= 9 + } + } + total += digit + isSecondDigit = !isSecondDigit + } + return total%10 == 0 +} diff --git a/internal/workers/order.go b/internal/workers/order.go new file mode 100644 index 0000000..a6703af --- /dev/null +++ b/internal/workers/order.go @@ -0,0 +1,123 @@ +package workers + +import ( + "context" + "fmt" + "github.com/spqrcor/gofermart/internal/client" + "github.com/spqrcor/gofermart/internal/config" + "github.com/spqrcor/gofermart/internal/services" + "go.uber.org/zap" + "time" +) + +type OrderWorker struct { + ctx context.Context + orderService services.Order + orderQueue chan string + logger *zap.Logger + conf config.Config + orderClient client.OrderClient +} + +func NewOrderWorker(opts ...func(*OrderWorker)) *OrderWorker { + orderWorker := &OrderWorker{ + ctx: context.Background(), + } + for _, opt := range opts { + opt(orderWorker) + } + return orderWorker +} + +func WithCtx(ctx context.Context) func(*OrderWorker) { + return func(o *OrderWorker) { + o.ctx = ctx + } +} + +func WithOrderService(orderService services.Order) func(*OrderWorker) { + return func(o *OrderWorker) { + o.orderService = orderService + } +} + +func WithOrderQueue(orderQueue chan string) func(*OrderWorker) { + return func(o *OrderWorker) { + o.orderQueue = orderQueue + } +} + +func WithLogger(logger *zap.Logger) func(*OrderWorker) { + return func(o *OrderWorker) { + o.logger = logger + } +} + +func WithConfig(conf config.Config) func(*OrderWorker) { + return func(o *OrderWorker) { + o.conf = conf + } +} + +func WithOrderClient(orderClient client.OrderClient) func(*OrderWorker) { + return func(o *OrderWorker) { + o.orderClient = orderClient + } +} + +func (w *OrderWorker) Run() { + retryCount := 0 + go w.fillQueue() + for i := 1; i <= w.conf.WorkerCount; i++ { + errorCh := w.worker() + + go func() { + for err := range errorCh { + if err != nil && retryCount < w.conf.RetryStartWorkerCount { + w.worker() + retryCount++ + } + } + }() + } +} + +func (w *OrderWorker) fillQueue() { + orders, _ := w.orderService.GetUnComplete(w.ctx) + for _, orderNum := range orders { + w.orderQueue <- orderNum + } +} + +func (w *OrderWorker) worker() chan error { + errors := make(chan error) + go func() { + defer close(errors) + for { + select { + case <-w.ctx.Done(): + return + case orderNum, ok := <-w.orderQueue: + if !ok { + w.logger.Info("order queue is closed") + errors <- fmt.Errorf("order queue is closed") + return + } + + result, sleepSeconds, err := w.orderClient.CheckOrder(orderNum) + if err != nil { + w.logger.Info(err.Error()) + } else { + if err := w.orderService.ChangeStatus(w.ctx, result); err != nil { + w.logger.Info(err.Error()) + } + } + + if sleepSeconds > 0 { + time.Sleep(time.Duration(sleepSeconds) * time.Second) + } + } + } + }() + return errors +} diff --git a/test/integration_test.go b/test/integration_test.go new file mode 100644 index 0000000..1bee502 --- /dev/null +++ b/test/integration_test.go @@ -0,0 +1,206 @@ +package tests + +import ( + "context" + "github.com/brianvoe/gofakeit/v7" + "github.com/gavv/httpexpect/v2" + "github.com/spqrcor/gofermart/internal/config" + "github.com/spqrcor/gofermart/internal/db" + "github.com/spqrcor/gofermart/internal/logger" + "github.com/spqrcor/gofermart/internal/services" + "log" + "net/http" + "net/url" + "testing" + "time" +) + +func TestIntegration(t *testing.T) { + login := gofakeit.Email() + password := gofakeit.Password(true, true, true, true, false, 10) + + conf := config.NewConfig() + loggerRes, err := logger.NewLogger(conf.LogLevel) + if err != nil { + log.Fatal(err) + } + dbRes, err := db.NewDB(loggerRes, conf.DatabaseURI) + if err != nil { + loggerRes.Fatal(err.Error()) + } + + orderQueue := make(chan string) + defer close(orderQueue) + orderService := services.NewOrderService(orderQueue, dbRes, loggerRes, conf.QueryTimeOut) + + u := url.URL{ + Scheme: "http", + Host: conf.RunAddr, + } + e := httpexpect.Default(t, u.String()) + + t.Run("register not post", func(t *testing.T) { + e.GET("/api/user/register"). + Expect(). + Status(http.StatusBadRequest) + }) + + t.Run("register short password", func(t *testing.T) { + e.POST("/api/user/register"). + WithJSON(services.InputDataUser{ + Login: login, + Password: "333", + }). + Expect(). + Status(http.StatusBadRequest) + }) + + t.Run("register short login", func(t *testing.T) { + e.POST("/api/user/register"). + WithJSON(services.InputDataUser{ + Login: "l", + Password: password, + }). + Expect(). + Status(http.StatusBadRequest) + }) + + t.Run("success register", func(t *testing.T) { + e.POST("/api/user/register"). + WithJSON(services.InputDataUser{ + Login: login, + Password: password, + }). + Expect(). + Status(http.StatusOK) + }) + + t.Run("user exists", func(t *testing.T) { + e.POST("/api/user/register"). + WithJSON(services.InputDataUser{ + Login: login, + Password: password, + }). + Expect(). + Status(http.StatusConflict) + }) + + t.Run("bad login or password", func(t *testing.T) { + e.POST("/api/user/login"). + WithJSON(services.InputDataUser{ + Login: login, + Password: "333", + }). + Expect(). + Status(http.StatusUnauthorized) + }) + + t.Run("success login", func(t *testing.T) { + e.POST("/api/user/login"). + WithJSON(services.InputDataUser{ + Login: login, + Password: password, + }). + Expect(). + Status(http.StatusOK) + }) + + t.Run("get orders no content", func(t *testing.T) { + e.GET("/api/user/orders"). + Expect(). + Status(http.StatusNoContent) + }) + + t.Run("add order format error", func(t *testing.T) { + e.POST("/api/user/orders"). + WithText("343"). + Expect(). + Status(http.StatusUnprocessableEntity) + }) + + t.Run("add order success", func(t *testing.T) { + e.POST("/api/user/orders"). + WithText("9399142970086005"). + Expect(). + Status(http.StatusAccepted) + }) + + t.Run("add order exists", func(t *testing.T) { + e.POST("/api/user/orders"). + WithText("9399142970086005"). + Expect(). + Status(http.StatusOK) + }) + + t.Run("get orders have content", func(t *testing.T) { + e.GET("/api/user/orders"). + Expect(). + Status(http.StatusOK) + }) + + t.Run("get balance zero", func(t *testing.T) { + e.GET("/api/user/balance"). + Expect(). + Status(http.StatusOK). + JSON().Object(). + ContainsKey("current").HasValue("current", 0). + ContainsKey("withdrawn").HasValue("withdrawn", 0) + }) + + t.Run("get withdrawals no content", func(t *testing.T) { + e.GET("/api/user/withdrawals"). + Expect(). + Status(http.StatusNoContent) + }) + + t.Run("add withdraw balance error", func(t *testing.T) { + e.POST("/api/user/balance/withdraw"). + WithJSON(services.InputWithdrawal{ + OrderNum: "9399142970086005", + Sum: 100, + }). + Expect(). + Status(http.StatusPaymentRequired) + }) + + t.Run("add withdraw order format error", func(t *testing.T) { + e.POST("/api/user/balance/withdraw"). + WithJSON(services.InputWithdrawal{ + OrderNum: "333", + Sum: 100, + }). + Expect(). + Status(http.StatusUnprocessableEntity) + }) + + _ = orderService.ChangeStatus(context.Background(), services.OrderFromAccrual{Status: "PROCESSED", Order: "9399142970086005", Accrual: 500}) + + t.Run("add withdraw success", func(t *testing.T) { + e.POST("/api/user/balance/withdraw"). + WithJSON(services.InputWithdrawal{ + OrderNum: "9399142970086005", + Sum: 100, + }). + Expect(). + Status(http.StatusOK) + }) + + t.Run("get withdrawals content exists", func(t *testing.T) { + e.GET("/api/user/withdrawals"). + Expect(). + Status(http.StatusOK) + }) + + t.Run("get balance not zero", func(t *testing.T) { + e.GET("/api/user/balance"). + Expect(). + Status(http.StatusOK). + JSON().Object(). + ContainsKey("current").HasValue("current", 400). + ContainsKey("withdrawn").HasValue("withdrawn", 100) + }) + + childCtx, cancel := context.WithTimeout(context.Background(), time.Second*3) + defer cancel() + _ = dbRes.QueryRowContext(childCtx, "DELETE FROM users WHERE login = $1", login) +}