diff --git a/README.md b/README.md index 63b118cecdb927f84206a37b25dc5528ae45f223..0362a84257b631c7c1537b0e7080d24490763e21 100644 --- a/README.md +++ b/README.md @@ -143,7 +143,7 @@ To build the codebase and generate all sources follow these steps. ```shell go install \ - "github.com/golang/protobuf/protoc-gen-go" \ + "google.golang.org/protobuf/cmd/protoc-gen-go" \ "google.golang.org/grpc/cmd/protoc-gen-go-grpc" \ "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway" \ "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2" diff --git a/apigrpc/apigrpc.pb.go b/apigrpc/apigrpc.pb.go index cf02969d66f2686a4208b4d71304913ecfbbff25..6fa4cee6c1b679b3bba31d7c57a2d8d596fa5681 100644 --- a/apigrpc/apigrpc.pb.go +++ b/apigrpc/apigrpc.pb.go @@ -17,14 +17,13 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.25.0 +// protoc-gen-go v1.26.0 // protoc v3.15.8 // source: apigrpc.proto package apigrpc import ( - proto "github.com/golang/protobuf/proto" _ "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2/options" api "github.com/heroiclabs/nakama-common/api" _ "google.golang.org/genproto/googleapis/api/annotations" @@ -41,10 +40,6 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - var File_apigrpc_proto protoreflect.FileDescriptor var file_apigrpc_proto_rawDesc = []byte{ diff --git a/build/tools.go b/build/tools.go index debb0733222348159959f247e1c607d67c41c969..0ab12f05f9a30fac1f567f6009af9a8fb87ce892 100644 --- a/build/tools.go +++ b/build/tools.go @@ -17,8 +17,8 @@ package build import ( - _ "github.com/golang/protobuf/protoc-gen-go" _ "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-grpc-gateway" _ "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2" _ "google.golang.org/grpc/cmd/protoc-gen-go-grpc" + _ "google.golang.org/protobuf/cmd/protoc-gen-go" ) diff --git a/console/console.pb.go b/console/console.pb.go index 9da6472cde10c4cae3d99239536fde8f4480c5df..c5006ec76e7c272837800d7d17306090a9487aad 100644 --- a/console/console.pb.go +++ b/console/console.pb.go @@ -17,14 +17,13 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.25.0 +// protoc-gen-go v1.26.0 // protoc v3.15.8 // source: console.proto package console import ( - proto "github.com/golang/protobuf/proto" _ "github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2/options" api "github.com/heroiclabs/nakama-common/api" rtapi "github.com/heroiclabs/nakama-common/rtapi" @@ -45,10 +44,6 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - type UserRole int32 const ( diff --git a/console/protoc-gen-angular/go.mod b/console/protoc-gen-angular/go.mod index a67c67d356ce530eff21968676bb80c85409b8b7..75cc8e3e9cb49d131fbd28f368e15e394d9d706e 100644 --- a/console/protoc-gen-angular/go.mod +++ b/console/protoc-gen-angular/go.mod @@ -5,7 +5,4 @@ go 1.13 require ( github.com/golang/protobuf v1.4.1 github.com/grpc-ecosystem/grpc-gateway v1.12.1 - github.com/kr/pretty v0.1.0 // indirect - gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect - gopkg.in/yaml.v2 v2.2.7 // indirect ) diff --git a/console/protoc-gen-angular/go.sum b/console/protoc-gen-angular/go.sum index 3751a5cb0f09ae9e09375b2122bca0a3a3f426e4..feba6cf967c92b3247aeb0732b521552a51d2a7c 100644 --- a/console/protoc-gen-angular/go.sum +++ b/console/protoc-gen-angular/go.sum @@ -1,17 +1,13 @@ 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/antihax/optional v0.0.0-20180407024304-ca021399b1a6/go.mod h1:V8iCPQYkqmusNa815XgQio277wI47sdRh1dUOLdyC6Q= -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/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= -github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= github.com/ghodss/yaml v1.0.0 h1:wQHKEahhL6wmXdzwWG11gIVCkOv05bNOh+Rxn0yngAk= github.com/ghodss/yaml v1.0.0/go.mod h1:4dBDuWmgqj2HViK6kFavaiC9ZROes6MMH2rRYeMEF04= github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b h1:VKtxabqXZkF25pY9ekfRL6a582T4P37/31XEstQ5p58= 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/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= -github.com/golang/protobuf v1.3.2 h1:6nsPYzhq5kReh6QImI3k5qWzO4PEbvbIW2cwSfR/6xs= github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= github.com/golang/protobuf v1.4.0-rc.1/go.mod h1:ceaxUfeHdC40wWswd/P6IGgMaK3YpKi5j83Wpe3EHw8= github.com/golang/protobuf v1.4.0-rc.1.0.20200221234624-67d41d38c208/go.mod h1:xKAWHe0F5eneWXFV3EuXVDTCmh+JuBKY0li0aMyXATA= @@ -23,16 +19,10 @@ github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QD github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5aqRK0M= github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= +github.com/google/go-cmp v0.4.0 h1:xsAVV57WRhGj6kEIi8ReJzQlHHqcBYCElAvkovg3B/4= github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= -github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= github.com/grpc-ecosystem/grpc-gateway v1.12.1 h1:zCy2xE9ablevUOrUZc3Dl72Dt+ya2FNAvC2yLYMHzi4= github.com/grpc-ecosystem/grpc-gateway v1.12.1/go.mod h1:8XEsbTttt/W+VvjtQhLACqCisSPWTxCZ7sBRjU6iH9c= -github.com/kr/pretty v0.1.0 h1:L/CwN0zerZDmRFUapSPitk6f+Q3+0za1rQkzVuMiMFI= -github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= -github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= -github.com/kr/text v0.1.0 h1:45sCR5RtlFHMR4UwH9sdQ5TC8v0qDQCHnXt+kaKSTVE= -github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= -github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= @@ -55,21 +45,15 @@ golang.org/x/tools v0.0.0-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGm 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/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/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-20190927181202-20e1ac93f88c h1:hrpEMCZ2O7DR5gC1n2AJGVhrwiEjOi35+jxtIuZpTMo= google.golang.org/genproto v0.0.0-20190927181202-20e1ac93f88c/go.mod h1:IbNlFCBrqXvoKpeg0TB2l7cyZUmoaFKYIwrEpbDKLA8= -google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb h1:ADPHZzpzM4tk4V4S5cnCrr5SwzvlrPRmqqCuJDB8UTs= -google.golang.org/genproto v0.0.0-20191230161307-f3c370f40bfb/go.mod h1:n3cpQtvxv34hfy77yVDNjmbRyujviMdxYliBSkLhpCc= -google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013 h1:+kGHl1aib/qcwaRi1CbqBZ1rk19r85MNUf8HaBghugY= -google.golang.org/genproto v0.0.0-20200526211855-cb27e3aa2013/go.mod h1:NbSheEEYHJ7i3ixzK3sjbqSGDJWnxyFXZblF3eUsNvo= 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.24.0/go.mod h1:XDChyiUovWa60DnaeDeZmSW86xtLtjtZbwvSiRnRtcA= -google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8= google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0= google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM= @@ -77,14 +61,9 @@ google.golang.org/protobuf v1.20.1-0.20200309200217-e05f789c0967/go.mod h1:A+miE google.golang.org/protobuf v1.21.0/go.mod h1:47Nbq4nVaFHyn7ilMalzfO3qCViNmqZ2kzikPIcrTAo= google.golang.org/protobuf v1.22.0 h1:cJv5/xdbk1NnMPR1VP9+HU6gupuG9MLBoH1r6RHZ2MY= google.golang.org/protobuf v1.22.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU= -google.golang.org/protobuf v1.25.0 h1:Ejskq+SyPohKW+1uil0JJMtmHCgJPJ/qWTxr8qp+R4c= -google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 h1:qIbj1fsPNlZgppZ+VLlY7N33q108Sa+fhmuc+sWQYwY= -gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v2 v2.2.3 h1:fvjTMHxHEw/mxHbtzPi3JCcKXQRAnQTBRo6YCJSVHKI= gopkg.in/yaml.v2 v2.2.3/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= -gopkg.in/yaml.v2 v2.2.7 h1:VUgggvou5XRW9mHwD/yXxIYSMtY0zoKQf/v226p2nyo= -gopkg.in/yaml.v2 v2.2.7/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 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/go.mod b/go.mod index 016f450b683d925c1a0ba02d69ac381d3f3e808e..a1424348c492d78b3a34f34ba3a1529142072ba9 100644 --- a/go.mod +++ b/go.mod @@ -9,12 +9,11 @@ require ( github.com/dop251/goja v0.0.0-20210406175830-1b11a6af686d github.com/glycerine/go-unsnap-stream v0.0.0-20190901134440-81cf024a9e0a // indirect github.com/gofrs/uuid v4.0.0+incompatible - github.com/golang/protobuf v1.5.2 github.com/gorilla/handlers v1.5.1 github.com/gorilla/mux v1.8.0 github.com/gorilla/websocket v1.4.2 github.com/grpc-ecosystem/grpc-gateway/v2 v2.3.0 - github.com/heroiclabs/nakama-common v1.13.1 + github.com/heroiclabs/nakama-common v1.13.2-0.20210421092134-6fdd0c82aa74 github.com/jackc/fake v0.0.0-20150926172116-812a484cc733 // indirect github.com/jackc/pgx v3.5.0+incompatible github.com/m3db/prometheus_client_golang v0.8.1 // indirect diff --git a/go.sum b/go.sum index ecb62e1c0807e5002f07d0cef2f8e7421be55ebe..82fbffa54bdec72d076f2969d96816b631f98b34 100644 --- a/go.sum +++ b/go.sum @@ -188,9 +188,8 @@ github.com/golang/protobuf v1.4.0/go.mod h1:jodUvKwWbYaEsadDk5Fwe5c77LiNKVO9IDvq github.com/golang/protobuf v1.4.1/go.mod h1:U8fpvMrcmy5pZrNK1lt4xCsGvpyWQ/VVv6QDs8UjoX8= github.com/golang/protobuf v1.4.2/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= github.com/golang/protobuf v1.4.3/go.mod h1:oDoupMAO8OvCJWAcko0GGGIgR6R6ocIYbsSw735rRwI= +github.com/golang/protobuf v1.5.0 h1:LUVKkCeviFUMKqHa4tXIIij/lbhnMbP7Fn5wKdKkRh4= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= -github.com/golang/protobuf v1.5.2 h1:ROPKBNFfQgOUMifHyP+KYbvpjbdoFNs+aK7DXlji0Tw= -github.com/golang/protobuf v1.5.2/go.mod h1:XVQd3VNwM+JqD3oG2Ue2ip4fOMUkwXdXDdiuN0vRsmY= github.com/golang/snappy v0.0.0-20180518054509-2e65f85255db/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4= github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= @@ -257,10 +256,8 @@ github.com/hashicorp/logutils v1.0.0/go.mod h1:QIAnNjmIWmVIIkWDTG1z5v++HQmx9WQRO github.com/hashicorp/mdns v1.0.0/go.mod h1:tL+uN++7HEJ6SQLQ2/p+z2pH24WQKWjBPkE0mNTz8vQ= github.com/hashicorp/memberlist v0.1.3/go.mod h1:ajVTdAv/9Im8oMAAj5G31PhhMCZJV2pPBoIllUwCN7I= github.com/hashicorp/serf v0.8.2/go.mod h1:6hOLApaqBFA1NXqRQAsxw9QxuDEvNxSQRwA/JwenrHc= -github.com/heroiclabs/nakama-common v0.0.0-20210416112859-c820a39d8e37 h1:S5O5Hy60KnqUJOrVzH5DFAm3MlrgcvQyUpnmg2K2Lps= -github.com/heroiclabs/nakama-common v0.0.0-20210416112859-c820a39d8e37/go.mod h1:DpIMr3IW0NLu409ItA6kdzK/KzDJUHWdASGC4zBCCDc= -github.com/heroiclabs/nakama-common v1.13.1 h1:CiT1jLq2wTBbl2Hfpy90te2jnjLCCvTvk6oVXSrOMEg= -github.com/heroiclabs/nakama-common v1.13.1/go.mod h1:DpIMr3IW0NLu409ItA6kdzK/KzDJUHWdASGC4zBCCDc= +github.com/heroiclabs/nakama-common v1.13.2-0.20210421092134-6fdd0c82aa74 h1:fF2NFwqdQTjwS1/RNSXRZYuUPMtE4cgWntklJJkw+o0= +github.com/heroiclabs/nakama-common v1.13.2-0.20210421092134-6fdd0c82aa74/go.mod h1:jzIGV5bI45ALRQFzHPkJn4Z0tV+xhtho1+pZhOXVAsk= github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= github.com/huandu/xstrings v1.3.2/go.mod h1:y5/lhBue+AyNmUVz9RLU9xbLR0o4KIIExikq4ovT0aE= github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc= diff --git a/main.go b/main.go index bca258094877ac77507efe88c41e2ebbe2e3345d..f893493ef98c5ac446e98b18f0d925358658df24 100644 --- a/main.go +++ b/main.go @@ -19,6 +19,7 @@ import ( "database/sql" "flag" "fmt" + "google.golang.org/protobuf/encoding/protojson" "math/rand" "net/http" "net/url" @@ -33,7 +34,7 @@ import ( "path/filepath" "github.com/gofrs/uuid" - "github.com/golang/protobuf/jsonpb" + "github.com/heroiclabs/nakama/v3/ga" "github.com/heroiclabs/nakama/v3/migrate" "github.com/heroiclabs/nakama/v3/server" @@ -50,14 +51,14 @@ var ( commitID string = "dev" // Shared utility components. - jsonpbMarshaler = &jsonpb.Marshaler{ - EnumsAsInts: true, - EmitDefaults: false, - Indent: "", - OrigName: true, + jsonpbMarshaler = &protojson.MarshalOptions{ + UseEnumNumbers: true, + EmitUnpopulated: false, + Indent: "", + UseProtoNames: true, } - jsonpbUnmarshaler = &jsonpb.Unmarshaler{ - AllowUnknownFields: false, + jsonpbUnmarshaler = &protojson.UnmarshalOptions{ + DiscardUnknown: false, } ) diff --git a/server/api.go b/server/api.go index 8b627c30f2f5944f59941b5449db52cce9046d6e..0a1052b1e289c9b09b74919b25eaa90b4ee4c7e2 100644 --- a/server/api.go +++ b/server/api.go @@ -32,8 +32,6 @@ import ( "github.com/dgrijalva/jwt-go" "github.com/gofrs/uuid" - "github.com/golang/protobuf/jsonpb" - "github.com/golang/protobuf/ptypes/empty" "github.com/gorilla/handlers" "github.com/gorilla/mux" grpcgw "github.com/grpc-ecosystem/grpc-gateway/v2/runtime" @@ -49,6 +47,7 @@ import ( "google.golang.org/grpc/peer" "google.golang.org/grpc/status" "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/types/known/emptypb" ) // Used as part of JSON input validation. @@ -80,7 +79,7 @@ type ApiServer struct { grpcGatewayServer *http.Server } -func StartApiServer(logger *zap.Logger, startupLogger *zap.Logger, db *sql.DB, jsonpbMarshaler *jsonpb.Marshaler, jsonpbUnmarshaler *jsonpb.Unmarshaler, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, leaderboardRankCache LeaderboardRankCache, sessionRegistry SessionRegistry, sessionCache SessionCache, statusRegistry *StatusRegistry, matchRegistry MatchRegistry, matchmaker Matchmaker, tracker Tracker, router MessageRouter, metrics *Metrics, pipeline *Pipeline, runtime *Runtime) *ApiServer { +func StartApiServer(logger *zap.Logger, startupLogger *zap.Logger, db *sql.DB, protojsonMarshaler *protojson.MarshalOptions, protojsonUnmarshaler *protojson.UnmarshalOptions, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, leaderboardRankCache LeaderboardRankCache, sessionRegistry SessionRegistry, sessionCache SessionCache, statusRegistry *StatusRegistry, matchRegistry MatchRegistry, matchmaker Matchmaker, tracker Tracker, router MessageRouter, metrics *Metrics, pipeline *Pipeline, runtime *Runtime) *ApiServer { var gatewayContextTimeoutMs string if config.GetSocket().IdleTimeoutMs > 500 { // Ensure the GRPC Gateway timeout is just under the idle timeout (if possible) to ensure it has priority. @@ -202,7 +201,7 @@ func StartApiServer(logger *zap.Logger, startupLogger *zap.Logger, db *sql.DB, j grpcGatewayRouter := mux.NewRouter() // Special case routes. Do NOT enable compression on WebSocket route, it results in "http: response.Write on hijacked connection" errors. grpcGatewayRouter.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) }).Methods("GET") - grpcGatewayRouter.HandleFunc("/ws", NewSocketWsAcceptor(logger, config, sessionRegistry, sessionCache, statusRegistry, matchmaker, tracker, metrics, runtime, jsonpbMarshaler, jsonpbUnmarshaler, pipeline)).Methods("GET") + grpcGatewayRouter.HandleFunc("/ws", NewSocketWsAcceptor(logger, config, sessionRegistry, sessionCache, statusRegistry, matchmaker, tracker, metrics, runtime, protojsonMarshaler, protojsonUnmarshaler, pipeline)).Methods("GET") // Another nested router to hijack RPC requests bound for GRPC Gateway. grpcGatewayMux := mux.NewRouter() @@ -289,8 +288,8 @@ func (s *ApiServer) Stop() { s.grpcServer.GracefulStop() } -func (s *ApiServer) Healthcheck(ctx context.Context, in *empty.Empty) (*empty.Empty, error) { - return &empty.Empty{}, nil +func (s *ApiServer) Healthcheck(ctx context.Context, in *emptypb.Empty) (*emptypb.Empty, error) { + return &emptypb.Empty{}, nil } func securityInterceptorFunc(logger *zap.Logger, config Config, sessionCache SessionCache, ctx context.Context, req interface{}, info *grpc.UnaryServerInfo) (context.Context, error) { diff --git a/server/api_account.go b/server/api_account.go index d66e4b11fea9234ce982a1f9467ae88a23c89d4e..a016c6682505ec4d3f703851b19ec28c7f115e31 100644 --- a/server/api_account.go +++ b/server/api_account.go @@ -17,15 +17,15 @@ package server import ( "context" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/empty" "github.com/heroiclabs/nakama-common/api" "github.com/jackc/pgx" "go.uber.org/zap" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/emptypb" ) -func (s *ApiServer) GetAccount(ctx context.Context, in *empty.Empty) (*api.Account, error) { +func (s *ApiServer) GetAccount(ctx context.Context, in *emptypb.Empty) (*api.Account, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -70,7 +70,7 @@ func (s *ApiServer) GetAccount(ctx context.Context, in *empty.Empty) (*api.Accou return account, nil } -func (s *ApiServer) UpdateAccount(ctx context.Context, in *api.UpdateAccountRequest) (*empty.Empty, error) { +func (s *ApiServer) UpdateAccount(ctx context.Context, in *api.UpdateAccountRequest) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -130,5 +130,5 @@ func (s *ApiServer) UpdateAccount(ctx context.Context, in *api.UpdateAccountRequ traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } diff --git a/server/api_event.go b/server/api_event.go index 981443371319830d7096add1631421660e79f4d9..85c2447978262dd061e3bc073efb99806c8d9597 100644 --- a/server/api_event.go +++ b/server/api_event.go @@ -17,14 +17,14 @@ package server import ( "context" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/empty" "github.com/heroiclabs/nakama-common/api" "go.uber.org/zap" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/emptypb" ) -func (s *ApiServer) Event(ctx context.Context, in *api.Event) (*empty.Empty, error) { +func (s *ApiServer) Event(ctx context.Context, in *api.Event) (*emptypb.Empty, error) { // Before hook. if fn := s.runtime.BeforeEvent(); fn != nil { beforeFn := func(clientIP, clientPort string) error { @@ -68,5 +68,5 @@ func (s *ApiServer) Event(ctx context.Context, in *api.Event) (*empty.Empty, err traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } diff --git a/server/api_friend.go b/server/api_friend.go index b77ab19d7f3bff4806c14ed9d83d7a5259b87491..a0eda48a6cf8cf3fe02e6ad7872123918c98a450 100644 --- a/server/api_friend.go +++ b/server/api_friend.go @@ -17,11 +17,11 @@ package server import ( "context" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/empty" "github.com/heroiclabs/nakama-common/api" "go.uber.org/zap" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/emptypb" "strconv" ) @@ -87,7 +87,7 @@ func (s *ApiServer) ListFriends(ctx context.Context, in *api.ListFriendsRequest) return friends, nil } -func (s *ApiServer) AddFriends(ctx context.Context, in *api.AddFriendsRequest) (*empty.Empty, error) { +func (s *ApiServer) AddFriends(ctx context.Context, in *api.AddFriendsRequest) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -114,7 +114,7 @@ func (s *ApiServer) AddFriends(ctx context.Context, in *api.AddFriendsRequest) ( } if len(in.GetIds()) == 0 && len(in.GetUsernames()) == 0 { - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } username := ctx.Value(ctxUsernameKey{}).(string) @@ -130,7 +130,7 @@ func (s *ApiServer) AddFriends(ctx context.Context, in *api.AddFriendsRequest) ( for _, u := range in.GetUsernames() { if u == "" { - return nil, status.Error(codes.InvalidArgument, "Username must not be empty.") + return nil, status.Error(codes.InvalidArgument, "Username must not be emptypb.") } if username == u { return nil, status.Error(codes.InvalidArgument, "Cannot add self as friend.") @@ -165,10 +165,10 @@ func (s *ApiServer) AddFriends(ctx context.Context, in *api.AddFriendsRequest) ( traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) DeleteFriends(ctx context.Context, in *api.DeleteFriendsRequest) (*empty.Empty, error) { +func (s *ApiServer) DeleteFriends(ctx context.Context, in *api.DeleteFriendsRequest) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -195,7 +195,7 @@ func (s *ApiServer) DeleteFriends(ctx context.Context, in *api.DeleteFriendsRequ } if len(in.GetIds()) == 0 && len(in.GetUsernames()) == 0 { - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } for _, id := range in.GetIds() { @@ -210,7 +210,7 @@ func (s *ApiServer) DeleteFriends(ctx context.Context, in *api.DeleteFriendsRequ username := ctx.Value(ctxUsernameKey{}).(string) for _, u := range in.GetUsernames() { if u == "" { - return nil, status.Error(codes.InvalidArgument, "Username must not be empty.") + return nil, status.Error(codes.InvalidArgument, "Username must not be emptypb.") } if username == u { return nil, status.Error(codes.InvalidArgument, "Cannot delete self.") @@ -225,7 +225,7 @@ func (s *ApiServer) DeleteFriends(ctx context.Context, in *api.DeleteFriendsRequ if len(userIDs)+len(in.GetIds()) == 0 { s.logger.Info("No valid ID or username was provided.") - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } allIDs := make([]string, 0, len(in.GetIds())+len(userIDs)) @@ -246,10 +246,10 @@ func (s *ApiServer) DeleteFriends(ctx context.Context, in *api.DeleteFriendsRequ traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) BlockFriends(ctx context.Context, in *api.BlockFriendsRequest) (*empty.Empty, error) { +func (s *ApiServer) BlockFriends(ctx context.Context, in *api.BlockFriendsRequest) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -276,7 +276,7 @@ func (s *ApiServer) BlockFriends(ctx context.Context, in *api.BlockFriendsReques } if len(in.GetIds()) == 0 && len(in.GetUsernames()) == 0 { - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } for _, id := range in.GetIds() { @@ -291,7 +291,7 @@ func (s *ApiServer) BlockFriends(ctx context.Context, in *api.BlockFriendsReques username := ctx.Value(ctxUsernameKey{}).(string) for _, u := range in.GetUsernames() { if u == "" { - return nil, status.Error(codes.InvalidArgument, "Username must not be empty.") + return nil, status.Error(codes.InvalidArgument, "Username must not be emptypb.") } if username == u { return nil, status.Error(codes.InvalidArgument, "Cannot block self.") @@ -326,10 +326,10 @@ func (s *ApiServer) BlockFriends(ctx context.Context, in *api.BlockFriendsReques traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) ImportFacebookFriends(ctx context.Context, in *api.ImportFacebookFriendsRequest) (*empty.Empty, error) { +func (s *ApiServer) ImportFacebookFriends(ctx context.Context, in *api.ImportFacebookFriendsRequest) (*emptypb.Empty, error) { // Before hook. if fn := s.runtime.BeforeImportFacebookFriends(); fn != nil { beforeFn := func(clientIP, clientPort string) error { @@ -373,10 +373,10 @@ func (s *ApiServer) ImportFacebookFriends(ctx context.Context, in *api.ImportFac traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) ImportSteamFriends(ctx context.Context, in *api.ImportSteamFriendsRequest) (*empty.Empty, error) { +func (s *ApiServer) ImportSteamFriends(ctx context.Context, in *api.ImportSteamFriendsRequest) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) username := ctx.Value(ctxUsernameKey{}).(string) vars := ctx.Value(ctxVarsKey{}).(map[string]string) @@ -435,5 +435,5 @@ func (s *ApiServer) ImportSteamFriends(ctx context.Context, in *api.ImportSteamF traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } diff --git a/server/api_group.go b/server/api_group.go index f4a21cfa231615a5fcdcd390ab7757dfd62b5929..2ff902d37dfb57547f0a89f09c4eb634657c78a4 100644 --- a/server/api_group.go +++ b/server/api_group.go @@ -17,11 +17,11 @@ package server import ( "context" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/empty" "github.com/heroiclabs/nakama-common/api" "go.uber.org/zap" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/emptypb" ) func (s *ApiServer) CreateGroup(ctx context.Context, in *api.CreateGroupRequest) (*api.Group, error) { @@ -83,7 +83,7 @@ func (s *ApiServer) CreateGroup(ctx context.Context, in *api.CreateGroupRequest) return group, nil } -func (s *ApiServer) UpdateGroup(ctx context.Context, in *api.UpdateGroupRequest) (*empty.Empty, error) { +func (s *ApiServer) UpdateGroup(ctx context.Context, in *api.UpdateGroupRequest) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -120,13 +120,13 @@ func (s *ApiServer) UpdateGroup(ctx context.Context, in *api.UpdateGroupRequest) if in.GetName() != nil { if len(in.GetName().String()) < 1 { - return nil, status.Error(codes.InvalidArgument, "Group name cannot be empty.") + return nil, status.Error(codes.InvalidArgument, "Group name cannot be emptypb.") } } if in.GetLangTag() != nil { if len(in.GetLangTag().String()) < 1 { - return nil, status.Error(codes.InvalidArgument, "Group language cannot be empty.") + return nil, status.Error(codes.InvalidArgument, "Group language cannot be emptypb.") } } @@ -152,10 +152,10 @@ func (s *ApiServer) UpdateGroup(ctx context.Context, in *api.UpdateGroupRequest) traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) DeleteGroup(ctx context.Context, in *api.DeleteGroupRequest) (*empty.Empty, error) { +func (s *ApiServer) DeleteGroup(ctx context.Context, in *api.DeleteGroupRequest) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -208,10 +208,10 @@ func (s *ApiServer) DeleteGroup(ctx context.Context, in *api.DeleteGroupRequest) traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) JoinGroup(ctx context.Context, in *api.JoinGroupRequest) (*empty.Empty, error) { +func (s *ApiServer) JoinGroup(ctx context.Context, in *api.JoinGroupRequest) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) username := ctx.Value(ctxUsernameKey{}).(string) @@ -267,10 +267,10 @@ func (s *ApiServer) JoinGroup(ctx context.Context, in *api.JoinGroupRequest) (*e traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) LeaveGroup(ctx context.Context, in *api.LeaveGroupRequest) (*empty.Empty, error) { +func (s *ApiServer) LeaveGroup(ctx context.Context, in *api.LeaveGroupRequest) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) username := ctx.Value(ctxUsernameKey{}).(string) @@ -324,10 +324,10 @@ func (s *ApiServer) LeaveGroup(ctx context.Context, in *api.LeaveGroupRequest) ( traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) AddGroupUsers(ctx context.Context, in *api.AddGroupUsersRequest) (*empty.Empty, error) { +func (s *ApiServer) AddGroupUsers(ctx context.Context, in *api.AddGroupUsersRequest) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -363,7 +363,7 @@ func (s *ApiServer) AddGroupUsers(ctx context.Context, in *api.AddGroupUsersRequ } if len(in.GetUserIds()) == 0 { - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } userIDs := make([]uuid.UUID, 0, len(in.GetUserIds())) @@ -397,10 +397,10 @@ func (s *ApiServer) AddGroupUsers(ctx context.Context, in *api.AddGroupUsersRequ traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) BanGroupUsers(ctx context.Context, in *api.BanGroupUsersRequest) (*empty.Empty, error) { +func (s *ApiServer) BanGroupUsers(ctx context.Context, in *api.BanGroupUsersRequest) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -436,7 +436,7 @@ func (s *ApiServer) BanGroupUsers(ctx context.Context, in *api.BanGroupUsersRequ } if len(in.GetUserIds()) == 0 { - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } userIDs := make([]uuid.UUID, 0, len(in.GetUserIds())) @@ -465,10 +465,10 @@ func (s *ApiServer) BanGroupUsers(ctx context.Context, in *api.BanGroupUsersRequ traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) KickGroupUsers(ctx context.Context, in *api.KickGroupUsersRequest) (*empty.Empty, error) { +func (s *ApiServer) KickGroupUsers(ctx context.Context, in *api.KickGroupUsersRequest) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -504,7 +504,7 @@ func (s *ApiServer) KickGroupUsers(ctx context.Context, in *api.KickGroupUsersRe } if len(in.GetUserIds()) == 0 { - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } userIDs := make([]uuid.UUID, 0, len(in.GetUserIds())) @@ -533,10 +533,10 @@ func (s *ApiServer) KickGroupUsers(ctx context.Context, in *api.KickGroupUsersRe traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) PromoteGroupUsers(ctx context.Context, in *api.PromoteGroupUsersRequest) (*empty.Empty, error) { +func (s *ApiServer) PromoteGroupUsers(ctx context.Context, in *api.PromoteGroupUsersRequest) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -572,7 +572,7 @@ func (s *ApiServer) PromoteGroupUsers(ctx context.Context, in *api.PromoteGroupU } if len(in.GetUserIds()) == 0 { - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } userIDs := make([]uuid.UUID, 0, len(in.GetUserIds())) @@ -604,7 +604,7 @@ func (s *ApiServer) PromoteGroupUsers(ctx context.Context, in *api.PromoteGroupU traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } func (s *ApiServer) ListGroupUsers(ctx context.Context, in *api.ListGroupUsersRequest) (*api.GroupUserList, error) { @@ -676,7 +676,7 @@ func (s *ApiServer) ListGroupUsers(ctx context.Context, in *api.ListGroupUsersRe return groupUsers, nil } -func (s *ApiServer) DemoteGroupUsers(ctx context.Context, in *api.DemoteGroupUsersRequest) (*empty.Empty, error) { +func (s *ApiServer) DemoteGroupUsers(ctx context.Context, in *api.DemoteGroupUsersRequest) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -744,7 +744,7 @@ func (s *ApiServer) DemoteGroupUsers(ctx context.Context, in *api.DemoteGroupUse traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } func (s *ApiServer) ListUserGroups(ctx context.Context, in *api.ListUserGroupsRequest) (*api.UserGroupList, error) { diff --git a/server/api_leaderboard.go b/server/api_leaderboard.go index fdb00cf47f3de0f38d0cdfe88ee2cce96ed08e40..b93e1403f671bbd81b2247e95380af8c800df820 100644 --- a/server/api_leaderboard.go +++ b/server/api_leaderboard.go @@ -18,17 +18,17 @@ import ( "bytes" "context" "encoding/json" + "google.golang.org/protobuf/types/known/wrapperspb" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/empty" - "github.com/golang/protobuf/ptypes/wrappers" "github.com/heroiclabs/nakama-common/api" "go.uber.org/zap" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/emptypb" ) -func (s *ApiServer) DeleteLeaderboardRecord(ctx context.Context, in *api.DeleteLeaderboardRecordRequest) (*empty.Empty, error) { +func (s *ApiServer) DeleteLeaderboardRecord(ctx context.Context, in *api.DeleteLeaderboardRecordRequest) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -77,7 +77,7 @@ func (s *ApiServer) DeleteLeaderboardRecord(ctx context.Context, in *api.DeleteL traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } func (s *ApiServer) ListLeaderboardRecords(ctx context.Context, in *api.ListLeaderboardRecordsRequest) (*api.LeaderboardRecordList, error) { @@ -108,14 +108,14 @@ func (s *ApiServer) ListLeaderboardRecords(ctx context.Context, in *api.ListLead return nil, status.Error(codes.InvalidArgument, "Invalid leaderboard ID.") } - var limit *wrappers.Int32Value + var limit *wrapperspb.Int32Value if in.GetLimit() != nil { if in.GetLimit().Value < 1 || in.GetLimit().Value > 100 { return nil, status.Error(codes.InvalidArgument, "Invalid limit - limit must be between 1 and 100.") } limit = in.GetLimit() } else if len(in.GetOwnerIds()) == 0 || in.GetCursor() != "" { - limit = &wrappers.Int32Value{Value: 1} + limit = &wrapperspb.Int32Value{Value: 1} } if len(in.GetOwnerIds()) != 0 { diff --git a/server/api_link.go b/server/api_link.go index 051ac179af122e33f6f325075f40f1de577f3a66..a969e5157334174fa373d5f9fc3daa31bcf02c9d 100644 --- a/server/api_link.go +++ b/server/api_link.go @@ -17,14 +17,14 @@ package server import ( "context" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/empty" "github.com/heroiclabs/nakama-common/api" "go.uber.org/zap" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/emptypb" ) -func (s *ApiServer) LinkApple(ctx context.Context, in *api.AccountApple) (*empty.Empty, error) { +func (s *ApiServer) LinkApple(ctx context.Context, in *api.AccountApple) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -65,10 +65,10 @@ func (s *ApiServer) LinkApple(ctx context.Context, in *api.AccountApple) (*empty traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) LinkCustom(ctx context.Context, in *api.AccountCustom) (*empty.Empty, error) { +func (s *ApiServer) LinkCustom(ctx context.Context, in *api.AccountCustom) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -109,10 +109,10 @@ func (s *ApiServer) LinkCustom(ctx context.Context, in *api.AccountCustom) (*emp traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) LinkDevice(ctx context.Context, in *api.AccountDevice) (*empty.Empty, error) { +func (s *ApiServer) LinkDevice(ctx context.Context, in *api.AccountDevice) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -153,10 +153,10 @@ func (s *ApiServer) LinkDevice(ctx context.Context, in *api.AccountDevice) (*emp traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) LinkEmail(ctx context.Context, in *api.AccountEmail) (*empty.Empty, error) { +func (s *ApiServer) LinkEmail(ctx context.Context, in *api.AccountEmail) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -197,10 +197,10 @@ func (s *ApiServer) LinkEmail(ctx context.Context, in *api.AccountEmail) (*empty traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) LinkFacebook(ctx context.Context, in *api.LinkFacebookRequest) (*empty.Empty, error) { +func (s *ApiServer) LinkFacebook(ctx context.Context, in *api.LinkFacebookRequest) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) username := ctx.Value(ctxUsernameKey{}).(string) @@ -246,10 +246,10 @@ func (s *ApiServer) LinkFacebook(ctx context.Context, in *api.LinkFacebookReques traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) LinkFacebookInstantGame(ctx context.Context, in *api.AccountFacebookInstantGame) (*empty.Empty, error) { +func (s *ApiServer) LinkFacebookInstantGame(ctx context.Context, in *api.AccountFacebookInstantGame) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -294,10 +294,10 @@ func (s *ApiServer) LinkFacebookInstantGame(ctx context.Context, in *api.Account traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) LinkGameCenter(ctx context.Context, in *api.AccountGameCenter) (*empty.Empty, error) { +func (s *ApiServer) LinkGameCenter(ctx context.Context, in *api.AccountGameCenter) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -338,10 +338,10 @@ func (s *ApiServer) LinkGameCenter(ctx context.Context, in *api.AccountGameCente traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) LinkGoogle(ctx context.Context, in *api.AccountGoogle) (*empty.Empty, error) { +func (s *ApiServer) LinkGoogle(ctx context.Context, in *api.AccountGoogle) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -382,10 +382,10 @@ func (s *ApiServer) LinkGoogle(ctx context.Context, in *api.AccountGoogle) (*emp traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) LinkSteam(ctx context.Context, in *api.LinkSteamRequest) (*empty.Empty, error) { +func (s *ApiServer) LinkSteam(ctx context.Context, in *api.LinkSteamRequest) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) username := ctx.Value(ctxUsernameKey{}).(string) @@ -427,5 +427,5 @@ func (s *ApiServer) LinkSteam(ctx context.Context, in *api.LinkSteamRequest) (*e traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } diff --git a/server/api_notification.go b/server/api_notification.go index 7b68af9f5888d95df6825d2f51252f726e6f4160..cc523d31f2ef34b98ab0c2ccab208b0afc107386 100644 --- a/server/api_notification.go +++ b/server/api_notification.go @@ -21,11 +21,11 @@ import ( "encoding/gob" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/empty" "github.com/heroiclabs/nakama-common/api" "go.uber.org/zap" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/emptypb" ) func (s *ApiServer) ListNotifications(ctx context.Context, in *api.ListNotificationsRequest) (*api.NotificationList, error) { @@ -95,7 +95,7 @@ func (s *ApiServer) ListNotifications(ctx context.Context, in *api.ListNotificat return notificationList, nil } -func (s *ApiServer) DeleteNotifications(ctx context.Context, in *api.DeleteNotificationsRequest) (*empty.Empty, error) { +func (s *ApiServer) DeleteNotifications(ctx context.Context, in *api.DeleteNotificationsRequest) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -122,7 +122,7 @@ func (s *ApiServer) DeleteNotifications(ctx context.Context, in *api.DeleteNotif } if len(in.GetIds()) == 0 { - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } if err := NotificationDelete(ctx, s.logger, s.db, userID, in.GetIds()); err != nil { @@ -139,5 +139,5 @@ func (s *ApiServer) DeleteNotifications(ctx context.Context, in *api.DeleteNotif traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } diff --git a/server/api_purchase.go b/server/api_purchase.go index a5624e4cd562c304e19ea93f737e66db93bac854..e530d7ee7f82b28cf8ee795aff4e922dc635dbae 100644 --- a/server/api_purchase.go +++ b/server/api_purchase.go @@ -55,7 +55,7 @@ func (s *ApiServer) ValidatePurchaseApple(ctx context.Context, in *api.ValidateP } if len(in.Receipt) < 1 { - return nil, status.Error(codes.InvalidArgument, "Receipt cannot be empty.") + return nil, status.Error(codes.InvalidArgument, "Receipt cannot be emptypb.") } validation, err := ValidatePurchasesApple(ctx, s.logger, s.db, userID, s.config.GetIAP().Apple.SharedPassword, in.Receipt) @@ -110,7 +110,7 @@ func (s *ApiServer) ValidatePurchaseGoogle(ctx context.Context, in *api.Validate } if len(in.Purchase) < 1 { - return nil, status.Error(codes.InvalidArgument, "Purchase cannot be empty.") + return nil, status.Error(codes.InvalidArgument, "Purchase cannot be emptypb.") } validation, err := ValidatePurchaseGoogle(ctx, s.logger, s.db, userID, s.config.GetIAP().Google, in.Purchase) @@ -167,11 +167,11 @@ func (s *ApiServer) ValidatePurchaseHuawei(ctx context.Context, in *api.Validate } if len(in.Purchase) < 1 { - return nil, status.Error(codes.InvalidArgument, "Purchase cannot be empty.") + return nil, status.Error(codes.InvalidArgument, "Purchase cannot be emptypb.") } if len(in.Signature) < 1 { - return nil, status.Error(codes.InvalidArgument, "Signature cannot be empty.") + return nil, status.Error(codes.InvalidArgument, "Signature cannot be emptypb.") } validation, err := ValidatePurchaseHuawei(ctx, s.logger, s.db, userID, s.config.GetIAP().Huawei, in.Purchase, in.Signature) diff --git a/server/api_session.go b/server/api_session.go index b506cc547fcf4e0ac9ed8e1677d17fd0de6d5f9f..342ea62c0306dd1c8dc572dd8d8620ed13216f0c 100644 --- a/server/api_session.go +++ b/server/api_session.go @@ -17,7 +17,7 @@ package server import ( "context" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/empty" + "google.golang.org/protobuf/types/known/emptypb" "github.com/heroiclabs/nakama-common/api" "go.uber.org/zap" @@ -82,7 +82,7 @@ func (s *ApiServer) SessionRefresh(ctx context.Context, in *api.SessionRefreshRe return session, nil } -func (s *ApiServer) SessionLogout(ctx context.Context, in *api.SessionLogoutRequest) (*empty.Empty, error) { +func (s *ApiServer) SessionLogout(ctx context.Context, in *api.SessionLogoutRequest) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -129,5 +129,5 @@ func (s *ApiServer) SessionLogout(ctx context.Context, in *api.SessionLogoutRequ traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } diff --git a/server/api_storage.go b/server/api_storage.go index 297270625a1d172c1d8115ef00749ff3ae43c8d9..b2325a79c9239419d92aa145eac8308c1e8f05a3 100644 --- a/server/api_storage.go +++ b/server/api_storage.go @@ -22,10 +22,10 @@ import ( "go.uber.org/zap" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/empty" "github.com/heroiclabs/nakama-common/api" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/emptypb" ) func (s *ApiServer) ListStorageObjects(ctx context.Context, in *api.ListStorageObjectsRequest) (*api.StorageObjectList, error) { @@ -236,7 +236,7 @@ func (s *ApiServer) WriteStorageObjects(ctx context.Context, in *api.WriteStorag return acks, nil } -func (s *ApiServer) DeleteStorageObjects(ctx context.Context, in *api.DeleteStorageObjectsRequest) (*empty.Empty, error) { +func (s *ApiServer) DeleteStorageObjects(ctx context.Context, in *api.DeleteStorageObjectsRequest) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID).String() // Before hook. @@ -263,7 +263,7 @@ func (s *ApiServer) DeleteStorageObjects(ctx context.Context, in *api.DeleteStor } if in.GetObjectIds() == nil || len(in.GetObjectIds()) == 0 { - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } for _, objectID := range in.GetObjectIds() { @@ -297,5 +297,5 @@ func (s *ApiServer) DeleteStorageObjects(ctx context.Context, in *api.DeleteStor traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } diff --git a/server/api_test.go b/server/api_test.go index 7373499f5ef281a8946ac60173e7dcc40be212ae..726c40befa5cbe167dd9be273edf617b9aa86c9e 100644 --- a/server/api_test.go +++ b/server/api_test.go @@ -21,7 +21,6 @@ import ( "encoding/base64" "encoding/json" "github.com/gofrs/uuid" - "github.com/golang/protobuf/jsonpb" "github.com/heroiclabs/nakama-common/api" "github.com/heroiclabs/nakama-common/rtapi" "github.com/heroiclabs/nakama-common/runtime" @@ -31,21 +30,22 @@ import ( "go.uber.org/zap/zapcore" "google.golang.org/grpc" "google.golang.org/grpc/metadata" + "google.golang.org/protobuf/encoding/protojson" "os" "strings" "testing" ) var ( - logger = NewConsoleLogger(os.Stdout, true) - cfg = NewConfig(logger) - jsonpbMarshaler = &jsonpb.Marshaler{ + logger = NewConsoleLogger(os.Stdout, true) + cfg = NewConfig(logger) + protojsonMarshaler = &protojson.MarshalOptions{ EnumsAsInts: true, EmitDefaults: false, Indent: "", OrigName: true, } - jsonpbUnmarshaler = &jsonpb.Unmarshaler{ + protojsonUnmarshaler = &protojson.UnmarshalOptions{ AllowUnknownFields: false, } metrics = NewMetrics(logger, logger, cfg) @@ -104,7 +104,7 @@ func (d *DummySession) Send(envelope *rtapi.Envelope, reliable bool) error { } func (d *DummySession) SendBytes(payload []byte, reliable bool) error { envelope := &rtapi.Envelope{} - jsonpbUnmarshaler.Unmarshal(bytes.NewReader(payload), envelope) + protojsonUnmarshaler.Unmarshal(bytes.NewReader(payload), envelope) d.messages = append(d.messages, envelope) return nil } @@ -167,8 +167,8 @@ func NewAPIServer(t *testing.T, runtime *Runtime) (*ApiServer, *Pipeline) { db := NewDB(t) router := &DummyMessageRouter{} tracker := &LocalTracker{} - pipeline := NewPipeline(logger, cfg, db, jsonpbMarshaler, jsonpbUnmarshaler, nil, nil, nil, nil, nil, tracker, router, runtime) - apiServer := StartApiServer(logger, logger, db, jsonpbMarshaler, jsonpbUnmarshaler, cfg, nil, nil, nil, nil, nil, nil, nil, nil, tracker, router, metrics, pipeline, runtime) + pipeline := NewPipeline(logger, cfg, db, protojsonMarshaler, protojsonUnmarshaler, nil, nil, nil, nil, nil, tracker, router, runtime) + apiServer := StartApiServer(logger, logger, db, protojsonMarshaler, protojsonUnmarshaler, cfg, nil, nil, nil, nil, nil, nil, nil, nil, tracker, router, metrics, pipeline, runtime) return apiServer, pipeline } diff --git a/server/api_tournament.go b/server/api_tournament.go index a087911154d7fa2b3f563a37e6fa562ab99f8e20..9d6729c40817f99ae7c750d56c43a582019f3bbd 100644 --- a/server/api_tournament.go +++ b/server/api_tournament.go @@ -20,19 +20,19 @@ import ( "encoding/base64" "encoding/gob" "encoding/json" + "google.golang.org/protobuf/types/known/wrapperspb" "time" "go.uber.org/zap" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/empty" - "github.com/golang/protobuf/ptypes/wrappers" "github.com/heroiclabs/nakama-common/api" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/emptypb" ) -func (s *ApiServer) JoinTournament(ctx context.Context, in *api.JoinTournamentRequest) (*empty.Empty, error) { +func (s *ApiServer) JoinTournament(ctx context.Context, in *api.JoinTournamentRequest) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) username := ctx.Value(ctxUsernameKey{}).(string) @@ -82,7 +82,7 @@ func (s *ApiServer) JoinTournament(ctx context.Context, in *api.JoinTournamentRe traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } func (s *ApiServer) ListTournamentRecords(ctx context.Context, in *api.ListTournamentRecordsRequest) (*api.TournamentRecordList, error) { @@ -121,14 +121,14 @@ func (s *ApiServer) ListTournamentRecords(ctx context.Context, in *api.ListTourn } } - var limit *wrappers.Int32Value + var limit *wrapperspb.Int32Value if in.GetLimit() != nil { if in.GetLimit().Value < 1 || in.GetLimit().Value > 100 { return nil, status.Error(codes.InvalidArgument, "Invalid limit - limit must be between 1 and 100.") } limit = in.GetLimit() } else if len(in.GetOwnerIds()) == 0 || in.GetCursor() == "" { - limit = &wrappers.Int32Value{Value: 10} + limit = &wrapperspb.Int32Value{Value: 10} } overrideExpiry := int64(0) diff --git a/server/api_unlink.go b/server/api_unlink.go index 00df32d0a400ffeaf661ee27d02eb7bc76c10045..e44ed6b987a4cca6d675dc36fe336ea78766eb66 100644 --- a/server/api_unlink.go +++ b/server/api_unlink.go @@ -17,14 +17,14 @@ package server import ( "context" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/empty" "github.com/heroiclabs/nakama-common/api" "go.uber.org/zap" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/emptypb" ) -func (s *ApiServer) UnlinkApple(ctx context.Context, in *api.AccountApple) (*empty.Empty, error) { +func (s *ApiServer) UnlinkApple(ctx context.Context, in *api.AccountApple) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -65,10 +65,10 @@ func (s *ApiServer) UnlinkApple(ctx context.Context, in *api.AccountApple) (*emp traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) UnlinkCustom(ctx context.Context, in *api.AccountCustom) (*empty.Empty, error) { +func (s *ApiServer) UnlinkCustom(ctx context.Context, in *api.AccountCustom) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -109,10 +109,10 @@ func (s *ApiServer) UnlinkCustom(ctx context.Context, in *api.AccountCustom) (*e traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) UnlinkDevice(ctx context.Context, in *api.AccountDevice) (*empty.Empty, error) { +func (s *ApiServer) UnlinkDevice(ctx context.Context, in *api.AccountDevice) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -153,10 +153,10 @@ func (s *ApiServer) UnlinkDevice(ctx context.Context, in *api.AccountDevice) (*e traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) UnlinkEmail(ctx context.Context, in *api.AccountEmail) (*empty.Empty, error) { +func (s *ApiServer) UnlinkEmail(ctx context.Context, in *api.AccountEmail) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -197,10 +197,10 @@ func (s *ApiServer) UnlinkEmail(ctx context.Context, in *api.AccountEmail) (*emp traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) UnlinkFacebook(ctx context.Context, in *api.AccountFacebook) (*empty.Empty, error) { +func (s *ApiServer) UnlinkFacebook(ctx context.Context, in *api.AccountFacebook) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -241,10 +241,10 @@ func (s *ApiServer) UnlinkFacebook(ctx context.Context, in *api.AccountFacebook) traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) UnlinkFacebookInstantGame(ctx context.Context, in *api.AccountFacebookInstantGame) (*empty.Empty, error) { +func (s *ApiServer) UnlinkFacebookInstantGame(ctx context.Context, in *api.AccountFacebookInstantGame) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -285,10 +285,10 @@ func (s *ApiServer) UnlinkFacebookInstantGame(ctx context.Context, in *api.Accou traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) UnlinkGameCenter(ctx context.Context, in *api.AccountGameCenter) (*empty.Empty, error) { +func (s *ApiServer) UnlinkGameCenter(ctx context.Context, in *api.AccountGameCenter) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -329,10 +329,10 @@ func (s *ApiServer) UnlinkGameCenter(ctx context.Context, in *api.AccountGameCen traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) UnlinkGoogle(ctx context.Context, in *api.AccountGoogle) (*empty.Empty, error) { +func (s *ApiServer) UnlinkGoogle(ctx context.Context, in *api.AccountGoogle) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -373,10 +373,10 @@ func (s *ApiServer) UnlinkGoogle(ctx context.Context, in *api.AccountGoogle) (*e traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ApiServer) UnlinkSteam(ctx context.Context, in *api.AccountSteam) (*empty.Empty, error) { +func (s *ApiServer) UnlinkSteam(ctx context.Context, in *api.AccountSteam) (*emptypb.Empty, error) { userID := ctx.Value(ctxUserIDKey{}).(uuid.UUID) // Before hook. @@ -417,5 +417,5 @@ func (s *ApiServer) UnlinkSteam(ctx context.Context, in *api.AccountSteam) (*emp traceApiAfter(ctx, s.logger, s.metrics, ctx.Value(ctxFullMethodKey{}).(string), afterFn) } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } diff --git a/server/console_account.go b/server/console_account.go index d1be0b537c5def7c4030cf758600d0e6889e265d..cedb1cf26e2d748914de2708d75b02121b222ec2 100644 --- a/server/console_account.go +++ b/server/console_account.go @@ -21,6 +21,7 @@ import ( "encoding/base64" "encoding/gob" "encoding/json" + "google.golang.org/protobuf/types/known/timestamppb" "strconv" "strings" @@ -28,12 +29,11 @@ import ( "golang.org/x/crypto/bcrypt" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/empty" - "github.com/golang/protobuf/ptypes/timestamp" "github.com/heroiclabs/nakama-common/api" "go.uber.org/zap" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/emptypb" "github.com/heroiclabs/nakama/v3/console" ) @@ -43,7 +43,7 @@ type consoleAccountCursor struct { Username string } -func (s *ConsoleServer) BanAccount(ctx context.Context, in *console.AccountId) (*empty.Empty, error) { +func (s *ConsoleServer) BanAccount(ctx context.Context, in *console.AccountId) (*emptypb.Empty, error) { userID, err := uuid.FromString(in.Id) if err != nil { return nil, status.Error(codes.InvalidArgument, "Requires a valid user ID.") @@ -57,10 +57,10 @@ func (s *ConsoleServer) BanAccount(ctx context.Context, in *console.AccountId) ( return nil, status.Error(codes.Internal, "An error occurred while trying to ban the user.") } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ConsoleServer) UnbanAccount(ctx context.Context, in *console.AccountId) (*empty.Empty, error) { +func (s *ConsoleServer) UnbanAccount(ctx context.Context, in *console.AccountId) (*emptypb.Empty, error) { userID, err := uuid.FromString(in.Id) if err != nil { return nil, status.Error(codes.InvalidArgument, "Requires a valid user ID.") @@ -74,10 +74,10 @@ func (s *ConsoleServer) UnbanAccount(ctx context.Context, in *console.AccountId) return nil, status.Error(codes.Internal, "An error occurred while trying to unban the user.") } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ConsoleServer) DeleteAccount(ctx context.Context, in *console.AccountDeleteRequest) (*empty.Empty, error) { +func (s *ConsoleServer) DeleteAccount(ctx context.Context, in *console.AccountDeleteRequest) (*emptypb.Empty, error) { userID, err := uuid.FromString(in.Id) if err != nil { return nil, status.Error(codes.InvalidArgument, "Requires a valid user ID.") @@ -91,20 +91,20 @@ func (s *ConsoleServer) DeleteAccount(ctx context.Context, in *console.AccountDe return nil, status.Error(codes.Internal, "An error occurred while trying to delete the user.") } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ConsoleServer) DeleteAccounts(ctx context.Context, in *empty.Empty) (*empty.Empty, error) { +func (s *ConsoleServer) DeleteAccounts(ctx context.Context, in *emptypb.Empty) (*emptypb.Empty, error) { // Delete all but the system user. Related data will be removed by cascading constraints. _, err := s.db.ExecContext(ctx, "DELETE FROM users WHERE id <> '00000000-0000-0000-0000-000000000000'") if err != nil { s.logger.Error("Error deleting all user accounts.", zap.Error(err)) return nil, status.Error(codes.Internal, "An error occurred while trying to delete all users.") } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ConsoleServer) DeleteFriend(ctx context.Context, in *console.DeleteFriendRequest) (*empty.Empty, error) { +func (s *ConsoleServer) DeleteFriend(ctx context.Context, in *console.DeleteFriendRequest) (*emptypb.Empty, error) { userID, err := uuid.FromString(in.Id) if err != nil { return nil, status.Error(codes.InvalidArgument, "Requires a valid user ID.") @@ -118,10 +118,10 @@ func (s *ConsoleServer) DeleteFriend(ctx context.Context, in *console.DeleteFrie return nil, status.Error(codes.Internal, "An error occurred while trying to delete the friend relationship.") } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ConsoleServer) DeleteGroupUser(ctx context.Context, in *console.DeleteGroupUserRequest) (*empty.Empty, error) { +func (s *ConsoleServer) DeleteGroupUser(ctx context.Context, in *console.DeleteGroupUserRequest) (*emptypb.Empty, error) { userID, err := uuid.FromString(in.Id) if err != nil { return nil, status.Error(codes.InvalidArgument, "Requires a valid user ID.") @@ -136,10 +136,10 @@ func (s *ConsoleServer) DeleteGroupUser(ctx context.Context, in *console.DeleteG return nil, status.Error(codes.Internal, "An error occurred while trying to remove the user from the group.") } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ConsoleServer) DeleteWalletLedger(ctx context.Context, in *console.DeleteWalletLedgerRequest) (*empty.Empty, error) { +func (s *ConsoleServer) DeleteWalletLedger(ctx context.Context, in *console.DeleteWalletLedgerRequest) (*emptypb.Empty, error) { userID, err := uuid.FromString(in.Id) if err != nil { return nil, status.Error(codes.InvalidArgument, "Requires a valid user ID.") @@ -155,7 +155,7 @@ func (s *ConsoleServer) DeleteWalletLedger(ctx context.Context, in *console.Dele return nil, status.Error(codes.Internal, "An error occurred while trying to remove the user's wallet ledger item.") } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } func (s *ConsoleServer) ExportAccount(ctx context.Context, in *console.AccountId) (*console.AccountExport, error) { @@ -255,8 +255,8 @@ func (s *ConsoleServer) GetWalletLedger(ctx context.Context, in *console.Account UserId: ledgerItem.UserID, Changeset: string(changeset), Metadata: string(metadata), - CreateTime: ×tamp.Timestamp{Seconds: ledgerItem.CreateTime}, - UpdateTime: ×tamp.Timestamp{Seconds: ledgerItem.UpdateTime}, + CreateTime: ×tamppb.Timestamp{Seconds: ledgerItem.CreateTime}, + UpdateTime: ×tamppb.Timestamp{Seconds: ledgerItem.UpdateTime}, }) } @@ -298,7 +298,7 @@ func (s *ConsoleServer) ListAccounts(ctx context.Context, in *console.ListAccoun Users: []*api.User{ { Id: in.Filter, - UpdateTime: ×tamp.Timestamp{Seconds: createTime.Time.Unix()}, + UpdateTime: ×tamppb.Timestamp{Seconds: createTime.Time.Unix()}, }, }, TotalCount: 1, @@ -325,7 +325,7 @@ func (s *ConsoleServer) ListAccounts(ctx context.Context, in *console.ListAccoun users = append(users, &api.User{ Id: id, - UpdateTime: ×tamp.Timestamp{Seconds: createTime.Time.Unix()}, + UpdateTime: ×tamppb.Timestamp{Seconds: createTime.Time.Unix()}, }) } _ = rows.Close() @@ -445,7 +445,7 @@ func (s *ConsoleServer) ListAccounts(ctx context.Context, in *console.ListAccoun return response, nil } -func (s *ConsoleServer) UpdateAccount(ctx context.Context, in *console.UpdateAccountRequest) (*empty.Empty, error) { +func (s *ConsoleServer) UpdateAccount(ctx context.Context, in *console.UpdateAccountRequest) (*emptypb.Empty, error) { userID, err := uuid.FromString(in.Id) if err != nil { return nil, status.Error(codes.InvalidArgument, "Requires a valid user ID.") @@ -459,7 +459,7 @@ func (s *ConsoleServer) UpdateAccount(ctx context.Context, in *console.UpdateAcc if v := in.Username; v != nil { if len(v.Value) == 0 { - return nil, status.Error(codes.InvalidArgument, "Username cannot be empty.") + return nil, status.Error(codes.InvalidArgument, "Username cannot be emptypb.") } if invalidCharsRegex.MatchString(v.Value) { return nil, status.Error(codes.InvalidArgument, "Username cannot contain spaces or control characters.") @@ -602,7 +602,7 @@ func (s *ConsoleServer) UpdateAccount(ctx context.Context, in *console.UpdateAcc if len(statements) == 0 && !removeCustomID && !removeEmail && len(in.DeviceIds) == 0 && len(newPassword) == 0 { // Nothing to update. - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } tx, err := s.db.BeginTx(ctx, nil) @@ -742,5 +742,5 @@ AND ((facebook_id IS NOT NULL return nil, status.Error(codes.Internal, "An error occurred while trying to update the user.") } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } diff --git a/server/console_api_explorer.go b/server/console_api_explorer.go index 0ef5f16ae7e950b6d810be1375f466293c9207a1..31bb95d857d83a9bee60bcae6f01ef12edbd84bf 100644 --- a/server/console_api_explorer.go +++ b/server/console_api_explorer.go @@ -5,14 +5,14 @@ import ( "database/sql" "fmt" "github.com/gofrs/uuid" - "github.com/golang/protobuf/jsonpb" - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes/empty" "github.com/heroiclabs/nakama-common/api" "github.com/heroiclabs/nakama/v3/console" "go.uber.org/zap" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/emptypb" "reflect" "sort" "strings" @@ -68,15 +68,15 @@ func (s *ConsoleServer) CallApiEndpoint(ctx context.Context, in *console.CallApi args[0] = reflect.ValueOf(s.api) args[1] = reflect.ValueOf(callCtx) - if r.method.Type.In(2) == reflect.TypeOf(&empty.Empty{}) { + if r.method.Type.In(2) == reflect.TypeOf(&emptypb.Empty{}) { if in.Body != "" { s.logger.Error("Body passed to an api call that doesn't accept any.", zap.String("method", in.Method)) return nil, status.Error(codes.InvalidArgument, "Api method doesn't accept a request body.") } - args[2] = reflect.ValueOf(&empty.Empty{}) + args[2] = reflect.ValueOf(&emptypb.Empty{}) } else { request := reflect.New(r.request).Interface().(proto.Message) - err = jsonpb.UnmarshalString(in.Body, request) + err = protojson.Unmarshal([]byte(in.Body), request) if err != nil { s.logger.Error("Error parsing method request body.", zap.String("method", in.Method), zap.Error(err)) return nil, status.Error(codes.InvalidArgument, "Error parsing method request body.") @@ -92,17 +92,17 @@ func (s *ConsoleServer) CallApiEndpoint(ctx context.Context, in *console.CallApi ErrorMessage: cerr.(error).Error(), }, nil } else { - var j string + var j []byte if cval != nil { - m := new(jsonpb.Marshaler) - j, err = m.MarshalToString(cval.(proto.Message)) + m := new(protojson.MarshalOptions) + j, err = m.Marshal(cval.(proto.Message)) if err != nil { s.logger.Error("Error serializing method response body.", zap.String("method", in.Method), zap.Error(err)) return nil, status.Error(codes.Internal, "Error serializing method response body.") } } return &console.CallApiEndpointResponse{ - Body: j, + Body: string(j), }, nil } @@ -145,7 +145,7 @@ func (s *ConsoleServer) extractApiCallContext(ctx context.Context, in *console.C return callCtx, nil } -func (s *ConsoleServer) ListApiEndpoints(ctx context.Context, _ *empty.Empty) (*console.ApiEndpointList, error) { +func (s *ConsoleServer) ListApiEndpoints(ctx context.Context, _ *emptypb.Empty) (*console.ApiEndpointList, error) { endpointNames := make([]string, 0, len(s.rpcMethodCache.endpoints)) for name := range s.rpcMethodCache.endpoints { endpointNames = append(endpointNames, string(name)) @@ -199,7 +199,7 @@ func (s *ConsoleServer) initRpcMethodCache() error { request := method.Type.In(2) - if request != reflect.TypeOf(&empty.Empty{}) { + if request != reflect.TypeOf(&emptypb.Empty{}) { if request.Kind() == reflect.Ptr { request = request.Elem() } @@ -296,10 +296,10 @@ func reflectProtoMessageAsJsonTemplate(s reflect.Type) (string, error) { return m } i := populate(reflect.New(s)).Interface().(proto.Message) - m := jsonpb.Marshaler{OrigName: false, EnumsAsInts: true, EmitDefaults: true} - j, err := m.MarshalToString(i) + m := protojson.MarshalOptions{UseProtoNames: false, UseEnumNumbers: true, EmitUnpopulated: true} + j, err := m.Marshal(i) if err != nil { return "", err } - return j, nil + return string(j), nil } diff --git a/server/console_config.go b/server/console_config.go index 036f75a17e3d010c28da59c6bfc3997e59d4a0d6..bd71276bca5ac7ff4c30937fb099252131a4d61d 100644 --- a/server/console_config.go +++ b/server/console_config.go @@ -21,16 +21,16 @@ import ( "net/url" "strings" - "github.com/golang/protobuf/ptypes/empty" "github.com/heroiclabs/nakama/v3/console" "go.uber.org/zap" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/emptypb" ) const ObfuscationString = "REDACTED" -func (s *ConsoleServer) GetConfig(ctx context.Context, in *empty.Empty) (*console.Config, error) { +func (s *ConsoleServer) GetConfig(ctx context.Context, in *emptypb.Empty) (*console.Config, error) { cfg, err := s.config.Clone() if err != nil { s.logger.Error("Error cloning config.", zap.Error(err)) diff --git a/server/console_leaderboard.go b/server/console_leaderboard.go index e261f061aa7234a49749f6fb97a1254bf0ef1a42..d71990e733758fb3996388c652d34825a6b0da14 100644 --- a/server/console_leaderboard.go +++ b/server/console_leaderboard.go @@ -17,17 +17,17 @@ package server import ( "context" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/empty" - "github.com/golang/protobuf/ptypes/timestamp" - "github.com/golang/protobuf/ptypes/wrappers" "github.com/heroiclabs/nakama-common/api" "github.com/heroiclabs/nakama/v3/console" "go.uber.org/zap" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/emptypb" + "google.golang.org/protobuf/types/known/timestamppb" + "google.golang.org/protobuf/types/known/wrapperspb" ) -func (s *ConsoleServer) ListLeaderboards(ctx context.Context, _ *empty.Empty) (*console.LeaderboardList, error) { +func (s *ConsoleServer) ListLeaderboards(ctx context.Context, _ *emptypb.Empty) (*console.LeaderboardList, error) { leaderboards := s.leaderboardCache.GetAllLeaderboards() resultList := make([]*console.Leaderboard, 0, len(leaderboards)) @@ -75,7 +75,7 @@ func (s *ConsoleServer) GetLeaderboard(ctx context.Context, in *console.Leaderbo SortOrder: uint32(l.SortOrder), Operator: uint32(l.Operator), ResetSchedule: l.ResetScheduleStr, - CreateTime: ×tamp.Timestamp{Seconds: l.CreateTime}, + CreateTime: ×tamppb.Timestamp{Seconds: l.CreateTime}, Authoritative: l.Authoritative, Metadata: l.Metadata, Tournament: false, @@ -101,14 +101,14 @@ func (s *ConsoleServer) GetLeaderboard(ctx context.Context, in *console.Leaderbo } func (s *ConsoleServer) ListLeaderboardRecords(ctx context.Context, in *api.ListLeaderboardRecordsRequest) (*api.LeaderboardRecordList, error) { - var limit *wrappers.Int32Value + var limit *wrapperspb.Int32Value if in.GetLimit() != nil { if in.GetLimit().Value < 1 || in.GetLimit().Value > 100 { return nil, status.Error(codes.InvalidArgument, "Invalid limit - limit must be between 1 and 100.") } limit = in.GetLimit() } else if len(in.GetOwnerIds()) == 0 || in.GetCursor() != "" { - limit = &wrappers.Int32Value{Value: 1} + limit = &wrapperspb.Int32Value{Value: 1} } if len(in.GetOwnerIds()) != 0 { @@ -136,7 +136,7 @@ func (s *ConsoleServer) ListLeaderboardRecords(ctx context.Context, in *api.List return records, nil } -func (s *ConsoleServer) DeleteLeaderboard(ctx context.Context, in *console.LeaderboardRequest) (*empty.Empty, error) { +func (s *ConsoleServer) DeleteLeaderboard(ctx context.Context, in *console.LeaderboardRequest) (*emptypb.Empty, error) { if in.Id == "" { return nil, status.Error(codes.InvalidArgument, "Expects a leaderboard ID") } @@ -146,10 +146,10 @@ func (s *ConsoleServer) DeleteLeaderboard(ctx context.Context, in *console.Leade return nil, status.Error(codes.Internal, "Error deleting leaderboard.") } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ConsoleServer) DeleteLeaderboardRecord(ctx context.Context, in *console.DeleteLeaderboardRecordRequest) (*empty.Empty, error) { +func (s *ConsoleServer) DeleteLeaderboardRecord(ctx context.Context, in *console.DeleteLeaderboardRecordRequest) (*emptypb.Empty, error) { if in.Id == "" { return nil, status.Error(codes.InvalidArgument, "Invalid leaderboard ID.") } @@ -162,5 +162,5 @@ func (s *ConsoleServer) DeleteLeaderboardRecord(ctx context.Context, in *console return nil, status.Error(codes.Internal, "Error deleting score from leaderboard.") } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } diff --git a/server/console_runtime.go b/server/console_runtime.go index aeda96144c987d27adeecf71f61dac13b2bef539..17b11851484e358ddb22fcd728889363c22c67ce 100644 --- a/server/console_runtime.go +++ b/server/console_runtime.go @@ -16,18 +16,18 @@ package server import ( "context" - "github.com/golang/protobuf/ptypes/empty" - "github.com/golang/protobuf/ptypes/timestamp" "github.com/heroiclabs/nakama/v3/console" + "google.golang.org/protobuf/types/known/emptypb" + "google.golang.org/protobuf/types/known/timestamppb" ) -func (s *ConsoleServer) GetRuntime(ctx context.Context, in *empty.Empty) (*console.RuntimeInfo, error) { +func (s *ConsoleServer) GetRuntime(ctx context.Context, in *emptypb.Empty) (*console.RuntimeInfo, error) { toConsole := func(modules []*moduleInfo) []*console.RuntimeInfo_ModuleInfo { result := make([]*console.RuntimeInfo_ModuleInfo, 0, len(modules)) for _, m := range modules { result = append(result, &console.RuntimeInfo_ModuleInfo{ Path: m.path, - ModTime: ×tamp.Timestamp{Seconds: m.modTime.UTC().Unix()}, + ModTime: ×tamppb.Timestamp{Seconds: m.modTime.UTC().Unix()}, }) } return result diff --git a/server/console_status.go b/server/console_status.go index 9391dc09420c59e2edf064edebdda83c25383f1d..03d27dcfa433bce8617bfe981c7de8e612504f13 100644 --- a/server/console_status.go +++ b/server/console_status.go @@ -16,16 +16,16 @@ package server import ( "context" - "github.com/golang/protobuf/ptypes/empty" - "github.com/golang/protobuf/ptypes/timestamp" "github.com/heroiclabs/nakama/v3/console" "go.uber.org/zap" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/emptypb" + "google.golang.org/protobuf/types/known/timestamppb" "time" ) -func (s *ConsoleServer) GetStatus(ctx context.Context, in *empty.Empty) (*console.StatusList, error) { +func (s *ConsoleServer) GetStatus(ctx context.Context, in *emptypb.Empty) (*console.StatusList, error) { nodes, err := s.statusHandler.GetStatus(ctx) if err != nil { s.logger.Error("Error getting status.", zap.Error(err)) @@ -34,6 +34,6 @@ func (s *ConsoleServer) GetStatus(ctx context.Context, in *empty.Empty) (*consol return &console.StatusList{ Nodes: nodes, - Timestamp: ×tamp.Timestamp{Seconds: time.Now().UTC().Unix()}, + Timestamp: ×tamppb.Timestamp{Seconds: time.Now().UTC().Unix()}, }, nil } diff --git a/server/console_storage.go b/server/console_storage.go index 0f1d8080b0e07fb6c1f5bacc606eba09ee8cc309..25381e1fa907897c3cae3e4016d79dca3772335f 100644 --- a/server/console_storage.go +++ b/server/console_storage.go @@ -21,18 +21,18 @@ import ( "encoding/base64" "encoding/gob" "encoding/json" + "google.golang.org/protobuf/types/known/timestamppb" "strconv" "sync/atomic" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/empty" - "github.com/golang/protobuf/ptypes/timestamp" "github.com/heroiclabs/nakama-common/api" "github.com/heroiclabs/nakama/v3/console" "github.com/jackc/pgx/pgtype" "go.uber.org/zap" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/emptypb" ) type consoleStorageCursor struct { @@ -44,16 +44,16 @@ type consoleStorageCursor struct { var collectionSetCache = &atomic.Value{} -func (s *ConsoleServer) DeleteStorage(ctx context.Context, in *empty.Empty) (*empty.Empty, error) { +func (s *ConsoleServer) DeleteStorage(ctx context.Context, in *emptypb.Empty) (*emptypb.Empty, error) { _, err := s.db.ExecContext(ctx, "TRUNCATE TABLE storage") if err != nil { s.logger.Error("Failed to truncate Storage table.", zap.Error(err)) return nil, status.Error(codes.Internal, "An error occurred while deleting storage objects.") } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ConsoleServer) DeleteStorageObject(ctx context.Context, in *console.DeleteStorageObjectRequest) (*empty.Empty, error) { +func (s *ConsoleServer) DeleteStorageObject(ctx context.Context, in *console.DeleteStorageObjectRequest) (*emptypb.Empty, error) { if in.Collection == "" { return nil, status.Error(codes.InvalidArgument, "Requires a valid collection.") } @@ -86,7 +86,7 @@ func (s *ConsoleServer) DeleteStorageObject(ctx context.Context, in *console.Del return nil, err } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } func (s *ConsoleServer) GetStorage(ctx context.Context, in *api.ReadStorageObjectId) (*api.StorageObject, error) { @@ -115,7 +115,7 @@ func (s *ConsoleServer) GetStorage(ctx context.Context, in *api.ReadStorageObjec return objects.Objects[0], nil } -func (s *ConsoleServer) ListStorageCollections(ctx context.Context, in *empty.Empty) (*console.StorageCollectionsList, error) { +func (s *ConsoleServer) ListStorageCollections(ctx context.Context, in *emptypb.Empty) (*console.StorageCollectionsList, error) { collectionSetCache := collectionSetCache.Load() if collectionSetCache == nil { return &console.StorageCollectionsList{ @@ -259,7 +259,7 @@ func (s *ConsoleServer) ListStorage(ctx context.Context, in *console.ListStorage var nextCursor *consoleStorageCursor for rows.Next() { - o := &api.StorageObject{CreateTime: ×tamp.Timestamp{}, UpdateTime: ×tamp.Timestamp{}} + o := &api.StorageObject{CreateTime: ×tamppb.Timestamp{}, UpdateTime: ×tamppb.Timestamp{}} var createTime pgtype.Timestamptz var updateTime pgtype.Timestamptz diff --git a/server/console_storage_import.go b/server/console_storage_import.go index 1ff9a0969507256b6884f6db2d6e6cf85e9e4c57..07c4bfa554ff45ea7abb3157da02bf8551d976c4 100644 --- a/server/console_storage_import.go +++ b/server/console_storage_import.go @@ -23,6 +23,7 @@ import ( "errors" "fmt" "github.com/heroiclabs/nakama/v3/console" + "google.golang.org/protobuf/types/known/wrapperspb" "io" "io/ioutil" "net/http" @@ -30,7 +31,6 @@ import ( "strings" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/wrappers" "github.com/heroiclabs/nakama-common/api" "go.uber.org/zap" ) @@ -190,8 +190,8 @@ func importStorageJSON(ctx context.Context, logger *zap.Logger, db *sql.DB, file Collection: d.Collection, Key: d.Key, Value: string(value), - PermissionRead: &wrappers.Int32Value{Value: int32(d.PermissionRead)}, - PermissionWrite: &wrappers.Int32Value{Value: int32(d.PermissionWrite)}, + PermissionRead: &wrapperspb.Int32Value{Value: int32(d.PermissionRead)}, + PermissionWrite: &wrapperspb.Int32Value{Value: int32(d.PermissionWrite)}, }, }) } @@ -289,8 +289,8 @@ func importStorageCSV(ctx context.Context, logger *zap.Logger, db *sql.DB, fileB Collection: collection, Key: key, Value: value, - PermissionRead: &wrappers.Int32Value{Value: int32(pr)}, - PermissionWrite: &wrappers.Int32Value{Value: int32(pw)}, + PermissionRead: &wrapperspb.Int32Value{Value: int32(pr)}, + PermissionWrite: &wrapperspb.Int32Value{Value: int32(pw)}, }, }) } diff --git a/server/console_unlink.go b/server/console_unlink.go index b607ee9f2966aa689ffec7fb4f8ec34231bbc751..8745bf10eb2618e0f9a57d0527c3f0ff0f5fd816 100644 --- a/server/console_unlink.go +++ b/server/console_unlink.go @@ -17,14 +17,14 @@ package server import ( "context" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/empty" "github.com/heroiclabs/nakama/v3/console" "go.uber.org/zap" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/emptypb" ) -func (s *ConsoleServer) UnlinkApple(ctx context.Context, in *console.AccountId) (*empty.Empty, error) { +func (s *ConsoleServer) UnlinkApple(ctx context.Context, in *console.AccountId) (*emptypb.Empty, error) { userID, err := uuid.FromString(in.Id) if err != nil { return nil, status.Error(codes.InvalidArgument, "Requires a valid user ID.") @@ -52,10 +52,10 @@ AND ((custom_id IS NOT NULL return nil, status.Error(codes.PermissionDenied, "Cannot unlink Apple ID when there are no other identifiers.") } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ConsoleServer) UnlinkCustom(ctx context.Context, in *console.AccountId) (*empty.Empty, error) { +func (s *ConsoleServer) UnlinkCustom(ctx context.Context, in *console.AccountId) (*emptypb.Empty, error) { userID, err := uuid.FromString(in.Id) if err != nil { return nil, status.Error(codes.InvalidArgument, "Requires a valid user ID.") @@ -83,10 +83,10 @@ AND ((apple_id IS NOT NULL return nil, status.Error(codes.PermissionDenied, "Cannot unlink custom ID when there are no other identifiers.") } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ConsoleServer) UnlinkDevice(ctx context.Context, in *console.UnlinkDeviceRequest) (*empty.Empty, error) { +func (s *ConsoleServer) UnlinkDevice(ctx context.Context, in *console.UnlinkDeviceRequest) (*emptypb.Empty, error) { userID, err := uuid.FromString(in.Id) if err != nil { return nil, status.Error(codes.InvalidArgument, "Requires a valid user ID.") @@ -143,10 +143,10 @@ AND (EXISTS (SELECT id FROM users WHERE id = $1 AND return nil, status.Error(codes.Internal, "Could not unlink device ID.") } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ConsoleServer) UnlinkEmail(ctx context.Context, in *console.AccountId) (*empty.Empty, error) { +func (s *ConsoleServer) UnlinkEmail(ctx context.Context, in *console.AccountId) (*emptypb.Empty, error) { userID, err := uuid.FromString(in.Id) if err != nil { return nil, status.Error(codes.InvalidArgument, "Requires a valid user ID.") @@ -174,10 +174,10 @@ AND ((apple_id IS NOT NULL return nil, status.Error(codes.PermissionDenied, "Cannot unlink email address when there are no other identifiers.") } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ConsoleServer) UnlinkFacebook(ctx context.Context, in *console.AccountId) (*empty.Empty, error) { +func (s *ConsoleServer) UnlinkFacebook(ctx context.Context, in *console.AccountId) (*emptypb.Empty, error) { userID, err := uuid.FromString(in.Id) if err != nil { return nil, status.Error(codes.InvalidArgument, "Requires a valid user ID.") @@ -205,10 +205,10 @@ AND ((apple_id IS NOT NULL return nil, status.Error(codes.PermissionDenied, "Cannot unlink Facebook ID when there are no other identifiers.") } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ConsoleServer) UnlinkFacebookInstantGame(ctx context.Context, in *console.AccountId) (*empty.Empty, error) { +func (s *ConsoleServer) UnlinkFacebookInstantGame(ctx context.Context, in *console.AccountId) (*emptypb.Empty, error) { userID, err := uuid.FromString(in.Id) if err != nil { return nil, status.Error(codes.InvalidArgument, "Requires a valid user ID.") @@ -236,10 +236,10 @@ AND ((apple_id IS NOT NULL return nil, status.Error(codes.PermissionDenied, "Cannot unlink Facebook ID when there are no other identifiers.") } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ConsoleServer) UnlinkGameCenter(ctx context.Context, in *console.AccountId) (*empty.Empty, error) { +func (s *ConsoleServer) UnlinkGameCenter(ctx context.Context, in *console.AccountId) (*emptypb.Empty, error) { userID, err := uuid.FromString(in.Id) if err != nil { return nil, status.Error(codes.InvalidArgument, "Requires a valid user ID.") @@ -267,10 +267,10 @@ AND ((apple_id IS NOT NULL return nil, status.Error(codes.PermissionDenied, "Cannot unlink Game Center ID when there are no other identifiers.") } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ConsoleServer) UnlinkGoogle(ctx context.Context, in *console.AccountId) (*empty.Empty, error) { +func (s *ConsoleServer) UnlinkGoogle(ctx context.Context, in *console.AccountId) (*emptypb.Empty, error) { userID, err := uuid.FromString(in.Id) if err != nil { return nil, status.Error(codes.InvalidArgument, "Requires a valid user ID.") @@ -298,10 +298,10 @@ AND ((apple_id IS NOT NULL return nil, status.Error(codes.PermissionDenied, "Cannot unlink Google ID when there are no other identifiers.") } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ConsoleServer) UnlinkSteam(ctx context.Context, in *console.AccountId) (*empty.Empty, error) { +func (s *ConsoleServer) UnlinkSteam(ctx context.Context, in *console.AccountId) (*emptypb.Empty, error) { userID, err := uuid.FromString(in.Id) if err != nil { return nil, status.Error(codes.InvalidArgument, "Requires a valid user ID.") @@ -329,5 +329,5 @@ AND ((apple_id IS NOT NULL return nil, status.Error(codes.PermissionDenied, "Cannot unlink Steam ID when there are no other identifiers.") } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } diff --git a/server/console_user.go b/server/console_user.go index 40c6a16bdaec484ecdc9fa47345ebe6d4d90a21e..2a99f35955e9b7db83cf62c84bc1222dd53f1980 100644 --- a/server/console_user.go +++ b/server/console_user.go @@ -23,18 +23,18 @@ import ( "unicode" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/empty" "github.com/heroiclabs/nakama/v3/console" "github.com/jackc/pgx" "go.uber.org/zap" "golang.org/x/crypto/bcrypt" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/emptypb" ) var usernameRegex = regexp.MustCompile("^[a-zA-Z0-9][a-zA-Z0-9._].*[a-zA-Z0-9]$") -func (s *ConsoleServer) AddUser(ctx context.Context, in *console.AddUserRequest) (*empty.Empty, error) { +func (s *ConsoleServer) AddUser(ctx context.Context, in *console.AddUserRequest) (*emptypb.Empty, error) { if in.Username == "" { return nil, status.Error(codes.InvalidArgument, "Username is required") @@ -86,7 +86,7 @@ func (s *ConsoleServer) AddUser(ctx context.Context, in *console.AddUserRequest) } else if !inserted { return nil, status.Error(codes.FailedPrecondition, "Username or Email already exists") } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } func (s *ConsoleServer) dbInsertConsoleUser(ctx context.Context, in *console.AddUserRequest) (bool, error) { @@ -111,7 +111,7 @@ func (s *ConsoleServer) dbInsertConsoleUser(ctx context.Context, in *console.Add return true, nil } -func (s *ConsoleServer) DeleteUser(ctx context.Context, in *console.Username) (*empty.Empty, error) { +func (s *ConsoleServer) DeleteUser(ctx context.Context, in *console.Username) (*emptypb.Empty, error) { if deleted, err := s.dbDeleteConsoleUser(ctx, in.Username); err != nil { s.logger.Error("failed to delete console user", zap.Error(err), zap.String("username", in.Username)) @@ -120,10 +120,10 @@ func (s *ConsoleServer) DeleteUser(ctx context.Context, in *console.Username) (* return nil, status.Error(codes.InvalidArgument, "User not found") } - return &empty.Empty{}, nil + return &emptypb.Empty{}, nil } -func (s *ConsoleServer) ListUsers(ctx context.Context, in *empty.Empty) (*console.UserList, error) { +func (s *ConsoleServer) ListUsers(ctx context.Context, in *emptypb.Empty) (*console.UserList, error) { users, err := s.dbListConsoleUsers(ctx) if err != nil { s.logger.Error("failed to list console users", zap.Error(err)) diff --git a/server/core_account.go b/server/core_account.go index 7dd6553b5e5c67815070414fda0de5d21d2dcdf9..6233ca37755a88b4f54e832acc4778fbd51a2a6f 100644 --- a/server/core_account.go +++ b/server/core_account.go @@ -20,8 +20,6 @@ import ( "encoding/json" "errors" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/timestamp" - "github.com/golang/protobuf/ptypes/wrappers" "github.com/heroiclabs/nakama-common/api" "github.com/heroiclabs/nakama/v3/console" "github.com/jackc/pgx" @@ -29,6 +27,8 @@ import ( "go.uber.org/zap" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/types/known/timestamppb" + "google.golang.org/protobuf/types/known/wrapperspb" "strconv" "strings" ) @@ -39,12 +39,12 @@ var ErrAccountNotFound = errors.New("account not found") type accountUpdate struct { userID uuid.UUID username string - displayName *wrappers.StringValue - timezone *wrappers.StringValue - location *wrappers.StringValue - langTag *wrappers.StringValue - avatarURL *wrappers.StringValue - metadata *wrappers.StringValue + displayName *wrapperspb.StringValue + timezone *wrapperspb.StringValue + location *wrapperspb.StringValue + langTag *wrapperspb.StringValue + avatarURL *wrapperspb.StringValue + metadata *wrapperspb.StringValue } func GetAccount(ctx context.Context, logger *zap.Logger, db *sql.DB, tracker Tracker, userID uuid.UUID) (*api.Account, error) { @@ -91,13 +91,13 @@ WHERE u.id = $1` devices = append(devices, &api.AccountDevice{Id: deviceID.String}) } - var verifyTimestamp *timestamp.Timestamp + var verifyTimestamp *timestamppb.Timestamp if verifyTime.Status == pgtype.Present && verifyTime.Time.Unix() != 0 { - verifyTimestamp = ×tamp.Timestamp{Seconds: verifyTime.Time.Unix()} + verifyTimestamp = ×tamppb.Timestamp{Seconds: verifyTime.Time.Unix()} } - var disableTimestamp *timestamp.Timestamp + var disableTimestamp *timestamppb.Timestamp if disableTime.Status == pgtype.Present && disableTime.Time.Unix() != 0 { - disableTimestamp = ×tamp.Timestamp{Seconds: disableTime.Time.Unix()} + disableTimestamp = ×tamppb.Timestamp{Seconds: disableTime.Time.Unix()} } online := false @@ -122,8 +122,8 @@ WHERE u.id = $1` GamecenterId: gamecenter.String, SteamId: steam.String, EdgeCount: int32(edgeCount), - CreateTime: ×tamp.Timestamp{Seconds: createTime.Time.Unix()}, - UpdateTime: ×tamp.Timestamp{Seconds: updateTime.Time.Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: createTime.Time.Unix()}, + UpdateTime: ×tamppb.Timestamp{Seconds: updateTime.Time.Unix()}, Online: online, }, Wallet: wallet.String, @@ -193,13 +193,13 @@ WHERE u.id IN (` + strings.Join(statements, ",") + `)` devices = append(devices, &api.AccountDevice{Id: deviceID.String}) } - var verifyTimestamp *timestamp.Timestamp + var verifyTimestamp *timestamppb.Timestamp if verifyTime.Status == pgtype.Present && verifyTime.Time.Unix() != 0 { - verifyTimestamp = ×tamp.Timestamp{Seconds: verifyTime.Time.Unix()} + verifyTimestamp = ×tamppb.Timestamp{Seconds: verifyTime.Time.Unix()} } - var disableTimestamp *timestamp.Timestamp + var disableTimestamp *timestamppb.Timestamp if disableTime.Status == pgtype.Present && disableTime.Time.Unix() != 0 { - disableTimestamp = ×tamp.Timestamp{Seconds: disableTime.Time.Unix()} + disableTimestamp = ×tamppb.Timestamp{Seconds: disableTime.Time.Unix()} } online := false @@ -224,8 +224,8 @@ WHERE u.id IN (` + strings.Join(statements, ",") + `)` GamecenterId: gamecenter.String, SteamId: steam.String, EdgeCount: int32(edgeCount), - CreateTime: ×tamp.Timestamp{Seconds: createTime.Time.Unix()}, - UpdateTime: ×tamp.Timestamp{Seconds: updateTime.Time.Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: createTime.Time.Unix()}, + UpdateTime: ×tamppb.Timestamp{Seconds: updateTime.Time.Unix()}, Online: online, }, Wallet: wallet.String, @@ -448,8 +448,8 @@ func ExportAccount(ctx context.Context, logger *zap.Logger, db *sql.DB, userID u UserId: w.UserID, Changeset: string(changeset), Metadata: string(metadata), - CreateTime: ×tamp.Timestamp{Seconds: w.CreateTime}, - UpdateTime: ×tamp.Timestamp{Seconds: w.UpdateTime}, + CreateTime: ×tamppb.Timestamp{Seconds: w.CreateTime}, + UpdateTime: ×tamppb.Timestamp{Seconds: w.UpdateTime}, } } diff --git a/server/core_authenticate.go b/server/core_authenticate.go index 6f6294f94b24959b1386b05b1feebc113dd3f6c6..3e4eb6d6262d694ba02cbf51ed2a9d681846b709 100644 --- a/server/core_authenticate.go +++ b/server/core_authenticate.go @@ -20,12 +20,12 @@ import ( "encoding/json" "errors" "fmt" + "google.golang.org/protobuf/types/known/timestamppb" "strconv" "strings" "time" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/timestamp" "github.com/heroiclabs/nakama-common/api" "github.com/heroiclabs/nakama/v3/social" "github.com/jackc/pgx" @@ -1067,7 +1067,7 @@ func sendFriendAddedNotification(ctx context.Context, logger *zap.Logger, db *sq SenderId: userID.String(), Code: NotificationCodeFriendJoinGame, Persistent: true, - CreateTime: ×tamp.Timestamp{Seconds: createTime}, + CreateTime: ×tamppb.Timestamp{Seconds: createTime}, }} } // Any error is already logged before it's returned here. diff --git a/server/core_channel.go b/server/core_channel.go index 291b9c5ce440aeb734ab85e938dac39d9f9952cc..223a91fc5d3619c32fcd95cc50f0befd3682f1df 100644 --- a/server/core_channel.go +++ b/server/core_channel.go @@ -22,12 +22,12 @@ import ( "encoding/gob" "errors" "fmt" + "google.golang.org/protobuf/types/known/timestamppb" + "google.golang.org/protobuf/types/known/wrapperspb" "strings" "time" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/timestamp" - "github.com/golang/protobuf/ptypes/wrappers" "github.com/heroiclabs/nakama-common/api" "github.com/jackc/pgx/pgtype" "go.uber.org/zap" @@ -163,13 +163,13 @@ WHERE stream_mode = $1 AND stream_subject = $2::UUID AND stream_descriptor = $3: message := &api.ChannelMessage{ ChannelId: channelID, MessageId: dbID, - Code: &wrappers.Int32Value{Value: dbCode}, + Code: &wrapperspb.Int32Value{Value: dbCode}, SenderId: dbSenderID, Username: dbUsername, Content: dbContent, - CreateTime: ×tamp.Timestamp{Seconds: dbCreateTime.Time.Unix()}, - UpdateTime: ×tamp.Timestamp{Seconds: dbUpdateTime.Time.Unix()}, - Persistent: &wrappers.BoolValue{Value: true}, + CreateTime: ×tamppb.Timestamp{Seconds: dbCreateTime.Time.Unix()}, + UpdateTime: ×tamppb.Timestamp{Seconds: dbUpdateTime.Time.Unix()}, + Persistent: &wrapperspb.BoolValue{Value: true}, } switch stream.Mode { case StreamModeChannel: @@ -314,13 +314,13 @@ func GetChannelMessages(ctx context.Context, logger *zap.Logger, db *sql.DB, use messages = append(messages, &api.ChannelMessage{ ChannelId: channelID, MessageId: dbID, - Code: &wrappers.Int32Value{Value: dbCode}, + Code: &wrapperspb.Int32Value{Value: dbCode}, SenderId: userID.String(), Username: dbUsername, Content: dbContent, - CreateTime: ×tamp.Timestamp{Seconds: dbCreateTime.Time.Unix()}, - UpdateTime: ×tamp.Timestamp{Seconds: dbUpdateTime.Time.Unix()}, - Persistent: &wrappers.BoolValue{Value: true}, + CreateTime: ×tamppb.Timestamp{Seconds: dbCreateTime.Time.Unix()}, + UpdateTime: ×tamppb.Timestamp{Seconds: dbUpdateTime.Time.Unix()}, + Persistent: &wrapperspb.BoolValue{Value: true}, }) } diff --git a/server/core_friend.go b/server/core_friend.go index cf3c4c1fc4ea7ac4e66051a1b5f8f199112b927f..8483bf7b62b86b52a6f75ef05658e8b2f5d11c12 100644 --- a/server/core_friend.go +++ b/server/core_friend.go @@ -22,15 +22,14 @@ import ( "encoding/json" "errors" "fmt" + "google.golang.org/protobuf/types/known/timestamppb" + "google.golang.org/protobuf/types/known/wrapperspb" "strconv" "time" - "github.com/golang/protobuf/ptypes/wrappers" - "context" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/timestamp" "github.com/heroiclabs/nakama-common/api" "github.com/jackc/pgx/pgtype" "go.uber.org/zap" @@ -75,7 +74,7 @@ FROM users, user_edge WHERE id = destination_id AND source_id = $1` friends = append(friends, &api.Friend{ User: user, - State: &wrappers.Int32Value{ + State: &wrapperspb.Int32Value{ Value: int32(state.Int64), }, }) @@ -88,7 +87,7 @@ FROM users, user_edge WHERE id = destination_id AND source_id = $1` return &api.FriendList{Friends: friends}, nil } -func ListFriends(ctx context.Context, logger *zap.Logger, db *sql.DB, tracker Tracker, userID uuid.UUID, limit int, state *wrappers.Int32Value, cursor string) (*api.FriendList, error) { +func ListFriends(ctx context.Context, logger *zap.Logger, db *sql.DB, tracker Tracker, userID uuid.UUID, limit int, state *wrapperspb.Int32Value, cursor string) (*api.FriendList, error) { var incomingCursor *edgeListCursor if cursor != "" { cb, err := base64.StdEncoding.DecodeString(cursor) @@ -196,8 +195,8 @@ FROM users, user_edge WHERE id = destination_id AND source_id = $1` Location: location.String, Timezone: timezone.String, Metadata: string(metadata), - CreateTime: ×tamp.Timestamp{Seconds: createTime.Time.Unix()}, - UpdateTime: ×tamp.Timestamp{Seconds: updateTime.Time.Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: createTime.Time.Unix()}, + UpdateTime: ×tamppb.Timestamp{Seconds: updateTime.Time.Unix()}, Online: online, FacebookId: facebookID.String, GoogleId: googleID.String, @@ -209,10 +208,10 @@ FROM users, user_edge WHERE id = destination_id AND source_id = $1` friends = append(friends, &api.Friend{ User: user, - State: &wrappers.Int32Value{ + State: &wrapperspb.Int32Value{ Value: int32(state.Int64), }, - UpdateTime: ×tamp.Timestamp{Seconds: edgeUpdateTime.Time.Unix()}, + UpdateTime: ×tamppb.Timestamp{Seconds: edgeUpdateTime.Time.Unix()}, }) } if err = rows.Err(); err != nil { @@ -272,7 +271,7 @@ func AddFriends(ctx context.Context, logger *zap.Logger, db *sql.DB, messageRout SenderId: userID.String(), Code: code, Persistent: true, - CreateTime: ×tamp.Timestamp{Seconds: time.Now().UTC().Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: time.Now().UTC().Unix()}, }} } diff --git a/server/core_group.go b/server/core_group.go index bd7e557f98a023b4700eb64b6adc1f2f359a5543..0ac5a2e7b96f1371c225889f1639f4a5db168904 100644 --- a/server/core_group.go +++ b/server/core_group.go @@ -23,6 +23,8 @@ import ( "encoding/json" "errors" "fmt" + "google.golang.org/protobuf/types/known/timestamppb" + "google.golang.org/protobuf/types/known/wrapperspb" "strconv" "strings" "time" @@ -30,8 +32,6 @@ import ( "github.com/heroiclabs/nakama-common/rtapi" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/timestamp" - "github.com/golang/protobuf/ptypes/wrappers" "github.com/heroiclabs/nakama-common/api" "github.com/jackc/pgx" "github.com/jackc/pgx/pgtype" @@ -141,7 +141,7 @@ RETURNING id, creator_id, name, description, avatar_url, state, edge_count, lang return group, nil } -func UpdateGroup(ctx context.Context, logger *zap.Logger, db *sql.DB, groupID uuid.UUID, userID uuid.UUID, creatorID uuid.UUID, name, lang, desc, avatar, metadata *wrappers.StringValue, open *wrappers.BoolValue, maxCount int) error { +func UpdateGroup(ctx context.Context, logger *zap.Logger, db *sql.DB, groupID uuid.UUID, userID uuid.UUID, creatorID uuid.UUID, name, lang, desc, avatar, metadata *wrapperspb.StringValue, open *wrapperspb.BoolValue, maxCount int) error { if userID != uuid.Nil { allowedUser, err := groupCheckUserPermission(ctx, logger, db, groupID, userID, 1) if err != nil { @@ -350,7 +350,7 @@ WHERE (id = $1) AND (disable_time = '1970-01-01 00:00:00 UTC')` SenderId: userID.String(), Code: NotificationCodeGroupJoinRequest, Persistent: true, - CreateTime: ×tamp.Timestamp{Seconds: time.Now().UTC().Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: time.Now().UTC().Unix()}, }, } } @@ -381,13 +381,13 @@ WHERE (id = $1) AND (disable_time = '1970-01-01 00:00:00 UTC')` message := &api.ChannelMessage{ ChannelId: channelID, MessageId: uuid.Must(uuid.NewV4()).String(), - Code: &wrappers.Int32Value{Value: ChannelMessageTypeGroupJoin}, + Code: &wrapperspb.Int32Value{Value: ChannelMessageTypeGroupJoin}, SenderId: userID.String(), Username: username, Content: "{}", - CreateTime: ×tamp.Timestamp{Seconds: ts}, - UpdateTime: ×tamp.Timestamp{Seconds: ts}, - Persistent: &wrappers.BoolValue{Value: true}, + CreateTime: ×tamppb.Timestamp{Seconds: ts}, + UpdateTime: ×tamppb.Timestamp{Seconds: ts}, + Persistent: &wrapperspb.BoolValue{Value: true}, GroupId: group.Id, } @@ -479,13 +479,13 @@ func LeaveGroup(ctx context.Context, logger *zap.Logger, db *sql.DB, router Mess message := &api.ChannelMessage{ ChannelId: channelID, MessageId: uuid.Must(uuid.NewV4()).String(), - Code: &wrappers.Int32Value{Value: ChannelMessageTypeGroupLeave}, + Code: &wrapperspb.Int32Value{Value: ChannelMessageTypeGroupLeave}, SenderId: userID.String(), Username: username, Content: "{}", - CreateTime: ×tamp.Timestamp{Seconds: ts}, - UpdateTime: ×tamp.Timestamp{Seconds: ts}, - Persistent: &wrappers.BoolValue{Value: true}, + CreateTime: ×tamppb.Timestamp{Seconds: ts}, + UpdateTime: ×tamppb.Timestamp{Seconds: ts}, + Persistent: &wrapperspb.BoolValue{Value: true}, GroupId: groupID.String(), } @@ -672,13 +672,13 @@ func AddGroupUsers(ctx context.Context, logger *zap.Logger, db *sql.DB, router M message := &api.ChannelMessage{ ChannelId: channelID, MessageId: uuid.Must(uuid.NewV4()).String(), - Code: &wrappers.Int32Value{Value: ChannelMessageTypeGroupAdd}, + Code: &wrapperspb.Int32Value{Value: ChannelMessageTypeGroupAdd}, SenderId: uid.String(), Username: username.String, Content: "{}", - CreateTime: ×tamp.Timestamp{Seconds: ts}, - UpdateTime: ×tamp.Timestamp{Seconds: ts}, - Persistent: &wrappers.BoolValue{Value: true}, + CreateTime: ×tamppb.Timestamp{Seconds: ts}, + UpdateTime: ×tamppb.Timestamp{Seconds: ts}, + Persistent: &wrapperspb.BoolValue{Value: true}, GroupId: groupID.String(), } @@ -699,7 +699,7 @@ VALUES ($1, $2, $3, $4, $5, $6::UUID, $7::UUID, $8, $9, $10, $10)` SenderId: caller.String(), Code: NotificationCodeGroupAdd, Persistent: true, - CreateTime: ×tamp.Timestamp{Seconds: time.Now().UTC().Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: time.Now().UTC().Unix()}, }, } } @@ -853,13 +853,13 @@ UPDATE SET state = $2, update_time = now()` message := &api.ChannelMessage{ ChannelId: channelID, MessageId: uuid.Must(uuid.NewV4()).String(), - Code: &wrappers.Int32Value{Value: ChannelMessageTypeGroupBan}, + Code: &wrapperspb.Int32Value{Value: ChannelMessageTypeGroupBan}, SenderId: uid.String(), Username: username.String, Content: "{}", - CreateTime: ×tamp.Timestamp{Seconds: ts}, - UpdateTime: ×tamp.Timestamp{Seconds: ts}, - Persistent: &wrappers.BoolValue{Value: true}, + CreateTime: ×tamppb.Timestamp{Seconds: ts}, + UpdateTime: ×tamppb.Timestamp{Seconds: ts}, + Persistent: &wrapperspb.BoolValue{Value: true}, GroupId: groupID.String(), } @@ -1008,13 +1008,13 @@ RETURNING state` message := &api.ChannelMessage{ ChannelId: channelID, MessageId: uuid.Must(uuid.NewV4()).String(), - Code: &wrappers.Int32Value{Value: ChannelMessageTypeGroupKick}, + Code: &wrapperspb.Int32Value{Value: ChannelMessageTypeGroupKick}, SenderId: uid.String(), Username: username.String, Content: "{}", - CreateTime: ×tamp.Timestamp{Seconds: ts}, - UpdateTime: ×tamp.Timestamp{Seconds: ts}, - Persistent: &wrappers.BoolValue{Value: true}, + CreateTime: ×tamppb.Timestamp{Seconds: ts}, + UpdateTime: ×tamppb.Timestamp{Seconds: ts}, + Persistent: &wrapperspb.BoolValue{Value: true}, GroupId: groupID.String(), } @@ -1150,13 +1150,13 @@ RETURNING state` message := &api.ChannelMessage{ ChannelId: channelID, MessageId: uuid.Must(uuid.NewV4()).String(), - Code: &wrappers.Int32Value{Value: ChannelMessageTypeGroupPromote}, + Code: &wrapperspb.Int32Value{Value: ChannelMessageTypeGroupPromote}, SenderId: uid.String(), Username: username.String, Content: "{}", - CreateTime: ×tamp.Timestamp{Seconds: ts}, - UpdateTime: ×tamp.Timestamp{Seconds: ts}, - Persistent: &wrappers.BoolValue{Value: true}, + CreateTime: ×tamppb.Timestamp{Seconds: ts}, + UpdateTime: ×tamppb.Timestamp{Seconds: ts}, + Persistent: &wrapperspb.BoolValue{Value: true}, GroupId: groupID.String(), } @@ -1296,13 +1296,13 @@ RETURNING state` message := &api.ChannelMessage{ ChannelId: channelID, MessageId: uuid.Must(uuid.NewV4()).String(), - Code: &wrappers.Int32Value{Value: ChannelMessageTypeGroupDemote}, + Code: &wrapperspb.Int32Value{Value: ChannelMessageTypeGroupDemote}, SenderId: uid.String(), Username: username.String, Content: "{}", - CreateTime: ×tamp.Timestamp{Seconds: ts}, - UpdateTime: ×tamp.Timestamp{Seconds: ts}, - Persistent: &wrappers.BoolValue{Value: true}, + CreateTime: ×tamppb.Timestamp{Seconds: ts}, + UpdateTime: ×tamppb.Timestamp{Seconds: ts}, + Persistent: &wrapperspb.BoolValue{Value: true}, GroupId: groupID.String(), } @@ -1328,7 +1328,7 @@ VALUES ($1, $2, $3, $4, $5, $6::UUID, $7::UUID, $8, $9, $10, $10)` return nil } -func ListGroupUsers(ctx context.Context, logger *zap.Logger, db *sql.DB, tracker Tracker, groupID uuid.UUID, limit int, state *wrappers.Int32Value, cursor string) (*api.GroupUserList, error) { +func ListGroupUsers(ctx context.Context, logger *zap.Logger, db *sql.DB, tracker Tracker, groupID uuid.UUID, limit int, state *wrapperspb.Int32Value, cursor string) (*api.GroupUserList, error) { var incomingCursor *edgeListCursor if cursor != "" { cb, err := base64.StdEncoding.DecodeString(cursor) @@ -1448,14 +1448,14 @@ WHERE u.id = ge.destination_id AND ge.source_id = $1` GamecenterId: gamecenter.String, SteamId: steam.String, EdgeCount: int32(edgeCount), - CreateTime: ×tamp.Timestamp{Seconds: createTime.Time.Unix()}, - UpdateTime: ×tamp.Timestamp{Seconds: updateTime.Time.Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: createTime.Time.Unix()}, + UpdateTime: ×tamppb.Timestamp{Seconds: updateTime.Time.Unix()}, Online: tracker.StreamExists(PresenceStream{Mode: StreamModeStatus, Subject: userID}), } groupUser := &api.GroupUserList_GroupUser{ User: user, - State: &wrappers.Int32Value{ + State: &wrapperspb.Int32Value{ Value: int32(state.Int64), }, } @@ -1466,7 +1466,7 @@ WHERE u.id = ge.destination_id AND ge.source_id = $1` return &api.GroupUserList{GroupUsers: groupUsers, Cursor: outgoingCursor}, nil } -func ListUserGroups(ctx context.Context, logger *zap.Logger, db *sql.DB, userID uuid.UUID, limit int, state *wrappers.Int32Value, cursor string) (*api.UserGroupList, error) { +func ListUserGroups(ctx context.Context, logger *zap.Logger, db *sql.DB, userID uuid.UUID, limit int, state *wrapperspb.Int32Value, cursor string) (*api.UserGroupList, error) { var incomingCursor *edgeListCursor if cursor != "" { cb, err := base64.StdEncoding.DecodeString(cursor) @@ -1575,16 +1575,16 @@ WHERE g.id = ge.destination_id AND ge.source_id = $1` AvatarUrl: avatarURL.String, LangTag: lang.String, Metadata: string(metadata), - Open: &wrappers.BoolValue{Value: open}, + Open: &wrapperspb.BoolValue{Value: open}, EdgeCount: int32(edgeCount.Int64), MaxCount: int32(maxCount.Int64), - CreateTime: ×tamp.Timestamp{Seconds: createTime.Time.Unix()}, - UpdateTime: ×tamp.Timestamp{Seconds: updateTime.Time.Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: createTime.Time.Unix()}, + UpdateTime: ×tamppb.Timestamp{Seconds: updateTime.Time.Unix()}, } userGroup := &api.UserGroupList_UserGroup{ Group: group, - State: &wrappers.Int32Value{ + State: &wrapperspb.Int32Value{ Value: int32(userState.Int64), }, } @@ -1767,11 +1767,11 @@ func groupConvertRows(rows *sql.Rows) ([]*api.Group, error) { AvatarUrl: avatarURL.String, LangTag: lang.String, Metadata: string(metadata), - Open: &wrappers.BoolValue{Value: open}, + Open: &wrapperspb.BoolValue{Value: open}, EdgeCount: int32(edgeCount.Int64), MaxCount: int32(maxCount.Int64), - CreateTime: ×tamp.Timestamp{Seconds: createTime.Time.Unix()}, - UpdateTime: ×tamp.Timestamp{Seconds: updateTime.Time.Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: createTime.Time.Unix()}, + UpdateTime: ×tamppb.Timestamp{Seconds: updateTime.Time.Unix()}, } groups = append(groups, group) diff --git a/server/core_leaderboard.go b/server/core_leaderboard.go index 8d2c7f49f04d278739af130bf80f0947405db8fa..21aee45a1cb9fcb000b6ac4f78a1584f4e29e6de 100644 --- a/server/core_leaderboard.go +++ b/server/core_leaderboard.go @@ -21,13 +21,13 @@ import ( "encoding/base64" "encoding/gob" "errors" + "google.golang.org/protobuf/types/known/timestamppb" + "google.golang.org/protobuf/types/known/wrapperspb" "strconv" "strings" "time" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/timestamp" - "github.com/golang/protobuf/ptypes/wrappers" "github.com/heroiclabs/nakama-common/api" "github.com/jackc/pgx/pgtype" "go.uber.org/zap" @@ -51,7 +51,7 @@ type leaderboardRecordListCursor struct { Rank int64 } -func LeaderboardRecordsList(ctx context.Context, logger *zap.Logger, db *sql.DB, leaderboardCache LeaderboardCache, rankCache LeaderboardRankCache, leaderboardId string, limit *wrappers.Int32Value, cursor string, ownerIds []string, overrideExpiry int64) (*api.LeaderboardRecordList, error) { +func LeaderboardRecordsList(ctx context.Context, logger *zap.Logger, db *sql.DB, leaderboardCache LeaderboardCache, rankCache LeaderboardRankCache, leaderboardId string, limit *wrapperspb.Int32Value, cursor string, ownerIds []string, overrideExpiry int64) (*api.LeaderboardRecordList, error) { leaderboard := leaderboardCache.Get(leaderboardId) if leaderboard == nil { return nil, ErrLeaderboardNotFound @@ -170,15 +170,15 @@ func LeaderboardRecordsList(ctx context.Context, logger *zap.Logger, db *sql.DB, NumScore: dbNumScore, MaxNumScore: uint32(dbMaxNumScore), Metadata: dbMetadata, - CreateTime: ×tamp.Timestamp{Seconds: dbCreateTime.Time.Unix()}, - UpdateTime: ×tamp.Timestamp{Seconds: dbUpdateTime.Time.Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: dbCreateTime.Time.Unix()}, + UpdateTime: ×tamppb.Timestamp{Seconds: dbUpdateTime.Time.Unix()}, Rank: rank, } if dbUsername.Valid { - record.Username = &wrappers.StringValue{Value: dbUsername.String} + record.Username = &wrapperspb.StringValue{Value: dbUsername.String} } if expiryTime != 0 { - record.ExpiryTime = ×tamp.Timestamp{Seconds: expiryTime} + record.ExpiryTime = ×tamppb.Timestamp{Seconds: expiryTime} } records = append(records, record) @@ -277,14 +277,14 @@ func LeaderboardRecordsList(ctx context.Context, logger *zap.Logger, db *sql.DB, NumScore: dbNumScore, MaxNumScore: uint32(dbMaxNumScore), Metadata: dbMetadata, - CreateTime: ×tamp.Timestamp{Seconds: dbCreateTime.Time.Unix()}, - UpdateTime: ×tamp.Timestamp{Seconds: dbUpdateTime.Time.Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: dbCreateTime.Time.Unix()}, + UpdateTime: ×tamppb.Timestamp{Seconds: dbUpdateTime.Time.Unix()}, } if dbUsername.Valid { - record.Username = &wrappers.StringValue{Value: dbUsername.String} + record.Username = &wrapperspb.StringValue{Value: dbUsername.String} } if expiryTime != 0 { - record.ExpiryTime = ×tamp.Timestamp{Seconds: expiryTime} + record.ExpiryTime = ×tamppb.Timestamp{Seconds: expiryTime} } ownerRecords = append(ownerRecords, record) @@ -409,14 +409,14 @@ func LeaderboardRecordWrite(ctx context.Context, logger *zap.Logger, db *sql.DB, NumScore: dbNumScore, MaxNumScore: uint32(dbMaxNumScore), Metadata: dbMetadata, - CreateTime: ×tamp.Timestamp{Seconds: dbCreateTime.Time.Unix()}, - UpdateTime: ×tamp.Timestamp{Seconds: dbUpdateTime.Time.Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: dbCreateTime.Time.Unix()}, + UpdateTime: ×tamppb.Timestamp{Seconds: dbUpdateTime.Time.Unix()}, } if dbUsername.Valid { - record.Username = &wrappers.StringValue{Value: dbUsername.String} + record.Username = &wrapperspb.StringValue{Value: dbUsername.String} } if expiryTime != 0 { - record.ExpiryTime = ×tamp.Timestamp{Seconds: expiryTime} + record.ExpiryTime = ×tamppb.Timestamp{Seconds: expiryTime} } return record, nil @@ -521,14 +521,14 @@ func getLeaderboardRecordsHaystack(ctx context.Context, logger *zap.Logger, db * NumScore: dbNumScore, MaxNumScore: uint32(dbMaxNumScore), Metadata: dbMetadata, - CreateTime: ×tamp.Timestamp{Seconds: dbCreateTime.Time.Unix()}, - UpdateTime: ×tamp.Timestamp{Seconds: dbUpdateTime.Time.Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: dbCreateTime.Time.Unix()}, + UpdateTime: ×tamppb.Timestamp{Seconds: dbUpdateTime.Time.Unix()}, } if dbUsername.Valid { - ownerRecord.Username = &wrappers.StringValue{Value: dbUsername.String} + ownerRecord.Username = &wrapperspb.StringValue{Value: dbUsername.String} } if expiryTime := dbExpiryTime.Time.Unix(); expiryTime != 0 { - ownerRecord.ExpiryTime = ×tamp.Timestamp{Seconds: expiryTime} + ownerRecord.ExpiryTime = ×tamppb.Timestamp{Seconds: expiryTime} } if limit == 1 { @@ -641,15 +641,15 @@ func parseLeaderboardRecords(logger *zap.Logger, rows *sql.Rows) ([]*api.Leaderb NumScore: dbNumScore, MaxNumScore: uint32(dbMaxNumScore), Metadata: dbMetadata, - CreateTime: ×tamp.Timestamp{Seconds: dbCreateTime.Time.Unix()}, - UpdateTime: ×tamp.Timestamp{Seconds: dbUpdateTime.Time.Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: dbCreateTime.Time.Unix()}, + UpdateTime: ×tamppb.Timestamp{Seconds: dbUpdateTime.Time.Unix()}, } if dbUsername.Valid { - record.Username = &wrappers.StringValue{Value: dbUsername.String} + record.Username = &wrapperspb.StringValue{Value: dbUsername.String} } expiryTime := dbExpiryTime.Time.Unix() if expiryTime != 0 { - record.ExpiryTime = ×tamp.Timestamp{Seconds: expiryTime} + record.ExpiryTime = ×tamppb.Timestamp{Seconds: expiryTime} } records = append(records, record) diff --git a/server/core_notification.go b/server/core_notification.go index 2840538941e9ffc32a81d66c9065c237ec607d88..80c3dbe07b419a883f0fdbf1527d8990e932882a 100644 --- a/server/core_notification.go +++ b/server/core_notification.go @@ -20,11 +20,11 @@ import ( "database/sql" "encoding/base64" "encoding/gob" + "google.golang.org/protobuf/types/known/timestamppb" "strconv" "strings" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/timestamp" "github.com/heroiclabs/nakama-common/api" "github.com/heroiclabs/nakama-common/rtapi" "github.com/jackc/pgx/pgtype" @@ -111,7 +111,7 @@ ORDER BY create_time ASC, id ASC`+limitQuery, params...) notifications := make([]*api.Notification, 0, limit) var lastCreateTime int64 for rows.Next() { - no := &api.Notification{Persistent: true, CreateTime: ×tamp.Timestamp{}} + no := &api.Notification{Persistent: true, CreateTime: ×tamppb.Timestamp{}} var createTime pgtype.Timestamptz if err := rows.Scan(&no.Id, &no.Subject, &no.Content, &no.Code, &no.SenderId, &createTime); err != nil { _ = rows.Close() diff --git a/server/core_purchase.go b/server/core_purchase.go index af7d411aedc57fbd7ceeacfcd3e59055bafbb095..7e21d9b2e0dac31f50d8a03f4e7f670792f7e10c 100644 --- a/server/core_purchase.go +++ b/server/core_purchase.go @@ -23,7 +23,6 @@ import ( "errors" "fmt" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/timestamp" "github.com/heroiclabs/nakama-common/api" "github.com/heroiclabs/nakama-common/runtime" "github.com/heroiclabs/nakama/v3/iap" @@ -101,9 +100,9 @@ func ValidatePurchasesApple(ctx context.Context, logger *zap.Logger, db *sql.DB, ProductId: p.productId, TransactionId: p.transactionId, Store: p.store, - PurchaseTime: ×tamp.Timestamp{Seconds: p.purchaseTime.Unix()}, - CreateTime: ×tamp.Timestamp{Seconds: p.createTime.Unix()}, - UpdateTime: ×tamp.Timestamp{Seconds: p.updateTime.Unix()}, + PurchaseTime: ×tamppb.Timestamp{Seconds: p.purchaseTime.Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: p.createTime.Unix()}, + UpdateTime: ×tamppb.Timestamp{Seconds: p.updateTime.Unix()}, ProviderResponse: string(raw), Environment: p.environment, }) @@ -155,9 +154,9 @@ func ValidatePurchaseGoogle(ctx context.Context, logger *zap.Logger, db *sql.DB, ProductId: p.productId, TransactionId: p.transactionId, Store: p.store, - PurchaseTime: ×tamp.Timestamp{Seconds: p.purchaseTime.Unix()}, - CreateTime: ×tamp.Timestamp{Seconds: p.createTime.Unix()}, - UpdateTime: ×tamp.Timestamp{Seconds: p.updateTime.Unix()}, + PurchaseTime: ×tamppb.Timestamp{Seconds: p.purchaseTime.Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: p.createTime.Unix()}, + UpdateTime: ×tamppb.Timestamp{Seconds: p.updateTime.Unix()}, ProviderResponse: string(raw), Environment: p.environment, }) @@ -218,9 +217,9 @@ func ValidatePurchaseHuawei(ctx context.Context, logger *zap.Logger, db *sql.DB, ProductId: p.productId, TransactionId: p.transactionId, Store: p.store, - PurchaseTime: ×tamp.Timestamp{Seconds: p.purchaseTime.Unix()}, - CreateTime: ×tamp.Timestamp{Seconds: p.createTime.Unix()}, - UpdateTime: ×tamp.Timestamp{Seconds: p.updateTime.Unix()}, + PurchaseTime: ×tamppb.Timestamp{Seconds: p.purchaseTime.Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: p.createTime.Unix()}, + UpdateTime: ×tamppb.Timestamp{Seconds: p.updateTime.Unix()}, ProviderResponse: string(raw), Environment: p.environment, }) @@ -274,9 +273,9 @@ WHERE TransactionId: transactionID, Store: store, ProviderResponse: rawResponse, - PurchaseTime: ×tamp.Timestamp{Seconds: purchaseTime.Time.Unix()}, - CreateTime: ×tamp.Timestamp{Seconds: createTime.Time.Unix()}, - UpdateTime: ×tamp.Timestamp{Seconds: updateTime.Time.Unix()}, + PurchaseTime: ×tamppb.Timestamp{Seconds: purchaseTime.Time.Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: createTime.Time.Unix()}, + UpdateTime: ×tamppb.Timestamp{Seconds: updateTime.Time.Unix()}, Environment: environment, }, nil } @@ -380,9 +379,9 @@ FROM ProductId: productId, TransactionId: transactionId, Store: store, - PurchaseTime: ×tamp.Timestamp{Seconds: purchaseTime.Time.Unix()}, - CreateTime: ×tamp.Timestamp{Seconds: createTime.Time.Unix()}, - UpdateTime: ×tamp.Timestamp{Seconds: updateTime.Time.Unix()}, + PurchaseTime: ×tamppb.Timestamp{Seconds: purchaseTime.Time.Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: createTime.Time.Unix()}, + UpdateTime: ×tamppb.Timestamp{Seconds: updateTime.Time.Unix()}, ProviderResponse: rawResponse, Environment: environment, } diff --git a/server/core_storage.go b/server/core_storage.go index a19f8350ddf1f791129170b31cdc145b8c467413..69933b74a94c5986e05b4f0871dad5d6f4d428b9 100644 --- a/server/core_storage.go +++ b/server/core_storage.go @@ -23,12 +23,12 @@ import ( "errors" "fmt" "github.com/jackc/pgx" + "google.golang.org/protobuf/types/known/timestamppb" "sort" "context" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/timestamp" "github.com/heroiclabs/nakama-common/api" "github.com/jackc/pgx/pgtype" "go.uber.org/zap" @@ -311,7 +311,7 @@ WHERE user_id = $1` funcObjects := make([]*api.StorageObject, 0, 10) for rows.Next() { - o := &api.StorageObject{CreateTime: ×tamp.Timestamp{}, UpdateTime: ×tamp.Timestamp{}} + o := &api.StorageObject{CreateTime: ×tamppb.Timestamp{}, UpdateTime: ×tamppb.Timestamp{}} var createTime pgtype.Timestamptz var updateTime pgtype.Timestamptz @@ -354,7 +354,7 @@ func storageListObjects(rows *sql.Rows, limit int) (*api.StorageObjectList, erro } // There is still room for more objects, read the next one. - o := &api.StorageObject{CreateTime: ×tamp.Timestamp{}, UpdateTime: ×tamp.Timestamp{}} + o := &api.StorageObject{CreateTime: ×tamppb.Timestamp{}, UpdateTime: ×tamppb.Timestamp{}} var createTime pgtype.Timestamptz var updateTime pgtype.Timestamptz @@ -438,7 +438,7 @@ WHERE funcObjects := &api.StorageObjects{Objects: make([]*api.StorageObject, 0, len(objectIDs))} for rows.Next() { - o := &api.StorageObject{CreateTime: ×tamp.Timestamp{}, UpdateTime: ×tamp.Timestamp{}} + o := &api.StorageObject{CreateTime: ×tamppb.Timestamp{}, UpdateTime: ×tamppb.Timestamp{}} var createTime pgtype.Timestamptz var updateTime pgtype.Timestamptz diff --git a/server/core_storage_test.go b/server/core_storage_test.go index defe3e2ada50596c92afb22d4a023301df5bf858..e89a77d497ba4dbaed4d0869ff5cccf88eb24ad7 100644 --- a/server/core_storage_test.go +++ b/server/core_storage_test.go @@ -21,10 +21,10 @@ import ( "testing" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/wrappers" "github.com/heroiclabs/nakama-common/api" "github.com/stretchr/testify/assert" "google.golang.org/grpc/codes" + "google.golang.org/protobuf/types/known/wrapperspb" ) func TestStorageWriteRuntimeGlobalSingle(t *testing.T) { @@ -38,8 +38,8 @@ func TestStorageWriteRuntimeGlobalSingle(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }} acks, code, err := StorageWriteObjects(context.Background(), logger, db, true, ops) @@ -88,8 +88,8 @@ func TestStorageWriteRuntimeUserMultiple(t *testing.T) { Collection: "testcollection", Key: GenerateString(), Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, &StorageOpWrite{ @@ -98,8 +98,8 @@ func TestStorageWriteRuntimeUserMultiple(t *testing.T) { Collection: "testcollection", Key: GenerateString(), Value: "{\"foo\":\"baz\"}", - PermissionRead: &wrappers.Int32Value{Value: 0}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 0}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, &StorageOpWrite{ @@ -108,8 +108,8 @@ func TestStorageWriteRuntimeUserMultiple(t *testing.T) { Collection: "testcollection", Key: GenerateString(), Value: "{\"foo\":\"qux\"}", - PermissionRead: &wrappers.Int32Value{Value: 1}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 1}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -140,8 +140,8 @@ func TestStorageWriteRuntimeGlobalSingleIfMatchNotExists(t *testing.T) { Key: GenerateString(), Value: "{\"foo\":\"bar\"}", Version: "fail", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -165,8 +165,8 @@ func TestStorageWriteRuntimeGlobalSingleIfMatchExists(t *testing.T) { Collection: "testcollection", Key: GenerateString(), Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -190,8 +190,8 @@ func TestStorageWriteRuntimeGlobalSingleIfMatchExists(t *testing.T) { Key: ops[0].Object.Key, Value: "{\"foo\":\"baz\"}", Version: acks.Acks[0].Version, - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -219,8 +219,8 @@ func TestStorageWriteRuntimeGlobalSingleIfMatchExistsFail(t *testing.T) { Collection: "testcollection", Key: GenerateString(), Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -244,8 +244,8 @@ func TestStorageWriteRuntimeGlobalSingleIfMatchExistsFail(t *testing.T) { Key: ops[0].Object.Key, Value: "{\"foo\":\"baz\"}", Version: "fail", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -270,8 +270,8 @@ func TestStorageWriteRuntimeGlobalSingleIfNoneMatchNotExists(t *testing.T) { Key: GenerateString(), Value: "{\"foo\":\"bar\"}", Version: "*", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -298,8 +298,8 @@ func TestStorageWriteRuntimeGlobalSingleIfNoneMatchExists(t *testing.T) { Collection: "testcollection", Key: GenerateString(), Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -322,8 +322,8 @@ func TestStorageWriteRuntimeGlobalSingleIfNoneMatchExists(t *testing.T) { Key: ops[0].Object.Key, Value: "{\"foo\":\"baz\"}", Version: "*", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -347,8 +347,8 @@ func TestStorageWriteRuntimeGlobalMultipleIfMatchNotExists(t *testing.T) { Collection: "testcollection", Key: GenerateString(), Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, &StorageOpWrite{ @@ -358,8 +358,8 @@ func TestStorageWriteRuntimeGlobalMultipleIfMatchNotExists(t *testing.T) { Key: GenerateString(), Value: "{\"foo\":\"baz\"}", Version: "fail", - PermissionRead: &wrappers.Int32Value{Value: 0}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 0}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, } @@ -386,8 +386,8 @@ func TestStorageWritePipelineUserSingle(t *testing.T) { Collection: "testcollection", Key: GenerateString(), Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -417,8 +417,8 @@ func TestStorageWritePipelineUserMultiple(t *testing.T) { Collection: "testcollection", Key: GenerateString(), Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, &StorageOpWrite{ @@ -427,8 +427,8 @@ func TestStorageWritePipelineUserMultiple(t *testing.T) { Collection: "testcollection", Key: GenerateString(), Value: "{\"foo\":\"baz\"}", - PermissionRead: &wrappers.Int32Value{Value: 0}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 0}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, &StorageOpWrite{ @@ -437,8 +437,8 @@ func TestStorageWritePipelineUserMultiple(t *testing.T) { Collection: "testcollection", Key: GenerateString(), Value: "{\"foo\":\"qux\"}", - PermissionRead: &wrappers.Int32Value{Value: 1}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 1}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -480,8 +480,8 @@ func TestStorageWriteRuntimeGlobalMultipleSameKey(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, &StorageOpWrite{ @@ -490,8 +490,8 @@ func TestStorageWriteRuntimeGlobalMultipleSameKey(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"baz\"}", - PermissionRead: &wrappers.Int32Value{Value: 0}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 0}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, &StorageOpWrite{ @@ -500,8 +500,8 @@ func TestStorageWriteRuntimeGlobalMultipleSameKey(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"qux\"}", - PermissionRead: &wrappers.Int32Value{Value: 1}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 1}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -559,8 +559,8 @@ func TestStorageWritePipelineUserMultipleSameKey(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, &StorageOpWrite{ @@ -569,8 +569,8 @@ func TestStorageWritePipelineUserMultipleSameKey(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"baz\"}", - PermissionRead: &wrappers.Int32Value{Value: 1}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 1}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, } @@ -623,8 +623,8 @@ func TestStorageWritePipelineIfMatchNotExists(t *testing.T) { Key: GenerateString(), Value: "{\"foo\":\"bar\"}", Version: "fail", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -651,8 +651,8 @@ func TestStorageWritePipelineIfMatchExistsFail(t *testing.T) { Collection: "testcollection", Key: GenerateString(), Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -675,8 +675,8 @@ func TestStorageWritePipelineIfMatchExistsFail(t *testing.T) { Key: GenerateString(), Value: "{\"foo\":\"baz\"}", Version: "fail", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -704,8 +704,8 @@ func TestStorageWritePipelineIfMatchExists(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -728,8 +728,8 @@ func TestStorageWritePipelineIfMatchExists(t *testing.T) { Key: key, Value: "{\"foo\":\"baz\"}", Version: acks.Acks[0].Version, - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -760,8 +760,8 @@ func TestStorageWritePipelineIfNoneMatchNotExists(t *testing.T) { Key: GenerateString(), Value: "{\"foo\":\"bar\"}", Version: "*", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -792,8 +792,8 @@ func TestStorageWritePipelineIfNoneMatchExists(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -816,8 +816,8 @@ func TestStorageWritePipelineIfNoneMatchExists(t *testing.T) { Key: key, Value: "{\"foo\":\"baz\"}", Version: "*", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -845,8 +845,8 @@ func TestStorageWritePipelinePermissionFail(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, } @@ -868,8 +868,8 @@ func TestStorageWritePipelinePermissionFail(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"baz\"}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -895,8 +895,8 @@ func TestStorageFetchRuntimeGlobalPrivate(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 0}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 0}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, } @@ -943,8 +943,8 @@ func TestStorageFetchRuntimeMixed(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 0}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 0}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, } @@ -998,8 +998,8 @@ func TestStorageFetchRuntimeUserPrivate(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 0}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 0}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, } @@ -1049,8 +1049,8 @@ func TestStorageFetchPipelineGlobalPrivate(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 0}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 0}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, } @@ -1094,8 +1094,8 @@ func TestStorageFetchPipelineUserPrivate(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 0}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 0}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, } @@ -1140,8 +1140,8 @@ func TestStorageFetchPipelineUserRead(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 1}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 1}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, } @@ -1193,8 +1193,8 @@ func TestStorageFetchPipelineUserPublic(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, } @@ -1245,8 +1245,8 @@ func TestStorageFetchPipelineUserOtherRead(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 1}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 1}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, } @@ -1290,8 +1290,8 @@ func TestStorageFetchPipelineUserOtherPublic(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, } @@ -1344,8 +1344,8 @@ func TestStorageFetchPipelineUserOtherPublicMixed(t *testing.T) { Collection: "testcollection", Key: record1, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, &StorageOpWrite{ @@ -1354,8 +1354,8 @@ func TestStorageFetchPipelineUserOtherPublicMixed(t *testing.T) { Collection: "testcollection", Key: record2, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 1}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 1}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, } @@ -1420,8 +1420,8 @@ func TestStorageRemoveRuntimeGlobalPublic(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 1}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 1}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -1465,8 +1465,8 @@ func TestStorageRemoveRuntimeGlobalPrivate(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 0}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 0}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, } @@ -1512,8 +1512,8 @@ func TestStorageRemoveRuntimeUserPublic(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 1}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 1}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -1559,8 +1559,8 @@ func TestStorageRemoveRuntimeUserPrivate(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 0}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 0}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, } @@ -1616,8 +1616,8 @@ func TestStorageRemovePipelineUserWrite(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 1}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 1}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -1663,8 +1663,8 @@ func TestStorageRemovePipelineUserDenied(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 1}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 1}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, } @@ -1729,8 +1729,8 @@ func TestStorageRemoveRuntimeGlobalIfMatchRejected(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 1}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 1}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -1776,8 +1776,8 @@ func TestStorageRemoveRuntimeGlobalIfMatch(t *testing.T) { Collection: "testcollection", Key: key, Value: "{\"foo\":\"bar\"}", - PermissionRead: &wrappers.Int32Value{Value: 1}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 1}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } @@ -1824,8 +1824,8 @@ func TestStorageListRuntimeUser(t *testing.T) { Collection: "testcollection", Key: "b", Value: "{}", - PermissionRead: &wrappers.Int32Value{Value: 1}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 1}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, &StorageOpWrite{ @@ -1834,8 +1834,8 @@ func TestStorageListRuntimeUser(t *testing.T) { Collection: "testcollection", Key: "a", Value: "{}", - PermissionRead: &wrappers.Int32Value{Value: 1}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 1}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, &StorageOpWrite{ @@ -1844,8 +1844,8 @@ func TestStorageListRuntimeUser(t *testing.T) { Collection: "testcollection", Key: "c", Value: "{}", - PermissionRead: &wrappers.Int32Value{Value: 0}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 0}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, } @@ -1881,8 +1881,8 @@ func TestStorageListPipelineUserSelf(t *testing.T) { Collection: collection, Key: "b", Value: "{}", - PermissionRead: &wrappers.Int32Value{Value: 1}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 1}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, &StorageOpWrite{ @@ -1891,8 +1891,8 @@ func TestStorageListPipelineUserSelf(t *testing.T) { Collection: collection, Key: "a", Value: "{}", - PermissionRead: &wrappers.Int32Value{Value: 1}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 1}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, &StorageOpWrite{ @@ -1901,8 +1901,8 @@ func TestStorageListPipelineUserSelf(t *testing.T) { Collection: collection, Key: "c", Value: "{}", - PermissionRead: &wrappers.Int32Value{Value: 0}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 0}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, } @@ -1940,8 +1940,8 @@ func TestStorageListPipelineUserOther(t *testing.T) { Collection: collection, Key: "b", Value: "{}", - PermissionRead: &wrappers.Int32Value{Value: 1}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 1}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, &StorageOpWrite{ @@ -1950,8 +1950,8 @@ func TestStorageListPipelineUserOther(t *testing.T) { Collection: collection, Key: "a", Value: "{}", - PermissionRead: &wrappers.Int32Value{Value: 1}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 1}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, &StorageOpWrite{ @@ -1960,8 +1960,8 @@ func TestStorageListPipelineUserOther(t *testing.T) { Collection: collection, Key: "c", Value: "{}", - PermissionRead: &wrappers.Int32Value{Value: 0}, - PermissionWrite: &wrappers.Int32Value{Value: 0}, + PermissionRead: &wrapperspb.Int32Value{Value: 0}, + PermissionWrite: &wrapperspb.Int32Value{Value: 0}, }, }, } @@ -1997,8 +1997,8 @@ func TestStorageListNoRepeats(t *testing.T) { Collection: collection, Key: "1", Value: "{}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, &StorageOpWrite{ @@ -2007,8 +2007,8 @@ func TestStorageListNoRepeats(t *testing.T) { Collection: collection, Key: "2", Value: "{}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, &StorageOpWrite{ @@ -2017,8 +2017,8 @@ func TestStorageListNoRepeats(t *testing.T) { Collection: collection, Key: "3", Value: "{}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, &StorageOpWrite{ @@ -2027,8 +2027,8 @@ func TestStorageListNoRepeats(t *testing.T) { Collection: collection, Key: "4", Value: "{}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, &StorageOpWrite{ @@ -2037,8 +2037,8 @@ func TestStorageListNoRepeats(t *testing.T) { Collection: collection, Key: "5", Value: "{}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, &StorageOpWrite{ @@ -2047,8 +2047,8 @@ func TestStorageListNoRepeats(t *testing.T) { Collection: collection, Key: "6", Value: "{}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, &StorageOpWrite{ @@ -2057,8 +2057,8 @@ func TestStorageListNoRepeats(t *testing.T) { Collection: collection, Key: "7", Value: "{}", - PermissionRead: &wrappers.Int32Value{Value: 2}, - PermissionWrite: &wrappers.Int32Value{Value: 1}, + PermissionRead: &wrapperspb.Int32Value{Value: 2}, + PermissionWrite: &wrapperspb.Int32Value{Value: 1}, }, }, } diff --git a/server/core_tournament.go b/server/core_tournament.go index c1d843fd4f77f7a2ddd9574ba358e1f4ddf83581..7abf8518436934a84f0c27f976a03c7ea6d5645d 100644 --- a/server/core_tournament.go +++ b/server/core_tournament.go @@ -22,13 +22,13 @@ import ( "encoding/gob" "errors" "fmt" + "google.golang.org/protobuf/types/known/timestamppb" + "google.golang.org/protobuf/types/known/wrapperspb" "strconv" "strings" "time" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/timestamp" - "github.com/golang/protobuf/ptypes/wrappers" "github.com/heroiclabs/nakama-common/api" "github.com/heroiclabs/nakama/v3/internal/cronexpr" "github.com/jackc/pgx/pgtype" @@ -304,13 +304,13 @@ func TournamentList(ctx context.Context, logger *zap.Logger, db *sql.DB, leaderb EndActive: uint32(endActiveUnix), NextReset: uint32(expiryUnix), Metadata: leaderboard.Metadata, - CreateTime: ×tamp.Timestamp{Seconds: leaderboard.CreateTime}, - StartTime: ×tamp.Timestamp{Seconds: leaderboard.StartTime}, + CreateTime: ×tamppb.Timestamp{Seconds: leaderboard.CreateTime}, + StartTime: ×tamppb.Timestamp{Seconds: leaderboard.StartTime}, Duration: uint32(leaderboard.Duration), StartActive: uint32(startActive), } if leaderboard.EndTime != 0 { - record.EndTime = ×tamp.Timestamp{Seconds: leaderboard.EndTime} + record.EndTime = ×tamppb.Timestamp{Seconds: leaderboard.EndTime} } records = append(records, record) } @@ -330,7 +330,7 @@ func TournamentList(ctx context.Context, logger *zap.Logger, db *sql.DB, leaderb return tournamentList, nil } -func TournamentRecordsList(ctx context.Context, logger *zap.Logger, db *sql.DB, leaderboardCache LeaderboardCache, rankCache LeaderboardRankCache, tournamentId string, ownerIds []string, limit *wrappers.Int32Value, cursor string, overrideExpiry int64) (*api.TournamentRecordList, error) { +func TournamentRecordsList(ctx context.Context, logger *zap.Logger, db *sql.DB, leaderboardCache LeaderboardCache, rankCache LeaderboardRankCache, tournamentId string, ownerIds []string, limit *wrapperspb.Int32Value, cursor string, overrideExpiry int64) (*api.TournamentRecordList, error) { leaderboard := leaderboardCache.Get(tournamentId) if leaderboard == nil || !leaderboard.IsTournament() { return nil, ErrTournamentNotFound @@ -534,14 +534,14 @@ func TournamentRecordWrite(ctx context.Context, logger *zap.Logger, db *sql.DB, NumScore: dbNumScore, MaxNumScore: uint32(dbMaxNumScore), Metadata: dbMetadata, - CreateTime: ×tamp.Timestamp{Seconds: dbCreateTime.Time.Unix()}, - UpdateTime: ×tamp.Timestamp{Seconds: dbUpdateTime.Time.Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: dbCreateTime.Time.Unix()}, + UpdateTime: ×tamppb.Timestamp{Seconds: dbUpdateTime.Time.Unix()}, } if dbUsername.Valid { - record.Username = &wrappers.StringValue{Value: dbUsername.String} + record.Username = &wrapperspb.StringValue{Value: dbUsername.String} } if u := expiryTime.Unix(); u != 0 { - record.ExpiryTime = ×tamp.Timestamp{Seconds: u} + record.ExpiryTime = ×tamppb.Timestamp{Seconds: u} } // Enrich the return record with rank data. @@ -689,14 +689,14 @@ func parseTournament(scannable Scannable, now time.Time) (*api.Tournament, error EndActive: uint32(endActiveUnix), NextReset: uint32(expiryUnix), Metadata: dbMetadata, - CreateTime: ×tamp.Timestamp{Seconds: dbCreateTime.Time.UTC().Unix()}, - StartTime: ×tamp.Timestamp{Seconds: dbStartTime.Time.UTC().Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: dbCreateTime.Time.UTC().Unix()}, + StartTime: ×tamppb.Timestamp{Seconds: dbStartTime.Time.UTC().Unix()}, Duration: uint32(dbDuration), StartActive: uint32(startActive), } if endTime > 0 { - tournament.EndTime = ×tamp.Timestamp{Seconds: endTime} + tournament.EndTime = ×tamppb.Timestamp{Seconds: endTime} } return tournament, nil diff --git a/server/core_user.go b/server/core_user.go index 4fb3fffe42da299a1f82566069f812b4e08c15b0..b811c20bc6b26905e2948d0e3b3cce411eb16e24 100644 --- a/server/core_user.go +++ b/server/core_user.go @@ -17,11 +17,11 @@ package server import ( "context" "database/sql" + "google.golang.org/protobuf/types/known/timestamppb" "strconv" "strings" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/timestamp" "github.com/heroiclabs/nakama-common/api" "github.com/jackc/pgx/pgtype" "go.uber.org/zap" @@ -207,8 +207,8 @@ func convertUser(tracker Tracker, rows *sql.Rows) (*api.User, error) { GamecenterId: gamecenter.String, SteamId: steam.String, EdgeCount: int32(edgeCount), - CreateTime: ×tamp.Timestamp{Seconds: createTime.Time.Unix()}, - UpdateTime: ×tamp.Timestamp{Seconds: updateTime.Time.Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: createTime.Time.Unix()}, + UpdateTime: ×tamppb.Timestamp{Seconds: updateTime.Time.Unix()}, Online: tracker.StreamExists(PresenceStream{Mode: StreamModeStatus, Subject: userID}), }, nil } diff --git a/server/match_registry.go b/server/match_registry.go index cc6d7d2fa3854a2513ab96893621f48b475877de..e0aaa9b9bc2ca1cf064979f15a746ac6498e5fb0 100644 --- a/server/match_registry.go +++ b/server/match_registry.go @@ -21,6 +21,7 @@ import ( "encoding/json" "errors" "fmt" + "google.golang.org/protobuf/types/known/wrapperspb" "strings" "sync" "time" @@ -29,7 +30,6 @@ import ( "github.com/blevesearch/bleve/v2/analysis/analyzer/keyword" "github.com/blevesearch/bleve/v2/search/query" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/wrappers" "github.com/heroiclabs/nakama-common/api" "github.com/heroiclabs/nakama-common/rtapi" "github.com/heroiclabs/nakama-common/runtime" @@ -99,7 +99,7 @@ type MatchRegistry interface { UpdateMatchLabel(id uuid.UUID, tickRate int, handlerName, label string, createTime int64) error // List (and optionally filter) currently running matches. // This can list across both authoritative and relayed matches. - ListMatches(ctx context.Context, limit int, authoritative *wrappers.BoolValue, label *wrappers.StringValue, minSize *wrappers.Int32Value, maxSize *wrappers.Int32Value, query *wrappers.StringValue) ([]*api.Match, error) + ListMatches(ctx context.Context, limit int, authoritative *wrapperspb.BoolValue, label *wrapperspb.StringValue, minSize *wrapperspb.Int32Value, maxSize *wrapperspb.Int32Value, query *wrapperspb.StringValue) ([]*api.Match, error) // Stop the match registry and close all matches it's tracking. Stop(graceSeconds int) chan struct{} // Returns the total number of currently active authoritative matches. @@ -304,7 +304,7 @@ func (r *LocalMatchRegistry) GetMatch(ctx context.Context, id string) (*api.Matc return &api.Match{ MatchId: handler.IDStr, Authoritative: true, - Label: &wrappers.StringValue{Value: handler.Label()}, + Label: &wrapperspb.StringValue{Value: handler.Label()}, Size: int32(handler.PresenceList.Size()), TickRate: int32(handler.Rate), HandlerName: handler.Core.HandlerName(), @@ -360,7 +360,7 @@ func (r *LocalMatchRegistry) UpdateMatchLabel(id uuid.UUID, tickRate int, handle return nil } -func (r *LocalMatchRegistry) ListMatches(ctx context.Context, limit int, authoritative *wrappers.BoolValue, label *wrappers.StringValue, minSize *wrappers.Int32Value, maxSize *wrappers.Int32Value, queryString *wrappers.StringValue) ([]*api.Match, error) { +func (r *LocalMatchRegistry) ListMatches(ctx context.Context, limit int, authoritative *wrapperspb.BoolValue, label *wrapperspb.StringValue, minSize *wrapperspb.Int32Value, maxSize *wrapperspb.Int32Value, queryString *wrapperspb.StringValue) ([]*api.Match, error) { if limit == 0 { return make([]*api.Match, 0), nil } @@ -519,7 +519,7 @@ func (r *LocalMatchRegistry) ListMatches(ctx context.Context, limit int, authori results = append(results, &api.Match{ MatchId: hit.ID, Authoritative: true, - Label: &wrappers.StringValue{Value: labelString}, + Label: &wrapperspb.StringValue{Value: labelString}, Size: size, TickRate: int32(tickRate), HandlerName: handlerName, diff --git a/server/message_router.go b/server/message_router.go index d857be8a87b0c7668e9af98d2c7f553f45704bbe..055e4f11e0e079b700c15b65113d9b77e2f6ae17 100644 --- a/server/message_router.go +++ b/server/message_router.go @@ -15,11 +15,10 @@ package server import ( - "bytes" - "github.com/golang/protobuf/jsonpb" - "github.com/golang/protobuf/proto" "github.com/heroiclabs/nakama-common/rtapi" "go.uber.org/zap" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" ) // Deferred message expected to be batched with other deferred messages. @@ -38,16 +37,16 @@ type MessageRouter interface { } type LocalMessageRouter struct { - jsonpbMarshaler *jsonpb.Marshaler - sessionRegistry SessionRegistry - tracker Tracker + protojsonMarshaler *protojson.MarshalOptions + sessionRegistry SessionRegistry + tracker Tracker } -func NewLocalMessageRouter(sessionRegistry SessionRegistry, tracker Tracker, jsonpbMarshaler *jsonpb.Marshaler) MessageRouter { +func NewLocalMessageRouter(sessionRegistry SessionRegistry, tracker Tracker, protojsonMarshaler *protojson.MarshalOptions) MessageRouter { return &LocalMessageRouter{ - jsonpbMarshaler: jsonpbMarshaler, - sessionRegistry: sessionRegistry, - tracker: tracker, + protojsonMarshaler: protojsonMarshaler, + sessionRegistry: sessionRegistry, + tracker: tracker, } } @@ -84,9 +83,8 @@ func (r *LocalMessageRouter) SendToPresenceIDs(logger *zap.Logger, presenceIDs [ default: if payloadJSON == nil { // Marshal the payload now that we know this format is needed. - var buf bytes.Buffer - if err = r.jsonpbMarshaler.Marshal(&buf, envelope); err == nil { - payloadJSON = buf.Bytes() + if buf, err := r.protojsonMarshaler.Marshal(envelope); err == nil { + payloadJSON = buf } else { logger.Error("Could not marshal message", zap.Error(err)) return diff --git a/server/pipeline.go b/server/pipeline.go index 89fb03bedf7d660024d8aa2df54601e1d804c4d1..79ee8b8fc7d4add82551166550cc8f2dcdea9d38 100644 --- a/server/pipeline.go +++ b/server/pipeline.go @@ -20,44 +20,44 @@ import ( "strings" - "github.com/golang/protobuf/jsonpb" "github.com/heroiclabs/nakama-common/rtapi" "go.uber.org/zap" + "google.golang.org/protobuf/encoding/protojson" ) type Pipeline struct { - logger *zap.Logger - config Config - db *sql.DB - jsonpbMarshaler *jsonpb.Marshaler - jsonpbUnmarshaler *jsonpb.Unmarshaler - sessionRegistry SessionRegistry - statusRegistry *StatusRegistry - matchRegistry MatchRegistry - partyRegistry PartyRegistry - matchmaker Matchmaker - tracker Tracker - router MessageRouter - runtime *Runtime - node string + logger *zap.Logger + config Config + db *sql.DB + protojsonMarshaler *protojson.MarshalOptions + protojsonUnmarshaler *protojson.UnmarshalOptions + sessionRegistry SessionRegistry + statusRegistry *StatusRegistry + matchRegistry MatchRegistry + partyRegistry PartyRegistry + matchmaker Matchmaker + tracker Tracker + router MessageRouter + runtime *Runtime + node string } -func NewPipeline(logger *zap.Logger, config Config, db *sql.DB, jsonpbMarshaler *jsonpb.Marshaler, jsonpbUnmarshaler *jsonpb.Unmarshaler, sessionRegistry SessionRegistry, statusRegistry *StatusRegistry, matchRegistry MatchRegistry, partyRegistry PartyRegistry, matchmaker Matchmaker, tracker Tracker, router MessageRouter, runtime *Runtime) *Pipeline { +func NewPipeline(logger *zap.Logger, config Config, db *sql.DB, protojsonMarshaler *protojson.MarshalOptions, protojsonUnmarshaler *protojson.UnmarshalOptions, sessionRegistry SessionRegistry, statusRegistry *StatusRegistry, matchRegistry MatchRegistry, partyRegistry PartyRegistry, matchmaker Matchmaker, tracker Tracker, router MessageRouter, runtime *Runtime) *Pipeline { return &Pipeline{ - logger: logger, - config: config, - db: db, - jsonpbMarshaler: jsonpbMarshaler, - jsonpbUnmarshaler: jsonpbUnmarshaler, - sessionRegistry: sessionRegistry, - statusRegistry: statusRegistry, - matchRegistry: matchRegistry, - partyRegistry: partyRegistry, - matchmaker: matchmaker, - tracker: tracker, - router: router, - runtime: runtime, - node: config.GetName(), + logger: logger, + config: config, + db: db, + protojsonMarshaler: protojsonMarshaler, + protojsonUnmarshaler: protojsonUnmarshaler, + sessionRegistry: sessionRegistry, + statusRegistry: statusRegistry, + matchRegistry: matchRegistry, + partyRegistry: partyRegistry, + matchmaker: matchmaker, + tracker: tracker, + router: router, + runtime: runtime, + node: config.GetName(), } } diff --git a/server/pipeline_channel.go b/server/pipeline_channel.go index f37153306d745abe6320d5a6839fcdd7ee36115e..500f0622164fb1be19492aab07711db5254763c3 100644 --- a/server/pipeline_channel.go +++ b/server/pipeline_channel.go @@ -20,13 +20,13 @@ import ( "encoding/json" "errors" "fmt" + "google.golang.org/protobuf/types/known/timestamppb" + "google.golang.org/protobuf/types/known/wrapperspb" "regexp" "time" "unicode/utf8" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/timestamp" - "github.com/golang/protobuf/ptypes/wrappers" "github.com/heroiclabs/nakama-common/api" "github.com/heroiclabs/nakama-common/rtapi" "github.com/jackc/pgx/pgtype" @@ -241,7 +241,7 @@ func (p *Pipeline) channelJoin(logger *zap.Logger, session Session, envelope *rt SenderId: userID.String(), Code: NotificationCodeDmRequest, Persistent: true, - CreateTime: ×tamp.Timestamp{Seconds: time.Now().UTC().Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: time.Now().UTC().Unix()}, }, }, } @@ -340,13 +340,13 @@ func (p *Pipeline) channelMessageSend(logger *zap.Logger, session Session, envel message := &api.ChannelMessage{ ChannelId: incoming.ChannelId, MessageId: uuid.Must(uuid.NewV4()).String(), - Code: &wrappers.Int32Value{Value: ChannelMessageTypeChat}, + Code: &wrapperspb.Int32Value{Value: ChannelMessageTypeChat}, SenderId: session.UserID().String(), Username: session.Username(), Content: incoming.Content, - CreateTime: ×tamp.Timestamp{Seconds: ts}, - UpdateTime: ×tamp.Timestamp{Seconds: ts}, - Persistent: &wrappers.BoolValue{Value: meta.Persistence}, + CreateTime: ×tamppb.Timestamp{Seconds: ts}, + UpdateTime: ×tamppb.Timestamp{Seconds: ts}, + Persistent: &wrapperspb.BoolValue{Value: meta.Persistence}, } switch streamConversionResult.Stream.Mode { case StreamModeChannel: @@ -437,13 +437,13 @@ func (p *Pipeline) channelMessageUpdate(logger *zap.Logger, session Session, env message := &api.ChannelMessage{ ChannelId: incoming.ChannelId, MessageId: incoming.MessageId, - Code: &wrappers.Int32Value{Value: ChannelMessageTypeChatUpdate}, + Code: &wrapperspb.Int32Value{Value: ChannelMessageTypeChatUpdate}, SenderId: session.UserID().String(), Username: session.Username(), Content: incoming.Content, - CreateTime: ×tamp.Timestamp{Seconds: ts}, - UpdateTime: ×tamp.Timestamp{Seconds: ts}, - Persistent: &wrappers.BoolValue{Value: meta.Persistence}, + CreateTime: ×tamppb.Timestamp{Seconds: ts}, + UpdateTime: ×tamppb.Timestamp{Seconds: ts}, + Persistent: &wrapperspb.BoolValue{Value: meta.Persistence}, } switch streamConversionResult.Stream.Mode { case StreamModeChannel: @@ -476,7 +476,7 @@ func (p *Pipeline) channelMessageUpdate(logger *zap.Logger, session Session, env return } // Replace the message create time with the real one from DB. - message.CreateTime = ×tamp.Timestamp{Seconds: dbCreateTime.Time.Unix()} + message.CreateTime = ×tamppb.Timestamp{Seconds: dbCreateTime.Time.Unix()} } ack := &rtapi.ChannelMessageAck{ @@ -536,13 +536,13 @@ func (p *Pipeline) channelMessageRemove(logger *zap.Logger, session Session, env message := &api.ChannelMessage{ ChannelId: incoming.ChannelId, MessageId: incoming.MessageId, - Code: &wrappers.Int32Value{Value: ChannelMessageTypeChatRemove}, + Code: &wrapperspb.Int32Value{Value: ChannelMessageTypeChatRemove}, SenderId: session.UserID().String(), Username: session.Username(), Content: "{}", - CreateTime: ×tamp.Timestamp{Seconds: ts}, - UpdateTime: ×tamp.Timestamp{Seconds: ts}, - Persistent: &wrappers.BoolValue{Value: meta.Persistence}, + CreateTime: ×tamppb.Timestamp{Seconds: ts}, + UpdateTime: ×tamppb.Timestamp{Seconds: ts}, + Persistent: &wrapperspb.BoolValue{Value: meta.Persistence}, } switch streamConversionResult.Stream.Mode { case StreamModeChannel: @@ -575,7 +575,7 @@ func (p *Pipeline) channelMessageRemove(logger *zap.Logger, session Session, env return } // Replace the message create time with the real one from DB. - message.CreateTime = ×tamp.Timestamp{Seconds: dbCreateTime.Time.Unix()} + message.CreateTime = ×tamppb.Timestamp{Seconds: dbCreateTime.Time.Unix()} } ack := &rtapi.ChannelMessageAck{ diff --git a/server/pipeline_match.go b/server/pipeline_match.go index e49bf0eea50dad15ea6840de8f2e2714ad209859..4f66f478d9c9e9c421dc86490ca2503a4e6ff3bc 100644 --- a/server/pipeline_match.go +++ b/server/pipeline_match.go @@ -17,12 +17,12 @@ package server import ( "crypto" "fmt" + "google.golang.org/protobuf/types/known/wrapperspb" "strings" "time" "github.com/dgrijalva/jwt-go" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/wrappers" "github.com/heroiclabs/nakama-common/rtapi" "go.uber.org/zap" ) @@ -145,7 +145,7 @@ func (p *Pipeline) matchJoin(logger *zap.Logger, session Session, envelope *rtap } var mode uint8 - var label *wrappers.StringValue + var label *wrapperspb.StringValue var presences []*rtapi.UserPresence username := session.Username() if node == "" { @@ -223,7 +223,7 @@ func (p *Pipeline) matchJoin(logger *zap.Logger, session Session, envelope *rtap p.tracker.Track(session.Context(), session.ID(), stream, session.UserID(), m, false) } - label = &wrappers.StringValue{Value: l} + label = &wrapperspb.StringValue{Value: l} presences = make([]*rtapi.UserPresence, 0, len(ps)) for _, p := range ps { if isNew && p.UserID == session.UserID() && p.SessionID == session.ID() { diff --git a/server/pipeline_status.go b/server/pipeline_status.go index 76f99b53af449ce6df71be7c8a9f9a5f15ff90a9..13e0f4042aad21650edeafec2ff1ff586493104e 100644 --- a/server/pipeline_status.go +++ b/server/pipeline_status.go @@ -15,11 +15,11 @@ package server import ( + "google.golang.org/protobuf/types/known/wrapperspb" "strconv" "strings" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/wrappers" "github.com/heroiclabs/nakama-common/rtapi" "go.uber.org/zap" ) @@ -205,7 +205,7 @@ func (p *Pipeline) statusFollow(logger *zap.Logger, session Session, envelope *r UserId: p.UserID.String(), SessionId: p.ID.SessionID.String(), Username: p.Meta.Username, - Status: &wrappers.StringValue{Value: p.Meta.Status}, + Status: &wrapperspb.StringValue{Value: p.Meta.Status}, }) } } diff --git a/server/runtime.go b/server/runtime.go index fa14b49267822c63033387823e94112f5b67f9d9..8179af0e9b00077a650771c6ce4af577b679a671 100644 --- a/server/runtime.go +++ b/server/runtime.go @@ -29,12 +29,12 @@ import ( "github.com/heroiclabs/nakama-common/runtime" "github.com/gofrs/uuid" - "github.com/golang/protobuf/jsonpb" "github.com/heroiclabs/nakama-common/api" "github.com/heroiclabs/nakama-common/rtapi" "github.com/heroiclabs/nakama/v3/social" "go.uber.org/zap" "google.golang.org/grpc/codes" + "google.golang.org/protobuf/encoding/protojson" ) var ( @@ -563,7 +563,7 @@ func CheckRuntime(logger *zap.Logger, config Config) error { return nil } -func NewRuntime(logger, startupLogger *zap.Logger, db *sql.DB, jsonpbMarshaler *jsonpb.Marshaler, jsonpbUnmarshaler *jsonpb.Unmarshaler, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, leaderboardRankCache LeaderboardRankCache, leaderboardScheduler LeaderboardScheduler, sessionRegistry SessionRegistry, sessionCache SessionCache, matchRegistry MatchRegistry, tracker Tracker, metrics *Metrics, streamManager StreamManager, router MessageRouter) (*Runtime, *RuntimeInfo, error) { +func NewRuntime(logger, startupLogger *zap.Logger, db *sql.DB, protojsonMarshaler *protojson.MarshalOptions, protojsonUnmarshaler *protojson.UnmarshalOptions, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, leaderboardRankCache LeaderboardRankCache, leaderboardScheduler LeaderboardScheduler, sessionRegistry SessionRegistry, sessionCache SessionCache, matchRegistry MatchRegistry, tracker Tracker, metrics *Metrics, streamManager StreamManager, router MessageRouter) (*Runtime, *RuntimeInfo, error) { runtimeConfig := config.GetRuntime() startupLogger.Info("Initialising runtime", zap.String("path", runtimeConfig.Path)) @@ -578,19 +578,19 @@ func NewRuntime(logger, startupLogger *zap.Logger, db *sql.DB, jsonpbMarshaler * matchProvider := NewMatchProvider() - goModules, goRPCFunctions, goBeforeRtFunctions, goAfterRtFunctions, goBeforeReqFunctions, goAfterReqFunctions, goMatchmakerMatchedFunction, goTournamentEndFunction, goTournamentResetFunction, goLeaderboardResetFunction, allEventFunctions, goMatchNamesListFn, err := NewRuntimeProviderGo(logger, startupLogger, db, jsonpbMarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, streamManager, router, runtimeConfig.Path, paths, eventQueue, matchProvider) + goModules, goRPCFunctions, goBeforeRtFunctions, goAfterRtFunctions, goBeforeReqFunctions, goAfterReqFunctions, goMatchmakerMatchedFunction, goTournamentEndFunction, goTournamentResetFunction, goLeaderboardResetFunction, allEventFunctions, goMatchNamesListFn, err := NewRuntimeProviderGo(logger, startupLogger, db, protojsonMarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, streamManager, router, runtimeConfig.Path, paths, eventQueue, matchProvider) if err != nil { startupLogger.Error("Error initialising Go runtime provider", zap.Error(err)) return nil, nil, err } - luaModules, luaRPCFunctions, luaBeforeRtFunctions, luaAfterRtFunctions, luaBeforeReqFunctions, luaAfterReqFunctions, luaMatchmakerMatchedFunction, luaTournamentEndFunction, luaTournamentResetFunction, luaLeaderboardResetFunction, err := NewRuntimeProviderLua(logger, startupLogger, db, jsonpbMarshaler, jsonpbUnmarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, metrics, streamManager, router, allEventFunctions.eventFunction, runtimeConfig.Path, paths, matchProvider) + luaModules, luaRPCFunctions, luaBeforeRtFunctions, luaAfterRtFunctions, luaBeforeReqFunctions, luaAfterReqFunctions, luaMatchmakerMatchedFunction, luaTournamentEndFunction, luaTournamentResetFunction, luaLeaderboardResetFunction, err := NewRuntimeProviderLua(logger, startupLogger, db, protojsonMarshaler, protojsonUnmarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, metrics, streamManager, router, allEventFunctions.eventFunction, runtimeConfig.Path, paths, matchProvider) if err != nil { startupLogger.Error("Error initialising Lua runtime provider", zap.Error(err)) return nil, nil, err } - jsModules, jsRPCFunctions, jsBeforeRtFunctions, jsAfterRtFunctions, jsBeforeReqFunctions, jsAfterReqFunctions, jsMatchmakerMatchedFunction, jsTournamentEndFunction, jsTournamentResetFunction, jsLeaderboardResetFunction, err := NewRuntimeProviderJS(logger, startupLogger, db, jsonpbMarshaler, jsonpbUnmarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, metrics, streamManager, router, allEventFunctions.eventFunction, runtimeConfig.Path, runtimeConfig.JsEntrypoint, matchProvider) + jsModules, jsRPCFunctions, jsBeforeRtFunctions, jsAfterRtFunctions, jsBeforeReqFunctions, jsAfterReqFunctions, jsMatchmakerMatchedFunction, jsTournamentEndFunction, jsTournamentResetFunction, jsLeaderboardResetFunction, err := NewRuntimeProviderJS(logger, startupLogger, db, protojsonMarshaler, protojsonUnmarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, metrics, streamManager, router, allEventFunctions.eventFunction, runtimeConfig.Path, runtimeConfig.JsEntrypoint, matchProvider) if err != nil { startupLogger.Error("Error initialising JavaScript runtime provider", zap.Error(err)) return nil, nil, err diff --git a/server/runtime_go.go b/server/runtime_go.go index f9b59207ab7d3bc49e4b0b45c48277225f988cf4..2da157f05fce77b94b90752cbd0f748f7d63b91c 100644 --- a/server/runtime_go.go +++ b/server/runtime_go.go @@ -18,15 +18,15 @@ import ( "context" "database/sql" "errors" - "github.com/golang/protobuf/jsonpb" "go.uber.org/atomic" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/types/known/timestamppb" "path/filepath" "plugin" "strings" "sync" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/timestamp" "github.com/heroiclabs/nakama-common/api" "github.com/heroiclabs/nakama-common/rtapi" "github.com/heroiclabs/nakama-common/runtime" @@ -2179,11 +2179,11 @@ func (ri *RuntimeGoInitializer) RegisterMatch(name string, fn func(ctx context.C return nil } -func NewRuntimeProviderGo(logger, startupLogger *zap.Logger, db *sql.DB, jsonpbMarshaler *jsonpb.Marshaler, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, leaderboardRankCache LeaderboardRankCache, leaderboardScheduler LeaderboardScheduler, sessionRegistry SessionRegistry, sessionCache SessionCache, matchRegistry MatchRegistry, tracker Tracker, streamManager StreamManager, router MessageRouter, rootPath string, paths []string, eventQueue *RuntimeEventQueue, matchProvider *MatchProvider) ([]string, map[string]RuntimeRpcFunction, map[string]RuntimeBeforeRtFunction, map[string]RuntimeAfterRtFunction, *RuntimeBeforeReqFunctions, *RuntimeAfterReqFunctions, RuntimeMatchmakerMatchedFunction, RuntimeTournamentEndFunction, RuntimeTournamentResetFunction, RuntimeLeaderboardResetFunction, *RuntimeEventFunctions, func() []string, error) { +func NewRuntimeProviderGo(logger, startupLogger *zap.Logger, db *sql.DB, protojsonMarshaler *protojson.MarshalOptions, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, leaderboardRankCache LeaderboardRankCache, leaderboardScheduler LeaderboardScheduler, sessionRegistry SessionRegistry, sessionCache SessionCache, matchRegistry MatchRegistry, tracker Tracker, streamManager StreamManager, router MessageRouter, rootPath string, paths []string, eventQueue *RuntimeEventQueue, matchProvider *MatchProvider) ([]string, map[string]RuntimeRpcFunction, map[string]RuntimeBeforeRtFunction, map[string]RuntimeAfterRtFunction, *RuntimeBeforeReqFunctions, *RuntimeAfterReqFunctions, RuntimeMatchmakerMatchedFunction, RuntimeTournamentEndFunction, RuntimeTournamentResetFunction, RuntimeLeaderboardResetFunction, *RuntimeEventFunctions, func() []string, error) { runtimeLogger := NewRuntimeGoLogger(logger) node := config.GetName() env := config.GetRuntime().Environment - nk := NewRuntimeGoNakamaModule(logger, db, jsonpbMarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, streamManager, router) + nk := NewRuntimeGoNakamaModule(logger, db, protojsonMarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, streamManager, router) match := make(map[string]func(ctx context.Context, logger runtime.Logger, db *sql.DB, nk runtime.NakamaModule) (runtime.Match, error), 0) @@ -2287,7 +2287,7 @@ func NewRuntimeProviderGo(logger, startupLogger *zap.Logger, db *sql.DB, jsonpbM ctx := NewRuntimeGoContext(context.Background(), initializer.node, initializer.env, RuntimeExecutionModeEvent, nil, expiry, userID, username, vars, sessionID, clientIP, clientPort) evt := &api.Event{ Name: "session_start", - Timestamp: ×tamp.Timestamp{Seconds: evtTimeSec}, + Timestamp: ×tamppb.Timestamp{Seconds: evtTimeSec}, } eventQueue.Queue(func() { for _, fn := range initializer.sessionStartFunctions { @@ -2302,7 +2302,7 @@ func NewRuntimeProviderGo(logger, startupLogger *zap.Logger, db *sql.DB, jsonpbM evt := &api.Event{ Name: "session_end", Properties: map[string]string{"reason": reason}, - Timestamp: ×tamp.Timestamp{Seconds: evtTimeSec}, + Timestamp: ×tamppb.Timestamp{Seconds: evtTimeSec}, } eventQueue.Queue(func() { for _, fn := range initializer.sessionEndFunctions { diff --git a/server/runtime_go_nakama.go b/server/runtime_go_nakama.go index 173faa51501d08e124656291ffbcf25844a5e431..6e1bc355e02213b997d73d7138c3d5ab235b8d59 100644 --- a/server/runtime_go_nakama.go +++ b/server/runtime_go_nakama.go @@ -23,28 +23,28 @@ import ( "encoding/json" "errors" "fmt" + "google.golang.org/protobuf/types/known/timestamppb" + "google.golang.org/protobuf/types/known/wrapperspb" "os" "strings" "sync" "time" "github.com/gofrs/uuid" - "github.com/golang/protobuf/jsonpb" - "github.com/golang/protobuf/ptypes/timestamp" - "github.com/golang/protobuf/ptypes/wrappers" "github.com/heroiclabs/nakama-common/api" "github.com/heroiclabs/nakama-common/rtapi" "github.com/heroiclabs/nakama-common/runtime" "github.com/heroiclabs/nakama/v3/internal/cronexpr" "github.com/heroiclabs/nakama/v3/social" "go.uber.org/zap" + "google.golang.org/protobuf/encoding/protojson" ) type RuntimeGoNakamaModule struct { sync.RWMutex logger *zap.Logger db *sql.DB - jsonpbMarshaler *jsonpb.Marshaler + protojsonMarshaler *protojson.MarshalOptions config Config socialClient *social.Client leaderboardCache LeaderboardCache @@ -64,11 +64,11 @@ type RuntimeGoNakamaModule struct { matchCreateFn RuntimeMatchCreateFunction } -func NewRuntimeGoNakamaModule(logger *zap.Logger, db *sql.DB, jsonpbMarshaler *jsonpb.Marshaler, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, leaderboardRankCache LeaderboardRankCache, leaderboardScheduler LeaderboardScheduler, sessionRegistry SessionRegistry, sessionCache SessionCache, matchRegistry MatchRegistry, tracker Tracker, streamManager StreamManager, router MessageRouter) *RuntimeGoNakamaModule { +func NewRuntimeGoNakamaModule(logger *zap.Logger, db *sql.DB, protojsonMarshaler *protojson.MarshalOptions, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, leaderboardRankCache LeaderboardRankCache, leaderboardScheduler LeaderboardScheduler, sessionRegistry SessionRegistry, sessionCache SessionCache, matchRegistry MatchRegistry, tracker Tracker, streamManager StreamManager, router MessageRouter) *RuntimeGoNakamaModule { return &RuntimeGoNakamaModule{ logger: logger, db: db, - jsonpbMarshaler: jsonpbMarshaler, + protojsonMarshaler: protojsonMarshaler, config: config, socialClient: socialClient, leaderboardCache: leaderboardCache, @@ -349,34 +349,34 @@ func (n *RuntimeGoNakamaModule) AccountUpdateId(ctx context.Context, userID, use return errors.New("expects user ID to be a valid identifier") } - var metadataWrapper *wrappers.StringValue + var metadataWrapper *wrapperspb.StringValue if metadata != nil { metadataBytes, err := json.Marshal(metadata) if err != nil { return fmt.Errorf("error encoding metadata: %v", err.Error()) } - metadataWrapper = &wrappers.StringValue{Value: string(metadataBytes)} + metadataWrapper = &wrapperspb.StringValue{Value: string(metadataBytes)} } - var displayNameWrapper *wrappers.StringValue + var displayNameWrapper *wrapperspb.StringValue if displayName != "" { - displayNameWrapper = &wrappers.StringValue{Value: displayName} + displayNameWrapper = &wrapperspb.StringValue{Value: displayName} } - var timezoneWrapper *wrappers.StringValue + var timezoneWrapper *wrapperspb.StringValue if timezone != "" { - timezoneWrapper = &wrappers.StringValue{Value: timezone} + timezoneWrapper = &wrapperspb.StringValue{Value: timezone} } - var locationWrapper *wrappers.StringValue + var locationWrapper *wrapperspb.StringValue if location != "" { - locationWrapper = &wrappers.StringValue{Value: location} + locationWrapper = &wrapperspb.StringValue{Value: location} } - var langWrapper *wrappers.StringValue + var langWrapper *wrapperspb.StringValue if langTag != "" { - langWrapper = &wrappers.StringValue{Value: langTag} + langWrapper = &wrapperspb.StringValue{Value: langTag} } - var avatarWrapper *wrappers.StringValue + var avatarWrapper *wrapperspb.StringValue if avatarUrl != "" { - avatarWrapper = &wrappers.StringValue{Value: avatarUrl} + avatarWrapper = &wrapperspb.StringValue{Value: avatarUrl} } return UpdateAccounts(ctx, n.logger, n.db, []*accountUpdate{{ @@ -411,12 +411,12 @@ func (n *RuntimeGoNakamaModule) AccountExportId(ctx context.Context, userID stri return "", fmt.Errorf("error exporting account: %v", err.Error()) } - exportString, err := n.jsonpbMarshaler.MarshalToString(export) + exportBytes, err := n.protojsonMarshaler.Marshal(export) if err != nil { return "", fmt.Errorf("error encoding account export: %v", err.Error()) } - return exportString, nil + return string(exportBytes), nil } func (n *RuntimeGoNakamaModule) UsersGetId(ctx context.Context, userIDs []string, facebookIDs []string) ([]*api.User, error) { @@ -1059,22 +1059,22 @@ func (n *RuntimeGoNakamaModule) MatchGet(ctx context.Context, id string) (*api.M } func (n *RuntimeGoNakamaModule) MatchList(ctx context.Context, limit int, authoritative bool, label string, minSize, maxSize *int, query string) ([]*api.Match, error) { - authoritativeWrapper := &wrappers.BoolValue{Value: authoritative} - var labelWrapper *wrappers.StringValue + authoritativeWrapper := &wrapperspb.BoolValue{Value: authoritative} + var labelWrapper *wrapperspb.StringValue if label != "" { - labelWrapper = &wrappers.StringValue{Value: label} + labelWrapper = &wrapperspb.StringValue{Value: label} } - var queryWrapper *wrappers.StringValue + var queryWrapper *wrapperspb.StringValue if query != "" { - queryWrapper = &wrappers.StringValue{Value: query} + queryWrapper = &wrapperspb.StringValue{Value: query} } - var minSizeWrapper *wrappers.Int32Value + var minSizeWrapper *wrapperspb.Int32Value if minSize != nil { - minSizeWrapper = &wrappers.Int32Value{Value: int32(*minSize)} + minSizeWrapper = &wrapperspb.Int32Value{Value: int32(*minSize)} } - var maxSizeWrapper *wrappers.Int32Value + var maxSizeWrapper *wrapperspb.Int32Value if maxSize != nil { - maxSizeWrapper = &wrappers.Int32Value{Value: int32(*maxSize)} + maxSizeWrapper = &wrapperspb.Int32Value{Value: int32(*maxSize)} } return n.matchRegistry.ListMatches(ctx, limit, authoritativeWrapper, labelWrapper, minSizeWrapper, maxSizeWrapper, queryWrapper) @@ -1116,7 +1116,7 @@ func (n *RuntimeGoNakamaModule) NotificationSend(ctx context.Context, userID, su Code: int32(code), SenderId: senderID, Persistent: persistent, - CreateTime: ×tamp.Timestamp{Seconds: time.Now().UTC().Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: time.Now().UTC().Unix()}, }} notifications := map[uuid.UUID][]*api.Notification{ uid: nots, @@ -1168,7 +1168,7 @@ func (n *RuntimeGoNakamaModule) NotificationsSend(ctx context.Context, notificat Code: int32(notification.Code), SenderId: senderID, Persistent: notification.Persistent, - CreateTime: ×tamp.Timestamp{Seconds: time.Now().UTC().Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: time.Now().UTC().Unix()}, }) ns[uid] = no } @@ -1359,8 +1359,8 @@ func (n *RuntimeGoNakamaModule) StorageWrite(ctx context.Context, writes []*runt Key: write.Key, Value: write.Value, Version: write.Version, - PermissionRead: &wrappers.Int32Value{Value: int32(write.PermissionRead)}, - PermissionWrite: &wrappers.Int32Value{Value: int32(write.PermissionWrite)}, + PermissionRead: &wrapperspb.Int32Value{Value: int32(write.PermissionRead)}, + PermissionWrite: &wrapperspb.Int32Value{Value: int32(write.PermissionWrite)}, }, } if write.UserID == "" { @@ -1431,34 +1431,34 @@ func (n *RuntimeGoNakamaModule) MultiUpdate(ctx context.Context, accountUpdates return nil, nil, errors.New("expects user ID to be a valid identifier") } - var metadataWrapper *wrappers.StringValue + var metadataWrapper *wrapperspb.StringValue if update.Metadata != nil { metadataBytes, err := json.Marshal(update.Metadata) if err != nil { return nil, nil, fmt.Errorf("error encoding metadata: %v", err.Error()) } - metadataWrapper = &wrappers.StringValue{Value: string(metadataBytes)} + metadataWrapper = &wrapperspb.StringValue{Value: string(metadataBytes)} } - var displayNameWrapper *wrappers.StringValue + var displayNameWrapper *wrapperspb.StringValue if update.DisplayName != "" { - displayNameWrapper = &wrappers.StringValue{Value: update.DisplayName} + displayNameWrapper = &wrapperspb.StringValue{Value: update.DisplayName} } - var timezoneWrapper *wrappers.StringValue + var timezoneWrapper *wrapperspb.StringValue if update.Timezone != "" { - timezoneWrapper = &wrappers.StringValue{Value: update.Timezone} + timezoneWrapper = &wrapperspb.StringValue{Value: update.Timezone} } - var locationWrapper *wrappers.StringValue + var locationWrapper *wrapperspb.StringValue if update.Location != "" { - locationWrapper = &wrappers.StringValue{Value: update.Location} + locationWrapper = &wrapperspb.StringValue{Value: update.Location} } - var langWrapper *wrappers.StringValue + var langWrapper *wrapperspb.StringValue if update.LangTag != "" { - langWrapper = &wrappers.StringValue{Value: update.LangTag} + langWrapper = &wrapperspb.StringValue{Value: update.LangTag} } - var avatarWrapper *wrappers.StringValue + var avatarWrapper *wrapperspb.StringValue if update.AvatarUrl != "" { - avatarWrapper = &wrappers.StringValue{Value: update.AvatarUrl} + avatarWrapper = &wrapperspb.StringValue{Value: update.AvatarUrl} } accountUpdateOps = append(accountUpdateOps, &accountUpdate{ @@ -1497,8 +1497,8 @@ func (n *RuntimeGoNakamaModule) MultiUpdate(ctx context.Context, accountUpdates Key: write.Key, Value: write.Value, Version: write.Version, - PermissionRead: &wrappers.Int32Value{Value: int32(write.PermissionRead)}, - PermissionWrite: &wrappers.Int32Value{Value: int32(write.PermissionWrite)}, + PermissionRead: &wrapperspb.Int32Value{Value: int32(write.PermissionRead)}, + PermissionWrite: &wrapperspb.Int32Value{Value: int32(write.PermissionWrite)}, }, } if write.UserID == "" { @@ -1607,11 +1607,11 @@ func (n *RuntimeGoNakamaModule) LeaderboardRecordsList(ctx context.Context, id s } } - var limitWrapper *wrappers.Int32Value + var limitWrapper *wrapperspb.Int32Value if limit < 0 || limit > 10000 { return nil, nil, "", "", errors.New("expects limit to be 0-10000") } - limitWrapper = &wrappers.Int32Value{Value: int32(limit)} + limitWrapper = &wrapperspb.Int32Value{Value: int32(limit)} if expiry < 0 { return nil, nil, "", "", errors.New("expects expiry to equal or greater than 0") @@ -1831,11 +1831,11 @@ func (n *RuntimeGoNakamaModule) TournamentRecordsList(ctx context.Context, tourn return nil, nil, "", "", errors.New("One or more ownerIDs are invalid.") } } - var limitWrapper *wrappers.Int32Value + var limitWrapper *wrapperspb.Int32Value if limit < 0 || limit > 10000 { return nil, nil, "", "", errors.New("expects limit to be 0-10000") } - limitWrapper = &wrappers.Int32Value{Value: int32(limit)} + limitWrapper = &wrapperspb.Int32Value{Value: int32(limit)} if overrideExpiry < 0 { return nil, nil, "", "", errors.New("expects expiry to equal or greater than 0") @@ -2042,9 +2042,9 @@ func (n *RuntimeGoNakamaModule) GroupUpdate(ctx context.Context, id, name, creat return errors.New("expects group ID to be a valid identifier") } - var nameWrapper *wrappers.StringValue + var nameWrapper *wrapperspb.StringValue if name != "" { - nameWrapper = &wrappers.StringValue{Value: name} + nameWrapper = &wrapperspb.StringValue{Value: name} } creator := uuid.Nil @@ -2056,30 +2056,30 @@ func (n *RuntimeGoNakamaModule) GroupUpdate(ctx context.Context, id, name, creat } } - var langTagWrapper *wrappers.StringValue + var langTagWrapper *wrapperspb.StringValue if langTag != "" { - langTagWrapper = &wrappers.StringValue{Value: langTag} + langTagWrapper = &wrapperspb.StringValue{Value: langTag} } - var descriptionWrapper *wrappers.StringValue + var descriptionWrapper *wrapperspb.StringValue if description != "" { - descriptionWrapper = &wrappers.StringValue{Value: description} + descriptionWrapper = &wrapperspb.StringValue{Value: description} } - var avatarURLWrapper *wrappers.StringValue + var avatarURLWrapper *wrapperspb.StringValue if avatarUrl != "" { - avatarURLWrapper = &wrappers.StringValue{Value: avatarUrl} + avatarURLWrapper = &wrapperspb.StringValue{Value: avatarUrl} } - openWrapper := &wrappers.BoolValue{Value: open} + openWrapper := &wrapperspb.BoolValue{Value: open} - var metadataWrapper *wrappers.StringValue + var metadataWrapper *wrapperspb.StringValue if metadata != nil { metadataBytes, err := json.Marshal(metadata) if err != nil { return fmt.Errorf("error encoding metadata: %v", err.Error()) } - metadataWrapper = &wrappers.StringValue{Value: string(metadataBytes)} + metadataWrapper = &wrapperspb.StringValue{Value: string(metadataBytes)} } maxCountValue := 0 @@ -2245,13 +2245,13 @@ func (n *RuntimeGoNakamaModule) GroupUsersList(ctx context.Context, id string, l return nil, "", errors.New("expects limit to be 1-100") } - var stateWrapper *wrappers.Int32Value + var stateWrapper *wrapperspb.Int32Value if state != nil { stateValue := *state if stateValue < 0 || stateValue > 4 { return nil, "", errors.New("expects state to be 0-4") } - stateWrapper = &wrappers.Int32Value{Value: int32(stateValue)} + stateWrapper = &wrapperspb.Int32Value{Value: int32(stateValue)} } users, err := ListGroupUsers(ctx, n.logger, n.db, n.tracker, groupID, limit, stateWrapper, cursor) @@ -2272,13 +2272,13 @@ func (n *RuntimeGoNakamaModule) UserGroupsList(ctx context.Context, userID strin return nil, "", errors.New("expects limit to be 1-100") } - var stateWrapper *wrappers.Int32Value + var stateWrapper *wrapperspb.Int32Value if state != nil { stateValue := *state if stateValue < 0 || stateValue > 4 { return nil, "", errors.New("expects state to be 0-4") } - stateWrapper = &wrappers.Int32Value{Value: int32(stateValue)} + stateWrapper = &wrapperspb.Int32Value{Value: int32(stateValue)} } groups, err := ListUserGroups(ctx, n.logger, n.db, uid, limit, stateWrapper, cursor) @@ -2317,13 +2317,13 @@ func (n *RuntimeGoNakamaModule) FriendsList(ctx context.Context, userID string, return nil, "", errors.New("expects limit to be 1-100") } - var stateWrapper *wrappers.Int32Value + var stateWrapper *wrapperspb.Int32Value if state != nil { stateValue := *state if stateValue < 0 || stateValue > 3 { return nil, "", errors.New("expects state to be 0-3") } - stateWrapper = &wrappers.Int32Value{Value: int32(stateValue)} + stateWrapper = &wrapperspb.Int32Value{Value: int32(stateValue)} } friends, err := ListFriends(ctx, n.logger, n.db, n.tracker, uid, limit, stateWrapper, cursor) diff --git a/server/runtime_javascript.go b/server/runtime_javascript.go index 46d92d0504ab2b066fdb05f4e0cc3bbe8e03f7b0..46727bc168c82c2f182132b4788d1d15925599cc 100644 --- a/server/runtime_javascript.go +++ b/server/runtime_javascript.go @@ -23,8 +23,6 @@ import ( "github.com/dop251/goja" "github.com/dop251/goja/ast" "github.com/gofrs/uuid" - "github.com/golang/protobuf/jsonpb" - "github.com/golang/protobuf/proto" "github.com/heroiclabs/nakama-common/api" "github.com/heroiclabs/nakama-common/rtapi" "github.com/heroiclabs/nakama-common/runtime" @@ -32,6 +30,8 @@ import ( "go.uber.org/atomic" "go.uber.org/zap" "google.golang.org/grpc/codes" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" "io/ioutil" "os" "path/filepath" @@ -138,8 +138,8 @@ func (mc *RuntimeJSModuleCache) Add(m *RuntimeJSModule) { type RuntimeProviderJS struct { logger *zap.Logger db *sql.DB - jsonpbMarshaler *jsonpb.Marshaler - jsonpbUnmarshaler *jsonpb.Unmarshaler + protojsonMarshaler *protojson.MarshalOptions + protojsonUnmarshaler *protojson.UnmarshalOptions config Config socialClient *social.Client leaderboardCache LeaderboardCache @@ -207,14 +207,14 @@ func (rp *RuntimeProviderJS) BeforeRt(ctx context.Context, id string, logger *za return nil, errors.New("Runtime Before function not found.") } - envelopeJSON, err := rp.jsonpbMarshaler.MarshalToString(envelope) + envelopeJSON, err := rp.protojsonMarshaler.Marshal(envelope) if err != nil { rp.Put(r) logger.Error("Could not marshall envelope to JSON", zap.Any("envelope", envelope), zap.Error(err)) return nil, errors.New("Could not run runtime Before function.") } var envelopeMap map[string]interface{} - if err := json.Unmarshal([]byte(envelopeJSON), &envelopeMap); err != nil { + if err := json.Unmarshal(envelopeJSON, &envelopeMap); err != nil { rp.Put(r) logger.Error("Could not unmarshall envelope to interface{}", zap.Any("envelope_json", envelopeJSON), zap.Error(err)) return nil, errors.New("Could not run runtime Before function.") @@ -244,7 +244,7 @@ func (rp *RuntimeProviderJS) BeforeRt(ctx context.Context, id string, logger *za return nil, errors.New("Could not complete runtime Before function.") } - if err = rp.jsonpbUnmarshaler.Unmarshal(strings.NewReader(string(resultJSON)), envelope); err != nil { + if err = rp.protojsonUnmarshaler.Unmarshal(resultJSON, envelope); err != nil { logger.Error("Could not unmarshal result to envelope", zap.Any("result", result), zap.Error(err)) return nil, errors.New("Could not complete runtime Before function.") } @@ -263,7 +263,7 @@ func (rp *RuntimeProviderJS) AfterRt(ctx context.Context, id string, logger *zap return errors.New("Runtime After function not found.") } - envelopeJSON, err := rp.jsonpbMarshaler.MarshalToString(envelope) + envelopeJSON, err := rp.protojsonMarshaler.Marshal(envelope) if err != nil { rp.Put(r) logger.Error("Could not marshall envelope to JSON", zap.Any("envelope", envelope), zap.Error(err)) @@ -315,7 +315,7 @@ func (rp *RuntimeProviderJS) BeforeReq(ctx context.Context, id string, logger *z logger.Error("Could not cast request to message", zap.Any("request", req)) return nil, errors.New("Could not run runtime Before function."), codes.Internal } - reqJSON, err := rp.jsonpbMarshaler.MarshalToString(reqProto) + reqJSON, err := rp.protojsonMarshaler.Marshal(reqProto) if err != nil { rp.Put(r) logger.Error("Could not marshall request to JSON", zap.Any("request", reqProto), zap.Error(err)) @@ -353,7 +353,7 @@ func (rp *RuntimeProviderJS) BeforeReq(ctx context.Context, id string, logger *z return nil, errors.New("Could not complete runtime Before function."), codes.Internal } - if err = rp.jsonpbUnmarshaler.Unmarshal(strings.NewReader(string(resultJSON)), reqProto); err != nil { + if err = rp.protojsonUnmarshaler.Unmarshal(resultJSON, reqProto); err != nil { logger.Error("Could not unmarshall result to request", zap.Any("result", result), zap.Error(err)) return nil, errors.New("Could not complete runtime Before function."), codes.Internal } @@ -381,7 +381,7 @@ func (rp *RuntimeProviderJS) AfterReq(ctx context.Context, id string, logger *za logger.Error("Could not cast response to message", zap.Any("response", res)) return errors.New("Could not run runtime After function.") } - resJSON, err := rp.jsonpbMarshaler.MarshalToString(resProto) + resJSON, err := rp.protojsonMarshaler.Marshal(resProto) if err != nil { rp.Put(r) logger.Error("Could not marshall response to JSON", zap.Any("response", resProto), zap.Error(err)) @@ -404,7 +404,7 @@ func (rp *RuntimeProviderJS) AfterReq(ctx context.Context, id string, logger *za logger.Error("Could not cast request to message", zap.Any("request", req)) return errors.New("Could not run runtime After function.") } - reqJSON, err := rp.jsonpbMarshaler.MarshalToString(reqProto) + reqJSON, err := rp.protojsonMarshaler.Marshal(reqProto) if err != nil { rp.Put(r) logger.Error("Could not marshall request to JSON", zap.Any("request", reqProto), zap.Error(err)) @@ -520,7 +520,7 @@ func (rp *RuntimeProviderJS) Put(r *RuntimeJS) { } } -func NewRuntimeProviderJS(logger, startupLogger *zap.Logger, db *sql.DB, jsonpbMarshaler *jsonpb.Marshaler, jsonpbUnmarshaler *jsonpb.Unmarshaler, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, leaderboardRankCache LeaderboardRankCache, leaderboardScheduler LeaderboardScheduler, sessionRegistry SessionRegistry, sessionCache SessionCache, matchRegistry MatchRegistry, tracker Tracker, metrics *Metrics, streamManager StreamManager, router MessageRouter, eventFn RuntimeEventCustomFunction, path, entrypoint string, matchProvider *MatchProvider) ([]string, map[string]RuntimeRpcFunction, map[string]RuntimeBeforeRtFunction, map[string]RuntimeAfterRtFunction, *RuntimeBeforeReqFunctions, *RuntimeAfterReqFunctions, RuntimeMatchmakerMatchedFunction, RuntimeTournamentEndFunction, RuntimeTournamentResetFunction, RuntimeLeaderboardResetFunction, error) { +func NewRuntimeProviderJS(logger, startupLogger *zap.Logger, db *sql.DB, protojsonMarshaler *protojson.MarshalOptions, protojsonUnmarshaler *protojson.UnmarshalOptions, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, leaderboardRankCache LeaderboardRankCache, leaderboardScheduler LeaderboardScheduler, sessionRegistry SessionRegistry, sessionCache SessionCache, matchRegistry MatchRegistry, tracker Tracker, metrics *Metrics, streamManager StreamManager, router MessageRouter, eventFn RuntimeEventCustomFunction, path, entrypoint string, matchProvider *MatchProvider) ([]string, map[string]RuntimeRpcFunction, map[string]RuntimeBeforeRtFunction, map[string]RuntimeAfterRtFunction, *RuntimeBeforeReqFunctions, *RuntimeAfterReqFunctions, RuntimeMatchmakerMatchedFunction, RuntimeTournamentEndFunction, RuntimeTournamentResetFunction, RuntimeLeaderboardResetFunction, error) { startupLogger.Info("Initialising JavaScript runtime provider", zap.String("path", path), zap.String("entrypoint", entrypoint)) modCache, err := cacheJavascriptModules(startupLogger, path, entrypoint) @@ -528,11 +528,11 @@ func NewRuntimeProviderJS(logger, startupLogger *zap.Logger, db *sql.DB, jsonpbM startupLogger.Fatal("Failed to load JavaScript files", zap.Error(err)) } - jsJsonpbMarshaler := &jsonpb.Marshaler{ - OrigName: false, - EnumsAsInts: jsonpbMarshaler.EnumsAsInts, - EmitDefaults: jsonpbMarshaler.EmitDefaults, - Indent: jsonpbMarshaler.Indent, + jsprotojsonMarshaler := &protojson.MarshalOptions{ + UseProtoNames: false, + UseEnumNumbers: protojsonMarshaler.UseEnumNumbers, + EmitUnpopulated: protojsonMarshaler.EmitUnpopulated, + Indent: protojsonMarshaler.Indent, } localCache := NewRuntimeJavascriptLocalCache() @@ -544,8 +544,8 @@ func NewRuntimeProviderJS(logger, startupLogger *zap.Logger, db *sql.DB, jsonpbM eventFn: eventFn, matchCreateFn: matchProvider.CreateMatch, matchRegistry: matchRegistry, - jsonpbMarshaler: jsJsonpbMarshaler, - jsonpbUnmarshaler: jsonpbUnmarshaler, + protojsonMarshaler: jsprotojsonMarshaler, + protojsonUnmarshaler: protojsonUnmarshaler, socialClient: socialClient, leaderboardCache: leaderboardCache, leaderboardRankCache: leaderboardRankCache, @@ -1430,7 +1430,7 @@ func NewRuntimeProviderJS(logger, startupLogger *zap.Logger, db *sql.DB, jsonpbM return nil, nil } - return NewRuntimeJavascriptMatchCore(logger, name, db, jsonpbMarshaler, jsonpbUnmarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, localCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, streamManager, router, matchProvider.CreateMatch, eventFn, id, node, stopped, mc, modCache) + return NewRuntimeJavascriptMatchCore(logger, name, db, protojsonMarshaler, protojsonUnmarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, localCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, streamManager, router, matchProvider.CreateMatch, eventFn, id, node, stopped, mc, modCache) }) runtimeProviderJS.newFn = func() *RuntimeJS { @@ -1445,7 +1445,7 @@ func NewRuntimeProviderJS(logger, startupLogger *zap.Logger, db *sql.DB, jsonpbM logger.Fatal("Failed to initialize JavaScript runtime", zap.Error(err)) } - nakamaModule := NewRuntimeJavascriptNakamaModule(logger, db, jsonpbMarshaler, jsonpbUnmarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, localCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, streamManager, router, eventFn, matchProvider.CreateMatch) + nakamaModule := NewRuntimeJavascriptNakamaModule(logger, db, protojsonMarshaler, protojsonUnmarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, localCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, streamManager, router, eventFn, matchProvider.CreateMatch) nk := runtime.ToValue(nakamaModule.Constructor(runtime)) nkInst, err := runtime.New(nk) if err != nil { @@ -1805,7 +1805,7 @@ func evalRuntimeModules(rp *RuntimeProviderJS, modCache *RuntimeJSModuleCache, m return nil, nil, err } - nakamaModule := NewRuntimeJavascriptNakamaModule(rp.logger, rp.db, rp.jsonpbMarshaler, rp.jsonpbUnmarshaler, rp.config, rp.socialClient, rp.leaderboardCache, rp.leaderboardRankCache, localCache, leaderboardScheduler, rp.sessionRegistry, rp.sessionCache, rp.matchRegistry, rp.tracker, rp.streamManager, rp.router, rp.eventFn, matchProvider.CreateMatch) + nakamaModule := NewRuntimeJavascriptNakamaModule(rp.logger, rp.db, rp.protojsonMarshaler, rp.protojsonUnmarshaler, rp.config, rp.socialClient, rp.leaderboardCache, rp.leaderboardRankCache, localCache, leaderboardScheduler, rp.sessionRegistry, rp.sessionCache, rp.matchRegistry, rp.tracker, rp.streamManager, rp.router, rp.eventFn, matchProvider.CreateMatch) nk := r.ToValue(nakamaModule.Constructor(r)) nkInst, err := r.New(nk) if err != nil { diff --git a/server/runtime_javascript_match_core.go b/server/runtime_javascript_match_core.go index 18dfc4f7e7674fc565ddb9e60d2f4de06c3751c0..cfbe272f5c35363a0a1da8878afcfd5e2e5ff0bd 100644 --- a/server/runtime_javascript_match_core.go +++ b/server/runtime_javascript_match_core.go @@ -23,11 +23,11 @@ import ( "github.com/dop251/goja" "github.com/gofrs/uuid" - "github.com/golang/protobuf/jsonpb" "github.com/heroiclabs/nakama-common/rtapi" "github.com/heroiclabs/nakama/v3/social" "go.uber.org/atomic" "go.uber.org/zap" + "google.golang.org/protobuf/encoding/protojson" ) var matchStoppedError = errors.New("match stopped") @@ -66,7 +66,7 @@ type RuntimeJavaScriptMatchCore struct { // ctxCancelFn context.CancelFunc } -func NewRuntimeJavascriptMatchCore(logger *zap.Logger, module string, db *sql.DB, jsonpbMarshaler *jsonpb.Marshaler, jsonpbUnmarshaler *jsonpb.Unmarshaler, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, rankCache LeaderboardRankCache, localCache *RuntimeJavascriptLocalCache, leaderboardScheduler LeaderboardScheduler, sessionRegistry SessionRegistry, sessionCache SessionCache, matchRegistry MatchRegistry, tracker Tracker, streamManager StreamManager, router MessageRouter, matchCreateFn RuntimeMatchCreateFunction, eventFn RuntimeEventCustomFunction, id uuid.UUID, node string, stopped *atomic.Bool, matchHandlers *jsMatchHandlers, modCache *RuntimeJSModuleCache) (RuntimeMatchCore, error) { +func NewRuntimeJavascriptMatchCore(logger *zap.Logger, module string, db *sql.DB, protojsonMarshaler *protojson.MarshalOptions, protojsonUnmarshaler *protojson.UnmarshalOptions, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, rankCache LeaderboardRankCache, localCache *RuntimeJavascriptLocalCache, leaderboardScheduler LeaderboardScheduler, sessionRegistry SessionRegistry, sessionCache SessionCache, matchRegistry MatchRegistry, tracker Tracker, streamManager StreamManager, router MessageRouter, matchCreateFn RuntimeMatchCreateFunction, eventFn RuntimeEventCustomFunction, id uuid.UUID, node string, stopped *atomic.Bool, matchHandlers *jsMatchHandlers, modCache *RuntimeJSModuleCache) (RuntimeMatchCore, error) { runtime := goja.New() jsLogger := NewJsLogger(logger) @@ -76,7 +76,7 @@ func NewRuntimeJavascriptMatchCore(logger *zap.Logger, module string, db *sql.DB logger.Fatal("Failed to initialize JavaScript runtime", zap.Error(err)) } - nakamaModule := NewRuntimeJavascriptNakamaModule(logger, db, jsonpbMarshaler, jsonpbUnmarshaler, config, socialClient, leaderboardCache, rankCache, localCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, streamManager, router, eventFn, matchCreateFn) + nakamaModule := NewRuntimeJavascriptNakamaModule(logger, db, protojsonMarshaler, protojsonUnmarshaler, config, socialClient, leaderboardCache, rankCache, localCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, streamManager, router, eventFn, matchCreateFn) nk := runtime.ToValue(nakamaModule.Constructor(runtime)) nkInst, err := runtime.New(nk) if err != nil { diff --git a/server/runtime_javascript_nakama.go b/server/runtime_javascript_nakama.go index e169217e1d1a040f3cd775d8c304fcf91a0fb0f5..e043fc9794d60f47a237f1281cb5eea802b69852 100644 --- a/server/runtime_javascript_nakama.go +++ b/server/runtime_javascript_nakama.go @@ -34,6 +34,9 @@ import ( "encoding/pem" "errors" "fmt" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/types/known/timestamppb" + "google.golang.org/protobuf/types/known/wrapperspb" "io" "io/ioutil" "net/http" @@ -46,9 +49,6 @@ import ( "github.com/dgrijalva/jwt-go" "github.com/dop251/goja" "github.com/gofrs/uuid" - "github.com/golang/protobuf/jsonpb" - "github.com/golang/protobuf/ptypes/timestamp" - "github.com/golang/protobuf/ptypes/wrappers" "github.com/heroiclabs/nakama-common/api" "github.com/heroiclabs/nakama/v3/social" "go.uber.org/zap" @@ -59,8 +59,8 @@ type runtimeJavascriptNakamaModule struct { logger *zap.Logger config Config db *sql.DB - jsonpbMarshaler *jsonpb.Marshaler - jsonpbUnmarshaler *jsonpb.Unmarshaler + protojsonMarshaler *protojson.MarshalOptions + protojsonUnmarshaler *protojson.UnmarshalOptions httpClient *http.Client socialClient *social.Client leaderboardCache LeaderboardCache @@ -79,13 +79,13 @@ type runtimeJavascriptNakamaModule struct { eventFn RuntimeEventCustomFunction } -func NewRuntimeJavascriptNakamaModule(logger *zap.Logger, db *sql.DB, jsonpbMarshaler *jsonpb.Marshaler, jsonpbUnmarshaler *jsonpb.Unmarshaler, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, rankCache LeaderboardRankCache, localCache *RuntimeJavascriptLocalCache, leaderboardScheduler LeaderboardScheduler, sessionRegistry SessionRegistry, sessionCache SessionCache, matchRegistry MatchRegistry, tracker Tracker, streamManager StreamManager, router MessageRouter, eventFn RuntimeEventCustomFunction, matchCreateFn RuntimeMatchCreateFunction) *runtimeJavascriptNakamaModule { +func NewRuntimeJavascriptNakamaModule(logger *zap.Logger, db *sql.DB, protojsonMarshaler *protojson.MarshalOptions, protojsonUnmarshaler *protojson.UnmarshalOptions, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, rankCache LeaderboardRankCache, localCache *RuntimeJavascriptLocalCache, leaderboardScheduler LeaderboardScheduler, sessionRegistry SessionRegistry, sessionCache SessionCache, matchRegistry MatchRegistry, tracker Tracker, streamManager StreamManager, router MessageRouter, eventFn RuntimeEventCustomFunction, matchCreateFn RuntimeMatchCreateFunction) *runtimeJavascriptNakamaModule { return &runtimeJavascriptNakamaModule{ logger: logger, config: config, db: db, - jsonpbMarshaler: jsonpbMarshaler, - jsonpbUnmarshaler: jsonpbUnmarshaler, + protojsonMarshaler: protojsonMarshaler, + protojsonUnmarshaler: protojsonUnmarshaler, streamManager: streamManager, sessionRegistry: sessionRegistry, sessionCache: sessionCache, @@ -249,7 +249,7 @@ func (n *runtimeJavascriptNakamaModule) event(r *goja.Runtime) func(goja.Functio return func(f goja.FunctionCall) goja.Value { eventName := getJsString(r, f.Argument(0)) properties := getJsStringMap(r, f.Argument(1)) - ts := ×tamp.Timestamp{} + ts := ×tamppb.Timestamp{} if f.Argument(2) != goja.Undefined() && f.Argument(2) != goja.Null() { ts.Seconds = getJsInt(r, f.Argument(2)) } else { @@ -418,7 +418,7 @@ func (n *runtimeJavascriptNakamaModule) httpRequest(r *goja.Runtime) func(goja.F n.logger.Debug(fmt.Sprintf("Http Timeout: %v", n.httpClient.Timeout)) if url == "" { - panic(r.NewTypeError("URL string cannot be empty.")) + panic(r.NewTypeError("URL string cannot be emptypb.")) } if !(method == "GET" || method == "POST" || method == "PUT" || method == "PATCH") { @@ -1381,32 +1381,32 @@ func (n *runtimeJavascriptNakamaModule) accountUpdateId(r *goja.Runtime) func(go username = getJsString(r, f.Argument(1)) } - var displayName *wrappers.StringValue + var displayName *wrapperspb.StringValue if f.Argument(2) != goja.Undefined() && f.Argument(2) != goja.Null() { - displayName = &wrappers.StringValue{Value: getJsString(r, f.Argument(2))} + displayName = &wrapperspb.StringValue{Value: getJsString(r, f.Argument(2))} } - var timezone *wrappers.StringValue + var timezone *wrapperspb.StringValue if f.Argument(3) != goja.Undefined() && f.Argument(3) != goja.Null() { - timezone = &wrappers.StringValue{Value: getJsString(r, f.Argument(3))} + timezone = &wrapperspb.StringValue{Value: getJsString(r, f.Argument(3))} } - var location *wrappers.StringValue + var location *wrapperspb.StringValue if f.Argument(4) != goja.Undefined() && f.Argument(4) != goja.Null() { - location = &wrappers.StringValue{Value: getJsString(r, f.Argument(4))} + location = &wrapperspb.StringValue{Value: getJsString(r, f.Argument(4))} } - var lang *wrappers.StringValue + var lang *wrapperspb.StringValue if f.Argument(5) != goja.Undefined() && f.Argument(5) != goja.Null() { - lang = &wrappers.StringValue{Value: getJsString(r, f.Argument(5))} + lang = &wrapperspb.StringValue{Value: getJsString(r, f.Argument(5))} } - var avatar *wrappers.StringValue + var avatar *wrapperspb.StringValue if f.Argument(6) != goja.Undefined() && f.Argument(6) != goja.Null() { - avatar = &wrappers.StringValue{Value: getJsString(r, f.Argument(6))} + avatar = &wrapperspb.StringValue{Value: getJsString(r, f.Argument(6))} } - var metadata *wrappers.StringValue + var metadata *wrapperspb.StringValue if f.Argument(7) != goja.Undefined() && f.Argument(7) != goja.Null() { metadataMap, ok := f.Argument(7).Export().(map[string]interface{}) if !ok { @@ -1416,7 +1416,7 @@ func (n *runtimeJavascriptNakamaModule) accountUpdateId(r *goja.Runtime) func(go if err != nil { panic(r.NewGoError(fmt.Errorf("failed to convert metadata: %s", err.Error()))) } - metadata = &wrappers.StringValue{Value: string(metadataBytes)} + metadata = &wrapperspb.StringValue{Value: string(metadataBytes)} } if err = UpdateAccounts(context.Background(), n.logger, n.db, []*accountUpdate{{ @@ -1468,7 +1468,7 @@ func (n *runtimeJavascriptNakamaModule) accountExportId(r *goja.Runtime) func(go panic(r.NewGoError(fmt.Errorf("error exporting account: %v", err.Error()))) } - exportString, err := n.jsonpbMarshaler.MarshalToString(export) + exportString, err := n.protojsonMarshaler.Marshal(export) if err != nil { panic(r.NewGoError(fmt.Errorf("error encoding account export: %v", err.Error()))) } @@ -2558,7 +2558,7 @@ func (n *runtimeJavascriptNakamaModule) streamSendRaw(r *goja.Runtime) func(goja } msg := &rtapi.Envelope{} - if err = n.jsonpbUnmarshaler.Unmarshal(bytes.NewReader(envelopeBytes), msg); err != nil { + if err = n.protojsonUnmarshaler.Unmarshal(envelopeBytes, msg); err != nil { panic(r.NewGoError(fmt.Errorf("not a valid envelope: %s", err.Error()))) } @@ -2740,29 +2740,29 @@ func (n *runtimeJavascriptNakamaModule) matchList(r *goja.Runtime) func(goja.Fun limit = int(getJsInt(r, f.Argument(0))) } - var authoritative *wrappers.BoolValue + var authoritative *wrapperspb.BoolValue if f.Argument(1) != goja.Undefined() && f.Argument(1) != goja.Null() { - authoritative = &wrappers.BoolValue{Value: getJsBool(r, f.Argument(1))} + authoritative = &wrapperspb.BoolValue{Value: getJsBool(r, f.Argument(1))} } - var label *wrappers.StringValue + var label *wrapperspb.StringValue if f.Argument(2) != goja.Undefined() && f.Argument(2) != goja.Null() { - label = &wrappers.StringValue{Value: getJsString(r, f.Argument(2))} + label = &wrapperspb.StringValue{Value: getJsString(r, f.Argument(2))} } - var minSize *wrappers.Int32Value + var minSize *wrapperspb.Int32Value if f.Argument(3) != goja.Undefined() && f.Argument(3) != goja.Null() { - minSize = &wrappers.Int32Value{Value: int32(getJsInt(r, f.Argument(3)))} + minSize = &wrapperspb.Int32Value{Value: int32(getJsInt(r, f.Argument(3)))} } - var maxSize *wrappers.Int32Value + var maxSize *wrapperspb.Int32Value if f.Argument(4) != goja.Undefined() && f.Argument(4) != goja.Null() { - maxSize = &wrappers.Int32Value{Value: int32(getJsInt(r, f.Argument(4)))} + maxSize = &wrapperspb.Int32Value{Value: int32(getJsInt(r, f.Argument(4)))} } - var query *wrappers.StringValue + var query *wrapperspb.StringValue if f.Argument(5) != goja.Undefined() && f.Argument(5) != goja.Null() { - query = &wrappers.StringValue{Value: getJsString(r, f.Argument(5))} + query = &wrapperspb.StringValue{Value: getJsString(r, f.Argument(5))} } results, err := n.matchRegistry.ListMatches(context.Background(), limit, authoritative, label, minSize, maxSize, query) @@ -2844,7 +2844,7 @@ func (n *runtimeJavascriptNakamaModule) notificationSend(r *goja.Runtime) func(g Code: int32(code), SenderId: senderID, Persistent: persistent, - CreateTime: ×tamp.Timestamp{Seconds: time.Now().UTC().Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: time.Now().UTC().Unix()}, }} notifications := map[uuid.UUID][]*api.Notification{ userID: nots, @@ -2953,7 +2953,7 @@ func (n *runtimeJavascriptNakamaModule) notificationsSend(r *goja.Runtime) func( } notification.Id = uuid.Must(uuid.NewV4()).String() - notification.CreateTime = ×tamp.Timestamp{Seconds: time.Now().UTC().Unix()} + notification.CreateTime = ×tamppb.Timestamp{Seconds: time.Now().UTC().Unix()} notification.SenderId = senderID.String() no := notifications[userID] @@ -3458,9 +3458,9 @@ func (n *runtimeJavascriptNakamaModule) storageWrite(r *goja.Runtime) func(goja. if !ok { panic(r.NewTypeError("expects 'permissionRead' value to be a number")) } - writeOp.PermissionRead = &wrappers.Int32Value{Value: int32(permissionRead)} + writeOp.PermissionRead = &wrapperspb.Int32Value{Value: int32(permissionRead)} } else { - writeOp.PermissionRead = &wrappers.Int32Value{Value: 1} + writeOp.PermissionRead = &wrapperspb.Int32Value{Value: 1} } if permissionWriteIn, ok := dataMap["permissionWrite"]; ok { @@ -3468,9 +3468,9 @@ func (n *runtimeJavascriptNakamaModule) storageWrite(r *goja.Runtime) func(goja. if !ok { panic(r.NewTypeError("expects 'permissionWrite' value to be a number")) } - writeOp.PermissionWrite = &wrappers.Int32Value{Value: int32(permissionWrite)} + writeOp.PermissionWrite = &wrapperspb.Int32Value{Value: int32(permissionWrite)} } else { - writeOp.PermissionWrite = &wrappers.Int32Value{Value: 1} + writeOp.PermissionWrite = &wrapperspb.Int32Value{Value: 1} } if writeOp.Collection == "" { @@ -3642,7 +3642,7 @@ func (n *runtimeJavascriptNakamaModule) multiUpdate(r *goja.Runtime) func(goja.F if !ok { panic(r.NewTypeError("expects a string")) } - update.displayName = &wrappers.StringValue{Value: displayNameStr} + update.displayName = &wrapperspb.StringValue{Value: displayNameStr} } if timezoneIn, ok := accUpdateObj["timezone"]; ok { @@ -3650,7 +3650,7 @@ func (n *runtimeJavascriptNakamaModule) multiUpdate(r *goja.Runtime) func(goja.F if !ok { panic(r.NewTypeError("expects a string")) } - update.timezone = &wrappers.StringValue{Value: timezoneStr} + update.timezone = &wrapperspb.StringValue{Value: timezoneStr} } if locationIn, ok := accUpdateObj["location"]; ok { @@ -3658,7 +3658,7 @@ func (n *runtimeJavascriptNakamaModule) multiUpdate(r *goja.Runtime) func(goja.F if !ok { panic(r.NewTypeError("expects a string")) } - update.location = &wrappers.StringValue{Value: locationStr} + update.location = &wrapperspb.StringValue{Value: locationStr} } if langIn, ok := accUpdateObj["langTag"]; ok { @@ -3666,7 +3666,7 @@ func (n *runtimeJavascriptNakamaModule) multiUpdate(r *goja.Runtime) func(goja.F if !ok { panic(r.NewTypeError("expects a string")) } - update.langTag = &wrappers.StringValue{Value: langStr} + update.langTag = &wrapperspb.StringValue{Value: langStr} } if avatarIn, ok := accUpdateObj["avatarUrl"]; ok { @@ -3674,7 +3674,7 @@ func (n *runtimeJavascriptNakamaModule) multiUpdate(r *goja.Runtime) func(goja.F if !ok { panic(r.NewTypeError("expects a string")) } - update.avatarURL = &wrappers.StringValue{Value: avatarStr} + update.avatarURL = &wrapperspb.StringValue{Value: avatarStr} } if metadataIn, ok := accUpdateObj["metadata"]; ok { @@ -3686,7 +3686,7 @@ func (n *runtimeJavascriptNakamaModule) multiUpdate(r *goja.Runtime) func(goja.F if err != nil { panic(r.NewGoError(fmt.Errorf("failed to convert metadata: %s", err.Error()))) } - update.metadata = &wrappers.StringValue{Value: string(metadataBytes)} + update.metadata = &wrapperspb.StringValue{Value: string(metadataBytes)} } accountUpdates = append(accountUpdates, update) @@ -3774,9 +3774,9 @@ func (n *runtimeJavascriptNakamaModule) multiUpdate(r *goja.Runtime) func(goja.F if !ok { panic(r.NewTypeError("expects 'permissionRead' value to be a number")) } - writeOp.PermissionRead = &wrappers.Int32Value{Value: int32(permissionRead)} + writeOp.PermissionRead = &wrapperspb.Int32Value{Value: int32(permissionRead)} } else { - writeOp.PermissionRead = &wrappers.Int32Value{Value: 1} + writeOp.PermissionRead = &wrapperspb.Int32Value{Value: 1} } if permissionWriteIn, ok := dataMap["permissionWrite"]; ok { @@ -3784,9 +3784,9 @@ func (n *runtimeJavascriptNakamaModule) multiUpdate(r *goja.Runtime) func(goja.F if !ok { panic(r.NewTypeError("expects 'permissionWrite' value to be a number")) } - writeOp.PermissionWrite = &wrappers.Int32Value{Value: int32(permissionWrite)} + writeOp.PermissionWrite = &wrapperspb.Int32Value{Value: int32(permissionWrite)} } else { - writeOp.PermissionWrite = &wrappers.Int32Value{Value: 1} + writeOp.PermissionWrite = &wrapperspb.Int32Value{Value: 1} } if writeOp.Collection == "" { @@ -4042,9 +4042,9 @@ func (n *runtimeJavascriptNakamaModule) leaderboardRecordsList(r *goja.Runtime) if f.Argument(2) != goja.Undefined() { limitNumber = int(getJsInt(r, f.Argument(2))) } - var limit *wrappers.Int32Value + var limit *wrapperspb.Int32Value if limitNumber != 0 { - limit = &wrappers.Int32Value{Value: int32(limitNumber)} + limit = &wrapperspb.Int32Value{Value: int32(limitNumber)} } cursor := "" @@ -4620,9 +4620,9 @@ func (n *runtimeJavascriptNakamaModule) tournamentRecordsList(r *goja.Runtime) f if f.Argument(2) != goja.Undefined() { limitNumber = int(getJsInt(r, f.Argument(2))) } - var limit *wrappers.Int32Value + var limit *wrapperspb.Int32Value if limitNumber != 0 { - limit = &wrappers.Int32Value{Value: int32(limitNumber)} + limit = &wrapperspb.Int32Value{Value: int32(limitNumber)} } cursor := "" @@ -5148,10 +5148,10 @@ func (n *runtimeJavascriptNakamaModule) groupUpdate(r *goja.Runtime) func(goja.F panic(r.NewTypeError("expects group ID to be a valid identifier")) } - var name *wrappers.StringValue + var name *wrapperspb.StringValue if f.Argument(1) != goja.Undefined() && f.Argument(1) != goja.Null() { nameStr := getJsString(r, f.Argument(1)) - name = &wrappers.StringValue{Value: nameStr} + name = &wrapperspb.StringValue{Value: nameStr} } creatorID := uuid.Nil @@ -5163,30 +5163,30 @@ func (n *runtimeJavascriptNakamaModule) groupUpdate(r *goja.Runtime) func(goja.F } } - var lang *wrappers.StringValue + var lang *wrapperspb.StringValue if f.Argument(3) != goja.Undefined() && f.Argument(3) != goja.Null() { langStr := getJsString(r, f.Argument(3)) - lang = &wrappers.StringValue{Value: langStr} + lang = &wrapperspb.StringValue{Value: langStr} } - var desc *wrappers.StringValue + var desc *wrapperspb.StringValue if f.Argument(4) != goja.Undefined() && f.Argument(4) != goja.Null() { descStr := getJsString(r, f.Argument(4)) - desc = &wrappers.StringValue{Value: descStr} + desc = &wrapperspb.StringValue{Value: descStr} } - var avatarURL *wrappers.StringValue + var avatarURL *wrapperspb.StringValue if f.Argument(5) != goja.Undefined() && f.Argument(5) != goja.Null() { avatarStr := getJsString(r, f.Argument(5)) - avatarURL = &wrappers.StringValue{Value: avatarStr} + avatarURL = &wrapperspb.StringValue{Value: avatarStr} } - var open *wrappers.BoolValue + var open *wrapperspb.BoolValue if f.Argument(6) != goja.Undefined() && f.Argument(6) != goja.Null() { - open = &wrappers.BoolValue{Value: getJsBool(r, f.Argument(6))} + open = &wrapperspb.BoolValue{Value: getJsBool(r, f.Argument(6))} } - var metadata *wrappers.StringValue + var metadata *wrapperspb.StringValue metadataIn := f.Argument(7) if metadataIn != goja.Undefined() && metadataIn != goja.Null() { metadataMap, ok := metadataIn.Export().(map[string]interface{}) @@ -5197,7 +5197,7 @@ func (n *runtimeJavascriptNakamaModule) groupUpdate(r *goja.Runtime) func(goja.F if err != nil { panic(r.NewGoError(fmt.Errorf("failed to convert metadata: %s", err.Error()))) } - metadata = &wrappers.StringValue{Value: string(metadataBytes)} + metadata = &wrapperspb.StringValue{Value: string(metadataBytes)} } maxCount := 0 @@ -5291,14 +5291,14 @@ func (n *runtimeJavascriptNakamaModule) groupUsersList(r *goja.Runtime) func(goj } } - var stateWrapper *wrappers.Int32Value + var stateWrapper *wrapperspb.Int32Value if !goja.IsUndefined(f.Argument(2)) && !goja.IsNull(f.Argument(2)) { state := getJsInt(r, f.Argument(2)) if state != -1 { if state < 0 || state > 4 { panic(r.NewTypeError("expects state to be 0-4")) } - stateWrapper = &wrappers.Int32Value{Value: int32(state)} + stateWrapper = &wrapperspb.Int32Value{Value: int32(state)} } } @@ -5390,14 +5390,14 @@ func (n *runtimeJavascriptNakamaModule) userGroupsList(r *goja.Runtime) func(goj } } - var stateWrapper *wrappers.Int32Value + var stateWrapper *wrapperspb.Int32Value if !goja.IsUndefined(f.Argument(2)) && !goja.IsNull(f.Argument(2)) { state := getJsInt(r, f.Argument(2)) if state != -1 { if state < 0 || state > 4 { panic(r.NewTypeError("expects state to be 0-4")) } - stateWrapper = &wrappers.Int32Value{Value: int32(state)} + stateWrapper = &wrapperspb.Int32Value{Value: int32(state)} } } @@ -5474,14 +5474,14 @@ func (n *runtimeJavascriptNakamaModule) friendsList(r *goja.Runtime) func(goja.F } } - var stateWrapper *wrappers.Int32Value + var stateWrapper *wrapperspb.Int32Value if !goja.IsUndefined(f.Argument(2)) && !goja.IsNull(f.Argument(2)) { state := getJsInt(r, f.Argument(2)) if state != -1 { if state < 0 || state > 3 { panic(r.NewTypeError("expects state to be 0-3")) } - stateWrapper = &wrappers.Int32Value{Value: int32(state)} + stateWrapper = &wrapperspb.Int32Value{Value: int32(state)} } } diff --git a/server/runtime_lua.go b/server/runtime_lua.go index 04c20c73791e62d8bf50536d82691c37d7fab76f..6408ec21d8824a3f34fafb89089b7489ddfa1c78 100644 --- a/server/runtime_lua.go +++ b/server/runtime_lua.go @@ -31,8 +31,6 @@ import ( "go.uber.org/atomic" "github.com/gofrs/uuid" - "github.com/golang/protobuf/jsonpb" - "github.com/golang/protobuf/proto" "github.com/heroiclabs/nakama-common/api" "github.com/heroiclabs/nakama-common/rtapi" "github.com/heroiclabs/nakama-common/runtime" @@ -41,6 +39,8 @@ import ( "go.uber.org/zap" "go.uber.org/zap/zapcore" "google.golang.org/grpc/codes" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" ) const LTSentinel = lua.LValueType(-1) @@ -86,8 +86,8 @@ func (mc *RuntimeLuaModuleCache) Add(m *RuntimeLuaModule) { type RuntimeProviderLua struct { logger *zap.Logger db *sql.DB - jsonpbMarshaler *jsonpb.Marshaler - jsonpbUnmarshaler *jsonpb.Unmarshaler + protojsonMarshaler *protojson.MarshalOptions + protojsonUnmarshaler *protojson.UnmarshalOptions config Config socialClient *social.Client leaderboardCache LeaderboardCache @@ -108,7 +108,7 @@ type RuntimeProviderLua struct { statsCtx context.Context } -func NewRuntimeProviderLua(logger, startupLogger *zap.Logger, db *sql.DB, jsonpbMarshaler *jsonpb.Marshaler, jsonpbUnmarshaler *jsonpb.Unmarshaler, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, leaderboardRankCache LeaderboardRankCache, leaderboardScheduler LeaderboardScheduler, sessionRegistry SessionRegistry, sessionCache SessionCache, matchRegistry MatchRegistry, tracker Tracker, metrics *Metrics, streamManager StreamManager, router MessageRouter, eventFn RuntimeEventCustomFunction, rootPath string, paths []string, matchProvider *MatchProvider) ([]string, map[string]RuntimeRpcFunction, map[string]RuntimeBeforeRtFunction, map[string]RuntimeAfterRtFunction, *RuntimeBeforeReqFunctions, *RuntimeAfterReqFunctions, RuntimeMatchmakerMatchedFunction, RuntimeTournamentEndFunction, RuntimeTournamentResetFunction, RuntimeLeaderboardResetFunction, error) { +func NewRuntimeProviderLua(logger, startupLogger *zap.Logger, db *sql.DB, protojsonMarshaler *protojson.MarshalOptions, protojsonUnmarshaler *protojson.UnmarshalOptions, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, leaderboardRankCache LeaderboardRankCache, leaderboardScheduler LeaderboardScheduler, sessionRegistry SessionRegistry, sessionCache SessionCache, matchRegistry MatchRegistry, tracker Tracker, metrics *Metrics, streamManager StreamManager, router MessageRouter, eventFn RuntimeEventCustomFunction, rootPath string, paths []string, matchProvider *MatchProvider) ([]string, map[string]RuntimeRpcFunction, map[string]RuntimeBeforeRtFunction, map[string]RuntimeAfterRtFunction, *RuntimeBeforeReqFunctions, *RuntimeAfterReqFunctions, RuntimeMatchmakerMatchedFunction, RuntimeTournamentEndFunction, RuntimeTournamentResetFunction, RuntimeLeaderboardResetFunction, error) { startupLogger.Info("Initialising Lua runtime provider", zap.String("path", rootPath)) // Load Lua modules into memory by reading the file contents. No evaluation/execution at this stage. @@ -136,8 +136,8 @@ func NewRuntimeProviderLua(logger, startupLogger *zap.Logger, db *sql.DB, jsonpb runtimeProviderLua := &RuntimeProviderLua{ logger: logger, db: db, - jsonpbMarshaler: jsonpbMarshaler, - jsonpbUnmarshaler: jsonpbUnmarshaler, + protojsonMarshaler: protojsonMarshaler, + protojsonUnmarshaler: protojsonUnmarshaler, config: config, socialClient: socialClient, leaderboardCache: leaderboardCache, @@ -160,11 +160,11 @@ func NewRuntimeProviderLua(logger, startupLogger *zap.Logger, db *sql.DB, jsonpb matchProvider.RegisterCreateFn("lua", func(ctx context.Context, logger *zap.Logger, id uuid.UUID, node string, stopped *atomic.Bool, name string) (RuntimeMatchCore, error) { - return NewRuntimeLuaMatchCore(logger, name, db, jsonpbMarshaler, jsonpbUnmarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, streamManager, router, stdLibs, once, localCache, eventFn, nil, nil, id, node, stopped, name, matchProvider) + return NewRuntimeLuaMatchCore(logger, name, db, protojsonMarshaler, protojsonUnmarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, streamManager, router, stdLibs, once, localCache, eventFn, nil, nil, id, node, stopped, name, matchProvider) }, ) - r, err := newRuntimeLuaVM(logger, db, jsonpbMarshaler, jsonpbUnmarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, streamManager, router, stdLibs, moduleCache, once, localCache, matchProvider.CreateMatch, eventFn, func(execMode RuntimeExecutionMode, id string) { + r, err := newRuntimeLuaVM(logger, db, protojsonMarshaler, protojsonUnmarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, streamManager, router, stdLibs, moduleCache, once, localCache, matchProvider.CreateMatch, eventFn, func(execMode RuntimeExecutionMode, id string) { switch execMode { case RuntimeExecutionModeRPC: rpcFunctions[id] = func(ctx context.Context, queryParams map[string][]string, userID, username string, vars map[string]string, expiry int64, sessionID, clientIP, clientPort, payload string) (string, error, codes.Code) { @@ -1071,7 +1071,7 @@ func NewRuntimeProviderLua(logger, startupLogger *zap.Logger, db *sql.DB, jsonpb r.Stop() runtimeProviderLua.newFn = func() *RuntimeLua { - r, err := newRuntimeLuaVM(logger, db, jsonpbMarshaler, jsonpbUnmarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, streamManager, router, stdLibs, moduleCache, once, localCache, matchProvider.CreateMatch, eventFn, nil) + r, err := newRuntimeLuaVM(logger, db, protojsonMarshaler, protojsonUnmarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, streamManager, router, stdLibs, moduleCache, once, localCache, matchProvider.CreateMatch, eventFn, nil) if err != nil { logger.Fatal("Failed to initialize Lua runtime", zap.Error(err)) } @@ -1234,7 +1234,7 @@ func (rp *RuntimeProviderLua) BeforeRt(ctx context.Context, id string, logger *z return nil, errors.New("Runtime Before function not found.") } - envelopeJSON, err := rp.jsonpbMarshaler.MarshalToString(envelope) + envelopeJSON, err := rp.protojsonMarshaler.Marshal(envelope) if err != nil { rp.Put(r) logger.Error("Could not marshall envelope to JSON", zap.Any("envelope", envelope), zap.Error(err)) @@ -1285,7 +1285,7 @@ func (rp *RuntimeProviderLua) BeforeRt(ctx context.Context, id string, logger *z return nil, errors.New("Could not complete runtime Before function.") } - if err = rp.jsonpbUnmarshaler.Unmarshal(strings.NewReader(string(resultJSON)), envelope); err != nil { + if err = rp.protojsonUnmarshaler.Unmarshal(resultJSON, envelope); err != nil { logger.Error("Could not unmarshal result to envelope", zap.Any("result", result), zap.Error(err)) return nil, errors.New("Could not complete runtime Before function.") } @@ -1304,7 +1304,7 @@ func (rp *RuntimeProviderLua) AfterRt(ctx context.Context, id string, logger *za return errors.New("Runtime After function not found.") } - envelopeJSON, err := rp.jsonpbMarshaler.MarshalToString(envelope) + envelopeJSON, err := rp.protojsonMarshaler.Marshal(envelope) if err != nil { rp.Put(r) logger.Error("Could not marshall envelope to JSON", zap.Any("envelope", envelope), zap.Error(err)) @@ -1370,7 +1370,7 @@ func (rp *RuntimeProviderLua) BeforeReq(ctx context.Context, id string, logger * logger.Error("Could not cast request to message", zap.Any("request", req)) return nil, errors.New("Could not run runtime Before function."), codes.Internal } - reqJSON, err := rp.jsonpbMarshaler.MarshalToString(reqProto) + reqJSON, err := rp.protojsonMarshaler.Marshal(reqProto) if err != nil { rp.Put(r) logger.Error("Could not marshall request to JSON", zap.Any("request", reqProto), zap.Error(err)) @@ -1422,7 +1422,7 @@ func (rp *RuntimeProviderLua) BeforeReq(ctx context.Context, id string, logger * return nil, errors.New("Could not complete runtime Before function."), codes.Internal } - if err = rp.jsonpbUnmarshaler.Unmarshal(strings.NewReader(string(resultJSON)), reqProto); err != nil { + if err = rp.protojsonUnmarshaler.Unmarshal(resultJSON, reqProto); err != nil { logger.Error("Could not unmarshall result to request", zap.Any("result", result), zap.Error(err)) return nil, errors.New("Could not complete runtime Before function."), codes.Internal } @@ -1450,7 +1450,7 @@ func (rp *RuntimeProviderLua) AfterReq(ctx context.Context, id string, logger *z logger.Error("Could not cast response to message", zap.Any("response", res)) return errors.New("Could not run runtime After function.") } - resJSON, err := rp.jsonpbMarshaler.MarshalToString(resProto) + resJSON, err := rp.protojsonMarshaler.Marshal(resProto) if err != nil { rp.Put(r) logger.Error("Could not marshall response to JSON", zap.Any("response", resProto), zap.Error(err)) @@ -1473,7 +1473,7 @@ func (rp *RuntimeProviderLua) AfterReq(ctx context.Context, id string, logger *z logger.Error("Could not cast request to message", zap.Any("request", req)) return errors.New("Could not run runtime After function.") } - reqJSON, err := rp.jsonpbMarshaler.MarshalToString(reqProto) + reqJSON, err := rp.protojsonMarshaler.Marshal(reqProto) if err != nil { rp.Put(r) logger.Error("Could not marshall request to JSON", zap.Any("request", reqProto), zap.Error(err)) @@ -2013,7 +2013,7 @@ func checkRuntimeLuaVM(logger *zap.Logger, config Config, stdLibs map[string]lua return nil } -func newRuntimeLuaVM(logger *zap.Logger, db *sql.DB, jsonpbMarshaler *jsonpb.Marshaler, jsonpbUnmarshaler *jsonpb.Unmarshaler, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, rankCache LeaderboardRankCache, leaderboardScheduler LeaderboardScheduler, sessionRegistry SessionRegistry, sessionCache SessionCache, matchRegistry MatchRegistry, tracker Tracker, streamManager StreamManager, router MessageRouter, stdLibs map[string]lua.LGFunction, moduleCache *RuntimeLuaModuleCache, once *sync.Once, localCache *RuntimeLuaLocalCache, matchCreateFn RuntimeMatchCreateFunction, eventFn RuntimeEventCustomFunction, announceCallbackFn func(RuntimeExecutionMode, string)) (*RuntimeLua, error) { +func newRuntimeLuaVM(logger *zap.Logger, db *sql.DB, protojsonMarshaler *protojson.MarshalOptions, protojsonUnmarshaler *protojson.UnmarshalOptions, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, rankCache LeaderboardRankCache, leaderboardScheduler LeaderboardScheduler, sessionRegistry SessionRegistry, sessionCache SessionCache, matchRegistry MatchRegistry, tracker Tracker, streamManager StreamManager, router MessageRouter, stdLibs map[string]lua.LGFunction, moduleCache *RuntimeLuaModuleCache, once *sync.Once, localCache *RuntimeLuaLocalCache, matchCreateFn RuntimeMatchCreateFunction, eventFn RuntimeEventCustomFunction, announceCallbackFn func(RuntimeExecutionMode, string)) (*RuntimeLua, error) { vm := lua.NewState(lua.Options{ CallStackSize: config.GetRuntime().GetLuaCallStackSize(), RegistrySize: config.GetRuntime().GetLuaRegistrySize(), @@ -2049,7 +2049,7 @@ func newRuntimeLuaVM(logger *zap.Logger, db *sql.DB, jsonpbMarshaler *jsonpb.Mar callbacks.LeaderboardReset = fn } } - nakamaModule := NewRuntimeLuaNakamaModule(logger, db, jsonpbMarshaler, jsonpbUnmarshaler, config, socialClient, leaderboardCache, rankCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, streamManager, router, once, localCache, matchCreateFn, eventFn, registerCallbackFn, announceCallbackFn) + nakamaModule := NewRuntimeLuaNakamaModule(logger, db, protojsonMarshaler, protojsonUnmarshaler, config, socialClient, leaderboardCache, rankCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, streamManager, router, once, localCache, matchCreateFn, eventFn, registerCallbackFn, announceCallbackFn) vm.PreloadModule("nakama", nakamaModule.Loader) r := &RuntimeLua{ logger: logger, diff --git a/server/runtime_lua_match_core.go b/server/runtime_lua_match_core.go index 1e95335c301b214c8161d2dda6b36e9263ad3ca5..8224c0cd37cea417b83fc3f8ea5c087bcf3b279b 100644 --- a/server/runtime_lua_match_core.go +++ b/server/runtime_lua_match_core.go @@ -25,12 +25,12 @@ import ( "time" "github.com/gofrs/uuid" - "github.com/golang/protobuf/jsonpb" "github.com/heroiclabs/nakama-common/rtapi" lua "github.com/heroiclabs/nakama/v3/internal/gopher-lua" "github.com/heroiclabs/nakama/v3/social" "go.uber.org/atomic" "go.uber.org/zap" + "google.golang.org/protobuf/encoding/protojson" ) type RuntimeLuaMatchCore struct { @@ -64,7 +64,7 @@ type RuntimeLuaMatchCore struct { ctxCancelFn context.CancelFunc } -func NewRuntimeLuaMatchCore(logger *zap.Logger, module string, db *sql.DB, jsonpbMarshaler *jsonpb.Marshaler, jsonpbUnmarshaler *jsonpb.Unmarshaler, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, rankCache LeaderboardRankCache, leaderboardScheduler LeaderboardScheduler, sessionRegistry SessionRegistry, sessionCache SessionCache, matchRegistry MatchRegistry, tracker Tracker, streamManager StreamManager, router MessageRouter, stdLibs map[string]lua.LGFunction, once *sync.Once, localCache *RuntimeLuaLocalCache, eventFn RuntimeEventCustomFunction, sharedReg, sharedGlobals *lua.LTable, id uuid.UUID, node string, stopped *atomic.Bool, name string, matchProvider *MatchProvider) (RuntimeMatchCore, error) { +func NewRuntimeLuaMatchCore(logger *zap.Logger, module string, db *sql.DB, protojsonMarshaler *protojson.MarshalOptions, protojsonUnmarshaler *protojson.UnmarshalOptions, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, rankCache LeaderboardRankCache, leaderboardScheduler LeaderboardScheduler, sessionRegistry SessionRegistry, sessionCache SessionCache, matchRegistry MatchRegistry, tracker Tracker, streamManager StreamManager, router MessageRouter, stdLibs map[string]lua.LGFunction, once *sync.Once, localCache *RuntimeLuaLocalCache, eventFn RuntimeEventCustomFunction, sharedReg, sharedGlobals *lua.LTable, id uuid.UUID, node string, stopped *atomic.Bool, name string, matchProvider *MatchProvider) (RuntimeMatchCore, error) { // Set up the Lua VM that will handle this match. vm := lua.NewState(lua.Options{ CallStackSize: config.GetRuntime().GetLuaCallStackSize(), @@ -94,7 +94,7 @@ func NewRuntimeLuaMatchCore(logger *zap.Logger, module string, db *sql.DB, jsonp vm.Call(1, 0) } - nakamaModule := NewRuntimeLuaNakamaModule(logger, db, jsonpbMarshaler, jsonpbUnmarshaler, config, socialClient, leaderboardCache, rankCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, streamManager, router, once, localCache, matchProvider.CreateMatch, eventFn, nil, nil) + nakamaModule := NewRuntimeLuaNakamaModule(logger, db, protojsonMarshaler, protojsonUnmarshaler, config, socialClient, leaderboardCache, rankCache, leaderboardScheduler, sessionRegistry, sessionCache, matchRegistry, tracker, streamManager, router, once, localCache, matchProvider.CreateMatch, eventFn, nil, nil) vm.PreloadModule("nakama", nakamaModule.Loader) } diff --git a/server/runtime_lua_nakama.go b/server/runtime_lua_nakama.go index 1fa2aa16431d6d92e8099e6ad110125c913a1370..babb6e852f5e60f745c01d1e73326c21e128c6bc 100644 --- a/server/runtime_lua_nakama.go +++ b/server/runtime_lua_nakama.go @@ -32,6 +32,8 @@ import ( "encoding/json" "encoding/pem" "fmt" + "google.golang.org/protobuf/types/known/timestamppb" + "google.golang.org/protobuf/types/known/wrapperspb" "io" "io/ioutil" "net/http" @@ -40,11 +42,9 @@ import ( "time" "github.com/dgrijalva/jwt-go" - "github.com/golang/protobuf/jsonpb" + "google.golang.org/protobuf/encoding/protojson" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/timestamp" - "github.com/golang/protobuf/ptypes/wrappers" "github.com/heroiclabs/nakama-common/api" "github.com/heroiclabs/nakama-common/rtapi" "github.com/heroiclabs/nakama/v3/internal/cronexpr" @@ -57,8 +57,8 @@ import ( type RuntimeLuaNakamaModule struct { logger *zap.Logger db *sql.DB - jsonpbMarshaler *jsonpb.Marshaler - jsonpbUnmarshaler *jsonpb.Unmarshaler + protojsonMarshaler *protojson.MarshalOptions + protojsonUnmarshaler *protojson.UnmarshalOptions config Config socialClient *social.Client leaderboardCache LeaderboardCache @@ -81,12 +81,12 @@ type RuntimeLuaNakamaModule struct { eventFn RuntimeEventCustomFunction } -func NewRuntimeLuaNakamaModule(logger *zap.Logger, db *sql.DB, jsonpbMarshaler *jsonpb.Marshaler, jsonpbUnmarshaler *jsonpb.Unmarshaler, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, rankCache LeaderboardRankCache, leaderboardScheduler LeaderboardScheduler, sessionRegistry SessionRegistry, sessionCache SessionCache, matchRegistry MatchRegistry, tracker Tracker, streamManager StreamManager, router MessageRouter, once *sync.Once, localCache *RuntimeLuaLocalCache, matchCreateFn RuntimeMatchCreateFunction, eventFn RuntimeEventCustomFunction, registerCallbackFn func(RuntimeExecutionMode, string, *lua.LFunction), announceCallbackFn func(RuntimeExecutionMode, string)) *RuntimeLuaNakamaModule { +func NewRuntimeLuaNakamaModule(logger *zap.Logger, db *sql.DB, protojsonMarshaler *protojson.MarshalOptions, protojsonUnmarshaler *protojson.UnmarshalOptions, config Config, socialClient *social.Client, leaderboardCache LeaderboardCache, rankCache LeaderboardRankCache, leaderboardScheduler LeaderboardScheduler, sessionRegistry SessionRegistry, sessionCache SessionCache, matchRegistry MatchRegistry, tracker Tracker, streamManager StreamManager, router MessageRouter, once *sync.Once, localCache *RuntimeLuaLocalCache, matchCreateFn RuntimeMatchCreateFunction, eventFn RuntimeEventCustomFunction, registerCallbackFn func(RuntimeExecutionMode, string, *lua.LFunction), announceCallbackFn func(RuntimeExecutionMode, string)) *RuntimeLuaNakamaModule { return &RuntimeLuaNakamaModule{ logger: logger, db: db, - jsonpbMarshaler: jsonpbMarshaler, - jsonpbUnmarshaler: jsonpbUnmarshaler, + protojsonMarshaler: protojsonMarshaler, + protojsonUnmarshaler: protojsonUnmarshaler, config: config, socialClient: socialClient, leaderboardCache: leaderboardCache, @@ -485,14 +485,14 @@ func (n *RuntimeLuaNakamaModule) event(l *lua.LState) int { } } - var ts *timestamp.Timestamp + var ts *timestamppb.Timestamp t := l.Get(3) if t != lua.LNil { if t.Type() != lua.LTNumber { l.ArgError(3, "timestamp must be numeric UTC seconds when provided") return 0 } - ts = ×tamp.Timestamp{Seconds: int64(t.(lua.LNumber))} + ts = ×tamppb.Timestamp{Seconds: int64(t.(lua.LNumber))} } external := l.OptBool(4, false) @@ -3670,7 +3670,7 @@ func (n *RuntimeLuaNakamaModule) streamSendRaw(l *lua.LState) int { } msg := &rtapi.Envelope{} - if err = n.jsonpbUnmarshaler.Unmarshal(bytes.NewReader(envelopeBytes), msg); err != nil { + if err = n.protojsonUnmarshaler.Unmarshal(envelopeBytes, msg); err != nil { l.ArgError(2, fmt.Sprintf("not a valid envelope: %s", err.Error())) return 0 } @@ -3865,52 +3865,52 @@ func (n *RuntimeLuaNakamaModule) matchList(l *lua.LState) int { limit := l.OptInt(1, 1) // Parse authoritative flag. - var authoritative *wrappers.BoolValue + var authoritative *wrapperspb.BoolValue if v := l.Get(2); v.Type() != lua.LTNil { if v.Type() != lua.LTBool { l.ArgError(2, "expects authoritative true/false or nil") return 0 } - authoritative = &wrappers.BoolValue{Value: lua.LVAsBool(v)} + authoritative = &wrapperspb.BoolValue{Value: lua.LVAsBool(v)} } // Parse label filter. - var label *wrappers.StringValue + var label *wrapperspb.StringValue if v := l.Get(3); v.Type() != lua.LTNil { if v.Type() != lua.LTString { l.ArgError(3, "expects label string or nil") return 0 } - label = &wrappers.StringValue{Value: lua.LVAsString(v)} + label = &wrapperspb.StringValue{Value: lua.LVAsString(v)} } // Parse minimum size filter. - var minSize *wrappers.Int32Value + var minSize *wrapperspb.Int32Value if v := l.Get(4); v.Type() != lua.LTNil { if v.Type() != lua.LTNumber { l.ArgError(4, "expects minimum size number or nil") return 0 } - minSize = &wrappers.Int32Value{Value: int32(lua.LVAsNumber(v))} + minSize = &wrapperspb.Int32Value{Value: int32(lua.LVAsNumber(v))} } // Parse maximum size filter. - var maxSize *wrappers.Int32Value + var maxSize *wrapperspb.Int32Value if v := l.Get(5); v.Type() != lua.LTNil { if v.Type() != lua.LTNumber { l.ArgError(5, "expects maximum size number or nil") return 0 } - maxSize = &wrappers.Int32Value{Value: int32(lua.LVAsNumber(v))} + maxSize = &wrapperspb.Int32Value{Value: int32(lua.LVAsNumber(v))} } - var query *wrappers.StringValue + var query *wrapperspb.StringValue if v := l.Get(6); v.Type() != lua.LTNil { if v.Type() != lua.LTString { l.ArgError(6, "expects query string or nil") return 0 } - query = &wrappers.StringValue{Value: lua.LVAsString(v)} + query = &wrapperspb.StringValue{Value: lua.LVAsString(v)} } results, err := n.matchRegistry.ListMatches(l.Context(), limit, authoritative, label, minSize, maxSize, query) @@ -3994,7 +3994,7 @@ func (n *RuntimeLuaNakamaModule) notificationSend(l *lua.LState) int { Code: int32(code), SenderId: senderID, Persistent: persistent, - CreateTime: ×tamp.Timestamp{Seconds: time.Now().UTC().Unix()}, + CreateTime: ×tamppb.Timestamp{Seconds: time.Now().UTC().Unix()}, }} notifications := map[uuid.UUID][]*api.Notification{ userID: nots, @@ -4138,7 +4138,7 @@ func (n *RuntimeLuaNakamaModule) notificationsSend(l *lua.LState) int { } notification.Id = uuid.Must(uuid.NewV4()).String() - notification.CreateTime = ×tamp.Timestamp{Seconds: time.Now().UTC().Unix()} + notification.CreateTime = ×tamppb.Timestamp{Seconds: time.Now().UTC().Unix()} notification.SenderId = senderID.String() no := notifications[userID] @@ -4743,14 +4743,14 @@ func (n *RuntimeLuaNakamaModule) storageWrite(l *lua.LState) int { l.ArgError(1, "expects permission_read to be number") return } - d.PermissionRead = &wrappers.Int32Value{Value: int32(v.(lua.LNumber))} + d.PermissionRead = &wrapperspb.Int32Value{Value: int32(v.(lua.LNumber))} case "permission_write": if v.Type() != lua.LTNumber { conversionError = true l.ArgError(1, "expects permission_write to be number") return } - d.PermissionWrite = &wrappers.Int32Value{Value: int32(v.(lua.LNumber))} + d.PermissionWrite = &wrapperspb.Int32Value{Value: int32(v.(lua.LNumber))} } }) @@ -4774,11 +4774,11 @@ func (n *RuntimeLuaNakamaModule) storageWrite(l *lua.LState) int { if d.PermissionRead == nil { // Default to owner read if no permission_read is supplied. - d.PermissionRead = &wrappers.Int32Value{Value: 1} + d.PermissionRead = &wrapperspb.Int32Value{Value: 1} } if d.PermissionWrite == nil { // Default to owner write if no permission_write is supplied. - d.PermissionWrite = &wrappers.Int32Value{Value: 1} + d.PermissionWrite = &wrapperspb.Int32Value{Value: 1} } ops = append(ops, &StorageOpWrite{ @@ -4982,7 +4982,7 @@ func (n *RuntimeLuaNakamaModule) multiUpdate(l *lua.LState) int { l.ArgError(1, fmt.Sprintf("error encoding metadata: %s", err.Error())) return } - update.metadata = &wrappers.StringValue{Value: string(metadataBytes)} + update.metadata = &wrapperspb.StringValue{Value: string(metadataBytes)} case "username": if v.Type() != lua.LTString { conversionError = true @@ -4996,35 +4996,35 @@ func (n *RuntimeLuaNakamaModule) multiUpdate(l *lua.LState) int { l.ArgError(1, "expects display name to be string") return } - update.displayName = &wrappers.StringValue{Value: v.String()} + update.displayName = &wrapperspb.StringValue{Value: v.String()} case "timezone": if v.Type() != lua.LTString { conversionError = true l.ArgError(1, "expects timezone to be string") return } - update.timezone = &wrappers.StringValue{Value: v.String()} + update.timezone = &wrapperspb.StringValue{Value: v.String()} case "location": if v.Type() != lua.LTString { conversionError = true l.ArgError(1, "expects location to be string") return } - update.location = &wrappers.StringValue{Value: v.String()} + update.location = &wrapperspb.StringValue{Value: v.String()} case "lang_tag": if v.Type() != lua.LTString { conversionError = true l.ArgError(1, "expects lang tag to be string") return } - update.langTag = &wrappers.StringValue{Value: v.String()} + update.langTag = &wrapperspb.StringValue{Value: v.String()} case "avatar_url": if v.Type() != lua.LTString { conversionError = true l.ArgError(1, "expects avatar url to be string") return } - update.avatarURL = &wrappers.StringValue{Value: v.String()} + update.avatarURL = &wrapperspb.StringValue{Value: v.String()} } }) if conversionError { @@ -5136,14 +5136,14 @@ func (n *RuntimeLuaNakamaModule) multiUpdate(l *lua.LState) int { l.ArgError(2, "expects permission_read to be number") return } - d.PermissionRead = &wrappers.Int32Value{Value: int32(v.(lua.LNumber))} + d.PermissionRead = &wrapperspb.Int32Value{Value: int32(v.(lua.LNumber))} case "permission_write": if v.Type() != lua.LTNumber { conversionError = true l.ArgError(2, "expects permission_write to be number") return } - d.PermissionWrite = &wrappers.Int32Value{Value: int32(v.(lua.LNumber))} + d.PermissionWrite = &wrapperspb.Int32Value{Value: int32(v.(lua.LNumber))} } }) @@ -5167,11 +5167,11 @@ func (n *RuntimeLuaNakamaModule) multiUpdate(l *lua.LState) int { if d.PermissionRead == nil { // Default to owner read if no permission_read is supplied. - d.PermissionRead = &wrappers.Int32Value{Value: 1} + d.PermissionRead = &wrapperspb.Int32Value{Value: 1} } if d.PermissionWrite == nil { // Default to owner write if no permission_write is supplied. - d.PermissionWrite = &wrappers.Int32Value{Value: 1} + d.PermissionWrite = &wrapperspb.Int32Value{Value: 1} } storageWriteOps = append(storageWriteOps, &StorageOpWrite{ @@ -5456,9 +5456,9 @@ func (n *RuntimeLuaNakamaModule) leaderboardRecordsList(l *lua.LState) int { l.ArgError(3, "expects limit to be 0-10000") return 0 } - var limit *wrappers.Int32Value + var limit *wrapperspb.Int32Value if limitNumber != 0 { - limit = &wrappers.Int32Value{Value: int32(limitNumber)} + limit = &wrapperspb.Int32Value{Value: int32(limitNumber)} } cursor := l.OptString(4, "") @@ -6027,9 +6027,9 @@ func (n *RuntimeLuaNakamaModule) tournamentRecordsList(l *lua.LState) int { l.ArgError(3, "expects limit to be 0-10000") return 0 } - var limit *wrappers.Int32Value + var limit *wrapperspb.Int32Value if limitNumber != 0 { - limit = &wrappers.Int32Value{Value: int32(limitNumber)} + limit = &wrapperspb.Int32Value{Value: int32(limitNumber)} } cursor := l.OptString(4, "") @@ -6538,9 +6538,9 @@ func (n *RuntimeLuaNakamaModule) groupUpdate(l *lua.LState) int { } nameStr := l.OptString(2, "") - var name *wrappers.StringValue + var name *wrapperspb.StringValue if nameStr != "" { - name = &wrappers.StringValue{Value: nameStr} + name = &wrapperspb.StringValue{Value: nameStr} } creatorIDStr := l.OptString(3, "") @@ -6555,31 +6555,31 @@ func (n *RuntimeLuaNakamaModule) groupUpdate(l *lua.LState) int { } langStr := l.OptString(4, "") - var lang *wrappers.StringValue + var lang *wrapperspb.StringValue if langStr != "" { - lang = &wrappers.StringValue{Value: langStr} + lang = &wrapperspb.StringValue{Value: langStr} } descStr := l.OptString(5, "") - var desc *wrappers.StringValue + var desc *wrapperspb.StringValue if descStr != "" { - desc = &wrappers.StringValue{Value: descStr} + desc = &wrapperspb.StringValue{Value: descStr} } avatarURLStr := l.OptString(6, "") - var avatarURL *wrappers.StringValue + var avatarURL *wrapperspb.StringValue if avatarURLStr != "" { - avatarURL = &wrappers.StringValue{Value: avatarURLStr} + avatarURL = &wrapperspb.StringValue{Value: avatarURLStr} } openV := l.Get(7) - var open *wrappers.BoolValue + var open *wrapperspb.BoolValue if openV != lua.LNil { - open = &wrappers.BoolValue{Value: l.OptBool(7, false)} + open = &wrapperspb.BoolValue{Value: l.OptBool(7, false)} } metadataTable := l.OptTable(8, nil) - var metadata *wrappers.StringValue + var metadata *wrapperspb.StringValue if metadataTable != nil { metadataMap := RuntimeLuaConvertLuaTable(metadataTable) metadataBytes, err := json.Marshal(metadataMap) @@ -6587,7 +6587,7 @@ func (n *RuntimeLuaNakamaModule) groupUpdate(l *lua.LState) int { l.RaiseError("error encoding metadata: %v", err.Error()) return 0 } - metadata = &wrappers.StringValue{Value: string(metadataBytes)} + metadata = &wrapperspb.StringValue{Value: string(metadataBytes)} } maxCountInt := l.OptInt(9, 0) @@ -6876,13 +6876,13 @@ func (n *RuntimeLuaNakamaModule) groupUsersList(l *lua.LState) int { } state := l.OptInt(3, -1) - var stateWrapper *wrappers.Int32Value + var stateWrapper *wrapperspb.Int32Value if state != -1 { if state < 0 || state > 4 { l.ArgError(3, "expects state to be 0-4") return 0 } - stateWrapper = &wrappers.Int32Value{Value: int32(state)} + stateWrapper = &wrapperspb.Int32Value{Value: int32(state)} } cursor := l.OptString(4, "") @@ -6967,13 +6967,13 @@ func (n *RuntimeLuaNakamaModule) userGroupsList(l *lua.LState) int { } state := l.OptInt(3, -1) - var stateWrapper *wrappers.Int32Value + var stateWrapper *wrapperspb.Int32Value if state != -1 { if state < 0 || state > 4 { l.ArgError(3, "expects state to be 0-4") return 0 } - stateWrapper = &wrappers.Int32Value{Value: int32(state)} + stateWrapper = &wrapperspb.Int32Value{Value: int32(state)} } cursor := l.OptString(4, "") @@ -7034,7 +7034,7 @@ func (n *RuntimeLuaNakamaModule) accountUpdateId(l *lua.LState) int { } metadataTable := l.OptTable(2, nil) - var metadata *wrappers.StringValue + var metadata *wrapperspb.StringValue if metadataTable != nil { metadataMap := RuntimeLuaConvertLuaTable(metadataTable) metadataBytes, err := json.Marshal(metadataMap) @@ -7042,39 +7042,39 @@ func (n *RuntimeLuaNakamaModule) accountUpdateId(l *lua.LState) int { l.RaiseError("error encoding metadata: %v", err.Error()) return 0 } - metadata = &wrappers.StringValue{Value: string(metadataBytes)} + metadata = &wrapperspb.StringValue{Value: string(metadataBytes)} } username := l.OptString(3, "") displayNameL := l.Get(4) - var displayName *wrappers.StringValue + var displayName *wrapperspb.StringValue if displayNameL != lua.LNil { - displayName = &wrappers.StringValue{Value: l.OptString(4, "")} + displayName = &wrapperspb.StringValue{Value: l.OptString(4, "")} } timezoneL := l.Get(5) - var timezone *wrappers.StringValue + var timezone *wrapperspb.StringValue if timezoneL != lua.LNil { - timezone = &wrappers.StringValue{Value: l.OptString(5, "")} + timezone = &wrapperspb.StringValue{Value: l.OptString(5, "")} } locationL := l.Get(6) - var location *wrappers.StringValue + var location *wrapperspb.StringValue if locationL != lua.LNil { - location = &wrappers.StringValue{Value: l.OptString(6, "")} + location = &wrapperspb.StringValue{Value: l.OptString(6, "")} } langL := l.Get(7) - var lang *wrappers.StringValue + var lang *wrapperspb.StringValue if langL != lua.LNil { - lang = &wrappers.StringValue{Value: l.OptString(7, "")} + lang = &wrapperspb.StringValue{Value: l.OptString(7, "")} } avatarL := l.Get(8) - var avatar *wrappers.StringValue + var avatar *wrapperspb.StringValue if avatarL != lua.LNil { - avatar = &wrappers.StringValue{Value: l.OptString(8, "")} + avatar = &wrapperspb.StringValue{Value: l.OptString(8, "")} } if err = UpdateAccounts(l.Context(), n.logger, n.db, []*accountUpdate{{ @@ -7122,7 +7122,7 @@ func (n *RuntimeLuaNakamaModule) accountExportId(l *lua.LState) int { return 0 } - exportString, err := n.jsonpbMarshaler.MarshalToString(export) + exportString, err := n.protojsonMarshaler.Marshal(export) if err != nil { l.RaiseError("error encoding account export: %v", err.Error()) return 0 @@ -7146,13 +7146,13 @@ func (n *RuntimeLuaNakamaModule) friendsList(l *lua.LState) int { } state := l.OptInt(3, -1) - var stateWrapper *wrappers.Int32Value + var stateWrapper *wrapperspb.Int32Value if state != -1 { if state < 0 || state > 3 { l.ArgError(3, "expects state to be 0-3") return 0 } - stateWrapper = &wrappers.Int32Value{Value: int32(state)} + stateWrapper = &wrapperspb.Int32Value{Value: int32(state)} } cursor := l.OptString(4, "") diff --git a/server/runtime_test.go b/server/runtime_test.go index dac77f24c6170969023a5a0c3163e8c68f26872a..dab7d06fc61e051c3ae28f083157b1c1d80cc879 100644 --- a/server/runtime_test.go +++ b/server/runtime_test.go @@ -27,10 +27,10 @@ import ( "fmt" "github.com/gofrs/uuid" - "github.com/golang/protobuf/ptypes/empty" "github.com/heroiclabs/nakama-common/api" "github.com/heroiclabs/nakama-common/rtapi" "golang.org/x/crypto/bcrypt" + "google.golang.org/protobuf/types/known/emptypb" ) const ( @@ -77,7 +77,7 @@ func runtimeWithModules(t *testing.T, modules map[string]string) (*Runtime, *Run cfg := NewConfig(logger) cfg.Runtime.Path = dir - return NewRuntime(logger, logger, NewDB(t), jsonpbMarshaler, jsonpbUnmarshaler, cfg, nil, nil, nil, nil, nil, nil, nil, nil, metrics, nil, &DummyMessageRouter{}) + return NewRuntime(logger, logger, NewDB(t), protojsonMarshaler, protojsonUnmarshaler, cfg, nil, nil, nil, nil, nil, nil, nil, nil, metrics, nil, &DummyMessageRouter{}) } func TestRuntimeSampleScript(t *testing.T) { @@ -354,8 +354,8 @@ nakama.register_rpc(test.printWorld, "helloworld")`, } db := NewDB(t) - pipeline := NewPipeline(logger, cfg, db, jsonpbMarshaler, jsonpbUnmarshaler, nil, nil, nil, nil, nil, nil, nil, runtime) - apiServer := StartApiServer(logger, logger, db, jsonpbMarshaler, jsonpbUnmarshaler, cfg, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, metrics, pipeline, runtime) + pipeline := NewPipeline(logger, cfg, db, protojsonMarshaler, protojsonUnmarshaler, nil, nil, nil, nil, nil, nil, nil, runtime) + apiServer := StartApiServer(logger, logger, db, protojsonMarshaler, protojsonUnmarshaler, cfg, nil, nil, nil, nil, nil, nil, nil, nil, nil, nil, metrics, pipeline, runtime) defer apiServer.Stop() payload := "\"Hello World\"" @@ -848,7 +848,7 @@ nakama.register_req_after(after_storage_write, "WriteStorageObjects")`, t.Fatal("Invocation failed. Return result not expected: ", len(acks.Acks)) } - account, err := client.GetAccount(ctx, &empty.Empty{}) + account, err := client.GetAccount(ctx, &emptypb.Empty{}) if err != nil { t.Fatal(err) } @@ -897,7 +897,7 @@ nakama.register_rt_before(before_match_create, "MatchCreate")`, pipeline.ProcessRequest(logger, session, envelope) - account, err := client.GetAccount(ctx, &empty.Empty{}) + account, err := client.GetAccount(ctx, &emptypb.Empty{}) if err != nil { t.Fatal(err) } @@ -951,7 +951,7 @@ nakama.register_rt_after(after_match_create, "MatchCreate")`, pipeline.ProcessRequest(logger, session, envelope) - account, err := client.GetAccount(ctx, &empty.Empty{}) + account, err := client.GetAccount(ctx, &emptypb.Empty{}) if err != nil { t.Fatal(err) } diff --git a/server/session_ws.go b/server/session_ws.go index 19c2aa2344584e8d094e3a4ada17d7a8d19285da..805b59199a20f735d88ee7fb4b1cd268f4bd490a 100644 --- a/server/session_ws.go +++ b/server/session_ws.go @@ -15,24 +15,23 @@ package server import ( - "bytes" "context" "errors" "fmt" "sync" "time" - "github.com/golang/protobuf/proto" + "google.golang.org/protobuf/proto" "net" "github.com/gofrs/uuid" - "github.com/golang/protobuf/jsonpb" "github.com/gorilla/websocket" "github.com/heroiclabs/nakama-common/rtapi" "github.com/heroiclabs/nakama-common/runtime" "go.uber.org/atomic" "go.uber.org/zap" + "google.golang.org/protobuf/encoding/protojson" ) var ErrSessionQueueFull = errors.New("session outgoing queue full") @@ -53,12 +52,12 @@ type sessionWS struct { ctx context.Context ctxCancelFn context.CancelFunc - jsonpbMarshaler *jsonpb.Marshaler - jsonpbUnmarshaler *jsonpb.Unmarshaler - wsMessageType int - pingPeriodDuration time.Duration - pongWaitDuration time.Duration - writeWaitDuration time.Duration + protojsonMarshaler *protojson.MarshalOptions + protojsonUnmarshaler *protojson.UnmarshalOptions + wsMessageType int + pingPeriodDuration time.Duration + pongWaitDuration time.Duration + writeWaitDuration time.Duration sessionRegistry SessionRegistry statusRegistry *StatusRegistry @@ -76,7 +75,7 @@ type sessionWS struct { outgoingCh chan []byte } -func NewSessionWS(logger *zap.Logger, config Config, format SessionFormat, sessionID, userID uuid.UUID, username string, vars map[string]string, expiry int64, clientIP string, clientPort string, jsonpbMarshaler *jsonpb.Marshaler, jsonpbUnmarshaler *jsonpb.Unmarshaler, conn *websocket.Conn, sessionRegistry SessionRegistry, statusRegistry *StatusRegistry, matchmaker Matchmaker, tracker Tracker, metrics *Metrics, pipeline *Pipeline, runtime *Runtime) Session { +func NewSessionWS(logger *zap.Logger, config Config, format SessionFormat, sessionID, userID uuid.UUID, username string, vars map[string]string, expiry int64, clientIP string, clientPort string, protojsonMarshaler *protojson.MarshalOptions, protojsonUnmarshaler *protojson.UnmarshalOptions, conn *websocket.Conn, sessionRegistry SessionRegistry, statusRegistry *StatusRegistry, matchmaker Matchmaker, tracker Tracker, metrics *Metrics, pipeline *Pipeline, runtime *Runtime) Session { sessionLogger := logger.With(zap.String("uid", userID.String()), zap.String("sid", sessionID.String())) sessionLogger.Info("New WebSocket session connected", zap.Uint8("format", uint8(format))) @@ -103,12 +102,12 @@ func NewSessionWS(logger *zap.Logger, config Config, format SessionFormat, sessi ctx: ctx, ctxCancelFn: ctxCancelFn, - jsonpbMarshaler: jsonpbMarshaler, - jsonpbUnmarshaler: jsonpbUnmarshaler, - wsMessageType: wsMessageType, - pingPeriodDuration: time.Duration(config.GetSocket().PingPeriodMs) * time.Millisecond, - pongWaitDuration: time.Duration(config.GetSocket().PongWaitMs) * time.Millisecond, - writeWaitDuration: time.Duration(config.GetSocket().WriteWaitMs) * time.Millisecond, + protojsonMarshaler: protojsonMarshaler, + protojsonUnmarshaler: protojsonUnmarshaler, + wsMessageType: wsMessageType, + pingPeriodDuration: time.Duration(config.GetSocket().PingPeriodMs) * time.Millisecond, + pongWaitDuration: time.Duration(config.GetSocket().PongWaitMs) * time.Millisecond, + writeWaitDuration: time.Duration(config.GetSocket().WriteWaitMs) * time.Millisecond, sessionRegistry: sessionRegistry, statusRegistry: statusRegistry, @@ -229,7 +228,7 @@ IncomingLoop: case SessionFormatJson: fallthrough default: - err = s.jsonpbUnmarshaler.Unmarshal(bytes.NewReader(data), request) + err = s.protojsonUnmarshaler.Unmarshal(data, request) } if err != nil { // If the payload is malformed the client is incompatible or misbehaving, either way disconnect it now. @@ -375,9 +374,8 @@ func (s *sessionWS) Send(envelope *rtapi.Envelope, reliable bool) error { case SessionFormatJson: fallthrough default: - var buf bytes.Buffer - if err = s.jsonpbMarshaler.Marshal(&buf, envelope); err == nil { - payload = buf.Bytes() + if buf, err := s.protojsonMarshaler.Marshal(envelope); err == nil { + payload = buf } } if err != nil { diff --git a/server/socket_ws.go b/server/socket_ws.go index 4f6400510e062f135252b3fc6b64aae6ac9650ed..e718a835bc3358acade1864a4d2f5ee7bdc6679a 100644 --- a/server/socket_ws.go +++ b/server/socket_ws.go @@ -20,12 +20,12 @@ import ( "strconv" "github.com/gofrs/uuid" - "github.com/golang/protobuf/jsonpb" "github.com/gorilla/websocket" "go.uber.org/zap" + "google.golang.org/protobuf/encoding/protojson" ) -func NewSocketWsAcceptor(logger *zap.Logger, config Config, sessionRegistry SessionRegistry, sessionCache SessionCache, statusRegistry *StatusRegistry, matchmaker Matchmaker, tracker Tracker, metrics *Metrics, runtime *Runtime, jsonpbMarshaler *jsonpb.Marshaler, jsonpbUnmarshaler *jsonpb.Unmarshaler, pipeline *Pipeline) func(http.ResponseWriter, *http.Request) { +func NewSocketWsAcceptor(logger *zap.Logger, config Config, sessionRegistry SessionRegistry, sessionCache SessionCache, statusRegistry *StatusRegistry, matchmaker Matchmaker, tracker Tracker, metrics *Metrics, runtime *Runtime, protojsonMarshaler *protojson.MarshalOptions, protojsonUnmarshaler *protojson.UnmarshalOptions, pipeline *Pipeline) func(http.ResponseWriter, *http.Request) { upgrader := &websocket.Upgrader{ ReadBufferSize: config.GetSocket().ReadBufferSizeBytes, WriteBufferSize: config.GetSocket().WriteBufferSizeBytes, @@ -82,7 +82,7 @@ func NewSocketWsAcceptor(logger *zap.Logger, config Config, sessionRegistry Sess metrics.CountWebsocketOpened(1) // Wrap the connection for application handling. - session := NewSessionWS(logger, config, format, sessionID, userID, username, vars, expiry, clientIP, clientPort, jsonpbMarshaler, jsonpbUnmarshaler, conn, sessionRegistry, statusRegistry, matchmaker, tracker, metrics, pipeline, runtime) + session := NewSessionWS(logger, config, format, sessionID, userID, username, vars, expiry, clientIP, clientPort, protojsonMarshaler, protojsonUnmarshaler, conn, sessionRegistry, statusRegistry, matchmaker, tracker, metrics, pipeline, runtime) // Add to the session registry. sessionRegistry.Add(session) diff --git a/server/status_registry.go b/server/status_registry.go index 26921928deaa14be4da48e79e266246953b5715d..fd5ba21412895a64719bffb31a11aeeb31729a06 100644 --- a/server/status_registry.go +++ b/server/status_registry.go @@ -15,15 +15,14 @@ package server import ( - "bytes" "context" "sync" "github.com/gofrs/uuid" - "github.com/golang/protobuf/jsonpb" - "github.com/golang/protobuf/proto" "github.com/heroiclabs/nakama-common/rtapi" "go.uber.org/zap" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" ) type statusEvent struct { @@ -34,9 +33,9 @@ type statusEvent struct { type StatusRegistry struct { sync.RWMutex - logger *zap.Logger - sessionRegistry SessionRegistry - jsonpbMarshaler *jsonpb.Marshaler + logger *zap.Logger + sessionRegistry SessionRegistry + protojsonMarshaler *protojson.MarshalOptions ctx context.Context ctxCancelFn context.CancelFunc @@ -46,13 +45,13 @@ type StatusRegistry struct { byUser map[uuid.UUID]map[uuid.UUID]struct{} } -func NewStatusRegistry(logger *zap.Logger, config Config, sessionRegistry SessionRegistry, jsonpbMarshaler *jsonpb.Marshaler) *StatusRegistry { +func NewStatusRegistry(logger *zap.Logger, config Config, sessionRegistry SessionRegistry, protojsonMarshaler *protojson.MarshalOptions) *StatusRegistry { ctx, ctxCancelFn := context.WithCancel(context.Background()) s := &StatusRegistry{ - logger: logger, - sessionRegistry: sessionRegistry, - jsonpbMarshaler: jsonpbMarshaler, + logger: logger, + sessionRegistry: sessionRegistry, + protojsonMarshaler: protojsonMarshaler, ctx: ctx, ctxCancelFn: ctxCancelFn, @@ -113,9 +112,8 @@ func NewStatusRegistry(logger *zap.Logger, config Config, sessionRegistry Sessio default: if payloadJSON == nil { // Marshal the payload now that we know this format is needed. - var buf bytes.Buffer - if err = s.jsonpbMarshaler.Marshal(&buf, envelope); err == nil { - payloadJSON = buf.Bytes() + if buf, err := s.protojsonMarshaler.Marshal(envelope); err == nil { + payloadJSON = buf } else { s.logger.Error("Could not marshal status event", zap.Error(err)) return diff --git a/server/tracker.go b/server/tracker.go index 784800995e81e29bb6b773f20ef097a2143cf546..d1a7f50470b35e71ecee4d85a450c41350497978 100644 --- a/server/tracker.go +++ b/server/tracker.go @@ -15,21 +15,20 @@ package server import ( - "bytes" "context" "fmt" + "google.golang.org/protobuf/types/known/wrapperspb" "sync" syncAtomic "sync/atomic" "time" "github.com/gofrs/uuid" - "github.com/golang/protobuf/jsonpb" - "github.com/golang/protobuf/proto" - "github.com/golang/protobuf/ptypes/wrappers" "github.com/heroiclabs/nakama-common/rtapi" "github.com/heroiclabs/nakama-common/runtime" "go.uber.org/atomic" "go.uber.org/zap" + "google.golang.org/protobuf/encoding/protojson" + "google.golang.org/protobuf/proto" ) const ( @@ -183,7 +182,7 @@ type LocalTracker struct { sessionRegistry SessionRegistry statusRegistry *StatusRegistry metrics *Metrics - jsonpbMarshaler *jsonpb.Marshaler + protojsonMarshaler *protojson.MarshalOptions name string eventsCh chan *PresenceEvent presencesByStream map[uint8]map[PresenceStream]map[presenceCompact]*Presence @@ -194,7 +193,7 @@ type LocalTracker struct { ctxCancelFn context.CancelFunc } -func StartLocalTracker(logger *zap.Logger, config Config, sessionRegistry SessionRegistry, statusRegistry *StatusRegistry, metrics *Metrics, jsonpbMarshaler *jsonpb.Marshaler) Tracker { +func StartLocalTracker(logger *zap.Logger, config Config, sessionRegistry SessionRegistry, statusRegistry *StatusRegistry, metrics *Metrics, protojsonMarshaler *protojson.MarshalOptions) Tracker { ctx, ctxCancelFn := context.WithCancel(context.Background()) t := &LocalTracker{ @@ -202,7 +201,7 @@ func StartLocalTracker(logger *zap.Logger, config Config, sessionRegistry Sessio sessionRegistry: sessionRegistry, statusRegistry: statusRegistry, metrics: metrics, - jsonpbMarshaler: jsonpbMarshaler, + protojsonMarshaler: protojsonMarshaler, name: config.GetName(), eventsCh: make(chan *PresenceEvent, config.GetTracker().EventQueueSize), presencesByStream: make(map[uint8]map[PresenceStream]map[presenceCompact]*Presence), @@ -824,7 +823,7 @@ func (t *LocalTracker) queueEvent(joins, leaves []*Presence) { case <-t.eventsCh: // Discard the event. default: - // Queue is now empty. + // Queue is now emptypb. return } } @@ -856,7 +855,7 @@ func (t *LocalTracker) processEvent(e *PresenceEvent) { } if p.Stream.Mode == StreamModeStatus { // Status field is only populated for status stream presences. - pWire.Status = &wrappers.StringValue{Value: p.Meta.Status} + pWire.Status = &wrapperspb.StringValue{Value: p.Meta.Status} } if j, ok := streamJoins[p.Stream]; ok { streamJoins[p.Stream] = append(j, pWire) @@ -899,7 +898,7 @@ func (t *LocalTracker) processEvent(e *PresenceEvent) { } if p.Stream.Mode == StreamModeStatus { // Status field is only populated for status stream presences. - pWire.Status = &wrappers.StringValue{Value: p.Meta.Status} + pWire.Status = &wrapperspb.StringValue{Value: p.Meta.Status} } if l, ok := streamLeaves[p.Stream]; ok { streamLeaves[p.Stream] = append(l, pWire) @@ -1074,9 +1073,8 @@ func (t *LocalTracker) processEvent(e *PresenceEvent) { default: if payloadJSON == nil { // Marshal the payload now that we know this format is needed. - var buf bytes.Buffer - if err = t.jsonpbMarshaler.Marshal(&buf, envelope); err == nil { - payloadJSON = buf.Bytes() + if buf, err := t.protojsonMarshaler.Marshal(envelope); err == nil { + payloadJSON = buf } else { t.logger.Error("Could not marshal presence event", zap.Error(err)) return @@ -1209,9 +1207,8 @@ func (t *LocalTracker) processEvent(e *PresenceEvent) { default: if payloadJSON == nil { // Marshal the payload now that we know this format is needed. - var buf bytes.Buffer - if err = t.jsonpbMarshaler.Marshal(&buf, envelope); err == nil { - payloadJSON = buf.Bytes() + if buf, err := t.protojsonMarshaler.Marshal(envelope); err == nil { + payloadJSON = buf } else { t.logger.Error("Could not marshal presence event", zap.Error(err)) return diff --git a/vendor/github.com/golang/protobuf/internal/gengogrpc/grpc.go b/vendor/github.com/golang/protobuf/internal/gengogrpc/grpc.go deleted file mode 100644 index fd2f51d890119559598e607d4b6e69a75403a20b..0000000000000000000000000000000000000000 --- a/vendor/github.com/golang/protobuf/internal/gengogrpc/grpc.go +++ /dev/null @@ -1,398 +0,0 @@ -// Copyright 2018 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package gengogrpc contains the gRPC code generator. -package gengogrpc - -import ( - "fmt" - "strconv" - "strings" - - "google.golang.org/protobuf/compiler/protogen" - - "google.golang.org/protobuf/types/descriptorpb" -) - -const ( - contextPackage = protogen.GoImportPath("context") - grpcPackage = protogen.GoImportPath("google.golang.org/grpc") - codesPackage = protogen.GoImportPath("google.golang.org/grpc/codes") - statusPackage = protogen.GoImportPath("google.golang.org/grpc/status") -) - -// GenerateFile generates a _grpc.pb.go file containing gRPC service definitions. -func GenerateFile(gen *protogen.Plugin, file *protogen.File) *protogen.GeneratedFile { - if len(file.Services) == 0 { - return nil - } - filename := file.GeneratedFilenamePrefix + "_grpc.pb.go" - g := gen.NewGeneratedFile(filename, file.GoImportPath) - g.P("// Code generated by protoc-gen-go-grpc. DO NOT EDIT.") - g.P() - g.P("package ", file.GoPackageName) - g.P() - GenerateFileContent(gen, file, g) - return g -} - -// GenerateFileContent generates the gRPC service definitions, excluding the package statement. -func GenerateFileContent(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile) { - if len(file.Services) == 0 { - return - } - - // TODO: Remove this. We don't need to include these references any more. - g.P("// Reference imports to suppress errors if they are not otherwise used.") - g.P("var _ ", contextPackage.Ident("Context")) - g.P("var _ ", grpcPackage.Ident("ClientConnInterface")) - g.P() - - g.P("// This is a compile-time assertion to ensure that this generated file") - g.P("// is compatible with the grpc package it is being compiled against.") - g.P("const _ = ", grpcPackage.Ident("SupportPackageIsVersion6")) - g.P() - for _, service := range file.Services { - genService(gen, file, g, service) - } -} - -func genService(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, service *protogen.Service) { - clientName := service.GoName + "Client" - - g.P("// ", clientName, " is the client API for ", service.GoName, " service.") - g.P("//") - g.P("// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://godoc.org/google.golang.org/grpc#ClientConn.NewStream.") - - // Client interface. - if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() { - g.P("//") - g.P(deprecationComment) - } - g.Annotate(clientName, service.Location) - g.P("type ", clientName, " interface {") - for _, method := range service.Methods { - g.Annotate(clientName+"."+method.GoName, method.Location) - if method.Desc.Options().(*descriptorpb.MethodOptions).GetDeprecated() { - g.P(deprecationComment) - } - g.P(method.Comments.Leading, - clientSignature(g, method)) - } - g.P("}") - g.P() - - // Client structure. - g.P("type ", unexport(clientName), " struct {") - g.P("cc ", grpcPackage.Ident("ClientConnInterface")) - g.P("}") - g.P() - - // NewClient factory. - if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() { - g.P(deprecationComment) - } - g.P("func New", clientName, " (cc ", grpcPackage.Ident("ClientConnInterface"), ") ", clientName, " {") - g.P("return &", unexport(clientName), "{cc}") - g.P("}") - g.P() - - var methodIndex, streamIndex int - // Client method implementations. - for _, method := range service.Methods { - if !method.Desc.IsStreamingServer() && !method.Desc.IsStreamingClient() { - // Unary RPC method - genClientMethod(gen, file, g, method, methodIndex) - methodIndex++ - } else { - // Streaming RPC method - genClientMethod(gen, file, g, method, streamIndex) - streamIndex++ - } - } - - // Server interface. - serverType := service.GoName + "Server" - g.P("// ", serverType, " is the server API for ", service.GoName, " service.") - if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() { - g.P("//") - g.P(deprecationComment) - } - g.Annotate(serverType, service.Location) - g.P("type ", serverType, " interface {") - for _, method := range service.Methods { - g.Annotate(serverType+"."+method.GoName, method.Location) - if method.Desc.Options().(*descriptorpb.MethodOptions).GetDeprecated() { - g.P(deprecationComment) - } - g.P(method.Comments.Leading, - serverSignature(g, method)) - } - g.P("}") - g.P() - - // Server Unimplemented struct for forward compatibility. - g.P("// Unimplemented", serverType, " can be embedded to have forward compatible implementations.") - g.P("type Unimplemented", serverType, " struct {") - g.P("}") - g.P() - for _, method := range service.Methods { - nilArg := "" - if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() { - nilArg = "nil," - } - g.P("func (*Unimplemented", serverType, ") ", serverSignature(g, method), "{") - g.P("return ", nilArg, statusPackage.Ident("Errorf"), "(", codesPackage.Ident("Unimplemented"), `, "method `, method.GoName, ` not implemented")`) - g.P("}") - } - g.P() - - // Server registration. - if service.Desc.Options().(*descriptorpb.ServiceOptions).GetDeprecated() { - g.P(deprecationComment) - } - serviceDescVar := "_" + service.GoName + "_serviceDesc" - g.P("func Register", service.GoName, "Server(s *", grpcPackage.Ident("Server"), ", srv ", serverType, ") {") - g.P("s.RegisterService(&", serviceDescVar, `, srv)`) - g.P("}") - g.P() - - // Server handler implementations. - var handlerNames []string - for _, method := range service.Methods { - hname := genServerMethod(gen, file, g, method) - handlerNames = append(handlerNames, hname) - } - - // Service descriptor. - g.P("var ", serviceDescVar, " = ", grpcPackage.Ident("ServiceDesc"), " {") - g.P("ServiceName: ", strconv.Quote(string(service.Desc.FullName())), ",") - g.P("HandlerType: (*", serverType, ")(nil),") - g.P("Methods: []", grpcPackage.Ident("MethodDesc"), "{") - for i, method := range service.Methods { - if method.Desc.IsStreamingClient() || method.Desc.IsStreamingServer() { - continue - } - g.P("{") - g.P("MethodName: ", strconv.Quote(string(method.Desc.Name())), ",") - g.P("Handler: ", handlerNames[i], ",") - g.P("},") - } - g.P("},") - g.P("Streams: []", grpcPackage.Ident("StreamDesc"), "{") - for i, method := range service.Methods { - if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() { - continue - } - g.P("{") - g.P("StreamName: ", strconv.Quote(string(method.Desc.Name())), ",") - g.P("Handler: ", handlerNames[i], ",") - if method.Desc.IsStreamingServer() { - g.P("ServerStreams: true,") - } - if method.Desc.IsStreamingClient() { - g.P("ClientStreams: true,") - } - g.P("},") - } - g.P("},") - g.P("Metadata: \"", file.Desc.Path(), "\",") - g.P("}") - g.P() -} - -func clientSignature(g *protogen.GeneratedFile, method *protogen.Method) string { - s := method.GoName + "(ctx " + g.QualifiedGoIdent(contextPackage.Ident("Context")) - if !method.Desc.IsStreamingClient() { - s += ", in *" + g.QualifiedGoIdent(method.Input.GoIdent) - } - s += ", opts ..." + g.QualifiedGoIdent(grpcPackage.Ident("CallOption")) + ") (" - if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() { - s += "*" + g.QualifiedGoIdent(method.Output.GoIdent) - } else { - s += method.Parent.GoName + "_" + method.GoName + "Client" - } - s += ", error)" - return s -} - -func genClientMethod(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, method *protogen.Method, index int) { - service := method.Parent - sname := fmt.Sprintf("/%s/%s", service.Desc.FullName(), method.Desc.Name()) - - if method.Desc.Options().(*descriptorpb.MethodOptions).GetDeprecated() { - g.P(deprecationComment) - } - g.P("func (c *", unexport(service.GoName), "Client) ", clientSignature(g, method), "{") - if !method.Desc.IsStreamingServer() && !method.Desc.IsStreamingClient() { - g.P("out := new(", method.Output.GoIdent, ")") - g.P(`err := c.cc.Invoke(ctx, "`, sname, `", in, out, opts...)`) - g.P("if err != nil { return nil, err }") - g.P("return out, nil") - g.P("}") - g.P() - return - } - streamType := unexport(service.GoName) + method.GoName + "Client" - serviceDescVar := "_" + service.GoName + "_serviceDesc" - g.P("stream, err := c.cc.NewStream(ctx, &", serviceDescVar, ".Streams[", index, `], "`, sname, `", opts...)`) - g.P("if err != nil { return nil, err }") - g.P("x := &", streamType, "{stream}") - if !method.Desc.IsStreamingClient() { - g.P("if err := x.ClientStream.SendMsg(in); err != nil { return nil, err }") - g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }") - } - g.P("return x, nil") - g.P("}") - g.P() - - genSend := method.Desc.IsStreamingClient() - genRecv := method.Desc.IsStreamingServer() - genCloseAndRecv := !method.Desc.IsStreamingServer() - - // Stream auxiliary types and methods. - g.P("type ", service.GoName, "_", method.GoName, "Client interface {") - if genSend { - g.P("Send(*", method.Input.GoIdent, ") error") - } - if genRecv { - g.P("Recv() (*", method.Output.GoIdent, ", error)") - } - if genCloseAndRecv { - g.P("CloseAndRecv() (*", method.Output.GoIdent, ", error)") - } - g.P(grpcPackage.Ident("ClientStream")) - g.P("}") - g.P() - - g.P("type ", streamType, " struct {") - g.P(grpcPackage.Ident("ClientStream")) - g.P("}") - g.P() - - if genSend { - g.P("func (x *", streamType, ") Send(m *", method.Input.GoIdent, ") error {") - g.P("return x.ClientStream.SendMsg(m)") - g.P("}") - g.P() - } - if genRecv { - g.P("func (x *", streamType, ") Recv() (*", method.Output.GoIdent, ", error) {") - g.P("m := new(", method.Output.GoIdent, ")") - g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }") - g.P("return m, nil") - g.P("}") - g.P() - } - if genCloseAndRecv { - g.P("func (x *", streamType, ") CloseAndRecv() (*", method.Output.GoIdent, ", error) {") - g.P("if err := x.ClientStream.CloseSend(); err != nil { return nil, err }") - g.P("m := new(", method.Output.GoIdent, ")") - g.P("if err := x.ClientStream.RecvMsg(m); err != nil { return nil, err }") - g.P("return m, nil") - g.P("}") - g.P() - } -} - -func serverSignature(g *protogen.GeneratedFile, method *protogen.Method) string { - var reqArgs []string - ret := "error" - if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() { - reqArgs = append(reqArgs, g.QualifiedGoIdent(contextPackage.Ident("Context"))) - ret = "(*" + g.QualifiedGoIdent(method.Output.GoIdent) + ", error)" - } - if !method.Desc.IsStreamingClient() { - reqArgs = append(reqArgs, "*"+g.QualifiedGoIdent(method.Input.GoIdent)) - } - if method.Desc.IsStreamingClient() || method.Desc.IsStreamingServer() { - reqArgs = append(reqArgs, method.Parent.GoName+"_"+method.GoName+"Server") - } - return method.GoName + "(" + strings.Join(reqArgs, ", ") + ") " + ret -} - -func genServerMethod(gen *protogen.Plugin, file *protogen.File, g *protogen.GeneratedFile, method *protogen.Method) string { - service := method.Parent - hname := fmt.Sprintf("_%s_%s_Handler", service.GoName, method.GoName) - - if !method.Desc.IsStreamingClient() && !method.Desc.IsStreamingServer() { - g.P("func ", hname, "(srv interface{}, ctx ", contextPackage.Ident("Context"), ", dec func(interface{}) error, interceptor ", grpcPackage.Ident("UnaryServerInterceptor"), ") (interface{}, error) {") - g.P("in := new(", method.Input.GoIdent, ")") - g.P("if err := dec(in); err != nil { return nil, err }") - g.P("if interceptor == nil { return srv.(", service.GoName, "Server).", method.GoName, "(ctx, in) }") - g.P("info := &", grpcPackage.Ident("UnaryServerInfo"), "{") - g.P("Server: srv,") - g.P("FullMethod: ", strconv.Quote(fmt.Sprintf("/%s/%s", service.Desc.FullName(), method.GoName)), ",") - g.P("}") - g.P("handler := func(ctx ", contextPackage.Ident("Context"), ", req interface{}) (interface{}, error) {") - g.P("return srv.(", service.GoName, "Server).", method.GoName, "(ctx, req.(*", method.Input.GoIdent, "))") - g.P("}") - g.P("return interceptor(ctx, in, info, handler)") - g.P("}") - g.P() - return hname - } - streamType := unexport(service.GoName) + method.GoName + "Server" - g.P("func ", hname, "(srv interface{}, stream ", grpcPackage.Ident("ServerStream"), ") error {") - if !method.Desc.IsStreamingClient() { - g.P("m := new(", method.Input.GoIdent, ")") - g.P("if err := stream.RecvMsg(m); err != nil { return err }") - g.P("return srv.(", service.GoName, "Server).", method.GoName, "(m, &", streamType, "{stream})") - } else { - g.P("return srv.(", service.GoName, "Server).", method.GoName, "(&", streamType, "{stream})") - } - g.P("}") - g.P() - - genSend := method.Desc.IsStreamingServer() - genSendAndClose := !method.Desc.IsStreamingServer() - genRecv := method.Desc.IsStreamingClient() - - // Stream auxiliary types and methods. - g.P("type ", service.GoName, "_", method.GoName, "Server interface {") - if genSend { - g.P("Send(*", method.Output.GoIdent, ") error") - } - if genSendAndClose { - g.P("SendAndClose(*", method.Output.GoIdent, ") error") - } - if genRecv { - g.P("Recv() (*", method.Input.GoIdent, ", error)") - } - g.P(grpcPackage.Ident("ServerStream")) - g.P("}") - g.P() - - g.P("type ", streamType, " struct {") - g.P(grpcPackage.Ident("ServerStream")) - g.P("}") - g.P() - - if genSend { - g.P("func (x *", streamType, ") Send(m *", method.Output.GoIdent, ") error {") - g.P("return x.ServerStream.SendMsg(m)") - g.P("}") - g.P() - } - if genSendAndClose { - g.P("func (x *", streamType, ") SendAndClose(m *", method.Output.GoIdent, ") error {") - g.P("return x.ServerStream.SendMsg(m)") - g.P("}") - g.P() - } - if genRecv { - g.P("func (x *", streamType, ") Recv() (*", method.Input.GoIdent, ", error) {") - g.P("m := new(", method.Input.GoIdent, ")") - g.P("if err := x.ServerStream.RecvMsg(m); err != nil { return nil, err }") - g.P("return m, nil") - g.P("}") - g.P() - } - - return hname -} - -const deprecationComment = "// Deprecated: Do not use." - -func unexport(s string) string { return strings.ToLower(s[:1]) + s[1:] } diff --git a/vendor/github.com/golang/protobuf/jsonpb/decode.go b/vendor/github.com/golang/protobuf/jsonpb/decode.go deleted file mode 100644 index 60e82caa9a2d30ac3d1abbd2b9ab6049f33a1a36..0000000000000000000000000000000000000000 --- a/vendor/github.com/golang/protobuf/jsonpb/decode.go +++ /dev/null @@ -1,524 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package jsonpb - -import ( - "encoding/json" - "errors" - "fmt" - "io" - "math" - "reflect" - "strconv" - "strings" - "time" - - "github.com/golang/protobuf/proto" - "google.golang.org/protobuf/encoding/protojson" - protoV2 "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/reflect/protoregistry" -) - -const wrapJSONUnmarshalV2 = false - -// UnmarshalNext unmarshals the next JSON object from d into m. -func UnmarshalNext(d *json.Decoder, m proto.Message) error { - return new(Unmarshaler).UnmarshalNext(d, m) -} - -// Unmarshal unmarshals a JSON object from r into m. -func Unmarshal(r io.Reader, m proto.Message) error { - return new(Unmarshaler).Unmarshal(r, m) -} - -// UnmarshalString unmarshals a JSON object from s into m. -func UnmarshalString(s string, m proto.Message) error { - return new(Unmarshaler).Unmarshal(strings.NewReader(s), m) -} - -// Unmarshaler is a configurable object for converting from a JSON -// representation to a protocol buffer object. -type Unmarshaler struct { - // AllowUnknownFields specifies whether to allow messages to contain - // unknown JSON fields, as opposed to failing to unmarshal. - AllowUnknownFields bool - - // AnyResolver is used to resolve the google.protobuf.Any well-known type. - // If unset, the global registry is used by default. - AnyResolver AnyResolver -} - -// JSONPBUnmarshaler is implemented by protobuf messages that customize the way -// they are unmarshaled from JSON. Messages that implement this should also -// implement JSONPBMarshaler so that the custom format can be produced. -// -// The JSON unmarshaling must follow the JSON to proto specification: -// https://developers.google.com/protocol-buffers/docs/proto3#json -// -// Deprecated: Custom types should implement protobuf reflection instead. -type JSONPBUnmarshaler interface { - UnmarshalJSONPB(*Unmarshaler, []byte) error -} - -// Unmarshal unmarshals a JSON object from r into m. -func (u *Unmarshaler) Unmarshal(r io.Reader, m proto.Message) error { - return u.UnmarshalNext(json.NewDecoder(r), m) -} - -// UnmarshalNext unmarshals the next JSON object from d into m. -func (u *Unmarshaler) UnmarshalNext(d *json.Decoder, m proto.Message) error { - if m == nil { - return errors.New("invalid nil message") - } - - // Parse the next JSON object from the stream. - raw := json.RawMessage{} - if err := d.Decode(&raw); err != nil { - return err - } - - // Check for custom unmarshalers first since they may not properly - // implement protobuf reflection that the logic below relies on. - if jsu, ok := m.(JSONPBUnmarshaler); ok { - return jsu.UnmarshalJSONPB(u, raw) - } - - mr := proto.MessageReflect(m) - - // NOTE: For historical reasons, a top-level null is treated as a noop. - // This is incorrect, but kept for compatibility. - if string(raw) == "null" && mr.Descriptor().FullName() != "google.protobuf.Value" { - return nil - } - - if wrapJSONUnmarshalV2 { - // NOTE: If input message is non-empty, we need to preserve merge semantics - // of the old jsonpb implementation. These semantics are not supported by - // the protobuf JSON specification. - isEmpty := true - mr.Range(func(protoreflect.FieldDescriptor, protoreflect.Value) bool { - isEmpty = false // at least one iteration implies non-empty - return false - }) - if !isEmpty { - // Perform unmarshaling into a newly allocated, empty message. - mr = mr.New() - - // Use a defer to copy all unmarshaled fields into the original message. - dst := proto.MessageReflect(m) - defer mr.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { - dst.Set(fd, v) - return true - }) - } - - // Unmarshal using the v2 JSON unmarshaler. - opts := protojson.UnmarshalOptions{ - DiscardUnknown: u.AllowUnknownFields, - } - if u.AnyResolver != nil { - opts.Resolver = anyResolver{u.AnyResolver} - } - return opts.Unmarshal(raw, mr.Interface()) - } else { - if err := u.unmarshalMessage(mr, raw); err != nil { - return err - } - return protoV2.CheckInitialized(mr.Interface()) - } -} - -func (u *Unmarshaler) unmarshalMessage(m protoreflect.Message, in []byte) error { - md := m.Descriptor() - fds := md.Fields() - - if jsu, ok := proto.MessageV1(m.Interface()).(JSONPBUnmarshaler); ok { - return jsu.UnmarshalJSONPB(u, in) - } - - if string(in) == "null" && md.FullName() != "google.protobuf.Value" { - return nil - } - - switch wellKnownType(md.FullName()) { - case "Any": - var jsonObject map[string]json.RawMessage - if err := json.Unmarshal(in, &jsonObject); err != nil { - return err - } - - rawTypeURL, ok := jsonObject["@type"] - if !ok { - return errors.New("Any JSON doesn't have '@type'") - } - typeURL, err := unquoteString(string(rawTypeURL)) - if err != nil { - return fmt.Errorf("can't unmarshal Any's '@type': %q", rawTypeURL) - } - m.Set(fds.ByNumber(1), protoreflect.ValueOfString(typeURL)) - - var m2 protoreflect.Message - if u.AnyResolver != nil { - mi, err := u.AnyResolver.Resolve(typeURL) - if err != nil { - return err - } - m2 = proto.MessageReflect(mi) - } else { - mt, err := protoregistry.GlobalTypes.FindMessageByURL(typeURL) - if err != nil { - if err == protoregistry.NotFound { - return fmt.Errorf("could not resolve Any message type: %v", typeURL) - } - return err - } - m2 = mt.New() - } - - if wellKnownType(m2.Descriptor().FullName()) != "" { - rawValue, ok := jsonObject["value"] - if !ok { - return errors.New("Any JSON doesn't have 'value'") - } - if err := u.unmarshalMessage(m2, rawValue); err != nil { - return fmt.Errorf("can't unmarshal Any nested proto %v: %v", typeURL, err) - } - } else { - delete(jsonObject, "@type") - rawJSON, err := json.Marshal(jsonObject) - if err != nil { - return fmt.Errorf("can't generate JSON for Any's nested proto to be unmarshaled: %v", err) - } - if err = u.unmarshalMessage(m2, rawJSON); err != nil { - return fmt.Errorf("can't unmarshal Any nested proto %v: %v", typeURL, err) - } - } - - rawWire, err := protoV2.Marshal(m2.Interface()) - if err != nil { - return fmt.Errorf("can't marshal proto %v into Any.Value: %v", typeURL, err) - } - m.Set(fds.ByNumber(2), protoreflect.ValueOfBytes(rawWire)) - return nil - case "BoolValue", "BytesValue", "StringValue", - "Int32Value", "UInt32Value", "FloatValue", - "Int64Value", "UInt64Value", "DoubleValue": - fd := fds.ByNumber(1) - v, err := u.unmarshalValue(m.NewField(fd), in, fd) - if err != nil { - return err - } - m.Set(fd, v) - return nil - case "Duration": - v, err := unquoteString(string(in)) - if err != nil { - return err - } - d, err := time.ParseDuration(v) - if err != nil { - return fmt.Errorf("bad Duration: %v", err) - } - - sec := d.Nanoseconds() / 1e9 - nsec := d.Nanoseconds() % 1e9 - m.Set(fds.ByNumber(1), protoreflect.ValueOfInt64(int64(sec))) - m.Set(fds.ByNumber(2), protoreflect.ValueOfInt32(int32(nsec))) - return nil - case "Timestamp": - v, err := unquoteString(string(in)) - if err != nil { - return err - } - t, err := time.Parse(time.RFC3339Nano, v) - if err != nil { - return fmt.Errorf("bad Timestamp: %v", err) - } - - sec := t.Unix() - nsec := t.Nanosecond() - m.Set(fds.ByNumber(1), protoreflect.ValueOfInt64(int64(sec))) - m.Set(fds.ByNumber(2), protoreflect.ValueOfInt32(int32(nsec))) - return nil - case "Value": - switch { - case string(in) == "null": - m.Set(fds.ByNumber(1), protoreflect.ValueOfEnum(0)) - case string(in) == "true": - m.Set(fds.ByNumber(4), protoreflect.ValueOfBool(true)) - case string(in) == "false": - m.Set(fds.ByNumber(4), protoreflect.ValueOfBool(false)) - case hasPrefixAndSuffix('"', in, '"'): - s, err := unquoteString(string(in)) - if err != nil { - return fmt.Errorf("unrecognized type for Value %q", in) - } - m.Set(fds.ByNumber(3), protoreflect.ValueOfString(s)) - case hasPrefixAndSuffix('[', in, ']'): - v := m.Mutable(fds.ByNumber(6)) - return u.unmarshalMessage(v.Message(), in) - case hasPrefixAndSuffix('{', in, '}'): - v := m.Mutable(fds.ByNumber(5)) - return u.unmarshalMessage(v.Message(), in) - default: - f, err := strconv.ParseFloat(string(in), 0) - if err != nil { - return fmt.Errorf("unrecognized type for Value %q", in) - } - m.Set(fds.ByNumber(2), protoreflect.ValueOfFloat64(f)) - } - return nil - case "ListValue": - var jsonArray []json.RawMessage - if err := json.Unmarshal(in, &jsonArray); err != nil { - return fmt.Errorf("bad ListValue: %v", err) - } - - lv := m.Mutable(fds.ByNumber(1)).List() - for _, raw := range jsonArray { - ve := lv.NewElement() - if err := u.unmarshalMessage(ve.Message(), raw); err != nil { - return err - } - lv.Append(ve) - } - return nil - case "Struct": - var jsonObject map[string]json.RawMessage - if err := json.Unmarshal(in, &jsonObject); err != nil { - return fmt.Errorf("bad StructValue: %v", err) - } - - mv := m.Mutable(fds.ByNumber(1)).Map() - for key, raw := range jsonObject { - kv := protoreflect.ValueOf(key).MapKey() - vv := mv.NewValue() - if err := u.unmarshalMessage(vv.Message(), raw); err != nil { - return fmt.Errorf("bad value in StructValue for key %q: %v", key, err) - } - mv.Set(kv, vv) - } - return nil - } - - var jsonObject map[string]json.RawMessage - if err := json.Unmarshal(in, &jsonObject); err != nil { - return err - } - - // Handle known fields. - for i := 0; i < fds.Len(); i++ { - fd := fds.Get(i) - if fd.IsWeak() && fd.Message().IsPlaceholder() { - continue // weak reference is not linked in - } - - // Search for any raw JSON value associated with this field. - var raw json.RawMessage - name := string(fd.Name()) - if fd.Kind() == protoreflect.GroupKind { - name = string(fd.Message().Name()) - } - if v, ok := jsonObject[name]; ok { - delete(jsonObject, name) - raw = v - } - name = string(fd.JSONName()) - if v, ok := jsonObject[name]; ok { - delete(jsonObject, name) - raw = v - } - - field := m.NewField(fd) - // Unmarshal the field value. - if raw == nil || (string(raw) == "null" && !isSingularWellKnownValue(fd) && !isSingularJSONPBUnmarshaler(field, fd)) { - continue - } - v, err := u.unmarshalValue(field, raw, fd) - if err != nil { - return err - } - m.Set(fd, v) - } - - // Handle extension fields. - for name, raw := range jsonObject { - if !strings.HasPrefix(name, "[") || !strings.HasSuffix(name, "]") { - continue - } - - // Resolve the extension field by name. - xname := protoreflect.FullName(name[len("[") : len(name)-len("]")]) - xt, _ := protoregistry.GlobalTypes.FindExtensionByName(xname) - if xt == nil && isMessageSet(md) { - xt, _ = protoregistry.GlobalTypes.FindExtensionByName(xname.Append("message_set_extension")) - } - if xt == nil { - continue - } - delete(jsonObject, name) - fd := xt.TypeDescriptor() - if fd.ContainingMessage().FullName() != m.Descriptor().FullName() { - return fmt.Errorf("extension field %q does not extend message %q", xname, m.Descriptor().FullName()) - } - - field := m.NewField(fd) - // Unmarshal the field value. - if raw == nil || (string(raw) == "null" && !isSingularWellKnownValue(fd) && !isSingularJSONPBUnmarshaler(field, fd)) { - continue - } - v, err := u.unmarshalValue(field, raw, fd) - if err != nil { - return err - } - m.Set(fd, v) - } - - if !u.AllowUnknownFields && len(jsonObject) > 0 { - for name := range jsonObject { - return fmt.Errorf("unknown field %q in %v", name, md.FullName()) - } - } - return nil -} - -func isSingularWellKnownValue(fd protoreflect.FieldDescriptor) bool { - if md := fd.Message(); md != nil { - return md.FullName() == "google.protobuf.Value" && fd.Cardinality() != protoreflect.Repeated - } - return false -} - -func isSingularJSONPBUnmarshaler(v protoreflect.Value, fd protoreflect.FieldDescriptor) bool { - if fd.Message() != nil && fd.Cardinality() != protoreflect.Repeated { - _, ok := proto.MessageV1(v.Interface()).(JSONPBUnmarshaler) - return ok - } - return false -} - -func (u *Unmarshaler) unmarshalValue(v protoreflect.Value, in []byte, fd protoreflect.FieldDescriptor) (protoreflect.Value, error) { - switch { - case fd.IsList(): - var jsonArray []json.RawMessage - if err := json.Unmarshal(in, &jsonArray); err != nil { - return v, err - } - lv := v.List() - for _, raw := range jsonArray { - ve, err := u.unmarshalSingularValue(lv.NewElement(), raw, fd) - if err != nil { - return v, err - } - lv.Append(ve) - } - return v, nil - case fd.IsMap(): - var jsonObject map[string]json.RawMessage - if err := json.Unmarshal(in, &jsonObject); err != nil { - return v, err - } - kfd := fd.MapKey() - vfd := fd.MapValue() - mv := v.Map() - for key, raw := range jsonObject { - var kv protoreflect.MapKey - if kfd.Kind() == protoreflect.StringKind { - kv = protoreflect.ValueOf(key).MapKey() - } else { - v, err := u.unmarshalSingularValue(kfd.Default(), []byte(key), kfd) - if err != nil { - return v, err - } - kv = v.MapKey() - } - - vv, err := u.unmarshalSingularValue(mv.NewValue(), raw, vfd) - if err != nil { - return v, err - } - mv.Set(kv, vv) - } - return v, nil - default: - return u.unmarshalSingularValue(v, in, fd) - } -} - -var nonFinite = map[string]float64{ - `"NaN"`: math.NaN(), - `"Infinity"`: math.Inf(+1), - `"-Infinity"`: math.Inf(-1), -} - -func (u *Unmarshaler) unmarshalSingularValue(v protoreflect.Value, in []byte, fd protoreflect.FieldDescriptor) (protoreflect.Value, error) { - switch fd.Kind() { - case protoreflect.BoolKind: - return unmarshalValue(in, new(bool)) - case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind: - return unmarshalValue(trimQuote(in), new(int32)) - case protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: - return unmarshalValue(trimQuote(in), new(int64)) - case protoreflect.Uint32Kind, protoreflect.Fixed32Kind: - return unmarshalValue(trimQuote(in), new(uint32)) - case protoreflect.Uint64Kind, protoreflect.Fixed64Kind: - return unmarshalValue(trimQuote(in), new(uint64)) - case protoreflect.FloatKind: - if f, ok := nonFinite[string(in)]; ok { - return protoreflect.ValueOfFloat32(float32(f)), nil - } - return unmarshalValue(trimQuote(in), new(float32)) - case protoreflect.DoubleKind: - if f, ok := nonFinite[string(in)]; ok { - return protoreflect.ValueOfFloat64(float64(f)), nil - } - return unmarshalValue(trimQuote(in), new(float64)) - case protoreflect.StringKind: - return unmarshalValue(in, new(string)) - case protoreflect.BytesKind: - return unmarshalValue(in, new([]byte)) - case protoreflect.EnumKind: - if hasPrefixAndSuffix('"', in, '"') { - vd := fd.Enum().Values().ByName(protoreflect.Name(trimQuote(in))) - if vd == nil { - return v, fmt.Errorf("unknown value %q for enum %s", in, fd.Enum().FullName()) - } - return protoreflect.ValueOfEnum(vd.Number()), nil - } - return unmarshalValue(in, new(protoreflect.EnumNumber)) - case protoreflect.MessageKind, protoreflect.GroupKind: - err := u.unmarshalMessage(v.Message(), in) - return v, err - default: - panic(fmt.Sprintf("invalid kind %v", fd.Kind())) - } -} - -func unmarshalValue(in []byte, v interface{}) (protoreflect.Value, error) { - err := json.Unmarshal(in, v) - return protoreflect.ValueOf(reflect.ValueOf(v).Elem().Interface()), err -} - -func unquoteString(in string) (out string, err error) { - err = json.Unmarshal([]byte(in), &out) - return out, err -} - -func hasPrefixAndSuffix(prefix byte, in []byte, suffix byte) bool { - if len(in) >= 2 && in[0] == prefix && in[len(in)-1] == suffix { - return true - } - return false -} - -// trimQuote is like unquoteString but simply strips surrounding quotes. -// This is incorrect, but is behavior done by the legacy implementation. -func trimQuote(in []byte) []byte { - if len(in) >= 2 && in[0] == '"' && in[len(in)-1] == '"' { - in = in[1 : len(in)-1] - } - return in -} diff --git a/vendor/github.com/golang/protobuf/jsonpb/encode.go b/vendor/github.com/golang/protobuf/jsonpb/encode.go deleted file mode 100644 index 685c80a62bc91a5744e9f958f4cf2b3855080a41..0000000000000000000000000000000000000000 --- a/vendor/github.com/golang/protobuf/jsonpb/encode.go +++ /dev/null @@ -1,559 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -package jsonpb - -import ( - "encoding/json" - "errors" - "fmt" - "io" - "math" - "reflect" - "sort" - "strconv" - "strings" - "time" - - "github.com/golang/protobuf/proto" - "google.golang.org/protobuf/encoding/protojson" - protoV2 "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/reflect/protoregistry" -) - -const wrapJSONMarshalV2 = false - -// Marshaler is a configurable object for marshaling protocol buffer messages -// to the specified JSON representation. -type Marshaler struct { - // OrigName specifies whether to use the original protobuf name for fields. - OrigName bool - - // EnumsAsInts specifies whether to render enum values as integers, - // as opposed to string values. - EnumsAsInts bool - - // EmitDefaults specifies whether to render fields with zero values. - EmitDefaults bool - - // Indent controls whether the output is compact or not. - // If empty, the output is compact JSON. Otherwise, every JSON object - // entry and JSON array value will be on its own line. - // Each line will be preceded by repeated copies of Indent, where the - // number of copies is the current indentation depth. - Indent string - - // AnyResolver is used to resolve the google.protobuf.Any well-known type. - // If unset, the global registry is used by default. - AnyResolver AnyResolver -} - -// JSONPBMarshaler is implemented by protobuf messages that customize the -// way they are marshaled to JSON. Messages that implement this should also -// implement JSONPBUnmarshaler so that the custom format can be parsed. -// -// The JSON marshaling must follow the proto to JSON specification: -// https://developers.google.com/protocol-buffers/docs/proto3#json -// -// Deprecated: Custom types should implement protobuf reflection instead. -type JSONPBMarshaler interface { - MarshalJSONPB(*Marshaler) ([]byte, error) -} - -// Marshal serializes a protobuf message as JSON into w. -func (jm *Marshaler) Marshal(w io.Writer, m proto.Message) error { - b, err := jm.marshal(m) - if len(b) > 0 { - if _, err := w.Write(b); err != nil { - return err - } - } - return err -} - -// MarshalToString serializes a protobuf message as JSON in string form. -func (jm *Marshaler) MarshalToString(m proto.Message) (string, error) { - b, err := jm.marshal(m) - if err != nil { - return "", err - } - return string(b), nil -} - -func (jm *Marshaler) marshal(m proto.Message) ([]byte, error) { - v := reflect.ValueOf(m) - if m == nil || (v.Kind() == reflect.Ptr && v.IsNil()) { - return nil, errors.New("Marshal called with nil") - } - - // Check for custom marshalers first since they may not properly - // implement protobuf reflection that the logic below relies on. - if jsm, ok := m.(JSONPBMarshaler); ok { - return jsm.MarshalJSONPB(jm) - } - - if wrapJSONMarshalV2 { - opts := protojson.MarshalOptions{ - UseProtoNames: jm.OrigName, - UseEnumNumbers: jm.EnumsAsInts, - EmitUnpopulated: jm.EmitDefaults, - Indent: jm.Indent, - } - if jm.AnyResolver != nil { - opts.Resolver = anyResolver{jm.AnyResolver} - } - return opts.Marshal(proto.MessageReflect(m).Interface()) - } else { - // Check for unpopulated required fields first. - m2 := proto.MessageReflect(m) - if err := protoV2.CheckInitialized(m2.Interface()); err != nil { - return nil, err - } - - w := jsonWriter{Marshaler: jm} - err := w.marshalMessage(m2, "", "") - return w.buf, err - } -} - -type jsonWriter struct { - *Marshaler - buf []byte -} - -func (w *jsonWriter) write(s string) { - w.buf = append(w.buf, s...) -} - -func (w *jsonWriter) marshalMessage(m protoreflect.Message, indent, typeURL string) error { - if jsm, ok := proto.MessageV1(m.Interface()).(JSONPBMarshaler); ok { - b, err := jsm.MarshalJSONPB(w.Marshaler) - if err != nil { - return err - } - if typeURL != "" { - // we are marshaling this object to an Any type - var js map[string]*json.RawMessage - if err = json.Unmarshal(b, &js); err != nil { - return fmt.Errorf("type %T produced invalid JSON: %v", m.Interface(), err) - } - turl, err := json.Marshal(typeURL) - if err != nil { - return fmt.Errorf("failed to marshal type URL %q to JSON: %v", typeURL, err) - } - js["@type"] = (*json.RawMessage)(&turl) - if b, err = json.Marshal(js); err != nil { - return err - } - } - w.write(string(b)) - return nil - } - - md := m.Descriptor() - fds := md.Fields() - - // Handle well-known types. - const secondInNanos = int64(time.Second / time.Nanosecond) - switch wellKnownType(md.FullName()) { - case "Any": - return w.marshalAny(m, indent) - case "BoolValue", "BytesValue", "StringValue", - "Int32Value", "UInt32Value", "FloatValue", - "Int64Value", "UInt64Value", "DoubleValue": - fd := fds.ByNumber(1) - return w.marshalValue(fd, m.Get(fd), indent) - case "Duration": - const maxSecondsInDuration = 315576000000 - // "Generated output always contains 0, 3, 6, or 9 fractional digits, - // depending on required precision." - s := m.Get(fds.ByNumber(1)).Int() - ns := m.Get(fds.ByNumber(2)).Int() - if s < -maxSecondsInDuration || s > maxSecondsInDuration { - return fmt.Errorf("seconds out of range %v", s) - } - if ns <= -secondInNanos || ns >= secondInNanos { - return fmt.Errorf("ns out of range (%v, %v)", -secondInNanos, secondInNanos) - } - if (s > 0 && ns < 0) || (s < 0 && ns > 0) { - return errors.New("signs of seconds and nanos do not match") - } - var sign string - if s < 0 || ns < 0 { - sign, s, ns = "-", -1*s, -1*ns - } - x := fmt.Sprintf("%s%d.%09d", sign, s, ns) - x = strings.TrimSuffix(x, "000") - x = strings.TrimSuffix(x, "000") - x = strings.TrimSuffix(x, ".000") - w.write(fmt.Sprintf(`"%vs"`, x)) - return nil - case "Timestamp": - // "RFC 3339, where generated output will always be Z-normalized - // and uses 0, 3, 6 or 9 fractional digits." - s := m.Get(fds.ByNumber(1)).Int() - ns := m.Get(fds.ByNumber(2)).Int() - if ns < 0 || ns >= secondInNanos { - return fmt.Errorf("ns out of range [0, %v)", secondInNanos) - } - t := time.Unix(s, ns).UTC() - // time.RFC3339Nano isn't exactly right (we need to get 3/6/9 fractional digits). - x := t.Format("2006-01-02T15:04:05.000000000") - x = strings.TrimSuffix(x, "000") - x = strings.TrimSuffix(x, "000") - x = strings.TrimSuffix(x, ".000") - w.write(fmt.Sprintf(`"%vZ"`, x)) - return nil - case "Value": - // JSON value; which is a null, number, string, bool, object, or array. - od := md.Oneofs().Get(0) - fd := m.WhichOneof(od) - if fd == nil { - return errors.New("nil Value") - } - return w.marshalValue(fd, m.Get(fd), indent) - case "Struct", "ListValue": - // JSON object or array. - fd := fds.ByNumber(1) - return w.marshalValue(fd, m.Get(fd), indent) - } - - w.write("{") - if w.Indent != "" { - w.write("\n") - } - - firstField := true - if typeURL != "" { - if err := w.marshalTypeURL(indent, typeURL); err != nil { - return err - } - firstField = false - } - - for i := 0; i < fds.Len(); { - fd := fds.Get(i) - if od := fd.ContainingOneof(); od != nil { - fd = m.WhichOneof(od) - i += od.Fields().Len() - if fd == nil { - continue - } - } else { - i++ - } - - v := m.Get(fd) - - if !m.Has(fd) { - if !w.EmitDefaults || fd.ContainingOneof() != nil { - continue - } - if fd.Cardinality() != protoreflect.Repeated && (fd.Message() != nil || fd.Syntax() == protoreflect.Proto2) { - v = protoreflect.Value{} // use "null" for singular messages or proto2 scalars - } - } - - if !firstField { - w.writeComma() - } - if err := w.marshalField(fd, v, indent); err != nil { - return err - } - firstField = false - } - - // Handle proto2 extensions. - if md.ExtensionRanges().Len() > 0 { - // Collect a sorted list of all extension descriptor and values. - type ext struct { - desc protoreflect.FieldDescriptor - val protoreflect.Value - } - var exts []ext - m.Range(func(fd protoreflect.FieldDescriptor, v protoreflect.Value) bool { - if fd.IsExtension() { - exts = append(exts, ext{fd, v}) - } - return true - }) - sort.Slice(exts, func(i, j int) bool { - return exts[i].desc.Number() < exts[j].desc.Number() - }) - - for _, ext := range exts { - if !firstField { - w.writeComma() - } - if err := w.marshalField(ext.desc, ext.val, indent); err != nil { - return err - } - firstField = false - } - } - - if w.Indent != "" { - w.write("\n") - w.write(indent) - } - w.write("}") - return nil -} - -func (w *jsonWriter) writeComma() { - if w.Indent != "" { - w.write(",\n") - } else { - w.write(",") - } -} - -func (w *jsonWriter) marshalAny(m protoreflect.Message, indent string) error { - // "If the Any contains a value that has a special JSON mapping, - // it will be converted as follows: {"@type": xxx, "value": yyy}. - // Otherwise, the value will be converted into a JSON object, - // and the "@type" field will be inserted to indicate the actual data type." - md := m.Descriptor() - typeURL := m.Get(md.Fields().ByNumber(1)).String() - rawVal := m.Get(md.Fields().ByNumber(2)).Bytes() - - var m2 protoreflect.Message - if w.AnyResolver != nil { - mi, err := w.AnyResolver.Resolve(typeURL) - if err != nil { - return err - } - m2 = proto.MessageReflect(mi) - } else { - mt, err := protoregistry.GlobalTypes.FindMessageByURL(typeURL) - if err != nil { - return err - } - m2 = mt.New() - } - - if err := protoV2.Unmarshal(rawVal, m2.Interface()); err != nil { - return err - } - - if wellKnownType(m2.Descriptor().FullName()) == "" { - return w.marshalMessage(m2, indent, typeURL) - } - - w.write("{") - if w.Indent != "" { - w.write("\n") - } - if err := w.marshalTypeURL(indent, typeURL); err != nil { - return err - } - w.writeComma() - if w.Indent != "" { - w.write(indent) - w.write(w.Indent) - w.write(`"value": `) - } else { - w.write(`"value":`) - } - if err := w.marshalMessage(m2, indent+w.Indent, ""); err != nil { - return err - } - if w.Indent != "" { - w.write("\n") - w.write(indent) - } - w.write("}") - return nil -} - -func (w *jsonWriter) marshalTypeURL(indent, typeURL string) error { - if w.Indent != "" { - w.write(indent) - w.write(w.Indent) - } - w.write(`"@type":`) - if w.Indent != "" { - w.write(" ") - } - b, err := json.Marshal(typeURL) - if err != nil { - return err - } - w.write(string(b)) - return nil -} - -// marshalField writes field description and value to the Writer. -func (w *jsonWriter) marshalField(fd protoreflect.FieldDescriptor, v protoreflect.Value, indent string) error { - if w.Indent != "" { - w.write(indent) - w.write(w.Indent) - } - w.write(`"`) - switch { - case fd.IsExtension(): - // For message set, use the fname of the message as the extension name. - name := string(fd.FullName()) - if isMessageSet(fd.ContainingMessage()) { - name = strings.TrimSuffix(name, ".message_set_extension") - } - - w.write("[" + name + "]") - case w.OrigName: - name := string(fd.Name()) - if fd.Kind() == protoreflect.GroupKind { - name = string(fd.Message().Name()) - } - w.write(name) - default: - w.write(string(fd.JSONName())) - } - w.write(`":`) - if w.Indent != "" { - w.write(" ") - } - return w.marshalValue(fd, v, indent) -} - -func (w *jsonWriter) marshalValue(fd protoreflect.FieldDescriptor, v protoreflect.Value, indent string) error { - switch { - case fd.IsList(): - w.write("[") - comma := "" - lv := v.List() - for i := 0; i < lv.Len(); i++ { - w.write(comma) - if w.Indent != "" { - w.write("\n") - w.write(indent) - w.write(w.Indent) - w.write(w.Indent) - } - if err := w.marshalSingularValue(fd, lv.Get(i), indent+w.Indent); err != nil { - return err - } - comma = "," - } - if w.Indent != "" { - w.write("\n") - w.write(indent) - w.write(w.Indent) - } - w.write("]") - return nil - case fd.IsMap(): - kfd := fd.MapKey() - vfd := fd.MapValue() - mv := v.Map() - - // Collect a sorted list of all map keys and values. - type entry struct{ key, val protoreflect.Value } - var entries []entry - mv.Range(func(k protoreflect.MapKey, v protoreflect.Value) bool { - entries = append(entries, entry{k.Value(), v}) - return true - }) - sort.Slice(entries, func(i, j int) bool { - switch kfd.Kind() { - case protoreflect.BoolKind: - return !entries[i].key.Bool() && entries[j].key.Bool() - case protoreflect.Int32Kind, protoreflect.Sint32Kind, protoreflect.Sfixed32Kind, protoreflect.Int64Kind, protoreflect.Sint64Kind, protoreflect.Sfixed64Kind: - return entries[i].key.Int() < entries[j].key.Int() - case protoreflect.Uint32Kind, protoreflect.Fixed32Kind, protoreflect.Uint64Kind, protoreflect.Fixed64Kind: - return entries[i].key.Uint() < entries[j].key.Uint() - case protoreflect.StringKind: - return entries[i].key.String() < entries[j].key.String() - default: - panic("invalid kind") - } - }) - - w.write(`{`) - comma := "" - for _, entry := range entries { - w.write(comma) - if w.Indent != "" { - w.write("\n") - w.write(indent) - w.write(w.Indent) - w.write(w.Indent) - } - - s := fmt.Sprint(entry.key.Interface()) - b, err := json.Marshal(s) - if err != nil { - return err - } - w.write(string(b)) - - w.write(`:`) - if w.Indent != "" { - w.write(` `) - } - - if err := w.marshalSingularValue(vfd, entry.val, indent+w.Indent); err != nil { - return err - } - comma = "," - } - if w.Indent != "" { - w.write("\n") - w.write(indent) - w.write(w.Indent) - } - w.write(`}`) - return nil - default: - return w.marshalSingularValue(fd, v, indent) - } -} - -func (w *jsonWriter) marshalSingularValue(fd protoreflect.FieldDescriptor, v protoreflect.Value, indent string) error { - switch { - case !v.IsValid(): - w.write("null") - return nil - case fd.Message() != nil: - return w.marshalMessage(v.Message(), indent+w.Indent, "") - case fd.Enum() != nil: - if fd.Enum().FullName() == "google.protobuf.NullValue" { - w.write("null") - return nil - } - - vd := fd.Enum().Values().ByNumber(v.Enum()) - if vd == nil || w.EnumsAsInts { - w.write(strconv.Itoa(int(v.Enum()))) - } else { - w.write(`"` + string(vd.Name()) + `"`) - } - return nil - default: - switch v.Interface().(type) { - case float32, float64: - switch { - case math.IsInf(v.Float(), +1): - w.write(`"Infinity"`) - return nil - case math.IsInf(v.Float(), -1): - w.write(`"-Infinity"`) - return nil - case math.IsNaN(v.Float()): - w.write(`"NaN"`) - return nil - } - case int64, uint64: - w.write(fmt.Sprintf(`"%d"`, v.Interface())) - return nil - } - - b, err := json.Marshal(v.Interface()) - if err != nil { - return err - } - w.write(string(b)) - return nil - } -} diff --git a/vendor/github.com/golang/protobuf/jsonpb/json.go b/vendor/github.com/golang/protobuf/jsonpb/json.go deleted file mode 100644 index 480e2448de661ad598f50c0232425287a8a617e6..0000000000000000000000000000000000000000 --- a/vendor/github.com/golang/protobuf/jsonpb/json.go +++ /dev/null @@ -1,69 +0,0 @@ -// Copyright 2015 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// Package jsonpb provides functionality to marshal and unmarshal between a -// protocol buffer message and JSON. It follows the specification at -// https://developers.google.com/protocol-buffers/docs/proto3#json. -// -// Do not rely on the default behavior of the standard encoding/json package -// when called on generated message types as it does not operate correctly. -// -// Deprecated: Use the "google.golang.org/protobuf/encoding/protojson" -// package instead. -package jsonpb - -import ( - "github.com/golang/protobuf/proto" - "google.golang.org/protobuf/reflect/protoreflect" - "google.golang.org/protobuf/reflect/protoregistry" - "google.golang.org/protobuf/runtime/protoimpl" -) - -// AnyResolver takes a type URL, present in an Any message, -// and resolves it into an instance of the associated message. -type AnyResolver interface { - Resolve(typeURL string) (proto.Message, error) -} - -type anyResolver struct{ AnyResolver } - -func (r anyResolver) FindMessageByName(message protoreflect.FullName) (protoreflect.MessageType, error) { - return r.FindMessageByURL(string(message)) -} - -func (r anyResolver) FindMessageByURL(url string) (protoreflect.MessageType, error) { - m, err := r.Resolve(url) - if err != nil { - return nil, err - } - return protoimpl.X.MessageTypeOf(m), nil -} - -func (r anyResolver) FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) { - return protoregistry.GlobalTypes.FindExtensionByName(field) -} - -func (r anyResolver) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) { - return protoregistry.GlobalTypes.FindExtensionByNumber(message, field) -} - -func wellKnownType(s protoreflect.FullName) string { - if s.Parent() == "google.protobuf" { - switch s.Name() { - case "Empty", "Any", - "BoolValue", "BytesValue", "StringValue", - "Int32Value", "UInt32Value", "FloatValue", - "Int64Value", "UInt64Value", "DoubleValue", - "Duration", "Timestamp", - "NullValue", "Struct", "Value", "ListValue": - return string(s.Name()) - } - } - return "" -} - -func isMessageSet(md protoreflect.MessageDescriptor) bool { - ms, ok := md.(interface{ IsMessageSet() bool }) - return ok && ms.IsMessageSet() -} diff --git a/vendor/github.com/golang/protobuf/protoc-gen-go/main.go b/vendor/github.com/golang/protobuf/protoc-gen-go/main.go deleted file mode 100644 index d45b719d1c6eeab31162aff4a65245d0c28a3a2e..0000000000000000000000000000000000000000 --- a/vendor/github.com/golang/protobuf/protoc-gen-go/main.go +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright 2010 The Go Authors. All rights reserved. -// Use of this source code is governed by a BSD-style -// license that can be found in the LICENSE file. - -// protoc-gen-go is a plugin for the Google protocol buffer compiler to generate -// Go code. Install it by building this program and making it accessible within -// your PATH with the name: -// protoc-gen-go -// -// The 'go' suffix becomes part of the argument for the protocol compiler, -// such that it can be invoked as: -// protoc --go_out=paths=source_relative:. path/to/file.proto -// -// This generates Go bindings for the protocol buffer defined by file.proto. -// With that input, the output will be written to: -// path/to/file.pb.go -// -// See the README and documentation for protocol buffers to learn more: -// https://developers.google.com/protocol-buffers/ -package main - -import ( - "flag" - "fmt" - "strings" - - "github.com/golang/protobuf/internal/gengogrpc" - gengo "google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo" - "google.golang.org/protobuf/compiler/protogen" -) - -func main() { - var ( - flags flag.FlagSet - plugins = flags.String("plugins", "", "list of plugins to enable (supported values: grpc)") - importPrefix = flags.String("import_prefix", "", "prefix to prepend to import paths") - ) - importRewriteFunc := func(importPath protogen.GoImportPath) protogen.GoImportPath { - switch importPath { - case "context", "fmt", "math": - return importPath - } - if *importPrefix != "" { - return protogen.GoImportPath(*importPrefix) + importPath - } - return importPath - } - protogen.Options{ - ParamFunc: flags.Set, - ImportRewriteFunc: importRewriteFunc, - }.Run(func(gen *protogen.Plugin) error { - grpc := false - for _, plugin := range strings.Split(*plugins, ",") { - switch plugin { - case "grpc": - grpc = true - case "": - default: - return fmt.Errorf("protoc-gen-go: unknown plugin %q", plugin) - } - } - for _, f := range gen.Files { - if !f.Generate { - continue - } - g := gengo.GenerateFile(gen, f) - if grpc { - gengogrpc.GenerateFileContent(gen, f, g) - } - } - gen.SupportedFeatures = gengo.SupportedFeatures - return nil - }) -} diff --git a/vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go b/vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go deleted file mode 100644 index 16686a65523b1111cd14c9a28a567d727563784f..0000000000000000000000000000000000000000 --- a/vendor/github.com/golang/protobuf/ptypes/empty/empty.pb.go +++ /dev/null @@ -1,62 +0,0 @@ -// Code generated by protoc-gen-go. DO NOT EDIT. -// source: github.com/golang/protobuf/ptypes/empty/empty.proto - -package empty - -import ( - protoreflect "google.golang.org/protobuf/reflect/protoreflect" - protoimpl "google.golang.org/protobuf/runtime/protoimpl" - emptypb "google.golang.org/protobuf/types/known/emptypb" - reflect "reflect" -) - -// Symbols defined in public import of google/protobuf/empty.proto. - -type Empty = emptypb.Empty - -var File_github_com_golang_protobuf_ptypes_empty_empty_proto protoreflect.FileDescriptor - -var file_github_com_golang_protobuf_ptypes_empty_empty_proto_rawDesc = []byte{ - 0x0a, 0x33, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, 0x2f, 0x67, 0x6f, 0x6c, - 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x70, 0x74, 0x79, - 0x70, 0x65, 0x73, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e, - 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x1a, 0x1b, 0x67, 0x6f, 0x6f, 0x67, 0x6c, 0x65, 0x2f, 0x70, 0x72, - 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x2e, 0x70, 0x72, 0x6f, - 0x74, 0x6f, 0x42, 0x2f, 0x5a, 0x2d, 0x67, 0x69, 0x74, 0x68, 0x75, 0x62, 0x2e, 0x63, 0x6f, 0x6d, - 0x2f, 0x67, 0x6f, 0x6c, 0x61, 0x6e, 0x67, 0x2f, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x62, 0x75, 0x66, - 0x2f, 0x70, 0x74, 0x79, 0x70, 0x65, 0x73, 0x2f, 0x65, 0x6d, 0x70, 0x74, 0x79, 0x3b, 0x65, 0x6d, - 0x70, 0x74, 0x79, 0x50, 0x00, 0x62, 0x06, 0x70, 0x72, 0x6f, 0x74, 0x6f, 0x33, -} - -var file_github_com_golang_protobuf_ptypes_empty_empty_proto_goTypes = []interface{}{} -var file_github_com_golang_protobuf_ptypes_empty_empty_proto_depIdxs = []int32{ - 0, // [0:0] is the sub-list for method output_type - 0, // [0:0] is the sub-list for method input_type - 0, // [0:0] is the sub-list for extension type_name - 0, // [0:0] is the sub-list for extension extendee - 0, // [0:0] is the sub-list for field type_name -} - -func init() { file_github_com_golang_protobuf_ptypes_empty_empty_proto_init() } -func file_github_com_golang_protobuf_ptypes_empty_empty_proto_init() { - if File_github_com_golang_protobuf_ptypes_empty_empty_proto != nil { - return - } - type x struct{} - out := protoimpl.TypeBuilder{ - File: protoimpl.DescBuilder{ - GoPackagePath: reflect.TypeOf(x{}).PkgPath(), - RawDescriptor: file_github_com_golang_protobuf_ptypes_empty_empty_proto_rawDesc, - NumEnums: 0, - NumMessages: 0, - NumExtensions: 0, - NumServices: 0, - }, - GoTypes: file_github_com_golang_protobuf_ptypes_empty_empty_proto_goTypes, - DependencyIndexes: file_github_com_golang_protobuf_ptypes_empty_empty_proto_depIdxs, - }.Build() - File_github_com_golang_protobuf_ptypes_empty_empty_proto = out.File - file_github_com_golang_protobuf_ptypes_empty_empty_proto_rawDesc = nil - file_github_com_golang_protobuf_ptypes_empty_empty_proto_goTypes = nil - file_github_com_golang_protobuf_ptypes_empty_empty_proto_depIdxs = nil -} diff --git a/vendor/github.com/heroiclabs/nakama-common/api/api.pb.go b/vendor/github.com/heroiclabs/nakama-common/api/api.pb.go index 428acb73dfe9aacc3ef1438179e08299fbd9b840..c36fccfa293c44b66ec04c715d04347ed53c1f62 100644 --- a/vendor/github.com/heroiclabs/nakama-common/api/api.pb.go +++ b/vendor/github.com/heroiclabs/nakama-common/api/api.pb.go @@ -17,14 +17,13 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.25.0 +// protoc-gen-go v1.26.0 // protoc v3.15.8 // source: api.proto package api import ( - proto "github.com/golang/protobuf/proto" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" timestamppb "google.golang.org/protobuf/types/known/timestamppb" @@ -40,10 +39,6 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - // The friendship status. type Friend_State int32 diff --git a/vendor/github.com/heroiclabs/nakama-common/rtapi/realtime.pb.go b/vendor/github.com/heroiclabs/nakama-common/rtapi/realtime.pb.go index 5e3b7ee143c04aeba81dd96a384ad18adc22f9d0..44a1717b1e675f364a3ac5a56bc85a05ebfa7630 100644 --- a/vendor/github.com/heroiclabs/nakama-common/rtapi/realtime.pb.go +++ b/vendor/github.com/heroiclabs/nakama-common/rtapi/realtime.pb.go @@ -17,14 +17,13 @@ // Code generated by protoc-gen-go. DO NOT EDIT. // versions: -// protoc-gen-go v1.25.0 +// protoc-gen-go v1.26.0 // protoc v3.15.8 // source: realtime.proto package rtapi import ( - proto "github.com/golang/protobuf/proto" api "github.com/heroiclabs/nakama-common/api" protoreflect "google.golang.org/protobuf/reflect/protoreflect" protoimpl "google.golang.org/protobuf/runtime/protoimpl" @@ -41,10 +40,6 @@ const ( _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) ) -// This is a compile-time assertion that a sufficiently up-to-date version -// of the legacy proto package is being used. -const _ = proto.ProtoPackageIsVersion4 - // The type of chat channel. type ChannelJoin_Type int32 diff --git a/vendor/google.golang.org/protobuf/cmd/protoc-gen-go/main.go b/vendor/google.golang.org/protobuf/cmd/protoc-gen-go/main.go new file mode 100644 index 0000000000000000000000000000000000000000..0559ee3306d93cb01b23e273a3228ac83c3abc51 --- /dev/null +++ b/vendor/google.golang.org/protobuf/cmd/protoc-gen-go/main.go @@ -0,0 +1,56 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +// The protoc-gen-go binary is a protoc plugin to generate Go code for +// both proto2 and proto3 versions of the protocol buffer language. +// +// For more information about the usage of this plugin, see: +// https://developers.google.com/protocol-buffers/docs/reference/go-generated +package main + +import ( + "errors" + "flag" + "fmt" + "os" + "path/filepath" + + gengo "google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo" + "google.golang.org/protobuf/compiler/protogen" + "google.golang.org/protobuf/internal/version" +) + +const genGoDocURL = "https://developers.google.com/protocol-buffers/docs/reference/go-generated" +const grpcDocURL = "https://grpc.io/docs/languages/go/quickstart/#regenerate-grpc-code" + +func main() { + if len(os.Args) == 2 && os.Args[1] == "--version" { + fmt.Fprintf(os.Stdout, "%v %v\n", filepath.Base(os.Args[0]), version.String()) + os.Exit(0) + } + if len(os.Args) == 2 && os.Args[1] == "--help" { + fmt.Fprintf(os.Stdout, "See "+genGoDocURL+" for usage information.\n") + os.Exit(0) + } + + var ( + flags flag.FlagSet + plugins = flags.String("plugins", "", "deprecated option") + ) + protogen.Options{ + ParamFunc: flags.Set, + }.Run(func(gen *protogen.Plugin) error { + if *plugins != "" { + return errors.New("protoc-gen-go: plugins are not supported; use 'protoc --go-grpc_out=...' to generate gRPC\n\n" + + "See " + grpcDocURL + " for more information.") + } + for _, f := range gen.Files { + if f.Generate { + gengo.GenerateFile(gen, f) + } + } + gen.SupportedFeatures = gengo.SupportedFeatures + return nil + }) +} diff --git a/vendor/modules.txt b/vendor/modules.txt index a7aa2ad945b67df6d243bfdca9a1649e4178f52a..ab2c3b5c2b9c2a6f7a34baf0eed93c2469d9e14a 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -103,18 +103,13 @@ github.com/go-sourcemap/sourcemap/internal/base64vlq github.com/gofrs/uuid # github.com/golang/glog v0.0.0-20160126235308-23def4e6c14b github.com/golang/glog -# github.com/golang/protobuf v1.5.2 -## explicit +# github.com/golang/protobuf v1.5.0 github.com/golang/protobuf/descriptor -github.com/golang/protobuf/internal/gengogrpc -github.com/golang/protobuf/jsonpb github.com/golang/protobuf/proto -github.com/golang/protobuf/protoc-gen-go github.com/golang/protobuf/protoc-gen-go/descriptor github.com/golang/protobuf/ptypes github.com/golang/protobuf/ptypes/any github.com/golang/protobuf/ptypes/duration -github.com/golang/protobuf/ptypes/empty github.com/golang/protobuf/ptypes/struct github.com/golang/protobuf/ptypes/timestamp github.com/golang/protobuf/ptypes/wrappers @@ -145,7 +140,7 @@ github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2/internal/genopena github.com/grpc-ecosystem/grpc-gateway/v2/protoc-gen-openapiv2/options github.com/grpc-ecosystem/grpc-gateway/v2/runtime github.com/grpc-ecosystem/grpc-gateway/v2/utilities -# github.com/heroiclabs/nakama-common v1.13.1 +# github.com/heroiclabs/nakama-common v1.13.2-0.20210421092134-6fdd0c82aa74 ## explicit github.com/heroiclabs/nakama-common/api github.com/heroiclabs/nakama-common/rtapi @@ -316,6 +311,7 @@ google.golang.org/grpc/tap google.golang.org/grpc/cmd/protoc-gen-go-grpc # google.golang.org/protobuf v1.26.0 ## explicit +google.golang.org/protobuf/cmd/protoc-gen-go google.golang.org/protobuf/cmd/protoc-gen-go/internal_gengo google.golang.org/protobuf/compiler/protogen google.golang.org/protobuf/encoding/protojson