diff --git a/go.work b/go.work index 1305ca9..e3a55cb 100644 --- a/go.work +++ b/go.work @@ -4,9 +4,11 @@ use ( . ./libraries/test ./services/game-player-data + ./services/game-tracker ./services/matchmaker ./services/mc-player-service ./services/message-handler + ./services/party-manager ./services/permission-service ./services/relationship-manager ) diff --git a/services/game-tracker/Dockerfile b/services/game-tracker/Dockerfile new file mode 100644 index 0000000..8b85b7b --- /dev/null +++ b/services/game-tracker/Dockerfile @@ -0,0 +1,33 @@ +FROM --platform=$BUILDPLATFORM golang:1.23-alpine AS build + +ARG SERVICE_NAME=game-tracker + +WORKDIR /build + +# Copy sources +COPY . . + +WORKDIR /build/services/$SERVICE_NAME + +RUN go mod download + +WORKDIR /build + +ARG TARGETOS +ARG TARGETARCH + +RUN --mount=type=cache,target=/root/.cache/go-build \ + --mount=type=cache,target=/go/pkg \ + CGO_ENABLED=0 \ + GOOS=$TARGETOS \ + GOARCH=$TARGETARCH \ + go build -ldflags="-s -w" -o $SERVICE_NAME ./services/$SERVICE_NAME/cmd/$SERVICE_NAME + +FROM alpine + +ARG SERVICE_NAME=game-tracker + +WORKDIR /app + +COPY --from=build /build/$SERVICE_NAME /build/services/$SERVICE_NAME/run ./ +CMD ["./game-tracker"] \ No newline at end of file diff --git a/services/game-tracker/cmd/game-tracker/game_tracker.go b/services/game-tracker/cmd/game-tracker/game_tracker.go new file mode 100644 index 0000000..2086b0d --- /dev/null +++ b/services/game-tracker/cmd/game-tracker/game_tracker.go @@ -0,0 +1,32 @@ +package main + +import ( + "github.com/emortalmc/mono-services/services/game-tracker/internal/app" + "github.com/emortalmc/mono-services/services/game-tracker/internal/config" + "go.uber.org/zap" + "log" +) + +func main() { + cfg := config.LoadGlobalConfig() + + unsugared, err := createLogger(cfg) + if err != nil { + log.Fatal(err) + } + logger := unsugared.Sugar() + + app.Run(cfg, logger) +} + +func createLogger(cfg config.Config) (logger *zap.Logger, err error) { + if cfg.Development { + logger, err = zap.NewDevelopment() + } else { + logger, err = zap.NewProduction() + } + if err != nil { + return nil, err + } + return logger, nil +} diff --git a/services/game-tracker/go.mod b/services/game-tracker/go.mod new file mode 100644 index 0000000..3a0f586 --- /dev/null +++ b/services/game-tracker/go.mod @@ -0,0 +1,47 @@ +module github.com/emortalmc/mono-services/services/game-tracker + +go 1.23 + +require ( + github.com/emortalmc/proto-specs/gen/go v0.0.0-20240927103241-2584fd28e0f9 + github.com/google/uuid v1.6.0 + github.com/segmentio/kafka-go v0.4.47 + github.com/spf13/pflag v1.0.5 + github.com/spf13/viper v1.19.0 + go.mongodb.org/mongo-driver v1.17.1 + go.uber.org/zap v1.27.0 + google.golang.org/protobuf v1.35.1 +) + +require ( + github.com/fsnotify/fsnotify v1.7.0 // indirect + github.com/golang/snappy v0.0.4 // indirect + github.com/hashicorp/hcl v1.0.0 // indirect + github.com/klauspost/compress v1.17.2 // indirect + github.com/magiconair/properties v1.8.7 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/montanaflynn/stats v0.7.1 // indirect + github.com/pelletier/go-toml/v2 v2.2.2 // indirect + github.com/pierrec/lz4/v4 v4.1.18 // indirect + github.com/rogpeppe/go-internal v1.10.0 // indirect + github.com/sagikazarmark/locafero v0.4.0 // indirect + github.com/sagikazarmark/slog-shim v0.1.0 // indirect + github.com/sourcegraph/conc v0.3.0 // indirect + github.com/spf13/afero v1.11.0 // indirect + github.com/spf13/cast v1.6.0 // indirect + github.com/subosito/gotenv v1.6.0 // indirect + github.com/xdg-go/pbkdf2 v1.0.0 // indirect + github.com/xdg-go/scram v1.1.2 // indirect + github.com/xdg-go/stringprep v1.0.4 // indirect + github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect + go.uber.org/multierr v1.10.0 // indirect + golang.org/x/crypto v0.26.0 // indirect + golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // 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 + gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect + gopkg.in/ini.v1 v1.67.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/services/game-tracker/go.sum b/services/game-tracker/go.sum new file mode 100644 index 0000000..271d467 --- /dev/null +++ b/services/game-tracker/go.sum @@ -0,0 +1,149 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/emortalmc/proto-specs/gen/go v0.0.0-20240927103241-2584fd28e0f9 h1:6xOnWrTvG2oJR1J6+B+tdZV5GdlbIgdQixdCCyfj4nA= +github.com/emortalmc/proto-specs/gen/go v0.0.0-20240927103241-2584fd28e0f9/go.mod h1:se+tHcK9FWxeadkxLF5uj+SPauEye0X+Iq6cGczXGJY= +github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= +github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= +github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +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/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= +github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +github.com/klauspost/compress v1.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU= +github.com/klauspost/compress v1.17.2 h1:RlWWUY/Dr4fL8qk9YG7DTZ7PDgME2V4csBXA8L/ixi4= +github.com/klauspost/compress v1.17.2/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +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/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= +github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/montanaflynn/stats v0.7.1 h1:etflOAAHORrCC44V+aR6Ftzort912ZU+YLiSTuV8eaE= +github.com/montanaflynn/stats v0.7.1/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow= +github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= +github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= +github.com/pierrec/lz4/v4 v4.1.15/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= +github.com/pierrec/lz4/v4 v4.1.18 h1:xaKrnTkyoqfh1YItXl56+6KJNVYWlEEPuAQW9xsplYQ= +github.com/pierrec/lz4/v4 v4.1.18/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= +github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ= +github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4= +github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= +github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= +github.com/segmentio/kafka-go v0.4.47 h1:IqziR4pA3vrZq7YdRxaT3w1/5fvIH5qpCwstUanQQB0= +github.com/segmentio/kafka-go v0.4.47/go.mod h1:HjF6XbOKh0Pjlkr5GVZxt6CsjjwnmhVOfURM5KMd8qg= +github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= +github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= +github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= +github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= +github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0= +github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI= +github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+Ntkg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +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/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= +github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= +github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c= +github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= +github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY= +github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4= +github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8= +github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= +github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM= +github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI= +github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +go.mongodb.org/mongo-driver v1.17.1 h1:Wic5cJIwJgSpBhe3lx3+/RybR5PiYRMpVFgO7cOHyIM= +go.mongodb.org/mongo-driver v1.17.1/go.mod h1:wwWm/+BuOddhcq3n68LKRmgk2wXzmF6s0SFOa0GINL4= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ= +go.uber.org/multierr v1.10.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-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= +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-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g= +golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= +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/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/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-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= +golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= +golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/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-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.13.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/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U= +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.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +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-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v1.35.1 h1:m3LfL6/Ca+fqnjnlqQXNpFPABW1UD7mjh8KO2mKFytA= +google.golang.org/protobuf v1.35.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= +gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +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= diff --git a/services/game-tracker/internal/app/game_tracker.go b/services/game-tracker/internal/app/game_tracker.go new file mode 100644 index 0000000..6e3c060 --- /dev/null +++ b/services/game-tracker/internal/app/game_tracker.go @@ -0,0 +1,37 @@ +package app + +import ( + "context" + "github.com/emortalmc/mono-services/services/game-tracker/internal/config" + "github.com/emortalmc/mono-services/services/game-tracker/internal/kafka" + "github.com/emortalmc/mono-services/services/game-tracker/internal/repository" + "go.uber.org/zap" + "os/signal" + "sync" + "syscall" +) + +func Run(cfg config.Config, logger *zap.SugaredLogger) { + ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer cancel() + wg := &sync.WaitGroup{} + + repoWg := &sync.WaitGroup{} + repoCtx, repoCancel := context.WithCancel(ctx) + + repo, err := repository.NewMongoRepository(repoCtx, logger, repoWg, cfg.MongoDB) + if err != nil { + logger.Fatalw("failed to create repository", err) + } + + kafka.NewConsumer(ctx, wg, cfg.Kafka, logger, repo) + + //service.RunServices(ctx, logger, wg, cfg, repo) todo: add services + + wg.Wait() + logger.Info("shutting down") + + logger.Info("shutting down repository") + repoCancel() + repoWg.Wait() +} diff --git a/services/game-tracker/internal/config/global.go b/services/game-tracker/internal/config/global.go new file mode 100644 index 0000000..045d890 --- /dev/null +++ b/services/game-tracker/internal/config/global.go @@ -0,0 +1,69 @@ +package config + +import ( + "github.com/emortalmc/mono-services/services/game-tracker/internal/utils/runtime" + "github.com/spf13/pflag" + "github.com/spf13/viper" + "strings" +) + +const ( + kafkaHostFlag = "kafka-host" + kafkaPortFlag = "kafka-port" + mongoDBURIFlag = "mongodb-uri" + developmentFlag = "development" + grpcPortFlag = "port" +) + +func LoadGlobalConfig() Config { + viper.SetDefault(kafkaHostFlag, "localhost") + viper.SetDefault(kafkaPortFlag, 9092) + viper.SetDefault(mongoDBURIFlag, "mongodb://localhost:27017") + viper.SetDefault(developmentFlag, true) + viper.SetDefault(grpcPortFlag, 10010) + + pflag.String(kafkaHostFlag, viper.GetString(kafkaHostFlag), "Kafka host") + pflag.Int32(kafkaPortFlag, viper.GetInt32(kafkaPortFlag), "Kafka port") + pflag.String(mongoDBURIFlag, viper.GetString(mongoDBURIFlag), "MongoDB URI") + pflag.Bool(developmentFlag, viper.GetBool(developmentFlag), "Development mode") + pflag.Int32(grpcPortFlag, viper.GetInt32(grpcPortFlag), "gRPC port") + pflag.Parse() + + // Bind the viper flags to environment variables + viper.SetEnvKeyReplacer(strings.NewReplacer("-", "_")) + runtime.Must(viper.BindEnv(kafkaHostFlag)) + runtime.Must(viper.BindEnv(kafkaPortFlag)) + runtime.Must(viper.BindEnv(mongoDBURIFlag)) + runtime.Must(viper.BindEnv(developmentFlag)) + runtime.Must(viper.BindEnv(grpcPortFlag)) + + return Config{ + Kafka: KafkaConfig{ + Host: viper.GetString(kafkaHostFlag), + Port: int(viper.GetInt32(kafkaPortFlag)), + }, + MongoDB: MongoDBConfig{ + URI: viper.GetString(mongoDBURIFlag), + }, + Development: viper.GetBool(developmentFlag), + GRPCPort: int(viper.GetInt32(grpcPortFlag)), + } +} + +type Config struct { + Kafka KafkaConfig + MongoDB MongoDBConfig + + Development bool + + GRPCPort int +} + +type KafkaConfig struct { + Host string + Port int +} + +type MongoDBConfig struct { + URI string +} diff --git a/services/game-tracker/internal/kafka/consumer.go b/services/game-tracker/internal/kafka/consumer.go new file mode 100644 index 0000000..c7ea174 --- /dev/null +++ b/services/game-tracker/internal/kafka/consumer.go @@ -0,0 +1,252 @@ +package kafka + +import ( + "context" + "fmt" + "github.com/emortalmc/mono-services/services/game-tracker/internal/config" + "github.com/emortalmc/mono-services/services/game-tracker/internal/parsers" + "github.com/emortalmc/mono-services/services/game-tracker/internal/repository" + "github.com/emortalmc/mono-services/services/game-tracker/internal/repository/model" + "github.com/emortalmc/mono-services/services/game-tracker/internal/utils" + "github.com/emortalmc/proto-specs/gen/go/message/gametracker" + "github.com/emortalmc/proto-specs/gen/go/nongenerated/kafkautils" + "github.com/segmentio/kafka-go" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.uber.org/zap" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/anypb" + "strings" + "sync" + "time" +) + +const gamesTopic = "game-tracker" + +type consumer struct { + logger *zap.SugaredLogger + repo repository.Repository + + reader *kafka.Reader + + liveHandler *parserHandler[model.LiveGame] + historicHandler *parserHandler[model.HistoricGame] +} + +func NewConsumer(ctx context.Context, wg *sync.WaitGroup, cfg config.KafkaConfig, logger *zap.SugaredLogger, + repo repository.Repository) { + + reader := kafka.NewReader(kafka.ReaderConfig{ + Brokers: []string{cfg.Host}, + GroupID: "game-tracker", + GroupTopics: []string{gamesTopic}, + + Logger: kafkautils.CreateLogger(logger), + ErrorLogger: kafkautils.CreateErrorLogger(logger), + }) + + c := &consumer{ + logger: logger, + repo: repo, + + reader: reader, + + liveHandler: &parserHandler[model.LiveGame]{logger: logger, parsers: parsers.LiveParsers}, + historicHandler: &parserHandler[model.HistoricGame]{logger: logger, parsers: parsers.HistoricParsers}, + } + + handler := kafkautils.NewConsumerHandler(logger, reader) + handler.RegisterHandler(&gametracker.GameStartMessage{}, c.handleGameStartMessage) + handler.RegisterHandler(&gametracker.GameUpdateMessage{}, c.handleGameUpdateMessage) + handler.RegisterHandler(&gametracker.GameFinishMessage{}, c.handleGameFinishMessage) + + logger.Infow("started listening for kafka messages", "topics", reader.Config().GroupTopics) + + wg.Add(1) + go func() { + defer wg.Done() + handler.Run(ctx) // Run is blocking until the context is cancelled + if err := reader.Close(); err != nil { + logger.Errorw("failed to close kafka reader", err) + } + }() +} + +func (c *consumer) handleGameStartMessage(ctx context.Context, _ *kafka.Message, uncastMsg proto.Message) { + m := uncastMsg.(*gametracker.GameStartMessage) + commonData := m.CommonData + + id, err := primitive.ObjectIDFromHex(commonData.GameId) + if err != nil { + c.logger.Errorw("failed to parse game id", "gameId", commonData.GameId) + return + } + + players, err := model.BasicPlayersFromProto(commonData.Players) + if err != nil { + c.logger.Errorw("failed to parse players", "players", commonData.Players) + return + } + + liveGame := &model.LiveGame{ + Game: &model.Game{ + Id: id, + GameModeId: commonData.GameModeId, + ServerId: commonData.ServerId, + StartTime: utils.Pointer(m.StartTime.AsTime()), + Players: players, + }, + LastUpdated: time.Now(), + } + + if err := c.liveHandler.handle(m.Content, liveGame); err != nil { + c.logger.Errorw("failed to handle game content", "game", commonData.GameId, "content", m.Content) + return + } + + if err := c.repo.SaveLiveGame(ctx, liveGame); err != nil { + c.logger.Errorw("failed to save live game", "game", liveGame, "error", err) + return + } +} + +func (c *consumer) handleGameUpdateMessage(ctx context.Context, _ *kafka.Message, uncastMsg proto.Message) { + m := uncastMsg.(*gametracker.GameUpdateMessage) + commonData := m.CommonData + + id, err := primitive.ObjectIDFromHex(commonData.GameId) + if err != nil { + c.logger.Errorw("failed to parse game id", "gameId", commonData.GameId) + return + } + + liveGame, err := c.repo.GetLiveGame(ctx, id) + if err != nil { + c.logger.Errorw("failed to get live game", "gameId", id.Hex(), err) + return + } + + // common data start + + players, err := model.BasicPlayersFromProto(commonData.Players) + if err != nil { + c.logger.Errorw("failed to parse players", "players", commonData.Players) + return + } + + liveGame.Players = players + liveGame.LastUpdated = time.Now() + + // common data end + + if err := c.liveHandler.handle(m.Content, liveGame); err != nil { + c.logger.Errorw("failed to handle game content", "game", commonData.GameId, "content", m.Content) + return + } + + if err := c.repo.SaveLiveGame(ctx, liveGame); err != nil { + c.logger.Errorw("failed to save live game", "game", liveGame, "error", err) + } +} + +func (c *consumer) handleGameFinishMessage(ctx context.Context, _ *kafka.Message, uncastMsg proto.Message) { + m := uncastMsg.(*gametracker.GameFinishMessage) + commonData := m.CommonData + + id, err := primitive.ObjectIDFromHex(commonData.GameId) + if err != nil { + c.logger.Errorw("failed to parse game id", "gameId", commonData.GameId) + return + } + + liveGame, err := c.repo.GetLiveGame(ctx, id) + if err != nil { + c.logger.Errorw("failed to get live game", "game", id, "error", err) + return + } + + if err := c.repo.DeleteLiveGame(ctx, id); err != nil { + c.logger.Errorw("failed to delete live game", "game", id, "error", err) + return + } + + players, err := model.BasicPlayersFromProto(commonData.Players) + if err != nil { + c.logger.Errorw("failed to parse players", "players", commonData.Players) + return + } + + game := &model.HistoricGame{ + Game: &model.Game{ + Id: id, + GameModeId: commonData.GameModeId, + ServerId: commonData.ServerId, + StartTime: liveGame.StartTime, + Players: players, + }, + EndTime: m.EndTime.AsTime(), + } + + if err := c.historicHandler.handle(m.Content, game); err != nil { + c.logger.Errorw("failed to handle game content", "error", err, "game", commonData.GameId, "content", m.Content) + return + } + + if err := c.repo.SaveHistoricGame(ctx, game); err != nil { + c.logger.Errorw("failed to save historic game", "game", game, "error", err) + } +} + +type parserHandler[T model.IGame] struct { + logger *zap.SugaredLogger + + parsers map[proto.Message]func(data proto.Message, game *T) error +} + +func (h *parserHandler[T]) handle(content []*anypb.Any, g *T) error { + unhandledIndexes := make([]bool, len(content)) // every index is false by default + + for i, anyPb := range content { + anyFullName := strings.SplitAfter(anyPb.TypeUrl, "type.googleapis.com/")[1] + + for key, parser := range h.parsers { + if anyFullName == string(key.ProtoReflect().Descriptor().FullName()) { + unmarshaled := key + if err := anyPb.UnmarshalTo(unmarshaled); err != nil { + return fmt.Errorf("failed to unmarshal game content: %w", err) + } + + if err := parser(unmarshaled, g); err != nil { + return fmt.Errorf("failed to parse game content: %w", err) + } + + unhandledIndexes[i] = true + break + } + } + + for key, parser := range parsers.DualParsers { + if anyFullName == string(key.ProtoReflect().Descriptor().FullName()) { + unmarshaled := key + if err := anyPb.UnmarshalTo(unmarshaled); err != nil { + return fmt.Errorf("failed to unmarshal game content: %w", err) + } + + if err := parser(unmarshaled, (*g).GetGame()); err != nil { + return fmt.Errorf("failed to parse game content: %w", err) + } + + unhandledIndexes[i] = true + break + } + } + } + + // check every index has been processed and warn if not + for i, b := range unhandledIndexes { + if !b { + h.logger.Warnw("unhandled game content index", "index", i, "game", g, "content", content) + } + } + + return nil +} diff --git a/services/game-tracker/internal/parsers/common_parsers.go b/services/game-tracker/internal/parsers/common_parsers.go new file mode 100644 index 0000000..08be460 --- /dev/null +++ b/services/game-tracker/internal/parsers/common_parsers.go @@ -0,0 +1,38 @@ +package parsers + +import ( + "github.com/emortalmc/mono-services/services/game-tracker/internal/repository/model" + pbmodel "github.com/emortalmc/proto-specs/gen/go/model/gametracker" + "google.golang.org/protobuf/proto" +) + +func parseGameTeamData(m proto.Message, g *model.Game) error { + cast := m.(*pbmodel.CommonGameTeamData) + + teams := make([]*model.Team, len(cast.Teams)) + for i, t := range cast.Teams { + parsed, err := model.TeamFromProto(t) + if err != nil { + return err + } + + teams[i] = parsed + } + + g.TeamData = &teams + + return nil +} + +func parseGameFinishWinnerData(m proto.Message, g *model.HistoricGame) error { + cast := m.(*pbmodel.CommonGameFinishWinnerData) + + d, err := model.HistoricWinnerDataFromProto(cast) + if err != nil { + return err + } + + g.WinnerData = d + + return nil +} diff --git a/services/game-tracker/internal/parsers/game_parsers.go b/services/game-tracker/internal/parsers/game_parsers.go new file mode 100644 index 0000000..f1b49ff --- /dev/null +++ b/services/game-tracker/internal/parsers/game_parsers.go @@ -0,0 +1,67 @@ +package parsers + +import ( + "fmt" + "github.com/emortalmc/mono-services/services/game-tracker/internal/repository/model" + pbmodel "github.com/emortalmc/proto-specs/gen/go/model/gametracker" + "google.golang.org/protobuf/proto" +) + +func handleTowerDefenceStartData(m proto.Message, g *model.LiveGame) error { + cast := m.(*pbmodel.TowerDefenceStartData) + g.SetGameData(model.CreateLiveTowerDefenceDataFromStart(cast)) + + return nil +} + +func handleTowerDefenceUpdateData(m proto.Message, g *model.LiveGame) error { + cast := m.(*pbmodel.TowerDefenceUpdateData) + + (g.GameData).(*model.LiveTowerDefenceData).Update(cast) + + return nil +} + +func handleTowerDefenceFinishData(m proto.Message, g *model.HistoricGame) error { + cast := m.(*pbmodel.TowerDefenceFinishData) + + g.GameData = model.CreateHistoricTowerDefenceDataFromFinish(cast) + + return nil +} + +// Block Sumo + +func handleBlockSumoUpdateData(m proto.Message, g *model.LiveGame) error { + cast := m.(*pbmodel.BlockSumoUpdateData) + + if g.GameData == nil { + newData, err := model.CreateLiveBlockSumoDataFromUpdate(cast) + + if err != nil { + return fmt.Errorf("failed to create new live block sumo data: %w", err) + } + + g.SetGameData(newData) + return nil + } + + if err := g.GameData.(*model.LiveBlockSumoData).Update(cast); err != nil { + return err + } + + return nil +} + +func handleBlockSumoFinishData(m proto.Message, g *model.HistoricGame) error { + cast := m.(*pbmodel.BlockSumoFinishData) + + data, err := model.CreateHistoricBlockSumoDataFromFinish(cast) + if err != nil { + return fmt.Errorf("failed to create historic block sumo data: %w", err) + } + + g.GameData = data + + return nil +} diff --git a/services/game-tracker/internal/parsers/public.go b/services/game-tracker/internal/parsers/public.go new file mode 100644 index 0000000..e1feb17 --- /dev/null +++ b/services/game-tracker/internal/parsers/public.go @@ -0,0 +1,28 @@ +package parsers + +import ( + "github.com/emortalmc/mono-services/services/game-tracker/internal/repository/model" + pbmodel "github.com/emortalmc/proto-specs/gen/go/model/gametracker" + "google.golang.org/protobuf/proto" +) + +var DualParsers = map[proto.Message]func(data proto.Message, g *model.Game) error{ + // Common + &pbmodel.CommonGameTeamData{}: parseGameTeamData, +} + +var LiveParsers = map[proto.Message]func(data proto.Message, g *model.LiveGame) error{ + // TowerDefence + &pbmodel.TowerDefenceStartData{}: handleTowerDefenceStartData, + &pbmodel.TowerDefenceUpdateData{}: handleTowerDefenceUpdateData, + &pbmodel.BlockSumoUpdateData{}: handleBlockSumoUpdateData, +} + +var HistoricParsers = map[proto.Message]func(data proto.Message, g *model.HistoricGame) error{ + // Common + &pbmodel.CommonGameFinishWinnerData{}: parseGameFinishWinnerData, + + // TowerDefence + &pbmodel.TowerDefenceFinishData{}: handleTowerDefenceFinishData, + &pbmodel.BlockSumoFinishData{}: handleBlockSumoFinishData, +} diff --git a/services/game-tracker/internal/repository/model/block_sumo.go b/services/game-tracker/internal/repository/model/block_sumo.go new file mode 100644 index 0000000..c0dc57c --- /dev/null +++ b/services/game-tracker/internal/repository/model/block_sumo.go @@ -0,0 +1,81 @@ +package model + +import ( + "fmt" + "github.com/emortalmc/proto-specs/gen/go/model/gametracker" + "github.com/google/uuid" +) + +type LiveBlockSumoData struct { + Scoreboard *BlockSumoScoreboard `bson:"scoreboard"` +} + +type HistoricBlockSumoData struct { + Scoreboard *BlockSumoScoreboard `bson:"scoreboard"` +} + +func CreateLiveBlockSumoDataFromUpdate(data *gametracker.BlockSumoUpdateData) (*LiveBlockSumoData, error) { + scoreboard, err := CreateBlockSumoScoreboard(data.Scoreboard) + if err != nil { + return nil, fmt.Errorf("failed to parse scoreboard: %w", err) + } + + return &LiveBlockSumoData{ + Scoreboard: scoreboard, + }, nil +} + +func (d *LiveBlockSumoData) Update(data *gametracker.BlockSumoUpdateData) error { + scoreboard, err := CreateBlockSumoScoreboard(data.Scoreboard) + if err != nil { + return fmt.Errorf("failed to parse scoreboard: %w", err) + } + + d.Scoreboard = scoreboard + + return nil +} + +func CreateBlockSumoScoreboard(data *gametracker.BlockSumoScoreboard) (*BlockSumoScoreboard, error) { + entries := make(map[uuid.UUID]*BlockSumoScoreboardEntry) + + for id, e := range data.Entries { + parsedId, err := uuid.Parse(id) + if err != nil { + return nil, fmt.Errorf("failed to parse player id: %w", err) + } + + entries[parsedId] = CreateBlockSumoScoreboardEntry(e) + } + + return &BlockSumoScoreboard{Entries: entries}, nil +} + +type BlockSumoScoreboard struct { + Entries map[uuid.UUID]*BlockSumoScoreboardEntry `bson:"entries"` +} + +type BlockSumoScoreboardEntry struct { + RemainingLives int32 `bson:"remainingLives"` + Kills int32 `bson:"kills"` + FinalKills int32 `bson:"finalKills"` +} + +func CreateBlockSumoScoreboardEntry(e *gametracker.BlockSumoScoreboard_Entry) *BlockSumoScoreboardEntry { + return &BlockSumoScoreboardEntry{ + RemainingLives: e.RemainingLives, + Kills: e.Kills, + FinalKills: e.FinalKills, + } +} + +func CreateHistoricBlockSumoDataFromFinish(data *gametracker.BlockSumoFinishData) (*HistoricBlockSumoData, error) { + scoreboard, err := CreateBlockSumoScoreboard(data.Scoreboard) + if err != nil { + return nil, fmt.Errorf("failed to parse scoreboard: %w", err) + } + + return &HistoricBlockSumoData{ + Scoreboard: scoreboard, + }, nil +} diff --git a/services/game-tracker/internal/repository/model/models.go b/services/game-tracker/internal/repository/model/models.go new file mode 100644 index 0000000..10506a3 --- /dev/null +++ b/services/game-tracker/internal/repository/model/models.go @@ -0,0 +1,220 @@ +package model + +import ( + "fmt" + "github.com/emortalmc/mono-services/services/game-tracker/internal/repository/registrytypes" + "github.com/emortalmc/mono-services/services/game-tracker/internal/utils" + "github.com/emortalmc/proto-specs/gen/go/model/gametracker" + "github.com/google/uuid" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsonrw" + "go.mongodb.org/mongo-driver/bson/primitive" + "time" +) + +type GameStage uint8 + +const ( + LiveTowerDefenceDataId int32 = 1 + LiveBlockSumoDataId int32 = 2 +) + +var dataType = map[int32]interface{}{ + LiveTowerDefenceDataId: &LiveTowerDefenceData{}, + LiveBlockSumoDataId: &LiveBlockSumoData{}, +} + +func getDataType(example interface{}) int32 { + for k, v := range dataType { + if utils.IsSameType(example, v) { + return k + } + } + + return 0 // 0 is ignored by omitempty so it won't be put in the db +} + +type IGame interface { + GetGame() *Game +} + +type Game struct { + Id primitive.ObjectID `bson:"_id"` + GameModeId string `bson:"gameModeId"` + + ServerId string `bson:"serverId"` + StartTime *time.Time `bson:"startTime,omitempty"` + Players []*BasicPlayer `bson:"players"` + + // The below data is all optional and varies by game mode + + TeamData *[]*Team `bson:"teams,omitempty"` + + // GameData is data specific to the game mode. It is only present if the game sends it + GameData interface{} `bson:"gameData,omitempty"` + GameDataType int32 `bson:"gameDataType,omitempty"` +} + +func (g *Game) GetGame() *Game { + return g +} + +func (g *Game) SetGameData(data interface{}) { + g.GameData = data + g.GameDataType = getDataType(data) +} + +// ParseGameData converts and replaces the game data from bson.D to the correct type +func (g *Game) ParseGameData() error { + if g.GameData == nil { + return nil + } + + if g.GameDataType == 0 { + return fmt.Errorf("game data type not set but game data is present") + } + + example, ok := dataType[g.GameDataType] + if !ok { + return fmt.Errorf("unknown game data type: %d", g.GameDataType) + } + + if example == nil { + return fmt.Errorf("unknown game data type: %d", g.GameDataType) + } + + // Convert the interface{} to bytes + bytes, err := bson.Marshal(g.GameData) + if err != nil { + return fmt.Errorf("failed to marshal game data: %w", err) + } + + // Parse the bytes from the interface{} into the correct type + dec, err := bson.NewDecoder(bsonrw.NewBSONDocumentReader(bytes)) + if err != nil { + return fmt.Errorf("failed to create decoder: %w", err) + } + + if err := dec.SetRegistry(registrytypes.CodecRegistry); err != nil { + return fmt.Errorf("failed to set registry: %w", err) + } + + if err := dec.Decode(example); err != nil { + return fmt.Errorf("failed to decode: %w", err) + } + + g.GameData = example + + return nil +} + +type LiveGame struct { + // Embed Game for common fields + *Game `bson:",inline"` + + // GameData provided at game create (allocation messages) + LastUpdated time.Time `bson:"lastUpdated"` +} + +type HistoricGame struct { + // Embed Game for common fields + *Game `bson:",inline"` + + EndTime time.Time `bson:"endTime"` + + // The below data is all optional and varies by game mode + WinnerData *HistoricWinnerData `bson:"winnerData,omitempty"` +} + +type HistoricWinnerData struct { + WinnerIds []uuid.UUID `bson:"winnerIds"` + LoserIds []uuid.UUID `bson:"loserIds"` +} + +func HistoricWinnerDataFromProto(d *gametracker.CommonGameFinishWinnerData) (*HistoricWinnerData, error) { + winnerIds, err := ParseUuids(d.WinnerIds) + if err != nil { + return nil, fmt.Errorf("failed to parse winners: %w", err) + } + + loserIds, err := ParseUuids(d.LoserIds) + if err != nil { + return nil, fmt.Errorf("failed to parse losers: %w", err) + } + + return &HistoricWinnerData{ + WinnerIds: winnerIds, + LoserIds: loserIds, + }, nil +} + +type BasicPlayer struct { + Id uuid.UUID `bson:"id"` + Username string `bson:"username"` +} + +func BasicPlayerFromProto(p *gametracker.BasicGamePlayer) (*BasicPlayer, error) { + id, err := uuid.Parse(p.Id) + if err != nil { + return nil, err + } + + return &BasicPlayer{ + Id: id, + Username: p.Username, + }, nil +} + +func BasicPlayersFromProto(players []*gametracker.BasicGamePlayer) ([]*BasicPlayer, error) { + basicPlayers := make([]*BasicPlayer, len(players)) + for i, p := range players { + basicPlayer, err := BasicPlayerFromProto(p) + if err != nil { + return nil, err + } + + basicPlayers[i] = basicPlayer + } + + return basicPlayers, nil +} + +type Team struct { + Id string `bson:"id"` + FriendlyName string `bson:"friendlyName"` + Color int32 `bson:"color"` + PlayerIds []uuid.UUID `bson:"playerIds"` +} + +func TeamFromProto(t *gametracker.Team) (*Team, error) { + playerIds := make([]uuid.UUID, len(t.PlayerIds)) + for i, id := range t.PlayerIds { + playerId, err := uuid.Parse(id) + if err != nil { + return nil, err + } + + playerIds[i] = playerId + } + + return &Team{ + Id: t.Id, + FriendlyName: t.FriendlyName, + Color: t.Color, + PlayerIds: playerIds, + }, nil +} + +func ParseUuids(uuidStrs []string) ([]uuid.UUID, error) { + ids := make([]uuid.UUID, len(uuidStrs)) + for i, id := range uuidStrs { + parsed, err := uuid.Parse(id) + if err != nil { + return nil, err + } + + ids[i] = parsed + } + + return ids, nil +} diff --git a/services/game-tracker/internal/repository/model/tower_defence.go b/services/game-tracker/internal/repository/model/tower_defence.go new file mode 100644 index 0000000..b5ee6cc --- /dev/null +++ b/services/game-tracker/internal/repository/model/tower_defence.go @@ -0,0 +1,42 @@ +package model + +import "github.com/emortalmc/proto-specs/gen/go/model/gametracker" + +type LiveTowerDefenceData struct { + MaxHealth int32 `bson:"maxHealth"` + RedHealth int32 `bson:"redHealth"` + BlueHealth int32 `bson:"blueHealth"` +} + +func (d *LiveTowerDefenceData) Update(data *gametracker.TowerDefenceUpdateData) { + healthData := data.HealthData + + d.RedHealth = healthData.RedHealth + d.BlueHealth = healthData.BlueHealth +} + +func CreateLiveTowerDefenceDataFromStart(data *gametracker.TowerDefenceStartData) *LiveTowerDefenceData { + healthData := data.HealthData + + return &LiveTowerDefenceData{ + MaxHealth: healthData.MaxHealth, + RedHealth: healthData.RedHealth, + BlueHealth: healthData.BlueHealth, + } +} + +type HistoricTowerDefenceData struct { + MaxHealth int32 `bson:"maxHealth"` + RedHealth int32 `bson:"redHealth"` + BlueHealth int32 `bson:"blueHealth"` +} + +func CreateHistoricTowerDefenceDataFromFinish(data *gametracker.TowerDefenceFinishData) *HistoricTowerDefenceData { + healthData := data.HealthData + + return &HistoricTowerDefenceData{ + MaxHealth: healthData.MaxHealth, + RedHealth: healthData.RedHealth, + BlueHealth: healthData.BlueHealth, + } +} diff --git a/services/game-tracker/internal/repository/mongo.go b/services/game-tracker/internal/repository/mongo.go new file mode 100644 index 0000000..d1a2d14 --- /dev/null +++ b/services/game-tracker/internal/repository/mongo.go @@ -0,0 +1,197 @@ +package repository + +import ( + "context" + "fmt" + "github.com/emortalmc/mono-services/services/game-tracker/internal/config" + "github.com/emortalmc/mono-services/services/game-tracker/internal/repository/model" + "github.com/emortalmc/mono-services/services/game-tracker/internal/repository/registrytypes" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" + "go.uber.org/zap" + "sync" + "time" +) + +const ( + databaseName = "game-tracker" + + liveGameCollectionName = "liveGame" + historicGameCollectionName = "historicGame" +) + +type mongoRepository struct { + database *mongo.Database + + liveGameCollection *mongo.Collection + historicGameCollection *mongo.Collection +} + +func NewMongoRepository(ctx context.Context, logger *zap.SugaredLogger, wg *sync.WaitGroup, cfg config.MongoDBConfig) (Repository, error) { + client, err := mongo.Connect(ctx, options.Client().ApplyURI(cfg.URI).SetRegistry(registrytypes.CodecRegistry)) + if err != nil { + return nil, fmt.Errorf("failed to connect to mongo: %w", err) + } + + database := client.Database(databaseName) + repo := &mongoRepository{ + database: database, + liveGameCollection: database.Collection(liveGameCollectionName), + historicGameCollection: database.Collection(historicGameCollectionName), + } + + wg.Add(1) + go func() { + defer wg.Done() + <-ctx.Done() + if err := client.Disconnect(ctx); err != nil { + logger.Errorw("failed to disconnect from mongo", err) + } + }() + + repo.createIndexes(ctx) + logger.Infow("created mongo indexes") + + return repo, nil +} + +// Note we create a lot more indexes for the game tracker because it's a debug data treasure trove. +// Not all indexes are used in code. +var ( + liveGameIndexes = []mongo.IndexModel{ + { + Keys: bson.D{{Key: "gameModeId", Value: 1}}, + Options: options.Index().SetName("gameModeId"), + }, + { + Keys: bson.D{{Key: "serverId", Value: 1}}, + Options: options.Index().SetName("serverId"), + }, + } + historicGameIndexes = []mongo.IndexModel{ + { + Keys: bson.D{{Key: "gameModeId", Value: 1}}, + Options: options.Index().SetName("gameModeId"), + }, + { + Keys: bson.D{{Key: "serverId", Value: 1}}, + Options: options.Index().SetName("serverId"), + }, + { + Keys: bson.D{{Key: "startTime", Value: 1}}, + Options: options.Index().SetName("startTime"), + }, + { + Keys: bson.D{{Key: "players.id", Value: 1}}, + Options: options.Index().SetName("players.id"), + }, + { + Keys: bson.D{{Key: "endTime", Value: 1}}, + Options: options.Index().SetName("endTime"), + }, + + // todo we might want indexes for game data and winner data + } +) + +func (m *mongoRepository) createIndexes(ctx context.Context) { + collIndexes := map[*mongo.Collection][]mongo.IndexModel{ + m.liveGameCollection: liveGameIndexes, + m.historicGameCollection: historicGameIndexes, + } + + wg := sync.WaitGroup{} + wg.Add(len(collIndexes)) + + for coll, indexes := range collIndexes { + go func(coll *mongo.Collection, indexes []mongo.IndexModel) { + defer wg.Done() + _, err := m.createCollIndexes(ctx, coll, indexes) + if err != nil { + panic(fmt.Sprintf("failed to create indexes for collection %s: %s", coll.Name(), err)) + } + }(coll, indexes) + } + + wg.Wait() +} + +func (m *mongoRepository) createCollIndexes(ctx context.Context, coll *mongo.Collection, indexes []mongo.IndexModel) (int, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + result, err := coll.Indexes().CreateMany(ctx, indexes) + if err != nil { + return 0, fmt.Errorf("failed to create indexes: %w", err) + } + + return len(result), nil +} + +func (m *mongoRepository) GetLiveGame(ctx context.Context, id primitive.ObjectID) (*model.LiveGame, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + var game model.LiveGame + if err := m.liveGameCollection.FindOne(ctx, bson.M{"_id": id}).Decode(&game); err != nil { + return nil, fmt.Errorf("failed to get live game: %w", err) + } + + if err := game.ParseGameData(); err != nil { + return nil, fmt.Errorf("failed to parse game data: %w", err) + } + + return &game, nil +} + +var ErrIdNotSet = fmt.Errorf("id not set") + +func (m *mongoRepository) SaveLiveGame(ctx context.Context, game *model.LiveGame) error { + if game.Id.IsZero() { + return ErrIdNotSet + } + + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + _, err := m.liveGameCollection.UpdateByID(ctx, game.Id, bson.M{"$set": game}, options.Update().SetUpsert(true)) + if err != nil { + return fmt.Errorf("failed to save live game: %w", err) + } + + return nil +} + +func (m *mongoRepository) DeleteLiveGame(ctx context.Context, id primitive.ObjectID) error { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + _, err := m.liveGameCollection.DeleteOne(ctx, bson.M{"_id": id}) + return err +} + +func (m *mongoRepository) SaveHistoricGame(ctx context.Context, game *model.HistoricGame) error { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + _, err := m.historicGameCollection.InsertOne(ctx, game) + return err +} + +func (m *mongoRepository) GetHistoricGame(ctx context.Context, id primitive.ObjectID) (*model.HistoricGame, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + var game model.HistoricGame + if err := m.historicGameCollection.FindOne(ctx, bson.M{"_id": id}).Decode(&game); err != nil { + return nil, fmt.Errorf("failed to get historic game: %w", err) + } + + if err := game.ParseGameData(); err != nil { + return nil, fmt.Errorf("failed to parse game data: %w", err) + } + + return &game, nil +} diff --git a/services/game-tracker/internal/repository/public.go b/services/game-tracker/internal/repository/public.go new file mode 100644 index 0000000..5513b7f --- /dev/null +++ b/services/game-tracker/internal/repository/public.go @@ -0,0 +1,17 @@ +package repository + +import ( + "context" + "github.com/emortalmc/mono-services/services/game-tracker/internal/repository/model" + "go.mongodb.org/mongo-driver/bson/primitive" +) + +type Repository interface { + GetLiveGame(ctx context.Context, id primitive.ObjectID) (*model.LiveGame, error) + // SaveLiveGame saves a game (with upsert) + SaveLiveGame(ctx context.Context, game *model.LiveGame) error + DeleteLiveGame(ctx context.Context, id primitive.ObjectID) error + + SaveHistoricGame(ctx context.Context, game *model.HistoricGame) error + GetHistoricGame(ctx context.Context, id primitive.ObjectID) (*model.HistoricGame, error) +} diff --git a/services/game-tracker/internal/repository/registrytypes/public.go b/services/game-tracker/internal/repository/registrytypes/public.go new file mode 100644 index 0000000..e615b01 --- /dev/null +++ b/services/game-tracker/internal/repository/registrytypes/public.go @@ -0,0 +1,17 @@ +package registrytypes + +import ( + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsoncodec" +) + +var CodecRegistry = createCodecRegistry() + +func createCodecRegistry() *bsoncodec.Registry { + r := bson.NewRegistry() + + r.RegisterTypeEncoder(UUIDType, bsoncodec.ValueEncoderFunc(UuidEncodeValue)) + r.RegisterTypeDecoder(UUIDType, bsoncodec.ValueDecoderFunc(UuidDecodeValue)) + + return r +} diff --git a/services/game-tracker/internal/repository/registrytypes/uuid_types.go b/services/game-tracker/internal/repository/registrytypes/uuid_types.go new file mode 100644 index 0000000..eb2262d --- /dev/null +++ b/services/game-tracker/internal/repository/registrytypes/uuid_types.go @@ -0,0 +1,58 @@ +// Package registrytypes +// taken from https://gist.github.com/SupaHam/3afe982dc75039356723600ccc91ff77 +package registrytypes + +import ( + "fmt" + "github.com/google/uuid" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/bson/bsonrw" + "reflect" +) + +var ( + UUIDType = reflect.TypeOf(uuid.UUID{}) + uuidSubtype = byte(0x04) +) + +func UuidEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != UUIDType { + return bsoncodec.ValueEncoderError{Name: "uuidEncodeValue", Types: []reflect.Type{UUIDType}, Received: val} + } + b := val.Interface().(uuid.UUID) + return vw.WriteBinaryWithSubtype(b[:], uuidSubtype) +} + +func UuidDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != UUIDType { + return bsoncodec.ValueDecoderError{Name: "uuidDecodeValue", Types: []reflect.Type{UUIDType}, Received: val} + } + + var data []byte + var subtype byte + var err error + switch vrType := vr.Type(); vrType { + case bson.TypeBinary: + data, subtype, err = vr.ReadBinary() + if subtype != uuidSubtype { + return fmt.Errorf("unsupported binary subtype %v for UUID", subtype) + } + case bson.TypeNull: + err = vr.ReadNull() + case bson.TypeUndefined: + err = vr.ReadUndefined() + default: + return fmt.Errorf("cannot decode %v into a UUID", vrType) + } + + if err != nil { + return err + } + uuid2, err := uuid.FromBytes(data) + if err != nil { + return err + } + val.Set(reflect.ValueOf(uuid2)) + return nil +} diff --git a/services/game-tracker/internal/utils/pointer.go b/services/game-tracker/internal/utils/pointer.go new file mode 100644 index 0000000..40e2bc4 --- /dev/null +++ b/services/game-tracker/internal/utils/pointer.go @@ -0,0 +1,5 @@ +package utils + +func Pointer[T any](v T) *T { + return &v +} diff --git a/services/game-tracker/internal/utils/runtime/runtime.go b/services/game-tracker/internal/utils/runtime/runtime.go new file mode 100644 index 0000000..ca62601 --- /dev/null +++ b/services/game-tracker/internal/utils/runtime/runtime.go @@ -0,0 +1,7 @@ +package runtime + +func Must(err error) { + if err != nil { + panic(err) + } +} diff --git a/services/game-tracker/internal/utils/type.go b/services/game-tracker/internal/utils/type.go new file mode 100644 index 0000000..ac8064e --- /dev/null +++ b/services/game-tracker/internal/utils/type.go @@ -0,0 +1,24 @@ +package utils + +import "reflect" + +func IsSameType(a, b interface{}) bool { + aType := reflect.TypeOf(a) + bType := reflect.TypeOf(b) + + // Check if both types are exactly the same + if aType == bType { + return true + } + + // Check if one of the types is a pointer and the other is the underlying element type + if aType.Kind() == reflect.Ptr && aType.Elem() == bType { + return true + } + + if bType.Kind() == reflect.Ptr && bType.Elem() == aType { + return true + } + + return false +} diff --git a/services/game-tracker/run/config.yaml b/services/game-tracker/run/config.yaml new file mode 100644 index 0000000..173c291 --- /dev/null +++ b/services/game-tracker/run/config.yaml @@ -0,0 +1,10 @@ +development: true + +kafka: + host: localhost + port: 9092 + +mongodb: + uri: mongodb://localhost:27017 + +port: 10010 diff --git a/services/game-tracker/test/game_process/main.go b/services/game-tracker/test/game_process/main.go new file mode 100644 index 0000000..3db0dfd --- /dev/null +++ b/services/game-tracker/test/game_process/main.go @@ -0,0 +1,195 @@ +package main + +import ( + "context" + "fmt" + "github.com/emortalmc/mono-services/services/game-tracker/internal/config" + "github.com/emortalmc/proto-specs/gen/go/message/gametracker" + pbmodel "github.com/emortalmc/proto-specs/gen/go/model/gametracker" + "github.com/google/uuid" + "go.mongodb.org/mongo-driver/bson/primitive" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/anypb" + "google.golang.org/protobuf/types/known/timestamppb" + "log" + "math/rand" + "time" +) + +var ( + serverId = "tower-defence-test-" + uuid.New().String()[:6] + gameId = primitive.NewObjectID() + + expectationalId = uuid.MustParse("8d36737e-1c0a-4a71-87de-9906f577845e") + emortaldevId = uuid.MustParse("7bd5b459-1e6b-4753-8274-1fbd2fe9a4d5") + + defaultPlayers = []*pbmodel.BasicGamePlayer{ + { + Id: expectationalId.String(), + Username: "Expectational", + }, + { + Id: emortaldevId.String(), + Username: "emortaldev", + }, + } +) + +type app struct { + w *kafka.Writer +} + +func main() { + cfg := config.LoadGlobalConfig() + + w := &kafka.Writer{ + Addr: kafka.TCP(fmt.Sprintf("%s:%d", cfg.Kafka.Host, cfg.Kafka.Port)), + Topic: "games", + Balancer: &kafka.LeastBytes{}, + Async: false, + } + + a := &app{ + w: w, + } + + a.writeStartMessage() + log.Printf("wrote start message, waiting 5 seconds before sending update") + time.Sleep(5 * time.Second) + + a.writeUpdateMessage() + log.Printf("wrote update message, waiting 5 seconds before sending end") + time.Sleep(5 * time.Second) + + a.writeFinishedMessage() + log.Printf("wrote finished message. All done :)") +} + +func (a *app) writeStartMessage() { + tdStartData, err := anypb.New(&pbmodel.TowerDefenceStartData{ + HealthData: &pbmodel.TowerDefenceHealthData{ + MaxHealth: 1000, + BlueHealth: 1000, + RedHealth: 1000, + }, + }) + if err != nil { + panic(err) + } + + teamStartData, err := anypb.New(&pbmodel.CommonGameTeamData{Teams: []*pbmodel.Team{ + { + Id: "blue", + FriendlyName: "Blue", + Color: 0x0000FF, + PlayerIds: []string{expectationalId.String()}, + }, + { + Id: "red", + FriendlyName: "Red", + Color: 0xFF0000, + PlayerIds: []string{emortaldevId.String()}, + }, + }}) + if err != nil { + panic(err) + } + + message := &gametracker.GameStartMessage{ + CommonData: &gametracker.CommonGameData{ + GameModeId: "tower-defence", + GameId: gameId.Hex(), + ServerId: serverId, + Players: defaultPlayers, + }, + StartTime: timestamppb.Now(), + MapId: "test-map", + Content: []*anypb.Any{tdStartData, teamStartData}, + } + + a.writeMessages(message) +} + +func (a *app) writeUpdateMessage() { + tdUpdateData, err := anypb.New(&pbmodel.TowerDefenceUpdateData{ + HealthData: &pbmodel.TowerDefenceHealthData{ + MaxHealth: 1000, + BlueHealth: 750, + RedHealth: 500, + }, + }) + if err != nil { + panic(err) + } + + message := &gametracker.GameUpdateMessage{ + CommonData: &gametracker.CommonGameData{ + GameModeId: "tower-defence", + GameId: gameId.Hex(), + ServerId: serverId, + Players: defaultPlayers, + }, + Content: []*anypb.Any{tdUpdateData}, + } + + a.writeMessages(message) +} + +func (a *app) writeFinishedMessage() { + tdFinishData, err := anypb.New(&pbmodel.TowerDefenceFinishData{ + HealthData: &pbmodel.TowerDefenceHealthData{ + MaxHealth: rand.Int31n(1000), + BlueHealth: rand.Int31n(1000), + RedHealth: rand.Int31n(1000), + }, + }) + if err != nil { + panic(err) + } + + winnerData, err := anypb.New(&pbmodel.CommonGameFinishWinnerData{ + WinnerIds: []string{defaultPlayers[0].GetId()}, + LoserIds: []string{defaultPlayers[1].GetId()}, + }) + if err != nil { + panic(err) + } + + message := &gametracker.GameFinishMessage{ + CommonData: &gametracker.CommonGameData{ + GameModeId: "tower-defence", + GameId: gameId.Hex(), + ServerId: serverId, + Players: defaultPlayers, + }, + EndTime: timestamppb.New(time.Now().Add(1 * time.Minute)), + Content: []*anypb.Any{tdFinishData, winnerData}, + } + + a.writeMessages(message) +} + +func (a *app) writeMessages(messages ...proto.Message) { + kMessages := make([]kafka.Message, len(messages)) + + for i, m := range messages { + bytes, err := proto.Marshal(m) + if err != nil { + panic(err) + } + + kMessages[i] = kafka.Message{ + Headers: []kafka.Header{ + { + Key: "X-Proto-Type", + Value: []byte(m.ProtoReflect().Descriptor().FullName()), + }, + }, + Value: bytes, + } + } + + if err := a.w.WriteMessages(context.Background(), kMessages...); err != nil { + panic(err) + } +} diff --git a/services/party-manager/Dockerfile b/services/party-manager/Dockerfile new file mode 100644 index 0000000..67c59ed --- /dev/null +++ b/services/party-manager/Dockerfile @@ -0,0 +1,33 @@ +FROM --platform=$BUILDPLATFORM golang:1.23-alpine AS build + +ARG SERVICE_NAME=party-manager + +WORKDIR /build + +# Copy sources +COPY . . + +WORKDIR /build/services/$SERVICE_NAME + +RUN go mod download + +WORKDIR /build + +ARG TARGETOS +ARG TARGETARCH + +RUN --mount=type=cache,target=/root/.cache/go-build \ + --mount=type=cache,target=/go/pkg \ + CGO_ENABLED=0 \ + GOOS=$TARGETOS \ + GOARCH=$TARGETARCH \ + go build -ldflags="-s -w" -o $SERVICE_NAME ./services/$SERVICE_NAME/cmd/$SERVICE_NAME + +FROM alpine + +ARG SERVICE_NAME=party-manager + +WORKDIR /app + +COPY --from=build /build/$SERVICE_NAME /build/services/$SERVICE_NAME/run ./ +CMD ["./party-manager"] \ No newline at end of file diff --git a/services/party-manager/cmd/party-manager/main.go b/services/party-manager/cmd/party-manager/main.go new file mode 100644 index 0000000..bb3c7a1 --- /dev/null +++ b/services/party-manager/cmd/party-manager/main.go @@ -0,0 +1,35 @@ +package main + +import ( + "github.com/emortalmc/mono-services/services/party-manager/internal/app" + "github.com/emortalmc/mono-services/services/party-manager/internal/config" + "go.uber.org/zap" + "log" +) + +func main() { + cfg, err := config.LoadGlobalConfig() + if err != nil { + log.Fatal("failed to load config", err) + } + + unsugared, err := createLogger(cfg) + if err != nil { + log.Fatal(err) + } + logger := unsugared.Sugar() + + app.Run(cfg, logger) +} + +func createLogger(cfg *config.Config) (logger *zap.Logger, err error) { + if cfg.Development { + logger, err = zap.NewDevelopment() + } else { + logger, err = zap.NewProduction() + } + if err != nil { + return nil, err + } + return logger, nil +} diff --git a/services/party-manager/cmd/party-manager/testing/testing.go b/services/party-manager/cmd/party-manager/testing/testing.go new file mode 100644 index 0000000..e19b499 --- /dev/null +++ b/services/party-manager/cmd/party-manager/testing/testing.go @@ -0,0 +1,30 @@ +package main + +import ( + "context" + pb "github.com/emortalmc/proto-specs/gen/go/grpc/party" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials/insecure" + "log" + "time" +) + +func main() { + conn, err := grpc.Dial("localhost:10006", grpc.WithTransportCredentials(insecure.NewCredentials())) + if err != nil { + panic(err) + } + + partyClient := pb.NewPartyServiceClient(conn) + + startTime := time.Now().UnixMilli() + res, err := partyClient.EmptyParty(context.Background(), &pb.EmptyPartyRequest{ + Id: &pb.EmptyPartyRequest_PlayerId{PlayerId: "8d36737e-1c0a-4a71-87de-9906f577845e"}, + }) + if err != nil { + panic(err) + } + + log.Printf("response: %+v", res) + log.Printf("took: %dms", time.Now().UnixMilli()-startTime) +} diff --git a/services/party-manager/go.mod b/services/party-manager/go.mod new file mode 100644 index 0000000..cb6b8a0 --- /dev/null +++ b/services/party-manager/go.mod @@ -0,0 +1,56 @@ +module github.com/emortalmc/mono-services/services/party-manager + +go 1.21 + +require ( + github.com/emortalmc/proto-specs/gen/go v0.0.0-20240927103241-2584fd28e0f9 + github.com/golang/mock v1.6.0 + github.com/google/uuid v1.6.0 + github.com/grpc-ecosystem/go-grpc-middleware v1.4.0 + github.com/segmentio/kafka-go v0.4.47 + github.com/spf13/viper v1.19.0 + github.com/stretchr/testify v1.9.0 + github.com/zakshearman/go-grpc-health v0.0.0-20230228185502-9e7f9da964a5 + go.mongodb.org/mongo-driver v1.17.1 + go.uber.org/zap v1.27.0 + google.golang.org/grpc v1.67.1 + google.golang.org/protobuf v1.35.1 +) + +require ( + github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect + github.com/fsnotify/fsnotify v1.7.0 // indirect + github.com/golang/protobuf v1.5.4 // indirect + github.com/golang/snappy v0.0.4 // indirect + github.com/hashicorp/hcl v1.0.0 // indirect + github.com/klauspost/compress v1.17.2 // indirect + github.com/magiconair/properties v1.8.7 // indirect + github.com/mitchellh/mapstructure v1.5.0 // indirect + github.com/montanaflynn/stats v0.7.1 // indirect + github.com/pelletier/go-toml/v2 v2.2.2 // indirect + github.com/pierrec/lz4/v4 v4.1.18 // indirect + github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect + github.com/rogpeppe/go-internal v1.10.0 // indirect + github.com/sagikazarmark/locafero v0.4.0 // indirect + github.com/sagikazarmark/slog-shim v0.1.0 // indirect + github.com/sourcegraph/conc v0.3.0 // indirect + github.com/spf13/afero v1.11.0 // indirect + github.com/spf13/cast v1.6.0 // indirect + github.com/spf13/pflag v1.0.5 // indirect + github.com/subosito/gotenv v1.6.0 // indirect + github.com/xdg-go/pbkdf2 v1.0.0 // indirect + github.com/xdg-go/scram v1.1.2 // indirect + github.com/xdg-go/stringprep v1.0.4 // indirect + github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect + go.uber.org/multierr v1.10.0 // indirect + golang.org/x/crypto v0.26.0 // indirect + golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // 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-20240814211410-ddb44dafa142 // indirect + gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c // indirect + gopkg.in/ini.v1 v1.67.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/services/party-manager/go.sum b/services/party-manager/go.sum new file mode 100644 index 0000000..23f7996 --- /dev/null +++ b/services/party-manager/go.sum @@ -0,0 +1,260 @@ +cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU= +github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= +github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU= +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/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= +github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/emortalmc/proto-specs/gen/go v0.0.0-20240927103241-2584fd28e0f9 h1:6xOnWrTvG2oJR1J6+B+tdZV5GdlbIgdQixdCCyfj4nA= +github.com/emortalmc/proto-specs/gen/go v0.0.0-20240927103241-2584fd28e0f9/go.mod h1:se+tHcK9FWxeadkxLF5uj+SPauEye0X+Iq6cGczXGJY= +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/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= +github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= +github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= +github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA= +github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM= +github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= +github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= +github.com/go-stack/stack v1.8.0/go.mod h1:v0f6uXyyMGvRgIKkXu+yp6POWl0qKG85gN/melR3HDY= +github.com/gogo/protobuf v1.3.2 h1:Ov1cvc58UF3b5XjBnZv7+opcTcQFZebYjWzi34vdm4Q= +github.com/gogo/protobuf v1.3.2/go.mod h1:P1XiOD3dCwIKUDQYPy72D8LYyHL2YPYrpS2s69NZV8Q= +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.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= +github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= +github.com/golang/snappy v0.0.4 h1:yAGX7huGHXlcLOEtBnF4w7FQwA26wojNCwOYAEhLjQM= +github.com/golang/snappy v0.0.4/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= +github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= +github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI= +github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY= +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/grpc-ecosystem/go-grpc-middleware v1.4.0 h1:UH//fgunKIs4JdUbpDl1VZCDaL56wXCB/5+wF6uHfaI= +github.com/grpc-ecosystem/go-grpc-middleware v1.4.0/go.mod h1:g5qyo/la0ALbONm6Vbp88Yd8NsDy6rZz+RcrMPxvld8= +github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= +github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= +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.15.9/go.mod h1:PhcZ0MbTNciWF3rruxRgKxI5NkcHHrHUDtV4Yw2GlzU= +github.com/klauspost/compress v1.17.2 h1:RlWWUY/Dr4fL8qk9YG7DTZ7PDgME2V4csBXA8L/ixi4= +github.com/klauspost/compress v1.17.2/go.mod h1:ntbaceVETuRiXiv4DpjP66DpAtAGkEQskQzEyD//IeE= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= +github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= +github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= +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/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= +github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY= +github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= +github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY= +github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo= +github.com/montanaflynn/stats v0.7.1 h1:etflOAAHORrCC44V+aR6Ftzort912ZU+YLiSTuV8eaE= +github.com/montanaflynn/stats v0.7.1/go.mod h1:etXPPgVO6n31NxCd9KQUMvCM+ve0ruNzt6R8Bnaayow= +github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= +github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM= +github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs= +github.com/pierrec/lz4/v4 v4.1.15/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= +github.com/pierrec/lz4/v4 v4.1.18 h1:xaKrnTkyoqfh1YItXl56+6KJNVYWlEEPuAQW9xsplYQ= +github.com/pierrec/lz4/v4 v4.1.18/go.mod h1:gZWDp/Ze/IJXGXf23ltt2EXimqmTUXEy0GFuRQyBid4= +github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U= +github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= +github.com/rogpeppe/go-internal v1.10.0 h1:TMyTOH3F/DB16zRVcYyreMH6GnZZrwQVAoYjRBZyWFQ= +github.com/rogpeppe/go-internal v1.10.0/go.mod h1:UQnix2H7Ngw/k4C5ijL5+65zddjncjaFoBhdsK/akog= +github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ= +github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4= +github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE= +github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ= +github.com/segmentio/kafka-go v0.4.47 h1:IqziR4pA3vrZq7YdRxaT3w1/5fvIH5qpCwstUanQQB0= +github.com/segmentio/kafka-go v0.4.47/go.mod h1:HjF6XbOKh0Pjlkr5GVZxt6CsjjwnmhVOfURM5KMd8qg= +github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= +github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= +github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= +github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= +github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= +github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0= +github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo= +github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= +github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= +github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI= +github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+Ntkg= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA= +github.com/stretchr/testify v1.2.2/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.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +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/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= +github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= +github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c= +github.com/xdg-go/pbkdf2 v1.0.0/go.mod h1:jrpuAogTd400dnrH08LKmI/xc1MbPOebTwRqcT5RDeI= +github.com/xdg-go/scram v1.1.2 h1:FHX5I5B4i4hKRVRBCFRxq1iQRej7WO3hhBuJf+UUySY= +github.com/xdg-go/scram v1.1.2/go.mod h1:RT/sEzTbU5y00aCK8UOx6R7YryM0iF1N2MOmC3kKLN4= +github.com/xdg-go/stringprep v1.0.4 h1:XLI/Ng3O1Atzq0oBs3TWm+5ZVgkq2aqdlvP9JtoZ6c8= +github.com/xdg-go/stringprep v1.0.4/go.mod h1:mPGuuIYwz7CmR2bT9j4GbQqutWS1zV24gijq1dTyGkM= +github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 h1:ilQV1hzziu+LLM3zUTJ0trRztfwgjqKnBWNtSRkbmwM= +github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78/go.mod h1:aL8wCCfTfSfmXjznFBSZNN13rSJjlIOI1fUNAtF7rmI= +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/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY= +github.com/zakshearman/go-grpc-health v0.0.0-20230228185502-9e7f9da964a5 h1:NP/BXh+6mKhho3IQNsVaRZJEnoq+SQl2VTOUGTJnBEA= +github.com/zakshearman/go-grpc-health v0.0.0-20230228185502-9e7f9da964a5/go.mod h1:QAtiPuoW09CaHmLIP7KJ0Dv75p4/hz0hs32uBesaBjk= +go.mongodb.org/mongo-driver v1.17.1 h1:Wic5cJIwJgSpBhe3lx3+/RybR5PiYRMpVFgO7cOHyIM= +go.mongodb.org/mongo-driver v1.17.1/go.mod h1:wwWm/+BuOddhcq3n68LKRmgk2wXzmF6s0SFOa0GINL4= +go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= +go.uber.org/goleak v1.1.10/go.mod h1:8a7PlsEVH3e/a/GLqe5IIrQx6GzcnRmZEufDUTk4A7A= +go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= +go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= +go.uber.org/multierr v1.6.0/go.mod h1:cdWPpRnG4AhwMwsgIHip0KRBQjJy5kYEpYjJxpXp9iU= +go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ= +go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= +go.uber.org/zap v1.18.1/go.mod h1:xg/QME4nWcxGxrpdeYfq7UvYrLh66cuVKdrbD1XF/NI= +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-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc= +golang.org/x/crypto v0.14.0/go.mod h1:MVFd36DqK4CsrnJYDkBA3VC4m2GkXAM0PvzMCn4JQf4= +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-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g= +golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k= +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/lint v0.0.0-20190930215403-16217165b5de/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.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA= +golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4= +golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs= +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-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-20201021035429-f5854403a974/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU= +golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg= +golang.org/x/net v0.0.0-20210405180319-a5a99cb37ef4/go.mod h1:p54w0d4576C0XHj96bSt6lcn1PtDYWL6XObtHCRCNQM= +golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c= +golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/net v0.17.0/go.mod h1:NxSsAGuq816PNPmqtQdLE42eU2Fs7NoRIZrHJAlaCOE= +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/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-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.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/sync v0.1.0/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-20190422165155-953cdadca894/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-20210330210617-4fbd30eecc44/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-20211025201205-69cdffdb9359/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-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.13.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/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= +golang.org/x/term v0.8.0/go.mod h1:xPskH00ivmX89bAKVGSKKtLOWNx2+17Eiy94tnKShWo= +golang.org/x/term v0.13.0/go.mod h1:LTmsnFJwVN6bCy1rVCoS+qHT1HhALEFxKncY3WNNh4U= +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.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= +golang.org/x/text v0.3.8/go.mod h1:E6s5w1FMmriuDzIBO73fBruAKo1PCIq6d2Q6DHfQ8WQ= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= +golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE= +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-20191108193012-7d206e10da11/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo= +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-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA= +golang.org/x/tools v0.1.1/go.mod h1:o0xws9oXOQQZyjljx8fwUC0k7L1pTE6eaCbjGeHmOkk= +golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc= +golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU= +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-20200423170343-7949de9c1215/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240814211410-ddb44dafa142 h1:e7S5W7MGGLaSu8j3YjdezkZ+m1/Nm0uRVRMEMGk26Xs= +google.golang.org/genproto/googleapis/rpc v0.0.0-20240814211410-ddb44dafa142/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.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= +google.golang.org/grpc v1.67.1 h1:zWnc1Vrcno+lHZCOofnIMvycFcc0QRGIzm9dhnDX68E= +google.golang.org/grpc v1.67.1/go.mod h1:1gLDyUQU7CTLJI90u3nXZ9ekeghjeM7pTDZlqFNg2AA= +google.golang.org/protobuf v1.35.1 h1:m3LfL6/Ca+fqnjnlqQXNpFPABW1UD7mjh8KO2mKFytA= +google.golang.org/protobuf v1.35.1/go.mod h1:9fA7Ob0pmnwhb644+1+CVWFRbNajQ6iRojtC/QF5bRE= +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/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= +gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= +gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= +gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= +gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= +gopkg.in/yaml.v2 v2.2.8/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.0-20210107192922-496545a6307b/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= diff --git a/services/party-manager/internal/app/app.go b/services/party-manager/internal/app/app.go new file mode 100644 index 0000000..c329e45 --- /dev/null +++ b/services/party-manager/internal/app/app.go @@ -0,0 +1,50 @@ +package app + +import ( + "context" + "github.com/emortalmc/mono-services/services/party-manager/internal/app/event" + "github.com/emortalmc/mono-services/services/party-manager/internal/app/party" + "github.com/emortalmc/mono-services/services/party-manager/internal/config" + "github.com/emortalmc/mono-services/services/party-manager/internal/grpc" + "github.com/emortalmc/mono-services/services/party-manager/internal/kafka/consumer" + "github.com/emortalmc/mono-services/services/party-manager/internal/kafka/writer" + "github.com/emortalmc/mono-services/services/party-manager/internal/repository" + "go.uber.org/zap" + "os/signal" + "sync" + "syscall" +) + +func Run(cfg *config.Config, logger *zap.SugaredLogger) { + ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) + defer cancel() + wg := &sync.WaitGroup{} + + delayedWg := &sync.WaitGroup{} + delayedCtx, delayedCancel := context.WithCancel(ctx) + + repo, err := repository.NewMongoRepository(delayedCtx, logger, delayedWg, cfg.MongoDB) + if err != nil { + logger.Fatalw("failed to connect to mongo", err) + } + + notif := writer.NewKafkaNotifier(delayedCtx, delayedWg, cfg.Kafka, logger) + if err != nil { + logger.Fatalw("failed to create kafka notifier", err) + } + + partySvc := party.NewService(logger, repo, notif) + eventSvc := event.NewService(repo, notif) + event.NewScheduler(ctx, wg, logger, repo, notif, partySvc) + + consumer.NewConsumer(ctx, wg, cfg.Kafka, logger, partySvc) + + grpc.RunServices(ctx, logger, wg, cfg, repo, partySvc, eventSvc) + + wg.Wait() + logger.Info("stopped services") + + logger.Info("shutting down repository and kafka") + delayedCancel() + delayedWg.Wait() +} diff --git a/services/party-manager/internal/app/event/kafka_writer.go b/services/party-manager/internal/app/event/kafka_writer.go new file mode 100644 index 0000000..bec06fd --- /dev/null +++ b/services/party-manager/internal/app/event/kafka_writer.go @@ -0,0 +1,17 @@ +package event + +import ( + "context" + "github.com/emortalmc/mono-services/services/party-manager/internal/kafka/writer" + "github.com/emortalmc/mono-services/services/party-manager/internal/repository/model" +) + +var ( + _ KafkaWriter = &writer.Notifier{} +) + +type KafkaWriter interface { + DisplayEvent(ctx context.Context, event *model.Event) + StartEvent(ctx context.Context, event *model.Event) + DeleteEvent(ctx context.Context, event *model.Event) +} diff --git a/services/party-manager/internal/app/event/repo.go b/services/party-manager/internal/app/event/repo.go new file mode 100644 index 0000000..99a64b6 --- /dev/null +++ b/services/party-manager/internal/app/event/repo.go @@ -0,0 +1,37 @@ +package event + +import ( + "context" + "github.com/emortalmc/mono-services/services/party-manager/internal/repository" + "github.com/emortalmc/mono-services/services/party-manager/internal/repository/model" + "go.mongodb.org/mongo-driver/bson/primitive" + "time" +) + +var ( + _ ReadWriter = &repository.MongoRepository{} +) + +type Reader interface { + ListEvents(ctx context.Context) ([]*model.Event, error) +} + +type Writer interface { + CreateEvent(ctx context.Context, event *model.Event) error + UpdateEvent(ctx context.Context, eventId string, displayTime *time.Time, startTime *time.Time) (*model.Event, error) + DeleteEvent(ctx context.Context, eventId string) error + GetLiveEvent(ctx context.Context) (*model.Event, error) + GetEventByID(ctx context.Context, eventId string) (*model.Event, error) + SetEventPartyID(ctx context.Context, eventId string, partyId primitive.ObjectID) error + + // Both GetEventToDisplay and GetEventToStart find an event where startTime/displayTime is after now + // and then marks the event as displayed/started. + + GetEventToDisplay(ctx context.Context) (*model.Event, error) + GetEventToStart(ctx context.Context) (*model.Event, error) +} + +type ReadWriter interface { + Reader + Writer +} diff --git a/services/party-manager/internal/app/event/scheduler.go b/services/party-manager/internal/app/event/scheduler.go new file mode 100644 index 0000000..7d49fb9 --- /dev/null +++ b/services/party-manager/internal/app/event/scheduler.go @@ -0,0 +1,129 @@ +package event + +import ( + "context" + "errors" + "github.com/emortalmc/mono-services/services/party-manager/internal/app/party" + "github.com/emortalmc/mono-services/services/party-manager/internal/kafka/writer" + "github.com/emortalmc/mono-services/services/party-manager/internal/repository" + "github.com/emortalmc/mono-services/services/party-manager/internal/repository/model" + "go.mongodb.org/mongo-driver/mongo" + "go.uber.org/zap" + "sync" + "time" +) + +type handler struct { + log *zap.SugaredLogger + repo *repository.MongoRepository // this is a horrible cross cutting concern but we'll cope for now + notif *writer.Notifier + partySvc *party.Service +} + +func NewScheduler(ctx context.Context, wg *sync.WaitGroup, log *zap.SugaredLogger, repo *repository.MongoRepository, notif *writer.Notifier, + partySvc *party.Service) { + h := &handler{ + log: log, + repo: repo, + notif: notif, + partySvc: partySvc, + } + + h.run(ctx, wg) +} + +func (h *handler) run(ctx context.Context, wg *sync.WaitGroup) { + go func() { + ticker := time.NewTicker(3 * time.Second) + + for { + select { + case <-ctx.Done(): + wg.Done() + return + case <-ticker.C: + h.runDisplayEvent(ctx) + h.runStartEvent(ctx) + } + } + }() +} + +func (h *handler) runDisplayEvent(ctx context.Context) { + e, err := h.repo.GetEventToDisplay(ctx) + if err != nil { + if errors.Is(err, mongo.ErrNoDocuments) { + return + } + + h.log.Errorf("failed to get event to display: %v", err) + return + } + + h.notif.DisplayEvent(ctx, e) +} + +func (h *handler) runStartEvent(ctx context.Context) { + e, err := h.repo.GetEventToStart(ctx) + if err != nil { + if errors.Is(err, mongo.ErrNoDocuments) { + return + } + + h.log.Errorf("failed to get event to start: %v", err) + return + } + + // We don't convert a party as it's too complex. Instead, we re-create it. + p, err := h.repo.GetPartyByMemberID(ctx, e.OwnerID) + if err != nil && !errors.Is(err, mongo.ErrNoDocuments) { + h.log.Errorf("failed to get party by member id: %v", err) + return + } + + if err == nil { + if p.LeaderId == e.OwnerID { + if err := h.partySvc.EmptyParty(ctx, p, true); err != nil { + h.log.Errorf("failed to empty party: %v", err) + return + } + } else { + // note: p gets reassigned to the player's new party + if p, err = h.partySvc.RemovePlayerFromParty(ctx, e.OwnerID, true); err != nil { + h.log.Errorf("failed to remove player from party: %v", err) + return + } + + if err := h.partySvc.SetOpenParty(ctx, p.ID, true); err != nil { + h.log.Errorf("failed to set open party: %v", err) + return + } + } + } else { + p = model.NewParty(e.OwnerID, e.OwnerUsername) + p.Open = true + if err := h.repo.CreateParty(ctx, p); err != nil { + h.log.Errorf("failed to create party: %v", err) + return + } + + // todo what is the impact of notifying this? could it be bad? + h.notif.PartyCreated(ctx, p) + } + + // We now have a party that is open with only the owner of the event in it. + + if err := h.repo.SetEventPartyID(ctx, e.ID, p.ID); err != nil { + h.log.Errorf("failed to set event party id: %v", err) + return + } + + if err := h.repo.SetPartyEventID(ctx, p.ID, e.ID); err != nil { + h.log.Errorf("failed to set party event id: %v", err) + return + } + + e.PartyID = &p.ID + + h.notif.StartEvent(ctx, e) +} diff --git a/services/party-manager/internal/app/event/service.go b/services/party-manager/internal/app/event/service.go new file mode 100644 index 0000000..3eac283 --- /dev/null +++ b/services/party-manager/internal/app/event/service.go @@ -0,0 +1,77 @@ +package event + +import ( + "context" + "errors" + "fmt" + "github.com/emortalmc/mono-services/services/party-manager/internal/repository" + "github.com/emortalmc/mono-services/services/party-manager/internal/repository/model" + "go.mongodb.org/mongo-driver/mongo" + "time" +) + +type Service struct { + repo *repository.MongoRepository + notif KafkaWriter +} + +func NewService(repo *repository.MongoRepository, notif KafkaWriter) *Service { + return &Service{ + repo: repo, + notif: notif, + } +} + +var ErrEventAlreadyExists = errors.New("event already exists") + +func (s *Service) CreateEvent(ctx context.Context, event *model.Event) error { + if err := s.repo.CreateEvent(ctx, event); err != nil { + if mongo.IsDuplicateKeyError(err) { + return ErrEventAlreadyExists + } + + return fmt.Errorf("failed to create event: %w", err) + } + + return nil +} + +func (s *Service) UpdateEvent(ctx context.Context, eventId string, displayTime *time.Time, startTime *time.Time) (*model.Event, error) { + return s.repo.UpdateEvent(ctx, eventId, displayTime, startTime) +} + +func (s *Service) DeleteCurrentEvent(ctx context.Context) error { + e, err := s.repo.GetLiveEvent(ctx) + if err != nil { + return fmt.Errorf("failed to delete current event: %w", err) + } + + return s.DeleteEvent(ctx, e) +} + +func (s *Service) DeleteEventByID(ctx context.Context, eventId string) error { + e, err := s.repo.GetEventByID(ctx, eventId) + if err != nil { + return fmt.Errorf("failed to get event: %w", err) + + } + + return s.DeleteEvent(ctx, e) +} + +func (s *Service) DeleteEvent(ctx context.Context, event *model.Event) error { + if err := s.repo.DeleteEvent(ctx, event.ID); err != nil { + return fmt.Errorf("failed to delete event: %w", err) + } + + // remove the event_id from the party if it was live + if event.PartyID != nil { + if err := s.repo.RemovePartyEventID(ctx, *event.PartyID); err != nil { + return fmt.Errorf("failed to remove event_id from party: %w", err) + } + } + + s.notif.DeleteEvent(ctx, event) + + return nil +} diff --git a/services/party-manager/internal/app/party/consumer.go b/services/party-manager/internal/app/party/consumer.go new file mode 100644 index 0000000..acd3bc6 --- /dev/null +++ b/services/party-manager/internal/app/party/consumer.go @@ -0,0 +1,115 @@ +package party + +import ( + "context" + "errors" + "github.com/emortalmc/mono-services/services/party-manager/internal/repository/model" + "github.com/google/uuid" + "math/rand" +) + +func (s *Service) HandlePlayerDisconnect(ctx context.Context, playerID uuid.UUID) { + party, err := s.repo.GetPartyByMemberID(ctx, playerID) + if err != nil { + s.log.Errorw("failed to get party by member id", err) + return + } + + // IF it is an event party then we don't want any leaving, promotion, deleting, ets.. logic to run + if party.IsEventParty() && party.LeaderId == playerID { + return + } + + // Party only has the leader in it + if playerID == party.LeaderId && len(party.Members) < 2 { + if err := s.repo.DeleteParty(ctx, party.ID); err != nil { + s.log.Errorw("failed to delete party", err) + return + } + + if err := s.repo.DeletePartyInvitesByPartyId(ctx, party.ID); err != nil { + s.log.Errorw("failed to delete party invites", err) + return + } + + s.notif.PartyDeleted(ctx, party) + return + } + + // Player may still be the party leader, but it has more than 1 member OR is an event party. + // As a result, do a new leader election. + + if err := s.repo.RemoveMemberFromParty(ctx, party.ID, playerID); err != nil { + s.log.Errorw("failed to remove member from party", err) + return + } + + partyMember, ok := party.GetMember(playerID) + if !ok { + s.log.Errorw("party member not found", "partyID", party.ID, "playerID", playerID) + return + } + + s.notif.PartyPlayerLeft(ctx, party.ID, partyMember) + + // If the player is the current leader, elect a new leader + if playerID == party.LeaderId { + newLeader, err := electNewPartyLeader(party) + if err != nil { + s.log.Errorw("failed to elect new party leader", err) + return // todo don't just return here - it leaves the party in a broken state. Very bad. + } + + if err := s.repo.SetPartyLeader(ctx, party.ID, newLeader.PlayerID); err != nil { + s.log.Errorw("failed to set party leader", err) + return + } + + s.notif.PartyLeaderChanged(ctx, party.ID, newLeader) + } +} + +func (s *Service) HandlePlayerConnect(ctx context.Context, playerId uuid.UUID, username string) { + if party, err := s.repo.GetPartyByMemberID(ctx, playerId); err == nil { + if party.IsEventParty() && party.LeaderId == playerId { + return + } + + s.log.Errorw("player already in party??", "playerID", playerId, "party", party) + return + } + + party := model.NewParty(playerId, username) + + if err := s.repo.CreateParty(ctx, party); err != nil { + s.log.Errorw("failed to create party", err) + return + } + + s.notif.PartyCreated(ctx, party) +} + +var ErrLeaderElecNotEnoughMembers = errors.New("party member count must be >= 2") + +// electNewPartyLeader elects a member of the party as a new leader of the party and returns the member that is the new +// leader. It assumes that party.LeaderId is still current to ignore them as a candidate for the new leader. +func electNewPartyLeader(party *model.Party) (*model.PartyMember, error) { + if len(party.Members) < 2 { + return nil, ErrLeaderElecNotEnoughMembers + } + + members := make([]*model.PartyMember, len(party.Members)-1) + + i := 0 + for _, member := range party.Members { + if member.PlayerID == party.LeaderId { + continue + } + + members[i] = member + i++ + } + + newLeader := members[rand.Intn(len(members))] + return newLeader, nil +} diff --git a/services/party-manager/internal/app/party/kafka_writer.go b/services/party-manager/internal/app/party/kafka_writer.go new file mode 100644 index 0000000..48b5a7f --- /dev/null +++ b/services/party-manager/internal/app/party/kafka_writer.go @@ -0,0 +1,27 @@ +package party + +import ( + "context" + "github.com/emortalmc/mono-services/services/party-manager/internal/kafka/writer" + "github.com/emortalmc/mono-services/services/party-manager/internal/repository/model" + "github.com/google/uuid" + "go.mongodb.org/mongo-driver/bson/primitive" +) + +var ( + _ KafkaWriter = &writer.Notifier{} +) + +type KafkaWriter interface { + PartyCreated(ctx context.Context, party *model.Party) + PartyDeleted(ctx context.Context, party *model.Party) + PartyEmptied(ctx context.Context, party *model.Party) + PartyOpenChanged(ctx context.Context, partyId primitive.ObjectID, open bool) + PartyInviteCreated(ctx context.Context, invite *model.PartyInvite) + PartyPlayerJoined(ctx context.Context, partyId primitive.ObjectID, player *model.PartyMember) + PartyPlayerLeft(ctx context.Context, partyId primitive.ObjectID, player *model.PartyMember) + PartyPlayerKicked(ctx context.Context, partyId primitive.ObjectID, kicked *model.PartyMember, kicker *model.PartyMember) + PartyLeaderChanged(ctx context.Context, partyId primitive.ObjectID, newLeader *model.PartyMember) + + PartySettingsChanged(ctx context.Context, playerId uuid.UUID, settings *model.PartySettings) +} diff --git a/services/party-manager/internal/app/party/repo.go b/services/party-manager/internal/app/party/repo.go new file mode 100644 index 0000000..9251b52 --- /dev/null +++ b/services/party-manager/internal/app/party/repo.go @@ -0,0 +1,67 @@ +package party + +import ( + "context" + "github.com/emortalmc/mono-services/services/party-manager/internal/repository" + "github.com/emortalmc/mono-services/services/party-manager/internal/repository/model" + "github.com/google/uuid" + "go.mongodb.org/mongo-driver/bson/primitive" +) + +var ( + _ ReadWriter = &repository.MongoRepository{} +) + +type Reader interface { + IsInParty(ctx context.Context, playerId uuid.UUID) (bool, error) + + GetPartyByID(ctx context.Context, partyId primitive.ObjectID) (*model.Party, error) + GetPartyByMemberID(ctx context.Context, playerId uuid.UUID) (*model.Party, error) + GetPartyIdByMemberId(ctx context.Context, playerId uuid.UUID) (primitive.ObjectID, error) + GetPartyLeaderIdByMemberId(ctx context.Context, playerId uuid.UUID) (uuid.UUID, error) + GetPartyLeaderByPartyId(ctx context.Context, partyId primitive.ObjectID) (uuid.UUID, error) + // GetPartyInvitesByPartyId returns all party invites for a given party. + // Note that this does not check if the party exists. If the party does not exist, an empty slice is returned. + GetPartyInvitesByPartyId(ctx context.Context, partyId primitive.ObjectID) ([]*model.PartyInvite, error) + DoesPartyInviteExist(ctx context.Context, partyId primitive.ObjectID, playerId uuid.UUID) (bool, error) + + GetPartySettings(ctx context.Context, playerId uuid.UUID) (*model.PartySettings, error) +} + +type Writer interface { + // CreateParty creates a new party and sets the ID of the party for the reference. + CreateParty(ctx context.Context, party *model.Party) error + DeleteParty(ctx context.Context, partyId primitive.ObjectID) error + + SetPartyMembers(ctx context.Context, partyId primitive.ObjectID, members []*model.PartyMember) error + AddPartyMember(ctx context.Context, partyId primitive.ObjectID, member *model.PartyMember) error + + SetPartyLeader(ctx context.Context, partyId primitive.ObjectID, leaderId uuid.UUID) error + + // SetPartyOpen sets the party to open or closed. + // If no party exists, mongo.ErrNoDocuments is thrown. + SetPartyOpen(ctx context.Context, partyId primitive.ObjectID, open bool) error + + SetPartyEventID(ctx context.Context, partyId primitive.ObjectID, eventId string) error + RemovePartyEventID(ctx context.Context, partyId primitive.ObjectID) error + + // RemoveMemberFromParty removes from party. + // Throws mongo.ErrNoDocuments if party does not exist. + // Throws repository.ErrNotInParty if player is not in the party. + RemoveMemberFromParty(ctx context.Context, partyId primitive.ObjectID, playerId uuid.UUID) error + // RemoveMemberFromSelfParty removes a player from their party. + // Throws mongo.ErrNoDocuments if the player is not in a party. + RemoveMemberFromSelfParty(ctx context.Context, playerId uuid.UUID) error + + // CreatePartyInvite creates a new invite and sets the ID of the invite for the reference. + CreatePartyInvite(ctx context.Context, invite *model.PartyInvite) error + DeletePartyInvite(ctx context.Context, partyId primitive.ObjectID, targetId uuid.UUID) error + DeletePartyInvitesByPartyId(ctx context.Context, partyId primitive.ObjectID) error + + UpdatePartySettings(ctx context.Context, settings *model.PartySettings) error +} + +type ReadWriter interface { + Reader + Writer +} diff --git a/services/party-manager/internal/app/party/service.go b/services/party-manager/internal/app/party/service.go new file mode 100644 index 0000000..9c79b95 --- /dev/null +++ b/services/party-manager/internal/app/party/service.go @@ -0,0 +1,328 @@ +package party + +import ( + "context" + "errors" + "fmt" + "github.com/emortalmc/mono-services/services/party-manager/internal/repository/model" + "github.com/google/uuid" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo" + "go.uber.org/zap" + "time" +) + +type Service struct { + log *zap.SugaredLogger + repo ReadWriter + notif KafkaWriter +} + +func NewService(log *zap.SugaredLogger, repo ReadWriter, notif KafkaWriter) *Service { + return &Service{ + log: log, + repo: repo, + notif: notif, + } +} + +var ErrPartyLeaderNotFound = errors.New("party leader not found") + +func (s *Service) EmptyParty(ctx context.Context, party *model.Party, partyOpen bool) error { + leader, ok := party.GetMember(party.LeaderId) + if !ok { + return ErrPartyLeaderNotFound + } + + if err := s.repo.SetPartyMembers(ctx, party.ID, []*model.PartyMember{leader}); err != nil { + return fmt.Errorf("failed to set party members: %w", err) + } + + if err := s.repo.DeletePartyInvitesByPartyId(ctx, party.ID); err != nil { + return fmt.Errorf("failed to delete party invites: %w", err) + } + + if party.Open != partyOpen { + if err := s.repo.SetPartyOpen(ctx, party.ID, partyOpen); err != nil { + return fmt.Errorf("failed to set party open: %w", err) + } + } + + s.notif.PartyEmptied(ctx, party) + + // Go through all the members and make them a new party. + for _, member := range party.Members { + if member.PlayerID == party.LeaderId { + continue + } + + newParty := model.NewParty(member.PlayerID, member.Username) + if err := s.repo.CreateParty(ctx, newParty); err != nil { + return fmt.Errorf("failed to create party: %w", err) + } + + s.notif.PartyCreated(ctx, newParty) + } + + return nil +} + +func (s *Service) SetOpenParty(ctx context.Context, partyID primitive.ObjectID, open bool) error { + if err := s.repo.SetPartyOpen(ctx, partyID, open); err != nil { + return fmt.Errorf("failed to set party open: %w", err) + } + + s.notif.PartyOpenChanged(ctx, partyID, open) + + return nil +} + +var ErrExecutorNotLeader = errors.New("executor is not the leader of the party") +var ErrTargetAndSelfSameParty = errors.New("target is in the same party as the executor") +var ErrTargetAlreadyInvited = errors.New("target is already invited to the party") + +func (s *Service) InvitePlayer(ctx context.Context, executorID uuid.UUID, executorUsername string, targetID uuid.UUID, + targetUsername string) (*model.PartyInvite, error) { + + // Get party of the inviter + party, err := s.repo.GetPartyByMemberID(ctx, executorID) + if err != nil { + // NOTE: We no longer implicitly create a party because a player should always be in a party + return nil, err + } + + settings, err := s.GetPartySettings(ctx, party.LeaderId) + if err != nil { + return nil, err + } + + if party.LeaderId != executorID { + if !settings.AllowMemberInvite { + return nil, ErrExecutorNotLeader + } + } + + targetParty, err := s.repo.GetPartyByMemberID(ctx, targetID) + if err != nil { + return nil, err + } + + if targetParty.ID == party.ID { + return nil, ErrTargetAndSelfSameParty + } + + // Check if the target is already invited + inviteExists, err := s.repo.DoesPartyInviteExist(ctx, party.ID, targetID) + if err != nil { + return nil, fmt.Errorf("failed to check if party invite exists: %w", err) + } + if inviteExists { + return nil, ErrTargetAlreadyInvited + } + + // Create invite + invite := &model.PartyInvite{ + PartyID: party.ID, + + InviterID: executorID, + InviterUsername: executorUsername, + + TargetID: targetID, + TargetUsername: targetUsername, + + ExpiresAt: time.Now().In(time.UTC).Add(5 * time.Minute), + } + + // Save invite + err = s.repo.CreatePartyInvite(ctx, invite) + if err != nil { + return nil, fmt.Errorf("failed to create party invite: %w", err) + } + + s.notif.PartyInviteCreated(ctx, invite) + + return invite, nil +} + +var ErrNotInvited = errors.New("player is not invited to the party") +var ErrAlreadyInSameParty = errors.New("player is already in the same party") + +func (s *Service) JoinPartyByMemberID(ctx context.Context, playerID uuid.UUID, playerUsername string, targetID uuid.UUID) (*model.Party, error) { + currentParty, err := s.repo.GetPartyByMemberID(ctx, playerID) + if err != nil { + return nil, fmt.Errorf("failed to get party by member id: %w", err) + } + + targetParty, err := s.repo.GetPartyByMemberID(ctx, targetID) + if err != nil { + return nil, fmt.Errorf("failed to get party by member id: %w", err) + } + + if targetParty.ID == currentParty.ID { + return nil, ErrAlreadyInSameParty + } + + if !targetParty.Open { + if err := s.repo.DeletePartyInvite(ctx, targetParty.ID, playerID); err != nil { + if errors.Is(err, mongo.ErrNoDocuments) { + return nil, ErrNotInvited + } else { + return nil, fmt.Errorf("failed to delete party invite: %w", err) + } + } + } + + if len(currentParty.Members) == 1 { + if err := s.repo.DeleteParty(ctx, currentParty.ID); err != nil { + return nil, fmt.Errorf("failed to delete party: %w", err) + } + + s.notif.PartyDeleted(ctx, currentParty) + } else { // RemovePlayerFromParty handles leader election if they are the leader of the party + if _, err := s.RemovePlayerFromParty(ctx, playerID, false); err != nil { + return nil, fmt.Errorf("failed to remove player from party: %w", err) + } + } + + newPartyMember := &model.PartyMember{ + PlayerID: playerID, + Username: playerUsername, + } + + if err := s.repo.AddPartyMember(ctx, targetParty.ID, newPartyMember); err != nil { + return nil, fmt.Errorf("failed to add party member: %w", err) + } + + s.notif.PartyPlayerJoined(ctx, targetParty.ID, newPartyMember) + + return targetParty, nil +} + +var ErrPlayerIsOnlyMember = errors.New("player is the only member of the party") + +func (s *Service) RemovePlayerFromParty(ctx context.Context, playerID uuid.UUID, createNewParty bool) (*model.Party, error) { + party, err := s.repo.GetPartyByMemberID(ctx, playerID) + if err != nil { + return nil, fmt.Errorf("failed to get party by member id: %w", err) + } + + if len(party.Members) == 1 { + return party, ErrPlayerIsOnlyMember + } + + if err := s.repo.RemoveMemberFromParty(ctx, party.ID, playerID); err != nil { + return nil, fmt.Errorf("failed to remove party member: %w", err) // wrapped is of type ErrNotInParty + } + + member, ok := party.GetMember(playerID) + if !ok { + return nil, fmt.Errorf("failed to get party member: %w", err) + } + + s.notif.PartyPlayerLeft(ctx, party.ID, member) + + if party.LeaderId == playerID { + newLeader, err := electNewPartyLeader(party) + if err != nil { + return nil, fmt.Errorf("failed to elect new party leader: %w", err) + } + + if err := s.repo.SetPartyLeader(ctx, party.ID, newLeader.PlayerID); err != nil { + return nil, fmt.Errorf("failed to set party leader: %w", err) + } + + s.notif.PartyLeaderChanged(ctx, party.ID, newLeader) + } + + if createNewParty { + if party, err = s.putPlayerInNewParty(ctx, playerID, member.Username); err != nil { + return nil, fmt.Errorf("failed to put player in new party: %w", err) + } + } + + return party, nil +} + +var ErrTargetNotInParty = errors.New("target is not in the party") + +// todo might be an issue here with someone trying to kick themselves? +func (s *Service) KickPlayerFromParty(ctx context.Context, executorID uuid.UUID, targetID uuid.UUID) error { + party, err := s.repo.GetPartyByMemberID(ctx, executorID) + if err != nil { + return fmt.Errorf("failed to get party by member id: %w", err) + } + + if party.LeaderId != executorID { + return ErrExecutorNotLeader + } + + targetMember, ok := party.GetMember(targetID) + if !ok { + return ErrTargetNotInParty + } + + // All checks passed, remove the player from the party + + if _, err := s.RemovePlayerFromParty(ctx, targetID, true); err != nil { + return fmt.Errorf("failed to remove player from party: %w", err) + } + + executorMember, ok := party.GetMember(executorID) + if !ok { + return fmt.Errorf("failed to get party member as they are not in own party?: %w", err) + } + + s.notif.PartyPlayerKicked(ctx, party.ID, targetMember, executorMember) + + if _, err := s.putPlayerInNewParty(ctx, targetID, targetMember.Username); err != nil { + return fmt.Errorf("failed to put player in new party: %w", err) + } + + return nil +} + +var ErrPlayerAlreadyLeader = errors.New("player is already the leader of the party") + +func (s *Service) ChangePartyLeader(ctx context.Context, party *model.Party, newLeaderID uuid.UUID) error { + leaderMember, ok := party.GetMember(newLeaderID) + if !ok { + return ErrTargetNotInParty + } + + if party.LeaderId == newLeaderID { + return ErrPlayerAlreadyLeader + } + + if err := s.repo.SetPartyLeader(ctx, party.ID, newLeaderID); err != nil { + return fmt.Errorf("failed to set party leaderMember: %w", err) + } + + s.notif.PartyLeaderChanged(ctx, party.ID, leaderMember) + + return nil +} + +func (s *Service) putPlayerInNewParty(ctx context.Context, playerID uuid.UUID, playerUsername string) (*model.Party, error) { + party := model.NewParty(playerID, playerUsername) + + if err := s.repo.CreateParty(ctx, party); err != nil { + return nil, fmt.Errorf("failed to create party: %w", err) + } + + s.notif.PartyCreated(ctx, party) + + return party, nil +} + +// GetPartySettings gets the party settings for a player or returns the default settings if the player has none. +func (s *Service) GetPartySettings(ctx context.Context, playerId uuid.UUID) (*model.PartySettings, error) { + settings, err := s.repo.GetPartySettings(ctx, playerId) + if err != nil { + if !errors.Is(err, mongo.ErrNoDocuments) { + return nil, fmt.Errorf("failed to get party settings: %w", err) + } + return model.NewPartySettings(playerId), nil + } + + return settings, nil +} diff --git a/services/party-manager/internal/config/global.go b/services/party-manager/internal/config/global.go new file mode 100644 index 0000000..1145830 --- /dev/null +++ b/services/party-manager/internal/config/global.go @@ -0,0 +1,43 @@ +package config + +import ( + "github.com/spf13/viper" + "strings" +) + +type Config struct { + Kafka KafkaConfig + MongoDB MongoDBConfig + + Port uint16 + Development bool +} + +type MongoDBConfig struct { + URI string +} + +type KafkaConfig struct { + Host string + Port int +} + +func LoadGlobalConfig() (*Config, error) { + cfg := &Config{} + + viper.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) + viper.AutomaticEnv() + + viper.SetConfigName("config") + viper.AddConfigPath(".") + + if err := viper.ReadInConfig(); err != nil { + return nil, err + } + + if err := viper.UnmarshalExact(cfg); err != nil { + return nil, err + } + + return cfg, nil +} diff --git a/services/party-manager/internal/grpc/event.go b/services/party-manager/internal/grpc/event.go new file mode 100644 index 0000000..fbbeef3 --- /dev/null +++ b/services/party-manager/internal/grpc/event.go @@ -0,0 +1,147 @@ +package grpc + +import ( + "context" + "errors" + "fmt" + "github.com/emortalmc/mono-services/services/party-manager/internal/app/event" + "github.com/emortalmc/mono-services/services/party-manager/internal/repository/model" + "github.com/emortalmc/mono-services/services/party-manager/internal/utils" + pb "github.com/emortalmc/proto-specs/gen/go/grpc/party" + pbmodel "github.com/emortalmc/proto-specs/gen/go/model/party" + "github.com/google/uuid" + "go.mongodb.org/mongo-driver/mongo" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "time" +) + +type eventService struct { + pb.UnimplementedEventServiceServer + + svc *event.Service + r event.Reader +} + +func newEventService(svc *event.Service, reader event.Reader) pb.EventServiceServer { + return &eventService{ + svc: svc, + r: reader, + } +} + +func (e *eventService) CreateEvent(ctx context.Context, req *pb.CreateEventRequest) (*pb.CreateEventResponse, error) { + reqEvent, err := eventFromRequest(req) + if err != nil { + return nil, fmt.Errorf("failed to create reqEvent: %w", err) + } + + if err := e.svc.CreateEvent(ctx, reqEvent); err != nil { + if errors.Is(err, event.ErrEventAlreadyExists) { + return nil, status.Error(codes.AlreadyExists, "event already exists") + } + + return nil, fmt.Errorf("failed to create event: %w", err) + + } + + return &pb.CreateEventResponse{ + Event: reqEvent.ToProto(), + }, nil +} + +func eventFromRequest(req *pb.CreateEventRequest) (*model.Event, error) { + ownerId, err := uuid.Parse(req.OwnerId) + if err != nil { + return nil, fmt.Errorf("invalid owner id: %w", err) + } + + var displayTime, startTime *time.Time + if req.DisplayTime != nil { + displayTime = utils.PointerOf(req.DisplayTime.AsTime()) + } + if req.StartTime != nil { + startTime = utils.PointerOf(req.StartTime.AsTime()) + } + + return &model.Event{ + ID: req.EventId, + OwnerID: ownerId, + OwnerUsername: req.OwnerUsername, + Skin: model.PlayerSkin{ + Texture: req.OwnerSkin.Texture, + Signature: req.OwnerSkin.Signature, + }, + DisplayTime: displayTime, + StartTime: startTime, + }, nil +} + +func (e *eventService) UpdateEvent(ctx context.Context, req *pb.UpdateEventRequest) (*pb.UpdateEventResponse, error) { + var displayTime, startTime *time.Time + if req.DisplayTime != nil { + displayTime = utils.PointerOf(req.DisplayTime.AsTime()) + } + if req.StartTime != nil { + startTime = utils.PointerOf(req.StartTime.AsTime()) + } + + res, err := e.svc.UpdateEvent(ctx, req.EventId, displayTime, startTime) + if err != nil { + if errors.Is(err, mongo.ErrNoDocuments) { + return nil, status.Error(codes.NotFound, "event not found") + } + + return nil, fmt.Errorf("failed to update event: %w", err) + } + + return &pb.UpdateEventResponse{ + Event: res.ToProto(), + }, nil +} + +var errNoCurrentEvent = panicIfErr(status.New(codes.NotFound, "no current event"). + WithDetails(&pb.DeleteEventErrorResponse{ErrorType: pb.DeleteEventErrorResponse_NO_CURRENT_EVENT})).Err() + +var errEventNotFound = panicIfErr(status.New(codes.NotFound, "event not found"). + WithDetails(&pb.DeleteEventErrorResponse{ErrorType: pb.DeleteEventErrorResponse_NOT_FOUND})).Err() + +func (e *eventService) DeleteEvent(ctx context.Context, in *pb.DeleteEventRequest) (*pb.DeleteEventResponse, error) { + if in.EventId == nil { + if err := e.svc.DeleteCurrentEvent(ctx); err != nil { + if errors.Is(err, mongo.ErrNoDocuments) { + return nil, errNoCurrentEvent + } + + return nil, fmt.Errorf("failed to delete current event: %w", err) + } + + return &pb.DeleteEventResponse{}, nil + } + + if err := e.svc.DeleteEventByID(ctx, in.GetEventId()); err != nil { + if errors.Is(err, mongo.ErrNoDocuments) { + return nil, errEventNotFound + } + + return nil, fmt.Errorf("failed to delete event: %w", err) + } + + return &pb.DeleteEventResponse{}, nil +} + +func (e *eventService) ListEvents(ctx context.Context, in *pb.ListEventsRequest) (*pb.ListEventsResponse, error) { + events, err := e.r.ListEvents(ctx) + if err != nil { + return nil, fmt.Errorf("failed to list events: %w", err) + } + + protoEvents := make([]*pbmodel.EventData, len(events)) + for i, event := range events { + protoEvents[i] = event.ToProto() + } + + return &pb.ListEventsResponse{ + Events: protoEvents, + }, nil +} diff --git a/services/party-manager/internal/grpc/party.go b/services/party-manager/internal/grpc/party.go new file mode 100644 index 0000000..7414791 --- /dev/null +++ b/services/party-manager/internal/grpc/party.go @@ -0,0 +1,368 @@ +package grpc + +import ( + "context" + "errors" + "fmt" + partySvc "github.com/emortalmc/mono-services/services/party-manager/internal/app/party" + "github.com/emortalmc/mono-services/services/party-manager/internal/repository/model" + pb "github.com/emortalmc/proto-specs/gen/go/grpc/party" + pbmodel "github.com/emortalmc/proto-specs/gen/go/model/party" + "github.com/google/uuid" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +type partyService struct { + pb.UnimplementedPartyServiceServer + + r partySvc.Reader + svc *partySvc.Service +} + +func newPartyService(r partySvc.Reader, svc *partySvc.Service) pb.PartyServiceServer { + return &partyService{ + r: r, + svc: svc, + } +} + +var ( + partyNotFoundErr = status.New(codes.NotFound, "party not found").Err() + playerNotInPartyErr = status.New(codes.NotFound, "player not in party").Err() +) + +func invalidFieldErr(field string) error { + return status.New(codes.InvalidArgument, fmt.Sprintf("invalid %s", field)).Err() +} + +var ( + emptyNotLeaderErr = panicIfErr(status.New(codes.PermissionDenied, "player is not the party leader"). + WithDetails(&pb.EmptyPartyErrorResponse{ErrorType: pb.EmptyPartyErrorResponse_NOT_LEADER})).Err() +) + +func (s *partyService) EmptyParty(ctx context.Context, request *pb.EmptyPartyRequest) (resp *pb.EmptyPartyResponse, err error) { + playerId := uuid.Nil + if request.GetPlayerId() != "" { + playerId, err = uuid.Parse(request.GetPlayerId()) + if err != nil { + return nil, invalidFieldErr("player id") + } + } + + var party *model.Party + if request.GetPartyId() != "" { + partyId, err := primitive.ObjectIDFromHex(request.GetPartyId()) + if err != nil { + return nil, invalidFieldErr("party id") + } + party, err = s.r.GetPartyByID(ctx, partyId) + if err != nil { + return nil, err + } + } else { + party, err = s.r.GetPartyByMemberID(ctx, playerId) + if err != nil { + return nil, err + } + } + + // Perform permission checks as request is made on behalf of a player. + if playerId != uuid.Nil { + if party.LeaderId != playerId { + return nil, emptyNotLeaderErr + } + } + + if err := s.svc.EmptyParty(ctx, party, false); err != nil { + return nil, fmt.Errorf("failed to empty party: %w", err) + } + + return &pb.EmptyPartyResponse{}, nil +} + +var ( + setOpenPartyNotLeaderErr = panicIfErr(status.New(codes.PermissionDenied, "player is not the party leader"). + WithDetails(&pb.SetOpenPartyErrorResponse{ErrorType: pb.SetOpenPartyErrorResponse_NOT_LEADER})).Err() +) + +func (s *partyService) SetOpenParty(ctx context.Context, request *pb.SetOpenPartyRequest) (*pb.SetOpenPartyResponse, error) { + playerId, err := uuid.Parse(request.GetPlayerId()) + if err != nil { + return nil, invalidFieldErr("player_id") + } + + party, err := s.r.GetPartyByMemberID(ctx, playerId) + if err != nil { + return nil, err + } + + if party.LeaderId != playerId { + return nil, setOpenPartyNotLeaderErr + } + + if err := s.svc.SetOpenParty(ctx, party.ID, request.GetOpen()); err != nil { + return nil, fmt.Errorf("failed to set party open: %w", err) + } + + return &pb.SetOpenPartyResponse{}, nil +} + +func (s *partyService) GetParty(ctx context.Context, request *pb.GetPartyRequest) (*pb.GetPartyResponse, error) { + if request.GetPartyId() != "" { + partyId, err := primitive.ObjectIDFromHex(request.GetPartyId()) + if err != nil { + return nil, invalidFieldErr("party_id") + } + party, err := s.r.GetPartyByID(ctx, partyId) + if err != nil { + if errors.Is(err, mongo.ErrNoDocuments) { + return nil, partyNotFoundErr + } + return nil, err + } + return &pb.GetPartyResponse{ + Party: party.ToProto(), + }, nil + } else { + playerId, err := uuid.Parse(request.GetPlayerId()) + if err != nil { + return nil, invalidFieldErr("player_id") + } + + party, err := s.r.GetPartyByMemberID(ctx, playerId) + if err != nil { + if errors.Is(err, mongo.ErrNoDocuments) { + return nil, playerNotInPartyErr + } + return nil, err + } + + return &pb.GetPartyResponse{ + Party: party.ToProto(), + }, nil + } +} + +func (s *partyService) GetPartyInvites(ctx context.Context, request *pb.GetPartyInvitesRequest) (*pb.GetPartyInvitesResponse, error) { + var partyId primitive.ObjectID + var err error + + if request.GetPartyId() != "" { + partyId, err = primitive.ObjectIDFromHex(request.GetPartyId()) + if err != nil { + return nil, invalidFieldErr("party_id") + } + } else { + playerId, err := uuid.Parse(request.GetPlayerId()) + if err != nil { + return nil, invalidFieldErr("player_id") + } + + partyId, err = s.r.GetPartyIdByMemberId(ctx, playerId) + if err != nil { + if errors.Is(err, mongo.ErrNoDocuments) { + return nil, playerNotInPartyErr + } + return nil, err + } + } + + invites, err := s.r.GetPartyInvitesByPartyId(ctx, partyId) + if err != nil { + if errors.Is(err, mongo.ErrNoDocuments) { + return nil, partyNotFoundErr + } + return nil, err + } + + inviteProtos := make([]*pbmodel.PartyInvite, 0, len(invites)) + for _, invite := range invites { + inviteProtos = append(inviteProtos, invite.ToProto()) + } + + return &pb.GetPartyInvitesResponse{ + Invites: inviteProtos, + }, nil +} + +var ( + inviteMustBeLeaderErr = panicIfErr(status.New(codes.PermissionDenied, "player must be leader"). + WithDetails(&pb.InvitePlayerErrorResponse{ErrorType: pb.InvitePlayerErrorResponse_NO_PERMISSION})).Err() + + inviteAlreadyInvitedErr = panicIfErr(status.New(codes.AlreadyExists, "player is already invited"). + WithDetails(&pb.InvitePlayerErrorResponse{ErrorType: pb.InvitePlayerErrorResponse_TARGET_ALREADY_INVITED})).Err() + + inviteTargetInSelfPartyErr = panicIfErr(status.New(codes.AlreadyExists, "target is already in the party"). + WithDetails(&pb.InvitePlayerErrorResponse{ErrorType: pb.InvitePlayerErrorResponse_TARGET_ALREADY_IN_SELF_PARTY})).Err() +) + +// InvitePlayer invites a player to the party of the inviter +// If the inviter is not in a party, one is implicitly created +func (s *partyService) InvitePlayer(ctx context.Context, request *pb.InvitePlayerRequest) (*pb.InvitePlayerResponse, error) { + issuerId, err := uuid.Parse(request.IssuerId) + if err != nil { + return nil, invalidFieldErr("issuer_id") + } + + targetId, err := uuid.Parse(request.TargetId) + if err != nil { + return nil, invalidFieldErr("target_id") + } + + invite, err := s.svc.InvitePlayer(ctx, issuerId, request.IssuerUsername, targetId, request.TargetUsername) + if err != nil { + if errors.Is(err, partySvc.ErrExecutorNotLeader) { + return nil, inviteMustBeLeaderErr + } + if errors.Is(err, partySvc.ErrTargetAndSelfSameParty) { + return nil, inviteTargetInSelfPartyErr + } + if errors.Is(err, partySvc.ErrTargetAlreadyInvited) { + return nil, inviteAlreadyInvitedErr + } + } + + return &pb.InvitePlayerResponse{Invite: invite.ToProto()}, nil +} + +var ( + joinPartyAlreadyInSamePartyErr = panicIfErr(status.New(codes.AlreadyExists, "player is already in a party"). + WithDetails(&pb.JoinPartyErrorResponse{ErrorType: pb.JoinPartyErrorResponse_ALREADY_IN_SAME_PARTY})).Err() + + joinPartyNotInvitedErr = panicIfErr(status.New(codes.PermissionDenied, "player is not invited to the party"). + WithDetails(&pb.JoinPartyErrorResponse{ErrorType: pb.JoinPartyErrorResponse_NOT_INVITED})).Err() +) + +func (s *partyService) JoinParty(ctx context.Context, request *pb.JoinPartyRequest) (*pb.JoinPartyResponse, error) { + playerId, err := uuid.Parse(request.PlayerId) + if err != nil { + return nil, invalidFieldErr("player_id") + } + + targetPlayerId, err := uuid.Parse(request.TargetPlayerId) + if err != nil { + return nil, invalidFieldErr("target_player_id") + } + + party, err := s.svc.JoinPartyByMemberID(ctx, playerId, request.PlayerUsername, targetPlayerId) + if err != nil { + if errors.Is(err, partySvc.ErrNotInvited) { + return nil, joinPartyNotInvitedErr + } + if errors.Is(err, partySvc.ErrAlreadyInSameParty) { + return nil, joinPartyAlreadyInSamePartyErr + } + + return nil, fmt.Errorf("failed to join party: %w", err) + } + + return &pb.JoinPartyResponse{ + Party: party.ToProto(), + }, nil +} + +var ( + leaveIsOnlyMember = panicIfErr(status.New(codes.FailedPrecondition, "player is the leader of the party"). + WithDetails(&pb.LeavePartyErrorResponse{ErrorType: pb.LeavePartyErrorResponse_CANNOT_LEAVE_ONLY_MEMBER})).Err() +) + +func (s *partyService) LeaveParty(ctx context.Context, request *pb.LeavePartyRequest) (*pb.LeavePartyResponse, error) { + playerId, err := uuid.Parse(request.PlayerId) + if err != nil { + return nil, invalidFieldErr("player_id") + } + + if _, err := s.svc.RemovePlayerFromParty(ctx, playerId, true); err != nil { + if errors.Is(err, partySvc.ErrPlayerIsOnlyMember) { + return nil, leaveIsOnlyMember + } + return nil, fmt.Errorf("failed to leave party: %w", err) + } + + return &pb.LeavePartyResponse{}, nil +} + +var ( + kickNotLeaderErr = panicIfErr(status.New(codes.FailedPrecondition, "issuer is not the leader of the party"). + WithDetails(&pb.KickPlayerErrorResponse{ErrorType: pb.KickPlayerErrorResponse_SELF_NOT_LEADER})).Err() + + // todo this error is no longer used. was stupid it existed in the first place oopsies + //kickTargetIsLeaderErr = panicIfErr(status.New(codes.FailedPrecondition, "target is the leader of the party"). + // WithDetails(&pb.KickPlayerErrorResponse{ErrorType: pb.KickPlayerErrorResponse_TARGET_IS_LEADER})).Err() + + kickTargetNotInPartyErr = panicIfErr(status.New(codes.FailedPrecondition, "target is not in the party"). + WithDetails(&pb.KickPlayerErrorResponse{ErrorType: pb.KickPlayerErrorResponse_TARGET_NOT_IN_PARTY})).Err() +) + +func (s *partyService) KickPlayer(ctx context.Context, request *pb.KickPlayerRequest) (*pb.KickPlayerResponse, error) { + issuerId, err := uuid.Parse(request.IssuerId) + if err != nil { + return nil, invalidFieldErr("issuer_id") + } + + targetId, err := uuid.Parse(request.TargetId) + if err != nil { + return nil, invalidFieldErr("target_id") + } + + if err := s.svc.KickPlayerFromParty(ctx, issuerId, targetId); err != nil { + if errors.Is(err, partySvc.ErrExecutorNotLeader) { + return nil, kickNotLeaderErr + } + if errors.Is(err, partySvc.ErrTargetNotInParty) { + return nil, kickTargetNotInPartyErr + } + } + + return &pb.KickPlayerResponse{}, nil +} + +var ( + setLeaderSelfNotLeaderErr = panicIfErr(status.New(codes.FailedPrecondition, "issuer is not the leader of the party"). + WithDetails(&pb.SetPartyLeaderErrorResponse{ErrorType: pb.SetPartyLeaderErrorResponse_SELF_NOT_LEADER})).Err() + + // setLeaderTargetNotInPartyErr this only means they are not in the same party, they may be in another party + setLeaderTargetNotInPartyErr = panicIfErr(status.New(codes.FailedPrecondition, "target is not in the party"). + WithDetails(&pb.SetPartyLeaderErrorResponse{ErrorType: pb.SetPartyLeaderErrorResponse_TARGET_NOT_IN_PARTY})).Err() +) + +func (s *partyService) SetPartyLeader(ctx context.Context, request *pb.SetPartyLeaderRequest) (*pb.SetPartyLeaderResponse, error) { + issuerId, err := uuid.Parse(request.IssuerId) + if err != nil { + return nil, invalidFieldErr("issuer_id") + } + + targetId, err := uuid.Parse(request.TargetId) + if err != nil { + return nil, invalidFieldErr("target_id") + } + + party, err := s.r.GetPartyByMemberID(ctx, issuerId) + if err != nil { + return nil, err + } + + // Check if the issuer is the party leader + if party.LeaderId != issuerId { + return nil, setLeaderSelfNotLeaderErr + } + + if err := s.svc.ChangePartyLeader(ctx, party, targetId); err != nil { + if errors.Is(err, partySvc.ErrTargetNotInParty) { + return nil, setLeaderTargetNotInPartyErr + } + return nil, fmt.Errorf("failed to set party leader: %w", err) + } + + return &pb.SetPartyLeaderResponse{}, nil +} + +func panicIfErr[T any](thing T, err error) T { + if err != nil { + panic(err) + } + return thing +} diff --git a/services/party-manager/internal/grpc/party_settings.go b/services/party-manager/internal/grpc/party_settings.go new file mode 100644 index 0000000..caa6012 --- /dev/null +++ b/services/party-manager/internal/grpc/party_settings.go @@ -0,0 +1,98 @@ +package grpc + +import ( + "context" + "errors" + "github.com/emortalmc/mono-services/services/party-manager/internal/app/party" + "github.com/emortalmc/mono-services/services/party-manager/internal/repository/model" + pb "github.com/emortalmc/proto-specs/gen/go/grpc/party" + "github.com/google/uuid" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +type partySettingsService struct { + pb.PartySettingsServiceServer + + r party.ReadWriter +} + +func newPartySettingsService(r party.ReadWriter) pb.PartySettingsServiceServer { + return &partySettingsService{ + r: r, + } +} + +func (p *partySettingsService) GetPartySettings(ctx context.Context, request *pb.GetPartySettingsRequest) (*pb.GetPartySettingsResponse, error) { + var playerId uuid.UUID + + if request.GetPartyId() != "" { + partyId, err := primitive.ObjectIDFromHex(request.GetPartyId()) + if err != nil { + return nil, status.New(codes.InvalidArgument, "partyId is invalid").Err() + } + + playerId, err = p.r.GetPartyLeaderByPartyId(ctx, partyId) + if err != nil { + if errors.Is(err, mongo.ErrNoDocuments) { + return nil, status.New(codes.NotFound, "party does not exist").Err() + } + return nil, status.New(codes.Internal, "error getting party").Err() + } + } else if request.GetPlayerId() != "" { + var err error + playerId, err = uuid.Parse(request.GetPlayerId()) + if err != nil { + return nil, status.New(codes.InvalidArgument, "playerId is invalid").Err() + } + } else { + return nil, status.New(codes.InvalidArgument, "partyId or playerId must be set").Err() + } + + settings, err := p.r.GetPartySettings(ctx, playerId) + if err != nil { + if errors.Is(err, mongo.ErrNoDocuments) { + return &pb.GetPartySettingsResponse{Settings: model.NewPartySettings(playerId).ToProto()}, nil + } + return nil, err + } + + return &pb.GetPartySettingsResponse{ + Settings: settings.ToProto(), + }, nil +} + +func (p *partySettingsService) UpdatePartySettings(ctx context.Context, request *pb.UpdatePartySettingsRequest) (*pb.UpdatePartySettingsResponse, error) { + playerId, err := uuid.Parse(request.IssuerId) + if err != nil { + return nil, status.New(codes.InvalidArgument, "issuerId is invalid").Err() + } + + settings, err := p.r.GetPartySettings(ctx, playerId) + if err != nil { + return nil, err + } + + if request.DequeueOnDisconnect != nil { + settings.DequeueOnDisconnect = *request.DequeueOnDisconnect + } + + if request.AllowMemberDequeue != nil { + settings.AllowMemberDequeue = *request.AllowMemberDequeue + } + + if request.AllowMemberInvite != nil { + settings.AllowMemberInvite = *request.AllowMemberInvite + } + + err = p.r.UpdatePartySettings(ctx, settings) + if err != nil { + return nil, status.New(codes.Internal, "error updating party settings").Err() + } + + // TODO: Notify + + return &pb.UpdatePartySettingsResponse{}, nil +} diff --git a/services/party-manager/internal/grpc/party_test.go b/services/party-manager/internal/grpc/party_test.go new file mode 100644 index 0000000..02537fd --- /dev/null +++ b/services/party-manager/internal/grpc/party_test.go @@ -0,0 +1,442 @@ +package grpc + +// +//import ( +// "context" +// pb "github.com/emortalmc/proto-specs/gen/go/grpc/party" +// pbmodel "github.com/emortalmc/proto-specs/gen/go/model/party" +// "github.com/golang/mock/gomock" +// "github.com/google/uuid" +// "github.com/stretchr/testify/assert" +// "go.mongodb.org/mongo-driver/bson/primitive" +// "go.mongodb.org/mongo-driver/mongo" +// "github.com/emortalmc/mono-services/services/party-manager/internal/kafka/writer" +// "github.com/emortalmc/mono-services/services/party-manager/internal/repository" +// "github.com/emortalmc/mono-services/services/party-manager/internal/repository/model" +// "testing" +// "time" +//) +// +//func TestPartyService_EmptyParty(t *testing.T) { +// partyId := primitive.NewObjectID() +// memberId := uuid.New() +// +// test := []struct { +// name string +// req *pb.EmptyPartyRequest +// +// getPartyByIdReq primitive.ObjectID +// getPartyByIdRes *model.Party +// getPartyByIdErr error +// +// getPartyByMemberIdReq uuid.UUID +// getPartyByMemberIdRes *model.Party +// getPartyByMemberIdErr error +// +// deletePartyReq primitive.ObjectID +// deletePartyErr error +// +// deletePartyInvitesByPartyIdReq bool +// deletePartyInvitesByPartyIdErr error +// +// wantErr error +// }{ +// { +// name: "success_by_party_id", +// req: &pb.EmptyPartyRequest{ +// Id: &pb.EmptyPartyRequest_PartyId{PartyId: partyId.Hex()}, +// }, +// +// getPartyByIdReq: partyId, +// getPartyByIdRes: &model.Party{ID: partyId, LeaderId: memberId, Members: []*model.PartyMember{{PlayerID: memberId, Username: "test"}}}, +// +// deletePartyReq: partyId, +// +// deletePartyInvitesByPartyIdReq: true, +// }, +// { +// name: "success_by_member_id", +// req: &pb.EmptyPartyRequest{ +// Id: &pb.EmptyPartyRequest_PlayerId{PlayerId: memberId.String()}, +// }, +// +// getPartyByMemberIdReq: memberId, +// getPartyByMemberIdRes: &model.Party{ID: partyId, LeaderId: memberId, Members: []*model.PartyMember{{PlayerID: memberId, Username: "test"}}}, +// +// deletePartyReq: partyId, +// +// deletePartyInvitesByPartyIdReq: true, +// }, +// } +// +// for _, tt := range test { +// t.Run(tt.name, func(t *testing.T) { +// ctx := context.Background() +// +// // Create mock r +// mockCntrl := gomock.NewController(t) +// defer mockCntrl.Finish() +// +// repo := repository.NewMockRepository(mockCntrl) +// +// if tt.req.GetPartyId() != "" { +// repo.EXPECT().GetPartyById(ctx, tt.getPartyByIdReq).Return(tt.getPartyByIdRes, tt.getPartyByIdErr) +// } +// if tt.getPartyByMemberIdReq != uuid.Nil { +// repo.EXPECT().GetPartyByMemberId(ctx, tt.getPartyByMemberIdReq).Return(tt.getPartyByMemberIdRes, tt.getPartyByMemberIdErr) +// } +// if tt.deletePartyReq != primitive.NilObjectID { +// var party *model.Party +// if tt.getPartyByIdRes != nil { +// party = tt.getPartyByIdRes +// } else if tt.getPartyByMemberIdRes != nil { +// party = tt.getPartyByMemberIdRes +// } +// +// leader, ok := party.GetMember(party.LeaderId) +// +// if ok { +// repo.EXPECT().SetPartyMembers(ctx, tt.deletePartyReq, []*model.PartyMember{leader}).Return(tt.deletePartyErr) +// } +// } +// if tt.deletePartyInvitesByPartyIdReq { +// repo.EXPECT().DeletePartyInvitesByPartyId(ctx, tt.deletePartyReq).Return(tt.deletePartyInvitesByPartyIdErr) +// } +// +// notif := writer.NewMockNotifier(mockCntrl) +// // If there are no errors yet, expect a notification +// if tt.deletePartyErr == nil && tt.getPartyByIdErr == nil && tt.getPartyByMemberIdErr == nil { +// var party *model.Party +// if tt.getPartyByIdRes != nil { +// party = tt.getPartyByIdRes +// } else if tt.getPartyByMemberIdRes != nil { +// party = tt.getPartyByMemberIdRes +// } +// notif.EXPECT().PartyEmptied(ctx, party) +// } +// +// s := newPartyService(notif, repo) +// +// res, err := s.EmptyParty(ctx, tt.req) +// assert.Equalf(t, tt.wantErr, err, "wantErr: %+v, got: %+v", tt.wantErr, err) +// assert.Empty(t, res) +// }) +// } +//} +// +//func TestPartyService_GetParty(t *testing.T) { +// partyId := primitive.NewObjectID() +// memberId := uuid.New() +// memberId2 := uuid.New() +// +// test := []struct { +// name string +// req *pb.GetPartyRequest +// +// getPartyByIdReq primitive.ObjectID +// getPartyByIdRes *model.Party +// getPartyByIdErr error +// +// getPartyByMemberIdReq uuid.UUID +// getPartyByMemberIdRes *model.Party +// getPartyByMemberIdErr error +// +// wantRes *pb.GetPartyResponse +// wantErr error +// }{ +// { +// name: "success_by_party_id", +// req: &pb.GetPartyRequest{ +// Id: &pb.GetPartyRequest_PartyId{PartyId: partyId.Hex()}, +// }, +// +// getPartyByIdReq: partyId, +// getPartyByIdRes: &model.Party{ +// ID: partyId, +// LeaderId: memberId, +// Members: []*model.PartyMember{{PlayerID: memberId, Username: "t"}, {PlayerID: memberId2, Username: "t2"}}, +// }, +// +// wantRes: &pb.GetPartyResponse{ +// Party: &pbmodel.Party{ +// Id: partyId.Hex(), +// LeaderId: memberId.String(), +// Members: []*pbmodel.PartyMember{{Id: memberId.String(), Username: "t"}, {Id: memberId2.String(), Username: "t2"}}, +// }, +// }, +// }, +// { +// name: "success_by_member_id", +// req: &pb.GetPartyRequest{ +// Id: &pb.GetPartyRequest_PlayerId{PlayerId: memberId.String()}, +// }, +// +// getPartyByMemberIdReq: memberId, +// getPartyByMemberIdRes: &model.Party{ +// ID: partyId, +// LeaderId: memberId, +// Members: []*model.PartyMember{{PlayerID: memberId, Username: "t"}, {PlayerID: memberId2, Username: "t2"}}, +// }, +// +// wantRes: &pb.GetPartyResponse{ +// Party: &pbmodel.Party{ +// Id: partyId.Hex(), +// LeaderId: memberId.String(), +// Members: []*pbmodel.PartyMember{{Id: memberId.String(), Username: "t"}, {Id: memberId2.String(), Username: "t2"}}, +// }, +// }, +// }, +// { +// name: "party_not_found_by_party_id", +// req: &pb.GetPartyRequest{ +// Id: &pb.GetPartyRequest_PartyId{PartyId: partyId.Hex()}, +// }, +// +// getPartyByIdReq: partyId, +// getPartyByIdErr: mongo.ErrNoDocuments, +// +// wantErr: partyNotFoundErr, +// }, +// { +// name: "party_not_found_by_member_id", +// req: &pb.GetPartyRequest{ +// Id: &pb.GetPartyRequest_PlayerId{PlayerId: memberId.String()}, +// }, +// +// getPartyByMemberIdReq: memberId, +// getPartyByMemberIdErr: mongo.ErrNoDocuments, +// +// wantErr: playerNotInPartyErr, +// }, +// } +// +// for _, tt := range test { +// t.Run(tt.name, func(t *testing.T) { +// ctx := context.Background() +// +// // Create mock r +// mockCntrl := gomock.NewController(t) +// defer mockCntrl.Finish() +// +// repo := repository.NewMockRepository(mockCntrl) +// +// if tt.getPartyByIdReq != primitive.NilObjectID { +// repo.EXPECT().GetPartyById(ctx, tt.getPartyByIdReq).Return(tt.getPartyByIdRes, tt.getPartyByIdErr) +// } +// if tt.getPartyByMemberIdReq != uuid.Nil { +// repo.EXPECT().GetPartyByMemberId(ctx, tt.getPartyByMemberIdReq).Return(tt.getPartyByMemberIdRes, tt.getPartyByMemberIdErr) +// } +// +// notif := writer.NewMockNotifier(mockCntrl) +// +// s := newPartyService(notif, repo) +// +// res, err := s.GetParty(ctx, tt.req) +// assert.Equalf(t, tt.wantErr, err, "wantErr: %+v, got: %+v", tt.wantErr, err) +// assert.Equalf(t, tt.wantRes, res, "wantRes: %+v, got: %+v", tt.wantRes, res) +// }) +// } +//} +// +//func TestPartyService_GetPartyInvites(t *testing.T) { +// partyId := primitive.NewObjectID() +// memberId := uuid.New() +// memberId2 := uuid.New() +// +// validPartyInvite := &model.PartyInvite{ +// ID: primitive.NewObjectID(), +// InviterID: memberId, +// InviterUsername: "t", +// TargetID: memberId2, +// TargetUsername: "t2", +// ExpiresAt: time.Now().Add(time.Hour), +// } +// +// var test = []struct { +// name string +// req *pb.GetPartyInvitesRequest +// +// getPartyIdByMemberIdReq uuid.UUID +// getPartyIdByMemberIdRes primitive.ObjectID +// getPartyIdByMemberIdErr error +// +// getPartyInvitesByPartyIdReq primitive.ObjectID +// getPartyInvitesByPartyIdRes []*model.PartyInvite +// getPartyInvitesByPartyIdErr error +// +// wantRes *pb.GetPartyInvitesResponse +// wantErr error +// }{ +// { +// name: "success_by_party_id", +// req: &pb.GetPartyInvitesRequest{ +// Id: &pb.GetPartyInvitesRequest_PartyId{PartyId: partyId.Hex()}, +// }, +// +// getPartyInvitesByPartyIdReq: partyId, +// getPartyInvitesByPartyIdRes: []*model.PartyInvite{validPartyInvite}, +// +// wantRes: &pb.GetPartyInvitesResponse{ +// Invites: []*pbmodel.PartyInvite{validPartyInvite.ToProto()}, +// }, +// }, +// { +// name: "success_by_member_id", +// req: &pb.GetPartyInvitesRequest{ +// Id: &pb.GetPartyInvitesRequest_PlayerId{PlayerId: memberId.String()}, +// }, +// +// getPartyIdByMemberIdReq: memberId, +// getPartyIdByMemberIdRes: partyId, +// +// getPartyInvitesByPartyIdReq: partyId, +// getPartyInvitesByPartyIdRes: []*model.PartyInvite{validPartyInvite}, +// +// wantRes: &pb.GetPartyInvitesResponse{ +// Invites: []*pbmodel.PartyInvite{validPartyInvite.ToProto()}, +// }, +// }, +// { +// name: "party_not_found_by_party_id", +// req: &pb.GetPartyInvitesRequest{ +// Id: &pb.GetPartyInvitesRequest_PartyId{PartyId: partyId.Hex()}, +// }, +// +// getPartyInvitesByPartyIdReq: partyId, +// getPartyInvitesByPartyIdErr: mongo.ErrNoDocuments, +// +// wantErr: partyNotFoundErr, +// }, +// { +// name: "party_not_found_by_member_id", +// req: &pb.GetPartyInvitesRequest{ +// Id: &pb.GetPartyInvitesRequest_PlayerId{PlayerId: memberId.String()}, +// }, +// +// getPartyIdByMemberIdReq: memberId, +// getPartyIdByMemberIdErr: mongo.ErrNoDocuments, +// +// wantErr: playerNotInPartyErr, +// }, +// } +// +// for _, tt := range test { +// t.Run(tt.name, func(t *testing.T) { +// ctx := context.Background() +// +// // Create mock r +// mockCntrl := gomock.NewController(t) +// defer mockCntrl.Finish() +// +// repo := repository.NewMockRepository(mockCntrl) +// +// if tt.getPartyIdByMemberIdReq != uuid.Nil { +// repo.EXPECT().GetPartyIdByMemberId(ctx, tt.getPartyIdByMemberIdReq).Return(tt.getPartyIdByMemberIdRes, tt.getPartyIdByMemberIdErr) +// } +// if tt.getPartyInvitesByPartyIdReq != primitive.NilObjectID { +// repo.EXPECT().GetPartyInvitesByPartyId(ctx, tt.getPartyInvitesByPartyIdReq).Return(tt.getPartyInvitesByPartyIdRes, tt.getPartyInvitesByPartyIdErr) +// } +// +// notif := writer.NewMockNotifier(mockCntrl) +// +// s := newPartyService(notif, repo) +// +// res, err := s.GetPartyInvites(ctx, tt.req) +// assert.Equalf(t, tt.wantErr, err, "wantErr: %+v, got: %+v", tt.wantErr, err) +// assert.Equalf(t, tt.wantRes, res, "wantRes: %+v, got: %+v", tt.wantRes, res) +// }) +// } +//} +// +//// TODO +////func TestPartyService_InvitePlayer(t *testing.T) { +//// playerIds := []uuid.UUID{uuid.New(), uuid.New(), uuid.New()} +//// playerUsernames := []string{"t", "t2", "t3"} +//// +//// partyId := primitive.NewObjectID() +//// +//// var test = []struct { +//// name string +//// req *pb.InvitePlayerRequest +//// +//// getPartyByMemberIdReq uuid.UUID +//// getPartyByMemberIdRes *model.Party +//// getPartyByMemberIdErr error +//// +//// // Note, will only ever get called if requester != leader +//// getPartySettingsRes *model.PartySettings +//// getPartySettingsErr error +//// +//// getPartyIdOfTargetReq uuid.UUID +//// getPartyIdOfTargetRes primitive.ObjectID +//// getPartyIdOfTargetErr error +//// +//// doesPartyInviteExistReqPartyId primitive.ObjectID +//// doesPartyInviteExistReqTargetId uuid.UUID +//// doesPartyInviteExistRes bool +//// doesPartyInviteExistErr error +//// +//// createPartyInviteReq *model.PartyInvite +//// createPartyInviteErr error +//// +//// wantRes *pb.InvitePlayerResponse +//// wantErr error +//// }{ +//// { +//// name: "success", +//// req: &pb.InvitePlayerRequest{ +//// IssuerId: playerIds[0].String(), +//// IssuerUsername: playerUsernames[0], +//// +//// TargetID: playerIds[0].String(), +//// TargetUsername: playerUsernames[0], +//// }, +//// +//// getPartyByMemberIdReq: playerIds[0], +//// getPartyByMemberIdRes: &model.Party{ +//// PlayerID: partyId, +//// LeaderId: playerIds[0], +//// Members: []*model.PartyMember{{PlayerID: playerIds[0], Username: playerUsernames[0]}}, +//// }, +//// +//// getPartyIdOfTargetReq: playerIds[1], +//// getPartyIdOfTargetRes: primitive.NilObjectID, +//// +//// doesPartyInviteExistReqPartyId: partyId, +//// doesPartyInviteExistReqTargetId: playerIds[1], +//// doesPartyInviteExistRes: false, +//// +//// createPartyInviteReq: &model.PartyInvite{ +//// PartyID: partyId, +//// } +//// }, +//// // Player 0 is inviting player 1 to the party. Player 2 is the leader and the party has all invites enabled. +//// { +//// name: "success_member_inviting", +//// req: &pb.InvitePlayerRequest{ +//// IssuerId: playerIds[0].String(), +//// IssuerUsername: playerUsernames[0], +//// +//// TargetID: playerIds[1].String(), +//// TargetUsername: playerUsernames[1], +//// }, +//// +//// getPartyByMemberIdReq: playerIds[0], +//// getPartyByMemberIdRes: &model.Party{ +//// PlayerID: partyId, +//// LeaderId: playerIds[2], +//// Members: []*model.PartyMember{{PlayerID: playerIds[0], Username: playerUsernames[0]}, {PlayerID: playerIds[2], Username: playerUsernames[2]}}, +//// }, +//// +//// getPartySettingsReq: partyId, +//// getPartySettingsRes: &model.PartySettings{ +//// AllowMemberInvite: true, +//// }, +//// +//// getPartyIdOfTargetReq: playerIds[1], +//// getPartyIdOfTargetRes: primitive.NilObjectID, +//// +//// doesPartyInviteExistReq: &model.PartyInvite{}, +//// }, +//// } +////} diff --git a/services/party-manager/internal/grpc/public.go b/services/party-manager/internal/grpc/public.go new file mode 100644 index 0000000..4a9c82c --- /dev/null +++ b/services/party-manager/internal/grpc/public.go @@ -0,0 +1,74 @@ +package grpc + +import ( + "context" + "fmt" + "github.com/emortalmc/mono-services/services/party-manager/internal/app/event" + "github.com/emortalmc/mono-services/services/party-manager/internal/app/party" + "github.com/emortalmc/mono-services/services/party-manager/internal/config" + "github.com/emortalmc/mono-services/services/party-manager/internal/repository" + pb "github.com/emortalmc/proto-specs/gen/go/grpc/party" + grpczap "github.com/grpc-ecosystem/go-grpc-middleware/logging/zap" + "github.com/zakshearman/go-grpc-health/pkg/health" + "go.uber.org/zap" + "go.uber.org/zap/zapcore" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/reflection" + "net" + "sync" +) + +func RunServices(ctx context.Context, logger *zap.SugaredLogger, wg *sync.WaitGroup, cfg *config.Config, + repo *repository.MongoRepository, partySvc *party.Service, eventSvc *event.Service) { + + lis, err := net.Listen("tcp", fmt.Sprintf(":%d", cfg.Port)) + if err != nil { + logger.Fatalw("failed to listen", "error", err) + } + + s := grpc.NewServer(grpc.ChainUnaryInterceptor( + grpczap.UnaryServerInterceptor(logger.Desugar(), grpczap.WithLevels(func(code codes.Code) zapcore.Level { + if code != codes.Internal && code != codes.Unavailable && code != codes.Unknown { + return zapcore.DebugLevel + } else { + return zapcore.ErrorLevel + } + })), + )) + + if cfg.Development { + reflection.Register(s) + } + + grpcPartySvc := newPartyService(repo, partySvc) + grpcPartySettingsSvc := newPartySettingsService(repo) + grpcEventSvc := newEventService(eventSvc, repo) + + pb.RegisterPartyServiceServer(s, grpcPartySvc) + pb.RegisterPartySettingsServiceServer(s, grpcPartySettingsSvc) + pb.RegisterEventServiceServer(s, grpcEventSvc) + + // Create health probe + healthSvc := health.NewHealthService() + healthSvc.AddProbe("repository", repo.HealthCheck) + + // Register health probe + health.RegisterHealthServiceServer(s, healthSvc) + + logger.Infow("listening on port", "port", cfg.Port) + + go func() { + if err := s.Serve(lis); err != nil { + logger.Fatalw("failed to serve", "error", err) + return + } + }() + + wg.Add(1) + go func() { + defer wg.Done() + <-ctx.Done() + s.GracefulStop() + }() +} diff --git a/services/party-manager/internal/kafka/consumer/consumer.go b/services/party-manager/internal/kafka/consumer/consumer.go new file mode 100644 index 0000000..a34b63a --- /dev/null +++ b/services/party-manager/internal/kafka/consumer/consumer.go @@ -0,0 +1,85 @@ +package consumer + +import ( + "context" + "fmt" + "github.com/emortalmc/mono-services/services/party-manager/internal/app/party" + "github.com/emortalmc/mono-services/services/party-manager/internal/config" + "github.com/emortalmc/proto-specs/gen/go/message/common" + "github.com/emortalmc/proto-specs/gen/go/nongenerated/kafkautils" + "github.com/google/uuid" + "github.com/segmentio/kafka-go" + "go.uber.org/zap" + "google.golang.org/protobuf/proto" + "sync" +) + +const connectionTopic = "mc-connections" + +type Consumer struct { + logger *zap.SugaredLogger + + partySvc *party.Service + + reader *kafka.Reader +} + +func NewConsumer(ctx context.Context, wg *sync.WaitGroup, config config.KafkaConfig, logger *zap.SugaredLogger, partySvc *party.Service) { + + reader := kafka.NewReader(kafka.ReaderConfig{ + Brokers: []string{fmt.Sprintf("%s:%d", config.Host, config.Port)}, + GroupID: "party-manager", + GroupTopics: []string{connectionTopic}, + + ErrorLogger: kafka.LoggerFunc(func(format string, args ...interface{}) { + logger.Errorw(fmt.Sprintf(format, args...)) + }), + }) + + c := &Consumer{ + logger: logger, + partySvc: partySvc, + reader: reader, + } + + handler := kafkautils.NewConsumerHandler(logger, reader) + handler.RegisterHandler(&common.PlayerConnectMessage{}, c.handlePlayerConnect) + handler.RegisterHandler(&common.PlayerDisconnectMessage{}, c.handlePlayerDisconnect) + + logger.Infow("started listening for kafka messages", "topics", reader.Config().GroupTopics) + + wg.Add(1) + go func() { + defer wg.Done() + handler.Run(ctx) // run is blocking until the context is cancelled + if err := reader.Close(); err != nil { + logger.Errorw("failed to close kafka reader", err) + } + }() +} + +// handlePlayerConnect creates a new party for a player +// when they join the server. +func (c *Consumer) handlePlayerConnect(ctx context.Context, _ *kafka.Message, uncastMsg proto.Message) { + m := uncastMsg.(*common.PlayerConnectMessage) + + playerId, err := uuid.Parse(m.PlayerId) + if err != nil { + c.logger.Errorw("failed to parse player id", err) + return + } + + c.partySvc.HandlePlayerConnect(ctx, playerId, m.PlayerUsername) +} + +func (c *Consumer) handlePlayerDisconnect(ctx context.Context, _ *kafka.Message, uncastMsg proto.Message) { + m := uncastMsg.(*common.PlayerDisconnectMessage) + + playerId, err := uuid.Parse(m.PlayerId) + if err != nil { + c.logger.Errorw("failed to parse player id", err) + return + } + + c.partySvc.HandlePlayerDisconnect(ctx, playerId) +} diff --git a/services/party-manager/internal/kafka/consumer/consumer_test.go b/services/party-manager/internal/kafka/consumer/consumer_test.go new file mode 100644 index 0000000..7d9b063 --- /dev/null +++ b/services/party-manager/internal/kafka/consumer/consumer_test.go @@ -0,0 +1,84 @@ +package consumer + +// +//import ( +// "github.com/emortalmc/mono-services/services/party-manager/internal/repository/model" +// "github.com/emortalmc/mono-services/services/party-manager/internal/utils" +// "testing" +//) +// +//var testUuids = utils.RandomUuidSlice(15) +// +//func createPartyWithMemberCount(mCount int) *model.Party { +// members := make([]*model.PartyMember, mCount) +// for i := 0; i < mCount; i++ { +// members[i] = &model.PartyMember{PlayerID: testUuids[i]} +// } +// +// return &model.Party{Members: members, LeaderId: testUuids[0]} +//} +// +//func TestElectNewPartyLeader(t *testing.T) { +// partyMap := make(map[int]*model.Party) +// for i := 1; i <= 10; i++ { // parties with 1-10 members +// partyMap[i] = createPartyWithMemberCount(i) +// } +// +// tests := []struct { +// name string +// repeats int +// +// party *model.Party +// +// acceptableResults []*model.PartyMember +// wantErr error +// }{ +// { +// name: "one member", +// party: partyMap[1], +// wantErr: leaderElectionNotEnoughMembersErr, +// }, +// { +// name: "two members", +// party: partyMap[2], +// }, +// { +// name: "three members", +// repeats: 300, +// party: partyMap[3], +// }, +// { +// name: "four members", +// repeats: 400, +// party: partyMap[4], +// }, +// { +// name: "10 members", +// repeats: 750, +// party: partyMap[10], +// }, +// } +// +// for _, test := range tests { +// for i := 0; i < test.repeats; i++ { +// t.Run(test.name, func(t *testing.T) { +// res, err := electNewPartyLeader(test.party) +// if err != test.wantErr { +// t.Errorf("got err %v, want %v", err, test.wantErr) +// } +// +// if test.wantErr != nil { +// return +// } +// +// for _, acceptableResult := range test.party.Members[1:] { +// if res == acceptableResult { +// return +// } +// } +// +// t.Errorf("got %v, want one of %v", res, test.acceptableResults) +// }) +// } +// } +//} diff --git a/services/party-manager/internal/kafka/writer/writer.gen.go b/services/party-manager/internal/kafka/writer/writer.gen.go new file mode 100644 index 0000000..a68e0d1 --- /dev/null +++ b/services/party-manager/internal/kafka/writer/writer.gen.go @@ -0,0 +1,158 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: internal/kafka/kafka_writer.go + +// Package kafka is a generated GoMock package. +package writer + +import ( + context "context" + model "github.com/emortalmc/mono-services/services/party-manager/internal/repository/model" + reflect "reflect" + + gomock "github.com/golang/mock/gomock" + uuid "github.com/google/uuid" + primitive "go.mongodb.org/mongo-driver/bson/primitive" +) + +// MockNotifier is a mock of Notifier interface. +type MockNotifier struct { + ctrl *gomock.Controller + recorder *MockNotifierMockRecorder +} + +// MockNotifierMockRecorder is the mock recorder for MockNotifier. +type MockNotifierMockRecorder struct { + mock *MockNotifier +} + +// NewMockNotifier creates a new mock instance. +func NewMockNotifier(ctrl *gomock.Controller) *MockNotifier { + mock := &MockNotifier{ctrl: ctrl} + mock.recorder = &MockNotifierMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockNotifier) EXPECT() *MockNotifierMockRecorder { + return m.recorder +} + +// PartyCreated mocks base method. +func (m *MockNotifier) PartyCreated(ctx context.Context, party *model.Party) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PartyCreated", ctx, party) +} + +// PartyCreated indicates an expected call of PartyCreated. +func (mr *MockNotifierMockRecorder) PartyCreated(ctx, party interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PartyCreated", reflect.TypeOf((*MockNotifier)(nil).PartyCreated), ctx, party) +} + +// PartyDeleted mocks base method. +func (m *MockNotifier) PartyDeleted(ctx context.Context, party *model.Party) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PartyDeleted", ctx, party) +} + +// PartyDeleted indicates an expected call of PartyDeleted. +func (mr *MockNotifierMockRecorder) PartyDeleted(ctx, party interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PartyDeleted", reflect.TypeOf((*MockNotifier)(nil).PartyDeleted), ctx, party) +} + +// PartyEmptied mocks base method. +func (m *MockNotifier) PartyEmptied(ctx context.Context, party *model.Party) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PartyEmptied", ctx, party) +} + +// PartyEmptied indicates an expected call of PartyEmptied. +func (mr *MockNotifierMockRecorder) PartyEmptied(ctx, party interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PartyEmptied", reflect.TypeOf((*MockNotifier)(nil).PartyEmptied), ctx, party) +} + +// PartyInviteCreated mocks base method. +func (m *MockNotifier) PartyInviteCreated(ctx context.Context, invite *model.PartyInvite) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PartyInviteCreated", ctx, invite) +} + +// PartyInviteCreated indicates an expected call of PartyInviteCreated. +func (mr *MockNotifierMockRecorder) PartyInviteCreated(ctx, invite interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PartyInviteCreated", reflect.TypeOf((*MockNotifier)(nil).PartyInviteCreated), ctx, invite) +} + +// PartyLeaderChanged mocks base method. +func (m *MockNotifier) PartyLeaderChanged(ctx context.Context, partyId primitive.ObjectID, newLeader *model.PartyMember) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PartyLeaderChanged", ctx, partyId, newLeader) +} + +// PartyLeaderChanged indicates an expected call of PartyLeaderChanged. +func (mr *MockNotifierMockRecorder) PartyLeaderChanged(ctx, partyId, newLeader interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PartyLeaderChanged", reflect.TypeOf((*MockNotifier)(nil).PartyLeaderChanged), ctx, partyId, newLeader) +} + +// PartyOpenChanged mocks base method. +func (m *MockNotifier) PartyOpenChanged(ctx context.Context, partyId primitive.ObjectID, open bool) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PartyOpenChanged", ctx, partyId, open) +} + +// PartyOpenChanged indicates an expected call of PartyOpenChanged. +func (mr *MockNotifierMockRecorder) PartyOpenChanged(ctx, partyId, open interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PartyOpenChanged", reflect.TypeOf((*MockNotifier)(nil).PartyOpenChanged), ctx, partyId, open) +} + +// PartyPlayerJoined mocks base method. +func (m *MockNotifier) PartyPlayerJoined(ctx context.Context, partyId primitive.ObjectID, player *model.PartyMember) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PartyPlayerJoined", ctx, partyId, player) +} + +// PartyPlayerJoined indicates an expected call of PartyPlayerJoined. +func (mr *MockNotifierMockRecorder) PartyPlayerJoined(ctx, partyId, player interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PartyPlayerJoined", reflect.TypeOf((*MockNotifier)(nil).PartyPlayerJoined), ctx, partyId, player) +} + +// PartyPlayerKicked mocks base method. +func (m *MockNotifier) PartyPlayerKicked(ctx context.Context, partyId primitive.ObjectID, kicked, kicker *model.PartyMember) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PartyPlayerKicked", ctx, partyId, kicked, kicker) +} + +// PartyPlayerKicked indicates an expected call of PartyPlayerKicked. +func (mr *MockNotifierMockRecorder) PartyPlayerKicked(ctx, partyId, kicked, kicker interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PartyPlayerKicked", reflect.TypeOf((*MockNotifier)(nil).PartyPlayerKicked), ctx, partyId, kicked, kicker) +} + +// PartyPlayerLeft mocks base method. +func (m *MockNotifier) PartyPlayerLeft(ctx context.Context, partyId primitive.ObjectID, player *model.PartyMember) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PartyPlayerLeft", ctx, partyId, player) +} + +// PartyPlayerLeft indicates an expected call of PartyPlayerLeft. +func (mr *MockNotifierMockRecorder) PartyPlayerLeft(ctx, partyId, player interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PartyPlayerLeft", reflect.TypeOf((*MockNotifier)(nil).PartyPlayerLeft), ctx, partyId, player) +} + +// PartySettingsChanged mocks base method. +func (m *MockNotifier) PartySettingsChanged(ctx context.Context, playerId uuid.UUID, settings *model.PartySettings) { + m.ctrl.T.Helper() + m.ctrl.Call(m, "PartySettingsChanged", ctx, playerId, settings) +} + +// PartySettingsChanged indicates an expected call of PartySettingsChanged. +func (mr *MockNotifierMockRecorder) PartySettingsChanged(ctx, playerId, settings interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "PartySettingsChanged", reflect.TypeOf((*MockNotifier)(nil).PartySettingsChanged), ctx, playerId, settings) +} diff --git a/services/party-manager/internal/kafka/writer/writer.go b/services/party-manager/internal/kafka/writer/writer.go new file mode 100644 index 0000000..b68ea45 --- /dev/null +++ b/services/party-manager/internal/kafka/writer/writer.go @@ -0,0 +1,185 @@ +package writer + +import ( + "context" + "fmt" + "github.com/emortalmc/mono-services/services/party-manager/internal/config" + "github.com/emortalmc/mono-services/services/party-manager/internal/repository/model" + partymsg "github.com/emortalmc/proto-specs/gen/go/message/party" + "github.com/google/uuid" + "github.com/segmentio/kafka-go" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.uber.org/zap" + "google.golang.org/protobuf/proto" + "sync" + "time" +) + +const partyWriteTopic = "party-manager" +const eventWriteTopic = "event-manager" + +type Notifier struct { + logger *zap.SugaredLogger + w *kafka.Writer +} + +func NewKafkaNotifier(ctx context.Context, wg *sync.WaitGroup, cfg config.KafkaConfig, logger *zap.SugaredLogger) *Notifier { + w := &kafka.Writer{ + Addr: kafka.TCP(fmt.Sprintf("%s:%d", cfg.Host, cfg.Port)), + Balancer: &kafka.LeastBytes{}, + Async: true, + BatchTimeout: 100 * time.Millisecond, + ErrorLogger: kafka.LoggerFunc(logger.Errorw), + } + + wg.Add(1) + go func() { + defer wg.Done() + <-ctx.Done() + if err := w.Close(); err != nil { + logger.Errorw("failed to close kafka writer", "err", err) + } + }() + + return &Notifier{ + logger: logger, + w: w, + } +} + +func (k *Notifier) PartyCreated(ctx context.Context, party *model.Party) { + msg := &partymsg.PartyCreatedMessage{Party: party.ToProto()} + + if err := k.writeMessage(ctx, msg, true); err != nil { + k.logger.Errorw("failed to write message", "err", err) + return + } +} + +func (k *Notifier) PartyDeleted(ctx context.Context, party *model.Party) { + msg := &partymsg.PartyDeletedMessage{Party: party.ToProto()} + + if err := k.writeMessage(ctx, msg, true); err != nil { + k.logger.Errorw("failed to write message", "err", err) + return + } +} + +func (k *Notifier) PartyEmptied(ctx context.Context, party *model.Party) { + msg := &partymsg.PartyEmptiedMessage{Party: party.ToProto()} + + if err := k.writeMessage(ctx, msg, true); err != nil { + k.logger.Errorw("failed to write message", "err", err) + return + } +} + +func (k *Notifier) PartyOpenChanged(ctx context.Context, partyId primitive.ObjectID, open bool) { + msg := &partymsg.PartyOpenChangedMessage{PartyId: partyId.Hex(), Open: open} + + if err := k.writeMessage(ctx, msg, true); err != nil { + k.logger.Errorw("failed to write message", "err", err) + return + } +} + +func (k *Notifier) PartyInviteCreated(ctx context.Context, invite *model.PartyInvite) { + msg := &partymsg.PartyInviteCreatedMessage{Invite: invite.ToProto()} + + if err := k.writeMessage(ctx, msg, true); err != nil { + k.logger.Errorw("failed to write message", "err", err) + return + } +} + +func (k *Notifier) PartyPlayerJoined(ctx context.Context, partyId primitive.ObjectID, player *model.PartyMember) { + msg := &partymsg.PartyPlayerJoinedMessage{PartyId: partyId.Hex(), Member: player.ToProto()} + + if err := k.writeMessage(ctx, msg, true); err != nil { + k.logger.Errorw("failed to write message", "err", err) + return + } +} + +func (k *Notifier) PartyPlayerLeft(ctx context.Context, partyId primitive.ObjectID, player *model.PartyMember) { + msg := &partymsg.PartyPlayerLeftMessage{PartyId: partyId.Hex(), Member: player.ToProto()} + + if err := k.writeMessage(ctx, msg, true); err != nil { + k.logger.Errorw("failed to write message", "err", err) + return + } +} + +func (k *Notifier) PartyPlayerKicked(ctx context.Context, partyId primitive.ObjectID, kicked *model.PartyMember, kicker *model.PartyMember) { + msg := &partymsg.PartyPlayerLeftMessage{PartyId: partyId.Hex(), Member: kicked.ToProto(), KickedBy: kicker.ToProto()} + + if err := k.writeMessage(ctx, msg, true); err != nil { + k.logger.Errorw("failed to write message", "err", err) + return + } +} + +func (k *Notifier) PartyLeaderChanged(ctx context.Context, partyId primitive.ObjectID, newLeader *model.PartyMember) { + msg := &partymsg.PartyLeaderChangedMessage{PartyId: partyId.Hex(), NewLeader: newLeader.ToProto()} + + if err := k.writeMessage(ctx, msg, true); err != nil { + k.logger.Errorw("failed to write message", "err", err) + return + } +} + +func (k *Notifier) PartySettingsChanged(ctx context.Context, playerId uuid.UUID, settings *model.PartySettings) { + msg := &partymsg.PartySettingsChangedMessage{PlayerId: playerId.String(), Settings: settings.ToProto()} + + if err := k.writeMessage(ctx, msg, true); err != nil { + k.logger.Errorw("failed to write message", "err", err) + return + } +} + +func (k *Notifier) DisplayEvent(ctx context.Context, event *model.Event) { + msg := &partymsg.EventDisplayMessage{Event: event.ToProto()} + + if err := k.writeMessage(ctx, msg, false); err != nil { + k.logger.Errorw("failed to write message", "err", err) + return + } +} + +func (k *Notifier) StartEvent(ctx context.Context, event *model.Event) { + msg := &partymsg.EventStartMessage{Event: event.ToProto()} + + if err := k.writeMessage(ctx, msg, false); err != nil { + k.logger.Errorw("failed to write message", "err", err) + return + } +} + +func (k *Notifier) DeleteEvent(ctx context.Context, event *model.Event) { + msg := &partymsg.EventDeleteMessage{Event: event.ToProto()} + + if err := k.writeMessage(ctx, msg, false); err != nil { + k.logger.Errorw("failed to write message", "err", err) + return + } +} + +func (k *Notifier) writeMessage(ctx context.Context, msg proto.Message, partyMsg bool) error { + bytes, err := proto.Marshal(msg) + if err != nil { + return fmt.Errorf("failed to marshal proto to bytes: %s", err) + } + + var topic string + if partyMsg { + topic = partyWriteTopic + } else { + topic = eventWriteTopic + } + + return k.w.WriteMessages(ctx, kafka.Message{ + Topic: topic, + Headers: []kafka.Header{{Key: "X-Proto-Type", Value: []byte(msg.ProtoReflect().Descriptor().FullName())}}, + Value: bytes, + }) +} diff --git a/services/party-manager/internal/repository/model/model.go b/services/party-manager/internal/repository/model/model.go new file mode 100644 index 0000000..f9f0d84 --- /dev/null +++ b/services/party-manager/internal/repository/model/model.go @@ -0,0 +1,189 @@ +package model + +import ( + "github.com/emortalmc/mono-services/services/party-manager/internal/utils" + "github.com/emortalmc/proto-specs/gen/go/model/common" + pb "github.com/emortalmc/proto-specs/gen/go/model/party" + "github.com/google/uuid" + "go.mongodb.org/mongo-driver/bson/primitive" + "google.golang.org/protobuf/types/known/timestamppb" + "time" +) + +type Party struct { + ID primitive.ObjectID `bson:"_id"` + + EventID string `bson:"eventId,omitempty"` + + LeaderId uuid.UUID `bson:"leaderId"` + Members []*PartyMember `bson:"members"` + + Open bool `bson:"open"` +} + +func NewParty(leaderId uuid.UUID, leaderUsername string) *Party { + return &Party{ + LeaderId: leaderId, + Members: []*PartyMember{{PlayerID: leaderId, Username: leaderUsername}}, + + Open: false, + } +} + +func (p *Party) ToProto() *pb.Party { + memberProtos := make([]*pb.PartyMember, len(p.Members)) + for i, member := range p.Members { + memberProtos[i] = member.ToProto() + } + + return &pb.Party{ + Id: p.ID.Hex(), + LeaderId: p.LeaderId.String(), + Members: memberProtos, + Open: p.Open, + } +} + +func (p *Party) ContainsMember(id uuid.UUID) bool { + for _, member := range p.Members { + if member.PlayerID == id { + return true + } + } + + return false +} + +func (p *Party) GetMember(id uuid.UUID) (member *PartyMember, ok bool) { + for _, loopMember := range p.Members { + if loopMember.PlayerID == id { + member = loopMember + ok = true + return + } + } + + return +} + +func (p *Party) IsEventParty() bool { + return p.EventID != "" +} + +type PartyMember struct { + PlayerID uuid.UUID `bson:"playerId"` + Username string `bson:"username"` +} + +func (m *PartyMember) ToProto() *pb.PartyMember { + return &pb.PartyMember{ + Id: m.PlayerID.String(), + Username: m.Username, + } +} + +type PartyInvite struct { + ID primitive.ObjectID `bson:"_id"` + PartyID primitive.ObjectID `bson:"partyId"` + + InviterID uuid.UUID `bson:"inviterId"` + InviterUsername string `bson:"inviterUsername"` + + TargetID uuid.UUID `bson:"targetId"` + TargetUsername string `bson:"targetUsername"` + + // ExpiresAt is the time at which the invite expires. + // Note: This depends on an expiry index being created on MongoDB that reads the expiresAt field. + ExpiresAt time.Time `bson:"expiresAt"` +} + +func (i *PartyInvite) ToProto() *pb.PartyInvite { + return &pb.PartyInvite{ + PartyId: i.PartyID.Hex(), + + TargetId: i.TargetID.String(), + TargetUsername: i.TargetUsername, + + SenderId: i.InviterID.String(), + SenderUsername: i.InviterUsername, + + ExpiresAt: timestamppb.New(i.ExpiresAt), + } +} + +type PartySettings struct { + PlayerID uuid.UUID `bson:"_id"` + + DequeueOnDisconnect bool `bson:"dequeueOnDisconnect"` + AllowMemberDequeue bool `bson:"allowMemberDequeue"` + AllowMemberInvite bool `bson:"allowMemberInvite"` + + // InDB is whether the settings originated from the database or not. + // If false, the default is probably returned. + InDB bool `bson:"-"` +} + +func NewPartySettings(playerId uuid.UUID) *PartySettings { + return &PartySettings{ + PlayerID: playerId, + + DequeueOnDisconnect: false, + AllowMemberDequeue: false, + AllowMemberInvite: false, + } +} + +func (s *PartySettings) ToProto() *pb.PartySettings { + return &pb.PartySettings{ + DequeueOnDisconnect: s.DequeueOnDisconnect, + AllowMemberDequeue: s.AllowMemberDequeue, + AllowMemberInvite: s.AllowMemberInvite, + } +} + +type PlayerSkin struct { + Texture string `bson:"texture"` + Signature string `bson:"signature"` +} + +type Event struct { + ID string `bson:"_id"` + + OwnerID uuid.UUID `bson:"ownerId"` + OwnerUsername string `bson:"ownerUsername"` + Skin PlayerSkin `bson:"skin"` + + DisplayTime *time.Time `bson:"displayTime"` + StartTime *time.Time `bson:"startTime"` + + // PartyID only present if the event has started. + PartyID *primitive.ObjectID `bson:"partyId,omitempty"` +} + +func (e *Event) ToProto() *pb.EventData { + var displayTime, startTime *timestamppb.Timestamp + if e.DisplayTime != nil { + displayTime = timestamppb.New(*e.DisplayTime) + } + if e.StartTime != nil { + startTime = timestamppb.New(*e.StartTime) + } + + var partyId *string + if e.PartyID != nil { + partyId = utils.PointerOf(e.PartyID.Hex()) + } + + return &pb.EventData{ + Id: e.ID, + OwnerId: e.OwnerID.String(), + OwnerUsername: e.OwnerUsername, + OwnerSkin: &common.PlayerSkin{ + Texture: e.Skin.Texture, + Signature: e.Skin.Signature, + }, + DisplayTime: displayTime, + StartTime: startTime, + PartyId: partyId, + } +} diff --git a/services/party-manager/internal/repository/model/model_test.go b/services/party-manager/internal/repository/model/model_test.go new file mode 100644 index 0000000..7652814 --- /dev/null +++ b/services/party-manager/internal/repository/model/model_test.go @@ -0,0 +1,174 @@ +package model + +import ( + pbmodel "github.com/emortalmc/proto-specs/gen/go/model/party" + "github.com/google/uuid" + "github.com/stretchr/testify/assert" + "go.mongodb.org/mongo-driver/bson/primitive" + "google.golang.org/protobuf/types/known/timestamppb" + "testing" + "time" +) + +func TestParty_ToProto(t *testing.T) { + partyId := primitive.NewObjectID() + playerIds := []uuid.UUID{uuid.New(), uuid.New()} + playerUsernames := []string{"test", "test2"} + + tests := []struct { + name string + party *Party + want *pbmodel.Party + }{ + { + name: "party to proto", + party: &Party{ + ID: partyId, + LeaderId: playerIds[0], + Members: []*PartyMember{{PlayerID: playerIds[0], Username: playerUsernames[0]}, {PlayerID: playerIds[1], Username: playerUsernames[1]}}, + }, + want: &pbmodel.Party{ + Id: partyId.Hex(), + LeaderId: playerIds[0].String(), + Members: []*pbmodel.PartyMember{{Id: playerIds[0].String(), Username: playerUsernames[0]}, {Id: playerIds[1].String(), Username: playerUsernames[1]}}, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + val := tt.party.ToProto() + assert.Equal(t, tt.want, val) + }) + } +} + +func TestParty_ContainsMember(t *testing.T) { + playerId := uuid.New() + tests := []struct { + name string + party *Party + testMemberId uuid.UUID + want bool + }{ + { + name: "party contains member", + party: &Party{ + Members: []*PartyMember{ + { + PlayerID: playerId, + }, + { + PlayerID: uuid.New(), + }, + }, + }, + testMemberId: playerId, + want: true, + }, + { + name: "party does not contain member", + party: &Party{ + Members: []*PartyMember{ + { + PlayerID: uuid.New(), + }, + { + PlayerID: playerId, + }, + }, + }, + testMemberId: uuid.New(), + want: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + val := tt.party.ContainsMember(tt.testMemberId) + assert.Equal(t, tt.want, val) + }) + } +} + +func TestPartyInvite_ToProto(t *testing.T) { + partyId := primitive.NewObjectID() + inviteId := primitive.NewObjectID() + + inviterId := uuid.New() + inviterUsername := "test" + + targetId := uuid.New() + targetUsername := "test2" + + expiresAt := time.Now().Add(time.Minute * 5) + + tests := []struct { + name string + invite *PartyInvite + want *pbmodel.PartyInvite + }{ + { + name: "party invite to proto", + invite: &PartyInvite{ + ID: inviteId, + PartyID: partyId, + + InviterID: inviterId, + InviterUsername: inviterUsername, + + TargetID: targetId, + TargetUsername: targetUsername, + ExpiresAt: expiresAt, + }, + want: &pbmodel.PartyInvite{ + PartyId: partyId.Hex(), + SenderId: inviterId.String(), + SenderUsername: inviterUsername, + TargetId: targetId.String(), + TargetUsername: targetUsername, + ExpiresAt: timestamppb.New(expiresAt), + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + val := tt.invite.ToProto() + assert.Equal(t, tt.want, val) + }) + } +} + +func TestPartySettings_ToProto(t *testing.T) { + playerId := uuid.New() + + tests := []struct { + name string + settings *PartySettings + want *pbmodel.PartySettings + }{ + { + name: "party settings to proto", + settings: &PartySettings{ + PlayerID: playerId, + + DequeueOnDisconnect: false, + AllowMemberDequeue: false, + AllowMemberInvite: false, + }, + want: &pbmodel.PartySettings{ + DequeueOnDisconnect: false, + AllowMemberDequeue: false, + AllowMemberInvite: false, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + val := tt.settings.ToProto() + assert.Equal(t, tt.want, val) + }) + } +} diff --git a/services/party-manager/internal/repository/mongo.go b/services/party-manager/internal/repository/mongo.go new file mode 100644 index 0000000..d4290c9 --- /dev/null +++ b/services/party-manager/internal/repository/mongo.go @@ -0,0 +1,657 @@ +package repository + +import ( + "context" + "errors" + "fmt" + "github.com/emortalmc/mono-services/services/party-manager/internal/config" + "github.com/emortalmc/mono-services/services/party-manager/internal/repository/model" + "github.com/emortalmc/mono-services/services/party-manager/internal/repository/registrytypes" + "github.com/google/uuid" + "github.com/zakshearman/go-grpc-health/pkg/health" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/bson/primitive" + "go.mongodb.org/mongo-driver/mongo" + "go.mongodb.org/mongo-driver/mongo/options" + "go.uber.org/zap" + "sync" + "time" +) + +const ( + databaseName = "party-manager" + + partyCollectionName = "party" + partyInviteCollectionName = "partyInvite" + partySettingsCollectionName = "partySettings" + eventCollectionName = "event" +) + +var ( + ErrAlreadyInParty = errors.New("player already in party") + ErrNotInParty = errors.New("player not in party") + ErrIdMustBeNil = errors.New("id must be nil") + ErrIdIsNil = errors.New("id must not be nil") + ErrAlreadyLeader = errors.New("player already leader") // TODO this isn't handled yet +) + +type MongoRepository struct { + logger *zap.SugaredLogger + + database *mongo.Database + + partyCollection *mongo.Collection + partyInviteCollection *mongo.Collection + partySettingsCollection *mongo.Collection + eventCollection *mongo.Collection +} + +func NewMongoRepository(ctx context.Context, logger *zap.SugaredLogger, wg *sync.WaitGroup, cfg config.MongoDBConfig) (*MongoRepository, error) { + client, err := mongo.Connect(ctx, options.Client().ApplyURI(cfg.URI).SetRegistry(createCodecRegistry())) + if err != nil { + return nil, err + } + + database := client.Database(databaseName) + repo := &MongoRepository{ + logger: logger, + + database: database, + + partyCollection: database.Collection(partyCollectionName), + partyInviteCollection: database.Collection(partyInviteCollectionName), + partySettingsCollection: database.Collection(partySettingsCollectionName), + eventCollection: database.Collection(eventCollectionName), + } + + wg.Add(1) + go func() { + defer wg.Done() + <-ctx.Done() + if err := client.Disconnect(ctx); err != nil { + logger.Errorw("failed to disconnect from mongo", err) + } + }() + + repo.createIndexes(ctx) + logger.Infow("created mongo indexes") + + return repo, nil +} + +var ( + partyIndexes = []mongo.IndexModel{ + { + Keys: bson.M{"leaderId": 1}, + Options: options.Index().SetName("leaderId").SetUnique(true), + }, + { + Keys: bson.M{"members.playerId": 1}, + Options: options.Index().SetName("members_playerId").SetUnique(true), + }, + } + + partyInviteIndexes = []mongo.IndexModel{ + { + Keys: bson.M{"partyId": 1}, + Options: options.Index().SetName("partyId"), + }, + { + Keys: bson.D{{Key: "partyId", Value: 1}, {Key: "targetId", Value: 1}}, + Options: options.Index().SetName("partyId_targetId").SetUnique(true), + }, + { + Keys: bson.M{"expiresAt": 1}, + Options: options.Index().SetName("expiresAt_TTL").SetExpireAfterSeconds(0), + }, + } +) + +func (m *MongoRepository) createIndexes(ctx context.Context) { + collIndexes := map[*mongo.Collection][]mongo.IndexModel{ + m.partyCollection: partyIndexes, + m.partyInviteCollection: partyInviteIndexes, + } + + wg := sync.WaitGroup{} + wg.Add(len(collIndexes)) + + for coll, indexes := range collIndexes { + go func(coll *mongo.Collection, indexes []mongo.IndexModel) { + defer wg.Done() + _, err := m.createCollIndexes(ctx, coll, indexes) + if err != nil { + panic(fmt.Sprintf("failed to create indexes for collection %s: %s", coll.Name(), err)) + } + }(coll, indexes) + } + + wg.Wait() +} + +func (m *MongoRepository) createCollIndexes(ctx context.Context, coll *mongo.Collection, indexes []mongo.IndexModel) (int, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + result, err := coll.Indexes().CreateMany(ctx, indexes) + if err != nil { + return 0, err + } + + return len(result), nil +} + +func (m *MongoRepository) HealthCheck(ctx context.Context) health.HealthStatus { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + err := m.database.Client().Ping(ctx, nil) + if err != nil { + m.logger.Errorw("failed to health check repository", err) + return health.HealthStatusUnhealthy + } + return health.HealthStatusHealthy +} + +func (m *MongoRepository) IsInParty(ctx context.Context, playerId uuid.UUID) (bool, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + count, err := m.partyCollection.CountDocuments(ctx, bson.M{"members.playerId": playerId}) + if err != nil { + return false, err + } + + return count > 0, nil +} + +func (m *MongoRepository) CreateParty(ctx context.Context, party *model.Party) error { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + if party.ID != primitive.NilObjectID { + return ErrIdMustBeNil + } + party.ID = primitive.NewObjectID() + + _, err := m.partyCollection.InsertOne(ctx, party) + if err != nil { + return err + } + + return nil +} + +func (m *MongoRepository) SetPartyMembers(ctx context.Context, partyId primitive.ObjectID, members []*model.PartyMember) error { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + _, err := m.partyCollection.UpdateByID(ctx, partyId, bson.M{"$set": bson.M{"members": members}}) + return err +} + +func (m *MongoRepository) DeleteParty(ctx context.Context, partyId primitive.ObjectID) error { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + err := m.partyCollection.FindOneAndDelete(ctx, bson.M{"_id": partyId}).Err() + return err +} + +func (m *MongoRepository) AddPartyMember(ctx context.Context, partyId primitive.ObjectID, member *model.PartyMember) error { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + res, err := m.partyCollection.UpdateByID(ctx, partyId, bson.M{"$addToSet": bson.M{"members": member}}) + if err != nil { + return err + } + + if res.MatchedCount == 0 { + return mongo.ErrNoDocuments + } + + if res.ModifiedCount == 0 { + return ErrAlreadyInParty + } + + return nil +} + +func (m *MongoRepository) SetPartyLeader(ctx context.Context, partyId primitive.ObjectID, leaderId uuid.UUID) error { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + res, err := m.partyCollection.UpdateByID(ctx, partyId, bson.M{"$set": bson.M{"leaderId": leaderId}}) + if err != nil { + return err + } + + if res.MatchedCount == 0 { + return mongo.ErrNoDocuments + } + + if res.ModifiedCount == 0 { + return ErrAlreadyLeader + } + + return nil +} + +func (m *MongoRepository) SetPartyOpen(ctx context.Context, partyId primitive.ObjectID, open bool) error { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + res, err := m.partyCollection.UpdateByID(ctx, partyId, bson.M{"$set": bson.M{"open": open}}) + if err != nil { + return err + } + + if res.MatchedCount == 0 { + return mongo.ErrNoDocuments + } + + return nil +} + +func (m *MongoRepository) SetPartyEventID(ctx context.Context, partyId primitive.ObjectID, eventId string) error { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + res, err := m.partyCollection.UpdateByID(ctx, partyId, bson.M{"$set": bson.M{"eventId": eventId}}) + if err != nil { + return err + } + + if res.MatchedCount == 0 { + return mongo.ErrNoDocuments + } + + return nil +} + +func (m *MongoRepository) RemovePartyEventID(ctx context.Context, partyId primitive.ObjectID) error { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + res, err := m.partyCollection.UpdateByID(ctx, partyId, bson.M{"$unset": bson.M{"eventId": ""}}) + if err != nil { + return err + } + + if res.MatchedCount == 0 { + return mongo.ErrNoDocuments + } + + return nil +} + +func (m *MongoRepository) GetPartyByID(ctx context.Context, partyId primitive.ObjectID) (*model.Party, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + var party model.Party + err := m.partyCollection.FindOne(ctx, bson.M{"_id": partyId}).Decode(&party) + if err != nil { + return nil, err + } + + return &party, nil +} + +func (m *MongoRepository) GetPartyByMemberID(ctx context.Context, playerId uuid.UUID) (*model.Party, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + var party model.Party + err := m.partyCollection.FindOne(ctx, bson.M{"members.playerId": playerId}).Decode(&party) + if err != nil { + return nil, err + } + + return &party, nil +} + +func (m *MongoRepository) GetPartyIdByMemberId(ctx context.Context, playerId uuid.UUID) (primitive.ObjectID, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + // Get only the id of the party + var result struct { + Id primitive.ObjectID `bson:"_id"` + } + err := m.partyCollection.FindOne(ctx, bson.M{"members.playerId": playerId}, options.FindOne().SetProjection(bson.M{"_id": 1})).Decode(&result) + if err != nil { + return primitive.NilObjectID, err + } + + return result.Id, nil +} + +func (m *MongoRepository) GetPartyLeaderIdByMemberId(ctx context.Context, playerId uuid.UUID) (uuid.UUID, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + // Get only the leaderId of the party + var result struct { + LeaderId uuid.UUID `bson:"leaderId"` + } + err := m.partyCollection.FindOne(ctx, bson.M{"members.playerId": playerId}, options.FindOne().SetProjection(bson.M{"leaderId": 1})).Decode(&result) + if err != nil { + return uuid.Nil, err + } + + return result.LeaderId, nil +} + +func (m *MongoRepository) GetPartyLeaderByPartyId(ctx context.Context, partyId primitive.ObjectID) (uuid.UUID, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + // Get only the leaderId of the party + var result struct { + LeaderId uuid.UUID `bson:"leaderId"` + } + err := m.partyCollection.FindOne(ctx, bson.M{"_id": partyId}, options.FindOne().SetProjection(bson.M{"leaderId": 1})).Decode(&result) + if err != nil { + return uuid.Nil, err + } + + return result.LeaderId, nil +} + +func (m *MongoRepository) RemoveMemberFromParty(ctx context.Context, partyId primitive.ObjectID, playerId uuid.UUID) error { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + res, err := m.partyCollection.UpdateByID(ctx, partyId, bson.M{"$pull": bson.M{"members": bson.M{"playerId": playerId}}}) + if err != nil { + return err + } + + if res.MatchedCount == 0 { + return mongo.ErrNoDocuments + } + + if res.ModifiedCount == 0 { + return ErrNotInParty + } + + return nil +} + +func (m *MongoRepository) RemoveMemberFromSelfParty(ctx context.Context, playerId uuid.UUID) error { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + res, err := m.partyCollection.UpdateOne(ctx, bson.M{"members.playerId": playerId}, bson.M{"$pull": bson.M{"members": bson.M{"playerId": playerId}}}) + if err != nil { + return err + } + + if res.MatchedCount == 0 { + return mongo.ErrNoDocuments + } + + return nil +} + +func (m *MongoRepository) CreatePartyInvite(ctx context.Context, invite *model.PartyInvite) error { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + if invite.ID != primitive.NilObjectID { + return ErrIdMustBeNil + } + invite.ID = primitive.NewObjectID() + + _, err := m.partyInviteCollection.InsertOne(ctx, invite) + if err != nil { + return err + } + + return nil +} + +func (m *MongoRepository) DeletePartyInvite(ctx context.Context, partyId primitive.ObjectID, targetId uuid.UUID) error { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + result, err := m.partyInviteCollection.DeleteOne(ctx, bson.M{"partyId": partyId, "targetId": targetId}) + if err != nil { + return err + } + + if result.DeletedCount == 0 { + return mongo.ErrNoDocuments + } + + return nil +} + +func (m *MongoRepository) DeletePartyInvitesByPartyId(ctx context.Context, partyId primitive.ObjectID) error { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + _, err := m.partyInviteCollection.DeleteMany(ctx, bson.M{"partyId": partyId}) + return err +} + +func (m *MongoRepository) GetPartyInvitesByPartyId(ctx context.Context, partyId primitive.ObjectID) ([]*model.PartyInvite, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + var invites []*model.PartyInvite + cursor, err := m.partyInviteCollection.Find(ctx, bson.M{"partyId": partyId}) + if err != nil { + return nil, err + } + + err = cursor.All(ctx, &invites) + if err != nil { + return nil, err + } + + return invites, nil +} + +func (m *MongoRepository) DoesPartyInviteExist(ctx context.Context, partyId primitive.ObjectID, playerId uuid.UUID) (bool, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + count, err := m.partyInviteCollection.CountDocuments(ctx, bson.M{"partyId": partyId, "targetId": playerId}) + if err != nil { + return false, err + } + + return count > 0, nil +} + +func (m *MongoRepository) GetPartySettings(ctx context.Context, playerId uuid.UUID) (*model.PartySettings, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + var settings model.PartySettings + err := m.partySettingsCollection.FindOne(ctx, bson.M{"_id": playerId}).Decode(&settings) + if err != nil { + return nil, err + } + + return &settings, nil +} + +func (m *MongoRepository) UpdatePartySettings(ctx context.Context, settings *model.PartySettings) error { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + _, err := m.partySettingsCollection.ReplaceOne(ctx, bson.M{"_id": settings.PlayerID}, settings, options.Replace().SetUpsert(true)) + if err != nil { + return err + } + + // NOTE: We don't care if the document was modified or not, because the settings are the same + return nil +} + +func (m *MongoRepository) CreateEvent(ctx context.Context, event *model.Event) error { + if event.ID == "" { + return ErrIdIsNil + } + + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + _, err := m.eventCollection.InsertOne(ctx, event) + if err != nil { + return fmt.Errorf("failed to create event: %w", err) + } + + return nil +} + +var ErrNoUpdateParams = errors.New("no update parameters") + +func (m *MongoRepository) UpdateEvent(ctx context.Context, eventId string, displayTime *time.Time, startTime *time.Time) (*model.Event, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + update := bson.M{} + if displayTime != nil { + update["displayTime"] = displayTime + } + if startTime != nil { + update["startTime"] = startTime + } + + if len(update) == 0 { + return nil, ErrNoUpdateParams + } + + res := m.eventCollection.FindOneAndUpdate(ctx, bson.M{"_id": eventId}, bson.M{"$set": update}) + if res.Err() != nil { + return nil, fmt.Errorf("failed to update event: %w", res.Err()) + } + + var event model.Event + if err := res.Decode(&event); err != nil { + return nil, fmt.Errorf("failed to decode updated event: %w", err) + } + + return &event, nil +} + +func (m *MongoRepository) DeleteEvent(ctx context.Context, eventId string) error { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + result, err := m.eventCollection.DeleteOne(ctx, bson.M{"_id": eventId}) + if err != nil { + return fmt.Errorf("failed to delete event: %w", err) + } + + if result.DeletedCount == 0 { + return mongo.ErrNoDocuments + } + + return nil +} + +func (m *MongoRepository) GetEventByID(ctx context.Context, eventId string) (*model.Event, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + var event model.Event + if err := m.eventCollection.FindOne(ctx, bson.M{"_id": eventId}).Decode(&event); err != nil { + return nil, fmt.Errorf("failed to get event by id: %w", err) + } + + return &event, nil +} + +func (m *MongoRepository) GetLiveEvent(ctx context.Context) (*model.Event, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + var event model.Event + if err := m.eventCollection.FindOne(ctx, bson.M{"started": true}).Decode(&event); err != nil { + return nil, fmt.Errorf("failed to get live event: %w", err) + } + + return &event, nil +} + +func (m *MongoRepository) ListEvents(ctx context.Context) ([]*model.Event, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + cursor, err := m.eventCollection.Find(ctx, bson.M{}) + if err != nil { + return nil, fmt.Errorf("failed to list events: %w", err) + } + + var events []*model.Event + err = cursor.All(ctx, &events) + if err != nil { + return nil, fmt.Errorf("failed to extract listed events: %w", err) + } + + return events, nil +} + +func (m *MongoRepository) SetEventPartyID(ctx context.Context, eventId string, partyId primitive.ObjectID) error { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + _, err := m.eventCollection.UpdateByID(ctx, eventId, bson.M{"$set": bson.M{"partyId": partyId}}) + if err != nil { + return fmt.Errorf("failed to set event party id: %w", err) + } + + return nil +} + +func (m *MongoRepository) GetEventToDisplay(ctx context.Context) (*model.Event, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + filter := bson.M{"$and": []bson.M{{"displayTime": bson.M{"$lte": time.Now()}}, {"displayed": bson.M{"$exists": false}}}} + res := m.eventCollection.FindOneAndUpdate(ctx, filter, bson.M{"$set": bson.M{"displayed": true}}) + if res.Err() != nil { + return nil, fmt.Errorf("failed to get event to display: %w", res.Err()) + } + + var event model.Event + if err := res.Decode(&event); err != nil { + return nil, fmt.Errorf("failed to decode event to display: %w", err) + } + + return &event, nil +} + +func (m *MongoRepository) GetEventToStart(ctx context.Context) (*model.Event, error) { + ctx, cancel := context.WithTimeout(ctx, 5*time.Second) + defer cancel() + + filter := bson.M{"$and": []bson.M{{"startTime": bson.M{"$lte": time.Now()}}, {"started": bson.M{"$exists": false}}}} + res := m.eventCollection.FindOneAndUpdate(ctx, filter, bson.M{"$set": bson.M{"started": true}}) + if res.Err() != nil { + return nil, fmt.Errorf("failed to get event to start: %w", res.Err()) + } + + var event model.Event + if err := res.Decode(&event); err != nil { + return nil, fmt.Errorf("failed to decode event to start: %w", err) + } + + return &event, nil +} + +func createCodecRegistry() *bsoncodec.Registry { + r := bson.NewRegistry() + + r.RegisterTypeEncoder(registrytypes.UUIDType, bsoncodec.ValueEncoderFunc(registrytypes.UuidEncodeValue)) + r.RegisterTypeDecoder(registrytypes.UUIDType, bsoncodec.ValueDecoderFunc(registrytypes.UuidDecodeValue)) + + return r +} diff --git a/services/party-manager/internal/repository/mongo_test.go b/services/party-manager/internal/repository/mongo_test.go new file mode 100644 index 0000000..349a24e --- /dev/null +++ b/services/party-manager/internal/repository/mongo_test.go @@ -0,0 +1,1181 @@ +package repository + +// +//import ( +// "context" +// "fmt" +// "github.com/google/uuid" +// "github.com/ory/dockertest/v3" +// "github.com/ory/dockertest/v3/docker" +// "github.com/stretchr/testify/assert" +// "go.mongodb.org/mongo-driver/bson" +// "go.mongodb.org/mongo-driver/bson/primitive" +// "go.mongodb.org/mongo-driver/mongo" +// "go.mongodb.org/mongo-driver/mongo/options" +// "go.uber.org/zap" +// "log" +// "os" +// "github.com/emortalmc/mono-services/services/party-manager/internal/config" +// "github.com/emortalmc/mono-services/services/party-manager/internal/repository/model" +// "sync" +// "testing" +// "time" +//) +// +//const ( +// mongoUri = "mongodb://root:password@localhost:%s" +//) +// +//var ( +// dbClient *mongo.Client +// database *mongo.Database +// repo Repository +//) +// +//// TODO some of the tests here don't check the database after operations are performed. +//// TODO This should be done. +// +//func TestMain(m *testing.M) { +// pool, err := dockertest.NewPool("") +// if err != nil { +// log.Fatalf("could not constuct pool: %s", err) +// } +// +// err = pool.Client.Ping() +// if err != nil { +// log.Fatalf("could not connect to docker: %s", err) +// } +// +// resource, err := pool.RunWithOptions(&dockertest.RunOptions{ +// Repository: "mongo", +// Tag: "6.0.5", +// Env: []string{ +// "MONGO_INITDB_ROOT_USERNAME=root", +// "MONGO_INITDB_ROOT_PASSWORD=password", +// }, +// }, func(cfg *docker.HostConfig) { +// cfg.AutoRemove = true +// cfg.RestartPolicy = docker.RestartPolicy{ +// Name: "no", +// } +// }) +// if err != nil { +// log.Fatalf("could not start resource: %s", err) +// } +// +// unsugaredLogger, err := zap.NewDevelopment() +// if err != nil { +// log.Fatalf("could not create logger: %s", err) +// } +// logger := unsugaredLogger.Sugar() +// +// uri := fmt.Sprintf(mongoUri, resource.GetPort("27017/tcp")) +// +// err = pool.Retry(func() (err error) { +// dbClient, err = mongo.Connect(context.Background(), options.Client().ApplyURI(uri).SetRegistry(createCodecRegistry())) +// if err != nil { +// return +// } +// err = dbClient.Ping(context.Background(), nil) +// if err != nil { +// return +// } +// +// // Ping was successful, let's create the mongo repo +// repo, err = NewMongoRepository(context.Background(), logger, &sync.WaitGroup{}, &config.MongoDBConfig{URI: uri}) +// database = dbClient.Database(databaseName) +// +// return +// }) +// +// if err != nil { +// log.Fatalf("could not connect to docker: %s", err) +// } +// +// code := m.Run() +// +// if err := pool.Purge(resource); err != nil { +// log.Fatalf("could not purge resource: %s", err) +// } +// +// os.Exit(code) +//} +// +//func TestMongoRepository_IsInParty(t *testing.T) { +// playerId := uuid.New() +// playerUsername := "test" +// +// tests := []struct { +// name string +// +// dbModel *model.Party +// +// player uuid.UUID +// +// want bool +// wantErr error +// }{ +// { +// name: "in_party", +// dbModel: &model.Party{ +// LeaderId: playerId, +// Members: []*model.PartyMember{{PlayerID: playerId, Username: playerUsername}}, +// }, +// +// player: playerId, +// +// want: true, +// wantErr: nil, +// }, +// { +// name: "not_in_party", +// dbModel: &model.Party{ +// LeaderId: playerId, +// Members: []*model.PartyMember{{PlayerID: playerId, Username: playerUsername}}, +// }, +// +// player: uuid.New(), +// +// want: false, +// wantErr: nil, +// }, +// } +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// t.Cleanup(cleanup) +// ctx := context.Background() +// +// collection := database.Collection(partyCollectionName) +// _, err := collection.InsertOne(ctx, tt.dbModel) +// assert.NoError(t, err) +// +// got, err := repo.IsInParty(ctx, tt.player) +// assert.Equal(t, tt.wantErr, err) +// assert.Equal(t, tt.want, got) +// }) +// } +//} +// +//func TestMongoRepository_CreateParty(t *testing.T) { +// playerId := uuid.New() +// playerUsername := "test" +// +// tests := []struct { +// name string +// +// party *model.Party +// +// wantErr error +// }{ +// { +// name: "success", +// party: &model.Party{ +// LeaderId: playerId, +// Members: []*model.PartyMember{{PlayerID: playerId, Username: playerUsername}}, +// }, +// +// wantErr: nil, +// }, +// { +// name: "failure_id_set", +// party: &model.Party{ +// ID: primitive.NewObjectID(), +// LeaderId: playerId, +// Members: []*model.PartyMember{{PlayerID: playerId, Username: playerUsername}}, +// }, +// wantErr: ErrIdMustBeNil, +// }, +// } +// +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// t.Cleanup(cleanup) +// ctx := context.Background() +// +// originalId := tt.party.ID +// +// err := repo.CreateParty(ctx, tt.party) +// assert.Equal(t, tt.wantErr, err) +// +// // Check the ID has been set +// if originalId == primitive.NilObjectID { +// assert.NotEmpty(t, tt.party.ID) +// } +// +// if tt.wantErr != nil { +// return +// } +// // Check if the party was created and is valid +// collection := database.Collection(partyCollectionName) +// var party model.Party +// +// err = collection.FindOne(ctx, bson.M{"_id": tt.party.ID}).Decode(&party) +// assert.NoError(t, err) +// assert.Equal(t, tt.party, &party) +// }) +// } +//} +// +//// todo +////func TestMongoRepository_SetPartyMembers(t *testing.T) { +//// party := &model.Party{ +//// ID: primitive.NewObjectID(), +//// LeaderId: uuid.New(), +//// Members: []*model.PartyMember{{PlayerID: uuid.New(), Username: "test"}}, +//// } +////} +// +//func TestMongoRepository_DeleteParty(t *testing.T) { +// party := &model.Party{ +// ID: primitive.NewObjectID(), +// LeaderId: uuid.New(), +// Members: []*model.PartyMember{{PlayerID: uuid.New(), Username: "test"}}, +// } +// +// tests := []struct { +// name string +// +// dbParty *model.Party +// +// partyId primitive.ObjectID +// +// wantErr error +// }{ +// { +// name: "success", +// dbParty: party, +// partyId: party.ID, +// wantErr: nil, +// }, +// { +// name: "failure_not_exists", +// dbParty: party, +// partyId: primitive.NewObjectID(), +// wantErr: mongo.ErrNoDocuments, +// }, +// } +// +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// t.Cleanup(cleanup) +// ctx := context.Background() +// +// collection := database.Collection(partyCollectionName) +// _, err := collection.InsertOne(ctx, tt.dbParty) +// assert.NoError(t, err) +// +// err = repo.DeleteParty(ctx, tt.partyId) +// assert.Equal(t, tt.wantErr, err) +// +// // Check the party was deleted in the database +// if tt.wantErr == nil { +// count, err := collection.CountDocuments(ctx, bson.M{"_id": tt.partyId}) +// assert.NoError(t, err) +// assert.Equal(t, int64(0), count) +// } +// }) +// } +//} +// +//func TestMongoRepository_AddPartyMember(t *testing.T) { +// partyMembers := []model.PartyMember{ +// {PlayerID: uuid.New(), Username: "test1"}, +// {PlayerID: uuid.New(), Username: "test2"}, +// } +// +// party := &model.Party{ +// ID: primitive.NewObjectID(), +// LeaderId: partyMembers[0].PlayerID, +// Members: []*model.PartyMember{&partyMembers[0]}, +// } +// +// tests := []struct { +// name string +// +// dbParty *model.Party +// +// partyId primitive.ObjectID +// addedMember *model.PartyMember +// +// wantErr error +// }{ +// { +// name: "success", +// +// dbParty: party, +// +// partyId: party.ID, +// addedMember: &partyMembers[1], +// +// wantErr: nil, +// }, +// { +// name: "failure_party_not_exists", +// +// dbParty: party, +// +// partyId: primitive.NewObjectID(), +// addedMember: &partyMembers[1], +// +// wantErr: mongo.ErrNoDocuments, +// }, +// { +// name: "failure_member_already_in_party", +// +// dbParty: party, +// +// partyId: party.ID, +// addedMember: &partyMembers[0], +// +// wantErr: ErrAlreadyInParty, +// }, +// } +// +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// t.Cleanup(cleanup) +// ctx := context.Background() +// +// collection := database.Collection(partyCollectionName) +// _, err := collection.InsertOne(ctx, tt.dbParty) +// assert.NoError(t, err) +// +// err = repo.AddPartyMember(ctx, tt.partyId, tt.addedMember) +// assert.Equal(t, tt.wantErr, err) +// +// // Check the party was updated in the database +// if tt.wantErr == nil { +// party := model.Party{} +// err = collection.FindOne(ctx, bson.M{"_id": tt.partyId}).Decode(&party) +// assert.NoError(t, err) +// assert.Contains(t, party.Members, tt.addedMember) +// } +// }) +// } +//} +// +//func TestMongoRepository_SetPartyLeader(t *testing.T) { +// partyMembers := []*model.PartyMember{ +// {PlayerID: uuid.New(), Username: "test1"}, +// {PlayerID: uuid.New(), Username: "test2"}, +// } +// +// party := &model.Party{ +// ID: primitive.NewObjectID(), +// LeaderId: partyMembers[0].PlayerID, +// Members: partyMembers, +// } +// +// tests := []struct { +// name string +// +// dbParty *model.Party +// +// partyId primitive.ObjectID +// setLeaderId uuid.UUID +// +// wantErr error +// }{ +// { +// name: "success", +// +// dbParty: party, +// +// partyId: party.ID, +// setLeaderId: partyMembers[1].PlayerID, +// +// wantErr: nil, +// }, +// { +// name: "failure_party_not_exists", +// +// dbParty: party, +// +// partyId: primitive.NewObjectID(), +// setLeaderId: partyMembers[1].PlayerID, +// +// wantErr: mongo.ErrNoDocuments, +// }, +// { +// name: "failure_already_leader", +// +// dbParty: party, +// +// partyId: party.ID, +// setLeaderId: partyMembers[0].PlayerID, +// +// wantErr: ErrAlreadyLeader, +// }, +// } +// +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// t.Cleanup(cleanup) +// ctx := context.Background() +// +// collection := database.Collection(partyCollectionName) +// _, err := collection.InsertOne(ctx, tt.dbParty) +// assert.NoError(t, err) +// +// err = repo.SetPartyLeader(ctx, tt.partyId, tt.setLeaderId) +// assert.Equal(t, tt.wantErr, err) +// +// // Check the party was updated in the database +// if tt.wantErr == nil { +// party := model.Party{} +// err = collection.FindOne(ctx, bson.M{"_id": tt.partyId}).Decode(&party) +// assert.NoError(t, err) +// assert.Equal(t, tt.setLeaderId, party.LeaderId) +// } +// }) +// } +//} +// +//func TestMongoRepository_GetPartyById(t *testing.T) { +// member := &model.PartyMember{PlayerID: uuid.New(), Username: "test"} +// +// party := &model.Party{ +// ID: primitive.NewObjectID(), +// LeaderId: member.PlayerID, +// Members: []*model.PartyMember{member}, +// } +// +// tests := []struct { +// name string +// +// dbParty *model.Party +// +// partyId primitive.ObjectID +// +// wantParty *model.Party +// wantErr error +// }{ +// { +// name: "success", +// dbParty: party, +// partyId: party.ID, +// +// wantParty: party, +// }, +// { +// name: "failure_party_not_exists", +// dbParty: party, +// partyId: primitive.NewObjectID(), +// +// wantErr: mongo.ErrNoDocuments, +// }, +// } +// +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// t.Cleanup(cleanup) +// ctx := context.Background() +// +// collection := database.Collection(partyCollectionName) +// _, err := collection.InsertOne(ctx, tt.dbParty) +// assert.NoError(t, err) +// +// party, err := repo.GetPartyByID(ctx, tt.partyId) +// assert.Equal(t, tt.wantErr, err) +// assert.Equal(t, tt.wantParty, party) +// }) +// } +//} +// +//func TestMongoRepository_GetPartyByMemberId(t *testing.T) { +// member := &model.PartyMember{PlayerID: uuid.New(), Username: "test"} +// +// party := &model.Party{ +// ID: primitive.NewObjectID(), +// LeaderId: member.PlayerID, +// Members: []*model.PartyMember{member}, +// } +// +// tests := []struct { +// name string +// +// dbParty *model.Party +// +// memberId uuid.UUID +// +// wantParty *model.Party +// wantErr error +// }{ +// { +// name: "success", +// dbParty: party, +// memberId: member.PlayerID, +// +// wantParty: party, +// }, +// { +// name: "failure_party_not_exists", +// dbParty: party, +// memberId: uuid.New(), +// +// wantErr: mongo.ErrNoDocuments, +// }, +// } +// +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// t.Cleanup(cleanup) +// ctx := context.Background() +// +// collection := database.Collection(partyCollectionName) +// _, err := collection.InsertOne(ctx, tt.dbParty) +// assert.NoError(t, err) +// +// party, err := repo.GetPartyByMemberID(ctx, tt.memberId) +// assert.Equal(t, tt.wantErr, err) +// assert.Equal(t, tt.wantParty, party) +// }) +// } +//} +// +//func TestMongoRepository_GetPartyIdByMemberId(t *testing.T) { +// member := &model.PartyMember{PlayerID: uuid.New(), Username: "test"} +// +// party := &model.Party{ +// ID: primitive.NewObjectID(), +// LeaderId: member.PlayerID, +// Members: []*model.PartyMember{member}, +// } +// +// tests := []struct { +// name string +// +// dbParty *model.Party +// +// memberId uuid.UUID +// +// wantPartyId primitive.ObjectID +// wantErr error +// }{ +// { +// name: "success", +// dbParty: party, +// memberId: member.PlayerID, +// +// wantPartyId: party.ID, +// }, +// { +// name: "failure_party_not_exists", +// dbParty: party, +// memberId: uuid.New(), +// +// wantErr: mongo.ErrNoDocuments, +// }, +// } +// +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// t.Cleanup(cleanup) +// ctx := context.Background() +// +// collection := database.Collection(partyCollectionName) +// _, err := collection.InsertOne(ctx, tt.dbParty) +// assert.NoError(t, err) +// +// partyId, err := repo.GetPartyIdByMemberId(ctx, tt.memberId) +// assert.Equal(t, tt.wantErr, err) +// assert.Equal(t, tt.wantPartyId, partyId) +// }) +// } +//} +// +//func TestMongoRepository_GetPartyLeaderIdByMemberId(t *testing.T) { +// members := []*model.PartyMember{{PlayerID: uuid.New(), Username: "test1"}, {PlayerID: uuid.New(), Username: "test2"}} +// +// party := &model.Party{ +// ID: primitive.NewObjectID(), +// LeaderId: members[0].PlayerID, +// Members: members, +// } +// +// tests := []struct { +// name string +// +// dbParty *model.Party +// +// targetId uuid.UUID +// +// wantLeaderId uuid.UUID +// wantErr error +// }{ +// { +// name: "success", +// dbParty: party, +// targetId: members[0].PlayerID, +// +// wantLeaderId: party.LeaderId, +// }, +// { +// name: "success_not_leader", +// dbParty: party, +// targetId: members[1].PlayerID, +// +// wantLeaderId: party.LeaderId, +// }, +// { +// name: "failure_party_not_exists", +// dbParty: party, +// targetId: uuid.New(), +// +// wantErr: mongo.ErrNoDocuments, +// }, +// } +// +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// t.Cleanup(cleanup) +// ctx := context.Background() +// +// collection := database.Collection(partyCollectionName) +// _, err := collection.InsertOne(ctx, tt.dbParty) +// assert.NoError(t, err) +// +// leaderId, err := repo.GetPartyLeaderIdByMemberId(ctx, tt.targetId) +// assert.Equal(t, tt.wantErr, err) +// assert.Equal(t, tt.wantLeaderId, leaderId) +// }) +// } +//} +// +//func TestMongoRepository_RemoveMemberFromParty(t *testing.T) { +// partyMembers := []*model.PartyMember{{PlayerID: uuid.New(), Username: "test1"}, {PlayerID: uuid.New(), Username: "test2"}} +// party := &model.Party{ +// ID: primitive.NewObjectID(), +// LeaderId: partyMembers[0].PlayerID, +// Members: partyMembers, +// } +// +// tests := []struct { +// name string +// +// dbParty *model.Party +// +// partyId primitive.ObjectID +// memberId uuid.UUID +// +// wantParty *model.Party +// wantErr error +// }{ +// { +// name: "success", +// dbParty: party, +// partyId: party.ID, +// memberId: partyMembers[1].PlayerID, +// +// wantParty: &model.Party{ +// ID: party.ID, +// LeaderId: party.LeaderId, +// Members: []*model.PartyMember{partyMembers[0]}, +// }, +// }, +// { +// name: "failure_party_not_exists", +// dbParty: party, +// partyId: primitive.NewObjectID(), +// memberId: partyMembers[1].PlayerID, +// +// wantParty: party, +// wantErr: mongo.ErrNoDocuments, +// }, +// { +// name: "failure_member_not_in_party", +// dbParty: party, +// partyId: party.ID, +// memberId: uuid.New(), +// +// wantParty: party, +// wantErr: ErrNotInParty, +// }, +// } +// +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// t.Cleanup(cleanup) +// ctx := context.Background() +// +// collection := database.Collection(partyCollectionName) +// _, err := collection.InsertOne(ctx, tt.dbParty) +// assert.NoError(t, err) +// +// err = repo.RemoveMemberFromParty(ctx, tt.partyId, tt.memberId) +// assert.Equal(t, tt.wantErr, err) +// +// var party *model.Party +// err = collection.FindOne(ctx, bson.M{"_id": tt.dbParty.ID}).Decode(&party) +// assert.NoError(t, err) +// assert.Equal(t, tt.wantParty, party) +// }) +// } +//} +// +//func TestMongoRepository_RemoveMemberFromSelfParty(t *testing.T) { +// members := []*model.PartyMember{{PlayerID: uuid.New(), Username: "test1"}, {PlayerID: uuid.New(), Username: "test2"}} +// party := &model.Party{ +// ID: primitive.NewObjectID(), +// LeaderId: members[0].PlayerID, +// Members: members, +// } +// +// tests := []struct { +// name string +// +// dbParty *model.Party +// +// memberId uuid.UUID +// +// wantParty *model.Party +// wantErr error +// }{ +// { +// name: "success", +// dbParty: party, +// memberId: members[1].PlayerID, +// +// wantParty: &model.Party{ +// ID: party.ID, +// LeaderId: party.LeaderId, +// Members: []*model.PartyMember{members[0]}, +// }, +// }, +// { +// name: "failure_member_not_in_party", +// dbParty: party, +// memberId: uuid.New(), +// +// wantParty: party, +// wantErr: mongo.ErrNoDocuments, +// }, +// } +// +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// t.Cleanup(cleanup) +// ctx := context.Background() +// +// collection := database.Collection(partyCollectionName) +// _, err := collection.InsertOne(ctx, tt.dbParty) +// assert.NoError(t, err) +// +// err = repo.RemoveMemberFromSelfParty(ctx, tt.memberId) +// assert.Equal(t, tt.wantErr, err) +// +// var party *model.Party +// err = collection.FindOne(ctx, bson.M{"_id": tt.dbParty.ID}).Decode(&party) +// assert.NoError(t, err) +// assert.Equal(t, tt.wantParty, party) +// }) +// } +//} +// +//func TestMongoRepository_CreatePartyInvite(t *testing.T) { +// invite := &model.PartyInvite{ +// InviterID: uuid.New(), +// InviterUsername: "test", +// +// TargetID: uuid.New(), +// TargetUsername: "test2", +// +// ExpiresAt: time.UnixMilli(time.Now().UnixMilli()).In(time.UTC), +// } +// +// tests := []struct { +// name string +// invite *model.PartyInvite +// wantErr error +// }{ +// { +// name: "success", +// invite: invite, +// }, +// { +// name: "failure_id_specified", +// invite: &model.PartyInvite{ +// ID: primitive.NewObjectID(), +// }, +// wantErr: ErrIdMustBeNil, +// }, +// } +// +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// t.Cleanup(cleanup) +// ctx := context.Background() +// +// err := repo.CreatePartyInvite(ctx, tt.invite) +// assert.Equal(t, tt.wantErr, err) +// assert.NotEqual(t, primitive.NilObjectID, tt.invite.ID) +// +// if tt.wantErr == nil { +// // Retrieve the invite from the database and compare it to the one we created +// collection := database.Collection(partyInviteCollectionName) +// var dbInvite *model.PartyInvite +// err = collection.FindOne(ctx, bson.M{"_id": tt.invite.ID}).Decode(&dbInvite) +// assert.NoError(t, err) +// assert.Equal(t, tt.invite, dbInvite) +// } +// }) +// } +//} +// +//func TestMongoRepository_DeletePartyInvite(t *testing.T) { +// invite := &model.PartyInvite{ +// InviterID: uuid.New(), +// InviterUsername: "test", +// +// TargetID: uuid.New(), +// TargetUsername: "test2", +// +// ExpiresAt: time.UnixMilli(time.Now().UnixMilli()).In(time.UTC), +// } +// +// tests := []struct { +// name string +// +// dbInvite *model.PartyInvite +// +// partyId primitive.ObjectID +// targetId uuid.UUID +// +// wantErr error +// wantPresent bool +// }{ +// { +// name: "success", +// +// dbInvite: invite, +// +// partyId: invite.PartyID, +// targetId: invite.TargetID, +// +// wantPresent: false, +// }, +// { +// name: "failure_wrong_party_id", +// +// dbInvite: invite, +// +// partyId: primitive.NewObjectID(), +// targetId: invite.TargetID, +// +// wantErr: mongo.ErrNoDocuments, +// wantPresent: true, +// }, +// { +// name: "failure_wrong_target_id", +// +// dbInvite: invite, +// +// partyId: invite.PartyID, +// targetId: uuid.New(), +// +// wantErr: mongo.ErrNoDocuments, +// wantPresent: true, +// }, +// } +// +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// t.Cleanup(cleanup) +// ctx := context.Background() +// +// collection := database.Collection(partyInviteCollectionName) +// _, err := collection.InsertOne(ctx, tt.dbInvite) +// assert.NoError(t, err) +// +// err = repo.DeletePartyInvite(ctx, tt.partyId, tt.targetId) +// assert.Equal(t, tt.wantErr, err) +// +// count, err := collection.CountDocuments(ctx, bson.M{"_id": tt.dbInvite.ID}) +// assert.NoError(t, err) +// assert.Equal(t, tt.wantPresent, count > 0) +// }) +// } +//} +// +//func TestMongoRepository_GetPartyInvitesByPartyId(t *testing.T) { +// partyId := primitive.NewObjectID() +// +// invites := []*model.PartyInvite{ +// { +// ID: primitive.NewObjectID(), +// PartyID: partyId, +// InviterID: uuid.New(), +// InviterUsername: "test", +// TargetID: uuid.New(), +// TargetUsername: "test2", +// ExpiresAt: time.UnixMilli(time.Now().UnixMilli()).In(time.UTC), +// }, +// { +// ID: primitive.NewObjectID(), +// PartyID: partyId, +// InviterID: uuid.New(), +// InviterUsername: "test", +// TargetID: uuid.New(), +// TargetUsername: "test3", +// ExpiresAt: time.UnixMilli(time.Now().UnixMilli()).In(time.UTC), +// }, +// { +// ID: primitive.NewObjectID(), +// PartyID: primitive.NewObjectID(), +// InviterID: uuid.New(), +// InviterUsername: "otherPartyTest", +// TargetID: uuid.New(), +// TargetUsername: "otherPartyTest2", +// ExpiresAt: time.UnixMilli(time.Now().UnixMilli()).In(time.UTC), +// }, +// } +// +// tests := []struct { +// name string +// +// dbInvites []*model.PartyInvite +// +// partyId primitive.ObjectID +// +// wantInvites []*model.PartyInvite +// }{ +// { +// name: "success", +// dbInvites: invites, +// partyId: partyId, +// +// wantInvites: invites[:2], +// }, +// { +// name: "failure_party_not_found", +// dbInvites: invites, +// partyId: primitive.NewObjectID(), +// +// wantInvites: nil, +// }, +// } +// +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// t.Cleanup(cleanup) +// ctx := context.Background() +// +// collection := database.Collection(partyInviteCollectionName) +// for _, invite := range tt.dbInvites { +// _, err := collection.InsertOne(ctx, invite) +// assert.NoError(t, err) +// } +// +// invites, err := repo.GetPartyInvitesByPartyId(ctx, tt.partyId) +// assert.Nil(t, err) +// assert.ElementsMatch(t, tt.wantInvites, invites) +// }) +// } +//} +// +//func TestMongoRepository_DoesPartyInviteExist(t *testing.T) { +// invites := []*model.PartyInvite{ +// { +// ID: primitive.NewObjectID(), +// PartyID: primitive.NewObjectID(), +// InviterID: uuid.New(), +// InviterUsername: "test", +// TargetID: uuid.New(), +// TargetUsername: "test2", +// ExpiresAt: time.UnixMilli(time.Now().UnixMilli()).In(time.UTC), +// }, +// { +// ID: primitive.NewObjectID(), +// PartyID: primitive.NewObjectID(), +// InviterID: uuid.New(), +// InviterUsername: "test3", +// TargetID: uuid.New(), +// TargetUsername: "test4", +// ExpiresAt: time.UnixMilli(time.Now().UnixMilli()).In(time.UTC), +// }, +// } +// +// tests := []struct { +// name string +// +// dbInvites []*model.PartyInvite +// +// partyId primitive.ObjectID +// targetId uuid.UUID +// +// wantExists bool +// }{ +// { +// name: "success", +// +// dbInvites: invites, +// +// partyId: invites[0].PartyID, +// targetId: invites[0].TargetID, +// +// wantExists: true, +// }, +// { +// name: "failure_party_not_found", +// +// dbInvites: invites, +// +// partyId: primitive.NewObjectID(), +// targetId: invites[0].TargetID, +// +// wantExists: false, +// }, +// { +// name: "failure_target_not_invited", +// +// dbInvites: invites, +// +// partyId: invites[0].PartyID, +// targetId: uuid.New(), +// +// wantExists: false, +// }, +// } +// +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// t.Cleanup(cleanup) +// ctx := context.Background() +// +// collection := database.Collection(partyInviteCollectionName) +// for _, invite := range tt.dbInvites { +// _, err := collection.InsertOne(ctx, invite) +// assert.NoError(t, err) +// } +// +// exists, err := repo.DoesPartyInviteExist(ctx, tt.partyId, tt.targetId) +// assert.NoError(t, err) +// assert.Equal(t, tt.wantExists, exists) +// }) +// } +//} +// +//func TestMongoRepository_GetPartySettings(t *testing.T) { +// settings := model.NewPartySettings(uuid.New()) +// +// tests := []struct { +// name string +// +// dbSettings *model.PartySettings +// +// playerId uuid.UUID +// +// wantSettings *model.PartySettings +// wantErr error +// }{ +// { +// name: "success", +// dbSettings: settings, +// +// playerId: settings.PlayerID, +// +// wantSettings: settings, +// }, +// { +// name: "failure_not_found", +// dbSettings: settings, +// +// playerId: uuid.New(), +// +// wantSettings: nil, +// wantErr: mongo.ErrNoDocuments, +// }, +// } +// +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// t.Cleanup(cleanup) +// ctx := context.Background() +// +// collection := database.Collection(partySettingsCollectionName) +// _, err := collection.InsertOne(ctx, tt.dbSettings) +// assert.NoError(t, err) +// +// settings, err := repo.GetPartySettings(ctx, tt.playerId) +// assert.Equal(t, tt.wantErr, err) +// assert.Equal(t, tt.wantSettings, settings) +// }) +// } +//} +// +//func TestMongoRepository_UpdatePartySettings(t *testing.T) { +// settings := model.NewPartySettings(uuid.New()) +// +// settings.AllowMemberDequeue = !settings.AllowMemberDequeue +// settings.AllowMemberInvite = !settings.AllowMemberInvite +// +// tests := []struct { +// name string +// +// dbSettings *model.PartySettings +// +// updateSettings *model.PartySettings +// +// wantErr bool +// }{ +// { +// name: "success", +// dbSettings: settings, +// +// updateSettings: settings, +// wantErr: false, +// }, +// { +// name: "success_no_changes", +// dbSettings: settings, +// +// updateSettings: settings, +// wantErr: false, +// }, +// { +// name: "success_no_found", +// dbSettings: settings, +// +// updateSettings: model.NewPartySettings(uuid.New()), +// wantErr: false, +// }, +// } +// +// for _, tt := range tests { +// t.Run(tt.name, func(t *testing.T) { +// t.Cleanup(cleanup) +// ctx := context.Background() +// +// collection := database.Collection(partySettingsCollectionName) +// _, err := collection.InsertOne(ctx, tt.dbSettings) +// assert.NoError(t, err) +// +// err = repo.UpdatePartySettings(ctx, tt.updateSettings) +// if tt.wantErr { +// assert.Error(t, err) +// } else { +// assert.NoError(t, err) +// } +// +// if !tt.wantErr { +// settings, err := repo.GetPartySettings(ctx, tt.updateSettings.PlayerID) +// assert.NoError(t, err) +// assert.Equal(t, tt.updateSettings, settings) +// +// // If the player IDs are different, ensure both settings are in the database +// if tt.updateSettings.PlayerID != tt.dbSettings.PlayerID { +// settings, err := repo.GetPartySettings(ctx, tt.dbSettings.PlayerID) +// assert.NoError(t, err) +// assert.Equal(t, tt.dbSettings, settings) +// } +// } +// }) +// } +//} +// +//func cleanup() { +// ctx := context.Background() +// if err := database.Drop(ctx); err != nil { +// log.Panicf("could not drop database: %s", err) +// } +//} diff --git a/services/party-manager/internal/repository/public_mock.gen.go b/services/party-manager/internal/repository/public_mock.gen.go new file mode 100644 index 0000000..b7aa151 --- /dev/null +++ b/services/party-manager/internal/repository/public_mock.gen.go @@ -0,0 +1,356 @@ +// Code generated by MockGen. DO NOT EDIT. +// Source: internal/repository/public.go + +// Package repository is a generated GoMock package. +package repository + +import ( + context "context" + model "github.com/emortalmc/mono-services/services/party-manager/internal/repository/model" + reflect "reflect" + + gomock "github.com/golang/mock/gomock" + uuid "github.com/google/uuid" + health "github.com/zakshearman/go-grpc-health/pkg/health" + primitive "go.mongodb.org/mongo-driver/bson/primitive" +) + +// MockRepository is a mock of Repository interface. +type MockRepository struct { + ctrl *gomock.Controller + recorder *MockRepositoryMockRecorder +} + +// MockRepositoryMockRecorder is the mock recorder for MockRepository. +type MockRepositoryMockRecorder struct { + mock *MockRepository +} + +// NewMockRepository creates a new mock instance. +func NewMockRepository(ctrl *gomock.Controller) *MockRepository { + mock := &MockRepository{ctrl: ctrl} + mock.recorder = &MockRepositoryMockRecorder{mock} + return mock +} + +// EXPECT returns an object that allows the caller to indicate expected use. +func (m *MockRepository) EXPECT() *MockRepositoryMockRecorder { + return m.recorder +} + +// AddPartyMember mocks base method. +func (m *MockRepository) AddPartyMember(ctx context.Context, partyId primitive.ObjectID, member *model.PartyMember) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "AddPartyMember", ctx, partyId, member) + ret0, _ := ret[0].(error) + return ret0 +} + +// AddPartyMember indicates an expected call of AddPartyMember. +func (mr *MockRepositoryMockRecorder) AddPartyMember(ctx, partyId, member interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "AddPartyMember", reflect.TypeOf((*MockRepository)(nil).AddPartyMember), ctx, partyId, member) +} + +// CreateParty mocks base method. +func (m *MockRepository) CreateParty(ctx context.Context, party *model.Party) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CreateParty", ctx, party) + ret0, _ := ret[0].(error) + return ret0 +} + +// CreateParty indicates an expected call of CreateParty. +func (mr *MockRepositoryMockRecorder) CreateParty(ctx, party interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreateParty", reflect.TypeOf((*MockRepository)(nil).CreateParty), ctx, party) +} + +// CreatePartyInvite mocks base method. +func (m *MockRepository) CreatePartyInvite(ctx context.Context, invite *model.PartyInvite) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "CreatePartyInvite", ctx, invite) + ret0, _ := ret[0].(error) + return ret0 +} + +// CreatePartyInvite indicates an expected call of CreatePartyInvite. +func (mr *MockRepositoryMockRecorder) CreatePartyInvite(ctx, invite interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "CreatePartyInvite", reflect.TypeOf((*MockRepository)(nil).CreatePartyInvite), ctx, invite) +} + +// DeleteParty mocks base method. +func (m *MockRepository) DeleteParty(ctx context.Context, partyId primitive.ObjectID) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DeleteParty", ctx, partyId) + ret0, _ := ret[0].(error) + return ret0 +} + +// DeleteParty indicates an expected call of DeleteParty. +func (mr *MockRepositoryMockRecorder) DeleteParty(ctx, partyId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeleteParty", reflect.TypeOf((*MockRepository)(nil).DeleteParty), ctx, partyId) +} + +// DeletePartyInvite mocks base method. +func (m *MockRepository) DeletePartyInvite(ctx context.Context, partyId primitive.ObjectID, targetId uuid.UUID) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DeletePartyInvite", ctx, partyId, targetId) + ret0, _ := ret[0].(error) + return ret0 +} + +// DeletePartyInvite indicates an expected call of DeletePartyInvite. +func (mr *MockRepositoryMockRecorder) DeletePartyInvite(ctx, partyId, targetId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePartyInvite", reflect.TypeOf((*MockRepository)(nil).DeletePartyInvite), ctx, partyId, targetId) +} + +// DeletePartyInvitesByPartyId mocks base method. +func (m *MockRepository) DeletePartyInvitesByPartyId(ctx context.Context, partyId primitive.ObjectID) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DeletePartyInvitesByPartyId", ctx, partyId) + ret0, _ := ret[0].(error) + return ret0 +} + +// DeletePartyInvitesByPartyId indicates an expected call of DeletePartyInvitesByPartyId. +func (mr *MockRepositoryMockRecorder) DeletePartyInvitesByPartyId(ctx, partyId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DeletePartyInvitesByPartyId", reflect.TypeOf((*MockRepository)(nil).DeletePartyInvitesByPartyId), ctx, partyId) +} + +// DoesPartyInviteExist mocks base method. +func (m *MockRepository) DoesPartyInviteExist(ctx context.Context, partyId primitive.ObjectID, playerId uuid.UUID) (bool, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "DoesPartyInviteExist", ctx, partyId, playerId) + ret0, _ := ret[0].(bool) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// DoesPartyInviteExist indicates an expected call of DoesPartyInviteExist. +func (mr *MockRepositoryMockRecorder) DoesPartyInviteExist(ctx, partyId, playerId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "DoesPartyInviteExist", reflect.TypeOf((*MockRepository)(nil).DoesPartyInviteExist), ctx, partyId, playerId) +} + +// GetPartyById mocks base method. +func (m *MockRepository) GetPartyByID(ctx context.Context, partyId primitive.ObjectID) (*model.Party, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPartyByID", ctx, partyId) + ret0, _ := ret[0].(*model.Party) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPartyById indicates an expected call of GetPartyById. +func (mr *MockRepositoryMockRecorder) GetPartyById(ctx, partyId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPartyByID", reflect.TypeOf((*MockRepository)(nil).GetPartyByID), ctx, partyId) +} + +// GetPartyByMemberId mocks base method. +func (m *MockRepository) GetPartyByMemberID(ctx context.Context, playerId uuid.UUID) (*model.Party, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPartyByMemberID", ctx, playerId) + ret0, _ := ret[0].(*model.Party) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPartyByMemberId indicates an expected call of GetPartyByMemberId. +func (mr *MockRepositoryMockRecorder) GetPartyByMemberId(ctx, playerId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPartyByMemberID", reflect.TypeOf((*MockRepository)(nil).GetPartyByMemberID), ctx, playerId) +} + +// GetPartyIdByMemberId mocks base method. +func (m *MockRepository) GetPartyIdByMemberId(ctx context.Context, playerId uuid.UUID) (primitive.ObjectID, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPartyIdByMemberId", ctx, playerId) + ret0, _ := ret[0].(primitive.ObjectID) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPartyIdByMemberId indicates an expected call of GetPartyIdByMemberId. +func (mr *MockRepositoryMockRecorder) GetPartyIdByMemberId(ctx, playerId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPartyIdByMemberId", reflect.TypeOf((*MockRepository)(nil).GetPartyIdByMemberId), ctx, playerId) +} + +// GetPartyInvitesByPartyId mocks base method. +func (m *MockRepository) GetPartyInvitesByPartyId(ctx context.Context, partyId primitive.ObjectID) ([]*model.PartyInvite, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPartyInvitesByPartyId", ctx, partyId) + ret0, _ := ret[0].([]*model.PartyInvite) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPartyInvitesByPartyId indicates an expected call of GetPartyInvitesByPartyId. +func (mr *MockRepositoryMockRecorder) GetPartyInvitesByPartyId(ctx, partyId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPartyInvitesByPartyId", reflect.TypeOf((*MockRepository)(nil).GetPartyInvitesByPartyId), ctx, partyId) +} + +// GetPartyLeaderByPartyId mocks base method. +func (m *MockRepository) GetPartyLeaderByPartyId(ctx context.Context, partyId primitive.ObjectID) (uuid.UUID, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPartyLeaderByPartyId", ctx, partyId) + ret0, _ := ret[0].(uuid.UUID) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPartyLeaderByPartyId indicates an expected call of GetPartyLeaderByPartyId. +func (mr *MockRepositoryMockRecorder) GetPartyLeaderByPartyId(ctx, partyId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPartyLeaderByPartyId", reflect.TypeOf((*MockRepository)(nil).GetPartyLeaderByPartyId), ctx, partyId) +} + +// GetPartyLeaderIdByMemberId mocks base method. +func (m *MockRepository) GetPartyLeaderIdByMemberId(ctx context.Context, playerId uuid.UUID) (uuid.UUID, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPartyLeaderIdByMemberId", ctx, playerId) + ret0, _ := ret[0].(uuid.UUID) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPartyLeaderIdByMemberId indicates an expected call of GetPartyLeaderIdByMemberId. +func (mr *MockRepositoryMockRecorder) GetPartyLeaderIdByMemberId(ctx, playerId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPartyLeaderIdByMemberId", reflect.TypeOf((*MockRepository)(nil).GetPartyLeaderIdByMemberId), ctx, playerId) +} + +// GetPartySettings mocks base method. +func (m *MockRepository) GetPartySettings(ctx context.Context, playerId uuid.UUID) (*model.PartySettings, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "GetPartySettings", ctx, playerId) + ret0, _ := ret[0].(*model.PartySettings) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// GetPartySettings indicates an expected call of GetPartySettings. +func (mr *MockRepositoryMockRecorder) GetPartySettings(ctx, playerId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "GetPartySettings", reflect.TypeOf((*MockRepository)(nil).GetPartySettings), ctx, playerId) +} + +// HealthCheck mocks base method. +func (m *MockRepository) HealthCheck(ctx context.Context) health.HealthStatus { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "HealthCheck", ctx) + ret0, _ := ret[0].(health.HealthStatus) + return ret0 +} + +// HealthCheck indicates an expected call of HealthCheck. +func (mr *MockRepositoryMockRecorder) HealthCheck(ctx interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "HealthCheck", reflect.TypeOf((*MockRepository)(nil).HealthCheck), ctx) +} + +// IsInParty mocks base method. +func (m *MockRepository) IsInParty(ctx context.Context, playerId uuid.UUID) (bool, error) { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "IsInParty", ctx, playerId) + ret0, _ := ret[0].(bool) + ret1, _ := ret[1].(error) + return ret0, ret1 +} + +// IsInParty indicates an expected call of IsInParty. +func (mr *MockRepositoryMockRecorder) IsInParty(ctx, playerId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "IsInParty", reflect.TypeOf((*MockRepository)(nil).IsInParty), ctx, playerId) +} + +// RemoveMemberFromParty mocks base method. +func (m *MockRepository) RemoveMemberFromParty(ctx context.Context, partyId primitive.ObjectID, playerId uuid.UUID) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "RemoveMemberFromParty", ctx, partyId, playerId) + ret0, _ := ret[0].(error) + return ret0 +} + +// RemoveMemberFromParty indicates an expected call of RemoveMemberFromParty. +func (mr *MockRepositoryMockRecorder) RemoveMemberFromParty(ctx, partyId, playerId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveMemberFromParty", reflect.TypeOf((*MockRepository)(nil).RemoveMemberFromParty), ctx, partyId, playerId) +} + +// RemoveMemberFromSelfParty mocks base method. +func (m *MockRepository) RemoveMemberFromSelfParty(ctx context.Context, playerId uuid.UUID) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "RemoveMemberFromSelfParty", ctx, playerId) + ret0, _ := ret[0].(error) + return ret0 +} + +// RemoveMemberFromSelfParty indicates an expected call of RemoveMemberFromSelfParty. +func (mr *MockRepositoryMockRecorder) RemoveMemberFromSelfParty(ctx, playerId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "RemoveMemberFromSelfParty", reflect.TypeOf((*MockRepository)(nil).RemoveMemberFromSelfParty), ctx, playerId) +} + +// SetPartyLeader mocks base method. +func (m *MockRepository) SetPartyLeader(ctx context.Context, partyId primitive.ObjectID, leaderId uuid.UUID) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SetPartyLeader", ctx, partyId, leaderId) + ret0, _ := ret[0].(error) + return ret0 +} + +// SetPartyLeader indicates an expected call of SetPartyLeader. +func (mr *MockRepositoryMockRecorder) SetPartyLeader(ctx, partyId, leaderId interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetPartyLeader", reflect.TypeOf((*MockRepository)(nil).SetPartyLeader), ctx, partyId, leaderId) +} + +// SetPartyMembers mocks base method. +func (m *MockRepository) SetPartyMembers(ctx context.Context, partyId primitive.ObjectID, members []*model.PartyMember) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SetPartyMembers", ctx, partyId, members) + ret0, _ := ret[0].(error) + return ret0 +} + +// SetPartyMembers indicates an expected call of SetPartyMembers. +func (mr *MockRepositoryMockRecorder) SetPartyMembers(ctx, partyId, members interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetPartyMembers", reflect.TypeOf((*MockRepository)(nil).SetPartyMembers), ctx, partyId, members) +} + +// SetPartyOpen mocks base method. +func (m *MockRepository) SetPartyOpen(ctx context.Context, partyId primitive.ObjectID, open bool) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "SetPartyOpen", ctx, partyId, open) + ret0, _ := ret[0].(error) + return ret0 +} + +// SetPartyOpen indicates an expected call of SetPartyOpen. +func (mr *MockRepositoryMockRecorder) SetPartyOpen(ctx, partyId, open interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "SetPartyOpen", reflect.TypeOf((*MockRepository)(nil).SetPartyOpen), ctx, partyId, open) +} + +// UpdatePartySettings mocks base method. +func (m *MockRepository) UpdatePartySettings(ctx context.Context, settings *model.PartySettings) error { + m.ctrl.T.Helper() + ret := m.ctrl.Call(m, "UpdatePartySettings", ctx, settings) + ret0, _ := ret[0].(error) + return ret0 +} + +// UpdatePartySettings indicates an expected call of UpdatePartySettings. +func (mr *MockRepositoryMockRecorder) UpdatePartySettings(ctx, settings interface{}) *gomock.Call { + mr.mock.ctrl.T.Helper() + return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "UpdatePartySettings", reflect.TypeOf((*MockRepository)(nil).UpdatePartySettings), ctx, settings) +} diff --git a/services/party-manager/internal/repository/registrytypes/uuid_types.go b/services/party-manager/internal/repository/registrytypes/uuid_types.go new file mode 100644 index 0000000..eb2262d --- /dev/null +++ b/services/party-manager/internal/repository/registrytypes/uuid_types.go @@ -0,0 +1,58 @@ +// Package registrytypes +// taken from https://gist.github.com/SupaHam/3afe982dc75039356723600ccc91ff77 +package registrytypes + +import ( + "fmt" + "github.com/google/uuid" + "go.mongodb.org/mongo-driver/bson" + "go.mongodb.org/mongo-driver/bson/bsoncodec" + "go.mongodb.org/mongo-driver/bson/bsonrw" + "reflect" +) + +var ( + UUIDType = reflect.TypeOf(uuid.UUID{}) + uuidSubtype = byte(0x04) +) + +func UuidEncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, val reflect.Value) error { + if !val.IsValid() || val.Type() != UUIDType { + return bsoncodec.ValueEncoderError{Name: "uuidEncodeValue", Types: []reflect.Type{UUIDType}, Received: val} + } + b := val.Interface().(uuid.UUID) + return vw.WriteBinaryWithSubtype(b[:], uuidSubtype) +} + +func UuidDecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, val reflect.Value) error { + if !val.CanSet() || val.Type() != UUIDType { + return bsoncodec.ValueDecoderError{Name: "uuidDecodeValue", Types: []reflect.Type{UUIDType}, Received: val} + } + + var data []byte + var subtype byte + var err error + switch vrType := vr.Type(); vrType { + case bson.TypeBinary: + data, subtype, err = vr.ReadBinary() + if subtype != uuidSubtype { + return fmt.Errorf("unsupported binary subtype %v for UUID", subtype) + } + case bson.TypeNull: + err = vr.ReadNull() + case bson.TypeUndefined: + err = vr.ReadUndefined() + default: + return fmt.Errorf("cannot decode %v into a UUID", vrType) + } + + if err != nil { + return err + } + uuid2, err := uuid.FromBytes(data) + if err != nil { + return err + } + val.Set(reflect.ValueOf(uuid2)) + return nil +} diff --git a/services/party-manager/internal/utils/pointer.go b/services/party-manager/internal/utils/pointer.go new file mode 100644 index 0000000..5b455d5 --- /dev/null +++ b/services/party-manager/internal/utils/pointer.go @@ -0,0 +1,5 @@ +package utils + +func PointerOf[T any](v T) *T { + return &v +} diff --git a/services/party-manager/internal/utils/uuid.go b/services/party-manager/internal/utils/uuid.go new file mode 100644 index 0000000..f6e801c --- /dev/null +++ b/services/party-manager/internal/utils/uuid.go @@ -0,0 +1,12 @@ +package utils + +import "github.com/google/uuid" + +func RandomUuidSlice(len int) []uuid.UUID { + uuids := make([]uuid.UUID, len) + for i := 0; i < len; i++ { + uuids[i] = uuid.New() + } + + return uuids +} diff --git a/services/party-manager/run/config.yaml b/services/party-manager/run/config.yaml new file mode 100644 index 0000000..6b9953c --- /dev/null +++ b/services/party-manager/run/config.yaml @@ -0,0 +1,10 @@ +kafka: + host: localhost + port: 9092 + +mongodb: + uri: mongodb://localhost:27017 + +port: 10006 + +development: true